@camstack/addon-admin-ui 1.0.2 → 1.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/assets/AddLocationWizard-D6tk8U-w.js +1 -0
  2. package/dist/assets/AddonCollectionPage-CPQWZfC0.js +1 -0
  3. package/dist/assets/Addons-BIu0hjHd.js +1 -0
  4. package/dist/assets/AdminPage-CN6ZMhf0.js +1 -0
  5. package/dist/assets/AdminTabs-Ddi8-SQJ.js +1 -0
  6. package/dist/assets/BrokerForm-Jzl9BAMO.js +1 -0
  7. package/dist/assets/BrokerStep-vbWWE4ss.js +1 -0
  8. package/dist/assets/Capabilities-GrzalIOH.js +1 -0
  9. package/dist/assets/CapabilityBadges-BN0gXK4w.js +1 -0
  10. package/dist/assets/Cluster-zuSKpmeo.js +7 -0
  11. package/dist/assets/Dashboard-Dl3BUDju.js +1 -0
  12. package/dist/assets/Data-DJn-KYZI.js +1 -0
  13. package/dist/assets/DetectionIntelligence-BhQAT1WX.js +1 -0
  14. package/dist/assets/DeviceDetail-C16YaYd6.js +2 -0
  15. package/dist/assets/Devices-D_zVs1PC.js +1 -0
  16. package/dist/assets/EmbedPlayerPage-BjQGYATU.js +1 -0
  17. package/dist/assets/FormBuilder-BXQEmfaE.js +1 -0
  18. package/dist/assets/Identity-ZvlfZz_A.js +1 -0
  19. package/dist/assets/IntegrationDetail-Bnpn2hQ2.js +1 -0
  20. package/dist/assets/Integrations-Bv07bA7c.js +1 -0
  21. package/dist/assets/Integrations-CsaOfFWR.js +1 -0
  22. package/dist/assets/Logs-DBoE5z_U.js +1 -0
  23. package/dist/assets/MaskShapeCanvas-C5K6H6Th.js +1 -0
  24. package/dist/assets/MotionZonesSettings-CepMSlXn.js +1 -0
  25. package/dist/assets/MyAccess-Bp5Cp_C6.js +2 -0
  26. package/dist/assets/Network-Dyg7yTc_.js +1 -0
  27. package/dist/assets/NodeAddonsSettingsPanel-9HVgS_gw.js +1 -0
  28. package/dist/assets/Pipeline-DzZm2XqD.js +1 -0
  29. package/dist/assets/PrivacyMaskSettings-Cl0lj_PR.js +1 -0
  30. package/dist/assets/ProviderIcon-DWSMqwcl.js +1 -0
  31. package/dist/assets/SchemaTabBar-ByWwzBUZ.js +1 -0
  32. package/dist/assets/Settings-ayyuAbCz.js +1 -0
  33. package/dist/assets/Showroom-CQ1h4YKK.js +1 -0
  34. package/dist/assets/StatusBadge-CkYubfRG.js +1 -0
  35. package/dist/assets/_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-CS4OeMKk.js +1 -0
  36. package/dist/assets/_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-CK8iQdP1.js +1 -0
  37. package/dist/assets/_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.js-DEeasWo3.js +1 -0
  38. package/dist/assets/{_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.js-C2cB5JUo.js → _virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.js-C1rR7FKs.js} +1 -1
  39. package/dist/assets/{_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-CXx5u_N6.js → _virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-DQOBkcAT.js} +1 -1
  40. package/dist/assets/{_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.js-B2sDsXg0.js → _virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.js-PYw2UAZ_.js} +3 -3
  41. package/dist/assets/bell-C9HUnDGC.js +1 -0
  42. package/dist/assets/circle-check-big-BDdzTa9p.js +1 -0
  43. package/dist/assets/copy-BtC330Ic.js +1 -0
  44. package/dist/assets/download-CEQQi2pw.js +1 -0
  45. package/dist/assets/format-size-CO9d3C3-.js +1 -0
  46. package/dist/assets/hls-IujbK-0_.js +40 -0
  47. package/dist/assets/{hostInit-BTTV3T99.js → hostInit-Y3VsYAf_.js} +1 -1
  48. package/dist/assets/index-DuroU2aU.js +4 -0
  49. package/dist/assets/key-round-C1aQCNHE.js +1 -0
  50. package/dist/assets/{mf-entry-bootstrap-0-2d3bf175.js → mf-entry-bootstrap-0-3e98f17f.js} +2 -2
  51. package/dist/assets/pencil-Dw6owGVy.js +1 -0
  52. package/dist/assets/player-overlays-DzZKARlk.js +1 -0
  53. package/dist/assets/plus-CbaF5MYw.js +1 -0
  54. package/dist/assets/radio-CyBw1Cvj.js +1 -0
  55. package/dist/assets/refresh-cw-CPqFoliO.js +1 -0
  56. package/dist/assets/remoteEntry-BXtCFyvA.js +1 -0
  57. package/dist/assets/rotate-ccw-BJL6I3ju.js +1 -0
  58. package/dist/assets/rotate-cw-DZGWB7EU.js +1 -0
  59. package/dist/assets/search-cFwrysqG.js +1 -0
  60. package/dist/assets/server-BgZ85UtO.js +1 -0
  61. package/dist/assets/sparkles-Dj3mm_rJ.js +1 -0
  62. package/dist/assets/square-D-dTwz52.js +1 -0
  63. package/dist/assets/square-check-big-CMEqldHV.js +1 -0
  64. package/dist/assets/src-CqVYgpnN.js +34 -0
  65. package/dist/assets/upload-tyMJOOSL.js +1 -0
  66. package/dist/assets/useDevice-DTk9eLX5.js +1 -0
  67. package/dist/assets/useEventInvalidation-CqPABxEF.js +1 -0
  68. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-Bkv14Bzm.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-B1bVOGqv.js} +2 -2
  69. package/dist/assets/wifi-Do23YMj8.js +1 -0
  70. package/dist/assets/zap-CZ68wiP1.js +1 -0
  71. package/dist/index.html +4 -3
  72. package/dist/sw.js +1 -1
  73. package/dist/workbox-14d7584c.js +1 -0
  74. package/package.json +1 -2
  75. package/dist/assets/_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-BxNjjb9O.js +0 -1
  76. package/dist/assets/_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-1rzf3QZV.js +0 -1
  77. package/dist/assets/_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.js-CPJ7iclX.js +0 -1
  78. package/dist/assets/dist-q2poCTnb.js +0 -75
  79. package/dist/assets/index-BKoIXFjm.js +0 -82
  80. package/dist/assets/remoteEntry-DLAuLulq.js +0 -1
  81. package/dist/assets/src-BE2rTAMO.js +0 -1
  82. package/dist/workbox-9c191d2f.js +0 -1
@@ -1,75 +0,0 @@
1
- import{t as e}from"./vite-preload-helper-zJ_50EbN.js";import{A as t,D as n,E as r,F as i,G as a,H as o,J as s,L as c,O as l,P as u,R as d,S as f,U as p,V as m,W as h,_ as g,a as _,b as v,d as y,o as b,q as x,t as S,u as C,w,x as T,y as E,z as D}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.js-1rzf3QZV.js";import{n as O,r as k,t as A}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.js-C2cB5JUo.js";import{n as j,t as M}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.js-CXx5u_N6.js";import{T as N,b as P,g as ee,k as F,o as te,x as I}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_client__loadShare__.js-CSJxMxg6.js";import{n as L,t as ne}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.js-CPJ7iclX.js";import{t as R}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare__konva__loadShare__.js-B7XYY0cV.js";import{a as re,c as ie,i as ae,l as z,n as oe,o as se,r as ce,s as le,t as ue}from"./_virtual_mf___mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.js-B2sDsXg0.js";import{C as de,D as fe,g as pe,h as me,w as he}from"./schemas-CuE8EXQ7.js";import{D as B,T as ge,_ as _e,b as V,c as ve,h as ye,i as be,l as xe,m as Se,o as Ce,p as we,r as Te,v as Ee,w as De,x as Oe,y as H}from"./src-CrhOk7JL.js";import{n as ke}from"./src-BE2rTAMO.js";s();var Ae={frigate:`#3b82f6`,scrypted:`#a855f7`,reolink:`#06b6d4`,homeAssistant:`#22d3ee`,rtsp:`#78716c`},je={primary:`#f59e42`,primaryForeground:`#0c0a09`,background:`#0c0a09`,backgroundElevated:`#1c1917`,surface:`#1c1917`,surfaceHover:`#292524`,border:`#292524`,borderSubtle:`#1c1917`,foreground:`#fafaf9`,foregroundMuted:`#a8a29e`,foregroundSubtle:`#78716c`,foregroundDisabled:`#57534e`,success:`#4ade80`,warning:`#fbbf24`,danger:`#f87171`,info:`#60a5fa`,provider:Ae},Me={primary:`#e67e22`,primaryForeground:`#ffffff`,background:`#fafaf9`,backgroundElevated:`#ffffff`,surface:`#f5f5f4`,surfaceHover:`#e7e5e4`,border:`#d6d3d1`,borderSubtle:`#e7e5e4`,foreground:`#1c1917`,foregroundMuted:`#57534e`,foregroundSubtle:`#78716c`,foregroundDisabled:`#a8a29e`,success:`#16a34a`,warning:`#d97706`,danger:`#dc2626`,info:`#2563eb`,provider:Ae},Ne={colors:{dark:je,light:Me},spacing:{xs:2,sm:4,md:8,lg:12,xl:16,"2xl":24,"3xl":32},radius:{sm:4,md:6,lg:8,xl:12},typography:{fontFamily:`-apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif`,sizes:{xs:{fontSize:10,lineHeight:14},sm:{fontSize:11,lineHeight:16},base:{fontSize:12,lineHeight:18},lg:{fontSize:13,lineHeight:18},xl:{fontSize:14,lineHeight:20},"2xl":{fontSize:16,lineHeight:22},"3xl":{fontSize:20,lineHeight:28}},weights:{regular:400,medium:500,semibold:600,bold:700}},table:{rowHeight:28,headerHeight:24,cellPaddingX:8,cellPaddingY:6},sidebar:{width:176,itemHeight:28,iconSize:14}};function Pe(e,t){let n={...e};for(let r in t){let i=t[r],a=e[r];i!==void 0&&typeof i==`object`&&i&&!Array.isArray(i)&&typeof a==`object`&&a?n[r]=Pe(a,i):i!==void 0&&(n[r]=i)}return n}function Fe(e){return e?Pe(structuredClone(Ne),e):structuredClone(Ne)}function Ie(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function Le(e){return`--color-${Ie(e)}`}function Re(e){let t=[];for(let[n,r]of Object.entries(e))n!==`provider`&&t.push(` ${Le(n)}: ${r};`);return t.join(`
2
- `)}function ze(e){let t=[];for(let[n,r]of Object.entries(e))t.push(` --color-provider-${Ie(n)}: ${r};`);return t.join(`
3
- `)}function Be(e){let t=[];for(let[n,r]of Object.entries(e))t.push(` --spacing-${n}: ${r}px;`);return t.join(`
4
- `)}function Ve(e){let t=[];for(let[n,r]of Object.entries(e))t.push(` --radius-${n}: ${r}px;`);return t.join(`
5
- `)}function He(e){let t=Re(e.colors.dark),n=Re(e.colors.light);return`@theme {
6
- ${ze(e.colors.dark.provider)}
7
- ${Be(e.spacing)}
8
- ${Ve(e.radius)}
9
- }
10
-
11
- .dark {
12
- ${t}
13
- }
14
-
15
- .light {
16
- ${n}
17
- }
18
-
19
- @media (prefers-color-scheme: dark) {
20
- :root {
21
- ${t.replace(/^ {2}/gm,` `)}
22
- }
23
- }
24
-
25
- @media (prefers-color-scheme: light) {
26
- :root {
27
- ${n.replace(/^ {2}/gm,` `)}
28
- }
29
- }
30
- `}var Ue=r(null),We=[`dark`,`light`,`system`];function Ge(){return typeof window>`u`||window.matchMedia(`(prefers-color-scheme: dark)`).matches?`dark`:`light`}function Ke(e,t){if(typeof window>`u`)return t;let n=localStorage.getItem(e);return n===`dark`||n===`light`||n===`system`?n:t}function qe(e){return e===`system`?Ge():e}function Je({children:e,defaultMode:t=`system`,storageKey:n=`camstack-theme-mode`}){let[r,i]=h(()=>Ke(n,t)),[a,s]=h(()=>qe(r)),l=u(e=>{i(e),s(qe(e)),typeof window<`u`&&localStorage.setItem(n,e)},[n]),d=u(()=>{l(We[(We.indexOf(r)+1)%We.length]??`dark`)},[r,l]);c(()=>{if(typeof document>`u`)return;let e=document.documentElement;e.classList.remove(`dark`,`light`),e.classList.add(a)},[r,a]),c(()=>{if(typeof window>`u`||r!==`system`)return;let e=window.matchMedia(`(prefers-color-scheme: dark)`),t=()=>{s(Ge())};return e.addEventListener(`change`,t),()=>e.removeEventListener(`change`,t)},[r]);let f=o(()=>({mode:r,resolvedMode:a,setMode:l,toggleMode:d}),[r,a,l,d]);return v(Ue.Provider,{value:f,children:e})}function Ye(){let e=i(Ue);if(!e)throw Error(`useThemeMode must be used within a ThemeProvider`);return e}s(),k();function Xe(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`)if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(n=Xe(e[t]))&&(r&&(r+=` `),r+=n)}else for(n in e)e[n]&&(r&&(r+=` `),r+=n);return r}function Ze(){for(var e,t,n=0,r=``,i=arguments.length;n<i;n++)(e=arguments[n])&&(t=Xe(e))&&(r&&(r+=` `),r+=t);return r}var Qe=(e,t)=>{let n=Array(e.length+t.length);for(let t=0;t<e.length;t++)n[t]=e[t];for(let r=0;r<t.length;r++)n[e.length+r]=t[r];return n},$e=(e,t)=>({classGroupId:e,validator:t}),et=(e=new Map,t=null,n)=>({nextPart:e,validators:t,classGroupId:n}),tt=`-`,nt=[],rt=`arbitrary..`,it=e=>{let t=st(e),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=e;return{getClassGroupId:e=>{if(e.startsWith(`[`)&&e.endsWith(`]`))return ot(e);let n=e.split(tt);return at(n,+(n[0]===``&&n.length>1),t)},getConflictingClassGroupIds:(e,t)=>{if(t){let t=r[e],i=n[e];return t?i?Qe(i,t):t:i||nt}return n[e]||nt}}},at=(e,t,n)=>{if(e.length-t===0)return n.classGroupId;let r=e[t],i=n.nextPart.get(r);if(i){let n=at(e,t+1,i);if(n)return n}let a=n.validators;if(a===null)return;let o=t===0?e.join(tt):e.slice(t).join(tt),s=a.length;for(let e=0;e<s;e++){let t=a[e];if(t.validator(o))return t.classGroupId}},ot=e=>e.slice(1,-1).indexOf(`:`)===-1?void 0:(()=>{let t=e.slice(1,-1),n=t.indexOf(`:`),r=t.slice(0,n);return r?rt+r:void 0})(),st=e=>{let{theme:t,classGroups:n}=e;return ct(n,t)},ct=(e,t)=>{let n=et();for(let r in e){let i=e[r];lt(i,n,r,t)}return n},lt=(e,t,n,r)=>{let i=e.length;for(let a=0;a<i;a++){let i=e[a];ut(i,t,n,r)}},ut=(e,t,n,r)=>{if(typeof e==`string`){dt(e,t,n);return}if(typeof e==`function`){ft(e,t,n,r);return}pt(e,t,n,r)},dt=(e,t,n)=>{let r=e===``?t:mt(t,e);r.classGroupId=n},ft=(e,t,n,r)=>{if(ht(e)){lt(e(r),t,n,r);return}t.validators===null&&(t.validators=[]),t.validators.push($e(n,e))},pt=(e,t,n,r)=>{let i=Object.entries(e),a=i.length;for(let e=0;e<a;e++){let[a,o]=i[e];lt(o,mt(t,a),n,r)}},mt=(e,t)=>{let n=e,r=t.split(tt),i=r.length;for(let e=0;e<i;e++){let t=r[e],i=n.nextPart.get(t);i||(i=et(),n.nextPart.set(t,i)),n=i}return n},ht=e=>`isThemeGetter`in e&&e.isThemeGetter===!0,gt=e=>{if(e<1)return{get:()=>void 0,set:()=>{}};let t=0,n=Object.create(null),r=Object.create(null),i=(i,a)=>{n[i]=a,t++,t>e&&(t=0,r=n,n=Object.create(null))};return{get(e){let t=n[e];if(t!==void 0)return t;if((t=r[e])!==void 0)return i(e,t),t},set(e,t){e in n?n[e]=t:i(e,t)}}},_t=`!`,vt=`:`,yt=[],bt=(e,t,n,r,i)=>({modifiers:e,hasImportantModifier:t,baseClassName:n,maybePostfixModifierPosition:r,isExternal:i}),xt=e=>{let{prefix:t,experimentalParseClassName:n}=e,r=e=>{let t=[],n=0,r=0,i=0,a,o=e.length;for(let s=0;s<o;s++){let o=e[s];if(n===0&&r===0){if(o===vt){t.push(e.slice(i,s)),i=s+1;continue}if(o===`/`){a=s;continue}}o===`[`?n++:o===`]`?n--:o===`(`?r++:o===`)`&&r--}let s=t.length===0?e:e.slice(i),c=s,l=!1;s.endsWith(_t)?(c=s.slice(0,-1),l=!0):s.startsWith(_t)&&(c=s.slice(1),l=!0);let u=a&&a>i?a-i:void 0;return bt(t,l,c,u)};if(t){let e=t+vt,n=r;r=t=>t.startsWith(e)?n(t.slice(e.length)):bt(yt,!1,t,void 0,!0)}if(n){let e=r;r=t=>n({className:t,parseClassName:e})}return r},St=e=>{let t=new Map;return e.orderSensitiveModifiers.forEach((e,n)=>{t.set(e,1e6+n)}),e=>{let n=[],r=[];for(let i=0;i<e.length;i++){let a=e[i],o=a[0]===`[`,s=t.has(a);o||s?(r.length>0&&(r.sort(),n.push(...r),r=[]),n.push(a)):r.push(a)}return r.length>0&&(r.sort(),n.push(...r)),n}},Ct=e=>({cache:gt(e.cacheSize),parseClassName:xt(e),sortModifiers:St(e),postfixLookupClassGroupIds:wt(e),...it(e)}),wt=e=>{let t=Object.create(null),n=e.postfixLookupClassGroups;if(n)for(let e=0;e<n.length;e++)t[n[e]]=!0;return t},Tt=/\s+/,Et=(e,t)=>{let{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:i,sortModifiers:a,postfixLookupClassGroupIds:o}=t,s=[],c=e.trim().split(Tt),l=``;for(let e=c.length-1;e>=0;--e){let t=c[e],{isExternal:u,modifiers:d,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:m}=n(t);if(u){l=t+(l.length>0?` `+l:l);continue}let h=!!m,g;if(h){g=r(p.substring(0,m));let e=g&&o[g]?r(p):void 0;e&&e!==g&&(g=e,h=!1)}else g=r(p);if(!g){if(!h){l=t+(l.length>0?` `+l:l);continue}if(g=r(p),!g){l=t+(l.length>0?` `+l:l);continue}h=!1}let _=d.length===0?``:d.length===1?d[0]:a(d).join(`:`),v=f?_+_t:_,y=v+g;if(s.indexOf(y)>-1)continue;s.push(y);let b=i(g,h);for(let e=0;e<b.length;++e){let t=b[e];s.push(v+t)}l=t+(l.length>0?` `+l:l)}return l},Dt=(...e)=>{let t=0,n,r,i=``;for(;t<e.length;)(n=e[t++])&&(r=Ot(n))&&(i&&(i+=` `),i+=r);return i},Ot=e=>{if(typeof e==`string`)return e;let t,n=``;for(let r=0;r<e.length;r++)e[r]&&(t=Ot(e[r]))&&(n&&(n+=` `),n+=t);return n},kt=(e,...t)=>{let n,r,i,a,o=o=>(n=Ct(t.reduce((e,t)=>t(e),e())),r=n.cache.get,i=n.cache.set,a=s,s(o)),s=e=>{let t=r(e);if(t)return t;let a=Et(e,n);return i(e,a),a};return a=o,(...e)=>a(Dt(...e))},At=[],jt=e=>{let t=t=>t[e]||At;return t.isThemeGetter=!0,t},Mt=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Nt=/^\((?:(\w[\w-]*):)?(.+)\)$/i,Pt=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,Ft=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,It=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Lt=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Rt=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,zt=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Bt=e=>Pt.test(e),Vt=e=>!!e&&!Number.isNaN(Number(e)),Ht=e=>!!e&&Number.isInteger(Number(e)),Ut=e=>e.endsWith(`%`)&&Vt(e.slice(0,-1)),Wt=e=>Ft.test(e),Gt=()=>!0,Kt=e=>It.test(e)&&!Lt.test(e),qt=()=>!1,Jt=e=>Rt.test(e),Yt=e=>zt.test(e),Xt=e=>!U(e)&&!W(e),Zt=e=>e.startsWith(`@container`)&&(e[10]===`/`&&e[11]!==void 0||e[11]===`s`&&e[16]!==void 0&&e.startsWith(`-size/`,10)||e[11]===`n`&&e[18]!==void 0&&e.startsWith(`-normal/`,10)),Qt=e=>mn(e,vn,qt),U=e=>Mt.test(e),$t=e=>mn(e,yn,Kt),en=e=>mn(e,bn,Vt),tn=e=>mn(e,Sn,Gt),nn=e=>mn(e,xn,qt),rn=e=>mn(e,gn,qt),an=e=>mn(e,_n,Yt),on=e=>mn(e,Cn,Jt),W=e=>Nt.test(e),sn=e=>hn(e,yn),cn=e=>hn(e,xn),ln=e=>hn(e,gn),un=e=>hn(e,vn),dn=e=>hn(e,_n),fn=e=>hn(e,Cn,!0),pn=e=>hn(e,Sn,!0),mn=(e,t,n)=>{let r=Mt.exec(e);return r?r[1]?t(r[1]):n(r[2]):!1},hn=(e,t,n=!1)=>{let r=Nt.exec(e);return r?r[1]?t(r[1]):n:!1},gn=e=>e===`position`||e===`percentage`,_n=e=>e===`image`||e===`url`,vn=e=>e===`length`||e===`size`||e===`bg-size`,yn=e=>e===`length`,bn=e=>e===`number`,xn=e=>e===`family-name`,Sn=e=>e===`number`||e===`weight`,Cn=e=>e===`shadow`,wn=kt(()=>{let e=jt(`color`),t=jt(`font`),n=jt(`text`),r=jt(`font-weight`),i=jt(`tracking`),a=jt(`leading`),o=jt(`breakpoint`),s=jt(`container`),c=jt(`spacing`),l=jt(`radius`),u=jt(`shadow`),d=jt(`inset-shadow`),f=jt(`text-shadow`),p=jt(`drop-shadow`),m=jt(`blur`),h=jt(`perspective`),g=jt(`aspect`),_=jt(`ease`),v=jt(`animate`),y=()=>[`auto`,`avoid`,`all`,`avoid-page`,`page`,`left`,`right`,`column`],b=()=>[`center`,`top`,`bottom`,`left`,`right`,`top-left`,`left-top`,`top-right`,`right-top`,`bottom-right`,`right-bottom`,`bottom-left`,`left-bottom`],x=()=>[...b(),W,U],S=()=>[`auto`,`hidden`,`clip`,`visible`,`scroll`],C=()=>[`auto`,`contain`,`none`],w=()=>[W,U,c],T=()=>[Bt,`full`,`auto`,...w()],E=()=>[Ht,`none`,`subgrid`,W,U],D=()=>[`auto`,{span:[`full`,Ht,W,U]},Ht,W,U],O=()=>[Ht,`auto`,W,U],k=()=>[`auto`,`min`,`max`,`fr`,W,U],A=()=>[`start`,`end`,`center`,`between`,`around`,`evenly`,`stretch`,`baseline`,`center-safe`,`end-safe`],j=()=>[`start`,`end`,`center`,`stretch`,`center-safe`,`end-safe`],M=()=>[`auto`,...w()],N=()=>[Bt,`auto`,`full`,`dvw`,`dvh`,`lvw`,`lvh`,`svw`,`svh`,`min`,`max`,`fit`,...w()],P=()=>[Bt,`screen`,`full`,`dvw`,`lvw`,`svw`,`min`,`max`,`fit`,...w()],ee=()=>[Bt,`screen`,`full`,`lh`,`dvh`,`lvh`,`svh`,`min`,`max`,`fit`,...w()],F=()=>[e,W,U],te=()=>[...b(),ln,rn,{position:[W,U]}],I=()=>[`no-repeat`,{repeat:[``,`x`,`y`,`space`,`round`]}],L=()=>[`auto`,`cover`,`contain`,un,Qt,{size:[W,U]}],ne=()=>[Ut,sn,$t],R=()=>[``,`none`,`full`,l,W,U],re=()=>[``,Vt,sn,$t],ie=()=>[`solid`,`dashed`,`dotted`,`double`],ae=()=>[`normal`,`multiply`,`screen`,`overlay`,`darken`,`lighten`,`color-dodge`,`color-burn`,`hard-light`,`soft-light`,`difference`,`exclusion`,`hue`,`saturation`,`color`,`luminosity`],z=()=>[Vt,Ut,ln,rn],oe=()=>[``,`none`,m,W,U],se=()=>[`none`,Vt,W,U],ce=()=>[`none`,Vt,W,U],le=()=>[Vt,W,U],ue=()=>[Bt,`full`,...w()];return{cacheSize:500,theme:{animate:[`spin`,`ping`,`pulse`,`bounce`],aspect:[`video`],blur:[Wt],breakpoint:[Wt],color:[Gt],container:[Wt],"drop-shadow":[Wt],ease:[`in`,`out`,`in-out`],font:[Xt],"font-weight":[`thin`,`extralight`,`light`,`normal`,`medium`,`semibold`,`bold`,`extrabold`,`black`],"inset-shadow":[Wt],leading:[`none`,`tight`,`snug`,`normal`,`relaxed`,`loose`],perspective:[`dramatic`,`near`,`normal`,`midrange`,`distant`,`none`],radius:[Wt],shadow:[Wt],spacing:[`px`,Vt],text:[Wt],"text-shadow":[Wt],tracking:[`tighter`,`tight`,`normal`,`wide`,`wider`,`widest`]},classGroups:{aspect:[{aspect:[`auto`,`square`,Bt,U,W,g]}],container:[`container`],"container-type":[{"@container":[``,`normal`,`size`,W,U]}],"container-named":[Zt],columns:[{columns:[Vt,U,W,s]}],"break-after":[{"break-after":y()}],"break-before":[{"break-before":y()}],"break-inside":[{"break-inside":[`auto`,`avoid`,`avoid-page`,`avoid-column`]}],"box-decoration":[{"box-decoration":[`slice`,`clone`]}],box:[{box:[`border`,`content`]}],display:[`block`,`inline-block`,`inline`,`flex`,`inline-flex`,`table`,`inline-table`,`table-caption`,`table-cell`,`table-column`,`table-column-group`,`table-footer-group`,`table-header-group`,`table-row-group`,`table-row`,`flow-root`,`grid`,`inline-grid`,`contents`,`list-item`,`hidden`],sr:[`sr-only`,`not-sr-only`],float:[{float:[`right`,`left`,`none`,`start`,`end`]}],clear:[{clear:[`left`,`right`,`both`,`none`,`start`,`end`]}],isolation:[`isolate`,`isolation-auto`],"object-fit":[{object:[`contain`,`cover`,`fill`,`none`,`scale-down`]}],"object-position":[{object:x()}],overflow:[{overflow:S()}],"overflow-x":[{"overflow-x":S()}],"overflow-y":[{"overflow-y":S()}],overscroll:[{overscroll:C()}],"overscroll-x":[{"overscroll-x":C()}],"overscroll-y":[{"overscroll-y":C()}],position:[`static`,`fixed`,`absolute`,`relative`,`sticky`],inset:[{inset:T()}],"inset-x":[{"inset-x":T()}],"inset-y":[{"inset-y":T()}],start:[{"inset-s":T(),start:T()}],end:[{"inset-e":T(),end:T()}],"inset-bs":[{"inset-bs":T()}],"inset-be":[{"inset-be":T()}],top:[{top:T()}],right:[{right:T()}],bottom:[{bottom:T()}],left:[{left:T()}],visibility:[`visible`,`invisible`,`collapse`],z:[{z:[Ht,`auto`,W,U]}],basis:[{basis:[Bt,`full`,`auto`,s,...w()]}],"flex-direction":[{flex:[`row`,`row-reverse`,`col`,`col-reverse`]}],"flex-wrap":[{flex:[`nowrap`,`wrap`,`wrap-reverse`]}],flex:[{flex:[Vt,Bt,`auto`,`initial`,`none`,U]}],grow:[{grow:[``,Vt,W,U]}],shrink:[{shrink:[``,Vt,W,U]}],order:[{order:[Ht,`first`,`last`,`none`,W,U]}],"grid-cols":[{"grid-cols":E()}],"col-start-end":[{col:D()}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":E()}],"row-start-end":[{row:D()}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":[`row`,`col`,`dense`,`row-dense`,`col-dense`]}],"auto-cols":[{"auto-cols":k()}],"auto-rows":[{"auto-rows":k()}],gap:[{gap:w()}],"gap-x":[{"gap-x":w()}],"gap-y":[{"gap-y":w()}],"justify-content":[{justify:[...A(),`normal`]}],"justify-items":[{"justify-items":[...j(),`normal`]}],"justify-self":[{"justify-self":[`auto`,...j()]}],"align-content":[{content:[`normal`,...A()]}],"align-items":[{items:[...j(),{baseline:[``,`last`]}]}],"align-self":[{self:[`auto`,...j(),{baseline:[``,`last`]}]}],"place-content":[{"place-content":A()}],"place-items":[{"place-items":[...j(),`baseline`]}],"place-self":[{"place-self":[`auto`,...j()]}],p:[{p:w()}],px:[{px:w()}],py:[{py:w()}],ps:[{ps:w()}],pe:[{pe:w()}],pbs:[{pbs:w()}],pbe:[{pbe:w()}],pt:[{pt:w()}],pr:[{pr:w()}],pb:[{pb:w()}],pl:[{pl:w()}],m:[{m:M()}],mx:[{mx:M()}],my:[{my:M()}],ms:[{ms:M()}],me:[{me:M()}],mbs:[{mbs:M()}],mbe:[{mbe:M()}],mt:[{mt:M()}],mr:[{mr:M()}],mb:[{mb:M()}],ml:[{ml:M()}],"space-x":[{"space-x":w()}],"space-x-reverse":[`space-x-reverse`],"space-y":[{"space-y":w()}],"space-y-reverse":[`space-y-reverse`],size:[{size:N()}],"inline-size":[{inline:[`auto`,...P()]}],"min-inline-size":[{"min-inline":[`auto`,...P()]}],"max-inline-size":[{"max-inline":[`none`,...P()]}],"block-size":[{block:[`auto`,...ee()]}],"min-block-size":[{"min-block":[`auto`,...ee()]}],"max-block-size":[{"max-block":[`none`,...ee()]}],w:[{w:[s,`screen`,...N()]}],"min-w":[{"min-w":[s,`screen`,`none`,...N()]}],"max-w":[{"max-w":[s,`screen`,`none`,`prose`,{screen:[o]},...N()]}],h:[{h:[`screen`,`lh`,...N()]}],"min-h":[{"min-h":[`screen`,`lh`,`none`,...N()]}],"max-h":[{"max-h":[`screen`,`lh`,...N()]}],"font-size":[{text:[`base`,n,sn,$t]}],"font-smoothing":[`antialiased`,`subpixel-antialiased`],"font-style":[`italic`,`not-italic`],"font-weight":[{font:[r,pn,tn]}],"font-stretch":[{"font-stretch":[`ultra-condensed`,`extra-condensed`,`condensed`,`semi-condensed`,`normal`,`semi-expanded`,`expanded`,`extra-expanded`,`ultra-expanded`,Ut,U]}],"font-family":[{font:[cn,nn,t]}],"font-features":[{"font-features":[U]}],"fvn-normal":[`normal-nums`],"fvn-ordinal":[`ordinal`],"fvn-slashed-zero":[`slashed-zero`],"fvn-figure":[`lining-nums`,`oldstyle-nums`],"fvn-spacing":[`proportional-nums`,`tabular-nums`],"fvn-fraction":[`diagonal-fractions`,`stacked-fractions`],tracking:[{tracking:[i,W,U]}],"line-clamp":[{"line-clamp":[Vt,`none`,W,en]}],leading:[{leading:[a,...w()]}],"list-image":[{"list-image":[`none`,W,U]}],"list-style-position":[{list:[`inside`,`outside`]}],"list-style-type":[{list:[`disc`,`decimal`,`none`,W,U]}],"text-alignment":[{text:[`left`,`center`,`right`,`justify`,`start`,`end`]}],"placeholder-color":[{placeholder:F()}],"text-color":[{text:F()}],"text-decoration":[`underline`,`overline`,`line-through`,`no-underline`],"text-decoration-style":[{decoration:[...ie(),`wavy`]}],"text-decoration-thickness":[{decoration:[Vt,`from-font`,`auto`,W,$t]}],"text-decoration-color":[{decoration:F()}],"underline-offset":[{"underline-offset":[Vt,`auto`,W,U]}],"text-transform":[`uppercase`,`lowercase`,`capitalize`,`normal-case`],"text-overflow":[`truncate`,`text-ellipsis`,`text-clip`],"text-wrap":[{text:[`wrap`,`nowrap`,`balance`,`pretty`]}],indent:[{indent:w()}],"tab-size":[{tab:[Ht,W,U]}],"vertical-align":[{align:[`baseline`,`top`,`middle`,`bottom`,`text-top`,`text-bottom`,`sub`,`super`,W,U]}],whitespace:[{whitespace:[`normal`,`nowrap`,`pre`,`pre-line`,`pre-wrap`,`break-spaces`]}],break:[{break:[`normal`,`words`,`all`,`keep`]}],wrap:[{wrap:[`break-word`,`anywhere`,`normal`]}],hyphens:[{hyphens:[`none`,`manual`,`auto`]}],content:[{content:[`none`,W,U]}],"bg-attachment":[{bg:[`fixed`,`local`,`scroll`]}],"bg-clip":[{"bg-clip":[`border`,`padding`,`content`,`text`]}],"bg-origin":[{"bg-origin":[`border`,`padding`,`content`]}],"bg-position":[{bg:te()}],"bg-repeat":[{bg:I()}],"bg-size":[{bg:L()}],"bg-image":[{bg:[`none`,{linear:[{to:[`t`,`tr`,`r`,`br`,`b`,`bl`,`l`,`tl`]},Ht,W,U],radial:[``,W,U],conic:[Ht,W,U]},dn,an]}],"bg-color":[{bg:F()}],"gradient-from-pos":[{from:ne()}],"gradient-via-pos":[{via:ne()}],"gradient-to-pos":[{to:ne()}],"gradient-from":[{from:F()}],"gradient-via":[{via:F()}],"gradient-to":[{to:F()}],rounded:[{rounded:R()}],"rounded-s":[{"rounded-s":R()}],"rounded-e":[{"rounded-e":R()}],"rounded-t":[{"rounded-t":R()}],"rounded-r":[{"rounded-r":R()}],"rounded-b":[{"rounded-b":R()}],"rounded-l":[{"rounded-l":R()}],"rounded-ss":[{"rounded-ss":R()}],"rounded-se":[{"rounded-se":R()}],"rounded-ee":[{"rounded-ee":R()}],"rounded-es":[{"rounded-es":R()}],"rounded-tl":[{"rounded-tl":R()}],"rounded-tr":[{"rounded-tr":R()}],"rounded-br":[{"rounded-br":R()}],"rounded-bl":[{"rounded-bl":R()}],"border-w":[{border:re()}],"border-w-x":[{"border-x":re()}],"border-w-y":[{"border-y":re()}],"border-w-s":[{"border-s":re()}],"border-w-e":[{"border-e":re()}],"border-w-bs":[{"border-bs":re()}],"border-w-be":[{"border-be":re()}],"border-w-t":[{"border-t":re()}],"border-w-r":[{"border-r":re()}],"border-w-b":[{"border-b":re()}],"border-w-l":[{"border-l":re()}],"divide-x":[{"divide-x":re()}],"divide-x-reverse":[`divide-x-reverse`],"divide-y":[{"divide-y":re()}],"divide-y-reverse":[`divide-y-reverse`],"border-style":[{border:[...ie(),`hidden`,`none`]}],"divide-style":[{divide:[...ie(),`hidden`,`none`]}],"border-color":[{border:F()}],"border-color-x":[{"border-x":F()}],"border-color-y":[{"border-y":F()}],"border-color-s":[{"border-s":F()}],"border-color-e":[{"border-e":F()}],"border-color-bs":[{"border-bs":F()}],"border-color-be":[{"border-be":F()}],"border-color-t":[{"border-t":F()}],"border-color-r":[{"border-r":F()}],"border-color-b":[{"border-b":F()}],"border-color-l":[{"border-l":F()}],"divide-color":[{divide:F()}],"outline-style":[{outline:[...ie(),`none`,`hidden`]}],"outline-offset":[{"outline-offset":[Vt,W,U]}],"outline-w":[{outline:[``,Vt,sn,$t]}],"outline-color":[{outline:F()}],shadow:[{shadow:[``,`none`,u,fn,on]}],"shadow-color":[{shadow:F()}],"inset-shadow":[{"inset-shadow":[`none`,d,fn,on]}],"inset-shadow-color":[{"inset-shadow":F()}],"ring-w":[{ring:re()}],"ring-w-inset":[`ring-inset`],"ring-color":[{ring:F()}],"ring-offset-w":[{"ring-offset":[Vt,$t]}],"ring-offset-color":[{"ring-offset":F()}],"inset-ring-w":[{"inset-ring":re()}],"inset-ring-color":[{"inset-ring":F()}],"text-shadow":[{"text-shadow":[`none`,f,fn,on]}],"text-shadow-color":[{"text-shadow":F()}],opacity:[{opacity:[Vt,W,U]}],"mix-blend":[{"mix-blend":[...ae(),`plus-darker`,`plus-lighter`]}],"bg-blend":[{"bg-blend":ae()}],"mask-clip":[{"mask-clip":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]},`mask-no-clip`],"mask-composite":[{mask:[`add`,`subtract`,`intersect`,`exclude`]}],"mask-image-linear-pos":[{"mask-linear":[Vt]}],"mask-image-linear-from-pos":[{"mask-linear-from":z()}],"mask-image-linear-to-pos":[{"mask-linear-to":z()}],"mask-image-linear-from-color":[{"mask-linear-from":F()}],"mask-image-linear-to-color":[{"mask-linear-to":F()}],"mask-image-t-from-pos":[{"mask-t-from":z()}],"mask-image-t-to-pos":[{"mask-t-to":z()}],"mask-image-t-from-color":[{"mask-t-from":F()}],"mask-image-t-to-color":[{"mask-t-to":F()}],"mask-image-r-from-pos":[{"mask-r-from":z()}],"mask-image-r-to-pos":[{"mask-r-to":z()}],"mask-image-r-from-color":[{"mask-r-from":F()}],"mask-image-r-to-color":[{"mask-r-to":F()}],"mask-image-b-from-pos":[{"mask-b-from":z()}],"mask-image-b-to-pos":[{"mask-b-to":z()}],"mask-image-b-from-color":[{"mask-b-from":F()}],"mask-image-b-to-color":[{"mask-b-to":F()}],"mask-image-l-from-pos":[{"mask-l-from":z()}],"mask-image-l-to-pos":[{"mask-l-to":z()}],"mask-image-l-from-color":[{"mask-l-from":F()}],"mask-image-l-to-color":[{"mask-l-to":F()}],"mask-image-x-from-pos":[{"mask-x-from":z()}],"mask-image-x-to-pos":[{"mask-x-to":z()}],"mask-image-x-from-color":[{"mask-x-from":F()}],"mask-image-x-to-color":[{"mask-x-to":F()}],"mask-image-y-from-pos":[{"mask-y-from":z()}],"mask-image-y-to-pos":[{"mask-y-to":z()}],"mask-image-y-from-color":[{"mask-y-from":F()}],"mask-image-y-to-color":[{"mask-y-to":F()}],"mask-image-radial":[{"mask-radial":[W,U]}],"mask-image-radial-from-pos":[{"mask-radial-from":z()}],"mask-image-radial-to-pos":[{"mask-radial-to":z()}],"mask-image-radial-from-color":[{"mask-radial-from":F()}],"mask-image-radial-to-color":[{"mask-radial-to":F()}],"mask-image-radial-shape":[{"mask-radial":[`circle`,`ellipse`]}],"mask-image-radial-size":[{"mask-radial":[{closest:[`side`,`corner`],farthest:[`side`,`corner`]}]}],"mask-image-radial-pos":[{"mask-radial-at":b()}],"mask-image-conic-pos":[{"mask-conic":[Vt]}],"mask-image-conic-from-pos":[{"mask-conic-from":z()}],"mask-image-conic-to-pos":[{"mask-conic-to":z()}],"mask-image-conic-from-color":[{"mask-conic-from":F()}],"mask-image-conic-to-color":[{"mask-conic-to":F()}],"mask-mode":[{mask:[`alpha`,`luminance`,`match`]}],"mask-origin":[{"mask-origin":[`border`,`padding`,`content`,`fill`,`stroke`,`view`]}],"mask-position":[{mask:te()}],"mask-repeat":[{mask:I()}],"mask-size":[{mask:L()}],"mask-type":[{"mask-type":[`alpha`,`luminance`]}],"mask-image":[{mask:[`none`,W,U]}],filter:[{filter:[``,`none`,W,U]}],blur:[{blur:oe()}],brightness:[{brightness:[Vt,W,U]}],contrast:[{contrast:[Vt,W,U]}],"drop-shadow":[{"drop-shadow":[``,`none`,p,fn,on]}],"drop-shadow-color":[{"drop-shadow":F()}],grayscale:[{grayscale:[``,Vt,W,U]}],"hue-rotate":[{"hue-rotate":[Vt,W,U]}],invert:[{invert:[``,Vt,W,U]}],saturate:[{saturate:[Vt,W,U]}],sepia:[{sepia:[``,Vt,W,U]}],"backdrop-filter":[{"backdrop-filter":[``,`none`,W,U]}],"backdrop-blur":[{"backdrop-blur":oe()}],"backdrop-brightness":[{"backdrop-brightness":[Vt,W,U]}],"backdrop-contrast":[{"backdrop-contrast":[Vt,W,U]}],"backdrop-grayscale":[{"backdrop-grayscale":[``,Vt,W,U]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[Vt,W,U]}],"backdrop-invert":[{"backdrop-invert":[``,Vt,W,U]}],"backdrop-opacity":[{"backdrop-opacity":[Vt,W,U]}],"backdrop-saturate":[{"backdrop-saturate":[Vt,W,U]}],"backdrop-sepia":[{"backdrop-sepia":[``,Vt,W,U]}],"border-collapse":[{border:[`collapse`,`separate`]}],"border-spacing":[{"border-spacing":w()}],"border-spacing-x":[{"border-spacing-x":w()}],"border-spacing-y":[{"border-spacing-y":w()}],"table-layout":[{table:[`auto`,`fixed`]}],caption:[{caption:[`top`,`bottom`]}],transition:[{transition:[``,`all`,`colors`,`opacity`,`shadow`,`transform`,`none`,W,U]}],"transition-behavior":[{transition:[`normal`,`discrete`]}],duration:[{duration:[Vt,`initial`,W,U]}],ease:[{ease:[`linear`,`initial`,_,W,U]}],delay:[{delay:[Vt,W,U]}],animate:[{animate:[`none`,v,W,U]}],backface:[{backface:[`hidden`,`visible`]}],perspective:[{perspective:[h,W,U]}],"perspective-origin":[{"perspective-origin":x()}],rotate:[{rotate:se()}],"rotate-x":[{"rotate-x":se()}],"rotate-y":[{"rotate-y":se()}],"rotate-z":[{"rotate-z":se()}],scale:[{scale:ce()}],"scale-x":[{"scale-x":ce()}],"scale-y":[{"scale-y":ce()}],"scale-z":[{"scale-z":ce()}],"scale-3d":[`scale-3d`],skew:[{skew:le()}],"skew-x":[{"skew-x":le()}],"skew-y":[{"skew-y":le()}],transform:[{transform:[W,U,``,`none`,`gpu`,`cpu`]}],"transform-origin":[{origin:x()}],"transform-style":[{transform:[`3d`,`flat`]}],translate:[{translate:ue()}],"translate-x":[{"translate-x":ue()}],"translate-y":[{"translate-y":ue()}],"translate-z":[{"translate-z":ue()}],"translate-none":[`translate-none`],zoom:[{zoom:[Ht,W,U]}],accent:[{accent:F()}],appearance:[{appearance:[`none`,`auto`]}],"caret-color":[{caret:F()}],"color-scheme":[{scheme:[`normal`,`dark`,`light`,`light-dark`,`only-dark`,`only-light`]}],cursor:[{cursor:[`auto`,`default`,`pointer`,`wait`,`text`,`move`,`help`,`not-allowed`,`none`,`context-menu`,`progress`,`cell`,`crosshair`,`vertical-text`,`alias`,`copy`,`no-drop`,`grab`,`grabbing`,`all-scroll`,`col-resize`,`row-resize`,`n-resize`,`e-resize`,`s-resize`,`w-resize`,`ne-resize`,`nw-resize`,`se-resize`,`sw-resize`,`ew-resize`,`ns-resize`,`nesw-resize`,`nwse-resize`,`zoom-in`,`zoom-out`,W,U]}],"field-sizing":[{"field-sizing":[`fixed`,`content`]}],"pointer-events":[{"pointer-events":[`auto`,`none`]}],resize:[{resize:[`none`,``,`y`,`x`]}],"scroll-behavior":[{scroll:[`auto`,`smooth`]}],"scrollbar-thumb-color":[{"scrollbar-thumb":F()}],"scrollbar-track-color":[{"scrollbar-track":F()}],"scrollbar-gutter":[{"scrollbar-gutter":[`auto`,`stable`,`both`]}],"scrollbar-w":[{scrollbar:[`auto`,`thin`,`none`]}],"scroll-m":[{"scroll-m":w()}],"scroll-mx":[{"scroll-mx":w()}],"scroll-my":[{"scroll-my":w()}],"scroll-ms":[{"scroll-ms":w()}],"scroll-me":[{"scroll-me":w()}],"scroll-mbs":[{"scroll-mbs":w()}],"scroll-mbe":[{"scroll-mbe":w()}],"scroll-mt":[{"scroll-mt":w()}],"scroll-mr":[{"scroll-mr":w()}],"scroll-mb":[{"scroll-mb":w()}],"scroll-ml":[{"scroll-ml":w()}],"scroll-p":[{"scroll-p":w()}],"scroll-px":[{"scroll-px":w()}],"scroll-py":[{"scroll-py":w()}],"scroll-ps":[{"scroll-ps":w()}],"scroll-pe":[{"scroll-pe":w()}],"scroll-pbs":[{"scroll-pbs":w()}],"scroll-pbe":[{"scroll-pbe":w()}],"scroll-pt":[{"scroll-pt":w()}],"scroll-pr":[{"scroll-pr":w()}],"scroll-pb":[{"scroll-pb":w()}],"scroll-pl":[{"scroll-pl":w()}],"snap-align":[{snap:[`start`,`end`,`center`,`align-none`]}],"snap-stop":[{snap:[`normal`,`always`]}],"snap-type":[{snap:[`none`,`x`,`y`,`both`]}],"snap-strictness":[{snap:[`mandatory`,`proximity`]}],touch:[{touch:[`auto`,`none`,`manipulation`]}],"touch-x":[{"touch-pan":[`x`,`left`,`right`]}],"touch-y":[{"touch-pan":[`y`,`up`,`down`]}],"touch-pz":[`touch-pinch-zoom`],select:[{select:[`none`,`text`,`all`,`auto`]}],"will-change":[{"will-change":[`auto`,`scroll`,`contents`,`transform`,W,U]}],fill:[{fill:[`none`,...F()]}],"stroke-w":[{stroke:[Vt,sn,$t,en]}],stroke:[{stroke:[`none`,...F()]}],"forced-color-adjust":[{"forced-color-adjust":[`auto`,`none`]}]},conflictingClassGroups:{"container-named":[`container-type`],overflow:[`overflow-x`,`overflow-y`],overscroll:[`overscroll-x`,`overscroll-y`],inset:[`inset-x`,`inset-y`,`inset-bs`,`inset-be`,`start`,`end`,`top`,`right`,`bottom`,`left`],"inset-x":[`right`,`left`],"inset-y":[`top`,`bottom`],flex:[`basis`,`grow`,`shrink`],gap:[`gap-x`,`gap-y`],p:[`px`,`py`,`ps`,`pe`,`pbs`,`pbe`,`pt`,`pr`,`pb`,`pl`],px:[`pr`,`pl`],py:[`pt`,`pb`],m:[`mx`,`my`,`ms`,`me`,`mbs`,`mbe`,`mt`,`mr`,`mb`,`ml`],mx:[`mr`,`ml`],my:[`mt`,`mb`],size:[`w`,`h`],"font-size":[`leading`],"fvn-normal":[`fvn-ordinal`,`fvn-slashed-zero`,`fvn-figure`,`fvn-spacing`,`fvn-fraction`],"fvn-ordinal":[`fvn-normal`],"fvn-slashed-zero":[`fvn-normal`],"fvn-figure":[`fvn-normal`],"fvn-spacing":[`fvn-normal`],"fvn-fraction":[`fvn-normal`],"line-clamp":[`display`,`overflow`],rounded:[`rounded-s`,`rounded-e`,`rounded-t`,`rounded-r`,`rounded-b`,`rounded-l`,`rounded-ss`,`rounded-se`,`rounded-ee`,`rounded-es`,`rounded-tl`,`rounded-tr`,`rounded-br`,`rounded-bl`],"rounded-s":[`rounded-ss`,`rounded-es`],"rounded-e":[`rounded-se`,`rounded-ee`],"rounded-t":[`rounded-tl`,`rounded-tr`],"rounded-r":[`rounded-tr`,`rounded-br`],"rounded-b":[`rounded-br`,`rounded-bl`],"rounded-l":[`rounded-tl`,`rounded-bl`],"border-spacing":[`border-spacing-x`,`border-spacing-y`],"border-w":[`border-w-x`,`border-w-y`,`border-w-s`,`border-w-e`,`border-w-bs`,`border-w-be`,`border-w-t`,`border-w-r`,`border-w-b`,`border-w-l`],"border-w-x":[`border-w-r`,`border-w-l`],"border-w-y":[`border-w-t`,`border-w-b`],"border-color":[`border-color-x`,`border-color-y`,`border-color-s`,`border-color-e`,`border-color-bs`,`border-color-be`,`border-color-t`,`border-color-r`,`border-color-b`,`border-color-l`],"border-color-x":[`border-color-r`,`border-color-l`],"border-color-y":[`border-color-t`,`border-color-b`],translate:[`translate-x`,`translate-y`,`translate-none`],"translate-none":[`translate`,`translate-x`,`translate-y`,`translate-z`],"scroll-m":[`scroll-mx`,`scroll-my`,`scroll-ms`,`scroll-me`,`scroll-mbs`,`scroll-mbe`,`scroll-mt`,`scroll-mr`,`scroll-mb`,`scroll-ml`],"scroll-mx":[`scroll-mr`,`scroll-ml`],"scroll-my":[`scroll-mt`,`scroll-mb`],"scroll-p":[`scroll-px`,`scroll-py`,`scroll-ps`,`scroll-pe`,`scroll-pbs`,`scroll-pbe`,`scroll-pt`,`scroll-pr`,`scroll-pb`,`scroll-pl`],"scroll-px":[`scroll-pr`,`scroll-pl`],"scroll-py":[`scroll-pt`,`scroll-pb`],touch:[`touch-x`,`touch-y`,`touch-pz`],"touch-x":[`touch`],"touch-y":[`touch`],"touch-pz":[`touch`]},conflictingClassGroupModifiers:{"font-size":[`leading`]},postfixLookupClassGroups:[`container-type`],orderSensitiveModifiers:[`*`,`**`,`after`,`backdrop`,`before`,`details-content`,`file`,`first-letter`,`first-line`,`marker`,`placeholder`,`selection`]}});function G(...e){return wn(Ze(e))}var Tn=1e3,En=60*Tn,Dn=60*En,On=24*Dn,kn=30*Tn;function An(e){if(e==null||e<=0)return null;let t=Date.now()-e;return t<kn?`just now`:t<Dn?`${String(Math.floor(t/En))}m ago`:t<On?`${String(Math.floor(t/Dn))}h ago`:`${String(Math.floor(t/On))}d ago`}var jn=/^(\d{4})-(\d{2})-(\d{2})/,Mn=/^(\d{2}):(\d{2})(?::(\d{2}))?$/;function Nn(e,t){let n=jn.exec(e);if(n===null)return e;let r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=new Date(r,i-1,a);if(Number.isNaN(o.getTime()))return e;try{return o.toLocaleDateString(t)}catch{return e}}function Pn(e,t){let n=Mn.exec(e);if(n===null)return e;let r=new Date(1970,0,1,Number(n[1]),Number(n[2]),n[3]===void 0?0:Number(n[3]));if(Number.isNaN(r.getTime()))return e;try{return r.toLocaleTimeString(t,{hour:`2-digit`,minute:`2-digit`})}catch{return e}}function Fn(e,t){let n=e.includes(`T`)?e:e.replace(` `,`T`),r=new Date(n);if(Number.isNaN(r.getTime()))return e;try{return r.toLocaleString(t,{dateStyle:`medium`,timeStyle:`short`})}catch{return e}}function In(e,t,n){return e===``?e:t===`date`?Nn(e,n):t===`time`?Pn(e,n):Fn(e,n)}function Ln(e){if(typeof e!=`object`||!e)return null;let t=Reflect.get(e,`data`);if(typeof t==`object`&&t){let e=Reflect.get(t,`capRouteReason`);if(typeof e==`string`)return e}return null}function Rn(e){let t=Ln(e);return t===null?(e instanceof Error?e.message:String(e)).includes(`provider not available`):t===`no-provider`||t===`node-offline`}var zn=`rounded-lg border border-border bg-surface overflow-hidden`,Bn=`border-b border-border px-3 sm:px-4 py-1.5 sm:py-2`,Vn=`p-2 sm:p-3 lg:p-4`,Hn=`space-y-3 sm:space-y-4`,Un=`gap-2 sm:gap-3`,Wn=`px-3 sm:px-4 py-1.5 sm:py-2`,Gn=`grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4`,Kn=`grid grid-cols-1 lg:grid-cols-2`,qn=`flex flex-col-reverse md:flex-row`,Jn=`w-full md:w-44 lg:w-52 md:flex-shrink-0 border-b md:border-b-0 md:border-l border-border`,Yn=`text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider`,Xn=`text-[11px] sm:text-xs text-foreground`,Zn=`text-[10px] text-foreground-subtle`,Qn=`text-[11px] sm:text-xs font-medium text-foreground`,$n=`text-base sm:text-lg font-semibold leading-tight text-foreground`,er=`inline-flex items-center justify-center gap-1 rounded border border-border bg-surface px-1.5 py-0.5 sm:px-2 sm:py-1 text-[10px] sm:text-[11px] font-medium text-foreground hover:bg-surface-hover transition-colors disabled:opacity-40`,tr=`inline-flex items-center justify-center gap-1 rounded border border-primary/40 bg-primary/15 px-1.5 py-0.5 sm:px-2 sm:py-1 text-[10px] sm:text-[11px] font-medium text-primary hover:bg-primary/25 transition-colors disabled:opacity-40`,nr=`inline-flex items-center justify-center gap-1 rounded border border-danger/40 bg-danger/10 px-1.5 py-0.5 sm:px-2 sm:py-1 text-[10px] sm:text-[11px] font-medium text-danger hover:bg-danger/20 transition-colors disabled:opacity-40`,rr=`inline-flex items-center justify-center gap-1 rounded border border-warning/40 bg-warning/10 px-1.5 py-0.5 sm:px-2 sm:py-1 text-[10px] sm:text-[11px] font-medium text-warning hover:bg-warning/20 transition-colors disabled:opacity-40`,ir=`w-full rounded border border-border bg-background px-1.5 py-0.5 sm:px-2 sm:py-1 text-[11px] sm:text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none`,ar=`inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-medium transition-colors`,or=`border-primary/50 bg-primary/15 text-primary`,sr=`border-border bg-surface text-foreground-subtle hover:bg-surface-hover`;function cr(e,t){for(let n of e.slots)for(let e of n.addons)if(e.id===t)return e;return null}function lr(e,t){return e.models.find(e=>e.id===t)??null}function ur(e,t){return e.models.find(e=>!!e.formats[t])??null}function dr(e,t){let n=new Set((t.configSchema??[]).map(e=>e.key)),r={};for(let[t,i]of Object.entries(e))n.has(t)&&(r[t]=i);return r}function fr(e){let{source:t,target:n,catalog:r,addonIds:i}=e,a=[];for(let e of i){let i=t.defaults[e];if(!i){a.push({addonId:e,outcome:`skip`,modelId:null,reason:`no source entry`,patch:null});continue}let o=cr(r,e);if(!o){a.push({addonId:e,outcome:`skip`,modelId:null,reason:`addon not in target catalog`,patch:null});continue}let s=lr(o,i.modelId),c=s!==null&&!!s.formats[n.engine.format],l,u;if(c)l=i.modelId,u=`exact`;else{let t=ur(o,n.engine.format);if(!t){a.push({addonId:e,outcome:`skip`,modelId:null,reason:`no compatible model for target format`,patch:null});continue}l=t.id,u=`mapped`}let d={enabled:i.enabled,modelId:l,settings:dr(i.settings,o)};a.push({addonId:e,outcome:u,modelId:l,patch:d})}return a}var pr={idle:{label:`Idle`,textColor:`text-foreground-subtle`,badgeClass:`border-border bg-surface-hover text-foreground-subtle`,dotClass:`bg-gray-400`,icon:`PowerOff`},active:{label:`Active`,textColor:`text-success`,badgeClass:`border-success/40 bg-success/10 text-success`,dotClass:`bg-red-500 animate-pulse`,icon:`Activity`},watching:{label:`Watching`,textColor:`text-foreground-subtle`,badgeClass:`border-border bg-surface-hover text-foreground-subtle`,dotClass:`bg-emerald-500`,icon:`Eye`},"load-shed":{label:`Load-Shed`,textColor:`text-amber-500`,badgeClass:`border-amber-500/40 bg-amber-500/10 text-amber-500`,dotClass:`bg-amber-500`,icon:`AlertTriangle`},paused:{label:`Paused`,textColor:`text-gray-400`,badgeClass:`border-gray-500/40 bg-gray-500/10 text-gray-400`,dotClass:`bg-gray-400`,icon:`PauseCircle`}};function mr(e){return pr[e]??pr.watching}function hr(e,t){if(typeof globalThis>`u`)return r(t);let n=globalThis.__camstackSharedContexts,i=n??new Map;n||(globalThis.__camstackSharedContexts=i);let a=i.get(e);if(a)return a;let o=r(t);return i.set(e,o),o}var gr=`FEDERATION_DEBUG`,_r={AT:`@`,HYPHEN:`-`,SLASH:`/`},vr={[_r.AT]:`scope_`,[_r.HYPHEN]:`_`,[_r.SLASH]:`__`};vr[_r.AT],_r.AT,vr[_r.HYPHEN],_r.HYPHEN,vr[_r.SLASH],_r.SLASH;var yr=function(e){return e[e.UNKNOWN=1]=`UNKNOWN`,e[e.CALCULATED=2]=`CALCULATED`,e[e.NO_USE=0]=`NO_USE`,e}({}),br=!0;function xr(){return br}function Sr(){return typeof navigator<`u`&&navigator?.product===`ReactNative`}function Cr(){try{if(xr()&&window.localStorage)return!!localStorage.getItem(gr)}catch{return!1}return!1}function wr(){return typeof process<`u`&&{}.FEDERATION_DEBUG?!!{}.FEDERATION_DEBUG:typeof FEDERATION_DEBUG<`u`&&FEDERATION_DEBUG?!0:Cr()}var Tr=`[ Federation Runtime ]`,Er=function(...e){return e.length?e.reduce((e,t)=>t?e?`${e}:${t}`:t:e,``):``},Dr=(e,t)=>{if(`getPublicPath`in e){let n;return n=e.getPublicPath.startsWith(`function`)?Function(`return `+e.getPublicPath)()():Function(e.getPublicPath)(),`${n}${t}`}else if(`publicPath`in e)return!xr()&&!Sr()&&`ssrPublicPath`in e&&typeof e.ssrPublicPath==`string`?`${e.ssrPublicPath}${t}`:`${e.publicPath}${t}`;else return console.warn(`Cannot get resource URL. If in debug mode, please ignore.`,e,t),``},Or=e=>{console.warn(`${Tr}: ${e}`)};function kr(e){try{return JSON.stringify(e,null,2)}catch{return``}}var Ar=(e,t)=>{if(!e)return t;let n=(e=>{if(e===`.`)return``;if(e.startsWith(`./`))return e.replace(`./`,``);if(e.startsWith(`/`)){let t=e.slice(1);return t.endsWith(`/`)?t.slice(0,-1):t}return e})(e);return n?n.endsWith(`/`)?`${n}${t}`:`${n}/${t}`:t};function jr(e){return e.replace(/#.*$/,``).replace(/\?.*$/,``).replace(/\/[^\/]+$/,`/`)}function Mr(e,t={}){let{remotes:n={},overrides:r={},version:i}=t,a,o=()=>`publicPath`in e.metaData?(e.metaData.publicPath===`auto`||e.metaData.publicPath===``)&&i?jr(i):e.metaData.publicPath:e.metaData.getPublicPath,s=Object.keys(r),c={};Object.keys(n).length||(c=e.remotes?.reduce((e,t)=>{let n,i=t.federationContainerName;return n=s.includes(i)?r[i]:`version`in t?t.version:t.entry,e[i]={matchedVersion:n},e},{})||{}),Object.keys(n).forEach(e=>c[e]={matchedVersion:s.includes(e)?r[e]:n[e]});let{remoteEntry:{path:l,name:u,type:d},types:f={path:``,name:``,zip:``,api:``},buildInfo:{buildVersion:p},globalName:m,ssrRemoteEntry:h}=e.metaData,{exposes:g}=e,_={version:i||``,buildVersion:p,globalName:m,remoteEntry:Ar(l,u),remoteEntryType:d,remoteTypes:Ar(f.path,f.name),remoteTypesZip:f.zip||``,remoteTypesAPI:f.api||``,remotesInfo:c,shared:e?.shared.map(e=>({assets:e.assets,sharedName:e.name,version:e.version,usedExports:e.referenceExports||[]})),modules:g?.map(e=>({moduleName:e.name,modulePath:e.path,assets:e.assets}))};if(`publicPath`in e.metaData?(a={..._,publicPath:o()},typeof e.metaData.ssrPublicPath==`string`&&(a.ssrPublicPath=e.metaData.ssrPublicPath)):a={..._,getPublicPath:o()},h){let e=Ar(h.path,h.name);a.ssrRemoteEntry=e,a.ssrRemoteEntryType=h.type||`commonjs-module`}return a}function Nr(e){return!!(`remoteEntry`in e&&e.remoteEntry.includes(`.json`))}var Pr=`[ Module Federation ]`,Fr=console,Ir=[`logger.ts`,`logger.js`,`captureStackTrace`,`Logger.emit`,`Logger.log`,`Logger.info`,`Logger.warn`,`Logger.error`,`Logger.debug`];function Lr(){try{let e=Error().stack;if(!e)return;let[,...t]=e.split(`
31
- `),n=t.filter(e=>!Ir.some(t=>e.includes(t)));return n.length?`Stack trace:\n${n.slice(0,5).join(`
32
- `)}`:void 0}catch{return}}var Rr=class{constructor(e,t=Fr){this.prefix=e,this.delegate=t??Fr}setPrefix(e){this.prefix=e}setDelegate(e){this.delegate=e??Fr}emit(e,t){let n=this.delegate,r=wr()?Lr():void 0,i=r?[...t,r]:t,a=(()=>{switch(e){case`log`:return[`log`,`info`];case`info`:return[`info`,`log`];case`warn`:return[`warn`,`info`,`log`];case`error`:return[`error`,`warn`,`log`];default:return[`debug`,`log`]}})();for(let e of a){let t=n[e];if(typeof t==`function`){t.call(n,this.prefix,...i);return}}for(let e of a){let t=Fr[e];if(typeof t==`function`){t.call(Fr,this.prefix,...i);return}}}log(...e){this.emit(`log`,e)}warn(...e){this.emit(`warn`,e)}error(...e){this.emit(`error`,e)}success(...e){this.emit(`info`,e)}info(...e){this.emit(`info`,e)}ready(...e){this.emit(`info`,e)}debug(...e){wr()&&this.emit(`debug`,e)}};function zr(e){return new Rr(e)}function Br(e){let t=new Rr(e);return Object.defineProperty(t,"__mf_infrastructure_logger__",{value:!0,enumerable:!1,configurable:!1}),t}zr(Pr),Br(Pr);async function Vr(e,t){try{return await e()}catch(e){!t&&Or(e);return}}function Hr(e,t){let n=/^(https?:)?\/\//i;return e.replace(n,``).replace(/\/$/,``)===t.replace(n,``).replace(/\/$/,``)}function Ur(e){let t=null,n=!0,r=2e4,i,a=document.getElementsByTagName(`script`);for(let r=0;r<a.length;r++){let i=a[r],o=i.getAttribute(`src`);if(o&&Hr(o,e.url)){t=i,n=!1;break}}if(!t){let n=e.attrs;t=document.createElement(`script`),t.type=n?.type===`module`?`module`:`text/javascript`;let i;e.createScriptHook&&(i=e.createScriptHook(e.url,e.attrs),i instanceof HTMLScriptElement?t=i:typeof i==`object`&&(`script`in i&&i.script&&(t=i.script),`timeout`in i&&i.timeout&&(r=i.timeout))),t.src||=e.url,n&&!i&&Object.keys(n).forEach(e=>{t&&(e===`async`||e===`defer`?t[e]=n[e]:t.getAttribute(e)||t.setAttribute(e,n[e]))})}let o=null,s=typeof window<`u`?t=>{if(t.filename&&Hr(t.filename,e.url)){let n=Error(`ScriptExecutionError: Script "${e.url}" loaded but threw a runtime error during execution: ${t.message} (${t.filename}:${t.lineno}:${t.colno})`);n.name=`ScriptExecutionError`,o=n}}:null;s&&window.addEventListener(`error`,s);let c=async(n,r)=>{clearTimeout(i),s&&window.removeEventListener(`error`,s);let a=()=>{if(r?.type===`error`){let t=Error(r?.isTimeout?`ScriptNetworkError: Script "${e.url}" timed out.`:`ScriptNetworkError: Failed to load script "${e.url}" - the script URL is unreachable or the server returned an error (network failure, 404, CORS, etc.)`);t.name=`ScriptNetworkError`,e?.onErrorCallback&&e?.onErrorCallback(t)}else o?e?.onErrorCallback&&e?.onErrorCallback(o):e?.cb&&e?.cb()};if(t&&(t.onerror=null,t.onload=null,Vr(()=>{let{needDeleteScript:n=!0}=e;n&&t?.parentNode&&t.parentNode.removeChild(t)}),n&&typeof n==`function`)){let e=n(r);if(e instanceof Promise){let t=await e;return a(),t}return a(),e}a()};return t.onerror=c.bind(null,t.onerror),t.onload=c.bind(null,t.onload),i=setTimeout(()=>{c(null,{type:`error`,isTimeout:!0})},r),{script:t,needAttach:n}}function Wr(e){let t=null,n=!0,r=2e4,i,a=document.getElementsByTagName(`link`);for(let r=0;r<a.length;r++){let i=a[r],o=i.getAttribute(`href`),s=i.getAttribute(`rel`);if(o&&Hr(o,e.url)&&s===e.attrs.rel){t=i,n=!1;break}}if(!t){t=document.createElement(`link`),t.setAttribute(`href`,e.url);let n,i=!0,a=e.attrs;e.createLinkHook&&(n=e.createLinkHook(e.url,a),n instanceof HTMLLinkElement?(t=n,i=!1):typeof n==`object`&&(`link`in n&&n.link&&(t=n.link,i=!1),`timeout`in n&&n.timeout&&(r=n.timeout))),a&&i&&Object.keys(a).forEach(e=>{t&&!t.getAttribute(e)&&t.setAttribute(e,a[e])})}if(!n)return Promise.resolve().then(()=>{e?.cb&&e?.cb()}),{link:t,needAttach:n};let o=(n,r)=>{i&&clearTimeout(i);let a=()=>{if(r?.type===`error`){let t=Error(r?.isTimeout?`LinkNetworkError: Link "${e.url}" timed out.`:`LinkNetworkError: Failed to load link "${e.url}" - the URL is unreachable or the server returned an error.`);t.name=`LinkNetworkError`,e?.onErrorCallback&&e?.onErrorCallback(t)}else e?.cb&&e?.cb()};if(t&&(t.onerror=null,t.onload=null,Vr(()=>{let{needDeleteLink:n=!0}=e;n&&t?.parentNode&&t.parentNode.removeChild(t)}),n)){let e=n(r);return a(),e}a()};return t.onerror=o.bind(null,t.onerror),t.onload=o.bind(null,t.onload),i=setTimeout(()=>{o(null,{type:`error`,isTimeout:!0})},r),{link:t,needAttach:n}}function Gr(e,t){let{attrs:n={},createScriptHook:r}=t;return new Promise((t,i)=>{let{script:a,needAttach:o}=Ur({url:e,cb:t,onErrorCallback:i,attrs:{fetchpriority:`high`,...n},createScriptHook:r,needDeleteScript:!0});o&&document.head.appendChild(a)})}var Kr=e=>`View the docs to see how to solve: https://module-federation.io/guide/troubleshooting/${e.split(`-`)[0].toLowerCase()}#${e.toLowerCase()}`,qr=(e,t,n,r)=>{let i=[`${[t[e]]} #${e}`];return n&&i.push(`args: ${JSON.stringify(n)}`),i.push(Kr(e)),r&&i.push(`Original Error Message:\n ${r}`),i.join(`
33
- `)};function Jr(e,t,n,r,i,a){return r(qr(e,t,n,i))}var Yr=`[ Federation Runtime ]`,Xr=zr(Yr);function Zr(e,t,n,r,i){e||(n===void 0?Qr(t):Qr(t,n,r,void 0,i))}function Qr(e,t,n,r,i){if(t!==void 0)return Jr(e,t,n??{},e=>{throw Error(`${Yr}: ${e}`)},r,i);let a=e;throw a instanceof Error?(a.message.startsWith(Yr)||(a.message=`${Yr}: ${a.message}`),a):Error(`${Yr}: ${a}`)}function $r(e){e instanceof Error&&(e.message.startsWith(Yr)||(e.message=`${Yr}: ${e.message}`)),Xr.warn(e)}function ei(e,t){return e.findIndex(e=>e===t)===-1&&e.push(t),e}function ti(e){return`version`in e&&e.version?`${e.name}:${e.version}`:`entry`in e&&e.entry?`${e.name}:${e.entry}`:`${e.name}`}function ni(e){return e.entry!==void 0}function ri(e){return!e.entry.includes(`.json`)}function ii(e){return e&&typeof e==`object`}var ai=Object.prototype.toString;function oi(e){return ai.call(e)===`[object Object]`}function si(e){return Array.isArray(e)?e:[e]}function ci(e){let t={url:``,type:`global`,globalName:``};return br||Sr()||!(`ssrRemoteEntry`in e)?`remoteEntry`in e?{url:e.remoteEntry,type:e.remoteEntryType,globalName:e.globalName}:t:`ssrRemoteEntry`in e?{url:e.ssrRemoteEntry||t.url,type:e.ssrRemoteEntryType||t.type,globalName:e.globalName}:t}var li=(e,t)=>{let n;return n=e.endsWith(`/`)?e.slice(0,-1):e,t.startsWith(`.`)&&(t=t.slice(1)),n+=t,n},ui=typeof globalThis==`object`?globalThis:window,di=(()=>{try{return document.defaultView}catch{return ui}})(),fi=di;function pi(e,t,n){Object.defineProperty(e,t,{value:n,configurable:!1,writable:!0})}function mi(e,t){return Object.hasOwnProperty.call(e,t)}mi(ui,`__GLOBAL_LOADING_REMOTE_ENTRY__`)||pi(ui,`__GLOBAL_LOADING_REMOTE_ENTRY__`,{});var hi=ui.__GLOBAL_LOADING_REMOTE_ENTRY__;function gi(e){mi(e,`__VMOK__`)&&!mi(e,`__FEDERATION__`)&&pi(e,`__FEDERATION__`,e.__VMOK__),mi(e,`__FEDERATION__`)||(pi(e,`__FEDERATION__`,{__GLOBAL_PLUGIN__:[],__INSTANCES__:[],moduleInfo:{},__SHARE__:{},__MANIFEST_LOADING__:{},__PRELOADED_MAP__:new Map}),pi(e,`__VMOK__`,e.__FEDERATION__)),e.__FEDERATION__.__GLOBAL_PLUGIN__??=[],e.__FEDERATION__.__INSTANCES__??=[],e.__FEDERATION__.moduleInfo??={},e.__FEDERATION__.__SHARE__??={},e.__FEDERATION__.__MANIFEST_LOADING__??={},e.__FEDERATION__.__PRELOADED_MAP__??=new Map}gi(ui),gi(di);function _i(e){ui.__FEDERATION__.__INSTANCES__.push(e)}function vi(){return ui.__FEDERATION__.__DEBUG_CONSTRUCTOR__}function yi(e,t=wr()){t&&(ui.__FEDERATION__.__DEBUG_CONSTRUCTOR__=e,ui.__FEDERATION__.__DEBUG_CONSTRUCTOR_VERSION__=`2.5.1`)}function bi(e,t){if(typeof t==`string`){if(e[t])return{value:e[t],key:t};{let n=Object.keys(e);for(let r of n){let[n,i]=r.split(`:`),a=`${n}:${t}`,o=e[a];if(o)return{value:o,key:a}}return{value:void 0,key:t}}}else Qr(`getInfoWithoutType: "key" must be a string, got ${typeof t} (${JSON.stringify(t)}).`)}var xi=()=>di.__FEDERATION__.moduleInfo,Si=(e,t)=>{let n=bi(t,ti(e)).value;if(n&&!n.version&&`version`in e&&e.version&&(n.version=e.version),n)return n;if(`version`in e&&e.version){let{version:t,...n}=e,r=ti(n),i=bi(di.__FEDERATION__.moduleInfo,r).value;if(i?.version===t)return i}},Ci=e=>Si(e,di.__FEDERATION__.moduleInfo),wi=(e,t)=>{let n=ti(e);return di.__FEDERATION__.moduleInfo[n]=t,di.__FEDERATION__.moduleInfo},Ti=e=>(di.__FEDERATION__.moduleInfo={...di.__FEDERATION__.moduleInfo,...e},()=>{let t=Object.keys(e);for(let e of t)delete di.__FEDERATION__.moduleInfo[e]}),Ei=(e,t)=>{let n=t||`__FEDERATION_${e}:custom__`;return{remoteEntryKey:n,entryExports:ui[n]}},Di=()=>di.__FEDERATION__.__GLOBAL_PLUGIN__,Oi=e=>ui.__FEDERATION__.__PRELOADED_MAP__.get(e),ki=e=>ui.__FEDERATION__.__PRELOADED_MAP__.set(e,!0),Ai=`[0-9A-Za-z-]+`,ji=`(?:\\+(${Ai}(?:\\.${Ai})*))`,Mi=`0|[1-9]\\d*`,Ni=`[0-9]+`,Pi=`\\d*[a-zA-Z-][a-zA-Z0-9-]*`,Fi=`(?:${Ni}|${Pi})`,Ii=`(?:-?(${Fi}(?:\\.${Fi})*))`,Li=`(?:${Mi}|${Pi})`,Ri=`(?:-(${Li}(?:\\.${Li})*))`,zi=`${Mi}|x|X|\\*`,Bi=`[v=\\s]*(${zi})(?:\\.(${zi})(?:\\.(${zi})(?:${Ri})?${ji}?)?)?`,Vi=`^\\s*(${Bi})\\s+-\\s+(${Bi})\\s*$`,Hi=`[v=\\s]*${`(${Ni})\\.(${Ni})\\.(${Ni})`}${Ii}?${ji}?`,Ui=`((?:<|>)?=?)`,Wi=`(\\s*)${Ui}\\s*(${Hi}|${Bi})`,Gi=`(?:~>?)`,Ki=`(\\s*)${Gi}\\s+`,qi=`(?:\\^)`,Ji=`(\\s*)${qi}\\s+`,Yi=`(<|>)?=?\\s*\\*`,Xi=`^${qi}${Bi}$`,Zi=`v?${`(${Mi})\\.(${Mi})\\.(${Mi})`}${Ri}?${ji}?`,Qi=`^${Gi}${Bi}$`,$i=`^${Ui}\\s*${Bi}$`,ea=`^${Ui}\\s*(${Zi})$|^$`,ta=`^\\s*>=\\s*0.0.0\\s*$`;function na(e){return new RegExp(e)}function ra(e){return!e||e.toLowerCase()===`x`||e===`*`}function ia(...e){return t=>e.reduce((e,t)=>t(e),t)}function aa(e){return e.match(na(ea))}function oa(e,t,n,r){let i=`${e}.${t}.${n}`;return r?`${i}-${r}`:i}function sa(e){return e.replace(na(Vi),(e,t,n,r,i,a,o,s,c,l,u,d)=>(t=ra(n)?``:ra(r)?`>=${n}.0.0`:ra(i)?`>=${n}.${r}.0`:`>=${t}`,s=ra(c)?``:ra(l)?`<${Number(c)+1}.0.0-0`:ra(u)?`<${c}.${Number(l)+1}.0-0`:d?`<=${c}.${l}.${u}-${d}`:`<=${s}`,`${t} ${s}`.trim()))}function ca(e){return e.replace(na(Wi),`$1$2$3`)}function la(e){return e.replace(na(Ki),`$1~`)}function ua(e){return e.replace(na(Ji),`$1^`)}function da(e){return e.trim().split(/\s+/).map(e=>e.replace(na(Xi),(e,t,n,r,i)=>ra(t)?``:ra(n)?`>=${t}.0.0 <${Number(t)+1}.0.0-0`:ra(r)?t===`0`?`>=${t}.${n}.0 <${t}.${Number(n)+1}.0-0`:`>=${t}.${n}.0 <${Number(t)+1}.0.0-0`:i?t===`0`?n===`0`?`>=${t}.${n}.${r}-${i} <${t}.${n}.${Number(r)+1}-0`:`>=${t}.${n}.${r}-${i} <${t}.${Number(n)+1}.0-0`:`>=${t}.${n}.${r}-${i} <${Number(t)+1}.0.0-0`:t===`0`?n===`0`?`>=${t}.${n}.${r} <${t}.${n}.${Number(r)+1}-0`:`>=${t}.${n}.${r} <${t}.${Number(n)+1}.0-0`:`>=${t}.${n}.${r} <${Number(t)+1}.0.0-0`)).join(` `)}function fa(e){return e.trim().split(/\s+/).map(e=>e.replace(na(Qi),(e,t,n,r,i)=>ra(t)?``:ra(n)?`>=${t}.0.0 <${Number(t)+1}.0.0-0`:ra(r)?`>=${t}.${n}.0 <${t}.${Number(n)+1}.0-0`:i?`>=${t}.${n}.${r}-${i} <${t}.${Number(n)+1}.0-0`:`>=${t}.${n}.${r} <${t}.${Number(n)+1}.0-0`)).join(` `)}function pa(e){return e.split(/\s+/).map(e=>e.trim().replace(na($i),(e,t,n,r,i,a)=>{let o=ra(n),s=o||ra(r),c=s||ra(i);return t===`=`&&c&&(t=``),a=``,o?t===`>`||t===`<`?`<0.0.0-0`:`*`:t&&c?(s&&(r=0),i=0,t===`>`?(t=`>=`,s?(n=Number(n)+1,r=0,i=0):(r=Number(r)+1,i=0)):t===`<=`&&(t=`<`,s?n=Number(n)+1:r=Number(r)+1),t===`<`&&(a=`-0`),`${t+n}.${r}.${i}${a}`):s?`>=${n}.0.0${a} <${Number(n)+1}.0.0-0`:c?`>=${n}.${r}.0${a} <${n}.${Number(r)+1}.0-0`:e})).join(` `)}function ma(e){return e.trim().replace(na(Yi),``)}function ha(e){return e.trim().replace(na(ta),``)}function ga(e,t){return e=Number(e)||e,t=Number(t)||t,e>t?1:e===t?0:-1}function _a(e,t){let{preRelease:n}=e,{preRelease:r}=t;if(n===void 0&&r)return 1;if(n&&r===void 0)return-1;if(n===void 0&&r===void 0)return 0;for(let e=0,t=n.length;e<=t;e++){let t=n[e],i=r[e];if(t!==i)return t===void 0&&i===void 0?0:t?i?ga(t,i):-1:1}return 0}function va(e,t){return ga(e.major,t.major)||ga(e.minor,t.minor)||ga(e.patch,t.patch)||_a(e,t)}function ya(e,t){return e.version===t.version}function ba(e,t){switch(e.operator){case``:case`=`:return ya(e,t);case`>`:return va(e,t)<0;case`>=`:return ya(e,t)||va(e,t)<0;case`<`:return va(e,t)>0;case`<=`:return ya(e,t)||va(e,t)>0;case void 0:return!0;default:return!1}}function xa(e){return ia(da,fa,pa,ma)(e)}function Sa(e){return ia(sa,ca,la,ua)(e.trim()).split(/\s+/).join(` `)}function Ca(e,t){if(!e)return!1;let n=aa(e);if(!n)return!1;let[,r,,i,a,o,s]=n,c={operator:r,version:oa(i,a,o,s),major:i,minor:a,patch:o,preRelease:s?.split(`.`)},l=t.split(`||`);for(let e of l){let t=e.trim();if(!t||t===`*`||t===`x`)return!0;try{let e=Sa(t);if(!e.trim())return!0;let n=e.split(` `).map(e=>xa(e)).join(` `);if(!n.trim())return!0;let r=n.split(/\s+/).map(e=>ha(e)).filter(Boolean);if(r.length===0)continue;let i=!0;for(let e of r){let t=aa(e);if(!t){i=!1;break}let[,n,,r,a,o,s]=t;if(!ba({operator:n,version:oa(r,a,o,s),major:r,minor:a,patch:o,preRelease:s?.split(`.`)},c)){i=!1;break}}if(i)return!0}catch(e){console.error(`[semver] Error processing range part "${t}":`,e);continue}}return!1}var wa=`default`,Ta=`global`;function Ea(e,t,n,r){let i;return i=`get`in e?e.get:`lib`in e?()=>Promise.resolve(e.lib):()=>Promise.resolve(()=>{Qr(`Cannot get shared "${n}" from "${t}": neither "get" nor "lib" is provided in the share config.`)}),e.shareConfig?.eager&&e.treeShaking?.mode&&Qr(`Invalid shared config for "${n}" from "${t}": cannot use both "eager: true" and "treeShaking.mode" simultaneously. Choose one strategy.`),{deps:[],useIn:[],from:t,loading:null,...e,shareConfig:{requiredVersion:`^${e.version}`,singleton:!1,eager:!1,strictVersion:!1,...e.shareConfig},get:i,loaded:e?.loaded||`lib`in e?!0:void 0,version:e.version??`0`,scope:Array.isArray(e.scope)?e.scope:[e.scope??`default`],strategy:(e.strategy??r)||`version-first`,treeShaking:e.treeShaking?{...e.treeShaking,mode:e.treeShaking.mode??`server-calc`,status:e.treeShaking.status??yr.UNKNOWN,useIn:[]}:void 0}}function Da(e,t){let n=t.shared||{},r=t.name,i=Object.keys(n).reduce((e,i)=>{let a=si(n[i]);return e[i]=e[i]||[],a.forEach(n=>{e[i].push(Ea(n,r,i,t.shareStrategy))}),e},{}),a={...e.shared};return Object.keys(i).forEach(e=>{a[e]?i[e].forEach(t=>{a[e].find(e=>e.version===t.version)||a[e].push(t)}):a[e]=i[e]}),{allShareInfos:a,newShareInfos:i}}function Oa(e,t){if(!e)return!1;let{status:n,mode:r}=e;return n===yr.NO_USE?!1:n===yr.CALCULATED?!0:r===`runtime-infer`?t?Na(e,t):!0:!1}function ka(e,t){let n=e=>{if(!Number.isNaN(Number(e))){let t=e.split(`.`),n=e;for(let e=0;e<3-t.length;e++)n+=`.0`;return n}return e};return!!Ca(n(e),`<=${n(t)}`)}var Aa=(e,t)=>{let n=t||function(e,t){return ka(e,t)};return Object.keys(e).reduce((e,t)=>!e||n(e,t)||e===`0`?t:e,0)},ja=e=>!!e.loaded||typeof e.lib==`function`,Ma=e=>!!e.loading,Na=(e,t)=>{if(!e||!t)return!1;let{usedExports:n}=e;return n?!!t.every(e=>n.includes(e)):!1};function Pa(e,t,n,r){let i=e[t][n],a=``,o=Oa(r),s=function(e,t){return o?i[e].treeShaking?i[t].treeShaking?!ja(i[e].treeShaking)&&ka(e,t):!1:!0:!ja(i[e])&&ka(e,t)};if(o){if(a=Aa(e[t][n],s),a)return{version:a,useTreesShaking:o};o=!1}return{version:Aa(e[t][n],s),useTreesShaking:o}}var Fa=e=>ja(e)||Ma(e);function Ia(e,t,n,r){let i=e[t][n],a=``,o=Oa(r),s=function(e,t){if(o){if(!i[e].treeShaking)return!0;if(!i[t].treeShaking)return!1;if(Fa(i[t].treeShaking))return Fa(i[e].treeShaking)?!!ka(e,t):!0;if(Fa(i[e].treeShaking))return!1}return Fa(i[t])?Fa(i[e])?!!ka(e,t):!0:Fa(i[e])?!1:ka(e,t)};if(o){if(a=Aa(e[t][n],s),a)return{version:a,useTreesShaking:o};o=!1}return{version:Aa(e[t][n],s),useTreesShaking:o}}function La(e){return e===`loaded-first`?Ia:Pa}function Ra(e,t,n,r){if(!e)return;let{shareConfig:i,scope:a=wa,strategy:o,treeShaking:s}=n,c=Array.isArray(a)?a:[a];for(let a of c)if(i&&e[a]&&e[a][t]){let{requiredVersion:c}=i,{version:l,useTreesShaking:u}=La(o)(e,a,t,s),d={shareScopeMap:e,scope:a,pkgName:t,version:l,GlobalFederation:fi.__FEDERATION__,shareInfo:n,resolver:()=>{let r=e[a][t][l];if(i.singleton){if(typeof c==`string`&&!Ca(l,c)){let e=`Version ${l} from ${l&&r.from} of shared singleton module ${t} does not satisfy the requirement of ${n.from} which needs ${c})`;i.strictVersion?Qr(e):$r(e)}return{shared:r,useTreesShaking:u}}else{if(c===!1||c===`*`||Ca(l,c))return{shared:r,useTreesShaking:u};let n=Oa(s);if(n){for(let[r,i]of Object.entries(e[a][t]))if(Oa(i.treeShaking,s?.usedExports)&&Ca(r,c))return{shared:i,useTreesShaking:n}}for(let[n,r]of Object.entries(e[a][t]))if(Ca(n,c))return{shared:r,useTreesShaking:!1}}}};return(r.emit(d)||d).resolver()}}function za(){return fi.__FEDERATION__.__SHARE__}function Ba(e){let{pkgName:t,extraOptions:n,shareInfos:r}=e,i=n?.resolver??(e=>{if(!e)return;let t={};return e.forEach(e=>{t[e.version]=e}),t[Aa(t,function(e,n){return!ja(t[e])&&ka(e,n)})]}),a=e=>typeof e==`object`&&!!e&&!Array.isArray(e),o=(...e)=>{let t={};for(let n of e)if(n)for(let[e,r]of Object.entries(n)){let n=t[e];a(n)&&a(r)?t[e]=o(n,r):r!==void 0&&(t[e]=r)}return t};return o(i(r[t]),n?.customShareInfo)}var Va=(e,t)=>{e.useIn||=[],ei(e.useIn,t)};function Ha(e,t){return t&&e.treeShaking?e.treeShaking:e}function Ua(e,t){return!t||t===`.`?e:`${e}/${t.replace(/^\.\//,``)}`}function Wa(e,t){for(let n of e){let e=t.startsWith(n.name),r=t.replace(n.name,``);if(e){if(r.startsWith(`/`)){let e=n.name;return r=`.${r}`,{pkgNameOrAlias:e,expose:r,remote:n}}else if(r===``)return{pkgNameOrAlias:n.name,expose:`.`,remote:n}}let i=n.alias&&t.startsWith(n.alias),a=n.alias&&t.replace(n.alias,``);if(n.alias&&i){if(a&&a.startsWith(`/`)){let e=n.alias;return a=`.${a}`,{pkgNameOrAlias:e,expose:a,remote:n}}else if(a===``)return{pkgNameOrAlias:n.alias,expose:`.`,remote:n}}}}function Ga(e,t){for(let n of e)if(t===n.name||n.alias&&t===n.alias)return n}var Ka=`RUNTIME-001`,qa=`RUNTIME-002`,Ja=`RUNTIME-003`,Ya=`RUNTIME-004`,Xa=`RUNTIME-005`,Za=`RUNTIME-006`,Qa=`RUNTIME-007`,$a=`RUNTIME-008`,eo=`RUNTIME-009`,to=`RUNTIME-010`,no=`RUNTIME-011`,ro=`RUNTIME-012`,io=`RUNTIME-013`,ao=`RUNTIME-014`,oo=`RUNTIME-015`,so=`TYPE-001`,co=`BUILD-001`,lo=`BUILD-002`,uo={[Ka]:`Failed to get remoteEntry exports.`,[qa]:`The remote entry interface does not contain "init"`,[Ja]:`Failed to get manifest.`,[Ya]:`Failed to locate remote.`,[Xa]:`Invalid loadShareSync function call from bundler runtime`,[Za]:`Invalid loadShareSync function call from runtime`,[Qa]:`Failed to get remote snapshot.`,[$a]:`Failed to load script resources.`,[eo]:`Please call createInstance first.`,[to]:`The name option cannot be changed after initialization. If you want to create a new instance with a different name, please use "createInstance" api.`,[no]:`The remoteEntry URL is missing from the remote snapshot.`,[ro]:`The getter for the shared module is not a function. This may be caused by setting "shared.import: false" without the host providing the corresponding lib.`,[io]:`The manifest is not a valid Module Federation manifest.`,[ao]:`The remote does not expose the requested module.`,[oo]:`Remote container initialization failed.`},fo={[so]:`Failed to generate type declaration. Execute the below cmd to reproduce and fix the error.`},po={[co]:`Failed to find expose module.`,[lo]:`PublicPath is required in prod mode.`};({...uo,...fo,...po});var mo=`.then(callbacks[0]).catch(callbacks[1])`;async function ho({entry:t,remoteEntryExports:n}){return new Promise((r,i)=>{try{n?r(n):typeof FEDERATION_ALLOW_NEW_FUNCTION<`u`?Function(`callbacks`,`import("${t}")${mo}`)([r,i]):e(()=>import(t).then(r),[]).catch(i)}catch(e){Qr(`Failed to load ESM entry from "${t}". ${e instanceof Error?e.message:String(e)}`)}})}async function go({entry:e,remoteEntryExports:t}){return new Promise((n,r)=>{try{t?n(t):typeof __system_context__>`u`?System.import(e).then(n).catch(r):Function(`callbacks`,`System.import("${e}")${mo}`)([n,r])}catch(t){Qr(`Failed to load SystemJS entry from "${e}". ${t instanceof Error?t.message:String(t)}`)}})}function _o(e,t,n){let{remoteEntryKey:r,entryExports:i}=Ei(e,t);return i||Qr(Ka,uo,{remoteName:e,remoteEntryUrl:n,remoteEntryKey:r}),i}async function vo({name:e,globalName:t,entry:n,remoteInfo:r,loaderHook:i,getEntryUrl:a,resourceContext:o}){let{entryExports:s}=Ei(e,t);if(s)return s;let c=a?a(n):n;return Gr(c,{attrs:{},createScriptHook:(e,t)=>{let n=i.lifecycle.createScript.emit({url:e,attrs:t,remoteInfo:r,resourceContext:o?{...o,url:e}:void 0});if(n&&(n instanceof HTMLScriptElement||`script`in n||`timeout`in n))return n}}).then(()=>_o(e,t,n),t=>{let n=t instanceof Error?t.message:String(t);Qr($a,uo,{remoteName:e,resourceUrl:c},n)})}async function yo({remoteInfo:e,remoteEntryExports:t,loaderHook:n,getEntryUrl:r,resourceContext:i}){let{entry:a,entryGlobalName:o,name:s,type:c}=e;switch(c){case`esm`:case`module`:return ho({entry:a,remoteEntryExports:t});case`system`:return go({entry:a,remoteEntryExports:t});default:return vo({entry:a,globalName:o,name:s,remoteInfo:e,loaderHook:n,getEntryUrl:r,resourceContext:i})}}function bo(e){let{entry:t,name:n}=e;return Er(n,t)}async function xo(e){let{origin:t,remoteEntryExports:n,remoteInfo:r,getEntryUrl:i,resourceContext:a,_inErrorHandling:o=!1}=e,s=bo(r);if(n)return n;if(!hi[s]){let e=t.remoteHandler.hooks.lifecycle.loadEntry,c=t.loaderHook;hi[s]=e.emit({origin:t,loaderHook:c,remoteInfo:r,remoteEntryExports:n}).then(e=>e||yo({remoteInfo:r,remoteEntryExports:n,loaderHook:c,getEntryUrl:i,resourceContext:a})).then(async e=>(await t.loaderHook.lifecycle.afterLoadEntry.emit({origin:t,remoteInfo:r,remoteEntryExports:e}),e)).catch(async e=>{let i=bo(r),a=e instanceof Error&&e.message.includes(`ScriptExecutionError`);if(e instanceof Error&&e.message.includes(`RUNTIME-008`)&&!a&&!o){let e=await t.loaderHook.lifecycle.loadEntryError.emit({getRemoteEntry:e=>xo({...e,_inErrorHandling:!0}),origin:t,remoteInfo:r,remoteEntryExports:n,globalLoading:hi,uniqueKey:i});if(e)return await t.loaderHook.lifecycle.afterLoadEntry.emit({origin:t,remoteInfo:r,remoteEntryExports:e,recovered:!0}),e}throw await t.loaderHook.lifecycle.afterLoadEntry.emit({origin:t,remoteInfo:r,error:e}),e})}return hi[s]}function So(e){return{...e,entry:`entry`in e?e.entry:``,type:e.type||`global`,entryGlobalName:e.entryGlobalName||e.name,shareScope:e.shareScope||`default`}}function Co(){return typeof FEDERATION_BUILD_IDENTIFIER<`u`?FEDERATION_BUILD_IDENTIFIER:``}function wo(e,t){let n=Di(),r=[t.hooks,t.remoteHandler.hooks,t.sharedHandler.hooks,t.snapshotHandler.hooks,t.loaderHook,t.bridgeHook];return n.length>0&&n.forEach(t=>{e?.find(e=>e.name!==t.name)&&e.push(t)}),e&&e.length>0&&e.forEach(e=>{r.forEach(n=>{n.applyPlugin(e,t)})}),e}function To(e){return{name:e.name,alias:e.alias,entry:`entry`in e?e.entry:void 0,version:`version`in e?e.version:void 0,type:e.type,entryGlobalName:e.entryGlobalName,shareScope:e.shareScope}}function Eo(e){let t={};for(let[n,r]of Object.entries(e.shared)){let e=r[0];e&&(t[n]={version:e.version,singleton:e.shareConfig?.singleton,requiredVersion:e.shareConfig?.requiredVersion===!1?!1:e.shareConfig?.requiredVersion,eager:e.eager,strictVersion:e.shareConfig?.strictVersion})}return{project:{name:e.name,mfRole:e.remotes?.length>0?`host`:`unknown`},mfConfig:{name:e.name,remotes:e.remotes?.map(To)??[],shared:t}}}function Do(e){return{resourceCategory:`sync`,share:!0,depsRemote:!0,...e}}function Oo(e,t){return t.map(t=>{let n=Ga(e,t.nameOrAlias);return Zr(n,`Unable to preload ${t.nameOrAlias} as it is not included in ${!n&&kr({remoteInfo:n,remotes:e})}`),{remote:n,preloadConfig:Do(t)}})}function ko(e){return e?e.map(e=>e===`.`?e:e.startsWith(`./`)?e.replace(`./`,``):e):[]}function Ao(e){return e instanceof Error?e.message.includes(`timed out`)||e.name.includes(`Timeout`):!1}function jo(e,t,n,r){return{url:t,status:n,resourceType:e.resourceType,initiator:e.initiator,id:e.id,error:r}}async function Mo(e,t,n,r){let i=e.moduleCache.get(n.name),a=n.entry;if(i?.remoteEntryExports)return jo(r,a,`cached`);try{if(!await xo({origin:e,remoteInfo:n,remoteEntryExports:i?.remoteEntryExports,resourceContext:{...r,url:a}}))throw Error(`Failed to load remoteEntry "${a}".`);return jo(r,a,`success`)}catch(e){return jo(r,a,Ao(e)?`timeout`:`error`,e)}}function No({host:e,remoteInfo:t,url:n,attrs:r,context:i,needDeleteLink:a}){return new Promise(o=>{let{link:s,needAttach:c}=Wr({url:n,cb:()=>{o(jo(i,n,c?`success`:`cached`))},onErrorCallback:e=>{o(jo(i,n,Ao(e)?`timeout`:`error`,e))},attrs:r,createLinkHook:(n,r)=>{let a=e.loaderHook.lifecycle.createLink.emit({url:n,attrs:r,remoteInfo:t,resourceContext:{...i,url:n}});return a instanceof HTMLLinkElement,a},needDeleteLink:a});c&&document.head.appendChild(s)})}function Po({host:e,remoteInfo:t,url:n,attrs:r,context:i}){return new Promise(a=>{let{script:o,needAttach:s}=Ur({url:n,cb:()=>{a(jo(i,n,s?`success`:`cached`))},onErrorCallback:e=>{a(jo(i,n,Ao(e)?`timeout`:`error`,e))},attrs:r,createScriptHook:(n,r)=>{let a=e.loaderHook.lifecycle.createScript.emit({url:n,attrs:r,remoteInfo:t,resourceContext:{...i,url:n}});return a instanceof HTMLScriptElement,a},needDeleteScript:!0});s&&document.head.appendChild(o)})}function Fo(e,t){return{...e,resourceType:t}}function Io(e,t,n,r=!0,i={initiator:`preloadRemote`,id:e.name}){let{cssAssets:a,jsAssetsWithoutEntry:o,entryAssets:s}=n,c=[];if(t.options.inBrowser){if(s.forEach(n=>{let{moduleInfo:r}=n;c.push(Mo(t,e,r,Fo(i,`remoteEntry`)))}),r){let n={rel:`preload`,as:`style`};a.forEach(r=>{c.push(No({host:t,remoteInfo:e,url:r,attrs:n,context:Fo(i,`css`)}))})}else{let n={rel:`stylesheet`,type:`text/css`};a.forEach(r=>{c.push(No({host:t,remoteInfo:e,url:r,attrs:n,needDeleteLink:!1,context:Fo(i,`css`)}))})}if(r){let n={rel:`preload`,as:`script`};o.forEach(r=>{c.push(No({host:t,remoteInfo:e,url:r,attrs:n,context:Fo(i,`js`)}))})}else{let n={fetchpriority:`high`,type:e?.type===`module`?`module`:`text/javascript`};o.forEach(r=>{c.push(Po({host:t,remoteInfo:e,url:r,attrs:n,context:Fo(i,`js`)}))})}}return Promise.all(c)}function Lo(e){if(!e||!(`modules`in e)||!Array.isArray(e.modules))return;let t=e.modules.map(e=>e.moduleName).filter(Boolean);return t.length?t.join(`,`):void 0}function Ro(e,t,n){let r=t,i=Array.isArray(e.shareScope)?e.shareScope:[e.shareScope];i.length||i.push(`default`),i.forEach(e=>{r[e]||(r[e]={})});let a={version:e.version||``,shareScopeKeys:Array.isArray(e.shareScope)?i:e.shareScope||`default`};return Object.defineProperty(a,"shareScopeMap",{value:r,enumerable:!1}),{remoteEntryInitOptions:a,shareScope:r[i[0]],initScope:n??[]}}var zo=class{constructor({remoteInfo:e,host:t}){this.inited=!1,this.initing=!1,this.lib=void 0,this.remoteInfo=e,this.host=t}async getEntry(e){if(this.remoteEntryExports)return this.remoteEntryExports;let t=await xo({origin:this.host,remoteInfo:this.remoteInfo,remoteEntryExports:this.remoteEntryExports,resourceContext:{initiator:`loadRemote`,id:Ua(this.remoteInfo.name,e),resourceType:`remoteEntry`}});return Zr(t,`remoteEntryExports is undefined \n ${kr(this.remoteInfo)}`),this.remoteEntryExports=t,this.remoteEntryExports}async init(e,t,n,r){let i=await this.getEntry(r);if(this.inited)return await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:i,cached:!0,origin:this.host}),i;if(this.initPromise){try{await this.initPromise,await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:i,cached:!0,origin:this.host})}catch(n){throw await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:i,error:n,cached:!0,origin:this.host}),n}return i}this.initing=!0,this.initPromise=(async()=>{await this.host.loaderHook.lifecycle.beforeInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,origin:this.host});let{remoteEntryInitOptions:r,shareScope:a,initScope:o}=Ro(this.remoteInfo,this.host.shareScopeMap,n),s=await this.host.hooks.lifecycle.beforeInitContainer.emit({shareScope:a,remoteEntryInitOptions:r,initScope:o,remoteInfo:this.remoteInfo,origin:this.host});i?.init===void 0&&Qr(qa,uo,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,remoteEntryKey:this.remoteInfo.entryGlobalName},void 0,Eo(this.host.options));try{await i.init(s.shareScope,s.initScope,s.remoteEntryInitOptions)}catch(e){Qr(oo,uo,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,remoteEntryKey:this.remoteInfo.entryGlobalName,shareScope:this.remoteInfo.shareScope},`${e}`,Eo(this.host.options))}await this.host.hooks.lifecycle.initContainer.emit({...s,id:e,remoteSnapshot:t,remoteEntryExports:i}),this.inited=!0})();try{await this.initPromise,await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:i,origin:this.host})}catch(n){throw await this.host.loaderHook.lifecycle.afterInitRemote.emit({id:e,remoteInfo:this.remoteInfo,remoteSnapshot:t,remoteEntryExports:i,error:n,origin:this.host}),n}finally{this.initing=!1,this.initPromise=void 0}return i}async get(e,t,n,r){let{loadFactory:i=!0}=n||{loadFactory:!0},a=await this.init(e,r,void 0,t);this.lib=a,await this.host.loaderHook.lifecycle.beforeGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:a,origin:this.host});let o;try{let n=await this.host.loaderHook.lifecycle.getModuleFactory.emit({remoteEntryExports:a,expose:t,moduleInfo:this.remoteInfo});o=typeof n==`function`?n:void 0,o||=await a.get(t),o||Qr(ao,uo,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,expose:t,requestId:e,availableExposes:Lo(r)},void 0,Eo(this.host.options)),await this.host.loaderHook.lifecycle.afterGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:a,moduleFactory:o,origin:this.host})}catch(n){throw await this.host.loaderHook.lifecycle.afterGetExpose.emit({id:e,expose:t,moduleInfo:this.remoteInfo,remoteEntryExports:a,error:n,origin:this.host}),n}let s=li(this.remoteInfo.name,t),c=this.wraperFactory(o,s);if(!i)return c;await this.host.loaderHook.lifecycle.beforeExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:i,origin:this.host});try{let n=await c();return await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:i,exposeModule:n,origin:this.host}),n}catch(n){throw await this.host.loaderHook.lifecycle.afterExecuteFactory.emit({id:e,expose:t,moduleInfo:this.remoteInfo,loadFactory:i,error:n,origin:this.host}),n}}wraperFactory(e,t){function n(e,t){e&&typeof e==`object`&&Object.isExtensible(e)&&!Object.getOwnPropertyDescriptor(e,Symbol.for(`mf_module_id`))&&Object.defineProperty(e,Symbol.for(`mf_module_id`),{value:t,enumerable:!1})}return()=>{let r=e();return r instanceof Promise?r.then(e=>(n(e,t),e)):(n(r,t),r)}}},Bo=class{constructor(e){this.type=``,this.listeners=new Set,e&&(this.type=e)}on(e){typeof e==`function`&&this.listeners.add(e)}once(e){let t=this;this.on(function n(...r){return t.remove(n),e.apply(null,r)})}emit(...e){let t;return this.listeners.size>0&&this.listeners.forEach(n=>{let r=n(...e);r!==void 0&&(t=r)}),t}remove(e){this.listeners.delete(e)}removeAll(){this.listeners.clear()}},Vo=class extends Bo{emit(...e){let t,n=Array.from(this.listeners);if(n.length>0){let r=0,i=t=>t===!1?!1:r<n.length?Promise.resolve(n[r++].apply(null,e)).then(n=>n===void 0||e.length===1&&n===e[0]?i(t):i(n)):t;t=i()}return Promise.resolve(t)}};function Ho(e,t){if(!ii(t))return!1;if(e!==t){for(let n in e)if(!(n in t))return!1}return!0}var Uo=class extends Bo{constructor(e){super(),this.onerror=Qr,this.type=e}emit(e){ii(e)||Qr(`The data for the "${this.type}" hook should be an object.`);for(let t of this.listeners)try{let n=t(e);if(n===void 0)continue;if(Ho(e,n))e=n;else{this.onerror(`A plugin returned an unacceptable value for the "${this.type}" type.`);break}}catch(e){$r(e),this.onerror(e)}return e}},Wo=class extends Bo{constructor(e){super(),this.onerror=Qr,this.type=e}emit(e){ii(e)||Qr(`The response data for the "${this.type}" hook must be an object.`);let t=Array.from(this.listeners);if(t.length>0){let n=0,r=t=>($r(t),this.onerror(t),e),i=a=>{if(a!==void 0&&Ho(e,a))e=a;else if(a!==void 0)return this.onerror(`A plugin returned an incorrect value for the "${this.type}" type.`),e;if(n<t.length)try{return Promise.resolve(t[n++](e)).then(i,r)}catch(e){return r(e)}return e};return Promise.resolve(i(e))}return Promise.resolve(e)}},Go=class{constructor(e){this.registerPlugins={},this.lifecycle=e,this.lifecycleKeys=Object.keys(e)}applyPlugin(e,t){Zr(oi(e),`Plugin configuration is invalid.`);let n=e.name;Zr(n,`A name must be provided by the plugin.`),this.registerPlugins[n]||(this.registerPlugins[n]=e,e.apply?.(t),Object.keys(this.lifecycle).forEach(t=>{let n=e[t];n&&this.lifecycle[t].on(n)}))}removePlugin(e){Zr(e,`A name is required.`);let t=this.registerPlugins[e];Zr(t,`The plugin "${e}" is not registered.`),Object.keys(t).forEach(e=>{e!==`name`&&this.lifecycle[e].remove(t[e])})}};function Ko(e,t){let n=ci(t);n.url||Qr(no,uo,{remoteName:e.name});let r=Dr(t,n.url);!br&&!r.startsWith(`http`)&&(r=`https:${r}`),e.type=n.type,e.entryGlobalName=n.globalName,e.entry=r,e.version=t.version,e.buildVersion=t.buildVersion}function qo(){return{name:`snapshot-plugin`,async afterResolve(e){let{remote:t,pkgNameOrAlias:n,expose:r,origin:i,remoteInfo:a,id:o}=e;if(!ni(t)||!ri(t)){let{remoteSnapshot:s,globalSnapshot:c}=await i.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:t,id:Ua(t.name,r)});Ko(a,s);let l={remote:t,preloadConfig:{nameOrAlias:n,exposes:[r],resourceCategory:`sync`,share:!1,depsRemote:!1}},u=await i.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({origin:i,preloadOptions:l,remoteInfo:a,remote:t,remoteSnapshot:s,globalSnapshot:c});return u&&Io(a,i,u,!1,{initiator:`loadRemote`,id:o}).catch(()=>void 0),{...e,remoteSnapshot:s}}return e}}}function Jo(e){let t=e.split(`:`);return t.length===1?{name:t[0],version:void 0}:t.length===2?{name:t[0],version:t[1]}:{name:t[1],version:t[2]}}function Yo(e,t,n,r,i={},a){let{value:o}=bi(e,ti(t)),s=a||o;if(s&&!Nr(s)&&(n(s,t,r),s.remotesInfo)){let t=Object.keys(s.remotesInfo);for(let r of t){if(i[r])continue;i[r]=!0;let t=Jo(r),a=s.remotesInfo[r];Yo(e,{name:t.name,version:a.matchedVersion},n,!1,i,void 0)}}}var Xo=(e,t)=>document.querySelector(`${e}[${e===`link`?`href`:`src`}="${t}"]`);function Zo(e,t,n,r,i){let a=[],o=[],s=[],c=new Set,l=new Set,{options:u}=e,{preloadConfig:d}=t,{depsRemote:f}=d;if(Yo(r,n,(t,n,r)=>{let i;if(r)i=d;else if(Array.isArray(f)){let e=f.find(e=>e.nameOrAlias===n.name||e.nameOrAlias===n.alias);if(!e)return;i=Do(e)}else if(f===!0)i=d;else return;let c=Dr(t,ci(t).url);c&&s.push({name:n.name,moduleInfo:{name:n.name,entry:c,type:`remoteEntryType`in t?t.remoteEntryType:`global`,entryGlobalName:`globalName`in t?t.globalName:n.name,shareScope:``,version:`version`in t?t.version:void 0},url:c});let l=`modules`in t?t.modules:[],u=ko(i.exposes);u.length&&`modules`in t&&(l=t?.modules?.reduce((e,t)=>(u?.indexOf(t.moduleName)!==-1&&e.push(t),e),[]));function p(e){let n=e.map(e=>Dr(t,e));return i.filter?n.filter(i.filter):n}if(l){let r=l.length;for(let s=0;s<r;s++){let r=l[s],c=`${n.name}/${r.moduleName}`;e.remoteHandler.hooks.lifecycle.handlePreloadModule.emit({id:r.moduleName===`.`?n.name:c,name:n.name,remoteSnapshot:t,preloadConfig:i,remote:n,origin:e}),!Oi(c)&&(i.resourceCategory===`all`?(a.push(...p(r.assets.css.async)),a.push(...p(r.assets.css.sync)),o.push(...p(r.assets.js.async)),o.push(...p(r.assets.js.sync))):i.resourceCategory===`sync`&&(a.push(...p(r.assets.css.sync)),o.push(...p(r.assets.js.sync))),ki(c))}}},!0,{},i),i.shared&&i.shared.length>0){let t=(t,n)=>{let{shared:r}=Ra(e.shareScopeMap,n.sharedName,t,e.sharedHandler.hooks.lifecycle.resolveShare)||{};r&&typeof r.lib==`function`&&(n.assets.js.sync.forEach(e=>{c.add(e)}),n.assets.css.sync.forEach(e=>{l.add(e)}))};i.shared.forEach(e=>{let n=u.shared?.[e.sharedName];if(!n)return;let r=e.version?n.find(t=>t.version===e.version):n;r&&si(r).forEach(n=>{t(n,e)})})}let p=o.filter(e=>!c.has(e)&&!Xo(`script`,e));return{cssAssets:a.filter(e=>!l.has(e)&&!Xo(`link`,e)),jsAssetsWithoutEntry:p,entryAssets:s.filter(e=>!Xo(`script`,e.url))}}var Qo=function(){return{name:`generate-preload-assets-plugin`,async generatePreloadAssets(e){let{origin:t,preloadOptions:n,remoteInfo:r,remote:i,globalSnapshot:a,remoteSnapshot:o}=e;return br?ni(i)&&ri(i)?{cssAssets:[],jsAssetsWithoutEntry:[],entryAssets:[{name:i.name,url:i.entry,moduleInfo:{name:r.name,entry:i.entry,type:r.type||`global`,entryGlobalName:``,shareScope:``}}]}:(Ko(r,o),Zo(t,n,r,a,o)):{cssAssets:[],jsAssetsWithoutEntry:[],entryAssets:[]}}}};function $o(e,t){let n=Ci({name:t.name,version:t.options.version}),r=n&&`remotesInfo`in n&&n.remotesInfo&&bi(n.remotesInfo,e.name).value;return r&&r.matchedVersion?{hostGlobalSnapshot:n,globalSnapshot:xi(),remoteSnapshot:Ci({name:e.name,version:r.matchedVersion})}:{hostGlobalSnapshot:void 0,globalSnapshot:xi(),remoteSnapshot:Ci({name:e.name,version:`version`in e?e.version:void 0})}}var es=class{constructor(e){this.loadingHostSnapshot=null,this.manifestCache=new Map,this.hooks=new Go({beforeLoadRemoteSnapshot:new Vo(`beforeLoadRemoteSnapshot`),loadSnapshot:new Wo(`loadGlobalSnapshot`),loadRemoteSnapshot:new Wo(`loadRemoteSnapshot`),afterLoadSnapshot:new Wo(`afterLoadSnapshot`)}),this.manifestLoading=fi.__FEDERATION__.__MANIFEST_LOADING__,this.HostInstance=e,this.loaderHook=e.loaderHook}async loadRemoteSnapshotInfo({moduleInfo:e,id:t,initiator:n=`loadRemote`}){let{options:r}=this.HostInstance;await this.hooks.lifecycle.beforeLoadRemoteSnapshot.emit({options:r,moduleInfo:e,origin:this.HostInstance});let i=Ci({name:this.HostInstance.options.name,version:this.HostInstance.options.version});i||(i={version:this.HostInstance.options.version||``,remoteEntry:``,remotesInfo:{}},Ti({[this.HostInstance.options.name]:i})),i&&`remotesInfo`in i&&!bi(i.remotesInfo,e.name).value&&(`version`in e||`entry`in e)&&(i.remotesInfo={...i?.remotesInfo,[e.name]:{matchedVersion:`version`in e?e.version:e.entry}});let{hostGlobalSnapshot:a,remoteSnapshot:o,globalSnapshot:s}=this.getGlobalRemoteInfo(e),{remoteSnapshot:c,globalSnapshot:l}=await this.hooks.lifecycle.loadSnapshot.emit({options:r,moduleInfo:e,hostGlobalSnapshot:a,remoteSnapshot:o,globalSnapshot:s}),u,d;if(c)if(Nr(c)){let r=br?c.remoteEntry:c.ssrRemoteEntry||c.remoteEntry||``,i=await this.loadManifestSnapshot(r,e,{},{initiator:n,id:t||e.name}),a=wi({...e,entry:r},i);u=i,d=a}else{let{remoteSnapshot:t}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:e,remoteSnapshot:c,from:`global`});u=t,d=l}else if(ni(e)){let r=await this.loadManifestSnapshot(e.entry,e,{},{initiator:n,id:t||e.name}),i=wi(e,r);u=r,d=i}else Qr(Qa,uo,{remoteName:e.name,remoteVersion:e.version,hostName:this.HostInstance.options.name,globalSnapshot:JSON.stringify(l)},void 0,Eo(this.HostInstance.options));return await this.hooks.lifecycle.afterLoadSnapshot.emit({id:t,host:this.HostInstance,options:r,moduleInfo:e,remoteSnapshot:u}),{remoteSnapshot:u,globalSnapshot:d}}getGlobalRemoteInfo(e){return $o(e,this.HostInstance)}async getManifestJson(e,t,n,r){return(async()=>{let n=So(t),i=this.manifestCache.get(e);if(i)return i;try{let t=await this.loaderHook.lifecycle.fetch.emit(e,{},n,r?{...r,url:e,resourceType:`manifest`}:void 0);(!t||!(t instanceof Response))&&(t=await fetch(e,{})),i=await t.json()}catch(r){i=await this.HostInstance.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:e,error:r,from:`runtime`,lifecycle:`afterResolve`,remote:n,origin:this.HostInstance}),i||(delete this.manifestLoading[e],Qr(Ja,uo,{manifestUrl:e,moduleName:t.name,hostName:this.HostInstance.options.name},`${r}`,Eo(this.HostInstance.options)))}let a=[!i.metaData&&`metaData`,!i.exposes&&`exposes`,!i.shared&&`shared`].filter(Boolean);return a.length>0&&await this.HostInstance.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:e,error:Error(`"${e}" is not a valid federation manifest for remote "${t.name}". Missing required fields: ${a.join(`, `)}.`),from:`runtime`,lifecycle:`afterResolve`,remote:n,origin:this.HostInstance}),a.length>0&&Qr(io,uo,{manifestUrl:e,moduleName:t.name,hostName:this.HostInstance.options.name,missingFields:a.join(`,`)},void 0,Eo(this.HostInstance.options)),this.manifestCache.set(e,i),i})()}async loadManifestSnapshot(e,t,n,r){let i=async()=>{let i=await this.getManifestJson(e,t,n,r),a=Mr(i,{version:e}),{remoteSnapshot:o}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:t,manifestJson:i,remoteSnapshot:a,manifestUrl:e,from:`manifest`});return o};return this.manifestLoading[e]||(this.manifestLoading[e]=i().then(e=>e)),this.manifestLoading[e]}},ts=class{constructor(e){this.hooks=new Go({beforeRegisterShare:new Uo(`beforeRegisterShare`),afterResolve:new Wo(`afterResolve`),beforeLoadShare:new Wo(`beforeLoadShare`),loadShare:new Vo,afterLoadShare:new Bo(`afterLoadShare`),errorLoadShare:new Bo(`errorLoadShare`),resolveShare:new Uo(`resolveShare`),initContainerShareScopeMap:new Uo(`initContainerShareScopeMap`)}),this.host=e,this.shareScopeMap={},this.initTokens={},this._setGlobalShareScopeMap(e.options)}emitAfterLoadShare({lifecycle:e,pkgName:t,shareInfo:n,selectedShared:r}){try{this.hooks.lifecycle.afterLoadShare.emit({pkgName:t,shareInfo:n,selectedShared:r,shared:this.host.options.shared,shareScopeMap:this.shareScopeMap,lifecycle:e,origin:this.host})}catch(e){$r(e)}}emitErrorLoadShare({lifecycle:e,pkgName:t,shareInfo:n,error:r,recovered:i}){try{this.hooks.lifecycle.errorLoadShare.emit({pkgName:t,shareInfo:n,shared:this.host.options.shared,shareScopeMap:this.shareScopeMap,lifecycle:e,origin:this.host,error:r,recovered:i})}catch(e){$r(e)}}registerShared(e,t){let{newShareInfos:n,allShareInfos:r}=Da(e,t);return Object.keys(n).forEach(e=>{n[e].forEach(n=>{n.scope.forEach(r=>{this.hooks.lifecycle.beforeRegisterShare.emit({origin:this.host,pkgName:e,shared:n}),this.shareScopeMap[r]?.[e]||this.setShared({pkgName:e,lib:n.lib,get:n.get,loaded:n.loaded||!!n.lib,shared:n,from:t.name})})})}),{newShareInfos:n,allShareInfos:r}}async loadShare(e,t){let{host:n}=this,r=Ba({pkgName:e,extraOptions:t,shareInfos:n.options.shared}),i=r;try{r?.scope&&await Promise.all(r.scope.map(async e=>{await Promise.all(this.initializeSharing(e,{strategy:r.strategy}))})),i=(await this.hooks.lifecycle.beforeLoadShare.emit({pkgName:e,shareInfo:r,shared:n.options.shared,origin:n})).shareInfo,Zr(i,`Cannot find shared "${e}" in host "${n.options.name}". Ensure the shared config for "${e}" is declared in the federation plugin options and the host has been initialized before loading shares.`);let a=i,{shared:o,useTreesShaking:s}=Ra(this.shareScopeMap,e,i,this.hooks.lifecycle.resolveShare)||{};if(o){let t=Ha(o,s);if(t.lib)return Va(t,n.options.name),this.emitAfterLoadShare({lifecycle:`loadShare`,pkgName:e,shareInfo:a,selectedShared:o}),t.lib;if(t.loading&&!t.loaded){let r=await t.loading;return t.loaded=!0,t.lib||=r,Va(t,n.options.name),this.emitAfterLoadShare({lifecycle:`loadShare`,pkgName:e,shareInfo:a,selectedShared:o}),r}else{let r=(async()=>{let e=await t.get();return Va(t,n.options.name),t.loaded=!0,t.lib=e,e})();this.setShared({pkgName:e,loaded:!1,shared:o,from:n.options.name,lib:null,loading:r,treeShaking:s?t:void 0});let i=await r;return this.emitAfterLoadShare({lifecycle:`loadShare`,pkgName:e,shareInfo:a,selectedShared:o}),i}}else{if(t?.customShareInfo)return this.emitErrorLoadShare({lifecycle:`loadShare`,pkgName:e,shareInfo:a,recovered:!0}),!1;let r=Oa(a.treeShaking),i=Ha(a,r),o=(async()=>{let t=await i.get();i.lib=t,i.loaded=!0,Va(i,n.options.name);let{shared:r,useTreesShaking:o}=Ra(this.shareScopeMap,e,a,this.hooks.lifecycle.resolveShare)||{};if(r){let e=Ha(r,o);e.lib=t,e.loaded=!0,r.from=a.from}return t})();this.setShared({pkgName:e,loaded:!1,shared:a,from:n.options.name,lib:null,loading:o,treeShaking:r?i:void 0});let s=await o;return this.emitAfterLoadShare({lifecycle:`loadShare`,pkgName:e,shareInfo:a,selectedShared:a}),s}}catch(t){throw this.emitErrorLoadShare({lifecycle:`loadShare`,pkgName:e,shareInfo:i,error:t}),t}}initializeSharing(e=wa,t){let{host:n}=this,r=t?.from,i=t?.strategy,a=t?.initScope,o=[];if(r!==`build`){let{initTokens:t}=this;a||=[];let n=t[e];if(n||=t[e]={from:this.host.name},a.indexOf(n)>=0)return o;a.push(n)}let s=this.shareScopeMap,c=n.options.name;s[e]||(s[e]={});let l=s[e],u=(e,t)=>{let{version:n,eager:r}=t;l[e]=l[e]||{};let i=l[e],a=i[n]&&Ha(i[n]),o=!!(a&&(`eager`in a&&a.eager||`shareConfig`in a&&a.shareConfig?.eager));(!a||a.strategy!==`loaded-first`&&!a.loaded&&(!r==!o?c>i[n].from:r))&&(i[n]=t)},d=async e=>{let{module:t}=await n.remoteHandler.getRemoteModuleAndOptions({id:e}),r;try{r=await t.getEntry()}catch(i){if(r=await n.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:e,error:i,from:`runtime`,lifecycle:`beforeLoadShare`,remote:t.remoteInfo,origin:n}),!r)return}finally{r?.init&&!t.initing&&(t.remoteEntryExports=r,await t.init(void 0,void 0,a))}};return Object.keys(n.options.shared).forEach(t=>{n.options.shared[t].forEach(n=>{n.scope.includes(e)&&u(t,n)})}),(n.options.shareStrategy===`version-first`||i===`version-first`)&&n.options.remotes.forEach(t=>{t.shareScope===e&&o.push(d(t.name))}),o}loadShareSync(e,t){let{host:n}=this,r=Ba({pkgName:e,extraOptions:t,shareInfos:n.options.shared});try{r?.scope&&r.scope.forEach(e=>{this.initializeSharing(e,{strategy:r.strategy})});let{shared:i}=Ra(this.shareScopeMap,e,r,this.hooks.lifecycle.resolveShare)||{};if(i){if(typeof i.lib==`function`)return Va(i,n.options.name),i.loaded||(i.loaded=!0,i.from===n.options.name&&(r.loaded=!0)),this.emitAfterLoadShare({lifecycle:`loadShareSync`,pkgName:e,shareInfo:r,selectedShared:i}),i.lib;if(typeof i.get==`function`){let t=i.get();if(!(t instanceof Promise))return Va(i,n.options.name),this.setShared({pkgName:e,loaded:!0,from:n.options.name,lib:t,shared:i}),this.emitAfterLoadShare({lifecycle:`loadShareSync`,pkgName:e,shareInfo:r,selectedShared:i}),t}}if(r.lib)return r.loaded||=!0,this.emitAfterLoadShare({lifecycle:`loadShareSync`,pkgName:e,shareInfo:r,selectedShared:r}),r.lib;if(r.get){let i=r.get();return i instanceof Promise&&Qr(t?.from===`build`?Xa:Za,uo,{hostName:n.options.name,sharedPkgName:e},void 0,Eo(n.options)),r.lib=i,this.setShared({pkgName:e,loaded:!0,from:n.options.name,lib:r.lib,shared:r}),this.emitAfterLoadShare({lifecycle:`loadShareSync`,pkgName:e,shareInfo:r,selectedShared:r}),r.lib}Qr(Za,uo,{hostName:n.options.name,sharedPkgName:e},void 0,Eo(n.options))}catch(t){throw this.emitErrorLoadShare({lifecycle:`loadShareSync`,pkgName:e,shareInfo:r,error:t}),t}}initShareScopeMap(e,t,n={}){let{host:r}=this;this.shareScopeMap[e]=t,this.hooks.lifecycle.initContainerShareScopeMap.emit({shareScope:t,options:r.options,origin:r,scopeName:e,hostShareScopeMap:n.hostShareScopeMap})}setShared({pkgName:e,shared:t,from:n,lib:r,loading:i,loaded:a,get:o,treeShaking:s}){let{version:c,scope:l=`default`,...u}=t,d=Array.isArray(l)?l:[l],f=e=>{let t=(e,t,n)=>{n&&!e[t]&&(e[t]=n)},n=s?e.treeShaking:e;t(n,`loaded`,a),t(n,`loading`,i),t(n,`get`,o)};d.forEach(t=>{this.shareScopeMap[t]||(this.shareScopeMap[t]={}),this.shareScopeMap[t][e]||(this.shareScopeMap[t][e]={}),this.shareScopeMap[t][e][c]||(this.shareScopeMap[t][e][c]={version:c,scope:[t],...u,lib:r});let i=this.shareScopeMap[t][e][c];f(i),n&&i.from!==n&&(i.from=n)})}_setGlobalShareScopeMap(e){let t=za(),n=e.id||e.name;n&&!t[n]&&(t[n]=this.shareScopeMap)}},ns=class{constructor(e){this.hooks=new Go({beforeRegisterRemote:new Uo(`beforeRegisterRemote`),registerRemote:new Uo(`registerRemote`),beforeRequest:new Wo(`beforeRequest`),afterMatchRemote:new Vo(`afterMatchRemote`),onLoad:new Vo(`onLoad`),afterLoadRemote:new Vo(`afterLoadRemote`),handlePreloadModule:new Bo(`handlePreloadModule`),errorLoadRemote:new Vo(`errorLoadRemote`),beforePreloadRemote:new Vo(`beforePreloadRemote`),generatePreloadAssets:new Vo(`generatePreloadAssets`),afterPreloadRemote:new Vo(`afterPreloadRemote`),loadEntry:new Vo}),this.host=e,this.idToRemoteMap={}}formatAndRegisterRemote(e,t){return(t.remotes||[]).reduce((e,t)=>(this.registerRemote(t,e,{force:!1}),e),e.remotes)}setIdToRemoteMap(e,t){let{remote:n,expose:r}=t,{name:i,alias:a}=n;if(this.idToRemoteMap[e]={name:n.name,expose:r},a&&e.startsWith(i)){let t=e.replace(i,a);this.idToRemoteMap[t]={name:n.name,expose:r};return}if(a&&e.startsWith(a)){let t=e.replace(a,i);this.idToRemoteMap[t]={name:n.name,expose:r}}}async loadRemote(e,t){let{host:n}=this,r=Wa(n.options.remotes,e),i=e,a=r?.expose,o=r?So(r.remote):void 0,s;try{let{loadFactory:r=!0}=t||{loadFactory:!0},{module:c,moduleOptions:l,remoteMatchInfo:u}=await this.getRemoteModuleAndOptions({id:e}),{pkgNameOrAlias:d,remote:f,expose:p,id:m,remoteSnapshot:h}=u;i=m,a=p,o=So(f);let g=await c.get(m,p,t,h),_=await this.hooks.lifecycle.onLoad.emit({id:m,pkgNameOrAlias:d,expose:p,exposeModule:r?g:void 0,exposeModuleFactory:r?void 0:g,remote:f,options:l,moduleInstance:c,origin:n});return this.setIdToRemoteMap(e,u),s={id:i,expose:a,remote:o,options:t,origin:n},typeof _==`function`?_:g}catch(r){let{from:c=`runtime`}=t||{from:`runtime`},l;try{l=await this.hooks.lifecycle.errorLoadRemote.emit({id:e,error:r,from:c,lifecycle:`onLoad`,expose:a,remote:o,origin:n})}catch(e){throw s={id:i,expose:a,remote:o,options:t,error:e,origin:n},e}if(!l)throw s={id:i,expose:a,remote:o,options:t,error:r,origin:n},r;return s={id:i,expose:a,remote:o,options:t,error:r,origin:n,recovered:!0},l}finally{s&&await this.hooks.lifecycle.afterLoadRemote.emit(s)}}async preloadRemote(e){let{host:t}=this,n=[];await this.hooks.lifecycle.beforePreloadRemote.emit({preloadOps:e,options:t.options,origin:t});let r=Oo(t.options.remotes,e),i=e=>{let{preloadConfig:t,remote:n}=e,r=t.exposes||[];return r.length?r.map(r=>({ops:{...e,preloadConfig:{...t,exposes:[r]}},id:Ua(n.name,r)})):[{ops:e,id:`${n.name}/*`}]},a;await Promise.all(r.flatMap(i).map(async e=>{let{ops:r,id:i}=e,{remote:a,preloadConfig:o}=r,s=So(a);try{let{globalSnapshot:e,remoteSnapshot:c}=await t.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:a,id:i,initiator:`preloadRemote`}),l=await this.hooks.lifecycle.generatePreloadAssets.emit({origin:t,preloadOptions:r,remote:a,remoteInfo:s,globalSnapshot:e,remoteSnapshot:c});if(!l)return;let u=await Io(s,t,l,!0,{initiator:`preloadRemote`,id:i});n.push({remote:a,remoteInfo:s,preloadConfig:o,id:i,results:u})}catch(e){n.push({remote:a,remoteInfo:s,preloadConfig:o,id:i,results:[{url:s.entry,status:`error`,resourceType:/\.json(?:$|[?#])/i.test(s.entry)?`manifest`:`remoteEntry`,initiator:`preloadRemote`,id:i,error:e}]})}}));let o=n.flatMap(e=>e.results.filter(e=>e.status===`error`||e.status===`timeout`));if(o.length>0&&(a=Error(`preloadRemote failed to load ${o.length} resource(s).`),Object.assign(a,{results:n,failedResults:o})),await this.hooks.lifecycle.afterPreloadRemote.emit({preloadOps:e,options:t.options,origin:t,results:n,error:a}),a)throw a}registerRemotes(e,t){let{host:n}=this;e.forEach(e=>{this.registerRemote(e,n.options.remotes,{force:t?.force})})}async getRemoteModuleAndOptions(e){let{host:t}=this,{id:n}=e,r;try{r=await this.hooks.lifecycle.beforeRequest.emit({id:n,options:t.options,origin:t})}catch(e){if(r=await this.hooks.lifecycle.errorLoadRemote.emit({id:n,options:t.options,origin:t,from:`runtime`,error:e,lifecycle:`beforeRequest`}),!r)throw e}let{id:i}=r,a=Wa(t.options.remotes,i);if(!a)try{Qr(Ya,uo,{hostName:t.options.name,requestId:i},void 0,Eo(t.options))}catch(e){throw await this.hooks.lifecycle.afterMatchRemote.emit({id:i,options:t.options,error:e,origin:t}),e}let{remote:o}=a,s=So(o);await this.hooks.lifecycle.afterMatchRemote.emit({id:i,...a,options:t.options,remoteInfo:s,origin:t});let c=await t.sharedHandler.hooks.lifecycle.afterResolve.emit({id:i,...a,options:t.options,origin:t,remoteInfo:s}),{remote:l,expose:u}=c;Zr(l&&u,`The 'beforeRequest' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${i}.`);let d=t.moduleCache.get(l.name),f={host:t,remoteInfo:s};return d||(d=new zo(f),t.moduleCache.set(l.name,d)),{module:d,moduleOptions:f,remoteMatchInfo:c}}registerRemote(e,t,n){let{host:r}=this,i=()=>{if(e.alias){let n=t.find(t=>e.alias&&(t.name.startsWith(e.alias)||t.alias?.startsWith(e.alias)));Zr(!n,`The alias ${e.alias} of remote ${e.name} is not allowed to be the prefix of ${n&&n.name} name or alias`)}`entry`in e&&br&&typeof window<`u`&&!e.entry.startsWith(`http`)&&(e.entry=new URL(e.entry,window.location.origin).href),e.shareScope||=wa,e.type||=Ta};this.hooks.lifecycle.beforeRegisterRemote.emit({remote:e,origin:r});let a=t.find(t=>t.name===e.name);if(!a)i(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:r});else{let o=[`The remote "${e.name}" is already registered.`,`Please note that overriding it may cause unexpected errors.`];n?.force&&(this.removeRemote(a),i(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:r}),Or(o.join(` `)))}}removeRemote(e){try{let{host:t}=this,{name:n}=e,r=t.options.remotes.findIndex(e=>e.name===n);r!==-1&&t.options.remotes.splice(r,1);let i=t.moduleCache.get(e.name);if(i){let n=i.remoteInfo,r=n.entryGlobalName;ui[r]&&(Object.getOwnPropertyDescriptor(ui,r)?.configurable?delete ui[r]:ui[r]=void 0);let a=bo(i.remoteInfo);hi[a]&&delete hi[a],t.snapshotHandler.manifestCache.delete(n.entry);let o=n.buildVersion?Er(n.name,n.buildVersion):n.name,s=ui.__FEDERATION__.__INSTANCES__.findIndex(e=>n.buildVersion?e.options.id===o:e.name===o);if(s!==-1){let e=ui.__FEDERATION__.__INSTANCES__[s];o=e.options.id||o;let t=za(),r=!0,i=[];Object.keys(t).forEach(e=>{let a=t[e];a&&Object.keys(a).forEach(t=>{let o=a[t];o&&Object.keys(o).forEach(a=>{let s=o[a];s&&Object.keys(s).forEach(o=>{let c=s[o];c&&typeof c==`object`&&c.from===n.name&&(c.loaded||c.loading?(c.useIn=c.useIn.filter(e=>e!==n.name),c.useIn.length?r=!1:i.push([e,t,a,o])):i.push([e,t,a,o]))})})})}),r&&(e.shareScopeMap={},delete t[o]),i.forEach(([e,n,r,i])=>{delete t[e]?.[n]?.[r]?.[i]}),ui.__FEDERATION__.__INSTANCES__.splice(s,1)}let{hostGlobalSnapshot:c}=$o(e,t);if(c){let t=c&&`remotesInfo`in c&&c.remotesInfo&&bi(c.remotesInfo,e.name).key;t&&(delete c.remotesInfo[t],fi.__FEDERATION__.__MANIFEST_LOADING__[t]&&delete fi.__FEDERATION__.__MANIFEST_LOADING__[t])}t.moduleCache.delete(e.name)}}catch(e){Xr.error(`removeRemote failed: ${e instanceof Error?e.message:String(e)}`)}}},rs=typeof FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN==`boolean`?!FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN:!0,is=class{constructor(e){this.hooks=new Go({beforeInit:new Uo(`beforeInit`),init:new Bo,beforeInitContainer:new Wo(`beforeInitContainer`),initContainer:new Wo(`initContainer`)}),this.version=`2.5.1`,this.moduleCache=new Map,this.loaderHook=new Go({getModuleInfo:new Bo,createScript:new Bo,createLink:new Bo,fetch:new Vo,loadEntryError:new Vo,afterLoadEntry:new Vo(`afterLoadEntry`),beforeInitRemote:new Vo(`beforeInitRemote`),afterInitRemote:new Vo(`afterInitRemote`),beforeGetExpose:new Vo(`beforeGetExpose`),afterGetExpose:new Vo(`afterGetExpose`),beforeExecuteFactory:new Vo(`beforeExecuteFactory`),afterExecuteFactory:new Vo(`afterExecuteFactory`),getModuleFactory:new Vo}),this.bridgeHook=new Go({beforeBridgeRender:new Bo,afterBridgeRender:new Bo,beforeBridgeDestroy:new Bo,afterBridgeDestroy:new Bo});let t=rs?[qo(),Qo()]:[],n={id:Co(),name:e.name,plugins:t,remotes:[],shared:{},inBrowser:br};this.name=e.name,this.options=n,this.snapshotHandler=new es(this),this.sharedHandler=new ts(this),this.remoteHandler=new ns(this),this.shareScopeMap=this.sharedHandler.shareScopeMap,this.registerPlugins([...n.plugins,...e.plugins||[]]),this.options=this.formatOptions(n,e)}initOptions(e){e.name&&e.name!==this.options.name&&Qr(qr(to,uo)),this.registerPlugins(e.plugins);let t=this.formatOptions(this.options,e);return this.options=t,t}async loadShare(e,t){return this.sharedHandler.loadShare(e,t)}loadShareSync(e,t){return this.sharedHandler.loadShareSync(e,t)}initializeSharing(e=wa,t){return this.sharedHandler.initializeSharing(e,t)}initRawContainer(e,t,n){let r=So({name:e,entry:t}),i=new zo({host:this,remoteInfo:r});return i.remoteEntryExports=n,this.moduleCache.set(e,i),i}async loadRemote(e,t){return this.remoteHandler.loadRemote(e,t)}async preloadRemote(e){return this.remoteHandler.preloadRemote(e)}initShareScopeMap(e,t,n={}){this.sharedHandler.initShareScopeMap(e,t,n)}formatOptions(e,t){let{allShareInfos:n}=Da(e,t),{userOptions:r,options:i}=this.hooks.lifecycle.beforeInit.emit({origin:this,userOptions:t,options:e,shareInfo:n}),a=this.remoteHandler.formatAndRegisterRemote(i,r),{allShareInfos:o}=this.sharedHandler.registerShared(i,r),s=[...i.plugins];r.plugins&&r.plugins.forEach(e=>{s.includes(e)||s.push(e)});let c={...e,...t,plugins:s,remotes:a,shared:o,id:r.id||e.id};return this.hooks.lifecycle.init.emit({origin:this,options:c}),c}registerPlugins(e){let t=wo(e,this);this.options.plugins=this.options.plugins.reduce((e,t)=>(t&&e&&!e.find(e=>e.name===t.name)&&e.push(t),e),t||[])}registerRemotes(e,t){return this.remoteHandler.registerRemotes(e,t)}registerShared(e){this.sharedHandler.registerShared(this.options,{...this.options,shared:e})}};function as(){return typeof FEDERATION_BUILD_IDENTIFIER<`u`?FEDERATION_BUILD_IDENTIFIER:``}function os(e,t){let n=as();return ui.__FEDERATION__.__INSTANCES__.find(r=>!!(n&&r.options.id===n||r.options.name===e&&!r.options.version&&!t||r.options.name===e&&t&&r.options.version===t))}function ss(e){let t=new((vi())||is)({id:`${e.name}@${e.version||Date.now()}`,...e});return _i(t),t}var cs=null;function ls(e){let t=os(e.name,e.version),n={...e,id:e.id||``};return t?(t.initOptions(n),cs||=t,t):(cs=ss(n),cs)}function us(...e){return Zr(cs,eo,uo),cs.loadRemote.apply(cs,e)}function ds(...e){return Zr(cs,eo,uo),cs.registerRemotes.apply(cs,e)}function fs(e){return e?ui.__FEDERATION__.__INSTANCES__.find(e)||null:cs}yi(is);function ps(e){let t=(typeof globalThis<`u`?globalThis:void 0)?.[e];return t&&typeof t==`object`?t:{}}var ms={singleton:!0,requiredVersion:!1,eager:!0},hs=e=>({version:`0.0.0`,scope:`default`,lib:e,shareConfig:ms}),gs=`__mf_module_cache__`;function _s(){let e=globalThis,t=e[gs];if(t&&typeof t==`object`){let e=t;return e.share??={},e.remote??={},e}let n={share:{},remote:{}};return e[gs]=n,n}function vs(){let e=_s();e.share.react??=x,e.share[`react-dom`]??=O,e.share[`react-dom/client`]??=j,e.share[`react/jsx-runtime`]??=f,e.share[`@tanstack/react-query`]??=g,e.share[`@trpc/client`]??=F,e.share[`@trpc/react-query`]??=L,e.share[`react-konva`]??=z,e.share.konva??=R,e.share[`@camstack/ui-library`]??=ps(`__camstackUiLibrary`),e.share[`@camstack/sdk`]??=ps(`__camstackSdk`),e.share[`@camstack/types`]??=ps(`__camstackTypes`)}function ys(){vs(),fs()===null&&ls({name:`admin_ui_host`,remotes:[],shared:{react:hs(()=>x),"react-dom":hs(()=>O),"react-dom/client":hs(()=>j),"react/jsx-runtime":hs(()=>f),"@tanstack/react-query":hs(()=>g),"@trpc/client":hs(()=>F),"@trpc/react-query":hs(()=>L),"react-konva":hs(()=>z),konva:hs(()=>R),"@camstack/ui-library":hs(()=>ps(`__camstackUiLibrary`)),"@camstack/sdk":hs(()=>ps(`__camstackSdk`)),"@camstack/types":hs(()=>ps(`__camstackTypes`))}})}var bs=(...e)=>e.filter((e,t,n)=>!!e&&e.trim()!==``&&n.indexOf(e)===t).join(` `).trim(),xs=e=>e.replace(/([a-z0-9])([A-Z])/g,`$1-$2`).toLowerCase(),Ss=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),Cs=e=>{let t=Ss(e);return t.charAt(0).toUpperCase()+t.slice(1)},ws={xmlns:`http://www.w3.org/2000/svg`,width:24,height:24,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:2,strokeLinecap:`round`,strokeLinejoin:`round`},Ts=e=>{for(let t in e)if(t.startsWith(`aria-`)||t===`role`||t===`title`)return!0;return!1},Es=l(({color:e=`currentColor`,size:t=24,strokeWidth:r=2,absoluteStrokeWidth:i,className:a=``,children:o,iconNode:s,...c},l)=>n(`svg`,{ref:l,...ws,width:t,height:t,stroke:e,strokeWidth:i?Number(r)*24/Number(t):r,className:bs(`lucide`,a),...!o&&!Ts(c)&&{"aria-hidden":`true`},...c},[...s.map(([e,t])=>n(e,t)),...Array.isArray(o)?o:[o]])),K=(e,t)=>{let r=l(({className:r,...i},a)=>n(Es,{ref:a,iconNode:t,className:bs(`lucide-${xs(Cs(e))}`,`lucide-${e}`,r),...i}));return r.displayName=Cs(e),r},Ds=K(`activity`,[[`path`,{d:`M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2`,key:`169zse`}]]),Os=K(`alarm-smoke`,[[`path`,{d:`M11 21c0-2.5 2-2.5 2-5`,key:`1sicvv`}],[`path`,{d:`M16 21c0-2.5 2-2.5 2-5`,key:`1o3eny`}],[`path`,{d:`m19 8-.8 3a1.25 1.25 0 0 1-1.2 1H7a1.25 1.25 0 0 1-1.2-1L5 8`,key:`1bvca4`}],[`path`,{d:`M21 3a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V4a1 1 0 0 1 1-1z`,key:`x3qr1j`}],[`path`,{d:`M6 21c0-2.5 2-2.5 2-5`,key:`i3w1gp`}]]),ks=K(`arrow-down-to-line`,[[`path`,{d:`M12 17V3`,key:`1cwfxf`}],[`path`,{d:`m6 11 6 6 6-6`,key:`12ii2o`}],[`path`,{d:`M19 21H5`,key:`150jfl`}]]),As=K(`arrow-down`,[[`path`,{d:`M12 5v14`,key:`s699le`}],[`path`,{d:`m19 12-7 7-7-7`,key:`1idqje`}]]),js=K(`arrow-left`,[[`path`,{d:`m12 19-7-7 7-7`,key:`1l729n`}],[`path`,{d:`M19 12H5`,key:`x3x0zl`}]]),Ms=K(`arrow-right`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`m12 5 7 7-7 7`,key:`xquz4c`}]]),Ns=K(`arrow-up-to-line`,[[`path`,{d:`M5 3h14`,key:`7usisc`}],[`path`,{d:`m18 13-6-6-6 6`,key:`1kf1n9`}],[`path`,{d:`M12 7v14`,key:`1akyts`}]]),Ps=K(`arrow-up`,[[`path`,{d:`m5 12 7-7 7 7`,key:`hav0vg`}],[`path`,{d:`M12 19V5`,key:`x0mq9r`}]]),Fs=K(`bath`,[[`path`,{d:`M10 4 8 6`,key:`1rru8s`}],[`path`,{d:`M17 19v2`,key:`ts1sot`}],[`path`,{d:`M2 12h20`,key:`9i4pu4`}],[`path`,{d:`M7 19v2`,key:`12npes`}],[`path`,{d:`M9 5 7.621 3.621A2.121 2.121 0 0 0 4 5v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5`,key:`14ym8i`}]]),Is=K(`battery-full`,[[`path`,{d:`M10 10v4`,key:`1mb2ec`}],[`path`,{d:`M14 10v4`,key:`1nt88p`}],[`path`,{d:`M22 14v-4`,key:`14q9d5`}],[`path`,{d:`M6 10v4`,key:`1n77qd`}],[`rect`,{x:`2`,y:`6`,width:`16`,height:`12`,rx:`2`,key:`13zb55`}]]),Ls=K(`battery-low`,[[`path`,{d:`M22 14v-4`,key:`14q9d5`}],[`path`,{d:`M6 14v-4`,key:`14a6bd`}],[`rect`,{x:`2`,y:`6`,width:`16`,height:`12`,rx:`2`,key:`13zb55`}]]),Rs=K(`battery-medium`,[[`path`,{d:`M10 14v-4`,key:`suye4c`}],[`path`,{d:`M22 14v-4`,key:`14q9d5`}],[`path`,{d:`M6 14v-4`,key:`14a6bd`}],[`rect`,{x:`2`,y:`6`,width:`16`,height:`12`,rx:`2`,key:`13zb55`}]]),zs=K(`battery-warning`,[[`path`,{d:`M10 17h.01`,key:`nbq80n`}],[`path`,{d:`M10 7v6`,key:`nne03l`}],[`path`,{d:`M14 6h2a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2`,key:`1m83kb`}],[`path`,{d:`M22 14v-4`,key:`14q9d5`}],[`path`,{d:`M6 18H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h2`,key:`h8lgfh`}]]),Bs=K(`battery`,[[`path`,{d:`M 22 14 L 22 10`,key:`nqc4tb`}],[`rect`,{x:`2`,y:`6`,width:`16`,height:`12`,rx:`2`,key:`13zb55`}]]),Vs=K(`bell-ring`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M22 8c0-2.3-.8-4.3-2-6`,key:`5bb3ad`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}],[`path`,{d:`M4 2C2.8 3.7 2 5.7 2 8`,key:`tap9e0`}]]),Hs=K(`bell`,[[`path`,{d:`M10.268 21a2 2 0 0 0 3.464 0`,key:`vwvbt9`}],[`path`,{d:`M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326`,key:`11g9vi`}]]),Us=K(`blinds`,[[`path`,{d:`M3 3h18`,key:`o7r712`}],[`path`,{d:`M20 7H8`,key:`gd2fo2`}],[`path`,{d:`M20 11H8`,key:`1ynp89`}],[`path`,{d:`M10 19h10`,key:`19hjk5`}],[`path`,{d:`M8 15h12`,key:`1yqzne`}],[`path`,{d:`M4 3v14`,key:`fggqzn`}],[`circle`,{cx:`4`,cy:`19`,r:`2`,key:`p3m9r0`}]]),Ws=K(`bot`,[[`path`,{d:`M12 8V4H8`,key:`hb8ula`}],[`rect`,{width:`16`,height:`12`,x:`4`,y:`8`,rx:`2`,key:`enze0r`}],[`path`,{d:`M2 14h2`,key:`vft8re`}],[`path`,{d:`M20 14h2`,key:`4cs60a`}],[`path`,{d:`M15 13v2`,key:`1xurst`}],[`path`,{d:`M9 13v2`,key:`rq6x2g`}]]),Gs=K(`box`,[[`path`,{d:`M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z`,key:`hh9hay`}],[`path`,{d:`m3.3 7 8.7 5 8.7-5`,key:`g66t2b`}],[`path`,{d:`M12 22V12`,key:`d0xqtd`}]]),Ks=K(`bug`,[[`path`,{d:`M12 20v-9`,key:`1qisl0`}],[`path`,{d:`M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z`,key:`uouzyp`}],[`path`,{d:`M14.12 3.88 16 2`,key:`qol33r`}],[`path`,{d:`M21 21a4 4 0 0 0-3.81-4`,key:`1b0z45`}],[`path`,{d:`M21 5a4 4 0 0 1-3.55 3.97`,key:`5cxbf6`}],[`path`,{d:`M22 13h-4`,key:`1jl80f`}],[`path`,{d:`M3 21a4 4 0 0 1 3.81-4`,key:`1fjd4g`}],[`path`,{d:`M3 5a4 4 0 0 0 3.55 3.97`,key:`1d7oge`}],[`path`,{d:`M6 13H2`,key:`82j7cp`}],[`path`,{d:`m8 2 1.88 1.88`,key:`fmnt4t`}],[`path`,{d:`M9 7.13V6a3 3 0 1 1 6 0v1.13`,key:`1vgav8`}]]),qs=K(`camera`,[[`path`,{d:`M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z`,key:`18u6gg`}],[`circle`,{cx:`12`,cy:`13`,r:`3`,key:`1vg3eu`}]]),Js=K(`cast`,[[`path`,{d:`M2 8V6a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-6`,key:`3zrzxg`}],[`path`,{d:`M2 12a9 9 0 0 1 8 8`,key:`g6cvee`}],[`path`,{d:`M2 16a5 5 0 0 1 4 4`,key:`1y1dii`}],[`line`,{x1:`2`,x2:`2.01`,y1:`20`,y2:`20`,key:`xu2jvo`}]]),Ys=K(`check`,[[`path`,{d:`M20 6 9 17l-5-5`,key:`1gmf2c`}]]),Xs=K(`chevron-down`,[[`path`,{d:`m6 9 6 6 6-6`,key:`qrunsl`}]]),Zs=K(`chevron-left`,[[`path`,{d:`m15 18-6-6 6-6`,key:`1wnfg3`}]]),Qs=K(`chevron-right`,[[`path`,{d:`m9 18 6-6-6-6`,key:`mthhwq`}]]),$s=K(`chevron-up`,[[`path`,{d:`m18 15-6-6-6 6`,key:`153udz`}]]),ec=K(`chevrons-down-up`,[[`path`,{d:`m7 20 5-5 5 5`,key:`13a0gw`}],[`path`,{d:`m7 4 5 5 5-5`,key:`1kwcof`}]]),tc=K(`chevrons-up-down`,[[`path`,{d:`m7 15 5 5 5-5`,key:`1hf1tw`}],[`path`,{d:`m7 9 5-5 5 5`,key:`sgt6xg`}]]),nc=K(`circle-alert`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`12`,x2:`12`,y1:`8`,y2:`12`,key:`1pkeuh`}],[`line`,{x1:`12`,x2:`12.01`,y1:`16`,y2:`16`,key:`4dfq90`}]]),rc=K(`circle-check-big`,[[`path`,{d:`M21.801 10A10 10 0 1 1 17 3.335`,key:`yps3ct`}],[`path`,{d:`m9 11 3 3L22 4`,key:`1pflzl`}]]),ic=K(`circle-check`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),ac=K(`circle-dot`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}]]),oc=K(`circle-pause`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`10`,x2:`10`,y1:`15`,y2:`9`,key:`c1nkhi`}],[`line`,{x1:`14`,x2:`14`,y1:`15`,y2:`9`,key:`h65svq`}]]),sc=K(`circle-plus`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M8 12h8`,key:`1wcyev`}],[`path`,{d:`M12 8v8`,key:`napkw2`}]]),cc=K(`circle-question-mark`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3`,key:`1u773s`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),lc=K(`circle-x`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m15 9-6 6`,key:`1uzhvr`}],[`path`,{d:`m9 9 6 6`,key:`z0biqf`}]]),uc=K(`clock`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 6v6l4 2`,key:`mmk7yg`}]]),dc=K(`cloud-fog`,[[`path`,{d:`M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242`,key:`1pljnt`}],[`path`,{d:`M16 17H7`,key:`pygtm1`}],[`path`,{d:`M17 21H9`,key:`1u2q02`}]]),fc=K(`cloud-lightning`,[[`path`,{d:`M6 16.326A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 .5 8.973`,key:`1cez44`}],[`path`,{d:`m13 12-3 5h4l-3 5`,key:`1t22er`}]]),pc=K(`cloud-rain`,[[`path`,{d:`M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242`,key:`1pljnt`}],[`path`,{d:`M16 14v6`,key:`1j4efv`}],[`path`,{d:`M8 14v6`,key:`17c4r9`}],[`path`,{d:`M12 16v6`,key:`c8a4gj`}]]),mc=K(`cloud-snow`,[[`path`,{d:`M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242`,key:`1pljnt`}],[`path`,{d:`M8 15h.01`,key:`a7atzg`}],[`path`,{d:`M8 19h.01`,key:`puxtts`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}],[`path`,{d:`M12 21h.01`,key:`h35vbk`}],[`path`,{d:`M16 15h.01`,key:`rnfrdf`}],[`path`,{d:`M16 19h.01`,key:`1vcnzz`}]]),hc=K(`cloud-sun`,[[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}],[`path`,{d:`M15.947 12.65a4 4 0 0 0-5.925-4.128`,key:`dpwdj0`}],[`path`,{d:`M13 22H7a5 5 0 1 1 4.9-6H13a3 3 0 0 1 0 6Z`,key:`s09mg5`}]]),gc=K(`cloud`,[[`path`,{d:`M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z`,key:`p7xjir`}]]),_c=K(`copy-plus`,[[`line`,{x1:`15`,x2:`15`,y1:`12`,y2:`18`,key:`1p7wdc`}],[`line`,{x1:`12`,x2:`18`,y1:`15`,y2:`15`,key:`1nscbv`}],[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),vc=K(`copy`,[[`rect`,{width:`14`,height:`14`,x:`8`,y:`8`,rx:`2`,ry:`2`,key:`17jyea`}],[`path`,{d:`M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2`,key:`zix9uf`}]]),yc=K(`cpu`,[[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M17 20v2`,key:`1rnc9c`}],[`path`,{d:`M17 2v2`,key:`11trls`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M2 17h2`,key:`7oei6x`}],[`path`,{d:`M2 7h2`,key:`asdhe0`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`M20 17h2`,key:`1fpfkl`}],[`path`,{d:`M20 7h2`,key:`1o8tra`}],[`path`,{d:`M7 20v2`,key:`4gnj0m`}],[`path`,{d:`M7 2v2`,key:`1i4yhu`}],[`rect`,{x:`4`,y:`4`,width:`16`,height:`16`,rx:`2`,key:`1vbyd7`}],[`rect`,{x:`8`,y:`8`,width:`8`,height:`8`,rx:`1`,key:`z9xiuo`}]]),bc=K(`crosshair`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`line`,{x1:`22`,x2:`18`,y1:`12`,y2:`12`,key:`l9bcsi`}],[`line`,{x1:`6`,x2:`2`,y1:`12`,y2:`12`,key:`13hhkx`}],[`line`,{x1:`12`,x2:`12`,y1:`6`,y2:`2`,key:`10w3f3`}],[`line`,{x1:`12`,x2:`12`,y1:`22`,y2:`18`,key:`15g9kq`}]]),xc=K(`database`,[[`ellipse`,{cx:`12`,cy:`5`,rx:`9`,ry:`3`,key:`msslwz`}],[`path`,{d:`M3 5V19A9 3 0 0 0 21 19V5`,key:`1wlel7`}],[`path`,{d:`M3 12A9 3 0 0 0 21 12`,key:`mv7ke4`}]]),Sc=K(`door-closed`,[[`path`,{d:`M10 12h.01`,key:`1kxr2c`}],[`path`,{d:`M18 20V6a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v14`,key:`36qu9e`}],[`path`,{d:`M2 20h20`,key:`owomy5`}]]),Cc=K(`door-open`,[[`path`,{d:`M11 20H2`,key:`nlcfvz`}],[`path`,{d:`M11 4.562v16.157a1 1 0 0 0 1.242.97L19 20V5.562a2 2 0 0 0-1.515-1.94l-4-1A2 2 0 0 0 11 4.561z`,key:`au4z13`}],[`path`,{d:`M11 4H8a2 2 0 0 0-2 2v14`,key:`74r1mk`}],[`path`,{d:`M14 12h.01`,key:`1jfl7z`}],[`path`,{d:`M22 20h-3`,key:`vhrsz`}]]),wc=K(`download`,[[`path`,{d:`M12 15V3`,key:`m9g1x1`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}],[`path`,{d:`m7 10 5 5 5-5`,key:`brsn70`}]]),Tc=K(`droplet`,[[`path`,{d:`M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z`,key:`c7niix`}]]),Ec=K(`droplets`,[[`path`,{d:`M7 16.3c2.2 0 4-1.83 4-4.05 0-1.16-.57-2.26-1.71-3.19S7.29 6.75 7 5.3c-.29 1.45-1.14 2.84-2.29 3.76S3 11.1 3 12.25c0 2.22 1.8 4.05 4 4.05z`,key:`1ptgy4`}],[`path`,{d:`M12.56 6.6A10.97 10.97 0 0 0 14 3.02c.5 2.5 2 4.9 4 6.5s3 3.5 3 5.5a6.98 6.98 0 0 1-11.91 4.97`,key:`1sl1rz`}]]),Dc=K(`ellipsis-vertical`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`12`,cy:`5`,r:`1`,key:`gxeob9`}],[`circle`,{cx:`12`,cy:`19`,r:`1`,key:`lyex9k`}]]),Oc=K(`external-link`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`M10 14 21 3`,key:`gplh6r`}],[`path`,{d:`M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6`,key:`a6xqqp`}]]),kc=K(`eye-off`,[[`path`,{d:`M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49`,key:`ct8e1f`}],[`path`,{d:`M14.084 14.158a3 3 0 0 1-4.242-4.242`,key:`151rxh`}],[`path`,{d:`M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143`,key:`13bj9a`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]),Ac=K(`eye`,[[`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`,key:`1nclc0`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),jc=K(`fan`,[[`path`,{d:`M10.827 16.379a6.082 6.082 0 0 1-8.618-7.002l5.412 1.45a6.082 6.082 0 0 1 7.002-8.618l-1.45 5.412a6.082 6.082 0 0 1 8.618 7.002l-5.412-1.45a6.082 6.082 0 0 1-7.002 8.618l1.45-5.412Z`,key:`484a7f`}],[`path`,{d:`M12 12v.01`,key:`u5ubse`}]]),Mc=K(`film`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}],[`path`,{d:`M7 3v18`,key:`bbkbws`}],[`path`,{d:`M3 7.5h4`,key:`zfgn84`}],[`path`,{d:`M3 12h18`,key:`1i2n21`}],[`path`,{d:`M3 16.5h4`,key:`1230mu`}],[`path`,{d:`M17 3v18`,key:`in4fa5`}],[`path`,{d:`M17 7.5h4`,key:`myr1c1`}],[`path`,{d:`M17 16.5h4`,key:`go4c1d`}]]),Nc=K(`flame`,[[`path`,{d:`M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4`,key:`1slcih`}]]),Pc=K(`flashlight`,[[`path`,{d:`M12 13v1`,key:`176q98`}],[`path`,{d:`M17 2a1 1 0 0 1 1 1v4a3 3 0 0 1-.6 1.8l-.6.8A4 4 0 0 0 16 12v8a2 2 0 0 1-2 2H10a2 2 0 0 1-2-2v-8a4 4 0 0 0-.8-2.4l-.6-.8A3 3 0 0 1 6 7V3a1 1 0 0 1 1-1z`,key:`17vh7j`}],[`path`,{d:`M6 6h12`,key:`n6hhss`}]]),Fc=K(`flask-conical`,[[`path`,{d:`M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2`,key:`18mbvz`}],[`path`,{d:`M6.453 15h11.094`,key:`3shlmq`}],[`path`,{d:`M8.5 2h7`,key:`csnxdl`}]]),Ic=K(`footprints`,[[`path`,{d:`M4 16v-2.38C4 11.5 2.97 10.5 3 8c.03-2.72 1.49-6 4.5-6C9.37 2 10 3.8 10 5.5c0 3.11-2 5.66-2 8.68V16a2 2 0 1 1-4 0Z`,key:`1dudjm`}],[`path`,{d:`M20 20v-2.38c0-2.12 1.03-3.12 1-5.62-.03-2.72-1.49-6-4.5-6C14.63 6 14 7.8 14 9.5c0 3.11 2 5.66 2 8.68V20a2 2 0 1 0 4 0Z`,key:`l2t8xc`}],[`path`,{d:`M16 17h4`,key:`1dejxt`}],[`path`,{d:`M4 13h4`,key:`1bwh8b`}]]),Lc=K(`funnel`,[[`path`,{d:`M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z`,key:`sc7q7i`}]]),Rc=K(`gamepad-2`,[[`line`,{x1:`6`,x2:`10`,y1:`11`,y2:`11`,key:`1gktln`}],[`line`,{x1:`8`,x2:`8`,y1:`9`,y2:`13`,key:`qnk9ow`}],[`line`,{x1:`15`,x2:`15.01`,y1:`12`,y2:`12`,key:`krot7o`}],[`line`,{x1:`18`,x2:`18.01`,y1:`10`,y2:`10`,key:`1lcuu1`}],[`path`,{d:`M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z`,key:`mfqc10`}]]),zc=K(`gauge`,[[`path`,{d:`m12 14 4-4`,key:`9kzdfg`}],[`path`,{d:`M3.34 19a10 10 0 1 1 17.32 0`,key:`19p75a`}]]),Bc=K(`grid-2x2`,[[`path`,{d:`M12 3v18`,key:`108xh3`}],[`path`,{d:`M3 12h18`,key:`1i2n21`}],[`rect`,{x:`3`,y:`3`,width:`18`,height:`18`,rx:`2`,key:`h1oib`}]]),Vc=K(`grip-horizontal`,[[`circle`,{cx:`12`,cy:`9`,r:`1`,key:`124mty`}],[`circle`,{cx:`19`,cy:`9`,r:`1`,key:`1ruzo2`}],[`circle`,{cx:`5`,cy:`9`,r:`1`,key:`1a8b28`}],[`circle`,{cx:`12`,cy:`15`,r:`1`,key:`1e56xg`}],[`circle`,{cx:`19`,cy:`15`,r:`1`,key:`1a92ep`}],[`circle`,{cx:`5`,cy:`15`,r:`1`,key:`5r1jwy`}]]),Hc=K(`hard-drive`,[[`path`,{d:`M10 16h.01`,key:`1bzywj`}],[`path`,{d:`M2.212 11.577a2 2 0 0 0-.212.896V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5.527a2 2 0 0 0-.212-.896L18.55 5.11A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z`,key:`18tbho`}],[`path`,{d:`M21.946 12.013H2.054`,key:`zqlbp7`}],[`path`,{d:`M6 16h.01`,key:`1pmjb7`}]]),Uc=K(`hash`,[[`line`,{x1:`4`,x2:`20`,y1:`9`,y2:`9`,key:`4lhtct`}],[`line`,{x1:`4`,x2:`20`,y1:`15`,y2:`15`,key:`vyu0kd`}],[`line`,{x1:`10`,x2:`8`,y1:`3`,y2:`21`,key:`1ggp8o`}],[`line`,{x1:`16`,x2:`14`,y1:`3`,y2:`21`,key:`weycgp`}]]),Wc=K(`hexagon`,[[`path`,{d:`M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z`,key:`yt0hxn`}]]),Gc=K(`house`,[[`path`,{d:`M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8`,key:`5wwlr5`}],[`path`,{d:`M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z`,key:`r6nss1`}]]),Kc=K(`image-off`,[[`line`,{x1:`2`,x2:`22`,y1:`2`,y2:`22`,key:`a6p6uj`}],[`path`,{d:`M10.41 10.41a2 2 0 1 1-2.83-2.83`,key:`1bzlo9`}],[`line`,{x1:`13.5`,x2:`6`,y1:`13.5`,y2:`21`,key:`1q0aeu`}],[`line`,{x1:`18`,x2:`21`,y1:`12`,y2:`15`,key:`5mozeu`}],[`path`,{d:`M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59`,key:`mmje98`}],[`path`,{d:`M21 15V5a2 2 0 0 0-2-2H9`,key:`43el77`}]]),qc=K(`image`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,ry:`2`,key:`1m3agn`}],[`circle`,{cx:`9`,cy:`9`,r:`2`,key:`af1f0g`}],[`path`,{d:`m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21`,key:`1xmnt7`}]]),Jc=K(`inbox`,[[`polyline`,{points:`22 12 16 12 14 15 10 15 8 12 2 12`,key:`o97t9d`}],[`path`,{d:`M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z`,key:`oot6mr`}]]),Yc=K(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),Xc=K(`layout-grid`,[[`rect`,{width:`7`,height:`7`,x:`3`,y:`3`,rx:`1`,key:`1g98yp`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`3`,rx:`1`,key:`6d4xhi`}],[`rect`,{width:`7`,height:`7`,x:`14`,y:`14`,rx:`1`,key:`nxv5o0`}],[`rect`,{width:`7`,height:`7`,x:`3`,y:`14`,rx:`1`,key:`1bb6yr`}]]),Zc=K(`lightbulb`,[[`path`,{d:`M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5`,key:`1gvzjb`}],[`path`,{d:`M9 18h6`,key:`x1upvd`}],[`path`,{d:`M10 22h4`,key:`ceow96`}]]),Qc=K(`list-checks`,[[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}],[`path`,{d:`m3 17 2 2 4-4`,key:`1jhpwq`}],[`path`,{d:`m3 7 2 2 4-4`,key:`1obspn`}]]),$c=K(`list`,[[`path`,{d:`M3 5h.01`,key:`18ugdj`}],[`path`,{d:`M3 12h.01`,key:`nlz23k`}],[`path`,{d:`M3 19h.01`,key:`noohij`}],[`path`,{d:`M8 5h13`,key:`1pao27`}],[`path`,{d:`M8 12h13`,key:`1za7za`}],[`path`,{d:`M8 19h13`,key:`m83p4d`}]]),el=K(`loader-circle`,[[`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`,key:`13zald`}]]),tl=K(`locate-fixed`,[[`line`,{x1:`2`,x2:`5`,y1:`12`,y2:`12`,key:`bvdh0s`}],[`line`,{x1:`19`,x2:`22`,y1:`12`,y2:`12`,key:`1tbv5k`}],[`line`,{x1:`12`,x2:`12`,y1:`2`,y2:`5`,key:`11lu5j`}],[`line`,{x1:`12`,x2:`12`,y1:`19`,y2:`22`,key:`x3vr5v`}],[`circle`,{cx:`12`,cy:`12`,r:`7`,key:`fim9np`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),nl=K(`lock-open`,[[`rect`,{width:`18`,height:`11`,x:`3`,y:`11`,rx:`2`,ry:`2`,key:`1w4ew1`}],[`path`,{d:`M7 11V7a5 5 0 0 1 9.9-1`,key:`1mm8w8`}]]),rl=K(`lock`,[[`rect`,{width:`18`,height:`11`,x:`3`,y:`11`,rx:`2`,ry:`2`,key:`1w4ew1`}],[`path`,{d:`M7 11V7a5 5 0 0 1 10 0v4`,key:`fwvmzm`}]]),il=K(`mail`,[[`path`,{d:`m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7`,key:`132q7q`}],[`rect`,{x:`2`,y:`4`,width:`20`,height:`16`,rx:`2`,key:`izxlao`}]]),al=K(`map-pin`,[[`path`,{d:`M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0`,key:`1r0f0z`}],[`circle`,{cx:`12`,cy:`10`,r:`3`,key:`ilqhr7`}]]),ol=K(`maximize-2`,[[`path`,{d:`M15 3h6v6`,key:`1q9fwt`}],[`path`,{d:`m21 3-7 7`,key:`1l2asr`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M9 21H3v-6`,key:`wtvkvv`}]]),sl=K(`megaphone`,[[`path`,{d:`M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z`,key:`q8bfy3`}],[`path`,{d:`M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14`,key:`1853fq`}],[`path`,{d:`M8 6v8`,key:`15ugcq`}]]),cl=K(`menu`,[[`path`,{d:`M4 5h16`,key:`1tepv9`}],[`path`,{d:`M4 12h16`,key:`1lakjw`}],[`path`,{d:`M4 19h16`,key:`1djgab`}]]),ll=K(`message-square`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}]]),ul=K(`mic`,[[`path`,{d:`M12 19v3`,key:`npa21l`}],[`path`,{d:`M19 10v2a7 7 0 0 1-14 0v-2`,key:`1vc78b`}],[`rect`,{x:`9`,y:`2`,width:`6`,height:`13`,rx:`3`,key:`s6n7sd`}]]),dl=K(`minimize-2`,[[`path`,{d:`m14 10 7-7`,key:`oa77jy`}],[`path`,{d:`M20 10h-6V4`,key:`mjg0md`}],[`path`,{d:`m3 21 7-7`,key:`tjx5ai`}],[`path`,{d:`M4 14h6v6`,key:`rmj7iw`}]]),fl=K(`minus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}]]),pl=K(`monitor-play`,[[`path`,{d:`M15.033 9.44a.647.647 0 0 1 0 1.12l-4.065 2.352a.645.645 0 0 1-.968-.56V7.648a.645.645 0 0 1 .967-.56z`,key:`vbtd3f`}],[`path`,{d:`M12 17v4`,key:`1riwvh`}],[`path`,{d:`M8 21h8`,key:`1ev6f3`}],[`rect`,{x:`2`,y:`3`,width:`20`,height:`14`,rx:`2`,key:`x3v2xh`}]]),ml=K(`moon`,[[`path`,{d:`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`,key:`kfwtm`}]]),hl=K(`mouse-pointer-click`,[[`path`,{d:`M14 4.1 12 6`,key:`ita8i4`}],[`path`,{d:`m5.1 8-2.9-.8`,key:`1go3kf`}],[`path`,{d:`m6 12-1.9 2`,key:`mnht97`}],[`path`,{d:`M7.2 2.2 8 5.1`,key:`1cfko1`}],[`path`,{d:`M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z`,key:`s0h3yz`}]]),gl=K(`move`,[[`path`,{d:`M12 2v20`,key:`t6zp3m`}],[`path`,{d:`m15 19-3 3-3-3`,key:`11eu04`}],[`path`,{d:`m19 9 3 3-3 3`,key:`1mg7y2`}],[`path`,{d:`M2 12h20`,key:`9i4pu4`}],[`path`,{d:`m5 9-3 3 3 3`,key:`j64kie`}],[`path`,{d:`m9 5 3-3 3 3`,key:`l8vdw6`}]]),_l=K(`music`,[[`path`,{d:`M9 18V5l12-2v13`,key:`1jmyc2`}],[`circle`,{cx:`6`,cy:`18`,r:`3`,key:`fqmcym`}],[`circle`,{cx:`18`,cy:`16`,r:`3`,key:`1hluhg`}]]),vl=K(`navigation`,[[`polygon`,{points:`3 11 22 2 13 21 11 13 3 11`,key:`1ltx0t`}]]),yl=K(`network`,[[`rect`,{x:`16`,y:`16`,width:`6`,height:`6`,rx:`1`,key:`4q2zg0`}],[`rect`,{x:`2`,y:`16`,width:`6`,height:`6`,rx:`1`,key:`8cvhb9`}],[`rect`,{x:`9`,y:`2`,width:`6`,height:`6`,rx:`1`,key:`1egb70`}],[`path`,{d:`M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3`,key:`1jsf9p`}],[`path`,{d:`M12 12V8`,key:`2874zd`}]]),bl=K(`pause`,[[`rect`,{x:`14`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`kaeet6`}],[`rect`,{x:`5`,y:`3`,width:`5`,height:`18`,rx:`1`,key:`1wsw3u`}]]),xl=K(`pencil`,[[`path`,{d:`M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z`,key:`1a8usu`}],[`path`,{d:`m15 5 4 4`,key:`1mk7zo`}]]),Sl=K(`pipette`,[[`path`,{d:`m12 9-8.414 8.414A2 2 0 0 0 3 18.828v1.344a2 2 0 0 1-.586 1.414A2 2 0 0 1 3.828 21h1.344a2 2 0 0 0 1.414-.586L15 12`,key:`1y3wsu`}],[`path`,{d:`m18 9 .4.4a1 1 0 1 1-3 3l-3.8-3.8a1 1 0 1 1 3-3l.4.4 3.4-3.4a1 1 0 1 1 3 3z`,key:`110lr1`}],[`path`,{d:`m2 22 .414-.414`,key:`jhxm08`}]]),Cl=K(`play`,[[`path`,{d:`M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z`,key:`10ikf1`}]]),wl=K(`plus`,[[`path`,{d:`M5 12h14`,key:`1ays0h`}],[`path`,{d:`M12 5v14`,key:`s699le`}]]),Tl=K(`plug`,[[`path`,{d:`M12 22v-5`,key:`1ega77`}],[`path`,{d:`M15 8V2`,key:`18g5xt`}],[`path`,{d:`M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z`,key:`1xoxul`}],[`path`,{d:`M9 8V2`,key:`14iosj`}]]),El=K(`power-off`,[[`path`,{d:`M18.36 6.64A9 9 0 0 1 20.77 15`,key:`dxknvb`}],[`path`,{d:`M6.16 6.16a9 9 0 1 0 12.68 12.68`,key:`1x7qb5`}],[`path`,{d:`M12 2v4`,key:`3427ic`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]),Dl=K(`power`,[[`path`,{d:`M12 2v10`,key:`mnfbl`}],[`path`,{d:`M18.4 6.6a9 9 0 1 1-12.77.04`,key:`obofu9`}]]),Ol=K(`qr-code`,[[`rect`,{width:`5`,height:`5`,x:`3`,y:`3`,rx:`1`,key:`1tu5fj`}],[`rect`,{width:`5`,height:`5`,x:`16`,y:`3`,rx:`1`,key:`1v8r4q`}],[`rect`,{width:`5`,height:`5`,x:`3`,y:`16`,rx:`1`,key:`1x03jg`}],[`path`,{d:`M21 16h-3a2 2 0 0 0-2 2v3`,key:`177gqh`}],[`path`,{d:`M21 21v.01`,key:`ents32`}],[`path`,{d:`M12 7v3a2 2 0 0 1-2 2H7`,key:`8crl2c`}],[`path`,{d:`M3 12h.01`,key:`nlz23k`}],[`path`,{d:`M12 3h.01`,key:`n36tog`}],[`path`,{d:`M12 16v.01`,key:`133mhm`}],[`path`,{d:`M16 12h1`,key:`1slzba`}],[`path`,{d:`M21 12v.01`,key:`1lwtk9`}],[`path`,{d:`M12 21v-1`,key:`1880an`}]]),kl=K(`radar`,[[`path`,{d:`M19.07 4.93A10 10 0 0 0 6.99 3.34`,key:`z3du51`}],[`path`,{d:`M4 6h.01`,key:`oypzma`}],[`path`,{d:`M2.29 9.62A10 10 0 1 0 21.31 8.35`,key:`qzzz0`}],[`path`,{d:`M16.24 7.76A6 6 0 1 0 8.23 16.67`,key:`1yjesh`}],[`path`,{d:`M12 18h.01`,key:`mhygvu`}],[`path`,{d:`M17.99 11.66A6 6 0 0 1 15.77 16.67`,key:`1u2y91`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}],[`path`,{d:`m13.41 10.59 5.66-5.66`,key:`mhq4k0`}]]),Al=K(`radio`,[[`path`,{d:`M16.247 7.761a6 6 0 0 1 0 8.478`,key:`1fwjs5`}],[`path`,{d:`M19.075 4.933a10 10 0 0 1 0 14.134`,key:`ehdyv1`}],[`path`,{d:`M4.925 19.067a10 10 0 0 1 0-14.134`,key:`1q22gi`}],[`path`,{d:`M7.753 16.239a6 6 0 0 1 0-8.478`,key:`r2q7qm`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),jl=K(`refresh-cw`,[[`path`,{d:`M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8`,key:`v9h5vc`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}],[`path`,{d:`M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16`,key:`3uifl3`}],[`path`,{d:`M8 16H3v5`,key:`1cv678`}]]),Ml=K(`rotate-ccw`,[[`path`,{d:`M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8`,key:`1357e3`}],[`path`,{d:`M3 3v5h5`,key:`1xhq8a`}]]),Nl=K(`rotate-cw`,[[`path`,{d:`M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8`,key:`1p45f6`}],[`path`,{d:`M21 3v5h-5`,key:`1q7to0`}]]),Pl=K(`save`,[[`path`,{d:`M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z`,key:`1c8476`}],[`path`,{d:`M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7`,key:`1ydtos`}],[`path`,{d:`M7 3v4a1 1 0 0 0 1 1h7`,key:`t51u73`}]]),Fl=K(`scan`,[[`path`,{d:`M3 7V5a2 2 0 0 1 2-2h2`,key:`aa7l1z`}],[`path`,{d:`M17 3h2a2 2 0 0 1 2 2v2`,key:`4qcy5o`}],[`path`,{d:`M21 17v2a2 2 0 0 1-2 2h-2`,key:`6vwrx8`}],[`path`,{d:`M7 21H5a2 2 0 0 1-2-2v-2`,key:`ioqczr`}]]),Il=K(`scroll-text`,[[`path`,{d:`M15 12h-5`,key:`r7krc0`}],[`path`,{d:`M15 8h-5`,key:`1khuty`}],[`path`,{d:`M19 17V5a2 2 0 0 0-2-2H4`,key:`zz82l3`}],[`path`,{d:`M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3`,key:`1ph1d7`}]]),Ll=K(`search`,[[`path`,{d:`m21 21-4.34-4.34`,key:`14j7rj`}],[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}]]),Rl=K(`server`,[[`rect`,{width:`20`,height:`8`,x:`2`,y:`2`,rx:`2`,ry:`2`,key:`ngkwjq`}],[`rect`,{width:`20`,height:`8`,x:`2`,y:`14`,rx:`2`,ry:`2`,key:`iecqi9`}],[`line`,{x1:`6`,x2:`6.01`,y1:`6`,y2:`6`,key:`16zg32`}],[`line`,{x1:`6`,x2:`6.01`,y1:`18`,y2:`18`,key:`nzw8ys`}]]),zl=K(`settings`,[[`path`,{d:`M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915`,key:`1i5ecw`}],[`circle`,{cx:`12`,cy:`12`,r:`3`,key:`1v7zrd`}]]),Bl=K(`share-2`,[[`circle`,{cx:`18`,cy:`5`,r:`3`,key:`gq8acd`}],[`circle`,{cx:`6`,cy:`12`,r:`3`,key:`w7nqdw`}],[`circle`,{cx:`18`,cy:`19`,r:`3`,key:`1xt0gg`}],[`line`,{x1:`8.59`,x2:`15.42`,y1:`13.51`,y2:`17.49`,key:`47mynk`}],[`line`,{x1:`15.41`,x2:`8.59`,y1:`6.51`,y2:`10.49`,key:`1n3mei`}]]),Vl=K(`shield-alert`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`M12 8v4`,key:`1got3b`}],[`path`,{d:`M12 16h.01`,key:`1drbdi`}]]),Hl=K(`shield-check`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}],[`path`,{d:`m9 12 2 2 4-4`,key:`dzmm74`}]]),Ul=K(`shield-off`,[[`path`,{d:`m2 2 20 20`,key:`1ooewy`}],[`path`,{d:`M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71`,key:`1jlk70`}],[`path`,{d:`M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264`,key:`18rp1v`}]]),Wl=K(`shield`,[[`path`,{d:`M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z`,key:`oel41y`}]]),Gl=K(`ship`,[[`path`,{d:`M12 10.189V14`,key:`1p8cqu`}],[`path`,{d:`M12 2v3`,key:`qbqxhf`}],[`path`,{d:`M19 13V7a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v6`,key:`qpkstq`}],[`path`,{d:`M19.38 20A11.6 11.6 0 0 0 21 14l-8.188-3.639a2 2 0 0 0-1.624 0L3 14a11.6 11.6 0 0 0 2.81 7.76`,key:`7tigtc`}],[`path`,{d:`M2 21c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1s1.2 1 2.5 1c2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1`,key:`1924j5`}]]),Kl=K(`siren`,[[`path`,{d:`M7 18v-6a5 5 0 1 1 10 0v6`,key:`pcx96s`}],[`path`,{d:`M5 21a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2z`,key:`1b4s83`}],[`path`,{d:`M21 12h1`,key:`jtio3y`}],[`path`,{d:`M18.5 4.5 18 5`,key:`g5sp9y`}],[`path`,{d:`M2 12h1`,key:`1uaihz`}],[`path`,{d:`M12 2v1`,key:`11qlp1`}],[`path`,{d:`m4.929 4.929.707.707`,key:`1i51kw`}],[`path`,{d:`M12 12v6`,key:`3ahymv`}]]),ql=K(`skip-back`,[[`path`,{d:`M17.971 4.285A2 2 0 0 1 21 6v12a2 2 0 0 1-3.029 1.715l-9.997-5.998a2 2 0 0 1-.003-3.432z`,key:`15892j`}],[`path`,{d:`M3 20V4`,key:`1ptbpl`}]]),Jl=K(`skip-forward`,[[`path`,{d:`M21 4v16`,key:`7j8fe9`}],[`path`,{d:`M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z`,key:`zs4d6`}]]),Yl=K(`sliders-horizontal`,[[`path`,{d:`M10 5H3`,key:`1qgfaw`}],[`path`,{d:`M12 19H3`,key:`yhmn1j`}],[`path`,{d:`M14 3v4`,key:`1sua03`}],[`path`,{d:`M16 17v4`,key:`1q0r14`}],[`path`,{d:`M21 12h-9`,key:`1o4lsq`}],[`path`,{d:`M21 19h-5`,key:`1rlt1p`}],[`path`,{d:`M21 5h-7`,key:`1oszz2`}],[`path`,{d:`M8 10v4`,key:`tgpxqk`}],[`path`,{d:`M8 12H3`,key:`a7s4jb`}]]),Xl=K(`smartphone`,[[`rect`,{width:`14`,height:`20`,x:`5`,y:`2`,rx:`2`,ry:`2`,key:`1yt0o3`}],[`path`,{d:`M12 18h.01`,key:`mhygvu`}]]),Zl=K(`square`,[[`rect`,{width:`18`,height:`18`,x:`3`,y:`3`,rx:`2`,key:`afitv7`}]]),Ql=K(`star`,[[`path`,{d:`M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z`,key:`r04s7s`}]]),$l=K(`sun`,[[`circle`,{cx:`12`,cy:`12`,r:`4`,key:`4exip2`}],[`path`,{d:`M12 2v2`,key:`tus03m`}],[`path`,{d:`M12 20v2`,key:`1lh1kg`}],[`path`,{d:`m4.93 4.93 1.41 1.41`,key:`149t6j`}],[`path`,{d:`m17.66 17.66 1.41 1.41`,key:`ptbguv`}],[`path`,{d:`M2 12h2`,key:`1t8f8n`}],[`path`,{d:`M20 12h2`,key:`1q8mjw`}],[`path`,{d:`m6.34 17.66-1.41 1.41`,key:`1m8zz5`}],[`path`,{d:`m19.07 4.93-1.41 1.41`,key:`1shlcs`}]]),eu=K(`table-2`,[[`path`,{d:`M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18`,key:`gugj83`}]]),tu=K(`target`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`circle`,{cx:`12`,cy:`12`,r:`6`,key:`1vlfrh`}],[`circle`,{cx:`12`,cy:`12`,r:`2`,key:`1c9p78`}]]),nu=K(`thermometer`,[[`path`,{d:`M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z`,key:`17jzev`}]]),ru=K(`toggle-left`,[[`circle`,{cx:`9`,cy:`12`,r:`3`,key:`u3jwor`}],[`rect`,{width:`20`,height:`14`,x:`2`,y:`5`,rx:`7`,key:`g7kal2`}]]),iu=K(`tractor`,[[`path`,{d:`m10 11 11 .9a1 1 0 0 1 .8 1.1l-.665 4.158a1 1 0 0 1-.988.842H20`,key:`she1j9`}],[`path`,{d:`M16 18h-5`,key:`bq60fd`}],[`path`,{d:`M18 5a1 1 0 0 0-1 1v5.573`,key:`1kv8ia`}],[`path`,{d:`M3 4h8.129a1 1 0 0 1 .99.863L13 11.246`,key:`1q1ert`}],[`path`,{d:`M4 11V4`,key:`9ft8pt`}],[`path`,{d:`M7 15h.01`,key:`k5ht0j`}],[`path`,{d:`M8 10.1V4`,key:`1jgyzo`}],[`circle`,{cx:`18`,cy:`18`,r:`2`,key:`1emm8v`}],[`circle`,{cx:`7`,cy:`15`,r:`5`,key:`ddtuc`}]]),au=K(`trash-2`,[[`path`,{d:`M10 11v6`,key:`nco0om`}],[`path`,{d:`M14 11v6`,key:`outv1u`}],[`path`,{d:`M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6`,key:`miytrc`}],[`path`,{d:`M3 6h18`,key:`d0wm0j`}],[`path`,{d:`M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2`,key:`e791ji`}]]),ou=K(`trending-up`,[[`path`,{d:`M16 7h6v6`,key:`box55l`}],[`path`,{d:`m22 7-8.5 8.5-5-5L2 17`,key:`1t1m79`}]]),su=K(`trending-down`,[[`path`,{d:`M16 17h6v-6`,key:`t6n2it`}],[`path`,{d:`m22 17-8.5-8.5-5 5L2 7`,key:`x473p`}]]),cu=K(`triangle-alert`,[[`path`,{d:`m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3`,key:`wmoenq`}],[`path`,{d:`M12 9v4`,key:`juzpu7`}],[`path`,{d:`M12 17h.01`,key:`p32p05`}]]),lu=K(`type`,[[`path`,{d:`M12 4v16`,key:`1654pz`}],[`path`,{d:`M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2`,key:`e0r10z`}],[`path`,{d:`M9 20h6`,key:`s66wpe`}]]),uu=K(`unlink-2`,[[`path`,{d:`M15 7h2a5 5 0 0 1 0 10h-2m-6 0H7A5 5 0 0 1 7 7h2`,key:`1re2ne`}]]),du=K(`upload`,[[`path`,{d:`M12 3v12`,key:`1x0j5s`}],[`path`,{d:`m17 8-5-5-5 5`,key:`7q97r8`}],[`path`,{d:`M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4`,key:`ih7n3h`}]]),fu=K(`vibrate`,[[`path`,{d:`m2 8 2 2-2 2 2 2-2 2`,key:`sv1b1`}],[`path`,{d:`m22 8-2 2 2 2-2 2 2 2`,key:`101i4y`}],[`rect`,{width:`8`,height:`14`,x:`8`,y:`5`,rx:`1`,key:`1oyrl4`}]]),pu=K(`volume-2`,[[`path`,{d:`M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z`,key:`uqj9uw`}],[`path`,{d:`M16 9a5 5 0 0 1 0 6`,key:`1q6k2b`}],[`path`,{d:`M19.364 18.364a9 9 0 0 0 0-12.728`,key:`ijwkga`}]]),mu=K(`volume-x`,[[`path`,{d:`M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z`,key:`uqj9uw`}],[`line`,{x1:`22`,x2:`16`,y1:`9`,y2:`15`,key:`1ewh16`}],[`line`,{x1:`16`,x2:`22`,y1:`9`,y2:`15`,key:`5ykzw1`}]]),hu=K(`waves`,[[`path`,{d:`M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1`,key:`knzxuh`}],[`path`,{d:`M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1`,key:`2jd2cc`}],[`path`,{d:`M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1`,key:`rd2r6e`}]]),gu=K(`wifi-off`,[[`path`,{d:`M12 20h.01`,key:`zekei9`}],[`path`,{d:`M8.5 16.429a5 5 0 0 1 7 0`,key:`1bycff`}],[`path`,{d:`M5 12.859a10 10 0 0 1 5.17-2.69`,key:`1dl1wf`}],[`path`,{d:`M19 12.859a10 10 0 0 0-2.007-1.523`,key:`4k23kn`}],[`path`,{d:`M2 8.82a15 15 0 0 1 4.177-2.643`,key:`1grhjp`}],[`path`,{d:`M22 8.82a15 15 0 0 0-11.288-3.764`,key:`z3jwby`}],[`path`,{d:`m2 2 20 20`,key:`1ooewy`}]]),_u=K(`wifi`,[[`path`,{d:`M12 20h.01`,key:`zekei9`}],[`path`,{d:`M2 8.82a15 15 0 0 1 20 0`,key:`dnpr2z`}],[`path`,{d:`M5 12.859a10 10 0 0 1 14 0`,key:`1x1e6c`}],[`path`,{d:`M8.5 16.429a5 5 0 0 1 7 0`,key:`1bycff`}]]),vu=K(`wind`,[[`path`,{d:`M12.8 19.6A2 2 0 1 0 14 16H2`,key:`148xed`}],[`path`,{d:`M17.5 8a2.5 2.5 0 1 1 2 4H2`,key:`1u4tom`}],[`path`,{d:`M9.8 4.4A2 2 0 1 1 11 8H2`,key:`75valh`}]]),yu=K(`workflow`,[[`rect`,{width:`8`,height:`8`,x:`3`,y:`3`,rx:`2`,key:`by2w9f`}],[`path`,{d:`M7 11v4a2 2 0 0 0 2 2h4`,key:`xkn7yn`}],[`rect`,{width:`8`,height:`8`,x:`13`,y:`13`,rx:`2`,key:`1cgmvn`}]]),bu=K(`wrench`,[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z`,key:`1ngwbx`}]]),xu=K(`x`,[[`path`,{d:`M18 6 6 18`,key:`1bl5f8`}],[`path`,{d:`m6 6 12 12`,key:`d8bk6v`}]]),Su=K(`zap`,[[`path`,{d:`M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z`,key:`1xq2db`}]]),Cu=K(`zoom-in`,[[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}],[`line`,{x1:`21`,x2:`16.65`,y1:`21`,y2:`16.65`,key:`13gj7c`}],[`line`,{x1:`11`,x2:`11`,y1:`8`,y2:`14`,key:`1vmskp`}],[`line`,{x1:`8`,x2:`14`,y1:`11`,y2:`11`,key:`durymu`}]]),wu=K(`zoom-out`,[[`circle`,{cx:`11`,cy:`11`,r:`8`,key:`4ej97u`}],[`line`,{x1:`21`,x2:`16.65`,y1:`21`,y2:`16.65`,key:`13gj7c`}],[`line`,{x1:`8`,x2:`14`,y1:`11`,y2:`11`,key:`durymu`}]]),Tu={frigate:Gl,scrypted:Wl,reolink:Al,homeAssistant:Gc,rtsp:Js},Eu={online:ic,offline:lc,degraded:nc,unknown:cc},Du=e=>typeof e==`boolean`?`${e}`:e===0?`0`:e,Ou=Ze,ku=(e,t)=>n=>{if(t?.variants==null)return Ou(e,n?.class,n?.className);let{variants:r,defaultVariants:i}=t,a=Object.keys(r).map(e=>{let t=n?.[e],a=i?.[e];if(t===null)return null;let o=Du(t)||Du(a);return r[e][o]}),o=n&&Object.entries(n).reduce((e,t)=>{let[n,r]=t;return r===void 0||(e[n]=r),e},{});return Ou(e,a,t?.compoundVariants?.reduce((e,t)=>{let{class:n,className:r,...a}=t;return Object.entries(a).every(e=>{let[t,n]=e;return Array.isArray(n)?n.includes({...i,...o}[t]):{...i,...o}[t]===n})?[...e,n,r]:e},[]),n?.class,n?.className)},Au=ku(`inline-flex items-center justify-center rounded-md font-medium transition-colors cursor-pointer disabled:opacity-50 disabled:pointer-events-none`,{variants:{variant:{primary:`bg-primary text-primary-foreground hover:bg-primary/90`,secondary:`bg-surface text-foreground hover:bg-surface-hover`,ghost:`hover:bg-surface-hover text-foreground-muted`,danger:`bg-danger text-white hover:bg-danger/90`,outline:`border border-border bg-transparent hover:bg-surface-hover`},size:{sm:`h-7 px-2.5 text-xs gap-1.5`,md:`h-8 px-3 text-sm gap-2`,lg:`h-9 px-4 text-sm gap-2`}},defaultVariants:{variant:`primary`,size:`sm`}}),ju=l(({className:e,variant:t,size:n,...r},i)=>v(`button`,{ref:i,className:G(Au({variant:t,size:n}),e),...r}));ju.displayName=`Button`;var Mu=ku(`inline-flex items-center justify-center rounded-md font-medium transition-colors cursor-pointer disabled:opacity-50 disabled:pointer-events-none`,{variants:{variant:{primary:`bg-primary text-primary-foreground hover:bg-primary/90`,secondary:`bg-surface text-foreground hover:bg-surface-hover`,ghost:`hover:bg-surface-hover text-foreground-muted`,danger:`bg-danger text-white hover:bg-danger/90`,outline:`border border-border bg-transparent hover:bg-surface-hover`},size:{sm:`h-7 w-7`,md:`h-8 w-8`,lg:`h-9 w-9`}},defaultVariants:{variant:`primary`,size:`sm`}}),Nu=l(({className:e,variant:t,size:n,icon:r,...i},a)=>v(`button`,{ref:a,className:G(Mu({variant:t,size:n}),e),...i,children:v(r,{className:`h-4 w-4`})}));Nu.displayName=`IconButton`;var Pu=ku(`inline-flex items-center rounded-full text-xs font-medium px-2 py-0.5`,{variants:{variant:{default:`bg-surface-hover text-foreground`,success:`bg-success/15 text-success`,warning:`bg-warning/15 text-warning`,danger:`bg-danger/15 text-danger`,info:`bg-info/15 text-info`},styleVariant:{solid:``,outline:`border bg-transparent`}},defaultVariants:{variant:`default`,styleVariant:`solid`}}),Fu=l(({className:e,variant:t,style:n,...r},i)=>v(`span`,{ref:i,className:G(Pu({variant:t,styleVariant:n}),e),...r}));Fu.displayName=`Badge`;var Iu=ku(`rounded-lg p-3`,{variants:{variant:{flat:`bg-surface`,bordered:`bg-surface border border-border`}},defaultVariants:{variant:`bordered`}}),Lu=l(({className:e,variant:t,...n},r)=>v(`div`,{ref:r,className:G(Iu({variant:t}),e),...n}));Lu.displayName=`Card`;function Ru({expanded:e,onExpandedChange:t,header:n,children:r,dimmed:i=!1,hideChevron:a=!1,className:o}){return T(`div`,{className:G(`rounded-lg border border-border bg-surface overflow-hidden`,i&&`opacity-[0.45]`,o),children:[T(`div`,{role:`button`,tabIndex:0,className:`flex items-center gap-2.5 px-3 py-2.5 cursor-pointer select-none`,onClick:()=>t(!e),onKeyDown:n=>{(n.key===`Enter`||n.key===` `)&&(n.preventDefault(),t(!e))},children:[!a&&v(`span`,{className:`text-foreground-subtle shrink-0`,children:v(e?Xs:Qs,{className:`h-4 w-4`})}),n]}),e&&r&&v(`div`,{className:`border-t border-border px-3 py-3`,children:r})]})}var zu=l(({className:e,...t},n)=>v(`label`,{ref:n,className:G(`text-[10px] uppercase tracking-wider text-foreground-muted font-medium`,e),...t}));zu.displayName=`Label`;var Bu=ku(``,{variants:{orientation:{horizontal:`h-px w-full bg-border-subtle`,vertical:`w-px h-full bg-border-subtle`}},defaultVariants:{orientation:`horizontal`}}),Vu=l(({className:e,orientation:t,...n},r)=>v(`div`,{ref:r,role:`separator`,className:G(Bu({orientation:t}),e),...n}));Vu.displayName=`Separator`;var Hu=l(({className:e,...t},n)=>v(`div`,{ref:n,className:G(`animate-pulse bg-surface-hover rounded-md h-4 w-full`,e),...t}));Hu.displayName=`Skeleton`;var Uu=ku(`h-7 w-full px-2.5 text-xs bg-surface border rounded-md text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary transition-colors`,{variants:{state:{default:`border-border`,error:`border-danger`}},defaultVariants:{state:`default`}}),Wu=l(({className:e,state:t,leftSlot:n,rightSlot:r,...i},a)=>n||r?T(`div`,{className:`relative flex items-center w-full`,children:[n&&v(`div`,{className:`absolute left-2.5 flex items-center pointer-events-none`,children:n}),v(`input`,{ref:a,className:G(Uu({state:t}),n?`pl-7`:``,r?`pr-7`:``,e),...i}),r&&v(`div`,{className:`absolute right-2.5 flex items-center pointer-events-none`,children:r})]}):v(`input`,{ref:a,className:G(Uu({state:t}),e),...i}));Wu.displayName=`Input`;var Gu=l(({className:e,options:t,...n},r)=>T(`div`,{className:`relative w-full`,children:[v(`select`,{ref:r,className:G(`h-7 w-full px-2.5 text-xs bg-surface border border-border rounded-md text-foreground appearance-none pr-7 focus:outline-none focus:ring-1 focus:ring-primary`,e),...n,children:t.map(e=>v(`option`,{value:e.value,children:e.label},e.value))}),v(`div`,{className:`absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none text-foreground-muted`,children:v(Xs,{className:`h-3.5 w-3.5`})})]}));Gu.displayName=`Select`;var Ku=l(({className:e,...t},n)=>v(`input`,{ref:n,type:`checkbox`,className:G(`w-3.5 h-3.5 rounded-sm border border-border accent-primary`,e),...t}));Ku.displayName=`Checkbox`;var qu=l(({className:e,checked:t,onCheckedChange:n,label:r,...i},a)=>T(`button`,{ref:a,role:`switch`,"aria-checked":t,type:`button`,onClick:()=>n(!t),className:G(`inline-flex items-center gap-2`,e),...i,children:[v(`span`,{className:G(`w-8 h-4 rounded-full transition-colors`,t?`bg-primary`:`bg-surface-hover`),children:v(`span`,{className:G(`block w-3.5 h-3.5 rounded-full bg-white transition-transform`,t?`translate-x-4`:`translate-x-0.5`)})}),r&&v(`span`,{className:`text-xs text-foreground`,children:r})]}));qu.displayName=`Switch`;var Ju=r(null);function Yu(){let e=i(Ju);if(!e)throw Error(`Dialog compound components must be used within <Dialog>`);return e}function Xu({children:e,open:t,onOpenChange:n}){let[r,i]=h(!1),a=t??r,o=D(),s=u(e=>{n?.(e),t===void 0&&i(e)},[t,n]);return v(Ju.Provider,{value:{open:a,setOpen:s,contentId:o},children:e})}function Zu({children:e,...t}){let{setOpen:n}=Yu();return v(`button`,{type:`button`,onClick:()=>n(!0),...t,children:e})}var Qu=ku(`fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 m-0 w-[calc(100vw-2rem)] bg-background-elevated border border-border rounded-lg p-4 backdrop:bg-black/50 backdrop:backdrop-blur-sm max-h-[calc(100dvh-2rem)] overflow-y-auto`,{variants:{width:{sm:`max-w-sm`,md:`max-w-md`,lg:`max-w-lg`}},defaultVariants:{width:`md`}}),$u=l(({className:e,width:t,children:n,...r},i)=>{let{open:a,setOpen:o,contentId:s}=Yu(),l=p(null),u=i??l;return c(()=>{let e=u.current;e&&(a&&!e.open&&e.showModal(),!a&&e.open&&e.close())},[a,u]),v(`dialog`,{ref:u,id:s,className:G(Qu({width:t}),e),onClick:e=>{e.target===e.currentTarget&&o(!1)},onClose:()=>o(!1),...r,children:n})});$u.displayName=`DialogContent`;function ed({className:e,...t}){return v(`div`,{className:G(`flex flex-col gap-1 mb-3`,e),...t})}function td({className:e,...t}){return v(`div`,{className:G(`flex justify-end gap-2 mt-4`,e),...t})}function nd({className:e,...t}){return v(`h2`,{className:G(`text-sm font-semibold text-foreground`,e),...t})}function rd({className:e,...t}){return v(`p`,{className:G(`text-xs text-foreground-muted`,e),...t})}var id=r(null);function ad(){let e=i(id);if(!e)throw Error(`Dropdown compound components must be used within <Dropdown>`);return e}function od({children:e}){let[t,n]=h(!1),r=D(),i=D(),a=p(null);return v(id.Provider,{value:{open:t,setOpen:n,triggerId:r,contentId:i,triggerRef:a},children:v(`div`,{className:`relative inline-block`,children:e})})}function sd({children:e,...t}){let{open:n,setOpen:r,triggerId:i,contentId:a,triggerRef:o}=ad();return v(`button`,{type:`button`,ref:o,id:i,"aria-haspopup":`menu`,"aria-expanded":n,"aria-controls":n?a:void 0,onClick:()=>r(!n),...t,children:e})}function cd({className:e,children:t,align:n=`start`,offset:r=4,...i}){let{open:a,setOpen:o,contentId:s,triggerId:l,triggerRef:u}=ad(),d=p(null),[f,g]=h(null);return m(()=>{if(!a){g(null);return}let e=()=>{let e=u.current;if(!e)return;let t=e.getBoundingClientRect(),i=n===`end`?t.right:t.left;g({top:t.bottom+r,left:i,minWidth:t.width})};return e(),window.addEventListener(`resize`,e),window.addEventListener(`scroll`,e,!0),()=>{window.removeEventListener(`resize`,e),window.removeEventListener(`scroll`,e,!0)}},[a,n,r,u]),c(()=>{if(!a)return;let e=e=>{let t=d.current,n=u.current;t&&!t.contains(e.target)&&!n?.contains(e.target)&&o(!1)},t=e=>{e.key===`Escape`&&o(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[a,o,u]),!a||!f||typeof document>`u`?null:A(v(`div`,{ref:d,id:s,role:`menu`,"aria-labelledby":l,style:{position:`fixed`,top:f.top,...n===`end`?{right:window.innerWidth-f.left}:{left:f.left},minWidth:f.minWidth},className:G(`z-50 bg-background-elevated border border-border rounded-md shadow-lg py-1 min-w-[160px]`,e),...i,children:t}),document.body)}function ld({className:e,icon:t,variant:n=`default`,children:r,onClick:i,...a}){let{setOpen:o}=ad(),s=u(e=>{i?.(e),o(!1)},[i,o]);return T(`button`,{type:`button`,role:`menuitem`,className:G(`h-7 text-xs px-2 w-full text-left flex items-center gap-2`,n===`danger`?`text-danger hover:bg-danger/10`:`text-foreground hover:bg-surface-hover`,e),onClick:s,...a,children:[t&&v(t,{size:14}),r]})}var ud=r(null);function dd(){let e=i(ud);if(!e)throw Error(`Tooltip compound components must be used within <Tooltip>`);return e}function fd({children:e,className:t}){let[n,r]=h(!1),i=p(null),a=D();return v(ud.Provider,{value:{open:n,show:()=>{i.current=setTimeout(()=>r(!0),300)},hide:()=>{i.current&&clearTimeout(i.current),r(!1)},tooltipId:a},children:v(`div`,{className:G(`relative`,t??`inline-block`),children:e})})}function pd({children:e,...t}){let{show:n,hide:r,tooltipId:i,open:a}=dd();return v(`div`,{onMouseEnter:n,onMouseLeave:r,onFocus:n,onBlur:r,"aria-describedby":a?i:void 0,...t,children:e})}function md({className:e,children:t,...n}){let{open:r,tooltipId:i}=dd();return v(`div`,{id:i,role:`tooltip`,className:G(`absolute bottom-full left-1/2 -translate-x-1/2 mb-2 bg-foreground text-background text-xs px-2 py-1 rounded-md shadow-md whitespace-nowrap pointer-events-none transition-opacity duration-150`,r?`opacity-100`:`opacity-0`,e),...n,children:t})}var hd=`(max-width: 767px)`,gd=`(min-width: 768px) and (max-width: 1023px)`;function _d(e){return t=>{let n=window.matchMedia(e);return n.addEventListener(`change`,t),()=>n.removeEventListener(`change`,t)}}function vd(e){return()=>window.matchMedia(e).matches}function yd(){return!1}function bd(){return a(_d(hd),vd(hd),yd)}function xd(){return a(_d(gd),vd(gd),yd)}function Sd({open:e,onClose:t,title:n,children:r,className:i}){return c(()=>{if(!e)return;let n=e=>{e.key===`Escape`&&t()};return document.addEventListener(`keydown`,n),document.body.style.overflow=`hidden`,()=>{document.removeEventListener(`keydown`,n),document.body.style.overflow=``}},[e,t]),T(E,{children:[v(`div`,{className:G(`fixed inset-0 z-40 bg-black/50 transition-opacity duration-200`,e?`opacity-100`:`pointer-events-none opacity-0`),onClick:t,"aria-hidden":`true`}),T(`div`,{role:`dialog`,"aria-modal":`true`,className:G(`fixed inset-x-0 bottom-0 z-50 flex flex-col bg-background-elevated border-t border-border rounded-t-xl shadow-2xl transition-transform duration-200 ease-out`,`max-h-[80dvh]`,e?`translate-y-0`:`translate-y-full`,i),children:[v(`div`,{className:`flex justify-center pt-2 pb-1`,children:v(`div`,{className:`h-1 w-8 rounded-full bg-foreground-subtle/30`})}),n&&T(`div`,{className:`flex items-center justify-between px-4 pb-2`,children:[v(`span`,{className:`text-sm font-medium text-foreground`,children:n}),v(`button`,{onClick:t,className:`p-1 rounded-md hover:bg-surface-hover text-foreground-muted transition-colors`,children:v(xu,{className:`h-4 w-4`})})]}),v(`div`,{className:`flex-1 overflow-y-auto px-4 pb-4`,children:r})]})]})}var Cd=r(null);function wd(){let e=i(Cd);if(!e)throw Error(`Popover compound components must be used within <Popover>`);return e}function Td({children:e,open:t,onOpenChange:n}){let[r,i]=h(!1),a=t??r,o=D(),s=D(),c=u(e=>{n?.(e),t===void 0&&i(e)},[t,n]);return v(Cd.Provider,{value:{open:a,setOpen:c,triggerId:o,contentId:s},children:v(`div`,{className:`relative inline-block`,children:e})})}function Ed({children:e,...t}){let{open:n,setOpen:r,triggerId:i,contentId:a}=wd();return v(`button`,{type:`button`,id:i,"aria-haspopup":`dialog`,"aria-expanded":n,"aria-controls":n?a:void 0,onClick:()=>r(!n),...t,children:e})}function Dd({className:e,children:t,...n}){let{open:r,setOpen:i,contentId:a,triggerId:o}=wd(),s=bd(),l=p(null);return c(()=>{if(!r||s)return;let e=e=>{let t=l.current,n=document.getElementById(o);t&&!t.contains(e.target)&&!n?.contains(e.target)&&i(!1)},t=e=>{e.key===`Escape`&&i(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[r,i,o,s]),r?s?v(Sd,{open:r,onClose:()=>i(!1),children:t}):v(`div`,{ref:l,id:a,role:`dialog`,"aria-labelledby":o,className:G(`absolute left-0 top-full z-50 mt-1 bg-background-elevated border border-border rounded-lg shadow-lg p-3`,e),...n,children:t}):null}var Od=r(null);function kd(){let e=i(Od);if(!e)throw Error(`Tabs compound components must be used within <Tabs>`);return e}function Ad({value:e,onValueChange:t,defaultValue:n=``,className:r,...i}){let[a,o]=h(n),s=e??a,c=u(n=>{t?.(n),e===void 0&&o(n)},[e,t]);return v(Od.Provider,{value:{value:s,setValue:c},children:v(`div`,{className:r,...i})})}function jd({className:e,...t}){return v(`div`,{role:`tablist`,className:G(`flex flex-row border-b border-border-subtle`,e),...t})}function Md({value:e,className:t,...n}){let{value:r,setValue:i}=kd(),a=e===r;return v(`button`,{type:`button`,role:`tab`,"aria-selected":a,"aria-controls":`tabpanel-${e}`,tabIndex:a?0:-1,className:G(`h-7 text-xs px-3 transition-colors`,a?`border-b-2 border-primary text-foreground font-medium`:`text-foreground-muted hover:text-foreground`,t),onClick:()=>i(e),...n})}function Nd({value:e,className:t,...n}){let{value:r}=kd();return e===r?v(`div`,{role:`tabpanel`,id:`tabpanel-${e}`,className:G(`pt-3`,t),...n}):null}var Pd=l(({className:e,...t},n)=>v(`div`,{ref:n,className:G(`overflow-auto [&::-webkit-scrollbar]:w-1 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:bg-surface-hover [&::-webkit-scrollbar-thumb]:rounded-full`,e),...t}));Pd.displayName=`ScrollArea`;function Fd({title:e,onClose:t,children:n,defaultWidth:r=360,defaultHeight:i=280,minWidth:a=280,minHeight:o=160,offsetIndex:s=0,className:l}){let[d,f]=h({x:80+s*30,y:80+s*30}),[m,g]=h({w:r,h:i}),[_,y]=h(!1),b=p(!1),x=p(!1),S=p({x:0,y:0}),C=bd(),w=u(e=>{e.preventDefault(),b.current=!0,S.current={x:e.clientX-d.x,y:e.clientY-d.y}},[d]),E=u(e=>{e.preventDefault(),e.stopPropagation(),x.current=!0,S.current={x:e.clientX,y:e.clientY}},[]);return c(()=>{let e=e=>{if(b.current&&f({x:e.clientX-S.current.x,y:e.clientY-S.current.y}),x.current){let t=e.clientX-S.current.x,n=e.clientY-S.current.y;S.current={x:e.clientX,y:e.clientY},g(e=>({w:Math.max(a,e.w+t),h:Math.max(o,e.h+n)}))}},t=()=>{b.current=!1,x.current=!1};return window.addEventListener(`mousemove`,e),window.addEventListener(`mouseup`,t),()=>{window.removeEventListener(`mousemove`,e),window.removeEventListener(`mouseup`,t)}},[a,o]),C?T(`div`,{className:G(`fixed inset-x-0 bottom-0 z-50 rounded-t-xl border-t border-border bg-background-elevated shadow-2xl flex flex-col overflow-hidden`,l),style:{maxHeight:`60dvh`},children:[T(`div`,{className:`flex items-center justify-between gap-2 px-3 py-2 border-b border-border shrink-0 bg-surface`,children:[v(`span`,{className:`text-[11px] font-medium truncate`,children:e}),T(`div`,{className:`flex items-center gap-1 shrink-0`,children:[v(`button`,{onClick:()=>y(!_),className:`p-0.5 rounded hover:bg-surface-hover text-foreground-muted transition-colors`,children:v(_?ol:dl,{size:12})}),v(`button`,{onClick:t,className:`p-0.5 rounded hover:bg-danger/20 text-foreground-muted hover:text-danger transition-colors`,children:v(xu,{size:12})})]})]}),!_&&v(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:n})]}):T(`div`,{className:G(`fixed z-50 rounded-lg border border-border bg-background-elevated shadow-2xl flex flex-col overflow-hidden`,l),style:{left:d.x,top:d.y,width:_?280:m.w,height:_?`auto`:m.h},children:[T(`div`,{onMouseDown:w,className:`flex items-center justify-between gap-2 px-3 py-2 border-b border-border cursor-move select-none shrink-0 bg-surface`,children:[T(`div`,{className:`flex items-center gap-2 min-w-0`,children:[v(Vc,{size:12,className:`text-foreground-subtle shrink-0`}),v(`span`,{className:`text-[11px] font-medium truncate`,children:e})]}),T(`div`,{className:`flex items-center gap-1 shrink-0`,children:[v(`button`,{onClick:()=>y(!_),className:`p-0.5 rounded hover:bg-surface-hover text-foreground-muted transition-colors`,title:_?`Restore`:`Minimize`,children:v(_?ol:dl,{size:12})}),v(`button`,{onClick:t,className:`p-0.5 rounded hover:bg-danger/20 text-foreground-muted hover:text-danger transition-colors`,title:`Close`,children:v(xu,{size:12})})]})]}),!_&&T(`div`,{className:`flex-1 min-h-0 overflow-y-auto relative`,children:[n,v(`div`,{onMouseDown:E,className:`absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize`,style:{background:`linear-gradient(135deg, transparent 50%, var(--color-foreground-subtle) 50%)`,opacity:.4}})]})]})}function Id({open:e,onClose:t,children:n,className:r,width:i=`w-64`}){let a=p(null);return c(()=>{if(!e)return;let n=e=>{e.key===`Escape`&&t()};return document.addEventListener(`keydown`,n),document.body.style.overflow=`hidden`,()=>{document.removeEventListener(`keydown`,n),document.body.style.overflow=``}},[e,t]),T(E,{children:[v(`div`,{className:G(`fixed inset-0 z-40 bg-black/50 backdrop-blur-sm transition-opacity duration-200`,e?`opacity-100`:`pointer-events-none opacity-0`),onClick:t,"aria-hidden":`true`}),v(`div`,{ref:a,role:`dialog`,"aria-modal":`true`,className:G(`fixed inset-y-0 left-0 z-50 flex flex-col bg-surface border-r border-border shadow-2xl transition-transform duration-200 ease-out pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]`,i,e?`translate-x-0`:`-translate-x-full`,r),children:n})]})}function Ld({items:e,className:t}){return v(`nav`,{className:`hidden md:flex items-center gap-1 text-[11px] text-foreground-subtle ${t??``}`,children:e.map((t,n)=>{let r=n===e.length-1,i=!r&&(t.onClick||t.href);return T(w.Fragment,{children:[n>0&&v(Qs,{className:`h-3 w-3 flex-shrink-0`}),i?t.onClick?v(`button`,{type:`button`,onClick:t.onClick,className:`hover:text-foreground transition-colors`,children:t.label}):v(`a`,{href:t.href,className:`hover:text-foreground transition-colors`,children:t.label}):v(`span`,{className:r?`text-foreground font-medium`:``,children:t.label})]},n)})})}var Rd={left:`text-left`,right:`text-right`,center:`text-center`};function zd({columns:e,rows:t,rowKey:n,onRowClick:r,minWidthPx:i=480,emptyMessage:a,className:o,bordered:s=!0,rowClassName:c}){return t.length===0&&a?v(`div`,{className:`rounded-lg ${s?`border border-border`:``} bg-surface px-3 py-4 text-xs text-foreground-subtle text-center ${o??``}`,children:a}):t.length===0?null:v(`div`,{className:`rounded-lg ${s?`border border-border`:``} bg-surface overflow-x-auto ${o??``}`,children:T(`table`,{className:`w-full text-xs`,style:{minWidth:`${i}px`},children:[v(`thead`,{className:`bg-surface`,children:v(`tr`,{children:e.map(e=>{let t=e.align??`left`,n=e.nowrap??!0;return v(`th`,{className:[`px-3 py-2 text-foreground-subtle font-medium bg-surface border-b border-border`,Rd[t],n?`whitespace-nowrap`:``,e.width??``].filter(Boolean).join(` `),children:e.headerRender?e.headerRender():e.header},e.key)})})}),v(`tbody`,{children:t.map((t,i)=>{let a=n?n(t,i):i,o=c?.(t,i)??``,s=r!==void 0;return v(`tr`,{onClick:s?()=>r(t,i):void 0,className:[s?`cursor-pointer hover:bg-primary/5`:`hover:bg-primary/5`,o].filter(Boolean).join(` `),children:e.map(e=>{let n=e.align??`left`,r=e.nowrap??!1;return v(`td`,{className:[`px-3 py-2 text-foreground border-b border-border`,Rd[n],r?`whitespace-nowrap`:``].filter(Boolean).join(` `),children:e.render(t,i)},e.key)})},a)})})]})})}function Bd({open:e,onClose:t,title:n,subtitle:r,footer:i,children:a,widthClass:o=`w-[360px]`}){return c(()=>{if(!e)return;let n=e=>{e.key===`Escape`&&t()};return window.addEventListener(`keydown`,n),()=>window.removeEventListener(`keydown`,n)},[e,t]),e?T(`aside`,{className:G(`absolute top-0 right-0 bottom-0 z-20 flex flex-col`,`bg-surface border-l border-border shadow-xl`,o),role:`dialog`,"aria-modal":`false`,children:[T(`header`,{className:`flex items-start justify-between gap-2 px-4 py-3 border-b border-border`,children:[T(`div`,{className:`min-w-0`,children:[v(`div`,{className:`text-sm font-semibold text-foreground truncate`,children:n}),r!==void 0&&v(`div`,{className:`text-[11px] text-foreground-subtle mt-0.5 truncate`,children:r})]}),v(`button`,{type:`button`,onClick:t,className:`p-1 rounded hover:bg-muted text-foreground-subtle hover:text-foreground`,"aria-label":`Close panel`,children:v(xu,{className:`w-4 h-4`})})]}),v(`div`,{className:`flex-1 min-h-0 overflow-y-auto px-4 py-3`,children:a}),i!==void 0&&v(`footer`,{className:`flex items-center gap-2 justify-end px-4 py-3 border-t border-border`,children:i})]}):null}var Vd={inherit:`bg-muted`,on:`bg-emerald-500`,off:`bg-orange-500`,na:`bg-gray-300 opacity-50`};function Hd({node:e,depth:t,selectedAddonId:n,onSelect:r,agentDots:i}){let a=e.addonId===n,o=i?.[e.addonId]??[];return T(`div`,{children:[T(`button`,{type:`button`,onClick:()=>r(e.addonId),className:G(`w-full flex items-center justify-between gap-2 text-left px-3 py-1.5 text-xs`,`border-l-2`,a?`bg-accent border-primary text-foreground font-medium`:`border-transparent hover:bg-muted/40 text-foreground`),style:{paddingLeft:`${12+t*14}px`},children:[v(`span`,{className:`truncate`,children:e.addonName}),o.length>0&&v(`span`,{className:`flex items-center gap-1 shrink-0`,children:o.map(e=>v(`span`,{title:`${e.agentNodeId}: ${e.state}`,className:G(`w-2 h-2 rounded-full`,Vd[e.state])},e.agentNodeId))})]}),e.children.map(e=>v(Hd,{node:e,depth:t+1,selectedAddonId:n,onSelect:r,agentDots:i},e.addonId))]})}function Ud({tree:e,selectedAddonId:t,onSelect:n,agentDots:r,className:i}){return v(`div`,{className:G(`flex flex-col py-2`,i),children:e.map(e=>v(Hd,{node:e,depth:0,selectedAddonId:t,onSelect:n,agentDots:r},e.addonId))})}function Wd(e){let t=[],n=[],r=new Map;for(let i of e.slots)for(let e of i.addons){let i={addonId:e.id,addonName:e.name,slot:e.slot,inputClasses:e.inputClasses,outputClasses:e.outputClasses,children:[]};e.slot===`audio-classifier`?t.push(i):(n.push(i),r.set(e.id,i))}let i=[];for(let e of n){if(e.inputClasses.length===0){i.push(e);continue}let t=n.find(t=>t.addonId!==e.addonId&&t.outputClasses.some(t=>e.inputClasses.includes(t)));t&&t.children.push(e)}return[...i,...t]}function Gd(e){return e?e.models.map(e=>({id:e.id,name:e.name})):[]}function Kd({step:e,schema:t,allSchemas:n,depth:r=0,onChange:i,onDelete:a,readOnly:o=!1,toggleMode:s=`simple`,overrideState:c=null,onOverrideChange:l,inheritedEnabled:u,hideModelAndSettings:d=!1}){let[f,p]=h(!1),m=Gd(t);if(m.length>0&&!m.some(t=>t.id===e.modelId)&&!o){let n=(t?.defaultModelId?m.find(e=>e.id===t.defaultModelId):null)??m[0];n&&n.id!==e.modelId&&queueMicrotask(()=>i({...e,modelId:n.id}))}let g=T(E,{children:[T(`div`,{className:`flex-1 min-w-0`,children:[v(`span`,{className:`text-[10px] uppercase tracking-wider font-medium text-foreground-subtle/60 block leading-none`,children:e.slot}),v(`span`,{className:`text-sm font-semibold text-foreground truncate block leading-tight`,children:e.addonName}),T(`div`,{className:`flex items-center gap-1 mt-0.5 flex-wrap`,children:[e.inputClasses.map(e=>v(`span`,{className:`text-[9px] uppercase font-semibold tracking-wide px-1.5 py-0.5 rounded bg-blue-500/12 text-blue-400`,children:e},e)),e.inputClasses.length>0&&e.outputClasses.length>0&&v(`span`,{className:`text-foreground-subtle/40 text-[10px]`,children:`→`}),e.outputClasses.map(e=>v(`span`,{className:`text-[9px] uppercase font-semibold tracking-wide px-1.5 py-0.5 rounded bg-green-500/12 text-green-400`,children:e},e))]})]}),!o&&s===`simple`&&v(`button`,{onClick:t=>{t.stopPropagation(),i({...e,enabled:!e.enabled})},className:G(`relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors`,e.enabled?`bg-success`:`bg-foreground-subtle/30`),children:v(`span`,{className:G(`inline-block h-4 w-4 rounded-full bg-white shadow transition-transform`,e.enabled?`translate-x-6`:`translate-x-1`)})}),!o&&s===`threeState`&&l&&T(`div`,{className:`flex items-center gap-0.5 rounded-md border border-border p-0.5`,onClick:e=>e.stopPropagation(),children:[v(Zd,{label:`Inherit`,active:c===null,variant:`inherit`,subtext:u===void 0?void 0:u?`on`:`off`,onClick:()=>l(null)}),v(Zd,{label:`On`,active:c===!0,variant:`on`,onClick:()=>l(!0)}),v(Zd,{label:`Off`,active:c===!1,variant:`off`,onClick:()=>l(!1)})]})]});return v(Ru,{expanded:f,onExpandedChange:p,dimmed:!e.enabled,header:g,children:d?v(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Model and detection settings are managed per agent — open the Pipeline page for this camera's agent to edit them.`}):T(`div`,{className:`space-y-3`,children:[v(qd,{label:`Model`,value:e.modelId,disabled:o,options:m.map(e=>({value:e.id,label:e.name})),onChange:t=>i({...e,modelId:t})}),e.slot===`audio-classifier`&&e.engine&&v(qd,{label:`Runtime`,value:`${e.engine.runtime}/${e.engine.backend}`,disabled:o,options:[{value:`node/cpu`,label:`Node.js — ONNX CPU`},{value:`node/coreml`,label:`Node.js — Apple SoundAnalysis (macOS)`},{value:`python/cpu`,label:`Python — ONNX CPU`}],onChange:t=>{let[n,r]=t.split(`/`),a=r===`coreml`?`coreml`:`onnx`;i({...e,engine:{runtime:n,backend:r,format:a}})}}),t?.configSchema?.map(n=>v(Xd,{field:n,allFields:t.configSchema??[],step:e,disabled:o,onChange:i},n.key))]})})}function qd({label:e,value:t,options:n,disabled:r,onChange:i}){return T(`div`,{children:[v(`label`,{className:`block text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-1.5`,children:e}),T(`select`,{value:t,onChange:e=>i(e.target.value),disabled:r,className:`w-full rounded-lg border border-border bg-surface px-3 py-2 text-xs text-foreground focus:outline-none focus:border-primary/50`,children:[n.length===0&&v(`option`,{value:t,children:t||`default`}),n.map(e=>v(`option`,{value:e.value,disabled:e.disabled,children:e.label},e.value))]})]})}function Jd({label:e,description:t,value:n,options:r,disabled:i,onChange:a}){function o(e){i||a(n.includes(e)?n.filter(t=>t!==e):[...n,e])}return T(`div`,{children:[v(`label`,{className:`block text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-1`,children:e}),t&&v(`p`,{className:`text-[10px] text-foreground-subtle/60 mb-1.5`,children:t}),v(`div`,{className:`flex flex-wrap gap-1.5`,children:r.map(e=>v(`button`,{type:`button`,disabled:i,onClick:()=>o(e.value),className:G(`text-[10px] font-medium px-2 py-1 rounded-md border transition-colors`,n.includes(e.value)?`bg-primary/20 text-primary border-primary/40`:`bg-surface text-foreground-subtle border-border hover:border-primary/30`,i&&`opacity-50 cursor-not-allowed`),children:e.label},e.value))})]})}function Yd(e,t,n){let r=t.settings?.[e];if(r!==void 0)return r;let i=n.find(t=>`key`in t&&t.key===e);return i&&`default`in i?i.default:void 0}function Xd({field:e,allFields:t,step:n,disabled:r,onChange:i}){let a=e.type!==`separator`&&e.type!==`info`?e.showWhen:void 0;if(a){let{field:e,equals:r,notEquals:i,in:o,notIn:s}=a,c=Yd(e,n,t);if(r!==void 0&&c!==r||i!==void 0&&c===i||o!==void 0&&!o.includes(c)||s!==void 0&&s.includes(c))return null}function o(t){i({...n,settings:{...n.settings,[e.key]:t}})}if(e.type===`select`){let t=n.settings?.[e.key],i=typeof t==`string`?t:e.default??``;return v(qd,{label:e.label,value:i,disabled:r||e.disabled,options:e.options,onChange:o})}if(e.type===`multiselect`){let t=n.settings?.[e.key],i=Array.isArray(t)?t:Array.isArray(e.default)?e.default:[];return v(Jd,{label:e.label,description:e.description,value:i,options:e.options,disabled:r||e.disabled,onChange:o})}if(e.type===`slider`||e.type===`number`){let t=n.settings?.[e.key],i=typeof e.default==`number`?e.default:e.min??0,a=typeof t==`number`?t:i,s=e.min??0,c=e.max??1,l=e.step??.01,u=e.type===`slider`?e.showValue:!0,d=`unit`in e?e.unit:void 0,f=e.type===`slider`?e.displayScale:void 0,p=f?a/f:a;return T(`div`,{children:[T(`div`,{className:`flex items-center justify-between mb-1`,children:[v(`span`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide`,children:e.label}),u&&T(`span`,{className:`text-xs font-medium text-foreground tabular-nums`,children:[typeof p==`number`?p.toFixed(2).replace(/\.?0+$/,``):p,d?` ${d}`:``]})]}),e.description&&v(`p`,{className:`text-[10px] text-foreground-subtle/60 mb-1.5`,children:e.description}),v(`input`,{type:`range`,min:s,max:c,step:l,value:a,disabled:r||e.disabled,onChange:e=>o(Number(e.target.value)),className:`w-full accent-primary h-1.5`})]})}if(e.type===`boolean`){let t=n.settings?.[e.key];return T(`label`,{className:`flex items-center gap-2`,children:[v(`input`,{type:`checkbox`,checked:typeof t==`boolean`?t:e.default===!0,disabled:r||e.disabled,onChange:e=>o(e.target.checked),className:`h-3.5 w-3.5 accent-primary`}),v(`span`,{className:`text-[10px] font-medium text-foreground-subtle uppercase tracking-wide`,children:e.label})]})}if(e.type===`text`||e.type===`password`||e.type===`textarea`){let t=n.settings?.[e.key],i=typeof t==`string`?t:e.default??``,a=e.type===`password`?`password`:`text`;return T(`div`,{children:[v(`label`,{className:`block text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-1.5`,children:e.label}),e.type===`textarea`?v(`textarea`,{value:i,disabled:r||e.disabled,placeholder:e.placeholder,onChange:e=>o(e.target.value),rows:3,className:`w-full rounded-lg border border-border bg-surface px-3 py-2 text-xs text-foreground focus:outline-none focus:border-primary/50 resize-y`}):v(`input`,{type:a,value:i,disabled:r||e.disabled,placeholder:e.placeholder,onChange:e=>o(e.target.value),className:`w-full rounded-lg border border-border bg-surface px-3 py-2 text-xs text-foreground focus:outline-none focus:border-primary/50`})]})}return e.type===`separator`?v(`div`,{className:`border-t border-border my-2`}):e.type===`info`?v(`div`,{className:`rounded-md border border-border bg-surface px-2 py-1.5 text-[10px] text-foreground-subtle`,children:e.content}):null}function Zd({label:e,active:t,variant:n,subtext:r,onClick:i}){return T(`button`,{type:`button`,onClick:i,className:G(`px-2 py-1 text-[10px] font-medium rounded transition-colors`,t?n===`on`?`bg-green-500/20 text-green-400`:n===`off`?`bg-red-500/20 text-red-400`:`bg-primary/20 text-primary`:`text-foreground-subtle hover:bg-surface-hover`),children:[e,r&&t&&T(`span`,{className:`ml-1 opacity-60`,children:[`(`,r,`)`]})]})}function Qd(e,t){return{addonId:e.id,addonName:e.name,slot:e.slot,inputClasses:[...e.inputClasses],outputClasses:[...e.outputClasses],enabled:t.enabled,modelId:t.modelId,children:[],settings:{...t.settings}}}function $d(e,t,n){return e!==`device`||!n?t:{enabled:n.enabled??t.enabled,modelId:n.modelId??t.modelId,settings:n.settings??t.settings}}function ef({addon:e,agentDefault:t,modelsForFormat:n,onChangeAgentConfig:r}){let i=e=>{r?.({...t,...e})};return T(`div`,{className:`space-y-4 text-xs`,children:[T(`label`,{className:`flex items-center gap-2`,children:[v(`input`,{type:`checkbox`,checked:t.enabled,onChange:e=>i({enabled:e.target.checked})}),T(`span`,{children:[`Enabled on this agent (`,e.name,`)`]})]}),T(`div`,{children:[v(`div`,{className:`text-[10px] uppercase tracking-widest text-foreground-subtle mb-1`,children:`Model`}),v(`select`,{className:`w-full bg-surface border border-border rounded px-2 py-1 text-xs`,value:t.modelId,onChange:e=>i({modelId:e.target.value}),children:n.map(e=>v(`option`,{value:e.id,children:e.name},e.id))})]}),(e.configSchema?.length??0)>0&&T(`div`,{className:`pt-2 border-t border-border/50 space-y-3`,children:[v(`div`,{className:`text-[10px] uppercase tracking-widest text-foreground-subtle`,children:`Settings`}),e.configSchema?.map(n=>v(Xd,{field:n,allFields:e.configSchema??[],step:Qd(e,t),disabled:!1,onChange:e=>i({settings:{...e.settings}})},n.key))]})]})}function tf({addon:e,agentDefault:t,agentNodeId:n,currentPatch:r,modelsForFormat:i,onChangePatch:a}){let o=$d(`device`,t,r),s=e=>{let t=e.enabled!==void 0||e.modelId!==void 0||e.settings!==void 0;a?.(t?e:null)},c=e=>{let{enabled:t,...n}=r??{};s(e===`inherit`?n:{...n,enabled:e===`on`})},l=e=>{let{modelId:t,...n}=r??{};s(e===void 0?n:{...n,modelId:e})},u=e=>{let{settings:t,...n}=r??{};s(e===void 0?n:{...n,settings:e})},d=r?.enabled===void 0?`inherit`:r.enabled?`on`:`off`,f=r?.modelId!==void 0;return T(`div`,{className:`space-y-4 text-xs`,children:[T(`div`,{className:`flex items-center gap-1`,children:[[`inherit`,`on`,`off`].map(e=>v(`button`,{type:`button`,onClick:()=>c(e),className:G(`px-3 py-1 border border-border rounded text-xs capitalize`,d===e?`bg-primary text-primary-foreground border-primary`:`bg-surface text-foreground hover:bg-muted`),children:e},e)),T(`span`,{className:`ml-2 text-[10px] text-foreground-subtle`,children:[`agent default:`,` `,v(`span`,{className:`font-semibold`,children:t.enabled?`on`:`off`})]})]}),T(`div`,{children:[T(`div`,{className:`flex items-center justify-between mb-1`,children:[v(`div`,{className:`text-[10px] uppercase tracking-widest text-foreground-subtle`,children:`Model`}),f?v(`button`,{type:`button`,className:`text-[10px] text-foreground-subtle hover:text-foreground`,onClick:()=>l(void 0),children:`Clear`}):v(`button`,{type:`button`,className:`text-[10px] text-primary hover:underline`,onClick:()=>l(t.modelId),children:`Override`})]}),v(`select`,{disabled:!f,className:`w-full bg-surface border border-border rounded px-2 py-1 text-xs disabled:opacity-50`,value:f?r?.modelId??t.modelId:t.modelId,onChange:e=>l(e.target.value),children:i.map(e=>v(`option`,{value:e.id,children:e.name},e.id))}),!f&&T(`div`,{className:`text-[10px] text-foreground-subtle mt-1`,children:[`inherits from `,n]})]}),(e.configSchema?.length??0)>0&&(()=>{let i=r?.settings!==void 0;return T(`div`,{className:`pt-2 border-t border-border/50 space-y-3`,children:[T(`div`,{className:`flex items-center justify-between`,children:[v(`div`,{className:`text-[10px] uppercase tracking-widest text-foreground-subtle`,children:`Settings`}),i?v(`button`,{type:`button`,className:`text-[10px] text-foreground-subtle hover:text-foreground`,onClick:()=>u(void 0),children:`Clear`}):v(`button`,{type:`button`,className:`text-[10px] text-primary hover:underline`,onClick:()=>u({...t.settings}),children:`Override`})]}),e.configSchema?.map(t=>v(Xd,{field:t,allFields:e.configSchema??[],step:Qd(e,o),disabled:!i,onChange:e=>u({...e.settings})},t.key)),!i&&T(`div`,{className:`text-[10px] text-foreground-subtle`,children:[`inherits from `,n]})]})})(),T(`div`,{className:`rounded bg-muted/40 px-3 py-2 text-[11px] text-foreground-subtle`,children:[v(`div`,{className:`font-semibold text-foreground mb-0.5`,children:`Effective config preview`}),T(`div`,{className:`font-mono truncate`,children:[e.id,` · model: `,o.modelId,` · `,o.enabled?`on`:`off`]})]})]})}function nf(e){let{mode:t,addon:n,agentDefault:r,agentNodeId:i,currentPatch:a,onChangeAgentConfig:s,onChangePatch:c,engineFormat:l}=e,u=o(()=>n.models.filter(e=>!!e.formats[l]),[n.models,l]);return t===`agent`?v(ef,{addon:n,agentDefault:r,modelsForFormat:u,onChangeAgentConfig:s}):v(tf,{addon:n,agentDefault:r,agentNodeId:i,currentPatch:a,modelsForFormat:u,onChangePatch:c})}function rf(e){let t=[],n=(e,r)=>{for(let i of e)t.push({node:i,depth:r}),n(i.children,r+1)};return n(e,0),t}var af={detector:{label:`detector`,className:`text-emerald-500`},cropper:{label:`cropper`,className:`text-blue-500`},classifier:{label:`classifier`,className:`text-violet-500`},refiner:{label:`refiner`,className:`text-amber-500`},"audio-classifier":{label:`audio classifier`,className:`text-pink-500`}};function of({slot:e}){let t=af[e]??af.classifier;return v(`span`,{className:G(`text-[9px] font-semibold uppercase tracking-widest leading-none`,t.className),children:t.label})}var sf=`inline-flex items-center rounded bg-muted px-1.5 py-px text-[9px] font-medium text-foreground-subtle`;function cf({inputs:e,outputs:t}){return e.length===0&&t.length===0?null:T(`span`,{className:`inline-flex items-center gap-1 flex-wrap`,children:[e.map(e=>v(`span`,{className:G(sf,`bg-blue-500/10 text-blue-500`),children:e},`in-${e}`)),e.length>0&&t.length>0&&v(`span`,{className:`text-foreground-subtle/60 text-[9px]`,children:`→`}),t.map(e=>v(`span`,{className:G(sf,`bg-emerald-500/10 text-emerald-500`),children:e},`out-${e}`))]})}function lf({enabled:e,onChange:t,disabled:n}){return v(`button`,{type:`button`,role:`switch`,"aria-checked":e,disabled:n,onClick:n=>{n.stopPropagation(),t(!e)},className:G(`relative inline-flex h-3.5 w-7 shrink-0 items-center rounded-full transition-colors`,e?`bg-emerald-500`:`bg-foreground-subtle/30`,n?`opacity-50 cursor-not-allowed`:`cursor-pointer`),title:e?`Click to disable`:`Click to enable`,children:v(`span`,{className:G(`inline-block h-3 w-3 rounded-full bg-white shadow transition-transform`,e?`translate-x-3.5`:`translate-x-0.5`)})})}function uf(e){return e.kind===`enabled`?T(`span`,{className:`inline-flex items-center gap-1`,children:[v(`span`,{className:`h-1.5 w-1.5 rounded-full bg-emerald-500 shrink-0`}),v(`span`,{className:`font-mono text-foreground`,children:e.modelId})]}):e.kind===`disabled`?T(`span`,{className:`inline-flex items-center gap-1 text-foreground-subtle`,children:[v(`span`,{className:`h-1.5 w-1.5 rounded-full border border-foreground-subtle/60 shrink-0`}),`off`]}):T(`span`,{className:`inline-flex items-center gap-1 text-foreground-subtle/70`,children:[v(`span`,{className:`h-1.5 w-1.5 rounded-full bg-muted shrink-0`}),`n/a`]})}function df({node:e,depth:t,agents:n,getCellState:r,onCellClick:i,selectedCell:a,toggleProps:o}){return T(E,{children:[T(`div`,{className:`sticky left-0 z-10 bg-surface px-3 py-2 border-b border-border text-xs flex items-start gap-2`,style:{paddingLeft:`${12+t*14}px`},children:[T(`div`,{className:`flex flex-col gap-1 min-w-0 flex-1`,children:[v(of,{slot:e.slot}),T(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[v(`span`,{className:`font-semibold truncate`,children:e.addonName}),v(cf,{inputs:e.inputClasses,outputs:e.outputClasses})]})]}),o&&v(`span`,{className:`pl-2 pt-0.5 shrink-0`,children:v(lf,{enabled:o.enabled,onChange:o.onChange,disabled:o.disabled})})]}),n.map(t=>{let n=r(e.addonId,t.agentNodeId),o=a?.addonId===e.addonId&&a.agentNodeId===t.agentNodeId;return v(`button`,{type:`button`,onClick:()=>i(e.addonId,t.agentNodeId),className:G(`text-left px-3 py-1.5 border-b border-l border-border text-xs hover:bg-muted/40`,n.kind===`enabled`&&`bg-emerald-500/5`,n.kind===`na`&&`bg-muted/30`,o&&`ring-2 ring-primary ring-inset`),children:uf(n)},t.agentNodeId)})]})}function ff({tree:e,agents:t,getCellState:n,onCellClick:r,selectedCell:i,onToggleEnabled:a}){let s=o(()=>rf(e),[e]),c=`minmax(320px, 1fr) repeat(${t.length}, minmax(160px, 220px))`,l=a!==void 0&&t.length===1,u=t[0]?.agentNodeId;return v(`div`,{className:`overflow-auto border border-border rounded`,children:T(`div`,{className:`grid`,style:{gridTemplateColumns:c},children:[v(`div`,{className:`sticky top-0 left-0 z-20 bg-muted/60 px-3 py-2 text-[10px] uppercase tracking-widest text-foreground-subtle border-b border-border`,children:`Step`}),t.map(e=>T(`div`,{className:`sticky top-0 z-10 bg-muted/60 px-3 py-2 border-b border-l border-border`,children:[v(`div`,{className:`text-xs font-semibold text-foreground`,children:e.agentNodeId}),v(`div`,{className:`text-[10px] text-foreground-subtle truncate`,children:e.engineLabel})]},e.agentNodeId)),s.map(({node:e,depth:o})=>{let s=l&&u!==void 0?n(e.addonId,u):null;return v(df,{node:e,depth:o,agents:t,getCellState:n,onCellClick:r,selectedCell:i,toggleProps:l&&s!==null?{enabled:s.kind===`enabled`,onChange:t=>a?.(e.addonId,t),disabled:s.kind===`na`}:void 0},e.addonId)})]})})}var pf=typeof globalThis<`u`?globalThis.__camstackTrpcReact:void 0,q=pf??ne();typeof globalThis<`u`&&!pf&&(globalThis.__camstackTrpcReact=q);var mf=hr(`camstack:system`,null);function hf({system:e,children:t}){return v(mf.Provider,{value:e,children:t})}function gf(){let e=i(mf);if(!e)throw Error(`useSystem(): no <SystemProvider> in tree`);return e}function _f(){return i(mf)}function vf(e,t){let n=gf(),r=p(t);r.current=t;let[i,a]=h(n.connectionVersion);c(()=>n.subscribeConnectionEvents((e,t)=>{e===`connected`&&a(t)}),[n]),c(()=>n.subscribeEvent(e,e=>{r.current(e)}),[n,e,i])}function yf(e){let t=p(e);return t.current=e,t}function bf(e,t){let[n,r]=h(null),i=yf(t);return vf(e,e=>{let t=e.data,n=i.current;n&&!n(t)||r(t)}),n}function xf(e,t,n){let[r,i]=h(()=>new Map),a=yf(t),s=yf(n);return vf(e,e=>{let t=e.data,n=s.current;if(n&&!n(t))return;let r=a.current(t);i(e=>{let n=new Map(e);return n.set(r,t),n})}),{map:r,values:o(()=>Array.from(r.values()),[r])}}function Sf(){let{data:e,isLoading:t}=q.nodes.topology.useQuery(void 0,{staleTime:6e4}),n=bf(`cluster.topology-snapshot`)?.nodes??e;return{nodes:o(()=>{let e=[];for(let t of n??[])e.push({id:String(t.id??``),name:String(t.name??t.id??``),shortName:t.isHub?`HUB`:String(t.name??t.id??``),isHub:!!t.isHub,isOnline:!!t.isOnline,localIps:t.localIps??[],addons:(t.addons??[]).map(e=>({addonId:e.id,capabilities:e.capabilities}))});return e.sort((e,t)=>e.isHub===t.isHub?e.name.localeCompare(t.name):e.isHub?-1:1),e},[n]),isLoading:t}}function Cf({selectedNodeId:e,onSelect:t,label:n=`Node`,hideIcon:r=!1,alwaysShow:i=!1}){let{nodes:a}=Sf();return!i&&a.length<=1?null:T(`div`,{className:`flex items-center gap-1.5`,children:[!r&&v(Rl,{className:`h-3.5 w-3.5 text-foreground-subtle`}),n&&v(`span`,{className:`text-[10px] uppercase tracking-wider text-foreground-subtle`,children:n}),v(`div`,{className:`flex rounded-md border border-border overflow-hidden text-[11px] font-medium`,children:a.map((n,r)=>{let i=e===n.id;return v(`button`,{type:`button`,onClick:()=>t(n.id),disabled:!n.isOnline,title:n.isOnline?n.name:`${n.name} (offline)`,className:G(`px-2.5 py-1 transition-colors`,i?`bg-primary/15 text-primary`:`bg-transparent text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,r>0&&`border-l border-border`,!n.isOnline&&`opacity-50 cursor-not-allowed`),children:n.shortName},n.id)})})]})}var wf={online:{colorClass:`bg-success`,label:`Online`},offline:{colorClass:`bg-danger`,label:`Offline`},degraded:{colorClass:`bg-warning`,label:`Degraded`},unknown:{colorClass:`bg-foreground-subtle`,label:`Unknown`}};function Tf({status:e,showDot:t=!0,showLabel:n=!0,size:r=`sm`,className:i}){let a=wf[e];return T(`span`,{className:G(`inline-flex items-center gap-1.5`,r===`sm`?`text-xs`:`text-sm`,i),children:[t&&v(`span`,{className:G(`h-1.5 w-1.5 shrink-0 rounded-full`,a.colorClass),"aria-hidden":`true`}),n&&v(`span`,{className:`text-foreground`,children:a.label})]})}var Ef={frigate:{colorClass:`bg-provider-frigate`,label:`Frigate`},scrypted:{colorClass:`bg-provider-scrypted`,label:`Scrypted`},reolink:{colorClass:`bg-provider-reolink`,label:`Reolink`},homeAssistant:{colorClass:`bg-provider-homeAssistant`,label:`Home Assistant`},rtsp:{colorClass:`bg-provider-rtsp`,label:`RTSP`}};function Df({provider:e,showLabel:t=!0,className:n}){let r=Ef[e];return T(`span`,{className:G(`inline-flex items-center gap-1.5 text-xs`,n),children:[v(`span`,{className:G(`h-1.5 w-1.5 shrink-0 rounded-sm`,r.colorClass),"aria-hidden":`true`}),t&&v(`span`,{className:`text-foreground`,children:r.label})]})}var Of={success:`bg-emerald-400 text-emerald-950`,warning:`bg-amber-400 text-amber-950`,danger:`bg-red-400 text-red-950`,info:`bg-blue-400 text-blue-950`,neutral:`bg-foreground-subtle/20 text-foreground`};function kf({children:e,variant:t=`neutral`,mono:n,className:r}){return v(`span`,{className:G(`inline-flex items-center rounded-md px-2 py-0.5 text-[11px] font-bold leading-tight`,n&&`font-mono`,Of[t],r),children:e})}function Af({version:e,preRelease:t,className:n}){return v(kf,{variant:t??/-(alpha|beta|rc|dev|canary|next)/i.test(e)?`warning`:`success`,mono:!0,className:n,children:e})}function jf({label:e,description:t,error:n,required:r,children:i,orientation:a=`vertical`,className:o}){let s=a===`horizontal`;return T(`div`,{className:G(`flex gap-2`,s?`flex-row items-center justify-between`:`flex-col`,o),children:[T(`div`,{className:G(s?`flex-1`:``),children:[T(zu,{children:[e,r&&v(`span`,{className:`text-danger ml-0.5`,children:`*`})]}),t&&v(`p`,{className:`text-foreground-subtle text-xs mt-0.5`,children:t})]}),v(`div`,{className:G(s?`shrink-0`:``),children:i}),n&&v(`p`,{className:`text-danger text-xs`,children:n})]})}function Mf({title:e,subtitle:t,actions:n,className:r}){return T(`div`,{className:G(`flex flex-col gap-2 mb-3 sm:flex-row sm:items-center sm:justify-between`,r),children:[T(`div`,{children:[v(`h1`,{className:`text-sm font-semibold text-foreground`,children:e}),t&&v(`p`,{className:`text-foreground-subtle text-xs`,children:t})]}),n&&v(`div`,{className:`flex items-center gap-2 flex-wrap`,children:n})]})}function Nf({icon:e,title:t,description:n,action:r,className:i}){return T(`div`,{className:G(`flex flex-col items-center justify-center gap-3 py-12`,i),children:[e&&v(e,{className:`h-12 w-12 text-foreground-subtle`,"aria-hidden":`true`}),T(`div`,{className:`flex flex-col items-center gap-1 text-center`,children:[v(`p`,{className:`text-foreground-muted text-sm font-medium`,children:t}),n&&v(`p`,{className:`text-foreground-subtle text-xs max-w-xs`,children:n})]}),r&&v(`div`,{className:`mt-1`,children:r})]})}var Pf={danger:{box:`border-danger/40 bg-danger/10`,icon:`text-danger`,title:`text-danger`,message:`text-danger`},warning:{box:`border-amber-500/40 bg-amber-500/10`,icon:`text-amber-600 dark:text-amber-400`,title:`text-amber-700 dark:text-amber-300`,message:`text-amber-700 dark:text-amber-300`}};function Ff({message:e,title:t,onRetry:n,action:r,variant:i=`danger`,className:a}){let o=Pf[i],s=i===`warning`?cu:nc;return T(`div`,{role:`alert`,className:G(`flex items-start gap-2.5 rounded border px-3 py-2.5`,o.box,a),children:[v(s,{className:G(`h-4 w-4 mt-0.5 shrink-0`,o.icon),"aria-hidden":`true`}),T(`div`,{className:`flex-1 min-w-0`,children:[t&&v(`p`,{className:G(`text-xs font-semibold`,o.title),children:t}),v(`div`,{className:G(`text-xs break-words`,o.message,t?`mt-0.5`:``),children:e})]}),r??(n&&T(`button`,{type:`button`,onClick:n,className:G(`shrink-0 inline-flex items-center gap-1 rounded px-2 py-1 text-[11px] font-medium`,`border border-current/30 hover:bg-current/10 transition-colors`,o.message),children:[v(jl,{className:`h-3 w-3`,"aria-hidden":`true`}),`Retry`]}))]})}var If=hr(`camstack:confirm-dialog`,null);function Lf(){let e=i(If);if(!e)throw Error(`useConfirm must be used within ConfirmDialogProvider`);return e.confirm}function Rf({children:e}){let[t,n]=h(null),r=u(e=>new Promise(t=>{n({...e,resolve:t})}),[]),i=()=>{t?.resolve(!0),n(null)},a=()=>{t?.resolve(!1),n(null)},o={danger:{icon:`text-red-400`,button:`bg-red-500 hover:bg-red-600 text-white`},warning:{icon:`text-orange-400`,button:`bg-orange-500 hover:bg-orange-600 text-white`},default:{icon:`text-primary`,button:`bg-primary hover:bg-primary/90 text-white`}},s=t?o[t.variant??`default`]:o.default;return T(If.Provider,{value:{confirm:r},children:[e,t&&T(`div`,{className:`fixed inset-0 z-50 flex items-center justify-center`,children:[v(`div`,{className:`absolute inset-0 bg-black/50 backdrop-blur-sm`,onClick:a}),T(`div`,{className:`relative z-10 w-full max-w-sm mx-4 rounded-xl border border-border bg-surface shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-150`,onClick:e=>e.stopPropagation(),children:[T(`div`,{className:`px-5 pt-5 pb-4`,children:[v(`h3`,{className:`text-sm font-semibold text-foreground`,children:t.title}),v(`p`,{className:`mt-2 text-xs text-foreground-subtle leading-relaxed`,children:t.message})]}),T(`div`,{className:`flex justify-end gap-2 px-5 py-3 border-t border-border bg-surface-hover/30`,children:[v(`button`,{type:`button`,onClick:a,className:`px-3 py-1.5 text-xs font-medium rounded-md border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:t.cancelLabel??`Cancel`}),v(`button`,{type:`button`,onClick:i,className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${s.button}`,children:t.confirmLabel??`Confirm`})]})]})]})]})}function zf({value:e,label:t,trend:n,className:r}){return T(Lu,{className:G(`flex flex-col gap-1`,r),children:[T(`div`,{className:`flex items-baseline gap-2`,children:[v(`span`,{className:`text-2xl font-semibold text-foreground`,children:e}),n&&T(`span`,{className:G(`inline-flex items-center gap-0.5 text-xs font-medium`,n.direction===`up`?`text-success`:`text-danger`),children:[n.direction===`up`?v(ou,{className:`h-3 w-3`}):v(su,{className:`h-3 w-3`}),n.value,`%`]})]}),v(`span`,{className:`text-xs text-foreground-muted`,children:t})]})}function Bf({items:e,className:t}){return v(`dl`,{className:G(`flex flex-col`,t),children:e.map(e=>T(`div`,{className:`flex items-center h-7`,children:[v(`dt`,{className:`text-foreground-subtle text-xs w-1/3 shrink-0`,children:e.key}),v(`dd`,{className:`text-foreground text-xs`,children:e.value})]},e.key))})}function Vf({children:e,maxHeight:t=300,className:n}){let[r,i]=h(!1),a=u(()=>{navigator.clipboard.writeText(e).then(()=>{i(!0),setTimeout(()=>i(!1),2e3)})},[e]);return T(`div`,{className:G(`relative group`,n),children:[v(Pd,{style:{maxHeight:t},children:v(`pre`,{className:`font-mono text-xs bg-surface p-3 rounded-md border border-border-subtle`,children:v(`code`,{children:e})})}),v(`div`,{className:`absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity`,children:v(Nu,{icon:r?Ys:vc,"aria-label":`Copy code`,variant:`ghost`,size:`sm`,onClick:a})})]})}function Hf({filters:e,values:t,onChange:n,className:r}){let i=bd(),[a,o]=h(!1),s=(e,r)=>{n({...t,[e]:r})},c=Object.values(t).filter(e=>e!==void 0&&e!==``).length;if(i){let n=e.find(e=>e.type===`search`),i=e.some(e=>e.type!==`search`);return T(`div`,{className:G(`flex items-center gap-2`,r),children:[n&&v(Wu,{placeholder:n.placeholder??`Search...`,value:t[n.key]??``,onChange:e=>s(n.key,e.target.value),leftSlot:v(Ll,{className:`h-3 w-3 text-foreground-subtle`}),className:`flex-1`}),i&&T(E,{children:[T(`button`,{onClick:()=>o(!0),className:`flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-xs text-foreground-muted hover:bg-surface-hover transition-colors shrink-0`,children:[v(Yl,{className:`h-3.5 w-3.5`}),`Filters`,c>0&&v(Fu,{variant:`info`,className:`ml-1 text-[10px] px-1 py-0`,children:c})]}),v(Sd,{open:a,onClose:()=>o(!1),title:`Filters`,children:v(`div`,{className:`flex flex-col gap-3`,children:e.filter(e=>e.type!==`search`).map(e=>{switch(e.type){case`select`:return T(`div`,{children:[v(`label`,{className:`text-xs text-foreground-muted mb-1 block`,children:e.label}),v(Gu,{options:e.options,value:t[e.key]??``,onChange:t=>s(e.key,t.target.value),className:`w-full`})]},e.key);case`badge-toggle`:return v(`div`,{className:`flex items-center gap-1 flex-wrap`,children:e.options.map(n=>{let r=t[e.key]===n.value;return v(`button`,{type:`button`,onClick:()=>s(e.key,r?void 0:n.value),children:v(Fu,{variant:r?`info`:`default`,className:`cursor-pointer`,children:n.label})},n.value)})},e.key);default:return null}})})})]})]})}return v(`div`,{className:G(`flex items-center gap-2 flex-wrap`,r),children:e.map(e=>{switch(e.type){case`search`:return v(Wu,{placeholder:e.placeholder??`Search...`,value:t[e.key]??``,onChange:t=>s(e.key,t.target.value),leftSlot:v(Ll,{className:`h-3 w-3 text-foreground-subtle`}),className:`w-48`},e.key);case`select`:return v(Gu,{options:e.options,value:t[e.key]??``,onChange:t=>s(e.key,t.target.value),className:`w-36`},e.key);case`badge-toggle`:return v(`div`,{className:`flex items-center gap-1`,children:e.options.map(n=>{let r=t[e.key]===n.value;return v(`button`,{type:`button`,onClick:()=>s(e.key,r?void 0:n.value),children:v(Fu,{variant:r?`info`:`default`,className:`cursor-pointer`,children:n.label})},n.value)})},e.key);default:return null}})})}function Uf({label:e,icon:t,href:n,badge:r,active:i=!1,className:a}){return T(`a`,{href:n,className:G(`flex items-center gap-2 h-7 px-2 text-[11px] transition-colors`,i?`border-l-2 border-primary bg-primary/[0.08] text-foreground rounded-r-md`:`text-foreground-subtle hover:bg-surface-hover rounded-md`,a),children:[v(t,{className:`h-3.5 w-3.5 shrink-0`}),v(`span`,{className:`truncate flex-1`,children:e}),r!==void 0&&v(Fu,{className:`ml-auto text-[10px] px-1.5 py-0`,children:r})]})}function Wf({logo:e,sections:t,footer:n,onNavigate:r,className:i}){return T(`nav`,{className:G(`bg-surface border-r border-border h-full flex flex-col`,i),children:[e&&v(`div`,{className:`px-3 py-2 shrink-0`,children:e}),v(`div`,{className:`flex-1 overflow-auto px-1 py-1`,children:t.map((e,t)=>T(`div`,{className:G(t>0?`mt-3`:``),children:[e.label&&v(`span`,{className:`text-[10px] text-foreground-disabled uppercase tracking-wider px-2 mb-1 block`,children:e.label}),v(`div`,{className:`flex flex-col gap-0.5`,onClick:r,children:e.items.map(e=>v(Uf,{...e},e.href))})]},t))}),n&&n.length>0&&T(`div`,{className:`shrink-0 px-1 pb-1`,children:[v(Vu,{className:`mb-1`}),v(`div`,{className:`flex flex-col gap-0.5`,onClick:r,children:n.map(e=>v(Uf,{...e},e.href))})]})]})}function Gf({sidebar:e,header:t,mobileLogo:n,mobileActions:r,children:i,className:a}){let o=bd(),[s,c]=h(!1);return T(`div`,{className:G(`flex h-screen`,a),children:[!o&&v(Wf,{...e,className:G(`w-44`,e.className)}),o&&v(Id,{open:s,onClose:()=>c(!1),width:`w-64`,children:v(Wf,{...e,onNavigate:()=>c(!1),className:`w-full border-r-0`})}),T(`div`,{className:`flex flex-1 flex-col min-w-0`,children:[o&&T(`header`,{className:`flex items-center h-12 border-b border-border px-3 shrink-0 bg-surface/80 backdrop-blur-sm`,children:[v(`button`,{onClick:()=>c(!0),className:`p-1.5 -ml-1.5 rounded-md hover:bg-surface-hover text-foreground-muted transition-colors`,"aria-label":`Open menu`,children:v(cl,{className:`h-5 w-5`})}),n&&v(`div`,{className:`flex-1 flex justify-center`,children:n}),r&&v(`div`,{className:`shrink-0`,children:r})]}),!o&&t&&T(`header`,{className:`flex items-center h-10 border-b border-border px-4 shrink-0`,children:[t.breadcrumbs&&t.breadcrumbs.length>0&&v(`nav`,{className:`flex items-center gap-1 text-xs flex-1 min-w-0`,children:t.breadcrumbs.map((e,n)=>{let r=n===t.breadcrumbs.length-1;return T(`span`,{className:`flex items-center gap-1`,children:[n>0&&v(Qs,{className:`h-3 w-3 text-foreground-subtle shrink-0`}),e.href&&!r?v(`a`,{href:e.href,className:`text-foreground-subtle hover:text-foreground transition-colors truncate`,children:e.label}):v(`span`,{className:`text-foreground truncate`,children:e.label})]},n)})}),t.actions&&v(`div`,{className:`flex items-center gap-2 ml-auto shrink-0`,children:t.actions})]}),v(`main`,{className:`flex-1 overflow-auto p-4`,children:i})]})]})}var Kf={online:`bg-success`,offline:`bg-danger`,warning:`bg-warning`,unknown:`bg-foreground-subtle`};function qf({title:e,subtitle:t,status:n,selected:r,onClick:i,badges:a,actions:o,offlineAction:s,className:c}){let l=n===`offline`;return T(`div`,{onClick:i,className:G(`w-full rounded-lg border p-3 text-left transition-colors`,i&&`cursor-pointer`,r?`border-primary bg-primary/10`:`border-border bg-surface hover:bg-surface-hover`,l&&!r&&`opacity-50`,c),children:[T(`div`,{className:`flex items-center justify-between mb-2`,children:[v(`span`,{className:`text-sm font-medium truncate`,children:e}),n&&v(`span`,{className:G(`h-2 w-2 rounded-full shrink-0`,Kf[n])})]}),t&&v(`div`,{className:`text-[11px] text-foreground-muted`,children:t}),a&&a.length>0&&v(`div`,{className:`flex flex-wrap gap-1 mt-2`,children:a.map((e,t)=>{let n=G(`rounded px-1.5 py-0.5 text-[10px] flex items-center gap-0.5`,r?`bg-primary/20`:`bg-surface-hover`,e.onClick&&`hover:opacity-80 transition-opacity cursor-pointer`);return e.onClick?T(`button`,{onClick:t=>{t.stopPropagation(),e.onClick()},className:n,children:[e.icon,e.label]},t):T(`span`,{className:n,children:[e.icon,e.label]},t)})}),!l&&o&&o.length>0&&v(`div`,{className:`flex items-center gap-0.5 mt-2 -mb-1`,children:o.map((e,t)=>v(`button`,{onClick:t=>{t.stopPropagation(),e.onClick()},className:`p-1 rounded hover:bg-surface-hover text-foreground-subtle hover:text-foreground transition-colors`,title:e.label,"aria-label":e.label,children:e.icon},t))}),l&&s&&v(`div`,{className:`mt-2`,onClick:e=>e.stopPropagation(),children:s})]})}function Jf({children:e,minCardWidth:t=220,gap:n=3,className:r}){return v(`div`,{className:G(`p-4 overflow-y-auto flex-1 content-start`,r),style:{display:`grid`,gridTemplateColumns:`repeat(auto-fill, minmax(${t}px, 1fr))`,gap:`${n*4}px`},children:e})}var Yf=`capability.binding-changed`;function Xf(e,t){let[n,r]=h(null);return c(()=>{if(t===null){r(null);return}let n=!1,i=async()=>{try{let i=await e.deviceManager.getBindings.query({deviceId:t});n||r(i)}catch{n||r(e=>e)}};i();let a=e.live?.onEvent.subscribe({category:Yf},{onData:e=>{let n=e.data?.source;if(!n){i();return}n.type===`device`&&n.id===t&&i()}});return()=>{n=!0,a?.unsubscribe()}},[e,t]),o(()=>n?we(e,n):null,[e,n])}function Zf(e){let t=u(t=>e?e.subscribe(()=>t()):()=>void 0,[e]),n=u(()=>e?.value,[e]);return a(t,n,n)}function Qf(e,t,n){let r=Xf(e,t);return Zf(r?n(r.state):void 0)}function $f(e){let t=Xf(e.trpc,e.deviceId),n=Zf(t===null?void 0:e.slice(t)),r=t===null?void 0:e.cap(t),i=Zf(t===null?void 0:t.state.deviceStatus),a=i?.online??!0,o=a?null:i?.lastChangedAt??null;return{dev:t,cap:r,slice:n,available:(e.requireFeature===void 0||(e.deviceFeatures??[]).includes(e.requireFeature))&&r!==void 0&&n!==void 0&&a,online:a,offlineSince:o}}var ep={[V.Camera]:{icon:qs,label:`Camera`},[V.Hub]:{icon:yl,label:`Hub`},[V.Light]:{icon:Zc,label:`Light`},[V.Siren]:{icon:Kl,label:`Siren`},[V.Switch]:{icon:ru,label:`Switch`},[V.Sensor]:{icon:Ds,label:`Sensor`},[V.Thermostat]:{icon:nu,label:`Thermostat`},[V.Button]:{icon:ac,label:`Button`},[V.EventEmitter]:{icon:Su,label:`Event Emitter`},[V.Update]:{icon:jl,label:`Update`},[V.Generic]:{icon:Gs,label:`Generic`},[V.Notifier]:{icon:Hs,label:`Notifier`},[V.Script]:{icon:Il,label:`Script`},[V.Automation]:{icon:yu,label:`Automation`},[V.Lock]:{icon:rl,label:`Lock`},[V.Cover]:{icon:Us,label:`Cover`},[V.Valve]:{icon:Sl,label:`Valve`},[V.Humidifier]:{icon:hu,label:`Humidifier`},[V.WaterHeater]:{icon:Fs,label:`Water heater`},[V.Fan]:{icon:jc,label:`Fan`},[V.MediaPlayer]:{icon:pl,label:`Media player`},[V.AlarmPanel]:{icon:Vl,label:`Alarm panel`},[V.Control]:{icon:Yl,label:`Control`},[V.Presence]:{icon:al,label:`Presence`},[V.Weather]:{icon:hc,label:`Weather`},[V.Vacuum]:{icon:Ws,label:`Vacuum`},[V.LawnMower]:{icon:iu,label:`Lawn mower`},[V.Container]:{icon:Gs,label:`Container`},[V.Image]:{icon:qc,label:`Image`}},tp={[H.Siren]:{icon:Kl,label:`Siren`},[H.Floodlight]:{icon:Zc,label:`Floodlight`},[H.Spotlight]:{icon:Pc,label:`Spotlight`},[H.PirSensor]:{icon:kl,label:`PIR sensor`},[H.Chime]:{icon:Hs,label:`Chime`},[H.Autotrack]:{icon:bc,label:`Auto-track`},[H.Nightvision]:{icon:ml,label:`Night vision`},[H.PrivacyMask]:{icon:kc,label:`Privacy mask`},[H.Doorbell]:{icon:Sc,label:`Doorbell`},[H.BinaryHelper]:{icon:ru,label:`Binary helper`},[H.MotionSensor]:{icon:Ic,label:`Motion sensor`},[H.ContactSensor]:{icon:Cc,label:`Contact sensor`},[H.LeakSensor]:{icon:Tc,label:`Leak sensor`},[H.SmokeSensor]:{icon:Os,label:`Smoke sensor`},[H.COSensor]:{icon:vu,label:`CO sensor`},[H.GasSensor]:{icon:Nc,label:`Gas sensor`},[H.TamperSensor]:{icon:Vl,label:`Tamper sensor`},[H.VibrationSensor]:{icon:fu,label:`Vibration sensor`},[H.ConnectivitySensor]:{icon:_u,label:`Connectivity`},[H.SoundSensor]:{icon:pu,label:`Sound sensor`},[H.BinarySensor]:{icon:ru,label:`Binary sensor`},[H.TemperatureSensor]:{icon:nu,label:`Temperature`},[H.HumiditySensor]:{icon:Ec,label:`Humidity`},[H.AmbientLightSensor]:{icon:$l,label:`Ambient light`},[H.PressureSensor]:{icon:zc,label:`Pressure`},[H.PowerSensor]:{icon:Su,label:`Power`},[H.EnergySensor]:{icon:Su,label:`Energy`},[H.VoltageSensor]:{icon:Su,label:`Voltage`},[H.CurrentSensor]:{icon:Su,label:`Current`},[H.AirQualitySensor]:{icon:vu,label:`Air quality`},[H.BatterySensor]:{icon:zc,label:`Battery`},[H.NumericSensor]:{icon:Uc,label:`Numeric sensor`},[H.EnumSensor]:{icon:$c,label:`Enum sensor`},[H.DateTimeSensor]:{icon:uc,label:`Date / time`},[H.GenericSensor]:{icon:zc,label:`Sensor`},[H.NumericControl]:{icon:Yl,label:`Numeric control`},[H.SelectControl]:{icon:Qc,label:`Select control`},[H.TextControl]:{icon:lu,label:`Text control`},[H.DateTimeControl]:{icon:uc,label:`Date / time control`},[H.MobilePushNotifier]:{icon:Xl,label:`Mobile push`},[H.MessagingNotifier]:{icon:ll,label:`Messaging`},[H.EmailNotifier]:{icon:il,label:`Email`},[H.GenericNotifier]:{icon:Hs,label:`Notifier`}},np=new Set(Object.values(V)),rp=new Set(Object.values(H));function ip(e){return np.has(e)}function ap(e){return rp.has(e)}function op(e){return ep[e]}function sp(e){return tp[e]}function cp(e){return ip(e)?ep[e]:ep[V.Generic]}function lp(e){return ap(e)?tp[e]:tp[H.GenericSensor]}var up=Object.values(V).map(e=>({id:e,label:ep[e].label,icon:ep[e].icon}));function dp(){return up}var fp=[`media-player`,`alarm-panel`,`thermostat`,`humidifier`,`water-heater`,`lock`,`cover`,`valve`,`fan`,`vacuum`,`lawn-mower`,`light`,`switch`,`siren`,`button`,`control`,`notifier`,`script`,`automation`,`update`,`presence`,`weather`,`image`,`sensor`];function pp(e,t){if(t!==void 0){let n=e.find(e=>e.entityId===t);if(n!==void 0)return n}return[...e].toSorted((e,t)=>mp(e.type)-mp(t.type))[0]??null}function mp(e){let t=fp.indexOf(e);return t===-1?fp.length:t}function hp(e){return e.sourceInfo?.id??e.stableId}function gp(e){return{id:e.id,entityId:hp(e),type:e.type}}function _p(e,t){if(t==null)return;let n=e.find(e=>e.id===t);return n===void 0?void 0:hp(n)}function vp(e,t,n){return pp(e.map(gp),n!=null&&n!==``?n:_p(e,t))}function yp(e){return e.parentDeviceId===null?`top-level`:e.role?`accessory`:`adopted`}var bp={minimal:{showIntegrationIcon:!1,showParentBadge:!1,showSnapshot:!1,showBattery:!1,showStableId:!1,showId:!1,showSwitchToggle:!0,showChildrenAccordion:!1},compact:{showIntegrationIcon:!0,showParentBadge:!0,showSnapshot:!0,showBattery:!0,showStableId:!1,showId:!1,showSwitchToggle:!0,showChildrenAccordion:!0},expanded:{showIntegrationIcon:!1,showParentBadge:!0,showSnapshot:!0,showBattery:!0,showStableId:!0,showId:!0,showSwitchToggle:!0,showChildrenAccordion:!0}};function xp(e){let t=bp[e.variant??`compact`];return{showIntegrationIcon:e.showIntegrationIcon??t.showIntegrationIcon,showParentBadge:e.showParentBadge??t.showParentBadge,showSnapshot:e.showSnapshot??t.showSnapshot,showBattery:e.showBattery??t.showBattery,showStableId:e.showStableId??t.showStableId,showId:e.showId??t.showId,showSwitchToggle:e.showSwitchToggle??t.showSwitchToggle,showChildrenAccordion:e.showChildrenAccordion??t.showChildrenAccordion}}function Sp(e){return e.role?lp(e.role).icon:cp(e.type).icon}var Cp={"native-snapshot":qc,"two-way-audio":ul,"pan-tilt-zoom":bc,"ptz-autotrack":tl,"doorbell-button":Cc,"motion-trigger":Ds,"battery-operated":Bs,rebootable:Nl},wp={"native-snapshot":`Native snapshot`,"two-way-audio":`Two-way audio`,"pan-tilt-zoom":`Pan-Tilt-Zoom`,"ptz-autotrack":`PTZ autotrack`,"doorbell-button":`Doorbell button`,"motion-trigger":`Motion trigger`,"battery-operated":`Battery operated`,rebootable:`Rebootable`},Tp={"native-snapshot":`snapshot`,rebootable:`reboot`,"pan-tilt-zoom":`ptz`,"ptz-autotrack":`ptz-autotrack`,"two-way-audio":`intercom`,"motion-trigger":`motion-trigger`},Ep=new Set([`camera`,`hub`,`nvr`]);function Dp(e){return!Ep.has(e.type.toLowerCase())}function Op(e){return e.role?!0:!Ep.has(e.type.toLowerCase())}function kp(e){return(e.features??[]).includes(`motion-trigger`)}function Ap(e,t){if(e.type!==V.Container)return e.online;let n=t??[];if(n.length===0)return e.online;let r=vp(n,e.linkDeviceId,e.primaryChildEntityId);if(r===null)return e.online;let i=n.find(e=>e.id===r.id);return i===void 0?e.online:i.online}function jp(e,t){if(e.type!==V.Container)return e.type;let n=t??[];if(n.length===0)return e.type;let r=vp(n,e.linkDeviceId,e.primaryChildEntityId);if(r===null)return e.type;let i=n.find(e=>e.id===r.id);return i===void 0?e.type:i.type}function Mp(e,t){if(e.type!==V.Container)return e;let n=t??[];if(n.length===0)return e;let r=vp(n,e.linkDeviceId,e.primaryChildEntityId);return r===null?e:n.find(e=>e.id===r.id)??e}function Np(e){if(e.length<=24)return e;let t=e.lastIndexOf(`:`);if(t>=0&&t<e.length-4)return e.slice(t+1);let n=e.split(`-`);if(n.length>2){let e=n.slice(-2).join(`-`);if(e.length>=6)return e}return`…${e.slice(-18)}`}function Pp({trpc:e,accessoryChildren:t,adoptedChildren:n,onNavigate:r}){return T(`div`,{className:`border-t border-border-subtle/50`,children:[n.length>0&&v(Fp,{trpc:e,label:`Adopted devices`,rows:n,onNavigate:r}),t.length>0&&v(Fp,{trpc:e,label:`Accessories`,rows:t,onNavigate:r})]})}function Fp({trpc:e,label:t,rows:n,onNavigate:r}){return T(`div`,{children:[v(`div`,{className:`px-3 pt-1.5 pb-1 text-[9px] font-semibold uppercase tracking-wide text-foreground-subtle`,children:t}),v(`ul`,{children:n.map(t=>v(Ip,{trpc:e,child:t,onNavigate:r},t.id))})]})}function Ip({trpc:e,child:t,onNavigate:n}){let r=!t.disabled,i=r&&Dp(t),a=r&&kp(t);return v(`li`,{children:T(`div`,{onClick:e=>{e.stopPropagation(),n(t.id)},className:`w-full flex items-center gap-2 px-3 py-1.5 text-left hover:bg-surface-hover transition-colors cursor-pointer`,children:[v(Sp(t),{className:`h-3 w-3 text-foreground-subtle flex-shrink-0`}),v(`span`,{className:`text-[10.5px] text-foreground flex-1 truncate`,children:t.name}),a&&v(Rp,{trpc:e,deviceId:t.id,features:t.features}),i&&v(Lp,{trpc:e,deviceId:t.id}),v(`span`,{className:G(`h-1.5 w-1.5 rounded-full flex-shrink-0`,t.online?`bg-success`:`bg-foreground-subtle/40`),title:t.online?`Online`:`Offline`})]})})}function Lp({trpc:e,deviceId:t}){let{dev:n,cap:r,slice:i,available:a}=$f({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch}),[o,s]=h(!1);if(n!==null&&!r)return null;let c=i?.on===!0,l={transform:c?`translateX(14px)`:`translateX(2px)`},u=async e=>{if(e.stopPropagation(),!(o||!a||!r)){s(!0);try{await r.setState({on:!c})}finally{s(!1)}}};return v(`button`,{type:`button`,onClick:e=>{u(e)},disabled:o||!a,className:G(`relative inline-flex h-4 w-7 items-center rounded-full border transition-colors flex-shrink-0`,c?`bg-success/30 border-success/50`:`bg-surface-hover border-border`,o&&`opacity-60`,!a&&`opacity-40 cursor-not-allowed`),title:a?c?`Turn off`:`Turn on`:`Awaiting state…`,"aria-pressed":c,children:v(`span`,{className:G(`absolute h-3 w-3 rounded-full transition-all`,c?`bg-success`:`bg-foreground-subtle`),style:l})})}function Rp({trpc:e,deviceId:t,features:n}){let{dev:r,cap:i,slice:a,available:o}=$f({trpc:e,deviceId:t,cap:e=>e.motionTrigger,slice:e=>e.state.motionTrigger,requireFeature:`motion-trigger`,deviceFeatures:n}),[s,c]=h(!1);if(r!==null&&!i)return null;let l=a?.enabled===!0,u=async e=>{if(e.stopPropagation(),!(s||!o||!i)){c(!0);try{await i.setMotionTrigger({enabled:!l})}finally{c(!1)}}};return v(`button`,{type:`button`,onClick:e=>{u(e)},disabled:s||!o,className:G(`inline-flex h-4 w-4 items-center justify-center rounded transition-colors flex-shrink-0`,l?`text-primary bg-primary/10`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,(s||!o)&&`opacity-50`),title:o?l?`Motion-trigger: on (click to disable)`:`Motion-trigger: off (click to enable)`:`Awaiting state…`,"aria-pressed":l,children:v(Ds,{className:`h-2.5 w-2.5`})})}var zp=[],Bp=r(null);function Vp({value:e,children:t}){return v(Bp.Provider,{value:e,children:t})}function Hp(e){return i(Bp)?.get(e)??zp}var Up={up:{pan:0,tilt:1},down:{pan:0,tilt:-1},left:{pan:-1,tilt:0},right:{pan:1,tilt:0},"up-left":{pan:-1,tilt:1},"up-right":{pan:1,tilt:1},"down-left":{pan:-1,tilt:-1},"down-right":{pan:1,tilt:-1}};function Wp(e,t,n){let r=n?.defaultSpeed??.5,i=n?.pulseMs??250,a=n?.enabled??!0,o=Xf(e,a?t:null)?.ptz,[s,l]=h([]),[d,f]=h(null),[p,m]=h(!1),[g,_]=h(null),v=u(async()=>{if(!(!a||!o))try{l(await o.getPresets({}))}catch(e){if(Rn(e))return;_(e instanceof Error?e.message:String(e))}},[o,a]),y=u(async()=>{if(!(!a||!o))try{f(await o.getOptions({}))}catch(e){if(Rn(e))return;_(e instanceof Error?e.message:String(e))}},[o,a]);c(()=>{v(),y()},[v,y]);let b=u(async e=>{if(!(!a||!o)){_(null),m(!0);try{return await e()}catch(e){_(e instanceof Error?e.message:String(e));return}finally{m(!1)}}},[a,o]);return{move:u(async(e,t)=>{if(!o)return;let n=Up[e],a=t??r;await b(async()=>{await o.move({pan:n.pan,tilt:n.tilt,speed:a}),await new Promise(e=>setTimeout(e,i)),await o.stop({})})},[o,r,i,b]),startContinuous:u(async(e,t)=>{if(!o)return;let n=Up[e],i=t??r;await b(()=>o.continuousMove({pan:n.pan,tilt:n.tilt,speed:i}))},[o,r,b]),stopContinuous:u(async()=>{o&&await b(()=>o.stop({}))},[o,b]),zoom:u(async(e,t)=>{if(!o)return;let n=e===`in`?1:-1,a=t??r;await b(async()=>{await o.move({zoom:n,speed:a}),await new Promise(e=>setTimeout(e,i)),await o.stop({})})},[o,r,i,b]),goHome:u(async()=>{o&&await b(()=>o.goHome({}))},[o,b]),goToPreset:u(async e=>{o&&await b(()=>o.goToPreset({presetId:e}))},[o,b]),savePreset:u(async e=>{if(o)return b(async()=>{let t=new Set(s.map(e=>Number(e.id)).filter(e=>Number.isInteger(e)&&e>=0)),n=0;for(;t.has(n);)n+=1;let r=String(n);return await o.savePreset({presetId:r,name:e}),await v(),r})},[o,s,v,b]),deletePreset:u(async e=>{o&&await b(async()=>{await o.deletePreset({presetId:e}),await v()})},[o,v,b]),presets:s,refreshPresets:v,options:d,busy:p,error:g}}function Gp({direction:e,icon:t,disabled:n,className:r,variant:i,onMove:a,onStart:o,onStop:s}){let[c,l]=h(null),[d,f]=h(!1),p=u(t=>{if(n)return;t.currentTarget.setPointerCapture(t.pointerId),l(Date.now()),f(!1);let r=setTimeout(()=>{f(!0),o(e)},250);t.currentTarget.dataset.timer=String(r)},[e,n,o]),m=u(t=>{let n=Number(t.currentTarget.dataset.timer);n&&clearTimeout(n),t.currentTarget.dataset.timer=``,d?s():c!==null&&a(e),l(null),f(!1)},[d,e,a,s,c]),g=u(e=>{let t=Number(e.currentTarget.dataset.timer);t&&clearTimeout(t),e.currentTarget.dataset.timer=``,d&&s(),l(null),f(!1)},[d,s]),_=i===`panel`?`h-9 w-9`:`h-7 w-7`,y=i===`panel`?`h-4 w-4`:`h-3.5 w-3.5`;return v(`button`,{type:`button`,disabled:n,onPointerDown:p,onPointerUp:m,onPointerCancel:g,className:G(`flex items-center justify-center rounded transition-colors disabled:opacity-40`,i===`panel`?`text-foreground hover:bg-surface-hover active:bg-surface-hover/80`:`text-white hover:bg-white/15 active:bg-white/25`,_,r),title:e,children:v(t,{className:y})})}function Kp({controls:e,mode:t=`overlay`,showPresets:n,showZoom:r=!0,showHome:i=!0,className:a}){let{move:o,startContinuous:s,stopContinuous:c,zoom:l,goHome:d,goToPreset:f,savePreset:p,deletePreset:m,presets:g,options:_,busy:y,error:b}=e,x=Lf(),[S,C]=h(!1),[w,D]=h(``),O=(n??g.length>0)&&g.length>0,k=t===`panel`,A=k&&(_?.supportsPresets??!1),j=_?.maxPresets!==void 0&&g.length>=_.maxPresets,M=u(async()=>{let e=w.trim();!e||y||j||await p(e)!==void 0&&D(``)},[w,y,j,p]),N=u(async(e,t)=>{await x({title:`Delete preset`,message:`Delete PTZ preset "${t}"? This removes it from the camera.`,confirmLabel:`Delete`,variant:`danger`})&&await m(e)},[x,m]),P=k?`flex flex-col items-stretch gap-2 w-full h-full p-3`:`pointer-events-auto absolute top-3 right-3 z-10 flex flex-col items-end gap-2`,ee=G(k?`flex items-center gap-3 rounded-lg p-2`:`flex items-center gap-2 rounded-lg border border-white/30 bg-zinc-900/90 backdrop-blur-md p-2 shadow-lg shadow-black/40`,y&&`ring-1 ring-primary/40`),F=k?`h-9 w-9`:`h-7 w-7`,te=k?`h-4 w-4`:`h-3.5 w-3.5`,I=k?`text-foreground hover:bg-surface-hover`:`text-white hover:bg-white/15`,L=k?`h-12 w-px bg-border mx-1`:`h-12 w-px bg-white/15 mx-1`;return T(`div`,{className:G(P,a),children:[b&&T(`div`,{className:`rounded bg-danger/90 px-2 py-1 text-[10px] font-medium text-white shadow-lg max-w-[200px] self-center`,children:[`PTZ: `,b]}),T(`div`,{className:G(ee,k&&`justify-center`),children:[T(`div`,{className:`grid grid-cols-3 gap-0.5`,children:[v(`span`,{"aria-hidden":!0,className:k?`h-9 w-9`:`h-7 w-7`}),v(Gp,{direction:`up`,icon:Ps,variant:t,onMove:o,onStart:s,onStop:c}),v(`span`,{"aria-hidden":!0,className:k?`h-9 w-9`:`h-7 w-7`}),v(Gp,{direction:`left`,icon:js,variant:t,onMove:o,onStart:s,onStop:c}),v(`span`,{"aria-hidden":!0,className:k?`h-9 w-9`:`h-7 w-7`}),v(Gp,{direction:`right`,icon:Ms,variant:t,onMove:o,onStart:s,onStop:c}),v(`span`,{"aria-hidden":!0,className:k?`h-9 w-9`:`h-7 w-7`}),v(Gp,{direction:`down`,icon:As,variant:t,onMove:o,onStart:s,onStop:c}),v(`span`,{"aria-hidden":!0,className:k?`h-9 w-9`:`h-7 w-7`})]}),(r||i)&&v(`div`,{className:L}),T(`div`,{className:`flex flex-col gap-0.5`,children:[r&&T(E,{children:[v(`button`,{type:`button`,onClick:()=>l(`in`),disabled:y,title:`Zoom in`,className:G(`flex items-center justify-center rounded disabled:opacity-40`,F,I),children:v(Cu,{className:te})}),v(`button`,{type:`button`,onClick:()=>l(`out`),disabled:y,title:`Zoom out`,className:G(`flex items-center justify-center rounded disabled:opacity-40`,F,I),children:v(wu,{className:te})})]}),i&&v(`button`,{type:`button`,onClick:()=>d(),disabled:y,title:`Go home`,className:G(`flex items-center justify-center rounded disabled:opacity-40`,F,I),children:v(Gc,{className:te})})]}),O&&T(`div`,{className:`relative`,children:[T(`button`,{type:`button`,onClick:()=>C(e=>!e),disabled:y,className:G(`flex items-center gap-1 rounded px-2 text-[10px] disabled:opacity-40`,k?`h-9 text-foreground hover:bg-surface-hover`:`h-7 text-white hover:bg-white/15`),title:`Presets`,children:[`Presets`,v(Xs,{className:G(`h-3 w-3 transition-transform`,S&&`rotate-180`)})]}),S&&v(`div`,{className:G(`absolute right-0 top-full mt-1 min-w-[140px] rounded-lg shadow-xl py-1 z-20`,k?`bg-surface border border-border`:`border border-white/30 bg-zinc-900/95 backdrop-blur-md`),children:g.map(e=>T(`div`,{className:G(`group flex items-center`,k?`hover:bg-surface-hover`:`hover:bg-white/15`),children:[v(`button`,{type:`button`,onClick:()=>{f(e.id),C(!1)},disabled:y,className:G(`flex-1 px-3 py-1.5 text-left text-[10px] disabled:opacity-40`,k?`text-foreground`:`text-white`),children:e.name||e.id}),A&&v(`button`,{type:`button`,onClick:()=>void N(e.id,e.name||e.id),disabled:y,title:`Delete preset ${e.name||e.id}`,className:G(`mr-1 flex h-5 w-5 shrink-0 items-center justify-center rounded`,`text-foreground-subtle hover:bg-danger/15 hover:text-danger disabled:opacity-40`),children:v(xu,{className:`h-3 w-3`})})]},e.id))})]})]}),A&&T(`div`,{className:`flex flex-col gap-1 rounded-lg border border-border p-2`,children:[T(`div`,{className:`flex items-center gap-2`,children:[v(`input`,{type:`text`,value:w,onChange:e=>D(e.target.value),onKeyDown:e=>{e.key===`Enter`&&M()},disabled:y||j,placeholder:`New preset name`,maxLength:64,className:G(`min-w-0 flex-1 rounded border border-border bg-surface px-2 py-1 text-[11px] text-foreground`,`placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary/50`,`disabled:opacity-40`)}),T(`button`,{type:`button`,onClick:()=>void M(),disabled:y||j||w.trim().length===0,title:j?`Camera preset limit reached (${_?.maxPresets})`:`Save current position as a new preset`,className:G(`flex h-7 shrink-0 items-center gap-1 rounded px-2 text-[10px] font-medium`,`bg-primary/15 text-primary hover:bg-primary/25 disabled:opacity-40`),children:[v(wl,{className:`h-3 w-3`}),`Save current position`]})]}),j&&T(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`Camera preset limit reached (`,_?.maxPresets,`). Delete a preset to add a new one.`]})]})]})}var qp=`fill`,Jp=`right`,Yp=`center`;function Xp({align:e,children:t,className:n,...r}){if(e===`fit`)return v(`div`,{...r,className:G(`inline-flex items-center`,n),children:t});let i=e===`center`?`justify-center`:`justify-end`;return v(`div`,{...r,className:G(`w-[140px] shrink-0 flex items-center gap-1.5`,i,e===`fill`?`[&>*:last-child]:w-full`:``,n),children:t})}function Zp({value:e,unit:t}){return T(`span`,{className:`text-sm text-foreground`,children:[e,t?v(`span`,{"data-unit":!0,className:`ml-0.5 text-[11px] text-foreground-subtle`,children:t}):null]})}function Qp({value:e,unit:t,onDelta:n}){return T(`div`,{className:`flex h-8 w-full overflow-hidden rounded-lg border border-border bg-surface`,children:[v(`button`,{type:`button`,"aria-label":`Decrement`,className:`w-9 shrink-0 bg-surface-hover text-base text-foreground`,onClick:()=>n(-1),children:`−`}),T(`span`,{className:`flex flex-1 items-center justify-center gap-0.5 border-x border-border/60 text-sm`,children:[e,t?v(`span`,{"data-unit":!0,className:`text-[11px] text-foreground-subtle`,children:t}):null]}),v(`button`,{type:`button`,"aria-label":`Increment`,className:`w-9 shrink-0 bg-surface-hover text-base text-foreground`,onClick:()=>n(1),children:`+`})]})}function $p({on:e,targetLabel:t,onConfirm:n}){let r=p(null),i=p(!1);return T(`div`,{className:G(`relative h-12 w-full rounded-full border flex items-center`,e?`bg-emerald-50 border-emerald-200 pl-4`:`bg-amber-50 border-amber-200 justify-end pr-4`),children:[v(`span`,{className:`text-xs font-semibold opacity-60`,children:t}),v(`span`,{"data-testid":`slide-thumb`,className:`absolute top-1 left-1 h-10 w-14 rounded-[19px] bg-surface shadow flex items-center justify-center`,onPointerDown:e=>{e.currentTarget.setPointerCapture?.(e.pointerId),r.current=e.clientX,i.current=!1},onPointerMove:e=>{r.current!==null&&Math.abs(e.clientX-r.current)>40&&(i.current=!0)},onPointerUp:()=>{i.current&&n(),i.current=!1,r.current=null},onPointerCancel:()=>{i.current=!1,r.current=null}})]})}var em=2,tm=270,nm=315;function rm(e){let t=(e-135+360)%360;return t>tm?+(t<=nm):t/tm}function im({fraction:e,color:t,knobTopPx:n,onDragFraction:r}){let i=-135+e*270,a=p(null),[o,s]=h(!1),c=r!==void 0,l=n??em,u=e=>{r!==void 0&&(e.preventDefault(),e.stopPropagation(),e.currentTarget.setPointerCapture?.(e.pointerId),s(!0))},d=e=>{if(r===void 0||!o)return;let t=a.current;if(t===null)return;let n=t.getBoundingClientRect(),i=n.left+n.width/2,s=n.top+n.height/2;r(rm(Math.atan2(e.clientY-s,e.clientX-i)*180/Math.PI))},f=e=>{r!==void 0&&(e.currentTarget.releasePointerCapture?.(e.pointerId),s(!1))};return v(`div`,{ref:a,className:`absolute inset-0`,style:{transform:`rotate(${i}deg)`},children:v(`div`,{className:G(`absolute left-1/2 h-5 w-5 -translate-x-1/2 rounded-full bg-white shadow`,c&&(o?`cursor-grabbing`:`cursor-grab`)),style:{top:l,border:`3px solid ${t}`},...c?{onPointerDown:u,onPointerMove:d,onPointerUp:f,onPointerCancel:f}:{}})})}function am({fraction:e,color:t}){return T(`div`,{className:`relative h-2 w-full rounded-full bg-border`,children:[v(`div`,{className:`absolute left-0 top-0 h-2 rounded-full`,style:{width:`${e*100}%`,background:t??`var(--color-primary)`}}),v(`div`,{className:`absolute -top-1 h-4 w-4 rounded-full bg-white shadow`,style:{left:`calc(${e*100}% - 8px)`}})]})}function om({trpc:e,deviceId:t}){let n=Xf(e,t),r=n===null?void 0:n.button;if(r===void 0)return null;let i=()=>{r.press({deviceId:t})};return T(`button`,{type:`button`,"aria-label":`Press`,title:`Press`,onClick:e=>{e.stopPropagation(),i()},className:G(`inline-flex h-5 items-center gap-1 rounded px-1.5 text-xs`,`bg-primary text-primary-foreground hover:bg-primary/90 transition-colors`),children:[v(hl,{className:`h-3 w-3`}),v(`span`,{children:`Press`})]})}function sm({trpc:e,deviceId:t}){let n=Xf(e,t),r=n===null?void 0:n.button;return r===void 0?null:T(`div`,{className:`flex flex-col items-center justify-center gap-4 rounded-lg border border-border bg-surface p-6`,children:[v(`button`,{type:`button`,"aria-label":`Press button`,onClick:()=>{r.press({deviceId:t})},className:G(`inline-flex h-14 w-14 items-center justify-center rounded-full`,`bg-primary text-primary-foreground hover:bg-primary/90 transition-colors`,`shadow-md`),children:v(hl,{className:`h-6 w-6`})}),v(`span`,{className:`text-sm font-medium text-foreground`,children:`Press`})]})}var cm=4e3;function lm(e){if(e!==void 0)return typeof e==`object`&&e&&`lastChangedAt`in e&&typeof e.lastChangedAt==`number`?e.lastChangedAt:e}function um(e,t){let n=t?.enabled!==!1,r=t?.timeoutMs??cm,[i,a]=h(void 0),o=p(void 0),s=p(void 0),l=p(!1),d=p(void 0),f=u(()=>{d.current!==void 0&&(clearTimeout(d.current),d.current=void 0),o.current=void 0,l.current=!1,s.current=void 0,a(void 0)},[]);c(()=>{if(!n||!l.current)return;let t=lm(e),r=s.current;t!==void 0&&t!==r&&f()}),c(()=>()=>{d.current!==void 0&&clearTimeout(d.current)},[]);let m=u(t=>{if(!n)return;d.current!==void 0&&(clearTimeout(d.current),d.current=void 0);let i=o.current??e;if(i!==void 0){let e={...i,...t};o.current=e,a(e)}s.current=lm(e),l.current=!0,d.current=setTimeout(f,r)},[n,e,f,r]);return n?{display:i===void 0?e:i,applyOptimistic:m}:{display:e,applyOptimistic:()=>{}}}function dm(e){switch(e){case`opening`:return{up:`accent`,stop:`neutral`,down:`neutral`};case`closing`:return{up:`neutral`,stop:`neutral`,down:`accent`};case`open`:return{up:`filled`,stop:`neutral`,down:`neutral`};case`closed`:return{up:`neutral`,stop:`neutral`,down:`filled`};default:return{up:`neutral`,stop:`neutral`,down:`neutral`}}}function fm(e){switch(e){case`accent`:return`bg-primary text-primary-foreground`;case`filled`:return`bg-primary/15 text-primary`;case`neutral`:return``}}function pm({label:e,busy:t,variant:n,onClick:r,children:i}){return v(`button`,{type:`button`,"aria-label":e,title:e,disabled:t,onClick:e=>{e.stopPropagation(),r()},className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,fm(n),t&&`opacity-40 cursor-not-allowed`),children:i})}function mm({trpc:e,deviceId:t,optimistic:n}){let{cap:r,slice:i,available:a}=$f({trpc:e,deviceId:t,cap:e=>e.cover,slice:e=>e.state.cover}),{display:o,applyOptimistic:s}=um(i,{enabled:n??!0});if(r===void 0)return null;let c=dm(o?.state),l=!a,u=(e,t)=>{l||!e||(t!==void 0&&s(t),e({}))};return T(`div`,{className:`inline-flex items-center gap-1`,children:[v(pm,{label:`Open`,busy:l,variant:c.up,onClick:()=>u(r?.open,{state:`opening`}),children:v($s,{className:`h-3.5 w-3.5`})}),v(pm,{label:`Stop`,busy:l,variant:c.stop,onClick:()=>u(r?.stop,{state:`stopped`}),children:v(Zl,{className:`h-3 w-3`})}),v(pm,{label:`Close`,busy:l,variant:c.down,onClick:()=>u(r?.close,{state:`closing`}),children:v(Xs,{className:`h-3.5 w-3.5`})}),o!==void 0&&o.position!==null&&T(`span`,{className:`tabular-nums text-xs text-foreground-subtle ml-1`,children:[o.position,`%`]})]})}function hm({label:e,busy:t,variant:n,onClick:r,children:i}){return v(`button`,{type:`button`,"aria-label":e,title:e,disabled:t,onClick:e=>{e.stopPropagation(),r()},className:G(`inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,n===`accent`&&`bg-primary text-primary-foreground hover:bg-primary/90`,n===`filled`&&`bg-primary/15 text-primary`,t&&`opacity-40 cursor-not-allowed`),children:i})}function gm(){return T(E,{children:[v(`div`,{"aria-hidden":`true`,className:`absolute inset-y-0 left-1/2 w-px -translate-x-px bg-white/60`}),v(`div`,{"aria-hidden":`true`,className:`absolute inset-x-0 top-1/2 h-px -translate-y-px bg-white/60`})]})}function _m({position:e,interactive:t,onSetPosition:n}){let r=(1-e/100)*100,i=p(null),a=p(!1),o=p(null),s=t=>{let n=i.current;if(n===null)return e;let r=n.getBoundingClientRect();if(r.height<=0)return e;let a=(t-r.top)/r.height,o=Math.round(100-a*100);return Math.min(100,Math.max(0,o))},c=e=>{if(n===void 0)return;let t=s(e);o.current!==t&&(o.current=t,n(t))},l=e=>{t&&(e.stopPropagation(),e.preventDefault(),a.current=!0,o.current=null,e.currentTarget.setPointerCapture(e.pointerId),c(e.clientY))},u=e=>{!t||!a.current||(e.stopPropagation(),c(e.clientY))},d=e=>{!t||!a.current||(e.stopPropagation(),a.current=!1,o.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))};return T(`div`,{ref:i,"data-testid":`cover-window`,...t?{"aria-label":`Drag to set position`,role:`slider`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":e}:{"aria-hidden":`true`},onPointerDown:t?l:void 0,onPointerMove:t?u:void 0,onPointerUp:t?d:void 0,onPointerCancel:t?d:void 0,className:G(`relative w-28 h-36 rounded border-2 border-amber-700/60 bg-gradient-to-b from-sky-200 to-sky-50 overflow-hidden flex-shrink-0`,t&&`cursor-ns-resize touch-none select-none`),style:{boxShadow:`inset 0 0 0 2px rgba(255,255,255,.5)`},children:[v(gm,{}),v(`div`,{className:`absolute inset-x-0 top-0 transition-all duration-200`,style:{height:`${r}%`,background:`repeating-linear-gradient(#c9cdd2, #c9cdd2 6px, #b7bcc2 6px, #b7bcc2 8px)`,borderBottom:r>0?`1px solid #9aa`:`none`}}),T(`div`,{"data-testid":`cover-lever`,className:G(`absolute inset-x-0 h-4 flex items-center justify-center gap-1 z-10 transition-all duration-200`,t&&`cursor-grab active:cursor-grabbing`),style:{top:`calc(${r}% - 8px)`},children:[v(`div`,{className:`absolute -inset-x-1.5 h-full rounded-lg bg-slate-600 shadow-md`}),v(`span`,{className:`h-1 w-1 rounded-full bg-white/70 relative z-10`,"aria-hidden":`true`}),v(`span`,{className:`h-1 w-1 rounded-full bg-white/70 relative z-10`,"aria-hidden":`true`}),v(`span`,{className:`h-1 w-1 rounded-full bg-white/70 relative z-10`,"aria-hidden":`true`}),T(`span`,{"data-testid":`cover-position-pct`,className:`absolute left-full ml-2 text-xs font-semibold text-foreground tabular-nums whitespace-nowrap`,children:[e,`%`]})]})]})}function vm({isOpen:e}){return T(`div`,{"data-testid":`cover-window`,"aria-hidden":`true`,className:`relative w-28 h-36 rounded border-2 border-amber-700/60 bg-gradient-to-b from-sky-200 to-sky-50 overflow-hidden flex-shrink-0`,style:{boxShadow:`inset 0 0 0 2px rgba(255,255,255,.5)`},children:[v(gm,{}),!e&&v(`div`,{className:`absolute inset-0`,style:{background:`repeating-linear-gradient(#c9cdd2, #c9cdd2 6px, #b7bcc2 6px, #b7bcc2 8px)`}})]})}function ym({trpc:e,deviceId:t,features:n,optimistic:r}){let{cap:i,slice:a,available:o}=$f({trpc:e,deviceId:t,cap:e=>e.cover,slice:e=>e.state.cover}),{display:s,applyOptimistic:c}=um(a,{enabled:r??!0});if(i===void 0)return null;let l=!o,u=(n??[]).includes(Ee.CoverPositionable),d=(n??[]).includes(Ee.CoverTilt),f=dm(s?.state),p=s?.position??null,m=p!==null,h=s?.state===`open`||s?.state===`opening`,g=(e,t)=>{l||!e||(t!==void 0&&c(t),e({}))},_=e=>{l||(c({position:e}),i?.setPosition({position:e}))};return T(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[T(`div`,{className:`flex items-center gap-6`,children:[m?v(_m,{position:p,interactive:u,onSetPosition:u?_:void 0}):v(vm,{isOpen:h}),T(`div`,{className:`flex flex-col gap-3 flex-1`,children:[m&&T(`div`,{className:`flex items-baseline gap-1`,children:[v(`span`,{className:`text-3xl font-semibold tabular-nums text-foreground`,children:p}),v(`span`,{className:`text-base text-foreground-subtle`,children:`%`}),v(`span`,{className:`text-xs text-foreground-subtle ml-1`,children:`open`})]}),!m&&v(`div`,{className:`flex items-baseline gap-1`,children:v(`span`,{className:`text-3xl font-semibold capitalize text-foreground`,children:s?.state??`—`})}),T(`div`,{className:`flex items-center gap-2`,children:[v(hm,{label:`Open`,busy:l,variant:f.up,onClick:()=>g(i?.open,{state:`opening`}),children:v($s,{className:`h-5 w-5`})}),v(hm,{label:`Stop`,busy:l,variant:f.stop,onClick:()=>g(i?.stop,{state:`stopped`}),children:v(Zl,{className:`h-4 w-4`})}),v(hm,{label:`Close`,busy:l,variant:f.down,onClick:()=>g(i?.close,{state:`closing`}),children:v(Xs,{className:`h-5 w-5`})})]})]})]}),u&&T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{className:`w-12 shrink-0`,children:`Position`}),v(`input`,{"aria-label":`Position`,type:`range`,min:0,max:100,step:1,value:p??0,disabled:l,className:`flex-1`,onChange:e=>{_(Number(e.target.value))}}),T(`span`,{className:`w-8 text-right tabular-nums`,children:[p??`—`,`%`]})]}),!u&&p!==null&&T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{className:`w-12 shrink-0`,children:`Position`}),v(`input`,{"aria-label":`Position`,type:`range`,min:0,max:100,step:1,value:p,disabled:!0,readOnly:!0,className:`flex-1 opacity-60`}),T(`span`,{className:`w-8 text-right tabular-nums`,children:[p,`%`]})]}),d&&T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{className:`w-12 shrink-0`,children:`Tilt`}),v(`input`,{"aria-label":`Tilt position`,type:`range`,min:0,max:100,step:1,value:s?.tiltPosition??0,disabled:l,className:`flex-1`,onChange:e=>{let t=Number(e.target.value);c({tiltPosition:t}),l||i?.setTiltPosition({tiltPosition:t})}}),T(`span`,{className:`w-8 text-right tabular-nums`,children:[s?.tiltPosition??`—`,`%`]})]})]})}function bm(e){return v(`span`,{className:`text-foreground-subtle text-xs select-none`,"aria-hidden":`true`,children:`—`})}function xm(e){return v(`div`,{className:`rounded border border-border bg-surface-subtle px-3 py-2 text-xs text-foreground-subtle`,children:`Controls coming soon`})}var Sm=q.accessories.setChildHidden.useMutation,Cm=q.accessories.getStatus.useQuery,wm=q.addonPages.listPages.useQuery,Tm=q.addons.list.useQuery,Em=q.addons.getLogs.useQuery,Dm=q.addons.listPackages.useQuery,Om=q.addons.installPackage.useMutation,km=q.addons.installFromWorkspace.useMutation,Am=q.addons.isWorkspaceAvailable.useQuery,jm=q.addons.listWorkspacePackages.useQuery,Mm=q.addons.uninstallPackage.useMutation,Nm=q.addons.reloadPackages.useMutation,Pm=q.addons.searchAvailable.useQuery,Fm=q.addons.listUpdates.useQuery,Im=q.addons.updatePackage.useMutation,Lm=q.addons.rollbackPackage.useMutation,Rm=q.addons.forceRefresh.useMutation,zm=q.addons.restartServer.useMutation,Bm=q.addons.getLastRestart.useQuery,Vm=q.addons.listFrameworkPackages.useQuery,Hm=q.addons.listCapabilityProviders.useQuery,Um=q.addons.setCapabilityProviderEnabled.useMutation,Wm=q.addons.updateFrameworkPackage.useMutation,Gm=q.addons.startBulkUpdate.useMutation,Km=q.addons.getBulkUpdateState.useQuery,qm=q.addons.cancelBulkUpdate.useMutation,Jm=q.addons.listActiveBulkUpdates.useQuery,Ym=q.addons.getVersions.useQuery,Xm=q.addons.restartAddon.useMutation,Zm=q.addons.retryLoad.useMutation,Qm=q.addons.getAutoUpdateSettings.useQuery,$m=q.addons.setAutoUpdateSettings.useMutation,eh=q.addons.getAddonAutoUpdate.useQuery,th=q.addons.setAddonAutoUpdate.useMutation,nh=q.addons.applyAutoUpdateToAll.useMutation,rh=q.addons.custom.useMutation,ih=q.addons.onAddonLogs.useSubscription,ah=q.addonSettings.getGlobalSettings.useQuery,oh=q.addonSettings.updateGlobalSettings.useMutation,sh=q.addonSettings.getDeviceSettings.useQuery,ch=q.addonSettings.updateDeviceSettings.useMutation,lh=q.addonWidgets.listWidgets.useQuery,uh=q.airQualitySensor.getStatus.useQuery,dh=q.alarmPanel.arm.useMutation,fh=q.alarmPanel.disarm.useMutation,ph=q.alarmPanel.trigger.useMutation,mh=q.alarmPanel.getStatus.useQuery,hh=q.alerts.emit.useMutation,gh=q.alerts.update.useMutation,_h=q.alerts.list.useQuery,vh=q.alerts.getUnreadCount.useQuery,yh=q.alerts.markRead.useMutation,bh=q.alerts.markAllRead.useMutation,xh=q.alerts.dismiss.useMutation,Sh=q.ambientLightSensor.getStatus.useQuery,Ch=q.audioAnalysis.resolveDeviceSettings.useQuery,wh=q.audioAnalysis.getDeviceSettingsContribution.useQuery,Th=q.audioAnalysis.getDeviceLiveContribution.useQuery,Eh=q.audioAnalysis.applyDeviceSettingsPatch.useMutation,Dh=q.audioAnalyzer.analyseChunk.useMutation,Oh=q.audioAnalyzer.classify.useQuery,kh=q.audioAnalyzer.isReady.useQuery,Ah=q.audioAnalyzer.dispose.useMutation,jh=q.audioAnalyzer.reprobeAudioEngine.useMutation,Mh=q.audioCodec.listSupportedCodecs.useQuery,Nh=q.audioCodec.canHandle.useQuery,Ph=q.audioCodec.createDecodeSession.useMutation,Fh=q.audioCodec.createEncodeSession.useMutation,Ih=q.audioCodec.closeSession.useMutation,Lh=q.audioCodec.pushEncodedFrame.useMutation,Rh=q.audioCodec.pullPcm.useQuery,zh=q.audioCodec.pushPcm.useMutation,Bh=q.audioCodec.pullEncoded.useQuery,Vh=q.audioCodec.flushEncode.useMutation,Hh=q.audioCodec.listActiveSessions.useQuery,Uh=q.audioMetrics.getCurrentSnapshot.useQuery,Wh=q.audioMetrics.getHistory.useQuery,Gh=q.automationControl.enable.useMutation,Kh=q.automationControl.disable.useMutation,qh=q.automationControl.trigger.useMutation,Jh=q.automationControl.getStatus.useQuery,Yh=q.backup.listDestinations.useQuery,Xh=q.backup.trigger.useMutation,Zh=q.backup.list.useQuery,Qh=q.backup.listLocations.useQuery,$h=q.backup.getEntries.useQuery,eg=q.backup.restore.useMutation,tg=q.backup.delete.useMutation,ng=q.backup.listArchives.useQuery,rg=q.backup.upsertDestinationPolicy.useMutation,ig=q.backup.previewSchedule.useQuery,ag=q.battery.wakeForStream.useMutation,og=q.battery.getStatus.useQuery,sg=q.binary.getStatus.useQuery,cg=q.brightness.setBrightness.useMutation,lg=q.brightness.getStatus.useQuery,ug=q.broker.list.useQuery,dg=q.broker.get.useQuery,fg=q.broker.listProviders.useQuery,pg=q.broker.add.useMutation,mg=q.broker.remove.useMutation,hg=q.broker.testConnection.useMutation,gg=q.broker.getSettings.useQuery,_g=q.broker.setSettings.useMutation,vg=q.broker.getBrokerConfig.useQuery,yg=q.broker.getSettingsSchema.useQuery,bg=q.broker.testSettings.useMutation,xg=q.broker.publish.useMutation,Sg=q.broker.subscribe.useMutation,Cg=q.broker.unsubscribe.useMutation,wg=q.broker.getState.useQuery,Tg=q.broker.getStatus.useQuery,Eg=q.button.press.useMutation,Dg=q.cameraCredentials.getCredentials.useQuery,Og=q.cameraCredentials.getStatus.useQuery,kg=q.cameraPipelineConfig.getDeviceSettingsContribution.useQuery,Ag=q.cameraPipelineConfig.getDeviceLiveContribution.useQuery,jg=q.cameraPipelineConfig.applyDeviceSettingsPatch.useMutation,Mg=q.cameraStreams.getCameraStreams.useQuery,Ng=q.cameraStreams.getBrokerStreams.useQuery,Pg=q.cameraStreams.getRtspEntries.useQuery,Fg=q.cameraStreams.getProfileRtspEntries.useQuery,Ig=q.cameraStreams.pickStream.useQuery,Lg=q.carbonMonoxide.getStatus.useQuery,Rg=q.climateControl.setMode.useMutation,zg=q.climateControl.setFanMode.useMutation,Bg=q.climateControl.setPreset.useMutation,Vg=q.climateControl.setTarget.useMutation,Hg=q.climateControl.setTargetRange.useMutation,Ug=q.climateControl.setTargetHumidity.useMutation,Wg=q.climateControl.getStatus.useQuery,Gg=q.color.setColor.useMutation,Kg=q.color.getStatus.useQuery,qg=q.connectivity.getStatus.useQuery,Jg=q.consumables.reset.useMutation,Yg=q.consumables.getStatus.useQuery,Xg=q.contact.getStatus.useQuery,Zg=q.control.setValue.useMutation,Qg=q.control.getStatus.useQuery,$g=q.cover.open.useMutation,e_=q.cover.close.useMutation,t_=q.cover.stop.useMutation,n_=q.cover.setPosition.useMutation,r_=q.cover.setTiltPosition.useMutation,i_=q.cover.getStatus.useQuery,a_=q.decoder.supportsCodec.useQuery,o_=q.decoder.getInfo.useQuery,s_=q.decoder.createSession.useQuery,c_=q.decoder.destroySession.useQuery,l_=q.decoder.pushPacket.useQuery,u_=q.decoder.openStream.useQuery,d_=q.decoder.pullFrames.useQuery,f_=q.decoder.pullHandles.useQuery,p_=q.decoder.getFrame.useQuery,m_=q.decoder.getShmStats.useQuery,h_=q.decoder.updateConfig.useQuery,g_=q.decoder.getStats.useQuery,__=q.decoder.listActiveSessions.useQuery,v_=q.decoder.reprobeHwaccel.useMutation,y_=q.detectionPipeline.getDeviceSettingsContribution.useQuery,b_=q.detectionPipeline.getDeviceLiveContribution.useQuery,x_=q.detectionPipeline.applyDeviceSettingsPatch.useMutation,S_=q.deviceAdoption.listCandidateFilters.useQuery,C_=q.deviceAdoption.listCandidates.useQuery,w_=q.deviceAdoption.getCandidate.useQuery,T_=q.deviceAdoption.refresh.useMutation,E_=q.deviceAdoption.adopt.useMutation,D_=q.deviceAdoption.release.useMutation,O_=q.deviceAdoption.resync.useMutation,k_=q.deviceAdoption.getStatus.useQuery,A_=q.deviceDiscovery.listDiscovered.useQuery,j_=q.deviceDiscovery.refreshDiscovery.useMutation,M_=q.deviceDiscovery.adoptDevice.useMutation,N_=q.deviceDiscovery.releaseDevice.useMutation,P_=q.deviceDiscovery.getStatus.useQuery,F_=q.deviceExport.getStatus.useQuery,I_=q.deviceExport.listSupportedDeviceKinds.useQuery,L_=q.deviceExport.listExposedDevices.useQuery,R_=q.deviceExport.exposeDevice.useMutation,z_=q.deviceExport.unexposeDevice.useMutation,B_=q.deviceExport.getDeviceSettingsContribution.useQuery,V_=q.deviceExport.getDeviceLiveContribution.useQuery,H_=q.deviceExport.applyDeviceSettingsPatch.useMutation,U_=q.deviceManager.allocateDeviceId.useMutation,W_=q.deviceManager.registerDevice.useMutation,G_=q.deviceManager.removeDevice.useMutation,K_=q.deviceManager.persistConfig.useMutation,q_=q.deviceManager.loadConfig.useQuery,J_=q.deviceManager.loadRuntimeState.useQuery,Y_=q.deviceManager.loadMeta.useQuery,X_=q.deviceManager.setName.useMutation,Z_=q.deviceManager.setLocation.useMutation,Q_=q.deviceManager.setType.useMutation,$_=q.deviceManager.setIntegrationId.useMutation,ev=q.deviceManager.setLinkDeviceId.useMutation,tv=q.deviceManager.setPrimaryChildEntityId.useMutation,nv=q.deviceManager.setChildLayout.useMutation,rv=q.deviceManager.setDeviceLinks.useMutation,iv=q.deviceManager.getWireableFields.useQuery,av=q.deviceManager.setRole.useMutation,ov=q.deviceManager.applyInitialMeta.useMutation,sv=q.deviceManager.setMetadata.useMutation,cv=q.deviceManager.listLocations.useQuery,lv=q.deviceManager.addLocation.useMutation,uv=q.deviceManager.removeLocation.useMutation,dv=q.deviceManager.setDisabled.useMutation,fv=q.deviceManager.listPersistedByAddon.useQuery,pv=q.deviceManager.listAll.useQuery,mv=q.deviceManager.getDevice.useQuery,hv=q.deviceManager.getChildren.useQuery,gv=q.deviceManager.getStreamSources.useQuery,_v=q.deviceManager.getConfigSchema.useQuery,vv=q.deviceManager.getSettingsSchema.useQuery,yv=q.deviceManager.updateConfig.useMutation,bv=q.deviceManager.enable.useMutation,xv=q.deviceManager.disable.useMutation,Sv=q.deviceManager.remove.useMutation,Cv=q.deviceManager.removeByIntegration.useMutation,wv=q.deviceManager.getStreamProfileMap.useQuery,Tv=q.deviceManager.setStreamProfileMap.useMutation,Ev=q.deviceManager.probeStreams.useMutation,Dv=q.deviceManager.getBindings.useQuery,Ov=q.deviceManager.getAllBindings.useQuery,kv=q.deviceManager.setWrapperActive.useMutation,Av=q.deviceManager.listWrappersForCap.useQuery,jv=q.deviceManager.listBindableCapsForDeviceType.useQuery,Mv=q.deviceManager.getDeviceSettingsAggregate.useQuery,Nv=q.deviceManager.getDeviceLiveInfoAggregate.useQuery,Pv=q.deviceManager.getDeviceAggregate.useQuery,Fv=q.deviceManager.runDeviceAction.useMutation,Iv=q.deviceManager.updateDeviceField.useMutation,Lv=q.deviceManager.updateDeviceFieldsBatch.useMutation,Rv=q.deviceManager.discoverDevices.useMutation,zv=q.deviceManager.adoptDevice.useMutation,Bv=q.deviceManager.getCreationSchema.useQuery,Vv=q.deviceManager.createDevice.useMutation,Hv=q.deviceManager.testCreationField.useMutation,Uv=q.deviceManager.adoptionListCandidates.useQuery,Wv=q.deviceManager.adoptionRefresh.useMutation,Gv=q.deviceManager.adoptionAdopt.useMutation,Kv=q.deviceManager.adoptionRelease.useMutation,qv=q.deviceManager.testField.useMutation,Jv=q.deviceManager.getDeviceStatusAggregate.useQuery,Yv=q.deviceOps.getStreamSources.useQuery,Xv=q.deviceOps.getConfigEntries.useQuery,Zv=q.deviceOps.setConfig.useMutation,Qv=q.deviceOps.runAction.useMutation,$v=q.deviceOps.removeDevice.useMutation,ey=q.deviceOps.getSettingsSchema.useQuery,ty=q.deviceOps.getRawState.useQuery,ny=q.deviceProvider.start.useMutation,ry=q.deviceProvider.stop.useMutation,iy=q.deviceProvider.getStatus.useQuery,ay=q.deviceProvider.getDevices.useQuery,oy=q.deviceProvider.supportsDiscovery.useQuery,sy=q.deviceProvider.discoverDevices.useMutation,cy=q.deviceProvider.adoptDiscoveredDevice.useMutation,ly=q.deviceProvider.supportsManualCreation.useQuery,uy=q.deviceProvider.getChildCreationSchema.useQuery,dy=q.deviceProvider.createDevice.useMutation,fy=q.deviceProvider.testCreationField.useMutation,py=q.deviceState.getSnapshot.useQuery,my=q.deviceState.getCapSlice.useQuery,hy=q.deviceState.getAllSnapshots.useQuery,gy=q.deviceState.setCapSlice.useMutation,_y=q.deviceStatus.getStatus.useQuery,vy=q.doorbell.getStatus.useQuery,yy=q.enumSensor.getStatus.useQuery,by=q.eventEmitter.getStatus.useQuery,xy=q.events.getEvents.useQuery,Sy=q.events.getEventThumbnail.useQuery,Cy=q.events.getEventClipUrl.useQuery,wy=q.faceGallery.listIdentities.useQuery,Ty=q.faceGallery.createIdentity.useMutation,Ey=q.faceGallery.renameIdentity.useMutation,Dy=q.faceGallery.deleteIdentity.useMutation,Oy=q.faceGallery.listIdentitySamples.useQuery,ky=q.faceGallery.removeSample.useMutation,Ay=q.faceGallery.listRecentFaces.useQuery,jy=q.faceGallery.getFaceByTrack.useQuery,My=q.faceGallery.getFaceMedia.useQuery,Ny=q.faceGallery.assignFace.useMutation,Py=q.faceGallery.unassignFace.useMutation,Fy=q.faceGallery.deleteFace.useMutation,Iy=q.faceGallery.assignFaces.useMutation,Ly=q.faceGallery.unassignFaces.useMutation,Ry=q.faceGallery.suggestFaceClusters.useQuery,zy=q.fanControl.setPercentage.useMutation,By=q.fanControl.setPreset.useMutation,Vy=q.fanControl.setDirection.useMutation,Hy=q.fanControl.setOscillating.useMutation,Uy=q.fanControl.getStatus.useQuery,Wy=q.featureProbe.getStatus.useQuery,Gy=q.flood.getStatus.useQuery,Ky=q.gas.getStatus.useQuery,qy=q.humidifier.setOn.useMutation,Jy=q.humidifier.setTargetHumidity.useMutation,Yy=q.humidifier.setMode.useMutation,Xy=q.humidifier.getStatus.useQuery,Zy=q.humiditySensor.getStatus.useQuery,Qy=q.image.getStatus.useQuery,$y=q.integrations.list.useQuery,eb=q.integrations.get.useQuery,tb=q.integrations.getByAddonId.useQuery,nb=q.integrations.create.useMutation,rb=q.integrations.update.useMutation,ib=q.integrations.delete.useMutation,ab=q.integrations.getSettings.useQuery,ob=q.integrations.setSettings.useMutation,sb=q.integrations.getAvailableTypes.useQuery,cb=q.integrations.testConnection.useMutation,lb=q.intercom.startSession.useMutation,ub=q.intercom.handleAnswer.useMutation,db=q.intercom.stopSession.useMutation,fb=q.intercom.startTalkSession.useMutation,pb=q.intercom.pushTalkAudio.useMutation,mb=q.intercom.endTalkSession.useMutation,hb=q.intercom.getStatus.useQuery,gb=q.lawnMowerControl.startMowing.useMutation,_b=q.lawnMowerControl.pause.useMutation,vb=q.lawnMowerControl.dock.useMutation,yb=q.lawnMowerControl.getStatus.useQuery,bb=q.localNetwork.list.useQuery,xb=q.localNetwork.getPreferred.useQuery,Sb=q.localNetwork.getConnectionEndpoints.useQuery,Cb=q.localNetwork.getAllowedAddresses.useQuery,wb=q.localNetwork.setAllowedAddresses.useMutation,Tb=q.localNetwork.resetAllowlistToBestMatch.useMutation,Eb=q.lockControl.lock.useMutation,Db=q.lockControl.unlock.useMutation,Ob=q.lockControl.open.useMutation,kb=q.lockControl.getStatus.useQuery,Ab=q.mediaPlayer.play.useMutation,jb=q.mediaPlayer.pause.useMutation,Mb=q.mediaPlayer.stop.useMutation,Nb=q.mediaPlayer.next.useMutation,Pb=q.mediaPlayer.previous.useMutation,Fb=q.mediaPlayer.seek.useMutation,Ib=q.mediaPlayer.setVolume.useMutation,Lb=q.mediaPlayer.setMute.useMutation,Rb=q.mediaPlayer.setShuffle.useMutation,zb=q.mediaPlayer.setRepeat.useMutation,Bb=q.mediaPlayer.selectSource.useMutation,Vb=q.mediaPlayer.playMedia.useMutation,Hb=q.mediaPlayer.getStatus.useQuery,Ub=q.meshNetwork.getStatus.useQuery,Wb=q.meshNetwork.join.useMutation,Gb=q.meshNetwork.startLogin.useMutation,Kb=q.meshNetwork.leave.useMutation,qb=q.meshNetwork.logout.useMutation,Jb=q.meshNetwork.listPeers.useQuery,Yb=q.meshNetwork.testConnection.useMutation,Xb=q.metricsProvider.collectSnapshot.useQuery,Zb=q.metricsProvider.getCached.useQuery,Qb=q.metricsProvider.getCurrent.useQuery,$b=q.metricsProvider.getDiskSpace.useQuery,ex=q.metricsProvider.getGpuInfo.useQuery,tx=q.metricsProvider.getCpuTemperature.useQuery,nx=q.metricsProvider.getProcessStats.useQuery,rx=q.metricsProvider.listAddonInstances.useQuery,ix=q.metricsProvider.getAddonStats.useQuery,ax=q.metricsProvider.listNodeProcesses.useQuery,ox=q.metricsProvider.killProcess.useMutation,sx=q.motion.isDetected.useQuery,cx=q.motion.getStatus.useQuery,lx=q.motionDetection.analyze.useMutation,ux=q.motionDetection.removeCamera.useMutation,dx=q.motionDetection.reset.useMutation,fx=q.motionDetection.getDeviceSettingsContribution.useQuery,px=q.motionDetection.getDeviceLiveContribution.useQuery,mx=q.motionDetection.applyDeviceSettingsPatch.useMutation,hx=q.motionTrigger.setMotionTrigger.useMutation,gx=q.motionTrigger.getStatus.useQuery,_x=q.motionZones.getOptions.useQuery,vx=q.motionZones.setZone.useMutation,yx=q.motionZones.getStatus.useQuery,bx=q.mqttBroker.listBrokers.useQuery,xx=q.mqttBroker.getBrokerConfig.useQuery,Sx=q.mqttBroker.addBroker.useMutation,Cx=q.mqttBroker.removeBroker.useMutation,wx=q.mqttBroker.testConnection.useMutation,Tx=q.mqttBroker.startEmbeddedBroker.useMutation,Ex=q.mqttBroker.stopEmbeddedBroker.useMutation,Dx=q.mqttBroker.getStatus.useQuery,Ox=q.nativeObjectDetection.setEnabled.useMutation,kx=q.nativeObjectDetection.getStatus.useQuery,Ax=q.networkAccess.start.useMutation,jx=q.networkAccess.stop.useMutation,Mx=q.networkAccess.getEndpoint.useQuery,Nx=q.networkAccess.getStatus.useQuery,Px=q.networkAccess.listEndpoints.useQuery,Fx=q.networkQuality.getDeviceStats.useQuery,Ix=q.networkQuality.getAllStats.useQuery,Lx=q.networkQuality.reportClientStats.useMutation,Rx=q.nodes.topology.useQuery,zx=q.nodes.deployAddon.useMutation,Bx=q.nodes.undeployAddon.useMutation,Vx=q.nodes.restartAddon.useMutation,Hx=q.nodes.restartProcess.useMutation,Ux=q.nodes.restartNode.useMutation,Wx=q.nodes.shutdownNode.useMutation,Gx=q.nodes.renameNode.useMutation,Kx=q.nodes.clusterAddonStatus.useQuery,qx=q.nodes.getCapUsageGraph.useQuery,Jx=q.nodes.getNodeAddons.useQuery,Yx=q.nodes.setProcessLogLevel.useMutation,Xx=q.nodes.executeQuery.useMutation,Zx=q.notificationOutput.send.useMutation,Qx=q.notificationOutput.sendTest.useMutation,$x=q.notifier.send.useMutation,eS=q.notifier.cancel.useMutation,tS=q.notifier.getStatus.useQuery,nS=q.numericSensor.getStatus.useQuery,rS=q.osd.setOverlay.useMutation,iS=q.osd.getStatus.useQuery,aS=q.pipelineAnalytics.getActiveTracks.useQuery,oS=q.pipelineAnalytics.getTrack.useQuery,sS=q.pipelineAnalytics.listTracks.useQuery,cS=q.pipelineAnalytics.clearTracks.useMutation,lS=q.pipelineAnalytics.getMotionEvents.useQuery,uS=q.pipelineAnalytics.getObjectEvents.useQuery,dS=q.pipelineAnalytics.getAudioEvents.useQuery,fS=q.pipelineAnalytics.getEventDensity.useQuery,pS=q.pipelineAnalytics.pruneEventsBefore.useMutation,mS=q.pipelineAnalytics.getEventMedia.useQuery,hS=q.pipelineAnalytics.getTrackMedia.useQuery,gS=q.pipelineAnalytics.getDeviceSettingsContribution.useQuery,_S=q.pipelineAnalytics.getDeviceLiveContribution.useQuery,vS=q.pipelineAnalytics.applyDeviceSettingsPatch.useMutation,yS=q.pipelineExecutor.getAvailableEngines.useQuery,bS=q.pipelineExecutor.getSelectedEngine.useQuery,xS=q.pipelineExecutor.getDefaultSteps.useQuery,SS=q.pipelineExecutor.reprobeEngine.useMutation,CS=q.pipelineExecutor.getVideoPipelineSteps.useQuery,wS=q.pipelineExecutor.setVideoPipelineSteps.useMutation,TS=q.pipelineExecutor.getSchema.useQuery,ES=q.pipelineExecutor.getGlobalSteps.useQuery,DS=q.pipelineExecutor.getGlobalPipelineConfig.useQuery,OS=q.pipelineExecutor.getOrchestratorConfigSchema.useQuery,kS=q.pipelineExecutor.listTemplates.useQuery,AS=q.pipelineExecutor.saveTemplate.useMutation,jS=q.pipelineExecutor.updateTemplate.useMutation,MS=q.pipelineExecutor.deleteTemplate.useMutation,NS=q.pipelineExecutor.getCapabilities.useQuery,PS=q.pipelineExecutor.getAddonModels.useQuery,FS=q.pipelineExecutor.downloadModel.useMutation,IS=q.pipelineExecutor.deleteModel.useMutation,LS=q.pipelineExecutor.detect.useQuery,RS=q.pipelineExecutor.runPipeline.useMutation,zS=q.pipelineExecutor.runPipelineBatch.useMutation,BS=q.pipelineExecutor.cacheFrameInPool.useMutation,VS=q.pipelineExecutor.inferCached.useMutation,HS=q.pipelineExecutor.uncacheFrame.useMutation,US=q.pipelineExecutor.getEffectiveTuning.useQuery,WS=q.pipelineExecutor.listLoadedEngines.useQuery,GS=q.pipelineExecutor.spinEngine.useMutation,KS=q.pipelineExecutor.killEngine.useMutation,qS=q.pipelineExecutor.listReferenceImages.useQuery,JS=q.pipelineExecutor.getReferenceImage.useQuery,YS=q.pipelineExecutor.getReferenceAudioFiles.useQuery,XS=q.pipelineExecutor.getReferenceAudio.useQuery,ZS=q.pipelineExecutor.getAudioCapabilities.useQuery,QS=q.pipelineExecutor.runAudioTest.useMutation,$S=q.pipelineExecutor.getDetectionConfigSchema.useQuery,eC=q.pipelineOrchestrator.assignPipeline.useMutation,tC=q.pipelineOrchestrator.unassignPipeline.useMutation,nC=q.pipelineOrchestrator.rebalance.useMutation,rC=q.pipelineOrchestrator.getPipelineAssignments.useQuery,iC=q.pipelineOrchestrator.getPipelineAssignment.useQuery,aC=q.pipelineOrchestrator.getAgentLoad.useQuery,oC=q.pipelineOrchestrator.getGlobalMetrics.useQuery,sC=q.pipelineOrchestrator.getCameraMetrics.useQuery,cC=q.pipelineOrchestrator.getCapabilityBindings.useQuery,lC=q.pipelineOrchestrator.setCapabilityBinding.useMutation,uC=q.pipelineOrchestrator.assignDecoder.useMutation,dC=q.pipelineOrchestrator.unassignDecoder.useMutation,fC=q.pipelineOrchestrator.getDecoderAssignments.useQuery,pC=q.pipelineOrchestrator.assignAudio.useMutation,mC=q.pipelineOrchestrator.unassignAudio.useMutation,hC=q.pipelineOrchestrator.getAudioAssignment.useQuery,gC=q.pipelineOrchestrator.getAudioNodeLoad.useQuery,_C=q.pipelineOrchestrator.getAudioAssignments.useQuery,vC=q.pipelineOrchestrator.getDecoderAssignment.useQuery,yC=q.pipelineOrchestrator.getAgentSettings.useQuery,bC=q.pipelineOrchestrator.listAgentSettings.useQuery,xC=q.pipelineOrchestrator.setAgentAddonDefaults.useMutation,SC=q.pipelineOrchestrator.removeAgentSettings.useMutation,CC=q.pipelineOrchestrator.getCameraSettings.useQuery,wC=q.pipelineOrchestrator.setCameraStepToggle.useMutation,TC=q.pipelineOrchestrator.getCameraStepOverrides.useQuery,EC=q.pipelineOrchestrator.setCameraStepOverride.useMutation,DC=q.pipelineOrchestrator.setCameraPipelineForAgent.useMutation,OC=q.pipelineOrchestrator.resolvePipeline.useQuery,kC=q.pipelineOrchestrator.listTemplates.useQuery,AC=q.pipelineOrchestrator.saveTemplate.useMutation,jC=q.pipelineOrchestrator.updateTemplate.useMutation,MC=q.pipelineOrchestrator.deleteTemplate.useMutation,NC=q.pipelineOrchestrator.getDeviceSettingsContribution.useQuery,PC=q.pipelineOrchestrator.getDeviceLiveContribution.useQuery,FC=q.pipelineOrchestrator.applyDeviceSettingsPatch.useMutation,IC=q.pipelineRunner.attachCamera.useMutation,LC=q.pipelineRunner.detachCamera.useMutation,RC=q.pipelineRunner.reportMotion.useMutation,zC=q.pipelineRunner.getLocalLoad.useQuery,BC=q.pipelineRunner.getLocalMetrics.useQuery,VC=q.pipelineRunner.getCameraMetrics.useQuery,HC=q.pipelineRunner.getAllCameraMetrics.useQuery,UC=q.pipelineRunner.getLocalCameras.useQuery,WC=q.plateGallery.listPlates.useQuery,GC=q.plateGallery.getPlateByTrack.useQuery,KC=q.plateGallery.getPlateMedia.useQuery,qC=q.plateGallery.searchPlates.useQuery,JC=q.plateGallery.suggestPlateClusters.useQuery,YC=q.plateGallery.correctPlateText.useMutation,XC=q.plateGallery.deletePlate.useMutation,ZC=q.powerMeter.getStatus.useQuery,QC=q.presence.getStatus.useQuery,$C=q.pressureSensor.getStatus.useQuery,ew=q.privacyMask.getOptions.useQuery,tw=q.privacyMask.setMask.useMutation,nw=q.privacyMask.getStatus.useQuery,rw=q.ptz.move.useMutation,iw=q.ptz.continuousMove.useMutation,aw=q.ptz.stop.useMutation,ow=q.ptz.getPresets.useQuery,sw=q.ptz.goToPreset.useMutation,cw=q.ptz.savePreset.useMutation,lw=q.ptz.deletePreset.useMutation,uw=q.ptz.getOptions.useQuery,dw=q.ptz.goHome.useMutation,fw=q.ptz.getPosition.useQuery,pw=q.ptz.setAutofocus.useMutation,mw=q.ptz.getStatus.useQuery,hw=q.ptzAutotrack.getStatus.useQuery,gw=q.ptzAutotrack.setEnabled.useMutation,_w=q.ptzAutotrack.getSettings.useQuery,vw=q.ptzAutotrack.setSettings.useMutation,yw=q.reboot.reboot.useMutation,bw=q.recording.getAvailability.useQuery,xw=q.recording.getDaysWithRecordings.useQuery,Sw=q.recording.getPlaybackManifest.useQuery,Cw=q.recording.getStorageUsage.useQuery,ww=q.recording.getDeviceConfig.useQuery,Tw=q.recording.locateSegment.useQuery,Ew=q.recording.readSegmentBytes.useQuery,Dw=q.recording.setDeviceConfig.useMutation,Ow=q.recording.rescanStorage.useMutation,kw=q.recording.pruneFootage.useMutation,Aw=q.recording.getStatus.useQuery,jw=q.recording.getDeviceSettingsContribution.useQuery,Mw=q.recording.getDeviceLiveContribution.useQuery,Nw=q.recording.applyDeviceSettingsPatch.useMutation,Pw=q.scriptRunner.run.useMutation,Fw=q.scriptRunner.stop.useMutation,Iw=q.scriptRunner.getStatus.useQuery,Lw=q.settingsStore.get.useQuery,Rw=q.settingsStore.set.useMutation,zw=q.settingsStore.query.useQuery,Bw=q.settingsStore.insert.useMutation,Vw=q.settingsStore.update.useMutation,Hw=q.settingsStore.delete.useMutation,Uw=q.settingsStore.count.useQuery,Ww=q.settingsStore.histogram.useQuery,Gw=q.settingsStore.isEmpty.useQuery,Kw=q.settingsStore.declareCollection.useMutation,qw=q.smoke.getStatus.useQuery,Jw=q.snapshot.getSnapshot.useQuery,Yw=q.snapshot.invalidateCache.useMutation,Xw=q.snapshot.getStatus.useQuery,Zw=q.snapshot.getDeviceSettingsContribution.useQuery,Qw=q.snapshot.getDeviceLiveContribution.useQuery,$w=q.snapshot.applyDeviceSettingsPatch.useMutation,eT=q.snapshotProvider.supportsDevice.useQuery,tT=q.snapshotProvider.getSnapshot.useQuery,nT=q.storage.resolve.useQuery,rT=q.storage.write.useMutation,iT=q.storage.read.useQuery,aT=q.storage.exists.useQuery,oT=q.storage.list.useQuery,sT=q.storage.delete.useMutation,cT=q.storage.getAvailableSpace.useQuery,lT=q.storage.beginUpload.useMutation,uT=q.storage.writeChunk.useMutation,dT=q.storage.finalizeUpload.useMutation,fT=q.storage.abortUpload.useMutation,pT=q.storage.beginDownload.useMutation,mT=q.storage.readChunk.useQuery,hT=q.storage.endDownload.useMutation,gT=q.storage.listLocations.useQuery,_T=q.storage.getDefaultLocation.useQuery,vT=q.storage.listLocationDeclarations.useQuery,yT=q.storage.upsertLocation.useMutation,bT=q.storage.deleteLocation.useMutation,xT=q.storage.testLocation.useQuery,ST=q.storage.listProviders.useQuery,CT=q.storage.testConfig.useQuery,wT=q.streamBroker.publishCameraStream.useMutation,TT=q.streamBroker.retractCameraStream.useMutation,ET=q.streamBroker.assignProfile.useMutation,DT=q.streamBroker.unassignProfile.useMutation,OT=q.streamBroker.listAllCameraStreams.useQuery,kT=q.streamBroker.listAllProfileSlots.useQuery,AT=q.streamBroker.getBrokerStats.useQuery,jT=q.streamBroker.probeStream.useMutation,MT=q.streamBroker.listClients.useQuery,NT=q.streamBroker.killClient.useMutation,PT=q.streamBroker.restartProfile.useMutation,FT=q.streamBroker.getStreamUrl.useQuery,IT=q.streamBroker.getStreamWithCodec.useMutation,LT=q.streamBroker.releaseStreamWithCodec.useMutation,RT=q.streamBroker.subscribeAudioChunks.useMutation,zT=q.streamBroker.pullAudioChunks.useQuery,BT=q.streamBroker.unsubscribeAudioChunks.useMutation,VT=q.streamBroker.subscribeFrames.useMutation,HT=q.streamBroker.pullFrameHandles.useQuery,UT=q.streamBroker.unsubscribeFrames.useMutation,WT=q.streamBroker.setPreBufferDuration.useMutation,GT=q.streamBroker.getPreBufferInfo.useQuery,KT=q.streamBroker.getRtspPort.useQuery,qT=q.streamBroker.getAllRtspEntries.useQuery,JT=q.streamBroker.getRtspEntry.useQuery,YT=q.streamBroker.regenerateRtspToken.useMutation,XT=q.streamBroker.setRtspEnabled.useMutation,ZT=q.streamBroker.isRtspEnabled.useQuery,QT=q.streamBroker.getDeviceSettingsContribution.useQuery,$T=q.streamBroker.getDeviceLiveContribution.useQuery,eE=q.streamBroker.applyDeviceSettingsPatch.useMutation,tE=q.streamCatalog.getCatalog.useQuery,nE=q.streamParams.getOptions.useQuery,rE=q.streamParams.setProfile.useMutation,iE=q.streamParams.getConfigSchema.useQuery,aE=q.streamParams.getStatus.useQuery,oE=q.switch.setState.useMutation,sE=q.switch.getStatus.useQuery,cE=q.system.info.useQuery,lE=q.system.health.useQuery,uE=q.system.featureFlags.useQuery,dE=q.system.networkAddresses.useQuery,fE=q.system.getRetentionConfig.useQuery,pE=q.system.setRetentionConfig.useMutation,mE=q.system.forceRetentionCleanup.useMutation,hE=q.tamper.getStatus.useQuery,gE=q.temperatureSensor.getStatus.useQuery,_E=q.toast.onToast.useSubscription,vE=q.turnProvider.getTurnServers.useQuery,yE=q.update.installUpdate.useMutation,bE=q.update.getStatus.useQuery,xE=q.userManagement.listUsers.useQuery,SE=q.userManagement.createUser.useMutation,CE=q.userManagement.updateUser.useMutation,wE=q.userManagement.deleteUser.useMutation,TE=q.userManagement.resetPassword.useMutation,EE=q.userManagement.setUserScopes.useMutation,DE=q.userManagement.validateCredentials.useMutation,OE=q.userManagement.listApiKeys.useQuery,kE=q.userManagement.createApiKey.useMutation,AE=q.userManagement.revokeApiKey.useMutation,jE=q.userManagement.validateApiKey.useMutation,ME=q.userManagement.createScopedToken.useMutation,NE=q.userManagement.revokeScopedToken.useMutation,PE=q.userManagement.validateScopedToken.useQuery,FE=q.userManagement.listScopedTokens.useQuery,IE=q.userManagement.setupTotp.useMutation,LE=q.userManagement.confirmTotp.useMutation,RE=q.userManagement.disableTotp.useMutation,zE=q.userManagement.getTotpStatus.useQuery,BE=q.userManagement.verifyTotp.useMutation,VE=q.userManagement.oauthIssueCode.useMutation,HE=q.userManagement.oauthExchangeCode.useMutation,UE=q.userManagement.oauthRefresh.useMutation,WE=q.userManagement.oauthVerifyAccessToken.useQuery,GE=q.userManagement.listOauthSessions.useQuery,KE=q.userManagement.revokeOauthSession.useMutation,qE=q.vacuumControl.start.useMutation,JE=q.vacuumControl.pause.useMutation,YE=q.vacuumControl.stop.useMutation,XE=q.vacuumControl.returnToBase.useMutation,ZE=q.vacuumControl.locate.useMutation,QE=q.vacuumControl.setFanSpeed.useMutation,$E=q.vacuumControl.getStatus.useQuery,eD=q.valve.open.useMutation,tD=q.valve.close.useMutation,nD=q.valve.stop.useMutation,rD=q.valve.setPosition.useMutation,iD=q.valve.getStatus.useQuery,aD=q.vibration.getStatus.useQuery,oD=q.videoclips.listClips.useQuery,sD=q.videoclips.getClipPlayback.useQuery,cD=q.waterHeater.setTargetTemp.useMutation,lD=q.waterHeater.setOperationMode.useMutation,uD=q.waterHeater.setAway.useMutation,dD=q.waterHeater.getStatus.useQuery,fD=q.weather.getStatus.useQuery,pD=q.webrtcSession.listStreams.useQuery,mD=q.webrtcSession.createSession.useMutation,hD=q.webrtcSession.handleOffer.useMutation,gD=q.webrtcSession.handleAnswer.useMutation,_D=q.webrtcSession.addIceCandidate.useMutation,vD=q.webrtcSession.getIceCandidates.useQuery,yD=q.webrtcSession.closeSession.useMutation,bD=q.webrtcSession.hasAdaptiveBitrate.useQuery,xD=q.webrtcSession.getSessionState.useQuery,SD=q.zoneAnalytics.getCurrentSnapshot.useQuery,CD=q.zoneAnalytics.getZoneHistory.useQuery,wD=q.zoneAnalytics.getCameraHistory.useQuery,TD=q.zoneAnalytics.getUnzonedHistory.useQuery,ED=q.zoneRules.listRules.useQuery,DD=q.zoneRules.setRules.useMutation,OD=q.zones.listZones.useQuery,kD=q.zones.addZone.useMutation,AD=q.zones.removeZone.useMutation,jD=q.zones.updateZone.useMutation;function MD(e,t){return t===void 0?Number.isInteger(e)?String(e):e.toFixed(1):e.toFixed(t)}var ND={kind:`binary`,field:`on`,onLabel:`Low`,offLabel:`Normal`,getSliceHandle:e=>e.binary};function PD(e){return e===`battery-sensor`}function FD(e,t){if(!LD(e))return!1;let n=e[t];if(typeof n!=`number`)return!1;let r=e.lastFetchedAt;return!(n===0&&r===0)}var ID={"temperature-sensor":{kind:`numeric`,field:`celsius`,canonicalUnit:`°C`,getSliceHandle:e=>e.temperatureSensor},"humidity-sensor":{kind:`numeric`,field:`percent`,canonicalUnit:`%`,getSliceHandle:e=>e.humiditySensor},"ambient-light-sensor":{kind:`numeric`,field:`lux`,canonicalUnit:`lx`,getSliceHandle:e=>e.ambientLightSensor},"pressure-sensor":{kind:`numeric`,field:`hpa`,canonicalUnit:`hPa`,getSliceHandle:e=>e.pressureSensor},"numeric-sensor":{kind:`numeric`,field:`value`,getSliceHandle:e=>e.numericSensor},"power-sensor":{kind:`numeric`,field:`watts`,canonicalUnit:`W`,getSliceHandle:e=>e.powerMeter},"energy-sensor":{kind:`numeric`,field:`kwhTotal`,canonicalUnit:`kWh`,getSliceHandle:e=>e.powerMeter},"voltage-sensor":{kind:`numeric`,field:`volts`,canonicalUnit:`V`,getSliceHandle:e=>e.powerMeter},"current-sensor":{kind:`numeric`,field:`amps`,canonicalUnit:`A`,getSliceHandle:e=>e.powerMeter},"battery-sensor":{kind:`numeric`,field:`value`,canonicalUnit:`%`,getSliceHandle:e=>e.numericSensor},"generic-sensor":{kind:`numeric`,field:`value`,getSliceHandle:e=>e.numericSensor},"motion-sensor":{kind:`binary`,field:`detected`,onLabel:`Detected`,offLabel:`Clear`,getSliceHandle:e=>e.motion},"pir-sensor":{kind:`binary`,field:`detected`,onLabel:`Detected`,offLabel:`Clear`,getSliceHandle:e=>e.motion},"contact-sensor":{kind:`binary`,field:`entryOpen`,onLabel:`Open`,offLabel:`Closed`,getSliceHandle:e=>e.contact},"smoke-sensor":{kind:`binary`,field:`detected`,onLabel:`Smoke!`,offLabel:`Clear`,getSliceHandle:e=>e.smoke},"leak-sensor":{kind:`binary`,field:`flooded`,onLabel:`Leak!`,offLabel:`Dry`,getSliceHandle:e=>e.flood},"co-sensor":{kind:`binary`,field:`detected`,onLabel:`CO!`,offLabel:`Clear`,getSliceHandle:e=>e.carbonMonoxide},"binary-sensor":{kind:`binary`,field:`on`,onLabel:`On`,offLabel:`Off`,getSliceHandle:e=>e.binary},presence:{kind:`presence`,getSliceHandle:e=>e.presence},"enum-sensor":{kind:`string`,getSliceHandle:e=>e.enumSensor},"datetime-sensor":{kind:`datetime`,format:`datetime`,getSliceHandle:e=>e.enumSensor}};function LD(e){return typeof e==`object`&&!!e}function RD(e){return typeof e==`object`&&!!e}function zD(e){return typeof e==`object`&&!!e&&`state`in e&&typeof e.state==`string`}function BD(e){return typeof e==`object`&&!!e&&`value`in e&&typeof e.value==`string`}function VD(e){if(typeof e!=`object`||!e)return;let t=e.format;if(t===`date`||t===`time`||t===`datetime`)return t}function HD(e){return e===`home`?`Home`:e===`not_home`?`Away`:e.charAt(0).toUpperCase()+e.slice(1)}function UD({trpc:e,device:t}){let n=t.role==null?void 0:ID[t.role],r=PD(t.role),i=Xf(e,t.id),a=Zf(i!==null&&n!==void 0?n.getSliceHandle(i.state):void 0),o=Zf(i!==null&&n?.kind===`numeric`?i.state.enumSensor:void 0),s=Zf(i!==null&&r?i.state.binary:void 0),c=r&&n?.kind===`numeric`&&!FD(a,n.field)&&s!==void 0,l=c?ND:n,u=c?s:a;if(l===void 0||u===void 0)return null;if(l.kind===`numeric`){if(!LD(u))return null;let e=u[l.field];if(typeof e!=`number`)return null;let t=u.lastFetchedAt,n=e===0&&t===0;if(n&&BD(o)&&o.value!==``)return v(`span`,{className:G(`inline-flex items-baseline text-xs text-foreground`),children:o.value});if(n)return null;let r=u,i=(typeof r.unit==`string`?r.unit:void 0)??l.canonicalUnit??``,a=MD(e,typeof r.precision==`number`?r.precision:void 0);return T(`span`,{className:G(`inline-flex items-baseline gap-0.5 tabular-nums text-xs text-foreground`),children:[v(`span`,{children:a}),i&&v(`span`,{className:`text-foreground-subtle`,children:i})]})}if(l.kind===`binary`){if(!RD(u))return null;let e=!!u[l.field],t=e?l.onLabel:l.offLabel;return v(`span`,{className:G(`inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium`,e?`bg-warning/15 text-warning`:`bg-surface-subtle text-foreground-subtle`),children:t})}if(l.kind===`string`)return!BD(u)||u.value===``?null:v(`span`,{className:G(`inline-flex items-baseline text-xs text-foreground`),children:u.value});if(l.kind===`datetime`){if(!BD(u)||u.value===``)return null;let e=VD(u)??l.format,t=In(u.value,e);return v(`span`,{className:G(`inline-flex items-baseline text-xs text-foreground`),children:t})}if(!zD(u))return null;let d=HD(u.state);return v(`span`,{className:G(`inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium`,u.state===`home`?`bg-success/15 text-success`:`bg-surface-subtle text-foreground-subtle`),children:d})}function WD(e){return{id:e.id,stableId:e.stableId,addonId:e.addonId,type:e.type,name:e.name,online:e.online,disabled:e.disabled,parentDeviceId:e.parentDeviceId,role:e.role??void 0,features:e.features}}function GD({trpc:e,deviceId:t}){let{data:n}=mv({deviceId:t},{staleTime:6e4});return n===void 0?null:v(UD,{trpc:e,device:WD(n)})}function KD(e){return typeof e==`object`&&!!e}function qD(e){return typeof e==`object`&&!!e}function JD(e){return typeof e==`object`&&!!e&&`state`in e&&typeof e.state==`string`}function YD(e){return e===`home`?`Home`:e===`not_home`?`Away`:e.charAt(0).toUpperCase()+e.slice(1)}var XD={low:`bg-danger`,medium:`bg-warning`,high:`bg-success`};function ZD(e){return e<=20?`low`:e<=50?`medium`:`high`}function QD({percent:e}){let t=Math.min(100,Math.max(0,e)),n=ZD(t);return v(`div`,{"data-testid":`battery-bar`,"data-band":n,className:`h-2 w-24 overflow-hidden rounded-full bg-border`,children:v(`div`,{className:G(`h-full rounded-full transition-all`,XD[n]),style:{width:`${t}%`}})})}function $D({trpc:e,device:t}){let n=t.role==null?void 0:ID[t.role],r=PD(t.role),i=Xf(e,t.id),a=Zf(i!==null&&n!==void 0?n.getSliceHandle(i.state):void 0),o=Zf(i!==null&&r?i.state.binary:void 0),s=r&&n?.kind===`numeric`&&!FD(a,n.field)&&o!==void 0,c=s?ND:n,l=s?o:a;if(c===void 0||l===void 0)return T(`div`,{className:`flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4 min-h-[96px]`,children:[v(`span`,{className:`text-sm text-foreground-subtle`,children:t.name}),v(`span`,{className:`text-xs text-foreground-subtle italic`,children:`Awaiting state…`})]});if(c.kind===`numeric`){if(!KD(l))return null;let e=l[c.field];if(typeof e!=`number`)return null;let n=l,i=(typeof n.unit==`string`?n.unit:void 0)??c.canonicalUnit??``;return T(`div`,{className:`flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4`,children:[T(`div`,{className:`flex items-baseline gap-1`,children:[v(`span`,{className:`text-3xl font-semibold tabular-nums text-foreground`,children:MD(e,typeof n.precision==`number`?n.precision:void 0)}),i&&v(`span`,{className:`text-base text-foreground-subtle`,children:i})]}),r&&v(QD,{percent:e}),v(`span`,{className:`text-sm text-foreground-subtle`,children:t.name})]})}if(c.kind===`binary`){if(!qD(l))return null;let e=!!l[c.field],n=e?c.onLabel:c.offLabel;return T(`div`,{className:`flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4`,children:[v(`span`,{className:G(`inline-flex items-center rounded px-3 py-1.5 text-lg font-semibold`,e?`bg-warning/15 text-warning`:`bg-surface-subtle text-foreground-subtle`),children:n}),v(`span`,{className:`text-sm text-foreground-subtle`,children:t.name})]})}if(c.kind===`datetime`){if(!BD(l))return null;if(l.value===``)return T(`div`,{className:`flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4 min-h-[96px]`,children:[v(`span`,{className:`text-sm text-foreground-subtle`,children:t.name}),v(`span`,{className:`text-xs text-foreground-subtle italic`,children:`Awaiting state…`})]});let e=VD(l)??c.format;return T(`div`,{className:`flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4`,children:[v(`span`,{className:`text-3xl font-semibold tabular-nums text-foreground`,children:In(l.value,e)}),v(`span`,{className:`text-sm text-foreground-subtle`,children:t.name})]})}if(c.kind===`string`)return!BD(l)||l.value===``?null:T(`div`,{className:`flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4`,children:[v(`span`,{className:`text-xl font-semibold text-foreground`,children:l.value}),v(`span`,{className:`text-sm text-foreground-subtle`,children:t.name})]});if(!JD(l))return null;let u=YD(l.state);return T(`div`,{className:`flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4`,children:[v(`span`,{className:G(`inline-flex items-center rounded px-3 py-1.5 text-lg font-semibold`,l.state===`home`?`bg-success/15 text-success`:`bg-surface-subtle text-foreground-subtle`),children:u}),v(`span`,{className:`text-sm text-foreground-subtle`,children:t.name})]})}function eO({trpc:e,deviceId:t}){let{data:n}=mv({deviceId:t},{staleTime:6e4});return n===void 0?null:v($D,{trpc:e,device:n})}function tO(e){return e===void 0||e.inProgress?!1:e.availableVersion!==null&&e.currentVersion!==null&&e.availableVersion!==e.currentVersion}function nO(e,t){return $f({trpc:e,deviceId:t,cap:e=>e.update,slice:e=>e.state.update})}function rO({trpc:e,deviceId:t}){let{cap:n,slice:r}=nO(e,t);return n===void 0?null:r?.inProgress?T(`span`,{className:`inline-flex items-center gap-1 text-xs text-foreground-subtle`,children:[v(el,{className:`h-3.5 w-3.5 animate-spin`}),`Updating…`]}):tO(r)?T(`span`,{className:`inline-flex items-center gap-1 rounded bg-warning/15 px-1.5 py-0.5 text-[10px] font-medium text-warning`,children:[v(wc,{className:`h-3 w-3`}),`Update`]}):T(`span`,{className:`inline-flex items-center gap-1 text-[10px] text-foreground-subtle`,children:[v(Ys,{className:`h-3 w-3 text-success`}),r?.currentVersion??`Up to date`]})}function iO({trpc:e,deviceId:t}){let{cap:n,slice:r,available:i}=nO(e,t);if(n===void 0)return null;let a=r?.inProgress===!0,o=tO(r),s=r?.currentVersion??`—`,c=()=>{!i||n===void 0||!o||n.installUpdate({})};return T(`div`,{className:`flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4`,children:[T(`div`,{className:`flex items-baseline gap-1.5`,children:[v(`span`,{className:`text-3xl font-semibold tabular-nums text-foreground`,children:s}),o&&r?.availableVersion!=null&&T(E,{children:[v(`span`,{className:`text-base text-foreground-subtle`,children:`→`}),v(`span`,{className:`text-base font-medium text-warning tabular-nums`,children:r.availableVersion})]})]}),a?T(`span`,{className:`inline-flex items-center gap-1.5 rounded px-3 py-1.5 text-sm font-medium text-foreground-subtle`,children:[v(el,{className:`h-4 w-4 animate-spin`}),`Installing…`]}):o?T(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),c()},disabled:!i,className:`inline-flex items-center gap-1.5 rounded-lg bg-primary px-4 py-1.5 text-sm font-medium text-primary-foreground shadow-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed`,children:[v(wc,{className:`h-4 w-4`}),`Install update`]}):T(`span`,{className:`inline-flex items-center gap-1.5 rounded bg-success/15 px-3 py-1 text-sm font-medium text-success`,children:[v(Ys,{className:`h-4 w-4`}),`Up to date`]}),r?.state!=null&&r.state!==``&&v(`span`,{className:`text-[10px] text-foreground-subtle`,children:r.state})]})}function aO(e){switch(e){case`cleaning`:return{label:`Cleaning`,tone:`text-primary`};case`paused`:return{label:`Paused`,tone:`text-warning`};case`returning`:return{label:`Returning`,tone:`text-primary`};case`docked`:return{label:`Docked`,tone:`text-success`};case`idle`:return{label:`Idle`,tone:`text-foreground-subtle`};case`error`:return{label:`Error`,tone:`text-destructive`};case void 0:return{label:`Unknown`,tone:`text-foreground-subtle`}}}function oO(e,t){return $f({trpc:e,deviceId:t,cap:e=>e.vacuumControl,slice:e=>e.state.vacuumControl})}function sO({label:e,busy:t,active:n,onClick:r,children:i}){return v(`button`,{type:`button`,"aria-label":e,title:e,disabled:t,onClick:e=>{e.stopPropagation(),r()},className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,n&&`bg-primary text-primary-foreground`,t&&`opacity-40 cursor-not-allowed`),children:i})}function cO(e){switch(e){case`cleaning`:return{glow:`bg-primary/15`,accent:`text-primary`,docked:!1,active:!0};case`returning`:return{glow:`bg-primary/10`,accent:`text-primary`,docked:!1,active:!0};case`docked`:return{glow:`bg-success/10`,accent:`text-success`,docked:!0,active:!1};case`paused`:return{glow:`bg-warning/10`,accent:`text-warning`,docked:!1,active:!1};case`error`:return{glow:`bg-destructive/10`,accent:`text-destructive`,docked:!1,active:!1};case`idle`:return{glow:`bg-transparent`,accent:`text-foreground-subtle`,docked:!1,active:!1};case void 0:return{glow:`bg-transparent`,accent:`text-foreground-subtle`,docked:!1,active:!1}}}function lO({state:e}){let t=cO(e);return T(`div`,{"aria-hidden":`true`,className:`relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0`,style:{boxShadow:`inset 0 0 0 2px rgba(255,255,255,.06)`},children:[v(`div`,{className:G(`absolute inset-0 transition-colors duration-300`,t.glow)}),v(`div`,{className:G(`absolute inset-0 flex items-center justify-center`,t.accent),children:T(`svg`,{viewBox:`0 0 100 100`,className:`w-20 h-20`,fill:`none`,children:[t.docked&&v(`rect`,{x:`34`,y:`80`,width:`32`,height:`8`,rx:`2`,fill:`currentColor`,opacity:`0.35`}),t.active&&v(`circle`,{cx:`50`,cy:`50`,r:`44`,stroke:`currentColor`,strokeWidth:`2`,opacity:`0.4`,className:`animate-ping`,style:{transformOrigin:`center`}}),v(`circle`,{cx:`50`,cy:`50`,r:`34`,fill:`currentColor`,fillOpacity:`0.12`,stroke:`currentColor`,strokeWidth:`2.5`}),v(`path`,{d:`M 24 42 A 34 34 0 0 1 76 42`,stroke:`currentColor`,strokeWidth:`3`,opacity:`0.55`,strokeLinecap:`round`}),v(`circle`,{cx:`50`,cy:`50`,r:`9`,fill:`currentColor`,fillOpacity:`0.25`,stroke:`currentColor`,strokeWidth:`2`}),v(`circle`,{cx:`50`,cy:`50`,r:`3`,fill:`currentColor`})]})})]})}function uO({level:e}){return T(`span`,{className:`inline-flex items-center gap-0.5 tabular-nums text-xs text-foreground-subtle`,children:[v(Rs,{className:`h-3.5 w-3.5`}),e,`%`]})}function dO(e){switch(e){case`cleanWater`:return!0;case`detergent`:return!0;case`dirtyWater`:return!1;case`dustBin`:return!1;default:return e}}function fO(e,t){let n=dO(e);return t.level===null?t.status===null?`ok`:n?t.status===`low`?`warning`:`ok`:t.status===`full`?`warning`:`ok`:n?t.level<=15?`warning`:`ok`:t.level>=85?`warning`:`ok`}function pO(e){switch(e){case`cleanWater`:return{label:`Clean water`,icon:v(Tc,{className:`h-3.5 w-3.5`})};case`dirtyWater`:return{label:`Dirty water`,icon:v(Ec,{className:`h-3.5 w-3.5`})};case`detergent`:return{label:`Detergent`,icon:v(Fc,{className:`h-3.5 w-3.5`})};case`dustBin`:return{label:`Dust bin`,icon:v(au,{className:`h-3.5 w-3.5`})};default:return e}}function mO({kind:e,tank:t}){if(t===null)return null;let n=pO(e),r=fO(e,t)===`warning`;return t.level===null?t.status===null?null:T(`div`,{className:`flex items-center gap-2 text-xs`,children:[T(`span`,{className:G(`inline-flex items-center gap-1 w-24 shrink-0`,r?`text-warning`:`text-foreground-subtle`),children:[n.icon,n.label]}),v(`span`,{className:G(`inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium`,r?`bg-warning/15 text-warning`:`bg-primary/15 text-foreground-subtle`),children:t.status})]}):T(`div`,{className:`flex items-center gap-2 text-xs`,children:[T(`span`,{className:G(`inline-flex items-center gap-1 w-24 shrink-0`,r?`text-warning`:`text-foreground-subtle`),children:[n.icon,n.label]}),v(`span`,{className:`relative h-1.5 flex-1 overflow-hidden rounded-full bg-surface-hover`,children:v(`span`,{className:G(`absolute inset-y-0 left-0 rounded-full transition-all`,r?`bg-warning`:`bg-primary`),style:{width:`${t.level}%`}})}),T(`span`,{className:G(`tabular-nums w-9 text-right`,r?`text-warning`:`text-foreground-subtle`),children:[t.level,`%`]})]})}function hO({cleanWater:e,dirtyWater:t,detergent:n,dustBin:r}){let i=[[`cleanWater`,e],[`dirtyWater`,t],[`detergent`,n],[`dustBin`,r]];return i.some(([,e])=>e!==null&&(e.level!==null||e.status!==null))?v(`div`,{className:`grid grid-cols-1 gap-x-6 gap-y-2 rounded-md border border-border bg-surface-hover/40 p-3 sm:grid-cols-2`,children:i.map(([e,t])=>v(mO,{kind:e,tank:t},e))}):null}function gO({trpc:e,deviceId:t}){let{cap:n,slice:r,available:i}=oO(e,t);if(n===void 0)return null;let a=!i,o=r?.state,s=o===`cleaning`,c=e=>{a||e===void 0||e({})};return T(`div`,{className:`inline-flex items-center gap-1`,children:[v(sO,{label:`Start`,busy:a,active:s,onClick:()=>c(n.start),children:v(Cl,{className:`h-3 w-3`})}),v(sO,{label:`Pause`,busy:a,active:o===`paused`,onClick:()=>c(n.pause),children:v(bl,{className:`h-3 w-3`})}),v(sO,{label:`Return to base`,busy:a,active:o===`returning`,onClick:()=>c(n.returnToBase),children:v(Gc,{className:`h-3.5 w-3.5`})}),r?.batteryLevel!=null&&v(`span`,{className:`ml-1`,children:v(uO,{level:r.batteryLevel})})]})}function _O({label:e,busy:t,active:n,onClick:r,children:i}){return v(`button`,{type:`button`,"aria-label":e,title:e,disabled:t,onClick:e=>{e.stopPropagation(),r()},className:G(`inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,n&&`bg-primary text-primary-foreground hover:bg-primary/90`,t&&`opacity-40 cursor-not-allowed`),children:i})}function vO({trpc:e,deviceId:t}){let{cap:n,slice:r,available:i}=oO(e,t);if(n===void 0)return null;let a=!i,o=r?.state,s=aO(o),c=r?.availableFanSpeeds??[],l=e=>{a||e===void 0||e({})},u=e=>{a||e===``||n.setFanSpeed({speed:e})};return T(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[T(`div`,{className:`flex items-center gap-6`,children:[v(lO,{state:o}),T(`div`,{className:`flex flex-col gap-3 flex-1`,children:[T(`div`,{className:`flex items-center justify-between`,children:[v(`span`,{className:G(`text-3xl font-semibold`,s.tone),children:s.label}),r?.batteryLevel!=null&&v(uO,{level:r.batteryLevel})]}),T(`div`,{className:`flex items-center gap-2`,children:[v(_O,{label:`Start`,busy:a,active:o===`cleaning`,onClick:()=>l(n.start),children:v(Cl,{className:`h-5 w-5`})}),v(_O,{label:`Pause`,busy:a,active:o===`paused`,onClick:()=>l(n.pause),children:v(bl,{className:`h-5 w-5`})}),v(_O,{label:`Stop`,busy:a,active:!1,onClick:()=>l(n.stop),children:v(Zl,{className:`h-4 w-4`})}),v(_O,{label:`Return to base`,busy:a,active:o===`returning`,onClick:()=>l(n.returnToBase),children:v(Gc,{className:`h-5 w-5`})}),v(_O,{label:`Locate`,busy:a,active:!1,onClick:()=>l(n.locate),children:v(sl,{className:`h-5 w-5`})})]})]})]}),c.length>0&&T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{className:`w-16 shrink-0`,children:`Fan speed`}),T(`select`,{"aria-label":`Fan speed`,value:r?.fanSpeed??``,disabled:a,onChange:e=>{u(e.target.value)},onClick:e=>{e.stopPropagation()},className:`flex-1 rounded border border-border bg-surface px-2 py-1 text-foreground disabled:opacity-50`,children:[r?.fanSpeed==null&&v(`option`,{value:``,children:`—`}),c.map(e=>v(`option`,{value:e,children:e},e))]})]}),v(hO,{cleanWater:r?.cleanWater??null,dirtyWater:r?.dirtyWater??null,detergent:r?.detergent??null,dustBin:r?.dustBin??null})]})}function yO(e){switch(e){case`mowing`:return{label:`Mowing`,tone:`text-primary`};case`paused`:return{label:`Paused`,tone:`text-warning`};case`docked`:return{label:`Docked`,tone:`text-success`};case`idle`:return{label:`Idle`,tone:`text-foreground-subtle`};case`error`:return{label:`Error`,tone:`text-destructive`};case void 0:return{label:`Unknown`,tone:`text-foreground-subtle`}}}function bO(e,t){return $f({trpc:e,deviceId:t,cap:e=>e.lawnMowerControl,slice:e=>e.state.lawnMowerControl})}function xO(e){switch(e){case`mowing`:return{glow:`bg-primary/15`,accent:`text-primary`,docked:!1,active:!0};case`docked`:return{glow:`bg-success/10`,accent:`text-success`,docked:!0,active:!1};case`paused`:return{glow:`bg-warning/10`,accent:`text-warning`,docked:!1,active:!1};case`error`:return{glow:`bg-destructive/10`,accent:`text-destructive`,docked:!1,active:!1};case`idle`:return{glow:`bg-transparent`,accent:`text-foreground-subtle`,docked:!1,active:!1};case void 0:return{glow:`bg-transparent`,accent:`text-foreground-subtle`,docked:!1,active:!1}}}function SO({activity:e}){let t=xO(e);return T(`div`,{"aria-hidden":`true`,className:`relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-emerald-700/40 to-emerald-900/30 overflow-hidden flex-shrink-0`,style:{boxShadow:`inset 0 0 0 2px rgba(255,255,255,.06)`},children:[v(`div`,{className:G(`absolute inset-0 transition-colors duration-300`,t.glow)}),v(`div`,{className:G(`absolute inset-0 flex items-center justify-center`,t.accent),children:T(`svg`,{viewBox:`0 0 100 100`,className:`w-20 h-20`,fill:`none`,children:[t.docked&&v(`rect`,{x:`30`,y:`78`,width:`40`,height:`9`,rx:`2`,fill:`currentColor`,opacity:`0.35`}),t.active&&T(`g`,{stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,opacity:`0.5`,children:[v(`line`,{x1:`18`,y1:`36`,x2:`10`,y2:`36`,className:`animate-pulse`}),v(`line`,{x1:`18`,y1:`50`,x2:`6`,y2:`50`,className:`animate-pulse`}),v(`line`,{x1:`18`,y1:`64`,x2:`10`,y2:`64`,className:`animate-pulse`})]}),v(`rect`,{x:`28`,y:`34`,width:`44`,height:`34`,rx:`8`,fill:`currentColor`,fillOpacity:`0.14`,stroke:`currentColor`,strokeWidth:`2.5`}),v(`line`,{x1:`34`,y1:`60`,x2:`66`,y2:`60`,stroke:`currentColor`,strokeWidth:`2`,opacity:`0.5`}),v(`circle`,{cx:`50`,cy:`48`,r:`5`,stroke:`currentColor`,strokeWidth:`2`,opacity:`0.6`}),v(`circle`,{cx:`34`,cy:`68`,r:`6`,fill:`currentColor`,fillOpacity:`0.3`,stroke:`currentColor`,strokeWidth:`2`}),v(`circle`,{cx:`66`,cy:`68`,r:`6`,fill:`currentColor`,fillOpacity:`0.3`,stroke:`currentColor`,strokeWidth:`2`})]})})]})}function CO({level:e}){return T(`span`,{className:`inline-flex items-center gap-0.5 tabular-nums text-xs text-foreground-subtle`,children:[v(Rs,{className:`h-3.5 w-3.5`}),e,`%`]})}function wO({label:e,busy:t,active:n,onClick:r,children:i}){return v(`button`,{type:`button`,"aria-label":e,title:e,disabled:t,onClick:e=>{e.stopPropagation(),r()},className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,n&&`bg-primary text-primary-foreground`,t&&`opacity-40 cursor-not-allowed`),children:i})}function TO({trpc:e,deviceId:t}){let{cap:n,slice:r,available:i}=bO(e,t);if(n===void 0)return null;let a=!i,o=r?.activity,s=e=>{a||e===void 0||e({})};return T(`div`,{className:`inline-flex items-center gap-1`,children:[v(wO,{label:`Mow`,busy:a,active:o===`mowing`,onClick:()=>s(n.startMowing),children:v(Cl,{className:`h-3 w-3`})}),v(wO,{label:`Pause`,busy:a,active:o===`paused`,onClick:()=>s(n.pause),children:v(bl,{className:`h-3 w-3`})}),v(wO,{label:`Dock`,busy:a,active:o===`docked`,onClick:()=>s(n.dock),children:v(Gc,{className:`h-3.5 w-3.5`})}),r?.batteryLevel!=null&&v(`span`,{className:`ml-1`,children:v(CO,{level:r.batteryLevel})})]})}function EO({label:e,busy:t,active:n,onClick:r,children:i}){return v(`button`,{type:`button`,"aria-label":e,title:e,disabled:t,onClick:e=>{e.stopPropagation(),r()},className:G(`inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,n&&`bg-primary text-primary-foreground hover:bg-primary/90`,t&&`opacity-40 cursor-not-allowed`),children:i})}function DO({trpc:e,deviceId:t}){let{cap:n,slice:r,available:i}=bO(e,t);if(n===void 0)return null;let a=!i,o=r?.activity,s=yO(o),c=e=>{a||e===void 0||e({})};return v(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:T(`div`,{className:`flex items-center gap-6`,children:[v(SO,{activity:o}),T(`div`,{className:`flex flex-col gap-3 flex-1`,children:[T(`div`,{className:`flex items-center justify-between`,children:[v(`span`,{className:G(`text-3xl font-semibold`,s.tone),children:s.label}),r?.batteryLevel!=null&&v(CO,{level:r.batteryLevel})]}),T(`div`,{className:`flex items-center gap-2`,children:[v(EO,{label:`Start mowing`,busy:a,active:o===`mowing`,onClick:()=>c(n.startMowing),children:v(Cl,{className:`h-5 w-5`})}),v(EO,{label:`Pause`,busy:a,active:o===`paused`,onClick:()=>c(n.pause),children:v(bl,{className:`h-5 w-5`})}),v(EO,{label:`Dock`,busy:a,active:o===`docked`,onClick:()=>c(n.dock),children:v(Gc,{className:`h-5 w-5`})})]})]})]})})}function OO(e){switch(e){case`open`:return{label:`Open`,tone:`text-primary`};case`opening`:return{label:`Opening`,tone:`text-primary`};case`closing`:return{label:`Closing`,tone:`text-warning`};case`closed`:return{label:`Closed`,tone:`text-foreground-subtle`};case`stopped`:return{label:`Stopped`,tone:`text-warning`};case void 0:return{label:`Unknown`,tone:`text-foreground-subtle`}}}function kO(e,t){return $f({trpc:e,deviceId:t,cap:e=>e.valve,slice:e=>e.state.valve})}function AO(e){switch(e){case`accent`:return`bg-primary text-primary-foreground`;case`filled`:return`bg-primary/15 text-primary`;case`neutral`:return``}}function jO({label:e,busy:t,variant:n,onClick:r,children:i}){return v(`button`,{type:`button`,"aria-label":e,title:e,disabled:t,onClick:e=>{e.stopPropagation(),r()},className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-xs text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,AO(n),t&&`opacity-40 cursor-not-allowed`),children:i})}function MO({trpc:e,deviceId:t,optimistic:n}){let{cap:r,slice:i,available:a}=kO(e,t),{display:o,applyOptimistic:s}=um(i,{enabled:n??!0});if(r===void 0)return null;let c=!a,l=dm(o?.state),u=(e,t)=>{c||!e||(t!==void 0&&s(t),e({}))};return T(`div`,{className:`inline-flex items-center gap-1`,children:[v(jO,{label:`Open`,busy:c,variant:l.up,onClick:()=>u(r.open,{state:`opening`}),children:v($s,{className:`h-3.5 w-3.5`})}),v(jO,{label:`Stop`,busy:c,variant:l.stop,onClick:()=>u(r.stop,{state:`stopped`}),children:v(Zl,{className:`h-3 w-3`})}),v(jO,{label:`Close`,busy:c,variant:l.down,onClick:()=>u(r.close,{state:`closing`}),children:v(Xs,{className:`h-3.5 w-3.5`})}),o!==void 0&&o.position!==null&&T(`span`,{className:`tabular-nums text-xs text-foreground-subtle ml-1`,children:[o.position,`%`]})]})}function NO(e){switch(e){case`open`:return{glow:`bg-primary/15`,accent:`text-primary`,flowing:!0,active:!1};case`opening`:return{glow:`bg-primary/10`,accent:`text-primary`,flowing:!0,active:!0};case`closing`:return{glow:`bg-warning/10`,accent:`text-warning`,flowing:!1,active:!0};case`closed`:return{glow:`bg-transparent`,accent:`text-foreground-subtle`,flowing:!1,active:!1};case`stopped`:return{glow:`bg-warning/10`,accent:`text-warning`,flowing:!1,active:!1};case void 0:return{glow:`bg-transparent`,accent:`text-foreground-subtle`,flowing:!1,active:!1}}}function PO(e){switch(e){case`open`:return 0;case`opening`:return 0;case`closed`:return 1;case`closing`:return 1;case`stopped`:return 1;case void 0:return 1}}function FO({state:e,position:t,interactive:n,onSetPosition:r}){let i=NO(e),a=t===null?PO(e):1-t/100,o=41+a*8,s=-90*(1-a),c=p(null),l=p(!1),u=p(null),d=e=>{let n=t??0,r=c.current;if(r===null)return n;let i=r.getBoundingClientRect();if(i.height<=0)return n;let a=(e-i.top)/i.height,o=Math.round(100-a*100);return Math.min(100,Math.max(0,o))},f=e=>{if(r===void 0)return;let t=d(e);u.current!==t&&(u.current=t,r(t))},m=e=>{n&&(e.stopPropagation(),e.preventDefault(),l.current=!0,u.current=null,e.currentTarget.setPointerCapture(e.pointerId),f(e.clientY))},h=e=>{!n||!l.current||(e.stopPropagation(),f(e.clientY))},g=e=>{!n||!l.current||(e.stopPropagation(),l.current=!1,u.current=null,e.currentTarget.hasPointerCapture(e.pointerId)&&e.currentTarget.releasePointerCapture(e.pointerId))};return T(`div`,{ref:c,"data-testid":`valve-graphic`,...n?{"aria-label":`Drag to set position`,role:`slider`,"aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":t??0}:{"aria-hidden":`true`},onPointerDown:n?m:void 0,onPointerMove:n?h:void 0,onPointerUp:n?g:void 0,onPointerCancel:n?g:void 0,className:G(`relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0`,n&&`cursor-ns-resize touch-none select-none`),style:{boxShadow:`inset 0 0 0 2px rgba(255,255,255,.06)`},children:[v(`div`,{className:G(`absolute inset-0 transition-colors duration-300`,i.glow)}),v(`div`,{className:G(`absolute inset-0 flex items-center justify-center`,i.accent),"aria-hidden":`true`,children:T(`svg`,{viewBox:`0 0 100 100`,className:`w-24 h-28`,fill:`none`,children:[v(`rect`,{x:`40`,y:`4`,width:`20`,height:`92`,rx:`3`,fill:`currentColor`,fillOpacity:`0.06`,stroke:`currentColor`,strokeWidth:`2.5`}),i.flowing&&v(`line`,{x1:`50`,y1:`8`,x2:`50`,y2:`92`,stroke:`currentColor`,strokeWidth:`4`,strokeLinecap:`round`,strokeDasharray:`4 8`,opacity:`0.5`,className:`animate-pulse`}),i.active&&v(`circle`,{cx:`50`,cy:`50`,r:`22`,stroke:`currentColor`,strokeWidth:`2`,opacity:`0.4`,className:`animate-ping`,style:{transformOrigin:`center`}}),v(`circle`,{cx:`50`,cy:`50`,r:`17`,fill:`currentColor`,fillOpacity:`0.12`,stroke:`currentColor`,strokeWidth:`2.5`}),v(`rect`,{x:`43`,y:o,width:`14`,height:`6`,rx:`1.5`,fill:`currentColor`,fillOpacity:`0.55`,className:`transition-all duration-200`}),v(`line`,{x1:`50`,y1:`33`,x2:`50`,y2:`22`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`}),v(`g`,{style:{transform:`rotate(${s}deg)`,transformOrigin:`50px 20px`,transition:`transform 200ms`},children:v(`rect`,{x:`34`,y:`17`,width:`32`,height:`6`,rx:`3`,fill:`currentColor`,fillOpacity:`0.7`})})]})})]})}function IO({label:e,busy:t,variant:n,onClick:r,children:i}){return v(`button`,{type:`button`,"aria-label":e,title:e,disabled:t,onClick:e=>{e.stopPropagation(),r()},className:G(`inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,AO(n),t&&`opacity-40 cursor-not-allowed`),children:i})}function LO({trpc:e,deviceId:t,features:n,optimistic:r}){let{cap:i,slice:a,available:o}=kO(e,t),{display:s,applyOptimistic:c}=um(a,{enabled:r??!0});if(i===void 0)return null;let l=!o,u=(n??[]).includes(Ee.ValvePositionable),d=dm(s?.state),f=OO(s?.state),p=s?.position??null,m=p!==null,h=(e,t)=>{l||!e||(t!==void 0&&c(t),e({}))},g=e=>{l||(c({position:e}),i.setPosition({position:e}))};return T(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[T(`div`,{className:`flex items-center gap-6`,children:[v(FO,{state:s?.state,position:p,interactive:u&&m,onSetPosition:u&&m?g:void 0}),T(`div`,{className:`flex flex-col gap-3 flex-1`,children:[m&&T(`div`,{className:`flex items-baseline gap-1`,children:[v(`span`,{className:`text-3xl font-semibold tabular-nums text-foreground`,children:p}),v(`span`,{className:`text-base text-foreground-subtle`,children:`%`}),v(`span`,{className:`text-xs text-foreground-subtle ml-1`,children:`open`})]}),!m&&v(`div`,{className:`flex items-baseline gap-1`,children:v(`span`,{className:G(`text-3xl font-semibold`,f.tone),children:f.label})}),T(`div`,{className:`flex items-center gap-2`,children:[v(IO,{label:`Open`,busy:l,variant:d.up,onClick:()=>h(i.open,{state:`opening`}),children:v($s,{className:`h-5 w-5`})}),v(IO,{label:`Stop`,busy:l,variant:d.stop,onClick:()=>h(i.stop,{state:`stopped`}),children:v(Zl,{className:`h-4 w-4`})}),v(IO,{label:`Close`,busy:l,variant:d.down,onClick:()=>h(i.close,{state:`closing`}),children:v(Xs,{className:`h-5 w-5`})})]})]})]}),u&&T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{className:`w-12 shrink-0`,children:`Position`}),v(`input`,{"aria-label":`Position`,type:`range`,min:0,max:100,step:1,value:p??0,disabled:l,className:`flex-1`,onChange:e=>{g(Number(e.target.value))}}),T(`span`,{className:`w-8 text-right tabular-nums`,children:[p??`—`,`%`]})]}),!u&&m&&T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{className:`w-12 shrink-0`,children:`Position`}),v(`input`,{"aria-label":`Position`,type:`range`,min:0,max:100,step:1,value:p,disabled:!0,readOnly:!0,className:`flex-1 opacity-60`}),T(`span`,{className:`w-8 text-right tabular-nums`,children:[p,`%`]})]})]})}function RO(e,t){switch(t){case`humidifying`:return{glow:`bg-primary/15`,accent:`text-primary`,misting:!0};case`drying`:return{glow:`bg-warning/10`,accent:`text-warning`,misting:!1};case`idle`:return{glow:`bg-transparent`,accent:`text-foreground-subtle`,misting:!1};case`off`:return{glow:`bg-transparent`,accent:`text-foreground-subtle`,misting:!1};default:return e?{glow:`bg-primary/10`,accent:`text-primary`,misting:!0}:{glow:`bg-transparent`,accent:`text-foreground-subtle`,misting:!1}}}function zO(e,t){return $f({trpc:e,deviceId:t,cap:e=>e.humidifier,slice:e=>e.state.humidifier})}function BO({trpc:e,deviceId:t,optimistic:n}){let{cap:r,slice:i,available:a}=zO(e,t),{display:o,applyOptimistic:s}=um(i,{enabled:n??!0});if(r===void 0)return null;let c=!a,l=o?.on??!1,u=()=>{c||(s({on:!l}),r.setOn({on:!l}))};return T(`div`,{className:`inline-flex items-center gap-2`,children:[v(`button`,{type:`button`,"aria-label":l?`Turn off`:`Turn on`,title:l?`Turn off`:`Turn on`,disabled:c,onClick:e=>{e.stopPropagation(),u()},className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-xs transition-colors`,l?`bg-primary text-primary-foreground`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,c&&`opacity-40 cursor-not-allowed`),children:v(Dl,{className:`h-3.5 w-3.5`})}),o!==void 0&&o.targetHumidity!==null&&T(`span`,{className:`tabular-nums text-xs text-foreground-subtle`,children:[o.currentHumidity!==null&&T(E,{children:[o.currentHumidity,`%`,v(`span`,{className:`mx-0.5`,children:`→`})]}),o.targetHumidity,`%`]})]})}function VO({fillPct:e,tint:t}){let n=82-Math.min(100,Math.max(0,e))/100*56,r=`humidifier-droplet-clip-${D()}`;return T(`div`,{"data-testid":`humidifier-graphic`,"aria-hidden":`true`,className:`relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0`,style:{boxShadow:`inset 0 0 0 2px rgba(255,255,255,.06)`},children:[v(`div`,{className:G(`absolute inset-0 transition-colors duration-300`,t.glow)}),v(`div`,{className:G(`absolute inset-0 flex items-center justify-center`,t.accent),children:T(`svg`,{viewBox:`0 0 100 100`,className:`w-24 h-28`,fill:`none`,children:[v(`defs`,{children:v(`clipPath`,{id:r,children:v(`path`,{d:`M50 26 C50 26 30 52 30 66 a20 20 0 0 0 40 0 C70 52 50 26 50 26 Z`})})}),t.misting&&T(`g`,{className:`animate-pulse`,opacity:`0.55`,children:[v(`line`,{x1:`42`,y1:`20`,x2:`42`,y2:`8`,stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,strokeDasharray:`3 5`}),v(`line`,{x1:`50`,y1:`18`,x2:`50`,y2:`4`,stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,strokeDasharray:`3 5`}),v(`line`,{x1:`58`,y1:`20`,x2:`58`,y2:`8`,stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,strokeDasharray:`3 5`})]}),v(`path`,{d:`M50 26 C50 26 30 52 30 66 a20 20 0 0 0 40 0 C70 52 50 26 50 26 Z`,fill:`currentColor`,fillOpacity:`0.08`,stroke:`currentColor`,strokeWidth:`2.5`}),v(`g`,{clipPath:`url(#${r})`,children:v(`rect`,{x:`28`,y:n,width:`44`,height:`60`,fill:`currentColor`,fillOpacity:`0.4`,className:`transition-all duration-300`})}),v(`circle`,{cx:`43`,cy:`56`,r:`3`,fill:`currentColor`,fillOpacity:`0.5`})]})})]})}function HO({trpc:e,deviceId:t,optimistic:n}){let{cap:r,slice:i,available:a}=zO(e,t),{display:o,applyOptimistic:s}=um(i,{enabled:n??!0});if(r===void 0||o===void 0)return null;let c=!a,l=RO(o.on,o.action),u=o.minHumidity??0,d=o.maxHumidity??100,f=o.targetHumidity,p=o.currentHumidity,m=p??f??0,h=()=>{c||(s({on:!o.on}),r.setOn({on:!o.on}))},g=e=>{c||(s({targetHumidity:e}),r.setTargetHumidity({humidity:e}))};return T(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[T(`div`,{className:`flex items-center gap-6`,children:[v(VO,{fillPct:m,tint:l}),T(`div`,{className:`flex flex-col gap-3 flex-1`,children:[T(`div`,{className:`flex items-baseline gap-1`,children:[v(`span`,{className:`text-3xl font-semibold tabular-nums text-foreground`,children:f===null?`—`:f}),v(`span`,{className:`text-base text-foreground-subtle`,children:`%`}),v(`span`,{className:`text-xs text-foreground-subtle ml-1`,children:`target`})]}),T(`div`,{className:`text-xs text-foreground-subtle tabular-nums`,children:[`Current: `,p===null?`—`:`${p}%`,o.action!==null&&T(`span`,{className:`ml-2 capitalize`,children:[`· `,o.action]})]}),T(`button`,{type:`button`,"aria-label":o.on?`Turn off`:`Turn on`,disabled:c,onClick:e=>{e.stopPropagation(),h()},className:G(`inline-flex w-fit items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors`,o.on?`bg-primary text-primary-foreground`:`border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,c&&`opacity-40 cursor-not-allowed`),children:[v(Dl,{className:`h-4 w-4`}),o.on?`On`:`Off`]})]})]}),T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{className:`w-12 shrink-0`,children:`Target`}),v(`input`,{"aria-label":`Target humidity`,type:`range`,min:u,max:d,step:1,value:f??u,disabled:c,className:`flex-1`,onChange:e=>{g(Number(e.target.value))}}),T(`span`,{className:`w-8 text-right tabular-nums`,children:[f??`—`,`%`]})]}),o.availableModes.length>0&&v(`select`,{"aria-label":`Mode`,value:o.mode??``,disabled:c,onChange:e=>{e.stopPropagation();let t=o.availableModes.find(t=>t===e.target.value);!c&&t!==void 0&&(s({mode:t}),r.setMode({mode:t}))},className:G(`w-full rounded border border-border bg-surface px-3 py-1.5 text-sm`,c&&`opacity-40 cursor-not-allowed`),children:o.availableModes.map(e=>v(`option`,{value:e,children:e},e))})]})}function UO(e){switch(e){case`heating`:return{glow:`bg-warning/10`,accent:`text-warning`,heating:!0};case`idle`:return{glow:`bg-primary/10`,accent:`text-primary`,heating:!1};case`off`:return{glow:`bg-transparent`,accent:`text-foreground-subtle`,heating:!1}}}function WO(e,t,n){return e===null||e===`off`?`off`:t!==null&&n!==null&&t<n?`heating`:`idle`}function GO(e,t){return $f({trpc:e,deviceId:t,cap:e=>e.waterHeater,slice:e=>e.state.waterHeater})}function KO({trpc:e,deviceId:t,optimistic:n}){let{cap:r,slice:i}=GO(e,t),{display:a}=um(i,{enabled:n??!0});return r===void 0||a===void 0?null:T(`div`,{className:`inline-flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[T(`span`,{className:`tabular-nums`,children:[a.currentTemp!==null&&T(E,{children:[a.currentTemp,`°`,v(`span`,{className:`mx-0.5`,children:`→`})]}),a.targetTemp===null?`—`:`${a.targetTemp}°`]}),a.operationMode!==null&&T(`span`,{className:`capitalize text-foreground-subtle/80`,children:[`· `,a.operationMode.replace(/_/g,` `)]})]})}function qO({fillPct:e,tint:t}){let n=86-Math.min(100,Math.max(0,e))/100*68,r=`water-heater-tank-clip-${D()}`;return T(`div`,{"data-testid":`water-heater-graphic`,"aria-hidden":`true`,className:`relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0`,style:{boxShadow:`inset 0 0 0 2px rgba(255,255,255,.06)`},children:[v(`div`,{className:G(`absolute inset-0 transition-colors duration-300`,t.glow)}),v(`div`,{className:G(`absolute inset-0 flex items-center justify-center`,t.accent),children:T(`svg`,{viewBox:`0 0 100 100`,className:`w-24 h-28`,fill:`none`,children:[v(`defs`,{children:v(`clipPath`,{id:r,children:v(`rect`,{x:`30`,y:`18`,width:`40`,height:`68`,rx:`14`})})}),v(`g`,{clipPath:`url(#${r})`,children:v(`rect`,{x:`28`,y:n,width:`44`,height:`72`,fill:`currentColor`,fillOpacity:`0.32`,className:`transition-all duration-300`})}),v(`rect`,{x:`30`,y:`18`,width:`40`,height:`68`,rx:`14`,fill:`currentColor`,fillOpacity:`0.06`,stroke:`currentColor`,strokeWidth:`2.5`}),v(`line`,{x1:`50`,y1:`18`,x2:`50`,y2:`8`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`}),v(`rect`,{x:`40`,y:`6`,width:`20`,height:`5`,rx:`2`,fill:`currentColor`,fillOpacity:`0.6`}),v(`g`,{className:t.heating?`animate-pulse`:void 0,opacity:t.heating?.9:.35,children:v(`path`,{d:`M38 74 q4 -6 8 0 q4 6 8 0 q4 -6 8 0`,stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,fill:`none`})}),v(`circle`,{cx:`62`,cy:`34`,r:`3.5`,stroke:`currentColor`,strokeWidth:`2`,fill:t.heating?`currentColor`:`none`,fillOpacity:`0.6`})]})})]})}function JO({trpc:e,deviceId:t,optimistic:n}){let{cap:r,slice:i,available:a}=GO(e,t),{display:o,applyOptimistic:s}=um(i,{enabled:n??!0});if(r===void 0||o===void 0)return null;let c=!a,l=WO(o.operationMode,o.currentTemp,o.targetTemp),u=UO(l),d=o.currentTemp,f=o.targetTemp,p=o.minTemp,m=o.maxTemp,h=d!==null&&f!==null&&f>0?Math.min(100,d/f*100):d!==null&&m!==null&&m>0?Math.min(100,d/m*100):50,g=e=>{let t=e;return p!==null&&(t=Math.max(p,t)),m!==null&&(t=Math.min(m,t)),t},_=e=>{if(c||f===null)return;let t=g(f+e);s({targetTemp:t}),r.setTargetTemp({temp:t})},y=()=>{c||o.away===null||(s({away:!o.away}),r.setAway({on:!o.away}))};return T(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[T(`div`,{className:`flex items-center gap-6`,children:[v(qO,{fillPct:h,tint:u}),T(`div`,{className:`flex flex-col gap-3 flex-1`,children:[T(`div`,{className:`flex items-baseline gap-1`,children:[v(`span`,{className:`text-3xl font-semibold tabular-nums text-foreground`,children:d===null?`—`:d}),v(`span`,{className:`text-base text-foreground-subtle`,children:`°`})]}),T(`div`,{className:`text-xs text-foreground-subtle tabular-nums`,children:[`Target: `,f===null?`—`:`${f}°`,T(`span`,{className:`ml-2 capitalize`,children:[`· `,l]})]}),f!==null&&v(`div`,{className:`w-[180px]`,children:v(Qp,{value:f,unit:`°`,onDelta:_})})]})]}),o.availableModes.length>0&&v(`select`,{"aria-label":`Operation mode`,value:o.operationMode??``,disabled:c,onChange:e=>{e.stopPropagation();let t=o.availableModes.find(t=>t===e.target.value);!c&&t!==void 0&&(s({operationMode:t}),r.setOperationMode({mode:t}))},className:G(`w-full rounded border border-border bg-surface px-3 py-1.5 text-sm`,c&&`opacity-40 cursor-not-allowed`),children:o.availableModes.map(e=>v(`option`,{value:e,children:e},e))}),o.away!==null&&T(`button`,{type:`button`,"aria-label":o.away?`Disable away mode`:`Enable away mode`,disabled:c,onClick:e=>{e.stopPropagation(),y()},className:G(`inline-flex w-fit items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors`,o.away?`bg-primary text-primary-foreground`:`border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,c&&`opacity-40 cursor-not-allowed`),children:[v(Dl,{className:`h-4 w-4`}),`Away `,o.away?`on`:`off`]})]})}function YO(e){switch(e){case`sunny`:return{label:`Sunny`,glyph:`sun`};case`clear-night`:return{label:`Clear night`,glyph:`clear-night`};case`partlycloudy`:return{label:`Partly cloudy`,glyph:`partly-cloudy`};case`cloudy`:return{label:`Cloudy`,glyph:`cloudy`};case`rainy`:return{label:`Rainy`,glyph:`rain`};case`pouring`:return{label:`Pouring`,glyph:`rain`};case`snowy`:return{label:`Snowy`,glyph:`snow`};case`snowy-rainy`:return{label:`Sleet`,glyph:`snow`};case`lightning`:return{label:`Lightning`,glyph:`lightning`};case`lightning-rainy`:return{label:`Thunderstorm`,glyph:`lightning`};case`fog`:return{label:`Fog`,glyph:`fog`};case`windy`:return{label:`Windy`,glyph:`wind`};case`windy-variant`:return{label:`Windy`,glyph:`wind`};case`hail`:return{label:`Hail`,glyph:`hail`};case`exceptional`:return{label:`Exceptional`,glyph:`cloudy`};case null:return{label:`Unknown`,glyph:`cloudy`};default:return{label:e,glyph:`cloudy`}}}function XO(e){switch(e){case`sunny`:return{glow:`bg-warning/15`,accent:`text-warning`};case`clear-night`:return{glow:`bg-primary/10`,accent:`text-primary`};case`partlycloudy`:return{glow:`bg-warning/10`,accent:`text-warning`};case`cloudy`:return{glow:`bg-transparent`,accent:`text-foreground-subtle`};case`rainy`:case`pouring`:return{glow:`bg-primary/15`,accent:`text-primary`};case`snowy`:case`snowy-rainy`:return{glow:`bg-primary/10`,accent:`text-primary`};case`lightning`:case`lightning-rainy`:return{glow:`bg-warning/20`,accent:`text-warning`};case`fog`:return{glow:`bg-transparent`,accent:`text-foreground-subtle`};case`windy`:case`windy-variant`:return{glow:`bg-transparent`,accent:`text-foreground-subtle`};case`hail`:return{glow:`bg-primary/10`,accent:`text-primary`};default:return{glow:`bg-transparent`,accent:`text-foreground-subtle`}}}function ZO(e){let t=`h-4 w-4`;switch(e){case`sun`:return v($l,{className:t});case`clear-night`:return v(ml,{className:t});case`partly-cloudy`:return v(hc,{className:t});case`cloudy`:return v(gc,{className:t});case`rain`:return v(pc,{className:t});case`snow`:return v(mc,{className:t});case`lightning`:return v(fc,{className:t});case`fog`:return v(dc,{className:t});case`wind`:return v(vu,{className:t});case`hail`:return v(mc,{className:t});default:return null}}function QO(e,t){return $f({trpc:e,deviceId:t,cap:e=>e.weather,slice:e=>e.state.weather})}function $O(e,t){return e===null?`—`:`${Math.round(e)}${t??`°`}`}function ek({trpc:e,deviceId:t}){let{slice:n}=QO(e,t);if(n===void 0)return null;let r=YO(n.condition);return T(`div`,{className:`inline-flex items-center gap-1.5 text-xs text-foreground-subtle`,children:[v(`span`,{className:G(`inline-flex`,XO(n.condition).accent),title:r.label,"aria-label":r.label,children:ZO(r.glyph)}),v(`span`,{className:`tabular-nums`,children:$O(n.temperature,n.temperatureUnit)})]})}function tk({glyph:e,tint:t}){let n=D();return T(`div`,{"data-testid":`weather-scene`,"aria-hidden":`true`,className:`relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0`,style:{boxShadow:`inset 0 0 0 2px rgba(255,255,255,.06)`},children:[v(`div`,{className:G(`absolute inset-0 transition-colors duration-300`,t.glow)}),v(`div`,{className:G(`absolute inset-0 flex items-center justify-center`,t.accent),children:v(`svg`,{viewBox:`0 0 100 100`,className:`w-24 h-28`,fill:`none`,"data-glyph":e,children:rk(e,n)})})]})}function nk({cx:e,cy:t,scale:n=1}){return v(`g`,{transform:`translate(${e} ${t}) scale(${n})`,children:v(`path`,{d:`M-22 8 a13 13 0 0 1 4 -25 a16 16 0 0 1 30 4 a11 11 0 0 1 -2 21 Z`,fill:`currentColor`,fillOpacity:`0.12`,stroke:`currentColor`,strokeWidth:`2.5`,strokeLinejoin:`round`})})}function rk(e,t){switch(e){case`sun`:return T(`g`,{children:[v(`circle`,{cx:`50`,cy:`48`,r:`16`,fill:`currentColor`,fillOpacity:`0.18`,stroke:`currentColor`,strokeWidth:`2.5`}),v(`g`,{stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,children:[0,45,90,135,180,225,270,315].map(e=>{let n=e*Math.PI/180;return v(`line`,{x1:50+Math.cos(n)*22,y1:48+Math.sin(n)*22,x2:50+Math.cos(n)*30,y2:48+Math.sin(n)*30},`${t}-ray-${e}`)})})]});case`clear-night`:return T(`g`,{children:[v(`path`,{d:`M62 30 a22 22 0 1 0 8 38 a18 18 0 0 1 -8 -38 Z`,fill:`currentColor`,fillOpacity:`0.18`,stroke:`currentColor`,strokeWidth:`2.5`}),v(`circle`,{cx:`34`,cy:`32`,r:`1.6`,fill:`currentColor`}),v(`circle`,{cx:`28`,cy:`48`,r:`1.2`,fill:`currentColor`}),v(`circle`,{cx:`40`,cy:`62`,r:`1.4`,fill:`currentColor`})]});case`partly-cloudy`:return T(`g`,{children:[v(`circle`,{cx:`38`,cy:`38`,r:`12`,fill:`currentColor`,fillOpacity:`0.18`,stroke:`currentColor`,strokeWidth:`2.5`}),v(`g`,{stroke:`currentColor`,strokeWidth:`2.5`,strokeLinecap:`round`,children:[200,240,300].map(e=>{let n=e*Math.PI/180;return v(`line`,{x1:38+Math.cos(n)*16,y1:38+Math.sin(n)*16,x2:38+Math.cos(n)*22,y2:38+Math.sin(n)*22},`${t}-pcray-${e}`)})}),v(nk,{cx:58,cy:60})]});case`cloudy`:return T(`g`,{children:[v(nk,{cx:40,cy:44,scale:.9}),v(nk,{cx:62,cy:58})]});case`rain`:return T(`g`,{children:[v(nk,{cx:50,cy:42}),T(`g`,{className:`animate-pulse`,stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,opacity:`0.7`,children:[v(`line`,{x1:`38`,y1:`62`,x2:`34`,y2:`78`}),v(`line`,{x1:`50`,y1:`62`,x2:`46`,y2:`80`}),v(`line`,{x1:`62`,y1:`62`,x2:`58`,y2:`78`})]})]});case`snow`:return T(`g`,{children:[v(nk,{cx:50,cy:42}),T(`g`,{fill:`currentColor`,opacity:`0.8`,className:`animate-pulse`,children:[v(`circle`,{cx:`38`,cy:`70`,r:`2.5`}),v(`circle`,{cx:`50`,cy:`76`,r:`2.5`}),v(`circle`,{cx:`62`,cy:`70`,r:`2.5`})]})]});case`lightning`:return T(`g`,{children:[v(nk,{cx:50,cy:40}),v(`path`,{d:`M52 58 L42 74 L50 74 L46 88 L62 68 L53 68 L58 58 Z`,fill:`currentColor`,fillOpacity:`0.85`,className:`animate-pulse`})]});case`fog`:return T(`g`,{stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,opacity:`0.6`,children:[v(`line`,{x1:`26`,y1:`40`,x2:`74`,y2:`40`}),v(`line`,{x1:`30`,y1:`52`,x2:`70`,y2:`52`}),v(`line`,{x1:`24`,y1:`64`,x2:`68`,y2:`64`}),v(`line`,{x1:`32`,y1:`76`,x2:`76`,y2:`76`})]});case`wind`:return T(`g`,{stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,fill:`none`,opacity:`0.75`,children:[v(`path`,{d:`M22 42 H60 a7 7 0 1 0 -7 -7`}),v(`path`,{d:`M22 56 H72 a7 7 0 1 1 -7 7`}),v(`path`,{d:`M22 70 H52 a6 6 0 1 0 -6 -6`})]});case`hail`:return T(`g`,{children:[v(nk,{cx:50,cy:42}),T(`g`,{fill:`currentColor`,opacity:`0.85`,className:`animate-pulse`,children:[v(`circle`,{cx:`40`,cy:`70`,r:`3`}),v(`circle`,{cx:`52`,cy:`78`,r:`3`}),v(`circle`,{cx:`62`,cy:`68`,r:`3`})]})]});default:return null}}function ik({icon:e,label:t,value:n}){return T(`div`,{className:`flex items-center gap-1.5 text-xs text-foreground-subtle`,title:t,children:[v(`span`,{className:`inline-flex text-foreground-subtle`,"aria-hidden":`true`,children:e}),v(`span`,{className:`tabular-nums text-foreground`,children:n})]})}function ak({trpc:e,deviceId:t}){let{slice:n}=QO(e,t);if(n===void 0)return null;let r=YO(n.condition),i=XO(n.condition),a=n.temperatureUnit??`°`;return v(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:T(`div`,{className:`flex items-center gap-6`,children:[v(tk,{glyph:r.glyph,tint:i}),T(`div`,{className:`flex flex-col gap-3 flex-1`,children:[T(`div`,{className:`flex items-baseline gap-1`,children:[v(`span`,{className:`text-3xl font-semibold tabular-nums text-foreground`,children:n.temperature===null?`—`:Math.round(n.temperature)}),v(`span`,{className:`text-base text-foreground-subtle`,children:a}),v(`span`,{className:`text-xs text-foreground-subtle ml-2 capitalize`,children:r.label})]}),T(`div`,{className:`flex flex-col gap-1.5`,children:[n.humidity!==null&&v(ik,{icon:v(Ec,{className:`h-3.5 w-3.5`}),label:`Humidity`,value:`${Math.round(n.humidity)}%`}),n.windSpeed!==null&&v(ik,{icon:n.windBearing===null?v(vu,{className:`h-3.5 w-3.5`}):v(vl,{className:`h-3.5 w-3.5`,style:{transform:`rotate(${n.windBearing}deg)`}}),label:`Wind`,value:`${Math.round(n.windSpeed)} ${n.windSpeedUnit??``}`.trim()}),n.pressure!==null&&v(ik,{icon:v(zc,{className:`h-3.5 w-3.5`}),label:`Pressure`,value:`${Math.round(n.pressure)} ${n.pressureUnit??``}`.trim()})]})]})]})})}var ok=288,sk=196,ck=`h-7 w-7 rounded`,lk=8,uk=8;function dk({src:e,alt:t,caption:n,placeholder:r=`No image`,thumbClassName:i=ck,expandedWidth:a=ok,expandedHeight:o=sk}){let s=p(null),[l,d]=h(null),[f,m]=h(!1);c(()=>{m(!1)},[e]);let g=e!==null&&!f,_=e??void 0,y=u(()=>{let e=s.current;if(!e)return;let t=e.getBoundingClientRect(),n=t.top,r=window.innerHeight-t.bottom,i=n<o+lk&&r>n?t.bottom+lk:t.top-o-lk,c=t.right-a;d({top:i,left:Math.max(uk,Math.min(c,window.innerWidth-a-uk))})},[a,o]),b=u(()=>d(null),[]);return T(E,{children:[v(`button`,{ref:s,type:`button`,onClick:e=>e.stopPropagation(),onMouseEnter:y,onMouseLeave:b,onFocus:y,onBlur:b,"aria-label":t,className:`flex flex-shrink-0 items-center justify-center overflow-hidden border border-border bg-background text-foreground-subtle transition-colors hover:bg-surface-hover ${i}`,children:g?v(`img`,{src:_,alt:``,onError:()=>m(!0),className:`h-full w-full object-cover`}):v(Kc,{className:`h-3.5 w-3.5`,"aria-hidden":`true`})}),l&&A(T(`div`,{"aria-hidden":`true`,style:{position:`fixed`,top:l.top,left:l.left,width:a,pointerEvents:`none`},className:`z-[9999] overflow-hidden rounded-lg border border-border bg-surface shadow-lg shadow-black/30`,children:[v(`div`,{className:`flex h-40 items-center justify-center bg-background`,children:g?v(`img`,{src:_,alt:t,className:`h-full w-full object-cover`}):v(`span`,{className:`text-xs text-foreground-subtle`,children:r})}),v(`div`,{className:`px-3 py-2`,children:v(`p`,{className:`truncate text-xs font-semibold text-foreground`,children:n??t})})]}),document.body)]})}function fk(e,t){return $f({trpc:e,deviceId:t,cap:e=>e.image,slice:e=>e.state.image})}function pk({trpc:e,deviceId:t}){let{slice:n}=fk(e,t);return n===void 0?null:v(dk,{src:n.url,alt:`Image`,placeholder:`No image`,thumbClassName:`h-7 w-7 rounded`})}function mk({trpc:e,deviceId:t,deviceName:n}){let{slice:r}=fk(e,t),[i,a]=h(!1);return c(()=>{a(!1)},[r?.url??null]),r===void 0?null:v(`div`,{className:`flex flex-col items-stretch gap-3 rounded-lg border border-border bg-surface p-4`,children:v(`div`,{className:`flex w-full items-center justify-center overflow-hidden rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface`,children:r.url!==null&&!i?v(`img`,{src:r.url,alt:n??`Image`,onError:()=>a(!0),className:`max-h-72 w-full object-contain`}):T(`div`,{"data-testid":`image-placeholder`,className:`flex h-48 w-full flex-col items-center justify-center gap-2 text-foreground-subtle`,children:[v(Kc,{className:`h-8 w-8`,"aria-hidden":`true`}),v(`span`,{className:`text-xs`,children:`No image`})]})})})}function hk({trpc:e,deviceId:t,optimistic:n}){let{cap:r,slice:i,available:a}=$f({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch}),{display:o,applyOptimistic:s}=um(i,{enabled:n??!0}),[c,l]=h(!1);if(o===void 0)return null;let u=o.on===!0,d=c||!a,f={transform:u?`translateX(14px)`:`translateX(2px)`},p=async()=>{if(d||!r)return;let e=!u;s({on:e}),l(!0);try{await r.setState({on:e})}finally{l(!1)}};return v(`button`,{type:`button`,"aria-pressed":u,title:u?`Turn off`:`Turn on`,disabled:d,onClick:e=>{e.stopPropagation(),p()},className:G(`relative inline-flex h-4 w-7 items-center rounded-full border transition-colors flex-shrink-0`,u?`bg-success/30 border-success/50`:`bg-surface-hover border-border`,d&&`opacity-60`),children:v(`span`,{className:G(`absolute h-3 w-3 rounded-full transition-all`,u?`bg-success`:`bg-foreground-subtle`),style:f})})}function gk(e){return e instanceof Error?e.message:String(e)}function _k({trpc:e,deviceId:t,layout:n,optimistic:r,features:i}){let{cap:a,slice:o,available:s}=$f({trpc:e,deviceId:t,cap:e=>e.lockControl,slice:e=>e.state.lockControl}),{display:c,applyOptimistic:l}=um(o,{enabled:r??!0}),[u,d]=h(null),[f,p]=h(!1),[m,g]=h(null);if(c===void 0)return null;let _=c.state===`locked`||c.state===`locking`,y=!s||c.state===`jammed`,b=i?.includes(Ee.LockOpen)===!0,x=n===`compact`,S=()=>{l({state:`locking`}),a?.lock({})},C=()=>{l({state:`unlocking`}),a?.unlock({})},w=()=>{a?.open({})},E=()=>{if(!y){if(!_){S();return}if(x){g(null),d(`unlock`);return}C()}},D=()=>{if(!y){if(x){g(null),d(`open`);return}w()}},O=()=>{f||d(null)},k=async()=>{if(!(f||u===null)){g(null),p(!0);try{u===`unlock`?(l({state:`unlocking`}),await a?.unlock({})):await a?.open({}),d(null)}catch(e){g(gk(e))}finally{p(!1)}}},A=_?`Unlock`:`Lock`,j=u===`open`?`Open door?`:`Unlock device?`,M=u===`open`?`This will release the latch and open the door.`:`This will unlock the device.`,N=u===`open`?`Confirm open`:`Confirm unlock`,P=v(u===`open`?Cc:nl,{className:`h-4 w-4 text-amber-400`});return T(`div`,{className:G(`inline-flex items-center`,n===`full`?`gap-2`:`gap-1`),children:[T(`button`,{type:`button`,"aria-label":A,title:c.state===`jammed`?`Jammed`:A,disabled:y,onClick:e=>{e.stopPropagation(),E()},className:G(`inline-flex items-center justify-center rounded transition-colors`,n===`full`?`h-7 gap-1.5 px-2 text-xs`:`h-5 w-5`,_?`text-success`:`text-warning`,y&&`opacity-40 cursor-not-allowed`,`hover:bg-surface-hover`),children:[v(_?rl:nl,{className:`h-3.5 w-3.5`}),n===`full`&&v(`span`,{children:c.state})]}),b&&T(`button`,{type:`button`,"aria-label":`Open door`,title:`Open door`,disabled:y,onClick:e=>{e.stopPropagation(),D()},className:G(`inline-flex items-center justify-center rounded transition-colors`,n===`full`?`h-7 gap-1.5 px-2 text-xs`:`h-5 w-5`,`text-foreground-muted`,y&&`opacity-40 cursor-not-allowed`,`hover:bg-surface-hover`),children:[v(Cc,{className:`h-3.5 w-3.5`}),n===`full`&&v(`span`,{children:`Open`})]}),x&&v(Xu,{open:u!==null,onOpenChange:e=>{e||O()},children:T($u,{width:`sm`,onClick:e=>e.stopPropagation(),children:[T(ed,{children:[T(nd,{className:`flex items-center gap-2`,children:[P,j]}),v(rd,{children:M})]}),m!==null&&v(`div`,{className:`mt-2 px-3 py-2 rounded border border-danger/40 bg-danger/10 text-xs text-danger`,children:m}),T(td,{children:[v(ju,{type:`button`,variant:`ghost`,size:`sm`,disabled:f,onClick:()=>O(),children:`Cancel`}),T(ju,{type:`button`,variant:`danger`,size:`sm`,"aria-label":N,disabled:f,onClick:()=>{k()},children:[f&&v(el,{className:`h-3.5 w-3.5 animate-spin`}),N]})]})]})})]})}function vk({trpc:e,deviceId:t,layout:n,optimistic:r}){let{cap:i,slice:a,available:o}=$f({trpc:e,deviceId:t,cap:e=>e.brightness,slice:e=>e.state.brightness}),{display:s,applyOptimistic:c}=um(a,{enabled:r??!0});if(s===void 0)return null;let l=!o;return T(`label`,{className:G(`flex items-center gap-2 text-xs text-foreground-subtle`,n===`compact`&&`min-w-[140px]`),children:[v(`input`,{"aria-label":`Brightness`,type:`range`,min:0,max:100,step:1,value:s.percentage,disabled:l,onChange:e=>{let t=Number(e.target.value);c({percentage:t}),l||i?.setBrightness({percentage:t})}}),T(`span`,{className:`tabular-nums w-8 text-right`,children:[s.percentage,`%`]})]})}function yk({trpc:e,deviceId:t,features:n,layout:r,optimistic:i}){let{cap:a,slice:o,available:s}=$f({trpc:e,deviceId:t,cap:e=>e.fanControl,slice:e=>e.state.fanControl}),{display:c,applyOptimistic:l}=um(o,{enabled:i??!0});if(c===void 0)return null;let u=!s,d=n??[],f=d.includes(`fan-speed`),p=d.includes(`fan-preset`),m=o?.percentageStep!=null&&o.percentageStep>0?o.percentageStep:1;return T(`div`,{className:G(`inline-flex items-center gap-2`,r===`full`&&`flex-col items-stretch`),children:[f&&T(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`input`,{"aria-label":`Fan speed`,type:`range`,min:0,max:100,step:m,value:c.percentage??0,disabled:u,onChange:e=>{let t=Number(e.target.value),n=Math.min(100,Math.max(0,Math.round(t/m)*m));l({percentage:n}),u||a?.setPercentage({percentage:n})}}),T(`span`,{className:`tabular-nums w-8 text-right`,children:[c.percentage??`—`,`%`]})]}),p&&c.availablePresets.length>0&&v(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:T(`select`,{"aria-label":`Fan preset`,value:c.preset,disabled:u,onChange:e=>{let t=e.target.value;!u&&t&&(l({preset:t}),a?.setPreset({preset:t}))},className:`bg-surface border border-border rounded px-1 py-0.5`,children:[v(`option`,{value:``,disabled:!0,children:`—`}),c.availablePresets.map(e=>v(`option`,{value:e,children:e},e))]})})]})}var bk={heat:`border-amber-400 bg-amber-50 dark:bg-amber-950`,cool:`border-blue-400 bg-blue-50 dark:bg-blue-950`,auto:`border-purple-400 bg-purple-50 dark:bg-purple-950`,heat_cool:`border-fuchsia-400 bg-fuchsia-50 dark:bg-fuchsia-950`,fan_only:`border-slate-400 bg-slate-50 dark:bg-slate-950`,dry:`border-cyan-400 bg-cyan-50 dark:bg-cyan-950`,off:`border-zinc-300 bg-zinc-50 dark:bg-zinc-900`},xk={heat:`text-amber-600 dark:text-amber-400`,cool:`text-blue-600 dark:text-blue-400`,auto:`text-purple-600 dark:text-purple-400`,heat_cool:`text-fuchsia-600 dark:text-fuchsia-400`,fan_only:`text-slate-600 dark:text-slate-400`,dry:`text-cyan-600 dark:text-cyan-400`,off:`text-foreground`},Sk={heat:`bg-amber-400 text-amber-950`,cool:`bg-blue-400 text-blue-950`,auto:`bg-purple-400 text-purple-950`,heat_cool:`bg-fuchsia-400 text-fuchsia-950`,fan_only:`bg-slate-400 text-slate-950`,dry:`bg-cyan-400 text-cyan-950`,off:`bg-zinc-300 text-zinc-700`};function Ck({trpc:e,deviceId:t,features:n,layout:r,optimistic:i}){let{cap:a,slice:o,available:s}=$f({trpc:e,deviceId:t,cap:e=>e.climateControl,slice:e=>e.state.climateControl}),{display:c,applyOptimistic:l}=um(o,{enabled:i??!0});if(a===void 0||c===void 0)return null;let u=!s;if(r===`compact`)return T(`div`,{"data-mode":c.mode,className:`inline-flex items-center gap-1`,children:[v(`span`,{className:G(`text-xs tabular-nums font-medium`,xk[c.mode]),children:c.target===null?c.currentTemp===null?null:T(`span`,{className:`text-foreground-subtle`,children:[c.currentTemp,`°`]}):T(E,{children:[c.target,`°`,c.currentTemp!==null&&T(`span`,{className:`text-foreground-subtle font-normal`,children:[` `,`(`,c.currentTemp,`°)`]})]})}),c.target!==null&&T(E,{children:[v(`button`,{type:`button`,"aria-label":`Decrease target`,disabled:u,onClick:e=>{if(e.stopPropagation(),!u&&c.target!==null){let e=c.target-1;l({target:e}),a.setTarget({target:e})}},className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,u&&`opacity-40 cursor-not-allowed`),children:`−`}),v(`button`,{type:`button`,"aria-label":`Increase target`,disabled:u,onClick:e=>{if(e.stopPropagation(),!u&&c.target!==null){let e=c.target+1;l({target:e}),a.setTarget({target:e})}},className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,u&&`opacity-40 cursor-not-allowed`),children:`+`})]}),v(`select`,{"aria-label":`Mode`,value:c.mode,disabled:u,onChange:e=>{e.stopPropagation();let t=e.target.value;u||(l({mode:t}),a.setMode({mode:t}))},className:G(`bg-transparent px-0.5 text-xs text-foreground-subtle hover:text-foreground cursor-pointer`,u&&`opacity-40 cursor-not-allowed`),children:c.availableModes.map(e=>v(`option`,{value:e,children:e},e))})]});let d=c.mode===`heat_cool`||c.targetLow!==null&&c.targetHigh!==null,f=!d&&c.target!==null;return T(`div`,{"data-mode":c.mode,className:G(`inline-flex items-center gap-2 rounded border px-2 py-1 transition-colors`,bk[c.mode],`flex-col items-stretch gap-3`),children:[T(`div`,{className:`inline-flex items-center gap-1 text-xs tabular-nums`,children:[c.currentTemp!==null&&T(`span`,{className:`text-foreground-subtle`,children:[c.currentTemp,`°`]}),f&&T(E,{children:[v(`span`,{className:`text-foreground-subtle`,children:`→`}),T(`span`,{className:`font-medium`,children:[c.target,`°`]}),v(`button`,{type:`button`,"aria-label":`Decrease target`,disabled:u,onClick:e=>{if(e.stopPropagation(),!u&&c.target!==null){let e=c.target-1;l({target:e}),a.setTarget({target:e})}},className:G(`inline-flex h-4 w-4 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,u&&`opacity-40 cursor-not-allowed`),children:`−`}),v(`button`,{type:`button`,"aria-label":`Increase target`,disabled:u,onClick:e=>{if(e.stopPropagation(),!u&&c.target!==null){let e=c.target+1;l({target:e}),a.setTarget({target:e})}},className:G(`inline-flex h-4 w-4 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,u&&`opacity-40 cursor-not-allowed`),children:`+`})]})]}),v(`div`,{className:`inline-flex items-center gap-0.5 rounded bg-surface-subtle p-0.5`,children:c.availableModes.map(e=>v(`button`,{type:`button`,"aria-label":e,disabled:u,onClick:t=>{t.stopPropagation(),u||(l({mode:e}),a.setMode({mode:e}))},className:G(`rounded px-1.5 py-0.5 text-xs transition-colors`,e===c.mode?Sk[e]:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,u&&`opacity-40 cursor-not-allowed`),children:e},e))}),d&&T(`div`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[T(`label`,{className:`flex items-center gap-1`,children:[v(`span`,{children:`Low`}),v(`input`,{"aria-label":`Target low`,type:`number`,step:.5,value:c.targetLow??``,disabled:u,onChange:e=>{if(!u){let t=Number(e.target.value),n=c.targetHigh??t;l({targetLow:t}),a.setTargetRange({targetLow:t,targetHigh:n})}},className:`w-14 rounded border border-border bg-surface px-1 py-0.5 tabular-nums`})]}),T(`label`,{className:`flex items-center gap-1`,children:[v(`span`,{children:`High`}),v(`input`,{"aria-label":`Target high`,type:`number`,step:.5,value:c.targetHigh??``,disabled:u,onChange:e=>{if(!u){let t=Number(e.target.value),n=c.targetLow??t;l({targetHigh:t}),a.setTargetRange({targetLow:n,targetHigh:t})}},className:`w-14 rounded border border-border bg-surface px-1 py-0.5 tabular-nums`})]})]}),c.availableFanModes.length>0&&T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{children:`Fan`}),T(`select`,{"aria-label":`Fan mode`,value:c.fanMode,disabled:u,onChange:e=>{let t=e.target.value;!u&&t&&(l({fanMode:t}),a.setFanMode({fanMode:t}))},className:`rounded border border-border bg-surface px-1 py-0.5`,children:[v(`option`,{value:``,disabled:!0,children:`—`}),c.availableFanModes.map(e=>v(`option`,{value:e,children:e},e))]})]}),c.availablePresets.length>0&&T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{children:`Preset`}),T(`select`,{"aria-label":`Preset`,value:c.preset,disabled:u,onChange:e=>{let t=e.target.value;!u&&t&&(l({preset:t}),a.setPreset({preset:t}))},className:`rounded border border-border bg-surface px-1 py-0.5`,children:[v(`option`,{value:``,disabled:!0,children:`—`}),c.availablePresets.map(e=>v(`option`,{value:e,children:e},e))]})]}),c.targetHumidity!==null&&T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{children:`Humidity`}),v(`input`,{"aria-label":`Target humidity`,type:`range`,min:0,max:100,step:1,value:c.targetHumidity,disabled:u,onChange:e=>{let t=Number(e.target.value);l({targetHumidity:t}),u||a.setTargetHumidity({targetHumidity:t})}}),T(`span`,{className:`tabular-nums w-8 text-right`,children:[c.targetHumidity,`%`]})]})]})}var wk={playing:`border-green-400 bg-green-50 dark:bg-green-950`,paused:`border-amber-400 bg-amber-50 dark:bg-amber-950`,buffering:`border-blue-400 bg-blue-50 dark:bg-blue-950`,on:`border-slate-400 bg-slate-50 dark:bg-slate-950`,idle:`border-slate-400 bg-slate-50 dark:bg-slate-950`,off:`border-zinc-300 bg-zinc-50 dark:bg-zinc-900`,standby:`border-zinc-300 bg-zinc-50 dark:bg-zinc-900`},Tk={playing:`bg-green-500`,paused:`bg-amber-400`,buffering:`bg-blue-400`,on:`bg-slate-400`,idle:`bg-slate-400`,off:`bg-zinc-300`,standby:`bg-zinc-300`},Ek=[`off`,`all`,`one`];function Dk(e){return Ek.includes(e)}var Ok={off:`Off`,all:`All`,one:`One`};function kk(e){return e===`playing`||e===`buffering`?`pause`:`play`}function Ak({trpc:e,deviceId:t,features:n,layout:r,optimistic:i}){let{cap:a,slice:o,available:s}=$f({trpc:e,deviceId:t,cap:e=>e.mediaPlayer,slice:e=>e.state.mediaPlayer}),{display:c,applyOptimistic:l}=um(o,{enabled:i??!0});if(c===void 0)return null;let u=!s,d=kk(c.state);return T(`div`,{"data-state":c.state,className:G(`inline-flex items-center gap-2 rounded border px-2 py-1 transition-colors`,wk[c.state],r===`full`&&`flex-col items-stretch gap-3`),children:[T(`div`,{className:`inline-flex items-center gap-2`,children:[v(`span`,{role:`status`,"aria-label":c.state,className:G(`inline-block h-2 w-2 rounded-full flex-shrink-0`,Tk[c.state])}),v(`button`,{type:`button`,"aria-label":d===`play`?`Play`:`Pause`,disabled:u,onClick:e=>{e.stopPropagation(),!u&&(d===`play`?(l({state:`playing`}),a?.play({})):(l({state:`paused`}),a?.pause({})))},className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,u&&`opacity-40 cursor-not-allowed`),children:d===`play`?`▶`:`⏸`})]}),r===`full`&&T(E,{children:[T(`div`,{className:`inline-flex items-center gap-1`,children:[v(`button`,{type:`button`,"aria-label":`Previous`,disabled:u,onClick:e=>{e.stopPropagation(),u||a?.previous({})},className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,u&&`opacity-40 cursor-not-allowed`),children:`⏮`}),v(`button`,{type:`button`,"aria-label":`Next`,disabled:u,onClick:e=>{e.stopPropagation(),u||a?.next({})},className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs`,u&&`opacity-40 cursor-not-allowed`),children:`⏭`})]}),c.volumeLevel!==null&&T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{children:`Vol`}),v(`input`,{"aria-label":`Volume`,type:`range`,min:0,max:100,step:1,value:c.volumeLevel,disabled:u,onChange:e=>{let t=Number(e.target.value);l({volumeLevel:t}),u||a?.setVolume({volumeLevel:t})}}),T(`span`,{className:`tabular-nums w-8 text-right`,children:[c.volumeLevel,`%`]})]}),c.isMuted!==null&&v(`button`,{type:`button`,"aria-label":c.isMuted?`Unmute`:`Mute`,disabled:u,onClick:e=>{if(e.stopPropagation(),!u&&c.isMuted!==null){let e=!c.isMuted;l({isMuted:e}),a?.setMute({muted:e})}},className:G(`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors`,c.isMuted?`bg-amber-400 text-amber-950`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,u&&`opacity-40 cursor-not-allowed`),children:c.isMuted?`🔇`:`🔊`}),c.availableSources.length>0&&T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{children:`Source`}),T(`select`,{"aria-label":`Source`,value:c.source,disabled:u,onChange:e=>{let t=e.target.value;!u&&t&&(l({source:t}),a?.selectSource({source:t}))},className:`rounded border border-border bg-surface px-1 py-0.5`,children:[v(`option`,{value:``,disabled:!0,children:`—`}),c.availableSources.map(e=>v(`option`,{value:e,children:e},e))]})]}),c.shuffle!==null&&v(`button`,{type:`button`,"aria-label":`Shuffle`,disabled:u,onClick:e=>{if(e.stopPropagation(),!u&&c.shuffle!==null){let e=!c.shuffle;l({shuffle:e}),a?.setShuffle({shuffle:e})}},className:G(`inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors`,c.shuffle?`bg-green-400 text-green-950`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,u&&`opacity-40 cursor-not-allowed`),children:`⇌ Shuffle`}),c.repeat!==null&&T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{children:`Repeat`}),v(`select`,{"aria-label":`Repeat`,value:c.repeat,disabled:u,onChange:e=>{let t=e.target.value;!u&&Dk(t)&&(l({repeat:t}),a?.setRepeat({repeat:t}))},className:`rounded border border-border bg-surface px-1 py-0.5`,children:Ek.map(e=>v(`option`,{value:e,children:Ok[e]},e))})]})]})]})}function jk(e){return e.slice(0,10)}function Mk(e){return e.slice(0,5)}function Nk(e){return(e.includes(`T`)?e:e.replace(` `,`T`)).slice(0,16)}function Pk({value:e,busy:t,onCommit:n,unit:r,min:i,max:a,step:o,precision:s}){let[c,l]=h(MD(e,s)),u=Number(c),d=c!==``&&!Number.isNaN(u),f=o??1,p=e=>{let t=e;return i!==void 0&&(t=Math.max(i,t)),a!==void 0&&(t=Math.min(a,t)),t},m=()=>{!t&&d&&n(p(u))};return T(`div`,{className:`inline-flex items-center gap-1`,children:[v(`button`,{type:`button`,"aria-label":`Decrement`,disabled:t,onClick:r=>{if(r.stopPropagation(),!t){let t=p(e-f);l(MD(t,s)),n(t)}},className:G(`inline-flex h-5 w-5 items-center justify-center rounded border border-border bg-surface text-xs transition-colors hover:bg-surface-hover`,t&&`opacity-40 cursor-not-allowed`),children:`−`}),v(`input`,{"aria-label":`Numeric value`,type:`number`,disabled:t,value:c,onChange:e=>{l(e.target.value);let r=Number(e.target.value);e.target.value!==``&&!Number.isNaN(r)&&(t||n(p(r)))},onBlur:m,onKeyDown:e=>{e.key===`Enter`&&m()},className:G(`w-16 rounded border border-border bg-surface px-1 py-0.5 text-xs tabular-nums text-center`,t&&`opacity-40 cursor-not-allowed`)}),r!==void 0&&v(`span`,{className:`text-foreground-subtle text-xs`,children:r}),v(`button`,{type:`button`,"aria-label":`Increment`,disabled:t,onClick:r=>{if(r.stopPropagation(),!t){let t=p(e+f);l(MD(t,s)),n(t)}},className:G(`inline-flex h-5 w-5 items-center justify-center rounded border border-border bg-surface text-xs transition-colors hover:bg-surface-hover`,t&&`opacity-40 cursor-not-allowed`),children:`+`})]})}function Fk({value:e,busy:t,onCommit:n}){let[r,i]=h(e);return v(`input`,{type:`text`,disabled:t,value:r,onChange:e=>i(e.target.value),onBlur:()=>{t||n(r)},onKeyDown:e=>{e.key===`Enter`&&!t&&n(r)},className:G(`rounded border border-border bg-surface px-2 py-0.5 text-xs`,t&&`opacity-40 cursor-not-allowed`)})}function Ik({slice:e,busy:t,setValueFn:n,layout:r}){switch(e.kind){case`numeric`:return v(Pk,{value:typeof e.value==`number`?e.value:Number(e.value),busy:t,onCommit:e=>{n({control:{kind:`numeric`,value:e}})},unit:e.unit,min:e.min,max:e.max,step:e.step,precision:e.precision});case`select`:return v(`select`,{"aria-label":`Control value`,disabled:t,value:String(e.value),onChange:e=>{e.stopPropagation(),t||n({control:{kind:`select`,value:e.target.value}})},className:G(`w-full max-w-full min-w-0 truncate rounded border border-border bg-surface px-1 py-0.5 text-xs`,t&&`opacity-40 cursor-not-allowed`),children:e.options.map(e=>v(`option`,{value:e,children:e},e))});case`text`:return v(Fk,{value:String(e.value),busy:t,onCommit:e=>{n({control:{kind:`text`,value:e}})}});case`datetime`:{let i=String(e.value),a=e.format??`datetime`;return r===`compact`?i===``?v(`span`,{"aria-label":`Control value`,className:`text-xs text-foreground-subtle`,children:`—`}):v(`span`,{"aria-label":`Control value`,className:`text-xs text-foreground`,children:In(i,a)}):v(`input`,{type:a===`date`?`date`:a===`time`?`time`:`datetime-local`,"aria-label":`Control value`,disabled:t,value:a===`date`?jk(i):a===`time`?Mk(i):Nk(i),onChange:e=>{e.stopPropagation(),t||n({control:{kind:`datetime`,value:e.target.value}})},className:G(`rounded border border-border bg-surface px-1 py-0.5 text-xs`,t&&`opacity-40 cursor-not-allowed`)})}default:return null}}function Lk({trpc:e,deviceId:t,features:n,layout:r,optimistic:i}){let{cap:a,slice:o,available:s}=$f({trpc:e,deviceId:t,cap:e=>e.control,slice:e=>e.state.control}),{display:c,applyOptimistic:l}=um(o,{enabled:i??!0});if(c===void 0)return null;let u=!s;return v(`div`,{"data-kind":c.kind,className:`inline-flex min-w-0 max-w-full items-center gap-1 rounded border border-border px-2 py-1 transition-colors`,children:v(Ik,{slice:c,busy:u,setValueFn:e=>{!u&&a&&(l({value:e.control.value}),a.setValue(e))},layout:r})})}var Rk=5,zk=35;function Bk(e,t,n){return n<=t?0:Math.min(1,Math.max(0,(e-t)/(n-t)))}function Vk(e,t,n){return Math.round(t+e*(n-t))}var Hk=176,Uk=76,Wk=2*Math.PI*Uk,Gk=270/360*Wk,Kk=Hk/2-Uk-10;function qk(e){let t=Hk/2,n=Hk/2,r=Wk-Gk,i=e.mode===`band`?(()=>{let t=e.band.from*Gk,n=Math.max(0,(e.band.to-e.band.from)*Gk);return{dasharray:`${n} ${Wk-n}`,dashoffset:-t}})():(()=>{let t=e.fraction*Gk;return{dasharray:`${t} ${Wk-t}`,dashoffset:void 0}})();return T(`svg`,{width:Hk,height:Hk,viewBox:`0 0 ${Hk} ${Hk}`,"aria-hidden":`true`,className:`absolute inset-0`,style:{transform:`rotate(135deg)`},children:[v(`circle`,{cx:t,cy:n,r:Uk,fill:`none`,stroke:`var(--color-border)`,strokeWidth:12,strokeDasharray:`${Gk} ${r}`,strokeLinecap:`round`}),v(`circle`,{cx:t,cy:n,r:Uk,fill:`none`,stroke:e.color,strokeWidth:12,strokeDasharray:i.dasharray,...i.dashoffset===void 0?{}:{strokeDashoffset:i.dashoffset},strokeLinecap:`round`})]})}var Jk={heat:`#f59e0b`,cool:`#60a5fa`,auto:`#c084fc`,heat_cool:`#e879f9`,fan_only:`#94a3b8`,dry:`#22d3ee`,off:`#d4d4d8`};function Yk({trpc:e,deviceId:t,features:n,optimistic:r}){let{cap:i,slice:a,available:o}=$f({trpc:e,deviceId:t,cap:e=>e.climateControl,slice:e=>e.state.climateControl}),{display:s,applyOptimistic:c}=um(a,{enabled:r??!0});if(i===void 0||s===void 0)return null;let l=!o,u=Jk[s.mode],d=s.mode===`heat_cool`||s.targetLow!==null&&s.targetHigh!==null,f=Rk,p=zk,m=!d&&s.target!==null?Bk(s.target,f,p):0,h=d&&s.targetLow!==null?Bk(s.targetLow,f,p):0,g=d&&s.targetHigh!==null?Bk(s.targetHigh,f,p):0;return T(`div`,{"data-mode":s.mode,className:G(`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4 transition-colors`,bk[s.mode]),children:[T(`div`,{className:`flex flex-col items-center gap-3`,children:[T(`div`,{className:`relative`,style:{width:Hk,height:Hk},children:[d?v(qk,{mode:`band`,band:{from:h,to:g},color:u}):v(qk,{mode:`fill`,fraction:m,color:u}),d?T(E,{children:[v(`div`,{"data-testid":`arc-knob`,children:v(im,{fraction:h,color:u,knobTopPx:Kk,onDragFraction:e=>{if(l||s.targetHigh===null)return;let t=Math.min(Vk(e,f,p),s.targetHigh);c({targetLow:t}),i.setTargetRange({targetLow:t,targetHigh:s.targetHigh})}})}),v(`div`,{"data-testid":`arc-knob`,children:v(im,{fraction:g,color:u,knobTopPx:Kk,onDragFraction:e=>{if(l||s.targetLow===null)return;let t=Math.max(Vk(e,f,p),s.targetLow);c({targetHigh:t}),i.setTargetRange({targetLow:s.targetLow,targetHigh:t})}})})]}):v(`div`,{"data-testid":`arc-knob`,children:v(im,{fraction:m,color:u,knobTopPx:Kk,onDragFraction:e=>{if(l)return;let t=Vk(e,f,p);c({target:t}),i.setTarget({target:t})}})}),T(`div`,{className:`absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none`,children:[T(`div`,{"data-testid":`current-temp`,className:`text-4xl font-bold tabular-nums text-foreground leading-none`,children:[s.currentTemp===null?`—`:s.currentTemp,v(`span`,{className:`text-lg text-foreground-subtle font-normal ml-0.5`,children:`°`})]}),!d&&s.target!==null&&T(`div`,{className:`text-xs font-semibold`,style:{color:u},children:[`set `,s.target,`°`]}),d&&s.targetLow!==null&&s.targetHigh!==null&&T(`div`,{className:`text-xs font-semibold`,style:{color:u},children:[s.targetLow,`° – `,s.targetHigh,`°`]})]})]}),!d&&s.target!==null&&v(`div`,{className:`w-[200px]`,children:v(Qp,{value:`${s.target}°`,onDelta:e=>{if(l||s.target===null)return;let t=s.target+e;c({target:t}),i.setTarget({target:t})}})})]}),v(`select`,{"aria-label":`Mode`,value:s.mode,disabled:l,onChange:e=>{e.stopPropagation();let t=e.target.value;!l&&t&&(c({mode:s.availableModes.find(e=>e===t)??s.mode}),i.setMode({mode:s.availableModes.find(e=>e===t)??s.mode}))},className:G(`w-full rounded border border-border bg-surface px-3 py-1.5 text-sm`,l&&`opacity-40 cursor-not-allowed`),children:s.availableModes.map(e=>v(`option`,{value:e,children:e},e))})]})}function Xk(e){return e===`locked`||e===`locking`}function Zk(e){return e===`jammed`}var Qk={locked:{colorClass:`border-success/30 bg-success/10 text-success`,icon:`locked`},locking:{colorClass:`border-success/30 bg-success/10 text-success`,icon:`locked`},unlocked:{colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`open`},unlocking:{colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`open`},jammed:{colorClass:`border-danger/30 bg-danger/10 text-danger`,icon:`locked`}};function $k({state:e}){let t=Qk[e];return v(`div`,{"data-testid":`lock-glyph`,"data-state":e,className:G(`flex h-16 w-16 items-center justify-center rounded-full border-2`,t.colorClass),children:t.icon===`locked`?v(rl,{className:`h-8 w-8`,"aria-hidden":`true`}):v(nl,{className:`h-8 w-8`,"aria-hidden":`true`})})}function eA({state:e}){return v(`span`,{className:G(`text-sm font-medium capitalize`,Zk(e)?`text-danger`:`text-foreground-muted`),children:e})}function tA({busy:e,onOpen:t}){return T(`button`,{type:`button`,"aria-label":`Open (unlatch)`,title:`Open (unlatch)`,disabled:e,onClick:e=>{e.stopPropagation(),t()},className:G(`inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs font-medium`,`text-foreground-muted hover:bg-surface-hover transition-colors`,e&&`opacity-40 cursor-not-allowed`),children:[v(Cc,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Open`]})}function nA({trpc:e,deviceId:t,features:n,optimistic:r}){let{cap:i,slice:a,available:o}=$f({trpc:e,deviceId:t,cap:e=>e.lockControl,slice:e=>e.state.lockControl}),{display:s,applyOptimistic:c}=um(a,{enabled:r??!0});if(i===void 0||s===void 0)return null;let l=Xk(s.state),u=Zk(s.state)||!o,d=n?.includes(Ee.LockOpen)===!0,f=()=>{u||(l?(c({state:`unlocking`}),i.unlock({})):(c({state:`locking`}),i.lock({})))},p=()=>{u||i.open({})},m=l?`Unlock`:`Lock`;return T(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[T(`div`,{className:`flex flex-col items-center gap-2`,children:[v($k,{state:s.state}),v(eA,{state:s.state})]}),v(`div`,{className:G(u&&`pointer-events-none opacity-40`),children:v($p,{on:l,targetLabel:m,onConfirm:f})}),d&&v(`div`,{className:`flex justify-center`,children:v(tA,{busy:u,onOpen:p})})]})}var rA=150,iA=64,aA=rA/2,oA=2*Math.PI*iA,sA=270/360*oA;function cA({fraction:e,color:t,children:n,onDragFraction:r}){let i=Math.min(1,Math.max(0,e)),a=rA/2,o=rA/2,s=oA-sA,c=i*sA;return T(`div`,{className:`relative`,style:{width:rA,height:rA},children:[T(`svg`,{width:rA,height:rA,viewBox:`0 0 ${rA} ${rA}`,"aria-hidden":`true`,className:`absolute inset-0`,style:{transform:`rotate(135deg)`},children:[v(`circle`,{cx:a,cy:o,r:iA,fill:`none`,stroke:`var(--color-border)`,strokeWidth:11,strokeDasharray:`${sA} ${s}`,strokeLinecap:`round`}),v(`circle`,{cx:a,cy:o,r:iA,fill:`none`,stroke:t,strokeWidth:11,strokeDasharray:`${c} ${oA-c}`,strokeLinecap:`round`})]}),v(`div`,{"data-testid":`arc-knob`,children:v(im,{fraction:i,color:t,knobTopPx:aA-iA-10,...r===void 0?{}:{onDragFraction:r}})}),v(`div`,{className:`absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none`,children:n})]})}function lA({on:e,busy:t,onToggle:n}){let r={transform:e?`translateX(30px)`:`translateX(3px)`};return v(`button`,{type:`button`,"aria-pressed":e,title:e?`Turn off`:`Turn on`,disabled:t,onClick:e=>{e.stopPropagation(),n()},className:G(`relative inline-flex h-8 w-16 items-center rounded-full border transition-colors flex-shrink-0`,e?`bg-success/30 border-success/50`:`bg-surface-hover border-border`,t&&`opacity-60 cursor-not-allowed`),children:v(`span`,{className:G(`absolute h-6 w-6 rounded-full transition-all`,e?`bg-success`:`bg-foreground-subtle`),style:r})})}var uA=500,dA=150,fA=`linear-gradient(90deg, #9ec9ff, #ffffff, #ffb24d)`;function pA(e,t,n){return n<=t?0:Math.min(1,Math.max(0,(e-t)/(n-t)))}function mA(e){return pA(e,dA,uA)}var hA=`#f4b740`,gA=`#d4d4d8`;function _A({trpc:e,deviceId:t,features:n,optimistic:r}){let i=$f({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch}),a=$f({trpc:e,deviceId:t,cap:e=>e.brightness,slice:e=>e.state.brightness}),o=$f({trpc:e,deviceId:t,cap:e=>e.color,slice:e=>e.state.color}),s=um(i.slice,{enabled:r??!0}),c=um(a.slice,{enabled:r??!0}),l=um(o.slice,{enabled:r??!0});if(i.cap===void 0||s.display===void 0)return null;let u=s.display.on===!0,d=!i.available,f=c.display?.percentage??0,p=!a.available,m=u?f/100:0,h=u?hA:gA,g=(n?.includes(Ee.LightColorMired)??!1)&&o.cap!==void 0,_=l.display?.mireds,y=!o.available;return T(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[T(`div`,{className:`flex flex-col items-center gap-3`,children:[T(cA,{fraction:m,color:h,children:[T(`div`,{"data-testid":`brightness-readout`,className:`text-3xl font-bold tabular-nums text-foreground leading-none`,children:[f,v(`span`,{className:`text-base text-foreground-subtle font-normal ml-0.5`,children:`%`})]}),v(Zc,{className:`h-5 w-5 text-foreground-subtle`,"aria-hidden":`true`})]}),a.cap!==void 0&&T(`label`,{className:`flex w-full items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{className:`w-16`,children:`Brightness`}),v(`input`,{"aria-label":`Brightness`,type:`range`,min:0,max:100,step:1,className:`flex-1`,value:f,disabled:p||!u,onChange:e=>{let t=Number(e.target.value);c.applyOptimistic({percentage:t}),p||a.cap?.setBrightness({percentage:t})}}),T(`span`,{className:`tabular-nums w-9 text-right`,children:[f,`%`]})]})]}),T(`div`,{className:`flex items-center justify-between`,children:[v(`span`,{className:`text-sm font-medium text-foreground-muted`,children:u?`On`:`Off`}),v(lA,{on:u,busy:d,onToggle:()=>{if(d)return;let e=!u;s.applyOptimistic({on:e}),i.cap?.setState({on:e})}})]}),g&&T(`div`,{className:`flex items-center gap-2`,"data-testid":`color-temp-strip`,children:[v(nu,{className:`h-4 w-4 text-foreground-subtle`,"aria-hidden":`true`}),T(`label`,{className:`flex-1`,children:[v(`span`,{className:`sr-only`,children:`Colour temperature`}),v(`input`,{"aria-label":`Colour temperature`,type:`range`,min:dA,max:uA,step:1,className:`w-full`,value:_??uA,disabled:y||!u,onChange:e=>{let t=Number(e.target.value);l.applyOptimistic({mode:`mired`,mireds:t}),y||o.cap?.setColor({color:{mode:`mired`,mireds:t}})}}),v(`div`,{className:`pointer-events-none mt-1`,children:v(am,{fraction:_===void 0?.5:mA(_),color:fA})})]})]})]})}var vA=`#3aa6a0`,yA=`#d4d4d8`;function bA({trpc:e,deviceId:t,features:n,optimistic:r}){let i=$f({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch}),a=$f({trpc:e,deviceId:t,cap:e=>e.fanControl,slice:e=>e.state.fanControl}),o=um(i.slice,{enabled:r??!0}),s=um(a.slice,{enabled:r??!0});if(i.cap===void 0||o.display===void 0)return null;let c=o.display.on===!0,l=!i.available,u=s.display?.percentage??0,d=!a.available,f=c?u/100:0,p=c?vA:yA,m=n?.includes(Ee.FanSpeed)??!1,h=(n?.includes(Ee.FanOscillating)??!1)&&a.cap!==void 0,g=s.display?.availablePresets??[],_=(n?.includes(Ee.FanPreset)??!1)&&a.cap!==void 0&&g.length>0,y=s.display?.preset??``,b=s.display?.oscillating===!0,x=()=>{if(l)return;let e=!c;o.applyOptimistic({on:e}),i.cap?.setState({on:e})},S=()=>{if(d)return;let e=!b;s.applyOptimistic({oscillating:e}),a.cap?.setOscillating({oscillating:e})},C=e=>{if(d)return;let t=s.display;if(t===void 0)return;let n=t.percentageStep!==void 0&&t.percentageStep>0?t.percentageStep:1,r=Math.min(100,Math.max(0,Math.round(e*100/n)*n));s.applyOptimistic({percentage:r}),a.cap?.setPercentage({percentage:r})},w=e=>{d||e===``||(s.applyOptimistic({preset:e}),a.cap?.setPreset({preset:e}))};return T(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4`,children:[v(`div`,{className:`flex flex-col items-center gap-3`,children:m?T(cA,{fraction:f,color:p,onDragFraction:C,children:[T(`div`,{"data-testid":`speed-readout`,className:`text-3xl font-bold tabular-nums text-foreground leading-none`,children:[u,v(`span`,{className:`text-base text-foreground-subtle font-normal ml-0.5`,children:`%`})]}),v(jc,{className:`h-5 w-5 text-foreground-subtle`,"aria-hidden":`true`})]}):v(`div`,{"data-testid":`fan-onoff-icon`,className:`flex h-[150px] w-[150px] items-center justify-center`,children:v(jc,{className:`h-16 w-16`,style:{color:p},"aria-hidden":`true`})})}),_&&v(`div`,{className:`flex justify-center`,children:T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{children:`Preset`}),T(`select`,{"aria-label":`Fan preset`,value:y,disabled:d,onChange:e=>{e.stopPropagation(),w(e.target.value)},className:G(`bg-surface border border-border rounded px-1 py-0.5`,d&&`opacity-40 cursor-not-allowed`),children:[v(`option`,{value:``,disabled:!0,children:`—`}),g.map(e=>v(`option`,{value:e,children:e},e))]})]})}),T(`div`,{className:`flex items-center justify-between gap-2`,children:[h?T(`button`,{type:`button`,"aria-label":`Oscillate`,"aria-pressed":b,disabled:d,onClick:e=>{e.stopPropagation(),S()},className:G(`inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium transition-colors`,b?`border-success/50 bg-success/10 text-success`:`border-border text-foreground-muted hover:bg-surface-hover`,d&&`opacity-40 cursor-not-allowed`),children:[v(jl,{className:`h-3.5 w-3.5`,"aria-hidden":`true`}),`Oscillate`]}):v(`span`,{className:`text-sm font-medium text-foreground-muted`,children:c?`On`:`Off`}),v(lA,{on:c,busy:l,onToggle:x})]})]})}function xA({trpc:e,deviceId:t,optimistic:n}){let{cap:r,slice:i,available:a}=$f({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch}),{display:o,applyOptimistic:s}=um(i,{enabled:n??!0});if(r===void 0||o===void 0)return null;let c=o.on===!0,l=!a;return T(`div`,{className:`flex flex-col items-center gap-4 rounded-lg border border-border bg-surface p-6`,children:[v(`div`,{"data-testid":`switch-glyph`,"data-state":c?`on`:`off`,className:G(`flex h-16 w-16 items-center justify-center rounded-full border-2 transition-colors`,c?`border-success/30 bg-success/10 text-success`:`border-border bg-surface-subtle text-foreground-subtle`),children:v(Dl,{className:`h-8 w-8`,"aria-hidden":`true`})}),v(`span`,{className:`text-sm font-medium text-foreground-muted`,children:c?`On`:`Off`}),v(lA,{on:c,busy:l,onToggle:()=>{if(l)return;let e=!c;s({on:e}),r.setState({on:e})}})]})}function SA(e){return e===`playing`||e===`buffering`?`pause`:`play`}function CA(e,t){return e===null||t===null||t<=0?0:Math.min(1,Math.max(0,e/t))}function wA(e){if(e===null)return`--:--`;let t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,`0`)}`}function TA({title:e,subtitle:t}){return T(`div`,{className:`flex flex-col items-center gap-1 text-center`,children:[v(_l,{className:`h-6 w-6 text-foreground-subtle`,"aria-hidden":`true`}),v(`span`,{className:`text-base font-semibold text-foreground line-clamp-1`,children:e??`Nothing playing`}),t&&v(`span`,{className:`text-xs text-foreground-subtle line-clamp-1`,children:t})]})}function EA({label:e,busy:t,onPress:n,children:r,primary:i}){return v(`button`,{type:`button`,"aria-label":e,title:e,disabled:t,onClick:e=>{e.stopPropagation(),t||n()},className:G(`inline-flex items-center justify-center rounded-full transition-colors`,i?`h-12 w-12 bg-primary text-primary-foreground hover:bg-primary/90 shadow-md`:`h-10 w-10 text-foreground-muted hover:bg-surface-hover`,t&&`opacity-40 cursor-not-allowed`),children:r})}function DA({trpc:e,deviceId:t,features:n,optimistic:r}){let{cap:i,slice:a,available:o}=$f({trpc:e,deviceId:t,cap:e=>e.mediaPlayer,slice:e=>e.state.mediaPlayer}),{display:s,applyOptimistic:c}=um(a,{enabled:r??!0});if(i===void 0||s===void 0)return null;let l=!o,u=SA(s.state),d=(n?.includes(Ee.MediaPlayerSeek)??!1)&&s.durationMs!==null&&s.durationMs>0,f=n?.includes(Ee.MediaPlayerNext)??!1,p=n?.includes(Ee.MediaPlayerPrevious)??!1,m=(n?.includes(Ee.MediaPlayerVolume)??!1)&&s.volumeLevel!==null,h=()=>{l||(u===`play`?(c({state:`playing`}),i.play({})):(c({state:`paused`}),i.pause({})))},g=s.currentMedia?.artist??s.currentMedia?.album??null,_=CA(s.positionMs,s.durationMs),y=s.volumeLevel??0;return T(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6`,children:[v(TA,{title:s.currentMedia?.title??null,subtitle:g}),d&&T(`div`,{"data-testid":`media-seek`,className:`flex flex-col gap-1`,children:[T(`label`,{className:`relative block`,children:[v(`span`,{className:`sr-only`,children:`Seek`}),v(`input`,{"aria-label":`Seek`,type:`range`,min:0,max:s.durationMs??0,step:1e3,className:`absolute inset-0 h-4 w-full cursor-pointer opacity-0`,value:s.positionMs??0,disabled:l,onChange:e=>{if(l)return;let t=Number(e.target.value);c({positionMs:t}),i.seek({positionMs:t})}}),v(`div`,{className:`pointer-events-none`,children:v(am,{fraction:_})})]}),T(`div`,{className:`flex justify-between text-[11px] tabular-nums text-foreground-subtle`,children:[v(`span`,{children:wA(s.positionMs)}),v(`span`,{children:wA(s.durationMs)})]})]}),T(`div`,{className:`flex items-center justify-center gap-4`,children:[p&&v(EA,{label:`Previous`,busy:l,onPress:()=>void i.previous({}),children:v(ql,{className:`h-5 w-5`,"aria-hidden":`true`})}),v(EA,{label:u===`play`?`Play`:`Pause`,busy:l,onPress:h,primary:!0,children:v(u===`play`?Cl:bl,{className:`h-6 w-6`,"aria-hidden":`true`})}),f&&v(EA,{label:`Next`,busy:l,onPress:()=>void i.next({}),children:v(Jl,{className:`h-5 w-5`,"aria-hidden":`true`})})]}),m&&T(`div`,{"data-testid":`media-volume`,className:`flex items-center gap-2`,children:[v(`button`,{type:`button`,"aria-label":s.isMuted===!0?`Unmute`:`Mute`,title:s.isMuted===!0?`Unmute`:`Mute`,disabled:l,onClick:e=>{if(e.stopPropagation(),l||s.isMuted===null)return;let t=!s.isMuted;c({isMuted:t}),i.setMute({muted:t})},className:G(`inline-flex h-7 w-7 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,l&&`opacity-40 cursor-not-allowed`),children:s.isMuted===!0?v(mu,{className:`h-4 w-4`,"aria-hidden":`true`}):v(pu,{className:`h-4 w-4`,"aria-hidden":`true`})}),T(`label`,{className:`relative block flex-1`,children:[v(`span`,{className:`sr-only`,children:`Volume`}),v(`input`,{"aria-label":`Volume`,type:`range`,min:0,max:100,step:1,className:`absolute inset-0 h-4 w-full cursor-pointer opacity-0`,value:y,disabled:l,onChange:e=>{if(l)return;let t=Number(e.target.value);c({volumeLevel:t}),i.setVolume({volumeLevel:t})}}),v(`div`,{className:`pointer-events-none`,children:v(am,{fraction:y/100})})]}),T(`span`,{className:`w-9 text-right text-[11px] tabular-nums text-foreground-subtle`,children:[y,`%`]})]})]})}var OA={disarmed:{label:`Disarmed`,colorClass:`border-border bg-surface-subtle text-foreground-subtle`,icon:`disarmed`},armed_home:{label:`Armed Home`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},armed_away:{label:`Armed Away`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},armed_night:{label:`Armed Night`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},armed_vacation:{label:`Armed Vacation`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},armed_custom_bypass:{label:`Armed (Bypass)`,colorClass:`border-success/30 bg-success/10 text-success`,icon:`armed`},arming:{label:`Arming…`,colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`pending`},disarming:{label:`Disarming…`,colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`pending`},pending:{label:`Pending`,colorClass:`border-warning/30 bg-warning/10 text-warning`,icon:`pending`},triggered:{label:`Triggered`,colorClass:`border-danger/30 bg-danger/10 text-danger`,icon:`triggered`}},kA={home:`Home`,away:`Away`,night:`Night`,vacation:`Vacation`,custom_bypass:`Bypass`};function AA(e){return e.startsWith(`armed_`)}function jA(e){return e===`arming`||e===`disarming`}function MA({icon:e}){return v(e===`disarmed`?Ul:e===`triggered`?Vl:e===`pending`?Wl:Hl,{className:`h-8 w-8`,"aria-hidden":`true`})}function NA({label:e,active:t,busy:n,onSelect:r}){return v(`button`,{type:`button`,"aria-label":e,"aria-pressed":t,disabled:n,onClick:e=>{e.stopPropagation(),n||r()},className:G(`flex-1 rounded-md px-3 py-2 text-sm font-medium transition-colors`,t?`bg-primary text-primary-foreground shadow-sm`:`text-foreground-muted hover:bg-surface-hover`,n&&`opacity-40 cursor-not-allowed`),children:e})}function PA({state:e,availableModes:t,busy:n,onDisarm:r,onArm:i}){let a=AA(e),o=jA(e);return T(`div`,{className:`flex items-stretch gap-1 rounded-lg border border-border bg-surface-subtle p-1`,children:[v(NA,{label:`Disarm`,active:!a&&!o,busy:n,onSelect:r}),t.map(t=>v(NA,{label:kA[t],active:!o&&e===`armed_${t}`,busy:n,onSelect:()=>i(t)},t))]})}function FA(e,t,n){let{cap:r,slice:i,available:a}=$f({trpc:e,deviceId:t,cap:e=>e.alarmPanel,slice:e=>e.state.alarmPanel}),{display:o,applyOptimistic:s}=um(i,{enabled:n??!0}),c=!a;return{display:o,capPresent:r!==void 0,busy:c,handleDisarm:()=>{r===void 0||c||(s({state:`disarming`}),r.disarm({}))},handleArm:e=>{r===void 0||c||(s({state:`arming`}),r.arm({mode:e}))}}}function IA({trpc:e,deviceId:t,optimistic:n}){let{display:r,capPresent:i,busy:a,handleDisarm:o,handleArm:s}=FA(e,t,n);return!i||r===void 0?null:v(PA,{state:r.state,availableModes:r.availableModes,busy:a,onDisarm:o,onArm:s})}function LA({trpc:e,deviceId:t,optimistic:n}){let{display:r,capPresent:i,busy:a,handleDisarm:o,handleArm:s}=FA(e,t,n);if(!i||r===void 0)return null;let c=OA[r.state];return T(`div`,{className:`flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6`,children:[T(`div`,{className:`flex flex-col items-center gap-2`,children:[v(`div`,{"data-testid":`alarm-state`,"data-state":r.state,className:G(`flex h-16 w-16 items-center justify-center rounded-full border-2`,c.colorClass),children:v(MA,{icon:c.icon})}),v(`span`,{className:`text-sm font-medium text-foreground-muted`,children:c.label})]}),v(PA,{state:r.state,availableModes:r.availableModes,busy:a,onDisarm:o,onArm:s})]})}function RA({children:e}){return v(`div`,{className:`flex flex-col items-stretch gap-3 rounded-lg border border-border bg-surface p-4`,children:e})}function zA(e,t){let{cap:n}=$f({trpc:e,deviceId:t,cap:e=>e.switch,slice:e=>e.state.switch});return n!==void 0}function BA({trpc:e,deviceId:t,features:n,optimistic:r}){return zA(e,t)?v(hk,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function VA(e,t){let{cap:n}=$f({trpc:e,deviceId:t,cap:e=>e.lockControl,slice:e=>e.state.lockControl});return n!==void 0}function HA({trpc:e,deviceId:t,features:n,optimistic:r}){return VA(e,t)?v(_k,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function UA({trpc:e,deviceId:t,features:n,optimistic:r}){return zA(e,t)?T(`div`,{className:`inline-flex items-center gap-2`,children:[v(hk,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}),v(vk,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r})]}):null}function WA(e,t){let{cap:n}=$f({trpc:e,deviceId:t,cap:e=>e.fanControl,slice:e=>e.state.fanControl});return n!==void 0}function GA({trpc:e,deviceId:t,features:n,optimistic:r}){return WA(e,t)?T(`div`,{className:`inline-flex items-center gap-2`,children:[v(hk,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}),v(yk,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r})]}):null}function KA(e,t){let{cap:n}=$f({trpc:e,deviceId:t,cap:e=>e.climateControl,slice:e=>e.state.climateControl});return n!==void 0}function qA({trpc:e,deviceId:t,features:n,optimistic:r}){return KA(e,t)?v(Ck,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function JA(e,t){let{cap:n}=$f({trpc:e,deviceId:t,cap:e=>e.mediaPlayer,slice:e=>e.state.mediaPlayer});return n!==void 0}function YA({trpc:e,deviceId:t,features:n,optimistic:r}){return JA(e,t)?v(Ak,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function XA(e,t){let{cap:n}=$f({trpc:e,deviceId:t,cap:e=>e.control,slice:e=>e.state.control});return n!==void 0}function ZA({trpc:e,deviceId:t,features:n,optimistic:r}){return XA(e,t)?v(Lk,{trpc:e,deviceId:t,features:n,layout:`compact`,optimistic:r}):null}function QA({trpc:e,deviceId:t,features:n,optimistic:r}){return XA(e,t)?v(RA,{children:v(Lk,{trpc:e,deviceId:t,features:n,layout:`full`,optimistic:r})}):null}var $A={InlineControl:mm,HeroCard:ym},ej={InlineControl:bm,HeroCard:xm},tj={InlineControl:GD,HeroCard:eO},nj={InlineControl:rO,HeroCard:iO},rj={InlineControl:BA,HeroCard:xA},ij={InlineControl:HA,HeroCard:nA},aj={InlineControl:UA,HeroCard:_A},oj={InlineControl:GA,HeroCard:bA},sj={InlineControl:qA,HeroCard:Yk},cj={InlineControl:YA,HeroCard:DA},lj={InlineControl:IA,HeroCard:LA},uj={InlineControl:ZA,HeroCard:QA},dj={InlineControl:gO,HeroCard:vO},fj={InlineControl:TO,HeroCard:DO},pj={InlineControl:MO,HeroCard:LO},mj={InlineControl:BO,HeroCard:HO},hj={InlineControl:KO,HeroCard:JO},gj={InlineControl:ek,HeroCard:ak},_j={InlineControl:pk,HeroCard:mk},vj={[V.Cover]:$A,[V.Valve]:pj,[V.Humidifier]:mj,[V.WaterHeater]:hj,[V.Camera]:ej,[V.Hub]:ej,[V.Switch]:rj,[V.Siren]:rj,[V.Light]:aj,[V.Fan]:oj,[V.Sensor]:tj,[V.Thermostat]:sj,[V.Button]:{InlineControl:om,HeroCard:sm},[V.EventEmitter]:ej,[V.Update]:nj,[V.Generic]:ej,[V.Notifier]:ej,[V.Script]:ej,[V.Automation]:ej,[V.Lock]:ij,[V.MediaPlayer]:cj,[V.AlarmPanel]:lj,[V.Control]:uj,[V.Presence]:tj,[V.Weather]:gj,[V.Vacuum]:dj,[V.LawnMower]:fj,[V.Container]:ej,[V.Image]:_j},yj={[V.Cover]:!0,[V.Valve]:!0,[V.Thermostat]:!0,[V.Control]:!0,[V.Button]:!0,[V.MediaPlayer]:!0,[V.AlarmPanel]:!0,[V.Lock]:!1,[V.Vacuum]:!1,[V.LawnMower]:!1,[V.Humidifier]:!1,[V.Switch]:!1,[V.Siren]:!1,[V.Light]:!1,[V.Fan]:!1,[V.WaterHeater]:!1,[V.Sensor]:!1,[V.Presence]:!1,[V.EventEmitter]:!1,[V.Notifier]:!1,[V.Script]:!1,[V.Automation]:!1,[V.Camera]:!1,[V.Hub]:!1,[V.Update]:!1,[V.Generic]:!1,[V.Weather]:!1,[V.Container]:!1,[V.Image]:!1},bj=new Set(Object.values(V));function xj(e){return bj.has(e)?vj[e]:null}function Sj(e,t){return t===`table`?`fit`:bj.has(e)&&yj[e]?qp:t===`center`?Yp:Jp}function Cj(e){return e instanceof Error?e.message:String(e)}function wj({trpc:e,deviceId:t,deviceName:n}){let{dev:r,cap:i}=$f({trpc:e,deviceId:t,cap:e=>e.reboot,slice:()=>void 0}),[a,o]=h(!1),[s,c]=h(!1),[l,u]=h(null);if(r===null||i==null)return null;let d=e=>{e.stopPropagation(),u(null),o(!0)},f=async()=>{if(!s){u(null),c(!0);try{await i.reboot({}),o(!1)}catch(e){u(Cj(e))}finally{c(!1)}}};return T(E,{children:[v(`button`,{type:`button`,onClick:d,className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors flex-shrink-0`,a&&`bg-surface-hover text-foreground`),title:`Reboot device`,"aria-label":`Reboot device`,"aria-haspopup":`dialog`,"aria-expanded":a,children:v(Nl,{className:`h-3 w-3`})}),v(Xu,{open:a,onOpenChange:e=>{s||o(e)},children:T($u,{width:`sm`,onClick:e=>e.stopPropagation(),children:[T(ed,{children:[T(nd,{className:`flex items-center gap-2`,children:[v(Nl,{className:`h-4 w-4 text-amber-400`}),`Reboot device?`]}),T(rd,{children:[`This will restart `,n,`. It may be unavailable for a moment.`]})]}),l!==null&&v(`div`,{className:`mt-2 px-3 py-2 rounded border border-danger/40 bg-danger/10 text-xs text-danger`,children:l}),T(td,{children:[v(ju,{type:`button`,variant:`ghost`,size:`sm`,disabled:s,onClick:()=>{s||o(!1)},children:`Cancel`}),T(ju,{type:`button`,variant:`danger`,size:`sm`,disabled:s,onClick:()=>{f()},children:[s&&v(el,{className:`h-3.5 w-3.5 animate-spin`}),`Reboot`]})]})]})})]})}var Tj=new Set([V.Sensor,V.Presence]);function Ej({trpc:e,device:t,controlPlacement:n}){let r=Hp(t.id),i=n??`right`;if(t.disabled)return null;if(t.type===V.Container){let n=vp(r,t.linkDeviceId,t.primaryChildEntityId),a=n===null?void 0:r.find(e=>e.id===n.id);return a===void 0?null:v(Dj,{trpc:e,child:a,placement:i})}let a=Tj.has(t.type),o=(a?null:xj(t.type))?.InlineControl??null,s=Sj(t.type,i),c=kp(t),l=(t.features??[]).includes(`rebootable`),u=(t.features??[]).includes(`pan-tilt-zoom`);return T(E,{children:[a&&T(Xp,{align:Sj(t.type,i),children:[c&&v(Oj,{trpc:e,deviceId:t.id,features:t.features}),v(UD,{trpc:e,device:t})]}),o!==null&&T(Xp,{align:s,onClick:e=>e.stopPropagation(),children:[c&&v(Oj,{trpc:e,deviceId:t.id,features:t.features}),v(o,{trpc:e,deviceId:t.id,features:t.features})]}),!a&&o===null&&c&&v(Oj,{trpc:e,deviceId:t.id,features:t.features}),u&&v(jj,{trpc:e,deviceId:t.id}),l&&v(wj,{trpc:e,deviceId:t.id,deviceName:t.name})]})}function Dj({trpc:e,child:t,placement:n}){if(Tj.has(t.type))return v(Xp,{align:Sj(t.type,n),children:v(UD,{trpc:e,device:t})});let r=xj(t.type)?.InlineControl??null;return r===null?null:v(Xp,{align:Sj(t.type,n),onClick:e=>e.stopPropagation(),children:v(r,{trpc:e,deviceId:t.id,features:t.features})})}function Oj({trpc:e,deviceId:t,features:n}){let{dev:r,cap:i,slice:a,available:o}=$f({trpc:e,deviceId:t,cap:e=>e.motionTrigger,slice:e=>e.state.motionTrigger,requireFeature:`motion-trigger`,deviceFeatures:n}),[s,c]=h(!1);if(r!==null&&!i)return null;let l=a?.enabled===!0,u=async e=>{if(e.stopPropagation(),!(s||!o||!i)){c(!0);try{await i.setMotionTrigger({enabled:!l})}finally{c(!1)}}};return v(`button`,{type:`button`,onClick:e=>{u(e)},disabled:s||!o,className:G(`inline-flex h-4 w-4 items-center justify-center rounded transition-colors flex-shrink-0`,l?`text-primary bg-primary/10`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,(s||!o)&&`opacity-50`),title:o?l?`Motion-trigger: on (click to disable)`:`Motion-trigger: off (click to enable)`:`Awaiting state…`,"aria-pressed":l,children:v(Ds,{className:`h-2.5 w-2.5`})})}var kj=4,Aj=300;function jj({trpc:e,deviceId:t}){let n=p(null),r=p(null),[i,a]=h(null),o=i!==null,s=Wp(e,t,{enabled:o}),l=()=>a(null),u=()=>{let e=n.current;if(!e)return;let t=e.getBoundingClientRect(),r=Math.min(Aj,window.innerWidth-16),i=Math.max(8,Math.min(t.right-r,window.innerWidth-r-8)),o=t.bottom+kj;a({top:o,left:i,width:r,maxHeight:Math.max(160,window.innerHeight-o-8)})};return c(()=>{if(!o)return;let e=e=>{let t=n.current,i=r.current,a=e.target;a!==null&&(t&&t.contains(a)||i&&i.contains(a)||l())},t=e=>{e.key===`Escape`&&(e.stopPropagation(),l())};return document.addEventListener(`mousedown`,e),document.addEventListener(`touchstart`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`touchstart`,e),document.removeEventListener(`keydown`,t)}},[o]),T(E,{children:[v(`button`,{ref:n,type:`button`,onClick:e=>{e.stopPropagation(),o?l():u()},className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors flex-shrink-0`,o&&`bg-surface-hover text-foreground`),title:`PTZ controls`,"aria-label":`PTZ controls`,"aria-haspopup":`dialog`,"aria-expanded":o,children:v(Rc,{className:`h-3 w-3`})}),i&&A(v(`div`,{ref:r,style:{position:`fixed`,top:i.top,left:i.left,width:i.width,maxHeight:i.maxHeight},className:`z-[9999] overflow-y-auto rounded-lg border border-border bg-surface shadow-lg shadow-black/30`,onClick:e=>e.stopPropagation(),children:v(Kp,{mode:`panel`,controls:s})}),document.body)]})}function Mj({icon:e,label:t,onClick:n,danger:r=!1}){return v(`button`,{type:`button`,"aria-label":t,title:t,onClick:n,className:G(`inline-flex h-6 w-6 items-center justify-center rounded transition-colors flex-shrink-0`,r?`text-danger hover:bg-danger/10`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`),children:v(e,{className:`h-3.5 w-3.5`})})}function Nj({device:e,onDelete:t}){let n=Lf(),r=async()=>{await n({title:`Delete device?`,message:`This will remove "${e.name.trim()===``?`#${String(e.id)}`:e.name}" and all its settings. This action cannot be undone.`,confirmLabel:`Delete`,variant:`danger`})&&t(e)};return v(`span`,{onClick:e=>e.stopPropagation(),children:v(Mj,{icon:au,label:`Delete device`,danger:!0,onClick:()=>{r()}})})}var Pj=Object.freeze([]);function Fj(e){return e===`native`?`native`:`enhanced`}function Ij(e){return e.map(e=>({kind:`marker`,feature:e}))}function Lj(e,t){let n=new Map,r=t.entries??[];for(let e of r)n.set(e.capName,e);let i=[];for(let t of e){let e=Tp[t];if(e===void 0){i.push({kind:`marker`,feature:t});continue}let r=n.get(e);r&&i.push({kind:Fj(r.kind),feature:t,capName:e})}return i}function Rj(e,t,n){let[r,i]=h(null),[a,o]=h(!1),[s,l]=h(!0);return c(()=>{if(t===null){i(null),o(!1),l(!1);return}let n=!1;l(!0),o(!1);let r=async()=>{try{let r=await e.deviceManager.getBindings.query({deviceId:t});if(n)return;i(r),l(!1)}catch{if(n)return;o(!0),l(!1)}};r();let a=e.live?.onEvent.subscribe({category:`capability.binding-changed`},{onData:e=>{let n=e.data?.source;if(!n){r();return}n.type===`device`&&n.id===t&&r()}});return()=>{n=!0,a?.unsubscribe()}},[e,t]),n.length===0?{loading:s,resolved:Pj}:s||a||!r?{loading:s,resolved:Ij(n)}:{loading:!1,resolved:Lj(n,r)}}var zj=[];function Bj({trpc:e,device:t,flags:n,accessoryCount:r,adoptedCount:i,showFeatureRow:a=!1}){let o=r+i,s=n.showChildrenAccordion&&o>0,c=t.features??zj,l=a&&c.length>0,{resolved:u}=Rj(e,l?t.id:null,c),d=l&&u.length>0;return!s&&!d?null:T(`div`,{className:`flex items-center gap-1.5 flex-nowrap whitespace-nowrap min-w-0`,children:[s&&v(Vj,{accessoryCount:r,adoptedCount:i}),d&&v(Wj,{resolved:u})]})}function Vj({accessoryCount:e,adoptedCount:t}){let n=e+t;return n===0?null:T(`span`,{className:`text-[9px] font-medium text-foreground-subtle bg-surface-elevated/60 rounded px-1.5 py-0.5 flex-shrink-0`,title:t>0&&e>0?`${String(t)} adopted · ${String(e)} accessor${e===1?`y`:`ies`}`:t>0?`${String(t)} adopted`:`${String(e)} accessor${e===1?`y`:`ies`}`,children:[`+`,n]})}var Hj=240,Uj=200;function Wj({resolved:e}){let t=p(null),[n,r]=h(null);return T(`span`,{ref:t,className:`relative inline-flex items-center gap-1 cursor-help`,onMouseEnter:()=>{let e=t.current;if(!e)return;let n=e.getBoundingClientRect();r({top:window.innerHeight-n.bottom>=Uj?n.bottom+4:n.top-Uj-4,left:Math.max(8,Math.min(n.left,window.innerWidth-Hj-8))})},onMouseLeave:()=>r(null),children:[e.map(e=>{let t=Cp[e.feature];return t?v(`span`,{className:`inline-flex items-center justify-center h-4 w-4 rounded bg-surface-elevated/60 text-foreground-subtle`,title:wp[e.feature]??e.feature,children:v(t,{className:`h-2.5 w-2.5`})},e.feature):null}),n&&A(v(Gj,{resolved:e,position:n}),document.body)]})}function Gj({resolved:e,position:t}){return T(`div`,{style:{position:`fixed`,top:t.top,left:t.left,width:Hj,pointerEvents:`none`},className:`z-[9999] rounded-md border border-border bg-surface shadow-lg shadow-black/30 p-2`,children:[v(`h5`,{className:`text-[9px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5`,children:`Features`}),v(`ul`,{className:`space-y-0.5`,children:e.map(e=>v(Kj,{entry:e},e.feature))})]})}function Kj({entry:e}){let t=Cp[e.feature],n=wp[e.feature]??e.feature;return T(`li`,{className:`flex items-center justify-between gap-2 text-[10px]`,children:[T(`span`,{className:`flex items-center gap-1.5 text-foreground`,children:[t&&v(t,{className:`h-3 w-3 text-foreground-subtle`}),v(`span`,{children:n})]}),v(qj,{kind:e.kind})]})}function qj({kind:e}){return e===`marker`?v(`span`,{className:`text-[8.5px] px-1 rounded text-foreground-subtle`,title:`Informational marker (no cap registered)`,children:`marker`}):v(`span`,{className:G(`text-[8.5px] px-1 rounded`,e===`native`?`bg-success/15 text-success`:`bg-primary/15 text-primary`),children:e})}var Jj={horizontal:`h-3.5 w-3.5`,stacked:`h-4 w-4 mt-0.5`};function Yj({device:e,variant:t,flags:n,parent:r,integrationIcon:i,hasChildren:a,expanded:o,onToggleExpand:s,onNavigateToParent:c,stacked:l=!1}){let u=Sp(Mp(e,Hp(e.id))),d=l?Jj.stacked:Jj.horizontal;return T(`div`,{className:G(l?`flex items-start gap-2 w-full min-w-0`:`flex items-center gap-2 flex-1 min-w-0`),children:[n.showChildrenAccordion&&a?v(`button`,{type:`button`,"data-testid":`chevron-slot`,onClick:e=>{e.stopPropagation(),s()},className:G(`flex items-center justify-center text-foreground-subtle hover:text-foreground transition-colors flex-shrink-0`,d),"aria-label":o?`Collapse children`:`Expand children`,"aria-expanded":o,children:v(o?Xs:Qs,{className:`h-3 w-3`})}):n.showChildrenAccordion?v(`span`,{"data-testid":`chevron-slot`,className:G(`flex-shrink-0`,d)}):null,v(u,{className:G(`text-foreground-subtle flex-shrink-0`,l?`h-4 w-4 mt-0.5`:t===`minimal`?`h-3 w-3`:`h-3.5 w-3.5`)}),T(`div`,{className:`flex-1 min-w-0`,children:[T(`div`,{className:G(`min-w-0`,l?`flex flex-col gap-1`:`flex items-center gap-1.5`),children:[n.showIntegrationIcon&&i&&v(`span`,{className:`flex-shrink-0`,children:i}),v(`span`,{className:G(`font-semibold text-foreground`,l?`text-[13px] leading-snug line-clamp-2 break-words`:G(`truncate`,t===`minimal`?`text-[10.5px]`:`text-[11px]`)),title:e.name,children:e.name})]}),(n.showId||n.showStableId)&&T(`div`,{className:`mt-0.5 flex items-center gap-1 text-[9px] text-foreground-subtle font-mono truncate`,title:n.showStableId?`stableId: ${e.stableId}`:void 0,children:[n.showId&&T(`span`,{className:`flex-shrink-0 tabular-nums`,children:[`#`,String(e.id)]}),n.showId&&n.showStableId&&v(`span`,{className:`flex-shrink-0 opacity-50`,children:`·`}),n.showStableId&&v(`span`,{className:`truncate`,children:Np(e.stableId)})]}),n.showParentBadge&&r&&T(`button`,{type:`button`,onClick:e=>{e.stopPropagation(),c(r.id)},className:`mt-0.5 inline-flex max-w-full items-center gap-1 text-[9px] text-foreground-subtle hover:text-primary transition-colors`,title:`Open parent: ${r.name} (#${String(r.id)})`,children:[v(yl,{className:`h-2.5 w-2.5 shrink-0`}),T(`span`,{className:`truncate`,children:[`Under: `,r.name]})]})]})]})}function Xj(e,t){return Qf(e,t,e=>e.battery)??null}function Zj(e,t){let n=Xf(e,t),r=p(!1),{data:i,isLoading:a,isFetching:o,refetch:s}=_({queryKey:[`device`,t,`snapshot`],queryFn:()=>{if(!n)throw Error(`useDeviceSnapshotImage: device proxy not ready`);let e=r.current;return r.current=!1,n.snapshot?.getSnapshot({force:e})??null},enabled:n!==null&&t!==null,staleTime:1e4,gcTime:1440*60*1e3,refetchOnWindowFocus:!1,refetchOnReconnect:!1,retry:!1}),c=i?`data:${i.contentType};base64,${i.base64}`:null;function l(){r.current=!0,s()}return{src:c,loading:a||o,refresh:l}}var Qj=50;function $j(e){return e<=10?zs:e<=30?Ls:e<=70?Rs:Is}function eM(e,t){return t===`none`?e<=10?`text-rose-400`:e<=30?`text-amber-400`:`text-foreground-subtle`:`text-emerald-400`}function tM({status:e,variant:t=`compact`,className:n}){if(!e)return null;if(e.binary===!0){let t=e.percentage<Qj,r=t?zs:Is;return T(`span`,{className:G(`inline-flex items-center gap-1 text-[10px] font-medium`,t?`text-rose-400`:`text-foreground-subtle`,n),title:`Battery: ${t?`low`:`normal`}`,children:[v(r,{className:`h-3.5 w-3.5`}),v(`span`,{children:t?`Low`:`Normal`})]})}let r=$j(e.percentage),i=eM(e.percentage,e.charging),a=e.charging===`solar`?$l:e.charging===`dc`?Tl:null,o=e.sleeping;return T(`span`,{className:G(`inline-flex items-center gap-1 text-[10px] font-medium`,i,n),title:`Battery: ${Math.round(e.percentage)}%`+(e.charging===`none`?``:` · charging (${e.charging})`)+(e.sleeping?` · sleeping`:``),children:[v(r,{className:`h-3.5 w-3.5`}),T(`span`,{children:[Math.round(e.percentage),`%`]}),a&&v(a,{className:`h-3 w-3`}),o&&v(ml,{className:`h-3 w-3 text-blue-300`}),t===`full`&&e.charging!==`none`&&v(`span`,{className:`text-foreground-subtle`,children:e.charging})]})}function nM({trpc:e,device:t,status:n,enabled:r,showStatusPills:i=!1}){let a=Zj(e,r&&t.online?t.id:null),o=(t.features??[]).includes(`battery-operated`),s=i&&o&&!t.disabled,c=Xj(e,s?t.id:null);if(!r&&!s)return null;let l=n===`offline`||n===`disabled`,u=n===`offline`?`Offline — no snapshot`:n===`disabled`?`Disabled`:`No snapshot yet`;return T(`span`,{className:`inline-flex items-center gap-1.5 flex-nowrap whitespace-nowrap`,children:[s&&c&&v(tM,{status:c}),r&&v(dk,{src:l?null:a.src,alt:t.name,placeholder:u,thumbClassName:`h-7 w-7 rounded`})]})}function rM(e,t){if(e===`disabled`)return`Disabled`;if(e===`online`)return`Online`;let n=An(t);return n===null?`Offline`:`Offline · last seen ${n}`}function iM({status:e,lastChangedAt:t}){return v(`span`,{className:G(`h-1.5 w-1.5 rounded-full flex-shrink-0`,e===`disabled`?`bg-warning`:e===`online`?`bg-success`:`bg-danger`),title:rM(e,t)})}var aM=[`name`,`icon`,`type`,`manufacturer`,`features`,`previewActions`],oM={devices:[`name`,`icon`,`type`,`manufacturer`,`features`,`previewActions`],"integration-detail":[`name`,`manufacturer`,`features`,`previewActions`]};function sM(e){return oM[e]}var cM={name:0,previewActions:1,icon:2,features:3,type:4,manufacturer:5},lM={name:``,previewActions:``,icon:``,features:`hidden md:table-cell`,type:`hidden lg:table-cell`,manufacturer:`hidden xl:table-cell`},uM=`manufacturer`,dM=`model`;function fM(e){if(typeof e==`string`){let t=e.trim();return t===``?null:t}return typeof e==`number`&&Number.isFinite(e)||typeof e==`boolean`?String(e):null}function pM(e,t){return e==null?null:fM(e[t])}function mM(e){let t=pM(e.metadata,uM),n=pM(e.metadata,dM);return t!==null&&n!==null?`${t} · ${n}`:t??n??null}function hM(e){if(e==null)return[];let t=[];for(let n of Object.keys(e)){let r=fM(e[n]);r!==null&&t.push({key:n,value:r})}return t}function gM(e){return pM(e.metadata,uM)!==null}function _M(e){return(pM(e.metadata,uM)??``).toLowerCase()}function vM(e){return(pM(e.metadata,dM)??``).toLowerCase()}function yM(e,t){let n=_M(e).localeCompare(_M(t));return n===0?vM(e).localeCompare(vM(t)):n}function bM({device:e}){let t=mM(e),n=hM(e.metadata);if(t===null&&n.length===0)return v(`span`,{className:`text-xs text-foreground-subtle/60`,children:`—`});let r=t??`—`;return n.length===0?v(`span`,{className:`block truncate text-xs text-foreground-subtle`,children:r}):T(fd,{className:`block w-full min-w-0`,children:[v(pd,{className:`block w-full min-w-0`,children:v(`span`,{className:`block truncate text-xs text-foreground-subtle`,children:r})}),v(md,{className:`whitespace-normal text-left max-w-xs`,children:v(`dl`,{className:`grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5`,children:n.map(e=>T(`div`,{className:`contents`,children:[v(`dt`,{className:`font-medium opacity-70`,children:e.key}),v(`dd`,{className:`break-words`,children:e.value})]},e.key))})})]})}function xM({title:e,count:t,children:n,defaultOpen:r=!0}){let[i,a]=h(r);return T(`div`,{className:`rounded-md border border-border-subtle/50`,children:[T(`button`,{type:`button`,onClick:()=>a(e=>!e),className:G(`w-full flex items-center gap-1.5 px-2 py-1.5 text-left transition-colors`,`hover:bg-surface-hover`),"aria-expanded":i,children:[v(i?Xs:Qs,{className:`h-3 w-3 text-foreground-subtle flex-shrink-0`}),v(`span`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle flex-1 truncate`,children:e}),v(`span`,{className:`text-[10px] font-medium text-foreground-subtle/70 tabular-nums`,children:t})]}),i&&v(`div`,{className:`space-y-1 px-1 pb-1.5`,children:n})]})}var SM=`Disabled`;function CM(e,t,n){let r=t.filter(e=>e.disabled!==!0),i=wM(t.filter(e=>e.disabled===!0));if(n===void 0||n.length===0)return{sections:[],ungrouped:r,disabledSection:i};let a=new Map;for(let e of r)a.set(e.stableId,e);let o=[],s=new Map,c=new Set;for(let t of n){let n=`${e}-${t.childKey}`,r=a.get(n);if(r===void 0)continue;let i=s.get(t.section);i===void 0&&(i={title:t.section,entries:[],collapsed:!1},s.set(t.section,i),o.push(t.section)),i.entries.push({child:r,order:t.order??2**53-1}),t.collapsed===!0&&(i.collapsed=!0),c.add(r.id)}return{sections:o.map(e=>{let t=s.get(e),n=[...t===void 0?[]:t.entries].toSorted((e,t)=>e.order===t.order?e.child.name.localeCompare(t.child.name):e.order-t.order),r=t===void 0?!0:!t.collapsed;return{title:e,children:n.map(e=>e.child),defaultOpen:r}}),ungrouped:r.filter(e=>!c.has(e.id)),disabledSection:i}}function wM(e){if(e.length!==0)return{title:SM,children:[...e].toSorted((e,t)=>e.name.localeCompare(t.name)),defaultOpen:!1,muted:!0}}function TM(e){let{trpc:t,device:n,parent:r,integrationIcon:i,onNavigate:a,className:o,renderRowAction:s,onDelete:c,selection:l}=e,u=xp(e),d=e.variant??`compact`,f=e.view??`card`,p=!n.disabled,m=n.isCamera??n.type.toLowerCase()===`camera`,g=e.children??[],_=g.filter(Op),y=g.filter(e=>!Op(e)),b=g.length>0,[x,S]=h(!1),C=e.expanded??x,w=e.onToggleExpand??(()=>S(e=>!e)),E=e=>{a?.(e)},D=e.rowClickSelects===!0&&l!==void 0,O=()=>{if(D&&l!==void 0){l.onToggle();return}E(n.id)},k=e.indentLevel??(e.isAccessoryRow?2:0),A=Ap(n,g),j=p?A?`online`:`offline`:`disabled`;return f===`table`?v(DM,{trpc:t,device:n,variant:d,flags:u,parent:r??null,integrationIcon:i??null,accessoryCount:_.length,adoptedCount:y.length,hasChildren:b,expanded:C,onToggleExpand:w,onRowClick:O,rowSelects:D,rowSelected:l?.selected??!1,onNavigate:E,displayStatus:j,isCamera:m,showSnapshot:u.showSnapshot&&m,isAccessoryRow:e.isAccessoryRow??!1,indentLevel:k,className:o,renderRowAction:s??null,onDelete:c??null,selection:l,showTypeCell:e.showTypeCell??!0,showManufacturerCell:e.showManufacturerCell??!0,showFeaturesCell:e.showFeaturesCell??!0}):d===`minimal`?T(`div`,{className:G(`rounded-lg border border-border bg-surface transition-colors`,!p&&`opacity-60`,o),children:[T(`div`,{"data-testid":`device-card-body`,onClick:O,...D?{role:`button`,"aria-pressed":l?.selected??!1,tabIndex:0,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),O())}}:{},className:G(`flex items-center gap-2 cursor-pointer hover:border-foreground-subtle/30 w-full px-2.5 py-1.5`,l?.selected&&`bg-primary/10`),children:[l&&v(`input`,{type:`checkbox`,checked:l.selected,onChange:l.onToggle,onClick:e=>e.stopPropagation(),"aria-label":`Select ${n.name}`,className:`flex-shrink-0`}),v(Yj,{device:n,variant:d,flags:u,parent:r??null,integrationIcon:i??null,hasChildren:b,expanded:C,onToggleExpand:w,onNavigateToParent:E}),v(Bj,{trpc:t,device:n,flags:u,accessoryCount:_.length,adoptedCount:y.length,showFeatureRow:!1}),v(nM,{trpc:t,device:n,status:j,enabled:u.showSnapshot&&m,showStatusPills:!0}),v(Ej,{trpc:t,device:n,flags:u,controlPlacement:`right`}),s&&v(`span`,{onClick:e=>e.stopPropagation(),children:s(n)}),v(iM,{status:j})]}),C&&b&&v(Pp,{trpc:t,accessoryChildren:_,adoptedChildren:y,onNavigate:E})]}):T(`div`,{className:G(`group rounded-xl border border-border bg-surface transition-colors`,`hover:border-foreground-subtle/30`,!p&&`opacity-60`,o),children:[T(`div`,{"data-testid":`device-card-body`,onClick:O,...D?{role:`button`,"aria-pressed":l?.selected??!1,tabIndex:0,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),O())}}:{},className:G(`flex flex-col gap-2 cursor-pointer w-full p-3 rounded-xl`,l?.selected&&`bg-primary/10`),children:[T(`div`,{className:`flex items-start justify-between gap-2`,children:[l&&v(`input`,{type:`checkbox`,checked:l.selected,onChange:l.onToggle,onClick:e=>e.stopPropagation(),"aria-label":`Select ${n.name}`,className:`flex-shrink-0 mt-0.5`}),v(Yj,{device:n,variant:d,flags:u,parent:r??null,integrationIcon:i??null,hasChildren:b,expanded:C,onToggleExpand:w,onNavigateToParent:E,stacked:!0}),v(iM,{status:j})]}),v(Bj,{trpc:t,device:n,flags:u,accessoryCount:_.length,adoptedCount:y.length,showFeatureRow:!1}),T(`div`,{className:`flex items-center justify-end gap-1.5`,children:[v(nM,{trpc:t,device:n,status:j,enabled:u.showSnapshot&&m,showStatusPills:!0}),v(Ej,{trpc:t,device:n,flags:u,controlPlacement:`right`}),s&&v(`span`,{onClick:e=>e.stopPropagation(),children:s(n)})]})]}),C&&b&&v(Pp,{trpc:t,accessoryChildren:_,adoptedChildren:y,onNavigate:E})]})}var EM={0:`pl-2`,1:`pl-6`,2:`pl-8`};function DM(e){let{trpc:t,device:n,variant:r,flags:i,parent:a,integrationIcon:o,accessoryCount:s,adoptedCount:c,hasChildren:l,expanded:u,onToggleExpand:d,onNavigate:f,onRowClick:p,rowSelects:m,rowSelected:h,displayStatus:g,isCamera:_,showSnapshot:y,isAccessoryRow:b,indentLevel:x,className:S,renderRowAction:C,onDelete:w,selection:E,showTypeCell:D,showManufacturerCell:O,showFeaturesCell:k}=e,A=Hp(n.id);return T(`tr`,{onClick:p,...m?{role:`button`,"aria-pressed":h,tabIndex:0,onKeyDown:e=>{(e.key===`Enter`||e.key===` `)&&(e.preventDefault(),p())}}:{},className:G(`group cursor-pointer hover:bg-surface-hover transition-colors`,!l&&`border-b border-border-subtle/40`,b&&`bg-foreground-subtle/[0.03]`,h&&`bg-primary/10`,S),children:[v(`td`,{className:G(`sticky left-0 z-[1] py-1.5 align-middle pr-2 transition-colors`,h?`bg-primary/10 group-hover:bg-surface-hover`:b?`bg-surface-subtle group-hover:bg-surface-hover`:`bg-surface group-hover:bg-surface-hover`,`w-64 max-w-[16rem] min-w-0 overflow-hidden`,EM[x]),children:T(`div`,{className:`flex items-center gap-1.5`,children:[E&&v(`input`,{type:`checkbox`,checked:E.selected,onChange:E.onToggle,onClick:e=>e.stopPropagation(),"aria-label":`Select ${n.name}`,className:`flex-shrink-0`}),v(Yj,{device:n,variant:r,flags:i,parent:a,integrationIcon:o,hasChildren:l,expanded:u,onToggleExpand:d,onNavigateToParent:f})]})}),D&&v(`td`,{className:G(lM.type,`px-2 py-1.5 align-middle text-[10px] text-foreground-subtle whitespace-nowrap`),children:jp(n,A)}),O&&v(`td`,{className:G(lM.manufacturer,`px-2 py-1.5 align-middle w-40 max-w-[10rem] min-w-0 overflow-hidden`),children:v(bM,{device:n})}),k&&v(`td`,{className:G(lM.features,`px-2 py-1.5 align-middle`),children:v(Bj,{trpc:t,device:n,flags:i,accessoryCount:s,adoptedCount:c,showFeatureRow:!0})}),v(`td`,{className:`px-2 py-1.5 align-middle text-right whitespace-nowrap`,children:T(`span`,{className:`inline-flex items-center justify-end gap-1.5`,children:[v(Ej,{trpc:t,device:n,flags:i,controlPlacement:`table`}),v(nM,{trpc:t,device:n,status:g,enabled:y&&_,showStatusPills:!0}),C&&v(`span`,{onClick:e=>e.stopPropagation(),children:C(n)}),w&&v(Nj,{device:n,onDelete:w}),v(iM,{status:g})]})})]})}function OM({selectedIds:e,onClear:t,remove:n,disable:r,enable:i}){let[a,o]=h(!1);if(e.size===0)return null;let s=[...e],c=s.length;return T(`div`,{className:`flex items-center gap-2 px-3 py-2 rounded-lg border border-border bg-surface-hover`,children:[T(`span`,{className:`text-xs font-medium text-foreground-subtle shrink-0`,children:[c,` selected`]}),v(`div`,{className:`h-3.5 w-px bg-border shrink-0`,"aria-hidden":`true`}),T(`div`,{className:`flex items-center gap-1.5 flex-wrap`,children:[v(`button`,{type:`button`,onClick:()=>{for(let e of s)r({deviceId:e});t()},className:G(`inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors`,`border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface`),children:`Disable`}),v(`button`,{type:`button`,onClick:()=>{for(let e of s)i({deviceId:e});t()},className:G(`inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors`,`border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface`),children:`Enable`}),a?T(E,{children:[T(`button`,{type:`button`,onClick:()=>{for(let e of s)n({deviceId:e});o(!1),t()},className:G(`inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors`,`border-red-500/50 bg-red-500/10 text-red-400 hover:bg-red-500/20`),children:[`Confirm delete `,c,`?`]}),v(`button`,{type:`button`,onClick:()=>{o(!1)},className:G(`inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors`,`border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface`),children:`Cancel`})]}):v(`button`,{type:`button`,onClick:()=>{o(!0)},className:G(`inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors`,`border-red-500/40 bg-red-500/10 text-red-400 hover:bg-red-500/20`),children:`Delete`}),v(`button`,{type:`button`,onClick:()=>{o(!1),t()},className:G(`inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors`,`border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface`),children:`Clear`})]})]})}function kM(e){let[t,n]=h(!1),r=p(null),i=e.selectedIds.size;return c(()=>{if(!t)return;let e=e=>{let t=e.target instanceof Node?e.target:null;t&&r.current&&!r.current.contains(t)&&n(!1)},i=e=>{e.key===`Escape`&&n(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`touchstart`,e),document.addEventListener(`keydown`,i),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`touchstart`,e),document.removeEventListener(`keydown`,i)}},[t]),i===0?null:T(E,{children:[v(`div`,{className:`hidden sm:block`,children:v(OM,{...e})}),T(`div`,{ref:r,"data-testid":`batch-actions-compact`,className:`relative sm:hidden`,children:[T(`button`,{type:`button`,onClick:()=>n(e=>!e),"aria-haspopup":`menu`,"aria-expanded":t,className:`inline-flex items-center gap-1.5 h-7 px-2.5 rounded-full border border-primary/40 bg-primary/15 text-[10.5px] font-medium text-primary`,children:[T(`span`,{children:[`Actions · `,String(i)]}),v(Xs,{className:`h-3 w-3 transition-transform ${t?`rotate-180`:``}`})]}),t&&v(`div`,{role:`menu`,className:`absolute left-0 top-full mt-1 z-30 rounded-lg border border-border bg-surface shadow-md`,children:v(OM,{...e})})]})]})}function AM(e,t){let[n,r]=h(e);return c(()=>{let n=setTimeout(()=>r(e),t);return()=>clearTimeout(n)},[e,t]),n}var jM=[25,50,100,200],MM=`camstack.device-list.pageSize`;function NM(e){return jM.includes(e)}function PM(e){return NM(e)?e:50}function FM(e){if(typeof window>`u`)return e;try{let t=window.localStorage.getItem(MM);if(t===null)return e;let n=Number.parseInt(t,10);return Number.isFinite(n)&&NM(n)?n:e}catch{return e}}function IM(e){if(!(typeof window>`u`))try{window.localStorage.setItem(MM,String(e))}catch{}}function LM(e){let t=PM(e),[n,r]=h(()=>FM(t));return[n,u(e=>{NM(e)&&(r(e),IM(e))},[])]}function RM(e){let t=new Map;for(let n of e)t.set(n.id,n);return e.filter(e=>{if(e.parentDeviceId===null||e.parentDeviceId===void 0)return!0;let n=t.get(e.parentDeviceId);return n?zM.has(n.type.toLowerCase()):!0})}var zM=new Set([`hub`,`nvr`]);function BM(e){let t=new Map;for(let n of e)t.set(n.id,n);let n=[],r=new Map;for(let i of e){let e=i.parentDeviceId;if(e==null){n.push(i);continue}let a=t.get(e);if(!a){n.push(i);continue}let o=i.role!==null&&i.role!==void 0;if(zM.has(a.type)&&!o){n.push(i);continue}let s=r.get(e);s?s.push(i):r.set(e,[i])}return{topLevel:n,accessoriesByParent:r}}function VM(e){return e.toLowerCase().replace(/[-_\s]+/g,``)}function HM(e,t){let n=VM(e);return n===``?!0:VM(t).includes(n)}var UM=2;function WM(e,t){if(t<=1)return[{kind:`page`,n:1}];if(t<=7){let e=[];for(let n=1;n<=t;n++)e.push({kind:`page`,n});return e}let n=[],r=Math.max(2,e-UM),i=Math.min(t-1,e+UM);n.push({kind:`page`,n:1}),r>2&&n.push({kind:`ellipsis`,side:`left`});for(let e=r;e<=i;e++)n.push({kind:`page`,n:e});return i<t-1&&n.push({kind:`ellipsis`,side:`right`}),n.push({kind:`page`,n:t}),n}function GM({currentPage:e,totalItems:t,pageSize:n,onPageChange:r,itemNoun:i=`devices`}){if(t<=n)return null;let a=Math.ceil(t/n),o=(e-1)*n+1,s=Math.min(e*n,t),c=WM(e,a);return T(`div`,{className:`flex items-center justify-between gap-4 flex-wrap pt-2 text-[11px] text-foreground-subtle`,children:[T(`span`,{children:[`Showing `,o,`–`,s,` of `,t,` `,i]}),T(`span`,{className:`inline-flex items-center gap-1`,children:[v(`button`,{type:`button`,"aria-label":`Previous page`,disabled:e===1,onClick:()=>r(e-1),className:G(`inline-flex items-center justify-center h-7 w-7 rounded border border-border bg-surface text-foreground-subtle`,`hover:text-foreground hover:bg-surface-hover transition-colors`,`disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-surface`),children:v(Zs,{className:`h-3 w-3`})}),c.map((t,n)=>t.kind===`ellipsis`?v(`span`,{className:`px-1 text-foreground-subtle/60 select-none`,children:`…`},`e-${n}`):v(`button`,{type:`button`,onClick:()=>r(t.n),className:G(`inline-flex items-center justify-center h-7 min-w-7 px-1.5 rounded border text-[10.5px] font-medium transition-colors`,t.n===e?`border-primary/40 bg-primary/10 text-primary`:`border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover`),children:t.n},`p-${t.n}`)),v(`button`,{type:`button`,"aria-label":`Next page`,disabled:e===a,onClick:()=>r(e+1),className:G(`inline-flex items-center justify-center h-7 w-7 rounded border border-border bg-surface text-foreground-subtle`,`hover:text-foreground hover:bg-surface-hover transition-colors`,`disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-surface`),children:v(Qs,{className:`h-3 w-3`})})]})]})}function KM({label:e,options:t,selected:n,onChange:r}){let[i,a]=h(!1),o=p(null);c(()=>{if(!i)return;let e=e=>{let t=e.target instanceof Node?e.target:null;t&&o.current&&!o.current.contains(t)&&a(!1)},t=e=>{e.key===`Escape`&&a(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`touchstart`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`touchstart`,e),document.removeEventListener(`keydown`,t)}},[i]);let s=new Set(n),l=n.length,u=e=>{let n=new Set(s);n.has(e)?n.delete(e):n.add(e),r(t.filter(e=>n.has(e.id)).map(e=>e.id))};return T(`div`,{ref:o,className:`relative`,children:[T(`button`,{type:`button`,onClick:()=>a(e=>!e),"aria-haspopup":`listbox`,"aria-expanded":i,className:`inline-flex items-center gap-1.5 h-7 px-2.5 rounded-full border text-[10.5px] font-medium transition-colors ${l>0?`border-primary/40 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[T(`span`,{children:[e,l>0?` · ${String(l)}`:``]}),v(Xs,{className:`h-3 w-3 transition-transform ${i?`rotate-180`:``}`})]}),i&&T(`div`,{role:`listbox`,className:`absolute left-0 top-full mt-1 z-30 min-w-[180px] max-h-72 overflow-y-auto rounded-lg border border-border bg-surface shadow-xl py-1`,children:[l>0&&v(`button`,{type:`button`,onClick:()=>r([]),className:`flex w-full items-center px-3 py-1.5 text-left text-[10.5px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:`Clear selection`}),t.map(e=>{let t=s.has(e.id),n=e.icon;return T(`button`,{type:`button`,role:`option`,"aria-selected":t,onClick:()=>u(e.id),className:`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[10.5px] text-foreground hover:bg-surface-hover`,children:[v(`span`,{className:`flex h-3.5 w-3.5 items-center justify-center rounded border shrink-0 ${t?`border-primary bg-primary`:`border-border`}`,children:t&&v(Ys,{className:`h-2.5 w-2.5 text-primary-foreground`})}),n&&v(n,{className:`h-3.5 w-3.5 shrink-0 text-foreground-subtle`}),v(`span`,{className:`truncate`,children:e.label})]},e.id)})]})]})}function qM({label:e,options:t,selected:n,onChange:r}){let i=p(null),[a,o]=h(null);c(()=>{let e=i.current;if(!e||typeof ResizeObserver>`u`)return;let t=new ResizeObserver(e=>{let t=e[0];t&&o(t.contentRect.width)});return t.observe(e),()=>t.disconnect()},[]);let s=new Set(n),l=e=>{let n=new Set(s);n.has(e)?n.delete(e):n.add(e),r(t.filter(e=>n.has(e.id)).map(e=>e.id))},u=56+t.length*88;return v(`div`,{ref:i,className:`min-w-0 flex-1`,children:a!==null&&a>=u?T(`div`,{className:`flex items-center gap-1.5 flex-wrap`,children:[v(`span`,{className:`text-[10px] font-medium uppercase tracking-wider text-foreground-subtle`,children:e}),t.map(e=>{let t=s.has(e.id),n=e.icon;return T(`button`,{type:`button`,onClick:()=>l(e.id),"aria-pressed":t,className:`inline-flex items-center gap-1 h-7 px-2.5 rounded-full border text-[10.5px] font-medium transition-colors ${t?`border-primary/40 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,children:[n&&v(n,{className:`h-3 w-3 shrink-0`}),e.label]},e.id)})]}):v(KM,{label:e,options:t,selected:n,onChange:r})})}function JM({view:e,onViewChange:t,hideView:n=!1,typeOptions:r,selectedTypes:i,onTypesChange:a,addons:o,selectedAddons:s,onAddonsChange:c,hideAddons:l=!1}){return T(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[!n&&e!==void 0&&t!==void 0&&T(`span`,{className:`inline-flex border border-border rounded-md overflow-hidden`,children:[v(`button`,{type:`button`,onClick:()=>t(`cards`),className:G(`inline-flex items-center justify-center h-7 w-8 transition-colors`,e===`cards`?`bg-primary/10 text-primary`:`bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover`),"aria-label":`Cards view`,children:v(Xc,{className:`h-3.5 w-3.5`})}),v(`button`,{type:`button`,onClick:()=>t(`table`),className:G(`inline-flex items-center justify-center h-7 w-8 border-l border-border transition-colors`,e===`table`?`bg-primary/10 text-primary`:`bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover`),"aria-label":`Table view`,children:v(eu,{className:`h-3.5 w-3.5`})})]}),r&&r.length>0&&v(qM,{label:`Type`,options:r,selected:i,onChange:a}),!l&&o&&o.length>0&&v(YM,{addons:o,selected:s,onChange:c})]})}function YM({addons:e,selected:t,onChange:n}){let[r,i]=h(!1),a=p(null);c(()=>{if(!r)return;let e=e=>{let t=e.target;t&&a.current&&!a.current.contains(t)&&i(!1)},t=e=>{e.key===`Escape`&&i(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`touchstart`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`touchstart`,e),document.removeEventListener(`keydown`,t)}},[r]);let o=new Set(t),s=t.length,l=t=>{let r=new Set(o);r.has(t)?r.delete(t):r.add(t),n(e.filter(e=>r.has(e.id)).map(e=>e.id))};return T(`div`,{ref:a,className:`relative`,children:[T(`button`,{type:`button`,onClick:()=>i(e=>!e),className:G(`inline-flex items-center gap-1.5 h-7 px-2.5 rounded-full border text-[10.5px] font-medium transition-colors`,s>0?`border-primary/40 bg-primary/15 text-primary`:`border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover`),"aria-haspopup":`listbox`,"aria-expanded":r,children:[T(`span`,{children:[`Integration`,s>0?` · ${String(s)}`:``]}),v(Xs,{className:G(`h-3 w-3 transition-transform`,r&&`rotate-180`)})]}),r&&T(`div`,{role:`listbox`,className:`absolute left-0 top-full mt-1 z-30 min-w-[180px] max-h-72 overflow-y-auto rounded-lg border border-border bg-surface shadow-xl py-1`,children:[s>0&&v(`button`,{type:`button`,onClick:()=>n([]),className:`flex w-full items-center px-3 py-1.5 text-left text-[10.5px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground`,children:`Clear selection`}),e.map(e=>{let t=o.has(e.id);return T(`button`,{type:`button`,role:`option`,"aria-selected":t,onClick:()=>l(e.id),className:G(`flex w-full items-center gap-2 px-3 py-1.5 text-left text-[10.5px] transition-colors`,t?`text-primary`:`text-foreground hover:bg-surface-hover`),children:[v(`span`,{className:G(`flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded border`,t?`border-primary bg-primary/20`:`border-border`),children:t&&v(Ys,{className:`h-2.5 w-2.5`})}),e.icon&&v(`span`,{className:`inline-flex items-center`,children:e.icon}),v(`span`,{className:`truncate`,children:e.name})]},e.id)})]})]})}function XM({variant:e,onClearFilters:t}){return T(`div`,{className:`flex flex-col items-center justify-center py-12 text-center`,children:[v(Jc,{className:`h-8 w-8 text-foreground-subtle/40 mb-3`}),v(`p`,{className:`text-sm font-medium text-foreground-subtle`,children:e===`filtered`?`No devices match the current filters`:`No devices yet`}),e===`filtered`&&t&&v(`button`,{type:`button`,onClick:t,className:`mt-2 text-[11px] text-primary hover:underline`,children:`Clear filters`})]})}function ZM(e){return e?e.split(`,`).map(e=>e.trim()).filter(e=>e.length>0):[]}function QM(e,t){if(e===`root`)return t===`addons`?`addon`:t===`types`?`type`:t;switch(t){case`view`:return`deviceView`;case`page`:return`devicePage`;case`types`:return`deviceType`;case`q`:return`deviceQ`;case`addons`:return`deviceAddon`}}function $M(e){try{let t=localStorage.getItem(`camstack:${e}:lastFilters`);if(!t)return{};let n=JSON.parse(t);return typeof n!=`object`||!n?{}:n}catch{return{}}}function eN(e,t){try{localStorage.setItem(`camstack:${e}:lastFilters`,JSON.stringify(t))}catch{}}function tN(e,t,n){let r=new URLSearchParams(window.location.search),i=r.get(QM(e,`view`)),a=i===`cards`||i===`table`?i:n.view??t,o=r.get(QM(e,`page`)),s=o?parseInt(o,10):1;return{view:a,page:Number.isFinite(s)&&s>=1?s:1,addons:ZM(r.get(QM(e,`addons`))??n.addon??null),types:ZM(r.get(QM(e,`types`))??n.type??null),q:r.get(QM(e,`q`))??n.q??``}}function nN(e,t,n){let r=new URLSearchParams(window.location.search),i=(e,t)=>{t===null||t===``?r.delete(e):r.set(e,t)};i(QM(e,`view`),t.view===n?null:t.view),i(QM(e,`page`),t.page===1?null:String(t.page)),i(QM(e,`addons`),t.addons.length>0?t.addons.join(`,`):null),i(QM(e,`types`),t.types.length>0?t.types.join(`,`):null),i(QM(e,`q`),t.q||null);let a=r.toString(),o=a?`${window.location.pathname}?${a}`:window.location.pathname;window.history.replaceState(null,``,o)}function rN(e){let{scope:t,defaultView:n,lsKey:r}=e,[i,a]=h(()=>tN(t,n,$M(r))),o=p(i);o.current=i,c(()=>{let e=()=>{let e=tN(t,n,$M(r));o.current=e,a(e)};return window.addEventListener(`popstate`,e),()=>window.removeEventListener(`popstate`,e)},[t,n,r]);let s=u(e=>{let i=e(o.current);o.current=i,a(i),nN(t,i,n),eN(r,{view:i.view,addon:i.addons.length>0?i.addons.join(`,`):null,type:i.types.length>0?i.types.join(`,`):null,q:i.q})},[t,n,r]);return{state:i,setView:u(e=>s(t=>({...t,view:e})),[s]),setPage:u(e=>s(t=>({...t,page:e})),[s]),setAddons:u(e=>s(t=>({...t,addons:e,page:1})),[s]),setTypes:u(e=>s(t=>({...t,types:e,page:1})),[s]),setQ:u(e=>s(t=>({...t,q:e,page:1})),[s]),clearFilters:u(()=>s(e=>({...e,addons:[],types:[],q:``,page:1})),[s])}}function iN({rows:e,accessoriesByParent:t,trpc:n,resolveIntegrationIcon:r,resolveParent:i,onNavigate:a,renderRowAction:o,selectable:s,rowClickSelects:c,activeSelected:l,onToggleSelection:u}){return v(`div`,{className:`grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 items-stretch`,children:e.map(e=>{let d=t.get(e.id)??[],f=s?{selected:l.has(e.id),onToggle:()=>u(e.id)}:void 0;return v(TM,{trpc:n,device:e,view:`card`,integrationIcon:r?.(e.addonId)??null,parent:e.parentDeviceId===null?null:i?.(e.parentDeviceId)??null,children:d,onNavigate:a??void 0,renderRowAction:o??void 0,selection:f,rowClickSelects:c},e.id)})})}function aN({columnId:e,label:t,sort:n,onSort:r}){let i=n!==null&&n.columnId===e;return T(`button`,{type:`button`,onClick:()=>r(e),className:`group/sort inline-flex items-center gap-0.5 uppercase tracking-wider hover:text-foreground transition-colors`,children:[v(`span`,{children:t}),i?n.dir===`asc`?v($s,{className:`h-3 w-3 flex-shrink-0`}):v(Xs,{className:`h-3 w-3 flex-shrink-0`}):v($s,{className:G(`h-3 w-3 flex-shrink-0 opacity-0 transition-opacity`,`group-hover/sort:opacity-30`)})]})}function oN(e,t){return e===null||e.columnId!==t?`none`:e.dir===`asc`?`ascending`:`descending`}var sN=new Set([`hub`,`nvr`]);function cN(e,t){return e.parentDeviceId===null||t===null?0:+!!sN.has(t.toLowerCase())}function lN({rows:e,accessoriesByParent:t,autoExpandedParents:n,devices:r,visibleColumns:i,trpc:a,resolveIntegrationIcon:s,resolveParent:c,onNavigate:l,renderRowAction:u,onDeleteDevice:d,selectable:f,rowClickSelects:p,activeSelected:m,onToggleSelection:h,sort:g,onSort:_}){let y=i.includes(`type`),b=i.includes(`features`),x=i.includes(`manufacturer`),S=i.includes(`icon`),C=o(()=>{let e=new Map;for(let t of r)e.set(t.id,t.type);return e},[r]);return v(`div`,{className:`rounded-lg border border-border bg-surface overflow-x-auto`,children:T(`table`,{className:`w-full border-collapse`,children:[v(`thead`,{children:T(`tr`,{className:`border-b border-border`,children:[v(`th`,{"aria-sort":oN(g,`name`),className:`sticky left-0 z-[1] bg-surface text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-64 max-w-[16rem]`,children:v(aN,{columnId:`name`,label:`Name`,sort:g,onSort:_})}),y&&v(`th`,{"aria-sort":oN(g,`type`),className:G(lM.type,`text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-24`),children:v(aN,{columnId:`type`,label:`Type`,sort:g,onSort:_})}),x&&v(`th`,{"aria-sort":oN(g,`manufacturer`),className:G(lM.manufacturer,`text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-40`),children:v(aN,{columnId:`manufacturer`,label:`Hardware`,sort:g,onSort:_})}),b&&v(`th`,{className:G(lM.features,`text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-32`),children:`Features`}),v(`th`,{className:`text-right px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-32`,children:`Preview`})]})}),v(`tbody`,{children:e.map(e=>{let r=t.get(e.id)??[],i=r.length>0,o=n.has(e.id),g=e.parentDeviceId===null?null:c?.(e.parentDeviceId)??null,_=e.parentDeviceId===null?null:C.get(e.parentDeviceId)??null,w=f?{selected:m.has(e.id),onToggle:()=>h(e.id)}:void 0;return v(uN,{parent:e,accessories:r,hasAccessories:i,forceExpanded:o,trpc:a,integrationIcon:S?s?.(e.addonId)??null:null,showType:y,showManufacturer:x,showFeatures:b,parentRowParent:g,indentLevel:cN(e,_),onNavigate:l??null,renderRowAction:u??null,onDeleteDevice:d,selection:w,rowClickSelects:p},e.id)})})]})})}function uN({parent:e,accessories:t,hasAccessories:n,forceExpanded:r,trpc:i,integrationIcon:a,showType:s,showManufacturer:l,showFeatures:u,parentRowParent:d,indentLevel:f,onNavigate:m,renderRowAction:g,onDeleteDevice:_,selection:y,rowClickSelects:b}){let[x,S]=h(r),C=p(r);c(()=>{C.current!==r&&(S(r),C.current=r)},[r]);let w=()=>S(e=>!e),D=n&&x,O=o(()=>CM(e.stableId,t,e.childLayout),[e.stableId,e.childLayout,t]),[k,A]=h(()=>{let e=O.sections.filter(e=>!e.defaultOpen).map(e=>e.title);return O.disabledSection!==void 0&&!O.disabledSection.defaultOpen&&e.push(O.disabledSection.title),new Set(e)}),j=e=>A(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n}),M=2+ +!!s+ +!!l+ +!!u,N=O.disabledSection;return T(E,{children:[v(TM,{trpc:i,device:e,view:`table`,integrationIcon:a,parent:d,children:t,onNavigate:m??void 0,showChildrenAccordion:!0,expanded:x,onToggleExpand:w,indentLevel:f,renderRowAction:g??void 0,onDelete:_??void 0,selection:y,rowClickSelects:b,showTypeCell:s,showManufacturerCell:l,showFeaturesCell:u}),D&&O.ungrouped.map(e=>v(dN,{trpc:i,accessory:e,showType:s,showManufacturer:l,showFeatures:u,onNavigate:m},e.id)),D&&O.sections.map(e=>{let t=!k.has(e.title);return v(fN,{title:e.title,count:e.children.length,open:t,colSpan:M,onToggle:()=>j(e.title),rows:e.children,trpc:i,showType:s,showManufacturer:l,showFeatures:u,onNavigate:m},e.title)}),D&&N!==void 0&&v(fN,{title:N.title,count:N.children.length,open:!k.has(N.title),colSpan:M,onToggle:()=>j(N.title),rows:N.children,trpc:i,showType:s,showManufacturer:l,showFeatures:u,onNavigate:m,muted:!0},N.title)]})}function dN({trpc:e,accessory:t,showType:n,showManufacturer:r,showFeatures:i,onNavigate:a,muted:o}){return v(TM,{trpc:e,device:t,view:`table`,integrationIcon:null,parent:null,isAccessoryRow:!0,showChildrenAccordion:!1,onNavigate:a??void 0,showTypeCell:n,showManufacturerCell:r,showFeaturesCell:i,className:o===!0?`opacity-60`:void 0})}function fN({title:e,count:t,open:n,colSpan:r,onToggle:i,rows:a,trpc:o,showType:s,showManufacturer:c,showFeatures:l,onNavigate:u,muted:d}){return T(E,{children:[v(`tr`,{className:G(`border-b border-border-subtle/40 bg-surface`,d===!0&&`opacity-60`),children:v(`td`,{colSpan:r,className:`p-0`,children:T(`button`,{type:`button`,onClick:i,className:`w-full flex items-center gap-1.5 pl-8 pr-2 py-1 text-left hover:bg-surface-hover transition-colors`,"aria-expanded":n,children:[v(n?Xs:Qs,{className:`h-3 w-3 text-foreground-subtle flex-shrink-0`}),v(`span`,{className:`text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle flex-1 truncate`,children:e}),v(`span`,{className:`text-[10px] font-medium text-foreground-subtle/70 tabular-nums`,children:t})]})})}),n&&a.map(e=>v(dN,{trpc:o,accessory:e,showType:s,showManufacturer:c,showFeatures:l,onNavigate:u,muted:d},e.id))]})}function pN(e){return cp(e.type).label.toLowerCase()}function mN(e){return e.name.toLowerCase()}function hN(e){return e===`name`?(e,t)=>mN(e).localeCompare(mN(t)):e===`type`?(e,t)=>pN(e).localeCompare(pN(t)):yM}function gN(e,t){return e===null||e.columnId!==t?{columnId:t,dir:`asc`}:e.dir===`asc`?{columnId:t,dir:`desc`}:null}function _N(e,t){if(t===null)return[...e];let n=hN(t.columnId),r=t.dir===`asc`?1:-1;return[...e].toSorted((e,i)=>{if(t.columnId===`manufacturer`){let t=gM(e);if(t!==gM(i))return t?-1:1}return r*n(e,i)})}var vN={cards:24,table:50};function yN(e){let{devices:t,trpc:n,context:r=`devices`,defaultView:i=`table`,filters:a,forceAddon:s,resolveIntegrationIcon:l,resolveParent:u,onNavigate:d,pageSize:f=vN,urlScope:p=`root`,lsKey:m=p===`root`?`devices`:`integrations:nested`,renderRowAction:g,onDeleteDevice:_,selectable:y=!1,selectedIds:b,onSelectionChange:x,batchActions:S}=e,[C,w]=h(!1),[D,O]=h(new Set),k=b??D,A=e=>{let t=new Set(k);t.has(e)?t.delete(e):t.add(e),b===void 0&&O(t),x?.(t)},j=()=>{b===void 0?O(new Set):x?.(new Set)},M=()=>{j(),w(!1)},N=y||S!==void 0&&C,P=S!==void 0&&C,ee=o(()=>sM(r),[r]),[F,te]=h(null),I=e=>te(t=>gN(t,e)),L=a?.typeOptions,ne=o(()=>L??dp(),[L]),R=rN({scope:p,defaultView:i,lsKey:m}),re=R.state.view,[ie,ae]=LM(f.table),z=re===`cards`?f.cards:ie,[oe,se]=h(R.state.q),ce=AM(oe,300);c(()=>{ce!==R.state.q&&R.setQ(ce)},[ce]);let le=o(()=>s===void 0?R.state.addons:[s],[s,R.state.addons]),ue=o(()=>{let e=new Map;for(let n of t){if(n.parentDeviceId===null||n.parentDeviceId===void 0)continue;let t=e.get(n.parentDeviceId);t?t.push(n):e.set(n.parentDeviceId,[n])}return e},[t]),de=o(()=>{let e=R.state.q,n=le.length>0?new Set(le):null,r=R.state.types.length>0?new Set(R.state.types):null;return t.filter(t=>!(n&&!n.has(t.addonId)||r&&!r.has(jp(t,ue.get(t.id)))||e.trim()!==``&&!HM(e,t.name)&&!HM(e,t.stableId)))},[t,ue,le,R.state.types,R.state.q]),fe=o(()=>BM(de),[de]),pe=o(()=>_N(fe.topLevel,F),[fe.topLevel,F]),me=o(()=>{if(R.state.q.trim()===``)return new Set;let e=R.state.q,t=new Set;for(let[n,r]of fe.accessoriesByParent.entries())r.some(t=>HM(e,t.name)||HM(e,t.stableId))&&t.add(n);return t},[fe.accessoriesByParent,R.state.q]),he=fe.topLevel.length,B=Math.max(1,Math.ceil(he/z)),ge=Math.min(R.state.page,B),_e=(ge-1)*z,V=pe.slice(_e,_e+z);c(()=>{ge!==R.state.page&&R.setPage(ge)},[ge]),bN();let ve=le.length>0||R.state.types.length>0||R.state.q!==``,ye=he===0;return T(`div`,{className:`flex flex-col gap-3`,children:[T(`div`,{className:`flex items-center justify-between gap-3 flex-wrap`,children:[v(JM,{view:re,onViewChange:R.setView,typeOptions:ne,selectedTypes:R.state.types,onTypesChange:R.setTypes,addons:a?.addons,selectedAddons:R.state.addons,onAddonsChange:R.setAddons,hideAddons:s!==void 0}),T(`div`,{className:`flex items-center gap-2`,children:[S!==void 0&&(C?T(`button`,{type:`button`,onClick:M,className:`inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md border border-border bg-surface text-[11px] font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:[v(xu,{className:`h-3 w-3`}),`Done`]}):T(`button`,{type:`button`,onClick:()=>w(!0),className:`inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md border border-border bg-surface text-[11px] font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:[v(Qc,{className:`h-3 w-3`}),`Select`]})),T(`div`,{className:`relative`,children:[v(Ll,{className:`absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-foreground-subtle pointer-events-none`}),v(`input`,{type:`text`,value:oe,onChange:e=>se(e.target.value),placeholder:`Search by name or stableId`,"aria-label":`Search devices by name or stableId`,className:`h-7 pl-7 pr-2.5 rounded-md border border-border bg-surface text-[11px] text-foreground placeholder:text-foreground-subtle/60 focus:outline-none focus:ring-1 focus:ring-primary/40 w-56`})]})]})]}),S!==void 0&&C&&v(kM,{selectedIds:k,onClear:j,remove:S.remove,disable:S.disable,enable:S.enable}),ye?v(XM,{variant:ve?`filtered`:`nofilter`,onClearFilters:ve?R.clearFilters:void 0}):re===`cards`?v(Vp,{value:fe.accessoriesByParent,children:v(iN,{rows:V,accessoriesByParent:fe.accessoriesByParent,trpc:n,resolveIntegrationIcon:l??null,resolveParent:u??null,onNavigate:d??null,renderRowAction:g??null,selectable:N,rowClickSelects:P,activeSelected:k,onToggleSelection:A})}):v(Vp,{value:fe.accessoriesByParent,children:v(lN,{rows:V,accessoriesByParent:fe.accessoriesByParent,autoExpandedParents:me,visibleColumns:ee,sort:F,onSort:I,devices:de,trpc:n,resolveIntegrationIcon:l??null,resolveParent:u??null,onNavigate:d??null,renderRowAction:g??null,onDeleteDevice:_??null,selectable:N,rowClickSelects:P,activeSelected:k,onToggleSelection:A})}),!ye&&re===`table`&&T(`div`,{className:`flex items-center justify-between gap-4 flex-wrap pt-2 text-[11px] text-foreground-subtle`,children:[T(`div`,{className:`inline-flex items-center gap-2`,children:[he<=ie&&T(`span`,{children:[he,` `,he===1?`device`:`devices`]}),T(`div`,{className:`inline-flex items-center gap-1.5`,children:[v(`span`,{"aria-hidden":`true`,children:`Per page`}),v(`select`,{"aria-label":`Devices per page`,value:ie,onChange:e=>{ae(Number.parseInt(e.target.value,10))},className:`h-7 px-1.5 rounded-md border border-border bg-surface text-[11px] text-foreground focus:outline-none focus:ring-1 focus:ring-primary/40`,children:jM.map(e=>v(`option`,{value:e,children:e},e))})]})]}),v(GM,{currentPage:ge,totalItems:he,pageSize:z,onPageChange:R.setPage})]}),!ye&&re===`cards`&&v(GM,{currentPage:ge,totalItems:he,pageSize:z,onPageChange:R.setPage}),s===void 0&&ve&&he>0&&T(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`Showing `,he,` of `,RM(t).length,` devices`,le.length>0&&T(E,{children:[` `,`· filtered by`,` `,v(`strong`,{className:`text-primary`,children:le.map(e=>a?.addons?.find(t=>t.id===e)?.name??e).join(`, `)})]})]})]})}function bN(){b()}function xN(e){let{items:t,getKey:n,getSearchText:r,renderItem:i,getFilterType:a,mapFilterOption:s,filterOptions:l,filterLabel:u=`Type`,columns:f,renderExpanded:p,isExpanded:m,rowClassName:g,onRowClick:_,isLoading:y=!1,searchPlaceholder:b=`Search`,emptyLabel:x=`No items found.`,pageSize:S=100,toolbar:C}=e,[w,E]=h(``),D=AM(w,300),[O,k]=h([]),[A,j]=h(1);c(()=>{j(1)},[D,O]);let M=o(()=>{if(!a)return[];if(l)return l;let e=new Set;for(let n of t){let t=a(n);t!==null&&t!==``&&e.add(t)}return[...e].toSorted().map(e=>{let t=s?.(e);return{id:e,label:t?.label??e,...t?.icon?{icon:t.icon}:{}}})},[t,a,s,l]),N=o(()=>new Set(O),[O]),P=o(()=>{let e=D;return t.filter(t=>{if(N.size>0&&a){let e=a(t);if(e===null||!N.has(e))return!1}return!(e.trim()!==``&&!HM(e,r(t)))})},[t,D,r,N,a]),ee=P.length,F=Math.max(1,Math.ceil(ee/S)),te=Math.min(A,F),I=(te-1)*S,L=P.slice(I,I+S);return c(()=>{te!==A&&j(te)},[te,A]),T(`div`,{className:`flex flex-col gap-3 h-full min-h-0`,children:[T(`div`,{className:`flex items-center justify-between gap-3 flex-wrap shrink-0`,children:[a&&M.length>0?v(qM,{label:u,options:M,selected:O,onChange:k}):v(`span`,{}),T(`div`,{className:`flex items-center gap-2`,children:[T(`div`,{className:`relative`,children:[v(Ll,{className:`absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-foreground-subtle pointer-events-none`}),v(`input`,{type:`text`,value:w,onChange:e=>E(e.target.value),placeholder:b,"aria-label":b,className:`h-7 pl-7 pr-2.5 rounded-md border border-border bg-surface text-[11px] text-foreground placeholder:text-foreground-subtle/60 focus:outline-none focus:ring-1 focus:ring-primary/40 w-56`})]}),C]})]}),v(`div`,{className:`flex-1 min-h-0 overflow-y-auto`,children:y&&ee===0?v(`div`,{className:`flex items-center justify-center py-12 text-xs text-foreground-subtle`,children:`Loading…`}):ee===0?v(`div`,{className:`flex items-center justify-center py-12 text-xs text-foreground-subtle`,children:x}):f?v(`div`,{className:`rounded-lg border border-border bg-surface overflow-x-auto`,children:T(`table`,{className:`w-full border-collapse`,children:[v(`thead`,{children:v(`tr`,{className:`border-b border-border`,children:f.map(e=>v(`th`,{className:`text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle ${e.headerClassName??``}`,children:e.header},e.key))})}),v(`tbody`,{children:L.map(e=>T(d,{children:[v(`tr`,{className:`border-b border-border/60 ${_?`cursor-pointer hover:bg-surface-hover transition-colors`:``} ${g?.(e)??``}`,..._?{onClick:()=>_(e),role:`button`,tabIndex:0,onKeyDown:t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),_(e))}}:{},children:f.map(t=>v(`td`,{className:`px-2 py-2 align-middle ${t.cellClassName??``}`,children:t.cell(e)},t.key))}),p&&m?.(e)&&v(`tr`,{className:`border-b border-border/60 bg-surface/40`,children:v(`td`,{colSpan:f.length,className:`px-2 pb-2 pt-0`,children:p(e)})})]},n(e)))})]})}):v(`div`,{className:`space-y-1.5`,children:L.map(e=>v(d,{children:i?.(e)},n(e)))})}),v(`div`,{className:`shrink-0`,children:v(GM,{currentPage:te,totalItems:ee,pageSize:S,onPageChange:j})})]})}function SN(e){return`mode`in e&&e.mode===`generic`?v(xN,{...e}):v(yN,{...e})}function CN({trpc:e,deviceId:t,features:n,layout:r}){let{cap:i,slice:a,available:o}=$f({trpc:e,deviceId:t,cap:e=>e.cover,slice:e=>e.state.cover});if(a===void 0)return null;let s=(n??[]).includes(`cover-positionable`),c=!o,l=a.position,u=e=>{c||!e||e({})};return T(`div`,{className:G(`inline-flex items-center gap-1`,r===`full`&&`flex-col items-stretch gap-2`),children:[T(`div`,{className:`inline-flex items-center gap-1`,children:[v(wN,{label:`Open`,busy:c,onClick:()=>u(i?.open),children:v($s,{className:`h-3.5 w-3.5`})}),v(wN,{label:`Stop`,busy:c,onClick:()=>u(i?.stop),children:v(Zl,{className:`h-3 w-3`})}),v(wN,{label:`Close`,busy:c,onClick:()=>u(i?.close),children:v(Xs,{className:`h-3.5 w-3.5`})})]}),s&&r===`full`&&T(`label`,{className:`flex items-center gap-2 text-xs text-foreground-subtle`,children:[v(`span`,{children:`Position`}),v(`input`,{"aria-label":`Position`,type:`range`,min:0,max:100,step:1,value:l??0,disabled:c,onChange:e=>{c||i?.setPosition({position:Number(e.target.value)})}}),T(`span`,{className:`tabular-nums w-8 text-right`,children:[l??`—`,`%`]})]})]})}function wN({label:e,busy:t,onClick:n,children:r}){return v(`button`,{type:`button`,"aria-label":e,title:e,disabled:t,onClick:e=>{e.stopPropagation(),n()},className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,t&&`opacity-40 cursor-not-allowed`),children:r})}var TN=[`cover`,`lock-control`,`switch`,`brightness`,`fan-control`,`climate-control`,`media-player`,`control`],EN=240,DN=6;function ON({icon:e,title:t,children:n}){let r=p(null),i=p(null),[a,o]=h(null),s=a!==null,l=()=>o(null),u=()=>{let e=r.current;if(!e)return;let t=e.getBoundingClientRect(),n=Math.min(EN,window.innerWidth-16),i=Math.max(8,Math.min(t.right-n,window.innerWidth-n-8));o({top:t.bottom+DN,left:i,width:n})};return c(()=>{if(!s)return;let e=e=>{let t=e.target;i.current?.contains(t)||r.current?.contains(t)||l()},t=e=>{e.key===`Escape`&&l()};return document.addEventListener(`mousedown`,e),document.addEventListener(`touchstart`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`touchstart`,e),document.removeEventListener(`keydown`,t)}},[s]),T(E,{children:[v(`button`,{ref:r,type:`button`,title:t,"aria-label":t,"aria-haspopup":`dialog`,"aria-expanded":s,onClick:e=>{e.stopPropagation(),s?l():u()},className:G(`inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors flex-shrink-0`,s&&`bg-surface-hover text-foreground`),children:v(e,{className:`h-3 w-3`})}),a&&A(v(`div`,{ref:i,style:{position:`fixed`,top:a.top,left:a.left,width:a.width},className:`z-[9999] rounded-lg border border-border bg-surface shadow-lg shadow-black/30 p-2`,onClick:e=>e.stopPropagation(),children:n}),document.body)]})}function kN({lastChangedAt:e,className:t}){let n=An(e);return T(`span`,{title:n===null?`Unavailable`:`Unavailable · last seen ${n}`,className:G(`inline-flex items-center gap-1 rounded-full px-2 py-0.5`,`bg-surface-hover text-foreground-subtle text-[10px] font-medium`,`border border-border`,t),children:[v(gu,{className:`h-3 w-3 flex-shrink-0`,"aria-hidden":`true`}),v(`span`,{children:`Unavailable`}),n===null?null:v(`span`,{className:`text-foreground-subtle/70`,children:`· last seen ${n}`})]})}function AN({trpc:e,children:t,linkDeviceId:n,primaryChildEntityId:r,onSetPrimary:i}){let a=vp(t,n,r),o=a===null?void 0:t.find(e=>e.id===a.id);if(o===void 0)return v(`div`,{className:`flex h-full w-full items-center justify-center p-4 text-[11px] italic text-foreground-subtle`,children:`No child entities to display.`});let s=xj(o.type)?.HeroCard??xm;return T(`div`,{className:`flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4`,children:[t.length>1&&v(jN,{childrenList:t,selectedId:o.id,onSetPrimary:i}),v(s,{trpc:e,deviceId:o.id,features:o.features})]})}function jN({childrenList:e,selectedId:t,onSetPrimary:n}){return T(`label`,{className:`flex items-center justify-end gap-1.5 self-end text-[11px] text-foreground-subtle`,children:[v(`span`,{children:`primary child:`}),v(`select`,{value:t,onChange:r=>{let i=Number(r.target.value);if(!Number.isFinite(i)||i===t)return;let a=e.find(e=>e.id===i);a!==void 0&&n(hp(a))},className:`rounded-md border border-border bg-surface px-1.5 py-0.5 text-[11px] text-foreground`,children:e.map(e=>T(`option`,{value:e.id,children:[e.name,` (`,e.type,`)`]},e.id))})]})}function MN({options:e,value:t,onChange:n}){return v(`div`,{className:`flex flex-wrap gap-2`,children:e.map(e=>{let r=e.id===t;return T(`button`,{onClick:()=>e.available&&n(e.id),disabled:!e.available,className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-xs font-medium transition-all ${r?`border-primary/40 bg-primary/10 text-primary`:e.available?`border-border bg-surface text-foreground-subtle hover:bg-surface-hover hover:text-foreground`:`border-border/40 bg-surface/40 text-foreground-subtle/40 cursor-not-allowed`}`,children:[v(yc,{className:`h-3.5 w-3.5 shrink-0`}),e.label,e.isBest&&T(`span`,{className:`inline-flex items-center gap-0.5 rounded-full bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-semibold text-amber-400`,children:[v(Ql,{className:`h-2.5 w-2.5`}),`Best`]}),e.platformScore!=null&&T(`span`,{className:`text-[10px] text-foreground-subtle/60`,children:[`(`,e.platformScore,`)`]}),v(`span`,{className:`h-1.5 w-1.5 rounded-full ${e.available?`bg-success`:`bg-danger`}`})]},e.id)})})}function NN(e,t){let n=new Set(t.slots.flatMap(e=>e.addons.map(e=>e.id))),r=[];function i(e){if(!n.has(e.addonId))return r.push(`Addon "${e.addonId}" is no longer available — step removed`),null;let a=t.slots.flatMap(e=>e.addons).find(t=>t.id===e.addonId),o=e.modelId;if(a&&!a.models.some(e=>e.id===o)){let t=a.defaultModelId;r.push(`Model "${o}" not available for ${e.addonId} — using "${t}"`),o=t}let s=e.children.map(e=>i(e)).filter(e=>e!==null);return{...e,modelId:o,children:s}}let a=e.map(e=>i(e)).filter(e=>e!==null);return{valid:r.length===0,steps:a,warnings:r}}function PN(e){let t=new Map;for(let n of e.slots)for(let e of n.addons)t.set(e.id,e);return t}function FN(e){return{addonId:e.id,addonName:e.name,slot:e.slot,inputClasses:[...e.inputClasses],outputClasses:[...e.outputClasses],enabled:!0,modelId:e.defaultModelId,children:[]}}function IN({addon:e,onClick:t}){return v(`button`,{type:`button`,onClick:t,className:`w-full rounded-lg border border-dashed border-border/60 px-3 py-2.5 text-left transition-all hover:border-primary/30 hover:bg-surface/60 group`,children:T(`div`,{className:`flex items-center gap-3`,children:[v(sc,{className:`h-[18px] w-[18px] text-foreground-subtle/30 group-hover:text-primary/60 shrink-0`}),T(`div`,{className:`flex-1 min-w-0`,children:[v(`span`,{className:`text-[13px] font-medium text-foreground-subtle/50 group-hover:text-foreground-subtle block truncate`,children:e.name}),T(`div`,{className:`flex items-center gap-1 mt-0.5 flex-wrap`,children:[e.inputClasses.map(e=>v(`span`,{className:`text-[9px] uppercase font-semibold tracking-wide px-1.5 py-0.5 rounded bg-blue-500/8 text-blue-400/50`,children:e},e)),e.inputClasses.length>0&&e.outputClasses.length>0&&v(`span`,{className:`text-foreground-subtle/25 text-[10px]`,children:`→`}),e.outputClasses.map(e=>v(`span`,{className:`text-[9px] uppercase font-semibold tracking-wide px-1.5 py-0.5 rounded bg-green-500/8 text-green-400/50`,children:e},e))]})]})]})})}function LN({schema:e,steps:t,onChange:n,templates:r,selectedTemplateId:i,onSelectTemplate:a,onSaveTemplate:s,onUpdateTemplate:c,onDeleteTemplate:l,readOnly:u=!1,excludeAddons:d=[],hideTemplates:f=!1,showOnlyEnabled:p=!1,showSlotLabels:m=!1,toggleMode:g=`simple`,overrides:_={},onOverrideChange:y,inheritedEnabledByAddon:b={},hideModelAndSettings:x=!1}){let S=e=>({toggleMode:g,hideModelAndSettings:x,...g===`threeState`?{overrideState:_[e]===void 0?null:_[e],onOverrideChange:y?t=>y(e,t):void 0,inheritedEnabled:b[e]}:{}}),C=o(()=>new Set(d),[d]),w=o(()=>PN(e),[e]),[E,D]=h([]),O=i?JSON.stringify(t)!==JSON.stringify(r.find(e=>e.id===i)?.steps):!1;function k(t){let n=t.target.value||null;if(n){let t=r.find(e=>e.id===n);t&&D([...NN(t.steps,e).warnings])}else D([]);a(n)}function A(){i&&c(i,t)}function j(){let e=window.prompt(`Template name:`);e?.trim()&&s(e.trim(),t)}function M(){if(!i)return;let e=r.find(e=>e.id===i);e&&window.confirm(`Delete template "${e.name}"?`)&&l(i)}function N(e){n(t.map(t=>t.addonId===e.addonId?P(e):t))}function P(e){let t=e.children.some(e=>e.enabled||e.children.some(e=>e.enabled));return{...e,enabled:e.enabled||t,children:e.children.map(e=>{let t=e.children.some(e=>e.enabled);return{...e,enabled:e.enabled||t}})}}function ee(e,r){let i=FN(r);n(t.map(t=>t.addonId===e?{...t,children:[...t.children,i]}:t))}function F(e){let t=new Set;for(let n of e){t.add(n.addonId);for(let e of n.children)t.add(e.addonId);let e=F(n.children);for(let n of e)t.add(n)}return t}let te=F(t);function I(t){let n=w.get(t.addonId);if(!n)return[];let r=e.slots.find(e=>e.id===n.slot)?.parentSlot==null,i=n.childSlots,a=new Set(t.children.map(e=>e.addonId)),o=[];for(let n of e.slots)if(i.includes(n.id))for(let e of n.addons){if(a.has(e.id)||C.has(e.id))continue;let n=e.inputClasses.length===0;n&&!r||(n||e.inputClasses.some(e=>t.outputClasses.includes(e)))&&o.push(e)}return o}function L(e){let r=p?{...e,children:e.children.filter(e=>e.enabled).map(e=>({...e,children:e.children.filter(e=>e.enabled)}))}:e,i=p?[]:I(r);return T(`div`,{className:`space-y-1.5`,children:[v(Kd,{step:r,schema:w.get(r.addonId)??null,allSchemas:w,onChange:N,onDelete:u?void 0:e=>n(t.filter(t=>t.addonId!==e)),readOnly:u,...S(r.addonId)}),(r.children.length>0||i.length>0)&&T(`div`,{className:`ml-4 pl-3 border-l border-border/60 space-y-1.5`,children:[m&&v(`span`,{className:`text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/40`,children:`Slot: Cropper / Classifier`}),r.children.map(e=>{let t=I(e);return T(`div`,{className:`space-y-1.5`,children:[v(Kd,{step:e,schema:w.get(e.addonId)??null,allSchemas:w,depth:1,onChange:e=>{N({...r,children:r.children.map(t=>t.addonId===e.addonId?e:t)})},onDelete:u?void 0:e=>{N({...r,children:r.children.filter(t=>t.addonId!==e)})},readOnly:u,...S(e.addonId)}),(e.children.length>0||t.length>0)&&T(`div`,{className:`ml-4 pl-3 border-l border-border/40 space-y-1.5`,children:[m&&v(`span`,{className:`text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/30`,children:`Slot: Recognizer`}),e.children.map(t=>v(Kd,{step:t,schema:w.get(t.addonId)??null,allSchemas:w,depth:2,onChange:t=>{N({...r,children:r.children.map(n=>n.addonId===e.addonId?{...n,children:n.children.map(e=>e.addonId===t.addonId?t:e)}:n)})},onDelete:u?void 0:t=>{N({...r,children:r.children.map(n=>n.addonId===e.addonId?{...n,children:n.children.filter(e=>e.addonId!==t)}:n)})},readOnly:u,...S(t.addonId)},t.addonId)),!u&&t.map(t=>v(IN,{addon:t,onClick:()=>{let n=FN(t);N({...r,children:r.children.map(t=>t.addonId===e.addonId?{...t,children:[...t.children,n]}:t)})}},t.id))]})]},e.addonId)}),!u&&i.map(e=>v(IN,{addon:e,onClick:()=>ee(r.addonId,e)},e.id))]})]},r.addonId)}let ne=e.slots.filter(e=>e.parentSlot===null).toSorted((e,t)=>e.priority-t.priority);return T(`div`,{className:`space-y-4`,children:[!f&&v(`div`,{className:`rounded-lg border border-border bg-surface p-3`,children:T(`div`,{className:`flex items-center gap-2`,children:[v(`div`,{className:`relative flex-1 min-w-0`,children:T(`select`,{value:i??``,onChange:k,className:`w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:border-primary/50`,children:[v(`option`,{value:``,children:`No template`}),r.map(e=>v(`option`,{value:e.id,children:e.name},e.id))]})}),O&&v(`span`,{className:`h-1.5 w-1.5 rounded-full bg-amber-500 shrink-0`}),v(`button`,{onClick:A,disabled:!i||u,title:`Save`,className:G(`p-2 rounded-lg border border-border transition-colors`,i&&!u?`text-foreground-subtle hover:bg-surface-hover`:`text-foreground-subtle/30 cursor-not-allowed`),children:v(Pl,{className:`h-4 w-4`})}),v(`button`,{onClick:j,disabled:u,title:`Save As`,className:G(`p-2 rounded-lg border border-border transition-colors`,u?`text-foreground-subtle/30 cursor-not-allowed`:`text-foreground-subtle hover:bg-surface-hover`),children:v(_c,{className:`h-4 w-4`})}),v(`button`,{onClick:M,disabled:!i||u,title:`Delete`,className:G(`p-2 rounded-lg border border-border transition-colors`,i&&!u?`text-foreground-subtle hover:text-danger`:`text-foreground-subtle/30 cursor-not-allowed`),children:v(au,{className:`h-4 w-4`})})]})}),E.length>0&&T(`div`,{className:`rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 text-xs text-amber-400 space-y-1`,children:[T(`div`,{className:`flex items-center justify-between`,children:[v(`span`,{className:`font-medium`,children:`Template loaded with warnings:`}),v(`button`,{onClick:()=>D([]),className:`text-amber-400/60 hover:text-amber-400`,children:v(xu,{className:`h-3.5 w-3.5`})})]}),E.map((e,t)=>T(`div`,{children:[`• `,e]},t))]}),ne.map(e=>{let r=t.filter(t=>t.slot===e.id&&!C.has(t.addonId)),i=p?r.filter(e=>e.enabled):r,a=p?[]:e.addons.filter(e=>!te.has(e.id)&&!C.has(e.id)),o=new Map,s=[];for(let e of i)e.group?(o.has(e.group)||o.set(e.group,[]),o.get(e.group).push(e)):s.push(e);return T(`div`,{className:`space-y-2`,children:[m&&T(`span`,{className:`text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/50`,children:[`Slot: `,e.label]}),s.map(e=>L(e)),[...o.entries()].map(([e,t])=>T(`div`,{className:`space-y-2 rounded-lg border border-border/40 p-2`,children:[v(`span`,{className:`text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/50 px-1`,children:e}),t.map(e=>L(e))]},e)),!u&&a.map(e=>v(IN,{addon:e,onClick:()=>{n([...t,FN(e)])}},e.id))]},e.id)})]})}var RN={person:`#3b82f6`,vehicle:`#f59e0b`,animal:`#22c55e`,face:`#a855f7`,plate:`#ec4899`,bird:`#14b8a6`,dog:`#84cc16`,cat:`#f97316`,car:`#f59e0b`,truck:`#d97706`,bus:`#b45309`,motorcycle:`#eab308`,bicycle:`#ca8a04`,motion:`#facc15`},zN=[`#ef4444`,`#8b5cf6`,`#06b6d4`,`#f97316`,`#10b981`,`#6366f1`,`#e11d48`,`#0891b2`,`#7c3aed`,`#059669`],BN=`#f59e42`;function VN(e,t){if(t?.[e])return t[e];if(t?.[e.toLowerCase()])return t[e.toLowerCase()];if(RN[e])return RN[e];if(RN[e.toLowerCase()])return RN[e.toLowerCase()];let n=0;for(let t=0;t<e.length;t++)n=n*31+(e.codePointAt(t)??0)>>>0;return zN[n%zN.length]??`#f59e42`}function HN({src:e,imageWidth:t,imageHeight:n,detections:r=[],classColors:i,aspectRatio:a,className:o,placeholder:s,showConfidence:c=!0,minConfidence:l=0,borderWidth:u=2}){function d(e){return VN(e,i)}let f=a??(t&&n?`${t}/${n}`:`16/9`),p=r.filter(e=>e.score>=l),m=p.filter(e=>e.kind===`first-level`),h=p.filter(e=>e.kind===`detail`),g=KN(h,e=>e.parentId??``);return v(`div`,{className:G(`rounded-lg border border-border bg-surface overflow-hidden relative`,o),style:{aspectRatio:f},children:e?T(E,{children:[v(`img`,{src:e,className:`absolute inset-0 w-full h-full object-fill`,alt:``}),p.map((e,r)=>e.debug?.mask&&e.debug.maskWidth&&e.debug.maskHeight?v(WN,{mask:e.debug.mask,maskWidth:e.debug.maskWidth,maskHeight:e.debug.maskHeight,bbox:e.bbox,imageWidth:t,imageHeight:n,color:d(e.macroClass)},`mask-${r}`):null),m.map(e=>{let r=g.get(e.id)??[];return v(UN,{detection:e,imageWidth:t,imageHeight:n,color:d(e.macroClass),showConfidence:c,borderWidth:e.debug?.mask?1:u,children:r.map(t=>v(GN,{child:t,parentBbox:e.bbox,color:d(t.macroClass),showConfidence:c},`child-${t.id}`))},`det-${e.id}`)}),h.filter(e=>!e.parentId||!m.some(t=>t.id===e.parentId)).map(e=>v(UN,{detection:e,imageWidth:t,imageHeight:n,color:d(e.macroClass),showConfidence:c,borderWidth:u},`orphan-${e.id}`))]}):v(`div`,{className:`w-full h-full flex items-center justify-center text-foreground-subtle text-sm`,children:s??`No image loaded`})})}function UN({detection:e,imageWidth:t,imageHeight:n,color:r,showConfidence:i,borderWidth:a,children:o}){let{x:s,y:c,width:l,height:u}=e.bbox,d=T(`div`,{className:`absolute left-0 flex flex-col items-start gap-px`,style:{bottom:`100%`,marginBottom:`2px`},children:[T(`span`,{className:`text-[10px] px-1 rounded-sm whitespace-nowrap text-white`,style:{backgroundColor:r},children:[e.macroClass,i&&` ${(e.score*100).toFixed(0)}%`]}),e.labels.map((t,n)=>T(`span`,{className:`text-[9px] font-semibold px-1 rounded-sm whitespace-nowrap text-white`,style:{backgroundColor:VN(t.label)},children:[t.label,` `,(t.score*100).toFixed(0),`%`]},`${e.id}-lbl-${n}`))]});return T(`div`,{className:`absolute rounded-sm`,style:{left:`${s/t*100}%`,top:`${c/n*100}%`,width:`${l/t*100}%`,height:`${u/n*100}%`,borderWidth:`${a}px`,borderStyle:`solid`,borderColor:r},children:[d,o]})}function WN({mask:e,maskWidth:t,maskHeight:n,bbox:r,imageWidth:i,imageHeight:a,color:o}){let s=p(null);return c(()=>{let r=s.current;if(!r)return;let i=r.getContext(`2d`);if(!i)return;let a=atob(e),c=new Uint8Array(a.length);for(let e=0;e<a.length;e++)c[e]=a.charCodeAt(e);let l=parseInt(o.slice(1,3),16),u=parseInt(o.slice(3,5),16),d=parseInt(o.slice(5,7),16);r.width=t,r.height=n;let f=i.createImageData(t,n),p=t*n;for(let e=0;e<p;e++){let t=e<c.length?c[e]:0,n=e*4;t>0&&(f.data[n]=l,f.data[n+1]=u,f.data[n+2]=d,f.data[n+3]=120)}i.putImageData(f,0,0)},[e,t,n,o]),v(`canvas`,{ref:s,className:`absolute pointer-events-none`,style:{left:`${r.x/i*100}%`,top:`${r.y/a*100}%`,width:`${r.width/i*100}%`,height:`${r.height/a*100}%`,imageRendering:`pixelated`}})}function GN({child:e,parentBbox:t,color:n,showConfidence:r}){if(t.width<=0||t.height<=0)return null;let i=(e.bbox.x-t.x)/t.width*100,a=(e.bbox.y-t.y)/t.height*100,o=e.bbox.width/t.width*100,s=e.bbox.height/t.height*100;return v(`div`,{className:`absolute rounded-sm`,style:{left:`${Math.max(0,i)}%`,top:`${Math.max(0,a)}%`,width:`${Math.min(100,o)}%`,height:`${Math.min(100,s)}%`,borderWidth:`1px`,borderStyle:`solid`,borderColor:n},children:T(`div`,{className:`absolute left-0 flex flex-col items-start gap-px`,style:{bottom:`100%`,marginBottom:`1px`},children:[T(`span`,{className:`text-[9px] px-0.5 rounded-sm whitespace-nowrap text-white`,style:{backgroundColor:n},children:[e.macroClass,r&&` ${(e.score*100).toFixed(0)}%`]}),e.labels.map((t,n)=>T(`span`,{className:`text-[8px] font-semibold px-0.5 rounded-sm whitespace-nowrap text-white`,style:{backgroundColor:VN(t.label)},children:[t.label,` `,(t.score*100).toFixed(0),`%`]},`${e.id}-lbl-${n}`))]})})}function KN(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e)??[];i.push(r),n.set(e,i)}return n}function qN({detections:e,classColors:t,className:n,hiddenKeys:r,onToggleVisibility:i}){let a=t;if(e.length===0)return v(`div`,{className:`text-sm text-foreground-subtle italic text-center py-4`,children:`No detections`});let o=e.filter(e=>e.kind===`first-level`),s=e.filter(e=>e.kind===`detail`),c=new Map;for(let e of s){if(!e.parentId)continue;let t=c.get(e.parentId)??[];t.push(e),c.set(e.parentId,t)}let l=s.filter(e=>!e.parentId||!o.some(t=>t.id===e.parentId));return T(`div`,{className:n,children:[T(`div`,{className:`text-xs font-medium text-foreground-subtle uppercase tracking-wide mb-2`,children:[`Detections (`,e.length,`)`]}),T(`div`,{className:`space-y-2`,children:[o.map(e=>v(JN,{detection:e,children_:c.get(e.id)??[],colors:a,hiddenKeys:r,onToggleVisibility:i},e.id)),l.map(e=>v(JN,{detection:e,children_:[],colors:a,hiddenKeys:r,onToggleVisibility:i},e.id))]})]})}function JN({detection:e,children_:t,colors:n,hiddenKeys:r,onToggleVisibility:i}){let a=VN(e.macroClass,n),o=!r?.has(e.id),s=e.debug?.mask,c=e.debug?.maskWidth,l=e.debug?.maskHeight,u=e.debug?.alternateLabels;return T(`div`,{className:`rounded-md border border-border bg-surface p-3 space-y-1 ${o?``:`opacity-40`}`,children:[T(`div`,{className:`flex justify-between items-center`,children:[T(`div`,{className:`flex items-center gap-2`,children:[i&&v(`input`,{type:`checkbox`,checked:o,onChange:()=>i(e.id,!o),className:`h-3.5 w-3.5 rounded border-border accent-primary cursor-pointer shrink-0`}),v(`span`,{className:`h-2.5 w-2.5 rounded-full shrink-0`,style:{backgroundColor:a}}),v(`span`,{className:`text-sm font-medium text-foreground`,children:e.macroClass}),e.kind===`detail`&&v(`span`,{className:`text-[9px] font-mono px-1 py-0.5 rounded bg-primary/10 text-primary`,children:`detail`}),s&&c&&l&&T(`span`,{className:`text-[9px] font-mono px-1 py-0.5 rounded bg-primary/10 text-primary`,children:[`mask `,c,`x`,l]})]}),v(ZN,{confidence:e.score})]}),T(`div`,{className:`text-[10px] text-foreground-subtle font-mono`,children:[`bbox: [`,Math.round(e.bbox.x),`, `,Math.round(e.bbox.y),`,`,` `,Math.round(e.bbox.x+e.bbox.width),`,`,` `,Math.round(e.bbox.y+e.bbox.height),`]`]}),e.labels.length>0&&v(`div`,{className:`flex flex-wrap gap-1 mt-1`,children:e.labels.map((e,t)=>T(`span`,{className:`inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full`,style:{backgroundColor:VN(e.label,n)+`20`,color:VN(e.label,n)},children:[e.label,T(`span`,{className:`opacity-60`,children:[(e.score*100).toFixed(0),`%`]}),e.detectionId&&T(`span`,{className:`opacity-40 text-[8px]`,children:[`→ `,e.detectionId]})]},t))}),u&&Object.keys(u).length>0&&v(XN,{alternateLabels:u,colors:n}),t.length>0&&v(YN,{items:t,colors:n,hiddenKeys:r,onToggleVisibility:i})]})}function YN({items:e,colors:t,hiddenKeys:n,onToggleVisibility:r}){return v(`div`,{className:`ml-4 mt-1.5 space-y-1.5 border-l-2 border-border pl-3`,children:e.map(e=>{let i=VN(e.macroClass,t),a=!n?.has(e.id),o=e.debug?.mask,s=e.debug?.maskWidth,c=e.debug?.maskHeight;return T(`div`,{className:`text-xs space-y-0.5 ${a?``:`opacity-40`}`,children:[T(`div`,{className:`flex items-center gap-1.5`,children:[r&&v(`input`,{type:`checkbox`,checked:a,onChange:()=>r(e.id,!a),className:`h-3 w-3 rounded border-border accent-primary cursor-pointer shrink-0`}),v(`span`,{className:`h-1.5 w-1.5 rounded-full shrink-0`,style:{backgroundColor:i}}),v(`span`,{className:`font-medium`,style:{color:i},children:e.macroClass}),T(`span`,{className:`text-foreground-subtle`,children:[(e.score*100).toFixed(0),`%`]}),o&&s&&c&&T(`span`,{className:`text-[9px] font-mono px-1 py-0.5 rounded bg-primary/10 text-primary`,children:[`mask `,s,`x`,c]})]}),e.labels.length>0&&v(`div`,{className:`flex flex-wrap gap-1 ml-5 mt-0.5`,children:e.labels.map((e,n)=>T(`span`,{className:`inline-flex items-center gap-0.5 text-[9px] font-medium px-1 py-0.5 rounded-full`,style:{backgroundColor:VN(e.label,t)+`20`,color:VN(e.label,t)},children:[e.label,` `,T(`span`,{className:`opacity-60`,children:[(e.score*100).toFixed(0),`%`]})]},n))})]},e.id)})})}function XN({alternateLabels:e,colors:t}){let[n,r]=h(!1),i=Object.keys(e);return T(`div`,{className:`mt-1`,children:[T(`button`,{onClick:()=>r(e=>!e),className:`text-[9px] text-foreground-subtle hover:text-foreground transition-colors flex items-center gap-1`,children:[v(`span`,{className:`transition-transform ${n?`rotate-90`:``}`,children:`▶`}),`Alternates (`,i.length,` source`,i.length===1?``:`s`,`)`]}),n&&v(`div`,{className:`mt-1 ml-3 space-y-1.5`,children:i.map(n=>{let r=e[n];return!r||r.length===0?null:T(`div`,{children:[v(`div`,{className:`text-[9px] font-medium text-foreground-subtle mb-0.5`,children:n}),v(`div`,{className:`flex flex-wrap gap-1`,children:r.map((e,r)=>T(`span`,{className:`inline-flex items-center gap-0.5 text-[9px] px-1 py-0.5 rounded-full`,style:{backgroundColor:VN(n,t)+`10`,color:VN(n,t),opacity:Math.max(.4,e.score)},children:[e.label,T(`span`,{className:`opacity-60`,children:[(e.score*100).toFixed(1),`%`]})]},r))})]},n)})})]})}function ZN({confidence:e}){return T(`span`,{className:`text-xs font-medium px-2 py-0.5 rounded-full ${e>=.8?`bg-success/10 text-success`:e>=.5?`bg-warning/10 text-warning`:`bg-danger/10 text-danger`}`,children:[(e*100).toFixed(1),`%`]})}function QN({timings:e,totalMs:t,className:n}){let r=Object.entries(e);return r.length===0&&t===void 0?null:T(`div`,{className:`rounded-lg border border-border bg-surface p-3 space-y-2 ${n??``}`,children:[v(`div`,{className:`text-xs font-medium text-foreground-subtle uppercase tracking-wide`,children:`Timings`}),T(`div`,{className:`space-y-1 text-xs`,children:[r.map(([e,t])=>T(`div`,{className:`flex justify-between`,children:[v(`span`,{className:`text-foreground-subtle`,children:e}),T(`span`,{className:`font-mono text-foreground`,children:[t.toFixed(1),`ms`]})]},e)),t!==void 0&&T(`div`,{className:`flex justify-between pt-1 border-t border-border font-medium text-foreground`,children:[v(`span`,{children:`Total`}),T(`span`,{className:`font-mono`,children:[t.toFixed(1),`ms`]})]})]})]})}function $N({images:e,selectedFilename:t,uploadedName:n,onSelect:r,onUpload:i,className:a,accept:o=`image/*`,uploadLabel:s=`Upload...`}){return T(`div`,{className:`flex flex-wrap items-center gap-2 ${a??``}`,children:[e.map(e=>v(`button`,{onClick:()=>r(e.filename),className:`px-3 py-1.5 text-xs rounded-md border transition-colors ${t===e.filename?`bg-primary text-primary-foreground border-primary`:`bg-surface border-border text-foreground hover:border-primary/50`}`,children:e.id??e.filename.replace(/\.[^.]+$/,``)},e.filename)),v(`button`,{onClick:()=>{let e=document.createElement(`input`);e.type=`file`,e.accept=o,e.onchange=()=>{let t=e.files?.[0];if(!t)return;let n=new FileReader;n.onload=()=>{let e=n.result,r=e.split(`,`)[1];r&&i(r,t.name,e)},n.readAsDataURL(t)},e.click()},className:`px-3 py-1.5 text-xs rounded-md border border-border bg-surface text-foreground hover:bg-surface-hover transition-colors`,children:s}),n&&v(`span`,{className:`text-xs text-foreground-subtle`,children:n})]})}var eP=`w-full px-3 py-2 text-sm rounded-md border border-border bg-surface text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50`;function tP({runtime:e,backend:t,modelId:n,agentId:r=`hub`,runtimes:i,backends:a,models:o,agents:s=[],onRuntimeChange:c,onBackendChange:l,onModelChange:u,onAgentChange:d,layout:f=`grid`,className:p,showAgent:m=!1}){return T(`div`,{className:`${f===`grid`?`grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4`:f===`horizontal`?`flex flex-wrap items-end gap-4`:`space-y-3`} ${p??``}`,children:[m&&s.length>0&&T(`label`,{className:`space-y-1`,children:[v(`span`,{className:`text-xs font-medium text-foreground-subtle`,children:`Agent`}),v(`select`,{value:r,onChange:e=>d?.(e.target.value),className:eP,children:s.map(e=>T(`option`,{value:e.id,children:[e.name,` (`,e.status,`)`]},e.id))})]}),T(`label`,{className:`space-y-1`,children:[v(`span`,{className:`text-xs font-medium text-foreground-subtle`,children:`Runtime`}),v(`select`,{value:e,onChange:e=>c(e.target.value),className:eP,children:i.map(e=>T(`option`,{value:e.value,disabled:!e.available,children:[e.label,e.available?``:` (unavailable)`]},e.value))})]}),T(`label`,{className:`space-y-1`,children:[v(`span`,{className:`text-xs font-medium text-foreground-subtle`,children:`Backend`}),v(`select`,{value:t,onChange:e=>l(e.target.value),className:eP,children:a.map(e=>T(`option`,{value:e.id,disabled:!e.available,children:[e.label,e.available?``:` (unavailable)`]},e.id))})]}),T(`label`,{className:`space-y-1`,children:[v(`span`,{className:`text-xs font-medium text-foreground-subtle`,children:`Model`}),v(`select`,{value:n,onChange:e=>u(e.target.value),className:eP,children:o.length===0?v(`option`,{value:``,children:`No compatible models`}):o.map(e=>T(`option`,{value:e.id,children:[e.name,e.downloaded?` ✓`:``]},e.id))})]})]})}var nP=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,t){this.keyToValue.set(e,t),this.valueToKey.set(t,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},rP=class{constructor(e){this.generateIdentifier=e,this.kv=new nP}register(e,t){this.kv.getByValue(e)||(t||=this.generateIdentifier(e),this.kv.set(t,e))}clear(){this.kv.clear()}getIdentifier(e){return this.kv.getByValue(e)}getValue(e){return this.kv.getByKey(e)}},iP=class extends rP{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,t){typeof t==`object`?(t.allowProps&&this.classToAllowedProps.set(e,t.allowProps),super.register(e,t.identifier)):super.register(e,t)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function aP(e){if(`values`in Object)return Object.values(e);let t=[];for(let n in e)e.hasOwnProperty(n)&&t.push(e[n]);return t}function oP(e,t){let n=aP(e);if(`find`in n)return n.find(t);let r=n;for(let e=0;e<r.length;e++){let n=r[e];if(t(n))return n}}function sP(e,t){Object.entries(e).forEach(([e,n])=>t(n,e))}function cP(e,t){return e.indexOf(t)!==-1}function lP(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(t(r))return r}}var uP=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return oP(this.transfomers,t=>t.isApplicable(e))}findByName(e){return this.transfomers[e]}},dP=e=>Object.prototype.toString.call(e).slice(8,-1),fP=e=>e===void 0,pP=e=>e===null,mP=e=>typeof e!=`object`||!e||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,hP=e=>mP(e)&&Object.keys(e).length===0,gP=e=>Array.isArray(e),_P=e=>typeof e==`string`,vP=e=>typeof e==`number`&&!isNaN(e),yP=e=>typeof e==`boolean`,bP=e=>e instanceof RegExp,xP=e=>e instanceof Map,SP=e=>e instanceof Set,CP=e=>dP(e)===`Symbol`,wP=e=>e instanceof Date&&!isNaN(e.valueOf()),TP=e=>e instanceof Error,EP=e=>typeof e==`number`&&isNaN(e),DP=e=>yP(e)||pP(e)||fP(e)||vP(e)||_P(e)||CP(e),OP=e=>typeof e==`bigint`,kP=e=>e===1/0||e===-1/0,AP=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),jP=e=>e instanceof URL,MP=e=>e.replace(/\\/g,`\\\\`).replace(/\./g,`\\.`),NP=e=>e.map(String).map(MP).join(`.`),PP=(e,t)=>{let n=[],r=``;for(let i=0;i<e.length;i++){let a=e.charAt(i);if(!t&&a===`\\`){let t=e.charAt(i+1);if(t===`\\`){r+=`\\`,i++;continue}else if(t!==`.`)throw Error(`invalid path`)}if(a===`\\`&&e.charAt(i+1)===`.`){r+=`.`,i++;continue}if(a===`.`){n.push(r),r=``;continue}r+=a}let i=r;return n.push(i),n};function FP(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var IP=[FP(fP,`undefined`,()=>null,()=>void 0),FP(OP,`bigint`,e=>e.toString(),e=>typeof BigInt<`u`?BigInt(e):(console.error(`Please add a BigInt polyfill.`),e)),FP(wP,`Date`,e=>e.toISOString(),e=>new Date(e)),FP(TP,`Error`,(e,t)=>{let n={name:e.name,message:e.message};return`cause`in e&&(n.cause=e.cause),t.allowedErrorProps.forEach(t=>{n[t]=e[t]}),n},(e,t)=>{let n=Error(e.message,{cause:e.cause});return n.name=e.name,n.stack=e.stack,t.allowedErrorProps.forEach(t=>{n[t]=e[t]}),n}),FP(bP,`regexp`,e=>``+e,e=>{let t=e.slice(1,e.lastIndexOf(`/`)),n=e.slice(e.lastIndexOf(`/`)+1);return new RegExp(t,n)}),FP(SP,`set`,e=>[...e.values()],e=>new Set(e)),FP(xP,`map`,e=>[...e.entries()],e=>new Map(e)),FP(e=>EP(e)||kP(e),`number`,e=>EP(e)?`NaN`:e>0?`Infinity`:`-Infinity`,Number),FP(e=>e===0&&1/e==-1/0,`number`,()=>`-0`,Number),FP(jP,`URL`,e=>e.toString(),e=>new URL(e))];function LP(e,t,n,r){return{isApplicable:e,annotation:t,transform:n,untransform:r}}var RP=LP((e,t)=>CP(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>[`symbol`,t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,n)=>{let r=n.symbolRegistry.getValue(t[1]);if(!r)throw Error(`Trying to deserialize unknown symbol`);return r}),zP=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),BP=LP(AP,e=>[`typed-array`,e.constructor.name],e=>[...e],(e,t)=>{let n=zP[t[1]];if(!n)throw Error(`Trying to deserialize unknown typed array`);return new n(e)});function VP(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var HP=LP(VP,(e,t)=>[`class`,t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{let n=t.classRegistry.getAllowedProps(e.constructor);if(!n)return{...e};let r={};return n.forEach(t=>{r[t]=e[t]}),r},(e,t,n)=>{let r=n.classRegistry.getValue(t[1]);if(!r)throw Error(`Trying to deserialize unknown class '${t[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(r.prototype),e)}),UP=LP((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>[`custom`,t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,n)=>{let r=n.customTransformerRegistry.findByName(t[1]);if(!r)throw Error(`Trying to deserialize unknown custom value`);return r.deserialize(e)}),WP=[HP,RP,UP,BP],GP=(e,t)=>{let n=lP(WP,n=>n.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation(e,t)};let r=lP(IP,n=>n.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation}},KP={};IP.forEach(e=>{KP[e.annotation]=e});var qP=(e,t,n)=>{if(gP(t))switch(t[0]){case`symbol`:return RP.untransform(e,t,n);case`class`:return HP.untransform(e,t,n);case`custom`:return UP.untransform(e,t,n);case`typed-array`:return BP.untransform(e,t,n);default:throw Error(`Unknown transformation: `+t)}else{let r=KP[t];if(!r)throw Error(`Unknown transformation: `+t);return r.untransform(e,n)}},JP=(e,t)=>{if(t>e.size)throw Error(`index out of bounds`);let n=e.keys();for(;t>0;)n.next(),t--;return n.next().value};function YP(e){if(cP(e,`__proto__`))throw Error(`__proto__ is not allowed as a property`);if(cP(e,`prototype`))throw Error(`prototype is not allowed as a property`);if(cP(e,`constructor`))throw Error(`constructor is not allowed as a property`)}var XP=(e,t)=>{YP(t);for(let n=0;n<t.length;n++){let r=t[n];if(SP(e))e=JP(e,+r);else if(xP(e)){let i=+r,a=+t[++n]==0?`key`:`value`,o=JP(e,i);switch(a){case`key`:e=o;break;case`value`:e=e.get(o);break}}else e=e[r]}return e},ZP=(e,t,n)=>{if(YP(t),t.length===0)return n(e);let r=e;for(let e=0;e<t.length-1;e++){let n=t[e];if(gP(r)){let e=+n;r=r[e]}else if(mP(r))r=r[n];else if(SP(r)){let e=+n;r=JP(r,e)}else if(xP(r)){if(e===t.length-2)break;let i=+n,a=+t[++e]==0?`key`:`value`,o=JP(r,i);switch(a){case`key`:r=o;break;case`value`:r=r.get(o);break}}}let i=t[t.length-1];if(gP(r)?r[+i]=n(r[+i]):mP(r)&&(r[i]=n(r[i])),SP(r)){let e=JP(r,+i),t=n(e);e!==t&&(r.delete(e),r.add(t))}if(xP(r)){let e=+t[t.length-2],a=JP(r,e);switch(+i==0?`key`:`value`){case`key`:{let e=n(a);r.set(e,r.get(a)),e!==a&&r.delete(a);break}case`value`:r.set(a,n(r.get(a)));break}}return e},QP=e=>e<1;function $P(e,t,n,r=[]){if(!e)return;let i=QP(n);if(!gP(e)){sP(e,(e,a)=>$P(e,t,n,[...r,...PP(a,i)]));return}let[a,o]=e;o&&sP(o,(e,a)=>{$P(e,t,n,[...r,...PP(a,i)])}),t(a,r)}function eF(e,t,n,r){return $P(t,(t,n)=>{e=ZP(e,n,e=>qP(e,t,r))},n),e}function tF(e,t,n){let r=QP(n);function i(t,n){let i=XP(e,PP(n,r));t.map(e=>PP(e,r)).forEach(t=>{e=ZP(e,t,()=>i)})}if(gP(t)){let[n,a]=t;n.forEach(t=>{e=ZP(e,PP(t,r),()=>e)}),a&&sP(a,i)}else sP(t,i);return e}var nF=(e,t)=>mP(e)||gP(e)||xP(e)||SP(e)||TP(e)||VP(e,t);function rF(e,t,n){let r=n.get(e);r?r.push(t):n.set(e,[t])}function iF(e,t){let n={},r;return e.forEach(e=>{if(e.length<=1)return;t||(e=e.map(e=>e.map(String)).sort((e,t)=>e.length-t.length));let[i,...a]=e;i.length===0?r=a.map(NP):n[NP(i)]=a.map(NP)}),r?hP(n)?[r]:[r,n]:hP(n)?void 0:n}var aF=(e,t,n,r,i=[],a=[],o=new Map)=>{let s=DP(e);if(!s){rF(e,i,t);let n=o.get(e);if(n)return r?{transformedValue:null}:n}if(!nF(e,n)){let t=GP(e,n),r=t?{transformedValue:t.value,annotations:[t.type]}:{transformedValue:e};return s||o.set(e,r),r}if(cP(a,e))return{transformedValue:null};let c=GP(e,n),l=c?.value??e,u=gP(l)?[]:{},d={};sP(l,(s,c)=>{if(c===`__proto__`||c===`constructor`||c===`prototype`)throw Error(`Detected property ${c}. This is a prototype pollution risk, please remove it from your object.`);let l=aF(s,t,n,r,[...i,c],[...a,e],o);u[c]=l.transformedValue,gP(l.annotations)?d[MP(c)]=l.annotations:mP(l.annotations)&&sP(l.annotations,(e,t)=>{d[MP(c)+`.`+t]=e})});let f=hP(d)?{transformedValue:u,annotations:c?[c.type]:void 0}:{transformedValue:u,annotations:c?[c.type,d]:d};return s||o.set(e,f),f};function oF(e){return Object.prototype.toString.call(e).slice(8,-1)}function sF(e){return oF(e)===`Array`}function cF(e){if(oF(e)!==`Object`)return!1;let t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function lF(e,t,n,r,i){let a={}.propertyIsEnumerable.call(r,t)?`enumerable`:`nonenumerable`;a===`enumerable`&&(e[t]=n),i&&a===`nonenumerable`&&Object.defineProperty(e,t,{value:n,enumerable:!1,writable:!0,configurable:!0})}function uF(e,t={}){if(sF(e))return e.map(e=>uF(e,t));if(!cF(e))return e;let n=Object.getOwnPropertyNames(e),r=Object.getOwnPropertySymbols(e);return[...n,...r].reduce((n,r)=>{if(r===`__proto__`||sF(t.props)&&!t.props.includes(r))return n;let i=e[r];return lF(n,r,uF(i,t),e,t.nonenumerable),n},{})}var dF=class{constructor({dedupe:e=!1}={}){this.classRegistry=new iP,this.symbolRegistry=new rP(e=>e.description??``),this.customTransformerRegistry=new uP,this.allowedErrorProps=[],this.dedupe=e}serialize(e){let t=new Map,n=aF(e,t,this,this.dedupe),r={json:n.transformedValue};n.annotations&&(r.meta={...r.meta,values:n.annotations});let i=iF(t,this.dedupe);return i&&(r.meta={...r.meta,referentialEqualities:i}),r.meta&&(r.meta.v=1),r}deserialize(e,t){let{json:n,meta:r}=e,i=t?.inPlace?n:uF(n);return r?.values&&(i=eF(i,r.values,r.v??0,this)),r?.referentialEqualities&&(i=tF(i,r.referentialEqualities,r.v??0)),i}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e),{inPlace:!0})}registerClass(e,t){this.classRegistry.register(e,t)}registerSymbol(e,t){this.symbolRegistry.register(e,t)}registerCustom(e,t){this.customTransformerRegistry.register({name:t,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};dF.defaultInstance=new dF,dF.serialize=dF.defaultInstance.serialize.bind(dF.defaultInstance),dF.deserialize=dF.defaultInstance.deserialize.bind(dF.defaultInstance),dF.stringify=dF.defaultInstance.stringify.bind(dF.defaultInstance),dF.parse=dF.defaultInstance.parse.bind(dF.defaultInstance),dF.registerClass=dF.defaultInstance.registerClass.bind(dF.defaultInstance),dF.registerSymbol=dF.defaultInstance.registerSymbol.bind(dF.defaultInstance),dF.registerCustom=dF.defaultInstance.registerCustom.bind(dF.defaultInstance),dF.allowErrorProps=dF.defaultInstance.allowErrorProps.bind(dF.defaultInstance),dF.serialize,dF.deserialize,dF.stringify,dF.parse,dF.registerClass,dF.registerCustom,dF.registerSymbol,dF.allowErrorProps;function fF({className:e}){return T(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e,children:[v(`path`,{d:`M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0`}),v(`circle`,{cx:`12`,cy:`12`,r:`3`})]})}function pF({className:e}){return T(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e,children:[v(`path`,{d:`M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49`}),v(`path`,{d:`M14.084 14.158a3 3 0 0 1-4.242-4.242`}),v(`path`,{d:`M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143`}),v(`path`,{d:`m2 2 20 20`})]})}function mF({className:e}){return v(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e,children:v(`path`,{d:`M21 12a9 9 0 1 1-6.219-8.56`})})}function hF({onLogin:e,serverUrl:t,logoSrc:n,error:r,className:i}){let[a,o]=h(``),[s,c]=h(``),[l,u]=h(!1),[d,f]=h(!1),[p,m]=h(null),g=r??p;return v(`div`,{className:G(`flex min-h-screen items-center justify-center bg-background p-4`,i),children:T(`div`,{className:`w-full max-w-sm`,children:[n&&v(`div`,{className:`flex justify-center mb-8`,children:v(`img`,{src:n,alt:`Logo`,className:`h-12`})}),t&&v(`p`,{className:`mb-4 text-center text-xs text-foreground-subtle truncate`,children:t}),T(`form`,{onSubmit:async t=>{if(t.preventDefault(),!d){m(null),f(!0);try{await e(a,s)}catch(e){m(e instanceof Error?e.message:`Login failed. Please try again.`)}finally{f(!1)}}},className:`space-y-4 rounded-xl border border-border bg-surface p-6 shadow-xl shadow-black/10`,children:[g&&v(`div`,{className:`rounded-md bg-danger/10 border border-danger/20 px-3 py-2 text-xs text-danger`,children:g}),T(`div`,{className:`space-y-1.5`,children:[v(`label`,{className:`text-xs font-medium text-foreground-subtle`,children:`Username`}),v(`input`,{type:`text`,value:a,onChange:e=>o(e.target.value),autoComplete:`username`,required:!0,className:`w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary`})]}),T(`div`,{className:`space-y-1.5`,children:[v(`label`,{className:`text-xs font-medium text-foreground-subtle`,children:`Password`}),T(`div`,{className:`relative`,children:[v(`input`,{type:l?`text`:`password`,value:s,onChange:e=>c(e.target.value),autoComplete:`current-password`,required:!0,className:`w-full rounded-lg border border-border bg-background px-3 py-2.5 pr-10 text-sm text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary`}),v(`button`,{type:`button`,onClick:()=>u(e=>!e),className:`absolute right-2.5 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground`,tabIndex:-1,children:v(l?pF:fF,{className:`h-4 w-4`})})]})]}),T(`button`,{type:`submit`,disabled:d,className:`w-full rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2`,children:[d&&v(mF,{className:`h-4 w-4 animate-spin`}),d?`Logging in...`:`Log in`]})]})]})})}var gF=`camstack_dev_token`,_F=r(null);function vF(){let e=i(_F);if(!e)throw Error(`useDevShell must be used within a DevShell`);return e}function yF(){return typeof window>`u`?null:localStorage.getItem(gF)}function bF({className:e}){return T(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e,children:[v(`circle`,{cx:`12`,cy:`12`,r:`4`}),v(`path`,{d:`M12 2v2`}),v(`path`,{d:`M12 20v2`}),v(`path`,{d:`m4.93 4.93 1.41 1.41`}),v(`path`,{d:`m17.66 17.66 1.41 1.41`}),v(`path`,{d:`M2 12h2`}),v(`path`,{d:`M20 12h2`}),v(`path`,{d:`m6.34 17.66-1.41 1.41`}),v(`path`,{d:`m19.07 4.93-1.41 1.41`})]})}function xF({className:e}){return v(`svg`,{xmlns:`http://www.w3.org/2000/svg`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,className:e,children:v(`path`,{d:`M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z`})})}function SF({children:e,serverUrl:t,title:n,token:r,onLogout:i}){let a=Ye(),s=o(()=>[ee({condition:e=>e.type===`subscription`,true:P({client:N({url:t.replace(/^http/,`ws`)+`/trpc`,connectionParams:()=>({token:r})}),transformer:dF}),false:te({url:`${t}/trpc`,transformer:dF,headers:()=>({authorization:`Bearer ${r}`})})})],[t,r]),l=o(()=>I({links:s}),[s]),u=o(()=>q.createClient({links:s}),[s]),d=o(()=>ke({serverUrl:t,token:r}),[t,r]);c(()=>(d.init().catch(()=>void 0),()=>{d.close()}),[d]);let f=o(()=>new y,[]),p=o(()=>({trpc:l,token:r,logout:i}),[l,r,i]);return v(hf,{system:d,children:v(q.Provider,{client:u,queryClient:f,children:v(C,{client:f,children:v(_F.Provider,{value:p,children:T(`div`,{className:`min-h-screen bg-background text-foreground`,children:[T(`div`,{className:`flex items-center justify-between border-b border-border bg-surface px-4 py-2`,children:[T(`div`,{className:`flex items-center gap-2`,children:[v(`span`,{className:`rounded bg-warning/20 px-2 py-0.5 text-xs font-bold text-warning`,children:`DEV MODE`}),n&&v(`span`,{className:`text-sm font-medium text-foreground`,children:n}),v(`span`,{className:`text-xs text-foreground-subtle`,children:t})]}),T(`div`,{className:`flex items-center gap-2`,children:[T(`button`,{type:`button`,onClick:a.toggleMode,className:`flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,title:`Theme: ${a.mode}`,children:[a.resolvedMode===`dark`?v(bF,{className:`h-3.5 w-3.5`}):v(xF,{className:`h-3.5 w-3.5`}),a.mode===`dark`?`Dark`:a.mode===`light`?`Light`:`System`]}),v(`button`,{type:`button`,onClick:i,className:`rounded-md px-2.5 py-1 text-xs font-medium text-danger hover:bg-danger/10 transition-colors`,children:`Logout`})]})]}),v(`div`,{className:`p-4`,children:e({trpc:l,theme:a})})]})})})})})}function CF({children:e,serverUrl:t=`https://localhost:4443`,title:n}){let[r,i]=h(yF),a=u(async(e,n)=>{let r=await I({links:[te({url:`${t}/trpc`,transformer:dF})]}).auth.login.mutate({username:e,password:n});if(!r.token)throw Error(`No token returned`);localStorage.setItem(gF,r.token),i(r.token)},[t]),o=u(()=>{localStorage.removeItem(gF),i(null)},[]);return r?v(Je,{children:v(SF,{serverUrl:t,title:n,token:r,onLogout:o,children:e})}):v(Je,{children:v(hF,{onLogin:a,serverUrl:t})})}function wF(e,t={}){let{serverUrl:r=`https://localhost:4443`,title:i,rootId:a=`root`}=t,o=document.getElementById(a);if(!o){console.error(`[mountAddonPage] Element #${a} not found`);return}M(o).render(n(CF,{serverUrl:r,title:i,children:({trpc:t,theme:r})=>n(e,{trpc:t,theme:{isDark:r.resolvedMode===`dark`},navigate:e=>{console.log(`[dev] navigate:`,e)}})}))}var TF=hr(`camstack:custom-field-renderers`,{});function EF({renderers:e,children:t}){return v(TF.Provider,{value:e,children:t})}function DF(e){return i(TF)[e]??null}var OF=hr(`camstack:device-context`,null);function kF({deviceId:e,device:t,children:n}){let r={deviceId:e,device:t??null};return v(OF.Provider,{value:r,children:n})}function AF(){return i(OF)?.deviceId??null}function jF(){return i(OF)?.device??null}var MF=hr(`camstack:widget-registry`,null),NF=new Map,PF=new Map,FF=new Set;function IF(e,t){return`${e}::${t}`}function LF(e){if(!e||typeof e!=`object`)return!1;let t=e.default;return typeof t==`object`&&!!t}function RF(e){if(!e||typeof e!=`object`)return typeof e;let t=e,n=Object.getPrototypeOf(t),r=n&&typeof n==`object`?n.constructor?.name:void 0;return{ownKeys:Object.keys(t),allKeys:Object.getOwnPropertyNames(t),proto:typeof r==`string`?r:void 0}}async function zF(e,t,n){let r=IF(e,t),i=NF.get(r);if(i)return i;let a=PF.get(r);if(a)return a;FF.has(e)||(ys(),ds([{name:e,entry:n,type:`module`}],{force:!1}),FF.add(e));let o=us(`${e}/${t.startsWith(`./`)?t.slice(2):t}`).then(i=>{if(!LF(i)){let r=RF(i);throw Error(`Remote ${e} (${n}) does not expose a default record on '${t}'. Got: ${JSON.stringify(r)}`)}let a=i.default;return NF.set(r,a),PF.delete(r),a}).catch(e=>{throw PF.delete(r),e});return PF.set(r,o),o}function BF(e,t){return NF.get(IF(e,t))}var VF=3e4,HF=2e3;function UF({children:e}){let t=b(),n=p(Date.now()),{data:r}=lh(void 0,{staleTime:0,refetchOnMount:`always`,refetchInterval:e=>{let t=e.state.data;return t&&t.length>0||Date.now()-n.current>=VF?!1:HF}});vf(`addon.widget-ready`,()=>{t.invalidateQueries({queryKey:[[`addonWidgets`,`listWidgets`]]})});let[i,a]=h(0),s=o(()=>r??[],[r]);c(()=>{if(s.length===0)return;let e=!1,t=new Set;for(let n of s){let r=IF(n.remote.remoteName,n.remote.exposedModule);if(t.has(r)||(t.add(r),NF.has(r)))continue;let i=n.bundleUrl;zF(n.remote.remoteName,n.remote.exposedModule,i).then(()=>{e||a(e=>e+1)}).catch(e=>{let t=e instanceof Error?e.message:String(e);(typeof globalThis<`u`?globalThis.console:void 0)?.error?.(`[WidgetRegistry] Failed to load widget remote`,{remoteName:n.remote.remoteName,exposedModule:n.remote.exposedModule,entryUrl:i,reason:t})})}return()=>{e=!0}},[s]);let l=o(()=>{let e=new Map,t=new Map;for(let n of s)e.set(`${n.addonId}/${n.stableId}`,n),t.set(n.remote.remoteName,n.bundleUrl);let n=(e,t)=>({widgetId:e,addonId:t.addonId,stableId:t.stableId,tab:t.tab,subTab:t.subTab,label:t.label,order:t.order,kind:t.kind,remote:t.remote,description:t.description,icon:t.icon,bundleUrl:t.bundleUrl,hosts:t.hosts,requires:t.requires,defaultSize:t.defaultSize,allowedSizes:t.allowedSizes,defaultColumns:t.defaultColumns,defaultRows:t.defaultRows});return{resolve:t=>{let n=e.get(t);if(!n)return;let r=BF(n.remote.remoteName,n.remote.exposedModule);if(!r)return null;let i=r[n.remote.componentKey??n.stableId];if(i)return i},metadata:t=>{let r=e.get(t);if(r)return n(t,r)},listAll:()=>{let t=[];for(let[r,i]of e)t.push(n(r,i));return t},entryUrlFor:e=>t.get(e)}},[s,i]);return v(MF.Provider,{value:l,children:e})}function WF(e){return JF().resolve(e)}function GF(e){return JF().metadata(e)}function KF(){return JF().listAll()}function qF(e,t){let n=YF(),r=t??n?.entryUrlFor(e.remoteName),[i,a]=h(0),[s,l]=h(!1);return c(()=>{if(!r||(l(!1),BF(e.remoteName,e.exposedModule)))return;let t=!1;return zF(e.remoteName,e.exposedModule,r).then(()=>{t||a(e=>e+1)}).catch(n=>{let i=n instanceof Error?n.message:String(n);(typeof globalThis<`u`?globalThis.console:void 0)?.error?.(`[WidgetRegistry] Failed to load remote component`,{remoteName:e.remoteName,exposedModule:e.exposedModule,entryUrl:r,reason:i}),t||l(!0)}),()=>{t=!0}},[e.remoteName,e.exposedModule,r]),o(()=>{if(!r||s)return;let t=BF(e.remoteName,e.exposedModule);if(!t)return null;let n=e.componentKey;return n===void 0?Object.values(t)[0]??void 0:t[n]??void 0},[e.remoteName,e.exposedModule,e.componentKey,r,i,s])}function JF(){let e=YF();if(!e)throw Error(`useWidgetRegistry(): no <WidgetRegistryProvider> in tree`);return e}function YF(){return XF(MF)}function XF(e){return i(e)}function ZF({title:e,icon:t,headerRight:n,collapsible:r=!1,defaultOpen:i=!0,bodyClassName:a=`p-3`,children:o}){let[s,c]=h(i),l=!r||s,u=T(E,{children:[T(`span`,{className:`flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-foreground`,children:[t,e]}),r?v(s?Xs:Qs,{className:`h-3.5 w-3.5 text-foreground-subtle`}):n]}),d=`px-4 py-2 flex items-center justify-between ${l?`border-b border-border`:``}`;return T(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[r?v(`button`,{type:`button`,onClick:()=>c(e=>!e),className:`w-full text-left ${d}`,children:u}):v(`div`,{className:d,children:u}),l?v(`div`,{className:a,children:o}):null]})}function QF({label:e,icon:t,children:n,footer:r}){return T(`div`,{className:`rounded-md border border-border/60 bg-background/40 px-3 py-2`,children:[T(`div`,{className:`mb-1 flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-foreground-subtle`,children:[t,e]}),v(`div`,{className:`text-sm font-medium text-foreground`,children:n}),r?v(`div`,{className:`mt-0.5 text-[10px] text-foreground-subtle`,children:r}):null]})}function $F({deviceId:e}){let t=Xf(gf().trpcClient,e),[n,r]=h(null),[i,a]=h(!1);c(()=>{if(!t)return;let e=!1;return(async()=>{try{let n=await t.ptz?.getStatus({});if(e||!n)return;r(n.autofocus)}catch{}})(),()=>{e=!0}},[t]);let o=u(async()=>{if(!(!t?.ptz||n===null)){a(!0);try{let e=!n;await t.ptz.setAutofocus({enabled:e}),r(e)}catch(e){console.error(`ptz.setAutofocus failed`,e)}finally{a(!1)}}},[t,n]);return n===null?null:T(`div`,{className:`flex items-center justify-between border-t border-border/40 mt-2 pt-2`,children:[v(`span`,{className:`text-[10.5px] font-semibold text-foreground`,children:`Autofocus`}),T(`button`,{type:`button`,onClick:()=>void o(),disabled:i,"aria-pressed":n,className:`flex items-center gap-1.5 rounded-md px-2 py-1 text-[10px] font-medium transition-colors ${n?`bg-success/15 text-success hover:bg-success/25`:`bg-surface-elevated/40 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`} disabled:opacity-50`,children:[v(`span`,{className:`h-1.5 w-1.5 rounded-full ${n?`bg-success`:`bg-foreground-subtle/40`}`}),n?`On`:`Off`]})]})}function eI({deviceId:e}){let t=gf(),n=Number.isFinite(e),r=Wp(t.trpcClient,n?e:0,{enabled:n});if(!n)return T(`div`,{className:`flex items-center justify-center h-full text-[11px] text-foreground-subtle italic`,children:[`Device #`,e,` not loaded.`]});let i=r.options?.hasAutofocus===!0;return T(ZF,{title:`PTZ`,icon:v(gl,{className:`h-3.5 w-3.5 text-foreground-subtle`}),bodyClassName:`p-3 flex flex-col overflow-y-auto`,children:[v(Kp,{controls:r,mode:`panel`}),i&&v($F,{deviceId:e})]})}var tI=15;function nI(e){return e.status===`replace`||e.level!==null&&e.level<=tI}function rI(e){try{return new Date(e).toLocaleDateString(void 0,{year:`numeric`,month:`short`,day:`numeric`})}catch{return``}}function iI({item:e,busy:t,canReset:n,onReset:r}){let i=nI(e),a=i?`bg-warning`:`bg-success`;return T(`div`,{className:`flex flex-col gap-1.5 rounded-md border p-3 ${i?`border-warning/40 bg-warning/5`:`border-border/40 bg-surface-elevated/30`}`,children:[T(`div`,{className:`flex items-center justify-between gap-2`,children:[v(`span`,{className:`text-xs font-semibold ${i?`text-warning`:`text-foreground`}`,children:e.label}),e.resettable&&v(`button`,{type:`button`,onClick:()=>r(e.key),disabled:t||!n,className:`rounded-md border border-border bg-surface px-2 py-0.5 text-[10px] font-medium text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors`,children:`Replaced`})]}),e.level===null?e.status===null?v(`span`,{className:`text-[10px] text-foreground-subtle`,children:`—`}):v(`span`,{className:`inline-flex w-fit items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium ${e.status===`replace`?`bg-warning/15 text-warning`:`bg-success/15 text-success`}`,children:e.status===`replace`?`Replace`:`OK`}):T(`div`,{className:`flex items-center gap-2`,children:[v(`div`,{className:`h-1.5 flex-1 overflow-hidden rounded-full bg-surface-elevated/60`,children:v(`div`,{className:`h-full rounded-full ${a} transition-all`,style:{width:`${Math.max(0,Math.min(100,e.level))}%`}})}),T(`span`,{className:`text-[10px] font-medium tabular-nums text-foreground-subtle`,children:[Math.round(e.level),`%`]})]}),e.lastResetAt!==null&&T(`span`,{className:`text-[10px] text-foreground-subtle`,children:[`Replaced `,rI(e.lastResetAt)]})]})}function aI({deviceId:e}){let t=gf(),n=Number.isFinite(e),{cap:r,slice:i,available:a}=$f({trpc:t.trpcClient,deviceId:n?e:null,cap:e=>e.consumables,slice:e=>e.state.consumables}),[o,s]=h(null),c=u(async e=>{if(r){s(e);try{await r.reset({key:e})}catch(e){console.error(`consumables.reset failed`,e)}finally{s(null)}}},[r]),l=i?.items??[];return v(ZF,{title:`Consumables`,icon:v(zc,{className:`h-3.5 w-3.5 text-foreground-subtle`}),bodyClassName:`p-3 overflow-y-auto`,children:l.length===0?v(`p`,{className:`text-[11px] text-foreground-subtle italic leading-relaxed`,children:`No consumables reported.`}):v(`div`,{className:`flex flex-col gap-2`,children:l.map(e=>v(iI,{item:e,busy:o===e.key,canReset:a,onReset:e=>void c(e)},e.key))})})}function oI(e){let t=b(),n=hw({deviceId:e??0},{enabled:e!==null&&Number.isFinite(e),refetchInterval:5e3,retry:1}),r=gw({onSuccess:()=>{t.invalidateQueries({queryKey:[[`ptzAutotrack`]]})}}),i=vw({onSuccess:()=>{t.invalidateQueries({queryKey:[[`ptzAutotrack`]]})}}),a=u(async t=>{e!==null&&await r.mutateAsync({deviceId:e,enabled:t})},[e,r]),o=u(async t=>{e!==null&&await i.mutateAsync({deviceId:e,settings:t})},[e,i]),s=n.error?n.error.message:r.error?r.error.message:i.error?i.error.message:null;return{status:n.data??null,isLoading:n.isLoading,isPending:r.isPending||i.isPending,error:s,setEnabled:a,setSettings:o}}function sI({deviceId:e}){let{status:t,isLoading:n,isPending:r,error:i,setEnabled:a,setSettings:o}=oI(Number.isFinite(e)?e:null),[s,l]=h({targetType:``,stopDelaySeconds:30,disappearDelaySeconds:15}),[u,d]=h(!1);c(()=>{if(u)return;let e=t?.currentSettings;e&&l({targetType:e.targetType,stopDelaySeconds:e.stopDelaySeconds,disappearDelaySeconds:e.disappearDelaySeconds})},[t,u]);let f=v(bc,{className:`h-3.5 w-3.5 text-foreground-subtle`});return n&&!t?v(ZF,{title:`Autotrack`,icon:f,children:T(`div`,{className:`flex items-center gap-2 text-[10.5px] text-foreground-subtle`,children:[v(el,{className:`h-3 w-3 animate-spin`}),`Loading autotrack…`]})}):T(ZF,{title:`Autotrack`,icon:f,headerRight:T(`button`,{type:`button`,onClick:()=>{a(!(t?.enabled??!1))},disabled:r,className:`flex items-center gap-1.5 rounded-md px-2 py-1 text-[10px] font-medium transition-colors ${t?.enabled?`bg-success/15 text-success hover:bg-success/25`:`bg-surface-elevated/40 text-foreground-subtle hover:bg-surface-hover hover:text-foreground`} disabled:opacity-50`,"aria-pressed":t?.enabled??!1,children:[v(`span`,{className:`h-1.5 w-1.5 rounded-full ${t?.enabled?`bg-success`:`bg-foreground-subtle/40`}`}),t?.enabled?`Enabled`:`Disabled`]}),bodyClassName:`p-3 space-y-2`,children:[i&&T(`div`,{className:`flex items-start gap-1.5 rounded-md border border-danger/30 bg-danger/5 px-2 py-1.5 text-[10px] text-danger`,children:[v(nc,{className:`h-3 w-3 flex-shrink-0 mt-0.5`}),v(`span`,{className:`leading-snug break-words`,children:i})]}),T(`div`,{className:`grid grid-cols-2 gap-2 px-2`,children:[(t?.supportedTargetTypes?.length??0)>0&&T(`label`,{className:`col-span-2 flex flex-col gap-1`,children:[v(`span`,{className:`text-[10px] font-medium text-foreground-subtle`,children:`Target type`}),v(`select`,{value:s.targetType,onFocus:()=>d(!0),onChange:e=>l(t=>({...t,targetType:e.target.value})),onBlur:()=>{d(!1);let e=t?.currentSettings?.targetType??``;s.targetType!==e&&o({targetType:s.targetType})},disabled:r,className:`rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground focus:border-primary focus:outline-none disabled:opacity-50`,children:(t?.supportedTargetTypes??[]).map(e=>v(`option`,{value:e.value,children:e.label},e.value))})]}),T(`label`,{className:`flex flex-col gap-1`,children:[v(`span`,{className:`text-[10px] font-medium text-foreground-subtle`,children:`Stop delay (s)`}),v(`input`,{type:`number`,min:0,max:300,value:s.stopDelaySeconds,onFocus:()=>d(!0),onChange:e=>l(t=>({...t,stopDelaySeconds:Number(e.target.value)||0})),onBlur:()=>{d(!1);let e=t?.currentSettings?.stopDelaySeconds??30;s.stopDelaySeconds!==e&&o({stopDelaySeconds:s.stopDelaySeconds})},disabled:r,className:`rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground focus:border-primary focus:outline-none disabled:opacity-50`})]}),T(`label`,{className:`flex flex-col gap-1`,children:[v(`span`,{className:`text-[10px] font-medium text-foreground-subtle`,children:`Disappear delay (s)`}),v(`input`,{type:`number`,min:0,max:300,value:s.disappearDelaySeconds,onFocus:()=>d(!0),onChange:e=>l(t=>({...t,disappearDelaySeconds:Number(e.target.value)||0})),onBlur:()=>{d(!1);let e=t?.currentSettings?.disappearDelaySeconds??15;s.disappearDelaySeconds!==e&&o({disappearDelaySeconds:s.disappearDelaySeconds})},disabled:r,className:`rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground focus:border-primary focus:outline-none disabled:opacity-50`})]})]}),v(`p`,{className:`px-2 text-[9.5px] text-foreground-subtle leading-snug italic`,children:`Settings save on blur. Vendor support varies — Reolink honours all three; Hikvision honours target type + stop delay only (disappear delay is accepted but ignored at firmware push).`})]})}var cI=hr(`camstack:player-overlays-state`,null),lI=hr(`camstack:player-overlays-actions`,null);function uI({children:e}){let[t,n]=h(()=>new Map),[r,i]=h(()=>new Map),a=u(e=>{n(t=>{let n=new Map(t);return n.set(e.id,e),n})},[]),s=u(e=>{n(t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n})},[]),c=u(e=>{i(t=>{let n=new Map(t);return n.set(e.id,e),n})},[]),l=u(e=>{i(t=>{if(!t.has(e))return t;let n=new Map(t);return n.delete(e),n})},[]),d=o(()=>({layers:t,buttons:r}),[t,r]),f=o(()=>({setLayer:a,removeLayer:s,setButton:c,removeButton:l}),[a,s,c,l]);return v(cI.Provider,{value:d,children:v(lI.Provider,{value:f,children:e})})}function dI(){let e=i(cI);return o(()=>e?[...e.layers.values()].toSorted((e,t)=>e.order-t.order):[],[e])}function fI(){let e=i(cI);return o(()=>e?[...e.buttons.values()].toSorted((e,t)=>e.order-t.order):[],[e])}function pI(e){let t=i(lI);c(()=>{if(!(!t||!e))return t.setLayer(e),()=>t.removeLayer(e.id)},[t,e])}function mI(e){let t=i(lI);c(()=>{if(!(!t||!e))return t.setButton(e),()=>t.removeButton(e.id)},[t,e])}var hI={rect:`#ef4444`,polygon:`#3b82f6`,grid:`#6366f1`,line:`#f59e0b`},gI=`33`,_I=`66`,vI=`#6366f1`,yI=3,bI=2,xI=12,SI=16,CI=9;function wI(e,t,n){return{x:e.x*t,y:e.y*n}}function TI(e,t,n){return{x:e.x/t,y:e.y/n}}function EI(e,t,n){return e.flatMap(e=>[e.x*t,e.y*n])}function DI(e){return!Number.isFinite(e)||e<0?0:e>1?1:e}function OI(e){return e.color??hI[e.shape.kind]}function kI(e,t){let n=e[t],r=e[(t+1)%e.length];if(!n||!r)return[...e];let i={x:(n.x+r.x)/2,y:(n.y+r.y)/2};return[...e.slice(0,t+1),i,...e.slice(t+1)]}function AI(e,t){return e.length===t.length?e.every((e,n)=>{let r=t[n];return Math.abs(e.x-r.x)<1e-6&&Math.abs(e.y-r.y)<1e-6}):!1}function jI(e){return e.kind===`polygon`||e.kind===`line`}function MI({items:e,selectedId:t,onSelect:n,onShapeChange:r,onDrawComplete:i,drawingKind:a,supportedShapes:o,transparent:s=!1,backdrop:l,polygonVertices:d,grid:f}){let m=p(null),[g,_]=h({w:800,h:450}),[y,b]=h([]),[x,S]=h(null),[C,w]=h(null),[E,D]=h(null),O=a!==null&&o.includes(a);c(()=>{if(!E)return;let t=e.find(e=>e.id===E.itemId);if(!t||!jI(t.shape)){D(null);return}AI(t.shape.points,E.points)&&D(null)},[e,E]),c(()=>{let e=m.current;if(!e)return;let t=new ResizeObserver(e=>{let t=e[0];if(!t)return;let{width:n,height:r}=t.contentRect;_(s?{w:n,h:r}:{w:n,h:n*9/16})});return t.observe(e),()=>t.disconnect()},[s]),c(()=>{!O&&x!==null&&S(null)},[O,x]);let k=u(e=>{i(e),b([])},[i]),A=u(e=>{if(!O||a===null){n(null);return}let t=e.target.getStage();if(!t)return;let r=t.getPointerPosition();if(!r)return;let i=TI(r,g.w,g.h);if(a===`rect`){let e=DI(i.x),t=DI(i.y);k({kind:`rect`,x:e,y:t,width:Math.min(.2,1-e),height:Math.min(.2,1-t)});return}if(a===`grid`){let e=f?.width??SI,t=f?.height??CI;k({kind:`grid`,gridWidth:e,gridHeight:t,cells:Array.from({length:e*t},()=>!1)});return}if(a===`line`){if(y.length===0){b([i]);return}k({kind:`line`,points:[...y,i]});return}if(a===`polygon`){if(y.length===0){b([i]);return}if(y.length>=yI){let e=wI(y[0],g.w,g.h);if(Math.hypot(r.x-e.x,r.y-e.y)<xI){k({kind:`polygon`,points:y});return}}b(e=>[...e,i])}},[O,a,y,g,f,k,n]),j=u(e=>{!O||a!==`polygon`||y.length<yI||(e.cancelBubble=!0,k({kind:`polygon`,points:y}))},[O,a,y,k]),M=p(null),N=p(null);c(()=>()=>{M.current!==null&&cancelAnimationFrame(M.current)},[]);let P=u(e=>{if(!O)return;let t=e.target.getStage();t&&(N.current=t.getPointerPosition()??null,M.current===null&&(M.current=requestAnimationFrame(()=>{M.current=null,S(N.current)})))},[O]),ee=p(!1),F=p(!0),te=p(new Set),I=u((e,t,n,i)=>{let a=t.gridWidth*t.gridHeight;if(n<0||n>=a||t.cells[n]===i)return;let o=[...t.cells];for(;o.length<a;)o.push(!1);o.length=a,o[n]=i,r(e,{...t,cells:o})},[r]),L=[];if(!s){for(let e=1;e<SI;e++){let t=g.w/SI*e;L.push(v(ie,{points:[t,0,t,g.h],stroke:`#ffffff`,strokeWidth:.5,opacity:.08},`gv-${e}`))}for(let e=1;e<CI;e++){let t=g.h/CI*e;L.push(v(ie,{points:[0,t,g.w,t],stroke:`#ffffff`,strokeWidth:.5,opacity:.08},`gh-${e}`))}}return T(`div`,{ref:m,className:s?`absolute inset-0`:`relative w-full bg-zinc-900 rounded-lg overflow-hidden`,style:{cursor:O?`crosshair`:`default`},children:[l&&!s?v(`div`,{className:`absolute inset-0 pointer-events-none [&>*]:w-full [&>*]:h-full [&>img]:object-cover [&>video]:object-cover`,style:{width:g.w,height:g.h},children:l}):null,T(re,{width:g.w,height:g.h,onClick:A,onDblClick:j,onMouseMove:P,children:[T(ue,{listening:!1,children:[v(ie,{points:[0,0,g.w,0,g.w,g.h,0,g.h,0,0],stroke:`transparent`,strokeWidth:0}),L]}),v(ue,{children:e.map(e=>{let i=e.id===t,a=e.enabled===!1,o=OI(e),s=i&&!O&&!a;if(e.shape.kind===`rect`)return v(FI,{item:e,shape:e.shape,color:o,selected:i,dimmed:a,editable:s,isDrawing:O,size:g,onSelect:n,onShapeChange:r},e.id);if(e.shape.kind===`grid`)return v(II,{item:e,shape:e.shape,color:o,dimmed:a,editable:s,size:g,onSelect:n,paintingRef:ee,paintValueRef:F,paintedRef:te,paintCell:I},e.id);let c=e.shape.kind===`line`,l=c?bI:Math.max(yI,d?.min??yI),u=c?bI:d?.max,f=E&&E.itemId===e.id?E.points:e.shape.points;return v(LI,{item:e,shape:e.shape,color:o,selected:i,dimmed:a,editable:s,isLine:c,isDrawing:O,size:g,effectivePoints:f,minVertices:l,maxVertices:u,isDragging:C===e.id,onSelect:n,onShapeChange:r,setDragOverride:D,setDraggingItemId:w},e.id)})}),v(ue,{listening:!1,children:O&&y.length>0&&T(ae,{children:[a===`polygon`&&y.length>=2&&v(ie,{points:EI(y,g.w,g.h),stroke:vI,strokeWidth:1.5,dash:[6,3],opacity:.8}),a===`line`&&y.length===1&&x&&v(ie,{points:[y[0].x*g.w,y[0].y*g.h,x.x,x.y],stroke:hI.line,strokeWidth:1.5,dash:[6,3],opacity:.7}),a===`polygon`&&x&&y.length>=1&&v(ie,{points:[y[y.length-1].x*g.w,y[y.length-1].y*g.h,x.x,x.y],stroke:vI,strokeWidth:1,dash:[4,4],opacity:.5}),y.map((e,t)=>{let n=wI(e,g.w,g.h),r=t===0&&a===`polygon`&&y.length>=yI;return v(le,{x:n.x,y:n.y,radius:r?7:4,fill:r?vI:`#ffffff`,stroke:vI,strokeWidth:1.5,opacity:.9},t)})]})})]}),O?v(`div`,{className:`px-3 py-1.5 bg-zinc-800/80 text-[11px] text-zinc-400 border-t border-zinc-700`,children:a===`line`?`Click to set the start point, click again to complete the line`:a===`rect`?`Click to drop a rectangle, then drag the corner to resize`:a===`grid`?`Click to add the grid, then paint cells`:y.length<yI?`Click to add points (min 3). Double-click or click the first point to close.`:`Continue adding points. Double-click or click the first point to close.`}):null]})}var NI=.02;function PI(e,t){return Math.abs(e.x-t.x)<1e-6&&Math.abs(e.y-t.y)<1e-6&&Math.abs(e.width-t.width)<1e-6&&Math.abs(e.height-t.height)<1e-6}function FI({item:e,shape:t,color:n,selected:r,dimmed:i,editable:a,isDrawing:o,size:s,onSelect:l,onShapeChange:u}){let[d,f]=h(null),p={x:t.x,y:t.y,width:t.width,height:t.height};c(()=>{d&&PI(p,d)&&f(null)},[t.x,t.y,t.width,t.height,d]);let m=d??p,g=m.x*s.w,_=m.y*s.h,y=m.width*s.w,b=m.height*s.h,x=i?.35:r?1:.85,S=t=>{f(t),u(e.id,{kind:`rect`,x:t.x,y:t.y,width:t.width,height:t.height})};return v(ae,{onClick:t=>{t.cancelBubble=!0,o||l(e.id)},children:T(ae,{draggable:a,dragBoundFunc:a?e=>({x:Math.max(-g,Math.min(s.w-(g+y),e.x)),y:Math.max(-_,Math.min(s.h-(_+b),e.y))}):void 0,onDragEnd:a?e=>{let t=e.target,n=t.x()/s.w,r=t.y()/s.h;if(t.position({x:0,y:0}),n===0&&r===0)return;let i=Math.min(Math.max(0,m.x+n),Math.max(0,1-m.width)),a=Math.min(Math.max(0,m.y+r),Math.max(0,1-m.height));S({...m,x:i,y:a})}:void 0,onMouseEnter:e=>{if(!a)return;let t=e.target.getStage();t&&(t.container().style.cursor=`move`)},onMouseLeave:e=>{if(!a)return;let t=e.target.getStage();t&&(t.container().style.cursor=o?`crosshair`:`default`)},children:[v(se,{x:g,y:_,width:y,height:b,fill:n+(r?_I:gI),stroke:n,strokeWidth:r?2.5:1.5,opacity:x}),e.label?v(oe,{x:g,y:_-16,text:e.label,fontSize:12,fill:n,stroke:`#000000`,strokeWidth:3,fillAfterStrokeEnabled:!0,fontStyle:`bold`,listening:!1}):null,a?v(le,{x:g+y,y:_+b,radius:6,fill:n,stroke:`#ffffff`,strokeWidth:1.5,draggable:!0,dragBoundFunc:e=>({x:Math.min(s.w,Math.max(g,e.x)),y:Math.min(s.h,Math.max(_,e.y))}),onDragStart:e=>{e.cancelBubble=!0},onDragMove:e=>{let t=e.target,n=DI(t.x()/s.w-m.x),r=DI(t.y()/s.h-m.y);f({...m,width:Math.max(NI,Math.min(n,1-m.x)),height:Math.max(NI,Math.min(r,1-m.y))})},onDragEnd:e=>{let t=e.target,n=DI(t.x()/s.w-m.x),r=DI(t.y()/s.h-m.y);S({...m,width:Math.max(NI,Math.min(n,1-m.x)),height:Math.max(NI,Math.min(r,1-m.y))})},onMouseEnter:e=>{let t=e.target.getStage();t&&(t.container().style.cursor=`nwse-resize`)},onMouseLeave:e=>{let t=e.target.getStage();t&&(t.container().style.cursor=`default`)}}):null]})})}function II({item:e,shape:t,color:n,dimmed:r,editable:i,size:a,onSelect:o,paintingRef:s,paintValueRef:c,paintedRef:l,paintCell:u}){let{gridWidth:d,gridHeight:f,cells:p}=t,m=a.w/d,h=a.h/f,g=d*f,_=r?.3:1,y=n=>{if(!i){o(e.id);return}let r=p[n]!==!0;s.current=!0,c.current=r,l.current=new Set([n]),u(e.id,t,n,r)},b=n=>{!s.current||!i||l.current.has(n)||(l.current.add(n),u(e.id,t,n,c.current))},x=()=>{s.current&&(s.current=!1,l.current=new Set)};return v(ae,{opacity:_,onMouseUp:x,onMouseLeave:x,children:Array.from({length:g},(e,t)=>{let r=t%d,i=Math.floor(t/d),a=p[t]===!0;return v(se,{x:r*m,y:i*h,width:m,height:h,fill:a?n+_I:`#ffffff10`,stroke:a?n:`#ffffff40`,strokeWidth:.5,onMouseDown:e=>{e.cancelBubble=!0,y(t)},onMouseEnter:()=>b(t)},t)})})}function LI({item:e,shape:t,color:n,selected:r,dimmed:i,editable:a,isLine:o,isDrawing:s,size:c,effectivePoints:l,minVertices:u,maxVertices:d,isDragging:f,onSelect:p,onShapeChange:m,setDragOverride:h,setDraggingItemId:g}){let _=EI(l,c.w,c.h),y=i?.35:r?1:o?.8:.85,b=e=>o?{kind:`line`,points:[...e]}:{kind:`polygon`,points:[...e]},x=l.map(e=>e.x*c.w),S=l.map(e=>e.y*c.h),C=x.length>0?Math.min(...x):0,w=x.length>0?Math.max(...x):0,E=S.length>0?Math.min(...S):0,D=S.length>0?Math.max(...S):0,O=e=>({x:Math.max(-C,Math.min(c.w-w,e.x)),y:Math.max(-E,Math.min(c.h-D,e.y))}),k=n=>{let r=n.target,i=r.x()/c.w,a=r.y()/c.h;if(r.position({x:0,y:0}),g(null),i===0&&a===0)return;let o=t.points.map(e=>({x:e.x+i,y:e.y+a}));h({itemId:e.id,points:o}),m(e.id,b(o))},A=!o&&l.length>u,j=!o&&(d===void 0||l.length<d);return T(ae,{onClick:t=>{t.cancelBubble=!0,s||p(e.id)},children:[T(ae,{draggable:a,dragBoundFunc:a?O:void 0,onDragStart:a?()=>g(e.id):void 0,onDragEnd:a?k:void 0,onMouseEnter:e=>{if(!a)return;let t=e.target.getStage();t&&(t.container().style.cursor=`move`)},onMouseLeave:e=>{if(!a)return;let t=e.target.getStage();t&&(t.container().style.cursor=s?`crosshair`:`default`)},children:[o?v(ce,{points:_,stroke:n,strokeWidth:r?3:2,fill:n,pointerLength:10,pointerWidth:8,opacity:y}):v(ie,{points:_,closed:!0,fill:n+(r?_I:gI),stroke:n,strokeWidth:r?2.5:1.5,opacity:y}),e.label&&l.length>0?(()=>{let t=wI({x:l.reduce((e,t)=>e+t.x,0)/l.length,y:l.reduce((e,t)=>e+t.y,0)/l.length},c.w,c.h),r=Math.max(40,e.label.length*11*.62);return v(oe,{x:t.x-r/2,y:t.y-7,width:r,align:`center`,text:e.label,fontSize:12,fill:n,stroke:`#000000`,strokeWidth:3,fillAfterStrokeEnabled:!0,fontStyle:`bold`,listening:!1})})():null]}),a&&!f&&l.map((r,i)=>{let a=wI(r,c.w,c.h);return v(le,{x:a.x,y:a.y,radius:5,fill:n,stroke:`#ffffff`,strokeWidth:1.5,draggable:!0,onDragMove:n=>{let r=TI({x:n.target.x(),y:n.target.y()},c.w,c.h);h(n=>{let a=n&&n.itemId===e.id?n.points:t.points;return{itemId:e.id,points:a.map((e,t)=>t===i?r:e)}})},onDragEnd:n=>{let r=TI({x:n.target.x(),y:n.target.y()},c.w,c.h),a=t.points.map((e,t)=>t===i?r:e);h({itemId:e.id,points:a}),m(e.id,b(a))},onContextMenu:n=>{n.evt.preventDefault(),n.cancelBubble=!0,A&&m(e.id,b(t.points.filter((e,t)=>t!==i)))}},`pt-${i}`)}),a&&!f&&j&&l.length>=2&&l.map((r,i)=>{let a=l[(i+1)%l.length],o=wI({x:(r.x+a.x)/2,y:(r.y+a.y)/2},c.w,c.h);return v(le,{x:o.x,y:o.y,radius:4,fill:`#ffffff`,stroke:n,strokeWidth:1.5,opacity:.6,onMouseEnter:e=>{let t=e.target;t.to({radius:6,opacity:1,duration:.1});let n=t.getStage();n&&(n.container().style.cursor=`copy`)},onMouseLeave:e=>{let t=e.target;t.to({radius:4,opacity:.6,duration:.1});let n=t.getStage();n&&(n.container().style.cursor=s?`crosshair`:`default`)},onClick:n=>{n.cancelBubble=!0,m(e.id,b(kI(t.points,i)))}},`mid-${i}`)})]})}var RI=t(MI),zI=110,BI=`motion-zones`,VI=0,HI=[1,2,3],UI=1,WI=`rounded-md border border-border bg-surface px-2 py-1 text-[11px] font-medium text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors`,GI=`rounded-md border border-primary/50 bg-primary/15 px-2.5 py-1 text-[11px] font-medium text-primary hover:bg-primary/25 disabled:opacity-40 transition-colors`;function KI(e,t,n){let r=t*n,i=Array(r);for(let t=0;t<r;t+=1)i[t]=e[t]===!0;return i}function qI(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}function JI(e,t){return Math.ceil(e/t)}function YI(e,t,n){return Math.min(n-1,Math.floor((e+.5)/t*n))}function XI(e,t,n,r){let i=JI(t,r),a=JI(n,r),o=Array(i*a).fill(!1);for(let r=0;r<n;r+=1){let s=YI(r,n,a);for(let n=0;n<t;n+=1)e[r*t+n]===!0&&(o[s*i+YI(n,t,i)]=!0)}return o}function ZI(e,t,n,r){let i=JI(t,r),a=JI(n,r),o=Array(t*n).fill(!1);for(let r=0;r<n;r+=1){let s=YI(r,n,a);for(let n=0;n<t;n+=1)o[r*t+n]=e[s*i+YI(n,t,i)]===!0}return o}function QI({deviceId:e}){let t=Xf(gf().trpcClient,e),[n,r]=h(null),[i,a]=h(!1),[s,l]=h(null),[d,f]=h(null),[m,g]=h(UI),[_,y]=h(!1),[b,x]=h(!1),S=p(!1);c(()=>{if(!t)return;let e=!1;return S.current=!1,r(null),a(!1),l(null),f(null),g(UI),x(!1),(async()=>{try{let n=await t.motionZones?.getOptions({});if(e)return;if(!n)throw Error(`device proxy not ready`);if(r(n),S.current)return;let i=await t.motionZones?.getStatus({});if(e)return;if(!i)throw Error(`device proxy not ready`);S.current=!0;let a=i.regions.find(e=>e.shape.kind===`grid`),o=KI(a?a.shape.cells:[],n.grid.width,n.grid.height);f(o),l(XI(o,n.grid.width,n.grid.height,UI))}catch(t){if(e)return;Rn(t)?a(!0):console.error(`Motion Zones load failed`,t)}})(),()=>{e=!0}},[t]);let C=n?n.grid.width:0,w=n?n.grid.height:0,D=JI(C,m),O=JI(w,m),k=o(()=>s&&n?ZI(s,C,w,m):null,[s,n,C,w,m]),A=o(()=>k!==null&&d!==null&&!qI(k,d),[k,d]),j=o(()=>k?k.reduce((e,t)=>t?e+1:e,0):0,[k]),M=C*w,N=D*O,P=u(e=>{N>0&&l(Array(N).fill(e))},[N]),ee=u(()=>{l(e=>e&&e.map(e=>!e))},[]),F=u(()=>{d&&n&&l(XI(d,C,w,m))},[d,n,C,w,m]),te=u(e=>{e===m||!n||l(t=>{if(!t)return g(e),t;let n=XI(ZI(t,C,w,m),C,w,e);return g(e),n})},[m,n,C,w]),I=o(()=>n&&s?[{id:VI,shape:{kind:`grid`,gridWidth:D,gridHeight:O,cells:[...s]}}]:[],[n,s,D,O]),L=u((e,t)=>{t.kind===`grid`&&l(t.cells)},[]),ne=u(async()=>{if(!(!t||!s||!n)){y(!0);try{let e=ZI(s,n.grid.width,n.grid.height,m),r={kind:`grid`,gridWidth:n.grid.width,gridHeight:n.grid.height,cells:e};await t.motionZones?.setZone({patch:{regions:[{id:VI,enabled:!0,shape:r}]}});let i=await t.motionZones?.getStatus({});if(i){let e=i.regions.find(e=>e.shape.kind===`grid`),t=KI(e?e.shape.cells:[],n.grid.width,n.grid.height);f(t),l(XI(t,n.grid.width,n.grid.height,m))}}catch(e){console.error(`Motion Zones save failed`,e)}finally{y(!1)}}},[t,s,n,m]);return pI(o(()=>b&&!i&&n&&s?{id:BI,order:zI,node:v(RI,{transparent:!0,items:I,supportedShapes:[`grid`],grid:{width:D,height:O},selectedId:VI,onSelect:()=>{},onShapeChange:L,onDrawComplete:()=>{},drawingKind:null})}:null,[b,i,n,s,I,L,D,O])),t?v(ZF,{title:`Motion Zones`,icon:v(Bc,{className:`h-3.5 w-3.5 text-foreground-subtle`}),children:v(`div`,{className:`flex flex-col gap-3`,children:i?v(`p`,{className:`${Zn} leading-relaxed`,children:`This camera doesn't expose an on-board motion zones grid.`}):!i&&n!==null&&s!==null?T(E,{children:[T(`p`,{className:`${Zn} leading-relaxed`,children:[`Toggle `,v(`strong`,{className:`text-foreground`,children:`Edit grid`}),` to paint the region directly on the live frame, then `,v(`strong`,{className:`text-foreground`,children:`Save`}),` to push the mask to the camera. Pick a bigger`,` `,v(`strong`,{className:`text-foreground`,children:`Cell size`}),` for quicker, broad-stroke painting — it's resampled to the camera's native `,n.grid.width,`×`,n.grid.height,` grid on save (×1 is the finest).`]}),T(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[v(`button`,{type:`button`,onClick:()=>x(e=>!e),disabled:_,"aria-pressed":b,className:b?GI:WI,children:b?`Done editing`:`Edit grid`}),v(`button`,{type:`button`,onClick:()=>P(!0),disabled:_,className:WI,children:`All on`}),v(`button`,{type:`button`,onClick:()=>P(!1),disabled:_,className:WI,children:`All off`}),v(`button`,{type:`button`,onClick:ee,disabled:_,className:WI,children:`Invert`}),T(`div`,{className:`flex items-center gap-1 ml-1`,role:`group`,"aria-label":`Cell size`,children:[v(`span`,{className:`${Zn} mr-0.5`,children:`Cell size`}),HI.map(e=>T(`button`,{type:`button`,onClick:()=>te(e),disabled:_,"aria-pressed":m===e,title:e===1?`Camera grid ${C}×${w} (finest)`:`${JI(C,e)}×${JI(w,e)} painting grid · cells ×${e} bigger`,className:m===e?GI:WI,children:[`×`,e]},e))]}),T(`span`,{className:`${Zn} ml-1 tabular-nums`,children:[j,` / `,M,` cells · `,n.grid.width,`×`,n.grid.height,m===1?``:` · paint ${D}×${O}`]}),v(`span`,{className:`flex-1`}),v(`button`,{type:`button`,onClick:F,disabled:_||!A,className:`rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors`,children:`Revert`}),v(`button`,{type:`button`,onClick:()=>void ne(),disabled:_||!A,className:GI,children:_?`Saving…`:`Save`})]})]}):v(`p`,{className:`${Zn} leading-relaxed`,children:`Loading the camera's grid…`})})}):null}var $I=120,eL=`privacy-mask`,tL=`rounded-md border border-border bg-surface px-2 py-1 text-[11px] font-medium text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors`,nL=`rounded-md border border-primary/50 bg-primary/15 px-2.5 py-1 text-[11px] font-medium text-primary hover:bg-primary/25 disabled:opacity-40 transition-colors`;function rL(e){return e.kind===`rect`||e.kind===`polygon`?e:null}function iL(e){let t=new Set(e.map(e=>e.id)),n=0;for(;t.has(n);)n+=1;return n}function aL(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(JSON.stringify(e[n])!==JSON.stringify(t[n]))return!1;return!0}function oL({deviceId:e}){let t=Xf(gf().trpcClient,e),[n,r]=h(null),[i,a]=h(!1),[s,l]=h(null),[d,f]=h(null),[m,g]=h(!1),[_,y]=h(!1),[b,x]=h(null),[S,C]=h(null),w=p(!1);c(()=>{if(!t)return;let e=!1;return w.current=!1,r(null),a(!1),l(null),f(null),y(!1),x(null),C(null),(async()=>{try{let n=await t.privacyMask?.getOptions({});if(e)return;if(!n)throw Error(`device proxy not ready`);if(r(n),w.current)return;let i=await t.privacyMask?.getStatus({});if(e)return;if(!i)throw Error(`device proxy not ready`);w.current=!0;let a={enabled:i.enabled,regions:i.regions};f(a),l(a)}catch(t){if(e)return;Rn(t)?a(!0):console.error(`Privacy Mask load failed`,t)}})(),()=>{e=!0}},[t]);let D=o(()=>s!==null&&d!==null&&(s.enabled!==d.enabled||!aL(s.regions,d.regions)),[s,d]),O=s?s.regions.length:0,k=n?n.maxRegions:0,A=p(0);c(()=>{A.current=k},[k]);let j=k>0&&O>=k,M=u(()=>{l(e=>e&&{...e,enabled:!e.enabled})},[]),N=u(e=>{x(typeof e==`number`?e:null)},[]),P=o(()=>s?s.regions.map(e=>({id:e.id,shape:e.shape,enabled:e.enabled,label:`Zone ${String(e.id)}`})):[],[s]),ee=u((e,t)=>{let n=rL(t);n&&l(t=>t&&{...t,regions:t.regions.map(t=>t.id===e?{...t,shape:n}:t)})},[]),F=u(e=>{let t=rL(e);t&&(C(null),l(e=>{if(!e)return e;let n=A.current;if(n>0&&e.regions.length>=n)return e;let r=iL(e.regions),i={id:r,enabled:!0,shape:t};return x(r),{...e,regions:[...e.regions,i]}}))},[]),te=u(e=>{y(!0),x(null),C(e)},[]),I=u(e=>{y(!0),C(null),x(e)},[]),L=u(e=>{x(t=>t===e?null:t),l(t=>t&&{...t,regions:t.regions.filter(t=>t.id!==e)})},[]),ne=u(()=>{C(null),x(null),d&&l({enabled:d.enabled,regions:d.regions})},[d]),R=u(async()=>{if(!(!t||!s)){g(!0);try{await t.privacyMask?.setMask({patch:{enabled:s.enabled,regions:[...s.regions]}});let e=await t.privacyMask?.getStatus({});if(e){let t={enabled:e.enabled,regions:e.regions};f(t),l(t)}}catch(e){console.error(`Privacy Mask save failed`,e)}finally{g(!1)}}},[t,s]),re=u(()=>{y(e=>(e&&(C(null),x(null)),!e))},[]),ie=n?.supportedShapes??[];pI(o(()=>_&&!i&&n&&s?{id:eL,order:$I,node:v(RI,{transparent:!0,items:P,supportedShapes:ie,polygonVertices:n.polygonVertices,selectedId:b,onSelect:N,onShapeChange:ee,onDrawComplete:F,drawingKind:S})}:null,[_,i,n,s,P,ie,b,N,ee,F,S]));let ae=n?.supportedShapes.includes(`rect`)??!1,z=n?.supportedShapes.includes(`polygon`)??!1,oe=n!==null&&(n.maxRegions<=0||n.supportedShapes.length===0);return t?v(ZF,{title:`Privacy Mask`,icon:v(kc,{className:`h-3.5 w-3.5 text-foreground-subtle`}),children:v(`div`,{className:`flex flex-col gap-3`,children:i||oe?v(`p`,{className:`${Zn} leading-relaxed`,children:`This camera doesn't support an on-board privacy mask.`}):!i&&!oe&&n!==null&&s!==null?T(E,{children:[T(`p`,{className:`${Zn} leading-relaxed`,children:[`Toggle `,v(`strong`,{className:`text-foreground`,children:`Edit mask`}),` to draw blanked-out zones on the live frame, then `,v(`strong`,{className:`text-foreground`,children:`Save`}),` to push them to the camera. Drag a rectangle to move, its corner to resize; drag polygon vertices, click an edge midpoint to add one, or right-click a vertex to remove it.`]}),T(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[v(`button`,{type:`button`,onClick:re,disabled:m,"aria-pressed":_,className:_?nL:tL,children:_?`Done editing`:`Edit mask`}),v(`button`,{type:`button`,onClick:M,disabled:m,"aria-pressed":s.enabled,className:s.enabled?nL:tL,children:s.enabled?`Mask on`:`Mask off`}),ae&&v(`button`,{type:`button`,onClick:()=>te(`rect`),disabled:m||j,"aria-pressed":S===`rect`,className:S===`rect`?nL:tL,title:j?`Maximum zones reached`:`Add a rectangle zone`,children:`+ Rect`}),z&&v(`button`,{type:`button`,onClick:()=>te(`polygon`),disabled:m||j,"aria-pressed":S===`polygon`,className:S===`polygon`?nL:tL,title:j?`Maximum zones reached`:`Add a polygon zone`,children:`+ Polygon`}),T(`span`,{className:`${Zn} ml-1 tabular-nums`,children:[O,` / `,k,` zones`]}),v(`span`,{className:`flex-1`}),v(`button`,{type:`button`,onClick:ne,disabled:m||!D,className:`rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors`,children:`Revert`}),v(`button`,{type:`button`,onClick:()=>void R(),disabled:m||!D,className:nL,children:m?`Saving…`:`Save`})]}),O>0?v(`div`,{className:`flex flex-col gap-1`,children:s.regions.map(e=>{let t=b===e.id,n=e.shape.kind===`polygon`?Wc:Zl;return T(`div`,{className:`flex items-center gap-2 rounded-md border px-2 py-1 transition-colors ${t?`border-primary/50 bg-primary/10`:`border-border bg-surface`}`,children:[T(`button`,{type:`button`,onClick:()=>I(e.id),disabled:m,className:`flex flex-1 items-center gap-2 text-left text-[11px] font-medium text-foreground-subtle hover:text-foreground disabled:opacity-40 transition-colors`,children:[v(n,{className:`h-3.5 w-3.5 shrink-0`}),T(`span`,{children:[`Zone `,e.id]}),v(`span`,{className:`text-foreground-faint capitalize`,children:e.shape.kind})]}),v(`button`,{type:`button`,onClick:()=>L(e.id),disabled:m,"aria-label":`Delete zone ${String(e.id)}`,title:`Delete zone`,className:`inline-flex h-6 w-6 items-center justify-center rounded border border-border bg-surface text-foreground-subtle hover:border-red-400/40 hover:bg-red-500/10 hover:text-red-400 disabled:opacity-40 transition-colors`,children:v(au,{className:`h-3.5 w-3.5`})})]},e.id)})}):null]}):v(`p`,{className:`${Zn} leading-relaxed`,children:`Loading the camera's privacy mask…`})})}):null}function sL(){return{schedule:{kind:`always`},mode:`continuous`,preBufferSec:0,postBufferSec:0,resetTimeoutOnNewEvent:!0}}function cL(e){return e===`onMotion`||e===`onAudioThreshold`}function lL(e,t,n){return e.map((e,r)=>r===t?{...e,...n}:e)}function uL(e,t){return e.filter((e,n)=>n!==t)}function dL(e){return e.schedules&&e.schedules.length>0?[...e.schedules]:e.schedule?[e.schedule]:[]}function fL(e){return{mode:e.mode??(e.enabled?`continuous`:`off`),profiles:e.profiles,segmentSeconds:e.segmentSeconds,schedules:dL(e),triggers:e.triggers??{},preBufferSec:e.preBufferSec,postBufferSec:e.postBufferSec,retention:e.retention}}function pL(e){return{enabled:e.mode!==`off`,mode:e.mode,profiles:e.profiles?[...e.profiles]:void 0,segmentSeconds:e.segmentSeconds,schedules:e.schedules.length>0?[...e.schedules]:void 0,triggers:Object.keys(e.triggers).length>0?e.triggers:void 0,preBufferSec:e.preBufferSec,postBufferSec:e.postBufferSec,retention:e.retention}}function mL(e){return e.mode==null&&(e.rules?.length??0)>0}var hL=[{d:0,label:`S`},{d:1,label:`M`},{d:2,label:`T`},{d:3,label:`W`},{d:4,label:`T`},{d:5,label:`F`},{d:6,label:`S`}];function gL(e){return e===`onMotion`||e===`onAudioThreshold`?e:`continuous`}function _L(e,t){return t===`onAudioThreshold`?{mode:t,thresholdDbfs:e.thresholdDbfs??-30}:t===`onMotion`?{mode:t,thresholdDbfs:void 0}:{mode:t,preBufferSec:0,postBufferSec:0,thresholdDbfs:void 0}}function vL({schedule:e,onChange:t}){let n=n=>{let r=e.days??[0,1,2,3,4,5,6],i=r.includes(n)?r.filter(e=>e!==n):[...r,n].toSorted((e,t)=>e-t);t({...e,days:i})};return T(`div`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:[v(`input`,{type:`time`,value:e.start,onChange:n=>t({...e,start:n.target.value}),className:`rounded-md border border-border bg-background px-2 py-1 text-xs`}),v(`span`,{children:`–`}),v(`input`,{type:`time`,value:e.end,onChange:n=>t({...e,end:n.target.value}),className:`rounded-md border border-border bg-background px-2 py-1 text-xs`}),v(`div`,{className:`flex gap-1`,children:hL.map(({d:t,label:r})=>v(`button`,{type:`button`,onClick:()=>n(t),className:`h-6 w-6 rounded text-[10px] ${!e.days||e.days.includes(t)?`bg-primary text-primary-foreground`:`bg-surface-hover text-foreground-subtle`}`,children:r},t))})]})}function yL({rules:e,onChange:t}){return T(`div`,{className:`space-y-2`,children:[e.length===0?v(`p`,{className:`text-xs text-foreground-subtle`,children:`No rules — recording is continuous (always) when enabled.`}):null,e.map((n,r)=>T(`div`,{className:`space-y-2 rounded-lg border border-border bg-surface p-3`,children:[T(`div`,{className:`flex items-center justify-between gap-2`,children:[T(`select`,{className:`rounded-md border border-border bg-background px-2 py-1 text-xs`,value:n.schedule.kind,onChange:n=>{t(lL(e,r,{schedule:n.target.value===`timeOfDay`?{kind:`timeOfDay`,start:`00:00`,end:`23:59`}:{kind:`always`}}))},children:[v(`option`,{value:`always`,children:`Always`}),v(`option`,{value:`timeOfDay`,children:`Time of day`})]}),v(`button`,{type:`button`,onClick:()=>t(uL(e,r)),className:`text-foreground-subtle hover:text-red-500`,children:v(xu,{className:`h-4 w-4`})})]}),n.schedule.kind===`timeOfDay`?v(vL,{schedule:n.schedule,onChange:n=>t(lL(e,r,{schedule:n}))}):null,T(`div`,{className:`flex flex-wrap items-center gap-2 text-xs`,children:[T(`select`,{className:`rounded-md border border-border bg-background px-2 py-1 text-xs`,value:n.mode,onChange:i=>t(lL(e,r,_L(n,gL(i.target.value)))),children:[v(`option`,{value:`continuous`,children:`Continuous`}),v(`option`,{value:`onMotion`,children:`On motion`}),v(`option`,{value:`onAudioThreshold`,children:`On audio`})]}),cL(n.mode)?T(E,{children:[T(`label`,{className:`flex items-center gap-1`,children:[`pre`,v(`input`,{type:`number`,min:0,value:n.preBufferSec,onChange:n=>t(lL(e,r,{preBufferSec:Number(n.target.value)})),className:`w-14 rounded-md border border-border bg-background px-1 py-1 text-xs`}),`s`]}),T(`label`,{className:`flex items-center gap-1`,children:[`post`,v(`input`,{type:`number`,min:0,value:n.postBufferSec,onChange:n=>t(lL(e,r,{postBufferSec:Number(n.target.value)})),className:`w-14 rounded-md border border-border bg-background px-1 py-1 text-xs`}),`s`]}),T(`label`,{className:`flex items-center gap-1`,children:[v(`input`,{type:`checkbox`,checked:n.resetTimeoutOnNewEvent,onChange:n=>t(lL(e,r,{resetTimeoutOnNewEvent:n.target.checked}))}),`reset`]})]}):null,n.mode===`onAudioThreshold`?T(`label`,{className:`flex items-center gap-1`,children:[`thr`,v(`input`,{type:`number`,value:n.thresholdDbfs??-30,onChange:n=>t(lL(e,r,{thresholdDbfs:Number(n.target.value)})),className:`w-16 rounded-md border border-border bg-background px-1 py-1 text-xs`}),`dBFS`]}):null]})]},r)),T(`button`,{type:`button`,onClick:()=>t([...e,sL()]),className:`flex items-center gap-1 rounded-md border border-dashed border-border px-3 py-1.5 text-xs text-foreground-subtle hover:border-primary hover:text-foreground`,children:[v(wl,{className:`h-3.5 w-3.5`}),` Add rule`]})]})}var bL=[{value:1,label:`Mon`},{value:2,label:`Tue`},{value:3,label:`Wed`},{value:4,label:`Thu`},{value:5,label:`Fri`},{value:6,label:`Sat`},{value:0,label:`Sun`}];function xL(){return{kind:`timeOfDay`,start:`09:00`,end:`18:00`}}function SL({schedules:e,onChange:t}){let n=(n,r)=>t(e.map((e,t)=>t===n?r:e)),r=n=>t(e.filter((e,t)=>t!==n));return T(`div`,{className:`space-y-2`,children:[e.length===0?v(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Sempre (24/7) — aggiungi una fascia per limitare gli orari.`}):e.map((e,t)=>v(CL,{band:e,onChange:e=>n(t,e),onRemove:()=>r(t)},t)),T(`button`,{type:`button`,onClick:()=>t([...e,xL()]),className:`flex items-center gap-1 rounded-md bg-surface-hover px-2 py-1 text-[11px] text-foreground-subtle hover:text-foreground`,children:[v(wl,{className:`h-3 w-3`}),` Aggiungi fascia`]})]})}function CL({band:e,onChange:t,onRemove:n}){if(e.kind===`always`)return T(`div`,{className:`flex items-center gap-2 text-xs`,children:[v(`span`,{className:`flex-1`,children:`Sempre`}),v(`button`,{type:`button`,onClick:()=>t(xL()),className:`text-foreground-subtle hover:text-foreground underline`,children:`imposta fascia`}),v(`button`,{type:`button`,onClick:n,"aria-label":`Rimuovi fascia`,className:`text-foreground-subtle hover:text-red-500`,children:v(au,{className:`h-3.5 w-3.5`})})]});let r=e.days??[],i=n=>{let i=r.includes(n)?r.filter(e=>e!==n):[...r,n];t({...e,days:i.length>0?i:void 0})};return T(`div`,{className:`space-y-1.5 rounded-md border border-border p-2`,children:[T(`div`,{className:`flex items-center gap-2 text-xs`,children:[v(`input`,{type:`time`,value:e.start,onChange:n=>t({...e,start:n.target.value}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),v(`span`,{className:`text-foreground-subtle`,children:`→`}),v(`input`,{type:`time`,value:e.end,onChange:n=>t({...e,end:n.target.value}),className:`rounded-md border border-border bg-background px-1 py-0.5`}),v(`span`,{className:`flex-1`}),v(`button`,{type:`button`,onClick:n,"aria-label":`Rimuovi fascia`,className:`text-foreground-subtle hover:text-red-500`,children:v(au,{className:`h-3.5 w-3.5`})})]}),T(`div`,{className:`flex flex-wrap gap-1`,children:[bL.map(e=>v(`button`,{type:`button`,onClick:()=>i(e.value),className:`rounded px-1.5 py-0.5 text-[10px] ${r.includes(e.value)?`bg-primary text-primary-foreground`:`bg-surface-hover text-foreground-subtle`}`,children:e.label},e.value)),r.length===0?v(`span`,{className:`self-center text-[10px] text-foreground-subtle`,children:`tutti i giorni`}):null]})]})}var wL=[`high`,`mid`,`low`],TL=[{value:`off`,label:`Off`},{value:`events`,label:`Events`},{value:`continuous`,label:`Continuous`}];function EL({initial:e,saving:t,onSave:n}){let[r,i]=h(mL(e)?`advanced`:`base`),[a,o]=h(fL(e)),[s,c]=h(e.enabled),[l,u]=h(e.rules?[...e.rules]:[]),[d,f]=h({profiles:e.profiles,segmentSeconds:e.segmentSeconds,retention:e.retention}),p=d.retention??{},m=e=>f({...d,retention:{...p,...e}}),g=e=>e===``?void 0:Number(e),_=e=>{let t=d.profiles??[],n=t.includes(e)?t.filter(t=>t!==e):[...t,e];f({...d,profiles:n.length?n:void 0})},y=e=>o({...a,triggers:{...a.triggers,...e}}),b=e=>{e===`advanced`&&l.length===0&&u([sL()]),i(e)};return T(`div`,{className:`space-y-4`,children:[v(`div`,{className:`flex gap-1 text-xs`,children:[`base`,`advanced`].map(e=>v(`button`,{type:`button`,onClick:()=>b(e),className:`rounded px-2.5 py-1 ${r===e?`bg-primary text-primary-foreground`:`bg-surface-hover text-foreground-subtle`}`,children:e===`base`?`Base`:`Advanced (rules)`},e))}),r===`base`?T(`div`,{className:`space-y-4`,children:[T(`div`,{className:`flex items-center gap-2 text-xs`,children:[v(`span`,{className:`text-foreground-subtle`,children:`Mode:`}),TL.map(e=>v(`button`,{type:`button`,onClick:()=>o({...a,mode:e.value}),className:`rounded px-2.5 py-1 ${a.mode===e.value?`bg-primary text-primary-foreground`:`bg-surface-hover text-foreground-subtle`}`,children:e.label},e.value))]}),a.mode===`off`?null:T(`div`,{children:[v(`div`,{className:`mb-1.5 text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Time bands`}),v(SL,{schedules:a.schedules,onChange:e=>o({...a,schedules:e})})]}),a.mode===`events`?T(`div`,{className:`space-y-2`,children:[v(`div`,{className:`text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Trigger`}),T(`label`,{className:`flex items-center gap-2 text-xs`,children:[v(`input`,{type:`checkbox`,checked:a.triggers.motion??!1,onChange:e=>y({motion:e.target.checked?!0:void 0})}),`Motion`]}),T(`label`,{className:`flex items-center gap-2 text-xs`,children:[v(`input`,{type:`checkbox`,checked:a.triggers.audioThresholdDbfs!=null,onChange:e=>y({audioThresholdDbfs:e.target.checked?-30:void 0})}),`Audio above threshold`,a.triggers.audioThresholdDbfs==null?null:v(`input`,{type:`number`,value:a.triggers.audioThresholdDbfs,onChange:e=>y({audioThresholdDbfs:g(e.target.value)}),className:`w-16 rounded-md border border-border bg-background px-1 py-0.5 text-xs`}),v(`span`,{className:`text-foreground-subtle`,children:`dBFS`})]}),T(`div`,{className:`flex flex-wrap items-center gap-3 text-xs`,children:[T(`label`,{className:`flex items-center gap-1`,children:[`Pre-buffer`,v(`input`,{type:`number`,min:0,value:a.preBufferSec??``,placeholder:`0`,onChange:e=>o({...a,preBufferSec:g(e.target.value)}),className:`w-16 rounded-md border border-border bg-background px-1 py-1 text-xs`}),`s`]}),T(`label`,{className:`flex items-center gap-1`,children:[`Post-buffer`,v(`input`,{type:`number`,min:0,value:a.postBufferSec??``,placeholder:`0`,onChange:e=>o({...a,postBufferSec:g(e.target.value)}),className:`w-16 rounded-md border border-border bg-background px-1 py-1 text-xs`}),`s`]})]})]}):null]}):T(`div`,{className:`space-y-4`,children:[T(`label`,{className:`flex items-center gap-2 text-xs`,children:[v(`input`,{type:`checkbox`,checked:s,onChange:e=>c(e.target.checked)}),`Record this camera`]}),T(`div`,{children:[v(`div`,{className:`mb-1.5 text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Rules`}),v(yL,{rules:l,onChange:u})]})]}),T(`div`,{className:`flex flex-wrap items-center gap-4 text-xs`,children:[T(`div`,{className:`flex items-center gap-2`,children:[v(`span`,{className:`text-foreground-subtle`,children:`Profiles:`}),wL.map(e=>v(`button`,{type:`button`,onClick:()=>_(e),className:`rounded px-2 py-1 ${(d.profiles??[]).includes(e)?`bg-primary text-primary-foreground`:`bg-surface-hover text-foreground-subtle`}`,children:e},e))]}),T(`label`,{className:`flex items-center gap-1`,children:[`Segment`,v(`input`,{type:`number`,min:1,value:d.segmentSeconds??``,placeholder:`default`,onChange:e=>f({...d,segmentSeconds:g(e.target.value)}),className:`w-16 rounded-md border border-border bg-background px-1 py-1 text-xs`}),`s`]})]}),T(`div`,{children:[v(`div`,{className:`mb-1.5 text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Retention (empty = node default)`}),T(`div`,{className:`flex flex-wrap items-center gap-3 text-xs`,children:[T(`label`,{className:`flex items-center gap-1`,children:[`Max age`,v(`input`,{type:`number`,min:0,value:p.maxAgeDays??``,placeholder:`14`,onChange:e=>m({maxAgeDays:g(e.target.value)}),className:`w-16 rounded-md border border-border bg-background px-1 py-1 text-xs`}),`days`]}),T(`label`,{className:`flex items-center gap-1`,children:[`Max size`,v(`input`,{type:`number`,min:0,value:p.maxSizeGb??``,placeholder:`∞`,onChange:e=>m({maxSizeGb:g(e.target.value)}),className:`w-16 rounded-md border border-border bg-background px-1 py-1 text-xs`}),`GB`]})]})]}),v(`div`,{className:`flex justify-end`,children:T(`button`,{type:`button`,disabled:t,onClick:()=>{n(r===`base`?pL({...a,profiles:d.profiles,segmentSeconds:d.segmentSeconds,retention:d.retention}):{enabled:s,rules:l,profiles:d.profiles?[...d.profiles]:void 0,segmentSeconds:d.segmentSeconds,retention:d.retention})},className:`flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-60`,children:[t?v(el,{className:`h-3.5 w-3.5 animate-spin`}):v(Pl,{className:`h-3.5 w-3.5`}),` `,`Save`]})})]})}var DL=hr(`camstack:vod-playback`,{request:null,play:()=>{},clear:()=>{}});function OL({children:e}){let[t,n]=h(null),r=o(()=>({request:t,play:e=>n(e),clear:()=>n(null)}),[t]);return v(DL.Provider,{value:r,children:e})}function kL(){return i(DL)}function AL(e){let t=e.filter(e=>e.endMs>e.startMs).map(e=>({startMs:e.startMs,endMs:e.endMs})).toSorted((e,t)=>e.startMs-t.startMs),n=[];for(let e of t){let t=n[n.length-1];t&&e.startMs<=t.endMs?e.endMs>t.endMs&&(n[n.length-1]={startMs:t.startMs,endMs:e.endMs}):n.push(e)}return n}function jL(e){if(!Number.isFinite(e)||e<0)return`—`;if(e<1024)return`${Math.round(e)} B`;let t=[`KB`,`MB`,`GB`,`TB`,`PB`],n=e/1024,r=`KB`;for(let e of t){if(r=e,n<1024)break;n/=1024}return`${n>=100?Math.round(n).toString():n.toFixed(1)} ${r}`}var ML=[`object`,`motion`,`audio`];function NL(e,t,n){let r=[];for(let i of e){let e={motion:i.motion,object:i.object,audio:i.audio},a=e.motion+e.object+e.audio;if(a===0)continue;let o=Math.floor((i.bucketStart-t)/n),s=null,c=-1;for(let t of ML)e[t]>c&&(c=e[t],s=t);r.push({index:o,startMs:i.bucketStart,endMs:i.bucketStart+n,counts:e,total:a,dominant:s})}return r.toSorted((e,t)=>e.index-t.index)}function PL(e,t){return e<t.startMs?t.startMs-e:e>t.endMs?e-t.endMs:0}function FL(e,t){if(t.length===0)return null;let n=t.find(t=>e>=t.startMs&&e<=t.endMs);if(n)return{fromMs:e,toMs:n.endMs};let r=null,i=1/0;for(let n of t){let t=PL(e,n);t<i&&(i=t,r=n)}return r?{fromMs:r.startMs,toMs:r.endMs}:null}function IL(e,t,n){let r=n-t;if(r<=0)return 0;let i=(e-t)/r*100;return i<0?0:i>100?100:i}function LL(e,t){let n=new Date(e.getFullYear(),e.getMonth(),e.getDate(),0,0,0,0).getTime(),r=new Date(e.getFullYear(),e.getMonth(),e.getDate()+1,0,0,0,0).getTime();return{fromMs:n,toMs:Math.max(n,Math.min(r,t))}}var RL=[24*36e5,12*36e5,6*36e5,36e5,15*6e4];function zL(e,t,n,r){if(n>=t.toMs-t.fromMs)return t;let i=r-n/2,a=r+n/2;return i<t.fromMs&&(i=t.fromMs,a=i+n),a>t.toMs&&(a=t.toMs,i=a-n),{fromMs:i,toMs:a}}function BL(e,t,n){let r=e.toMs-e.fromMs,i=e.fromMs+n,a=e.toMs+n;return i<t.fromMs&&(i=t.fromMs,a=i+r),a>t.toMs&&(a=t.toMs,i=a-r),{fromMs:i,toMs:a}}var VL=[15*6e4,5*6e4,6e4,3e4,15e3,5e3];function HL(e){let t=e/100;for(let e of VL)if(e<=t)return e;return VL[VL.length-1]??5e3}function UL(e,t,n){if(n<=1)return[{pct:0,label:new Date(e).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})}];let r=[];for(let i=0;i<n;i++){let a=e+i/(n-1)*(t-e),o=IL(a,e,t),s=new Date(a).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`});r.push({pct:o,label:s})}return r}function WL({windowFrom:e,windowTo:t,spans:n,playheadMs:r,onSeek:i}){let[a,o]=h(null),s=n=>{let r=n.currentTarget.getBoundingClientRect();if(r.width<=0)return null;let i=(n.clientX-r.left)/r.width;return e+Math.min(1,Math.max(0,i))*(t-e)},c=e=>{let t=s(e);t!==null&&i(t)},l=e=>{let t=s(e);if(t===null)return;let n=e.currentTarget.getBoundingClientRect();o({xPct:n.width>0?(e.clientX-n.left)/n.width*100:0,ms:t})},u=()=>{o(null)},d=a===null?null:new Date(a.ms).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`});return T(`div`,{className:`relative`,children:[T(`div`,{"data-testid":`coverage-track`,onClick:c,onMouseMove:l,onMouseLeave:u,className:`relative h-5 cursor-pointer overflow-hidden rounded bg-background/40`,role:`group`,"aria-label":`Recorded coverage timeline`,children:[n.map(n=>{let r=IL(n.startMs,e,t),i=IL(n.endMs,e,t);return v(`div`,{"data-testid":`coverage-fascia`,className:`absolute inset-y-0 bg-gradient-to-b from-primary to-primary/80`,style:{left:`${r}%`,width:`${Math.max(.5,i-r)}%`}},`${n.startMs}-${n.endMs}`)}),r===null?null:v(`div`,{"data-testid":`coverage-playhead`,className:`absolute inset-y-[-2px] w-0.5 bg-amber-500 shadow-[0_0_6px] shadow-amber-500`,style:{left:`${IL(r,e,t)}%`}})]}),a!==null&&d!==null?v(`div`,{"data-testid":`coverage-hover-tooltip`,className:`pointer-events-none absolute top-full z-10 mt-0.5 -translate-x-1/2 rounded bg-popover px-1.5 py-0.5 text-[9px] text-popover-foreground shadow`,style:{left:`${a.xPct}%`},children:d}):null]})}var GL={motion:`bg-emerald-500`,object:`bg-violet-500`,audio:`bg-orange-500`};function KL({windowFrom:e,windowTo:t,buckets:n,selectedIndex:r,onSelectBucket:i}){let a=n.reduce((e,t)=>Math.max(e,t.total),0),o=n[0],s=o?IL(o.endMs,e,t)-IL(o.startMs,e,t):0;return v(`div`,{className:`relative h-6 rounded bg-background/40`,children:n.map(n=>{if(n.total===0||n.dominant===null)return null;let o=a>0?Math.max(15,n.total/a*100):0,c=IL(n.startMs,e,t),l=n.index===r;return v(`button`,{type:`button`,"data-testid":`heatmap-bar`,title:`${new Date(n.startMs).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})} · motion ${n.counts.motion} · object ${n.counts.object}`,onClick:()=>i(n.index),className:`absolute bottom-0 rounded-t-sm transition-opacity ${GL[n.dominant]} ${l?`opacity-100 ring-1 ring-amber-400`:`opacity-80 hover:opacity-100`}`,style:{left:`${c}%`,width:`${Math.max(.6,s)}%`,height:`${o}%`}},n.index)})})}function qL({mediaUrl:e,kind:t}){let[n,r]=h(!1);return e&&!n?v(`img`,{src:e,alt:``,className:`h-full w-full object-cover`,loading:`lazy`,onError:()=>r(!0)}):v(`div`,{className:`flex h-full w-full items-center justify-center text-white/30`,children:v(JL,{kind:t,large:!0})})}function JL({kind:e,large:t=!1}){return v(e===`object`?Gs:e===`audio`?pu:Ds,{className:t?`h-7 w-7`:`h-3.5 w-3.5 text-foreground-subtle`})}var YL=[`motion`,`object`,`audio`];function XL(e){return new Date(e).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})}function ZL({clips:e,loading:t,busyKey:n,onPlay:r,enabledKinds:i,onToggleKind:a,hasMore:o,onLoadMore:s}){let c=v(`div`,{className:`flex items-center gap-3 pb-1`,children:YL.map(e=>T(`label`,{className:`flex cursor-pointer items-center gap-1 text-xs text-foreground-subtle select-none`,children:[v(`input`,{type:`checkbox`,checked:i.has(e),onChange:()=>a(e),className:`h-3.5 w-3.5 accent-primary`}),e]},e))});return t&&e.length===0?T(`div`,{className:`space-y-2`,children:[c,v(`div`,{className:`px-1 py-2 text-xs text-foreground-subtle`,children:`Loading events…`})]}):e.length===0?T(`div`,{className:`space-y-2`,children:[c,v(`div`,{className:`px-1 py-2 text-xs text-foreground-subtle`,children:`No events in this window.`})]}):T(`div`,{className:`space-y-2`,children:[c,t?v(`div`,{className:`px-1 text-[10px] text-foreground-subtle`,children:`Loading events…`}):null,v(`div`,{className:`grid grid-cols-2 gap-2 sm:grid-cols-3`,children:e.map(e=>{let t=`event:${e.id}`;return T(`button`,{type:`button`,disabled:n!==null,onClick:()=>r(e),className:`group overflow-hidden rounded-lg border border-border text-left transition-colors hover:border-primary disabled:opacity-60`,children:[T(`div`,{className:`relative aspect-video bg-black/90`,children:[v(qL,{mediaUrl:e.mediaUrl,kind:e.kind}),v(`div`,{className:`absolute inset-0 flex items-center justify-center bg-black/0 transition-colors group-hover:bg-black/30`,children:n===t?v(el,{className:`h-6 w-6 animate-spin text-white`}):v(Cl,{className:`h-6 w-6 text-white opacity-0 transition-opacity group-hover:opacity-100`})})]}),T(`div`,{className:`flex items-center gap-1.5 bg-surface px-2 py-1.5`,children:[v(JL,{kind:e.kind}),T(`div`,{className:`min-w-0 flex-1`,children:[v(`div`,{className:`truncate text-xs font-medium text-foreground`,children:e.label}),v(`div`,{className:`text-[10px] text-foreground-subtle`,children:XL(e.timestamp)})]})]})]},t)})}),e.length>0?T(`div`,{className:`flex items-center gap-2 pt-1 text-[11px] text-foreground-subtle`,children:[T(`span`,{children:[`(`,e.length,` shown)`]}),o?v(`button`,{type:`button`,onClick:s,className:`rounded px-2 py-0.5 text-[11px] font-medium text-primary hover:underline`,children:`Load more`}):null]}):null]})}function QL(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,`0`)}-${String(e.getDate()).padStart(2,`0`)}`}function $L(e){let t=e.split(`-`),n=t[0]===void 0?NaN:parseInt(t[0],10),r=t[1]===void 0?NaN:parseInt(t[1],10),i=t[2]===void 0?NaN:parseInt(t[2],10);return isNaN(n)||isNaN(r)||isNaN(i)?null:new Date(n,r-1,i)}function eR({day:e,onDayChange:t,view:n,dayBounds:r,onViewChange:i}){let a=e=>{let n=$L(e.target.value);n!==null&&t(n)},o=n.toMs-n.fromMs,s=(()=>{let e=0,t=1/0;for(let n=0;n<RL.length;n++){let r=RL[n];if(r===void 0)continue;let i=Math.abs(r-o);i<t&&(t=i,e=n)}return e})(),c=(n.fromMs+n.toMs)/2,l=()=>{let e=RL[Math.min(s+1,RL.length-1)];e!==void 0&&i(zL(n,r,e,c))},u=()=>{let e=RL[Math.max(s-1,0)];e!==void 0&&i(zL(n,r,e,c))},d=s<RL.length-1,f=s>0;return T(`div`,{className:`flex items-center gap-2`,children:[v(`input`,{type:`date`,value:QL(e),max:QL(new Date),onChange:a,className:`rounded border border-border bg-background px-2 py-0.5 text-[11px] text-foreground focus:outline-none focus:ring-1 focus:ring-primary`,"aria-label":`Select recording day`}),T(`div`,{className:`ml-auto flex items-center gap-1`,children:[v(`button`,{type:`button`,onClick:u,disabled:!f,title:`Zoom out`,"aria-label":`Zoom out`,className:`rounded p-1 text-foreground-subtle transition-colors hover:bg-background/60 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40`,children:v(wu,{size:13})}),v(`button`,{type:`button`,onClick:l,disabled:!d,title:`Zoom in`,"aria-label":`Zoom in`,className:`rounded p-1 text-foreground-subtle transition-colors hover:bg-background/60 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40`,children:v(Cu,{size:13})})]}),v(`span`,{className:`text-[9px] text-foreground-subtle`,children:tR(o)})]})}function tR(e){let t=e/36e5;if(t>=24)return`24h`;if(t>=1)return`${Math.round(t)}h`;let n=e/6e4;return`${Math.round(n)}m`}var nR=[`motion`,`object`,`audio`],rR=60,iR=18e3/100,aR=5e3,oR=1e4,sR=[];function cR({deviceId:e}){let t=gf(),n=kL(),[r,i]=h(null),[a,s]=h(null),[l,d]=h(null),[f,m]=h(null),[g,_]=h(()=>new Set(nR)),y=u(e=>{_(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[b,x]=h(rR),S=u(()=>{x(e=>e+rR)},[]);c(()=>{x(rR)},[r]);let[C,w]=h(()=>new Date),[E,D]=h(()=>LL(new Date,Date.now())),O=o(()=>LL(C,Date.now()),[C]),k=u(e=>{w(e),D(LL(e,Date.now())),i(null)},[]),A=u(e=>{D(e),i(null)},[]),j=p(null),M=u(e=>{let t=Math.abs(e.deltaX)>Math.abs(e.deltaY)?e.deltaX:e.shiftKey?e.deltaY:0;if(t===0)return;e.preventDefault();let n=t*iR;D(e=>BL(e,O,n))},[O]),N=HL(E.toMs-E.fromMs),P=bw({deviceId:e,fromMs:E.fromMs,toMs:E.toMs}),ee=fS({deviceId:e,since:E.fromMs,until:E.toMs,bucketMs:N}),F=P.data?.ranges??sR,te=o(()=>AL(F),[F]),I=o(()=>NL(ee.data??[],E.fromMs,N),[ee.data,E.fromMs,N]),L=r===null?void 0:I.find(e=>e.index===r),ne=L!==void 0,R=L?.startMs??0,re=L?Math.min(L.endMs,E.toMs):0,ie=uS({deviceId:e,since:R,until:re,limit:b,projection:`slim`},{enabled:ne&&g.has(`object`)}),ae=lS({deviceId:e,since:R,until:re,limit:b,projection:`slim`},{enabled:ne&&g.has(`motion`)}),z=dS({deviceId:e,since:R,until:re,limit:b,projection:`slim`},{enabled:ne&&g.has(`audio`)}),oe=o(()=>{if(!L)return[];let e=[];if(g.has(`object`))for(let t of ie.data??[])e.push({id:t.id,timestamp:t.timestamp,kind:`object`,label:t.label??t.className,mediaUrl:t.mediaUrl});if(g.has(`motion`))for(let t of ae.data??[])e.push({id:t.id,timestamp:t.timestamp,kind:`motion`,label:`Motion (${t.regionCount})`,mediaUrl:t.mediaUrl});if(g.has(`audio`))for(let t of z.data??[])e.push({id:t.id,timestamp:t.timestamp,kind:`audio`,label:t.classification?.className??`Audio`,mediaUrl:t.mediaUrl});return e.toSorted((e,t)=>t.timestamp-e.timestamp)},[L,g,ie.data,ae.data,z.data]),se=o(()=>!!(g.has(`object`)&&(ie.data?.length??0)===b||g.has(`motion`)&&(ae.data?.length??0)===b||g.has(`audio`)&&(z.data?.length??0)===b),[g,ie.data,ae.data,z.data,b]),ce=u(async(r,i,a,o,c)=>{d(r),m(null);try{let r=await t.trpcClient.recording.getPlaybackManifest.query({deviceId:e,fromMs:i,toMs:a});r?.playbackUrl?(s(c),n.play({url:r.playbackUrl,label:o})):m(`No playable footage for this selection.`)}catch{m(`Could not load this recording.`)}finally{d(null)}},[t,e,n]),le=u(e=>{let t=FL(e,te);if(!t)return;let n=`Recording · ${new Date(t.fromMs).toLocaleString(void 0,{month:`short`,day:`numeric`,hour:`2-digit`,minute:`2-digit`})}`;ce(`seek:${t.fromMs}`,t.fromMs,t.toMs,n,t.fromMs)},[te,ce]),ue=u(e=>{let t=`${e.label} · ${new Date(e.timestamp).toLocaleTimeString(void 0,{hour:`2-digit`,minute:`2-digit`})}`;ce(`event:${e.id}`,e.timestamp-aR,e.timestamp+oR,t,e.timestamp)},[ce]),de=u(e=>{i(t=>t===e?null:e)},[]),fe=P.isLoading,pe=ee.isLoading,me=(ie.isLoading||ae.isLoading||z.isLoading)&&ne,he=o(()=>UL(E.fromMs,E.toMs,5),[E.fromMs,E.toMs]);return T(`div`,{className:`space-y-3`,children:[P.isError?v(Ff,{variant:`warning`,message:`Recorder unavailable — the recording service may not be running for this node.`}):null,f?v(Ff,{variant:`warning`,message:f}):null,v(eR,{day:C,onDayChange:k,view:E,dayBounds:O,onViewChange:A}),T(`div`,{ref:j,onWheel:M,className:`space-y-1`,children:[T(`div`,{className:`space-y-1`,children:[v(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Recorded`}),fe?v(`div`,{className:`h-5 animate-pulse rounded bg-background/40`}):te.length===0?v(Nf,{icon:Mc,title:`No recordings for this window.`}):v(WL,{windowFrom:E.fromMs,windowTo:E.toMs,spans:te,playheadMs:a,onSeek:le})]}),T(`div`,{className:`space-y-1`,children:[v(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Events · density`}),pe?v(`div`,{className:`h-6 animate-pulse rounded bg-background/40`}):v(KL,{windowFrom:E.fromMs,windowTo:E.toMs,buckets:I,selectedIndex:r,onSelectBucket:de})]}),v(`div`,{className:`relative h-3`,children:he.map(e=>v(`span`,{className:`absolute -translate-x-1/2 text-[9px] text-foreground-subtle`,style:{left:`${e.pct}%`},children:e.label},e.pct))})]}),L?v(ZL,{clips:oe,loading:me,busyKey:l,onPlay:ue,enabledKinds:g,onToggleKind:y,hasMore:se,onLoadMore:S}):v(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Click the coverage bar to play from any point, or a density bar to browse that window's events.`})]})}var lR=1440*60*1e3;function uR(e){let t=Math.round(e/1e3),n=Math.floor(t/3600),r=Math.floor(t%3600/60),i=t%60;return n>0?`${n}h ${r}m`:r>0?`${r}m ${i}s`:`${i}s`}function dR({deviceId:e}){let t=b(),n=Aw({deviceId:e}),r=ww({deviceId:e}),i=Dw(),a=Ow(),s=t=>{i.mutate({deviceId:e,config:t},{onSuccess:()=>{r.refetch(),n.refetch()}})},c=u(()=>{a.mutate({deviceId:e},{onSuccess:()=>{t.invalidateQueries({queryKey:[[`recording`]]})}})},[e,t,a]),l=o(()=>Date.now(),[]),d=bw({deviceId:e,fromMs:l-lR,toMs:l}),f=n.data?Ce.safeParse(n.data):null,p=f?.success?f.data:null,m=r.data?Oe.safeParse(r.data):null,h=m?.success?m.data:null,g=d.data?.ranges??[],_=g.reduce((e,t)=>e+Math.max(0,t.endMs-t.startMs),0),y=p?.enabled===!0&&p.activeMode===`continuous`;return T(`div`,{className:`space-y-3`,children:[v(ZF,{title:`Settings`,icon:v(zl,{className:`h-3.5 w-3.5 text-foreground-subtle`}),collapsible:!0,defaultOpen:!1,children:h?v(EL,{initial:h,saving:i.isPending,onSave:s},JSON.stringify(h)):v(`div`,{className:`px-1 py-2 text-xs text-foreground-subtle`,children:`Loading settings…`})}),v(ZF,{title:`Recording`,icon:v(Mc,{className:`h-3.5 w-3.5 text-foreground-subtle`}),headerRight:T(`span`,{className:`flex items-center gap-2`,children:[y?T(`span`,{className:`flex items-center gap-1.5 text-[10px] text-emerald-500`,children:[v(Al,{className:`h-3 w-3`}),` Recording`]}):null,v(`button`,{type:`button`,onClick:c,disabled:a.isPending,"aria-label":`Rescan storage`,className:`flex items-center rounded p-0.5 text-foreground-subtle transition-colors hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50`,children:v(jl,{className:`h-3.5 w-3.5 ${a.isPending?`animate-spin`:``}`})})]}),children:T(`div`,{className:`space-y-3`,children:[T(`div`,{className:`grid grid-cols-1 gap-2 sm:grid-cols-3`,children:[v(QF,{label:`Status`,icon:v(ac,{className:`h-3.5 w-3.5 ${y?`text-emerald-500`:``}`}),footer:p?.nodeId?`node: ${p.nodeId}`:void 0,children:n.isLoading?`…`:y?`Recording (continuous)`:`Idle`}),v(QF,{label:`Storage`,icon:v(Hc,{className:`h-3.5 w-3.5`}),children:p?jL(p.storageBytes):`—`}),v(QF,{label:`Recorded (24h)`,icon:v(uc,{className:`h-3.5 w-3.5`}),footer:`${g.length} segment range${g.length===1?``:`s`}`,children:d.isLoading?`…`:uR(_)})]}),n.isError?v(Ff,{variant:`warning`,message:`Recorder unavailable — the recording service may not be running for this node.`}):null,v(cR,{deviceId:e}),v(`p`,{className:`text-[11px] text-foreground-subtle`,children:`Recordings play in the main player above — switch back to live from there.`})]})})]})}var fR={"host/motion-zones-grid":QI,"host/privacy-mask-grid":oL,"host/ptz-panel":eI,"host/consumables-panel":aI,"host/ptz-autotrack":sI,"host/recording-panel":dR};function pR(e){let{widgetId:t,deviceId:n}=e,r=fR[t];return r===void 0?v(mR,{...e}):n===void 0?v(_R,{widgetId:t,reason:`missing-device-context`}):v(r,{deviceId:n})}function mR(e){let{widgetId:t}=e,n=GF(t);return n===void 0?v(_R,{widgetId:t,reason:`unknown`}):v(hR,{...e,metadata:n})}function hR(e){let{widgetId:t,host:n=`device-tab`,config:r,deviceId:i,integrationId:a,instanceId:s,size:c,columns:l,rows:u,metadata:d}=e,f=qF(d.remote,d.bundleUrl),p=o(()=>s??t,[s,t]);return f===null?v(gR,{}):f===void 0?v(_R,{widgetId:t,reason:`missing-export`}):d.requires.deviceContext&&i===void 0?v(_R,{widgetId:t,reason:`missing-device-context`}):d.requires.integrationContext&&a===void 0?v(_R,{widgetId:t,reason:`missing-integration-context`}):v(f,{instanceId:p,host:n,config:r,deviceId:i,integrationId:a,size:c,columns:l,rows:u})}function gR(){return T(`div`,{className:`rounded-lg border border-border bg-surface/40 p-4 animate-pulse`,children:[v(`div`,{className:`h-3 w-24 bg-foreground-subtle/20 rounded mb-2`}),v(`div`,{className:`h-2 w-full bg-foreground-subtle/10 rounded mb-1`}),v(`div`,{className:`h-2 w-3/4 bg-foreground-subtle/10 rounded`})]})}function _R({widgetId:e,reason:t}){return v(`div`,{className:`rounded-lg border border-warning/30 bg-warning/10 px-3 py-2 text-xs text-warning`,children:t===`unknown`?`Widget "${e}" not registered`:t===`missing-export`?`Widget "${e}" bundle does not export this stableId`:t===`missing-device-context`?`Widget "${e}" requires a deviceId`:`Widget "${e}" requires an integrationId`})}var vR=Object.defineProperty,yR=Object.getOwnPropertySymbols,bR=Object.prototype.hasOwnProperty,xR=Object.prototype.propertyIsEnumerable,SR=(e,t,n)=>t in e?vR(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,CR=(e,t)=>{for(var n in t||={})bR.call(t,n)&&SR(e,n,t[n]);if(yR)for(var n of yR(t))xR.call(t,n)&&SR(e,n,t[n]);return e},wR=(e,t)=>{var n={};for(var r in e)bR.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&yR)for(var r of yR(e))t.indexOf(r)<0&&xR.call(e,r)&&(n[r]=e[r]);return n},TR;(e=>{let t=class t{constructor(e,n,r,a){if(this.version=e,this.errorCorrectionLevel=n,this.modules=[],this.isFunction=[],e<t.MIN_VERSION||e>t.MAX_VERSION)throw RangeError(`Version value out of range`);if(a<-1||a>7)throw RangeError(`Mask value out of range`);this.size=e*4+17;let o=[];for(let e=0;e<this.size;e++)o.push(!1);for(let e=0;e<this.size;e++)this.modules.push(o.slice()),this.isFunction.push(o.slice());this.drawFunctionPatterns();let s=this.addEccAndInterleave(r);if(this.drawCodewords(s),a==-1){let e=1e9;for(let t=0;t<8;t++){this.applyMask(t),this.drawFormatBits(t);let n=this.getPenaltyScore();n<e&&(a=t,e=n),this.applyMask(t)}}i(0<=a&&a<=7),this.mask=a,this.applyMask(a),this.drawFormatBits(a),this.isFunction=[]}static encodeText(n,r){let i=e.QrSegment.makeSegments(n);return t.encodeSegments(i,r)}static encodeBinary(n,r){let i=e.QrSegment.makeBytes(n);return t.encodeSegments([i],r)}static encodeSegments(e,r,a=1,s=40,c=-1,l=!0){if(!(t.MIN_VERSION<=a&&a<=s&&s<=t.MAX_VERSION)||c<-1||c>7)throw RangeError(`Invalid value`);let u,d;for(u=a;;u++){let n=t.getNumDataCodewords(u,r)*8,i=o.getTotalBits(e,u);if(i<=n){d=i;break}if(u>=s)throw RangeError(`Data too long`)}for(let e of[t.Ecc.MEDIUM,t.Ecc.QUARTILE,t.Ecc.HIGH])l&&d<=t.getNumDataCodewords(u,e)*8&&(r=e);let f=[];for(let t of e){n(t.mode.modeBits,4,f),n(t.numChars,t.mode.numCharCountBits(u),f);for(let e of t.getData())f.push(e)}i(f.length==d);let p=t.getNumDataCodewords(u,r)*8;i(f.length<=p),n(0,Math.min(4,p-f.length),f),n(0,(8-f.length%8)%8,f),i(f.length%8==0);for(let e=236;f.length<p;e^=253)n(e,8,f);let m=[];for(;m.length*8<f.length;)m.push(0);return f.forEach((e,t)=>m[t>>>3]|=e<<7-(t&7)),new t(u,r,m,c)}getModule(e,t){return 0<=e&&e<this.size&&0<=t&&t<this.size&&this.modules[t][e]}getModules(){return this.modules}drawFunctionPatterns(){for(let e=0;e<this.size;e++)this.setFunctionModule(6,e,e%2==0),this.setFunctionModule(e,6,e%2==0);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);let e=this.getAlignmentPatternPositions(),t=e.length;for(let n=0;n<t;n++)for(let r=0;r<t;r++)n==0&&r==0||n==0&&r==t-1||n==t-1&&r==0||this.drawAlignmentPattern(e[n],e[r]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(e){let t=this.errorCorrectionLevel.formatBits<<3|e,n=t;for(let e=0;e<10;e++)n=n<<1^(n>>>9)*1335;let a=(t<<10|n)^21522;i(a>>>15==0);for(let e=0;e<=5;e++)this.setFunctionModule(8,e,r(a,e));this.setFunctionModule(8,7,r(a,6)),this.setFunctionModule(8,8,r(a,7)),this.setFunctionModule(7,8,r(a,8));for(let e=9;e<15;e++)this.setFunctionModule(14-e,8,r(a,e));for(let e=0;e<8;e++)this.setFunctionModule(this.size-1-e,8,r(a,e));for(let e=8;e<15;e++)this.setFunctionModule(8,this.size-15+e,r(a,e));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let e=this.version;for(let t=0;t<12;t++)e=e<<1^(e>>>11)*7973;let t=this.version<<12|e;i(t>>>18==0);for(let e=0;e<18;e++){let n=r(t,e),i=this.size-11+e%3,a=Math.floor(e/3);this.setFunctionModule(i,a,n),this.setFunctionModule(a,i,n)}}drawFinderPattern(e,t){for(let n=-4;n<=4;n++)for(let r=-4;r<=4;r++){let i=Math.max(Math.abs(r),Math.abs(n)),a=e+r,o=t+n;0<=a&&a<this.size&&0<=o&&o<this.size&&this.setFunctionModule(a,o,i!=2&&i!=4)}}drawAlignmentPattern(e,t){for(let n=-2;n<=2;n++)for(let r=-2;r<=2;r++)this.setFunctionModule(e+r,t+n,Math.max(Math.abs(r),Math.abs(n))!=1)}setFunctionModule(e,t,n){this.modules[t][e]=n,this.isFunction[t][e]=!0}addEccAndInterleave(e){let n=this.version,r=this.errorCorrectionLevel;if(e.length!=t.getNumDataCodewords(n,r))throw RangeError(`Invalid argument`);let a=t.NUM_ERROR_CORRECTION_BLOCKS[r.ordinal][n],o=t.ECC_CODEWORDS_PER_BLOCK[r.ordinal][n],s=Math.floor(t.getNumRawDataModules(n)/8),c=a-s%a,l=Math.floor(s/a),u=[],d=t.reedSolomonComputeDivisor(o);for(let n=0,r=0;n<a;n++){let i=e.slice(r,r+l-o+(n<c?0:1));r+=i.length;let a=t.reedSolomonComputeRemainder(i,d);n<c&&i.push(0),u.push(i.concat(a))}let f=[];for(let e=0;e<u[0].length;e++)u.forEach((t,n)=>{(e!=l-o||n>=c)&&f.push(t[e])});return i(f.length==s),f}drawCodewords(e){if(e.length!=Math.floor(t.getNumRawDataModules(this.version)/8))throw RangeError(`Invalid argument`);let n=0;for(let t=this.size-1;t>=1;t-=2){t==6&&(t=5);for(let i=0;i<this.size;i++)for(let a=0;a<2;a++){let o=t-a,s=t+1&2?i:this.size-1-i;!this.isFunction[s][o]&&n<e.length*8&&(this.modules[s][o]=r(e[n>>>3],7-(n&7)),n++)}}i(n==e.length*8)}applyMask(e){if(e<0||e>7)throw RangeError(`Mask value out of range`);for(let t=0;t<this.size;t++)for(let n=0;n<this.size;n++){let r;switch(e){case 0:r=(n+t)%2==0;break;case 1:r=t%2==0;break;case 2:r=n%3==0;break;case 3:r=(n+t)%3==0;break;case 4:r=(Math.floor(n/3)+Math.floor(t/2))%2==0;break;case 5:r=n*t%2+n*t%3==0;break;case 6:r=(n*t%2+n*t%3)%2==0;break;case 7:r=((n+t)%2+n*t%3)%2==0;break;default:throw Error(`Unreachable`)}!this.isFunction[t][n]&&r&&(this.modules[t][n]=!this.modules[t][n])}}getPenaltyScore(){let e=0;for(let n=0;n<this.size;n++){let r=!1,i=0,a=[0,0,0,0,0,0,0];for(let o=0;o<this.size;o++)this.modules[n][o]==r?(i++,i==5?e+=t.PENALTY_N1:i>5&&e++):(this.finderPenaltyAddHistory(i,a),r||(e+=this.finderPenaltyCountPatterns(a)*t.PENALTY_N3),r=this.modules[n][o],i=1);e+=this.finderPenaltyTerminateAndCount(r,i,a)*t.PENALTY_N3}for(let n=0;n<this.size;n++){let r=!1,i=0,a=[0,0,0,0,0,0,0];for(let o=0;o<this.size;o++)this.modules[o][n]==r?(i++,i==5?e+=t.PENALTY_N1:i>5&&e++):(this.finderPenaltyAddHistory(i,a),r||(e+=this.finderPenaltyCountPatterns(a)*t.PENALTY_N3),r=this.modules[o][n],i=1);e+=this.finderPenaltyTerminateAndCount(r,i,a)*t.PENALTY_N3}for(let n=0;n<this.size-1;n++)for(let r=0;r<this.size-1;r++){let i=this.modules[n][r];i==this.modules[n][r+1]&&i==this.modules[n+1][r]&&i==this.modules[n+1][r+1]&&(e+=t.PENALTY_N2)}let n=0;for(let e of this.modules)n=e.reduce((e,t)=>e+ +!!t,n);let r=this.size*this.size,a=Math.ceil(Math.abs(n*20-r*10)/r)-1;return i(0<=a&&a<=9),e+=a*t.PENALTY_N4,i(0<=e&&e<=2568888),e}getAlignmentPatternPositions(){if(this.version==1)return[];{let e=Math.floor(this.version/7)+2,t=this.version==32?26:Math.ceil((this.version*4+4)/(e*2-2))*2,n=[6];for(let r=this.size-7;n.length<e;r-=t)n.splice(1,0,r);return n}}static getNumRawDataModules(e){if(e<t.MIN_VERSION||e>t.MAX_VERSION)throw RangeError(`Version number out of range`);let n=(16*e+128)*e+64;if(e>=2){let t=Math.floor(e/7)+2;n-=(25*t-10)*t-55,e>=7&&(n-=36)}return i(208<=n&&n<=29648),n}static getNumDataCodewords(e,n){return Math.floor(t.getNumRawDataModules(e)/8)-t.ECC_CODEWORDS_PER_BLOCK[n.ordinal][e]*t.NUM_ERROR_CORRECTION_BLOCKS[n.ordinal][e]}static reedSolomonComputeDivisor(e){if(e<1||e>255)throw RangeError(`Degree out of range`);let n=[];for(let t=0;t<e-1;t++)n.push(0);n.push(1);let r=1;for(let i=0;i<e;i++){for(let e=0;e<n.length;e++)n[e]=t.reedSolomonMultiply(n[e],r),e+1<n.length&&(n[e]^=n[e+1]);r=t.reedSolomonMultiply(r,2)}return n}static reedSolomonComputeRemainder(e,n){let r=n.map(e=>0);for(let i of e){let e=i^r.shift();r.push(0),n.forEach((n,i)=>r[i]^=t.reedSolomonMultiply(n,e))}return r}static reedSolomonMultiply(e,t){if(e>>>8||t>>>8)throw RangeError(`Byte out of range`);let n=0;for(let r=7;r>=0;r--)n=n<<1^(n>>>7)*285,n^=(t>>>r&1)*e;return i(n>>>8==0),n}finderPenaltyCountPatterns(e){let t=e[1];i(t<=this.size*3);let n=t>0&&e[2]==t&&e[3]==t*3&&e[4]==t&&e[5]==t;return(n&&e[0]>=t*4&&e[6]>=t?1:0)+(n&&e[6]>=t*4&&e[0]>=t?1:0)}finderPenaltyTerminateAndCount(e,t,n){return e&&(this.finderPenaltyAddHistory(t,n),t=0),t+=this.size,this.finderPenaltyAddHistory(t,n),this.finderPenaltyCountPatterns(n)}finderPenaltyAddHistory(e,t){t[0]==0&&(e+=this.size),t.pop(),t.unshift(e)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],e.QrCode=t;function n(e,t,n){if(t<0||t>31||e>>>t)throw RangeError(`Value out of range`);for(let r=t-1;r>=0;r--)n.push(e>>>r&1)}function r(e,t){return(e>>>t&1)!=0}function i(e){if(!e)throw Error(`Assertion error`)}let a=class e{constructor(e,t,n){if(this.mode=e,this.numChars=t,this.bitData=n,t<0)throw RangeError(`Invalid argument`);this.bitData=n.slice()}static makeBytes(t){let r=[];for(let e of t)n(e,8,r);return new e(e.Mode.BYTE,t.length,r)}static makeNumeric(t){if(!e.isNumeric(t))throw RangeError(`String contains non-numeric characters`);let r=[];for(let e=0;e<t.length;){let i=Math.min(t.length-e,3);n(parseInt(t.substring(e,e+i),10),i*3+1,r),e+=i}return new e(e.Mode.NUMERIC,t.length,r)}static makeAlphanumeric(t){if(!e.isAlphanumeric(t))throw RangeError(`String contains unencodable characters in alphanumeric mode`);let r=[],i;for(i=0;i+2<=t.length;i+=2){let a=e.ALPHANUMERIC_CHARSET.indexOf(t.charAt(i))*45;a+=e.ALPHANUMERIC_CHARSET.indexOf(t.charAt(i+1)),n(a,11,r)}return i<t.length&&n(e.ALPHANUMERIC_CHARSET.indexOf(t.charAt(i)),6,r),new e(e.Mode.ALPHANUMERIC,t.length,r)}static makeSegments(t){return t==``?[]:e.isNumeric(t)?[e.makeNumeric(t)]:e.isAlphanumeric(t)?[e.makeAlphanumeric(t)]:[e.makeBytes(e.toUtf8ByteArray(t))]}static makeEci(t){let r=[];if(t<0)throw RangeError(`ECI assignment value out of range`);if(t<128)n(t,8,r);else if(t<16384)n(2,2,r),n(t,14,r);else if(t<1e6)n(6,3,r),n(t,21,r);else throw RangeError(`ECI assignment value out of range`);return new e(e.Mode.ECI,0,r)}static isNumeric(t){return e.NUMERIC_REGEX.test(t)}static isAlphanumeric(t){return e.ALPHANUMERIC_REGEX.test(t)}getData(){return this.bitData.slice()}static getTotalBits(e,t){let n=0;for(let r of e){let e=r.mode.numCharCountBits(t);if(r.numChars>=1<<e)return 1/0;n+=4+e+r.bitData.length}return n}static toUtf8ByteArray(e){e=encodeURI(e);let t=[];for(let n=0;n<e.length;n++)e.charAt(n)==`%`?(t.push(parseInt(e.substring(n+1,n+3),16)),n+=2):t.push(e.charCodeAt(n));return t}};a.NUMERIC_REGEX=/^[0-9]*$/,a.ALPHANUMERIC_REGEX=/^[A-Z0-9 $%*+.\/:-]*$/,a.ALPHANUMERIC_CHARSET=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:`;let o=a;e.QrSegment=a})(TR||={}),(e=>{(e=>{let t=class{constructor(e,t){this.ordinal=e,this.formatBits=t}};t.LOW=new t(0,1),t.MEDIUM=new t(1,0),t.QUARTILE=new t(2,3),t.HIGH=new t(3,2),e.Ecc=t})(e.QrCode||={})})(TR||={}),(e=>{(e=>{let t=class{constructor(e,t){this.modeBits=e,this.numBitsCharCount=t}numCharCountBits(e){return this.numBitsCharCount[Math.floor((e+7)/17)]}};t.NUMERIC=new t(1,[10,12,14]),t.ALPHANUMERIC=new t(2,[9,11,13]),t.BYTE=new t(4,[8,16,16]),t.KANJI=new t(8,[8,10,12]),t.ECI=new t(7,[0,0,0]),e.Mode=t})(e.QrSegment||={})})(TR||={});var ER=TR,DR={L:ER.QrCode.Ecc.LOW,M:ER.QrCode.Ecc.MEDIUM,Q:ER.QrCode.Ecc.QUARTILE,H:ER.QrCode.Ecc.HIGH},OR=128,kR=`L`,AR=`#FFFFFF`,jR=`#000000`,MR=!1,NR=1,PR=4,FR=0,IR=.1;function LR(e,t=0){let n=[];return e.forEach(function(e,r){let i=null;e.forEach(function(a,o){if(!a&&i!==null){n.push(`M${i+t} ${r+t}h${o-i}v1H${i+t}z`),i=null;return}if(o===e.length-1){if(!a)return;i===null?n.push(`M${o+t},${r+t} h1v1H${o+t}z`):n.push(`M${i+t},${r+t} h${o+1-i}v1H${i+t}z`);return}a&&i===null&&(i=o)})}),n.join(``)}function RR(e,t){return e.slice().map((e,n)=>n<t.y||n>=t.y+t.h?e:e.map((e,n)=>n<t.x||n>=t.x+t.w?e:!1))}function zR(e,t,n,r){if(r==null)return null;let i=e.length+n*2,a=Math.floor(t*IR),o=i/t,s=(r.width||a)*o,c=(r.height||a)*o,l=r.x==null?e.length/2-s/2:r.x*o,u=r.y==null?e.length/2-c/2:r.y*o,d=r.opacity==null?1:r.opacity,f=null;if(r.excavate){let e=Math.floor(l),t=Math.floor(u);f={x:e,y:t,w:Math.ceil(s+l-e),h:Math.ceil(c+u-t)}}let p=r.crossOrigin;return{x:l,y:u,h:c,w:s,excavation:f,opacity:d,crossOrigin:p}}function BR(e,t){return t==null?e?PR:FR:Math.max(Math.floor(t),0)}function VR({value:e,level:t,minVersion:n,includeMargin:r,marginSize:i,imageSettings:a,size:o,boostLevel:s}){let c=w.useMemo(()=>{let r=(Array.isArray(e)?e:[e]).reduce((e,t)=>(e.push(...ER.QrSegment.makeSegments(t)),e),[]);return ER.QrCode.encodeSegments(r,DR[t],n,void 0,void 0,s)},[e,t,n,s]),{cells:l,margin:u,numCells:d,calculatedImageSettings:f}=w.useMemo(()=>{let e=c.getModules(),t=BR(r,i);return{cells:e,margin:t,numCells:e.length+t*2,calculatedImageSettings:zR(e,o,t,a)}},[c,o,a,r,i]);return{qrcode:c,margin:u,cells:l,numCells:d,calculatedImageSettings:f}}var HR=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),UR=w.forwardRef(function(e,t){let n=e,{value:r,size:i=OR,level:a=kR,bgColor:o=AR,fgColor:s=jR,includeMargin:c=MR,minVersion:l=NR,boostLevel:u,marginSize:d,imageSettings:f}=n,p=wR(n,[`value`,`size`,`level`,`bgColor`,`fgColor`,`includeMargin`,`minVersion`,`boostLevel`,`marginSize`,`imageSettings`]),{style:m}=p,h=wR(p,[`style`]),g=f?.src,_=w.useRef(null),v=w.useRef(null),y=w.useCallback(e=>{_.current=e,typeof t==`function`?t(e):t&&(t.current=e)},[t]),[b,x]=w.useState(!1),{margin:S,cells:C,numCells:T,calculatedImageSettings:E}=VR({value:r,level:a,minVersion:l,boostLevel:u,includeMargin:c,marginSize:d,imageSettings:f,size:i});w.useEffect(()=>{if(_.current!=null){let e=_.current,t=e.getContext(`2d`);if(!t)return;let n=C,r=v.current,a=E!=null&&r!==null&&r.complete&&r.naturalHeight!==0&&r.naturalWidth!==0;a&&E.excavation!=null&&(n=RR(C,E.excavation));let c=window.devicePixelRatio||1;e.height=e.width=i*c;let l=i/T*c;t.scale(l,l),t.fillStyle=o,t.fillRect(0,0,T,T),t.fillStyle=s,HR?t.fill(new Path2D(LR(n,S))):C.forEach(function(e,n){e.forEach(function(e,r){e&&t.fillRect(r+S,n+S,1,1)})}),E&&(t.globalAlpha=E.opacity),a&&t.drawImage(r,E.x+S,E.y+S,E.w,E.h)}}),w.useEffect(()=>{x(!1)},[g]);let D=CR({height:i,width:i},m),O=null;return g!=null&&(O=w.createElement(`img`,{src:g,key:g,style:{display:`none`},onLoad:()=>{x(!0)},ref:v,crossOrigin:E?.crossOrigin})),w.createElement(w.Fragment,null,w.createElement(`canvas`,CR({style:D,height:i,width:i,ref:y,role:`img`},h)),O)});UR.displayName=`QRCodeCanvas`;var WR=w.forwardRef(function(e,t){let n=e,{value:r,size:i=OR,level:a=kR,bgColor:o=AR,fgColor:s=jR,includeMargin:c=MR,minVersion:l=NR,boostLevel:u,title:d,marginSize:f,imageSettings:p}=n,m=wR(n,[`value`,`size`,`level`,`bgColor`,`fgColor`,`includeMargin`,`minVersion`,`boostLevel`,`title`,`marginSize`,`imageSettings`]),{margin:h,cells:g,numCells:_,calculatedImageSettings:v}=VR({value:r,level:a,minVersion:l,boostLevel:u,includeMargin:c,marginSize:f,imageSettings:p,size:i}),y=g,b=null;p!=null&&v!=null&&(v.excavation!=null&&(y=RR(g,v.excavation)),b=w.createElement(`image`,{href:p.src,height:v.h,width:v.w,x:v.x+h,y:v.y+h,preserveAspectRatio:`none`,opacity:v.opacity,crossOrigin:v.crossOrigin}));let x=LR(y,h);return w.createElement(`svg`,CR({height:i,width:i,viewBox:`0 0 ${_} ${_}`,ref:t,role:`img`},m),!!d&&w.createElement(`title`,null,d),w.createElement(`path`,{fill:o,d:`M0,0 h${_}v${_}H0z`,shapeRendering:`crispEdges`}),w.createElement(`path`,{fill:s,d:x,shapeRendering:`crispEdges`}),b)});WR.displayName=`QRCodeSVG`;var GR=192;function KR({value:e,size:t=GR,className:n,alt:r}){let i=e.trim();return i.length===0?null:v(`div`,{className:G(`inline-flex rounded-md bg-white p-2`,n),children:v(WR,{value:i,size:t,marginSize:1,title:r??`QR code`})})}var qR=`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none disabled:opacity-50 disabled:cursor-not-allowed`;function JR({value:e,onChange:t,disabled:n}){let r=[];for(let e of De)r.includes(e.region)||r.push(e.region);return T(`select`,{className:qR,value:e,disabled:n,onChange:e=>t(e.target.value),children:[!ge(e)&&v(`option`,{value:``,children:`— Select timezone —`}),r.map(e=>v(`optgroup`,{label:e,children:De.filter(t=>t.region===e).map(e=>v(`option`,{value:e.id,children:e.label},e.id))},e))]})}var YR=`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none disabled:opacity-50 disabled:cursor-not-allowed`,XR=`block text-[11px] font-medium text-foreground mb-1 break-words`,ZR=`text-[10px] text-foreground-subtle mt-0.5 break-words`;function QR({label:e,description:t,required:n,span:r,children:i,translationFn:a}){let o=r===2?`col-span-1 @[480px]:col-span-2`:r===3?`col-span-1 @[480px]:col-span-2 @[880px]:col-span-3`:r===4?`col-span-1 @[480px]:col-span-2 @[1140px]:col-span-4`:`col-span-1`,s=Hz(e,a),c=Hz(t,a),l=s!==void 0&&s!==``;return T(`div`,{className:`${o} min-w-0`,children:[l&&T(`label`,{className:XR,children:[s,n&&v(`span`,{className:`text-danger ml-0.5`,children:`*`})]}),i,c&&v(`p`,{className:ZR,children:c})]})}function $R({field:e,value:t,onChange:n,disabled:r,translationFn:i}){return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:v(`input`,{type:e.inputType??`text`,className:YR,value:t==null?``:String(t),placeholder:e.placeholder,maxLength:e.maxLength,pattern:e.pattern,disabled:r||e.disabled,onChange:e=>n(e.target.value)})})}function ez({field:e,value:t,onChange:n,disabled:r,translationFn:i}){let[a,o]=h(t==null?``:String(t)),s=p(!1);c(()=>{s.current||o(t==null?``:String(t))},[t]);let l=e=>{if(o(e),e===``||e===`-`){n(void 0);return}let t=Number(e);Number.isNaN(t)||n(t)};return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:T(`div`,{className:`flex items-center gap-1`,children:[v(`input`,{type:`number`,className:YR,value:a,placeholder:e.placeholder,min:e.min,max:e.max,step:e.step,disabled:r||e.disabled,onFocus:()=>{s.current=!0},onBlur:()=>{s.current=!1},onChange:e=>l(e.target.value)}),e.unit&&v(`span`,{className:`text-xs text-foreground-subtle whitespace-nowrap`,children:e.unit})]})})}function tz({field:e,value:t,onChange:n,disabled:r,translationFn:i}){let a=!!t,o=r||e.disabled;return e.style===`checkbox`?v(QR,{label:void 0,description:e.description,required:e.required,span:e.span,translationFn:i,children:T(`label`,{className:`flex items-center gap-2 cursor-pointer select-none`,children:[v(`input`,{type:`checkbox`,className:`h-3.5 w-3.5 rounded border-border accent-primary`,checked:a,disabled:o,onChange:e=>n(e.target.checked)}),v(`span`,{className:`text-xs font-medium text-foreground`,children:Hz(e.label,i)}),e.required&&v(`span`,{className:`text-danger`,children:`*`})]})}):v(QR,{label:void 0,description:e.description,required:e.required,span:e.span,translationFn:i,children:T(`div`,{className:`flex items-center justify-between`,children:[T(`span`,{className:`block text-[11px] font-medium text-foreground mb-1 break-words mb-0`,children:[Hz(e.label,i),e.required&&v(`span`,{className:`text-danger ml-0.5`,children:`*`})]}),v(`button`,{type:`button`,role:`switch`,"aria-checked":a,disabled:o,onClick:()=>!o&&n(!a),className:[`relative inline-flex h-4 w-8 shrink-0 items-center rounded-full transition-colors duration-150`,a?`bg-primary`:`bg-foreground-subtle/30`,o?`opacity-50 cursor-not-allowed`:`cursor-pointer`].join(` `),children:v(`span`,{className:[`inline-block h-3 w-3 rounded-full bg-white shadow transition-transform duration-150`,a?`translate-x-4`:`translate-x-0.5`].join(` `)})})]})})}function nz({field:e,value:t,onChange:n,disabled:r,translationFn:i}){let a=e.options.some(e=>e.value===``);return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:T(`select`,{className:YR,value:t==null?``:String(t),disabled:r||e.disabled,onChange:e=>n(e.target.value),children:[!e.required&&!a&&v(`option`,{value:``,children:`— Select —`}),e.options.map(e=>v(`option`,{value:e.value,children:e.label},e.value))]})})}function rz({field:e,value:t,onChange:n,disabled:r,translationFn:i}){return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:v(JR,{value:typeof t==`string`?t:``,onChange:n,disabled:r||e.disabled})})}function iz({field:e,value:t,onChange:n,disabled:r,translationFn:i}){return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:v(`input`,{type:`datetime-local`,className:YR,value:typeof t==`string`?t:``,placeholder:e.placeholder,disabled:r||e.disabled,onChange:e=>n(e.target.value)})})}function az({field:e,value:t,onChange:n,disabled:r,translationFn:i}){let a=Array.isArray(t)?t:[],o=t=>{if(a.includes(t))n(a.filter(e=>e!==t));else{if(e.maxItems!==void 0&&a.length>=e.maxItems)return;n([...a,t])}};return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:v(`div`,{className:`flex flex-wrap gap-2`,children:e.options.map(t=>{let n=a.includes(t.value);return T(`label`,{className:[`flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs cursor-pointer select-none transition-colors`,n?`border-primary bg-primary/10 text-primary`:`border-border bg-background text-foreground hover:bg-surface`,r||e.disabled?`opacity-50 cursor-not-allowed`:``].join(` `),children:[v(`input`,{type:`checkbox`,className:`sr-only`,checked:n,disabled:r||e.disabled,onChange:()=>o(t.value)}),t.label]},t.value)})})})}function oz({field:e,value:t,onChange:n,disabled:r,translationFn:i}){let[a,o]=h(!1),s=e.showToggle!==!1;return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:T(`div`,{className:`relative`,children:[v(`input`,{type:a?`text`:`password`,className:YR+(s?` pr-9`:``),value:t==null?``:String(t),placeholder:e.placeholder,disabled:r||e.disabled,onChange:e=>n(e.target.value)}),s&&v(`button`,{type:`button`,className:`absolute right-2 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground`,tabIndex:-1,onClick:()=>o(e=>!e),children:v(a?kc:Ac,{className:`h-3.5 w-3.5`})})]})})}function sz({field:e,value:t,onChange:n,disabled:r,translationFn:i}){return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:v(`textarea`,{className:`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none disabled:opacity-50 disabled:cursor-not-allowed resize-y min-h-[60px]`,value:t==null?``:String(t),placeholder:e.placeholder,rows:e.rows??3,maxLength:e.maxLength,disabled:r||e.disabled,onChange:e=>n(e.target.value)})})}function cz({field:e,value:t,onChange:n,disabled:r,translationFn:i}){let a=t==null,o=e.nullable===!0,s=a?e.default??e.min:Number(t),c=e.showValue!==!1,l=e.nullLabel??`Auto`,u=r||e.disabled,d=e.displayScale??1,f=e.min/d,p=e.max/d,m=s/d,h=(e.step??1)/d;if(o&&a)return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:T(`button`,{className:`w-full rounded-lg border border-dashed border-border px-3 py-2 text-xs text-foreground-subtle hover:border-primary/40 hover:text-primary transition-colors text-left`,disabled:u,onClick:()=>n(e.default??e.min),children:[l,` — click to set manually`]})});let g=e.showStepper===!0&&c,_=t=>{let r=s+t*(e.step??1),i=Math.min(e.max,Math.max(e.min,r));i!==s&&n(i)},y=`flex h-6 w-6 shrink-0 items-center justify-center rounded border border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:cursor-not-allowed disabled:opacity-40`;return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:T(`div`,{className:`flex flex-wrap items-center gap-x-3 gap-y-2`,children:[T(`div`,{className:`flex min-w-0 flex-1 basis-[160px] items-center gap-2`,children:[v(`span`,{className:`text-[10px] text-foreground-subtle tabular-nums shrink-0`,children:f}),v(`input`,{type:`range`,className:`min-w-0 flex-1 h-1 accent-primary cursor-pointer disabled:opacity-50`,min:f,max:p,step:h,value:m,disabled:u,onChange:e=>n(Number(e.target.value)*d)}),v(`span`,{className:`text-[10px] text-foreground-subtle tabular-nums shrink-0`,children:p})]}),(c||o||e.unit)&&T(`div`,{className:`flex shrink-0 items-center gap-2`,children:[g&&v(`button`,{type:`button`,className:y,disabled:u||s<=e.min,onClick:()=>_(-1),title:`Decrease by ${e.step??1}`,"aria-label":`Decrement`,children:v(fl,{className:`h-3 w-3`})}),c&&v(`input`,{type:`number`,className:`w-16 rounded border border-border bg-surface px-1.5 py-0.5 text-xs text-center text-foreground tabular-nums focus:outline-none focus:ring-1 focus:ring-primary`,min:f,max:p,step:h,value:m,disabled:u,onChange:t=>{if(t.target.value===``){n(o?null:e.min);return}let r=Number(t.target.value)*d,i=e.step??1,a=r-e.min,s=e.min+Math.round(a/i)*i;n(Math.min(e.max,Math.max(e.min,s)))}}),g&&v(`button`,{type:`button`,className:y,disabled:u||s>=e.max,onClick:()=>_(1),title:`Increase by ${e.step??1}`,"aria-label":`Increment`,children:v(wl,{className:`h-3 w-3`})}),e.unit&&v(`span`,{className:`text-[10px] text-foreground-subtle`,children:e.unit}),o&&v(`button`,{className:`text-[10px] text-foreground-subtle hover:text-primary transition-colors`,title:`Reset to ${l}`,disabled:u,onClick:()=>n(null),children:l})]})]})})}function lz({field:e,value:t,onChange:n,disabled:r,translationFn:i}){let a=Array.isArray(t)?t:[],[o,s]=h(``),c=p(null),l=u(t=>{let r=t.trim();!r||a.includes(r)||e.maxTags!==void 0&&a.length>=e.maxTags||(n([...a,r]),s(``))},[a,e.maxTags,n]),d=e=>n(a.filter(t=>t!==e)),f=e=>{e.key===`Enter`||e.key===`,`?(e.preventDefault(),l(o)):e.key===`Backspace`&&o===``&&a.length>0&&d(a[a.length-1])},m=r||e.disabled;return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:T(`div`,{className:[`flex flex-wrap gap-1.5 rounded-md border border-border bg-background px-2 py-1.5 min-h-[38px] cursor-text`,`focus-within:border-primary focus-within:ring-1 focus-within:ring-primary/30`,m?`opacity-50 cursor-not-allowed`:``].join(` `),onClick:()=>!m&&c.current?.focus(),children:[a.map(e=>T(`span`,{className:`inline-flex items-center gap-1 rounded-md bg-primary/10 px-1.5 py-0.5 text-xs text-primary`,children:[e,!m&&v(`button`,{type:`button`,onClick:()=>d(e),className:`hover:text-danger`,children:v(xu,{className:`h-2.5 w-2.5`})})]},e)),v(`input`,{ref:c,type:`text`,className:`flex-1 min-w-[80px] bg-transparent text-sm text-foreground outline-none placeholder:text-foreground-disabled`,value:o,placeholder:a.length===0?e.placeholder??`Add tags…`:``,disabled:m,list:`tags-suggestions-${e.key}`,onChange:e=>s(e.target.value),onKeyDown:f,onBlur:()=>{o.trim()&&l(o)}}),e.suggestions&&v(`datalist`,{id:`tags-suggestions-${e.key}`,children:e.suggestions.map(e=>v(`option`,{value:e},e))})]})})}function uz({field:e,value:t,onChange:n,disabled:r,translationFn:i}){let{nodes:a}=Sf(),o=typeof t==`string`?t:``,s=e.showOffline?a:a.filter(e=>e.isOnline);return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:T(`select`,{className:`w-full px-3 py-2 text-sm bg-background border border-border rounded-lg text-foreground focus:outline-none focus:border-primary/50 disabled:opacity-50`,value:o,onChange:e=>n(e.target.value),disabled:r,children:[v(`option`,{value:``,children:`Select node…`}),s.map(e=>T(`option`,{value:e.id,disabled:!e.isOnline,children:[e.shortName,e.isOnline?``:` (offline)`]},e.id))]})})}function dz({field:e,value:t,onChange:n,disabled:r,translationFn:i}){let{nodes:a}=Sf(),o=new Set(Array.isArray(t)?t.map(String):[]),s=e.showOffline?a:a.filter(e=>e.isOnline),c=e=>{let t=new Set(o);t.has(e)?t.delete(e):t.add(e),n([...t])};return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:v(`div`,{className:`flex flex-wrap gap-1.5`,children:s.map(e=>{let t=o.has(e.id);return v(`button`,{type:`button`,onClick:()=>c(e.id),disabled:r||!e.isOnline,className:`px-2.5 py-1 text-xs font-medium rounded-md border transition-colors ${t?`border-primary bg-primary/10 text-primary`:`border-border bg-surface text-foreground-subtle hover:bg-surface-hover`} ${e.isOnline?``:`opacity-50 cursor-not-allowed`}`,children:e.shortName},e.id)})})})}function fz({field:e,value:t,onChange:n,disabled:r,translationFn:i}){let a=t==null?`#000000`:String(t);return T(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:[T(`div`,{className:`flex items-center gap-2`,children:[v(`input`,{type:`color`,className:`h-9 w-9 rounded-md border border-border bg-background cursor-pointer p-0.5 disabled:opacity-50`,value:a,disabled:r||e.disabled,onChange:e=>n(e.target.value)}),v(`input`,{type:`text`,className:`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none disabled:opacity-50 disabled:cursor-not-allowed flex-1 font-mono`,value:a,placeholder:`#000000`,disabled:r||e.disabled,onChange:e=>n(e.target.value)})]}),e.presets&&e.presets.length>0&&v(`div`,{className:`flex gap-1.5 mt-1.5`,children:e.presets.map(t=>v(`button`,{type:`button`,className:`h-5 w-5 rounded-md border border-border hover:scale-110 transition-transform disabled:opacity-50`,style:{backgroundColor:t},disabled:r||e.disabled,title:t,onClick:()=>n(t)},t))})]})}function pz({field:e,value:t,onChange:n,disabled:r,translationFn:i,onTestField:a,onAction:o,externalProbe:s}){let[c,l]=h(`idle`),[d,f]=h(null),p=s?.status??c,m=s?.result??d,g=!!a||!!o,_=u(async()=>{if(g){l(`probing`),f(null);try{let n=a?await a(e.key,t):await o(`test-probe`,e.key,t),r=n&&typeof n==`object`?n:{status:`error`,error:`Probe handler returned no result`};f(r),l(r.status===`ok`?`ok`:`error`)}catch(e){f({status:`error`,error:e instanceof Error?e.message:String(e)}),l(`error`)}}},[a,o,e.key,t,g]),y=p===`probing`?`border-primary/40 bg-primary/10 text-primary`:p===`ok`?`border-success/40 bg-success/10 text-success hover:bg-success/15`:p===`error`?`border-danger/40 bg-danger/10 text-danger hover:bg-danger/15`:`border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,b=p===`probing`?v(el,{className:`h-3 w-3 animate-spin`}):v(p===`ok`?rc:p===`error`?nc:_u,{className:`h-3 w-3`});return T(QR,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:i,children:[T(`div`,{className:`@container flex items-center gap-2`,style:{containerType:`inline-size`},children:[T(`button`,{type:`button`,onClick:_,title:`Test`,disabled:e.disabled||p===`probing`||!g||!t,className:`flex-shrink-0 inline-flex items-center gap-1.5 rounded-md border px-2 py-2 text-xs font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed @[280px]:px-3 ${y}`,children:[b,v(`span`,{className:`hidden @[280px]:inline`,children:`Test`})]}),v(`input`,{type:e.inputType??`url`,className:`w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none disabled:opacity-50 disabled:cursor-not-allowed flex-1 min-w-0`,value:t==null?``:String(t),placeholder:e.placeholder,disabled:r||e.disabled,onChange:e=>{n(e.target.value),c!==`idle`&&(l(`idle`),f(null))}})]}),p===`ok`&&m?.labels&&m.labels.length>0&&v(`div`,{className:`flex flex-wrap gap-1 mt-1.5`,children:m.labels.map((e,t)=>v(`span`,{className:`text-xs bg-success/10 text-success rounded px-2 py-0.5 font-mono`,children:e},t))}),p===`error`&&m?.error&&v(`p`,{className:`text-xs text-danger mt-1 truncate`,title:m.error,children:m.error})]})}function mz({field:e,values:t,onChange:n,disabled:r,translationFn:i,onTestField:a}){let[o,s]=h(e.defaultCollapsed??!1),c=e.style===`accordion`;return v(`div`,{className:`${e.span===2?`col-span-2`:e.span===3?`col-span-3`:e.span===4?`col-span-4`:`col-span-1`} min-w-0`,children:T(`div`,{className:`@container rounded-lg border border-border bg-surface/50 overflow-hidden`,style:{containerType:`inline-size`},children:[T(`div`,{className:[`px-3 py-2 flex items-center justify-between min-w-0`,c?`cursor-pointer hover:bg-surface`:``].join(` `),onClick:c?()=>s(e=>!e):void 0,children:[v(`span`,{className:`text-xs font-semibold text-foreground min-w-0 break-words`,children:Hz(e.label,i)}),c&&v(`span`,{className:`text-foreground-subtle text-xs shrink-0 ml-2`,children:o?`▸`:`▾`})]}),!o&&v(`div`,{className:`px-3 pb-3 grid grid-cols-1 @[480px]:grid-cols-2 gap-x-4 gap-y-3`,children:e.fields.map(e=>v(Bz,{field:e,values:t,onChange:n,disabled:r,translationFn:i,onTestField:a},e.key))})]})})}function hz({field:e,values:t,onChange:n,disabled:r,translationFn:i,onTestField:a,onAction:o}){let[s,c]=h(e.tabs[0]?.id??``),l=e.span===2?`col-span-2`:e.span===3?`col-span-3`:e.span===4?`col-span-4`:`col-span-1`;return e.tabs.length===0?null:T(`div`,{className:`${l} min-w-0`,children:[e.label&&v(`div`,{className:XR,children:Hz(e.label,i)}),T(`div`,{className:`@container rounded-lg border border-border-subtle bg-surface-hover/40 overflow-hidden`,style:{containerType:`inline-size`},children:[v(`div`,{className:`flex flex-wrap gap-1 p-1.5 border-b border-border-subtle bg-surface/40`,role:`tablist`,children:e.tabs.map(e=>{let t=e.id===s;return T(`button`,{type:`button`,role:`tab`,"aria-selected":t,onClick:()=>c(e.id),className:`inline-flex items-center gap-1.5 whitespace-nowrap rounded-md px-2.5 py-1 text-[11px] transition-colors ${t?`bg-primary text-primary-foreground font-medium shadow-sm`:`bg-transparent text-foreground-subtle hover:bg-surface hover:text-foreground`}`,children:[v(`span`,{children:Hz(e.label,i)}),e.badge&&v(`span`,{className:`text-[9px] px-1 py-0.5 rounded-full font-medium ${t?`bg-primary-foreground/20 text-primary-foreground`:`bg-primary/10 text-primary`}`,children:e.badge})]},e.id)})}),e.tabs.map(e=>e.id===s?v(`div`,{role:`tabpanel`,className:`px-3 pb-3 pt-2 grid grid-cols-1 @[480px]:grid-cols-2 gap-x-4 gap-y-3`,children:e.fields.map((s,c)=>{let l=`key`in s&&typeof s.key==`string`?s.key:`__${e.id}__${c}`;return v(Bz,{field:s,values:t,onChange:n,disabled:r,translationFn:i,onTestField:a,onAction:o},l)})},e.id):null)]})]})}function gz({span:e}){return v(`div`,{className:e===2?`col-span-2`:e===3?`col-span-3`:e===4?`col-span-4`:`col-span-full`,children:v(`hr`,{className:`border-border`})})}var _z={info:{border:`border-info`,bg:`bg-info/5`,text:`text-info`},warning:{border:`border-warning`,bg:`bg-warning/5`,text:`text-warning`},success:{border:`border-success`,bg:`bg-success/5`,text:`text-success`},danger:{border:`border-danger`,bg:`bg-danger/5`,text:`text-danger`}};function vz(e){if(typeof window>`u`||typeof DOMParser>`u`)return``;let t=new Set([`A`,`UL`,`OL`,`LI`,`STRONG`,`EM`,`CODE`,`BR`,`P`,`SPAN`]),n=new DOMParser().parseFromString(`<div>${e}</div>`,`text/html`),r=n.body.firstElementChild;if(!r)return``;let i=e=>{let r=Array.from(e.children);for(let e of r){if(!t.has(e.tagName)){let t=n.createTextNode(e.textContent??``);e.replaceWith(t);continue}let r=e.tagName===`A`?new Set([`href`]):new Set;for(let t of Array.from(e.attributes))r.has(t.name)||e.removeAttribute(t.name);if(e.tagName===`A`){let t=e.getAttribute(`href`)??``;!/^https?:\/\//i.test(t)&&!t.startsWith(`mailto:`)?e.removeAttribute(`href`):(e.setAttribute(`target`,`_blank`),e.setAttribute(`rel`,`noopener noreferrer`))}i(e)}};return i(r),r.innerHTML}function yz({field:e}){let t=_z[e.variant??`info`]??_z.info,n=e.format===`html`;return v(`div`,{className:`col-span-full`,children:T(`div`,{className:`rounded-md border-l-4 px-3 py-2.5 ${t.border} ${t.bg}`,children:[e.label&&v(`p`,{className:`text-xs font-semibold mb-0.5 ${t.text}`,children:e.label}),n?v(`div`,{className:`text-xs text-foreground-subtle leading-relaxed info-html-content`,dangerouslySetInnerHTML:{__html:vz(e.content)}}):v(`p`,{className:`text-xs text-foreground-subtle leading-relaxed whitespace-pre-line`,children:e.content})]})})}function bz({field:e}){let t=e.value;if(!t||t.length===0)return null;let n=e.size??192,r=e.alt??e.label;return v(`div`,{className:`col-span-full`,children:T(`div`,{className:`rounded-md border border-foreground-subtle/20 px-3 py-3 bg-background-subtle/40 flex flex-col items-start gap-2`,children:[e.label&&v(`p`,{className:`text-xs font-semibold text-foreground`,children:e.label}),e.caption&&v(`p`,{className:`text-xs text-foreground-subtle leading-relaxed`,children:e.caption}),v(KR,{value:t,size:n,alt:r})]})})}var xz={ok:`bg-success`,warn:`bg-amber-500`,danger:`bg-danger`,idle:`bg-foreground-subtle/40`,unknown:`bg-foreground-subtle/40`};function Sz(e){if(!Number.isFinite(e)||e<0)return`—`;if(e<1e3)return`${e}ms`;let t=Math.round(e/1e3);if(t<60)return`${t}s`;let n=Math.floor(t/60),r=t%60;return r===0?`${n}m`:`${n}m ${r}s`}function Cz(e){return!Number.isFinite(e)||e<=0?`—`:new Date(e).toLocaleTimeString()}function wz({kind:e,value:t}){return t==null||t===``?v(`span`,{className:`text-foreground-subtle/60`,children:`—`}):e===`monospace`?v(`span`,{className:`font-mono text-[11px]`,children:String(t)}):e===`status`?T(`span`,{className:`inline-flex items-center gap-1.5`,children:[v(`span`,{className:`inline-block h-1.5 w-1.5 rounded-full ${xz[String(t).toLowerCase()]??xz.unknown}`}),v(`span`,{children:String(t)})]}):e===`duration`&&typeof t==`number`?v(`span`,{className:`font-mono text-[11px]`,children:Sz(t)}):e===`timestamp`&&typeof t==`number`?v(`span`,{className:`font-mono text-[11px]`,children:Cz(t)}):v(`span`,{children:String(t)})}function Tz({field:e}){let t=e.value??[],n=e.description;return T(`div`,{className:`col-span-full`,children:[e.label&&v(`p`,{className:`text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1`,children:e.label}),n&&v(`p`,{className:`text-xs text-foreground-subtle mb-2`,children:n}),t.length===0?v(`div`,{className:`rounded-md border border-border bg-surface-subtle px-3 py-2 text-xs text-foreground-subtle`,children:e.emptyMessage??`No entries`}):v(`div`,{className:`rounded-md border border-border overflow-hidden`,children:T(`table`,{className:`w-full text-xs`,children:[v(`thead`,{className:`bg-surface-subtle border-b border-border`,children:v(`tr`,{children:e.columns.map(e=>v(`th`,{className:`px-3 py-1.5 text-left font-medium text-foreground-subtle`,style:e.width?{width:e.width}:void 0,children:e.label},e.key))})}),v(`tbody`,{className:`divide-y divide-border`,children:t.map((t,n)=>v(`tr`,{className:`hover:bg-surface-hover/40`,children:e.columns.map(e=>v(`td`,{className:`px-3 py-1.5 align-top text-foreground`,children:v(wz,{kind:e.kind,value:t[e.key]})},e.key))},n))})]})})]})}function Ez({field:e,value:t,onChange:n,disabled:r,translationFn:i,onTestField:a,onAction:o}){let s=Array.isArray(t)?t:[],c=e.minRows??0,l=e.maxRows??1/0,u=(e,t,r)=>{let i=s.slice();i[e]={...i[e]??{},[t]:r},n(i)},d=e=>{s.length<=c||n(s.filter((t,n)=>n!==e))},f=()=>{if(s.length>=l)return;let t=e.defaultItem??{};n([...s,{...t}])},p=(t,n)=>e.rowTitleTemplate?e.rowTitleTemplate.replace(/\{(\w+)\}/g,(e,n)=>{let r=t[n];return r==null||r===``?`—`:String(r)}):`Row ${n+1}`,m=s.length>c,h=s.length<l;return T(`div`,{className:`col-span-full space-y-2`,children:[T(`div`,{className:`space-y-0.5`,children:[e.label&&v(`p`,{className:`text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:Hz(e.label,i)}),e.description&&v(`p`,{className:`text-[11px] text-foreground-subtle`,children:Hz(e.description,i)})]}),s.length===0?v(`div`,{className:`rounded-md border border-dashed border-border bg-background px-3 py-3 text-center text-[11px] text-foreground-subtle`,children:e.emptyMessage??`No entries`}):v(`div`,{className:`space-y-2`,children:s.map((t,n)=>T(`div`,{className:`rounded-md border border-border bg-background`,children:[T(`div`,{className:`flex items-center justify-between border-b border-border px-3 py-1.5`,children:[v(`span`,{className:`text-xs font-medium text-foreground`,children:p(t,n)}),T(`button`,{type:`button`,onClick:()=>d(n),disabled:r||!m,className:`inline-flex items-center gap-1 rounded px-2 py-0.5 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-30 disabled:cursor-not-allowed`,title:m?`Remove this row`:`At least ${c} row(s) required`,children:[v(fl,{className:`h-3 w-3`}),`Remove`]})]}),v(`div`,{className:`grid grid-cols-1 @[480px]:grid-cols-2 gap-x-3 gap-y-2 p-3`,children:e.itemFields.map(s=>v(Bz,{field:s,values:t,onChange:(e,t)=>u(n,e,t),disabled:r,translationFn:i,onTestField:a,allFields:e.itemFields,onAction:o},s.key))})]},n))}),T(`div`,{children:[T(`button`,{type:`button`,onClick:f,disabled:r||!h,className:`inline-flex items-center gap-1 rounded border border-border bg-surface px-3 py-1 text-[11px] font-medium text-foreground hover:border-primary/40 hover:bg-primary/5 disabled:opacity-30 disabled:cursor-not-allowed`,children:[v(wl,{className:`h-3 w-3`}),e.addLabel??`Add`]}),!h&&Number.isFinite(l)&&T(`span`,{className:`ml-2 text-[10px] text-foreground-subtle`,children:[`(limit: `,l,`)`]})]})]})}function Dz({field:e,disabled:t,onAction:n}){let[r,i]=h(!1),a=Lf(),o=async()=>{if(!(e.confirmMessage&&!await a({title:e.label,message:e.confirmMessage,confirmLabel:e.buttonLabel,variant:e.variant===`danger`?`danger`:`default`}))&&n){i(!0);try{await n(e.action,e.key)}finally{i(!1)}}},s={default:`border border-border text-foreground hover:bg-surface-hover`,primary:`bg-primary text-primary-foreground hover:bg-primary/90`,danger:`bg-danger text-white hover:bg-danger/90`};return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,children:v(`button`,{onClick:o,disabled:t||r,className:`inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50 ${s[e.variant??`default`]??s.default}`,children:r?`Processing...`:e.buttonLabel})})}function Oz(e,t){let n={...e.paramsStatic};if(e.paramsFromForm)for(let[r,i]of Object.entries(e.paramsFromForm)){let e=t[i];e!=null&&e!==``&&(n[r]=e)}return n}function kz({field:e,value:t,values:n,onChange:r,disabled:i,onAction:a}){let[o,s]=h(!1),[l,u]=h(null),[d,f]=h(null),p=Oz(e,n),m=Object.keys(e.paramsFromForm??{}).some(e=>p[e]===void 0);c(()=>{if(!a||m){f(null),u(null);return}let t=!1;return s(!0),u(null),a(e.action,e.key,p).then(e=>{if(t)return;let n=e,r=[];if(Array.isArray(n))r=n;else if(n&&typeof n==`object`)for(let e of Object.keys(n)){let t=n[e];if(Array.isArray(t)){r=t;break}}f(r)}).catch(e=>{t||(u(e instanceof Error?e.message:String(e)),f([]))}).finally(()=>{t||s(!1)}),()=>{t=!0}},[(e.refreshOn??Object.values(e.paramsFromForm??{})).map(e=>`${e}=${JSON.stringify(n[e])}`).join(`|`),a,e.action,e.key]);let g=e.mapOption.value,_=e.mapOption.label,y=e.mapOption.description;return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,children:m?v(`div`,{className:`text-[11px] text-foreground-subtle italic`,children:e.emptyParamsMessage??`Fill the prerequisite fields above first.`}):o?T(`div`,{className:`flex items-center gap-2 text-[11px] text-foreground-subtle`,children:[v(el,{className:`h-3 w-3 animate-spin`}),` Loading options…`]}):l?v(`div`,{className:`text-[11px] text-danger`,children:l}):d&&d.length===0?v(`div`,{className:`text-[11px] text-foreground-subtle italic`,children:e.emptyResultsMessage??`No options returned.`}):(()=>{let e=(d??[]).some(e=>{let t=e[g];return t===``||t===void 0});return T(`select`,{className:`w-full rounded-md border border-border bg-surface px-2 py-1.5 text-xs text-foreground`,value:typeof t==`string`?t:``,disabled:i,onChange:e=>r(e.target.value),children:[!e&&v(`option`,{value:``,children:`— Select —`}),(d??[]).map((e,t)=>{let n=e[g],r=e[_],i=y?e[y]:void 0,a=typeof n==`string`&&n!==``?n:`row-${t}`;return T(`option`,{value:typeof n==`string`?n:String(n??``),children:[typeof r==`string`?r:String(r??a),i===void 0?``:` (${String(i)})`]},a)})]})})()})}function Az({field:e,values:t,disabled:n,onAction:r}){let[i,a]=h(!1),[o,s]=h(null),c=Lf(),l=async()=>{if(e.confirmMessage&&!await c({title:e.label,message:e.confirmMessage,confirmLabel:e.buttonLabel,variant:e.variant===`danger`?`danger`:`default`})||!r)return;let n=Oz(e,t);a(!0),s(null);try{let t=await r(e.action,e.key,n),i=typeof t==`object`&&t?t:null;s({kind:`ok`,text:e.successMessage?e.successMessage.replace(/\{(\w+)\}/g,(e,t)=>{let n=i?.[t];return n===void 0?``:String(n)}):`Done.`})}catch(e){s({kind:`error`,text:e instanceof Error?e.message:String(e)})}finally{a(!1)}},u={default:`border border-border text-foreground hover:bg-surface-hover`,primary:`bg-primary text-primary-foreground hover:bg-primary/90`,danger:`bg-danger text-white hover:bg-danger/90`};return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,children:T(`div`,{className:`flex flex-col gap-1.5`,children:[v(`button`,{onClick:l,disabled:n||i,className:`inline-flex w-fit items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50 ${u[e.variant??`default`]??u.default}`,children:i?`Working…`:e.buttonLabel}),o&&v(`div`,{className:`text-[11px] ${o.kind===`ok`?`text-emerald-700 dark:text-emerald-300`:`text-danger`}`,children:o.text})]})})}function jz({field:e,values:t,disabled:n,onAction:r}){let[i,a]=h(!1),[o,s]=h(null),c=Lf(),l=async()=>{if(e.confirmMessage&&!await c({title:e.label,message:e.confirmMessage,confirmLabel:e.buttonLabel,variant:e.variant===`danger`?`danger`:`default`})||!r)return;let n=Oz(e,t);a(!0),s(null);try{let t=await r(`device-custom-action`,e.action,n),i=typeof t==`object`&&t?t:null;s({kind:`ok`,text:e.successMessage?e.successMessage.replace(/\{(\w+)\}/g,(e,t)=>{let n=i?.[t];return n===void 0?``:String(n)}):`Done.`})}catch(e){s({kind:`error`,text:e instanceof Error?e.message:String(e)})}finally{a(!1)}},u={default:`border border-border text-foreground hover:bg-surface-hover`,primary:`bg-primary text-primary-foreground hover:bg-primary/90`,danger:`bg-danger text-white hover:bg-danger/90`};return v(QR,{label:e.label,description:e.description,required:e.required,span:e.span,children:T(`div`,{className:`flex flex-col gap-1.5`,children:[v(`button`,{onClick:l,disabled:n||i,className:`inline-flex w-fit items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50 ${u[e.variant??`default`]??u.default}`,children:i?`Working…`:e.buttonLabel}),o&&v(`div`,{className:`text-[11px] ${o.kind===`ok`?`text-emerald-700 dark:text-emerald-300`:`text-danger`}`,children:o.text})]})})}function Mz({field:e}){let t=AF();return v(QR,{label:void 0,description:void 0,span:e.span,children:v(pR,{widgetId:e.widgetId,host:`device-tab`,config:e.widgetConfig,deviceId:t??void 0,instanceId:e.key})})}function Nz(e,t){if(e==null)return`—`;if(typeof e==`boolean`)return e?`yes`:`no`;if(typeof e==`number`){let n=Number.isInteger(e)?String(e):e.toFixed(2);return t?`${n} ${t}`:n}return typeof e==`string`?e:JSON.stringify(e)}function Pz({field:e,values:t,onAction:n,translationFn:r}){let i=`key`in e?e.key:void 0;if(!i)return null;let a=t[i],o=a===void 0?`default`in e?e.default:void 0:a,s=Nz(o,`unit`in e?e.unit:void 0),c=`label`in e?e.label:void 0,l=`description`in e?e.description:void 0,u=`span`in e?e.span:void 0,d=`actions`in e?e.actions??[]:[];return v(QR,{label:c,description:l,span:u,translationFn:r,children:T(`div`,{className:`flex items-stretch gap-1`,children:[v(`div`,{className:`flex-1 rounded-md border border-border bg-surface-alt px-2.5 py-1.5 text-xs text-foreground font-mono break-all`,children:s}),d.length>0&&v(`div`,{className:`flex items-center gap-1`,children:d.map(e=>v(Iz,{action:e,fieldKey:i,value:o,onAction:n},e.action))})]})})}function Fz({name:e}){let t=`h-3.5 w-3.5`;switch(e){case`copy`:return v(vc,{className:t});case`refresh-cw`:return v(jl,{className:t});case`external-link`:return v(Oc,{className:t});case`trash-2`:return v(au,{className:t});case`download`:return v(wc,{className:t});case`upload`:return v(du,{className:t});default:return v(bu,{className:t})}}function Iz({action:e,fieldKey:t,value:n,onAction:r}){let i=Lf(),[a,o]=h(!1),s=e.variant===`danger`?`text-danger hover:bg-danger/10 border-danger/30`:e.variant===`primary`?`text-primary hover:bg-primary/10 border-primary/30`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover border-border`;return v(`button`,{type:`button`,onClick:async()=>{if(!(e.confirmMessage&&!await i({title:e.tooltip,message:e.confirmMessage,variant:e.variant===`danger`?`danger`:`default`}))){if(e.action===`copy-value`){try{await navigator.clipboard.writeText(typeof n==`string`?n:String(n))}catch{}return}if(r){o(!0);try{await r(e.action,t)}finally{o(!1)}}}},disabled:a,title:e.tooltip,className:`inline-flex items-center justify-center rounded-md border px-2 py-1.5 transition-colors disabled:opacity-50 ${s}`,children:v(Fz,{name:e.icon})})}function Lz(e){return`multiple`in e&&e.multiple!=null}function Rz({field:e,values:t,onChange:n,disabled:r,translationFn:i,onTestField:a,externalProbe:o,allFields:s,onAction:c}){let l=e.multiple,u=l.min,d=l.max,f=t[e.key],p=[...Array.isArray(f)?f:f==null?[]:[f]],m=l.itemDefault===void 0?`default`in e&&e.default!==void 0?e.default:``:l.itemDefault;for(;p.length<u;)p.push(m);let h=t=>n(e.key,[...t]),g=(e,t)=>{let n=[...p];n[e]=t,h(n)},_=()=>{p.length>=d||h([...p,m])},y=e=>{p.length<=u||h(p.filter((t,n)=>n!==e))},b=()=>{let{multiple:t,...n}=e,r={label:void 0,description:void 0,required:!1};return{...n,...r}};return v(QR,{label:e.label,description:e.description,required:u>0?e.required:!1,span:e.span,translationFn:i,children:T(`div`,{className:`space-y-2`,children:[p.map((n,o)=>{let d=l.itemLabel?.replace("${n}",String(o+1));return T(`div`,{className:`space-y-1`,children:[d&&v(`div`,{className:XR,children:d}),T(`div`,{className:`flex items-center gap-2`,children:[v(`div`,{className:`flex-1 min-w-0`,children:v(Bz,{field:b(),values:{...t,[e.key]:n},onChange:(e,t)=>g(o,t),disabled:r,translationFn:i,onTestField:a,onAction:c,allFields:s})}),p.length>u&&v(`button`,{type:`button`,onClick:()=>y(o),disabled:r,title:`Remove`,className:`flex-shrink-0 inline-flex items-center justify-center rounded-md border border-border p-1.5 text-foreground-subtle hover:text-danger hover:border-danger/50 transition-colors disabled:opacity-40`,children:v(au,{className:`h-3.5 w-3.5`})})]})]},o)}),T(`div`,{className:`flex items-center justify-between pt-1`,children:[p.length<d?T(`button`,{type:`button`,onClick:_,disabled:r,className:`inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-40`,children:[v(wl,{className:`h-3 w-3`}),l.addLabel??`Add`]}):v(`span`,{}),T(`span`,{className:`text-[10px] text-foreground-subtle tabular-nums`,children:[p.length,`/`,d]})]})]})})}function zz(e,t,n){if(!(`showWhen`in e)||!e.showWhen)return!0;let r=e.showWhen,i=t[r.field],a=n?.find(e=>`key`in e&&e.key===r.field),o=a&&`default`in a?a.default:void 0,s=i===void 0?o:i;return r.equals===void 0?r.notEquals===void 0?r.in===void 0?r.notIn===void 0?r.includes===void 0?r.notIncludes===void 0?!0:!Array.isArray(s)||!s.includes(r.notIncludes):Array.isArray(s)&&s.includes(r.includes):!r.notIn.includes(s):r.in.includes(s):s!==r.notEquals:s===r.equals}function Bz({field:e,values:t,onChange:n,disabled:r,translationFn:i,onTestField:a,externalProbe:o,allFields:s,onAction:c}){if(Lz(e))return v(Rz,{field:e,values:t,onChange:n,disabled:r,translationFn:i,onTestField:a,externalProbe:o,allFields:s,onAction:c});if(`readonlyField`in e&&e.readonlyField===!0)return v(Pz,{field:e,values:t,onAction:c,translationFn:i});if(!zz(e,t,s))return null;let l=t[e.key],u=l===void 0?`default`in e?e.default:void 0:l,d=t=>n(e.key,t),f=DF(e.type);switch(e.type){case`text`:return v($R,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`number`:return v(ez,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`boolean`:return v(tz,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`select`:return v(nz,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`multiselect`:return v(az,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`timezone`:return v(rz,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`datetime`:return v(iz,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`password`:return v(oz,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`textarea`:return v(sz,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`slider`:return v(cz,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`tags`:return v(lz,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`color`:return v(fz,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`node-select`:return v(uz,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`node-multiselect`:return v(dz,{field:e,value:u,onChange:d,disabled:r,translationFn:i});case`probe`:return v(pz,{field:e,value:u,onChange:d,disabled:r,translationFn:i,onTestField:a,onAction:c,externalProbe:o});case`group`:return v(mz,{field:e,values:t,onChange:n,disabled:r,translationFn:i,onTestField:a});case`sub-tabs`:return v(hz,{field:e,values:t,onChange:n,disabled:r,translationFn:i,onTestField:a,onAction:c});case`separator`:return v(gz,{});case`info`:return v(yz,{field:e});case`qr-code`:return v(bz,{field:e});case`object-array`:return v(Tz,{field:e});case`editable-array`:return v(Ez,{field:e,value:u,onChange:d,disabled:r,translationFn:i,onTestField:a,onAction:c});case`button`:return v(Dz,{field:e,disabled:r,onAction:c});case`addon-action-select`:return v(kz,{field:e,value:u,values:t,onChange:d,disabled:r,onAction:c});case`addon-action-button`:return v(Az,{field:e,values:t,disabled:r,onAction:c});case`device-action-button`:return v(jz,{field:e,values:t,disabled:r,onAction:c});case`widget`:return v(Mz,{field:e});default:return f?v(f,{field:e,value:u,onChange:d,disabled:r}):null}}function Vz(e){return/^[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)+$/.test(e)}function Hz(e,t){if(e!==void 0)return t&&Vz(e)?t(e):e}function Uz({section:e,values:t,onChange:n,disabled:r,translationFn:i,onTestField:a,probeResults:o}){let[s,c]=h(e.defaultCollapsed??!1),l=e.style===`accordion`,u=e.columns??2,d=u===1?`grid-cols-1`:u===3?`grid-cols-1 @[480px]:grid-cols-2 @[880px]:grid-cols-3`:u===4?`grid-cols-1 @[480px]:grid-cols-2 @[1140px]:grid-cols-4`:`grid-cols-1 @[480px]:grid-cols-2`;return T(`div`,{className:`@container rounded-lg border border-border bg-surface p-3`,style:{containerType:`inline-size`},children:[T(`div`,{className:[`flex items-center justify-between mb-2`,l?`cursor-pointer`:``].join(` `),onClick:l?()=>c(e=>!e):void 0,children:[T(`div`,{children:[v(`h3`,{className:`text-[11px] font-semibold text-foreground-subtle uppercase tracking-wider`,children:Hz(e.title,i)}),e.description&&v(`p`,{className:`text-[10px] text-foreground-subtle mt-0.5`,children:Hz(e.description,i)})]}),l&&v(`span`,{className:`text-foreground-subtle text-xs ml-2`,children:s?`▸`:`▾`})]}),!s&&v(`div`,{className:`grid ${d} gap-x-3 gap-y-2.5`,children:e.fields.map(e=>v(Bz,{field:e,values:t,onChange:n,disabled:r,translationFn:i,onTestField:a,externalProbe:o?.[e.key]},e.key))})]})}function Wz({schema:e,values:t,onChange:n,disabled:r,translationFn:i,onTestField:a,probeResults:o,onClearProbe:s}){let c=(e,r)=>{n({...t,[e]:r}),s?.(e)};return v(`div`,{className:`space-y-4`,children:e.sections.map(e=>v(Uz,{section:e,values:t,onChange:c,disabled:r,translationFn:i,onTestField:a,probeResults:o},e.id))})}var Gz=({open:e})=>v(`svg`,{className:`h-3 w-3 transition-transform ${e?`rotate-90`:``}`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":!0,children:v(`polyline`,{points:`9 18 15 12 9 6`})});function Kz(e){let t={};if(!e)return t;for(let n of e.sections)for(let e of n.fields){if(e.type===`separator`||e.type===`info`||e.type===`button`||e.type===`group`)continue;let n=e.key;t[n]=e.value}return t}function qz(e){return{...e,sections:e.sections.map(e=>({...e,fields:e.fields.map(e=>{if(e.type===`separator`||e.type===`info`||e.type===`button`||e.type===`group`)return e;let{value:t,...n}=e;return n})}))}}function Jz({trpc:e,addonId:t,nodeId:n,title:r,disabled:i,onAfterChange:a,refreshToken:s,collapsible:l,defaultOpen:u,mode:d,onOverrideChange:f}){let p=d??`persist`,[m,g]=h(null),[_,y]=h(!0),[b,x]=h(null),[S,C]=h(!1),[w,D]=h(u??!1),[O,k]=h({}),[A,j]=h(null);c(()=>{j(null),k({})},[e,t,n,s,p]),c(()=>{let r=!1;y(!0),x(null);let i=p===`override`&&Object.keys(O).length>0?O:void 0;return e.addonSettings.getGlobalSettings.query({addonId:t,nodeId:n,...i?{overlay:i}:{}}).then(e=>{r||(g(e),i||j(Kz(e)),y(!1))}).catch(e=>{r||(x(e instanceof Error?e.message:String(e)),y(!1))}),()=>{r=!0}},[e,t,n,s,p,JSON.stringify(O)]);let M=o(()=>Kz(m),[m]),N=o(()=>m?qz(m):null,[m]),P=async r=>{if(p===`override`){let e=A??M,t={};for(let n of Object.keys(r))r[n]!==e[n]&&(t[n]=r[n]);let n={...e,...t};k(t),f?.(t,n);return}let i={};for(let e of Object.keys(r))r[e]!==M[e]&&(i[e]=r[e]);if(Object.keys(i).length!==0){C(!0);try{await e.addonSettings.updateGlobalSettings.mutate({addonId:t,nodeId:n,patch:i}),g(await e.addonSettings.getGlobalSettings.query({addonId:t,nodeId:n})),a?.()}catch(e){x(e instanceof Error?e.message:String(e))}finally{C(!1)}}};if(_)return T(`div`,{className:`text-xs text-foreground-subtle animate-pulse`,children:[`Loading `,r??t,`…`]});if(b)return T(`div`,{className:`text-xs text-red-400`,children:[r??t,`: `,b]});if(!m||!N)return T(`div`,{className:`text-xs text-foreground-subtle`,children:[r??t,` not available on `,n,`.`]});let ee=p===`override`?{...M,...O}:M,F=T(E,{children:[p===`override`?v(`div`,{className:`mb-2 text-[11px] text-foreground-subtle`,children:`Benchmark override — applies to this run only. The addon's saved settings are not changed.`}):null,v(Wz,{schema:N,values:ee,onChange:P,disabled:i===!0||S})]});return l===!0?T(`section`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[T(`button`,{type:`button`,onClick:()=>D(e=>!e),className:`w-full px-4 py-2 flex items-center gap-2 hover:bg-surface-hover text-left`,"aria-expanded":w,children:[v(Gz,{open:w}),v(`h3`,{className:`text-xs font-semibold text-foreground uppercase tracking-wide flex-1`,children:r??t}),v(`span`,{className:`text-[10px] text-foreground-subtle`,children:w?`hide`:`edit`})]}),w?v(`div`,{className:`border-t border-border px-4 py-3`,children:F}):null]}):r?T(`section`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[v(`div`,{className:`border-b border-border px-4 py-2`,children:v(`h3`,{className:`text-xs font-semibold text-foreground uppercase tracking-wide`,children:r})}),v(`div`,{className:`px-4 py-3`,children:F})]}):v(`div`,{children:F})}function Yz({detections:{motion:e,motionRaw:t,detection:n,phase:r},showMotionZones:i=!0,showMotionRaw:a=!0,showDetections:o=!0,showPhaseIndicator:s=!0}){let c=i&&e&&e.zones.length>0,l=a&&t&&t.boxes.length>0,u=o&&n&&n.detections.length>0;return!c&&!l&&!u&&!s?null:T(`div`,{className:`absolute inset-0 pointer-events-none z-10`,children:[s&&v(Xz,{phase:r}),l&&v(Zz,{raw:t}),c&&v(Qz,{motion:e}),u&&v($z,{detections:n.detections,frameWidth:n.frameWidth,frameHeight:n.frameHeight})]})}function Xz({phase:e}){let t=mr(e);return T(`div`,{className:`absolute top-2 left-2 flex items-center gap-1.5 px-2 py-1 rounded-md bg-black/60 backdrop-blur-sm`,children:[v(`span`,{className:`w-2 h-2 rounded-full ${t.dotClass}`}),v(`span`,{className:`text-[10px] font-semibold text-white uppercase tracking-wider`,children:t.label})]})}function Zz({raw:e}){return e.frameWidth===0||e.frameHeight===0?null:v(E,{children:e.boxes.map((t,n)=>{let[r,i,a,o]=t.bbox,s=r/e.frameWidth*100,c=i/e.frameHeight*100,l=(a-r)/e.frameWidth*100,u=(o-i)/e.frameHeight*100,d=Math.max(.05,Math.min(.25,t.changeScore*.3));return v(`div`,{className:`absolute rounded-sm`,style:{left:`${s}%`,top:`${c}%`,width:`${l}%`,height:`${u}%`,backgroundColor:`rgba(239, 68, 68, ${d})`}},`mr-${n}`)})})}function Qz({motion:e}){return e.frameWidth===0||e.frameHeight===0?null:v(E,{children:e.zones.filter(t=>t.w*t.h/(e.frameWidth*e.frameHeight)<.9).map((t,n)=>{let r=Math.max(.15,Math.min(.5,t.intensity/255));return v(`div`,{className:`absolute rounded-sm`,style:{left:`${t.x/e.frameWidth*100}%`,top:`${t.y/e.frameHeight*100}%`,width:`${t.w/e.frameWidth*100}%`,height:`${t.h/e.frameHeight*100}%`,border:`1px solid rgba(250, 204, 21, ${r})`,backgroundColor:`rgba(250, 204, 21, ${r*.15})`}},`mz-${n}`)})})}function $z({detections:e,frameWidth:t,frameHeight:n}){return t===0||n===0?null:v(E,{children:e.map(e=>{let{x:r,y:i,width:a,height:o}=e.bbox,s=r/t*100,c=i/n*100,l=a/t*100,u=o/n*100,d=VN(e.macroClass),f=[`${e.macroClass} ${(e.score*100).toFixed(0)}%`];for(let t of e.labels)f.push(t.label);return v(`div`,{className:`absolute border-2 rounded-sm`,style:{left:`${s}%`,top:`${c}%`,width:`${l}%`,height:`${u}%`,borderColor:d},children:v(`div`,{className:`absolute -top-4 left-0 px-1 py-0.5 text-[9px] font-bold text-white rounded-sm whitespace-nowrap`,style:{backgroundColor:d},children:f.join(` | `)})},`det-${e.id}`)})})}function eB(){return typeof window>`u`?!1:window.matchMedia(`(hover: none) and (pointer: coarse)`).matches||typeof navigator<`u`&&navigator.maxTouchPoints>0||`ontouchstart`in window}function tB(e,t,n){let r=0;for(let i=0;i<8;i++)for(let a=0;a<8;a++){let o=Math.min(t-1,Math.floor((a+.5)/8*t)),s=Math.min(n-1,Math.floor((i+.5)/8*n)),{data:c}=e.getImageData(o,s,1,1);.2126*(c[0]??0)+.7152*(c[1]??0)+.0722*(c[2]??0)>12&&r++}return r<=1}function nB(e){let t={};if(typeof window<`u`){if(e){let n=e.getBoundingClientRect();n.width>0&&n.height>0&&(t.viewportWidth=Math.round(n.width),t.viewportHeight=Math.round(n.height))}t.viewportWidth===void 0&&(t.viewportWidth=window.innerWidth,t.viewportHeight=window.innerHeight),t.devicePixelRatio=window.devicePixelRatio||1;let n=navigator.connection;n?.downlink&&n.downlink>0&&(t.downlinkMbps=n.downlink)}return t}var rB=1500,iB=15e3,aB=40;function oB({serverUrl:e,streamKey:t,label:n,autoPlay:r=!0,muted:i=!0,showControls:a=!0,showStats:o=!1,onPlaybackStats:s,className:l=``,onStateChange:d,onError:f,overlay:m,createSession:g,sendAnswer:_,handleOffer:y,getIceServers:b,addIceCandidate:x,getIceCandidates:S,closeSession:C,getSessionState:w,reoffer:E,posterUrl:D,hintsOverride:O,reconnectSignal:k,onControlChannel:A}){let j=p(null),M=p(null),N=p(null),P=p(new Set),ee=p(null),F=p(null),te=p(0),I=p(!0),L=p(A);L.current=A;let ne=p(null),R=p(null),re=p(0),ie=p(!1),ae=p(async()=>{}),[z,oe]=h(`idle`),[se,ce]=h(``),[le,ue]=h(i),[de,fe]=h(!1),[pe,me]=h(!1),he=eB(),[B,ge]=h(!0),_e=p(null),V=p(!1);(_||g)&&(V.current=!0);let ve=V.current,ye=p(!1);y&&(ye.current=!0);let be=ye.current,[xe,Se]=h(!1),Ce=p(null),[we,Te]=h(null),[Ee,De]=h(!1),Oe=u(()=>{let e=j.current;if(!(!e||e.readyState<2||!e.videoWidth||!e.videoHeight))try{let t=document.createElement(`canvas`);t.width=e.videoWidth,t.height=e.videoHeight;let n=t.getContext(`2d`);if(!n||(n.drawImage(e,0,0),tB(n,t.width,t.height)))return;Ce.current=t.toDataURL(`image/jpeg`,.6)}catch{}},[]),H=u(e=>{oe(e),e===`playing`&&Se(!0),d?.(e)},[d]),ke=u(()=>{if(ee.current?.abort(),ee.current=null,F.current&&=(clearTimeout(F.current),null),R.current&&=(clearTimeout(R.current),null),ne.current=null,ie.current=!1,re.current=0,N.current&&=(N.current.close(),null),C&&P.current.size>0){for(let e of P.current)C(e).catch(()=>{});P.current.clear()}},[C]),Ae=u(()=>{ee.current?.abort(),ee.current=null,F.current&&=(clearTimeout(F.current),null),R.current&&=(clearTimeout(R.current),null),ne.current=null,ie.current=!1,re.current=0},[]),je=1e3,Me=u(e=>{if(!w||!E)return;R.current&&=(clearTimeout(R.current),null);let t=async()=>{if(I.current&&ne.current===e){if(!ie.current)try{let{pendingRenegotiation:t}=await w(e);if(I.current&&ne.current===e&&t&&t.epoch>re.current&&!ie.current){re.current=t.epoch,await ae.current(e,t.target);return}}catch{}!I.current||ne.current!==e||(R.current=setTimeout(()=>{t()},je))}};R.current=setTimeout(()=>{t()},je)},[w,E]),Ne=u(async(e=!1)=>{if(!I.current||!g||!_)return;let t=e?N.current:null,n=e?new Set(P.current):null;e?Ae():ke(),H(`connecting`);let r=new AbortController;ee.current=r;try{let{sessionId:i,sdpOffer:a,iceServers:o}=await g({...nB(M.current),...O});if(P.current.add(i),!I.current||r.signal.aborted){C?.(i).catch(()=>{}),P.current.delete(i);return}let s=new RTCPeerConnection({iceServers:[...o??[],{urls:`stun:stun.l.google.com:19302`}]});e||(N.current=s);let c=new MediaStream,l=!1,u=()=>{if(!(l||!I.current)){if(l=!0,N.current=s,j.current&&(j.current.srcObject=c,j.current.play().catch(()=>{})),t&&t!==s)try{t.close()}catch{}if(n)for(let e of n)P.current.delete(e),C?.(e).catch(()=>{})}};s.ontrack=t=>{if(console.debug(`[WebRTC] ontrack`,t.track.kind,t.track.readyState),c.addTrack(t.track),e){u();return}j.current&&(j.current.srcObject=c,j.current.play().catch(()=>{}))},s.oniceconnectionstatechange=()=>{if(!I.current)return;let t=s.iceConnectionState;if(console.debug(`[WebRTC] ICE state:`,t),t===`connected`||t===`completed`)te.current=0,e&&u(),H(`playing`),j.current?.paused&&(console.debug(`[WebRTC] video was paused at ICE connected — calling play()`),j.current.play().catch(()=>{}));else if(t===`failed`||t===`disconnected`||t===`closed`){if(e&&!l)try{s.close()}catch{}H(`disconnected`),Re()}},s.onicecandidateerror=e=>{console.debug(`[WebRTC] ICE candidate error:`,e)},console.debug(`[WebRTC] Setting remote description (server offer)...`),await s.setRemoteDescription({type:`offer`,sdp:a});let d=await s.createAnswer();if(await s.setLocalDescription(d),console.debug(`[WebRTC] Local description set, waiting for ICE gathering...`),await cB(s),!I.current)return;let f=(s.localDescription?.sdp??``).split(`
34
- `).filter(e=>e.startsWith(`a=candidate:`)).length;console.debug(`[WebRTC] Sending answer to server`,{localCandidates:f,sessionId:i.slice(0,8)}),await _(i,s.localDescription?.sdp??``),console.debug(`[WebRTC] Answer sent successfully`);let p=s,m=()=>{let e=p.connectionState;if(e===`closed`||e===`failed`)return;let t=j.current;t&&t.readyState===0&&console.log(`[WebRTC] no video data yet (ice=${p.iceConnectionState})`)};setTimeout(m,3e3),setTimeout(m,8e3)}catch(e){if(!I.current)return;let t=e instanceof Error?e.message:String(e);ce(t),H(`error`),f?.(t),Re()}},[e,t,g,_,ke,Ae,C,H,f,O]),Pe=u(async()=>{if(I.current){ke(),H(`connecting`);try{let n=new RTCPeerConnection({iceServers:[{urls:`stun:stun.l.google.com:19302`}]});N.current=n,n.addTransceiver(`video`,{direction:`recvonly`}),n.addTransceiver(`audio`,{direction:`recvonly`});let r=new MediaStream;n.ontrack=e=>{r.addTrack(e.track),j.current&&(j.current.srcObject=r,j.current.play().catch(()=>{}))},n.oniceconnectionstatechange=()=>{if(!I.current)return;let e=n.iceConnectionState;e===`connected`||e===`completed`?(te.current=0,H(`playing`),j.current?.paused&&j.current.play().catch(()=>{})):(e===`failed`||e===`disconnected`||e===`closed`)&&(H(`disconnected`),Re())};let i=await n.createOffer();if(await n.setLocalDescription(i),await cB(n),!I.current)return;let a=`${e}/api/webrtc?src=${encodeURIComponent(t)}`,o=await fetch(a,{method:`POST`,headers:{"Content-Type":`application/sdp`},body:n.localDescription?.sdp??``});if(!o.ok)throw Error(`WHEP ${o.status}: ${o.statusText}`);let s=await o.text();await n.setRemoteDescription({type:`answer`,sdp:s})}catch(e){if(!I.current)return;let t=e instanceof Error?e.message:String(e);ce(t),H(`error`),f?.(t),Re()}}},[e,t,ke,H,f]),Fe=u(async(e=!1)=>{if(!I.current||!y)return;let t=e?N.current:null,n=e?new Set(P.current):null;e?Ae():ke(),H(`connecting`);let r=new AbortController;ee.current=r;try{let i=await b?.();if(!I.current||r.signal.aborted)return;let a=new RTCPeerConnection({iceServers:[...i??[],{urls:`stun:stun.l.google.com:19302`}]});e||(N.current=a);let o=new MediaStream,s=!1,c=()=>{if(!(s||!I.current)){if(s=!0,N.current=a,j.current&&(j.current.srcObject=o,j.current.play().catch(()=>{})),t&&t!==a)try{t.close()}catch{}if(n)for(let e of n)P.current.delete(e),C?.(e).catch(()=>{})}};a.ontrack=t=>{if(console.debug(`[WebRTC] ontrack (client-offer)`,t.track.kind,t.track.readyState),o.addTrack(t.track),e){c();return}j.current&&(j.current.srcObject=o,j.current.play().catch(()=>{}))},a.oniceconnectionstatechange=()=>{if(!I.current)return;let t=a.iceConnectionState;if(console.debug(`[WebRTC] ICE state (client-offer):`,t),t===`connected`||t===`completed`)te.current=0,e&&c(),H(`playing`),j.current?.paused&&j.current.play().catch(()=>{});else if(t===`failed`||t===`disconnected`||t===`closed`){if(e&&!s)try{a.close()}catch{}H(`disconnected`),Re()}};let l=null,u=[];if(a.onicecandidate=e=>{if(!e.candidate)return;let t=e.candidate.toJSON();l&&x?x(l,t).catch(()=>{}):u.push(t)},a.addTransceiver(`video`,{direction:`recvonly`}),a.addTransceiver(`audio`,{direction:`recvonly`}),L.current){let e=a.createDataChannel(`camstack-control`);L.current(e)}let d=await a.createOffer();if(await a.setLocalDescription(d),!I.current||r.signal.aborted)return;let{sessionId:f,sdpAnswer:p}=await y(a.localDescription?.sdp??d.sdp??``);if(l=f,P.current.add(f),ne.current=f,!I.current||r.signal.aborted){C?.(f).catch(()=>{}),P.current.delete(f);return}if(x)for(let e of u)x(f,e).catch(()=>{});if(u.length=0,await a.setRemoteDescription({type:`answer`,sdp:p}),console.debug(`[WebRTC] Client-offer answer set (trickle)`,{sessionId:f.slice(0,8)}),S){let e=new Set,t=Date.now(),n=async()=>{if(!(!I.current||r.signal.aborted)&&!(a.connectionState===`closed`||a.signalingState===`closed`)){try{let{candidates:n,done:r}=await S(f);for(let t of n){let n=t.candidate??``;n&&!e.has(n)&&(e.add(n),a.addIceCandidate(new RTCIceCandidate(t)).catch(()=>{}))}let i=a.iceConnectionState;if(r||Date.now()-t>1e4||i===`connected`||i===`completed`)return}catch{}setTimeout(()=>{n()},200)}};n()}Me(f)}catch(e){if(!I.current)return;let t=e instanceof Error?e.message:String(e);ce(t),H(`error`),f?.(t),Re()}},[y,b,x,S,C,ke,Ae,H,f,Me]);ae.current=u(async(e,t)=>{let n=E;if(!I.current||!n)return;let r=N.current;ie.current=!0;try{let i=await b?.();if(!I.current)return;let a=new RTCPeerConnection({iceServers:[...i??[],{urls:`stun:stun.l.google.com:19302`}]}),o=new MediaStream,s=!1,c=()=>{s||!I.current||(s=!0,N.current=a,j.current&&(j.current.srcObject=o,j.current.play().catch(()=>{})),r&&r!==a&&r.close())};a.ontrack=e=>{console.debug(`[WebRTC] ontrack (reoffer)`,e.track.kind,e.track.readyState),o.addTrack(e.track),c()},a.oniceconnectionstatechange=()=>{if(!I.current)return;let e=a.iceConnectionState;console.debug(`[WebRTC] ICE state (reoffer):`,e),e===`connected`||e===`completed`?(te.current=0,c(),H(`playing`),j.current?.paused&&j.current.play().catch(()=>{})):(e===`failed`||e===`closed`)&&(!s&&e===`failed`&&a.close(),H(`disconnected`),Re())};let l=null,u=[];if(a.onicecandidate=e=>{if(!e.candidate)return;let t=e.candidate.toJSON();l&&x?x(l,t).catch(()=>{}):u.push(t)},a.addTransceiver(`video`,{direction:`recvonly`}),a.addTransceiver(`audio`,{direction:`recvonly`}),L.current){let e=a.createDataChannel(`camstack-control`);L.current(e)}let d=await a.createOffer();if(await a.setLocalDescription(d),!I.current){a.close();return}let{sessionId:f,sdpAnswer:p}=await n(e,a.localDescription?.sdp??d.sdp??``,t);if(!I.current){a.close();return}if(l=f,P.current.add(f),ne.current=f,x)for(let e of u)x(f,e).catch(()=>{});if(u.length=0,await a.setRemoteDescription({type:`answer`,sdp:p}),S){let e=new Set,t=Date.now(),n=async()=>{if(I.current&&!(a.connectionState===`closed`||a.signalingState===`closed`)){try{let{candidates:n,done:r}=await S(f);for(let t of n){let n=t.candidate??``;n&&!e.has(n)&&(e.add(n),a.addIceCandidate(new RTCIceCandidate(t)).catch(()=>{}))}let i=a.iceConnectionState;if(r||Date.now()-t>1e4||i===`connected`||i===`completed`)return}catch{}setTimeout(()=>{n()},200)}};n()}Me(f)}catch(t){console.debug(`[WebRTC] reoffer failed; keeping last frame, re-arming poll`,t instanceof Error?t.message:String(t)),Me(e)}finally{ie.current=!1}},[E,b,x,S,H,Me]);let Ie=be?Fe:ve?Ne:Pe,Le=p(()=>{});Le.current=Ie;let Re=u(()=>{if(!I.current||te.current>=aB)return;let e=te.current;te.current+=1;let t=Math.min(iB,rB*2**e),n=Math.round(t*(.8+Math.random()*.4));F.current=setTimeout(()=>{I.current&&Le.current()},n)},[]);c(()=>(I.current=!0,te.current=0,r&&Ie(),()=>{I.current=!1,ke()}),[e,t]);let ze=p(!1);c(()=>{if(r){if(be){if(!y)return}else if(ve){if(!g||!_)return}else return;ze.current||N.current||(ze.current=!0,Ie())}},[r,be,ve,y,g,_,Ie]);let Be=()=>{te.current=0,Ie()},Ve=()=>{if(te.current=0,N.current&&be){Fe(!0);return}if(N.current&&ve){Ne(!0);return}Ie()},He=p(k);c(()=>{He.current!==k&&(He.current=k,I.current&&Ve())},[k]);let Ue=()=>{j.current&&(j.current.muted=!j.current.muted,ue(j.current.muted))},We=async()=>{if(M.current)try{if(document.fullscreenElement){await document.exitFullscreen();return}if(M.current.requestFullscreen){await M.current.requestFullscreen();return}let e=j.current;e?.webkitEnterFullscreen&&e.webkitEnterFullscreen()}catch(e){console.warn(`Fullscreen toggle failed: ${e instanceof Error?e.message:e}`)}},Ge=async()=>{let e=j.current;if(e)try{if(typeof e.webkitSetPresentationMode==`function`){e.webkitSetPresentationMode(e.webkitPresentationMode===`picture-in-picture`?`inline`:`picture-in-picture`);return}document.pictureInPictureElement?await document.exitPictureInPicture():await e.requestPictureInPicture()}catch(e){console.warn(`PiP toggle failed: ${e instanceof Error?e.message:String(e)}`)}},Ke=()=>{if(!j.current)return;let e=document.createElement(`canvas`);e.width=j.current.videoWidth||1280,e.height=j.current.videoHeight||720;let n=e.getContext(`2d`);if(!n)return;n.drawImage(j.current,0,0);let r=document.createElement(`a`);r.download=`${t.replace(/[/:]/g,`-`)}-${Date.now()}.jpg`,r.href=e.toDataURL(`image/jpeg`,.92),r.click()};c(()=>{let e=()=>fe(!!document.fullscreenElement);document.addEventListener(`fullscreenchange`,e);let t=j.current;return t?.addEventListener(`webkitbeginfullscreen`,e),t?.addEventListener(`webkitendfullscreen`,e),()=>{document.removeEventListener(`fullscreenchange`,e),t?.removeEventListener(`webkitbeginfullscreen`,e),t?.removeEventListener(`webkitendfullscreen`,e)}},[]),c(()=>{let e=j.current,t=typeof document<`u`&&document.pictureInPictureEnabled===!0,n=e!==null&&typeof e.webkitSetPresentationMode==`function`;me(t||n)},[]);let[qe,Je]=h(``),Ye=p(null);c(()=>{if(!o){Je(``),Ye.current=null;return}let e=async()=>{let e=N.current;if(e)try{let t=await e.getStats(),n=0,r=0,i=0,a=0,o=0,s=0;t.forEach(e=>{let t=e;t.type===`inbound-rtp`&&(t.kind??t.mediaType)===`video`?(n=t.bytesReceived??0,r=t.timestamp,i=t.framesPerSecond??0,a=t.frameWidth??0,o=t.frameHeight??0):t.type===`candidate-pair`&&t.nominated&&typeof t.currentRoundTripTime==`number`&&(s=t.currentRoundTripTime)});let c=0;Ye.current&&r>Ye.current.ts&&(c=Math.round((n-Ye.current.bytes)*8/(r-Ye.current.ts))),Ye.current={bytes:n,ts:r};let l=[];a&&o&&l.push(`${a}×${o}`),i&&l.push(`${Math.round(i)}fps`),c>0&&l.push(`${c} kbps`),s&&l.push(`${Math.round(s*1e3)}ms`),Je(l.join(` · `))}catch{}};e();let t=setInterval(()=>{e()},1e3);return()=>clearInterval(t)},[o]);let Xe=p(null);c(()=>{if(!s){Xe.current=null;return}let e=async()=>{let e=N.current,t=j.current;if(e)try{let n=await e.getStats(),r=0,i=0,a=0,o=0,c=0,l=0,u=0,d=0;n.forEach(e=>{let t=e;t.type===`inbound-rtp`&&(t.kind??t.mediaType)===`video`&&(r=t.framesReceived??0,i=t.framesDecoded??0,a=t.framesDropped??0,o=t.framesPerSecond??0,c=t.freezeCount??0,l=t.totalFreezesDuration??0,u=t.jitterBufferDelay??0,d=t.jitterBufferEmittedCount??0)});let f=t?.currentTime??0,p=Date.now(),m=Xe.current,h=d>0?Math.round(u/d*1e3):0;m&&s({dRecv:r-m.recv,dDec:i-m.dec,dDrop:a-m.drop,fps:Math.round(o),dFreeze:c-m.freeze,freezeTotalMs:Math.round(l*1e3),avgJitterMs:h,dCtMs:Math.round((f-m.ct)*1e3),dtMs:p-m.ts,readyState:t?.readyState??-1}),Xe.current={recv:r,dec:i,drop:a,freeze:c,ct:f,ts:p}}catch{}};e();let t=setInterval(()=>{e()},1e3);return()=>clearInterval(t)},[s]),c(()=>{ue(i);let e=j.current;e&&(e.muted=i,i||e.play().catch(()=>{}))},[i]);let Ze=()=>{he||(ge(!0),_e.current&&clearTimeout(_e.current),_e.current=setTimeout(()=>ge(!1),3e3))},Qe=()=>{ge(e=>!e),_e.current&&clearTimeout(_e.current)};c(()=>{if(z===`playing`){Oe();let e=setInterval(Oe,2e3);return()=>clearInterval(e)}xe&&Ce.current&&Te(Ce.current)},[z,xe,Oe]),c(()=>{if(z!==`playing`){De(!1);return}let e=j.current;if(!e)return;let t=!1,n=()=>{t||De(!0)},r;typeof e.requestVideoFrameCallback==`function`&&(r=e.requestVideoFrameCallback(()=>n())),e.addEventListener(`loadeddata`,n,{once:!0});let i=setTimeout(n,12e3);return()=>{t=!0,clearTimeout(i),r!==void 0&&typeof e.cancelVideoFrameCallback==`function`&&e.cancelVideoFrameCallback(r),e.removeEventListener(`loadeddata`,n)}},[z]);let $e=xe&&we?we:D??null,et=!Ee&&$e!==null;return T(`div`,{ref:M,className:`relative isolate bg-black overflow-hidden group ${l}`,onMouseMove:Ze,onMouseEnter:Ze,onTouchStart:Qe,children:[v(`video`,{ref:j,autoPlay:r,muted:le,playsInline:!0,className:`w-full h-full object-contain relative z-0`}),et&&$e&&v(`img`,{src:$e,alt:``,className:`absolute inset-0 w-full h-full object-contain z-[5] transform-gpu pointer-events-none`}),n&&z===`playing`&&v(`div`,{className:`absolute top-2 left-2 z-10 transform-gpu px-2 py-0.5 rounded bg-black/60 text-[10px] text-white font-medium`,children:n}),o&&qe&&v(`div`,{className:`absolute top-2 right-2 z-10 transform-gpu px-2 py-0.5 rounded bg-black/60 text-[10px] text-white font-mono`,children:qe}),m,!$e&&z===`connecting`&&T(`div`,{className:`absolute inset-0 z-10 transform-gpu flex flex-col items-center justify-center bg-black/70 gap-2`,children:[v(`svg`,{className:`h-6 w-6 text-white/60 animate-spin`,viewBox:`0 0 24 24`,fill:`none`,children:v(`circle`,{cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,strokeDasharray:`32`,strokeDashoffset:`32`,className:`animate-[dash_1.5s_ease-in-out_infinite]`})}),v(`span`,{className:`text-xs text-white/60`,children:`Connecting…`})]}),!$e&&(z===`error`||z===`disconnected`)&&T(`div`,{className:`absolute inset-0 z-10 transform-gpu flex flex-col items-center justify-center bg-black/70 gap-2`,children:[v(`svg`,{className:`h-6 w-6 text-red-400`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,children:v(`path`,{d:`M1 1l5.5 5.5M23 23l-5.5-5.5M8.11 15.89a8 8 0 0110.78-10.78M3.64 3.64A12 12 0 0020.36 20.36`,strokeLinecap:`round`})}),v(`span`,{className:`text-xs text-red-400 text-center px-4`,children:z===`error`?se||`Connection failed`:`Disconnected`}),v(`button`,{onClick:Be,className:`mt-1 inline-flex items-center gap-1.5 rounded px-3 py-1 text-xs bg-white/10 text-white hover:bg-white/20 transition-colors`,children:`Reconnect`})]}),$e&&(z===`connecting`||z===`disconnected`)&&v(`div`,{className:`absolute top-2 left-2 z-10 transform-gpu flex h-6 w-6 items-center justify-center rounded-full bg-black/55`,children:v(`svg`,{className:`h-3.5 w-3.5 text-white/90 animate-spin`,viewBox:`0 0 24 24`,fill:`none`,children:v(`circle`,{cx:`12`,cy:`12`,r:`10`,stroke:`currentColor`,strokeWidth:`3`,strokeLinecap:`round`,strokeDasharray:`32`,strokeDashoffset:`32`,className:`animate-[dash_1.5s_ease-in-out_infinite]`})})}),$e&&z===`error`&&v(`button`,{onClick:Be,title:se||`Reconnect`,className:`absolute top-2 left-2 z-10 transform-gpu flex h-6 w-6 items-center justify-center rounded-full bg-black/55 text-white/90 hover:bg-black/75 transition-colors`,children:T(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[v(`path`,{d:`M23 4v6h-6M1 20v-6h6`}),v(`path`,{d:`M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15`})]})}),a&&z!==`idle`&&z!==`error`&&T(`div`,{className:`absolute bottom-0 inset-x-0 z-20 transform-gpu flex items-center justify-between px-3 py-1.5 bg-gradient-to-t from-black/80 to-transparent transition-opacity duration-200 ${he||B?`opacity-100 pointer-events-auto`:`opacity-0 pointer-events-none`}`,children:[v(`div`,{className:`flex items-center gap-1`,children:v(sB,{onClick:Ue,title:le?`Unmute`:`Mute`,children:le?T(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[v(`polygon`,{points:`11 5 6 9 2 9 2 15 6 15 11 19 11 5`}),v(`line`,{x1:`23`,y1:`9`,x2:`17`,y2:`15`}),v(`line`,{x1:`17`,y1:`9`,x2:`23`,y2:`15`})]}):T(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[v(`polygon`,{points:`11 5 6 9 2 9 2 15 6 15 11 19 11 5`}),v(`path`,{d:`M19.07 4.93a10 10 0 010 14.14M15.54 8.46a5 5 0 010 7.07`})]})})}),T(`div`,{className:`flex items-center gap-1`,children:[v(sB,{onClick:Ke,title:`Take snapshot`,children:T(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:[v(`path`,{d:`M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z`}),v(`circle`,{cx:`12`,cy:`13`,r:`4`})]})}),pe&&v(sB,{onClick:Ge,title:`Picture-in-Picture`,children:T(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[v(`path`,{d:`M21 9V6a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2h4`}),v(`rect`,{width:`10`,height:`7`,x:`12`,y:`13`,rx:`2`})]})}),v(sB,{onClick:We,title:de?`Exit fullscreen`:`Fullscreen`,children:de?v(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:v(`path`,{d:`M8 3v3a2 2 0 01-2 2H3m18 0h-3a2 2 0 01-2-2V3m0 18v-3a2 2 0 012-2h3M3 16h3a2 2 0 012 2v3`})}):v(`svg`,{className:`h-3.5 w-3.5`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,children:v(`path`,{d:`M8 3H5a2 2 0 00-2 2v3m18 0V5a2 2 0 00-2-2h-3m0 18h3a2 2 0 002-2v-3M3 16v3a2 2 0 002 2h3`})})})]})]})]})}function sB({onClick:e,title:t,children:n}){return v(`button`,{onClick:e,title:t,className:`rounded-full p-1.5 min-w-[44px] min-h-[44px] flex items-center justify-center text-white/80 hover:text-white hover:bg-white/20 active:bg-white/30 transition-colors`,children:n})}async function cB(e){if(e.iceGatheringState!==`complete`)return new Promise(t=>{let n=!1,r,i=()=>{n||(n=!0,r&&clearInterval(r),e.removeEventListener(`icegatheringstatechange`,a),t())},a=()=>{e.iceGatheringState===`complete`&&i()};e.addEventListener(`icegatheringstatechange`,a);let o=Date.now();r=setInterval(()=>{let t=e.localDescription?.sdp??``;/ typ host/.test(t)&&Date.now()-o>=600&&i()},100),setTimeout(i,2500)})}var J=Number.isFinite||function(e){return typeof e==`number`&&isFinite(e)},lB=Number.isSafeInteger||function(e){return typeof e==`number`&&Math.abs(e)<=uB},uB=2**53-1||9007199254740991,Y=function(e){return e.NETWORK_ERROR=`networkError`,e.MEDIA_ERROR=`mediaError`,e.KEY_SYSTEM_ERROR=`keySystemError`,e.MUX_ERROR=`muxError`,e.OTHER_ERROR=`otherError`,e}({}),X=function(e){return e.KEY_SYSTEM_NO_KEYS=`keySystemNoKeys`,e.KEY_SYSTEM_NO_ACCESS=`keySystemNoAccess`,e.KEY_SYSTEM_NO_SESSION=`keySystemNoSession`,e.KEY_SYSTEM_NO_CONFIGURED_LICENSE=`keySystemNoConfiguredLicense`,e.KEY_SYSTEM_LICENSE_REQUEST_FAILED=`keySystemLicenseRequestFailed`,e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED=`keySystemServerCertificateRequestFailed`,e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED=`keySystemServerCertificateUpdateFailed`,e.KEY_SYSTEM_SESSION_UPDATE_FAILED=`keySystemSessionUpdateFailed`,e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED=`keySystemStatusOutputRestricted`,e.KEY_SYSTEM_STATUS_INTERNAL_ERROR=`keySystemStatusInternalError`,e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR=`keySystemDestroyMediaKeysError`,e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR=`keySystemDestroyCloseSessionError`,e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR=`keySystemDestroyRemoveSessionError`,e.MANIFEST_LOAD_ERROR=`manifestLoadError`,e.MANIFEST_LOAD_TIMEOUT=`manifestLoadTimeOut`,e.MANIFEST_PARSING_ERROR=`manifestParsingError`,e.MANIFEST_INCOMPATIBLE_CODECS_ERROR=`manifestIncompatibleCodecsError`,e.LEVEL_EMPTY_ERROR=`levelEmptyError`,e.LEVEL_LOAD_ERROR=`levelLoadError`,e.LEVEL_LOAD_TIMEOUT=`levelLoadTimeOut`,e.LEVEL_PARSING_ERROR=`levelParsingError`,e.LEVEL_SWITCH_ERROR=`levelSwitchError`,e.AUDIO_TRACK_LOAD_ERROR=`audioTrackLoadError`,e.AUDIO_TRACK_LOAD_TIMEOUT=`audioTrackLoadTimeOut`,e.SUBTITLE_LOAD_ERROR=`subtitleTrackLoadError`,e.SUBTITLE_TRACK_LOAD_TIMEOUT=`subtitleTrackLoadTimeOut`,e.FRAG_LOAD_ERROR=`fragLoadError`,e.FRAG_LOAD_TIMEOUT=`fragLoadTimeOut`,e.FRAG_DECRYPT_ERROR=`fragDecryptError`,e.FRAG_PARSING_ERROR=`fragParsingError`,e.FRAG_GAP=`fragGap`,e.REMUX_ALLOC_ERROR=`remuxAllocError`,e.KEY_LOAD_ERROR=`keyLoadError`,e.KEY_LOAD_TIMEOUT=`keyLoadTimeOut`,e.BUFFER_ADD_CODEC_ERROR=`bufferAddCodecError`,e.BUFFER_INCOMPATIBLE_CODECS_ERROR=`bufferIncompatibleCodecsError`,e.BUFFER_APPEND_ERROR=`bufferAppendError`,e.BUFFER_APPENDING_ERROR=`bufferAppendingError`,e.BUFFER_STALLED_ERROR=`bufferStalledError`,e.BUFFER_FULL_ERROR=`bufferFullError`,e.BUFFER_SEEK_OVER_HOLE=`bufferSeekOverHole`,e.BUFFER_NUDGE_ON_STALL=`bufferNudgeOnStall`,e.ASSET_LIST_LOAD_ERROR=`assetListLoadError`,e.ASSET_LIST_LOAD_TIMEOUT=`assetListLoadTimeout`,e.ASSET_LIST_PARSING_ERROR=`assetListParsingError`,e.INTERSTITIAL_ASSET_ITEM_ERROR=`interstitialAssetItemError`,e.INTERNAL_EXCEPTION=`internalException`,e.INTERNAL_ABORTED=`aborted`,e.ATTACH_MEDIA_ERROR=`attachMediaError`,e.UNKNOWN=`unknown`,e}({}),Z=function(e){return e.MEDIA_ATTACHING=`hlsMediaAttaching`,e.MEDIA_ATTACHED=`hlsMediaAttached`,e.MEDIA_DETACHING=`hlsMediaDetaching`,e.MEDIA_DETACHED=`hlsMediaDetached`,e.MEDIA_ENDED=`hlsMediaEnded`,e.STALL_RESOLVED=`hlsStallResolved`,e.BUFFER_RESET=`hlsBufferReset`,e.BUFFER_CODECS=`hlsBufferCodecs`,e.BUFFER_CREATED=`hlsBufferCreated`,e.BUFFER_APPENDING=`hlsBufferAppending`,e.BUFFER_APPENDED=`hlsBufferAppended`,e.BUFFER_EOS=`hlsBufferEos`,e.BUFFERED_TO_END=`hlsBufferedToEnd`,e.BUFFER_FLUSHING=`hlsBufferFlushing`,e.BUFFER_FLUSHED=`hlsBufferFlushed`,e.MANIFEST_LOADING=`hlsManifestLoading`,e.MANIFEST_LOADED=`hlsManifestLoaded`,e.MANIFEST_PARSED=`hlsManifestParsed`,e.LEVEL_SWITCHING=`hlsLevelSwitching`,e.LEVEL_SWITCHED=`hlsLevelSwitched`,e.LEVEL_LOADING=`hlsLevelLoading`,e.LEVEL_LOADED=`hlsLevelLoaded`,e.LEVEL_UPDATED=`hlsLevelUpdated`,e.LEVEL_PTS_UPDATED=`hlsLevelPtsUpdated`,e.LEVELS_UPDATED=`hlsLevelsUpdated`,e.AUDIO_TRACKS_UPDATED=`hlsAudioTracksUpdated`,e.AUDIO_TRACK_SWITCHING=`hlsAudioTrackSwitching`,e.AUDIO_TRACK_SWITCHED=`hlsAudioTrackSwitched`,e.AUDIO_TRACK_LOADING=`hlsAudioTrackLoading`,e.AUDIO_TRACK_LOADED=`hlsAudioTrackLoaded`,e.AUDIO_TRACK_UPDATED=`hlsAudioTrackUpdated`,e.SUBTITLE_TRACKS_UPDATED=`hlsSubtitleTracksUpdated`,e.SUBTITLE_TRACKS_CLEARED=`hlsSubtitleTracksCleared`,e.SUBTITLE_TRACK_SWITCH=`hlsSubtitleTrackSwitch`,e.SUBTITLE_TRACK_LOADING=`hlsSubtitleTrackLoading`,e.SUBTITLE_TRACK_LOADED=`hlsSubtitleTrackLoaded`,e.SUBTITLE_TRACK_UPDATED=`hlsSubtitleTrackUpdated`,e.SUBTITLE_FRAG_PROCESSED=`hlsSubtitleFragProcessed`,e.CUES_PARSED=`hlsCuesParsed`,e.NON_NATIVE_TEXT_TRACKS_FOUND=`hlsNonNativeTextTracksFound`,e.INIT_PTS_FOUND=`hlsInitPtsFound`,e.FRAG_LOADING=`hlsFragLoading`,e.FRAG_LOAD_EMERGENCY_ABORTED=`hlsFragLoadEmergencyAborted`,e.FRAG_LOADED=`hlsFragLoaded`,e.FRAG_DECRYPTED=`hlsFragDecrypted`,e.FRAG_PARSING_INIT_SEGMENT=`hlsFragParsingInitSegment`,e.FRAG_PARSING_USERDATA=`hlsFragParsingUserdata`,e.FRAG_PARSING_METADATA=`hlsFragParsingMetadata`,e.FRAG_PARSED=`hlsFragParsed`,e.FRAG_BUFFERED=`hlsFragBuffered`,e.FRAG_CHANGED=`hlsFragChanged`,e.FPS_DROP=`hlsFpsDrop`,e.FPS_DROP_LEVEL_CAPPING=`hlsFpsDropLevelCapping`,e.MAX_AUTO_LEVEL_UPDATED=`hlsMaxAutoLevelUpdated`,e.ERROR=`hlsError`,e.DESTROYING=`hlsDestroying`,e.KEY_LOADING=`hlsKeyLoading`,e.KEY_LOADED=`hlsKeyLoaded`,e.LIVE_BACK_BUFFER_REACHED=`hlsLiveBackBufferReached`,e.BACK_BUFFER_REACHED=`hlsBackBufferReached`,e.STEERING_MANIFEST_LOADED=`hlsSteeringManifestLoaded`,e.ASSET_LIST_LOADING=`hlsAssetListLoading`,e.ASSET_LIST_LOADED=`hlsAssetListLoaded`,e.INTERSTITIALS_UPDATED=`hlsInterstitialsUpdated`,e.INTERSTITIALS_BUFFERED_TO_BOUNDARY=`hlsInterstitialsBufferedToBoundary`,e.INTERSTITIAL_ASSET_PLAYER_CREATED=`hlsInterstitialAssetPlayerCreated`,e.INTERSTITIAL_STARTED=`hlsInterstitialStarted`,e.INTERSTITIAL_ASSET_STARTED=`hlsInterstitialAssetStarted`,e.INTERSTITIAL_ASSET_ENDED=`hlsInterstitialAssetEnded`,e.INTERSTITIAL_ASSET_ERROR=`hlsInterstitialAssetError`,e.INTERSTITIAL_ENDED=`hlsInterstitialEnded`,e.INTERSTITIALS_PRIMARY_RESUMED=`hlsInterstitialsPrimaryResumed`,e.PLAYOUT_LIMIT_REACHED=`hlsPlayoutLimitReached`,e.EVENT_CUE_ENTER=`hlsEventCueEnter`,e}({}),dB={MANIFEST:`manifest`,LEVEL:`level`,AUDIO_TRACK:`audioTrack`,SUBTITLE_TRACK:`subtitleTrack`},Q={MAIN:`main`,AUDIO:`audio`,SUBTITLE:`subtitle`},fB=class{constructor(e,t=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=n}sample(e,t){let n=this.alpha_**+e;this.estimate_=t*(1-n)+n*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){let e=1-this.alpha_**+this.totalWeight_;if(e)return this.estimate_/e}return this.estimate_}},pB=class{constructor(e,t,n,r=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new fB(e),this.fast_=new fB(t),this.defaultTTFB_=r,this.ttfb_=new fB(e)}update(e,t){let{slow_:n,fast_:r,ttfb_:i}=this;n.halfLife!==e&&(this.slow_=new fB(e,n.getEstimate(),n.getTotalWeight())),r.halfLife!==t&&(this.fast_=new fB(t,r.getEstimate(),r.getTotalWeight())),i.halfLife!==e&&(this.ttfb_=new fB(e,i.getEstimate(),i.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);let n=8*t,r=e/1e3,i=n/r;this.fast_.sample(r,i),this.slow_.sample(r,i)}sampleTTFB(e){let t=e/1e3,n=Math.sqrt(2)*Math.exp(-(t**2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function mB(e,t,n){return(t=yB(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function hB(){return hB=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},hB.apply(null,arguments)}function gB(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function _B(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?gB(Object(n),!0).forEach(function(t){mB(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):gB(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function vB(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function yB(e){var t=vB(e,`string`);return typeof t==`symbol`?t:t+``}var bB=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;let n=`[${e}]:`;this.trace=xB,this.debug=t.debug.bind(null,n),this.log=t.log.bind(null,n),this.warn=t.warn.bind(null,n),this.info=t.info.bind(null,n),this.error=t.error.bind(null,n)}},xB=function(){},SB={trace:xB,debug:xB,log:xB,warn:xB,info:xB,error:xB};function CB(){return hB({},SB)}function wB(e,t){let n=self.console[e];return n?n.bind(self.console,`${t?`[`+t+`] `:``}[${e}] >`):xB}function TB(e,t,n){return t[e]?t[e].bind(t):wB(e,n)}var EB=CB();function DB(e,t,n){let r=CB();if(typeof console==`object`&&e===!0||typeof e==`object`){let i=[`debug`,`log`,`info`,`warn`,`error`];i.forEach(t=>{r[t]=TB(t,e,n)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return CB()}i.forEach(t=>{EB[t]=TB(t,e)})}else hB(EB,r);return r}var OB=EB;function kB(e=!0){if(!(typeof self>`u`))return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function AB(e){return typeof self<`u`&&e===self.ManagedMediaSource}function jB(e,t){let n=Object.keys(e),r=Object.keys(t),i=n.length,a=r.length;return!i||!a||i===a&&!n.some(e=>r.indexOf(e)===-1)}function MB(e,t=!1){if(typeof TextDecoder<`u`){let n=new TextDecoder(`utf-8`).decode(e);if(t){let e=n.indexOf(`\0`);return e===-1?n:n.substring(0,e)}return n.replace(/\0/g,``)}let n=e.length,r,i,a,o=``,s=0;for(;s<n;){if(r=e[s++],r===0&&t)return o;if(!(r===0||r===3))switch(r>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(r);break;case 12:case 13:i=e[s++],o+=String.fromCharCode((r&31)<<6|i&63);break;case 14:i=e[s++],a=e[s++],o+=String.fromCharCode((r&15)<<12|(i&63)<<6|(a&63)<<0);break}}return o}function NB(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n].toString(16);r.length<2&&(r=`0`+r),t+=r}return t}function PB(e){return Uint8Array.from(e.replace(/^0x/,``).replace(/([\da-fA-F]{2}) ?/g,`0x$1 `).replace(/ +$/,``).split(` `)).buffer}function FB(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var IB={exports:{}},LB;function RB(){return LB?IB.exports:(LB=1,(function(e,t){(function(t){var n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,r=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(e,t,n){if(n||={},e=e.trim(),t=t.trim(),!t){if(!n.alwaysNormalize)return e;var i=o.parseURL(e);if(!i)throw Error(`Error trying to parse base URL.`);return i.path=o.normalizePath(i.path),o.buildURLFromParts(i)}var a=o.parseURL(t);if(!a)throw Error(`Error trying to parse relative URL.`);if(a.scheme)return n.alwaysNormalize?(a.path=o.normalizePath(a.path),o.buildURLFromParts(a)):t;var s=o.parseURL(e);if(!s)throw Error(`Error trying to parse base URL.`);if(!s.netLoc&&s.path&&s.path[0]!==`/`){var c=r.exec(s.path);s.netLoc=c[1],s.path=c[2]}s.netLoc&&!s.path&&(s.path=`/`);var l={scheme:s.scheme,netLoc:a.netLoc,path:null,params:a.params,query:a.query,fragment:a.fragment};if(!a.netLoc&&(l.netLoc=s.netLoc,a.path[0]!==`/`))if(!a.path)l.path=s.path,a.params||(l.params=s.params,a.query||(l.query=s.query));else{var u=s.path,d=u.substring(0,u.lastIndexOf(`/`)+1)+a.path;l.path=o.normalizePath(d)}return l.path===null&&(l.path=n.alwaysNormalize?o.normalizePath(a.path):a.path),o.buildURLFromParts(l)},parseURL:function(e){var t=n.exec(e);return t?{scheme:t[1]||``,netLoc:t[2]||``,path:t[3]||``,params:t[4]||``,query:t[5]||``,fragment:t[6]||``}:null},normalizePath:function(e){for(e=e.split(``).reverse().join(``).replace(i,``);e.length!==(e=e.replace(a,``)).length;);return e.split(``).reverse().join(``)},buildURLFromParts:function(e){return e.scheme+e.netLoc+e.path+e.params+e.query+e.fragment}};e.exports=o})()})(IB),IB.exports)}var zB=RB(),BB=class{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}},VB={AUDIO:`audio`,VIDEO:`video`,AUDIOVIDEO:`audiovideo`},HB=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e==`string`&&(e={url:e}),this.base=e,qB(this,`stats`)}setByteRange(e,t){let n=e.split(`@`,2),r;r=n.length===1?t?.byteRangeEndOffset||0:parseInt(n[1]),this._byteRange=[r,parseInt(n[0])+r]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[VB.AUDIO]:null,[VB.VIDEO]:null,[VB.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new BB),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=zB.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||``}set url(e){this._url=e}clearElementaryStreamInfo(){let{elementaryStreams:e}=this;e[VB.AUDIO]=null,e[VB.VIDEO]=null,e[VB.AUDIOVIDEO]=null}};function UB(e){return e.sn!==`initSegment`}var WB=class extends HB{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){let e=this.stats.total;if(e)return e}if(this.byteRange.length){let e=this.byteRange[0],t=this.byteRange[1];if(J(e)&&J(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;let{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||=t.identity.getDecryptData(this.sn);else if(!((e=this._decryptdata)!=null&&e.keyId)){let e=Object.keys(t);if(e.length===1){let n=this._decryptdata=t[e[0]]||null;n&&(this._decryptdata=n.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;let e=J(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;let e=Object.keys(this.levelkeys),n=e.length;if(n>1||n===1&&(t=this.levelkeys[e[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!J(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return UB(this)?(this._ref||={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime},this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){let t=this.levelkeys;if(t){var n;let r=t[e];r&&!((n=this._decryptdata)!=null&&n.keyId)&&(this._decryptdata=r.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,n,r,i,a=!1){let{elementaryStreams:o}=this,s=o[e];if(!s){o[e]={startPTS:t,endPTS:n,startDTS:r,endDTS:i,partial:a};return}s.startPTS=Math.min(s.startPTS,t),s.endPTS=Math.max(s.endPTS,n),s.startDTS=Math.min(s.startDTS,r),s.endDTS=Math.max(s.endDTS,i)}},GB=class extends HB{constructor(e,t,n,r,i){super(n),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint(`DURATION`),this.gap=e.bool(`GAP`),this.independent=e.bool(`INDEPENDENT`),this.relurl=e.enumeratedString(`URI`),this.fragment=t,this.index=r;let a=e.enumeratedString(`BYTERANGE`);a&&this.setByteRange(a,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){let{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}};function KB(e,t){let n=Object.getPrototypeOf(e);if(n)return Object.getOwnPropertyDescriptor(n,t)||KB(n,t)}function qB(e,t){let n=KB(e,t);n&&(n.enumerable=!0,Object.defineProperty(e,t,n))}var JB=2**32-1,YB=[].push,XB={video:1,audio:2,id3:3,text:4};function ZB(e){return String.fromCharCode.apply(null,e)}function QB(e,t){let n=e[t]<<8|e[t+1];return n<0?65536+n:n}function $B(e,t){let n=tV(e,t);return n<0?4294967296+n:n}function eV(e,t){let n=$B(e,t);return n*=2**32,n+=$B(e,t+4),n}function tV(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function nV(e){let t=e.byteLength;for(let n=0;n<t;){let r=$B(e,n);if(r>8&&e[n+4]===109&&e[n+5]===111&&e[n+6]===111&&e[n+7]===102)return!0;n=r>1?n+r:t}return!1}function rV(e,t){let n=[];if(!t.length)return n;let r=e.byteLength;for(let i=0;i<r;){let a=$B(e,i),o=ZB(e.subarray(i+4,i+8)),s=a>1?i+a:r;if(o===t[0])if(t.length===1)n.push(e.subarray(i+8,s));else{let r=rV(e.subarray(i+8,s),t.slice(1));r.length&&YB.apply(n,r)}i=s}return n}function iV(e){let t=[],n=e[0],r=8,i=$B(e,r);r+=4;let a=0,o=0;n===0?(a=$B(e,r),o=$B(e,r+4),r+=8):(a=eV(e,r),o=eV(e,r+8),r+=16),r+=2;let s=e.length+o,c=QB(e,r);r+=2;for(let n=0;n<c;n++){let n=r,a=$B(e,n);n+=4;let o=a&2147483647;if((a&2147483648)>>>31==1)return OB.warn(`SIDX has hierarchical references (not supported)`),null;let c=$B(e,n);n+=4,t.push({referenceSize:o,subsegmentDuration:c,info:{duration:c/i,start:s,end:s+o-1}}),s+=o,n+=4,r=n}return{earliestPresentationTime:a,timescale:i,version:n,referencesCount:c,references:t}}function aV(e){let t=[],n=rV(e,[`moov`,`trak`]);for(let e=0;e<n.length;e++){let r=n[e],i=rV(r,[`tkhd`])[0];if(i){let e=i[0],n=$B(i,e===0?12:20),a=rV(r,[`mdia`,`mdhd`])[0];if(a){e=a[0];let i=$B(a,e===0?12:20),o=rV(r,[`mdia`,`hdlr`])[0];if(o){let e=ZB(o.subarray(8,12)),a={soun:VB.AUDIO,vide:VB.VIDEO}[e],s=rV(r,[`mdia`,`minf`,`stbl`,`stsd`])[0],c=oV(s);a?(t[n]={timescale:i,type:a,stsd:c},t[a]=_B({timescale:i,id:n},c)):t[n]={timescale:i,type:e,stsd:c}}}}}return rV(e,[`moov`,`mvex`,`trex`]).forEach(e=>{let n=t[$B(e,4)];n&&(n.default={duration:$B(e,12),flags:$B(e,20)})}),t}function oV(e){let t=e.subarray(8),n=t.subarray(86),r=ZB(t.subarray(4,8)),i=r,a,o=r===`enca`||r===`encv`;o&&rV(rV(t,[r])[0].subarray(r===`enca`?28:78),[`sinf`]).forEach(e=>{let t=rV(e,[`schm`])[0];if(t){let n=ZB(t.subarray(4,8));if(n===`cbcs`||n===`cenc`){let t=rV(e,[`frma`])[0];t&&(i=ZB(t))}}});let s=i;switch(i){case`avc1`:case`avc2`:case`avc3`:case`avc4`:{let e=rV(n,[`avcC`])[0];e&&e.length>3&&(i+=`.`+uV(e[1])+uV(e[2])+uV(e[3]),a=sV(s===`avc1`?`dva1`:`dvav`,n));break}case`mp4a`:{let e=rV(t,[r])[0],n=rV(e.subarray(28),[`esds`])[0];if(n&&n.length>7){let e=4;if(n[e++]!==3)break;e=lV(n,e),e+=2;let t=n[e++];if(t&128&&(e+=2),t&64&&(e+=n[e++]),n[e++]!==4)break;e=lV(n,e);let r=n[e++];if(r===64)i+=`.`+uV(r);else break;if(e+=12,n[e++]!==5)break;e=lV(n,e);let a=n[e++],o=(a&248)>>3;o===31&&(o+=1+((a&7)<<3)+((n[e]&224)>>5)),i+=`.`+o}break}case`hvc1`:case`hev1`:{let e=rV(n,[`hvcC`])[0];if(e&&e.length>12){let t=e[1],n=[``,`A`,`B`,`C`][t>>6],r=t&31,a=$B(e,2),o=(t&32)>>5?`H`:`L`,s=e[12],c=e.subarray(6,12);i+=`.`+n+r,i+=`.`+cV(a).toString(16).toUpperCase(),i+=`.`+o+s;let l=``;for(let e=c.length;e--;){let t=c[e];(t||l)&&(l=`.`+t.toString(16).toUpperCase()+l)}i+=l}a=sV(s==`hev1`?`dvhe`:`dvh1`,n);break}case`dvh1`:case`dvhe`:case`dvav`:case`dva1`:case`dav1`:i=sV(i,n)||i;break;case`vp09`:{let e=rV(n,[`vpcC`])[0];if(e&&e.length>6){let t=e[4],n=e[5],r=e[6]>>4&15;i+=`.`+dV(t)+`.`+dV(n)+`.`+dV(r)}break}case`av01`:{let e=rV(n,[`av1C`])[0];if(e&&e.length>2){let t=e[1]>>>5,r=e[1]&31,o=e[2]>>>7?`H`:`M`,s=(e[2]&64)>>6,c=(e[2]&32)>>5,l=t===2&&s?c?12:10:s?10:8,u=(e[2]&16)>>4,d=(e[2]&8)>>3,f=(e[2]&4)>>2,p=e[2]&3;i+=`.`+t+`.`+dV(r)+o+`.`+dV(l)+`.`+u+`.`+d+f+p+`.`+dV(1)+`.`+dV(1)+`.`+dV(1)+`.0`,a=sV(`dav1`,n)}break}}return{codec:i,encrypted:o,supplemental:a}}function sV(e,t){let n=rV(t,[`dvvC`]),r=n.length?n[0]:rV(t,[`dvcC`])[0];if(r){let t=r[2]>>1&127,n=r[2]<<5&32|r[3]>>3&31;return e+`.`+dV(t)+`.`+dV(n)}}function cV(e){let t=0;for(let n=0;n<32;n++)t|=(e>>n&1)<<31-n;return t>>>0}function lV(e,t){let n=t+5;for(;e[t++]&128&&t<n;);return t}function uV(e){return(`0`+e.toString(16).toUpperCase()).slice(-2)}function dV(e){return(e<10?`0`:``)+e}function fV(e,t){if(!e||!t)return;let n=t.keyId;n&&t.isCommonEncryption&&mV(e,(e,t)=>{let r=e.subarray(8,24);r.some(e=>e!==0)||(OB.log(`[eme] Patching keyId in 'enc${t?`a`:`v`}>sinf>>tenc' box: ${NB(r)} -> ${NB(n)}`),e.set(n,8))})}function pV(e){let t=[];return mV(e,e=>t.push(e.subarray(8,24))),t}function mV(e,t){rV(e,[`moov`,`trak`]).forEach(e=>{let n=rV(e,[`mdia`,`minf`,`stbl`,`stsd`])[0];if(!n)return;let r=n.subarray(8),i=rV(r,[`enca`]),a=i.length>0;a||(i=rV(r,[`encv`])),i.forEach(e=>{rV(a?e.subarray(28):e.subarray(78),[`sinf`]).forEach(e=>{let n=hV(e);n&&t(n,a)})})})}function hV(e){let t=rV(e,[`schm`])[0];if(t){let n=ZB(t.subarray(4,8));if(n===`cbcs`||n===`cenc`){let t=rV(e,[`schi`,`tenc`])[0];if(t)return t}}}function gV(e,t,n){let r={},i=rV(e,[`moof`,`traf`]);for(let e=0;e<i.length;e++){let a=i[e],o=rV(a,[`tfhd`])[0],s=$B(o,4),c=t[s];if(!c)continue;r[s]||(r[s]={start:NaN,duration:0,sampleCount:0,timescale:c.timescale,type:c.type});let l=r[s],u=rV(a,[`tfdt`])[0];if(u){let e=u[0],t=$B(u,4);e===1&&(t===JB?n.warn(`[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time`):(t*=JB+1,t+=$B(u,8))),J(t)&&(!J(l.start)||t<l.start)&&(l.start=t)}let d=c.default,f=$B(o,0)|d?.flags,p=d?.duration||0;f&8&&(p=f&2?$B(o,12):$B(o,8));let m=rV(a,[`trun`]),h=l.start||0,g=0,_=p;for(let e=0;e<m.length;e++){let t=m[e],n=$B(t,4),r=l.sampleCount;l.sampleCount+=n;let i=t[3]&1,a=t[3]&4,o=t[2]&1,s=t[2]&2,c=t[2]&4,u=t[2]&8,d=8,f=n;for(i&&(d+=4),a&&n&&(!(t[d+1]&1)&&l.keyFrameIndex===void 0&&(l.keyFrameIndex=r),d+=4,o?(_=$B(t,d),d+=4):_=p,s&&(d+=4),u&&(d+=4),h+=_,g+=_,f--);f--;)o?(_=$B(t,d),d+=4):_=p,s&&(d+=4),c&&(t[d+1]&1||l.keyFrameIndex===void 0&&(l.keyFrameIndex=l.sampleCount-(f+1),l.keyFrameStart=h),d+=4),u&&(d+=4),h+=_,g+=_;!g&&p&&(g+=p*n)}l.duration+=g}if(!Object.keys(r).some(e=>r[e].duration)){let t=1/0,n=0,i=rV(e,[`sidx`]);for(let e=0;e<i.length;e++){let r=iV(i[e]);if(r!=null&&r.references){t=Math.min(t,r.earliestPresentationTime/r.timescale);let e=r.references.reduce((e,t)=>e+t.info.duration||0,0);n=Math.max(n,e+r.earliestPresentationTime/r.timescale)}}n&&J(n)&&Object.keys(r).forEach(e=>{r[e].duration||(r[e].duration=n*r[e].timescale-r[e].start)})}return r}function _V(e){let t={valid:null,remainder:null},n=rV(e,[`moof`]);if(n.length<2)return t.remainder=e,t;let r=n[n.length-1];return t.valid=e.slice(0,r.byteOffset-8),t.remainder=e.slice(r.byteOffset-8),t}function vV(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}function yV(e,t){let n=[],r=t.samples,i=t.timescale,a=t.id,o=!1;return rV(r,[`moof`]).map(s=>{let c=s.byteOffset-8;rV(s,[`traf`]).map(s=>{let l=rV(s,[`tfdt`]).map(e=>{let t=e[0],n=$B(e,4);return t===1&&(n*=2**32,n+=$B(e,8)),n/i})[0];return l!==void 0&&(e=l),rV(s,[`tfhd`]).map(l=>{let u=$B(l,4),d=$B(l,0)&16777215,f=(d&1)!=0,p=(d&2)!=0,m=(d&8)!=0,h=0,g=(d&16)!=0,_=0,v=(d&32)!=0,y=8;u===a&&(f&&(y+=8),p&&(y+=4),m&&(h=$B(l,y),y+=4),g&&(_=$B(l,y),y+=4),v&&(y+=4),t.type===`video`&&(o=bV(t.codec)),rV(s,[`trun`]).map(a=>{let s=a[0],l=$B(a,0)&16777215,u=(l&1)!=0,d=0,f=(l&4)!=0,p=(l&256)!=0,m=0,g=(l&512)!=0,v=0,y=(l&1024)!=0,b=(l&2048)!=0,x=0,S=$B(a,4),C=8;u&&(d=$B(a,C),C+=4),f&&(C+=4);let w=d+c;for(let c=0;c<S;c++){if(p?(m=$B(a,C),C+=4):m=h,g?(v=$B(a,C),C+=4):v=_,y&&(C+=4),b&&(x=s===0?$B(a,C):tV(a,C),C+=4),t.type===VB.VIDEO){let t=0;for(;t<v;){let a=$B(r,w);w+=4,xV(o,r[w])&&SV(r.subarray(w,w+a),o?2:1,e+x/i,n),w+=a,t+=a+4}}e+=m/i}}))})})}),n}function bV(e){if(!e)return!1;let t=e.substring(0,4);return t===`hvc1`||t===`hev1`||t===`dvh1`||t===`dvhe`}function xV(e,t){if(e){let e=t>>1&63;return e===39||e===40}else return(t&31)==6}function SV(e,t,n,r){let i=CV(e),a=0;a+=t;let o=0,s=0,c=0;for(;a<i.length;){o=0;do{if(a>=i.length)break;c=i[a++],o+=c}while(c===255);s=0;do{if(a>=i.length)break;c=i[a++],s+=c}while(c===255);let e=i.length-a,t=a;if(s<e)a+=s;else if(s>e){OB.error(`Malformed SEI payload. ${s} is too small, only ${e} bytes left to parse.`);break}if(o===4){if(i[t++]===181){let e=QB(i,t);if(t+=2,e===49){let e=$B(i,t);if(t+=4,e===1195456820){let e=i[t++];if(e===3){let a=i[t++],s=31&a,c=64&a,l=c?2+s*3:0,u=new Uint8Array(l);if(c){u[0]=a;for(let e=1;e<l;e++)u[e]=i[t++]}r.push({type:e,payloadType:o,pts:n,bytes:u})}}}}}else if(o===5&&s>16){let e=[];for(let n=0;n<16;n++){let r=i[t++].toString(16);e.push(r.length==1?`0`+r:r),(n===3||n===5||n===7||n===9)&&e.push(`-`)}let a=s-16,c=new Uint8Array(a);for(let e=0;e<a;e++)c[e]=i[t++];r.push({payloadType:o,pts:n,uuid:e.join(``),userData:MB(c),userDataBytes:c})}}}function CV(e){let t=e.byteLength,n=[],r=1;for(;r<t-2;)e[r]===0&&e[r+1]===0&&e[r+2]===3?(n.push(r+2),r+=2):r++;if(n.length===0)return e;let i=t-n.length,a=new Uint8Array(i),o=0;for(r=0;r<i;o++,r++)o===n[0]&&(o++,n.shift()),a[r]=e[o];return a}function wV(e){let t=e[0],n=``,r=``,i=0,a=0,o=0,s=0,c=0,l=0;if(t===0){for(;ZB(e.subarray(l,l+1))!==`\0`;)n+=ZB(e.subarray(l,l+1)),l+=1;for(n+=ZB(e.subarray(l,l+1)),l+=1;ZB(e.subarray(l,l+1))!==`\0`;)r+=ZB(e.subarray(l,l+1)),l+=1;r+=ZB(e.subarray(l,l+1)),l+=1,i=$B(e,12),a=$B(e,16),s=$B(e,20),c=$B(e,24),l=28}else if(t===1){l+=4,i=$B(e,l),l+=4;let t=$B(e,l);l+=4;let a=$B(e,l);for(l+=4,o=2**32*t+a,lB(o)||(o=2**53-1,OB.warn(`Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box`)),s=$B(e,l),l+=4,c=$B(e,l),l+=4;ZB(e.subarray(l,l+1))!==`\0`;)n+=ZB(e.subarray(l,l+1)),l+=1;for(n+=ZB(e.subarray(l,l+1)),l+=1;ZB(e.subarray(l,l+1))!==`\0`;)r+=ZB(e.subarray(l,l+1)),l+=1;r+=ZB(e.subarray(l,l+1)),l+=1}let u=e.subarray(l,e.byteLength);return{schemeIdUri:n,value:r,timeScale:i,presentationTime:o,presentationTimeDelta:a,eventDuration:s,id:c,payload:u}}function TV(e,...t){let n=t.length,r=8,i=n;for(;i--;)r+=t[i].byteLength;let a=new Uint8Array(r);for(a[0]=r>>24&255,a[1]=r>>16&255,a[2]=r>>8&255,a[3]=r&255,a.set(e,4),i=0,r=8;i<n;i++)a.set(t[i],r),r+=t[i].byteLength;return a}function EV(e,t,n){if(e.byteLength!==16)throw RangeError(`Invalid system id`);let r,i;r=0,i=new Uint8Array;let a;r>0?(a=new Uint8Array(4),t.length>0&&new DataView(a.buffer).setUint32(0,t.length,!1)):a=new Uint8Array;let o=new Uint8Array(4);return n.byteLength>0&&new DataView(o.buffer).setUint32(0,n.byteLength,!1),TV([112,115,115,104],new Uint8Array([r,0,0,0]),e,a,i,o,n)}function DV(e){let t=[];if(e instanceof ArrayBuffer){let n=e.byteLength,r=0;for(;r+32<n;){let n=OV(new DataView(e,r));t.push(n),r+=n.size}}return t}function OV(e){let t=e.getUint32(0),n=e.byteOffset,r=e.byteLength;if(r<t)return{offset:n,size:r};if(e.getUint32(4)!==1886614376)return{offset:n,size:t};let i=e.getUint32(8)>>>24;if(i!==0&&i!==1)return{offset:n,size:t};let a=e.buffer,o=NB(new Uint8Array(a,n+12,16)),s=null,c=null,l=0;if(i===0)l=28;else{let i=e.getUint32(28);if(!i||r<32+i*16)return{offset:n,size:t};s=[];for(let e=0;e<i;e++)s.push(new Uint8Array(a,n+32+e*16,16));l=32+i*16}if(!l)return{offset:n,size:t};let u=e.getUint32(l);return t-32<u?{offset:n,size:t}:(c=new Uint8Array(a,n+l+4,u),{version:i,systemId:o,kids:s,data:c,offset:n,size:t})}var kV=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),AV={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function jV(e,t){let n=AV[t];return!!n&&!!n[e.slice(0,4)]}function MV(e,t,n=!0){return!e.split(`,`).some(e=>!NV(e,t,n))}function NV(e,t,n=!0){return kB(n)?.isTypeSupported(PV(e,t))??!1}function PV(e,t){return`${t}/mp4;codecs=${e}`}function FV(e){if(e){let t=e.substring(0,4);return AV.video[t]}return 2}function IV(e){let t=kV();return e.split(`,`).reduce((e,n)=>{let r=t&&bV(n)?9:AV.video[n];return r?(r*2+e)/(e?3:2):(AV.audio[n]+e)/(e?2:1)},0)}var LV={};function RV(e,t=!0){if(LV[e])return LV[e];let n={flac:[`flac`,`fLaC`,`FLAC`],opus:[`opus`,`Opus`],"mp4a.40.34":[`mp3`]}[e];for(let i=0;i<n.length;i++){var r;if(NV(n[i],`audio`,t))return LV[e]=n[i],n[i];if(n[i]===`mp3`&&(r=kB(t))!=null&&r.isTypeSupported(`audio/mpeg`))return``}return e}var zV=/flac|opus|mp4a\.40\.34/i;function BV(e,t=!0){return e.replace(zV,e=>RV(e.toLowerCase(),t))}function VV(e,t){let n=[];if(e){let t=e.split(`,`);for(let e=0;e<t.length;e++)jV(t[e],`video`)||n.push(t[e])}return t&&n.push(t),n.join(`,`)}function HV(e,t){if(e&&(e.length>4||[`ac-3`,`ec-3`,`alac`,`fLaC`,`Opus`].indexOf(e)!==-1)&&(UV(e,`audio`)||UV(e,`video`)))return e;if(t){let n=t.split(`,`);if(n.length>1){if(e){for(let t=n.length;t--;)if(n[t].substring(0,4)===e.substring(0,4))return n[t]}return n[0]}}return t||e}function UV(e,t){return jV(e,t)&&NV(e,t)}function WV(e){let t=e.split(`,`);for(let e=0;e<t.length;e++){let n=t[e].split(`.`);n.length>2&&n[0]===`avc1`&&(t[e]=`avc1.${parseInt(n[1]).toString(16)}${(`000`+parseInt(n[2]).toString(16)).slice(-4)}`)}return t.join(`,`)}function GV(e){if(e.startsWith(`av01.`)){let t=e.split(`.`),n=[`0`,`111`,`01`,`01`,`01`,`0`];for(let e=t.length;e>4&&e<10;e++)t[e]=n[e-4];return t.join(`.`)}return e}function KV(e){let t=kB(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported(`audio/mpeg`),mp3:t.isTypeSupported(`audio/mp4; codecs="mp3"`),ac3:t.isTypeSupported(`audio/mp4; codecs="ac-3"`)}}function qV(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,`$1`)}var JV={supported:!0,powerEfficient:!0,smooth:!0},YV={supported:!1,smooth:!1,powerEfficient:!1},XV={supported:!0,configurations:[],decodingInfoResults:[JV]};function ZV(e,t){return{supported:!1,configurations:t,decodingInfoResults:[YV],error:e}}function QV(e,t,n,r,i,a){let o=e.videoCodec,s=e.audioCodec?e.audioGroups:null,c=a?.audioCodec,l=a?.channels,u=l?parseInt(l):c?1/0:2,d=null;if(s!=null&&s.length)try{d=s.length===1&&s[0]?t.groups[s[0]].channels:s.reduce((e,n)=>{if(n){let r=t.groups[n];if(!r)throw Error(`Audio track group ${n} not found`);Object.keys(r.channels).forEach(t=>{e[t]=(e[t]||0)+r.channels[t]})}return e},{2:0})}catch{return!0}return o!==void 0&&(o.split(`,`).some(e=>bV(e))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(r,30)||e.videoRange!==`SDR`&&e.videoRange!==n||e.bitrate>Math.max(i,8e6))||!!d&&J(u)&&Object.keys(d).some(e=>parseInt(e)>u)}function $V(e,t,n,r={}){let i=e.videoCodec;if(!i&&!e.audioCodec||!n)return Promise.resolve(XV);let a=[],o=eH(e),s=o.length,c=tH(e,t,s>0),l=c.length;for(let e=s||1*l||1;e--;){let t={type:`media-source`};if(s&&(t.video=o[e%s]),l){t.audio=c[e%l];let n=t.audio.bitrate;t.video&&n&&(t.video.bitrate-=n)}a.push(t)}if(i){let e=navigator.userAgent;if(i.split(`,`).some(e=>bV(e))&&kV())return Promise.resolve(ZV(Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${e})`),a))}return Promise.all(a.map(e=>{let t=iH(e);return r[t]||(r[t]=n.decodingInfo(e))})).then(e=>({supported:!e.some(e=>!e.supported),configurations:a,decodingInfoResults:e})).catch(e=>({supported:!1,configurations:a,decodingInfoResults:[],error:e}))}function eH(e){let t=e.videoCodec?.split(`,`),n=rH(e),r=e.width||640,i=e.height||480,a=e.frameRate||30,o=e.videoRange.toLowerCase();return t?t.map(e=>{let t={contentType:PV(GV(e),`video`),width:r,height:i,bitrate:n,framerate:a};return o!==`sdr`&&(t.transferFunction=o),t}):[]}function tH(e,t,n){let r=e.audioCodec?.split(`,`),i=rH(e);return r&&e.audioGroups?e.audioGroups.reduce((e,a)=>{let o=a?t.groups[a]?.tracks:null;return o?o.reduce((e,t)=>{if(t.groupId===a){let a=parseFloat(t.channels||``);r.forEach(t=>{let r={contentType:PV(t,`audio`),bitrate:n?nH(t,i):i};a&&(r.channels=``+a),e.push(r)})}return e},e):e},[]):[]}function nH(e,t){if(t<=1)return 1;let n=128e3;return e===`ec-3`?n=768e3:e===`ac-3`&&(n=64e4),Math.min(t/2,n)}function rH(e){return Math.ceil(Math.max(e.bitrate*.9,e.averageBitrate)/1e3)*1e3||1}function iH(e){let t=``,{audio:n,video:r}=e;if(r){let e=qV(r.contentType);t+=`${e}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||`sd`}_${Math.ceil(r.bitrate/1e5)}`}if(n){let e=qV(n.contentType);t+=`${r?`_`:``}${e}_c${n.channels}`}return t}var aH=[`NONE`,`TYPE-0`,`TYPE-1`,null];function oH(e){return aH.indexOf(e)>-1}var sH=[`SDR`,`PQ`,`HLG`];function cH(e){return!!e&&sH.indexOf(e)>-1}var lH={No:``,Yes:`YES`,v2:`v2`};function uH(e){let{canSkipUntil:t,canSkipDateRanges:n,age:r}=e,i=r<t/2;return t&&i?n?lH.v2:lH.Yes:lH.No}var dH=class{constructor(e,t,n){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=n}addDirectives(e){let t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set(`_HLS_msn`,this.msn.toString()),this.part!==void 0&&t.searchParams.set(`_HLS_part`,this.part.toString()),this.skip&&t.searchParams.set(`_HLS_skip`,this.skip),t.href}},fH=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat(`FRAME-RATE`,0),this._avgBitrate=e.attrs.decimalInteger(`AVERAGE-BANDWIDTH`),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(e=>!!e).map(e=>e.substring(0,4)).join(`,`),`supplemental`in e){this.supplemental=e.supplemental;let t=e.supplemental?.videoCodec;t&&t!==e.videoCodec&&(this.codecSet+=`,${t.substring(0,4)}`)}this.addGroupId(`audio`,e.attrs.AUDIO),this.addGroupId(`text`,e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||``}get pathwayId(){return this.attrs[`PATHWAY-ID`]||`.`}get videoRange(){return this.attrs[`VIDEO-RANGE`]||`SDR`}get score(){return this.attrs.optionalFloat(`SCORE`,0)}get uri(){return this.url[0]||``}hasAudioGroup(e){return pH(this._audioGroups,e)}hasSubtitleGroup(e){return pH(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e===`audio`){let e=this._audioGroups;e||=this._audioGroups=[],e.indexOf(t)===-1&&e.push(t)}else if(e===`text`){let e=this._subtitleGroups;e||=this._subtitleGroups=[],e.indexOf(t)===-1&&e.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){return this.audioGroups?.[0]}get textGroupId(){return this.subtitleGroups?.[0]}addFallback(){}};function pH(e,t){return!t||!e?!1:e.indexOf(t)!==-1}function mH(){if(typeof matchMedia==`function`){let e=matchMedia(`(dynamic-range: high)`),t=matchMedia(`bad query`);if(e.media!==t.media)return e.matches===!0}return!1}function hH(e,t){let n=!1,r=[];if(e&&(n=e!==`SDR`,r=[e]),t){r=t.allowedVideoRanges||sH.slice(0);let e=r.join(``)!==`SDR`&&!t.videoCodec;n=t.preferHDR===void 0?e&&mH():t.preferHDR,n||(r=[`SDR`])}return{preferHDR:n,allowedVideoRanges:r}}var gH=e=>{let t=new WeakSet;return(n,r)=>{if(e&&(r=e(n,r)),typeof r==`object`&&r){if(t.has(r))return;t.add(r)}return r}},_H=(e,t)=>JSON.stringify(e,gH(t));function vH(e,t,n,r,i){let a=Object.keys(e),o=r?.channels,s=r?.audioCodec,c=i?.videoCodec,l=o&&parseInt(o)===2,u=!1,d=!1,f=1/0,p=1/0,m=1/0,h=1/0,g=0,_=[],{preferHDR:v,allowedVideoRanges:y}=hH(t,i);for(let t=a.length;t--;){let n=e[a[t]];u||=n.channels[2]>0,f=Math.min(f,n.minHeight),p=Math.min(p,n.minFramerate),m=Math.min(m,n.minBitrate),y.filter(e=>n.videoRanges[e]>0).length>0&&(d=!0)}f=J(f)?f:0,p=J(p)?p:0;let b=Math.max(1080,f),x=Math.max(30,p);m=J(m)?m:n,n=Math.max(m,n),d||(t=void 0);let S=a.length>1;return{codecSet:a.reduce((t,r)=>{let i=e[r];if(r===t)return t;if(_=d?y.filter(e=>i.videoRanges[e]>0):[],S){if(i.minBitrate>n)return yH(r,`min bitrate of ${i.minBitrate} > current estimate of ${n}`),t;if(!i.hasDefaultAudio)return yH(r,`no renditions with default or auto-select sound found`),t;if(s&&r.indexOf(s.substring(0,4))%5!=0)return yH(r,`audio codec preference "${s}" not found`),t;if(o&&!l){if(!i.channels[o])return yH(r,`no renditions with ${o} channel sound found (channels options: ${Object.keys(i.channels)})`),t}else if((!s||l)&&u&&i.channels[2]===0)return yH(r,`no renditions with stereo sound found`),t;if(i.minHeight>b)return yH(r,`min resolution of ${i.minHeight} > maximum of ${b}`),t;if(i.minFramerate>x)return yH(r,`min framerate of ${i.minFramerate} > maximum of ${x}`),t;if(!_.some(e=>i.videoRanges[e]>0))return yH(r,`no variants with VIDEO-RANGE of ${_H(_)} found`),t;if(c&&r.indexOf(c.substring(0,4))%5!=0)return yH(r,`video codec preference "${c}" not found`),t;if(i.maxScore<g)return yH(r,`max score of ${i.maxScore} < selected max of ${g}`),t}return t&&(IV(r)>=IV(t)||i.fragmentError>e[t].fragmentError)?t:(h=i.minIndex,g=i.maxScore,r)},void 0),videoRanges:_,preferHDR:v,minFramerate:p,minBitrate:m,minIndex:h}}function yH(e,t){OB.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function bH(e){return e.reduce((e,t)=>{let n=e.groups[t.groupId];n||=e.groups[t.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1},n.tracks.push(t);let r=t.channels||`2`;return n.channels[r]=(n.channels[r]||0)+1,n.hasDefault=n.hasDefault||t.default,n.hasAutoSelect=n.hasAutoSelect||t.autoselect,n.hasDefault&&(e.hasDefaultAudio=!0),n.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function xH(e,t,n,r){return e.slice(n,r+1).reduce((e,n,r)=>{if(!n.codecSet)return e;let i=n.audioGroups,a=e[n.codecSet];a||(e[n.codecSet]=a={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:r,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!i,fragmentError:0}),a.minBitrate=Math.min(a.minBitrate,n.bitrate);let o=Math.min(n.height,n.width);return a.minHeight=Math.min(a.minHeight,o),a.minFramerate=Math.min(a.minFramerate,n.frameRate),a.minIndex=Math.min(a.minIndex,r),a.maxScore=Math.max(a.maxScore,n.score),a.fragmentError+=n.fragmentError,a.videoRanges[n.videoRange]=(a.videoRanges[n.videoRange]||0)+1,i&&i.forEach(e=>{if(!e)return;let n=t.groups[e];n&&(a.hasDefaultAudio=a.hasDefaultAudio||t.hasDefaultAudio?n.hasDefault:n.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(n.channels).forEach(e=>{a.channels[e]=(a.channels[e]||0)+n.channels[e]}))}),e},{})}function SH(e){if(!e)return e;let{lang:t,assocLang:n,characteristics:r,channels:i,audioCodec:a}=e;return{lang:t,assocLang:n,characteristics:r,channels:i,audioCodec:a}}function CH(e,t,n){if(`attrs`in e){let n=t.indexOf(e);if(n!==-1)return n}for(let r=0;r<t.length;r++){let i=t[r];if(wH(e,i,n))return r}return-1}function wH(e,t,n){let{groupId:r,name:i,lang:a,assocLang:o,default:s}=e,c=e.forced;return(r===void 0||t.groupId===r)&&(i===void 0||t.name===i)&&(a===void 0||TH(a,t.lang))&&(a===void 0||t.assocLang===o)&&(s===void 0||t.default===s)&&(c===void 0||t.forced===c)&&(!(`characteristics`in e)||EH(e.characteristics||``,t.characteristics))&&(n===void 0||n(e,t))}function TH(e,t=`--`){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}function EH(e,t=``){let n=e.split(`,`),r=t.split(`,`);return n.length===r.length&&!n.some(e=>r.indexOf(e)===-1)}function DH(e,t){let{audioCodec:n,channels:r}=e;return(n===void 0||(t.audioCodec||``).substring(0,4)===n.substring(0,4))&&(r===void 0||r===(t.channels||`2`))}function OH(e,t,n,r,i){let a=t[r],o=t.reduce((e,t,n)=>{let r=t.uri;return(e[r]||(e[r]=[])).push(n),e},{})[a.uri];o.length>1&&(r=Math.max.apply(Math,o));let s=a.videoRange,c=a.frameRate,l=a.codecSet.substring(0,4),u=kH(t,r,t=>{if(t.videoRange!==s||t.frameRate!==c||t.codecSet.substring(0,4)!==l)return!1;let r=t.audioGroups;return CH(e,n.filter(e=>!r||r.indexOf(e.groupId)!==-1),i)>-1});return u>-1?u:kH(t,r,t=>{let r=t.audioGroups;return CH(e,n.filter(e=>!r||r.indexOf(e.groupId)!==-1),i)>-1})}function kH(e,t,n){for(let r=t;r>-1;r--)if(n(e[r]))return r;for(let r=t+1;r<e.length;r++)if(n(e[r]))return r;return-1}function AH(e,t){return!!e&&e!==t.loadLevelObj?.uri}var jH=class extends bB{constructor(e){super(`abr`,e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey=``,this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=e=>{let{fragCurrent:t,partCurrent:n,hls:r}=this,{autoLevelEnabled:i,media:a}=r;if(!t||!a)return;let o=performance.now(),s=n?n.stats:t.stats,c=n?n.duration:t.duration,l=o-s.loading.start,u=r.minAutoLevel,d=t.level,f=this._nextAutoLevel;if(s.aborted||s.loaded&&s.loaded===s.total||d<=u){this.clearTimer(),this._nextAutoLevel=-1;return}if(!i)return;let p=f>-1&&f!==d,m=!!e||p;if(!m&&(a.paused||!a.playbackRate||!a.readyState))return;let h=r.mainForwardBufferInfo;if(!m&&h===null)return;let g=this.bwEstimator.getEstimateTTFB(),_=Math.abs(a.playbackRate);if(l<=Math.max(g,1e3*(c/(_*2))))return;let v=h?h.len/_:0,y=s.loading.first?s.loading.first-s.loading.start:-1,b=s.loaded&&y>-1,x=this.getBwEstimate(),S=r.levels,C=S[d],w=Math.max(s.loaded,Math.round(c*(t.bitrate||C.averageBitrate)/8)),T=b?l-y:l;T<1&&b&&(T=Math.min(l,s.loaded*8/x));let E=b?s.loaded*1e3/T:0,D=g/1e3,O=E?(w-s.loaded)/E:w*8/x+D;if(O<=v)return;let k=E?E*8:x,A=(e?.details||this.hls.latestLevelDetails)?.live===!0,j=this.hls.config.abrBandWidthUpFactor,M=1/0,N;for(N=d-1;N>u;N--){let e=S[N].maxBitrate,t=!S[N].details||A;if(M=this.getTimeToLoadFrag(D,k,c*e,t),M<Math.min(v,c+D))break}if(M>=O||M>c*10)return;b?this.bwEstimator.sample(l-Math.min(g,y),s.loaded):this.bwEstimator.sampleTTFB(l);let P=S[N].maxBitrate;this.getBwEstimate()*j>P&&this.resetEstimator(P);let ee=this.findBestLevel(P,u,N,0,v,1,1);ee>-1&&(N=ee),this.warn(`Fragment ${t.sn}${n?` part `+n.index:``} of level ${d} is loading too slowly;
35
- Fragment duration: ${t.duration.toFixed(3)}
36
- Time to underbuffer: ${v.toFixed(3)} s
37
- Estimated load time for current fragment: ${O.toFixed(3)} s
38
- Estimated load time for down switch fragment: ${M.toFixed(3)} s
39
- TTFB estimate: ${y|0} ms
40
- Current BW estimate: ${J(x)?x|0:`Unknown`} bps
41
- New BW estimate: ${this.getBwEstimate()|0} bps
42
- Switching to level ${N} @ ${P|0} bps`),r.nextLoadLevel=r.nextAutoLevel=N,this.clearTimer();let F=()=>{if(this.clearTimer(),this.fragCurrent===t&&this.hls.loadLevel===N&&N>0){let e=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${N>0?`and switching down`:``}
43
- Fragment duration: ${t.duration.toFixed(3)} s
44
- Time to underbuffer: ${e.toFixed(3)} s`),t.abortRequests(),this.fragCurrent=this.partCurrent=null,N>u){let t=this.findBestLevel(this.hls.levels[u].bitrate,u,N,0,e,1,1);t===-1&&(t=u),this.hls.nextLoadLevel=this.hls.nextAutoLevel=t,this.resetEstimator(this.hls.levels[t].bitrate)}}};p||O>M*2?F():this.timer=self.setInterval(F,M*1e3),r.trigger(Z.FRAG_LOAD_EMERGENCY_ABORTED,{frag:t,part:n,stats:s})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){let e=this.hls.config;return new pB(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){let{hls:e}=this;e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.FRAG_LOADING,this.onFragLoading,this),e.on(Z.FRAG_LOADED,this.onFragLoaded,this),e.on(Z.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Z.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Z.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Z.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(Z.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e&&(e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.FRAG_LOADING,this.onFragLoading,this),e.off(Z.FRAG_LOADED,this.onFragLoaded,this),e.off(Z.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Z.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Z.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Z.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(Z.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=``}onFragLoading(e,t){let n=t.frag;this.ignoreFragment(n)||(n.bitrateTest||(this.fragCurrent=n,this.partCurrent=t.part??null),this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100))}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case X.BUFFER_ADD_CODEC_ERROR:case X.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case X.FRAG_LOAD_TIMEOUT:{let e=t.frag,{fragCurrent:n,partCurrent:r}=this;if(e&&n&&e.sn===n.sn&&e.level===n.level){let t=performance.now(),n=r?r.stats:e.stats,i=t-n.loading.start,a=n.loading.first?n.loading.first-n.loading.start:-1;if(n.loaded&&a>-1){let e=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(i-Math.min(e,a),n.loaded)}else this.bwEstimator.sampleTTFB(i)}break}}}getTimeToLoadFrag(e,t,n,r){return e+n/t+(r?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){let n=this.hls.config,{loading:r}=t.stats,i=r.end-r.first;J(i)&&(this.lastLevelLoadSec=i/1e3),t.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:n}){let r=n?n.stats:t.stats;if(t.type===Q.MAIN&&this.bwEstimator.sampleTTFB(r.loading.first-r.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){let e=n?n.duration:t.duration,i=this.hls.levels[t.level],a=(i.loaded?i.loaded.bytes:0)+r.loaded,o=(i.loaded?i.loaded.duration:0)+e;i.loaded={bytes:a,duration:o},i.realBitrate=Math.round(8*a/o)}if(t.bitrateTest){let e={stats:r,frag:t,part:n,id:t.type};this.onFragBuffered(Z.FRAG_BUFFERED,e),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){let{frag:n,part:r}=t,i=r!=null&&r.stats.loaded?r.stats:n.stats;if(i.aborted||this.ignoreFragment(n))return;let a=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,i.loaded),i.bwEstimate=this.getBwEstimate(),n.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Q.MAIN||e.sn===`initSegment`}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){let{maxAutoLevel:e,minAutoLevel:t}=this.hls,n=this.getBwEstimate(),r=this.hls.config.maxStarvationDelay,i=this.findBestLevel(n,t,e,0,r,1,1);if(i>-1)return i;let a=this.hls.firstLevel,o=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){let e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),n=this.lastLoadedFragLevel>-1;if(e!==-1&&(!t||!n||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;let r=t&&n?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){let t=this.hls.levels;if(t.length>Math.max(e,r)&&t[e].loadError<=t[r].loadError)return e}return this._nextAutoLevel=r,this.nextAutoLevelKey=this.getAutoLevelKey(),r}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){let{fragCurrent:e,partCurrent:t,hls:n}=this;if(n.levels.length<=1)return n.loadLevel;let{maxAutoLevel:r,config:i,minAutoLevel:a}=n,o=t?t.duration:e?e.duration:0,s=this.getBwEstimate(),c=this.getStarvationDelay(),l=i.abrBandWidthFactor,u=i.abrBandWidthUpFactor;if(c){let e=this.findBestLevel(s,a,r,c,0,l,u);if(e>=0)return this.rebufferNotice=-1,e}let d=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!c){let e=this.bitrateTestDelay;e&&(d=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-e,this.info(`bitrate test took ${Math.round(1e3*e)}ms, set first fragment max fetchDuration to ${Math.round(1e3*d)} ms`),l=u=1)}let f=this.findBestLevel(s,a,r,c,d,l,u);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${c?`rebuffering expected`:`buffer is empty`}, optimal quality level ${f}`)),f>-1)return f;let p=n.levels[a],m=n.loadLevelObj;return m&&p?.bitrate<m.bitrate?a:n.loadLevel}getStarvationDelay(){let e=this.hls,t=e.media;if(!t)return 1/0;let n=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,r=e.mainForwardBufferInfo;return(r?r.len:0)/n}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,n,r,i,a,o){var s;let c=r+i,l=this.lastLoadedFragLevel,u=l===-1?this.hls.firstLevel:l,{fragCurrent:d,partCurrent:f}=this,{levels:p,allAudioTracks:m,loadLevel:h,config:g}=this.hls;if(p.length===1)return 0;let _=p[u],v=!!((s=this.hls.latestLevelDetails)!=null&&s.live),y=h===-1||l===-1,b,x=`SDR`,S=_?.frameRate||0,{audioPreference:C,videoPreference:w}=g,T=this.audioTracksByGroup||=bH(m),E=-1;if(y){if(this.firstSelection!==-1)return this.firstSelection;let r=vH(this.codecTiers||=xH(p,T,t,n),x,e,C,w),{codecSet:i,videoRanges:a,minFramerate:o,minBitrate:s,minIndex:c,preferHDR:l}=r;E=c,b=i,x=l?a[a.length-1]:a[0],S=o,e=Math.max(e,s),this.log(`picked start tier ${_H(r)}`)}else b=_?.codecSet,x=_?.videoRange;let D=f?f.duration:d?d.duration:0,O=this.bwEstimator.getEstimateTTFB()/1e3,k=[];for(let s=n;s>=t;s--){var A;let t=p[s],d=s>u;if(!t)continue;if(g.useMediaCapabilities&&!t.supportedResult&&!t.supportedPromise){let n=navigator.mediaCapabilities;typeof n?.decodingInfo==`function`&&QV(t,T,x,S,e,C)?(t.supportedPromise=$V(t,T,n,this.supportedCache),t.supportedPromise.then(e=>{if(!this.hls)return;t.supportedResult=e;let n=this.hls.levels,r=n.indexOf(t);e.error?this.warn(`MediaCapabilities decodingInfo error: "${e.error}" for level ${r} ${_H(e)}`):e.supported?e.decodingInfoResults.some(e=>e.smooth===!1||e.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${r} not smooth or powerEfficient: ${_H(e)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${r} ${_H(e)}`),r>-1&&n.length>1&&(this.log(`Removing unsupported level ${r}`),this.hls.removeLevel(r),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(e=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${e}`)})):t.supportedResult=XV}if((b&&t.codecSet!==b||x&&t.videoRange!==x||d&&S>t.frameRate||!d&&S>0&&S<t.frameRate||(A=t.supportedResult)!=null&&(A=A.decodingInfoResults)!=null&&A.some(e=>e.smooth===!1))&&(!y||s!==E)){k.push(s);continue}let m=t.details,_=(f?m?.partTarget:m?.averagetargetduration)||D,w;w=d?o*e:a*e;let j=D&&r>=D*2&&i===0?t.averageBitrate:t.maxBitrate,M=this.getTimeToLoadFrag(O,w,j*_,m===void 0);if(w>=j&&(s===l||t.loadError===0&&t.fragmentError===0)&&(M<=O||!J(M)||v&&!this.bitrateTestDelay||M<c)){let e=this.forcedAutoLevel;return s!==h&&(e===-1||e!==h)&&(k.length&&this.trace(`Skipped level(s) ${k.join(`,`)} of ${n} max with CODECS and VIDEO-RANGE:"${p[k[0]].codecs}" ${p[k[0]].videoRange}; not compatible with "${b}" ${x}`),this.info(`switch candidate:${u}->${s} adjustedbw(${Math.round(w)})-bitrate=${Math.round(w-j)} ttfb:${O.toFixed(1)} avgDuration:${_.toFixed(1)} maxFetchDuration:${c.toFixed(1)} fetchDuration:${M.toFixed(1)} firstSelection:${y} codecSet:${t.codecSet} videoRange:${t.videoRange} hls.loadLevel:${h}`)),y&&(this.firstSelection=s),s}}return-1}set nextAutoLevel(e){let t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey=``,this._nextAutoLevel=t)}deriveNextAutoLevel(e){let{maxAutoLevel:t,minAutoLevel:n}=this.hls;return Math.min(Math.max(e,n),t)}},MH={search:function(e,t){let n=0,r=e.length-1,i=null,a=null;for(;n<=r;){i=(n+r)/2|0,a=e[i];let o=t(a);if(o>0)n=i+1;else if(o<0)r=i-1;else return a}return null}};function NH(e,t,n){if(t===null||!Array.isArray(e)||!e.length||!J(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;for(let r=0;r<e.length;++r){let i=e[r];if(LH(t,n,i))return i}return null}function PH(e,t,n=0,r=0,i=.005){let a=null;if(e){a=t[1+e.sn-t[0].sn]||null;let r=e.endDTS-n;r>0&&r<15e-7&&(n+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else n===0&&t[0].start===0&&(a=t[0]);if(a&&((!e||e.level===a.level)&&IH(n,r,a)===0||FH(a,e,Math.min(i,r))))return a;let o=MH.search(t,IH.bind(null,n,r));return o&&(o!==e||!a)?o:a}function FH(e,t,n){if(t&&t.start===0&&t.level<e.level&&(t.endPTS||0)>0){let r=t.tagList.reduce((e,t)=>(t[0]===`INF`&&(e+=parseFloat(t[1])),e),n);return e.start<=r}return!1}function IH(e=0,t=0,n){if(n.start<=e&&n.start+n.duration>e)return 0;let r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));return n.start+n.duration-r<=e?1:n.start-r>e&&n.start?-1:0}function LH(e,t,n){let r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>e}function RH(e,t,n){if(e&&e.startCC<=t&&e.endCC>=t){let r=e.fragments,{fragmentHint:i}=e;i&&(r=r.concat(i));let a;return MH.search(r,e=>e.cc<t?1:e.cc>t?-1:(a=e,e.end<=n?1:e.start>n?-1:0)),a||null}return null}function zH(e){switch(e.details){case X.FRAG_LOAD_TIMEOUT:case X.KEY_LOAD_TIMEOUT:case X.LEVEL_LOAD_TIMEOUT:case X.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function BH(e){return e.details.startsWith(`key`)}function VH(e){return BH(e)&&!!e.frag&&!e.frag.decryptdata}function HH(e,t){let n=zH(t);return e.default[`${n?`timeout`:`error`}Retry`]}function UH(e,t){let n=e.backoff===`linear`?1:2**t;return Math.min(n*e.retryDelayMs,e.maxRetryDelayMs)}function WH(e){return _B(_B({},e),{errorRetry:null,timeoutRetry:null})}function GH(e,t,n,r){if(!e)return!1;let i=r?.code,a=t<e.maxNumRetry&&(KH(i)||!!n);return e.shouldRetry?e.shouldRetry(e,t,n,r,a):a}function KH(e){return qH(e)||!!e&&(e<400||e>499)}function qH(e){return e===0&&navigator.onLine===!1}var JH={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},YH={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8},XH=class extends bB{constructor(e){super(`error-controller`,e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(Z.ERROR,this.onError,this),e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){let e=this.hls;e&&(e.off(Z.ERROR,this.onError,this),e.off(Z.ERROR,this.onErrorOut,this),e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===Q.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;let t=this.hls,n=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||n===-1?t.loadLevel:n}variantHasKey(e,t){if(e){var n;if((n=e.details)!=null&&n.hasKey(t))return!0;let r=e.audioGroups;if(r)return this.hls.allAudioTracks.filter(e=>r.indexOf(e.groupId)>=0).some(e=>e.details?.hasKey(t))}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var n;if(t.fatal)return;let r=this.hls,i=t.context;switch(t.details){case X.FRAG_LOAD_ERROR:case X.FRAG_LOAD_TIMEOUT:case X.KEY_LOAD_ERROR:case X.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case X.FRAG_PARSING_ERROR:if((n=t.frag)!=null&&n.gap){t.errorAction=ZH();return}case X.FRAG_GAP:case X.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=JH.SendAlternateToPenaltyBox;return;case X.LEVEL_EMPTY_ERROR:case X.LEVEL_PARSING_ERROR:{var a;let e=t.parent===Q.MAIN?t.level:r.loadLevel;t.details===X.LEVEL_EMPTY_ERROR&&(a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,e):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,e))}return;case X.LEVEL_LOAD_ERROR:case X.LEVEL_LOAD_TIMEOUT:typeof i?.level==`number`&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,i.level));return;case X.AUDIO_TRACK_LOAD_ERROR:case X.AUDIO_TRACK_LOAD_TIMEOUT:case X.SUBTITLE_LOAD_ERROR:case X.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){let e=r.loadLevelObj;if(e&&(i.type===dB.AUDIO_TRACK&&e.hasAudioGroup(i.groupId)||i.type===dB.SUBTITLE_TRACK&&e.hasSubtitleGroup(i.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,r.loadLevel),t.errorAction.action=JH.SendAlternateToPenaltyBox,t.errorAction.flags=YH.MoveAllAlternatesMatchingHost;return}}return;case X.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:JH.SendAlternateToPenaltyBox,flags:YH.MoveAllAlternatesMatchingHDCP};return;case X.KEY_SYSTEM_SESSION_UPDATE_FAILED:case X.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case X.KEY_SYSTEM_NO_SESSION:t.errorAction={action:JH.SendAlternateToPenaltyBox,flags:YH.MoveAllAlternatesMatchingKey};return;case X.BUFFER_ADD_CODEC_ERROR:case X.REMUX_ALLOC_ERROR:case X.BUFFER_APPEND_ERROR:t.errorAction||=this.getLevelSwitchAction(t,t.level??r.loadLevel);return;case X.INTERNAL_EXCEPTION:case X.BUFFER_APPENDING_ERROR:case X.BUFFER_FULL_ERROR:case X.LEVEL_SWITCH_ERROR:case X.BUFFER_STALLED_ERROR:case X.BUFFER_SEEK_OVER_HOLE:case X.BUFFER_NUDGE_ON_STALL:t.errorAction=ZH();return}t.type===Y.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=ZH())}getPlaylistRetryOrSwitchAction(e,t){let n=this.hls,r=HH(n.config.playlistLoadPolicy,e),i=this.playlistError++;if(GH(r,i,zH(e),e.response))return{action:JH.RetryRequest,flags:YH.None,retryConfig:r,retryCount:i};let a=this.getLevelSwitchAction(e,t);return r&&(a.retryConfig=r,a.retryCount=i),a}getFragRetryOrSwitchAction(e){let t=this.hls,n=this.getVariantLevelIndex(e.frag),r=t.levels[n],{fragLoadPolicy:i,keyLoadPolicy:a}=t.config,o=HH(BH(e)?a:i,e),s=t.levels.reduce((e,t)=>e+t.fragmentError,0);if(r&&(e.details!==X.FRAG_GAP&&r.fragmentError++,!VH(e)&&GH(o,s,zH(e),e.response)))return{action:JH.RetryRequest,flags:YH.None,retryConfig:o,retryCount:s};let c=this.getLevelSwitchAction(e,n);return o&&(c.retryConfig=o,c.retryCount=s),c}getLevelSwitchAction(e,t){let n=this.hls;t??=n.loadLevel;let r=this.hls.levels[t];if(r){let t=e.details;r.loadError++,t===X.BUFFER_APPEND_ERROR&&r.fragmentError++;let o=-1,{levels:s,loadLevel:c,minAutoLevel:l,maxAutoLevel:u}=n;!n.autoLevelEnabled&&!n.config.preserveManualLevelOnError&&(n.loadLevel=-1);let d=e.frag?.type,f=(d===Q.AUDIO&&t===X.FRAG_PARSING_ERROR||e.sourceBufferName===`audio`&&(t===X.BUFFER_ADD_CODEC_ERROR||t===X.BUFFER_APPEND_ERROR))&&s.some(({audioCodec:e})=>r.audioCodec!==e),p=e.sourceBufferName===`video`&&(t===X.BUFFER_ADD_CODEC_ERROR||t===X.BUFFER_APPEND_ERROR)&&s.some(({codecSet:e,audioCodec:t})=>r.codecSet!==e&&r.audioCodec===t),{type:m,groupId:h}=e.context??{};for(let n=s.length;n--;){let g=(n+c)%s.length;if(g!==c&&g>=l&&g<=u&&s[g].loadError===0){var i,a;let n=s[g];if(t===X.FRAG_GAP&&d===Q.MAIN&&e.frag){let t=s[g].details;if(t){let n=PH(e.frag,t.fragments,e.frag.start);if(n!=null&&n.gap)continue}}else if(m===dB.AUDIO_TRACK&&n.hasAudioGroup(h)||m===dB.SUBTITLE_TRACK&&n.hasSubtitleGroup(h))continue;else if(d===Q.AUDIO&&(i=r.audioGroups)!=null&&i.some(e=>n.hasAudioGroup(e))||d===Q.SUBTITLE&&(a=r.subtitleGroups)!=null&&a.some(e=>n.hasSubtitleGroup(e))||f&&r.audioCodec===n.audioCodec||p&&r.codecSet===n.codecSet||!f&&r.codecSet!==n.codecSet)continue;o=g;break}}if(o>-1&&n.loadLevel!==o)return e.levelRetry=!0,this.playlistError=0,{action:JH.SendAlternateToPenaltyBox,flags:YH.None,nextAutoLevel:o}}return{action:JH.SendAlternateToPenaltyBox,flags:YH.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){switch(t.errorAction?.action){case JH.DoNothing:break;case JH.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==X.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break;case JH.RetryRequest:break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){let t=this.hls,n=e.errorAction;if(!n)return;let{flags:r}=n,i=n.nextAutoLevel;switch(r){case YH.None:this.switchLevel(e,i);break;case YH.MoveAllAlternatesMatchingHDCP:{let r=this.getVariantLevelIndex(e.frag),i=t.levels[r]?.attrs[`HDCP-LEVEL`];if(n.hdcpLevel=i,i===`NONE`)this.warn(`HDCP policy resticted output with HDCP-LEVEL=NONE`);else if(i){t.maxHdcpLevel=aH[aH.indexOf(i)-1],n.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case YH.MoveAllAlternatesMatchingKey:{let t=e.decryptdata;if(t){let r=this.hls.levels,i=r.length;for(let n=i;n--;)this.variantHasKey(r[n],t)&&(this.log(`Banned key found in level ${n} (${r[n].bitrate}bps) or audio group "${r[n].audioGroups?.join(`,`)}" (${e.frag?.type} fragment) ${NB(t.keyId||[])}`),r[n].fragmentError++,r[n].loadError++,this.log(`Removing level ${n} with key error (${e.error})`),this.hls.removeLevel(n));let a=e.frag;if(this.hls.levels.length<i)n.resolved=!0;else if(a&&a.type!==Q.MAIN){let e=a.decryptdata;e&&!t.matches(e)&&(n.resolved=!0)}}break}}n.resolved||this.switchLevel(e,i)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===X.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!==`audiovideo`)){let t=qV(e.mimeType),n=this.hls.levels;for(let r=n.length;r--;)n[r][`${e.sourceBufferName}Codec`]===t&&(this.log(`Removing level ${r} for ${e.details} ("${t}" not supported)`),this.hls.removeLevel(r))}}};function ZH(e){let t={action:JH.DoNothing,flags:YH.None};return e&&(t.resolved=!0),t}var QH={NOT_LOADED:`NOT_LOADED`,APPENDING:`APPENDING`,PARTIAL:`PARTIAL`,OK:`OK`},$H=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){let{hls:e}=this;e&&(e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Z.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Z.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Z.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Z.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){let n=this.activePartLists[t];if(n)for(let t=n.length;t--;){let r=n[t];if(!r)break;if(r.start<=e&&e<=r.end&&r.loaded)return r}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,n){let{fragments:r}=this,i=Object.keys(r);for(let a=i.length;a--;){let o=r[i[a]];if(o?.body.type===t&&(!n||o.buffered)){let t=o.body;if(t.start<=e&&e<=t.end)return t}}return null}detectEvictedFragments(e,t,n,r,i){this.timeRanges&&(this.timeRanges[e]=t);let a=r?.fragment.sn||-1;Object.keys(this.fragments).forEach(r=>{let o=this.fragments[r];if(!o||a>=o.body.sn)return;if(!o.buffered&&(!o.loaded||i)){o.body.type===n&&this.removeFragment(o.body);return}let s=o.range[e];if(s){if(s.time.length===0){this.removeFragment(o.body);return}s.time.some(e=>{let n=!this.isTimeBuffered(e.startPTS,e.endPTS,t);return n&&this.removeFragment(o.body),n})}})}detectPartialFragments(e){let t=this.timeRanges;if(!t||e.frag.sn===`initSegment`)return;let n=e.frag,r=tU(n),i=this.fragments[r];if(!i||i.buffered&&n.gap)return;let a=!n.relurl;Object.keys(t).forEach(r=>{let o=n.elementaryStreams[r];if(!o)return;let s=t[r],c=a||o.partial===!0;i.range[r]=this.getBufferedTimes(n,e.part,c,s)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,n),eU(i)||this.removeParts(n.sn-1,n.type)):this.removeFragment(i.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){let n=this.activePartLists[t];n&&(this.activePartLists[t]=nU(n,t=>t.fragment.sn>=e))}fragBuffered(e,t){let n=tU(e),r=this.fragments[n];!r&&t&&(r=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),r&&(r.loaded=null,this.bufferedEnd(r,e))}getBufferedTimes(e,t,n,r){let i={time:[],partial:n},a=e.start,o=e.end,s=e.minEndPTS||o,c=e.maxStartPTS||a;for(let e=0;e<r.length;e++){let t=r.start(e)-this.bufferPadding,n=r.end(e)+this.bufferPadding;if(c>=t&&s<=n){i.time.push({startPTS:Math.max(a,r.start(e)),endPTS:Math.min(o,r.end(e))});break}else if(a<n&&o>t){let t=Math.max(a,r.start(e)),n=Math.min(o,r.end(e));n>t&&(i.partial=!0,i.time.push({startPTS:t,endPTS:n}))}else if(o<=t)break}return i}getPartialFragment(e){let t=null,n,r,i,a=0,{bufferPadding:o,fragments:s}=this;return Object.keys(s).forEach(c=>{let l=s[c];l&&eU(l)&&(r=l.body.start-o,i=l.body.end+o,e>=r&&e<=i&&(n=Math.min(e-r,i-e),a<=n&&(t=l.body,a=n)))}),t}isEndListAppended(e){let t=this.endListFragments[e];return t!==void 0&&(t.buffered||eU(t))}getState(e){let t=tU(e),n=this.fragments[t];return n?n.buffered?eU(n)?QH.PARTIAL:QH.OK:QH.APPENDING:QH.NOT_LOADED}isTimeBuffered(e,t,n){let r,i;for(let a=0;a<n.length;a++){if(r=n.start(a)-this.bufferPadding,i=n.end(a)+this.bufferPadding,e>=r&&t<=i)return!0;if(t<=r)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn===`initSegment`||t.frag.bitrateTest)return;let n=t.frag,r=t.part?null:t,i=tU(n);this.fragments[i]={body:n,appendedPTS:null,loaded:r,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){let{frag:n,part:r,timeRanges:i,type:a}=t;if(n.sn===`initSegment`)return;let o=n.type;if(r){let e=this.activePartLists[o];e||(this.activePartLists[o]=e=[]),e.push(r)}this.timeRanges=i;let s=i[a];this.detectEvictedFragments(a,s,o,r)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){let t=tU(e);return!!this.fragments[t]}hasFragments(e){let{fragments:t}=this,n=Object.keys(t);if(!e)return n.length>0;for(let r=n.length;r--;)if(t[n[r]]?.body.type===e)return!0;return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,n,r,i){r&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{let o=this.fragments[a];if(!o)return;let s=o.body;s.type!==n||r&&!s.gap||s.start<t&&s.end>e&&(o.buffered||i)&&this.removeFragment(s)})}removeFragment(e){let t=tU(e);e.clearElementaryStreamInfo();let n=this.activePartLists[e.type];if(n){let t=e.sn;this.activePartLists[e.type]=nU(n,e=>e.fragment.sn!==t)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;let t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(e=>e.clearElementaryStreamInfo())}};function eU(e){var t,n,r;return e.buffered&&!!(e.body.gap||(t=e.range.video)!=null&&t.partial||(n=e.range.audio)!=null&&n.partial||(r=e.range.audiovideo)!=null&&r.partial)}function tU(e){return`${e.type}_${e.level}_${e.sn}`}function nU(e,t){return e.filter(e=>{let n=t(e);return n||e.clearElementaryStreamInfo(),n})}var rU={cbc:0,ctr:1},iU=class{constructor(e,t,n){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=n}decrypt(e,t){switch(this.aesMode){case rU.cbc:return this.subtle.decrypt({name:`AES-CBC`,iv:this.aesIV},t,e);case rU.ctr:return this.subtle.decrypt({name:`AES-CTR`,counter:this.aesIV,length:64},t,e);default:throw Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function aU(e){let t=e.byteLength,n=t&&new DataView(e.buffer).getUint8(t-1);return n?e.slice(0,t-n):e}var oU=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array,this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){let t=new DataView(e),n=new Uint32Array(4);for(let e=0;e<4;e++)n[e]=t.getUint32(e*4);return n}initTable(){let e=this.sBox,t=this.invSBox,n=this.subMix,r=n[0],i=n[1],a=n[2],o=n[3],s=this.invSubMix,c=s[0],l=s[1],u=s[2],d=s[3],f=new Uint32Array(256),p=0,m=0,h=0;for(h=0;h<256;h++)h<128?f[h]=h<<1:f[h]=h<<1^283;for(h=0;h<256;h++){let n=m^m<<1^m<<2^m<<3^m<<4;n=n>>>8^n&255^99,e[p]=n,t[n]=p;let s=f[p],h=f[s],g=f[h],_=f[n]*257^n*16843008;r[p]=_<<24|_>>>8,i[p]=_<<16|_>>>16,a[p]=_<<8|_>>>24,o[p]=_,_=g*16843009^h*65537^s*257^p*16843008,c[n]=_<<24|_>>>8,l[n]=_<<16|_>>>16,u[n]=_<<8|_>>>24,d[n]=_,p?(p=s^f[f[f[g^s]]],m^=f[f[m]]):p=m=1}}expandKey(e){let t=this.uint8ArrayToUint32Array_(e),n=!0,r=0;for(;r<t.length&&n;)n=t[r]===this.key[r],r++;if(n)return;this.key=t;let i=this.keySize=t.length;if(i!==4&&i!==6&&i!==8)throw Error(`Invalid aes key size=`+i);let a=this.ksRows=(i+6+1)*4,o,s,c=this.keySchedule=new Uint32Array(a),l=this.invKeySchedule=new Uint32Array(a),u=this.sBox,d=this.rcon,f=this.invSubMix,p=f[0],m=f[1],h=f[2],g=f[3],_,v;for(o=0;o<a;o++){if(o<i){_=c[o]=t[o];continue}v=_,o%i===0?(v=v<<8|v>>>24,v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255],v^=d[o/i|0]<<24):i>6&&o%i===4&&(v=u[v>>>24]<<24|u[v>>>16&255]<<16|u[v>>>8&255]<<8|u[v&255]),c[o]=_=(c[o-i]^v)>>>0}for(s=0;s<a;s++)o=a-s,v=s&3?c[o]:c[o-4],s<4||o<=4?l[s]=v:l[s]=p[u[v>>>24]]^m[u[v>>>16&255]]^h[u[v>>>8&255]]^g[u[v&255]],l[s]=l[s]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,n){let r=this.keySize+6,i=this.invKeySchedule,a=this.invSBox,o=this.invSubMix,s=o[0],c=o[1],l=o[2],u=o[3],d=this.uint8ArrayToUint32Array_(n),f=d[0],p=d[1],m=d[2],h=d[3],g=new Int32Array(e),_=new Int32Array(g.length),v,y,b,x,S,C,w,T,E,D,O,k,A,j,M=this.networkToHostOrderSwap;for(;t<g.length;){for(E=M(g[t]),D=M(g[t+1]),O=M(g[t+2]),k=M(g[t+3]),S=E^i[0],C=k^i[1],w=O^i[2],T=D^i[3],A=4,j=1;j<r;j++)v=s[S>>>24]^c[C>>16&255]^l[w>>8&255]^u[T&255]^i[A],y=s[C>>>24]^c[w>>16&255]^l[T>>8&255]^u[S&255]^i[A+1],b=s[w>>>24]^c[T>>16&255]^l[S>>8&255]^u[C&255]^i[A+2],x=s[T>>>24]^c[S>>16&255]^l[C>>8&255]^u[w&255]^i[A+3],S=v,C=y,w=b,T=x,A+=4;v=a[S>>>24]<<24^a[C>>16&255]<<16^a[w>>8&255]<<8^a[T&255]^i[A],y=a[C>>>24]<<24^a[w>>16&255]<<16^a[T>>8&255]<<8^a[S&255]^i[A+1],b=a[w>>>24]<<24^a[T>>16&255]<<16^a[S>>8&255]<<8^a[C&255]^i[A+2],x=a[T>>>24]<<24^a[S>>16&255]<<16^a[C>>8&255]<<8^a[w&255]^i[A+3],_[t]=M(v^f),_[t+1]=M(x^p),_[t+2]=M(b^m),_[t+3]=M(y^h),f=E,p=D,m=O,h=k,t+=4}return _.buffer}},sU=class{constructor(e,t,n){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=n}expandKey(){let e=cU(this.aesMode);return this.subtle.importKey(`raw`,this.key,{name:e},!1,[`encrypt`,`decrypt`])}};function cU(e){switch(e){case rU.cbc:return`AES-CBC`;case rU.ctr:return`AES-CTR`;default:throw Error(`[FastAESKey] invalid aes mode ${e}`)}}var lU=16,uU=class{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{let e=self.crypto;e&&(this.subtle=e.subtle||e.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){let{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;let n=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?aU(n):n}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&=null}decrypt(e,t,n,r){return this.useSoftware?new Promise((i,a)=>{let o=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(o,t,n,r);let s=this.flush();s?i(s.buffer):a(Error(`[softwareDecrypt] Failed to decrypt data`))}):this.webCryptoDecrypt(new Uint8Array(e),t,n,r)}softwareDecrypt(e,t,n,r){let{currentIV:i,currentResult:a,remainderData:o}=this;if(r!==rU.cbc||t.byteLength!==16)return OB.warn(`SoftwareDecrypt: can only handle AES-128-CBC`),null;this.logOnce(`JS AES decrypt`),o&&(e=vV(o,e),this.remainderData=null);let s=this.getValidChunk(e);if(!s.length)return null;i&&(n=i);let c=this.softwareDecrypter;c||=this.softwareDecrypter=new oU,c.expandKey(t);let l=a;return this.currentResult=c.decrypt(s.buffer,0,n),this.currentIV=s.slice(-16).buffer,l||null}webCryptoDecrypt(e,t,n,r){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,n,r));this.key=t,this.fastAesKey=new sU(this.subtle,t,r)}return this.fastAesKey.expandKey().then(t=>this.subtle?(this.logOnce(`WebCrypto AES decrypt`),new iU(this.subtle,new Uint8Array(n),r).decrypt(e.buffer,t)):Promise.reject(Error(`web crypto not initialized`))).catch(i=>(OB.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,t,n,r)))}onWebCryptoError(e,t,n,r){let i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,n,r);let i=this.flush();if(i)return i.buffer}throw Error(`WebCrypto`+(i?` and softwareDecrypt`:``)+`: failed to decrypt data`)}getValidChunk(e){let t=e,n=e.length-e.length%lU;return n!==e.length&&(t=e.slice(0,n),this.remainderData=e.slice(n)),t}logOnce(e){this.logEnabled&&=(OB.log(`[decrypter]: ${e}`),!1)}},dU=2**17,fU=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&=(this.loader.destroy(),null)}abort(){this.loader&&this.loader.abort()}load(e,t){let n=e.url;if(!n)return Promise.reject(new gU({type:Y.NETWORK_ERROR,details:X.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:Error(`Fragment does not have a ${n?`part list`:`url`}`),networkDetails:null}));this.abort();let r=this.config,i=r.fLoader,a=r.loader;return new Promise((o,s)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(e=>e[0]===`GAP`)){s(mU(e));return}else e.gap=!1;let c=this.loader=i?new i(r):new a(r),l=pU(e);e.loader=c;let u=WH(r.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn===`initSegment`?1/0:dU};e.stats=c.stats;let f={onSuccess:(t,n,r,i)=>{this.resetLoader(e,c);let a=t.data;r.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(a.slice(0,16)),a=a.slice(16)),o({frag:e,part:null,payload:a,networkDetails:i})},onError:(t,r,i,a)=>{this.resetLoader(e,c),s(new gU({type:Y.NETWORK_ERROR,details:X.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:_B({url:n,data:void 0},t),error:Error(`HTTP Error ${t.code} ${t.text}`),networkDetails:i,stats:a}))},onAbort:(t,n,r)=>{this.resetLoader(e,c),s(new gU({type:Y.NETWORK_ERROR,details:X.INTERNAL_ABORTED,fatal:!1,frag:e,error:Error(`Aborted`),networkDetails:r,stats:t}))},onTimeout:(t,n,r)=>{this.resetLoader(e,c),s(new gU({type:Y.NETWORK_ERROR,details:X.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:Error(`Timeout after ${d.timeout}ms`),networkDetails:r,stats:t}))}};t&&(f.onProgress=(n,r,i,a)=>t({frag:e,part:null,payload:i,networkDetails:a})),c.load(l,d,f)})}loadPart(e,t,n){this.abort();let r=this.config,i=r.fLoader,a=r.loader;return new Promise((o,s)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){s(mU(e,t));return}let c=this.loader=i?new i(r):new a(r),l=pU(e,t);e.loader=c;let u=WH(r.fragLoadPolicy.default),d={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:dU};t.stats=c.stats,c.load(l,d,{onSuccess:(r,i,a,s)=>{this.resetLoader(e,c),this.updateStatsFromPart(e,t);let l={frag:e,part:t,payload:r.data,networkDetails:s};n(l),o(l)},onError:(n,r,i,a)=>{this.resetLoader(e,c),s(new gU({type:Y.NETWORK_ERROR,details:X.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:_B({url:l.url,data:void 0},n),error:Error(`HTTP Error ${n.code} ${n.text}`),networkDetails:i,stats:a}))},onAbort:(n,r,i)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,c),s(new gU({type:Y.NETWORK_ERROR,details:X.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:Error(`Aborted`),networkDetails:i,stats:n}))},onTimeout:(n,r,i)=>{this.resetLoader(e,c),s(new gU({type:Y.NETWORK_ERROR,details:X.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:Error(`Timeout after ${d.timeout}ms`),networkDetails:i,stats:n}))}})})}updateStatsFromPart(e,t){let n=e.stats,r=t.stats,i=r.total;if(n.loaded+=r.loaded,i){let r=Math.round(e.duration/t.duration),a=Math.min(Math.round(n.loaded/i),r),o=(r-a)*Math.round(n.loaded/a);n.total=n.loaded+o}else n.total=Math.max(n.loaded,n.total);let a=n.loading,o=r.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function pU(e,t=null){let n=t||e,r={frag:e,part:t,responseType:`arraybuffer`,url:n.url,headers:{},rangeStart:0,rangeEnd:0},i=n.byteRangeStartOffset,a=n.byteRangeEndOffset;if(J(i)&&J(a)){let t=i,n=a;if(e.sn===`initSegment`&&hU(e.decryptdata?.method)){let e=a-i;e%16&&(n=a+(16-e%16)),i!==0&&(r.resetIV=!0,t=i-16)}r.rangeStart=t,r.rangeEnd=n}return r}function mU(e,t){let n=Error(`GAP ${e.gap?`tag`:`attribute`} found`),r={type:Y.MEDIA_ERROR,details:X.FRAG_GAP,fatal:!1,frag:e,error:n,networkDetails:null};return t&&(r.part=t),(t||e).stats.aborted=!0,new gU(r)}function hU(e){return e===`AES-128`||e===`AES-256`}var gU=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},_U=class extends bB{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},vU=class{constructor(e,t,n,r=0,i=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=yU(),this.buffering={audio:yU(),video:yU(),audiovideo:yU()},this.level=e,this.sn=t,this.id=n,this.size=r,this.part=i,this.partial=a}};function yU(){return{start:0,executeStart:0,executeEnd:0,end:0}}var bU={length:0,start:()=>0,end:()=>0},xU=class e{static isBuffered(t,n){if(t){let r=e.getBuffered(t);for(let e=r.length;e--;)if(n>=r.start(e)&&n<=r.end(e))return!0}return!1}static bufferedRanges(t){if(t){let n=e.getBuffered(t);return e.timeRangesToArray(n)}return[]}static timeRangesToArray(e){let t=[];for(let n=0;n<e.length;n++)t.push({start:e.start(n),end:e.end(n)});return t}static bufferInfo(t,n,r){if(t){let i=e.bufferedRanges(t);if(i.length)return e.bufferedInfo(i,n,r)}return{len:0,start:n,end:n,bufferedIndex:-1}}static bufferedInfo(e,t,n){t=Math.max(0,t),e.length>1&&e.sort((e,t)=>e.start-t.start||t.end-e.end);let r=-1,i=[];if(n)for(let a=0;a<e.length;a++){t>=e[a].start&&t<=e[a].end&&(r=a);let o=i.length;if(o){let t=i[o-1].end;e[a].start-t<n?e[a].end>t&&(i[o-1].end=e[a].end):i.push(e[a])}else i.push(e[a])}else i=e;let a=0,o,s=t,c=t;for(let e=0;e<i.length;e++){let l=i[e].start,u=i[e].end;if(r===-1&&t>=l&&t<=u&&(r=e),t+n>=l&&t<u)s=l,c=u,a=c-t;else if(t+n<l){o=l;break}}return{len:a,start:s||0,end:c||0,nextStart:o,buffered:e,bufferedIndex:r}}static getBuffered(e){try{return e.buffered||bU}catch(e){return OB.log(`failed to get media.buffered`,e),bU}}},SU=/\{\$([a-zA-Z0-9-_]+)\}/g;function CU(e){return SU.test(e)}function wU(e,t){if(e.variableList!==null||e.hasVariableRefs){let n=e.variableList;return t.replace(SU,t=>{let r=t.substring(2,t.length-1),i=n?.[r];return i===void 0?(e.playlistParsingError||=Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${r}"`),t):i})}return t}function TU(e,t,n){let r=e.variableList;r||(e.variableList=r={});let i,a;if(`QUERYPARAM`in t){i=t.QUERYPARAM;try{let e=new self.URL(n).searchParams;if(e.has(i))a=e.get(i);else throw Error(`"${i}" does not match any query parameter in URI: "${n}"`)}catch(t){e.playlistParsingError||=Error(`EXT-X-DEFINE QUERYPARAM: ${t.message}`)}}else i=t.NAME,a=t.VALUE;i in r?e.playlistParsingError||=Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`):r[i]=a||``}function EU(e,t,n){let r=t.IMPORT;if(n&&r in n){let t=e.variableList;t||(e.variableList=t={}),t[r]=n[r]}else e.playlistParsingError||=Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`)}var DU=/^(\d+)x(\d+)$/,OU=/(.+?)=(".*?"|.*?)(?:,|$)/g,kU=class e{constructor(t,n){typeof t==`string`&&(t=e.parseAttrList(t,n)),hB(this,t)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)===`X-`)}decimalInteger(e){let t=parseInt(this[e],10);return t>2**53-1?1/0:t}hexadecimalInteger(e){if(this[e]){let t=(this[e]||`0x`).slice(2);t=(t.length&1?`0`:``)+t;let n=new Uint8Array(t.length/2);for(let e=0;e<t.length/2;e++)n[e]=parseInt(t.slice(e*2,e*2+2),16);return n}return null}hexadecimalIntegerAsNumber(e){let t=parseInt(this[e],16);return t>2**53-1?1/0:t}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,t){let n=this[e];return n?parseFloat(n):t}enumeratedString(e){return this[e]}enumeratedStringList(e,t){let n=this[e];return(n?n.split(/[ ,]+/):[]).reduce((e,t)=>(e[t.toLowerCase()]=!0,e),t)}bool(e){return this[e]===`YES`}decimalResolution(e){let t=DU.exec(this[e]);if(t!==null)return{width:parseInt(t[1],10),height:parseInt(t[2],10)}}static parseAttrList(e,t){let n,r={};for(OU.lastIndex=0;(n=OU.exec(e))!==null;){let i=n[1].trim(),a=n[2],o=a.indexOf(`"`)===0&&a.lastIndexOf(`"`)===a.length-1,s=!1;if(o)a=a.slice(1,-1);else switch(i){case`IV`:case`SCTE35-CMD`:case`SCTE35-IN`:case`SCTE35-OUT`:s=!0}if(t&&(o||s))a=wU(t,a);else if(!s&&!o)switch(i){case`CLOSED-CAPTIONS`:if(a===`NONE`)break;case`ALLOWED-CPC`:case`CLASS`:case`ASSOC-LANGUAGE`:case`AUDIO`:case`BYTERANGE`:case`CHANNELS`:case`CHARACTERISTICS`:case`CODECS`:case`DATA-ID`:case`END-DATE`:case`GROUP-ID`:case`ID`:case`IMPORT`:case`INSTREAM-ID`:case`KEYFORMAT`:case`KEYFORMATVERSIONS`:case`LANGUAGE`:case`NAME`:case`PATHWAY-ID`:case`QUERYPARAM`:case`RECENTLY-REMOVED-DATERANGES`:case`SERVER-URI`:case`STABLE-RENDITION-ID`:case`STABLE-VARIANT-ID`:case`START-DATE`:case`SUBTITLES`:case`SUPPLEMENTAL-CODECS`:case`URI`:case`VALUE`:case`VIDEO`:case`X-ASSET-LIST`:case`X-ASSET-URI`:OB.warn(`${e}: attribute ${i} is missing quotes`)}r[i]=a}return r}},AU=`com.apple.hls.interstitial`;function jU(e){return e!==`ID`&&e!==`CLASS`&&e!==`CUE`&&e!==`START-DATE`&&e!==`DURATION`&&e!==`END-DATE`&&e!==`END-ON-NEXT`}function MU(e){return e===`SCTE35-OUT`||e===`SCTE35-IN`||e===`SCTE35-CMD`}var NU=class{constructor(e,t,n=0){if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=t?.tagOrder??n,t){let n=t.attr;for(let t in n)if(Object.prototype.hasOwnProperty.call(e,t)&&e[t]!==n[t]){OB.warn(`DATERANGE tag attribute: "${t}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=t;break}e=hB(new kU({}),n,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e[`START-DATE`]),`END-DATE`in this.attr){let e=t?.endDate||new Date(this.attr[`END-DATE`]);J(e.getTime())&&(this._endDate=e)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){let e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?`CUE`:`X-CUE`,{pre:!1,post:!1,once:!1}):e}get startTime(){let{tagAnchor:e}=this;return e===null||e.programDateTime===null?(OB.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){let e=this._endDate||this._dateAtEnd;if(e)return e;let t=this.duration;return t===null?null:this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3)}get duration(){if(`DURATION`in this.attr){let e=this.attr.decimalFloatingPoint(`DURATION`);if(J(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return`PLANNED-DURATION`in this.attr?this.attr.decimalFloatingPoint(`PLANNED-DURATION`):null}get endOnNext(){return this.attr.bool(`END-ON-NEXT`)}get isInterstitial(){return this.class===AU}get isValid(){return!!this.id&&!this._badValueForSameId&&J(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||`X-ASSET-URI`in this.attr||`X-ASSET-LIST`in this.attr)}},PU=10,FU=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8=``,this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}let t=this.lastPartSn-e.lastPartSn,n=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!n||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&n>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let n=t.decryptdata;return n||=(t.setKeyFormat(e.keyFormat),t.decryptdata),!!n&&e.matches(n)})}get hasProgramDateTime(){return this.fragments.length?J(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||PU}get drift(){let e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){let e=this.partList;if(e){let t=this.lastPartIndex;if(t!==-1){for(let n=e.length;n--;)if(e[n].index>t)return e[n].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){let e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}};function IU(e,t){return e.length===t.length?!e.some((e,n)=>e!==t[n]):!1}function LU(e,t){return!e&&!t?!0:!e||!t?!1:IU(e,t)}function RU(e){return e===`AES-128`||e===`AES-256`||e===`AES-256-CTR`}function zU(e){switch(e){case`AES-128`:case`AES-256`:return rU.cbc;case`AES-256-CTR`:return rU.ctr;default:throw Error(`invalid full segment method ${e}`)}}function BU(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0))}function VU(e){return Uint8Array.from(unescape(encodeURIComponent(e)),e=>e.charCodeAt(0))}function HU(e){let t=VU(e).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function UU(e){let t=function(e,t,n){let r=e[t];e[t]=e[n],e[n]=r};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function WU(e){let t=e.split(`:`),n=null;if(t[0]===`data`&&t.length===2){let e=t[1].split(`;`),r=e[e.length-1].split(`,`);if(r.length===2){let t=r[0]===`base64`,i=r[1];t?(e.splice(-1,1),n=BU(i)):n=HU(i)}}return n}var GU=typeof self<`u`?self:void 0,KU={CLEARKEY:`org.w3.clearkey`,FAIRPLAY:`com.apple.fps`,PLAYREADY:`com.microsoft.playready`,WIDEVINE:`com.widevine.alpha`},qU={CLEARKEY:`org.w3.clearkey`,FAIRPLAY:`com.apple.streamingkeydelivery`,PLAYREADY:`com.microsoft.playready`,WIDEVINE:`urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed`};function JU(e){switch(e){case qU.FAIRPLAY:return KU.FAIRPLAY;case qU.PLAYREADY:return KU.PLAYREADY;case qU.WIDEVINE:return KU.WIDEVINE;case qU.CLEARKEY:return KU.CLEARKEY}}function YU(e){switch(e){case KU.FAIRPLAY:return qU.FAIRPLAY;case KU.PLAYREADY:return qU.PLAYREADY;case KU.WIDEVINE:return qU.WIDEVINE;case KU.CLEARKEY:return qU.CLEARKEY}}function XU(e){let{drmSystems:t,widevineLicenseUrl:n}=e,r=t?[KU.FAIRPLAY,KU.WIDEVINE,KU.PLAYREADY,KU.CLEARKEY].filter(e=>!!t[e]):[];return!r[KU.WIDEVINE]&&n&&r.push(KU.WIDEVINE),r}var ZU=function(e){return GU!=null&&(e=GU.navigator)!=null&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function QU(e,t,n,r){let i;switch(e){case KU.FAIRPLAY:i=[`cenc`,`sinf`];break;case KU.WIDEVINE:case KU.PLAYREADY:i=[`cenc`];break;case KU.CLEARKEY:i=[`cenc`,`keyids`];break;default:throw Error(`Unknown key-system: ${e}`)}return $U(i,t,n,r)}function $U(e,t,n,r){return[{initDataTypes:e,persistentState:r.persistentState||`optional`,distinctiveIdentifier:r.distinctiveIdentifier||`optional`,sessionTypes:r.sessionTypes||[r.sessionType||`temporary`],audioCapabilities:t.map(e=>({contentType:`audio/mp4; codecs=${e}`,robustness:r.audioRobustness||``,encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:n.map(e=>({contentType:`video/mp4; codecs=${e}`,robustness:r.videoRobustness||``,encryptionScheme:r.videoEncryptionScheme||null}))}]}function eW(e){var t;return!!e&&(e.sessionType===`persistent-license`||!!((t=e.sessionTypes)!=null&&t.some(e=>e===`persistent-license`)))}function tW(e){let t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),n=String.fromCharCode.apply(null,Array.from(t)),r=n.substring(n.indexOf(`<`),n.length),i=new DOMParser().parseFromString(r,`text/xml`).getElementsByTagName(`KID`)[0];if(i){let e=i.childNodes[0]?i.childNodes[0].nodeValue:i.getAttribute(`VALUE`);if(e){let t=BU(e).subarray(0,16);return UU(t),t}}return null}var nW={},rW=class e{static clearKeyUriToKeyIdMap(){nW={}}static setKeyIdForUri(e,t){nW[e]=t}static addKeyIdForUri(e){let t=Object.keys(nW).length%(2**53-1),n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,t),nW[e]=n,n}constructor(e,t,n,r=[1],i=null,a){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=e,this.uri=t,this.keyFormat=n,this.keyFormatVersions=r,this.iv=i,this.encrypted=e?e!==`NONE`:!1,this.isCommonEncryption=this.encrypted&&!RU(e),a!=null&&a.startsWith(`0x`)&&(this.keyId=new Uint8Array(PB(a)))}matches(e){return e.uri===this.uri&&e.method===this.method&&e.encrypted===this.encrypted&&e.keyFormat===this.keyFormat&&IU(e.keyFormatVersions,this.keyFormatVersions)&&LU(e.iv,this.iv)&&LU(e.keyId,this.keyId)}isSupported(){if(this.method){if(RU(this.method)||this.method===`NONE`)return!0;if(this.keyFormat===`identity`)return this.method===`SAMPLE-AES`;switch(this.keyFormat){case qU.FAIRPLAY:case qU.WIDEVINE:case qU.PLAYREADY:case qU.CLEARKEY:return[`SAMPLE-AES`,`SAMPLE-AES-CENC`,`SAMPLE-AES-CTR`].indexOf(this.method)!==-1}}return!1}getDecryptData(t,n){if(!this.encrypted||!this.uri)return null;if(RU(this.method)){let n=this.iv;return n||=(typeof t!=`number`&&(OB.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),oW(t)),new e(this.method,this.uri,`identity`,this.keyFormatVersions,n)}if(this.keyId){let t=nW[this.uri];if(t&&!IU(this.keyId,t)&&e.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}let r=WU(this.uri);if(r)switch(this.keyFormat){case qU.WIDEVINE:if(this.pssh=r,!this.keyId){let e=DV(r.buffer);if(e.length){var i;let t=e[0];this.keyId=(i=t.kids)!=null&&i.length?t.kids[0]:null}}this.keyId||=aW(n);break;case qU.PLAYREADY:{let e=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=EV(e,null,r),this.keyId=tW(r);break}default:{let e=r.subarray(0,16);if(e.length!==16){let t=new Uint8Array(16);t.set(e,16-e.length),e=t}this.keyId=e;break}}if(!this.keyId||this.keyId.byteLength!==16){let t;t=iW(n),t||(t=aW(n),t||=nW[this.uri]),t&&(this.keyId=t,e.setKeyIdForUri(this.uri,t))}return this}};function iW(e){let t=e?.[qU.WIDEVINE];return t?t.keyId:null}function aW(e){let t=e?.[qU.PLAYREADY];if(t){let e=WU(t.uri);if(e)return tW(e)}return null}function oW(e){let t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=e>>8*(15-n)&255;return t}var sW=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,cW=/#EXT-X-MEDIA:(.*)/g,lW=/^#EXT(?:INF|-X-TARGETDURATION):/m,uW=new RegExp([`#EXTINF:\\s*(\\d*(?:\\.\\d+)?)(?:,(.*)\\s+)?`,`(?!#) *(\\S[^\\r\\n]*)`,`#.*`].join(`|`),`g`),dW=new RegExp([`#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)`,`#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\\d+)`,`#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)`,`(#)([^:]*):(.*)`,`(#)(.*)(?:.*)\\r?\\n?`].join(`|`)),fW=class e{static findGroup(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r.id===t)return r}}static resolve(e,t){return zB.buildAbsoluteURL(t,e,{alwaysNormalize:!0})}static isMediaPlaylist(e){return lW.test(e)}static parseMasterPlaylist(t,n){let r={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:CU(t)},i=[];if(sW.lastIndex=0,!t.startsWith(`#EXTM3U`))return r.playlistParsingError=Error(`no EXTM3U delimiter`),r;let a;for(;(a=sW.exec(t))!=null;)if(a[1]){var o;let t=new kU(a[1],r),s=wU(r,a[2]),c={attrs:t,bitrate:t.decimalInteger(`BANDWIDTH`)||t.decimalInteger(`AVERAGE-BANDWIDTH`),name:t.NAME,url:e.resolve(s,n)},l=t.decimalResolution(`RESOLUTION`);l&&(c.width=l.width,c.height=l.height),_W(t.CODECS,c);let u=t[`SUPPLEMENTAL-CODECS`];u&&(c.supplemental={},_W(u,c.supplemental)),(o=c.unknownCodecs)!=null&&o.length||i.push(c),r.levels.push(c)}else if(a[3]){let t=a[3],i=a[4];switch(t){case`SESSION-DATA`:{let e=new kU(i,r),t=e[`DATA-ID`];t&&(r.sessionData===null&&(r.sessionData={}),r.sessionData[t]=e);break}case`SESSION-KEY`:{let e=hW(i,n,r);e.encrypted&&e.isSupported()?(r.sessionKeys===null&&(r.sessionKeys=[]),r.sessionKeys.push(e)):OB.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${i}"`);break}case`DEFINE`:TU(r,new kU(i,r),n);break;case`CONTENT-STEERING`:{let t=new kU(i,r);r.contentSteering={uri:e.resolve(t[`SERVER-URI`],n),pathwayId:t[`PATHWAY-ID`]||`.`};break}case`START`:r.startTimeOffset=gW(i);break}}return r.levels=i.length>0&&i.length<r.levels.length?i:r.levels,r.levels.length===0&&(r.playlistParsingError=Error(`no levels found in manifest`)),r}static parseMasterPlaylistMedia(t,n,r){let i,a={},o=r.levels,s={AUDIO:o.map(e=>({id:e.attrs.AUDIO,audioCodec:e.audioCodec})),SUBTITLES:o.map(e=>({id:e.attrs.SUBTITLES,textCodec:e.textCodec})),"CLOSED-CAPTIONS":[]},c=0;for(cW.lastIndex=0;(i=cW.exec(t))!==null;){let t=new kU(i[1],r),o=t.TYPE;if(o){let r=s[o],i=a[o]||[];a[o]=i;let l=t.LANGUAGE,u=t[`ASSOC-LANGUAGE`],d=t.CHANNELS,f=t.CHARACTERISTICS,p=t[`INSTREAM-ID`],m={attrs:t,bitrate:0,id:c++,groupId:t[`GROUP-ID`]||``,name:t.NAME||l||``,type:o,default:t.bool(`DEFAULT`),autoselect:t.bool(`AUTOSELECT`),forced:t.bool(`FORCED`),lang:l,url:t.URI?e.resolve(t.URI,n):``};if(u&&(m.assocLang=u),d&&(m.channels=d),f&&(m.characteristics=f),p&&(m.instreamId=p),r!=null&&r.length){let t=e.findGroup(r,m.groupId)||r[0];vW(m,t,`audioCodec`),vW(m,t,`textCodec`)}i.push(m)}}return a}static parseLevelPlaylist(e,t,n,r,i,a){let o={url:t},s=new FU(t),c=s.fragments,l=[],u=null,d=0,f=0,p=0,m=0,h=0,g=null,_=new WB(r,o),v,y,b,x=-1,S=!1,C=null,w;if(uW.lastIndex=0,s.m3u8=e,s.hasVariableRefs=CU(e),uW.exec(e)?.[0]!==`#EXTM3U`)return s.playlistParsingError=Error(`Missing format identifier #EXTM3U`),s;for(;(v=uW.exec(e))!==null;){S&&(S=!1,_=new WB(r,o),_.playlistOffset=p,_.setStart(p),_.sn=d,_.cc=m,h&&(_.bitrate=h),_.level=n,u&&(_.initSegment=u,u.rawProgramDateTime&&(_.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null),C&&=(_.setByteRange(C),null)));let e=v[1];if(e){_.duration=parseFloat(e);let t=(` `+v[2]).slice(1);_.title=t||null,_.tagList.push(t?[`INF`,e,t]:[`INF`,e])}else if(v[3]){if(J(_.duration)){_.playlistOffset=p,_.setStart(p),b&&SW(_,b,s),_.sn=d,_.level=n,_.cc=m,c.push(_);let e=(` `+v[3]).slice(1);_.relurl=wU(s,e),bW(_,g,l),g=_,p+=_.duration,d++,f=0,S=!0}}else{if(v=v[0].match(dW),!v){OB.warn(`No matches on slow regex match for level playlist!`);continue}for(y=1;y<v.length&&v[y]===void 0;y++);let e=(` `+v[y]).slice(1),i=(` `+v[y+1]).slice(1),l=v[y+2]?(` `+v[y+2]).slice(1):null;switch(e){case`BYTERANGE`:g?_.setByteRange(i,g):_.setByteRange(i);break;case`PROGRAM-DATE-TIME`:_.rawProgramDateTime=i,_.tagList.push([`PROGRAM-DATE-TIME`,i]),x===-1&&(x=c.length);break;case`PLAYLIST-TYPE`:s.type&&CW(s,e,v),s.type=i.toUpperCase();break;case`MEDIA-SEQUENCE`:s.startSN===0?c.length>0&&wW(s,e,v):CW(s,e,v),d=s.startSN=parseInt(i);break;case`SKIP`:{s.skippedSegments&&CW(s,e,v);let t=new kU(i,s),n=t.decimalInteger(`SKIPPED-SEGMENTS`);if(J(n)){s.skippedSegments+=n;for(let e=n;e--;)c.push(null);d+=n}let r=t.enumeratedString(`RECENTLY-REMOVED-DATERANGES`);r&&(s.recentlyRemovedDateranges=(s.recentlyRemovedDateranges||[]).concat(r.split(` `)));break}case`TARGETDURATION`:s.targetduration!==0&&CW(s,e,v),s.targetduration=Math.max(parseInt(i),1);break;case`VERSION`:s.version!==null&&CW(s,e,v),s.version=parseInt(i);break;case`INDEPENDENT-SEGMENTS`:break;case`ENDLIST`:s.live||CW(s,e,v),s.live=!1;break;case`#`:(i||l)&&_.tagList.push(l?[i,l]:[i]);break;case`DISCONTINUITY`:m++,_.tagList.push([`DIS`]);break;case`GAP`:_.gap=!0,_.tagList.push([e]);break;case`BITRATE`:_.tagList.push([e,i]),h=parseInt(i)*1e3,J(h)?_.bitrate=h:h=0;break;case`DATERANGE`:{let e=new kU(i,s),t=new NU(e,s.dateRanges[e.ID],s.dateRangeTagCount);s.dateRangeTagCount++,t.isValid||s.skippedSegments?s.dateRanges[t.id]=t:OB.warn(`Ignoring invalid DATERANGE tag: "${i}"`),_.tagList.push([`EXT-X-DATERANGE`,i]);break}case`DEFINE`:{let e=new kU(i,s);`IMPORT`in e?EU(s,e,a):TU(s,e,t)}break;case`DISCONTINUITY-SEQUENCE`:s.startCC===0?c.length>0&&wW(s,e,v):CW(s,e,v),s.startCC=m=parseInt(i);break;case`KEY`:{let e=hW(i,t,s);if(e.isSupported()){if(e.method===`NONE`){b=void 0;break}b||={};let t=b[e.keyFormat];t!=null&&t.matches(e)||(t&&(b=hB({},b)),b[e.keyFormat]=e)}else OB.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${i}"`);break}case`START`:s.startTimeOffset=gW(i);break;case`MAP`:{let e=new kU(i,s);if(_.duration){let t=new WB(r,o);xW(t,e,n,b),u=t,_.initSegment=u,u.rawProgramDateTime&&!_.rawProgramDateTime&&(_.rawProgramDateTime=u.rawProgramDateTime)}else{let t=_.byteRangeEndOffset;if(t){let e=_.byteRangeStartOffset;C=`${t-e}@${e}`}else C=null;xW(_,e,n,b),u=_,S=!0}u.cc=m;break}case`SERVER-CONTROL`:w&&CW(s,e,v),w=new kU(i),s.canBlockReload=w.bool(`CAN-BLOCK-RELOAD`),s.canSkipUntil=w.optionalFloat(`CAN-SKIP-UNTIL`,0),s.canSkipDateRanges=s.canSkipUntil>0&&w.bool(`CAN-SKIP-DATERANGES`),s.partHoldBack=w.optionalFloat(`PART-HOLD-BACK`,0),s.holdBack=w.optionalFloat(`HOLD-BACK`,0);break;case`PART-INF`:s.partTarget&&CW(s,e,v),s.partTarget=new kU(i).decimalFloatingPoint(`PART-TARGET`);break;case`PART`:{let e=s.partList;e||=s.partList=[];let t=f>0?e[e.length-1]:void 0,n=f++,r=new GB(new kU(i,s),_,o,n,t);e.push(r),_.duration+=r.duration;break}case`PRELOAD-HINT`:s.preloadHint=new kU(i,s);break;case`RENDITION-REPORT`:{let e=new kU(i,s);s.renditionReports=s.renditionReports||[],s.renditionReports.push(e);break}default:OB.warn(`line parsed but not handled: ${v}`);break}}}g&&!g.relurl?(c.pop(),p-=g.duration,s.partList&&(s.fragmentHint=g)):s.partList&&(bW(_,g,l),_.cc=m,s.fragmentHint=_,b&&SW(_,b,s)),s.targetduration||(s.playlistParsingError=Error(`Missing Target Duration`));let T=c.length,E=c[0],D=c[T-1];if(p+=s.skippedSegments*s.targetduration,p>0&&T&&D){s.averagetargetduration=p/T;let e=D.sn;s.endSN=e===`initSegment`?0:e,s.live||(D.endList=!0),x>0&&(yW(c,x),E&&l.unshift(E))}return s.fragmentHint&&(p+=s.fragmentHint.duration),s.totalduration=p,l.length&&s.dateRangeTagCount&&E&&pW(l,s),s.endCC=m,s}};function pW(e,t){let n=e.length;if(!n)if(t.hasProgramDateTime){let r=t.fragments[t.fragments.length-1];e.push(r),n++}else return;let r=e[n-1],i=t.live?1/0:t.totalduration,a=Object.keys(t.dateRanges);for(let o=a.length;o--;){let s=t.dateRanges[a[o]],c=s.startDate.getTime();s.tagAnchor=r.ref;for(let r=n;r--&&!(e[r]?.sn<t.startSN);){let n=mW(t,c,e,r,i);if(n!==-1){s.tagAnchor=t.fragments[n].ref;break}}}}function mW(e,t,n,r,i){let a=n[r];if(a){let o=a.programDateTime;if((t>=o||r===0)&&t<=o+((n[r+1]?.start||i)-a.start)*1e3){let i=n[r].sn-e.startSN;if(i<0)return-1;let a=e.fragments;if(a.length>n.length){let o=(n[r+1]||a[a.length-1]).sn-e.startSN;for(let e=o;e>i;e--){let n=a[e].programDateTime;if(t>=n&&t<n+a[e].duration*1e3)return e}}return i}}return-1}function hW(e,t,n){let r=new kU(e,n),i=r.METHOD??``,a=r.URI,o=r.hexadecimalInteger(`IV`),s=r.KEYFORMATVERSIONS,c=r.KEYFORMAT??`identity`;return a&&r.IV&&!o&&OB.error(`Invalid IV: ${r.IV}`),new rW(i,a?fW.resolve(a,t):``,c,(s||`1`).split(`/`).map(Number).filter(Number.isFinite),o,r.KEYID)}function gW(e){let t=new kU(e).decimalFloatingPoint(`TIME-OFFSET`);return J(t)?t:null}function _W(e,t){let n=(e||``).split(/[ ,]+/).filter(e=>e);[`video`,`audio`,`text`].forEach(e=>{let r=n.filter(t=>jV(t,e));r.length&&(t[`${e}Codec`]=r.map(e=>e.split(`/`)[0]).join(`,`),n=n.filter(e=>r.indexOf(e)===-1))}),t.unknownCodecs=n}function vW(e,t,n){let r=t[n];r&&(e[n]=r)}function yW(e,t){let n=e[t];for(let r=t;r--;){let t=e[r];if(!t)return;t.programDateTime=n.programDateTime-t.duration*1e3,n=t}}function bW(e,t,n){e.rawProgramDateTime?n.push(e):t!=null&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function xW(e,t,n,r){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=n,e.sn=`initSegment`,r&&(e.levelkeys=r),e.initSegment=null}function SW(e,t,n){e.levelkeys=t;let{encryptedFragments:r}=n;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(e=>t[e].isCommonEncryption)&&r.push(e)}function CW(e,t,n){e.playlistParsingError=Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function wW(e,t,n){e.playlistParsingError=Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function TW(e,t){let n=t.startPTS;if(J(n)){let r=0,i;t.sn>e.sn?(r=n-e.start,i=e):(r=e.start-n,i=t),i.duration!==r&&i.setDuration(r)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function EW(e,t,n,r,i,a,o){r-n<=0&&(o.warn(`Fragment should have a positive duration`,t),r=n+t.duration,a=i+t.duration);let s=n,c=r,l=t.startPTS,u=t.endPTS;if(J(l)){let d=Math.abs(l-n);e&&d>e.totalduration?o.warn(`media timestamps and playlist times differ by ${d}s for level ${t.level} ${e.url}`):J(t.deltaPTS)?t.deltaPTS=Math.max(d,t.deltaPTS):t.deltaPTS=d,s=Math.max(n,l),n=Math.min(n,l),i=t.startDTS===void 0?i:Math.min(i,t.startDTS),c=Math.min(r,u),r=Math.max(r,u),a=t.endDTS===void 0?a:Math.max(a,t.endDTS)}let d=n-t.start;t.start!==0&&t.setStart(n),t.setDuration(r-t.start),t.startPTS=n,t.maxStartPTS=s,t.startDTS=i,t.endPTS=r,t.minEndPTS=c,t.endDTS=a;let f=t.sn;if(!e||f<e.startSN||f>e.endSN)return 0;let p,m=f-e.startSN,h=e.fragments;for(h[m]=t,p=m;p>0;p--)TW(h[p],h[p-1]);for(p=m;p<h.length-1;p++)TW(h[p],h[p+1]);return e.fragmentHint&&TW(h[h.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,d}function DW(e,t,n){if(e===t)return;let r=null,i=e.fragments;for(let e=i.length-1;e>=0;e--){let t=i[e].initSegment;if(t){r=t;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let a;AW(e,t,(e,n,i,o)=>{if((!t.startCC||t.skippedSegments)&&n.cc!==e.cc){let r=e.cc-n.cc;for(let e=i;e<o.length;e++)o[e].cc+=r;t.endCC=o[o.length-1].cc}J(e.startPTS)&&J(e.endPTS)&&(n.setStart(n.startPTS=e.startPTS),n.startDTS=e.startDTS,n.maxStartPTS=e.maxStartPTS,n.endPTS=e.endPTS,n.endDTS=e.endDTS,n.minEndPTS=e.minEndPTS,n.setDuration(e.endPTS-e.startPTS),n.duration&&(a=n),t.PTSKnown=t.alignedSliding=!0),e.hasStreams&&(n.elementaryStreams=e.elementaryStreams),n.loader=e.loader,e.hasStats&&(n.stats=e.stats),e.initSegment&&(n.initSegment=e.initSegment,r=e.initSegment)});let o=t.fragments,s=t.fragmentHint?o.concat(t.fragmentHint):o;if(r&&s.forEach(e=>{e&&(!e.initSegment||e.initSegment.relurl===r?.relurl)&&(e.initSegment=r)}),t.skippedSegments){if(t.deltaUpdateFailed=o.some(e=>!e),t.deltaUpdateFailed){n.warn(`[level-helper] Previous playlist missing segments skipped in delta playlist`);for(let e=t.skippedSegments;e--;)o.shift();t.startSN=o[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=OW(e.dateRanges,t,n));let r=e.fragments.filter(e=>e.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let e=1;e<s.length;e++)s[e].programDateTime===null&&bW(s[e],s[e-1],r);pW(r,t)}t.endCC=o[o.length-1].cc}t.startCC||=FW(e,t.startSN-1)?.cc??o[0].cc,kW(e.partList,t.partList,(e,t)=>{t.elementaryStreams=e.elementaryStreams,t.stats=e.stats}),a?EW(t,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,n):MW(e,t),o.length&&(t.totalduration=t.edge-o[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;let c=t.advancedDateTime;if(t.advanced&&c){let e=t.edge;t.driftStart||=(t.driftStartTime=c,e),t.driftEndTime=c,t.driftEnd=e}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=e.requestScheduled)}function OW(e,t,n){let{dateRanges:r,recentlyRemovedDateranges:i}=t,a=hB({},e);i&&i.forEach(e=>{delete a[e]});let o=Object.keys(a).length;return o?(Object.keys(r).forEach(e=>{let t=a[e],i=new NU(r[e].attr,t);i.isValid?(a[e]=i,t||(i.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${_H(r[e].attr)}"`)}),a):r}function kW(e,t,n){if(e&&t){let r=0;for(let i=0,a=e.length;i<=a;i++){let a=e[i],o=t[i+r];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?n(a,o):r--}}}function AW(e,t,n){let r=t.skippedSegments,i=Math.max(e.startSN,t.startSN)-t.startSN,a=+!!e.fragmentHint+(r?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,o=t.startSN-e.startSN,s=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,c=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let l=i;l<=a;l++){let i=c[o+l],a=s[l];if(r&&!a&&i&&(a=t.fragments[l]=i),i&&a){n(i,a,l,s);let r=i.relurl,o=a.relurl;if(r&&zW(r,o)){t.playlistParsingError=jW(`media sequence mismatch ${a.sn}:`,e,t,i,a);return}else if(i.cc!==a.cc){t.playlistParsingError=jW(`discontinuity sequence mismatch (${i.cc}!=${a.cc})`,e,t,i,a);return}}}}function jW(e,t,n,r,i){return Error(`${e} ${i.url}
45
- Playlist starting @${t.startSN}
46
- ${t.m3u8}
47
-
48
- Playlist starting @${n.startSN}
49
- ${n.m3u8}`)}function MW(e,t,n=!0){let r=t.startSN+t.skippedSegments-e.startSN,i=e.fragments,a=r>=0,o=0;if(a&&r<i.length)o=i[r].start;else if(a&&t.startSN===e.endSN+1)o=e.fragmentEnd;else if(a&&n)o=e.fragmentStart+r*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)o=e.fragmentStart;else return;NW(t,o)}function NW(e,t){if(t){let n=e.fragments;for(let r=e.skippedSegments;r<n.length;r++)n[r].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function PW(e,t=1/0){let n=1e3*e.targetduration;if(e.updated){let r=e.fragments;if(r.length&&n*4>t){let e=r[r.length-1].duration*1e3;e<n&&(n=e)}}else n/=2;return Math.round(n)}function FW(e,t,n){if(!e)return null;let r=e.fragments[t-e.startSN];return r||(r=e.fragmentHint,r&&r.sn===t)?r:t<e.startSN&&n&&n.sn===t?n:null}function IW(e,t,n){return e?LW(e.partList,t,n):null}function LW(e,t,n){if(e)for(let r=e.length;r--;){let i=e[r];if(i.index===n&&i.fragment.sn===t)return i}return null}function RW(e){e.forEach((e,t)=>{var n;(n=e.details)==null||n.fragments.forEach(e=>{e.level=t,e.initSegment&&(e.initSegment.level=t)})})}function zW(e,t){return e!==t&&t?BW(e)!==BW(t):!1}function BW(e){return e.replace(/\?[^?]*$/,``)}function VW(e,t){for(let n=0,r=e.length;n<r;n++)if(e[n]?.cc===t)return e[n];return null}function HW(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}function UW(e,t){let n=e.start+t;e.startPTS=n,e.setStart(n),e.endPTS=n+e.duration}function WW(e,t){let n=t.fragments;for(let t=0,r=n.length;t<r;t++)UW(n[t],e);t.fragmentHint&&UW(t.fragmentHint,e),t.alignedSliding=!0}function GW(e,t){e&&(KW(t,e),t.alignedSliding||qW(t,e),!t.alignedSliding&&!t.skippedSegments&&MW(e,t,!1))}function KW(e,t){if(!HW(t,e))return;let n=Math.min(t.endCC,e.endCC),r=VW(t.fragments,n),i=VW(e.fragments,n);!r||!i||(OB.log(`Aligning playlist at start of dicontinuity sequence ${n}`),WW(r.start-i.start,e))}function qW(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;let n=e.fragments,r=t.fragments;if(!n.length||!r.length)return;let i,a,o=Math.min(t.endCC,e.endCC);t.startCC<o&&e.startCC<o&&(i=VW(r,o),a=VW(n,o)),(!i||!a)&&(i=r[Math.floor(r.length/2)],a=VW(n,i.cc)||n[Math.floor(n.length/2)]);let s=i.programDateTime,c=a.programDateTime;!s||!c||WW((c-s)/1e3-(a.start-i.start),e)}function JW(e,t,n){YW(e,t,n),e.addEventListener(t,n)}function YW(e,t,n){e.removeEventListener(t,n)}var XW={toString:function(e){let t=``,n=e.length;for(let r=0;r<n;r++)t+=`[${e.start(r).toFixed(3)}-${e.end(r).toFixed(3)}]`;return t}},$={STOPPED:`STOPPED`,IDLE:`IDLE`,KEY_LOADING:`KEY_LOADING`,FRAG_LOADING:`FRAG_LOADING`,FRAG_LOADING_WAITING_RETRY:`FRAG_LOADING_WAITING_RETRY`,WAITING_TRACK:`WAITING_TRACK`,PARSING:`PARSING`,PARSED:`PARSED`,ENDED:`ENDED`,ERROR:`ERROR`,WAITING_INIT_PTS:`WAITING_INIT_PTS`,WAITING_LEVEL:`WAITING_LEVEL`},ZW=class extends _U{constructor(e,t,n,r,i){super(r,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=$.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{let{config:e,fragCurrent:t,media:n,mediaBuffer:r,state:i}=this,a=n?n.currentTime:0,o=xU.bufferInfo(r||n,a,e.maxBufferHole),s=!o.len;if(this.log(`Media seeking to ${J(a)?a.toFixed(3):a}, state: ${i}, ${s?`out of`:`in`} buffer`),this.state===$.ENDED)this.resetLoadingState();else if(t){let n=e.maxFragLookUpTolerance,r=t.start-n,i=t.start+t.duration+n;if(s||i<o.start||r>o.end){let e=a>i;(a<r||e)&&(e&&t.loader&&(this.log(`Cancelling fragment load for seek (sn: ${t.sn})`),t.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(n&&(this.fragmentTracker.removeFragmentsInRange(a,1/0,this.playlistType,!0),a>this.lastCurrentTime&&(this.lastCurrentTime=a),!this.loadingParts)){let e=Math.max(o.end,a),t=this.shouldLoadParts(this.getLevelDetails(),e);t&&(this.log(`LL-Part loading ON after seeking to ${a.toFixed(2)} with buffer @${e.toFixed(2)}`),this.loadingParts=t)}this.hls.hasEnoughToStart||(this.log(`Setting ${s?`startPosition`:`nextLoadPosition`} to ${a} for seek without enough to start`),this.nextLoadPosition=a,s&&(this.startPosition=a)),s&&this.state===$.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log(`setting startPosition to 0 because media ended`),this.startPosition=this.lastCurrentTime=0},this.playlistType=i,this.hls=e,this.fragmentLoader=new fU(e.config),this.keyLoader=n,this.fragmentTracker=t,this.config=e.config,this.decrypter=new uU(e.config)}registerListeners(){let{hls:e}=this;e.on(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Z.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Z.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===$.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);let e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=$.STOPPED}get startPositionValue(){let{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;let n=e.end||0,r=this.config.timelineOffset||0;if(n<=r)return!1;let i=e.buffered;this.config.maxBufferHole&&i&&i.length>1&&(e=xU.bufferedInfo(i,e.start,0));let a=e.nextStart;if(a&&a>r&&a<t.edge||this.media.currentTime<e.start)return!1;let o=t.partList;if(o!=null&&o.length){let e=o[o.length-1];return xU.isBuffered(this.media,e.start+e.duration/2)}let s=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(s)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){let e=this.config.timelineOffset;return e?this.getLevelDetails()?.appliedTimelineOffset||e:0}onMediaAttached(e,t){let n=this.media=this.mediaBuffer=t.media;JW(n,`seeking`,this.onMediaSeeking),JW(n,`ended`,this.onMediaEnded);let r=this.config;this.levels&&r.autoStartLoad&&this.state===$.STOPPED&&this.startLoad(r.startPosition)}onMediaDetaching(e,t){let n=!!t.transferMedia,r=this.media;if(r!==null){if(r.ended&&(this.log(`MSE detaching and video ended, reset startPosition`),this.startPosition=this.lastCurrentTime=0),YW(r,`seeking`,this.onMediaSeeking),YW(r,`ended`,this.onMediaEnded),this.keyLoader&&!n&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,n){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&=(this.transmuxer.destroy(),null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=$.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,n){this.startFragRequested=!0,this._loadFragForPlayback(e,t,n)}_loadFragForPlayback(e,t,n){this._doFragLoad(e,t,n,e=>{let t=e.frag;if(this.fragContextChanged(t)){this.warn(`${t.type} sn: ${t.sn}${e.part?` part: `+e.part.index:``} of ${this.fragInfo(t,!1,e.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(t);return}t.stats.chunkCount++,this._handleFragmentLoadProgress(e)}).then(e=>{if(!e)return;let t=this.state,n=e.frag;if(this.fragContextChanged(n)){(t===$.FRAG_LOADING||!this.fragCurrent&&t===$.PARSING)&&(this.fragmentTracker.removeFragment(n),this.state=$.IDLE);return}`payload`in e&&(this.log(`Loaded ${n.type} sn: ${n.sn} of ${this.playlistLabel()} ${n.level}`),this.hls.trigger(Z.FRAG_LOADED,e)),this._handleFragmentLoadComplete(e)}).catch(t=>{this.state===$.STOPPED||this.state===$.ERROR||(this.warn(`Frag error: ${t?.message||t}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){let{fragmentTracker:t}=this;if(t.getState(e)===QH.APPENDING){let n=e.type,r=this.getFwdBufferInfo(this.mediaBuffer,n),i=Math.max(e.duration,r?r.len:this.config.maxBufferLength),a=this.backtrackFragment;((a?e.sn-a.sn:0)===1||this.reduceMaxBufferLength(i,e.duration))&&t.removeFragment(e)}else this.mediaBuffer?.buffered.length===0?t.removeAllFragments():t.hasParts(e.type)&&(t.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),t.getState(e)===QH.PARTIAL&&t.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){let t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){let t=e.details;return t?.live&&t.type!==`EVENT`&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,n=null){if(!(e-t))return;let r={startOffset:e,endOffset:t,type:n};this.hls.trigger(Z.BUFFER_FLUSHING,r)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(e=>{let t=e?.frag;if(!t||this.fragContextChanged(t)||!this.levels)throw Error(`init load aborted`);return e}).then(e=>{let{hls:t}=this,{frag:n,payload:r}=e,i=n.decryptdata;if(r&&r.byteLength>0&&i!=null&&i.key&&i.iv&&RU(i.method)){let a=self.performance.now();return this.decrypter.decrypt(new Uint8Array(r),i.key.buffer,i.iv.buffer,zU(i.method)).catch(e=>{throw t.trigger(Z.ERROR,{type:Y.MEDIA_ERROR,details:X.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:n}),e}).then(r=>{let i=self.performance.now();return t.trigger(Z.FRAG_DECRYPTED,{frag:n,payload:r,stats:{tstart:a,tdecrypt:i}}),e.payload=r,this.completeInitSegmentLoad(e)})}return this.completeInitSegmentLoad(e)}).catch(t=>{this.state===$.STOPPED||this.state===$.ERROR||(this.warn(t),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){let{levels:t}=this;if(!t)throw Error(`init load aborted, missing levels`);let n=e.frag.stats;this.state!==$.STOPPED&&(this.state=$.IDLE),e.frag.data=new Uint8Array(e.payload),n.parsing.start=n.buffering.start=self.performance.now(),n.parsing.end=n.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var n,r;let i=e.tracks;if(i&&!t.encrypted&&((n=i.audio)!=null&&n.encrypted||(r=i.video)!=null&&r.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){let e=this.media,n=Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${e?`attached mediaKeys: `+e.mediaKeys:`detached`})`);return this.warn(n.message),!e||e.mediaKeys?!1:(this.hls.trigger(Z.ERROR,{type:Y.KEY_SYSTEM_ERROR,details:X.KEY_SYSTEM_NO_KEYS,fatal:!1,error:n,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){let{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){let n=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?` part: `+t.index:``} of ${this.fragInfo(e,!1,t)} > buffer:${n?XW.toString(xU.getBuffered(n)):`(detached)`})`),UB(e)){if(e.type!==Q.SUBTITLE){let t=e.elementaryStreams;if(!Object.keys(t).some(e=>!!t[e])){this.state=$.IDLE;return}}let t=this.levels?.[e.level];t!=null&&t.fragmentError&&(this.log(`Resetting level fragment error count of ${t.fragmentError} on frag buffered`),t.fragmentError=0)}this.state=$.IDLE}_handleFragmentLoadComplete(e){let{transmuxer:t}=this;if(!t)return;let{frag:n,part:r,partsLoaded:i}=e,a=!i||i.length===0||i.some(e=>!e),o=new vU(n.level,n.sn,n.stats.chunkCount+1,0,r?r.index:-1,!a);t.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,n=null,r){var i;this.fragCurrent=e;let a=t.details;if(!this.levels||!a)throw Error(`frag load aborted, missing level${a?``:` detail`}s`);let o=null;if(e.encrypted&&!((i=e.decryptdata)!=null&&i.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=$.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(e=>{if(!this.fragContextChanged(e.frag))return this.hls.trigger(Z.KEY_LOADED,e),this.state===$.KEY_LOADING&&(this.state=$.IDLE),e}),this.hls.trigger(Z.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log(`context changed in KEY_LOADING`),Promise.resolve(null)}else e.encrypted||(o=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),o&&this.log(`[eme] blocking frag load until media-keys acquired`));let s=this.fragPrevious;if(UB(e)&&(!s||e.sn!==s.sn)){let n=this.shouldLoadParts(t.details,e.end);n!==this.loadingParts&&(this.log(`LL-Part loading ${n?`ON`:`OFF`} loading sn ${s?.sn}->${e.sn}`),this.loadingParts=n)}if(n=Math.max(e.start,n||0),this.loadingParts&&UB(e)){let i=a.partList;if(i&&r){n>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);let s=this.getNextPart(i,e,n);if(s>-1){let c=i[s];e=this.fragCurrent=c.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${c.index} (${s}/${i.length-1}) of ${this.fragInfo(e,!1,c)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=c.start+c.duration,this.state=$.FRAG_LOADING;let l;return l=o?o.then(n=>!n||this.fragContextChanged(n.frag)?null:this.doFragPartsLoad(e,c,t,r)).catch(e=>this.handleFragLoadError(e)):this.doFragPartsLoad(e,c,t,r).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(Z.FRAG_LOADING,{frag:e,part:c,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(Error(`frag load aborted, context changed in FRAG_LOADING parts`)):l}else if(!e.url||this.loadedEndOfParts(i,n))return Promise.resolve(null)}}if(UB(e)&&this.loadingParts)this.log(`LL-Part loading OFF after next part miss @${n.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${a.partList?.filter(e=>e.loaded).map(e=>`[${e.start}-${e.end}]`)}`),this.loadingParts=!1;else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${`[`+a.startSN+`-`+a.endSN+`]`}, target: ${parseFloat(n.toFixed(3))}`),J(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=$.FRAG_LOADING;let c=this.config.progressive&&e.type!==Q.SUBTITLE,l;return l=c&&o?o.then(t=>!t||this.fragContextChanged(t.frag)?null:this.fragmentLoader.load(e,r)).catch(e=>this.handleFragLoadError(e)):Promise.all([this.fragmentLoader.load(e,c?r:void 0),o]).then(([e])=>(!c&&r&&r(e),e)).catch(e=>this.handleFragLoadError(e)),this.hls.trigger(Z.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(Error(`frag load aborted, context changed in FRAG_LOADING`)):l}doFragPartsLoad(e,t,n,r){return new Promise((i,a)=>{let o=[],s=n.details?.partList,c=t=>{this.fragmentLoader.loadPart(e,t,r).then(r=>{o[t.index]=r;let a=r.part;this.hls.trigger(Z.FRAG_LOADED,r);let l=IW(n.details,e.sn,t.index+1)||LW(s,e.sn,t.index+1);if(l)c(l);else return i({frag:e,part:a,partsLoaded:o})}).catch(a)};c(t)})}handleFragLoadError(e){if(`data`in e){let t=e.data;t.frag&&t.details===X.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===Y.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger(Z.ERROR,t)}else this.hls.trigger(Z.ERROR,{type:Y.OTHER_ERROR,details:X.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){let t=this.getCurrentContext(e);if(!t||this.state!==$.PARSING){!this.fragCurrent&&this.state!==$.STOPPED&&this.state!==$.ERROR&&(this.state=$.IDLE);return}let{frag:n,part:r,level:i}=t,a=self.performance.now();n.stats.parsing.end=a,r&&(r.stats.parsing.end=a);let o=this.getLevelDetails(),s=o&&n.sn>o.endSN||this.shouldLoadParts(o,n.end);s!==this.loadingParts&&(this.log(`LL-Part loading ${s?`ON`:`OFF`} after parsing segment ending @${n.end.toFixed(2)}`),this.loadingParts=s),this.updateLevelTiming(n,r,i,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){let n=e.partList[0];if(n.fragment.type===Q.SUBTITLE)return!1;if(t>=n.end+(e.fragmentHint?.duration||0)&&(this.hls.hasEnoughToStart?this.media?.currentTime||this.lastCurrentTime:this.getLoadPosition())>n.start-n.fragment.duration)return!0}}return!1}getCurrentContext(e){let{levels:t,fragCurrent:n}=this,{level:r,sn:i,part:a}=e;if(!(t!=null&&t[r]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${r}. The current chunk will not be buffered.`),null;let o=t[r],s=o.details,c=a>-1?IW(s,i,a):null,l=c?c.fragment:FW(s,i,n);return l?(n&&n!==l&&(l.stats=n.stats),{frag:l,part:c,level:o}):null}bufferFragmentData(e,t,n,r,i){if(this.state!==$.PARSING)return;let{data1:a,data2:o}=e,s=a;if(o&&(s=vV(a,o)),!s.length)return;let c=this.initPTS[t.cc],l=c?-c.baseTime/c.timescale:void 0,u={type:e.type,frag:t,part:n,chunkMeta:r,offset:l,parent:t.type,data:s};if(this.hls.trigger(Z.BUFFER_APPENDING,u),e.dropped&&e.independent&&!n){if(i)return;this.flushBufferGap(t)}}flushBufferGap(e){let t=this.media;if(!t)return;if(!xU.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}let n=t.currentTime,r=xU.bufferInfo(t,n,0),i=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(e.start-a,r.end-a),n+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,t){var n;let r=this.getLoadPosition();if(!J(r))return null;let i=this.lastCurrentTime>r||(n=this.media)!=null&&n.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,r,t,i)}getFwdBufferInfoAtPos(e,t,n,r){let i=xU.bufferInfo(e,t,r);if(i.len===0&&i.nextStart!==void 0){let a=this.fragmentTracker.getBufferedFrag(t,n);if(a&&(i.nextStart<=a.end||a.gap)){let n=Math.max(Math.min(i.nextStart,a.end)-t,r);return xU.bufferInfo(e,t,n)}}return i}getMaxBufferLength(e){let{config:t}=this,n;return n=e?Math.max(8*t.maxBufferSize/e,t.maxBufferLength):t.maxBufferLength,Math.min(n,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,n){let r=e.nextStart;if(r&&n.start>r){let r=e.buffered;if(r){let i=e.len,a=e.bufferedIndex;for(let e=r.length-1;e>a;e--)r[e].start<n.start&&(i+=r[e].end-r[e].start);return i>=t}}return!1}reduceMaxBufferLength(e,t){let n=this.config,r=Math.max(Math.min(e-t,n.maxBufferLength),t),i=Math.max(e-t*3,n.maxMaxBufferLength/2,r);return i>=r?(n.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}getAppendedFrag(e,t=Q.MAIN){let n=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return n&&`fragment`in n?n.fragment:n}getNextFragment(e,t){let n=t.fragments,r=n.length;if(!r)return null;let{config:i}=this,a=t.fragmentStart,o=i.lowLatencyMode&&!!t.partList,s=null;if(t.live){let n=i.initialLiveManifestSize;if(r<n)return this.warn(`Not enough fragments to start playback (have: ${r}, need: ${n})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){o&&!this.loadingParts&&(this.log(`LL-Part loading ON for initial live fragment`),this.loadingParts=!0),s=this.getInitialLiveFragment(t);let n=this.config.startPosition,r=this.hls.startPosition,i=this.hls.liveSyncPosition,c=s?.start||0,l,u;r!==-1&&r>=a?(l=r,u=r===n?`config`:`next load start`):i===null?(l=e,u=`buffer pos`):(l=i,u=`live edge`),l<c&&(l=c,u=`live frag start`),l<a&&(l=a,u=`playlist start`),(this.startPosition!=l||this.nextLoadPosition!=l)&&(this.log(`Setting startPosition to ${l.toFixed(3)} ${r===-1?``:`(from ${n}) `}based on ${u}. live edge: ${i} live frag start: ${c.toFixed(3)} playlist start: ${a.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=l)}}else e<=a&&(s=n[0]);if(!s){let n=this.loadingParts?t.partEnd:t.fragmentEnd;s=this.getFragmentAtPosition(e,n,t)}let c=this.filterReplacedPrimary(s,t);if(!c&&s){let e=s.sn-t.startSN;c=this.filterReplacedPrimary(n[e+1]||null,t)}return this.mapToInitFragWhenRequired(c)}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;let n=this.fragmentTracker.getState(e);return n===QH.OK||n===QH.PARTIAL&&!!e.gap}getNextFragmentLoopLoading(e,t,n,r,i){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&n.nextStart)){let e=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,n.nextStart,r,0);if(e!==null&&n.len+e.len>=i){let e=a.sn;return this.loopSn!==e&&(this.log(`buffer full after gaps in "${r}" playlist starting at sn: ${e}`),this.loopSn=e),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(QW(this.config)){var e;if(!((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null)&&e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(QW(this.config)&&e.type!==Q.SUBTITLE){let n=this.hls.interstitialsManager,r=n?.bufferingItem;if(r){let n=r.event;if(n){if(n.appendInPlace||Math.abs(e.start-r.start)>1||r.start===0)return null}else if(e.end<=r.start&&t?.live===!1||e.start>r.end&&r.nextEvent&&(r.nextEvent.appendInPlace||e.start-r.end>1))return null}let i=n?.playerQueue;if(i)for(let t=i.length;t--;){let n=i[t].interstitial;if(n.appendInPlace&&e.start>=n.startTime&&e.end<=n.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,n){let r=-1,i=!1,a=!0;for(let o=0,s=e.length;o<s;o++){let s=e[o];if(a&&=!s.independent,r>-1&&n<s.start)break;let c=s.loaded;c?r=-1:(i||(s.independent||a)&&s.fragment===t)&&(s.fragment!==t&&this.warn(`Need buffer at ${n} but next unloaded part starts at ${s.start}`),r=o),i=c}return r}loadedEndOfParts(e,t){let n;for(let r=e.length;r--;){if(n=e[r],!n.loaded)return!1;if(t>n.start)return!0}return!1}getInitialLiveFragment(e){let t=e.fragments,n=this.fragPrevious,r=null;if(n){if(e.hasProgramDateTime&&(r=NH(t,n.endProgramDateTime,this.config.maxFragLookUpTolerance),r&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`)),!r){let i=n.sn+1;if(i>=e.startSN&&i<=e.endSN){let a=t[i-e.startSN];n.cc===a.cc&&(r=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${r.sn}`))}r||(r=RH(e,n.cc,n.end),r&&this.log(`Live playlist, switching playlist, load frag with same CC: ${r.sn}`))}}else{let t=this.hls.liveSyncPosition;t!==null&&(r=this.getFragmentAtPosition(t,this.bitrateTest?e.fragmentEnd:e.edge,e))}return r}getFragmentAtPosition(e,t,n){let{config:r}=this,{fragPrevious:i}=this,{fragments:a,endSN:o}=n,{fragmentHint:s}=n,{maxFragLookUpTolerance:c}=r,l=n.partList,u=!!(this.loadingParts&&l!=null&&l.length&&s);u&&!this.bitrateTest&&l[l.length-1].fragment.sn===s.sn&&(a=a.concat(s),o=s.sn);let d;if(e<t){var f;let n=e<this.lastCurrentTime||e>t-c||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:c;d=PH(i,a,e,n)}else d=a[a.length-1];if(d){let e=d.sn-n.startSN,t=this.fragmentTracker.getState(d);if((t===QH.OK||t===QH.PARTIAL&&d.gap)&&(i=d),i&&d.sn===i.sn&&(!u||l[0].fragment.sn>d.sn||!n.live)&&d.level===i.level){let t=a[e+1];d=d.sn<o&&this.fragmentTracker.getState(t)!==QH.OK?t:null}}return d}alignPlaylists(e,t,n){let r=e.fragments.length;if(!r)return this.warn(`No fragments in live playlist`),0;let i=e.fragmentStart,a=!t,o=e.alignedSliding&&J(i);if(a||!o&&!i){GW(n,e);let i=e.fragmentStart;return this.log(`Live playlist sliding: ${i.toFixed(2)} start-sn: ${t?t.startSN:`na`}->${e.startSN} fragments: ${r}`),i}return i}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let n=this.startPosition;n<t&&(n=-1);let r=this.timelineOffset;if(n===-1){let i=this.startTimeOffset!==null,a=i?this.startTimeOffset:e.startTimeOffset;a!==null&&J(a)?(n=t+a,a<0&&(n+=e.edge),n=Math.min(Math.max(t,n),t+e.totalduration),this.log(`Setting startPosition to ${n} for start time offset ${a} found in ${i?`multivariant`:`media`} playlist`),this.startPosition=n):e.live?(n=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${n}`),this.startPosition=-1):(this.log(`setting startPosition to 0 by default`),this.startPosition=n=0),this.lastCurrentTime=n+r}this.nextLoadPosition=n+r}getLoadPosition(){var e;let{media:t}=this,n=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?n=t.currentTime:this.nextLoadPosition>=0&&(n=this.nextLoadPosition),n}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&UB(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?` part `+t.index:``} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==$.FRAG_LOADING_WAITING_RETRY)&&(this.state=$.IDLE)}onFragmentOrKeyLoadError(e,t){if(t.chunkMeta&&!t.frag){let e=this.getCurrentContext(t.chunkMeta);e&&(t.frag=e.frag)}let n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){this.warn(`Frag load error must match current frag to retry ${n.url} > ${this.fragCurrent?.url}`);return}let r=t.details===X.FRAG_GAP;r&&this.fragmentTracker.fragBuffered(n,!0);let i=t.errorAction;if(!i){this.state=$.ERROR;return}let{action:a,flags:o,retryCount:s=0,retryConfig:c}=i,l=!!c,u=l&&a===JH.RetryRequest,d=l&&!i.resolved&&o===YH.MoveAllAlternatesMatchingHost,f=this.hls.latestLevelDetails?.live;if(!u&&d&&UB(n)&&!n.endList&&f&&!VH(t))this.resetFragmentErrors(e),this.treatAsGap(n),i.resolved=!0;else if((u||d)&&s<c.maxNumRetry){let r=qH(t.response?.code),a=UH(c,s);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+a,this.state=$.FRAG_LOADING_WAITING_RETRY,i.resolved=!0,r){this.log(`Waiting for connection (offline)`),this.retryDate=1/0,t.reason=`offline`;return}this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${s+1}/${c.maxNumRetry} in ${a}ms`)}else if(c)if(this.resetFragmentErrors(e),s<c.maxNumRetry)!r&&a!==JH.RemoveAlternatePermanently&&(i.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${s})`);return}else a===JH.SendAlternateToPenaltyBox?this.state=$.WAITING_LEVEL:this.state=$.ERROR;this.tickImmediate()}checkRetryDate(){let e=self.performance.now(),t=this.retryDate,n=t===1/0;(!t||e>=t||n&&!qH(0))&&(n&&this.log(`Connection restored (online)`),this.resetStartWhenNotLoaded(),this.state=$.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===$.PARSING||this.state===$.PARSED){let t=e.frag,n=e.parent,r=this.getFwdBufferInfo(this.mediaBuffer,n),i=r&&r.len>.5;i&&this.reduceMaxBufferLength(r.len,t?.duration||10);let a=!i;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${n} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===Q.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==$.STOPPED&&(this.state=$.IDLE)}afterBufferFlushed(e,t,n){if(!e)return;let r=xU.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,r,n),this.state===$.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log(`Reset loading state`),this.fragCurrent=null,this.fragPrevious=null,this.state!==$.STOPPED&&(this.state=$.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;let e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log(`resetting startPosition for live start`),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?`<removed>`:e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,n,r){let i=n.details;if(!i){this.warn(`level.details undefined`);return}if(!Object.keys(e.elementaryStreams).reduce((t,a)=>{let o=e.elementaryStreams[a];if(o){let s=o.endPTS-o.startPTS;if(s<=0)return this.warn(`Could not parse fragment ${e.sn} ${a} duration reliably (${s})`),t||!1;let c=r?0:EW(i,e,o.startPTS,o.endPTS,o.startDTS,o.endDTS,this);return this.hls.trigger(Z.LEVEL_PTS_UPDATED,{details:i,level:n,drift:c,type:a,frag:e,start:o.startPTS,end:o.endPTS}),!0}return t},!1)){let t=this.transmuxer?.error===null;if((n.fragmentError===0||t&&(n.fragmentError<2||e.endList))&&this.treatAsGap(e,n),t){let t=Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(t.message),this.hls.trigger(Z.ERROR,{type:Y.MEDIA_ERROR,details:X.FRAG_PARSING_ERROR,fatal:!1,error:t,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=$.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?` part: `+t.index:``} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger(Z.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===Q.MAIN?`level`:`track`}fragInfo(e,t=!0,n){return`${this.playlistLabel()} ${e.level} (${n?`part`:`frag`}:[${((t&&!n?e.startPTS:(n||e).start)??NaN).toFixed(3)}-${((t&&!n?e.endPTS:(n||e).end)??NaN).toFixed(3)}]${n&&e.type===`main`?`INDEPENDENT=`+(n.independent?`YES`:`NO`):``}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event===`demuxerWorker`&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&=(this.transmuxer.destroy(),null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){let t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}};function QW(e){return!!e.interstitialsController&&e.enableInterstitialPlayback!==!1}var $W=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){let{chunks:e,dataLength:t}=this,n;if(e.length)n=e.length===1?e[0]:eG(e,t);else return new Uint8Array;return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}};function eG(e,t){let n=new Uint8Array(t),r=0;for(let t=0;t<e.length;t++){let i=e[t];n.set(i,r),r+=i.length}return n}var tG={exports:{}},nG;function rG(){return nG?tG.exports:(nG=1,(function(e){var t=Object.prototype.hasOwnProperty,n=`~`;function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function a(e,t,r,a,o){if(typeof r!=`function`)throw TypeError(`The listener must be a function`);var s=new i(r,a||e,o),c=n?n+t:t;return e._events[c]?e._events[c].fn?e._events[c]=[e._events[c],s]:e._events[c].push(s):(e._events[c]=s,e._eventsCount++),e}function o(e,t){--e._eventsCount===0?e._events=new r:delete e._events[t]}function s(){this._events=new r,this._eventsCount=0}s.prototype.eventNames=function(){var e=[],r,i;if(this._eventsCount===0)return e;for(i in r=this._events)t.call(r,i)&&e.push(n?i.slice(1):i);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},s.prototype.listeners=function(e){var t=n?n+e:e,r=this._events[t];if(!r)return[];if(r.fn)return[r.fn];for(var i=0,a=r.length,o=Array(a);i<a;i++)o[i]=r[i].fn;return o},s.prototype.listenerCount=function(e){var t=n?n+e:e,r=this._events[t];return r?r.fn?1:r.length:0},s.prototype.emit=function(e,t,r,i,a,o){var s=n?n+e:e;if(!this._events[s])return!1;var c=this._events[s],l=arguments.length,u,d;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),l){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,r),!0;case 4:return c.fn.call(c.context,t,r,i),!0;case 5:return c.fn.call(c.context,t,r,i,a),!0;case 6:return c.fn.call(c.context,t,r,i,a,o),!0}for(d=1,u=Array(l-1);d<l;d++)u[d-1]=arguments[d];c.fn.apply(c.context,u)}else{var f=c.length,p;for(d=0;d<f;d++)switch(c[d].once&&this.removeListener(e,c[d].fn,void 0,!0),l){case 1:c[d].fn.call(c[d].context);break;case 2:c[d].fn.call(c[d].context,t);break;case 3:c[d].fn.call(c[d].context,t,r);break;case 4:c[d].fn.call(c[d].context,t,r,i);break;default:if(!u)for(p=1,u=Array(l-1);p<l;p++)u[p-1]=arguments[p];c[d].fn.apply(c[d].context,u)}}return!0},s.prototype.on=function(e,t,n){return a(this,e,t,n,!1)},s.prototype.once=function(e,t,n){return a(this,e,t,n,!0)},s.prototype.removeListener=function(e,t,r,i){var a=n?n+e:e;if(!this._events[a])return this;if(!t)return o(this,a),this;var s=this._events[a];if(s.fn)s.fn===t&&(!i||s.once)&&(!r||s.context===r)&&o(this,a);else{for(var c=0,l=[],u=s.length;c<u;c++)(s[c].fn!==t||i&&!s[c].once||r&&s[c].context!==r)&&l.push(s[c]);l.length?this._events[a]=l.length===1?l[0]:l:o(this,a)}return this},s.prototype.removeAllListeners=function(e){var t;return e?(t=n?n+e:e,this._events[t]&&o(this,t)):(this._events=new r,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=n,s.EventEmitter=s,e.exports=s})(tG),tG.exports)}var iG=FB(rG()),aG=`1.6.16`,oG={};function sG(){return typeof __HLS_WORKER_BUNDLE__==`function`}function cG(){let e=oG[aG];if(e)return e.clientCount++,e;let t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:`text/javascript`}),n=self.URL.createObjectURL(t),r={worker:new self.Worker(n),objectURL:n,clientCount:1};return oG[aG]=r,r}function lG(e){let t=oG[e];if(t)return t.clientCount++,t;let n=new self.URL(e,self.location.href).href,r={worker:new self.Worker(n),scriptURL:n,clientCount:1};return oG[e]=r,r}function uG(e){let t=oG[e||aG];if(t&&t.clientCount--===1){let{worker:n,objectURL:r}=t;delete oG[e||aG],r&&self.URL.revokeObjectURL(r),n.terminate()}}function dG(e,t){return t+10<=e.length&&e[t]===51&&e[t+1]===68&&e[t+2]===73&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function fG(e,t){return t+10<=e.length&&e[t]===73&&e[t+1]===68&&e[t+2]===51&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function pG(e,t){let n=0;return n=(e[t]&127)<<21,n|=(e[t+1]&127)<<14,n|=(e[t+2]&127)<<7,n|=e[t+3]&127,n}function mG(e,t){let n=t,r=0;for(;fG(e,t);){r+=10;let n=pG(e,t+6);r+=n,dG(e,t+10)&&(r+=10),t+=r}if(r>0)return e.subarray(n,n+r)}function hG(e,t,n,r){let i=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],a=t[n+2],o=a>>2&15;if(o>12){let t=Error(`invalid ADTS sampling index:${o}`);e.emit(Z.ERROR,Z.ERROR,{type:Y.MEDIA_ERROR,details:X.FRAG_PARSING_ERROR,fatal:!0,error:t,reason:t.message});return}let s=(a>>6&3)+1,c=t[n+3]>>6&3|(a&1)<<2,l=`mp4a.40.`+s,u=i[o],d=o;(s===5||s===29)&&(d-=3);let f=[s<<3|(d&14)>>1,(d&1)<<7|c<<3];return OB.log(`manifest codec:${r}, parsed codec:${l}, channels:${c}, rate:${u} (ADTS object type:${s} sampling index:${o})`),{config:f,samplerate:u,channelCount:c,codec:l,parsedCodec:l,manifestCodec:r}}function gG(e,t){return e[t]===255&&(e[t+1]&246)==240}function _G(e,t){return e[t+1]&1?7:9}function vG(e,t){return(e[t+3]&3)<<11|e[t+4]<<3|(e[t+5]&224)>>>5}function yG(e,t){return t+5<e.length}function bG(e,t){return t+1<e.length&&gG(e,t)}function xG(e,t){return yG(e,t)&&gG(e,t)&&vG(e,t)<=e.length-t}function SG(e,t){if(bG(e,t)){let n=_G(e,t);if(t+n>=e.length)return!1;let r=vG(e,t);if(r<=n)return!1;let i=t+r;return i===e.length||bG(e,i)}return!1}function CG(e,t,n,r,i){if(!e.samplerate){let a=hG(t,n,r,i);if(!a)return;hB(e,a)}}function wG(e){return 1024*9e4/e}function TG(e,t){let n=_G(e,t);if(t+n<=e.length){let r=vG(e,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function EG(e,t,n,r,i){let a=r+i*wG(e.samplerate),o=TG(t,n),s;if(o){let{frameLength:r,headerLength:i}=o,c=i+r,l=Math.max(0,n+c-t.length);l?(s=new Uint8Array(c-i),s.set(t.subarray(n+i,t.length),0)):s=t.subarray(n+i,n+c);let u={unit:s,pts:a};return l||e.samples.push(u),{sample:u,length:c,missing:l}}let c=t.length-n;return s=new Uint8Array(c),s.set(t.subarray(n,t.length),0),{sample:{unit:s,pts:a},length:c,missing:-1}}function DG(e,t){return fG(e,t)&&pG(e,t+6)+10<=e.length-t}function OG(e){return e instanceof ArrayBuffer?e:e.byteOffset==0&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function kG(e,t=0,n=1/0){return AG(e,t,n,Uint8Array)}function AG(e,t,n,r){let i=jG(e),a=1;`BYTES_PER_ELEMENT`in r&&(a=r.BYTES_PER_ELEMENT);let o=MG(e)?e.byteOffset:0,s=(o+e.byteLength)/a,c=(o+t)/a,l=Math.floor(Math.max(0,Math.min(c,s)));return new r(i,l,Math.floor(Math.min(l+Math.max(n,0),s))-l)}function jG(e){return e instanceof ArrayBuffer?e:e.buffer}function MG(e){return e&&e.buffer instanceof ArrayBuffer&&e.byteLength!==void 0&&e.byteOffset!==void 0}function NG(e){let t={key:e.type,description:``,data:``,mimeType:null,pictureType:null};if(e.size<2)return;if(e.data[0]!==3){console.log(`Ignore frame with unrecognized character encoding`);return}let n=e.data.subarray(1).indexOf(0);if(n===-1)return;let r=MB(kG(e.data,1,n)),i=e.data[2+n],a=e.data.subarray(3+n).indexOf(0);if(a===-1)return;let o=MB(kG(e.data,3+n,a)),s;return s=r===`-->`?MB(kG(e.data,4+n+a)):OG(e.data.subarray(4+n+a)),t.mimeType=r,t.pictureType=i,t.description=o,t.data=s,t}function PG(e){if(e.size<2)return;let t=MB(e.data,!0),n=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:n.buffer}}function FG(e){if(e.size<2)return;if(e.type===`TXXX`){let t=1,n=MB(e.data.subarray(t),!0);t+=n.length+1;let r=MB(e.data.subarray(t));return{key:e.type,info:n,data:r}}let t=MB(e.data.subarray(1));return{key:e.type,info:``,data:t}}function IG(e){if(e.type===`WXXX`){if(e.size<2)return;let t=1,n=MB(e.data.subarray(t),!0);t+=n.length+1;let r=MB(e.data.subarray(t));return{key:e.type,info:n,data:r}}let t=MB(e.data);return{key:e.type,info:``,data:t}}function LG(e){return e.type===`PRIV`?PG(e):e.type[0]===`W`?IG(e):e.type===`APIC`?NG(e):FG(e)}function RG(e){let t=String.fromCharCode(e[0],e[1],e[2],e[3]),n=pG(e,4);return{type:t,size:n,data:e.subarray(10,10+n)}}var zG=10,BG=10;function VG(e){let t=0,n=[];for(;fG(e,t);){let r=pG(e,t+6);e[t+5]>>6&1&&(t+=zG),t+=zG;let i=t+r;for(;t+BG<i;){let r=RG(e.subarray(t)),i=LG(r);i&&n.push(i),t+=r.size+zG}dG(e,t)&&(t+=zG)}return n}function HG(e){return e&&e.key===`PRIV`&&e.info===`com.apple.streaming.transportStreamTimestamp`}function UG(e){if(e.data.byteLength===8){let t=new Uint8Array(e.data),n=t[3]&1,r=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return r/=45,n&&(r+=47721858.84),Math.round(r)}}function WG(e){let t=VG(e);for(let e=0;e<t.length;e++){let n=t[e];if(HG(n))return UG(n)}}var GG=function(e){return e.audioId3=`org.id3`,e.dateRange=`com.apple.quicktime.HLS`,e.emsg=`https://aomedia.org/emsg/ID3`,e.misbklv=`urn:misb:KLV:bin:1910.1`,e}({});function KG(e=``,t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var qG=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,n,r){this._id3Track={type:`id3`,id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,n){}demux(e,t){this.cachedData&&=(e=vV(this.cachedData,e),null);let n=mG(e,0),r=n?n.length:0,i,a=this._audioTrack,o=this._id3Track,s=n?WG(n):void 0,c=e.length;for((this.basePTS===null||this.frameIndex===0&&J(s))&&(this.basePTS=JG(s,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),n&&n.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:GG.audioId3,duration:1/0});r<c;){if(this.canParse(e,r)){let t=this.appendFrame(a,e,r);t?(this.frameIndex++,this.lastPTS=t.sample.pts,r+=t.length,i=r):r=c}else DG(e,r)?(n=mG(e,r),o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:GG.audioId3,duration:1/0}),r+=n.length,i=r):r++;if(r===c&&i!==c){let t=e.slice(i);this.cachedData?this.cachedData=vV(this.cachedData,t):this.cachedData=t}}return{audioTrack:a,videoTrack:KG(),id3Track:o,textTrack:KG()}}demuxSampleAes(e,t,n){return Promise.reject(Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){let t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:KG(),id3Track:this._id3Track,textTrack:KG()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},JG=(e,t,n)=>{if(J(e))return e*90;let r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r},YG=null,XG=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],ZG=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],QG=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],$G=[0,1,1,4];function eK(e,t,n,r,i){if(n+24>t.length)return;let a=tK(t,n);if(a&&n+a.frameLength<=t.length){let o=r+i*(a.samplesPerFrame*9e4/a.sampleRate),s={unit:t.subarray(n,n+a.frameLength),pts:o,dts:o};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(s),{sample:s,length:a.frameLength,missing:0}}}function tK(e,t){let n=e[t+1]>>3&3,r=e[t+1]>>1&3,i=e[t+2]>>4&15,a=e[t+2]>>2&3;if(n!==1&&i!==0&&i!==15&&a!==3){let o=e[t+2]>>1&1,s=e[t+3]>>6,c=XG[(n===3?3-r:r===3?3:4)*14+i-1]*1e3,l=ZG[(n===3?0:n===2?1:2)*3+a],u=s===3?1:2,d=QG[n][r],f=$G[r],p=d*8*f,m=Math.floor(d*c/l+o)*f;if(YG===null){let e=(navigator.userAgent||``).match(/Chrome\/(\d+)/i);YG=e?parseInt(e[1]):0}return YG&&YG<=87&&r===2&&c>=224e3&&s===0&&(e[t+3]=e[t+3]|128),{sampleRate:l,channelCount:u,frameLength:m,samplesPerFrame:p}}}function nK(e,t){return e[t]===255&&(e[t+1]&224)==224&&(e[t+1]&6)!=0}function rK(e,t){return t+1<e.length&&nK(e,t)}function iK(e,t){return nK(e,t)&&4<=e.length-t}function aK(e,t){if(t+1<e.length&&nK(e,t)){let n=tK(e,t),r=4;n!=null&&n.frameLength&&(r=n.frameLength);let i=t+r;return i===e.length||rK(e,i)}return!1}var oK=class extends qG{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:`audio/adts`,type:`audio`,id:2,pid:-1,sequenceNumber:0,segmentCodec:`aac`,samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;let n=mG(e,0)?.length||0;if(aK(e,n))return!1;for(let r=e.length;n<r;n++)if(SG(e,n))return t.log(`ADTS sync word found !`),!0;return!1}canParse(e,t){return xG(e,t)}appendFrame(e,t,n){CG(e,this.observer,t,n,e.manifestCodec);let r=EG(e,t,n,this.basePTS,this.frameIndex);if(r&&r.missing===0)return r}},sK=(e,t)=>{let n=0,r=5;t+=r;let i=new Uint32Array(1),a=new Uint32Array(1),o=new Uint8Array(1);for(;r>0;){o[0]=e[t];let s=Math.min(r,8),c=8-s;a[0]=4278190080>>>24+c<<c,i[0]=(o[0]&a[0])>>c,n=n?n<<s|i[0]:i[0],t+=1,r-=s}return n},cK=class extends qG{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:`audio/ac-3`,type:`audio`,id:2,pid:-1,sequenceNumber:0,segmentCodec:`ac3`,samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,n){let r=lK(e,t,n,this.basePTS,this.frameIndex);if(r!==-1)return{sample:e.samples[e.samples.length-1],length:r,missing:0}}static probe(e){if(!e)return!1;let t=mG(e,0);if(!t)return!1;let n=t.length;return e[n]===11&&e[n+1]===119&&WG(t)!==void 0&&sK(e,n)<16}};function lK(e,t,n,r,i){if(n+8>t.length||t[n]!==11||t[n+1]!==119)return-1;let a=t[n+4]>>6;if(a>=3)return-1;let o=[48e3,44100,32e3][a],s=t[n+4]&63,c=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][s*3+a]*2;if(n+c>t.length)return-1;let l=t[n+6]>>5,u=0;l===2?u+=2:(l&1&&l!==1&&(u+=2),l&4&&(u+=2));let d=(t[n+6]<<8|t[n+7])>>12-u&1,f=[2,1,2,3,3,4,4,5][l]+d,p=t[n+5]>>3,m=t[n+5]&7,h=new Uint8Array([a<<6|p<<1|m>>2,(m&3)<<6|l<<3|d<<2|s>>4,s<<4&224]),g=r+i*(1536/o*9e4),_=t.subarray(n,n+c);return e.config=h,e.channelCount=f,e.samplerate=o,e.samples.push({unit:_,pts:g}),c}var uK=class extends qG{resetInitSegment(e,t,n,r){super.resetInitSegment(e,t,n,r),this._audioTrack={container:`audio/mpeg`,type:`audio`,id:2,pid:-1,sequenceNumber:0,segmentCodec:`mp3`,samples:[],manifestCodec:t,duration:r,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;let t=mG(e,0),n=t?.length||0;if(t&&e[n]===11&&e[n+1]===119&&WG(t)!==void 0&&sK(e,n)<=16)return!1;for(let t=e.length;n<t;n++)if(aK(e,n))return OB.log(`MPEG Audio sync word found !`),!0;return!1}canParse(e,t){return iK(e,t)}appendFrame(e,t,n){if(this.basePTS!==null)return eK(e,t,n,this.basePTS,this.frameIndex)}},dK=/\/emsg[-/]ID3/i,fK=class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,n,r){let i=this.videoTrack=KG(`video`,1),a=this.audioTrack=KG(`audio`,1),o=this.txtTrack=KG(`text`,1);if(this.id3Track=KG(`id3`,1),this.timeOffset=0,!(e!=null&&e.byteLength))return;let s=aV(e);if(s.video){let{id:e,timescale:t,codec:n,supplemental:r}=s.video;i.id=e,i.timescale=o.timescale=t,i.codec=n,i.supplemental=r}if(s.audio){let{id:e,timescale:t,codec:n}=s.audio;a.id=e,a.timescale=t,a.codec=n}o.id=XB.text,i.sampleDuration=0,i.duration=a.duration=r}resetContiguity(){this.remainderData=null}static probe(e){return nV(e)}demux(e,t){this.timeOffset=t;let n=e,r=this.videoTrack,i=this.txtTrack;if(this.config.progressive){this.remainderData&&(n=vV(this.remainderData,e));let t=_V(n);this.remainderData=t.remainder,r.samples=t.valid||new Uint8Array}else r.samples=n;let a=this.extractID3Track(r,t);return i.samples=yV(t,r),{videoTrack:r,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){let e=this.timeOffset,t=this.videoTrack,n=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;let r=this.extractID3Track(t,this.timeOffset);return n.samples=yV(e,t),{videoTrack:t,audioTrack:KG(),id3Track:r,textTrack:KG()}}extractID3Track(e,t){let n=this.id3Track;if(e.samples.length){let r=rV(e.samples,[`emsg`]);r&&r.forEach(e=>{let r=wV(e);if(dK.test(r.schemeIdUri)){let e=pK(r,t),i=r.eventDuration===4294967295?1/0:r.eventDuration/r.timeScale;i<=.001&&(i=1/0);let a=r.payload;n.samples.push({data:a,len:a.byteLength,dts:e,pts:e,type:GG.emsg,duration:i})}else if(this.config.enableEmsgKLVMetadata&&r.schemeIdUri.startsWith(`urn:misb:KLV:bin:1910.1`)){let e=pK(r,t);n.samples.push({data:r.payload,len:r.payload.byteLength,dts:e,pts:e,type:GG.misbklv,duration:1/0})}})}return n}demuxSampleAes(e,t,n){return Promise.reject(Error(`The MP4 demuxer does not support SAMPLE-AES decryption`))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}};function pK(e,t){return J(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var mK=class{constructor(e,t,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new uU(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,rU.cbc)}decryptAacSample(e,t,n){let r=e[t].unit;if(r.length<=16)return;let i=r.subarray(16,r.length-r.length%16),a=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(a).then(i=>{let a=new Uint8Array(i);r.set(a,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,n)}).catch(n)}decryptAacSamples(e,t,n){for(;;t++){if(t>=e.length){n();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){let t=Math.floor((e.length-48)/160)*16+16,n=new Int8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)n.set(e.subarray(t,t+16),r);return n}getAvcDecryptedUnit(e,t){let n=new Uint8Array(t),r=0;for(let t=32;t<e.length-16;t+=160,r+=16)e.set(n.subarray(r,r+16),t);return e}decryptAvcSample(e,t,n,r,i){let a=CV(i.data),o=this.getAvcEncryptedData(a);this.decryptBuffer(o.buffer).then(o=>{i.data=this.getAvcDecryptedUnit(a,o),this.decrypter.isSync()||this.decryptAvcSamples(e,t,n+1,r)}).catch(r)}decryptAvcSamples(e,t,n,r){if(e instanceof Uint8Array)throw Error(`Cannot decrypt samples of type Uint8Array`);for(;;t++,n=0){if(t>=e.length){r();return}let i=e[t].units;for(;!(n>=i.length);n++){let a=i[n];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,n,r,a),!this.decrypter.isSync()))return}}}},hK=class{constructor(){this.VideoSample=null}createVideoSample(e,t,n){return{key:e,frame:!1,pts:t,dts:n,units:[],length:0}}getLastNalUnit(e){var t;let n=this.VideoSample,r;if((!n||n.units.length===0)&&(n=e[e.length-1]),(t=n)!=null&&t.units){let e=n.units;r=e[e.length-1]}return r}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){let n=t.samples,r=n.length;if(r){let t=n[r-1];e.pts=t.pts,e.dts=t.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,n){let r=t.byteLength,i=e.naluState||0,a=i,o=[],s=0,c,l,u,d=-1,f=0;for(i===-1&&(d=0,f=this.getNALuType(t,0),i=0,s=1);s<r;){if(c=t[s++],!i){i=+!c;continue}if(i===1){i=c?0:2;continue}if(!c)i=3;else if(c===1){if(l=s-i-1,d>=0){let e={data:t.subarray(d,l),type:f};o.push(e)}else{let n=this.getLastNalUnit(e.samples);n&&(a&&s<=4-a&&n.state&&(n.data=n.data.subarray(0,n.data.byteLength-a)),l>0&&(n.data=vV(n.data,t.subarray(0,l)),n.state=0))}s<r?(u=this.getNALuType(t,s),d=s,f=u,i=0):i=-1}else i=0}if(d>=0&&i>=0){let e={data:t.subarray(d,r),type:f,state:i};o.push(e)}if(o.length===0){let n=this.getLastNalUnit(e.samples);n&&(n.data=vV(n.data,t))}return e.naluState=i,o}},gK=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){let e=this.data,t=this.bytesAvailable,n=e.byteLength-t,r=new Uint8Array(4),i=Math.min(4,t);if(i===0)throw Error(`no bytes available`);r.set(e.subarray(n,n+i)),this.word=new DataView(r.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e),n=this.word>>>32-t;if(e>32&&OB.error(`Cannot read more than 32 bits at a time`),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw Error(`no bits available`);return t=e-t,t>0&&this.bitsAvailable?n<<t|this.readBits(t):n}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if(this.word&2147483648>>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){let e=this.skipLZ();return this.readBits(e+1)-1}readEG(){let e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},_K=class extends hK{parsePES(e,t,n,r){let i=this.parseNALu(e,n.data,r),a=this.VideoSample,o,s=!1;n.data=null,a&&i.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),i.forEach(r=>{var i,c;switch(r.type){case 1:{let t=!1;o=!0;let i=r.data;if(s&&i.length>4){let e=this.readSliceType(i);(e===2||e===4||e===7||e===9)&&(t=!0)}if(t){var l;(l=a)!=null&&l.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.frame=!0,a.key=t;break}case 5:o=!0,(i=a)!=null&&i.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.key=!0,a.frame=!0;break;case 6:o=!0,SV(r.data,1,n.pts,t.samples);break;case 7:{o=!0,s=!0;let t=r.data,n=this.readSPS(t);if(!e.sps||e.width!==n.width||e.height!==n.height||e.pixelRatio?.[0]!==n.pixelRatio[0]||e.pixelRatio?.[1]!==n.pixelRatio[1]){e.width=n.width,e.height=n.height,e.pixelRatio=n.pixelRatio,e.sps=[t];let r=t.subarray(1,4),i=`avc1.`;for(let e=0;e<3;e++){let t=r[e].toString(16);t.length<2&&(t=`0`+t),i+=t}e.codec=i}break}case 8:o=!0,e.pps=[r.data];break;case 9:o=!0,e.audFound=!0,(c=a)!=null&&c.frame&&(this.pushAccessUnit(a,e),a=null),a||=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts);break;case 12:o=!0;break;default:o=!1;break}a&&o&&a.units.push(r)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){let t=new gK(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let n=8,r=8,i;for(let a=0;a<e;a++)r!==0&&(i=t.readEG(),r=(n+i+256)%256),n=r===0?n:r}readSPS(e){let t=new gK(e),n=0,r=0,i=0,a=0,o,s,c,l=t.readUByte.bind(t),u=t.readBits.bind(t),d=t.readUEG.bind(t),f=t.readBoolean.bind(t),p=t.skipBits.bind(t),m=t.skipEG.bind(t),h=t.skipUEG.bind(t),g=this.skipScalingList.bind(this);l();let _=l();if(u(5),p(3),l(),h(),_===100||_===110||_===122||_===244||_===44||_===83||_===86||_===118||_===128){let e=d();if(e===3&&p(1),h(),h(),p(1),f())for(s=e===3?12:8,c=0;c<s;c++)f()&&g(c<6?16:64,t)}h();let v=d();if(v===0)d();else if(v===1)for(p(1),m(),m(),o=d(),c=0;c<o;c++)m();h(),p(1);let y=d(),b=d(),x=u(1);x===0&&p(1),p(1),f()&&(n=d(),r=d(),i=d(),a=d());let S=[1,1];if(f()&&f())switch(l()){case 1:S=[1,1];break;case 2:S=[12,11];break;case 3:S=[10,11];break;case 4:S=[16,11];break;case 5:S=[40,33];break;case 6:S=[24,11];break;case 7:S=[20,11];break;case 8:S=[32,11];break;case 9:S=[80,33];break;case 10:S=[18,11];break;case 11:S=[15,11];break;case 12:S=[64,33];break;case 13:S=[160,99];break;case 14:S=[4,3];break;case 15:S=[3,2];break;case 16:S=[2,1];break;case 255:S=[l()<<8|l(),l()<<8|l()];break}return{width:Math.ceil((y+1)*16-n*2-r*2),height:(2-x)*(b+1)*16-(x?2:4)*(i+a),pixelRatio:S}}},vK=class extends hK{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,n,r){let i=this.parseNALu(e,n.data,r),a=this.VideoSample,o,s=!1;n.data=null,a&&i.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts)),i.forEach(r=>{var i,c;switch(r.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts),a.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,s){var l;(l=a)!=null&&l.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.key=!0,a.frame=!0;break;case 19:case 20:o=!0,(i=a)!=null&&i.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.key=!0,a.frame=!0;break;case 39:o=!0,SV(r.data,2,n.pts,t.samples);break;case 32:o=!0,e.vps||(typeof e.params!=`object`&&(e.params={}),e.params=hB(e.params,this.readVPS(r.data)),this.initVPS=r.data),e.vps=[r.data];break;case 33:if(o=!0,s=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],r.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){let t=this.readSPS(r.data);e.width=t.width,e.height=t.height,e.pixelRatio=t.pixelRatio,e.codec=t.codecString,e.sps=[],typeof e.params!=`object`&&(e.params={});for(let n in t.params)e.params[n]=t.params[n]}this.pushParameterSet(e.sps,r.data,e.vps),a||=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts),a.key=!0;break;case 34:if(o=!0,typeof e.params==`object`){if(!e.pps){e.pps=[];let t=this.readPPS(r.data);for(let n in t)e.params[n]=t[n]}this.pushParameterSet(e.pps,r.data,e.vps)}break;case 35:o=!0,e.audFound=!0,(c=a)!=null&&c.frame&&(this.pushAccessUnit(a,e),a=null),a||=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts);break;default:o=!1;break}a&&o&&a.units.push(r)}),r&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,n){(n&&n[0]===this.initVPS||!n&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){let t=new Uint8Array(e.byteLength),n=0;for(let r=0;r<e.byteLength;r++)r>=2&&e[r]===3&&e[r-1]===0&&e[r-2]===0||(t[n]=e[r],n++);return new Uint8Array(t.buffer,0,n)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&=null}readVPS(e){let t=new gK(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);let n=t.readBits(3),r=t.readBoolean();return{numTemporalLayers:n+1,temporalIdNested:r}}readSPS(e){let t=new gK(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);let n=t.readBits(3);t.readBoolean();let r=t.readBits(2),i=t.readBoolean(),a=t.readBits(5),o=t.readUByte(),s=t.readUByte(),c=t.readUByte(),l=t.readUByte(),u=t.readUByte(),d=t.readUByte(),f=t.readUByte(),p=t.readUByte(),m=t.readUByte(),h=t.readUByte(),g=t.readUByte(),_=[],v=[];for(let e=0;e<n;e++)_.push(t.readBoolean()),v.push(t.readBoolean());if(n>0)for(let e=n;e<8;e++)t.readBits(2);for(let e=0;e<n;e++)_[e]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),v[e]&&t.readUByte();t.readUEG();let y=t.readUEG();y==3&&t.skipBits(1);let b=t.readUEG(),x=t.readUEG(),S=t.readBoolean(),C=0,w=0,T=0,E=0;S&&(C+=t.readUEG(),w+=t.readUEG(),T+=t.readUEG(),E+=t.readUEG());let D=t.readUEG(),O=t.readUEG(),k=t.readUEG(),A=t.readBoolean();for(let e=A?0:n;e<=n;e++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let e=0;e<4;e++)for(let n=0;n<(e===3?2:6);n++)if(!t.readBoolean())t.readUEG();else{let n=Math.min(64,1<<4+(e<<1));e>1&&t.readEG();for(let e=0;e<n;e++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());let j=t.readUEG(),M=0;for(let e=0;e<j;e++){let n=!1;if(e!==0&&(n=t.readBoolean()),n){e===j&&t.readUEG(),t.readBoolean(),t.readUEG();let n=0;for(let e=0;e<=M;e++){let e=t.readBoolean(),r=!1;e||(r=t.readBoolean()),(e||r)&&n++}M=n}else{let e=t.readUEG(),n=t.readUEG();M=e+n;for(let n=0;n<e;n++)t.readUEG(),t.readBoolean();for(let e=0;e<n;e++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){let e=t.readUEG();for(let n=0;n<e;n++){for(let e=0;e<k+4;e++)t.readBits(1);t.readBits(1)}}let N=0,P=1,ee=1,F=!0,te=1,I=0;t.readBoolean(),t.readBoolean();let L=!1;if(t.readBoolean()){if(t.readBoolean()){let e=t.readUByte();e>0&&e<16?(P=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2][e-1],ee=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1][e-1]):e===255&&(P=t.readBits(16),ee=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),L=t.readBoolean(),L&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(te=t.readBits(32),I=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){let e=t.readBoolean(),r=t.readBoolean(),i=!1;(e||r)&&(i=t.readBoolean(),i&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),i&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let a=0;a<=n;a++){F=t.readBoolean();let n=F||t.readBoolean(),a=!1;n?t.readEG():a=t.readBoolean();let o=a?1:t.readUEG()+1;if(e)for(let e=0;e<o;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(r)for(let e=0;e<o;e++)t.readUEG(),t.readUEG(),i&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),N=t.readUEG())}let ne=b,R=x;if(S){let e=1,t=1;y===1?e=t=2:y==2&&(e=2),ne=b-e*w-e*C,R=x-t*E-t*T}let re=r?[`A`,`B`,`C`][r]:``,ie=o<<24|s<<16|c<<8|l,ae=0;for(let e=0;e<32;e++)ae=(ae|(ie>>e&1)<<31-e)>>>0;let z=ae.toString(16);return a===1&&z===`2`&&(z=`6`),{codecString:`hvc1.${re}${a}.${z}.${i?`H`:`L`}${g}.B0`,params:{general_tier_flag:i,general_profile_idc:a,general_profile_space:r,general_profile_compatibility_flags:[o,s,c,l],general_constraint_indicator_flags:[u,d,f,p,m,h],general_level_idc:g,bit_depth:D+8,bit_depth_luma_minus8:D,bit_depth_chroma_minus8:O,min_spatial_segmentation_idc:N,chroma_format_idc:y,frame_rate:{fixed:F,fps:I/te}},width:ne,height:R,pixelRatio:[P,ee]}}readPPS(e){let t=new gK(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);let n=t.readBoolean(),r=t.readBoolean(),i=1;return r&&n?i=0:r?i=3:n&&(i=2),{parallelismType:i}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},yK=188,bK=class e{constructor(e,t,n,r){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=t,this.typeSupported=n,this.logger=r,this.videoParser=null}static probe(t,n){let r=e.syncOffset(t);return r>0&&n.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(e){let t=e.length,n=Math.min(yK*5,t-yK)+1,r=0;for(;r<n;){let i=!1,a=-1,o=0;for(let s=r;s<t;s+=yK)if(e[s]===71&&(t-s===yK||e[s+yK]===71)){if(o++,a===-1&&(a=s,a!==0&&(n=Math.min(a+yK*99,e.length-yK)+1)),i||=xK(e,s)===0,i&&o>1&&(a===0&&o>2||s+yK>n))return a}else if(o)return-1;else break;r++}return-1}static createTrack(e,t){return{container:e===`video`||e===`audio`?`video/mp2t`:void 0,type:e,id:XB[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e===`audio`?t:void 0}}resetInitSegment(t,n,r,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=e.createTrack(`video`),this._videoTrack.duration=i,this._audioTrack=e.createTrack(`audio`,i),this._id3Track=e.createTrack(`id3`),this._txtTrack=e.createTrack(`text`),this._audioTrack.segmentCodec=`aac`,this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=n,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){let{_audioTrack:e,_videoTrack:t,_id3Track:n}=this;e&&(e.pesData=null),t&&(t.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,n,r=!1,i=!1){r||(this.sampleAes=null);let a,o=this._videoTrack,s=this._audioTrack,c=this._id3Track,l=this._txtTrack,u=o.pid,d=o.pesData,f=s.pid,p=c.pid,m=s.pesData,h=c.pesData,g=null,_=this.pmtParsed,v=this._pmtId,y=t.length;if(this.remainderData&&=(t=vV(this.remainderData,t),y=t.length,null),y<yK&&!i)return this.remainderData=t,{audioTrack:s,videoTrack:o,id3Track:c,textTrack:l};let b=Math.max(0,e.syncOffset(t));y-=(y-b)%yK,y<t.byteLength&&!i&&(this.remainderData=new Uint8Array(t.buffer,y,t.buffer.byteLength-y));let x=0;for(let e=b;e<y;e+=yK)if(t[e]===71){let n=!!(t[e+1]&64),i=xK(t,e),y=(t[e+3]&48)>>4,x;if(y>1){if(x=e+5+t[e+4],x===e+yK)continue}else x=e+4;switch(i){case u:n&&(d&&(a=EK(d,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,l,a,!1)),d={data:[],size:0}),d&&(d.data.push(t.subarray(x,e+yK)),d.size+=e+yK-x);break;case f:if(n){if(m&&(a=EK(m,this.logger)))switch(s.segmentCodec){case`aac`:this.parseAACPES(s,a);break;case`mp3`:this.parseMPEGPES(s,a);break;case`ac3`:this.parseAC3PES(s,a);break}m={data:[],size:0}}m&&(m.data.push(t.subarray(x,e+yK)),m.size+=e+yK-x);break;case p:n&&(h&&(a=EK(h,this.logger))&&this.parseID3PES(c,a),h={data:[],size:0}),h&&(h.data.push(t.subarray(x,e+yK)),h.size+=e+yK-x);break;case 0:n&&(x+=t[x]+1),v=this._pmtId=SK(t,x);break;case v:{n&&(x+=t[x]+1);let i=CK(t,x,this.typeSupported,r,this.observer,this.logger);u=i.videoPid,u>0&&(o.pid=u,o.segmentCodec=i.segmentVideoCodec),f=i.audioPid,f>0&&(s.pid=f,s.segmentCodec=i.segmentAudioCodec),p=i.id3Pid,p>0&&(c.pid=p),g!==null&&!_&&(this.logger.warn(`MPEG-TS PMT found at ${e} after unknown PID '${g}'. Backtracking to sync byte @${b} to parse all TS packets.`),g=null,e=b-188),_=this.pmtParsed=!0;break}case 17:case 8191:break;default:g=i;break}}else x++;x>0&&wK(this.observer,Error(`Found ${x} TS packet/s that do not start with 0x47`),void 0,this.logger),o.pesData=d,s.pesData=m,c.pesData=h;let S={audioTrack:s,videoTrack:o,id3Track:c,textTrack:l};return i&&this.extractRemainingSamples(S),S}flush(){let{remainderData:e}=this;this.remainderData=null;let t;return t=e?this.demux(e,-1,!1,!0):{videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(t),this.sampleAes?this.decrypt(t,this.sampleAes):t}extractRemainingSamples(e){let{audioTrack:t,videoTrack:n,id3Track:r,textTrack:i}=e,a=n.pesData,o=t.pesData,s=r.pesData,c;if(a&&(c=EK(a,this.logger))?(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(n,i,c,!0),n.pesData=null)):n.pesData=a,o&&(c=EK(o,this.logger))){switch(t.segmentCodec){case`aac`:this.parseAACPES(t,c);break;case`mp3`:this.parseMPEGPES(t,c);break;case`ac3`:this.parseAC3PES(t,c);break}t.pesData=null}else o!=null&&o.size&&this.logger.log(`last AAC PES packet truncated,might overlap between fragments`),t.pesData=o;s&&(c=EK(s,this.logger))?(this.parseID3PES(r,c),r.pesData=null):r.pesData=s}demuxSampleAes(e,t,n){let r=this.demux(e,n,!0,!this.config.progressive),i=this.sampleAes=new mK(this.observer,this.config,t);return this.decrypt(r,i)}readyVideoParser(e){this.videoParser===null&&(e===`avc`?this.videoParser=new _K:e===`hevc`&&(this.videoParser=new vK))}decrypt(e,t){return new Promise(n=>{let{audioTrack:r,videoTrack:i}=e;r.samples&&r.segmentCodec===`aac`?t.decryptAacSamples(r.samples,0,()=>{i.samples?t.decryptAvcSamples(i.samples,0,0,()=>{n(e)}):n(e)}):i.samples&&t.decryptAvcSamples(i.samples,0,0,()=>{n(e)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(e,t){let n=0,r=this.aacOverFlow,i=t.data;if(r){this.aacOverFlow=null;let t=r.missing,a=r.sample.unit.byteLength;if(t===-1)i=vV(r.sample.unit,i);else{let o=a-t;r.sample.unit.set(i.subarray(0,t),o),e.samples.push(r.sample),n=r.missing}}let a,o;for(a=n,o=i.length;a<o-1&&!bG(i,a);a++);if(a!==n){let e,t=a<o-1;if(e=t?`AAC PES did not start with ADTS header,offset:${a}`:`No ADTS header found in AAC PES`,wK(this.observer,Error(e),t,this.logger),!t)return}CG(e,this.observer,i,a,this.audioCodec);let s;if(t.pts!==void 0)s=t.pts;else if(r){let t=wG(e.samplerate);s=r.sample.pts+t}else{this.logger.warn(`[tsdemuxer]: AAC PES unknown PTS`);return}let c=0,l;for(;a<o;)if(l=EG(e,i,a,s,c),a+=l.length,l.missing){this.aacOverFlow=l;break}else for(c++;a<o-1&&!bG(i,a);a++);}parseMPEGPES(e,t){let n=t.data,r=n.length,i=0,a=0,o=t.pts;if(o===void 0){this.logger.warn(`[tsdemuxer]: MPEG PES unknown PTS`);return}for(;a<r;)if(rK(n,a)){let t=eK(e,n,a,o,i);if(t)a+=t.length,i++;else break}else a++}parseAC3PES(e,t){{let n=t.data,r=t.pts;if(r===void 0){this.logger.warn(`[tsdemuxer]: AC3 PES unknown PTS`);return}let i=n.length,a=0,o=0,s;for(;o<i&&(s=lK(e,n,o,r,a++))>0;)o+=s}}parseID3PES(e,t){if(t.pts===void 0){this.logger.warn(`[tsdemuxer]: ID3 PES unknown PTS`);return}let n=hB({},t,{type:this._videoTrack?GG.emsg:GG.audioId3,duration:1/0});e.samples.push(n)}};function xK(e,t){return((e[t+1]&31)<<8)+e[t+2]}function SK(e,t){return(e[t+10]&31)<<8|e[t+11]}function CK(e,t,n,r,i,a){let o={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:`avc`,segmentAudioCodec:`aac`},s=(e[t+1]&15)<<8|e[t+2],c=t+3+s-4,l=(e[t+10]&15)<<8|e[t+11];for(t+=12+l;t<c;){let s=xK(e,t),c=(e[t+3]&15)<<8|e[t+4];switch(e[t]){case 207:if(!r){TK(`ADTS AAC`,a);break}case 15:o.audioPid===-1&&(o.audioPid=s);break;case 21:o.id3Pid===-1&&(o.id3Pid=s);break;case 219:if(!r){TK(`H.264`,a);break}case 27:o.videoPid===-1&&(o.videoPid=s);break;case 3:case 4:!n.mpeg&&!n.mp3?a.log(`MPEG audio found, not supported in this browser`):o.audioPid===-1&&(o.audioPid=s,o.segmentAudioCodec=`mp3`);break;case 193:if(!r){TK(`AC-3`,a);break}case 129:n.ac3?o.audioPid===-1&&(o.audioPid=s,o.segmentAudioCodec=`ac3`):a.log(`AC-3 audio found, not supported in this browser`);break;case 6:if(o.audioPid===-1&&c>0){let r=t+5,i=c;for(;i>2;){switch(e[r]){case 106:n.ac3===!0?(o.audioPid=s,o.segmentAudioCodec=`ac3`):a.log(`AC-3 audio found, not supported in this browser for now`);break}let t=e[r+1]+2;r+=t,i-=t}}break;case 194:case 135:return wK(i,Error(`Unsupported EC-3 in M2TS found`),void 0,a),o;case 36:o.videoPid===-1&&(o.videoPid=s,o.segmentVideoCodec=`hevc`,a.log(`HEVC in M2TS found`));break}t+=c+5}return o}function wK(e,t,n,r){r.warn(`parsing error: ${t.message}`),e.emit(Z.ERROR,Z.ERROR,{type:Y.MEDIA_ERROR,details:X.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,error:t,reason:t.message})}function TK(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function EK(e,t){let n=0,r,i,a,o,s,c=e.data;if(!e||e.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=vV(c[0],c[1]),c.splice(1,1);if(r=c[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(i=(r[4]<<8)+r[5],i&&i>e.size-6)return null;let l=r[7];l&192&&(o=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,l&64?(s=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,o-s>60*9e4&&(t.warn(`${Math.round((o-s)/9e4)}s delta between PTS and DTS, align them`),o=s)):s=o),a=r[8];let u=a+9;if(e.size<=u)return null;e.size-=u;let d=new Uint8Array(e.size);for(let e=0,t=c.length;e<t;e++){r=c[e];let t=r.byteLength;if(u)if(u>t){u-=t;continue}else r=r.subarray(u),t-=u,u=0;d.set(r,n),n+=t}return i&&(i-=a+3),{data:d,pts:o,dts:s,len:i}}return null}var DK=class{static getSilentFrame(e,t){switch(e){case`mp4a.40.2`:if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2||t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},OK=2**32-1,kK=class e{static init(){e.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in e.types)e.types.hasOwnProperty(t)&&(e.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);e.HDLR_TYPES={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])};let n=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);e.STTS=e.STSC=e.STCO=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),e.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),e.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),e.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);let r=new Uint8Array([105,115,111,109]),i=new Uint8Array([97,118,99,49]),a=new Uint8Array([0,0,0,1]);e.FTYP=e.box(e.types.ftyp,r,a,r,i),e.DINF=e.box(e.types.dinf,e.box(e.types.dref,n))}static box(e,...t){let n=8,r=t.length,i=r;for(;r--;)n+=t[r].byteLength;let a=new Uint8Array(n);for(a[0]=n>>24&255,a[1]=n>>16&255,a[2]=n>>8&255,a[3]=n&255,a.set(e,4),r=0,n=8;r<i;r++)a.set(t[r],n),n+=t[r].byteLength;return a}static hdlr(t){return e.box(e.types.hdlr,e.HDLR_TYPES[t])}static mdat(t){return e.box(e.types.mdat,t)}static mdhd(t,n){n*=t;let r=Math.floor(n/(OK+1)),i=Math.floor(n%(OK+1));return e.box(e.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(t){return e.box(e.types.mdia,e.mdhd(t.timescale||0,t.duration||0),e.hdlr(t.type),e.minf(t))}static mfhd(t){return e.box(e.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type===`audio`?e.box(e.types.minf,e.box(e.types.smhd,e.SMHD),e.DINF,e.stbl(t)):e.box(e.types.minf,e.box(e.types.vmhd,e.VMHD),e.DINF,e.stbl(t))}static moof(t,n,r){return e.box(e.types.moof,e.mfhd(t),e.traf(r,n))}static moov(t){let n=t.length,r=[];for(;n--;)r[n]=e.trak(t[n]);return e.box.apply(null,[e.types.moov,e.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r,e.mvex(t)))}static mvex(t){let n=t.length,r=[];for(;n--;)r[n]=e.trex(t[n]);return e.box.apply(null,[e.types.mvex,...r])}static mvhd(t,n){n*=t;let r=Math.floor(n/(OK+1)),i=Math.floor(n%(OK+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return e.box(e.types.mvhd,a)}static sdtp(t){let n=t.samples||[],r=new Uint8Array(4+n.length),i,a;for(i=0;i<n.length;i++)a=n[i].flags,r[i+4]=a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy;return e.box(e.types.sdtp,r)}static stbl(t){return e.box(e.types.stbl,e.stsd(t),e.box(e.types.stts,e.STTS),e.box(e.types.stsc,e.STSC),e.box(e.types.stsz,e.STSZ),e.box(e.types.stco,e.STCO))}static avc1(t){let n=[],r=[],i,a,o;for(i=0;i<t.sps.length;i++)a=t.sps[i],o=a.byteLength,n.push(o>>>8&255),n.push(o&255),n=n.concat(Array.prototype.slice.call(a));for(i=0;i<t.pps.length;i++)a=t.pps[i],o=a.byteLength,r.push(o>>>8&255),r.push(o&255),r=r.concat(Array.prototype.slice.call(a));let s=e.box(e.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n,[t.pps.length],r))),c=t.width,l=t.height,u=t.pixelRatio[0],d=t.pixelRatio[1];return e.box(e.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,c>>8&255,c&255,l>>8&255,l&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),s,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){let t=e.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...t,6,1,2])}static audioStsd(e){let t=e.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount||0,0,16,0,0,0,0,t>>8&255,t&255,0,0])}static mp4a(t){return e.box(e.types.mp4a,e.audioStsd(t),e.box(e.types.esds,e.esds(t)))}static mp3(t){return e.box(e.types[`.mp3`],e.audioStsd(t))}static ac3(t){return e.box(e.types[`ac-3`],e.audioStsd(t),e.box(e.types.dac3,t.config))}static stsd(t){let{segmentCodec:n}=t;if(t.type===`audio`){if(n===`aac`)return e.box(e.types.stsd,e.STSD,e.mp4a(t));if(n===`ac3`&&t.config)return e.box(e.types.stsd,e.STSD,e.ac3(t));if(n===`mp3`&&t.codec===`mp3`)return e.box(e.types.stsd,e.STSD,e.mp3(t))}else if(t.pps&&t.sps){if(n===`avc`)return e.box(e.types.stsd,e.STSD,e.avc1(t));if(n===`hevc`&&t.vps)return e.box(e.types.stsd,e.STSD,e.hvc1(t))}else throw Error(`video track missing pps or sps`);throw Error(`unsupported ${t.type} segment codec (${n}/${t.codec})`)}static tkhd(t){let n=t.id,r=(t.duration||0)*(t.timescale||0),i=t.width||0,a=t.height||0,o=Math.floor(r/(OK+1)),s=Math.floor(r%(OK+1));return e.box(e.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,n>>24&255,n>>16&255,n>>8&255,n&255,0,0,0,0,o>>24,o>>16&255,o>>8&255,o&255,s>>24,s>>16&255,s>>8&255,s&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,a>>8&255,a&255,0,0]))}static traf(t,n){let r=e.sdtp(t),i=t.id,a=Math.floor(n/(OK+1)),o=Math.floor(n%(OK+1));return e.box(e.types.traf,e.box(e.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),e.box(e.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255])),e.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,e.box(e.types.trak,e.tkhd(t),e.mdia(t))}static trex(t){let n=t.id;return e.box(e.types.trex,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,n){let r=t.samples||[],i=r.length,a=12+16*i,o=new Uint8Array(a),s,c,l,u,d,f;for(n+=8+a,o.set([+(t.type===`video`),0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255],0),s=0;s<i;s++)c=r[s],l=c.duration,u=c.size,d=c.flags,f=c.cts,o.set([l>>>24&255,l>>>16&255,l>>>8&255,l&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,f>>>24&255,f>>>16&255,f>>>8&255,f&255],12+16*s);return e.box(e.types.trun,o)}static initSegment(t){e.types||e.init();let n=e.moov(t);return vV(e.FTYP,n)}static hvc1(t){let n=t.params,r=[t.vps,t.sps,t.pps],i=new Uint8Array([1,n.general_profile_space<<6|(n.general_tier_flag?32:0)|n.general_profile_idc,n.general_profile_compatibility_flags[0],n.general_profile_compatibility_flags[1],n.general_profile_compatibility_flags[2],n.general_profile_compatibility_flags[3],n.general_constraint_indicator_flags[0],n.general_constraint_indicator_flags[1],n.general_constraint_indicator_flags[2],n.general_constraint_indicator_flags[3],n.general_constraint_indicator_flags[4],n.general_constraint_indicator_flags[5],n.general_level_idc,240|n.min_spatial_segmentation_idc>>8,255&n.min_spatial_segmentation_idc,252|n.parallelismType,252|n.chroma_format_idc,248|n.bit_depth_luma_minus8,248|n.bit_depth_chroma_minus8,0,parseInt(n.frame_rate.fps),3|n.temporal_id_nested<<2|n.num_temporal_layers<<3|(n.frame_rate.fixed?64:0),r.length]),a=i.length;for(let e=0;e<r.length;e+=1){a+=3;for(let t=0;t<r[e].length;t+=1)a+=2+r[e][t].length}let o=new Uint8Array(a);o.set(i,0),a=i.length;let s=r.length-1;for(let e=0;e<r.length;e+=1){o.set(new Uint8Array([32+e|(e===s?128:0),0,r[e].length]),a),a+=3;for(let t=0;t<r[e].length;t+=1)o.set(new Uint8Array([r[e][t].length>>8,r[e][t].length&255]),a),a+=2,o.set(r[e][t],a),a+=r[e][t].length}let c=e.box(e.types.hvcC,o),l=t.width,u=t.height,d=t.pixelRatio[0],f=t.pixelRatio[1];return e.box(e.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,l>>8&255,l&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),c,e.box(e.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),e.box(e.types.pasp,new Uint8Array([d>>24,d>>16&255,d>>8&255,d&255,f>>24,f>>16&255,f>>8&255,f&255])))}};kK.types=void 0,kK.HDLR_TYPES=void 0,kK.STTS=void 0,kK.STSC=void 0,kK.STCO=void 0,kK.STSZ=void 0,kK.VMHD=void 0,kK.SMHD=void 0,kK.STSD=void 0,kK.FTYP=void 0,kK.DINF=void 0;var AK=9e4;function jK(e,t,n=1,r=!1){let i=e*t*n;return r?Math.round(i):i}function MK(e,t,n=1,r=!1){return jK(e,t,1/n,r)}function NK(e,t=!1){return jK(e,1e3,1/AK,t)}function PK(e,t=1){return jK(e,AK,1/t)}function FK(e){let{baseTime:t,timescale:n,trackId:r}=e;return`${t/n} (${t}/${n}) trackId: ${r}`}var IK=10*1e3,LK=1024,RK=1152,zK=1536,BK=null,VK=null;function HK(e,t,n,r){return{duration:t,size:n,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:+!e}}}var UK=class extends bB{constructor(e,t,n,r){if(super(`mp4-remuxer`,r),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=n,this.ISGenerated=!1,BK===null){let e=(navigator.userAgent||``).match(/Chrome\/(\d+)/i);BK=e?parseInt(e[1]):0}if(VK===null){let e=navigator.userAgent.match(/Safari\/(\d+)/i);VK=e?parseInt(e[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){let t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&FK(t)} > ${e&&FK(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log(`reset next timestamp`),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log(`ISGenerated flag reset`),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1,n=e[0].pts,r=e.reduce((e,r)=>{let i=r.pts,a=i-e;return a<-4294967296&&(t=!0,i=WK(i,n),a=i-e),a>0?e:i},n);return t&&this.debug(`PTS rollover detected`),r}remux(e,t,n,r,i,a,o,s){let c,l,u,d,f,p,m=i,h=i,g=e.pid>-1,_=t.pid>-1,v=t.samples.length,y=e.samples.length>0,b=o&&v>0||v>1;if((!g||y)&&(!_||b)||this.ISGenerated||o){if(this.ISGenerated){let e=this.videoTrackConfig;(e&&(t.width!==e.width||t.height!==e.height||t.pixelRatio?.[0]!==e.pixelRatio?.[0]||t.pixelRatio?.[1]!==e.pixelRatio?.[1])||!e&&b||this.nextAudioTs===null&&y)&&this.resetInitSegment()}this.ISGenerated||(u=this.generateIS(e,t,i,a));let n=this.isVideoContiguous,r=-1,o;if(b&&(r=GK(t.samples),!n&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,r>0){this.warn(`Dropped ${r} out of ${v} video samples due to a missing keyframe`);let e=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(r),t.dropped+=r,h+=(t.samples[0].pts-e)/t.inputTimeScale,o=h}else r===-1&&(this.warn(`No keyframe found out of ${v} video samples`),p=!1);if(this.ISGenerated){if(y&&b){let n=this.getVideoStartPts(t.samples),r=(WK(e.samples[0].pts,n)-n)/t.inputTimeScale;m+=Math.max(0,r),h+=Math.max(0,-r)}if(y){if(e.samplerate||(this.warn(`regenerate InitSegment as audio detected`),u=this.generateIS(e,t,i,a)),l=this.remuxAudio(e,m,this.isAudioContiguous,a,_||b||s===Q.AUDIO?h:void 0),b){let r=l?l.endPTS-l.startPTS:0;t.inputTimeScale||(this.warn(`regenerate InitSegment as video detected`),u=this.generateIS(e,t,i,a)),c=this.remuxVideo(t,h,n,r)}}else b&&(c=this.remuxVideo(t,h,n,0));c&&(c.firstKeyFrame=r,c.independent=r!==-1,c.firstKeyFramePTS=o)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(f=KK(n,i,this._initPTS,this._initDTS)),r.samples.length&&(d=qK(r,i,this._initPTS))),{audio:l,video:c,initSegment:u,independent:p,text:d,id3:f}}computeInitPts(e,t,n,r){let i=Math.round(n*t),a=WK(e,i);if(a<i+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(i-a)/t} ${r}`);a<i+t;)a+=8589934592;return a-i}generateIS(e,t,n,r){let i=e.samples,a=t.samples,o=this.typeSupported,s={},c=this._initPTS,l=!c||r,u=`audio/mp4`,d,f,p,m=-1;if(l&&(d=f=1/0),e.config&&i.length){switch(e.timescale=e.samplerate,e.segmentCodec){case`mp3`:o.mpeg?(u=`audio/mpeg`,e.codec=``):o.mp3&&(e.codec=`mp3`);break;case`ac3`:e.codec=`ac-3`;break}s.audio={id:`audio`,container:u,codec:e.codec,initSegment:e.segmentCodec===`mp3`&&o.mpeg?new Uint8Array:kK.initSegment([e]),metadata:{channelCount:e.channelCount}},l&&(m=e.id,p=e.inputTimeScale,!c||p!==c.timescale?d=f=this.computeInitPts(i[0].pts,p,n,`audio`):l=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,s.video={id:`main`,container:`video/mp4`,codec:t.codec,initSegment:kK.initSegment([t]),metadata:{width:t.width,height:t.height}},l)if(m=t.id,p=t.inputTimeScale,!c||p!==c.timescale){let e=this.getVideoStartPts(a),t=WK(a[0].dts,e),r=this.computeInitPts(t,p,n,`video`),i=this.computeInitPts(e,p,n,`video`);f=Math.min(f,r),d=Math.min(d,i)}else l=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(s).length)return this.ISGenerated=!0,l?(c&&this.warn(`Timestamps at playlist time: ${r?``:`~`}${n} ${d/p} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${n} offset: ${d/p} (${d}/${p}) trackId: ${m}`),this._initPTS={baseTime:d,timescale:p,trackId:m},this._initDTS={baseTime:f,timescale:p,trackId:m}):d=p=void 0,{tracks:s,initPTS:d,timescale:p,trackId:m}}remuxVideo(e,t,n,r){let i=e.inputTimeScale,a=e.samples,o=[],s=a.length,c=this._initPTS,l=c.baseTime*i/c.timescale,u=this.nextVideoTs,d=8,f=this.videoSampleDuration,p,m,h=1/0,g=-1/0,_=!1;if(!n||u===null){let e=l+t*i,r=a[0].pts-WK(a[0].dts,a[0].pts);BK&&u!==null&&Math.abs(e-r-(u+l))<15e3?n=!0:u=e-r-l}let v=u+l;for(let e=0;e<s;e++){let t=a[e];t.pts=WK(t.pts,v),t.dts=WK(t.dts,v),t.dts<a[e>0?e-1:e].dts&&(_=!0)}_&&a.sort(function(e,t){let n=e.dts-t.dts,r=e.pts-t.pts;return n||r}),p=a[0].dts,m=a[a.length-1].dts;let y=m-p,b=y?Math.round(y/(s-1)):f||e.inputTimeScale/30;if(n){let n=p-v,r=n>b,i=n<-1;if((r||i)&&(r?this.warn(`${(e.segmentCodec||``).toUpperCase()}: ${NK(n,!0)} ms (${n}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||``).toUpperCase()}: ${NK(-n,!0)} ms (${n}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!i||v>=a[0].pts||BK)){p=v;let e=a[0].pts-n;if(r)a[0].dts=p,a[0].pts=e;else{let t=!0;for(let r=0;r<a.length&&!(a[r].dts>e&&t);r++){let e=a[r].pts;if(a[r].dts-=n,a[r].pts-=n,r<a.length-1){let n=a[r+1].pts;t=n<=a[r].pts==n<=e}}}this.log(`Video: Initial PTS/DTS adjusted: ${NK(e,!0)}/${NK(p,!0)}, delta: ${NK(n,!0)} ms`)}}p=Math.max(0,p);let x=0,S=0,C=p;for(let e=0;e<s;e++){let t=a[e],n=t.units,r=n.length,i=0;for(let e=0;e<r;e++)i+=n[e].data.length;S+=i,x+=r,t.length=i,t.dts<C?(t.dts=C,C+=b/4|0||1):C=t.dts,h=Math.min(t.pts,h),g=Math.max(t.pts,g)}m=a[s-1].dts;let w=S+4*x+8,T;try{T=new Uint8Array(w)}catch(e){this.observer.emit(Z.ERROR,Z.ERROR,{type:Y.MUX_ERROR,details:X.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:w,reason:`fail allocating video mdat ${w}`});return}let E=new DataView(T.buffer);E.setUint32(0,w),T.set(kK.types.mdat,4);let D=!1,O=1/0,k=1/0,A=-1/0,j=-1/0;for(let e=0;e<s;e++){let t=a[e],n=t.units,c=0;for(let e=0,t=n.length;e<t;e++){let t=n[e],r=t.data,i=t.data.byteLength;E.setUint32(d,i),d+=4,T.set(r,d),d+=i,c+=4+i}let u;if(e<s-1)f=a[e+1].dts-t.dts,u=a[e+1].pts-t.pts;else{let n=this.config,o=e>0?t.dts-a[e-1].dts:b;if(u=e>0?t.pts-a[e-1].pts:b,n.stretchShortVideoTrack&&this.nextAudioTs!==null){let e=Math.floor(n.maxBufferHole*i),a=(r?h+r*i:this.nextAudioTs+l)-t.pts;a>e?(f=a-o,f<0?f=o:D=!0,this.log(`It is approximately ${a/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=o}else f=o}let p=Math.round(t.pts-t.dts);O=Math.min(O,f),A=Math.max(A,f),k=Math.min(k,u),j=Math.max(j,u),o.push(HK(t.key,f,c,p))}if(o.length){if(BK){if(BK<70){let e=o[0].flags;e.dependsOn=2,e.isNonSync=0}}else if(VK&&j-k<A-O&&b/A<.025&&o[0].cts===0){this.warn(`Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.`);let e=p;for(let t=0,n=o.length;t<n;t++){let r=e+o[t].duration,i=e+o[t].cts;if(t<n-1){let e=r+o[t+1].cts;o[t].duration=e-i}else o[t].duration=t?o[t-1].duration:b;o[t].cts=0,e=r}}}f=D||!f?b:f;let M=m+f;this.nextVideoTs=u=M-l,this.videoSampleDuration=f,this.isVideoContiguous=!0;let N={data1:kK.moof(e.sequenceNumber++,p,hB(e,{samples:o})),data2:T,startPTS:(h-l)/i,endPTS:(g+f-l)/i,startDTS:(p-l)/i,endDTS:u/i,type:`video`,hasAudio:!1,hasVideo:!0,nb:o.length,dropped:e.dropped};return e.samples=[],e.dropped=0,N}getSamplesPerFrame(e){switch(e.segmentCodec){case`mp3`:return RK;case`ac3`:return zK;default:return LK}}remuxAudio(e,t,n,r,i){let a=e.inputTimeScale,o=a/(e.samplerate?e.samplerate:a),s=this.getSamplesPerFrame(e),c=s*o,l=this._initPTS,u=e.segmentCodec===`mp3`&&this.typeSupported.mpeg,d=[],f=i!==void 0,p=e.samples,m=u?0:8,h=this.nextAudioTs||-1,g=l.baseTime*a/l.timescale,_=g+t*a;if(this.isAudioContiguous=n||=p.length&&h>0&&(r&&Math.abs(_-(h+g))<9e3||Math.abs(WK(p[0].pts,_)-(h+g))<20*c),p.forEach(function(e){e.pts=WK(e.pts,_)}),!n||h<0){let e=p.length;if(p=p.filter(e=>e.pts>=0),e!==p.length&&this.warn(`Removed ${p.length-e} of ${e} samples (initPTS ${g} / ${a})`),!p.length)return;h=i===0?0:r&&!f?Math.max(0,_-g):p[0].pts-g}if(e.segmentCodec===`aac`){let t=this.config.maxAudioFramesDrift;for(let n=0,r=h+g;n<p.length;n++){let i=p[n],o=i.pts,s=o-r,l=Math.abs(1e3*s/a);if(s<=-t*c&&f)n===0&&(this.warn(`Audio frame @ ${(o/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*s/a)} ms.`),this.nextAudioTs=h=o-g,r=o);else if(s>=t*c&&l<IK&&f){let t=Math.round(s/c);for(r=o-t*c;r<0&&t&&c;)t--,r+=c;n===0&&(this.nextAudioTs=h=r-g),this.warn(`Injecting ${t} audio frames @ ${((r-g)/a).toFixed(3)}s due to ${Math.round(1e3*s/a)} ms gap.`);for(let a=0;a<t;a++){let t=DK.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);t||=(this.log(`Unable to get silent frame for given audio codec; duplicating last frame instead.`),i.unit.subarray()),p.splice(n,0,{unit:t,pts:r}),r+=c,n++}}i.pts=r,r+=c}}let v=null,y=null,b,x=0,S=p.length;for(;S--;)x+=p[S].unit.byteLength;for(let t=0,r=p.length;t<r;t++){let r=p[t],i=r.unit,a=r.pts;if(y!==null){let e=d[t-1];e.duration=Math.round((a-y)/o)}else if(n&&e.segmentCodec===`aac`&&(a=h+g),v=a,x>0){x+=m;try{b=new Uint8Array(x)}catch(e){this.observer.emit(Z.ERROR,Z.ERROR,{type:Y.MUX_ERROR,details:X.REMUX_ALLOC_ERROR,fatal:!1,error:e,bytes:x,reason:`fail allocating audio mdat ${x}`});return}u||(new DataView(b.buffer).setUint32(0,x),b.set(kK.types.mdat,4))}else return;b.set(i,m);let c=i.byteLength;m+=c,d.push(HK(!0,s,c,0)),y=a}let C=d.length;if(!C)return;let w=d[d.length-1];h=y-g,this.nextAudioTs=h+o*w.duration;let T=u?new Uint8Array:kK.moof(e.sequenceNumber++,v/o,hB({},e,{samples:d}));e.samples=[];let E=(v-g)/a,D=this.nextAudioTs/a,O={data1:T,data2:b,startPTS:E,endPTS:D,startDTS:E,endDTS:D,type:`audio`,hasAudio:!0,hasVideo:!1,nb:C};return this.isAudioContiguous=!0,O}};function WK(e,t){let n;if(t===null)return e;for(n=t<e?-8589934592:8589934592;Math.abs(e-t)>4294967296;)e+=n;return e}function GK(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function KK(e,t,n,r){let i=e.samples.length;if(!i)return;let a=e.inputTimeScale;for(let o=0;o<i;o++){let i=e.samples[o];i.pts=WK(i.pts-n.baseTime*a/n.timescale,t*a)/a,i.dts=WK(i.dts-r.baseTime*a/r.timescale,t*a)/a}let o=e.samples;return e.samples=[],{samples:o}}function qK(e,t,n){let r=e.samples.length;if(!r)return;let i=e.inputTimeScale;for(let a=0;a<r;a++){let r=e.samples[a];r.pts=WK(r.pts-n.baseTime*i/n.timescale,t*i)/i}e.samples.sort((e,t)=>e.pts-t.pts);let a=e.samples;return e.samples=[],{samples:a}}var JK=class extends bB{constructor(e,t,n,r){super(`passthrough-remuxer`,r),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;let t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,n,r){this.audioCodec=t,this.videoCodec=n,this.generateInitSegment(e,r),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:n,videoCodec:r}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}let{audio:i,video:a}=this.initData=aV(e);if(t)fV(e,t);else{let e=i||a;e!=null&&e.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${e.codec}")!`)}i&&(n=ZK(i,VB.AUDIO,this)),a&&(r=ZK(a,VB.VIDEO,this));let o={};i&&a?o.audiovideo={container:`video/mp4`,codec:n+`,`+r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:`main`}:i?o.audio={container:`audio/mp4`,codec:n,encrypted:i.encrypted,initSegment:e,id:`audio`}:a?o.video={container:`video/mp4`,codec:r,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:`main`}:this.warn(`initSegment does not contain moov or trak boxes.`),this.initTracks=o}remux(e,t,n,r,i,a){var o,s;let{initPTS:c,lastEndTime:l}=this,u={audio:void 0,video:void 0,text:r,id3:n,initSegment:void 0};J(l)||(l=this.lastEndTime=i||0);let d=t.samples;if(!d.length)return u;let f={initPTS:void 0,timescale:void 0,trackId:void 0},p=this.initData;if((o=p)!=null&&o.length||(this.generateInitSegment(d),p=this.initData),!((s=p)!=null&&s.length))return this.warn(`Failed to generate initSegment.`),u;this.emitInitSegment&&=(f.tracks=this.initTracks,!1);let m=gV(d,p,this),h=p.audio?m[p.audio.id]:null,g=p.video?m[p.video.id]:null,_=YK(g,1/0),v=YK(h,1/0),y=YK(g,0,!0),b=YK(h,0,!0),x=i,S=0,C=h&&(!g||!c&&v<_||c&&c.trackId===p.audio.id),w=C?h:g;if(w){let e=w.timescale,t=w.start-i*e,n=C?p.audio.id:p.video.id;x=w.start/e,S=C?b-v:y-_,(a||!c)&&(XK(c,x,i,S)||e!==c.timescale)&&(c&&this.warn(`Timestamps at playlist time: ${a?``:`~`}${i} ${t/e} != initPTS: ${c.baseTime/c.timescale} (${c.baseTime}/${c.timescale}) trackId: ${c.trackId}`),this.log(`Found initPTS at playlist time: ${i} offset: ${x-i} (${t}/${e}) trackId: ${n}`),c=null,f.initPTS=t,f.timescale=e,f.trackId=n)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${i}`);c?(f.initPTS=c.baseTime,f.timescale=c.timescale,f.trackId=c.trackId):((!f.timescale||f.trackId===void 0||f.initPTS===void 0)&&(this.warn(`Could not set initPTS`),f.initPTS=x,f.timescale=1,f.trackId=-1),this.initPTS=c={baseTime:f.initPTS,timescale:f.timescale,trackId:f.trackId});let T=x-c.baseTime/c.timescale,E=T+S;S>0?this.lastEndTime=E:(this.warn(`Duration parsed from mp4 should be greater than zero`),this.resetNextTimestamp());let D=!!p.audio,O=!!p.video,k=``;D&&(k+=`audio`),O&&(k+=`video`);let A=(p.audio?p.audio.encrypted:!1)||(p.video?p.video.encrypted:!1),j={data1:d,startPTS:T,startDTS:T,endPTS:E,endDTS:E,type:k,hasAudio:D,hasVideo:O,nb:1,dropped:0,encrypted:A};u.audio=D&&!O?j:void 0,u.video=O?j:void 0;let M=g?.sampleCount;if(M){let e=g.keyFrameIndex,t=e!==-1;j.nb=M,j.dropped=e===0||this.isVideoContiguous?0:t?e:M,j.independent=t,j.firstKeyFrame=e,t&&g.keyFrameStart&&(j.firstKeyFramePTS=(g.keyFrameStart-c.baseTime)/c.timescale),this.isVideoContiguous||(u.independent=t),this.isVideoContiguous||=t,j.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${e}/${M} dropped: ${j.dropped} start: ${j.firstKeyFramePTS||`NA`}`)}return u.initSegment=f,u.id3=KK(n,i,c,c),r.samples.length&&(u.text=qK(r,i,c)),u}};function YK(e,t,n=!1){return e?.start===void 0?t:(e.start+(n?e.duration:0))/e.timescale}function XK(e,t,n,r){if(e===null)return!0;let i=Math.max(r,1),a=t-e.baseTime/e.timescale;return Math.abs(a-n)>i}function ZK(e,t,n){let r=e.codec;return r&&r.length>4?r:t===VB.AUDIO?r===`ec-3`||r===`ac-3`||r===`alac`?r:r===`fLaC`||r===`Opus`?BV(r,!1):(n.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||`mp4a`):(n.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||`avc1`)}var QK;try{QK=self.performance.now.bind(self.performance)}catch{QK=Date.now}var $K=[{demux:fK,remux:JK},{demux:bK,remux:UK},{demux:oK,remux:UK},{demux:uK,remux:UK}];$K.splice(2,0,{demux:cK,remux:UK});var eq=class{constructor(e,t,n,r,i,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=n,this.id=i,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,n,r){let i=n.transmuxing;i.executeStart=QK();let a=new Uint8Array(e),{currentTransmuxState:o,transmuxConfig:s}=this;r&&(this.currentTransmuxState=r);let{contiguous:c,discontinuity:l,trackSwitch:u,accurateTimeOffset:d,timeOffset:f,initSegmentChange:p}=r||o,{audioCodec:m,videoCodec:h,defaultInitPts:g,duration:_,initSegmentData:v}=s,y=tq(a,t);if(y&&RU(y.method)){let e=this.getDecrypter(),t=zU(y.method);if(e.isSync()){let r=e.softwareDecrypt(a,y.key.buffer,y.iv.buffer,t);if(n.part>-1){let t=e.flush();r=t&&t.buffer}if(!r)return i.executeEnd=QK(),nq(n);a=new Uint8Array(r)}else return this.asyncResult=!0,this.decryptionPromise=e.webCryptoDecrypt(a,y.key.buffer,y.iv.buffer,t).then(e=>{let t=this.push(e,null,n);return this.decryptionPromise=null,t}),this.decryptionPromise}let b=this.needsProbing(l,u);if(b){let e=this.configureTransmuxer(a);if(e)return this.logger.warn(`[transmuxer] ${e.message}`),this.observer.emit(Z.ERROR,Z.ERROR,{type:Y.MEDIA_ERROR,details:X.FRAG_PARSING_ERROR,fatal:!1,error:e,reason:e.message}),i.executeEnd=QK(),nq(n)}(l||u||p||b)&&this.resetInitSegment(v,m,h,_,t),(l||p||b)&&this.resetInitialTimestamp(g),c||this.resetContiguity();let x=this.transmux(a,y,f,d,n);this.asyncResult=rq(x);let S=this.currentTransmuxState;return S.contiguous=!0,S.discontinuity=!1,S.trackSwitch=!1,i.executeEnd=QK(),x}flush(e){let t=e.transmuxing;t.executeStart=QK();let{decrypter:n,currentTransmuxState:r,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(e));let a=[],{timeOffset:o}=r;if(n){let t=n.flush();t&&a.push(this.push(t.buffer,null,e))}let{demuxer:s,remuxer:c}=this;if(!s||!c){t.executeEnd=QK();let n=[nq(e)];return this.asyncResult?Promise.resolve(n):n}let l=s.flush(o);return rq(l)?(this.asyncResult=!0,l.then(t=>(this.flushRemux(a,t,e),a))):(this.flushRemux(a,l,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,n){let{audioTrack:r,videoTrack:i,id3Track:a,textTrack:o}=t,{accurateTimeOffset:s,timeOffset:c}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${n.sn}${n.part>-1?` part: `+n.part:``} of ${this.id===Q.MAIN?`level`:`track`} ${n.level}`);let l=this.remuxer.remux(r,i,a,o,c,s,!0,this.id);e.push({remuxResult:l,chunkMeta:n}),n.transmuxing.executeEnd=QK()}resetInitialTimestamp(e){let{demuxer:t,remuxer:n}=this;!t||!n||(t.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){let{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,n,r,i){let{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,t,n,r),o.resetInitSegment(e,t,n,i))}destroy(){this.demuxer&&=(this.demuxer.destroy(),void 0),this.remuxer&&=(this.remuxer.destroy(),void 0)}transmux(e,t,n,r,i){let a;return a=t&&t.method===`SAMPLE-AES`?this.transmuxSampleAes(e,t,n,r,i):this.transmuxUnencrypted(e,n,r,i),a}transmuxUnencrypted(e,t,n,r){let{audioTrack:i,videoTrack:a,id3Track:o,textTrack:s}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,a,o,s,t,n,!1,this.id),chunkMeta:r}}transmuxSampleAes(e,t,n,r,i){return this.demuxer.demuxSampleAes(e,t,n).then(e=>({remuxResult:this.remuxer.remux(e.audioTrack,e.videoTrack,e.id3Track,e.textTrack,n,r,!1,this.id),chunkMeta:i}))}configureTransmuxer(e){let{config:t,observer:n,typeSupported:r}=this,i;for(let t=0,n=$K.length;t<n;t++){var a;if((a=$K[t].demux)!=null&&a.probe(e,this.logger)){i=$K[t];break}}if(!i)return Error(`Failed to find demuxer by probing fragment data`);let o=this.demuxer,s=this.remuxer,c=i.remux,l=i.demux;(!s||!(s instanceof c))&&(this.remuxer=new c(n,t,r,this.logger)),(!o||!(o instanceof l))&&(this.demuxer=new l(n,t,r,this.logger),this.probe=l.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||=this.decrypter=new uU(this.config),e}};function tq(e,t){let n=null;return e.byteLength>0&&t?.key!=null&&t.iv!==null&&t.method!=null&&(n=t),n}var nq=e=>({remuxResult:{},chunkMeta:e});function rq(e){return`then`in e&&e.then instanceof Function}var iq=class{constructor(e,t,n,r,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=n,this.duration=r,this.defaultInitPts=i||null}},aq=class{constructor(e,t,n,r,i,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=n,this.trackSwitch=r,this.timeOffset=i,this.initSegmentChange=a}},oq=0,sq=class{constructor(e,t,n,r){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=oq++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=e=>{let t=e.data,n=this.hls;if(!(!n||!(t!=null&&t.event)||t.instanceNo!==this.instanceNo))switch(t.event){case`init`:{let e=this.workerContext?.objectURL;e&&self.URL.revokeObjectURL(e);break}case`transmuxComplete`:this.handleTransmuxComplete(t.data);break;case`flush`:this.onFlush(t.data);break;case`workerLog`:n.logger[t.data.logType]&&n.logger[t.data.logType](t.data.message);break;default:t.data=t.data||{},t.data.frag=this.frag,t.data.part=this.part,t.data.id=this.id,n.trigger(t.event,t.data);break}},this.onWorkerError=e=>{if(!this.hls)return;let t=Error(`${e.message} (${e.filename}:${e.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(Z.ERROR,{type:Y.OTHER_ERROR,details:X.INTERNAL_EXCEPTION,fatal:!1,event:`demuxerWorker`,error:t})};let i=e.config;this.hls=e,this.id=t,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=n,this.onFlush=r;let a=(e,t)=>{t||={},t.frag=this.frag||void 0,e===Z.ERROR&&(t=t,t.parent=this.id,t.part=this.part,this.error=t.error),this.hls.trigger(e,t)};this.observer=new iG,this.observer.on(Z.FRAG_DECRYPTED,a),this.observer.on(Z.ERROR,a);let o=KV(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<`u`){let n=this.hls.logger;if(i.workerPath||sG()){try{i.workerPath?(n.log(`loading Web Worker ${i.workerPath} for "${t}"`),this.workerContext=lG(i.workerPath)):(n.log(`injecting Web Worker for "${t}"`),this.workerContext=cG());let{worker:e}=this.workerContext;e.addEventListener(`message`,this.onWorkerMessage),e.addEventListener(`error`,this.onWorkerError),e.postMessage({instanceNo:this.instanceNo,cmd:`init`,typeSupported:o,id:t,config:_H(i)})}catch(r){n.warn(`Error setting up "${t}" Web Worker, fallback to inline`,r),this.terminateWorker(),this.error=null,this.transmuxer=new eq(this.observer,o,i,``,t,e.logger)}return}}this.transmuxer=new eq(this.observer,o,i,``,t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){let e=this.instanceNo;this.instanceNo=oq++;let t=this.hls.config,n=KV(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:`reset`,resetNo:e,typeSupported:n,id:this.id,config:_H(t)})}}terminateWorker(){if(this.workerContext){let{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener(`message`,this.onWorkerMessage),e.removeEventListener(`error`,this.onWorkerError),uG(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{let e=this.transmuxer;e&&(e.destroy(),this.transmuxer=null)}let e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,n,r,i,a,o,s,c,l){c.transmuxing.start=self.performance.now();let{instanceNo:u,transmuxer:d}=this,f=a?a.start:i.start,p=i.decryptdata,m=this.frag,h=!(m&&i.cc===m.cc),g=!(m&&c.level===m.level),_=m?c.sn-m.sn:-1,v=this.part?c.part-this.part.index:-1,y=_===0&&c.id>1&&c.id===m?.stats.chunkCount,b=!g&&(_===1||_===0&&(v===1||y&&v<=0)),x=self.performance.now();(g||_||i.stats.parsing.start===0)&&(i.stats.parsing.start=x),a&&(v||!b)&&(a.stats.parsing.start=x);let S=!(m&&i.initSegment?.url===m.initSegment?.url),C=new aq(h,b,s,g,f,S);if(!b||h||S){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${c.sn}${c.part>-1?` part: `+c.part:``} ${this.id===Q.MAIN?`level`:`track`}: ${c.level} id: ${c.id}
50
- discontinuity: ${h}
51
- trackSwitch: ${g}
52
- contiguous: ${b}
53
- accurateTimeOffset: ${s}
54
- timeOffset: ${f}
55
- initSegmentChange: ${S}`);let e=new iq(n,r,t,o,l);this.configureTransmuxer(e)}if(this.frag=i,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:u,cmd:`demux`,data:e,decryptdata:p,chunkMeta:c,state:C},e instanceof ArrayBuffer?[e]:[]);else if(d){let t=d.push(e,p,c,C);rq(t)?t.then(e=>{this.handleTransmuxComplete(e)}).catch(e=>{this.transmuxerError(e,c,`transmuxer-interface push error`)}):this.handleTransmuxComplete(t)}}flush(e){e.transmuxing.start=self.performance.now();let{instanceNo:t,transmuxer:n}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:`flush`,chunkMeta:e});else if(n){let t=n.flush(e);rq(t)?t.then(t=>{this.handleFlushResult(t,e)}).catch(t=>{this.transmuxerError(t,e,`transmuxer-interface flush error`)}):this.handleFlushResult(t,e)}}transmuxerError(e,t,n){this.hls&&(this.error=e,this.hls.trigger(Z.ERROR,{type:Y.MEDIA_ERROR,details:X.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,t){e.forEach(e=>{this.handleTransmuxComplete(e)}),this.onFlush(t)}configureTransmuxer(e){let{instanceNo:t,transmuxer:n}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:`configure`,config:e}):n&&n.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},cq=100,lq=class extends ZW{constructor(e,t,n){super(e,t,n,`audio-stream-controller`,Q.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(Z.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Z.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(Z.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Z.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Z.BUFFER_RESET,this.onBufferReset,this),e.on(Z.BUFFER_CREATED,this.onBufferCreated,this),e.on(Z.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Z.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Z.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Z.FRAG_LOADING,this.onFragLoading,this),e.on(Z.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){let{hls:e}=this;e&&(super.unregisterListeners(),e.off(Z.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Z.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(Z.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Z.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Z.BUFFER_RESET,this.onBufferReset,this),e.off(Z.BUFFER_CREATED,this.onBufferCreated,this),e.off(Z.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Z.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Z.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Z.FRAG_LOADING,this.onFragLoading,this),e.off(Z.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:i,trackId:a}){if(n===Q.MAIN){let e=t.cc,n=this.fragCurrent;if(this.initPTS[e]={baseTime:r,timescale:i,trackId:a},this.log(`InitPTS for cc: ${e} found from main: ${r/i} (${r}/${i}) trackId: ${a}`),this.mainAnchor=t,this.state===$.WAITING_INIT_PTS){let n=this.waitingData;(!n&&!this.loadingParts||n&&n.frag.cc!==e)&&this.syncWithAnchor(t,n?.frag)}else !this.hls.hasEnoughToStart&&n&&n.cc!==e?(n.abortRequests(),this.syncWithAnchor(t,n)):this.state===$.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){let n=this.mainFragLoading?.frag||null;if(t&&n?.cc===t.cc)return;let r=(n||e).cc,i=RH(this.getLevelDetails(),r,this.getLoadPosition());i&&(this.log(`Syncing with main frag at ${i.start} cc ${i.cc}`),this.startFragRequested=!1,this.nextLoadPosition=i.start,this.resetLoadingState(),this.state===$.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=$.STOPPED;return}let n=this.lastCurrentTime;this.stopLoad(),this.setInterval(cq),n>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n,this.state=$.IDLE):this.state=$.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case $.IDLE:this.doTickIdle();break;case $.WAITING_TRACK:{let{levels:e,trackId:t}=this,n=e?.[t],r=n?.details;if(r&&!this.waitForLive(n)){if(this.waitForCdnTuneIn(r))break;this.state=$.WAITING_INIT_PTS}break}case $.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case $.WAITING_INIT_PTS:{let e=this.waitingData;if(e){let{frag:t,part:n,cache:r,complete:i}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=$.FRAG_LOADING;let e={frag:t,part:n,payload:r.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(e),i&&super._handleFragmentLoadComplete(e)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=$.IDLE}}this.onTickEnd()}resetLoadingState(){let e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){let{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){let{hls:e,levels:t,media:n,trackId:r}=this,i=e.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!i.startFragPrefetch)||!(t!=null&&t[r]))return;let a=t[r],o=a.details;if(!o||this.waitForLive(a)||this.waitForCdnTuneIn(o)){this.state=$.WAITING_TRACK,this.startFragRequested=!1;return}let s=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&s&&(this.bufferFlushed=!1,this.afterBufferFlushed(s,VB.AUDIO,Q.AUDIO));let c=this.getFwdBufferInfo(s,Q.AUDIO);if(c===null)return;if(!this.switchingTrack&&this._streamEnded(c,o)){e.trigger(Z.BUFFER_EOS,{type:`audio`}),this.state=$.ENDED;return}let l=c.len,u=e.maxBufferLength,d=o.fragments,f=d[0].start,p=this.getLoadPosition(),m=this.flushing?p:c.end;if(this.switchingTrack&&n){let e=p;o.PTSKnown&&e<f&&(c.end>f||c.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track`),n.currentTime=f+.05)}if(l>=u&&!this.switchingTrack&&m<d[d.length-1].start)return;let h=this.getNextFragment(m,o);if(h&&this.isLoopLoading(h,m)&&(h=this.getNextFragmentLoopLoading(h,o,c,Q.MAIN,u)),!h){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(c,u,h))return;let g=this.mainFragLoading?.frag||null;if(!this.audioOnly&&this.startFragRequested&&g&&UB(h)&&!h.endList&&(!o.live||!this.loadingParts&&m<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(g)===QH.OK&&(this.mainFragLoading=g=null),g&&UB(g))){if(h.start>g.end){let e=this.fragmentTracker.getFragAtPos(m,Q.MAIN);e&&e.end>g.end&&(g=e,this.mainFragLoading={frag:e,targetBufferTime:null})}if(h.start>g.end)return}this.loadFragment(h,a,m)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(e=>new fH(e))}onAudioTrackSwitching(e,t){let n=!!t.url;this.trackId=t.id;let{fragCurrent:r}=this;r&&(r.abortRequests(),this.removeUnbufferedFrags(r.start)),this.resetLoadingState(),n?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==$.STOPPED&&(this.setInterval(cq),this.state=$.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;let n=this.cachedTrackLoadedData;n&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(Z.AUDIO_TRACK_LOADED,n))}onAudioTrackLoaded(e,t){var n;let{levels:r}=this,{details:i,id:a,groupId:o,track:s}=t;if(!r){this.warn(`Audio tracks reset while loading track ${a} "${s.name}" of "${o}"`);return}let c=this.mainDetails;if(!c||i.endCC>c.endCC||c.expired){this.cachedTrackLoadedData=t,this.state!==$.STOPPED&&(this.state=$.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${s.name}" of "${o}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:``},duration:${i.totalduration}`);let l=r[a],u=0;if(i.live||(n=l.details)!=null&&n.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;l.details&&(u=this.alignPlaylists(i,l.details,this.levelLastLoaded?.details)),i.alignedSliding||(KW(i,c),i.alignedSliding||qW(i,c),u=i.fragmentStart)}l.details=i,this.levelLastLoaded=l,this.startFragRequested||this.setStartPosition(c,u),this.hls.trigger(Z.AUDIO_TRACK_UPDATED,{details:i,id:a,groupId:t.groupId}),this.state===$.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=$.IDLE),this.tick()}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:r}=e,{config:i,trackId:a,levels:o}=this;if(!o){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${t.sn} of level ${t.level} will not be buffered`);return}let s=o[a];if(!s){this.warn(`Audio track is undefined on fragment load progress`);return}let c=s.details;if(!c){this.warn(`Audio track details undefined on fragment load progress`),this.removeUnbufferedFrags(t.start);return}let l=i.defaultAudioCodec||s.audioCodec||`mp4a.40.2`,u=this.transmuxer;u||=this.transmuxer=new sq(this.hls,Q.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this));let d=this.initPTS[t.cc],f=t.initSegment?.data;if(d!==void 0){let e=n?n.index:-1,i=e!==-1,a=new vU(t.level,t.sn,t.stats.chunkCount,r.byteLength,e,i);u.push(r,f,l,``,t,n,c.totalduration,!1,a,d)}else{this.log(`Unknown video PTS for cc ${t.cc}, waiting for video PTS before demuxing audio frag ${t.sn} of [${c.startSN} ,${c.endSN}],track ${a}`);let{cache:e}=this.waitingData=this.waitingData||{frag:t,part:n,cache:new $W,complete:!1};e.push(new Uint8Array(r)),this.state!==$.STOPPED&&(this.state=$.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;let n=t.tracks.audio;n&&(this.mediaBuffer=n.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===Q.MAIN&&UB(t.frag)&&(this.mainFragLoading=t,this.state===$.IDLE&&this.tick())}onFragBuffered(e,t){let{frag:n,part:r}=t;if(n.type!==Q.AUDIO){!this.audioOnly&&n.type===Q.MAIN&&!n.elementaryStreams.video&&!n.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?` p: `+r.index:``} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:`false`}`);return}if(UB(n)){this.fragPrevious=n;let e=this.switchingTrack;e&&(this.bufferedTrack=e,this.switchingTrack=null,this.hls.trigger(Z.AUDIO_TRACK_SWITCHED,_B({},e)))}this.fragBufferedComplete(n,r),this.media&&this.tick()}onError(e,t){if(t.fatal){this.state=$.ERROR;return}switch(t.details){case X.FRAG_GAP:case X.FRAG_PARSING_ERROR:case X.FRAG_DECRYPT_ERROR:case X.FRAG_LOAD_ERROR:case X.FRAG_LOAD_TIMEOUT:case X.KEY_LOAD_ERROR:case X.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Q.AUDIO,t);break;case X.AUDIO_TRACK_LOAD_ERROR:case X.AUDIO_TRACK_LOAD_TIMEOUT:case X.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===$.WAITING_TRACK&&t.context?.type===dB.AUDIO_TRACK&&(this.state=$.IDLE);break;case X.BUFFER_ADD_CODEC_ERROR:case X.BUFFER_APPEND_ERROR:if(t.parent!==`audio`)return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case X.BUFFER_FULL_ERROR:if(t.parent!==`audio`)return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,1/0,`audio`));break;case X.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==VB.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==VB.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===$.ENDED&&(this.state=$.IDLE);let e=this.mediaBuffer||this.media;e&&(this.afterBufferFlushed(e,t,Q.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;let n=`audio`,{hls:r}=this,{remuxResult:i,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}let{frag:s,part:c,level:l}=o,{details:u}=l,{audio:d,text:f,id3:p,initSegment:m}=i;if(this.fragContextChanged(s)||!u){this.fragmentTracker.removeFragment(s);return}if(this.state=$.PARSING,this.switchingTrack&&d&&this.completeAudioSwitch(this.switchingTrack),m!=null&&m.tracks){let e=s.initSegment||s;if(this.unhandledEncryptionError(m,s))return;this._bufferInitSegment(l,m.tracks,e,a),r.trigger(Z.FRAG_PARSING_INIT_SEGMENT,{frag:e,id:n,tracks:m.tracks})}if(d){let{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=d;c&&(c.elementaryStreams[VB.AUDIO]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),s.setElementaryStreamInfo(VB.AUDIO,e,t,n,r),this.bufferFragmentData(d,s,c,a)}if(p!=null&&(t=p.samples)!=null&&t.length){let e=hB({id:n,frag:s,details:u},p);r.trigger(Z.FRAG_PARSING_METADATA,e)}if(f){let e=hB({id:n,frag:s,details:u},f);r.trigger(Z.FRAG_PARSING_USERDATA,e)}}_bufferInitSegment(e,t,n,r){if(this.state!==$.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;let i=t.audio;i.id=Q.AUDIO;let a=e.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${a}/${i.codec}]`),a&&a.split(`,`).length===1&&(i.levelCodec=a),this.hls.trigger(Z.BUFFER_CODECS,t);let o=i.initSegment;if(o!=null&&o.byteLength){let e={type:`audio`,frag:n,part:null,chunkMeta:r,parent:n.type,data:o};this.hls.trigger(Z.BUFFER_APPENDING,e)}this.tickImmediate()}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);if(this.switchingTrack||r===QH.NOT_LOADED||r===QH.PARTIAL){var i;if(!UB(e))this._loadInitSegment(e,t);else if((i=t.details)!=null&&i.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=$.WAITING_INIT_PTS;let n=this.mainDetails;n&&n.fragmentStart!==t.details.fragmentStart&&qW(t.details,n)}else super.loadFragment(e,t,n)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){let{name:t,lang:n,assocLang:r,characteristics:i,audioCodec:a,channels:o}=this.bufferedTrack;wH({name:t,lang:n,assocLang:r,characteristics:i,audioCodec:a,channels:o},e,DH)||(AH(e.url,this.hls)?(this.log(`Switching audio track : flushing all audio`),super.flushMainBuffer(0,1/0,`audio`),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){let{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger(Z.AUDIO_TRACK_SWITCHED,_B({},e))}},uq=class extends bB{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,n){let r=t?.renditionReports;if(r){let i=-1;for(let n=0;n<r.length;n++){let a=r[n],o;try{o=new self.URL(a.URI,t.url).href}catch(e){this.warn(`Could not construct new URL for Rendition Report: ${e}`),o=a.URI||``}if(o===e){i=n;break}else o===e.substring(0,o.length)&&(i=n)}if(i!==-1){let e=r[i],a=parseInt(e[`LAST-MSN`])||t.lastPartSn,o=parseInt(e[`LAST-PART`])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){let e=Math.min(t.age-t.partTarget,t.targetduration);o>=0&&e>t.partTarget&&(o+=1)}let s=n&&uH(n);return new dH(a,o>=0?o:void 0,s)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(e){this.warn(`Could not construct new URL with HLS Delivery Directives: ${e}`)}return e}playlistLoaded(e,t,n){let{details:r,stats:i}=t,a=self.performance.now(),o=i.loading.first?Math.max(0,a-i.loading.first):0;r.advancedDateTime=Date.now()-o;let s=this.hls.config.timelineOffset;if(s!==r.appliedTimelineOffset){let e=Math.max(s||0,0);r.appliedTimelineOffset=e,r.fragments.forEach(t=>{t.setStart(t.playlistOffset+e)})}if(r.live||n!=null&&n.live){let s=`levelInfo`in t?t.levelInfo:t.track;if(r.reloaded(n),n&&r.fragments.length>0){DW(n,r,this);let e=r.playlistParsingError;if(e){this.warn(e);let n=this.hls;if(!n.config.ignorePlaylistParsingErrors){let{networkDetails:a}=t;n.trigger(Z.ERROR,{type:Y.NETWORK_ERROR,details:X.LEVEL_PARSING_ERROR,fatal:!1,url:r.url,error:e,reason:e.message,level:t.level||void 0,parent:r.fragments[0]?.type,networkDetails:a,stats:i});return}r.playlistParsingError=null}}r.requestScheduled===-1&&(r.requestScheduled=i.loading.start);let c=this.hls.mainForwardBufferInfo,l=c?c.end-c.len:0,u=PW(r,(r.edge-l)*1e3);if(r.requestScheduled+u<a?r.requestScheduled=a:r.requestScheduled+=u,this.log(`live playlist ${e} ${r.advanced?`REFRESHED `+r.lastPartSn+`-`+r.lastPartIndex:r.updated?`UPDATED`:`MISSED`}`),!this.canLoad||!r.live)return;let d,f,p;if(r.canBlockReload&&r.endSN&&r.advanced){let e=this.hls.config.lowLatencyMode,i=r.lastPartSn,o=r.endSN,c=r.lastPartIndex,l=c!==-1,u=i===o;l?u?(f=o+1,p=e?0:c):(f=i,p=e?c+1:r.maxPartIndex):f=o+1;let m=r.age,h=m+r.ageHeader,g=Math.min(h-r.partTarget,r.targetduration*1.5);if(g>0){if(h>r.targetduration*3)this.log(`Playlist last advanced ${m.toFixed(2)}s ago. Omitting segment and part directives.`),f=void 0,p=void 0;else if(n!=null&&n.tuneInGoal&&h-r.partTarget>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${g} with playlist age: ${r.age}`),g=0;else{let e=Math.floor(g/r.targetduration);if(f+=e,p!==void 0){let e=Math.round(g%r.targetduration/r.partTarget);p+=e}this.log(`CDN Tune-in age: ${r.ageHeader}s last advanced ${m.toFixed(2)}s goal: ${g} skip sn ${e} to part ${p}`)}r.tuneInGoal=g}if(d=this.getDeliveryDirectives(r,t.deliveryDirectives,f,p),e||!u){r.requestScheduled=a,this.loadingPlaylist(s,d);return}}else (r.canBlockReload||r.canSkipUntil)&&(d=this.getDeliveryDirectives(r,t.deliveryDirectives,f,p));d&&f!==void 0&&r.canBlockReload&&(r.requestScheduled=i.loading.first+Math.max(u-o*2,u/2)),this.scheduleLoading(s,d,r)}else this.clearTimer()}scheduleLoading(e,t,n){let r=n||e.details;if(!r){this.loadingPlaylist(e,t);return}let i=self.performance.now(),a=r.requestScheduled;if(i>=a){this.loadingPlaylist(e,t);return}let o=a-i;this.log(`reload live playlist ${e.name||e.bitrate+`bps`} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),o)}getDeliveryDirectives(e,t,n,r){let i=uH(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(n=t.msn,r=t.part,i=lH.No),new dH(n,r,i)}checkRetry(e){let t=e.details,n=zH(e),r=e.errorAction,{action:i,retryCount:a=0,retryConfig:o}=r||{},s=!!r&&!!o&&(i===JH.RetryRequest||!r.resolved&&i===JH.SendAlternateToPenaltyBox);if(s){var c;if(a>=o.maxNumRetry)return!1;if(n&&(c=e.context)!=null&&c.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{let e=UH(o,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),e),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${t}" in ${e}ms`)}e.levelRetry=!0,r.resolved=!0}return s}};function dq(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!fq(e[n].attrs,t[n].attrs))return!1;return!0}function fq(e,t,n){let r=e[`STABLE-RENDITION-ID`];return r&&!n?r===t[`STABLE-RENDITION-ID`]:!(n||[`LANGUAGE`,`NAME`,`CHARACTERISTICS`,`AUTOSELECT`,`DEFAULT`,`FORCED`,`ASSOC-LANGUAGE`]).some(n=>e[n]!==t[n])}function pq(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||``).toLowerCase())}var mq=class extends uq{constructor(e){super(e,`audio-track-controller`),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){let{hls:e}=this;e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Z.LEVEL_LOADING,this.onLevelLoading,this),e.on(Z.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Z.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(Z.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Z.LEVEL_LOADING,this.onLevelLoading,this),e.off(Z.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Z.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(Z.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){let{id:n,groupId:r,details:i}=t,a=this.tracksInGroup[n];if(!a||a.groupId!==r){this.warn(`Audio track with id:${n} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Audio track ${n} "${a.name}" lang:${a.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let n=t.audioGroups||null,r=this.groupIds,i=this.currentTrack;if(!n||r?.length!==n?.length||n!=null&&n.some(e=>r?.indexOf(e)===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>!n||n.indexOf(e.groupId)!==-1);if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.audioPreference;if(!i&&t){let n=CH(t,e,DH);if(n>-1)i=e[n];else{let e=CH(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);r===-1&&i&&(r=this.findTrackId(null));let a={audioTracks:e};this.log(`Updating audio tracks, ${e.length} track(s) found in group(s): ${n?.join(`,`)}`),this.hls.trigger(Z.AUDIO_TRACKS_UPDATED,a);let o=this.trackId;if(r!==-1&&o===-1)this.setAudioTrack(r);else if(e.length&&o===-1){let t=Error(`No audio track selected for current audio group-ID(s): ${this.groupIds?.join(`,`)} track count: ${e.length}`);this.warn(t.message),this.hls.trigger(Z.ERROR,{type:Y.MEDIA_ERROR,details:X.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:t})}}}onError(e,t){t.fatal||!t.context||t.context.type===dB.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){let t=this.hls;if(t.config.audioPreference=e,e){let n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){let r=this.currentTrack;if(r&&wH(e,r,DH))return r;let i=CH(e,this.tracksInGroup,DH);if(i>-1){let e=this.tracksInGroup[i];return this.setAudioTrack(i),e}else if(r){let r=t.loadLevel;r===-1&&(r=t.firstAutoLevel);let i=OH(e,t.levels,n,r,DH);if(i===-1)return null;t.nextLoadLevel=i}if(e.channels||e.audioCodec){let t=CH(e,n);if(t>-1)return n[t]}}}return null}setAudioTrack(e){let t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;let n=this.currentTrack,r=t[e],i=r.details&&!r.details.live;if(e===this.trackId&&r===n&&i||(this.log(`Switching to audio-track ${e} "${r.name}" lang:${r.lang} group:${r.groupId} channels:${r.channels}`),this.trackId=e,this.currentTrack=r,this.hls.trigger(Z.AUDIO_TRACK_SWITCHING,_B({},r)),i))return;let a=this.switchParams(r.url,n?.details,r.details);this.loadPlaylist(a)}findTrackId(e){let t=this.tracksInGroup;for(let n=0;n<t.length;n++){let r=t[n];if(!(this.selectDefaultTrack&&!r.default)&&(!e||wH(e,r,DH)))return n}if(e){let{name:n,lang:r,assocLang:i,characteristics:a,audioCodec:o,channels:s}=e;for(let e=0;e<t.length;e++){let c=t[e];if(wH({name:n,lang:r,assocLang:i,characteristics:a,audioCodec:o,channels:s},c,DH))return e}for(let n=0;n<t.length;n++){let r=t[n];if(fq(e.attrs,r.attrs,[`LANGUAGE`,`ASSOC-LANGUAGE`,`CHARACTERISTICS`]))return n}for(let n=0;n<t.length;n++){let r=t[n];if(fq(e.attrs,r.attrs,[`LANGUAGE`]))return n}}return-1}loadPlaylist(e){super.loadPlaylist();let t=this.currentTrack;this.shouldLoadPlaylist(t)&&AH(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading audio-track ${n} "${e.name}" lang:${e.lang} group:${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${i}`),this.hls.trigger(Z.AUDIO_TRACK_LOADING,{url:i,id:n,groupId:r,deliveryDirectives:t||null,track:e})}},hq=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,n){if(this.queues===null||this.tracks===null)return;let r=this.queues[t];r.push(e),r.length===1&&!n&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{let n={label:`async-blocker`,execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(n,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){let n={label:`async-blocker-prepend`,execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(n)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{let t=e[0]?.label;(t===`async-blocker`||t===`async-blocker-prepend`)&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){this.queues!==null&&this.queues.audio[0]===e&&this.shiftAndExecuteNext(`audio`)}executeNext(e){if(this.queues===null||this.tracks===null)return;let t=this.queues[e];if(t.length){let n=t[0];try{n.execute()}catch(t){if(n.onError(t),this.queues===null||this.tracks===null)return;let r=this.tracks[e]?.buffer;r!=null&&r.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){return this.queues?.[e][0]||null}toString(){let{queues:e,tracks:t}=this;return e===null||t===null?`<destroyed>`:`
56
- ${this.list(`video`)}
57
- ${this.list(`audio`)}
58
- ${this.list(`audiovideo`)}}`}list(e){var t,n;return(t=this.queues)!=null&&t[e]||(n=this.tracks)!=null&&n[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:``}listSbInfo(e){let t=this.tracks?.[e],n=t?.buffer;return n?`SourceBuffer${n.updating?` updating`:``}${t.ended?` ended`:``}${t.ending?` ending`:``}`:`none`}listOps(e){return this.queues?.[e].map(e=>e.label).join(`, `)||``}},gq=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,_q=`HlsJsTrackRemovedError`,vq=class extends Error{constructor(e){super(e),this.name=_q}},yq=class extends bB{constructor(e,t){super(`buffer-controller`,e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=e=>{this.hls&&this.mediaSource?.readyState===`open`&&this.hls.pauseBuffering()},this._onStartStreaming=e=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=e=>{let{media:t,mediaSource:n}=this;e&&this.log(`Media source opened`),!(!t||!n)&&(n.removeEventListener(`sourceopen`,this._onMediaSourceOpen),t.removeEventListener(`emptied`,this._onMediaEmptied),this.updateDuration(),this.hls.trigger(Z.MEDIA_ATTACHED,{media:t,mediaSource:n}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log(`Media source closed`)},this._onMediaSourceEnded=()=>{this.log(`Media source ended`)},this._onMediaEmptied=()=>{let{mediaSrc:e,_objectUrl:t}=this;e!==t&&this.error(`Media element src was set while attaching MediaSource (${t} > ${e})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=AB(kB(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&=(this.operationQueue.destroy(),null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){let{hls:e}=this;e.on(Z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Z.BUFFER_RESET,this.onBufferReset,this),e.on(Z.BUFFER_APPENDING,this.onBufferAppending,this),e.on(Z.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Z.BUFFER_EOS,this.onBufferEos,this),e.on(Z.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Z.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Z.FRAG_PARSED,this.onFragParsed,this),e.on(Z.FRAG_CHANGED,this.onFragChanged,this),e.on(Z.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(Z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Z.BUFFER_RESET,this.onBufferReset,this),e.off(Z.BUFFER_APPENDING,this.onBufferAppending,this),e.off(Z.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Z.BUFFER_EOS,this.onBufferEos,this),e.off(Z.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Z.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Z.FRAG_PARSED,this.onFragParsed,this),e.off(Z.FRAG_CHANGED,this.onFragChanged,this),e.off(Z.ERROR,this.onError,this)}transferMedia(){let{media:e,mediaSource:t}=this;if(!e)return null;let n={};if(this.operationQueue){let e=this.isUpdating();e||this.operationQueue.removeBlockers();let t=this.isQueued();(e||t)&&this.warn(`Transfering MediaSource with${t?` operations in queue`:``}${e?` updating SourceBuffer(s)`:``} ${this.operationQueue}`),this.operationQueue.destroy()}let r=this.transferData;return!this.sourceBufferCount&&r&&r.mediaSource===t?hB(n,r.tracks):this.sourceBuffers.forEach(e=>{let[t]=e;t&&(n[t]=hB({},this.tracks[t]),this.removeBuffer(t)),e[0]=e[1]=null}),{media:e,mediaSource:t,tracks:n}}initTracks(){let e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var n;let r=2;(t.audio&&!t.video||!t.altAudio)&&(r=1),this.bufferCodecEventsTotal=r,this.log(`${r} bufferCodec event(s) expected.`),(n=this.transferData)!=null&&n.mediaSource&&this.sourceBufferCount&&r&&this.bufferCreated()}onMediaAttaching(e,t){let n=this.media=t.media;this.transferData=this.overrides=void 0;let r=kB(this.appendSource);if(r){let e=!!t.mediaSource;(e||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);let i=this.mediaSource=t.mediaSource||new r;if(this.assignMediaSource(i),e)this._objectUrl=n.src,this.attachTransferred();else{let e=this._objectUrl=self.URL.createObjectURL(i);if(this.appendSource)try{n.removeAttribute(`src`);let t=self.ManagedMediaSource;n.disableRemotePlayback=n.disableRemotePlayback||t&&i instanceof t,bq(n),xq(n,e),n.load()}catch{n.src=e}else n.src=e}n.addEventListener(`emptied`,this._onMediaEmptied)}}assignMediaSource(e){this.log(`${this.transferData?.mediaSource===e?`transferred`:`created`} media source: ${e.constructor?.name}`),e.addEventListener(`sourceopen`,this._onMediaSourceOpen),e.addEventListener(`sourceended`,this._onMediaSourceEnded),e.addEventListener(`sourceclose`,this._onMediaSourceClose),this.appendSource&&(e.addEventListener(`startstreaming`,this._onStartStreaming),e.addEventListener(`endstreaming`,this._onEndStreaming))}attachTransferred(){let e=this.media,t=this.transferData;if(!t||!e)return;let n=this.tracks,r=t.tracks,i=r?Object.keys(r):null,a=i?i.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(r&&i&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log(`attachTransferred: waiting for SourceBuffer track info`);return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
59
- required tracks: ${_H(n,(e,t)=>e===`initSegment`?void 0:t)};
60
- transfer tracks: ${_H(r,(e,t)=>e===`initSegment`?void 0:t)}}`),!jB(r,n)){t.mediaSource=null,t.tracks=void 0;let i=e.currentTime,a=this.details,o=Math.max(i,a?.fragments[0].start||0);if(o-i>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${i} -> ${o}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(r)}"->"${Object.keys(n)}") start time: ${o} currentTime: ${i}`),this.onMediaDetaching(Z.MEDIA_DETACHING,{}),this.onMediaAttaching(Z.MEDIA_ATTACHING,t),e.currentTime=o;return}this.transferData=void 0,i.forEach(e=>{let t=e,n=r[t];if(n){let e=n.buffer;if(e){let r=this.fragmentTracker,i=n.id;if(r.hasFragments(i)||r.hasParts(i)){let n=xU.getBuffered(e);r.detectEvictedFragments(t,n,i,null,!0)}let a=Sq(t),o=[t,e];this.sourceBuffers[a]=o,e.updating&&this.operationQueue&&this.operationQueue.prependBlocker(t),this.trackSourceBuffer(t,n)}}}),o(),this.bufferCreated()}else this.log(`attachTransferred: MediaSource w/o SourceBuffers`),o()}get mediaSourceOpenOrEnded(){let e=this.mediaSource?.readyState;return e===`open`||e===`ended`}onMediaDetaching(e,t){let n=!!t.transferMedia;this.transferData=this.overrides=void 0;let{media:r,mediaSource:i,_objectUrl:a}=this;if(i){if(this.log(`media source ${n?`transferring`:`detaching`}`),n)this.sourceBuffers.forEach(([e])=>{e&&this.removeBuffer(e)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){let e=i.readyState===`open`;try{let t=i.sourceBuffers;for(let n=t.length;n--;)e&&t[n].abort(),i.removeSourceBuffer(t[n]);e&&i.endOfStream()}catch(e){this.warn(`onMediaDetaching: ${e.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener(`sourceopen`,this._onMediaSourceOpen),i.removeEventListener(`sourceended`,this._onMediaSourceEnded),i.removeEventListener(`sourceclose`,this._onMediaSourceClose),this.appendSource&&(i.removeEventListener(`startstreaming`,this._onStartStreaming),i.removeEventListener(`endstreaming`,this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}r&&(r.removeEventListener(`emptied`,this._onMediaEmptied),n||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(r.removeAttribute(`src`),this.appendSource&&bq(r),r.load()):this.warn(`media|source.src was changed by a third party - skip cleanup`)),this.media=null),this.hls.trigger(Z.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){let t=this.tracks[e]?.buffer;if(this.removeBuffer(e),t)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(t)}catch(t){this.warn(`onBufferReset ${e}`,t)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Sq(e)]=[null,null];let t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new hq(this.tracks)}onBufferCodecs(e,t){let n=this.tracks,r=Object.keys(t);this.log(`BUFFER_CODECS: "${r}" (current SB count ${this.sourceBufferCount})`);let i=`audiovideo`in t&&(n.audio||n.video)||n.audiovideo&&(`audio`in t||`video`in t),a=!i&&this.sourceBufferCount&&this.media&&r.some(e=>!n[e]);if(i||a){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${r}" SourceBuffers`);return}r.forEach(e=>{var r;let{id:i,codec:a,levelCodec:o,container:s,metadata:c,supplemental:l}=t[e],u=n[e],d=(r=this.transferData)==null||(r=r.tracks)==null?void 0:r[e],f=d!=null&&d.buffer?d:u,p=f?.pendingCodec||f?.codec,m=f?.levelCodec;u||=n[e]={buffer:void 0,listeners:[],codec:a,supplemental:l,container:s,levelCodec:o,metadata:c,id:i};let h=HV(p,m),g=h?.replace(gq,`$1`),_=HV(a,o),v=_?.replace(gq,`$1`);_&&h&&g!==v&&(e.slice(0,5)===`audio`&&(_=BV(_,this.appendSource)),this.log(`switching codec ${p} to ${_}`),_!==(u.pendingCodec||u.codec)&&(u.pendingCodec=_),u.container=s,this.appendChangeType(e,s,_))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&t.audio?.id===`main`&&(this.log(`Main audio-only`),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{let n=this.tracks[t];return e[t]={id:n.id,container:n.container,codec:n.codec,levelCodec:n.levelCodec},e},{})}appendChangeType(e,t,n){let r=`${t};codecs=${n}`,i={label:`change-type=${r}`,execute:()=>{let i=this.tracks[e];if(i){let a=i.buffer;a!=null&&a.changeType&&(this.log(`changing ${e} sourceBuffer type to ${r}`),a.changeType(r),i.codec=n,i.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:t=>{this.warn(`Failed to change ${e} SourceBuffer type`,t)}};this.append(i,e,this.isPending(this.tracks[e]))}blockAudio(e){let t=e.start,n=t+e.duration*.05;if(this.fragmentTracker.getAppendedFrag(t,Q.MAIN)?.gap===!0)return;let r={label:`block-audio`,execute:()=>{let e=this.tracks.video;(this.lastVideoAppendEnd>n||e!=null&&e.buffer&&xU.isBuffered(e.buffer,n)||this.fragmentTracker.getAppendedFrag(n,Q.MAIN)?.gap===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext(`audio`))},onStart:()=>{},onComplete:()=>{},onError:e=>{this.warn(`Error executing block-audio operation`,e)}};this.blockedAudioAppend={op:r,frag:e},this.append(r,`audio`,!0)}unblockAudio(){let{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){let{tracks:n}=this,{data:r,type:i,parent:a,frag:o,part:s,chunkMeta:c,offset:l}=t,u=c.buffering[i],{sn:d,cc:f}=o,p=self.performance.now();u.start=p;let m=o.stats.buffering,h=s?s.stats.buffering:null;m.start===0&&(m.start=p),h&&h.start===0&&(h.start=p);let g=n.audio,_=!1;i===`audio`&&g?.container===`audio/mpeg`&&(_=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);let v=n.video,y=v?.buffer;if(y&&d!==`initSegment`){let e=s||o,t=this.blockedAudioAppend;if(i===`audio`&&a!==`main`&&!this.blockedAudioAppend&&!(v.ending||v.ended)){let t=e.start+e.duration*.05,n=y.buffered,r=this.currentOp(`video`);(!n.length&&!r||!r&&!xU.isBuffered(y,t)&&this.lastVideoAppendEnd<t)&&this.blockAudio(e)}else if(i===`video`){let n=e.end;if(t){let e=t.frag.start;(n>e||n<this.lastVideoAppendEnd||xU.isBuffered(y,e))&&this.unblockAudio()}this.lastVideoAppendEnd=n}}let b=(s||o).start,x={label:`append-${i}`,execute:()=>{u.executeStart=self.performance.now();let e=this.tracks[i]?.buffer;e&&(_?this.updateTimestampOffset(e,b,.1,i,d,f):l!==void 0&&J(l)&&this.updateTimestampOffset(e,l,1e-6,i,d,f)),this.appendExecutor(r,i)},onStart:()=>{},onComplete:()=>{let e=self.performance.now();u.executeEnd=u.end=e,m.first===0&&(m.first=e),h&&h.first===0&&(h.first=e);let t={};this.sourceBuffers.forEach(([e,n])=>{e&&(t[e]=xU.getBuffered(n))}),this.appendErrors[i]=0,i===`audio`||i===`video`?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(Z.BUFFER_APPENDED,{type:i,frag:o,part:s,chunkMeta:c,parent:o.type,timeRanges:t})},onError:e=>{let t={type:Y.MEDIA_ERROR,parent:o.type,details:X.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:s,chunkMeta:c,error:e,err:e,fatal:!1},n=this.media?.error;if(e.code===DOMException.QUOTA_EXCEEDED_ERR||e.name==`QuotaExceededError`||`quota`in e)t.details=X.BUFFER_FULL_ERROR;else if(e.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!n)t.errorAction=ZH(!0);else if(e.name===_q&&this.sourceBufferCount===0)t.errorAction=ZH(!0);else{let e=++this.appendErrors[i];this.warn(`Failed ${e}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${n||`no media error`})`),(e>=this.hls.config.appendErrorMaxRetry||n)&&(t.fatal=!0)}this.hls.trigger(Z.ERROR,t)}};this.log(`queuing "${i}" append sn: ${d}${s?` p: `+s.index:``} of ${o.type===Q.MAIN?`level`:`track`} ${o.level} cc: ${f}`),this.append(x,i,this.isPending(this.tracks[i]))}getFlushOp(e,t,n){return this.log(`queuing "${e}" remove ${t}-${n}`),{label:`remove`,execute:()=>{this.removeExecutor(e,t,n)},onStart:()=>{},onComplete:()=>{this.hls.trigger(Z.BUFFER_FLUSHED,{type:e})},onError:r=>{this.warn(`Failed to remove ${t}-${n} from "${e}" SourceBuffer`,r)}}}onBufferFlushing(e,t){let{type:n,startOffset:r,endOffset:i}=t;n?this.append(this.getFlushOp(n,r,i),n):this.sourceBuffers.forEach(([e])=>{e&&this.append(this.getFlushOp(e,r,i),e)})}onFragParsed(e,t){let{frag:n,part:r}=t,i=[],a=r?r.elementaryStreams:n.elementaryStreams;a[VB.AUDIOVIDEO]?i.push(`audiovideo`):(a[VB.AUDIO]&&i.push(`audio`),a[VB.VIDEO]&&i.push(`video`)),i.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(()=>{let e=self.performance.now();n.stats.buffering.end=e,r&&(r.stats.buffering.end=e);let t=r?r.stats:n.stats;this.hls.trigger(Z.FRAG_BUFFERED,{frag:n,part:r,stats:t,id:n.type})},i).catch(e=>{this.warn(`Fragment buffered callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){let t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){this.sourceBuffers.forEach(([e])=>{if(e){let n=this.tracks[e];(!t.type||t.type===e)&&(n.ending=!0,n.ended||(n.ended=!0,this.log(`${e} buffer reached EOS`)))}});let n=this.overrides?.endOfStream!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{var t;return e&&!((t=this.tracks[e])!=null&&t.ended)})?n?(this.log(`Queueing EOS`),this.blockUntilOpen(()=>{this.tracksEnded();let{mediaSource:e}=this;if(!e||e.readyState!==`open`){e&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${e.readyState}`);return}this.log(`Calling mediaSource.endOfStream()`),e.endOfStream(),this.hls.trigger(Z.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(Z.BUFFERED_TO_END,void 0)):t.type===`video`&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){let t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{let e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===X.BUFFER_APPEND_ERROR&&t.frag){let e=t.errorAction?.nextAutoLevel;J(e)&&e!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){let{hls:e,details:t,media:n}=this;if(!n||t===null||!this.sourceBufferCount)return;let r=e.config,i=n.currentTime,a=t.levelTargetDuration,o=t.live&&r.liveBackBufferLength!==null?r.liveBackBufferLength:r.backBufferLength;if(J(o)&&o>=0){let e=Math.max(o,a),t=Math.floor(i/a)*a-e;this.flushBackBuffer(i,a,t)}let s=r.frontBufferFlushThreshold;if(J(s)&&s>0){let e=Math.max(r.maxBufferLength,s),t=Math.max(e,a),n=Math.floor(i/a)*a+t;this.flushFrontBuffer(i,a,n)}}flushBackBuffer(e,t,n){this.sourceBuffers.forEach(([e,t])=>{if(t){let i=xU.getBuffered(t);if(i.length>0&&n>i.start(0)){var r;this.hls.trigger(Z.BACK_BUFFER_REACHED,{bufferEnd:n});let t=this.tracks[e];if((r=this.details)!=null&&r.live)this.hls.trigger(Z.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(t!=null&&t.ended){this.log(`Cannot flush ${e} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(Z.BUFFER_FLUSHING,{startOffset:0,endOffset:n,type:e})}}})}flushFrontBuffer(e,t,n){this.sourceBuffers.forEach(([t,r])=>{if(r){let i=xU.getBuffered(r),a=i.length;if(a<2)return;let o=i.start(a-1),s=i.end(a-1);if(n>o||e>=o&&e<=s)return;this.hls.trigger(Z.BUFFER_FLUSHING,{startOffset:o,endOffset:1/0,type:t})}})}getDurationAndRange(){let{details:e,mediaSource:t}=this;if(!e||!this.media||t?.readyState!==`open`)return null;let n=e.edge;if(e.live&&this.hls.config.liveDurationInfinity){if(e.fragments.length&&t.setLiveSeekableRange){let t=Math.max(0,e.fragmentStart);return{duration:1/0,start:t,end:Math.max(t,n)}}return{duration:1/0}}let r=this.overrides?.duration;if(r)return J(r)?{duration:r}:null;let i=this.media.duration;return n>(J(t.duration)?t.duration:0)&&n>i||!J(i)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:n}){let r=this.mediaSource;!this.media||!r||r.readyState!==`open`||(r.duration!==e&&(J(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),r.duration=e),t!==void 0&&n!==void 0&&(this.log(`MediaSource duration is set to ${r.duration}. Setting seekable range to ${t}-${n}.`),r.setLiveSeekableRange(t,n)))}get tracksReady(){let e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){let{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:n}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${_H(n)}`),this.tracksReady){let e=this.transferData?.tracks;e&&Object.keys(e).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){let e={};this.sourceBuffers.forEach(([t,n])=>{if(t){let r=this.tracks[t];e[t]={buffer:n,container:r.container,codec:r.codec,supplemental:r.supplemental,levelCodec:r.levelCodec,id:r.id,metadata:r.metadata}}}),this.hls.trigger(Z.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([e])=>{this.executeNext(e)})}else{let e=Error(`could not create source buffer for media codec(s)`);this.hls.trigger(Z.ERROR,{type:Y.MEDIA_ERROR,details:X.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){let{tracks:e,sourceBuffers:t,mediaSource:n}=this;if(!n)throw Error(`createSourceBuffers called when mediaSource was null`);for(let i in e){let a=i,o=e[a];if(this.isPending(o)){let e=this.getTrackCodec(o,a),i=`${o.container};codecs=${e}`;o.codec=e,this.log(`creating sourceBuffer(${i})${this.currentOp(a)?` Queued`:``} ${_H(o)}`);try{let e=n.addSourceBuffer(i),r=Sq(a);t[r]=[a,e],o.buffer=e}catch(e){var r;this.error(`error while trying to add sourceBuffer: ${e.message}`),this.shiftAndExecuteNext(a),(r=this.operationQueue)==null||r.removeBlockers(),delete this.tracks[a],this.hls.trigger(Z.ERROR,{type:Y.MEDIA_ERROR,details:X.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:e,sourceBufferName:a,mimeType:i,parent:o.id});return}this.trackSourceBuffer(a,o)}}this.bufferCreated()}getTrackCodec(e,t){let n=e.supplemental,r=e.codec;n&&(t===`video`||t===`audiovideo`)&&MV(n,`video`)&&(r=VV(r,n));let i=HV(r,e.levelCodec);return i?t.slice(0,5)===`audio`?BV(i,this.appendSource):i:``}trackSourceBuffer(e,t){let n=t.buffer;if(!n)return;let r=this.getTrackCodec(t,e);this.tracks[e]={buffer:n,codec:r,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,`updatestart`,this.onSBUpdateStart),this.addBufferListener(e,`updateend`,this.onSBUpdateEnd),this.addBufferListener(e,`error`,this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,`bufferedchange`,(e,t)=>{let n=t.removedRanges;n!=null&&n.length&&this.hls.trigger(Z.BUFFER_FLUSHED,{type:e})})}get mediaSrc(){var e,t;return(((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,`source`))||this.media)?.src}onSBUpdateStart(e){let t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){if(this.mediaSource?.readyState===`closed`){this.resetBuffer(e);return}let t=this.currentOp(e);t&&(t.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){let n=Error(`${e} SourceBuffer error. MediaSource readyState: ${this.mediaSource?.readyState}`);this.error(`${n}`,t),this.hls.trigger(Z.ERROR,{type:Y.MEDIA_ERROR,details:X.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});let r=this.currentOp(e);r&&r.onError(n)}updateTimestampOffset(e,t,n,r,i,a){let o=t-e.timestampOffset;Math.abs(o)>=n&&(this.log(`Updating ${r} SourceBuffer timestampOffset to ${t} (sn: ${i} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,n){let{media:r,mediaSource:i}=this,a=this.tracks[e],o=a?.buffer;if(!r||!i||!o){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}let s=J(r.duration)?r.duration:1/0,c=J(i.duration)?i.duration:1/0,l=Math.max(0,t),u=Math.min(n,s,c);u>l&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${l},${u}] from the ${e} SourceBuffer`),o.remove(l,u)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){let n=this.tracks[t],r=n?.buffer;if(!r)throw new vq(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);n.ending=!1,n.ended=!1,r.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(e=>{this.warn(`SourceBuffer blocked callback ${e}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(e){this.warn(`Callback run without blocking ${this.operationQueue} ${e}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log(`Blocking operation requested, but no SourceBuffers exist`),Promise.resolve().then(e);let{operationQueue:n}=this,r=t.map(e=>this.appendBlocker(e));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(r).then(t=>{n===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(e=>{let t=this.tracks[e]?.buffer;!t||t.updating||this.shiftAndExecuteNext(e)})}append(e,t,n){this.operationQueue&&this.operationQueue.append(e,t,n)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+ +!!this.isPending(this.tracks[t]),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+ +!!t,0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,n){let r=this.tracks[e];if(!r)return;let i=r.buffer;if(!i)return;let a=n.bind(this,e);r.listeners.push({event:t,listener:a}),i.addEventListener(t,a)}removeBufferListeners(e){let t=this.tracks[e];if(!t)return;let n=t.buffer;n&&(t.listeners.forEach(e=>{n.removeEventListener(e.event,e.listener)}),t.listeners.length=0)}};function bq(e){let t=e.querySelectorAll(`source`);[].slice.call(t).forEach(t=>{e.removeChild(t)})}function xq(e,t){let n=self.document.createElement(`source`);n.type=`video/mp4`,n.src=t,e.appendChild(n)}function Sq(e){return+(e===`audio`)}var Cq=class e{constructor(e){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=e,this.autoLevelCapping=1/0,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(e){this.streamController=e}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){let{hls:e}=this;e.on(Z.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.on(Z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Z.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Z.BUFFER_CODECS,this.onBufferCodecs,this),e.on(Z.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){let{hls:e}=this;e.off(Z.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),e.off(Z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Z.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Z.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Z.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(e,t){let n=this.hls.levels[t.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(e,t){this.media=t.media instanceof HTMLVideoElement?t.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(e,t){let n=this.hls;this.restrictedLevels=[],this.firstLevel=t.firstLevel,n.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onLevelsUpdated(e,t){this.timer&&J(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(e,t){this.hls.config.capLevelToPlayerSize&&t.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}let e=this.hls.levels;if(e.length){let t=this.hls,n=this.getMaxLevel(e.length-1);n!==this.autoLevelCapping&&t.logger.log(`Setting autoLevelCapping to ${n}: ${e[n].height}p@${e[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),t.autoLevelCapping=n,t.autoLevelEnabled&&t.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=t.autoLevelCapping}}}getMaxLevel(t){let n=this.hls.levels;if(!n.length)return-1;let r=n.filter((e,n)=>this.isLevelAllowed(e)&&n<=t);return this.clientRect=null,e.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=1/0,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=1/0,this.timer&&=(self.clearInterval(this.timer),void 0)}getDimensions(){if(this.clientRect)return this.clientRect;let e=this.media,t={width:0,height:0};if(e){let n=e.getBoundingClientRect();t.width=n.width,t.height=n.height,!t.width&&!t.height&&(t.width=n.right-n.left||e.width||0,t.height=n.bottom-n.top||e.height||0)}return this.clientRect=t,t}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return Math.min(e,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(e){return!this.restrictedLevels.some(t=>e.bitrate===t.bitrate&&e.width===t.width&&e.height===t.height)}static getMaxLevelByMediaSize(e,t,n){if(!(e!=null&&e.length))return-1;let r=(e,t)=>t?e.width!==t.width||e.height!==t.height:!0,i=e.length-1,a=Math.max(t,n);for(let t=0;t<e.length;t+=1){let n=e[t];if((n.width>=a||n.height>=a)&&r(n,e[t+1])){i=t;break}}return i}},wq={MANIFEST:`m`,AUDIO:`a`,VIDEO:`v`,MUXED:`av`,INIT:`i`,CAPTION:`c`,TIMED_TEXT:`tt`,KEY:`k`,OTHER:`o`},Tq={HLS:`h`},Eq=class e{constructor(t,n){Array.isArray(t)&&(t=t.map(t=>t instanceof e?t:new e(t))),this.value=t,this.params=n}},Dq=`Dict`;function Oq(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?`Map{}`:e instanceof Set?`Set{}`:typeof e==`object`?JSON.stringify(e):String(e)}function kq(e,t,n,r){return Error(`failed to ${e} "${Oq(t)}" as ${n}`,{cause:r})}function Aq(e,t,n){return kq(`serialize`,e,t,n)}var jq=class{constructor(e){this.description=e}},Mq=`Bare Item`,Nq=`Boolean`;function Pq(e){if(typeof e!=`boolean`)throw Aq(e,Nq);return e?`?1`:`?0`}function Fq(e){return btoa(String.fromCharCode(...e))}var Iq=`Byte Sequence`;function Lq(e){if(ArrayBuffer.isView(e)===!1)throw Aq(e,Iq);return`:${Fq(e)}:`}var Rq=`Integer`;function zq(e){return e<-999999999999999||999999999999999<e}function Bq(e){if(zq(e))throw Aq(e,Rq);return e.toString()}function Vq(e){return`@${Bq(e.getTime()/1e3)}`}function Hq(e,t){if(e<0)return-Hq(-e,t);let n=10**t;if(Math.abs(e*n%1-.5)<2**-52){let t=Math.floor(e*n);return(t%2==0?t:t+1)/n}else return Math.round(e*n)/n}var Uq=`Decimal`;function Wq(e){let t=Hq(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw Aq(e,Uq);let n=t.toString();return n.includes(`.`)?n:`${n}.0`}var Gq=`String`,Kq=/[\x00-\x1f\x7f]+/;function qq(e){if(Kq.test(e))throw Aq(e,Gq);return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}function Jq(e){return e.description||e.toString().slice(7,-1)}var Yq=`Token`;function Xq(e){let t=Jq(e);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw Aq(t,Yq);return t}function Zq(e){switch(typeof e){case`number`:if(!J(e))throw Aq(e,Mq);return Number.isInteger(e)?Bq(e):Wq(e);case`string`:return qq(e);case`symbol`:return Xq(e);case`boolean`:return Pq(e);case`object`:if(e instanceof Date)return Vq(e);if(e instanceof Uint8Array)return Lq(e);if(e instanceof jq)return Xq(e);default:throw Aq(e,Mq)}}var Qq=`Key`;function $q(e){if(/^[a-z*][a-z0-9\-_.*]*$/.test(e)===!1)throw Aq(e,Qq);return e}function eJ(e){return e==null?``:Object.entries(e).map(([e,t])=>t===!0?`;${$q(e)}`:`;${$q(e)}=${Zq(t)}`).join(``)}function tJ(e){return e instanceof Eq?`${Zq(e.value)}${eJ(e.params)}`:Zq(e)}function nJ(e){return`(${e.value.map(tJ).join(` `)})${eJ(e.params)}`}function rJ(e,t={whitespace:!0}){if(typeof e!=`object`||!e)throw Aq(e,Dq);let n=e instanceof Map?e.entries():Object.entries(e),r=t?.whitespace?` `:``;return Array.from(n).map(([e,t])=>{t instanceof Eq||(t=new Eq(t));let n=$q(e);return t.value===!0?n+=eJ(t.params):(n+=`=`,Array.isArray(t.value)?n+=nJ(t):n+=tJ(t)),n}).join(`,${r}`)}function iJ(e,t){return rJ(e,t)}var aJ=`CMCD-Object`,oJ=`CMCD-Request`,sJ=`CMCD-Session`,cJ=`CMCD-Status`,lJ={br:aJ,ab:aJ,d:aJ,ot:aJ,tb:aJ,tpb:aJ,lb:aJ,tab:aJ,lab:aJ,url:aJ,pb:oJ,bl:oJ,tbl:oJ,dl:oJ,ltc:oJ,mtp:oJ,nor:oJ,nrr:oJ,rc:oJ,sn:oJ,sta:oJ,su:oJ,ttfb:oJ,ttfbb:oJ,ttlb:oJ,cmsdd:oJ,cmsds:oJ,smrt:oJ,df:oJ,cs:oJ,ts:oJ,cid:sJ,pr:sJ,sf:sJ,sid:sJ,st:sJ,v:sJ,msd:sJ,bs:cJ,bsd:cJ,cdn:cJ,rtp:cJ,bg:cJ,pt:cJ,ec:cJ,e:cJ},uJ={REQUEST:oJ};function dJ(e){return Object.keys(e).reduce((t,n)=>{var r;return(r=e[n])==null||r.forEach(e=>t[e]=n),t},{})}function fJ(e,t){let n={};if(!e)return n;let r=Object.keys(e),i=t?dJ(t):{};return r.reduce((t,n)=>{let r=lJ[n]||i[n]||uJ.REQUEST,a=t[r]??(t[r]={});return a[n]=e[n],t},n)}function pJ(e){return[`ot`,`sf`,`st`,`e`,`sta`].includes(e)}function mJ(e){return typeof e==`number`?J(e):e!=null&&e!==``&&e!==!1}var hJ=`event`;function gJ(e,t){let n=new URL(e),r=new URL(t);if(n.origin!==r.origin)return e;let i=n.pathname.split(`/`).slice(1),a=r.pathname.split(`/`).slice(1,-1);for(;i[0]===a[0];)i.shift(),a.shift();for(;a.length;)a.shift(),i.unshift(`..`);return i.join(`/`)+n.search+n.hash}var _J=e=>Math.round(e),vJ=(e,t)=>Array.isArray(e)?e.map(e=>vJ(e,t)):e instanceof Eq&&typeof e.value==`string`?new Eq(vJ(e.value,t),e.params):(t.baseUrl&&(e=gJ(e,t.baseUrl)),t.version===1?encodeURIComponent(e):e),yJ=e=>_J(e/100)*100,bJ={br:_J,d:_J,bl:yJ,dl:yJ,mtp:yJ,nor:(e,t)=>{let n=e;return t.version>=2&&(e instanceof Eq&&typeof e.value==`string`?n=new Eq([e]):typeof e==`string`&&(n=[e])),vJ(n,t)},rtp:yJ,tb:_J},xJ=`request`,SJ=`response`,CJ=`ab.bg.bl.br.bs.bsd.cdn.cid.cs.df.ec.lab.lb.ltc.msd.mtp.pb.pr.pt.sf.sid.sn.st.sta.tab.tb.tbl.tpb.ts.v`.split(`.`),wJ=[`e`],TJ=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function EJ(e){return TJ.test(e)}function DJ(e){return CJ.includes(e)||wJ.includes(e)||EJ(e)}var OJ=[`d`,`dl`,`nor`,`ot`,`rtp`,`su`];function kJ(e){return CJ.includes(e)||OJ.includes(e)||EJ(e)}var AJ=[`cmsdd`,`cmsds`,`rc`,`smrt`,`ttfb`,`ttfbb`,`ttlb`,`url`];function jJ(e){return CJ.includes(e)||OJ.includes(e)||AJ.includes(e)||EJ(e)}var MJ=[`bl`,`br`,`bs`,`cid`,`d`,`dl`,`mtp`,`nor`,`nrr`,`ot`,`pr`,`rtp`,`sf`,`sid`,`st`,`su`,`tb`,`v`];function NJ(e){return MJ.includes(e)||EJ(e)}var PJ={[SJ]:jJ,[hJ]:DJ,[xJ]:kJ};function FJ(e,t={}){let n={};if(typeof e!=`object`||!e)return n;let r=t.version||e.v||1,i=t.reportingMode||xJ,a=r===1?NJ:PJ[i],o=Object.keys(e).filter(a),s=t.filter;typeof s==`function`&&(o=o.filter(s));let c=i===SJ||i===hJ;c&&!o.includes(`ts`)&&o.push(`ts`),r>1&&!o.includes(`v`)&&o.push(`v`);let l=hB({},bJ,t.formatters),u={version:r,reportingMode:i,baseUrl:t.baseUrl};return o.sort().forEach(t=>{let i=e[t],a=l[t];if(typeof a==`function`&&(i=a(i,u)),t===`v`){if(r===1)return;i=r}t==`pr`&&i===1||(c&&t===`ts`&&!J(i)&&(i=Date.now()),mJ(i)&&(pJ(t)&&typeof i==`string`&&(i=new jq(i)),n[t]=i))}),n}function IJ(e,t={}){let n={};if(!e)return n;let r=fJ(FJ(e,t),t?.customHeaderMap);return Object.entries(r).reduce((e,[t,n])=>{let r=iJ(n,{whitespace:!1});return r&&(e[t]=r),e},n)}function LJ(e,t,n){return hB(e,IJ(t,n))}var RJ=`CMCD`;function zJ(e,t={}){return e?iJ(FJ(e,t),{whitespace:!1}):``}function BJ(e,t={}){if(!e)return``;let n=zJ(e,t);return encodeURIComponent(n)}function VJ(e,t={}){return e?`${RJ}=${BJ(e,t)}`:``}var HJ=/CMCD=[^&#]+/;function UJ(e,t,n){let r=VJ(t,n);return r?HJ.test(e)?e.replace(HJ,r):`${e}${e.includes(`?`)?`&`:`?`}${r}`:e}var WJ=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||=!0,this.buffering=!1},this.applyPlaylistData=e=>{try{this.apply(e,{ot:wq.MANIFEST,su:!this.initialized})}catch(e){this.hls.logger.warn(`Could not generate manifest CMCD data.`,e)}},this.applyFragmentData=e=>{try{let{frag:t,part:n}=e,r=this.hls.levels[t.level],i=this.getObjectType(t),a={d:(n||t).duration*1e3,ot:i};(i===wq.VIDEO||i===wq.AUDIO||i==wq.MUXED)&&(a.br=r.bitrate/1e3,a.tb=this.getTopBandwidth(i)/1e3,a.bl=this.getBufferLength(i));let o=n?this.getNextPart(n):this.getNextFrag(t);o!=null&&o.url&&o.url!==t.url&&(a.nor=o.url),this.apply(e,a)}catch(e){this.hls.logger.warn(`Could not generate segment CMCD data.`,e)}},this.hls=e;let t=this.config=e.config,{cmcd:n}=t;n!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||e.sessionId,this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.includeKeys=n.includeKeys,this.registerListeners())}registerListeners(){let e=this.hls;e.on(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Z.MEDIA_DETACHED,this.onMediaDetached,this),e.on(Z.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){let e=this.hls;e.off(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Z.MEDIA_DETACHED,this.onMediaDetached,this),e.off(Z.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener(`waiting`,this.onWaiting),this.media.addEventListener(`playing`,this.onPlaying)}onMediaDetached(){this.media&&=(this.media.removeEventListener(`waiting`,this.onWaiting),this.media.removeEventListener(`playing`,this.onPlaying),null)}onBufferCreated(e,t){this.audioBuffer=t.tracks.audio?.buffer,this.videoBuffer=t.tracks.video?.buffer}createData(){return{v:1,sf:Tq.HLS,sid:this.sid,cid:this.cid,pr:this.media?.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){hB(t,this.createData());let n=t.ot===wq.INIT||t.ot===wq.VIDEO||t.ot===wq.MUXED;this.starved&&n&&(t.bs=!0,t.su=!0,this.starved=!1),t.su??=this.buffering;let{includeKeys:r}=this;r&&(t=Object.keys(t).reduce((e,n)=>(r.includes(n)&&(e[n]=t[n]),e),{}));let i={baseUrl:e.url};this.useHeaders?(e.headers||={},LJ(e.headers,t,i)):e.url=UJ(e.url,t,i)}getNextFrag(e){let t=this.hls.levels[e.level]?.details;if(t){let n=e.sn-t.startSN;return t.fragments[n+1]}}getNextPart(e){var t;let{index:n,fragment:r}=e,i=(t=this.hls.levels[r.level])==null||(t=t.details)==null?void 0:t.partList;if(i){let{sn:e}=r;for(let t=i.length-1;t>=0;t--){let r=i[t];if(r.index===n&&r.fragment.sn===e)return i[t+1]}}}getObjectType(e){let{type:t}=e;if(t===`subtitle`)return wq.TIMED_TEXT;if(e.sn===`initSegment`)return wq.INIT;if(t===`audio`)return wq.AUDIO;if(t===`main`)return this.hls.audioTracks.length?wq.VIDEO:wq.MUXED}getTopBandwidth(e){let t=0,n,r=this.hls;if(e===wq.AUDIO)n=r.audioTracks;else{let e=r.maxAutoLevel,t=e>-1?e+1:r.levels.length;n=r.levels.slice(0,t)}return n.forEach(e=>{e.bitrate>t&&(t=e.bitrate)}),t>0?t:NaN}getBufferLength(e){let t=this.media,n=e===wq.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!t?NaN:xU.bufferInfo(n,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){let{pLoader:e}=this.config,t=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,r)}}}createFragmentLoader(){let{fLoader:e}=this.config,t=this.applyFragmentData,n=e||this.config.loader;return class{constructor(e){this.loader=void 0,this.loader=new n(e)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(e,n,r){t(e),this.loader.load(e,n,r)}}}},GJ=3e5,KJ=class extends bB{constructor(e){super(`content-steering`,e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=`.`,this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){let e=this.hls;e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Z.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Z.ERROR,this.onError,this)}unregisterListeners(){let e=this.hls;e&&(e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Z.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Z.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){let e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&=(this.loader.destroy(),null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){let t=this.levels;t&&(this.levels=t.filter(t=>t!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=`.`,this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){let{contentSteering:n}=t;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){let{errorAction:n}=t;if(n?.action===JH.SendAlternateToPenaltyBox&&n.flags===YH.MoveAllAlternatesMatchingHost){let e=this.levels,r=this._pathwayPriority,i=this.pathwayId;if(t.context){let{groupId:n,pathwayId:r,type:a}=t.context;n&&e?i=this.getPathwayForGroupId(n,a,i):r&&(i=r)}i in this.penalizedPathways||(this.penalizedPathways[i]=performance.now()),!r&&e&&(r=this.pathways()),r&&r.length>1&&(this.updatePathwayPriority(r),n.resolved=this.pathwayId!==i),t.details===X.BUFFER_APPEND_ERROR&&!t.fatal?n.resolved=!0:n.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${i} levels: ${e&&e.length} priorities: ${_H(r)} penalized: ${_H(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){let n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),t=this.getLevelsForPathway(n),this.pathwayId=n}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t,n=this.penalizedPathways,r=performance.now();Object.keys(n).forEach(e=>{r-n[e]>GJ&&delete n[e]});for(let r=0;r<e.length;r++){let i=e[r];if(i in n)continue;if(i===this.pathwayId)return;let a=this.hls.nextLoadLevel,o=this.hls.levels[a];if(t=this.getLevelsForPathway(i),t.length>0){this.log(`Setting Pathway to "${i}"`),this.pathwayId=i,RW(t),this.hls.trigger(Z.LEVELS_UPDATED,{levels:t});let e=this.hls.levels[a];o&&e&&this.levels&&(e.attrs[`STABLE-VARIANT-ID`]!==o.attrs[`STABLE-VARIANT-ID`]&&e.bitrate!==o.bitrate&&this.log(`Unstable Pathways change from bitrate ${o.bitrate} to ${e.bitrate}`),this.hls.nextLoadLevel=a);break}}}getPathwayForGroupId(e,t,n){let r=this.getLevelsForPathway(n).concat(this.levels||[]);for(let n=0;n<r.length;n++)if(t===dB.AUDIO_TRACK&&r[n].hasAudioGroup(e)||t===dB.SUBTITLE_TRACK&&r[n].hasSubtitleGroup(e))return r[n].pathwayId;return n}clonePathways(e){let t=this.levels;if(!t)return;let n={},r={};e.forEach(e=>{let{ID:i,"BASE-ID":a,"URI-REPLACEMENT":o}=e;if(t.some(e=>e.pathwayId===i))return;let s=this.getLevelsForPathway(a).map(e=>{let t=new kU(e.attrs);t[`PATHWAY-ID`]=i;let a=t.AUDIO&&`${t.AUDIO}_clone_${i}`,s=t.SUBTITLES&&`${t.SUBTITLES}_clone_${i}`;a&&(n[t.AUDIO]=a,t.AUDIO=a),s&&(r[t.SUBTITLES]=s,t.SUBTITLES=s);let c=JJ(e.uri,t[`STABLE-VARIANT-ID`],`PER-VARIANT-URIS`,o),l=new fH({attrs:t,audioCodec:e.audioCodec,bitrate:e.bitrate,height:e.height,name:e.name,url:c,videoCodec:e.videoCodec,width:e.width});if(e.audioGroups)for(let t=1;t<e.audioGroups.length;t++)l.addGroupId(`audio`,`${e.audioGroups[t]}_clone_${i}`);if(e.subtitleGroups)for(let t=1;t<e.subtitleGroups.length;t++)l.addGroupId(`text`,`${e.subtitleGroups[t]}_clone_${i}`);return l});t.push(...s),qJ(this.audioTracks,n,o,i),qJ(this.subtitleTracks,r,o,i)})}loadSteeringManifest(e){let t=this.hls.config,n=t.loader;this.loader&&this.loader.destroy(),this.loader=new n(t);let r;try{r=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(r.protocol!==`data:`){let e=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;r.searchParams.set(`_HLS_pathway`,this.pathwayId),r.searchParams.set(`_HLS_throughput`,``+e)}let i={responseType:`json`,url:r.href},a=t.steeringManifestLoadPolicy.default,o=a.errorRetry||a.timeoutRetry||{},s={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:o.maxNumRetry||0,retryDelay:o.retryDelayMs||0,maxRetryDelay:o.maxRetryDelayMs||0};this.log(`Requesting steering manifest: ${r}`),this.loader.load(i,s,{onSuccess:(e,t,n,i)=>{this.log(`Loaded steering manifest: "${r}"`);let a=e.data;if(a?.VERSION!==1){this.log(`Steering VERSION ${a.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=a.TTL;let{"RELOAD-URI":o,"PATHWAY-CLONES":s,"PATHWAY-PRIORITY":c}=a;if(o)try{this.uri=new self.URL(o,r).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${o}`);return}this.scheduleRefresh(this.uri||n.url),s&&this.clonePathways(s);let l={steeringManifest:a,url:r.toString()};this.hls.trigger(Z.STEERING_MANIFEST_LOADED,l),c&&this.updatePathwayPriority(c)},onError:(e,t,n,r)=>{if(this.log(`Error loading steering manifest: ${e.code} ${e.text} (${t.url})`),this.stopLoad(),e.code===410){this.enabled=!1,this.log(`Steering manifest ${t.url} no longer available`);return}let i=this.timeToLoad*1e3;if(e.code===429){let e=this.loader;if(typeof e?.getResponseHeader==`function`){let t=e.getResponseHeader(`Retry-After`);t&&(i=parseFloat(t)*1e3)}this.log(`Steering manifest ${t.url} rate limited`);return}this.scheduleRefresh(this.uri||t.url,i)},onTimeout:(e,t,n)=>{this.log(`Timeout loading steering manifest (${t.url})`),this.scheduleRefresh(this.uri||t.url)}})}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{let t=this.hls?.media;if(t&&!t.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function qJ(e,t,n,r){e&&Object.keys(t).forEach(i=>{let a=e.filter(e=>e.groupId===i).map(e=>{let a=hB({},e);return a.details=void 0,a.attrs=new kU(a.attrs),a.url=a.attrs.URI=JJ(e.url,e.attrs[`STABLE-RENDITION-ID`],`PER-RENDITION-URIS`,n),a.groupId=a.attrs[`GROUP-ID`]=t[i],a.attrs[`PATHWAY-ID`]=r,a});e.push(...a)})}function JJ(e,t,n,r){let{HOST:i,PARAMS:a,[n]:o}=r,s;t&&(s=o?.[t],s&&(e=s));let c=new self.URL(e);return i&&!s&&(c.host=i),a&&Object.keys(a).sort().forEach(e=>{e&&c.searchParams.set(e,a[e])}),c.href}var YJ=class e extends bB{constructor(t){super(`eme`,t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=e.CDMCleanupPromise?[e.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=e=>{let{initDataType:t,initData:n}=e,r=`"${e.type}" event: init data type: "${t}"`;if(this.debug(r),n!==null){if(!this.keyFormatPromise){let e=Object.keys(this.keySystemAccessPromises);e.length||(e=XU(this.config));let t=e.map(YU).filter(e=>!!e);this.keyFormatPromise=this.getKeyFormatPromise(t)}this.keyFormatPromise.then(i=>{let a=JU(i);if(t!==`sinf`||a!==KU.FAIRPLAY){this.log(`Ignoring "${e.type}" event with init data type: "${t}" for selected key-system ${a}`);return}let o;try{let e=ZB(new Uint8Array(n)),t=hV(BU(JSON.parse(e).sinf));if(!t)throw Error(`'schm' box missing or not cbcs/cenc with schi > tenc`);o=new Uint8Array(t.subarray(8,24))}catch(e){this.warn(`${r} Failed to parse sinf: ${e}`);return}let s=NB(o),{keyIdToKeySessionPromise:c,mediaKeySessions:l}=this,u=c[s];for(let e=0;e<l.length;e++){let r=l[e],i=r.decryptdata;if(!i.keyId)continue;let a=NB(i.keyId);if(IU(o,i.keyId)||i.uri.replace(/-/g,``).indexOf(s)!==-1){if(u=c[a],!u)continue;if(i.pssh)break;delete c[a],i.pssh=new Uint8Array(n),i.keyId=o,u=c[s]=u.then(()=>this.generateRequestWithPreferredKeySession(r,t,n,`encrypted-event-key-match`)),u.catch(e=>this.handleError(e));break}}u||this.handleError(Error(`Key ID ${s} not encountered in playlist. Key-system sessions ${l.length}.`))}).catch(e=>this.handleError(e))}},this.onWaitingForKey=e=>{this.log(`"${e.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();let e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(Z.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(Z.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(Z.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(Z.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(Z.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(Z.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(Z.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(Z.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(e){let{drmSystems:t,widevineLicenseUrl:n}=this.config,r=t?.[e];if(r)return r.licenseUrl;if(e===KU.WIDEVINE&&n)return n}getLicenseServerUrlOrThrow(e){let t=this.getLicenseServerUrl(e);if(t===void 0)throw Error(`no license server URL configured for key-system "${e}"`);return t}getServerCertificateUrl(e){let{drmSystems:t}=this.config,n=t?.[e];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){let t=this.hls.levels,n=(e,t,n)=>!!e&&n.indexOf(e)===t,r=t.map(e=>e.audioCodec).filter(n),i=t.map(e=>e.videoCodec).filter(n);return r.length+i.length===0&&i.push(`avc1.42e01e`),new Promise((t,n)=>{let a=e=>{let o=e.shift();this.getMediaKeysPromise(o,r,i).then(e=>t({keySystem:o,mediaKeys:e})).catch(t=>{e.length?a(e):t instanceof QJ?n(t):n(new QJ({type:Y.KEY_SYSTEM_ERROR,details:X.KEY_SYSTEM_NO_ACCESS,error:t,fatal:!0},t.message))})};a(e)})}requestMediaKeySystemAccess(e,t){let{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!=`function`){let e=`Configured requestMediaKeySystemAccess is not a function ${n}`;return ZU===null&&self.location.protocol===`http:`&&(e=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(Error(e))}return n(e,t)}getMediaKeysPromise(e,t,n){let r=QU(e,t,n,this.config.drmSystemOptions||{}),i=this.keySystemAccessPromises[e],a=i?.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${_H(r)}`),a=this.requestMediaKeySystemAccess(e,r);let t=i=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(t=>{this.log(`Failed to obtain access to key-system "${e}": ${t}`)}),a.then(n=>{this.log(`Access for key-system "${n.keySystem}" obtained`);let r=this.fetchServerCertificate(e);this.log(`Create media-keys for "${e}"`);let i=t.mediaKeys=n.createMediaKeys().then(n=>(this.log(`Media-keys created for "${e}"`),t.hasMediaKeys=!0,r.then(t=>t?this.setMediaKeysServerCertificate(n,e,t):n)));return i.catch(t=>{this.error(`Failed to create media-keys for "${e}"}: ${t}`)}),i})}return a.then(()=>i.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:t,mediaKeys:n}){this.log(`Creating key-system session "${t}" keyId: ${NB(e.keyId||[])} keyUri: ${e.uri}`);let r={decryptdata:e,keySystem:t,mediaKeys:n,mediaKeysSession:n.createSession(),keyStatus:`status-pending`};return this.mediaKeySessions.push(r),r}renewKeySession(e){let t=e.decryptdata;if(t.pssh){let n=this.createMediaKeySessionContext(e),r=XJ(t);this.keyIdToKeySessionPromise[r]=this.generateRequestWithPreferredKeySession(n,`cenc`,t.pssh.buffer,`expired`)}else this.warn(`Could not renew expired session. Missing pssh initData.`);this.removeSession(e)}updateKeySession(e,t){let n=e.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyId ${NB(e.decryptdata.keyId||[])}
61
- } (data length: ${t.byteLength})`),n.update(t)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(e=>({keySystem:e,hasMediaKeys:this.keySystemAccessPromises[e].hasMediaKeys})).filter(({hasMediaKeys:e})=>!!e).map(({keySystem:e})=>YU(e)).filter(e=>!!e)}getKeySystemAccess(e){return this.getKeySystemSelectionPromise(e).then(({keySystem:e,mediaKeys:t})=>this.attemptSetMediaKeys(e,t))}selectKeySystem(e){return new Promise((t,n)=>{this.getKeySystemSelectionPromise(e).then(({keySystem:e})=>{let r=YU(e);r?t(r):n(Error(`Unable to find format for key-system "${e}"`))}).catch(n)})}selectKeySystemFormat(e){let t=Object.keys(e.levelkeys||{});return this.keyFormatPromise||=(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${t.join(`, `)}`),this.getKeyFormatPromise(t)),this.keyFormatPromise}getKeyFormatPromise(e){let t=XU(this.config),n=e.map(JU).filter(e=>!!e&&t.indexOf(e)!==-1);return this.selectKeySystem(n)}getKeyStatus(e){let{mediaKeySessions:t}=this;for(let n=0;n<t.length;n++){let r=ZJ(e,t[n]);if(r)return r}}loadKey(e){let t=e.keyInfo.decryptdata,n=XJ(t),r=this.bannedKeyIds[n];if(r||this.getKeyStatus(t)===`internal-error`){let n=$J(r||`internal-error`,t);return this.handleError(n,e.frag),Promise.reject(n)}let i=`(keyId: ${n} format: "${t.keyFormat}" method: ${t.method} uri: ${t.uri})`;this.log(`Starting session for key ${i}`);let a=this.keyIdToKeySessionPromise[n];if(!a){let r=this.getKeySystemForKeyPromise(t).then(({keySystem:n,mediaKeys:r})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(n,r).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:n,mediaKeys:r,decryptdata:t}))))).then(e=>{let n=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(e,`cenc`,n,`playlist-key`)});return r.catch(t=>this.handleError(t,e.frag)),this.keyIdToKeySessionPromise[n]=r,r}return a.catch(n=>{if(n instanceof QJ){let r=_B({},n.data);this.getKeyStatus(t)===`internal-error`&&(r.decryptdata=t);let i=new QJ(r,n.message);this.handleError(i,e.frag)}}),a}throwIfDestroyed(e=`Invalid state`){if(!this.hls)throw Error(`invalid state`)}handleError(e,t){if(this.hls)if(e instanceof QJ){t&&(e.data.frag=t);let n=e.data.decryptdata;this.error(`${e.message}${n?` (${NB(n.keyId||[])})`:``}`),this.hls.trigger(Z.ERROR,e.data)}else this.error(e.message),this.hls.trigger(Z.ERROR,{type:Y.KEY_SYSTEM_ERROR,details:X.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0})}getKeySystemForKeyPromise(e){let t=XJ(e),n=this.keyIdToKeySessionPromise[t];if(!n){let t=JU(e.keyFormat),n=t?[t]:XU(this.config);return this.attemptKeySystemAccess(n)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=XU(this.config)),e.length===0)throw new QJ({type:Y.KEY_SYSTEM_ERROR,details:X.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${_H({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}attemptSetMediaKeys(e,t){if(this.mediaResolved=void 0,this.mediaKeys===t)return Promise.resolve();let n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);let r=Promise.all(n).then(()=>this.media?this.media.setMediaKeys(t):new Promise((e,n)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return n(Error(`Attempted to set mediaKeys without media element attached`));this.mediaKeys=t,this.media.setMediaKeys(t).then(e).catch(n)}}));return this.mediaKeys=t,this.setMediaKeysQueue.push(r),r.then(()=>{this.log(`Media-keys set for "${e}"`),n.push(r),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(e=>n.indexOf(e)===-1)})}generateRequestWithPreferredKeySession(e,t,n,r){var i;let a=(i=this.config.drmSystems)==null||(i=i[e.keySystem])==null?void 0:i.generateRequest;if(a)try{let r=a.call(this.hls,t,n,e);if(!r)throw Error(`Invalid response from configured generateRequest filter`);t=r.initDataType,n=r.initData?r.initData:null,e.decryptdata.pssh=n?new Uint8Array(n):null}catch(e){if(this.warn(e.message),this.hls&&this.hls.config.debug)throw e}if(n===null)return this.log(`Skipping key-session request for "${r}" (no initData)`),Promise.resolve(e);let o=XJ(e.decryptdata),s=e.decryptdata.uri;this.log(`Generating key-session request for "${r}" keyId: ${o} URI: ${s} (init data type: ${t} length: ${n.byteLength})`);let c=new iG,l=e._onmessage=t=>{let n=e.mediaKeysSession;if(!n){c.emit(`error`,Error(`invalid state`));return}let{messageType:r,message:i}=t;this.log(`"${r}" message event for session "${n.sessionId}" message size: ${i.byteLength}`),r===`license-request`||r===`license-renewal`?this.renewLicense(e,i).catch(e=>{c.eventNames().length?c.emit(`error`,e):this.handleError(e)}):r===`license-release`?e.keySystem===KU.FAIRPLAY&&this.updateKeySession(e,VU(`acknowledged`)).then(()=>this.removeSession(e)).catch(e=>this.handleError(e)):this.warn(`unhandled media key message type "${r}"`)},u=(e,t)=>{t.keyStatus=e;let n;e.startsWith(`usable`)?c.emit(`resolved`):e===`internal-error`||e===`output-restricted`||e===`output-downscaled`?n=$J(e,t.decryptdata):e===`expired`?n=Error(`key expired (keyId: ${o})`):e===`released`?n=Error(`key released`):e===`status-pending`||this.warn(`unhandled key status change "${e}" (keyId: ${o})`),n&&(c.eventNames().length?c.emit(`error`,n):this.handleError(n))},d=e._onkeystatuseschange=t=>{if(!e.mediaKeysSession){c.emit(`error`,Error(`invalid state`));return}let n=this.getKeyStatuses(e);if(!Object.keys(n).some(e=>n[e]!==`status-pending`))return;if(n[o]===`expired`){this.log(`Expired key ${_H(n)} in key-session "${e.mediaKeysSession.sessionId}"`),this.renewKeySession(e);return}let r=n[o];if(r)u(r,e);else{var i;let t=1e3;e.keyStatusTimeouts||={},(i=e.keyStatusTimeouts)[o]||(i[o]=self.setTimeout(()=>{if(!e.mediaKeysSession||!this.mediaKeys)return;let n=this.getKeyStatus(e.decryptdata);if(n&&n!==`status-pending`)return this.log(`No status for keyId ${o} in key-session "${e.mediaKeysSession.sessionId}". Using session key-status ${n} from other session.`),u(n,e);this.log(`key status for ${o} in key-session "${e.mediaKeysSession.sessionId}" timed out after ${t}ms`),r=`internal-error`,u(r,e)},t)),this.log(`No status for keyId ${o} (${_H(n)}).`)}};JW(e.mediaKeysSession,`message`,l),JW(e.mediaKeysSession,`keystatuseschange`,d);let f=new Promise((e,t)=>{c.on(`error`,t),c.on(`resolved`,e)});return e.mediaKeysSession.generateRequest(t,n).then(()=>{this.log(`Request generated for key-session "${e.mediaKeysSession.sessionId}" keyId: ${o} URI: ${s}`)}).catch(t=>{throw new QJ({type:Y.KEY_SYSTEM_ERROR,details:X.KEY_SYSTEM_NO_SESSION,error:t,decryptdata:e.decryptdata,fatal:!1},`Error generating key-session request: ${t}`)}).then(()=>f).catch(t=>(c.removeAllListeners(),this.removeSession(e).then(()=>{throw t}))).then(()=>(c.removeAllListeners(),e))}getKeyStatuses(e){let t={};return e.mediaKeysSession.keyStatuses.forEach((n,r)=>{if(typeof r==`string`&&typeof n==`object`){let e=r;r=n,n=e}let i=`buffer`in r?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r);if(e.keySystem===KU.PLAYREADY&&i.length===16){let e=NB(i);t[e]=n,UU(i)}let a=NB(i);n===`internal-error`&&(this.bannedKeyIds[a]=n),this.log(`key status change "${n}" for keyStatuses keyId: ${a} key-session "${e.mediaKeysSession.sessionId}"`),t[a]=n}),t}fetchServerCertificate(e){let t=this.config,n=t.loader,r=new n(t),i=this.getServerCertificateUrl(e);return i?(this.log(`Fetching server certificate for "${e}"`),new Promise((n,a)=>{let o={responseType:`arraybuffer`,url:i},s=t.certLoadPolicy.default,c={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};r.load(o,c,{onSuccess:(e,t,r,i)=>{n(e.data)},onError:(t,n,r,s)=>{a(new QJ({type:Y.KEY_SYSTEM_ERROR,details:X.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:_B({url:o.url,data:void 0},t)},`"${e}" certificate request failed (${i}). Status: ${t.code} (${t.text})`))},onTimeout:(t,n,r)=>{a(new QJ({type:Y.KEY_SYSTEM_ERROR,details:X.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:r,response:{url:o.url,data:void 0}},`"${e}" certificate request timed out (${i})`))},onAbort:(e,t,n)=>{a(Error(`aborted`))}})})):Promise.resolve()}setMediaKeysServerCertificate(e,t,n){return new Promise((r,i)=>{e.setServerCertificate(n).then(i=>{this.log(`setServerCertificate ${i?`success`:`not supported by CDM`} (${n.byteLength}) on "${t}"`),r(e)}).catch(e=>{i(new QJ({type:Y.KEY_SYSTEM_ERROR,details:X.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:e,fatal:!0},e.message))})})}renewLicense(e,t){return this.requestLicense(e,new Uint8Array(t)).then(t=>this.updateKeySession(e,new Uint8Array(t)).catch(t=>{throw new QJ({type:Y.KEY_SYSTEM_ERROR,details:X.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:e.decryptdata,error:t,fatal:!1},t.message)}))}unpackPlayReadyKeyMessage(e,t){let n=String.fromCharCode.apply(null,new Uint16Array(t.buffer));if(!n.includes(`PlayReadyKeyMessage`))return e.setRequestHeader(`Content-Type`,`text/xml; charset=utf-8`),t;let r=new DOMParser().parseFromString(n,`application/xml`),i=r.querySelectorAll(`HttpHeader`);if(i.length>0){let t;for(let n=0,r=i.length;n<r;n++){t=i[n];let r=t.querySelector(`name`)?.textContent,a=t.querySelector(`value`)?.textContent;r&&a&&e.setRequestHeader(r,a)}}let a=r.querySelector(`Challenge`)?.textContent;if(!a)throw Error(`Cannot find <Challenge> in key message`);return VU(atob(a))}setupLicenseXHR(e,t,n,r){let i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!n.decryptdata)throw Error(`Key removed`);return i.call(this.hls,e,t,n,r)}).catch(a=>{if(!n.decryptdata)throw a;return e.open(`POST`,t,!0),i.call(this.hls,e,t,n,r)}).then(n=>(e.readyState||e.open(`POST`,t,!0),{xhr:e,licenseChallenge:n||r})):(e.open(`POST`,t,!0),Promise.resolve({xhr:e,licenseChallenge:r}))}requestLicense(e,t){let n=this.config.keyLoadPolicy.default;return new Promise((r,i)=>{let a=this.getLicenseServerUrlOrThrow(e.keySystem);this.log(`Sending license request to URL: ${a}`);let o=new XMLHttpRequest;o.responseType=`arraybuffer`,o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return i(Error(`invalid state`));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let t=o.response;this.log(`License received ${t instanceof ArrayBuffer?t.byteLength:t}`);let n=this.config.licenseResponseCallback;if(n)try{t=n.call(this.hls,o,a,e)}catch(e){this.error(e)}r(t)}else{let s=n.errorRetry,c=s?s.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>c||o.status>=400&&o.status<500)i(new QJ({type:Y.KEY_SYSTEM_ERROR,details:X.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:e.decryptdata,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{let n=c-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${n} attempts left`),this.requestLicense(e,t).then(r,i)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,t).then(({xhr:t,licenseChallenge:n})=>{e.keySystem==KU.PLAYREADY&&(n=this.unpackPlayReadyKeyMessage(t,n)),t.send(n)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(e,t){if(!this.config.emeEnabled)return;let n=t.media;this.media=n,JW(n,`encrypted`,this.onMediaEncrypted),JW(n,`waitingforkey`,this.onWaitingForKey);let r=this.mediaResolved;r?r():this.mediaKeys=n.mediaKeys}onMediaDetached(){let e=this.media;e&&(YW(e,`encrypted`,this.onMediaEncrypted),YW(e,`waitingforkey`,this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};let n=this.mediaResolved;if(n&&n(),!this.mediaKeys&&!this.mediaKeySessions.length)return;let r=this.media,i=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,rW.clearKeyUriToKeyIdMap();let a=i.length;e.CDMCleanupPromise=Promise.all(i.map(e=>this.removeSession(e)).concat((r==null||(t=r.setMediaKeys(null))==null?void 0:t.catch(e=>{this.log(`Could not clear media keys: ${e}`),this.hls&&this.hls.trigger(Z.ERROR,{type:Y.OTHER_ERROR,details:X.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:Error(`Could not clear media keys: ${e}`)})}))||Promise.resolve())).catch(e=>{this.log(`Could not close sessions and clear media keys: ${e}`),this.hls&&this.hls.trigger(Z.ERROR,{type:Y.OTHER_ERROR,details:X.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close sessions and clear media keys: ${e}`)})}).then(()=>{a&&this.log(`finished closing key sessions and clearing media keys`)})}onManifestLoading(){this._clear()}onManifestLoaded(e,{sessionKeys:t}){if(!(!t||!this.config.emeEnabled)&&!this.keyFormatPromise){let e=t.reduce((e,t)=>(e.indexOf(t.keyFormat)===-1&&e.push(t.keyFormat),e),[]);this.log(`Selecting key-system from session-keys ${e.join(`, `)}`),this.keyFormatPromise=this.getKeyFormatPromise(e)}}removeSession(e){let{mediaKeysSession:t,licenseXhr:n,decryptdata:r}=e;if(t){this.log(`Remove licenses and keys and close session "${t.sessionId}" keyId: ${NB(r?.keyId||[])}`),e._onmessage&&=(t.removeEventListener(`message`,e._onmessage),void 0),e._onkeystatuseschange&&=(t.removeEventListener(`keystatuseschange`,e._onkeystatuseschange),void 0),n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;let i=this.mediaKeySessions.indexOf(e);i>-1&&this.mediaKeySessions.splice(i,1);let{keyStatusTimeouts:a}=e;a&&Object.keys(a).forEach(e=>self.clearTimeout(a[e]));let{drmSystemOptions:o}=this.config;return(eW(o)?new Promise((e,n)=>{self.setTimeout(()=>n(Error(`MediaKeySession.remove() timeout`)),8e3),t.remove().then(e).catch(n)}):Promise.resolve()).catch(e=>{this.log(`Could not remove session: ${e}`),this.hls&&this.hls.trigger(Z.ERROR,{type:Y.OTHER_ERROR,details:X.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:Error(`Could not remove session: ${e}`)})}).then(()=>t.close()).catch(e=>{this.log(`Could not close session: ${e}`),this.hls&&this.hls.trigger(Z.ERROR,{type:Y.OTHER_ERROR,details:X.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:Error(`Could not close session: ${e}`)})})}return Promise.resolve()}};YJ.CDMCleanupPromise=void 0;function XJ(e){if(!e)throw Error(`Could not read keyId of undefined decryptdata`);if(e.keyId===null)throw Error(`keyId is null`);return NB(e.keyId)}function ZJ(e,t){if(e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId))return t.mediaKeysSession.keyStatuses.get(e.keyId);if(e.matches(t.decryptdata))return t.keyStatus}var QJ=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||=Error(t),this.data=e,e.err=e.error}};function $J(e,t){let n=e===`output-restricted`,r=n?X.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:X.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new QJ({type:Y.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?`HDCP level output restricted`:`key status changed to "${e}"`)}var eY=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on(Z.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Z.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Z.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Z.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){let n=this.hls.config;if(n.capLevelOnFPSDrop){let e=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=e,e&&typeof e.getVideoPlaybackQuality==`function`&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,n){let r=performance.now();if(t){if(this.lastTime){let e=r-this.lastTime,i=n-this.lastDroppedFrames,a=t-this.lastDecodedFrames,o=1e3*i/e,s=this.hls;if(s.trigger(Z.FPS_DROP,{currentDropped:i,currentDecoded:a,totalDroppedFrames:n}),o>0&&i>s.config.fpsDroppedMonitoringThreshold*a){let e=s.currentLevel;s.logger.warn(`drop FPS ratio greater than max allowed value for currentLevel: `+e),e>0&&(s.autoLevelCapping===-1||s.autoLevelCapping>=e)&&(--e,s.trigger(Z.FPS_DROP_LEVEL_CAPPING,{level:e,droppedLevel:s.currentLevel}),s.autoLevelCapping=e,this.streamController.nextLevelSwitch())}}this.lastTime=r,this.lastDroppedFrames=n,this.lastDecodedFrames=t}}checkFPSInterval(){let e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){let t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}};function tY(e,t){let n;try{n=new Event(`addtrack`)}catch{n=document.createEvent(`Event`),n.initEvent(`addtrack`,!1,!1)}n.track=e,t.dispatchEvent(n)}function nY(e,t){let n=e.mode;if(n===`disabled`&&(e.mode=`hidden`),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw Error(`addCue is failed for: ${t}`)}catch(n){OB.debug(`[texttrack-utils]: ${n}`);try{let n=new self.TextTrackCue(t.startTime,t.endTime,t.text);n.id=t.id,e.addCue(n)}catch(e){OB.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${e}`)}}n===`disabled`&&(e.mode=n)}function rY(e,t){let n=e.mode;if(n===`disabled`&&(e.mode=`hidden`),e.cues)for(let n=e.cues.length;n--;)t&&e.cues[n].removeEventListener(`enter`,t),e.removeCue(e.cues[n]);n===`disabled`&&(e.mode=n)}function iY(e,t,n,r){let i=e.mode;if(i===`disabled`&&(e.mode=`hidden`),e.cues&&e.cues.length>0){let i=oY(e.cues,t,n);for(let t=0;t<i.length;t++)(!r||r(i[t]))&&e.removeCue(i[t])}i===`disabled`&&(e.mode=i)}function aY(e,t){if(t<=e[0].startTime)return 0;let n=e.length-1;if(t>e[n].endTime)return-1;let r=0,i=n,a;for(;r<=i;)if(a=Math.floor((i+r)/2),t<e[a].startTime)i=a-1;else if(t>e[a].startTime&&r<n)r=a+1;else return a;return e[r].startTime-t<t-e[i].startTime?r:i}function oY(e,t,n){let r=[],i=aY(e,t);if(i>-1)for(let a=i,o=e.length;a<o;a++){let i=e[a];if(i.startTime>=t&&i.endTime<=n)r.push(i);else if(i.startTime>n)return r}return r}function sY(e){let t=[];for(let n=0;n<e.length;n++){let r=e[n];(r.kind===`subtitles`||r.kind===`captions`)&&r.label&&t.push(e[n])}return t}var cY=class extends uq{constructor(e){super(e,`subtitle-track-controller`),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let e=null,t=sY(this.media.textTracks);for(let n=0;n<t.length;n++)if(t[n].mode===`hidden`)e=t[n];else if(t[n].mode===`showing`){e=t[n];break}let n=this.findTrackForTextTrack(e);this.subtitleTrack!==n&&this.setSubtitleTrack(n)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){let{hls:e}=this;e.on(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Z.LEVEL_LOADING,this.onLevelLoading,this),e.on(Z.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(Z.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Z.ERROR,this.onError,this)}unregisterListeners(){let{hls:e}=this;e.off(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Z.LEVEL_LOADING,this.onLevelLoading,this),e.off(Z.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(Z.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Z.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&`onchange`in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener(`change`,this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){let n=this.media;if(!n)return;let r=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||n.textTracks.removeEventListener(`change`,this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,!r&&sY(n.textTracks).forEach(e=>{rY(e)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){let{id:n,groupId:r,details:i}=t,a=this.tracksInGroup[n];if(!a||a.groupId!==r){this.warn(`Subtitle track with id:${n} and group:${r} not found in active group ${a?.groupId}`);return}let o=a.details;a.details=t.details,this.log(`Subtitle track ${n} "${a.name}" lang:${a.lang} group:${r} loaded [${i.startSN}-${i.endSN}]`),n===this.trackId&&this.playlistLoaded(n,t,o)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){let t=this.hls.levels[e];if(!t)return;let n=t.subtitleGroups||null,r=this.groupIds,i=this.currentTrack;if(!n||r?.length!==n?.length||n!=null&&n.some(e=>r?.indexOf(e)===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;let e=this.tracks.filter(e=>!n||n.indexOf(e.groupId)!==-1);if(e.length)this.selectDefaultTrack&&!e.some(e=>e.default)&&(this.selectDefaultTrack=!1),e.forEach((e,t)=>{e.id=t});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=e;let t=this.hls.config.subtitlePreference;if(!i&&t){this.selectDefaultTrack=!1;let n=CH(t,e);if(n>-1)i=e[n];else{let e=CH(t,this.tracks);i=this.tracks[e]}}let r=this.findTrackId(i);r===-1&&i&&(r=this.findTrackId(null));let a={subtitleTracks:e};this.log(`Updating subtitle tracks, ${e.length} track(s) found in "${n?.join(`,`)}" group-id`),this.hls.trigger(Z.SUBTITLE_TRACKS_UPDATED,a),r!==-1&&this.trackId===-1&&this.setSubtitleTrack(r)}}findTrackId(e){let t=this.tracksInGroup,n=this.selectDefaultTrack;for(let r=0;r<t.length;r++){let i=t[r];if(!(n&&!i.default||!n&&!e)&&(!e||wH(i,e)))return r}if(e){for(let n=0;n<t.length;n++){let r=t[n];if(fq(e.attrs,r.attrs,[`LANGUAGE`,`ASSOC-LANGUAGE`,`CHARACTERISTICS`]))return n}for(let n=0;n<t.length;n++){let r=t[n];if(fq(e.attrs,r.attrs,[`LANGUAGE`]))return n}}return-1}findTrackForTextTrack(e){if(e){let t=this.tracksInGroup;for(let n=0;n<t.length;n++){let r=t[n];if(pq(r,e))return n}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===dB.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;let t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){let n=this.currentTrack;if(n&&wH(e,n))return n;let r=CH(e,this.tracksInGroup);if(r>-1){let e=this.tracksInGroup[r];return this.setSubtitleTrack(r),e}else if(n)return null;else{let n=CH(e,t);if(n>-1)return t[n]}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=e.id,r=e.groupId,i=this.getUrlWithDirectives(e.url,t),a=e.details,o=a?.age;this.log(`Loading subtitle ${n} "${e.name}" lang:${e.lang} group:${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${i}`),this.hls.trigger(Z.SUBTITLE_TRACK_LOADING,{url:i,id:n,groupId:r,deliveryDirectives:t||null,track:e})}toggleTrackModes(){let{media:e}=this;if(!e)return;let t=sY(e.textTracks),n=this.currentTrack,r;if(n&&(r=t.filter(e=>pq(n,e))[0],r||this.warn(`Unable to find subtitle TextTrack with name "${n.name}" and language "${n.lang}"`)),[].slice.call(t).forEach(e=>{e.mode!==`disabled`&&e!==r&&(e.mode=`disabled`)}),r){let e=this.subtitleDisplay?`showing`:`hidden`;r.mode!==e&&(r.mode=e)}}setSubtitleTrack(e){let t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!J(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;let n=this.currentTrack,r=t[e]||null;if(this.trackId=e,this.currentTrack=r,this.toggleTrackModes(),!r){this.hls.trigger(Z.SUBTITLE_TRACK_SWITCH,{id:e});return}let i=!!r.details&&!r.details.live;if(e===this.trackId&&r===n&&i)return;this.log(`Switching to subtitle-track ${e}`+(r?` "${r.name}" lang:${r.lang} group:${r.groupId}`:``));let{id:a,groupId:o=``,name:s,type:c,url:l}=r;this.hls.trigger(Z.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:s,type:c,url:l});let u=this.switchParams(r.url,n?.details,r.details);this.loadPlaylist(u)}};function lY(){try{return crypto.randomUUID()}catch{try{let e=URL.createObjectURL(new Blob),t=e.toString();return URL.revokeObjectURL(e),t.slice(t.lastIndexOf(`/`)+1)}catch{let e=new Date().getTime();return`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,t=>{let n=(e+Math.random()*16)%16|0;return e=Math.floor(e/16),(t==`x`?n:n&3|8).toString(16)})}}}function uY(e){let t=5381,n=e.length;for(;n;)t=t*33^e.charCodeAt(--n);return(t>>>0).toString()}var dY=.025,fY=function(e){return e[e.Point=0]=`Point`,e[e.Range=1]=`Range`,e}({});function pY(e,t,n){return`${e.identifier}-${n+1}-${uY(t)}`}var mY=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat(`X-RESUME-OFFSET`,this.resumeOffset),this.playoutLimit=e.attr.optionalFloat(`X-PLAYOUT-LIMIT`,this.playoutLimit),this.restrictions=e.attr.enumeratedStringList(`X-RESTRICT`,this.restrictions),this.snapOptions=e.attr.enumeratedStringList(`X-SNAP`,this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){if(e>0&&e>=this.assetList.length)return!0;let t=this.playoutLimit;return e<=0||isNaN(t)?!1:t===0?!0:(this.assetList[e]?.startOffset||0)>t}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){let e=this.dateRange.startTime;if(this.snapOptions.out){let t=this.dateRange.tagAnchor;if(t)return hY(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;let e=this.dateRange.tagAnchor;if(e){let t=this.dateRange.startTime;return t-hY(t,e)<.1}return!1}get resumptionOffset(){let e=this.resumeOffset,t=J(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){let e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){let t=this.resumeAnchor;if(t)return hY(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<dY))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart===null?this.startTime:this._timelineStart}set timelineStart(e){this._timelineStart=e}get duration(){let e=this.playoutLimit,t;return t=this._duration===null?this.dateRange.duration?this.dateRange.duration:this.dateRange.plannedDuration||0:this._duration,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr[`X-TIMELINE-OCCUPIES`]===`RANGE`?fY.Range:fY.Point}get supplementsPrimary(){return this.dateRange.attr[`X-TIMELINE-STYLE`]===`PRIMARY`}get contentMayVary(){return this.dateRange.attr[`X-CONTENT-MAY-VARY`]!==`NO`}get assetUrl(){return this.dateRange.attr[`X-ASSET-URI`]}get assetListUrl(){return this.dateRange.attr[`X-ASSET-LIST`]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return vY(this)}};function hY(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<dY)?t.start:t.start+t.duration}function gY(e,t,n){let r=new self.URL(e,n);return r.protocol!==`data:`&&r.searchParams.set(`_HLS_primary_id`,t),r}function _Y(e,t){for(;(n=e.assetList[++t])!=null&&n.error;)var n;return t}function vY(e){return`["${e.identifier}" ${e.cue.pre?`<pre>`:e.cue.post?`<post>`:``}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function yY(e){let t=e.timelineStart,n=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}var bY=class{constructor(e,t,n,r){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(Z.PLAYOUT_LIMIT_REACHED,{})};let i=this.hls=new e(t);this.interstitial=n,this.assetItem=r;let a=()=>{this.hasDetails=!0};i.once(Z.LEVEL_LOADED,a),i.once(Z.AUDIO_TRACK_LOADED,a),i.once(Z.SUBTITLE_TRACK_LOADED,a),i.on(Z.MEDIA_ATTACHING,(e,{media:t})=>{this.removeMediaListeners(),this.mediaAttached=t,this.interstitial.playoutLimit&&(t.addEventListener(`timeupdate`,this.checkPlayout),this.appendInPlace&&i.on(Z.BUFFER_APPENDED,()=>{let e=this.bufferedEnd;this.reachedPlayout(e)&&(this._bufferedEosTime=e,i.trigger(Z.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){let e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=gY(t,e.config.primarySessionId||``).href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;let n=Math.min(this._bufferedEosTime||1/0,this.duration),r=this.timelineOffset,i=xU.bufferInfo(e,r,0);return this.getAssetTime(i.end)>=n-.02}reachedPlayout(e){let t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){return this.hls?.media||null}get bufferedEnd(){let e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;let t=xU.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){let e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){let e=this.assetItem.duration;if(!e)return 0;let t=this.interstitial.playoutLimit;if(t){let n=t-this.startOffset;if(n>0&&n<e)return n}return e}get remaining(){let e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){return this.hls?.config.timelineOffset||0}set timelineOffset(e){let t=this.timelineOffset;if(e!==t){let n=e-t;if(Math.abs(n)>1/9e4&&this.hls){if(this.hasDetails)throw Error(`Cannot set timelineOffset after playlists are loaded`);this.hls.config.timelineOffset=e}}}getAssetTime(e){let t=this.timelineOffset,n=this.duration;return Math.min(Math.max(0,e-t),n)}removeMediaListeners(){let e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener(`timeupdate`,this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){return this.bufferSnapShot(),this.hls?.transferMedia()||null}resetDetails(){let e=this.hls;if(e&&this.hasDetails){e.stopLoad();let t=e=>delete e.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,n){var r;(r=this.hls)==null||r.on(e,t)}once(e,t,n){var r;(r=this.hls)==null||r.once(e,t)}off(e,t,n){var r;(r=this.hls)==null||r.off(e,t)}toString(){return`HlsAssetPlayer: ${yY(this.assetItem)} ${this.hls?.sessionId} ${this.appendInPlace?`append-in-place`:``}`}},xY=.033,SY=class extends bB{constructor(e,t){super(`interstitials-sched`,t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((n,r)=>e<=r.startOffset&&t>r.startOffset?(delete r.error,n+1):n,0):0}get duration(){let e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let n=-1;e.nextEvent?n=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(n=this.findEventIndex(e.previousEvent.identifier)+1);let r=this.items;if(r)for(r[n]||(t===void 0&&(t=e.start),n=this.findItemIndexAtTime(t));n>=0&&(i=r[n])!=null&&i.event;){var i;n--}return n}findItemIndexAtTime(e,t){let n=this.items;if(n)for(let r=0;r<n.length;r++){let i=n[r];if(t&&t!==`primary`&&(i=i[t]),e===i.start||e>i.start&&e<i.end)return r}return-1}findJumpRestrictedIndex(e,t){let n=this.items;if(n)for(let r=e;r<=t&&n[r];r++){let e=n[r].event;if(e!=null&&e.restrictions.jump&&!e.appendInPlace)return r}return-1}findEventIndex(e){let t=this.items;if(t){for(let n=t.length;n--;)if(t[n].event?.identifier===e)return n}return-1}findAssetIndex(e,t){let n=e.assetList,r=n.length;if(r>1)for(let e=0;e<r;e++){let i=n[e];if(!i.error){let n=i.timelineStart;if(t===n||t>n&&(t<n+(i.duration||0)||e===r-1))return e}}return 0}get assetIdAtEnd(){var e;let t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){let e=t.assetList,n=e[e.length-1];if(n)return n.identifier}return null}parseInterstitialDateRanges(e,t){let n=e.main.details,{dateRanges:r}=n,i=this.events,a=this.parseDateRanges(r,{url:n.url},t),o=Object.keys(r),s=i?i.filter(e=>!o.includes(e.identifier)):[];a.length&&a.sort((e,t)=>{let n=e.cue.pre,r=e.cue.post,i=t.cue.pre,a=t.cue.post;if(n&&!i)return-1;if(i&&!n||r&&!a)return 1;if(a&&!r)return-1;if(!n&&!i&&!r&&!a){let n=e.startTime,r=t.startTime;if(n!==r)return n-r}return e.dateRange.tagOrder-t.dateRange.tagOrder}),this.events=a,s.forEach(e=>{this.removeEvent(e)}),this.updateSchedule(e,s)}updateSchedule(e,t=[],n=!1){let r=this.events||[];if(r.length||t.length||this.length<2){let i=this.items,a=this.parseSchedule(r,e);(n||t.length||i?.length!==a.length||a.some((e,t)=>Math.abs(e.playout.start-i[t].playout.start)>.005||Math.abs(e.playout.end-i[t].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,i))}}parseDateRanges(e,t,n){let r=[],i=Object.keys(e);for(let a=0;a<i.length;a++){let o=i[a],s=e[o];if(s.isInterstitial){let e=this.eventMap[o];e?e.setDateRange(s):(e=new mY(s,t),this.eventMap[o]=e,n===!1&&(e.appendInPlace=n)),r.push(e)}}return r}parseSchedule(e,t){let n=[],r=t.main.details,i=r.live?1/0:r.edge,a=0;if(e=e.filter(e=>!e.error&&!(e.cue.once&&e.hasPlayed)),e.length){this.resolveOffsets(e,t);let r=0,o=0;if(e.forEach((t,s)=>{let c=t.cue.pre,l=t.cue.post,u=e[s-1]||null,d=t.appendInPlace,f=l?i:t.startOffset,p=t.duration,m=t.timelineOccupancy===fY.Range?p:0,h=t.resumptionOffset,g=u?.startTime===f,_=f+t.cumulativeDuration,v=d?_+p:f+h;if(c||!l&&f<=0){let e=o;o+=m,t.timelineStart=_;let r=a;a+=p,n.push({event:t,start:_,end:v,playout:{start:r,end:a},integrated:{start:e,end:o}})}else if(f<=i){if(!g){let i=f-r;if(i>xY){let c=r,l=o;o+=i;let u=a;a+=i;let d={previousEvent:e[s-1]||null,nextEvent:t,start:c,end:c+i,playout:{start:u,end:a},integrated:{start:l,end:o}};n.push(d)}else i>0&&u&&(u.cumulativeDuration+=i,n[n.length-1].end=f)}l&&(v=_),t.timelineStart=_;let i=o;o+=m;let c=a;a+=p,n.push({event:t,start:_,end:v,playout:{start:c,end:a},integrated:{start:i,end:o}})}else return;let y=t.resumeTime;r=l||y>i?i:y}),r<i){let e=r,t=o,s=i-r;o+=s;let c=a;a+=s,n.push({previousEvent:n[n.length-1]?.event||null,nextEvent:null,start:r,end:e+s,playout:{start:c,end:a},integrated:{start:t,end:o}})}this.setDurations(i,a,o)}else n.push({previousEvent:null,nextEvent:null,start:0,end:i,playout:{start:0,end:i},integrated:{start:0,end:i}}),this.setDurations(i,i,i);return n}setDurations(e,t,n){this.durations={primary:e,playout:t,integrated:n}}resolveOffsets(e,t){let n=t.main.details,r=n.live?1/0:n.edge,i=0,a=-1;e.forEach((o,s)=>{let c=o.cue.pre,l=o.cue.post,u=c?0:l?r:o.startTime;this.updateAssetDurations(o),a===u?o.cumulativeDuration=i:(i=0,a=u),!l&&o.snapOptions.in&&(o.resumeAnchor=PH(null,n.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,t)||(o.appendInPlace=!1)),!o.appendInPlace&&s+1<e.length&&e[s+1].startTime-e[s].resumeTime<xY&&(e[s+1].appendInPlace=!1,e[s+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${o}`));let d=J(o.resumeOffset)?o.resumeOffset:o.duration;i+=d})}primaryCanResumeInPlaceAt(e,t){let n=e.resumeTime,r=e.startTime+e.resumptionOffset;return Math.abs(n-r)>dY?(this.log(`"${e.identifier}" resumption ${n} not aligned with estimated timeline end ${r}`),!1):!Object.keys(t).some(r=>{let i=t[r].details,a=i.edge;if(n>=a)return this.log(`"${e.identifier}" resumption ${n} past ${r} playlist end ${a}`),!1;let o=PH(null,i.fragments,n);if(!o)return this.log(`"${e.identifier}" resumption ${n} does not align with any fragments in ${r} playlist (${i.fragStart}-${i.fragmentEnd})`),!0;let s=r===`audio`?.175:0;return Math.abs(o.start-n)<dY+s||Math.abs(o.end-n)<dY+s?!1:(this.log(`"${e.identifier}" resumption ${n} not aligned with ${r} fragment bounds (${o.start}-${o.end} sn: ${o.sn} cc: ${o.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;let t=e.timelineStart,n=0,r=!1,i=!1;for(let a=0;a<e.assetList.length;a++){let o=e.assetList[a],s=t+n;o.startOffset=n,o.timelineStart=s,r||=o.duration===null,i||=!!o.error;let c=o.error?0:o.duration||0;n+=c}r&&!i?e.duration=Math.max(n,e.duration):e.duration=n}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function CY(e){return`[${e.event?`"`+e.event.identifier+`"`:`primary`}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}var wY=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){let n=e.assetListUrl,r;try{r=gY(n,this.hls.sessionId,e.baseUrl)}catch(t){let r=this.assignAssetListError(e,X.ASSET_LIST_LOAD_ERROR,t,n);this.hls.trigger(Z.ERROR,r);return}t&&r.protocol!==`data:`&&r.searchParams.set(`_HLS_start_offset`,``+t);let i=this.hls.config,a=i.loader,o=new a(i),s={responseType:`json`,url:r.href},c=i.interstitialAssetListLoadPolicy.default,l={loadPolicy:c,timeout:c.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return o.load(s,l,{onSuccess:(t,n,r,i)=>{let a=t.data,o=a?.ASSETS;if(!Array.isArray(o)){let t=this.assignAssetListError(e,X.ASSET_LIST_PARSING_ERROR,Error(`Invalid interstitial asset list`),r.url,n,i);this.hls.trigger(Z.ERROR,t);return}e.assetListResponse=a,this.hls.trigger(Z.ASSET_LIST_LOADED,{event:e,assetListResponse:a,networkDetails:i})},onError:(t,n,r,i)=>{let a=this.assignAssetListError(e,X.ASSET_LIST_LOAD_ERROR,Error(`Error loading X-ASSET-LIST: HTTP status ${t.code} ${t.text} (${n.url})`),n.url,i,r);this.hls.trigger(Z.ERROR,a)},onTimeout:(t,n,r)=>{let i=this.assignAssetListError(e,X.ASSET_LIST_LOAD_TIMEOUT,Error(`Timeout loading X-ASSET-LIST (${n.url})`),n.url,t,r);this.hls.trigger(Z.ERROR,i)}}),this.hls.trigger(Z.ASSET_LIST_LOADING,{event:e}),o}assignAssetListError(e,t,n,r,i,a){return e.error=n,{type:Y.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:r,error:n,networkDetails:a,stats:i}}};function TY(e){var t;e==null||(t=e.play())==null||t.catch(()=>{})}function EY(e,t){return`[${e}] Advancing timeline position to ${t}`}var DY=class extends bB{constructor(e,t){super(`interstitials`,e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{let e=this.currentTime;if(e===void 0||this.playbackDisabled||!this.schedule)return;let t=e-this.timelinePos;if(Math.abs(t)<1/7056e5)return;let n=t<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=e,this.bufferedPos=e;let r=this.playingItem;if(!r){this.checkBuffer();return}if(n&&this.schedule.resetErrorsInRange(e,e-t)&&this.updateSchedule(!0),this.checkBuffer(),n&&e<r.start||e>=r.end){var i;let t=this.findItemIndex(r),a=this.schedule.findItemIndexAtTime(e);if(a===-1&&(a=t+(n?-1:1),this.log(`seeked ${n?`back `:``}to position not covered by schedule ${e} (resolving from ${t} to ${a})`)),!this.isInterstitial(r)&&(i=this.media)!=null&&i.paused&&(this.shouldPlay=!1),!n&&a>t){let e=this.schedule.findJumpRestrictedIndex(t+1,a);if(e>t){this.setSchedulePosition(e);return}}this.setSchedulePosition(a);return}let a=this.playingAsset;if(!a){if(this.playingLastItem&&this.isInterstitial(r)){let t=r.event.assetList[0];t&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(e,t))}return}let o=a.timelineStart,s=a.duration||0;if(n&&e<o||e>=o+s){var c;(c=r.event)!=null&&c.appendInPlace&&(this.clearAssetPlayers(r.event,r),this.flushFrontBuffer(e)),this.setScheduleToAssetAtTime(e,a)}},this.onTimeupdate=()=>{let e=this.currentTime;if(e===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),e>this.timelinePos)this.timelinePos=e,e>this.bufferedPos&&this.checkBuffer();else return;let t=this.playingItem;if(!t||this.playingLastItem)return;if(e>=t.end){this.timelinePos=t.end;let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}let n=this.playingAsset;n&&e>=n.timelineStart+(n.duration||0)&&this.setScheduleToAssetAtTime(e,n)},this.onScheduleUpdate=(e,t)=>{let n=this.schedule;if(!n)return;let r=this.playingItem,i=n.events||[],a=n.items||[],o=n.durations,s=e.map(e=>e.identifier),c=!!(i.length||s.length);(c||t)&&this.log(`INTERSTITIALS_UPDATED (${i.length}): ${i}
62
- Schedule: ${a.map(e=>CY(e))} pos: ${this.timelinePos}`),s.length&&this.log(`Removed events ${s}`);let l=null,u=null;r&&(l=this.updateItem(r,this.timelinePos),this.itemsMatch(r,l)?this.playingItem=l:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);let d=this.bufferingItem;if(d&&(u=this.updateItem(d,this.bufferedPos),this.itemsMatch(d,u)?this.bufferingItem=u:d.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(d.event,null))),e.forEach(e=>{e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,null)})}),this.playerQueue.forEach(e=>{if(e.interstitial.appendInPlace){let t=e.assetItem.timelineStart,n=e.timelineOffset-t;if(n)try{e.timelineOffset=t}catch(r){Math.abs(n)>dY&&this.warn(`${r} ("${e.assetId}" ${e.timelineOffset}->${t})`)}}}),c||t){if(this.hls.trigger(Z.INTERSTITIALS_UPDATED,{events:i.slice(0),schedule:a.slice(0),durations:o,removedIds:s}),this.isInterstitial(r)&&s.includes(r.event.identifier)){this.warn(`Interstitial "${r.event.identifier}" removed while playing`),this.primaryFallback(r.event);return}r&&this.trimInPlace(l,r),d&&u!==l&&this.trimInPlace(u,d),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new wY(e),this.schedule=new SY(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){let e=this.hls;e&&(e.on(Z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Z.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Z.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on(Z.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Z.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on(Z.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on(Z.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on(Z.BUFFER_APPENDED,this.onBufferAppended,this),e.on(Z.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Z.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on(Z.MEDIA_ENDED,this.onMediaEnded,this),e.on(Z.ERROR,this.onError,this),e.on(Z.DESTROYING,this.onDestroying,this))}unregisterListeners(){let e=this.hls;e&&(e.off(Z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Z.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Z.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off(Z.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Z.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off(Z.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off(Z.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off(Z.BUFFER_CODECS,this.onBufferCodecs,this),e.off(Z.BUFFER_APPENDED,this.onBufferAppended,this),e.off(Z.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Z.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off(Z.MEDIA_ENDED,this.onMediaEnded,this),e.off(Z.ERROR,this.onError,this),e.off(Z.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){let e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){YW(e,`play`,this.onPlay),YW(e,`pause`,this.onPause),YW(e,`seeking`,this.onSeeking),YW(e,`timeupdate`,this.onTimeupdate)}onMediaAttaching(e,t){let n=this.media=t.media;JW(n,`seeking`,this.onSeeking),JW(n,`timeupdate`,this.onTimeupdate),JW(n,`play`,this.onPlay),JW(n,`pause`,this.onPause)}onMediaAttached(e,t){let n=this.effectivePlayingItem,r=this.detachedData;if(this.detachedData=null,n===null)this.checkStart();else if(!r){this.clearScheduleState();let e=this.findItemIndex(n);this.setSchedulePosition(e)}}clearScheduleState(){this.log(`clear schedule state`),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){let n=!!t.transferMedia,r=this.media;if(this.media=null,!n&&(r&&this.removeMediaListeners(r),this.detachedData)){let e=this.getBufferingPlayer();e&&(this.log(`Removing schedule state for detachedData and ${e}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,e.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;let e=this,t=()=>e.bufferingItem||e.waitingItem,n=t=>t&&e.getAssetPlayer(t.identifier),r=(t,r,i,o,s)=>{if(t){let c=t[r].start,l=t.event;if(l){if(r===`playout`||l.timelineOccupancy!==fY.Point){let e=n(i);e?.interstitial===l&&(c+=e.assetItem.startOffset+e[s])}}else{let n=o===`bufferedPos`?a():e[o];c+=n-t.start}return c}return 0},i=(t,n)=>{var r;if(t!==0&&n!==`primary`&&(r=e.schedule)!=null&&r.length){let r=e.schedule.findItemIndexAtTime(t),i=e.schedule.items?.[r];if(i)return t+(i[n].start-i.start)}return t},a=()=>{let t=e.bufferedPos;return t===Number.MAX_VALUE?o(`primary`):Math.max(t,0)},o=t=>{var n;return(n=e.primaryDetails)!=null&&n.live?e.primaryDetails.edge:e.schedule?.durations[t]||0},s=(t,i)=>{var a;let o=e.effectivePlayingItem;if(o!=null&&(a=o.event)!=null&&a.restrictions.skip||!e.schedule)return;e.log(`seek to ${t} "${i}"`);let s=e.effectivePlayingItem,c=e.schedule.findItemIndexAtTime(t,i),l=e.schedule.items?.[c],u=e.getBufferingPlayer(),d=u?.interstitial?.appendInPlace,f=s&&e.itemsMatch(s,l);if(s&&(d||f)){let a=n(e.playingAsset),o=a?.media||e.primaryMedia;if(o){let n=i===`primary`?o.currentTime:r(s,i,e.playingAsset,`timelinePos`,`currentTime`),c=t-n,l=(d?n:o.currentTime)+c;if(l>=0&&(!a||d||l<=a.duration)){o.currentTime=l;return}}}if(l){let n=t;if(i!==`primary`){let e=t-l[i].start;n=l.start+e}let r=!e.isInterstitial(l);if((!e.isInterstitial(s)||s.event.appendInPlace)&&(r||l.event.appendInPlace)){let t=e.media||(d?u?.media:null);t&&(t.currentTime=n)}else if(s){let a=e.findItemIndex(s);if(c>a){let t=e.schedule.findJumpRestrictedIndex(a+1,c);if(t>a){e.setSchedulePosition(t);return}}let o=0;if(r)e.timelinePos=n,e.checkBuffer();else{let e=l.event.assetList,n=t-(l[i]||l).start;for(let t=e.length;t--;){let r=e[t];if(r.duration&&n>=r.startOffset&&n<r.startOffset+r.duration){o=t;break}}}e.setSchedulePosition(c,o)}}},c=()=>{let n=e.effectivePlayingItem;if(e.isInterstitial(n))return n;let r=t();return e.isInterstitial(r)?r:null},l={get bufferedEnd(){let n=t(),i=e.bufferingItem;return i&&i===n&&(r(i,`playout`,e.bufferingAsset,`bufferedPos`,`bufferedEnd`)-i.playout.start||e.bufferingAsset?.startOffset)||0},get currentTime(){let t=c(),n=e.effectivePlayingItem;return n&&n===t?r(n,`playout`,e.effectivePlayingAsset,`timelinePos`,`currentTime`)-n.playout.start:0},set currentTime(t){let n=c(),r=e.effectivePlayingItem;r&&r===n&&s(t+r.playout.start,`playout`)},get duration(){let e=c();return e?e.playout.end-e.playout.start:0},get assetPlayers(){let t=c()?.event.assetList;return t?t.map(t=>e.getAssetPlayer(t.identifier)):[]},get playingIndex(){let t=c()?.event;return t&&e.effectivePlayingAsset?t.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return c()}};return this.manager={get events(){var t;return((t=e.schedule)==null||(t=t.events)==null?void 0:t.slice(0))||[]},get schedule(){var t;return((t=e.schedule)==null||(t=t.items)==null?void 0:t.slice(0))||[]},get interstitialPlayer(){return c()?l:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){let n=t();return e.findItemIndex(n)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){let t=e.effectivePlayingItem;return e.findItemIndex(t)},primary:{get bufferedEnd(){return a()},get currentTime(){let t=e.timelinePos;return t>0?t:0},set currentTime(e){s(e,`primary`)},get duration(){return o(`primary`)},get seekableStart(){return e.primaryDetails?.fragmentStart||0}},integrated:{get bufferedEnd(){return r(t(),`integrated`,e.bufferingAsset,`bufferedPos`,`bufferedEnd`)},get currentTime(){return r(e.effectivePlayingItem,`integrated`,e.effectivePlayingAsset,`timelinePos`,`currentTime`)},set currentTime(e){s(e,`integrated`)},get duration(){return o(`integrated`)},get seekableStart(){return i(e.primaryDetails?.fragmentStart||0,`integrated`)}},skip:()=>{let t=e.effectivePlayingItem,n=t?.event;if(n&&!n.restrictions.skip){let r=e.findItemIndex(t);n.appendInPlace?s(t.playout.start+t.event.duration+.001,`playout`):e.advanceAfterAssetEnded(n,r,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){let e=this.playingItem,t=this.schedule?.items;return!this.playbackStarted||!e||!t?!1:this.findItemIndex(e)===t.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e;if(this.mediaSelection===null)return;let t=this.waitingItem||this.playingItem;if(this.isInterstitial(t)&&!t.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);let r=n?.currentTime;if(!(r===void 0||!J(r)))return r}get primaryMedia(){return this.media||this.detachedData?.media||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){let n=this.getAssetPlayer(e);n&&this.transferMediaFromPlayer(n,t)}transferMediaFromPlayer(e,t){let n=e.interstitial.appendInPlace,r=e.media;if(n&&r===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&r){this.detachedData={media:r};return}let n=e.transferMedia();this.log(`transfer MediaSource from ${e} ${_H(n)}`),this.detachedData=n}else t&&r&&(this.shouldPlay||=!r.paused)}transferMediaTo(e,t){if(e.media===t)return;let n=null,r=this.hls,i=e!==r,a=i&&e.interstitial.appendInPlace,o=this.detachedData?.mediaSource,s;if(r.media)a&&(n=r.transferMedia(),this.detachedData=n),s=`Primary`;else if(o){let e=this.getBufferingPlayer();e?(n=e.transferMedia(),s=`${e}`):s=`detached MediaSource`}else s=`detached media`;if(!n){if(o)n=this.detachedData,this.log(`using detachedData: MediaSource ${_H(n)}`);else if(!this.detachedData||r.media===t){let e=this.playerQueue;e.length>1&&e.forEach(e=>{if(i&&e.interstitial.appendInPlace!==a){let t=e.interstitial;this.clearInterstitial(e.interstitial,null),t.appendInPlace=!1,t.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${t}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}let c=n&&`mediaSource`in n&&n.mediaSource?.readyState!==`closed`,l=c&&n?n:t;this.log(`${c?`transfering MediaSource`:`attaching media`} to ${i?e:`Primary`} from ${s} (media.currentTime: ${t.currentTime})`);let u=this.schedule;if(l===n&&u){let t=i&&e.assetId===u.assetIdAtEnd;l.overrides={duration:u.duration,endOfStream:!i||t,cueRemoval:!i}}e.attachMedia(l)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){let e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);let n=this.timelinePos,r=this.effectivePlayingItem;if(n===-1){let n=this.hls.startPosition;if(this.timelinePos=n,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(EY(`checkStart (preroll)`,n));let r=e.findEventIndex(t[0].identifier);this.setSchedulePosition(r)}else if(n>=0||!this.primaryLive){this.log(EY(`checkStart`,n));let t=this.timelinePos=n>0?n:0,r=e.findItemIndexAtTime(t);this.setSchedulePosition(r)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log(`[checkStart] waiting for live start`)}else if(r&&!this.playingItem){this.log(EY(`checkStart (playing item)`,r.start));let t=e.findItemIndex(r);this.setSchedulePosition(t)}}advanceAssetBuffering(e,t){let n=e.event,r=_Y(n,n.findAssetIndex(t));if(!n.isAssetPastPlayoutLimit(r))this.bufferedToEvent(e,r);else if(this.schedule){let t=this.schedule.items?.[this.findItemIndex(e)+1];t&&this.bufferedToItem(t)}}advanceAfterAssetEnded(e,t,n){let r=_Y(e,n);if(!e.isAssetPastPlayoutLimit(r)){if(e.appendInPlace){let t=e.assetList[r];t&&this.advanceInPlace(t.timelineStart)}this.setSchedulePosition(t,r)}else if(this.schedule){let n=this.schedule.items;if(n){let r=t+1;if(r>=n.length){this.setSchedulePosition(-1);return}let i=e.resumeTime;this.timelinePos<i&&(this.log(EY(`advanceAfterAssetEnded`,i)),this.timelinePos=i,e.appendInPlace&&this.advanceInPlace(i),this.checkBuffer(this.bufferedPos<i)),this.setSchedulePosition(r)}}}setScheduleToAssetAtTime(e,t){let n=this.schedule;if(!n)return;let r=t.parentIdentifier,i=n.getEvent(r);if(i){let t=n.findEventIndex(r),a=n.findAssetIndex(i,e);this.advanceAfterAssetEnded(i,t,a-1)}}setSchedulePosition(e,t){let n=this.schedule?.items;if(!n||this.playbackDisabled)return;let r=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${r&&CY(r)}) pos: ${this.timelinePos}`);let i=this.waitingItem||this.playingItem,a=this.playingLastItem;if(this.isInterstitial(i)){let s=i.event,c=this.playingAsset,l=c?.identifier,u=l?this.getAssetPlayer(l):null;if(u&&l&&(!this.eventItemsMatch(i,r)||t!==void 0&&l!==s.assetList[t].identifier)){var o;let t=s.findAssetIndex(c);if(this.log(`INTERSTITIAL_ASSET_ENDED ${t+1}/${s.assetList.length} ${yY(c)}`),this.endedAsset=c,this.playingAsset=null,this.hls.trigger(Z.INTERSTITIAL_ASSET_ENDED,{asset:c,assetListIndex:t,event:s,schedule:n.slice(0),scheduleIndex:e,player:u}),i!==this.playingItem){this.itemsMatch(i,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(s,this.findItemIndex(this.playingItem),t);return}this.retreiveMediaSource(l,r),u.media&&!((o=this.detachedData)!=null&&o.mediaSource)&&u.detachMedia()}if(!this.eventItemsMatch(i,r)&&(this.endedItem=i,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${s} ${CY(i)}`),s.hasPlayed=!0,this.hls.trigger(Z.INTERSTITIAL_ENDED,{event:s,schedule:n.slice(0),scheduleIndex:e}),s.cue.once)){this.updateSchedule();let e=this.schedule?.items;if(r&&e){let n=this.findItemIndex(r);this.advanceSchedule(n,e,t,i,a)}return}}this.advanceSchedule(e,n,t,i,a)}advanceSchedule(e,t,n,r,i){let a=this.schedule;if(!a)return;let o=t[e]||null,s=this.primaryMedia,c=this.playerQueue;if(c.length&&c.forEach(t=>{let n=t.interstitial,r=a.findEventIndex(n.identifier);(r<e||r>e+1)&&this.clearInterstitial(n,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);let i=o.event;if(n===void 0){n=a.findAssetIndex(i,this.timelinePos);let t=_Y(i,n-1);if(i.isAssetPastPlayoutLimit(t)||i.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(i,e,n);return}n=t}let c=this.waitingItem;this.assetsBuffered(o,s)||this.setBufferingItem(o);let l=this.preloadAssets(i,n);if(this.eventItemsMatch(o,c||r)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${CY(o)} ${i.appendInPlace?`append in place`:``}`),this.hls.trigger(Z.INTERSTITIAL_STARTED,{event:i,schedule:t.slice(0),scheduleIndex:e})),!i.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${i}`);return}if(i.assetListLoader&&=(i.assetListLoader.destroy(),void 0),!s){this.log(`Waiting for attachMedia to start Interstitial ${i}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;let u=i.assetList[n];if(!u){this.advanceAfterAssetEnded(i,e,n||0);return}if(l||=this.getAssetPlayer(u.identifier),l===null||l.destroyed){let e=i.assetList.length;this.warn(`asset ${n+1}/${e} player destroyed ${i}`),l=this.createAssetPlayer(i,u,n),l.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&i.appendInPlace&&this.isAssetBuffered(u))return;this.startAssetPlayer(l,n,t,e,s),this.shouldPlay&&TY(l.media)}else o?(this.resumePrimary(o,e,r),this.shouldPlay&&TY(this.hls.media)):i&&this.isInterstitial(r)&&(this.endedItem=null,this.playingItem=r,r.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){return this.mediaSelection?.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,n){var r;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${CY(e)}`),!((r=this.detachedData)!=null&&r.mediaSource)){let n=this.timelinePos;(n<e.start||n>=e.end)&&(n=this.getPrimaryResumption(e,t),this.log(EY(`resumePrimary`,n)),this.timelinePos=n),this.attachPrimary(n,e)}if(!n)return;let i=this.schedule?.items;i&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${CY(e)}`),this.hls.trigger(Z.INTERSTITIALS_PRIMARY_RESUMED,{schedule:i.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){let n=e.start;if(this.primaryLive){let e=this.primaryDetails;if(t===0)return this.hls.startPosition;if(e&&(n<e.fragmentStart||n>e.edge))return this.hls.liveSyncPosition||-1}return n}isAssetBuffered(e){let t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:xU.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,n){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;let r=this.primaryMedia;if(!r)return;let i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,r),n&&this.startLoadingPrimaryAt(e,n)),n||(this.log(EY(`attachPrimary`,e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,n))}startLoadingPrimaryAt(e,t){let n=this.hls;!n.loadingEnabled||!n.media||Math.abs((n.mainForwardBufferInfo?.start||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(Z.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Z.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;let n=this.hls.levels[t.level];if(!n.details)return;let r=_B(_B({},this.mediaSelection||this.altSelection),{},{main:n});this.mediaSelection=r,this.schedule.parseInterstitialDateRanges(r,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){let n=this.hls.audioTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=_B(_B({},this.altSelection),{},{audio:n});return}let i=_B(_B({},r),{},{audio:n});this.mediaSelection=i}onSubtitleTrackUpdated(e,t){let n=this.hls.subtitleTracks[t.id],r=this.mediaSelection;if(!r){this.altSelection=_B(_B({},this.altSelection),{},{subtitles:n});return}let i=_B(_B({},r),{},{subtitles:n});this.mediaSelection=i}onAudioTrackSwitching(e,t){let n=SH(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setAudioOption(t)||e.setAudioOption(n)))}onSubtitleTrackSwitch(e,t){let n=SH(t);this.playerQueue.forEach(({hls:e})=>e&&(e.setSubtitleOption(t)||t.id!==-1&&e.setSubtitleOption(n)))}onBufferCodecs(e,t){let n=t.tracks;n&&(this.requiredTracks=n)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){let n=this.playingItem;if(n&&!this.itemsMatch(n,this.bufferingItem)&&!this.isInterstitial(n)){let e=this.timelinePos;this.bufferedPos=e,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;let t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let e=0;e<t.length;e++){let n=t[e];if(n.cue.post){let e=this.schedule.findEventIndex(n.identifier),t=this.schedule.items?.[e];this.isInterstitial(t)&&this.eventItemsMatch(t,this.bufferingItem)&&this.bufferedToItem(t,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){let t=this.playingItem;if(!this.playingLastItem&&t){let e=this.findItemIndex(t);this.setSchedulePosition(e+1)}else this.shouldPlay=!1}updateItem(e,t){let n=this.schedule?.items;return e&&n&&n[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((t,n)=>{e.event.isAssetPastPlayoutLimit(n)&&this.clearAssetPlayer(t.identifier,null)});let n=e.end+.25,r=xU.bufferInfo(this.primaryMedia,n,0);(r.end>n||(r.nextStart||0)>n)&&(this.log(`trim buffered interstitial ${CY(e)} (was ${CY(t)})`),this.attachPrimary(n,null,!0),this.flushFrontBuffer(n))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){return!!t&&(e===t||e.event.identifier===t.event?.identifier)}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;let n=this.mediaSelection;n&&((t=this.schedule)==null||t.updateSchedule(n,[],e))}checkBuffer(e){let t=this.schedule?.items;if(!t)return;let n=xU.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||=n.len<1,this.updateBufferedPos(n.end,t,e)}updateBufferedPos(e,t,n){let r=this.schedule,i=this.bufferingItem;if(this.bufferedPos>e||!r)return;if(t.length===1&&this.itemsMatch(t[0],i)){this.bufferedPos=e;return}let a=this.playingItem,o=this.findItemIndex(a),s=r.findItemIndexAtTime(e);if(this.bufferedPos<e){var c;let n=this.findItemIndex(i),r=Math.min(n+1,t.length-1),a=t[r];if((s===-1&&i&&e>=i.end||(c=a.event)!=null&&c.appendInPlace&&e+.01>=a.start)&&(s=r),this.isInterstitial(i)){let e=i.event;if(r-o>1&&e.appendInPlace===!1||e.assetList.length===0&&e.assetListLoader)return}if(this.bufferedPos=e,s>n&&s>o)this.bufferedToItem(a);else{let t=this.primaryDetails;this.primaryLive&&t&&e>t.edge-t.targetduration&&a.start<t.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(a)&&this.preloadAssets(a.event,0)}}else n&&a&&!this.itemsMatch(a,i)&&(s===o?this.bufferedToItem(a):s===o+1&&this.bufferedToItem(t[s]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(e=>{let n=this.getAssetPlayer(e.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){let t=this.bufferingItem,n=this.schedule;if(!this.itemsMatch(e,t)&&n){let{items:r,events:i}=n;if(!r||!i)return t;let a=this.isInterstitial(e),o=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));let s=o?o.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${CY(e)}`+(t?` (${s.toFixed(2)} remaining)`:``)),!this.playbackDisabled)if(a){let t=n.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((e,n)=>{let r=this.getAssetPlayer(e.identifier);r&&(n===t&&r.loadSource(),r.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(e=>e.pauseBuffering());this.hls.trigger(Z.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:r.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){let n=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(n!==null){this.bufferingAsset=null;let t=this.detachedData;t&&t.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e)}}}preloadPrimary(e){let t=this.findItemIndex(e),n=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(n)}bufferedToEvent(e,t){let n=e.event,r=n.assetList.length===0&&!n.assetListLoader,i=n.cue.once;if(r||!i){let e=this.preloadAssets(n,t);if(e!=null&&e.interstitial.appendInPlace){let t=this.primaryMedia;t&&this.bufferAssetPlayer(e,t)}}}preloadAssets(e,t){let n=e.assetUrl,r=e.assetList.length,i=r===0&&!e.assetListLoader,a=e.cue.once;if(i){let i=e.timelineStart;if(e.appendInPlace){var o;let t=this.playingItem;!this.isInterstitial(t)&&(t==null||(o=t.nextEvent)==null?void 0:o.identifier)===e.identifier&&this.flushFrontBuffer(i+.25)}let a,s=0;if(!this.playingItem&&this.primaryLive&&(s=this.hls.startPosition,s===-1&&(s=this.hls.liveSyncPosition||0)),s&&!(e.cue.pre||e.cue.post)){let e=s-i;e>0&&(a=Math.round(e*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${n?1:r} ${e}${a?` live-start: ${s} start-offset: ${a}`:``}`),n)return this.createAsset(e,0,0,i,e.duration,n);let c=this.assetListLoader.loadAssetList(e,a);c&&(e.assetListLoader=c)}else if(!a&&r){for(let n=t;n<r;n++){let t=e.assetList[n],r=this.getAssetPlayerQueueIndex(t.identifier);(r===-1||this.playerQueue[r].destroyed)&&!t.error&&this.createAssetPlayer(e,t,n)}let n=e.assetList[t];if(n){let e=this.getAssetPlayer(n.identifier);return e&&e.loadSource(),e}}return null}flushFrontBuffer(e){let t=this.requiredTracks;t&&(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(t=>{this.hls.trigger(Z.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:t})}))}getAssetPlayerQueueIndex(e){let t=this.playerQueue;for(let n=0;n<t.length;n++)if(e===t[n].assetId)return n;return-1}getAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){let{playerQueue:e,primaryMedia:t}=this;if(t){for(let n=0;n<e.length;n++)if(e[n].media===t)return e[n]}return null}createAsset(e,t,n,r,i,a){let o={parentIdentifier:e.identifier,identifier:pY(e,a,t),duration:i,startOffset:n,timelineStart:r,uri:a};return this.createAssetPlayer(e,o,t)}createAssetPlayer(e,t,n){let r=this.hls,i=r.userConfig,a=i.videoPreference,o=r.loadLevelObj||r.levels[r.currentLevel];(a||o)&&(a=hB({},a),o.videoCodec&&(a.videoCodec=o.videoCodec),o.videoRange&&(a.allowedVideoRanges=[o.videoRange]));let s=r.audioTracks[r.audioTrack],c=r.subtitleTracks[r.subtitleTrack],l=0;if(this.primaryLive||e.appendInPlace){let e=this.timelinePos-t.timelineStart;if(e>1){let n=t.duration;n&&e<n&&(l=e)}}let u=t.identifier,d=_B(_B({},i),{},{maxMaxBufferLength:Math.min(180,r.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:r.sessionId,assetPlayerId:u,abrEwmaDefaultEstimate:r.bandwidthEstimate,interstitialsController:void 0,startPosition:l,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:s||i.audioPreference,subtitlePreference:c||i.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(d.timelineOffset=t.timelineStart));let f=d.cmcd;f!=null&&f.sessionId&&f.contentId&&(d.cmcd=hB({},f,{contentId:uY(t.uri)})),this.getAssetPlayer(u)&&this.warn(`Duplicate date range identifier ${e} and asset ${u}`);let p=new bY(this.HlsPlayerClass,d,e,t);this.playerQueue.push(p),e.assetList[n]=t;let m=!0,h=r=>{if(r.live){let t=Error(`Interstitials MUST be VOD assets ${e}`),r={fatal:!0,type:Y.OTHER_ERROR,details:X.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},i=this.schedule?.findEventIndex(e.identifier)||-1;this.handleAssetItemError(r,e,i,n,t.message);return}let i=r.edge-r.fragmentStart,a=t.duration;(m||a===null||i>a)&&(m=!1,this.log(`Interstitial asset "${u}" duration change ${a} > ${i}`),t.duration=i,this.updateSchedule())};p.on(Z.LEVEL_UPDATED,(e,{details:t})=>h(t)),p.on(Z.LEVEL_PTS_UPDATED,(e,{details:t})=>h(t)),p.on(Z.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());let g=(e,t)=>{let n=this.getAssetPlayer(u);if(n&&t.tracks){n.off(Z.BUFFER_CODECS,g),n.tracks=t.tracks;let e=this.primaryMedia;this.bufferingAsset===n.assetItem&&e&&!n.media&&this.bufferAssetPlayer(n,e)}};p.on(Z.BUFFER_CODECS,g),p.on(Z.BUFFERED_TO_END,()=>{let n=this.getAssetPlayer(u);if(this.log(`buffered to end of asset ${n}`),!n||!this.schedule)return;let r=this.schedule.findEventIndex(e.identifier),i=this.schedule.items?.[r];this.isInterstitial(i)&&this.advanceAssetBuffering(i,t)});let _=t=>()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;this.shouldPlay=!0;let n=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,n,t)};return p.once(Z.MEDIA_ENDED,_(n)),p.once(Z.PLAYOUT_LIMIT_REACHED,_(1/0)),p.on(Z.ERROR,(t,r)=>{if(!this.schedule)return;let i=this.getAssetPlayer(u);if(r.details===X.BUFFER_STALLED_ERROR){if(i!=null&&i.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),n,`Asset player error ${r.error} ${e}`)}),p.on(Z.DESTROYING,()=>{if(!this.getAssetPlayer(u)||!this.schedule)return;let t=Error(`Asset player destroyed unexpectedly ${u}`),r={fatal:!0,type:Y.OTHER_ERROR,details:X.INTERSTITIAL_ASSET_ITEM_ERROR,error:t};this.handleAssetItemError(r,e,this.schedule.findEventIndex(e.identifier),n,t.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${yY(t)}`),this.hls.trigger(Z.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:n,event:e,player:p}),p}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(e=>{this.clearAssetPlayer(e.identifier,t)})}resetAssetPlayer(e){let t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);let n=this.playerQueue[t];this.transferMediaFromPlayer(n,null),n.resetDetails()}}clearAssetPlayer(e,t){let n=this.getAssetPlayerQueueIndex(e);if(n!==-1){let e=this.playerQueue[n];this.log(`clear ${e} toSegment: ${t&&CY(t)}`),this.transferMediaFromPlayer(e,t),this.playerQueue.splice(n,1),e.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,n,r,i){let{interstitial:a,assetItem:o,assetId:s}=e,c=a.assetList.length,l=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!l||l.identifier!==s)&&(l&&(this.clearAssetPlayer(l.identifier,n[r]),delete l.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${c} ${yY(o)}`),this.hls.trigger(Z.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:t,event:a,schedule:n.slice(0),scheduleIndex:r,player:e})),this.bufferAssetPlayer(e,i)}bufferAssetPlayer(e,t){if(!this.schedule)return;let{interstitial:n,assetItem:r}=e,i=this.schedule.findEventIndex(n.identifier),a=this.schedule.items?.[i];if(!a)return;e.loadSource(),this.setBufferingItem(a),this.bufferingAsset=r;let o=this.getBufferingPlayer();if(o===e)return;let s=n.appendInPlace;if(s&&o?.interstitial.appendInPlace===!1)return;let c=o?.tracks||this.detachedData?.tracks||this.requiredTracks;if(s&&r!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(c&&!jB(c,e.tracks)){let t=Error(`Asset ${yY(r)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(c)}')`),a={fatal:!0,type:Y.OTHER_ERROR,details:X.INTERSTITIAL_ASSET_ITEM_ERROR,error:t},o=n.findAssetIndex(r);this.handleAssetItemError(a,n,i,o,t.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){let t=this.schedule,n=this.primaryMedia;if(!t||!n)return;let r=n.currentTime,i=t.findAssetIndex(e,r),a=e.assetList[i];if(a){let o=this.getAssetPlayer(a.identifier);if(o){let s=o.currentTime||r-a.timelineStart,c=o.duration-s;if(this.warn(`Stalled at ${s} of ${s+c} in ${o} ${e} (media.currentTime: ${r})`),s&&(c/n.playbackRate<.5||o.bufferedInPlaceToEnd(n))&&o.hls){let n=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,n,i)}}}}advanceInPlace(e){let t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,n,r,i){if(e.details===X.BUFFER_STALLED_ERROR)return;let a=t.assetList[r]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&yY(a)} ${e.error}`),!this.schedule)return;let o=a?.identifier||``,s=this.getAssetPlayerQueueIndex(o),c=this.playerQueue[s]||null,l=this.schedule.items,u=hB({},e,{fatal:!1,errorAction:ZH(!0),asset:a,assetListIndex:r,event:t,schedule:l,scheduleIndex:n,player:c});if(this.hls.trigger(Z.INTERSTITIAL_ASSET_ERROR,u),!e.fatal)return;let d=this.playingAsset,f=this.bufferingAsset,p=Error(i);if(a&&(this.clearAssetPlayer(o,null),a.error=p),!t.assetList.some(e=>!e.error))t.error=p;else for(let e=r;e<t.assetList.length;e++)this.resetAssetPlayer(t.assetList[e].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):d&&d.identifier===o?this.advanceAfterAssetEnded(t,n,r):f&&f.identifier===o&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,f)}primaryFallback(e){let t=e.timelineStart,n=this.effectivePlayingItem,r=this.timelinePos;if(n){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${r} playing: ${CY(n)} error: ${e.error}`),r===-1&&(r=this.hls.startPosition);let i=this.updateItem(n,r);this.itemsMatch(n,i)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(r===-1){this.checkStart();return}if(!this.schedule)return;let i=this.schedule.findItemIndexAtTime(r);this.setSchedulePosition(i)}onAssetListLoaded(e,t){var n;let r=t.event,i=r.identifier,a=t.assetListResponse.ASSETS;if(!((n=this.schedule)!=null&&n.hasEvent(i)))return;let o=r.timelineStart,s=r.duration,c=0;a.forEach((e,t)=>{let n=parseFloat(e.DURATION);this.createAsset(r,t,c,o+c,n,e.URI),c+=n}),r.duration=c,this.log(`Loaded asset-list with duration: ${c} (was: ${s}) ${r}`);let l=this.waitingItem?.event.identifier===i;this.updateSchedule();let u=this.bufferingItem?.event;if(l){let e=this.schedule.findEventIndex(i),t=this.schedule.items?.[e];if(t){if(!this.playingItem&&this.timelinePos>t.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==e){r.error=Error(`Interstitial ${a.length?`no longer within playback range`:`asset-list is empty`} ${this.timelinePos} ${r}`),this.log(r.error.message),this.updateSchedule(!0),this.primaryFallback(r);return}this.setBufferingItem(t)}this.setSchedulePosition(e)}else if(u?.identifier===i){let e=r.assetList[0];if(e){let t=this.getAssetPlayer(e.identifier);if(u.appendInPlace){let e=this.primaryMedia;t&&e&&this.bufferAssetPlayer(t,e)}else t&&t.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case X.ASSET_LIST_PARSING_ERROR:case X.ASSET_LIST_LOAD_ERROR:case X.ASSET_LIST_LOAD_TIMEOUT:{let e=t.interstitial;e&&(this.updateSchedule(!0),this.primaryFallback(e));break}case X.BUFFER_STALLED_ERROR:{let e=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(e)&&e.event.appendInPlace){this.handleInPlaceStall(e.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},OY=500,kY=class extends ZW{constructor(e,t,n){super(e,t,n,`subtitle-stream-controller`,Q.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(Z.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Z.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Z.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on(Z.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(Z.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on(Z.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(Z.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Z.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Z.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off(Z.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(Z.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off(Z.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=$.IDLE,this.setInterval(OY),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){let{frag:n,success:r}=t;if(this.fragContextChanged(n)||(UB(n)&&(this.fragPrevious=n),this.state=$.IDLE),!r)return;let i=this.tracksBuffered[this.currentTrackId];if(!i)return;let a,o=n.start;for(let e=0;e<i.length;e++)if(o>=i[e].start&&o<=i[e].end){a=i[e];break}let s=n.start+n.duration;a?a.end=s:(a={start:o,end:s},i.push(a)),this.fragmentTracker.fragBuffered(n),this.fragBufferedComplete(n,null),this.media&&this.tick()}onBufferFlushing(e,t){let{startOffset:n,endOffset:r}=t;if(n===0&&r!==1/0){let e=r-1;if(e<=0)return;t.endOffsetSubtitles=Math.max(0,e),this.tracksBuffered.forEach(t=>{for(let n=0;n<t.length;){if(t[n].end<=e){t.shift();continue}else if(t[n].start<e)t[n].start=e;else break;n++}}),this.fragmentTracker.removeFragmentsInRange(n,e,Q.SUBTITLE)}}onError(e,t){let n=t.frag;n?.type===Q.SUBTITLE&&(t.details===X.FRAG_GAP&&this.fragmentTracker.fragBuffered(n,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==$.STOPPED&&(this.state=$.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&dq(this.levels,t)){this.levels=t.map(e=>new fH(e));return}this.tracksBuffered=[],this.levels=t.map(e=>{let t=new fH(e);return this.tracksBuffered[t.id]=[],t}),this.fragmentTracker.removeFragmentsInRange(0,1/0,Q.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var n;if(this.currentTrackId=t.id,!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}let r=this.levels[this.currentTrackId];r!=null&&r.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,r&&this.state!==$.STOPPED&&this.setInterval(OY)}onSubtitleTrackLoaded(e,t){var n;let{currentTrackId:r,levels:i}=this,{details:a,id:o}=t;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}let s=i[o];if(o>=i.length||!s)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:``},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let c=0;if(a.live||(n=s.details)!=null&&n.live){if(a.deltaUpdateFailed)return;let e=this.mainDetails;if(!e){this.startFragRequested=!1;return}let t=e.fragments[0];s.details?(c=this.alignPlaylists(a,s.details,this.levelLastLoaded?.details),c===0&&t&&(c=t.start,NW(a,c))):a.hasProgramDateTime&&e.hasProgramDateTime?(qW(a,e),c=a.fragmentStart):t&&(c=t.start,NW(a,c)),e&&!this.startFragRequested&&this.setStartPosition(e,c)}s.details=a,this.levelLastLoaded=s,o===r&&(this.hls.trigger(Z.SUBTITLE_TRACK_UPDATED,{details:a,id:o,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===$.IDLE&&(PH(null,a.fragments,this.media.currentTime,0)||(this.warn(`Subtitle playlist not aligned with playback`),s.details=void 0)))}_handleFragmentLoadComplete(e){let{frag:t,payload:n}=e,r=t.decryptdata,i=this.hls;if(!this.fragContextChanged(t)&&n&&n.byteLength>0&&r!=null&&r.key&&r.iv&&RU(r.method)){let e=performance.now();this.decrypter.decrypt(new Uint8Array(n),r.key.buffer,r.iv.buffer,zU(r.method)).catch(e=>{throw i.trigger(Z.ERROR,{type:Y.MEDIA_ERROR,details:X.FRAG_DECRYPT_ERROR,fatal:!1,error:e,reason:e.message,frag:t}),e}).then(n=>{let r=performance.now();i.trigger(Z.FRAG_DECRYPTED,{frag:t,payload:n,stats:{tstart:e,tdecrypt:r}})}).catch(e=>{this.warn(`${e.name}: ${e.message}`),this.state=$.IDLE})}}doTick(){if(!this.media){this.state=$.IDLE;return}if(this.state===$.IDLE){let{currentTrackId:e,levels:t}=this,n=t?.[e];if(!n||!t.length||!n.details||this.waitForLive(n))return;let{config:r}=this,i=this.getLoadPosition(),{end:a,len:o}=xU.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,r.maxBufferHole),s=n.details;if(o>this.hls.maxBufferLength+s.levelTargetDuration)return;let c=s.fragments,l=c.length,u=s.edge,d=null,f=this.fragPrevious;if(a<u){let e=r.maxFragLookUpTolerance,t=a>u-e?0:e;d=PH(f,c,Math.max(c[0].start,a),t),!d&&f&&f.start<c[0].start&&(d=c[0])}else d=c[l-1];if(d=this.filterReplacedPrimary(d,n.details),!d)return;let p=c[d.sn-s.startSN-1];if(p&&p.cc===d.cc&&this.fragmentTracker.getState(p)===QH.NOT_LOADED&&(d=p),this.fragmentTracker.getState(d)===QH.NOT_LOADED){let e=this.mapToInitFragWhenRequired(d);e&&this.loadFragment(e,n,a)}}}loadFragment(e,t,n){UB(e)?super.loadFragment(e,t,n):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new AY(this.tracksBuffered[this.currentTrackId]||[])}},AY=class{constructor(e){this.buffered=void 0;let t=(t,n,r)=>{if(n>>>=0,n>r-1)throw new DOMException(`Failed to execute '${t}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${r})`);return e[n][t]};this.buffered={get length(){return e.length},end(n){return t(`end`,n,e.length)},start(n){return t(`start`,n,e.length)}}}},jY={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},MY=e=>String.fromCharCode(jY[e]||e),NY=15,PY=100,FY={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},IY={17:2,18:4,21:6,22:8,23:10,19:13,20:15},LY={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},RY={25:2,26:4,29:6,30:8,31:10,27:13,28:15},zY=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`black`,`transparent`],BY=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){let n=typeof t==`function`?t():t;OB.log(`${this.time} [${e}] ${n}`)}}},VY=function(e){let t=[];for(let n=0;n<e.length;n++)t.push(e[n].toString(16));return t},HY=class{constructor(){this.foreground=`white`,this.underline=!1,this.italics=!1,this.background=`black`,this.flash=!1}reset(){this.foreground=`white`,this.underline=!1,this.italics=!1,this.background=`black`,this.flash=!1}setStyles(e){let t=[`foreground`,`underline`,`italics`,`background`,`flash`];for(let n=0;n<t.length;n++){let r=t[n];e.hasOwnProperty(r)&&(this[r]=e[r])}}isDefault(){return this.foreground===`white`&&!this.underline&&!this.italics&&this.background===`black`&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return`color=`+this.foreground+`, underline=`+this.underline+`, italics=`+this.italics+`, background=`+this.background+`, flash=`+this.flash}},UY=class{constructor(){this.uchar=` `,this.penState=new HY}reset(){this.uchar=` `,this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===` `&&this.penState.isDefault()}},WY=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new HY,this.cueStartTime=null,this.logger=void 0;for(let e=0;e<PY;e++)this.chars.push(new UY);this.logger=e}equals(e){for(let t=0;t<PY;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<PY;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<PY;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,`Negative cursor position `+this.pos),this.pos=0):this.pos>PY&&(this.logger.log(3,`Too large cursor position `+this.pos),this.pos=PY)}moveCursor(e){let t=this.pos+e;if(e>1)for(let e=this.pos+1;e<t+1;e++)this.chars[e].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(` `,this.currPenState)}insertChar(e){e>=144&&this.backSpace();let t=MY(e);if(this.pos>=PY){this.logger.log(0,()=>`Cannot insert `+e.toString(16)+` (`+t+`) at position `+this.pos+`. Skipping it!`);return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<PY;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){let e=[],t=!0;for(let n=0;n<PY;n++){let r=this.chars[n].uchar;r!==` `&&(t=!1),e.push(r)}return t?``:e.join(``)}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},GY=class{constructor(e){this.rows=[],this.currRow=NY-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<NY;t++)this.rows.push(new WY(e));this.logger=e}reset(){for(let e=0;e<NY;e++)this.rows[e].clear();this.currRow=NY-1}equals(e){let t=!0;for(let n=0;n<NY;n++)if(!this.rows[n].equals(e.rows[n])){t=!1;break}return t}copy(e){for(let t=0;t<NY;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<NY;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,`setCursor: `+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>`pacData = `+_H(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let e=0;e<NY;e++)this.rows[e].clear();let e=this.currRow+1-this.nrRollUpRows,n=this.lastOutputScreen;if(n){let r=n.rows[e].cueStartTime,i=this.logger.time;if(r!==null&&i!==null&&r<i)for(let r=0;r<this.nrRollUpRows;r++)this.rows[t-this.nrRollUpRows+r+1].copy(n.rows[e+r])}}this.currRow=t;let n=this.rows[this.currRow];if(e.indent!==null){let t=e.indent,r=Math.max(t-1,0);n.setCursor(e.indent),e.color=n.chars[r].penState.foreground}let r={foreground:e.color,underline:e.underline,italics:e.italics,background:`black`,flash:!1};this.setPen(r)}setBkgData(e){this.logger.log(2,()=>`bkgData = `+_H(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,`roll_up but nrRollUpRows not set yet`);return}this.logger.log(1,()=>this.getDisplayText());let e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,`Rolling up`)}getDisplayText(e){e||=!1;let t=[],n=``,r=-1;for(let n=0;n<NY;n++){let i=this.rows[n].getTextString();i&&(r=n+1,e?t.push(`Row `+r+`: '`+i+`'`):t.push(i.trim()))}return t.length>0&&(n=e?`[`+t.join(` | `)+`]`:t.join(`
63
- `)),n}getTextAndFormat(){return this.rows}},KY=class{constructor(e,t,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new GY(n),this.nonDisplayedMemory=new GY(n),this.lastOutputScreen=new GY(n),this.currRollUpRow=this.displayedMemory.rows[NY-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[NY-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>`MODE=`+e),this.mode===`MODE_POP-ON`?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!==`MODE_ROLL-UP`&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let t=0;t<e.length;t++)this.writeScreen.insertChar(e[t]);let t=this.writeScreen===this.displayedMemory?`DISP`:`NON_DISP`;this.logger.log(2,()=>t+`: `+this.writeScreen.getDisplayText(!0)),(this.mode===`MODE_PAINT-ON`||this.mode===`MODE_ROLL-UP`)&&(this.logger.log(1,()=>`DISPLAYED: `+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,`RCL - Resume Caption Loading`),this.setMode(`MODE_POP-ON`)}ccBS(){this.logger.log(2,`BS - BackSpace`),this.mode!==`MODE_TEXT`&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,`DER- Delete to End of Row`),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,`RU(`+e+`) - Roll Up`),this.writeScreen=this.displayedMemory,this.setMode(`MODE_ROLL-UP`),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,`FON - Flash On`),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,`RDC - Resume Direct Captioning`),this.setMode(`MODE_PAINT-ON`)}ccTR(){this.logger.log(2,`TR`),this.setMode(`MODE_TEXT`)}ccRTD(){this.logger.log(2,`RTD`),this.setMode(`MODE_TEXT`)}ccEDM(){this.logger.log(2,`EDM - Erase Displayed Memory`),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,`CR - Carriage Return`),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,`ENM - Erase Non-displayed Memory`),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,`EOC - End Of Caption`),this.mode===`MODE_POP-ON`){let e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>`DISP: `+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,`TO(`+e+`) - Tab Offset`),this.writeScreen.moveCursor(e)}ccMIDROW(e){let t={flash:!1};t.underline=e%2==1,t.italics=e>=46,t.italics?t.foreground=`white`:t.foreground=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`][Math.floor(e/2)-16],this.logger.log(2,`MIDROW: `+_H(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){let t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},qY=class{constructor(e,t,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=XY(),this.logger=void 0;let r=this.logger=new BY;this.channels=[null,new KY(e,t,r),new KY(e+1,n,r)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let e=0;e<t.length;e+=2){let n=t[e]&127,r=t[e+1]&127,i=!1,a=null;if(n===0&&r===0)continue;this.logger.log(3,()=>`[`+VY([t[e],t[e+1]])+`] -> (`+VY([n,r])+`)`);let o=this.cmdHistory;if(n>=16&&n<=31){if(YY(n,r,o)){JY(null,null,o),this.logger.log(3,()=>`Repeated command (`+VY([n,r])+`) is dropped`);continue}JY(n,r,this.cmdHistory),i=this.parseCmd(n,r),i||=this.parseMidrow(n,r),i||=this.parsePAC(n,r),i||=this.parseBackgroundAttributes(n,r)}else JY(null,null,o);if(!i&&(a=this.parseChars(n,r),a)){let e=this.currentChannel;e&&e>0?this.channels[e].insertChars(a):this.logger.log(2,`No channel found yet. TEXT-MODE?`)}!i&&!a&&this.logger.log(2,()=>`Couldn't parse cleaned data `+VY([n,r])+` orig: `+VY([t[e],t[e+1]]))}}parseCmd(e,t){if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47||(e===23||e===31)&&t>=33&&t<=35))return!1;let n=e===20||e===21||e===23?1:2,r=this.channels[n];return e===20||e===21||e===28||e===29?t===32?r.ccRCL():t===33?r.ccBS():t===34?r.ccAOF():t===35?r.ccAON():t===36?r.ccDER():t===37?r.ccRU(2):t===38?r.ccRU(3):t===39?r.ccRU(4):t===40?r.ccFON():t===41?r.ccRDC():t===42?r.ccTR():t===43?r.ccRTD():t===44?r.ccEDM():t===45?r.ccCR():t===46?r.ccENM():t===47&&r.ccEOC():r.ccTO(t-32),this.currentChannel=n,!0}parseMidrow(e,t){let n=0;if((e===17||e===25)&&t>=32&&t<=47){if(n=e===17?1:2,n!==this.currentChannel)return this.logger.log(0,`Mismatch channel in midrow parsing`),!1;let r=this.channels[n];return r?(r.ccMIDROW(t),this.logger.log(3,()=>`MIDROW (`+VY([e,t])+`)`),!0):!1}return!1}parsePAC(e,t){let n;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(e===16||e===24)&&t>=64&&t<=95))return!1;let r=e<=23?1:2;n=t>=64&&t<=95?r===1?FY[e]:LY[e]:r===1?IY[e]:RY[e];let i=this.channels[r];return i?(i.setPAC(this.interpretPAC(n,t)),this.currentChannel=r,!0):!1}interpretPAC(e,t){let n,r={color:null,italics:!1,indent:null,underline:!1,row:e};return n=t>95?t-96:t-64,r.underline=(n&1)==1,n<=13?r.color=[`white`,`green`,`blue`,`cyan`,`red`,`yellow`,`magenta`,`white`][Math.floor(n/2)]:n<=15?(r.italics=!0,r.color=`white`):r.indent=Math.floor((n-16)/2)*4,r}parseChars(e,t){let n,r=null,i=null;if(e>=25?(n=2,i=e-8):(n=1,i=e),i>=17&&i<=19){let e;e=i===17?t+80:i===18?t+112:t+144,this.logger.log(2,()=>`Special char '`+MY(e)+`' in channel `+n),r=[e]}else e>=32&&e<=127&&(r=t===0?[e]:[e,t]);return r&&this.logger.log(3,()=>`Char codes = `+VY(r).join(`,`)),r}parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47||(e===23||e===31)&&t>=45&&t<=47))return!1;let n,r={};e===16||e===24?(n=Math.floor((t-32)/2),r.background=zY[n],t%2==1&&(r.background+=`_semi`)):t===45?r.background=`transparent`:(r.foreground=`black`,t===47&&(r.underline=!0));let i=e<=23?1:2;return this.channels[i].setBkgData(r),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){let t=this.channels[e];t&&t.reset()}JY(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){let n=this.channels[t];n&&n.cueSplitAtTime(e)}}};function JY(e,t,n){n.a=e,n.b=t}function YY(e,t,n){return n.a===e&&n.b===t}function XY(){return{a:null,b:null}}var ZY=(function(){if(GU!=null&&GU.VTTCue)return self.VTTCue;let e=[``,`lr`,`rl`],t=[`start`,`middle`,`end`,`left`,`right`];function n(e,t){if(typeof t!=`string`||!Array.isArray(e))return!1;let n=t.toLowerCase();return~e.indexOf(n)?n:!1}function r(t){return n(e,t)}function i(e){return n(t,e)}function a(e,...t){let n=1;for(;n<arguments.length;n++){let t=arguments[n];for(let n in t)e[n]=t[n]}return e}function o(e,t,n){let o=this,s={enumerable:!0};o.hasBeenReset=!1;let c=``,l=!1,u=e,d=t,f=n,p=null,m=``,h=!0,g=`auto`,_=`start`,v=50,y=`middle`,b=50,x=`middle`;Object.defineProperty(o,"id",a({},s,{get:function(){return c},set:function(e){c=``+e}})),Object.defineProperty(o,"pauseOnExit",a({},s,{get:function(){return l},set:function(e){l=!!e}})),Object.defineProperty(o,"startTime",a({},s,{get:function(){return u},set:function(e){if(typeof e!=`number`)throw TypeError(`Start time must be set to a number.`);u=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"endTime",a({},s,{get:function(){return d},set:function(e){if(typeof e!=`number`)throw TypeError(`End time must be set to a number.`);d=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"text",a({},s,{get:function(){return f},set:function(e){f=``+e,this.hasBeenReset=!0}})),Object.defineProperty(o,"region",a({},s,{get:function(){return p},set:function(e){p=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"vertical",a({},s,{get:function(){return m},set:function(e){let t=r(e);if(t===!1)throw SyntaxError(`An invalid or illegal string was specified.`);m=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"snapToLines",a({},s,{get:function(){return h},set:function(e){h=!!e,this.hasBeenReset=!0}})),Object.defineProperty(o,"line",a({},s,{get:function(){return g},set:function(e){if(typeof e!=`number`&&e!==`auto`)throw SyntaxError(`An invalid number or illegal string was specified.`);g=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"lineAlign",a({},s,{get:function(){return _},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);_=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"position",a({},s,{get:function(){return v},set:function(e){if(e<0||e>100)throw Error(`Position must be between 0 and 100.`);v=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"positionAlign",a({},s,{get:function(){return y},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);y=t,this.hasBeenReset=!0}})),Object.defineProperty(o,"size",a({},s,{get:function(){return b},set:function(e){if(e<0||e>100)throw Error(`Size must be between 0 and 100.`);b=e,this.hasBeenReset=!0}})),Object.defineProperty(o,"align",a({},s,{get:function(){return x},set:function(e){let t=i(e);if(!t)throw SyntaxError(`An invalid or illegal string was specified.`);x=t,this.hasBeenReset=!0}})),o.displayState=void 0}return o.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},o})(),QY=class{decode(e,t){if(!e)return``;if(typeof e!=`string`)throw Error(`Error - expected string data.`);return decodeURIComponent(encodeURIComponent(e))}};function $Y(e){function t(e,t,n,r){return(e|0)*3600+(t|0)*60+(n|0)+parseFloat(r||0)}let n=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return n?parseFloat(n[2])>59?t(n[2],n[3],0,n[4]):t(n[1],n[2],n[3],n[4]):null}var eX=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==``&&(this.values[e]=t)}get(e,t,n){return n?this.has(e)?this.values[e]:t[n]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,n){for(let r=0;r<n.length;++r)if(t===n[r]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){let n=parseFloat(t);if(n>=0&&n<=100)return this.set(e,n),!0}return!1}};function tX(e,t,n,r){let i=r?e.split(r):[e];for(let e in i){if(typeof i[e]!=`string`)continue;let r=i[e].split(n);if(r.length!==2)continue;let a=r[0],o=r[1];t(a,o)}}var nX=new ZY(0,0,``),rX=nX.align===`middle`?`middle`:`center`;function iX(e,t,n){let r=e;function i(){let t=$Y(e);if(t===null)throw Error(`Malformed timestamp: `+r);return e=e.replace(/^[^\sa-zA-Z-]+/,``),t}function a(e,t){let r=new eX;tX(e,function(e,t){let i;switch(e){case`region`:for(let i=n.length-1;i>=0;i--)if(n[i].id===t){r.set(e,n[i].region);break}break;case`vertical`:r.alt(e,t,[`rl`,`lr`]);break;case`line`:i=t.split(`,`),r.integer(e,i[0]),r.percent(e,i[0])&&r.set(`snapToLines`,!1),r.alt(e,i[0],[`auto`]),i.length===2&&r.alt(`lineAlign`,i[1],[`start`,rX,`end`]);break;case`position`:i=t.split(`,`),r.percent(e,i[0]),i.length===2&&r.alt(`positionAlign`,i[1],[`start`,rX,`end`,`line-left`,`line-right`,`auto`]);break;case`size`:r.percent(e,t);break;case`align`:r.alt(e,t,[`start`,rX,`end`,`left`,`right`]);break}},/:/,/\s/),t.region=r.get(`region`,null),t.vertical=r.get(`vertical`,``);let i=r.get(`line`,`auto`);i===`auto`&&nX.line===-1&&(i=-1),t.line=i,t.lineAlign=r.get(`lineAlign`,`start`),t.snapToLines=r.get(`snapToLines`,!0),t.size=r.get(`size`,100),t.align=r.get(`align`,rX);let a=r.get(`position`,`auto`);a===`auto`&&nX.position===50&&(a=t.align===`start`||t.align===`left`?0:t.align===`end`||t.align===`right`?100:50),t.position=a}function o(){e=e.replace(/^\s+/,``)}if(o(),t.startTime=i(),o(),e.slice(0,3)!==`-->`)throw Error(`Malformed time stamp (time stamps must be separated by '-->'): `+r);e=e.slice(3),o(),t.endTime=i(),o(),a(e,t)}function aX(e){return e.replace(/<br(?: \/)?>/gi,`
64
- `)}var oX=class{constructor(){this.state=`INITIAL`,this.buffer=``,this.decoder=new QY,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){let t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function n(){let e=t.buffer,n=0;for(e=aX(e);n<e.length&&e[n]!==`\r`&&e[n]!==`
65
- `;)++n;let r=e.slice(0,n);return e[n]===`\r`&&++n,e[n]===`
66
- `&&++n,t.buffer=e.slice(n),r}function r(e){tX(e,function(e,t){},/:/)}try{let e=``;if(t.state===`INITIAL`){if(!/\r\n|\n/.test(t.buffer))return this;e=n();let r=e.match(/^()?WEBVTT([ \t].*)?$/);if(!(r!=null&&r[0]))throw Error(`Malformed WebVTT signature.`);t.state=`HEADER`}let i=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(i?i=!1:e=n(),t.state){case`HEADER`:/:/.test(e)?r(e):e||(t.state=`ID`);continue;case`NOTE`:e||(t.state=`ID`);continue;case`ID`:if(/^NOTE($|[ \t])/.test(e)){t.state=`NOTE`;break}if(!e)continue;if(t.cue=new ZY(0,0,``),t.state=`CUE`,e.indexOf(`-->`)===-1){t.cue.id=e;continue}case`CUE`:if(!t.cue){t.state=`BADCUE`;continue}try{iX(e,t.cue,t.regionList)}catch{t.cue=null,t.state=`BADCUE`;continue}t.state=`CUETEXT`;continue;case`CUETEXT`:{let n=e.indexOf(`-->`)!==-1;if(!e||n&&(i=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state=`ID`;continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
67
- `),t.cue.text+=e}continue;case`BADCUE`:e||(t.state=`ID`)}}}catch{t.state===`CUETEXT`&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state===`INITIAL`?`BADWEBVTT`:`BADCUE`}return this}flush(){let e=this;try{if((e.cue||e.state===`HEADER`)&&(e.buffer+=`
68
-
69
- `,e.parse()),e.state===`INITIAL`||e.state===`BADWEBVTT`)throw Error(`Malformed WebVTT signature.`)}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},sX=/\r\n|\n\r|\n|\r/g,cX=function(e,t,n=0){return e.slice(n,n+t.length)===t},lX=function(e){let t=parseInt(e.slice(-3)),n=parseInt(e.slice(-6,-4)),r=parseInt(e.slice(-9,-7)),i=e.length>9?parseInt(e.substring(0,e.indexOf(`:`))):0;if(!J(t)||!J(n)||!J(r)||!J(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return t+=1e3*n,t+=60*1e3*r,t+=3600*1e3*i,t};function uX(e,t,n){return uY(e.toString())+uY(t.toString())+uY(n)}var dX=function(e,t,n){let r=e[t],i=e[r.prevCC];if(!i||!i.new&&r.new){e.ccOffset=e.presentationOffset=r.start,r.new=!1;return}for(;(a=i)!=null&&a.new;){var a;e.ccOffset+=r.start-i.start,r.new=!1,r=i,i=e[r.prevCC]}e.presentationOffset=n};function fX(e,t,n,r,i,a,o){let s=new oX,c=MB(new Uint8Array(e)).trim().replace(sX,`
70
- `).split(`
71
- `),l=[],u=t?PK(t.baseTime,t.timescale):0,d=`00:00.000`,f=0,p=0,m,h=!0;s.oncue=function(e){let a=n[r],o=n.ccOffset,s=(f-u)/9e4;if(a!=null&&a.new&&(p===void 0?dX(n,r,s):o=n.ccOffset=a.start),s){if(!t){m=Error(`Missing initPTS for VTT MPEGTS`);return}o=s-n.presentationOffset}let c=e.endTime-e.startTime,d=WK((e.startTime+o-p)*9e4,i*9e4)/9e4;e.startTime=Math.max(d,0),e.endTime=Math.max(d+c,0);let h=e.text.trim();e.text=decodeURIComponent(encodeURIComponent(h)),e.id||=uX(e.startTime,e.endTime,h),e.endTime>0&&l.push(e)},s.onparsingerror=function(e){m=e},s.onflush=function(){if(m){o(m);return}a(l)},c.forEach(e=>{if(h)if(cX(e,`X-TIMESTAMP-MAP=`)){h=!1,e.slice(16).split(`,`).forEach(e=>{cX(e,`LOCAL:`)?d=e.slice(6):cX(e,`MPEGTS:`)&&(f=parseInt(e.slice(7)))});try{p=lX(d)/1e3}catch(e){m=e}return}else e===``&&(h=!1);s.parse(e+`
72
- `)}),s.flush()}var pX=`stpp.ttml.im1t`,mX=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,hX=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,gX={left:`start`,center:`center`,right:`end`,start:`start`,end:`end`};function _X(e,t,n,r){let i=rV(new Uint8Array(e),[`mdat`]);if(i.length===0){r(Error(`Could not parse IMSC1 mdat`));return}let a=i.map(e=>MB(e)),o=MK(t.baseTime,1,t.timescale);try{a.forEach(e=>n(vX(e,o)))}catch(e){r(e)}}function vX(e,t){let n=new DOMParser().parseFromString(e,`text/xml`).getElementsByTagName(`tt`)[0];if(!n)throw Error(`Invalid ttml`);let r={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},i=Object.keys(r).reduce((e,t)=>(e[t]=n.getAttribute(`ttp:${t}`)||r[t],e),{}),a=n.getAttribute(`xml:space`)!==`preserve`,o=bX(yX(n,`styling`,`style`)),s=bX(yX(n,`layout`,`region`)),c=yX(n,`body`,`[begin]`);return[].map.call(c,e=>{let n=xX(e,a);if(!n||!e.hasAttribute(`begin`))return null;let r=TX(e.getAttribute(`begin`),i),c=TX(e.getAttribute(`dur`),i),l=TX(e.getAttribute(`end`),i);if(r===null)throw wX(e);if(l===null){if(c===null)throw wX(e);l=r+c}let u=new ZY(r-t,l-t,n);u.id=uX(u.startTime,u.endTime,u.text);let d=s[e.getAttribute(`region`)],f=o[e.getAttribute(`style`)],p=SX(d,f,o),{textAlign:m}=p;if(m){let e=gX[m];e&&(u.lineAlign=e),u.align=m}return hB(u,p),u}).filter(e=>e!==null)}function yX(e,t,n){let r=e.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function bX(e){return e.reduce((e,t)=>{let n=t.getAttribute(`xml:id`);return n&&(e[n]=t),e},{})}function xX(e,t){return[].slice.call(e.childNodes).reduce((e,n,r)=>{var i;return n.nodeName===`br`&&r?e+`
73
- `:(i=n.childNodes)!=null&&i.length?xX(n,t):t?e+n.textContent.trim().replace(/\s+/g,` `):e+n.textContent},``)}function SX(e,t,n){let r=`http://www.w3.org/ns/ttml#styling`,i=null,a=[`displayAlign`,`textAlign`,`color`,`backgroundColor`,`fontSize`,`fontFamily`],o=e!=null&&e.hasAttribute(`style`)?e.getAttribute(`style`):null;return o&&n.hasOwnProperty(o)&&(i=n[o]),a.reduce((n,a)=>{let o=CX(t,r,a)||CX(e,r,a)||CX(i,r,a);return o&&(n[a]=o),n},{})}function CX(e,t,n){return e&&e.hasAttributeNS(t,n)?e.getAttributeNS(t,n):null}function wX(e){return Error(`Could not parse ttml timestamp ${e}`)}function TX(e,t){if(!e)return null;let n=$Y(e);return n===null&&(mX.test(e)?n=EX(e,t):hX.test(e)&&(n=DX(e,t))),n}function EX(e,t){let n=mX.exec(e),r=(n[4]|0)+(n[5]|0)/t.subFrameRate;return(n[1]|0)*3600+(n[2]|0)*60+(n[3]|0)+r/t.frameRate}function DX(e,t){let n=hX.exec(e),r=Number(n[1]);switch(n[2]){case`h`:return r*3600;case`m`:return r*60;case`ms`:return r*1e3;case`f`:return r/t.frameRate;case`t`:return r/t.tickRate}return r}var OX=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,n){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},kX=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=NX(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on(Z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Z.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(Z.FRAG_LOADING,this.onFragLoading,this),e.on(Z.FRAG_LOADED,this.onFragLoaded,this),e.on(Z.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(Z.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(Z.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(Z.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(Z.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){let{hls:e}=this;e.off(Z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Z.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(Z.FRAG_LOADING,this.onFragLoading,this),e.off(Z.FRAG_LOADED,this.onFragLoaded,this),e.off(Z.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(Z.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(Z.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(Z.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(Z.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){let e=new OX(this,`textTrack1`),t=new OX(this,`textTrack2`),n=new OX(this,`textTrack3`),r=new OX(this,`textTrack4`);this.cea608Parser1=new qY(1,e,t),this.cea608Parser2=new qY(3,n,r)}addCues(e,t,n,r,i){let a=!1;for(let e=i.length;e--;){let r=i[e],o=MX(r[0],r[1],t,n);if(o>=0&&(r[0]=Math.min(r[0],t),r[1]=Math.max(r[1],n),a=!0,o/(n-t)>.5))return}if(a||i.push([t,n]),this.config.renderTextTracksNatively){let i=this.captionsTracks[e];this.Cues.newCue(i,t,n,r)}else{let i=this.Cues.newCue(null,t,n,r);this.hls.trigger(Z.CUES_PARSED,{type:`captions`,cues:i,track:e})}}onInitPtsFound(e,{frag:t,id:n,initPTS:r,timescale:i,trackId:a}){let{unparsedVttFrags:o}=this;n===Q.MAIN&&(this.initPTS[t.cc]={baseTime:r,timescale:i,trackId:a}),o.length&&(this.unparsedVttFrags=[],o.forEach(e=>{this.initPTS[e.frag.cc]?this.onFragLoaded(Z.FRAG_LOADED,e):this.hls.trigger(Z.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e.frag,error:Error(`Subtitle discontinuity domain does not match main`)})}))}getExistingTrack(e,t){let{media:n}=this;if(n)for(let r=0;r<n.textTracks.length;r++){let i=n.textTracks[r];if(jX(i,{name:e,lang:t,characteristics:`transcribes-spoken-dialog,describes-music-and-sound`}))return i}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;let{captionsProperties:t,captionsTracks:n,media:r}=this,{label:i,languageCode:a}=t[e],o=this.getExistingTrack(i,a);if(o)n[e]=o,rY(n[e]),tY(n[e],r);else{let t=this.createTextTrack(`captions`,i,a);t&&(t[e]=!0,n[e]=t)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;let t=this.captionsProperties[e];if(!t)return;let n={_id:e,label:t.label,kind:`captions`,default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=n,this.hls.trigger(Z.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[n]})}createTextTrack(e,t,n){let r=this.media;if(r)return r.addTextTrack(e,t,n)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){let n=!!t.transferMedia;if(this.media=null,n)return;let{captionsTracks:r}=this;Object.keys(r).forEach(e=>{rY(r[e]),delete r[e]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=NX(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){let{media:e}=this;if(!e)return;let t=e.textTracks;if(t)for(let e=0;e<t.length;e++)rY(t[e])}onSubtitleTracksUpdated(e,t){let n=t.subtitleTracks||[],r=n.some(e=>e.textCodec===pX);if(this.config.enableWebVTT||r&&this.config.enableIMSC1){if(dq(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){let e=this.media,t=e?sY(e.textTracks):null;if(this.tracks.forEach((e,n)=>{let r;if(t){let n=null;for(let r=0;r<t.length;r++)if(t[r]&&jX(t[r],e)){n=t[r],t[r]=null;break}n&&(r=n)}if(r)rY(r);else{let t=AX(e);r=this.createTextTrack(t,e.name,e.lang),r&&(r.mode=`disabled`)}r&&this.textTracks.push(r)}),t!=null&&t.length){let e=t.filter(e=>e!==null).map(e=>e.label);e.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${e.join(`, `)}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){let e=this.tracks.map(e=>({label:e.name,kind:e.type.toLowerCase(),default:e.default,subtitleTrack:e}));this.hls.trigger(Z.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:e})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(e=>{let t=/(?:CC|SERVICE)([1-4])/.exec(e.instreamId);if(!t)return;let n=`textTrack${t[1]}`,r=this.captionsProperties[n];r&&(r.label=e.name,e.lang&&(r.languageCode=e.lang),r.media=e)})}closedCaptionsForLevel(e){return this.hls.levels[e.level]?.attrs[`CLOSED-CAPTIONS`]}onFragLoading(e,t){if(this.enabled&&t.frag.type===Q.MAIN){let{cea608Parser1:e,cea608Parser2:n,lastSn:r}=this,{cc:i,sn:a}=t.frag,o=t.part?.index??-1;e&&n&&(a!==r+1||a===r&&o!==this.lastPartIndex+1||i!==this.lastCc)&&(e.reset(),n.reset()),this.lastCc=i,this.lastSn=a,this.lastPartIndex=o}}onFragLoaded(e,t){let{frag:n,payload:r}=t;if(n.type===Q.SUBTITLE)if(r.byteLength){let e=n.decryptdata,i=`stats`in t;if(e==null||!e.encrypted||i){let e=this.tracks[n.level],i=this.vttCCs;i[n.cc]||(i[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),e&&e.textCodec===pX?this._parseIMSC1(n,r):this._parseVTTs(t)}}else this.hls.trigger(Z.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:Error(`Empty subtitle payload`)})}_parseIMSC1(e,t){let n=this.hls;_X(t,this.initPTS[e.cc],t=>{this._appendCues(t,e.level),n.trigger(Z.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},t=>{n.logger.log(`Failed to parse IMSC1: ${t}`),n.trigger(Z.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:t})})}_parseVTTs(e){var t;let{frag:n,payload:r}=e,{initPTS:i,unparsedVttFrags:a}=this,o=i.length-1;if(!i[n.cc]&&o===-1){a.push(e);return}let s=this.hls;fX((t=n.initSegment)!=null&&t.data?vV(n.initSegment.data,new Uint8Array(r)).buffer:r,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,e=>{this._appendCues(e,n.level),s.trigger(Z.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},t=>{let i=t.message===`Missing initPTS for VTT MPEGTS`;i?a.push(e):this._fallbackToIMSC1(n,r),s.logger.log(`Failed to parse VTT cue: ${t}`),!(i&&o>n.cc)&&s.trigger(Z.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:t})})}_fallbackToIMSC1(e,t){let n=this.tracks[e.level];n.textCodec||_X(t,this.initPTS[e.cc],()=>{n.textCodec=pX,this._parseIMSC1(e,t)},()=>{n.textCodec=`wvtt`})}_appendCues(e,t){let n=this.hls;if(this.config.renderTextTracksNatively){let n=this.textTracks[t];if(!n||n.mode===`disabled`)return;e.forEach(e=>nY(n,e))}else{let r=this.tracks[t];if(!r)return;let i=r.default?`default`:`subtitles`+t;n.trigger(Z.CUES_PARSED,{type:`subtitles`,cues:e,track:i})}}onFragDecrypted(e,t){let{frag:n}=t;n.type===Q.SUBTITLE&&this.onFragLoaded(Z.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;let{frag:n,samples:r}=t;if(!(n.type===Q.MAIN&&this.closedCaptionsForLevel(n)===`NONE`))for(let e=0;e<r.length;e++){let t=r[e].bytes;if(t){this.cea608Parser1||this.initCea608Parsers();let n=this.extractCea608Data(t);this.cea608Parser1.addData(r[e].pts,n[0]),this.cea608Parser2.addData(r[e].pts,n[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:n,endOffsetSubtitles:r,type:i}){let{media:a}=this;if(!(!a||a.currentTime<n)){if(!i||i===`video`){let{captionsTracks:e}=this;Object.keys(e).forEach(r=>iY(e[r],t,n))}if(this.config.renderTextTracksNatively&&t===0&&r!==void 0){let{textTracks:e}=this;Object.keys(e).forEach(n=>iY(e[n],t,r))}}}extractCea608Data(e){let t=[[],[]],n=e[0]&31,r=2;for(let i=0;i<n;i++){let n=e[r++],i=127&e[r++],a=127&e[r++];if(!(i===0&&a===0)&&4&n){let e=3&n;(e===0||e===1)&&(t[e].push(i),t[e].push(a))}}return t}};function AX(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?`captions`:`subtitles`}function jX(e,t){return!!e&&e.kind===AX(t)&&pq(t,e)}function MX(e,t,n,r){return Math.min(t,r)-Math.max(e,n)}function NX(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var PX=/\s/,FX={newCue(e,t,n,r){let i=[],a,o,s,c,l,u=self.VTTCue||self.TextTrackCue;for(let f=0;f<r.rows.length;f++)if(a=r.rows[f],s=!0,c=0,l=``,!a.isEmpty()){var d;for(let e=0;e<a.chars.length;e++)PX.test(a.chars[e].uchar)&&s?c++:(l+=a.chars[e].uchar,s=!1);a.cueStartTime=t,t===n&&(n+=1e-4),c>=16?c--:c++;let r=aX(l.trim()),p=uX(t,n,r);e!=null&&(d=e.cues)!=null&&d.getCueById(p)||(o=new u(t,n,r),o.id=p,o.line=f+1,o.align=`left`,o.position=10+Math.min(80,Math.floor(c*8/32)*10),i.push(o))}return e&&i.length&&(i.sort((e,t)=>e.line===`auto`||t.line===`auto`?0:e.line>8&&t.line>8?t.line-e.line:e.line-t.line),i.forEach(t=>nY(e,t))),i}};function IX(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var LX=/(\d+)-(\d+)\/(\d+)/,RX=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||HX,this.controller=new self.AbortController,this.stats=new BB}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,n){let r=this.stats;if(r.loading.start)throw Error(`Loader can only be used once.`);r.loading.start=self.performance.now();let i=zX(e,this.controller.signal),a=e.responseType===`arraybuffer`,o=a?`byteLength`:`length`,{maxTimeToFirstByteMs:s,maxLoadTimeMs:c}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=n,this.request=this.fetchSetup(e,i),self.clearTimeout(this.requestTimeout),t.timeout=s&&J(s)?s:c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},t.timeout),(rq(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(n=>{this.response=this.loader=n;let i=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(r,e,this.response))},c-(i-r.loading.start)),!n.ok){let{status:e,statusText:t}=n;throw new UX(t||`fetch, bad network response`,e,n)}r.loading.first=i,r.total=VX(n.headers)||r.total;let o=this.callbacks?.onProgress;return o&&J(t.highWaterMark)?this.loadProgressively(n,r,e,t.highWaterMark,o):a?n.arrayBuffer():e.responseType===`json`?n.json():n.text()}).then(n=>{var i;let a=this.response;if(!a)throw Error(`loader destroyed`);self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);let s=n[o];s&&(r.loaded=r.total=s);let c={url:a.url,data:n,code:a.status},l=this.callbacks?.onProgress;l&&!J(t.highWaterMark)&&l(r,e,n,a),(i=this.callbacks)==null||i.onSuccess(c,r,e,a)}).catch(t=>{var n;if(self.clearTimeout(this.requestTimeout),r.aborted)return;let i=t&&t.code||0,a=t?t.message:null;(n=this.callbacks)==null||n.onError({code:i,text:a},e,t?t.details:null,r)})}getCacheAge(){let e=null;if(this.response){let t=this.response.headers.get(`age`);e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,n,r=0,i){let a=new $W,o=e.body.getReader(),s=()=>o.read().then(o=>{if(o.done)return a.dataLength&&i(t,n,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));let c=o.value,l=c.length;return t.loaded+=l,l<r||a.dataLength?(a.push(c),a.dataLength>=r&&i(t,n,a.flush().buffer,e)):i(t,n,c.buffer,e),s()}).catch(()=>Promise.reject());return s()}};function zX(e,t){let n={method:`GET`,mode:`cors`,credentials:`same-origin`,signal:t,headers:new self.Headers(hB({},e.headers))};return e.rangeEnd&&n.headers.set(`Range`,`bytes=`+e.rangeStart+`-`+String(e.rangeEnd-1)),n}function BX(e){let t=LX.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function VX(e){let t=e.get(`Content-Range`);if(t){let e=BX(t);if(J(e))return e}let n=e.get(`Content-Length`);if(n)return parseInt(n)}function HX(e,t){return new self.Request(e.url,t)}var UX=class extends Error{constructor(e,t,n){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=n}},WX=/^age:\s*[\d.]+\s*$/im,GX=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new BB,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){let e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,n){if(this.stats.loading.start)throw Error(`Loader can only be used once.`);this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=n,this.loadInternal()}loadInternal(){let{config:e,context:t}=this;if(!e||!t)return;let n=this.loader=new self.XMLHttpRequest,r=this.stats;r.loading.first=0,r.loaded=0,r.aborted=!1;let i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return i(n,t.url)}).catch(e=>{if(!(this.loader!==n||this.stats.aborted))return n.open(`GET`,t.url,!0),i(n,t.url)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,t,e)}).catch(e=>{var i;(i=this.callbacks)==null||i.onError({code:n.status,text:e.message},t,n,r)}):this.openAndSendXhr(n,t,e)}openAndSendXhr(e,t,n){e.readyState||e.open(`GET`,t.url,!0);let r=t.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:a}=n.loadPolicy;if(r)for(let t in r)e.setRequestHeader(t,r[t]);t.rangeEnd&&e.setRequestHeader(`Range`,`bytes=`+t.rangeStart+`-`+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),n.timeout=i&&J(i)?i:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){let{context:e,loader:t,stats:n}=this;if(!e||!t)return;let r=t.readyState,i=this.config;if(!n.aborted&&r>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(n.loading.first-n.loading.start)))),r===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;let r=t.status,s=t.responseType===`text`?t.responseText:null;if(r>=200&&r<300){let i=s??t.response;if(i!=null){var a;n.loading.end=Math.max(self.performance.now(),n.loading.first),n.loaded=n.total=t.responseType===`arraybuffer`?i.byteLength:i.length,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first);let o=this.callbacks?.onProgress;o&&o(n,e,i,t);let s={url:t.responseURL,data:i,code:r};(a=this.callbacks)==null||a.onSuccess(s,n,e,t);return}}let c=i.loadPolicy.errorRetry,l=n.retry;if(GH(c,l,!1,{url:e.url,data:void 0,code:r}))this.retry(c);else{var o;OB.error(`${r} while loading ${e.url}`),(o=this.callbacks)==null||o.onError({code:r,text:t.statusText},e,t,n)}}}loadtimeout(){if(!this.config)return;let e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(GH(e,t,!0))this.retry(e);else{OB.warn(`timeout while loading ${this.context?.url}`);let e=this.callbacks;e&&(this.abortInternal(),e.onTimeout(this.stats,this.context,this.loader))}}retry(e){let{context:t,stats:n}=this;this.retryDelay=UH(e,n.retry),n.retry++,OB.warn(`${status?`HTTP Status `+status:`Timeout`} while loading ${t?.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){let t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&WX.test(this.loader.getAllResponseHeaders())){let t=this.loader.getResponseHeader(`age`);e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&RegExp(`^${e}:\\s*[\\d.]+\\s*$`,`im`).test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},KX=_B(_B({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:1/0,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:`edge`,liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:GX,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:jH,bufferController:yq,capLevelController:Cq,errorController:XH,fpsController:eY,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:ZU,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:`linear`}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},qX()),{},{subtitleStreamController:kY,subtitleTrackController:cY,timelineController:kX,audioStreamController:lq,audioTrackController:mq,emeController:YJ,cmcdController:WJ,contentSteeringController:KJ,interstitialsController:DY});function qX(){return{cueHandler:FX,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:`English`,captionsTextTrack1LanguageCode:`en`,captionsTextTrack2Label:`Spanish`,captionsTextTrack2LanguageCode:`es`,captionsTextTrack3Label:`Unknown CC`,captionsTextTrack3LanguageCode:``,captionsTextTrack4Label:`Unknown CC`,captionsTextTrack4LanguageCode:``,renderTextTracksNatively:!0}}function JX(e,t,n){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw Error(`Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration`);if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw Error(`Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"`);if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw Error(`Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"`);let r=YX(e),i=[`manifest`,`level`,`frag`],a=[`TimeOut`,`MaxRetry`,`RetryDelay`,`MaxRetryTimeout`];return i.forEach(e=>{let i=`${e===`level`?`playlist`:e}LoadPolicy`,o=t[i]===void 0,s=[];a.forEach(n=>{let a=`${e}Loading${n}`,c=t[a];if(c!==void 0&&o){s.push(a);let e=r[i].default;switch(t[i]={default:e},n){case`TimeOut`:e.maxLoadTimeMs=c,e.maxTimeToFirstByteMs=c;break;case`MaxRetry`:e.errorRetry.maxNumRetry=c,e.timeoutRetry.maxNumRetry=c;break;case`RetryDelay`:e.errorRetry.retryDelayMs=c,e.timeoutRetry.retryDelayMs=c;break;case`MaxRetryTimeout`:e.errorRetry.maxRetryDelayMs=c,e.timeoutRetry.maxRetryDelayMs=c;break}}}),s.length&&n.warn(`hls.js config: "${s.join(`", "`)}" setting(s) are deprecated, use "${i}": ${_H(t[i])}`)}),_B(_B({},r),t)}function YX(e){return e&&typeof e==`object`?Array.isArray(e)?e.map(YX):Object.keys(e).reduce((t,n)=>(t[n]=YX(e[n]),t),{}):e}function XX(e,t){let n=e.loader;n!==RX&&n!==GX?(t.log(`[config]: Custom loader detected, cannot enable progressive streaming`),e.progressive=!1):IX()&&(e.loader=RX,e.progressive=!0,e.enableSoftwareAES=!0,t.log(`[config]: Progressive streaming enabled, using FetchLoader`))}var ZX=2,QX=.1,$X=.05,eZ=100,tZ=class extends _U{constructor(e,t){super(`gap-controller`,e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var e;(e=this.media)!=null&&e.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{this.hls&&(this.ended=this.media?.currentTime||1,this.hls.trigger(Z.MEDIA_ENDED,{stalled:!1}))},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){let{hls:e}=this;e&&(e.on(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Z.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Z.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(eZ),this.mediaSource=t.mediaSource;let n=this.media=t.media;JW(n,`playing`,this.onMediaPlaying),JW(n,`waiting`,this.onMediaWaiting),JW(n,`ended`,this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();let{media:n}=this;n&&(YW(n,`playing`,this.onMediaPlaying),YW(n,`waiting`,this.onMediaWaiting),YW(n,`ended`,this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;let t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){let n=this.hls?.config;if(!n)return;let r=this.media;if(!r)return;let{seeking:i}=r,a=this.seeking&&!i,o=!this.seeking&&i,s=r.paused&&!i||r.ended||r.playbackRate===0;if(this.seeking=i,e!==t){t&&(this.ended=0),this.moved=!0,i||(this.nudgeRetry=0,n.nudgeOnVideoHole&&!s&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(o||a){a&&this.stallResolved(e);return}if(s){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&r.ended&&this.hls&&(this.ended=e||1,this.hls.trigger(Z.MEDIA_ENDED,{stalled:!1}));return}if(!xU.getBuffered(r).length){this.nudgeRetry=0;return}let c=xU.bufferInfo(r,e,0),l=c.nextStart||0,u=this.fragmentTracker;if(i&&u&&this.hls){let t=nZ(this.hls.inFlightFragments,e),n=c.len>ZX,r=!l||t||l-e>ZX&&!u.getPartialFragment(e);if(n||r)return;this.moved=!1}let d=this.hls?.latestLevelDetails;if(!this.moved&&this.stalled!==null&&u){if(!(c.len>0)&&!l)return;let t=Math.max(l,c.start||0)-e,n=d!=null&&d.live?d.targetduration*2:ZX,i=iZ(e,u);if(t>0&&(t<=n||i)){r.paused||this._trySkipBufferHole(i);return}}let f=n.detectStallWithCurrentTimeMs,p=self.performance.now(),m=this.waiting,h=this.stalled;if(h===null)if(m>0&&p-m<f)h=this.stalled=m;else{this.stalled=p;return}let g=p-h;if(!i&&(g>=f||m)&&this.hls){if(this.mediaSource?.readyState===`ended`&&!(d!=null&&d.live)&&Math.abs(e-(d?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger(Z.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(c),!this.media||!this.hls)return}let _=xU.bufferInfo(r,e,n.maxBufferHole);this._tryFixBufferStall(_,g,e)}stallResolved(e){let t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){let n=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(n)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(Z.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var n;let r=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(n=this.buffered.audio)!=null&&n.length&&r&&r.length>1&&e>r.end(0)){let n=xU.bufferedInfo(xU.timeRangesToArray(this.buffered.audio),e,0);if(n.len>1&&t>=n.start){let n=xU.timeRangesToArray(r),i=xU.bufferedInfo(n,t,0).bufferedIndex;if(i>-1&&i<n.length-1){let t=xU.bufferedInfo(n,e,0).bufferedIndex,r=n[i].end,a=n[i+1].start;if((t===-1||t>i)&&a-r<1&&e-r<2){let n=Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${r} -> ${a} buffered index: ${t}`);this.warn(n.message),this.media.currentTime+=1e-6;let i=iZ(e,this.fragmentTracker);i&&`fragment`in i?i=i.fragment:i||=void 0;let o=xU.bufferInfo(this.media,e,0);this.hls.trigger(Z.ERROR,{type:Y.MEDIA_ERROR,details:X.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:n,reason:n.message,frag:i,buffer:o.len,bufferInfo:o})}}}}}_tryFixBufferStall(e,t,n){let{fragmentTracker:r,media:i}=this,a=this.hls?.config;if(!i||!r||!a)return;let o=this.hls?.latestLevelDetails,s=iZ(n,r);if((s||o!=null&&o.live&&n<o.fragmentStart)&&(this._trySkipBufferHole(s)||!this.media))return;let c=e.buffered,l=this.adjacentTraversal(e,n);(c&&c.length>1&&e.len>a.maxBufferHole||e.nextStart&&(e.nextStart-n<a.maxBufferHole||l))&&(t>a.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn(`Trying to nudge playhead over buffer-hole`),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){let n=this.fragmentTracker,r=e.nextStart;if(n&&r){let e=n.getFragAtPos(t,Q.MAIN),i=n.getFragAtPos(r,Q.MAIN);if(e&&i)return i.sn-e.sn<2}return!1}_reportStall(e){let{hls:t,media:n,stallReported:r,stalled:i}=this;if(!r&&i!==null&&n&&t){this.stallReported=!0;let r=Error(`Playback stalling at @${n.currentTime} due to low buffer (${_H(e)})`);this.warn(r.message),t.trigger(Z.ERROR,{type:Y.MEDIA_ERROR,details:X.BUFFER_STALLED_ERROR,fatal:!1,error:r,buffer:e.len,bufferInfo:e,stalled:{start:i}})}}_trySkipBufferHole(e){let{fragmentTracker:t,media:n}=this,r=this.hls?.config;if(!n||!t||!r)return 0;let i=n.currentTime,a=xU.bufferInfo(n,i,0),o=i<a.start?a.start:a.nextStart;if(o&&this.hls){let c=a.len<=r.maxBufferHole,l=a.len>0&&a.len<1&&n.readyState<3,u=o-i;if(u>0&&(c||l)){if(u>r.maxBufferHole){let n=!1;if(i===0){let e=t.getAppendedFrag(0,Q.MAIN);e&&o<e.end&&(n=!0)}if(!n&&e){var s;if(!((s=this.hls.loadLevelObj)!=null&&s.details)||nZ(this.hls.inFlightFragments,o))return 0;let n=!1,r=e.end;for(;r<o;){let e=iZ(r,t);if(e)r+=e.duration;else{n=!0;break}}if(n)return 0}}let c=Math.max(o+$X,i+QX);if(this.warn(`skipping hole, adjusting currentTime from ${i} to ${c}`),this.moved=!0,n.currentTime=c,!(e!=null&&e.gap)){let t=Error(`fragment loaded with buffer holes, seeking from ${i} to ${c}`),n={type:Y.MEDIA_ERROR,details:X.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:t,reason:t.message,buffer:a.len,bufferInfo:a};e&&(`fragment`in e?n.part=e:n.frag=e),this.hls.trigger(Z.ERROR,n)}return c}}return 0}_tryNudgeBuffer(e){let{hls:t,media:n,nudgeRetry:r}=this,i=t?.config;if(!n||!i)return 0;let a=n.currentTime;if(this.nudgeRetry++,r<i.nudgeMaxRetry){let o=a+(r+1)*i.nudgeOffset,s=Error(`Nudging 'currentTime' from ${a} to ${o}`);this.warn(s.message),n.currentTime=o,t.trigger(Z.ERROR,{type:Y.MEDIA_ERROR,details:X.BUFFER_NUDGE_ON_STALL,error:s,fatal:!1,buffer:e.len,bufferInfo:e})}else{let n=Error(`Playhead still not moving while enough data buffered @${a} after ${i.nudgeMaxRetry} nudges`);this.error(n.message),t.trigger(Z.ERROR,{type:Y.MEDIA_ERROR,details:X.BUFFER_STALLED_ERROR,error:n,fatal:!0,buffer:e.len,bufferInfo:e})}}};function nZ(e,t){let n=rZ(e.main);if(n&&n.start<=t)return n;let r=rZ(e.audio);return r&&r.start<=t?r:null}function rZ(e){if(!e)return null;switch(e.state){case $.IDLE:case $.STOPPED:case $.ENDED:case $.ERROR:return null}return e.frag}function iZ(e,t){return t.getAppendedFrag(e,Q.MAIN)||t.getPartialFragment(e)}var aZ=.25;function oZ(){if(!(typeof self>`u`))return self.VTTCue||self.TextTrackCue}function sZ(e,t,n,r,i){let a=new e(t,n,``);try{a.value=r,i&&(a.type=i)}catch{a=new e(t,n,_H(i?_B({type:i},r):r))}return a}var cZ=(()=>{let e=oZ();try{e&&new e(0,1/0,``)}catch{return Number.MAX_VALUE}return 1/0})(),lZ=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger(Z.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){let{hls:e}=this;e&&(e.on(Z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(Z.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(Z.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Z.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){let{hls:e}=this;e&&(e.off(Z.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(Z.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(Z.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Z.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){this.media=t.media,t.overrides?.cueRemoval===!1&&(this.removeCues=!1)}onMediaAttached(){let e=this.hls?.latestLevelDetails;e&&this.updateDateRangeCues(e)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&=(this.removeCues&&rY(this.id3Track,this.onEventCueEnter),null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){let t=this.getID3Track(e.textTracks);return t.mode=`hidden`,t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){let n=e[t];if(n.kind===`metadata`&&n.label===`id3`)return tY(n,this.media),n}return this.media.addTextTrack(`metadata`,`id3`)}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;let{enableEmsgMetadataCues:n,enableID3MetadataCues:r}=this.hls.config;if(!n&&!r)return;let{samples:i}=t;this.id3Track||=this.createTrack(this.media);let a=oZ();if(a)for(let e=0;e<i.length;e++){let t=i[e].type;if(t===GG.emsg&&!n||!r)continue;let o=VG(i[e].data),s=i[e].pts,c=s+i[e].duration;c>cZ&&(c=cZ),c-s<=0&&(c=s+aZ);for(let e=0;e<o.length;e++){let n=o[e];if(!HG(n)){this.updateId3CueEnds(s,t);let e=sZ(a,s,c,n,t);e&&this.id3Track.addCue(e)}}}}updateId3CueEnds(e,t){let n=this.id3Track?.cues;if(n)for(let r=n.length;r--;){let i=n[r];i.type===t&&i.startTime<e&&i.endTime===cZ&&(i.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:n,type:r}){let{id3Track:i,hls:a}=this;if(!a)return;let{config:{enableEmsgMetadataCues:o,enableID3MetadataCues:s}}=a;if(i&&(o||s)){let e;e=r===`audio`?e=>e.type===GG.audioId3&&s:r===`video`?e=>e.type===GG.emsg&&o:e=>e.type===GG.audioId3&&s||e.type===GG.emsg&&o,iY(i,t,n,e)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;let{assetPlayerId:n,timelineOffset:r,enableDateRangeMetadataCues:i,interstitialsController:a}=this.hls.config;if(!i)return;let o=oZ();if(n&&r&&!a){let{fragmentStart:t,fragmentEnd:r}=e,i=this.assetCue;i?(i.startTime=t,i.endTime=r):o&&(i=this.assetCue=sZ(o,t,r,{assetPlayerId:this.hls.config.assetPlayerId},`hlsjs.interstitial.asset`),i&&(i.id=n,this.id3Track||=this.createTrack(this.media),this.id3Track.addCue(i),i.addEventListener(`enter`,this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;let{id3Track:s}=this,{dateRanges:c}=e,l=Object.keys(c),u=this.dateRangeCuesAppended;if(s&&t){var d;if((d=s.cues)!=null&&d.length){let e=Object.keys(u).filter(e=>!l.includes(e));for(let t=e.length;t--;){let n=e[t],r=u[n]?.cues;delete u[n],r&&Object.keys(r).forEach(e=>{let t=r[e];if(t){t.removeEventListener(`enter`,this.onEventCueEnter);try{s.removeCue(t)}catch{}}})}}else u=this.dateRangeCuesAppended={}}let f=e.fragments[e.fragments.length-1];if(!(l.length===0||!J(f?.programDateTime))){this.id3Track||=this.createTrack(this.media);for(let e=0;e<l.length;e++){let t=l[e],n=c[t],r=n.startTime,i=u[t],s=i?.cues||{},d=i?.durationKnown||!1,f=cZ,{duration:p,endDate:m}=n;if(m&&p!==null)f=r+p,d=!0;else if(n.endOnNext&&!d){let e=l.reduce((e,t)=>{if(t!==n.id){let r=c[t];if(r.class===n.class&&r.startDate>n.startDate&&(!e||n.startDate<e.startDate))return r}return e},null);e&&(f=e.startTime,d=!0)}let h=Object.keys(n.attr);for(let e=0;e<h.length;e++){let c=h[e];if(!jU(c))continue;let l=s[c];if(l)d&&!(i!=null&&i.durationKnown)?l.endTime=f:Math.abs(l.startTime-r)>.01&&(l.startTime=r,l.endTime=f);else if(o){let e=n.attr[c];MU(c)&&(e=PB(e));let i=sZ(o,r,f,{key:c,data:e},GG.dateRange);i&&(i.id=t,this.id3Track.addCue(i),s[c]=i,a&&(c===`X-ASSET-LIST`||c===`X-ASSET-URL`)&&i.addEventListener(`enter`,this.onEventCueEnter))}}u[t]={cues:s,dateRange:n,durationKnown:d}}}}},uZ=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{let{media:e}=this,t=this.levelDetails;if(!e||!t)return;this.currentTime=e.currentTime;let n=this.computeLatency();if(n===null)return;this._latency=n;let{lowLatencyMode:r,maxLiveSyncPlaybackRate:i}=this.config;if(!r||i===1||!t.live)return;let a=this.targetLatency;if(a===null)return;let o=n-a;if(o<Math.min(this.maxLatency,a+t.targetduration)&&o>.05&&this.forwardBufferLength>1){let t=Math.min(2,Math.max(1,i)),n=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20,r=Math.min(t,Math.max(1,n));this.changeMediaPlaybackRate(e,r)}else e.playbackRate!==1&&e.playbackRate!==0&&this.changeMediaPlaybackRate(e,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){return this.hls?.latestLevelDetails||null}get latency(){return this._latency||0}get maxLatency(){let{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;let t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){let e=this.levelDetails;if(e===null||this.hls===null)return null;let{holdBack:t,partHoldBack:n,targetduration:r}=e,{liveSyncDuration:i,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,s=this.hls.userConfig,c=o&&n||t;(this._targetLatencyUpdated||s.liveSyncDuration||s.liveSyncDurationCount||c===0)&&(c=i===void 0?a*r:i);let l=r;return c+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,l)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){let e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;let n=this.levelDetails;if(n===null)return null;let r=n.edge,i=e-t-this.edgeStalled,a=r-n.totalduration,o=r-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(a,i),o)}get drift(){let e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){let e=this.levelDetails;if(e===null)return 0;let t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){let{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;let n=e.buffered.length;return(n?e.buffered.end(n-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){let{hls:e}=this;e&&(e.on(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(Z.ERROR,this.onError,this))}unregisterListeners(){let{hls:e}=this;e&&(e.off(Z.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(Z.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(Z.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener(`timeupdate`,this.onTimeupdate)}onMediaDetaching(){this.media&&=(this.media.removeEventListener(`timeupdate`,this.onTimeupdate),null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener(`timeupdate`,this.onTimeupdate)}onError(e,t){var n;t.details===X.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(n=this.levelDetails)!=null&&n.live&&this.hls.logger.warn(`[latency-controller]: Stall detected, adjusting target latency`))}changeMediaPlaybackRate(e,t){var n;e.playbackRate!==t&&((n=this.hls)==null||n.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${this.targetLatency?.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){let e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){let e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},dZ=class extends uq{constructor(e,t){super(e,`level-controller`),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){let{hls:e}=this;e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(Z.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Z.FRAG_BUFFERED,this.onFragBuffered,this),e.on(Z.ERROR,this.onError,this)}_unregisterListeners(){let{hls:e}=this;e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(Z.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Z.FRAG_BUFFERED,this.onFragBuffered,this),e.off(Z.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){let n=this.hls.config.preferManagedMediaSource,r=[],i={},a={},o=!1,s=!1,c=!1;t.levels.forEach(e=>{let t=e.attrs,{audioCodec:l,videoCodec:u}=e;l&&(e.audioCodec=l=BV(l,n)||void 0),u&&=e.videoCodec=WV(u);let{width:d,height:f,unknownCodecs:p}=e,m=p?.length||0;if(o||=!!(d&&f),s||=!!u,c||=!!l,m||l&&!this.isAudioSupported(l)||u&&!this.isVideoSupported(u)){this.log(`Some or all CODECS not supported "${t.CODECS}"`);return}let{CODECS:h,"FRAME-RATE":g,"HDCP-LEVEL":_,"PATHWAY-ID":v,RESOLUTION:y,"VIDEO-RANGE":b}=t,x=`${`${v||`.`}-`}${e.bitrate}-${y}-${g}-${h}-${b}-${_}`;if(!i[x]){let t=this.createLevel(e);i[x]=t,a[x]=1,r.push(t)}else if(i[x].uri!==e.url&&!e.attrs[`PATHWAY-ID`]){let t=a[x]+=1;e.attrs[`PATHWAY-ID`]=Array(t+1).join(`.`);let n=this.createLevel(e);i[x]=n,r.push(n)}else i[x].addGroupId(`audio`,t.AUDIO),i[x].addGroupId(`text`,t.SUBTITLES)}),this.filterAndSortMediaOptions(r,t,o,s,c)}createLevel(e){let t=new fH(e),n=e.supplemental;if(n!=null&&n.videoCodec&&!this.isVideoSupported(n.videoCodec)){let e=Error(`SUPPLEMENTAL-CODECS not supported "${n.videoCodec}"`);this.log(e.message),t.supportedResult=ZV(e,[])}return t}isAudioSupported(e){return MV(e,`audio`,this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return MV(e,`video`,this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,n,r,i){let a=[],o=[],s=e,c=t.stats?.parsing||{};if((n||r)&&i&&(s=s.filter(({videoCodec:e,videoRange:t,width:n,height:r})=>(!!e||!!(n&&r))&&cH(t))),s.length===0){Promise.resolve().then(()=>{if(this.hls){let e=`no level with compatible codecs found in manifest`,n=e;t.levels.length&&(n=`one or more CODECS in variant not supported: ${_H(t.levels.map(e=>e.attrs.CODECS).filter((e,t,n)=>n.indexOf(e)===t))}`,this.warn(n),e+=` (${n})`);let r=Error(e);this.hls.trigger(Z.ERROR,{type:Y.MEDIA_ERROR,details:X.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:r,reason:n})}}),c.end=performance.now();return}t.audioTracks&&(a=t.audioTracks.filter(e=>!e.audioCodec||this.isAudioSupported(e.audioCodec)),fZ(a)),t.subtitles&&(o=t.subtitles,fZ(o));let l=s.slice(0);s.sort((e,t)=>{if(e.attrs[`HDCP-LEVEL`]!==t.attrs[`HDCP-LEVEL`])return(e.attrs[`HDCP-LEVEL`]||``)>(t.attrs[`HDCP-LEVEL`]||``)?1:-1;if(n&&e.height!==t.height)return e.height-t.height;if(e.frameRate!==t.frameRate)return e.frameRate-t.frameRate;if(e.videoRange!==t.videoRange)return sH.indexOf(e.videoRange)-sH.indexOf(t.videoRange);if(e.videoCodec!==t.videoCodec){let n=FV(e.videoCodec),r=FV(t.videoCodec);if(n!==r)return r-n}if(e.uri===t.uri&&e.codecSet!==t.codecSet){let n=IV(e.codecSet),r=IV(t.codecSet);if(n!==r)return r-n}return e.averageBitrate===t.averageBitrate?0:e.averageBitrate-t.averageBitrate});let u=l[0];if(this.steering&&(s=this.steering.filterParsedLevels(s),s.length!==l.length)){for(let e=0;e<l.length;e++)if(l[e].pathwayId===s[0].pathwayId){u=l[e];break}}this._levels=s;for(let e=0;e<s.length;e++)if(s[e]===u){this._firstLevel=e;let t=u.bitrate,n=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${s.length} level(s) found, first bitrate: ${t}`),this.hls.userConfig?.abrEwmaDefaultEstimate===void 0){let e=Math.min(t,this.hls.config.abrEwmaDefaultEstimateMax);e>n&&n===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=e)}break}let d=i&&!r,f=this.hls.config,p=!!(f.audioStreamController&&f.audioTrackController),m={levels:s,audioTracks:a,subtitleTracks:o,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:i,video:r,altAudio:p&&!d&&a.some(e=>!!e.url)};c.end=performance.now(),this.hls.trigger(Z.MANIFEST_PARSED,m)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){let t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){let n=Error(`invalid level idx`),r=e<0;if(this.hls.trigger(Z.ERROR,{type:Y.OTHER_ERROR,details:X.LEVEL_SWITCH_ERROR,level:e,fatal:r,error:n,reason:n.message}),r)return;e=Math.min(e,t.length-1)}let n=this.currentLevelIndex,r=this.currentLevel,i=r?r.attrs[`PATHWAY-ID`]:void 0,a=t[e],o=a.attrs[`PATHWAY-ID`];if(this.currentLevelIndex=e,this.currentLevel=a,n===e&&r&&i===o)return;this.log(`Switching to level ${e} (${a.height?a.height+`p `:``}${a.videoRange?a.videoRange+` `:``}${a.codecSet?a.codecSet+` `:``}@${a.bitrate})${o?` with Pathway `+o:``} from level ${n}${i?` with Pathway `+i:``}`);let s={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger(Z.LEVEL_SWITCHING,s);let c=a.details;if(!c||c.live){let e=this.switchParams(a.uri,r?.details,c);this.loadPlaylist(e)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){let e=this.hls.config.startLevel;return e===void 0?this.hls.firstAutoLevel:e}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){let t=this.steering.pathways(),n=e.filter(e=>t.indexOf(e)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=n}}onError(e,t){t.fatal||!t.context||t.context.type===dB.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===Q.MAIN){let e=t.elementaryStreams;if(!Object.keys(e).some(t=>!!e[t]))return;let n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var n;let{level:r,details:i}=t,a=t.levelInfo;if(!a){var o;this.warn(`Invalid level index ${r}`),(o=t.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let e=a.details;e===t.details&&e.advanced&&(e=void 0),this.playlistLoaded(r,t,e)}else (n=t.deliveryDirectives)!=null&&n.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);let n=this.getUrlWithDirectives(e.uri,t),r=this.currentLevelIndex,i=e.attrs[`PATHWAY-ID`],a=e.details,o=a?.age;this.log(`Loading level index ${r}${t?.msn===void 0?``:` at sn `+t.msn+` part `+t.part}${i?` Pathway `+i:``}${o&&a.live?` age `+o.toFixed(1)+(a.type&&` `+a.type||``):``} ${n}`),this.hls.trigger(Z.LEVEL_LOADING,{url:n,level:r,levelInfo:e,pathwayId:e.attrs[`PATHWAY-ID`],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex===-1?this.hls.nextAutoLevel:this.manualLevelIndex}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;let n=this._levels.filter((t,n)=>n===e?(this.steering&&this.steering.removeLevel(t),t===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,t.details&&t.details.fragments.forEach(e=>e.level=-1)),!1):!0);RW(n),this._levels=n,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);let r=n.length-1;this._firstLevel=Math.min(this._firstLevel,r),this._startLevel&&=Math.min(this._startLevel,r),this.hls.trigger(Z.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){let{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger(Z.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}};function fZ(e){let t={};e.forEach(e=>{let n=e.groupId||``;e.id=t[n]=t[n]||0,t[n]++})}function pZ(){return self.SourceBuffer||self.WebKitSourceBuffer}function mZ(){if(!kB())return!1;let e=pZ();return!e||e.prototype&&typeof e.prototype.appendBuffer==`function`&&typeof e.prototype.remove==`function`}function hZ(){if(!mZ())return!1;let e=kB();return typeof e?.isTypeSupported==`function`&&([`avc1.42E01E,mp4a.40.2`,`av01.0.01M.08`,`vp09.00.50.08`].some(t=>e.isTypeSupported(PV(t,`video`)))||[`mp4a.40.2`,`fLaC`].some(t=>e.isTypeSupported(PV(t,`audio`))))}function gZ(){var e;let t=pZ();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)==`function`}var _Z=100,vZ=class extends ZW{constructor(e,t,n){super(e,t,n,`stream-controller`,Q.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{let e=this.media,t=e?e.currentTime:null;if(t===null||!J(t)||(this.log(`Media seeked to ${t.toFixed(3)}`),!this.getBufferedFrag(t)))return;let n=this.getFwdBufferInfoAtPos(e,t,Q.MAIN,0);if(n===null||n.len===0){this.warn(`Main forward buffer length at ${t} on "seeked" event ${n?n.len:`empty`})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();let{hls:e}=this;e.on(Z.MANIFEST_PARSED,this.onManifestParsed,this),e.on(Z.LEVEL_LOADING,this.onLevelLoading,this),e.on(Z.LEVEL_LOADED,this.onLevelLoaded,this),e.on(Z.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on(Z.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(Z.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on(Z.BUFFER_CREATED,this.onBufferCreated,this),e.on(Z.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(Z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(Z.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();let{hls:e}=this;e.off(Z.MANIFEST_PARSED,this.onManifestParsed,this),e.off(Z.LEVEL_LOADED,this.onLevelLoaded,this),e.off(Z.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off(Z.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(Z.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off(Z.BUFFER_CREATED,this.onBufferCreated,this),e.off(Z.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(Z.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(Z.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){let{lastCurrentTime:n,hls:r}=this;if(this.stopLoad(),this.setInterval(_Z),this.level=-1,!this.startFragRequested){let e=r.startLevel;e===-1&&(r.config.testBandwidth&&this.levels.length>1?(e=0,this.bitrateTest=!0):e=r.firstAutoLevel),r.nextLoadLevel=e,this.level=r.loadLevel,this._hasEnoughToStart=!!t}n>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${n.toFixed(3)}`),e=n),this.state=$.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=$.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case $.WAITING_LEVEL:{let{levels:e,level:t}=this,n=e?.[t],r=n?.details;if(r&&(!r.live||this.levelLastLoaded===n&&!this.waitForLive(n))){if(this.waitForCdnTuneIn(r))break;this.state=$.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=$.IDLE;break}break}case $.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===$.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){let{hls:e,levelLastLoaded:t,levels:n,media:r}=this;if(t===null||!r&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;let i=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(n!=null&&n[i]))return;let a=n[i],o=this.getMainFwdBufferInfo();if(o===null)return;let s=this.getLevelDetails();if(s&&this._streamEnded(o,s)){let e={};this.altAudio===2&&(e.type=`video`),this.hls.trigger(Z.BUFFER_EOS,e),this.state=$.ENDED;return}if(!this.buffering)return;e.loadLevel!==i&&e.manualLevel===-1&&this.log(`Adapting to level ${i} from level ${this.level}`),this.level=e.nextLoadLevel=i;let c=a.details;if(!c||this.state===$.WAITING_LEVEL||this.waitForLive(a)){this.level=i,this.state=$.WAITING_LEVEL,this.startFragRequested=!1;return}let l=o.len,u=this.getMaxBufferLength(a.maxBitrate);if(l>=u)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);let d=this.backtrackFragment?this.backtrackFragment.start:o.end,f=this.getNextFragment(d,c);if(this.couldBacktrack&&!this.fragPrevious&&f&&UB(f)&&this.fragmentTracker.getState(f)!==QH.OK){let e=(this.backtrackFragment??f).sn-c.startSN,t=c.fragments[e-1];t&&f.cc===t.cc&&(f=t,this.fragmentTracker.removeFragment(t))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,d)){if(!f.gap){let e=this.audioOnly&&!this.altAudio?VB.AUDIO:VB.VIDEO,t=(e===VB.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;t&&this.afterBufferFlushed(t,e,Q.MAIN)}f=this.getNextFragmentLoopLoading(f,c,o,Q.MAIN,u)}f&&(this.exceedsMaxBuffer(o,u,f)||(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,a,d)))}loadFragment(e,t,n){let r=this.fragmentTracker.getState(e);r===QH.NOT_LOADED||r===QH.PARTIAL?UB(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,n):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Q.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,1/0),this.altAudio!==0&&(this.getLevelDetails()?.fragmentStart||0)>this.lastCurrentTime&&super.flushMainBuffer(0,1/0,`audio`)}nextLevelSwitch(){let{levels:e,media:t}=this;if(t!=null&&t.readyState){let n,r=this.getAppendedFrag(t.currentTime);r&&r.start>1&&this.flushMainBuffer(0,r.start-1);let i=this.getLevelDetails();if(i!=null&&i.live){let e=this.getMainFwdBufferInfo();if(!e||e.len<i.targetduration*2)return}if(!t.paused&&e){let t=e[this.hls.nextLoadLevel],r=this.fragLastKbps;n=r&&this.fragCurrent?this.fragCurrent.duration*t.maxBitrate/(1e3*r)+1:0}else n=0;let a=this.getBufferedFrag(t.currentTime+n);if(a){let e=this.followingBufferedFrag(a);if(e){this.abortCurrentFrag();let t=e.maxStartPTS?e.maxStartPTS:e.start,n=e.duration,r=Math.max(a.end,t+Math.min(Math.max(n-this.config.maxFragLookUpTolerance,n*(this.couldBacktrack?.5:.125)),n*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(r,1/0)}}}}abortCurrentFrag(){let e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case $.KEY_LOADING:case $.FRAG_LOADING:case $.FRAG_LOADING_WAITING_RETRY:case $.PARSING:case $.PARSED:this.state=$.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?`video`:null)}onMediaAttached(e,t){super.onMediaAttached(e,t);let n=t.media;JW(n,`playing`,this.onMediaPlaying),JW(n,`seeked`,this.onMediaSeeked)}onMediaDetaching(e,t){let{media:n}=this;n&&(YW(n,`playing`,this.onMediaPlaying),YW(n,`seeked`,this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log(`Trigger BUFFER_RESET`),this.hls.trigger(Z.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let n=!1,r=!1;for(let e=0;e<t.levels.length;e++){let i=t.levels[e].audioCodec;i&&(n||=i.indexOf(`mp4a.40.2`)!==-1,r||=i.indexOf(`mp4a.40.5`)!==-1)}this.audioCodecSwitch=n&&r&&!gZ(),this.audioCodecSwitch&&this.log(`Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC`),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){let{levels:n}=this;if(!n||this.state!==$.IDLE)return;let r=t.levelInfo;(!r.details||r.details.live&&(this.levelLastLoaded!==r||r.details.expired)||this.waitForCdnTuneIn(r.details))&&(this.state=$.WAITING_LEVEL)}onLevelLoaded(e,t){var n;let{levels:r,startFragRequested:i}=this,a=t.level,o=t.details,s=o.totalduration;if(!r){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${o.startSN},${o.endSN}]${o.lastPartSn?`[part-${o.lastPartSn}-${o.lastPartIndex}]`:``}, cc [${o.startCC}, ${o.endCC}] duration:${s}`);let c=t.levelInfo,l=this.fragCurrent;l&&(this.state===$.FRAG_LOADING||this.state===$.FRAG_LOADING_WAITING_RETRY)&&l.level!==t.level&&l.loader&&this.abortCurrentFrag();let u=0;if(o.live||(n=c.details)!=null&&n.live){if(this.checkLiveUpdate(o),o.deltaUpdateFailed)return;u=this.alignPlaylists(o,c.details,this.levelLastLoaded?.details)}if(c.details=o,this.levelLastLoaded=c,i||this.setStartPosition(o,u),this.hls.trigger(Z.LEVEL_UPDATED,{details:o,level:a}),this.state===$.WAITING_LEVEL){if(this.waitForCdnTuneIn(o))return;this.state=$.IDLE}i&&o.live&&this.synchronizeToLiveEdge(o),this.tick()}synchronizeToLiveEdge(e){let{config:t,media:n}=this;if(!n)return;let r=this.hls.liveSyncPosition,i=this.getLoadPosition(),a=e.fragmentStart,o=e.edge,s=i>=a-t.maxFragLookUpTolerance&&i<=o;if(r!==null&&n.duration>r&&(i<r||!s)){let a=t.liveMaxLatencyDuration===void 0?t.liveMaxLatencyDurationCount*e.targetduration:t.liveMaxLatencyDuration;if((!s&&n.readyState<4||i<o-a)&&(this._hasEnoughToStart||(this.nextLoadPosition=r),n.readyState))if(this.warn(`Playback: ${i.toFixed(3)} is located too far from the end of live sliding playlist: ${o}, reset currentTime to : ${r.toFixed(3)}`),this.config.liveSyncMode===`buffered`){var c;let e=xU.bufferInfo(n,r,0);if(!((c=e.buffered)!=null&&c.length)){n.currentTime=r;return}if(e.start<=i){n.currentTime=r;return}let{nextStart:t}=xU.bufferedInfo(e.buffered,i,0);t&&(n.currentTime=t)}else n.currentTime=r}}_handleFragmentLoadProgress(e){let t=e.frag,{part:n,payload:r}=e,{levels:i}=this;if(!i){this.warn(`Levels were reset while fragment load was in progress. Fragment ${t.sn} of level ${t.level} will not be buffered`);return}let a=i[t.level];if(!a){this.warn(`Level ${t.level} not found on progress`);return}let o=a.details;if(!o){this.warn(`Dropping fragment ${t.sn} of level ${t.level} after level details were reset`),this.fragmentTracker.removeFragment(t);return}let s=a.videoCodec,c=o.PTSKnown||!o.live,l=t.initSegment?.data,u=this._getAudioCodec(a),d=this.transmuxer=this.transmuxer||new sq(this.hls,Q.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),f=n?n.index:-1,p=f!==-1,m=new vU(t.level,t.sn,t.stats.chunkCount,r.byteLength,f,p),h=this.initPTS[t.cc];d.push(r,l,u,s,t,n,o.totalduration,c,m,h)}onAudioTrackSwitching(e,t){let n=this.hls,r=this.altAudio!==0;if(AH(t.url,n))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log(`Switching on main audio, use media.buffered to schedule main fragment loading`),this.mediaBuffer=this.media;let e=this.fragCurrent;e&&(this.log(`Switching to main audio track, cancel main fragment load`),e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(r){this.altAudio=0,this.fragmentTracker.removeAllFragments(),n.once(Z.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger(Z.AUDIO_TRACK_SWITCHED,t)}),n.trigger(Z.BUFFER_FLUSHING,{startOffset:0,endOffset:1/0,type:null});return}n.trigger(Z.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){let n=AH(t.url,this.hls);if(n){let e=this.videoBuffer;e&&this.mediaBuffer!==e&&(this.log(`Switching on alternate audio, use video.buffered to schedule main fragment loading`),this.mediaBuffer=e)}this.altAudio=n?2:0,this.tick()}onBufferCreated(e,t){let n=t.tracks,r,i,a=!1;for(let e in n){let t=n[e];if(t.id===`main`){if(i=e,r=t,e===`video`){let t=n[e];t&&(this.videoBuffer=t.buffer)}}else a=!0}a&&r?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=r.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){let{frag:n,part:r}=t,i=n.type===Q.MAIN;if(i){if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${r?` p: `+r.index:``} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===$.PARSED&&(this.state=$.IDLE);return}let e=r?r.stats:n.stats;this.fragLastKbps=Math.round(8*e.total/(e.buffering.end-e.loading.first)),UB(n)&&(this.fragPrevious=n),this.fragBufferedComplete(n,r)}let a=this.media;a&&(!this._hasEnoughToStart&&xU.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){if(t.fatal){this.state=$.ERROR;return}switch(t.details){case X.FRAG_GAP:case X.FRAG_PARSING_ERROR:case X.FRAG_DECRYPT_ERROR:case X.FRAG_LOAD_ERROR:case X.FRAG_LOAD_TIMEOUT:case X.KEY_LOAD_ERROR:case X.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Q.MAIN,t);break;case X.LEVEL_LOAD_ERROR:case X.LEVEL_LOAD_TIMEOUT:case X.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===$.WAITING_LEVEL&&t.context?.type===dB.LEVEL&&(this.state=$.IDLE);break;case X.BUFFER_ADD_CODEC_ERROR:case X.BUFFER_APPEND_ERROR:if(t.parent!==`main`)return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case X.BUFFER_FULL_ERROR:if(t.parent!==`main`)return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,1/0));break;case X.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=$.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==VB.AUDIO||!this.altAudio){let e=(t===VB.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;e&&(this.afterBufferFlushed(e,t,Q.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){let{media:e}=this;if(!e)return;let t=e.currentTime,n=this.startPosition;if(n>=0&&t<n){if(e.seeking){this.log(`could not seek to ${n}, already seeking at ${t}`);return}let r=this.timelineOffset;r&&n&&(n+=r);let i=this.getLevelDetails(),a=xU.getBuffered(e),o=a.length?a.start(0):0,s=o-n,c=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||s>0&&(s<c||this.loadingParts&&s<2*(i?.partTarget||0)))&&(this.log(`adjusting start position by ${s} to match buffer start`),n+=s,this.startPosition=n),t<n&&(this.log(`seek to target start position ${n} from current time ${t} buffer start ${o}`),e.currentTime=n)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log(`Swapping audio codec`),t=t.indexOf(`mp4a.40.5`)===-1?`mp4a.40.5`:`mp4a.40.2`),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(e=>{let{hls:n}=this,r=e?.frag;if(!r||this.fragContextChanged(r))return;t.fragmentError=0,this.state=$.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;let i=r.stats;i.parsing.start=i.parsing.end=i.buffering.start=i.buffering.end=self.performance.now(),n.trigger(Z.FRAG_LOADED,e),r.bitrateTest=!1}).catch(t=>{this.state===$.STOPPED||this.state===$.ERROR||(this.warn(t),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){let t=this.playlistType,{hls:n}=this,{remuxResult:r,chunkMeta:i}=e,a=this.getCurrentContext(i);if(!a){this.resetWhenMissingContext(i);return}let{frag:o,part:s,level:c}=a,{video:l,text:u,id3:d,initSegment:f}=r,{details:p}=c,m=this.altAudio?void 0:r.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=$.PARSING,f){let e=f.tracks;if(e){let r=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(c,e,r,i),n.trigger(Z.FRAG_PARSING_INIT_SEGMENT,{frag:r,id:t,tracks:e})}let r=f.initPTS,a=f.timescale,s=this.initPTS[o.cc];if(J(r)&&(!s||s.baseTime!==r||s.timescale!==a)){let e=f.trackId;this.initPTS[o.cc]={baseTime:r,timescale:a,trackId:e},n.trigger(Z.INIT_PTS_FOUND,{frag:o,id:t,initPTS:r,timescale:a,trackId:e})}}if(l&&p){m&&l.type===`audiovideo`&&this.logMuxedErr(o);let e=p.fragments[o.sn-1-p.startSN],t=o.sn===p.startSN,n=!e||o.cc>e.cc;if(r.independent!==!1){let{startPTS:e,endPTS:r,startDTS:a,endDTS:c}=l;if(s)s.elementaryStreams[l.type]={startPTS:e,endPTS:r,startDTS:a,endDTS:c};else if(l.firstKeyFrame&&l.independent&&i.id===1&&!n&&(this.couldBacktrack=!0),l.dropped&&l.independent){let i=this.getMainFwdBufferInfo(),a=(i?i.end:this.getLoadPosition())+this.config.maxBufferHole,s=l.firstKeyFramePTS?l.firstKeyFramePTS:e;if(!t&&a<s-this.config.maxBufferHole&&!n){this.backtrack(o);return}else n&&(o.gap=!0);o.setElementaryStreamInfo(l.type,o.start,r,o.start,c,!0)}else t&&e-(p.appliedTimelineOffset||0)>ZX&&(o.gap=!0);o.setElementaryStreamInfo(l.type,e,r,a,c),this.backtrackFragment&&=o,this.bufferFragmentData(l,o,s,i,t||n)}else if(t||n)o.gap=!0;else{this.backtrack(o);return}}if(m){let{startPTS:e,endPTS:t,startDTS:n,endDTS:r}=m;s&&(s.elementaryStreams[VB.AUDIO]={startPTS:e,endPTS:t,startDTS:n,endDTS:r}),o.setElementaryStreamInfo(VB.AUDIO,e,t,n,r),this.bufferFragmentData(m,o,s,i)}if(p&&d!=null&&d.samples.length){let e={id:t,frag:o,details:p,samples:d.samples};n.trigger(Z.FRAG_PARSING_METADATA,e)}if(p&&u){let e={id:t,frag:o,details:p,samples:u.samples};n.trigger(Z.FRAG_PARSING_USERDATA,e)}}logMuxedErr(e){this.warn(`${UB(e)?`Media`:`Init`} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,n,r){if(this.state!==$.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(n));let{audio:i,video:a,audiovideo:o}=t;if(i){let n=e.audioCodec,r=HV(i.codec,n);r===`mp4a`&&(r=`mp4a.40.5`);let a=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){r&&=r.indexOf(`mp4a.40.5`)===-1?`mp4a.40.5`:`mp4a.40.2`;let e=i.metadata;e&&`channelCount`in e&&(e.channelCount||1)!==1&&a.indexOf(`firefox`)===-1&&(r=`mp4a.40.5`)}r&&r.indexOf(`mp4a.40.5`)!==-1&&a.indexOf(`android`)!==-1&&i.container!==`audio/mpeg`&&(r=`mp4a.40.2`,this.log(`Android: force audio codec to ${r}`)),n&&n!==r&&this.log(`Swapping manifest audio codec "${n}" for "${r}"`),i.levelCodec=r,i.id=Q.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${r||``}/${n||``}/${i.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=Q.MAIN;let n=a.codec;if(n?.length===4)switch(n){case`hvc1`:case`hev1`:a.codec=`hvc1.1.6.L120.90`;break;case`av01`:a.codec=`av01.0.04M.08`;break;case`avc1`:a.codec=`avc1.42e01e`;break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||``}/${n}]${a.codec===n?``:` parsed-corrected=`+a.codec}${a.supplemental?` supplemental=`+a.supplemental:``}`),delete t.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),delete t.video,delete t.audio);let s=Object.keys(t);if(s.length){if(this.hls.trigger(Z.BUFFER_CODECS,t),!this.hls)return;s.forEach(e=>{let i=t[e].initSegment;i!=null&&i.byteLength&&this.hls.trigger(Z.BUFFER_APPENDING,{type:e,data:i,frag:n,part:null,chunkMeta:r,parent:n.type})})}this.tickImmediate()}getMainFwdBufferInfo(){let e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,Q.MAIN)}get maxBufferLength(){let{levels:e,level:t}=this,n=e?.[t];return n?this.getMaxBufferLength(n.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=$.IDLE}checkFragmentChanged(){let e=this.media,t=null;if(e&&e.readyState>1&&e.seeking===!1){let n=e.currentTime;if(xU.isBuffered(e,n)?t=this.getAppendedFrag(n):xU.isBuffered(e,n+.1)&&(t=this.getAppendedFrag(n+.1)),t){this.backtrackFragment=null;let e=this.fragPlaying,n=t.level;(!e||t.sn!==e.sn||e.level!==n)&&(this.fragPlaying=t,this.hls.trigger(Z.FRAG_CHANGED,{frag:t}),(!e||e.level!==n)&&this.hls.trigger(Z.LEVEL_SWITCHED,{level:n}))}}}get nextLevel(){let e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){if(this.fragPlaying)return this.fragPlaying;let e=this.media?.currentTime||this.lastCurrentTime;return J(e)?this.getAppendedFrag(e):null}get currentProgramDateTime(){let e=this.media?.currentTime||this.lastCurrentTime;if(J(e)){let t=this.getLevelDetails(),n=this.currentFrag||(t?PH(null,t.fragments,e):null);if(n){let t=n.programDateTime;if(t!==null){let r=t+(e-n.start)*1e3;return new Date(r)}}}return null}get currentLevel(){let e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){let e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},yZ=class extends bB{constructor(e,t){super(`key-loader`,t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(let t in this.keyIdToKeyInfo){let n=this.keyIdToKeyInfo[t].loader;if(n){if(e&&e!==n.context?.frag.type)return;n.abort()}}}detach(){for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(let e in this.keyIdToKeyInfo){let t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=X.KEY_LOAD_ERROR,n,r,i){return new gU({type:Y.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:i,error:n,networkDetails:r})}loadClear(e,t,n){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let r=0,i=t.length;r<i;r++){let a=t[r];if(e.cc<=a.cc&&(!UB(e)||!UB(a)||e.sn<a.sn)||!n&&r==i-1)return this.emeController.selectKeySystemFormat(a).then(e=>{if(!this.emeController)return;a.setKeyFormat(e);let t=JU(e);if(t)return this.emeController.getKeySystemAccess([t])})}if(this.config.requireKeySystemAccessOnStart){let e=XU(this.config);if(e.length)return this.emeController.getKeySystemAccess(e)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var n,r;t&&e.setKeyFormat(t);let i=e.decryptdata;if(!i){let n=Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,X.KEY_LOAD_ERROR,n))}let a=i.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,X.KEY_LOAD_ERROR,Error(`Invalid key URI: "${a}"`)));let o=bZ(i),s=this.keyIdToKeyInfo[o];if((n=s)!=null&&n.decryptdata.key)return i.key=s.decryptdata.key,Promise.resolve({frag:e,keyInfo:s});if(this.emeController&&(r=s)!=null&&r.keyLoadPromise)switch(this.emeController.getKeyStatus(s.decryptdata)){case`usable`:case`usable-in-future`:return s.keyLoadPromise.then(t=>{let{keyInfo:n}=t;return i.key=n.decryptdata.key,{frag:e,keyInfo:n}})}switch(this.log(`${this.keyIdToKeyInfo[o]?`Rel`:`L`}oading${i.keyId?` keyId: `+NB(i.keyId):``} URI: ${i.uri} from ${e.type} ${e.level}`),s=this.keyIdToKeyInfo[o]={decryptdata:i,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},i.method){case`SAMPLE-AES`:case`SAMPLE-AES-CENC`:case`SAMPLE-AES-CTR`:return i.keyFormat===`identity`?this.loadKeyHTTP(s,e):this.loadKeyEME(s,e);case`AES-128`:case`AES-256`:case`AES-256-CTR`:return this.loadKeyHTTP(s,e);default:return Promise.reject(this.createKeyLoadError(e,X.KEY_LOAD_ERROR,Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(e,t){let n={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var r;if(!e.decryptdata.keyId&&(r=t.initSegment)!=null&&r.data){let n=pV(t.initSegment.data);if(n.length){let t=n[0];t.some(e=>e!==0)?(this.log(`Using keyId found in init segment ${NB(t)}`),rW.setKeyIdForUri(e.decryptdata.uri,t)):(t=rW.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${NB(t)}`)),e.decryptdata.keyId=t}}return!e.decryptdata.keyId&&!UB(t)?Promise.resolve(n):(e.keyLoadPromise=this.emeController.loadKey(n).then(t=>(e.mediaKeySessionContext=t,n))).catch(n=>{throw e.keyLoadPromise=null,`data`in n&&(n.data.frag=t),n})}return Promise.resolve(n)}loadKeyHTTP(e,t){let n=this.config,r=n.loader,i=new r(n);return t.keyLoader=e.loader=i,e.keyLoadPromise=new Promise((r,a)=>{let o={keyInfo:e,frag:t,responseType:`arraybuffer`,url:e.decryptdata.uri},s=n.keyLoadPolicy.default,c={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};i.load(o,c,{onSuccess:(e,t,n,i)=>{let{frag:o,keyInfo:s}=n,c=bZ(s.decryptdata);if(!o.decryptdata||s!==this.keyIdToKeyInfo[c])return a(this.createKeyLoadError(o,X.KEY_LOAD_ERROR,Error(`after key load, decryptdata unset or changed`),i));s.decryptdata.key=o.decryptdata.key=new Uint8Array(e.data),o.keyLoader=null,s.loader=null,r({frag:o,keyInfo:s})},onError:(e,n,r,i)=>{this.resetLoader(n),a(this.createKeyLoadError(t,X.KEY_LOAD_ERROR,Error(`HTTP Error ${e.code} loading key ${e.text}`),r,_B({url:o.url,data:void 0},e)))},onTimeout:(e,n,r)=>{this.resetLoader(n),a(this.createKeyLoadError(t,X.KEY_LOAD_TIMEOUT,Error(`key loading timed out`),r))},onAbort:(e,n,r)=>{this.resetLoader(n),a(this.createKeyLoadError(t,X.INTERNAL_ABORTED,Error(`key loading aborted`),r))}})})}resetLoader(e){let{frag:t,keyInfo:n,url:r}=e,i=n.loader;t.keyLoader===i&&(t.keyLoader=null,n.loader=null);let a=bZ(n.decryptdata)||r;delete this.keyIdToKeyInfo[a],i&&i.destroy()}};function bZ(e){if(e.keyFormat!==qU.FAIRPLAY){let t=e.keyId;if(t)return NB(t)}return e.uri}function xZ(e){let{type:t}=e;switch(t){case dB.AUDIO_TRACK:return Q.AUDIO;case dB.SUBTITLE_TRACK:return Q.SUBTITLE;default:return Q.MAIN}}function SZ(e,t){let n=e.url;return(n===void 0||n.indexOf(`data:`)===0)&&(n=t.url),n}var CZ=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){let{hls:e}=this;e.on(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.on(Z.LEVEL_LOADING,this.onLevelLoading,this),e.on(Z.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(Z.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on(Z.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){let{hls:e}=this;e.off(Z.MANIFEST_LOADING,this.onManifestLoading,this),e.off(Z.LEVEL_LOADING,this.onLevelLoading,this),e.off(Z.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(Z.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off(Z.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){let t=this.hls.config,n=t.pLoader,r=t.loader,i=new(n||r)(t);return this.loaders[e.type]=i,i}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(let e in this.loaders){let t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){let{url:n}=t;this.variableList=null,this.load({id:null,level:0,responseType:`text`,type:dB.MANIFEST,url:n,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){let{id:n,level:r,pathwayId:i,url:a,deliveryDirectives:o,levelInfo:s}=t;this.load({id:n,level:r,pathwayId:i,responseType:`text`,type:dB.LEVEL,url:a,deliveryDirectives:o,levelOrTrack:s})}onAudioTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:dB.AUDIO_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onSubtitleTrackLoading(e,t){let{id:n,groupId:r,url:i,deliveryDirectives:a,track:o}=t;this.load({id:n,groupId:r,level:null,responseType:`text`,type:dB.SUBTITLE_TRACK,url:i,deliveryDirectives:a,levelOrTrack:o})}onLevelsUpdated(e,t){let n=this.loaders[dB.LEVEL];if(n){let e=n.context;e&&!t.levels.some(t=>t===e.levelOrTrack)&&(n.abort(),delete this.loaders[dB.LEVEL])}}load(e){let t=this.hls.config,n=this.getInternalLoader(e);if(n){let t=this.hls.logger,r=n.context;if(r&&r.levelOrTrack===e.levelOrTrack&&(r.url===e.url||r.deliveryDirectives&&!e.deliveryDirectives)){r.url===e.url?t.log(`[playlist-loader]: ignore ${e.url} ongoing request`):t.log(`[playlist-loader]: ignore ${e.url} in favor of ${r.url}`);return}t.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let r;if(r=e.type===dB.MANIFEST?t.manifestLoadPolicy.default:hB({},t.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),J(e.deliveryDirectives?.part)){let t;if(e.type===dB.LEVEL&&e.level!==null?t=this.hls.levels[e.level].details:e.type===dB.AUDIO_TRACK&&e.id!==null?t=this.hls.audioTracks[e.id].details:e.type===dB.SUBTITLE_TRACK&&e.id!==null&&(t=this.hls.subtitleTracks[e.id].details),t){let e=t.partTarget,n=t.targetduration;if(e&&n){let t=Math.max(e*3,n*.8)*1e3;r=hB({},r,{maxTimeToFirstByteMs:Math.min(t,r.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(t,r.maxTimeToFirstByteMs)})}}}let i=r.errorRetry||r.timeoutRetry||{},a={loadPolicy:r,timeout:r.maxLoadTimeMs,maxRetry:i.maxNumRetry||0,retryDelay:i.retryDelayMs||0,maxRetryDelay:i.maxRetryDelayMs||0};n.load(e,a,{onSuccess:(e,t,n,r)=>{let i=this.getInternalLoader(n);this.resetInternalLoader(n.type);let a=e.data;t.parsing.start=performance.now(),fW.isMediaPlaylist(a)||n.type!==dB.MANIFEST?this.handleTrackOrLevelPlaylist(e,t,n,r||null,i):this.handleMasterPlaylist(e,t,n,r)},onError:(e,t,n,r)=>{this.handleNetworkError(t,n,!1,e,r)},onTimeout:(e,t,n)=>{this.handleNetworkError(t,n,!0,void 0,e)}})}checkAutostartLoad(){if(!this.hls)return;let{config:{autoStartLoad:e,startPosition:t},forceStartLoad:n}=this.hls;(e||n)&&(this.hls.logger.log(`${e?`auto`:`force`} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,n,r){let i=this.hls,a=e.data,o=SZ(e,n),s=fW.parseMasterPlaylist(a,o);if(s.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,n,s.playlistParsingError,r,t);return}let{contentSteering:c,levels:l,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:p}=s;this.variableList=p,l.forEach(e=>{let{unknownCodecs:t}=e;if(t){let{preferManagedMediaSource:n}=this.hls.config,{audioCodec:r,videoCodec:i}=e;for(let a=t.length;a--;){let o=t[a];MV(o,`audio`,n)?(e.audioCodec=r=r?`${r},${o}`:o,AV.audio[r.substring(0,4)]=2,t.splice(a,1)):MV(o,`video`,n)&&(e.videoCodec=i=i?`${i},${o}`:o,AV.video[i.substring(0,4)]=2,t.splice(a,1))}}});let{AUDIO:m=[],SUBTITLES:h,"CLOSED-CAPTIONS":g}=fW.parseMasterPlaylistMedia(a,o,s);m.length&&!m.some(e=>!e.url)&&l[0].audioCodec&&!l[0].attrs.AUDIO&&(this.hls.logger.log(`[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one`),m.unshift({type:`main`,name:`main`,groupId:`main`,default:!1,autoselect:!1,forced:!1,id:-1,attrs:new kU({}),bitrate:0,url:``})),i.trigger(Z.MANIFEST_LOADED,{levels:l,audioTracks:m,subtitles:h,captions:g,contentSteering:c,url:o,stats:t,networkDetails:r,sessionData:u,sessionKeys:d,startTimeOffset:f,variableList:p})}handleTrackOrLevelPlaylist(e,t,n,r,i){let a=this.hls,{id:o,level:s,type:c}=n,l=SZ(e,n),u=J(s)?s:J(o)?o:0,d=xZ(n),f=fW.parseLevelPlaylist(e.data,l,u,d,0,this.variableList);if(c===dB.MANIFEST){let e={attrs:new kU({}),bitrate:0,details:f,name:``,url:l};f.requestScheduled=t.loading.start+PW(f,0),a.trigger(Z.MANIFEST_LOADED,{levels:[e],audioTracks:[],url:l,stats:t,networkDetails:r,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),n.levelDetails=f,this.handlePlaylistLoaded(f,e,t,n,r,i)}handleManifestParsingError(e,t,n,r,i){this.hls.trigger(Z.ERROR,{type:Y.NETWORK_ERROR,details:X.MANIFEST_PARSING_ERROR,fatal:t.type===dB.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:t,networkDetails:r,stats:i})}handleNetworkError(e,t,n=!1,r,i){let a=`A network ${n?`timeout`:`error`+(r?` (status `+r.code+`)`:``)} occurred while loading ${e.type}`;e.type===dB.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===dB.AUDIO_TRACK||e.type===dB.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);let o=Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let s=X.UNKNOWN,c=!1,l=this.getInternalLoader(e);switch(e.type){case dB.MANIFEST:s=n?X.MANIFEST_LOAD_TIMEOUT:X.MANIFEST_LOAD_ERROR,c=!0;break;case dB.LEVEL:s=n?X.LEVEL_LOAD_TIMEOUT:X.LEVEL_LOAD_ERROR,c=!1;break;case dB.AUDIO_TRACK:s=n?X.AUDIO_TRACK_LOAD_TIMEOUT:X.AUDIO_TRACK_LOAD_ERROR,c=!1;break;case dB.SUBTITLE_TRACK:s=n?X.SUBTITLE_TRACK_LOAD_TIMEOUT:X.SUBTITLE_LOAD_ERROR,c=!1;break}l&&this.resetInternalLoader(e.type);let u={type:Y.NETWORK_ERROR,details:s,fatal:c,url:e.url,loader:l,context:e,error:o,networkDetails:t,stats:i};r&&(u.response=_B({url:t?.url||e.url,data:void 0},r)),this.hls.trigger(Z.ERROR,u)}handlePlaylistLoaded(e,t,n,r,i,a){let o=this.hls,{type:s,level:c,levelOrTrack:l,id:u,groupId:d,deliveryDirectives:f}=r,p=SZ(t,r),m=xZ(r),h=typeof r.level==`number`&&m===Q.MAIN?c:void 0,g=e.playlistParsingError;if(g){if(this.hls.logger.warn(`${g} ${e.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(Z.ERROR,{type:Y.NETWORK_ERROR,details:X.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:g,reason:g.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}e.playlistParsingError=null}if(!e.fragments.length){let a=e.playlistParsingError=Error(`No Segments found in Playlist`);o.trigger(Z.ERROR,{type:Y.NETWORK_ERROR,details:X.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:a,reason:a.message,response:t,context:r,level:h,parent:m,networkDetails:i,stats:n});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),s){case dB.MANIFEST:case dB.LEVEL:if(h){if(!l)h=0;else if(l!==o.levels[h]){let e=o.levels.indexOf(l);e>-1&&(h=e)}}o.trigger(Z.LEVEL_LOADED,{details:e,levelInfo:l||o.levels[0],level:h||0,id:u||0,stats:n,networkDetails:i,deliveryDirectives:f,withoutMultiVariant:s===dB.MANIFEST});break;case dB.AUDIO_TRACK:o.trigger(Z.AUDIO_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f});break;case dB.SUBTITLE_TRACK:o.trigger(Z.SUBTITLE_TRACK_LOADED,{details:e,track:l,id:u||0,groupId:d||``,stats:n,networkDetails:i,deliveryDirectives:f});break}}},wZ=class e{static get version(){return aG}static isMSESupported(){return mZ()}static isSupported(){return hZ()}static getMediaSource(){return kB()}static get Events(){return Z}static get MetadataSchema(){return GG}static get ErrorTypes(){return Y}static get ErrorDetails(){return X}static get DefaultConfig(){return e.defaultConfig?e.defaultConfig:KX}static set DefaultConfig(t){e.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new iG,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;let n=this.logger=DB(t.debug||!1,`Hls instance`,t.assetPlayerId),r=this.config=JX(e.DefaultConfig,t,n);this.userConfig=t,r.progressive&&XX(r,n);let{abrController:i,bufferController:a,capLevelController:o,errorController:s,fpsController:c}=r,l=new s(this),u=this.abrController=new i(this),d=new $H(this),f=r.interstitialsController,p=f?this.interstitialsController=new f(this,e):null,m=this.bufferController=new a(this,d),h=this.capLevelController=new o(this),g=new c(this),_=new CZ(this),v=r.contentSteeringController,y=v?new v(this):null,b=this.levelController=new dZ(this,y),x=new lZ(this),S=new yZ(this.config,this.logger),C=this.streamController=new vZ(this,d,S),w=this.gapController=new tZ(this,d);h.setStreamController(C),g.setStreamController(C);let T=[_,b,C];p&&T.splice(1,0,p),y&&T.splice(1,0,y),this.networkControllers=T;let E=[u,m,w,h,g,x,d];this.audioTrackController=this.createController(r.audioTrackController,T);let D=r.audioStreamController;D&&T.push(this.audioStreamController=new D(this,d,S)),this.subtitleTrackController=this.createController(r.subtitleTrackController,T);let O=r.subtitleStreamController;O&&T.push(this.subtititleStreamController=new O(this,d,S)),this.createController(r.timelineController,E),S.emeController=this.emeController=this.createController(r.emeController,E),this.cmcdController=this.createController(r.cmcdController,E),this.latencyController=this.createController(uZ,E),this.coreComponents=E,T.push(l);let k=l.onErrorOut;typeof k==`function`&&this.on(Z.ERROR,k,l),this.on(Z.MANIFEST_LOADED,_.onManifestLoaded,_)}createController(e,t){if(e){let n=new e(this);return t&&t.push(n),n}return null}on(e,t,n=this){this._emitter.on(e,t,n)}once(e,t,n=this){this._emitter.once(e,t,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,t,n=this,r){this._emitter.off(e,t,n,r)}listeners(e){return this._emitter.listeners(e)}emit(e,t,n){return this._emitter.emit(e,t,n)}trigger(e,t){if(this.config.debug)return this.emit(e,e,t);try{return this.emit(e,e,t)}catch(t){if(this.logger.error(`An internal error happened while handling event `+e+`. Error message: "`+t.message+`". Here is a stacktrace:`,t),!this.triggeringException){this.triggeringException=!0;let n=e===Z.ERROR;this.trigger(Z.ERROR,{type:Y.OTHER_ERROR,details:X.INTERNAL_EXCEPTION,fatal:n,event:e,error:t}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){this.logger.log(`destroy`),this.trigger(Z.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(e=>e.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(e=>e.destroy()),this.coreComponents.length=0;let e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){if(!e||`media`in e&&!e.media){let t=Error(`attachMedia failed: invalid argument (${e})`);this.trigger(Z.ERROR,{type:Y.OTHER_ERROR,details:X.ATTACH_MEDIA_ERROR,fatal:!0,error:t});return}this.logger.log(`attachMedia`),this._media&&(this.logger.warn(`media must be detached before attaching`),this.detachMedia());let t=`media`in e,n=t?e.media:e,r=t?e:{media:n};this._media=n,this.trigger(Z.MEDIA_ATTACHING,r)}detachMedia(){this.logger.log(`detachMedia`),this.trigger(Z.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;let e=this.bufferController.transferMedia();return this.trigger(Z.MEDIA_DETACHING,{transferMedia:e}),e}loadSource(e){this.stopLoad();let t=this.media,n=this._url,r=this._url=zB.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${r}`),t&&n&&(n!==r||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(t)),this.trigger(Z.MANIFEST_LOADING,{url:e})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(e=-1,t){this.logger.log(`startLoad(${e+(t?`, <skip seek to start>`:``)})`),this.started=!0,this.resumeBuffering();for(let n=0;n<this.networkControllers.length&&(this.networkControllers[n].startLoad(e,t),!(!this.started||!this.networkControllers));n++);}stopLoad(){this.logger.log(`stopLoad`),this.started=!1;for(let e=0;e<this.networkControllers.length&&(this.networkControllers[e].stopLoad(),!(this.started||!this.networkControllers));e++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log(`resume buffering`),this.networkControllers.forEach(e=>{e.resumeBuffering&&e.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log(`pause buffering`),this.networkControllers.forEach(e=>{e.pauseBuffering&&e.pauseBuffering()}))}get inFlightFragments(){let e={[Q.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(e[Q.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(e[Q.SUBTITLE]=this.subtititleStreamController.inFlightFrag),e}swapAudioCodec(){this.logger.log(`swapAudioCodec`),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log(`recoverMediaError`);let e=this._media,t=e?.currentTime;this.detachMedia(),e&&(this.attachMedia(e),t&&this.startLoad(t))}removeLevel(e){this.levelController.removeLevel(e)}get sessionId(){let e=this._sessionId;return e||=this._sessionId=lY(),e}get levels(){return this.levelController.levels||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){this.logger.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){this.logger.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){this.logger.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){this.logger.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){let e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){this.logger.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){let t=!!e;t!==this.config.capLevelToPlayerSize&&(t?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=t)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get abrEwmaDefaultEstimate(){let{bwEstimator:e}=this.abrController;return e?e.defaultEstimate:NaN}get ttfbEstimate(){let{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(this.logger.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){oH(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){let{levels:e,config:{minAutoBitrate:t}}=this;if(!e)return 0;let n=e.length;for(let r=0;r<n;r++)if(e[r].maxBitrate>=t)return r;return 0}get maxAutoLevel(){let{levels:e,autoLevelCapping:t,maxHdcpLevel:n}=this,r;if(r=t===-1&&e!=null&&e.length?e.length-1:t,n)for(let t=r;t--;){let r=e[t].attrs[`HDCP-LEVEL`];if(r&&r<=n)return t}return r}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(e){return this.audioTrackController?.setAudioOption(e)||null}setSubtitleOption(e){return this.subtitleTrackController?.setSubtitleOption(e)||null}get allAudioTracks(){let e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){let e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){let e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){let t=this.audioTrackController;t&&(t.audioTrack=e)}get allSubtitleTracks(){let e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){let e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){let e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){let t=this.subtitleTrackController;t&&(t.subtitleTrack=e)}get subtitleDisplay(){let e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){let t=this.subtitleTrackController;t&&(t.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(e){this.latencyController.targetLatency=e}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(e){this.levelController.pathwayPriority=e}get bufferedToEnd(){var e;return!!((e=this.bufferController)!=null&&e.bufferedToEnd)}get interstitialsManager(){return this.interstitialsController?.interstitialsManager||null}getMediaDecodingInfo(e,t=this.allAudioTracks){return $V(e,bH(t),navigator.mediaCapabilities)}};wZ.defaultConfig=void 0;function TZ(e,t){return e.name!==void 0&&e.name.length>0?e.name:e.height!==void 0&&e.height>0?`${e.height}p`:e.bitrate!==void 0&&e.bitrate>0?`${Math.round(e.bitrate/1e3)} kbps`:`Level ${t+1}`}function EZ(e){return[{value:-1,label:`Auto`},...e.map((e,t)=>({value:t,label:TZ(e,t)}))]}function DZ(e){return{height:e.height>0?e.height:void 0,bitrate:e.bitrate>0?e.bitrate:void 0,name:e.name.length>0?e.name:void 0}}function OZ({url:e,authToken:t,posterUrl:n,autoPlay:r=!0,className:i,onQualityOptions:a,selectedLevel:o=-1}){let s=p(null),l=p(null),[u,d]=h(null),[f,m]=h(!0);return c(()=>{let n=s.current;if(!n||!e)return;d(null),m(!0),a?.([]);let i=()=>m(!1);if(n.addEventListener(`playing`,i),wZ.isSupported()){let o=new wZ({enableWorker:!0,lowLatencyMode:!1,xhrSetup:e=>{e.withCredentials=!0,t&&e.setRequestHeader(`Authorization`,`Bearer ${t}`)}});return l.current=o,o.loadSource(e),o.attachMedia(n),o.on(wZ.Events.MANIFEST_PARSED,(e,t)=>{let i=t.levels.map(DZ);a?.(i.length>1?EZ(i):[]),r&&n.play().catch(()=>{})}),o.on(wZ.Events.ERROR,(e,t)=>{t.fatal&&(m(!1),d(`Playback error (${t.type}).`))}),()=>{n.removeEventListener(`playing`,i),l.current=null,o.destroy()}}if(n.canPlayType(`application/vnd.apple.mpegurl`)){n.src=e;let t=()=>{r&&n.play().catch(()=>{})};return n.addEventListener(`loadedmetadata`,t),n.addEventListener(`error`,()=>d(`Could not load this recording.`)),()=>{n.removeEventListener(`loadedmetadata`,t),n.removeEventListener(`playing`,i),n.removeAttribute(`src`),n.load()}}return m(!1),d(`HLS playback is not supported in this browser.`),()=>n.removeEventListener(`playing`,i)},[e,t,r,a]),c(()=>{let e=l.current;e!==null&&(e.currentLevel=o)},[o]),T(`div`,{className:`relative h-full w-full bg-black ${i??``}`,children:[v(`video`,{ref:s,controls:!0,playsInline:!0,className:`h-full w-full`,...n?{poster:n}:{}}),f&&!u?v(`div`,{className:`pointer-events-none absolute inset-0 flex items-center justify-center`,children:v(`div`,{className:`h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/60`})}):null,u?v(`div`,{className:`absolute inset-0 flex items-center justify-center px-4 text-center text-sm text-amber-400`,children:u}):null]})}function kZ(e){return e===`streaming`?`bg-emerald-500`:e===`connecting`?`bg-amber-500`:e===`error`?`bg-rose-500`:`bg-zinc-500`}function AZ(e){let t=Math.floor(e/1e3);return t<60?`${t}s`:t<3600?`${Math.floor(t/60)}m`:`${Math.floor(t/3600)}h${Math.floor(t%3600/60)}m`}function jZ({className:e}){return v(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:v(`polygon`,{points:`5 3 19 12 5 21 5 3`})})}function MZ({className:e}){return v(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`currentColor`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:v(`rect`,{x:`6`,y:`6`,width:`12`,height:`12`,rx:`1`})})}function NZ({className:e}){return T(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[v(`path`,{d:`M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z`}),v(`path`,{d:`M19 10v2a7 7 0 0 1-14 0v-2`}),v(`line`,{x1:`12`,y1:`19`,x2:`12`,y2:`23`}),v(`line`,{x1:`8`,y1:`23`,x2:`16`,y2:`23`})]})}function PZ({className:e}){return T(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`currentColor`,children:[v(`circle`,{cx:`5`,cy:`12`,r:`2`}),v(`circle`,{cx:`12`,cy:`12`,r:`2`}),v(`circle`,{cx:`19`,cy:`12`,r:`2`})]})}function FZ({label:e,active:t,onClick:n}){return T(`button`,{type:`button`,onClick:n,className:`w-full flex items-center justify-between gap-3 px-3 py-1.5 text-[11px] text-foreground hover:bg-surface-hover transition-colors`,children:[v(`span`,{children:e}),v(`span`,{className:`inline-block h-3 w-5 rounded-full transition-colors ${t?`bg-primary`:`bg-foreground-subtle/30`} relative`,children:v(`span`,{className:`absolute top-0.5 h-2 w-2 rounded-full bg-white transition-all ${t?`left-2.5`:`left-0.5`}`})})]})}function IZ({className:e}){return T(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[v(`circle`,{cx:`12`,cy:`12`,r:`2`,fill:`currentColor`}),v(`path`,{d:`M16.24 7.76a6 6 0 0 1 0 8.49M7.76 16.24a6 6 0 0 1 0-8.49M19.07 4.93a10 10 0 0 1 0 14.14M4.93 19.07a10 10 0 0 1 0-14.14`})]})}function LZ({className:e}){return T(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[v(`polyline`,{points:`23 4 23 10 17 10`}),v(`polyline`,{points:`1 20 1 14 7 14`}),v(`path`,{d:`M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15`})]})}function RZ({className:e}){return T(`svg`,{className:e,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:[v(`line`,{x1:`2`,y1:`2`,x2:`22`,y2:`22`}),v(`path`,{d:`M10.41 10.41a2 2 0 11-2.83-2.83`}),v(`line`,{x1:`13.5`,y1:`13.5`,x2:`6`,y2:`21`}),v(`path`,{d:`M18 12l-1.5-1.5`}),v(`path`,{d:`M21 15V5a2 2 0 00-2-2H5`}),v(`path`,{d:`M21 21H5a2 2 0 01-2-2V11`})]})}function zZ({serverUrl:e,createSession:t,sendAnswer:n,handleOffer:r,getIceServers:i,addIceCandidate:a,getIceCandidates:s,closeSession:l,getSessionState:d,playbackUrl:f,playbackAuthToken:m,onExitPlayback:g,posterUrl:_,streams:y,activeStreamId:b,onStreamChange:x,deviceName:S,phase:C,pipelineMetrics:w,detections:D,defaultShowDetections:O=!0,defaultShowMotion:k=!1,streamStats:A,autoPlay:j=!1,showPlayStop:M=!1,snapshotSrc:N,snapshotLoading:P=!1,onRefreshSnapshot:ee,showStreamStats:F=!1,children:te,extraOverlay:I,ptzAvailable:L=!1,ptzShown:ne=!1,ptzOverlay:R,onPtzToggle:re,intercomAvailable:ie=!1,intercomShown:ae=!1,onIntercomToggle:z,chromeless:oe=!1,className:se}){let ce=fI(),[le,ue]=h(j),[de,fe]=h(O),[pe,me]=h(k),[he,B]=h(null),[ge,_e]=h([]),[V,ve]=h(-1),[ye,be]=h(!1),xe=p(null);c(()=>{if(!ye)return;function e(e){xe.current&&!xe.current.contains(e.target)&&be(!1)}return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[ye]),c(()=>{ve(-1)},[f]);let Se=u(e=>{_e(e)},[]),Ce=b??he??y?.[0]?.id??``,we=y?.find(e=>e.id===Ce)??y?.[0],Te=we?.inputFps==null?null:{status:we.status??`unknown`,inputFps:we.inputFps,bitrateKbps:we.bitrateKbps??0},Ee=e=>{B(e),x?.(e),le&&M&&(ue(!1),setTimeout(()=>ue(!0),50))},De=o(()=>{let e=we?.target;if(!(!e||!t))return n=>t(e,n)},[t,we]),Oe=o(()=>{let e=we?.target;if(!(!e||!r))return(t,n)=>r(e,t,n)},[r,we]),H=o(()=>{if(r)return(e,t,n)=>r(n,t,e)},[r]),ke=y,Ae=()=>ue(!0),je=()=>ue(!1),Me=w?.phase??C,Ne=Me===`active`,Pe=!!D,Fe=Pe&&(de||pe),Ie=L&&ne&&!!R,Le=!!f,Re=Le||(M?le:!0);return T(`div`,{className:`overflow-hidden ${oe?``:`rounded-xl border border-border bg-surface`} ${se??``}`,children:[T(`div`,{className:`flex flex-wrap items-center justify-between gap-2 px-3 py-2 border-b border-border`,children:[T(`div`,{className:`flex items-center gap-2 min-w-0`,children:[(A??Te)&&v(`span`,{className:`shrink-0 w-2 h-2 rounded-full ${kZ((A??Te).status)}`}),S&&v(`span`,{className:`text-xs font-medium text-foreground truncate`,children:S}),!Le&&ke&&ke.length>1&&T(`div`,{className:`relative`,children:[v(`select`,{"data-testid":`stream-profile-select`,value:Ce,onChange:e=>Ee(e.target.value),className:`appearance-none cursor-pointer rounded-md border border-border bg-surface-hover hover:bg-surface text-foreground text-[11px] font-medium pl-2 pr-6 py-1 focus:outline-none focus:ring-1 focus:ring-primary transition-colors`,children:ke.map(e=>v(`option`,{value:e.id,children:e.label},e.id))}),v(`span`,{className:`pointer-events-none absolute right-1.5 top-1/2 -translate-y-1/2 text-foreground-subtle`,children:v(`svg`,{className:`h-2.5 w-2.5`,viewBox:`0 0 12 12`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:v(`polyline`,{points:`3 4.5 6 7.5 9 4.5`})})})]}),Le&&ge.length>1&&T(`div`,{className:`relative`,children:[v(`select`,{"data-testid":`vod-quality-select`,value:V,onChange:e=>ve(Number(e.target.value)),className:`appearance-none cursor-pointer rounded-md border border-border bg-surface-hover hover:bg-surface text-foreground text-[11px] font-medium pl-2 pr-6 py-1 focus:outline-none focus:ring-1 focus:ring-primary transition-colors`,children:ge.map(e=>v(`option`,{value:e.value,children:e.label},e.value))}),v(`span`,{className:`pointer-events-none absolute right-1.5 top-1/2 -translate-y-1/2 text-foreground-subtle`,children:v(`svg`,{className:`h-2.5 w-2.5`,viewBox:`0 0 12 12`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:v(`polyline`,{points:`3 4.5 6 7.5 9 4.5`})})})]})]}),T(`div`,{className:`flex items-center gap-1.5 shrink-0 ml-auto`,children:[ie&&!Le&&T(`button`,{"data-testid":`stream-intercom-toggle`,"data-intercom-shown":ae?`true`:`false`,onClick:z,className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors ${ae?`bg-primary/15 text-primary`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,title:ae?`Close intercom`:`Open intercom`,children:[v(NZ,{className:`h-3 w-3`}),v(`span`,{className:`hidden xl:inline`,children:`Intercom`})]}),ce.map(e=>{let t=e.tone===`primary`?`bg-primary text-primary-foreground`:`bg-primary/15 text-primary`;return T(`button`,{type:`button`,"data-toolbar-button-id":e.id,"data-toolbar-button-active":e.active?`true`:`false`,onClick:e.onClick,disabled:e.disabled,className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors disabled:opacity-50 ${e.active?t:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`}`,title:e.title??e.label,children:[e.icon,v(`span`,{className:`hidden xl:inline`,children:e.label})]},e.id)}),M&&T(`button`,{"data-testid":`stream-play-toggle`,"data-stream-playing":Re?`true`:`false`,"data-vod":Le?`true`:`false`,onClick:Le?g:Re?je:Ae,className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors ${Le?`bg-primary/10 text-primary hover:bg-primary/20`:Re?`bg-danger/10 text-danger hover:bg-danger/20`:`bg-primary/10 text-primary hover:bg-primary/20`}`,title:Le?`Return to live`:Re?`Stop stream`:`Start stream`,children:[v(Le?IZ:Re?MZ:jZ,{className:`h-3 w-3`}),v(`span`,{className:`hidden xl:inline`,children:Le?`Live`:Re?`Stop`:`Play`})]}),ee&&!Le&&T(`button`,{"data-testid":`stream-snapshot-refresh`,onClick:ee,disabled:P,className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50`,title:`Force snapshot refresh`,children:[v(LZ,{className:`h-3 w-3 ${P?`animate-spin`:``}`}),v(`span`,{className:`hidden xl:inline`,children:`Snapshot`})]}),(Pe||L||w||Me||A||Te&&Te.inputFps>0)&&T(`div`,{ref:xe,className:`relative`,children:[v(`button`,{onClick:()=>be(e=>!e),title:`More controls`,className:`inline-flex items-center justify-center rounded-md p-1 text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,children:v(PZ,{className:`h-3.5 w-3.5`})}),ye&&T(`div`,{className:`absolute right-0 top-full mt-1 z-30 min-w-[200px] rounded-lg border border-border bg-surface shadow-xl py-1.5`,children:[F&&A&&T(`div`,{className:`px-3 py-1.5 text-[10px] text-foreground-subtle border-b border-border-subtle`,children:[T(`div`,{className:`flex justify-between gap-3`,children:[v(`span`,{children:`Input`}),T(`span`,{className:`tabular-nums text-foreground`,children:[A.inputFps.toFixed(1),` fps`]})]}),T(`div`,{className:`flex justify-between gap-3`,children:[v(`span`,{children:`Decode`}),T(`span`,{className:`tabular-nums text-foreground`,children:[A.decodeFps.toFixed(1),` fps`]})]}),T(`div`,{className:`flex justify-between gap-3`,children:[v(`span`,{children:`Uptime`}),v(`span`,{className:`tabular-nums text-foreground`,children:AZ(A.uptimeMs)})]})]}),!F&&Te&&Te.inputFps>0&&T(`div`,{className:`px-3 py-1.5 text-[10px] text-foreground-subtle border-b border-border-subtle`,children:[T(`div`,{className:`flex justify-between gap-3`,children:[v(`span`,{children:`Input`}),T(`span`,{className:`tabular-nums text-foreground`,children:[Te.inputFps.toFixed(1),` fps`]})]}),Te.bitrateKbps>0&&T(`div`,{className:`flex justify-between gap-3`,children:[v(`span`,{children:`Bitrate`}),T(`span`,{className:`tabular-nums text-foreground`,children:[Te.bitrateKbps,` kbps`]})]})]}),(w||Pe&&Me)&&T(`div`,{className:`px-3 py-1.5 text-[10px] text-foreground-subtle border-b border-border-subtle`,children:[T(`div`,{className:`flex justify-between gap-3 items-center`,children:[v(`span`,{children:`Phase`}),T(`span`,{className:`flex items-center gap-1 font-semibold uppercase tracking-wider ${Ne?`text-red-400`:`text-emerald-400`}`,children:[v(`span`,{className:`w-1.5 h-1.5 rounded-full ${Ne?`bg-red-500 animate-pulse`:`bg-emerald-500`}`}),Ne?`Active`:`Watching`]})]}),w&&w.detectionFps>0&&T(`div`,{className:`flex justify-between gap-3`,children:[v(`span`,{children:`Detection`}),T(`span`,{className:`tabular-nums text-foreground`,children:[w.detectionFps.toFixed(1),` det/s`]})]}),w&&w.avgInferenceMs>0&&T(`div`,{className:`flex justify-between gap-3`,children:[v(`span`,{children:`Inference`}),T(`span`,{className:`tabular-nums text-foreground`,children:[w.avgInferenceMs.toFixed(0),` ms`]})]})]}),Pe&&T(E,{children:[v(FZ,{label:`Show detections`,active:de,onClick:()=>fe(e=>!e)}),v(FZ,{label:`Show motion`,active:pe,onClick:()=>me(e=>!e)})]}),L&&v(FZ,{label:`PTZ controls`,active:ne,onClick:()=>{re?.(),be(!1)}})]})]})]})]}),f?T(`div`,{className:`aspect-video relative`,children:[v(OZ,{url:f,authToken:m??null,onQualityOptions:Se,selectedLevel:V,..._?{posterUrl:_}:{}}),I||Ie?T(E,{children:[I,Ie&&R]}):null]}):Re&&e?v(`div`,{className:`aspect-video relative`,children:v(oB,{serverUrl:e,streamKey:Ce,autoPlay:!0,className:`w-full h-full`,createSession:De,sendAnswer:n,handleOffer:Oe,reoffer:H,getSessionState:d,getIceServers:i,addIceCandidate:a,getIceCandidates:s,closeSession:l,..._?{posterUrl:_}:{},overlay:Fe||I||Ie?T(E,{children:[Fe&&v(Yz,{detections:D,showPhaseIndicator:!1,showMotionZones:pe,showMotionRaw:pe,showDetections:de}),I,Ie&&R]}):void 0},Ce)}):v(BZ,{src:N??null,isLoading:P,onPlay:Ae,onRetry:ee,extraOverlay:I||Ie?T(E,{children:[I,Ie&&R]}):null,suppressPlayHover:!!I||Ie}),te]})}function BZ({src:e,isLoading:t,onPlay:n,onRetry:r,extraOverlay:i,suppressPlayHover:a=!1}){return e?T(`div`,{className:`relative w-full aspect-video bg-black/90 flex items-center justify-center`,children:[v(`img`,{src:e,alt:`Camera snapshot`,className:`w-full h-full object-contain`}),!a&&v(`button`,{onClick:n,className:`absolute inset-0 flex items-center justify-center bg-black/30 opacity-0 hover:opacity-100 transition-opacity cursor-pointer`,children:v(`div`,{className:`h-14 w-14 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center`,children:v(jZ,{className:`h-7 w-7 text-white ml-0.5`})})}),i]}):t?v(`div`,{className:`relative w-full aspect-video bg-black/90 flex items-center justify-center`,children:v(`div`,{className:`h-8 w-8 border-2 border-white/20 border-t-white/60 rounded-full animate-spin`})}):v(`div`,{className:`relative w-full aspect-video bg-black/90 flex items-center justify-center`,children:T(`div`,{className:`flex flex-col items-center gap-2 text-white/40`,children:[v(RZ,{className:`h-8 w-8`}),v(`span`,{className:`text-xs`,children:`No snapshot available`}),T(`div`,{className:`flex items-center gap-2 mt-1`,children:[r&&T(`button`,{onClick:r,className:`inline-flex items-center gap-1.5 rounded-md border border-white/20 px-3 py-1.5 text-xs font-medium text-white/60 hover:text-white hover:border-white/40 transition-colors`,children:[v(LZ,{className:`h-3 w-3`}),`Retry`]}),T(`button`,{onClick:n,className:`inline-flex items-center gap-1.5 rounded-md bg-primary/80 px-3 py-1.5 text-xs font-medium text-white hover:bg-primary transition-colors`,children:[v(jZ,{className:`h-3 w-3`}),`Play Live`]})]})]})})}var VZ={value:`auto`,label:`Auto (best available)`};function HZ(e){return e.charAt(0).toUpperCase()+e.slice(1)}function UZ({deviceId:e,value:t,onChange:n,disabled:r,label:i,className:a}){let o=D(),s=Pg({deviceId:e},{refetchOnWindowFocus:!1}),[l,u]=h([VZ]);c(()=>{if(!s.data)return;let t=`${e}/`,n=[VZ];for(let e of s.data){if(!e.enabled)continue;let r=e.brokerId.startsWith(t)?e.brokerId.slice(t.length):e.brokerId;n.push({value:r,label:HZ(r)})}u(n)},[s.data,e]);let d=i??`Preferred stream`,f=s.isLoading?`Loading available streams…`:s.isError?`Could not load streams — only Auto available.`:l.length===1?`No enabled streams found — only Auto available.`:null;return T(`div`,{className:a,children:[v(`label`,{id:o,className:`text-xs font-medium text-foreground-muted block mb-1`,children:d}),v(Gu,{"aria-labelledby":o,options:l,value:t,disabled:r,onChange:e=>n(e.target.value)}),f!==null&&v(`p`,{className:`text-foreground-subtle text-[10px] mt-1`,children:f})]})}var WZ=2e3;function GZ({value:e,label:t,className:n,disabled:r}){let[i,a]=h(!1),o=u(()=>{e&&navigator.clipboard.writeText(e).then(()=>{a(!0),setTimeout(()=>a(!1),WZ)})},[e]);return T(ju,{size:`sm`,variant:`ghost`,type:`button`,disabled:r||e.length===0,onClick:o,className:G(n),"aria-label":i?`Copied`:`Copy ${t??`value`}`,children:[i?v(Ys,{className:`h-3.5 w-3.5 text-success`}):v(vc,{className:`h-3.5 w-3.5`}),t?v(`span`,{className:`ml-1`,children:i?`Copied`:t}):null]})}var KZ=me(xe),qZ=he({id:de(),stableId:fe(),addonId:fe(),type:fe(),name:fe(),online:pe(),disabled:pe(),parentDeviceId:de().nullable(),role:fe().nullable().optional(),features:me(fe()).optional(),isCamera:pe().optional(),sourceInfo:_e.optional()}),JZ=me(fe()),YZ=1e4;function XZ(e){return e===`linked`?`success`:e===`error`?`danger`:`warning`}function ZZ(e){return e===`linked`?`Linked`:e===`unlinked`?`Unlinked`:e===`error`?`Error`:e}function QZ({field:e}){let[t,n]=h(!1),r=e.secret===!0,i=r&&!t?`•`.repeat(Math.min(e.value.length,24)):e.value;return T(`div`,{className:`flex items-center gap-2 py-1.5`,children:[v(`span`,{className:`text-[11px] text-foreground-subtle w-32 shrink-0`,children:e.label}),v(`span`,{className:`flex-1 min-w-0 truncate font-mono text-xs text-foreground`,children:i||`—`}),r&&v(ju,{size:`sm`,variant:`ghost`,type:`button`,"aria-label":t?`Hide value`:`Reveal value`,onClick:()=>n(e=>!e),children:v(t?kc:Ac,{className:`h-3.5 w-3.5`})}),v(GZ,{value:e.value,label:e.label})]})}function $Z({setup:e}){let t=e.fields??[];return T(`div`,{className:`border-b border-border bg-surface-hover/10`,children:[T(`div`,{className:`flex items-center gap-2 px-4 py-2 border-b border-border`,children:[v(Ol,{className:`h-3.5 w-3.5 text-foreground-subtle shrink-0`}),v(`span`,{className:`text-[11px] font-semibold text-foreground-subtle uppercase tracking-wide`,children:`Setup`})]}),T(`div`,{className:`flex flex-col gap-3 p-4 sm:flex-row sm:items-start`,children:[e.qr&&v(`div`,{className:`shrink-0`,children:v(KR,{value:e.qr,alt:`Pairing QR code`})}),T(`div`,{className:`flex-1 min-w-0`,children:[e.note&&v(`p`,{className:`text-xs text-foreground-muted whitespace-pre-line mb-2`,children:e.note}),t.length>0&&v(`div`,{className:`divide-y divide-border-subtle`,children:t.map(e=>v(QZ,{field:e},e.label))})]})]})]})}function eQ({addonId:e,deviceId:t,exposed:n,busy:r,onExpose:i,onUnexpose:a}){return v(ju,{size:`sm`,variant:n?`ghost`:`primary`,disabled:r,onClick:e=>{e.stopPropagation(),!r&&(n?a(t):i(t))},title:n?`Stop exposing to "${e}"`:`Expose to "${e}"`,children:n?T(E,{children:[v(uu,{className:`mr-1 h-3.5 w-3.5`}),`Exposed`]}):T(E,{children:[v(Bl,{className:`mr-1 h-3.5 w-3.5`}),`Expose`]})})}function tQ({addonId:e,trpc:t,onOpenDevice:n}){let r=b(),i=F_({nodeId:`hub`,addonId:e},{refetchInterval:YZ,retry:!1}),a=L_({nodeId:`hub`,addonId:e},{refetchInterval:YZ,retry:!1}),s=I_({nodeId:`hub`,addonId:e},{retry:!1}),c=pv({},{refetchInterval:5e3}),l=u(()=>{r.invalidateQueries({queryKey:[[`deviceExport`]]})},[r]),d=R_({onSuccess:l}),f=z_({onSuccess:l}),p=o(()=>{let e=ve.safeParse(i.data);return e.success?e.data:null},[i.data]),m=o(()=>{let e=KZ.safeParse(a.data);return e.success?e.data:[]},[a.data]),h=o(()=>new Set(m.map(e=>e.deviceId)),[m]),g=o(()=>{let e=JZ.safeParse(s.data);return new Set(e.success?e.data:[])},[s.data]),_=o(()=>[...g].toSorted(),[g]),y=o(()=>_.map(e=>{let t=cp(e);return{id:e,label:t.label,icon:t.icon}}),[_]),x=o(()=>{let e=c.data;if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=qZ.safeParse(n);e.success&&g.has(e.data.type)&&t.push(e.data)}return t},[c.data,g]),S=p?.linkState??`unlinked`,C=i.isLoading||a.isLoading||s.isLoading||c.isLoading,w=p?.exposedDeviceCount??h.size,E=d.isPending||f.isPending,D=u(t=>{d.mutate({deviceId:t,nodeId:`hub`,addonId:e})},[d,e]),O=u(t=>{f.mutate({deviceId:t,nodeId:`hub`,addonId:e})},[f,e]),k=u(t=>{let n=String(t.id);return v(eQ,{addonId:e,deviceId:n,exposed:h.has(n),busy:E,onExpose:D,onUnexpose:O})},[e,h,E,D,O]),A=u(e=>n?.(String(e)),[n]),j=_.length>0;return T(`div`,{className:`rounded-lg border border-border bg-surface overflow-hidden`,children:[T(`div`,{className:`flex items-center justify-between gap-3 px-4 py-2.5 border-b border-border bg-surface-hover/20`,children:[T(`div`,{className:`flex items-center gap-2 min-w-0`,children:[v(Bl,{className:`h-3.5 w-3.5 text-foreground-subtle shrink-0`}),v(`span`,{className:`text-[11px] font-semibold text-foreground-subtle uppercase tracking-wide`,children:`Exported devices`}),v(Fu,{variant:XZ(S),children:ZZ(S)}),T(`span`,{className:`text-[11px] text-foreground-subtle`,children:[w,` exposed`]})]}),C&&v(el,{className:`h-3.5 w-3.5 animate-spin text-foreground-subtle`})]}),p?.error&&v(`div`,{className:`px-4 py-3 border-b border-border`,children:v(Ff,{message:p.error})}),p?.setup&&v($Z,{setup:p.setup}),v(`div`,{className:`p-3`,children:j&&x.length>0?v(SN,{devices:x,trpc:t,defaultView:`table`,filters:{typeOptions:y},urlScope:`nested`,lsKey:`device-export:${e}`,onNavigate:n?A:void 0,renderRowAction:k}):v(Nf,{icon:Bl,title:`No exportable devices`,description:j?`No devices of the supported kinds (${_.join(`, `)}) are available to expose to "${e}".`:`"${e}" reports no exportable device kinds yet.`})})]})}function nQ({samples:e,sampleRate:t=16e3,height:n=96,className:r=``,color:i=`#3b82f6`,bgColor:a=`transparent`}){let o=p(null),s=p(null),l=u(()=>{let t=o.current,r=s.current;if(!t||!r||!e||e.length===0)return;let c=r.clientWidth;if(c===0)return;let l=window.devicePixelRatio||1;t.width=c*l,t.height=n*l,t.style.width=`${c}px`,t.style.height=`${n}px`;let u=t.getContext(`2d`);if(!u)return;u.scale(l,l),a===`transparent`?u.clearRect(0,0,c,n):(u.fillStyle=a,u.fillRect(0,0,c,n));let d=e.length/c,f=n/2;u.fillStyle=i,u.globalAlpha=.7;for(let t=0;t<c;t++){let n=Math.floor(t*d),r=Math.min(Math.floor((t+1)*d),e.length),i=0,a=0;for(let t=n;t<r;t++){let n=e[t];n<i&&(i=n),n>a&&(a=n)}let o=f-a*f,s=f-i*f,c=Math.max(1,s-o);u.fillRect(t,o,1,c)}u.globalAlpha=1,u.strokeStyle=i,u.globalAlpha=.2,u.lineWidth=1,u.beginPath(),u.moveTo(0,f),u.lineTo(c,f),u.stroke(),u.globalAlpha=1},[e,n,i,a]);c(()=>{l()},[l]),c(()=>{let e=new ResizeObserver(()=>l()),t=s.current;return t&&e.observe(t),()=>e.disconnect()},[l]);let d=((e&&t?Math.round(e.length/t*1e3):0)/1e3).toFixed(1);return T(`div`,{ref:s,className:`relative ${r}`,children:[v(`canvas`,{ref:o,className:`w-full rounded-md`}),e&&e.length>0&&T(`div`,{className:`absolute bottom-1 right-2 text-[10px] text-foreground-subtle/60 font-mono`,children:[d,`s · `,t/1e3,`kHz · `,e.length.toLocaleString(),` samples`]})]})}function rQ({currentDbfs:e,durationSec:t=30,maxSamples:n=120,height:r=64,className:i=``,color:a=`#10b981`,clipColor:o=`#ef4444`,clipThreshold:s=-6,minDbfs:l=-96}){let d=p(null),f=p(null),[m,g]=h([]);c(()=>{e!==null&&g(t=>{let r=[...t,{dbfs:e,timestamp:Date.now()}];return r.length>n?r.slice(-n):r})},[e,n]);let _=u(()=>{let e=d.current,n=f.current;if(!e||!n)return;let i=n.clientWidth;if(i===0)return;let c=window.devicePixelRatio||1;e.width=i*c,e.height=r*c,e.style.width=`${i}px`,e.style.height=`${r}px`;let u=e.getContext(`2d`);if(!u||(u.scale(c,c),u.clearRect(0,0,i,r),m.length===0))return;let p=m[m.length-1].timestamp,h=t*1e3,g=p-h,_=m.filter(e=>e.timestamp>=g);if(_.length===0)return;let v=Math.max(1,Math.floor(i/(t*2))),y=Math.abs(l);for(let e of _){let t=e.timestamp-g,n=Math.floor(t/h*i),c=(Math.max(l,Math.min(0,e.dbfs))-l)/y,d=Math.max(1,c*r);u.fillStyle=e.dbfs>=s?o:a,u.globalAlpha=.8,u.fillRect(n,r-d,v,d)}u.globalAlpha=1;let b=r-(s-l)/y*r;u.strokeStyle=o,u.globalAlpha=.25,u.lineWidth=1,u.setLineDash([4,4]),u.beginPath(),u.moveTo(0,b),u.lineTo(i,b),u.stroke(),u.setLineDash([]),u.globalAlpha=1},[m,t,r,a,o,s,l]);c(()=>{_()},[_]),c(()=>{let e=new ResizeObserver(()=>_()),t=f.current;return t&&e.observe(t),()=>e.disconnect()},[_]);let y=m.length>0?m[m.length-1].dbfs:null;return T(`div`,{ref:f,className:`relative ${i}`,children:[v(`canvas`,{ref:d,className:`w-full rounded-md`}),T(`div`,{className:`absolute top-1 left-2 text-[9px] text-foreground-subtle/50 font-mono`,children:[t,`s`]}),y!==null&&T(`div`,{className:`absolute bottom-1 right-2 text-[9px] text-foreground-subtle/50 font-mono`,children:[y.toFixed(1),` dBFS · `,m.length,` samples`]})]})}function iQ(e){return e>=.8?`bg-emerald-500`:e>=.5?`bg-amber-500`:e>=.3?`bg-orange-500`:`bg-zinc-500`}function aQ(e){return e>=.8?`text-emerald-400`:e>=.5?`text-amber-400`:e>=.3?`text-orange-400`:`text-zinc-400`}function oQ({classifications:e,processing:t=!1,inferenceMs:n,maxItems:r=10,className:i=``}){let a=e.slice(0,r),o=a.length>0?a[0].score:1;return t?v(`div`,{className:`rounded-xl border border-border bg-surface p-4 text-center ${i}`,children:v(`div`,{className:`text-sm text-foreground-subtle animate-pulse`,children:`Classifying audio...`})}):a.length===0?v(`div`,{className:`rounded-xl border border-border bg-surface p-4 text-center ${i}`,children:v(`div`,{className:`text-xs text-foreground-subtle`,children:`No classifications yet`})}):T(`div`,{className:`rounded-xl border border-border bg-surface overflow-hidden ${i}`,children:[T(`div`,{className:`px-3 py-2 border-b border-border flex items-center justify-between`,children:[v(`h3`,{className:`text-xs font-medium text-foreground`,children:`Audio Classifications`}),T(`div`,{className:`flex items-center gap-3 text-[10px] text-foreground-subtle`,children:[a.length<e.length&&T(`span`,{children:[`showing `,a.length,` of `,e.length]}),n!==void 0&&T(`span`,{className:`font-mono`,children:[n.toFixed(1),`ms`]})]})]}),v(`div`,{className:`divide-y divide-border/50`,children:a.map((e,t)=>{let n=o>0?e.score/o*100:0;return T(`div`,{className:`px-3 py-1.5 flex items-center gap-3 hover:bg-surface-hover/30`,children:[v(`span`,{className:`text-[10px] text-foreground-subtle w-5 text-right font-mono`,children:t+1}),v(`span`,{className:`text-xs font-medium text-foreground min-w-[120px]`,children:e.className}),v(`div`,{className:`flex-1 h-2 rounded-full bg-zinc-800 overflow-hidden`,children:v(`div`,{className:`h-full rounded-full transition-all duration-300 ${iQ(e.score)}`,style:{width:`${n}%`}})}),T(`span`,{className:`text-xs font-mono font-semibold w-14 text-right ${aQ(e.score)}`,children:[(e.score*100).toFixed(1),`%`]})]},`${e.className}-${t}`)})})]})}function sQ({data:e,label:t=`Response`,className:n=``}){let[r,i]=h(!1);if(!e)return null;let a=JSON.stringify(e,null,2);return T(`div`,{className:`rounded-xl border border-border bg-surface overflow-hidden ${n}`,children:[T(`div`,{className:`px-3 py-2 border-b border-border flex items-center justify-between cursor-pointer select-none hover:bg-surface-hover/30`,onClick:()=>i(e=>!e),children:[T(`div`,{className:`flex items-center gap-2`,children:[v(`span`,{className:`text-[10px] text-foreground-subtle`,children:r?`▼`:`▶`}),v(`h3`,{className:`text-xs font-medium text-foreground`,children:t})]}),v(`span`,{className:`text-[10px] text-foreground-subtle font-mono`,children:a.length>1e3?`${(a.length/1024).toFixed(1)} KB`:`${a.length} bytes`})]}),r&&v(`div`,{className:`max-h-80 overflow-y-auto overflow-x-auto`,children:v(`pre`,{className:`p-3 text-[10px] leading-4 font-mono text-foreground-subtle whitespace-pre`,children:a})})]})}var cQ={Activity:Ds,Eye:Ac,AlertTriangle:cu,PauseCircle:oc,PowerOff:El};function lQ({phase:e,...t}){let n=cQ[mr(e).icon];return v(n,{...t})}function uQ(e){let[t,n]=h([]),r=u(t=>{n(n=>{let r=[...n,t];return r.length>e?r.slice(-e):r})},[e]),i=u(()=>{n([])},[]);return o(()=>({entries:t,append:r,reset:i}),[t,r,i])}function dQ(e,t=40){return e.scrollHeight-e.scrollTop-e.clientHeight<=t}function fQ(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}var pQ={error:{icon:nc,color:`text-red-400`},warn:{icon:cu,color:`text-amber-400`},info:{icon:Yc,color:`text-blue-400`},debug:{icon:Ks,color:`text-gray-500`}},mQ={debug:0,info:1,warn:2,error:3},hQ=[`all`,`debug`,`info`,`warn`,`error`],gQ=500;function _Q(e,t){return t?(mQ[e]??0)>=(mQ[t]??0):!0}function vQ({agentId:e,addonId:t,deviceId:n,containerDeviceId:r,integrationId:i,requestId:a,level:s,maxHeight:l=`max-h-96`,showScope:d=!1,showFilters:f=!0,limit:g=100,liveBuffer:_,onClose:y,className:b}){let[x,S]=h(``),[C,w]=h(``),[E,D]=h(s),O=e,k=t??(x||void 0),A=n??(C?Number(C):void 0),j=i,M=a,N=o(()=>{let e={};return O&&(e.agentId=O),k&&(e.addonId=k),r!==void 0&&Number.isFinite(r)?e.containerDeviceId=r:A!==void 0&&Number.isFinite(A)&&(e.deviceId=A),j&&(e.integrationId=j),M&&(e.requestId=M),Object.keys(e).length>0?e:void 0},[O,k,A,r,j,M]),P=uQ(gQ),ee=_??P,F=ee.entries,[te,I]=h(0),[L,ne]=h(!0),R=p(!1),[re,ie]=h(!1),[ae,z]=h(!1),[oe,se]=h(new Set),[ce,le]=h(``),ue=p(null),de=`${O??``}:${k??``}:${String(A??``)}:${String(r??``)}:${j??``}:${M??``}`,fe=p(de);c(()=>{fe.current!==de&&(fe.current=de,ee.reset(),I(0),se(new Set),ie(!1))},[de,ee]);let{data:pe,isLoading:me}=q.logs.query.useQuery({...N?{tags:N}:{},limit:g},{staleTime:3e4});q.logs.subscribe.useSubscription(N?{tags:N}:{},{onData:e=>{ee.append(e)}});let he=o(()=>{let e=(pe??[]).map(e=>({timestamp:e.timestamp,level:e.level,message:e.message,scope:e.scope,tags:e.tags,meta:e.meta})),t=new Map;for(let n of e)t.set(`${n.timestamp}|${n.level}|${n.scope??``}|${n.message}`,n);for(let e of F)t.set(`${e.timestamp}|${e.level}|${e.scope??``}|${e.message}`,e);let n=[...t.values()].toSorted((e,t)=>new Date(e.timestamp).getTime()-new Date(t.timestamp).getTime()),r=(te>0?n.filter(e=>new Date(e.timestamp).getTime()>te):n).filter(e=>_Q(e.level,E)),i=ce.trim().toLowerCase();return i?r.filter(e=>{if(e.message.toLowerCase().includes(i)||e.scope&&e.scope.toLowerCase().includes(i))return!0;if(e.tags){for(let t of Object.values(e.tags))if(t!==void 0&&String(t).toLowerCase().includes(i))return!0}if(e.meta){for(let t of Object.values(e.meta))if(t!=null&&fQ(t).toLowerCase().includes(i))return!0}return!1}):r},[pe,F,E,te,ce]),B=u(e=>{let t=ue.current;t&&(R.current=!0,t.scrollTo({top:t.scrollHeight,...e?{behavior:e}:{}}))},[]),[ge,_e]=h(!1),V=p(he.length);m(()=>{let e=he.length>V.current;V.current=he.length,e&&(L?B():_e(!0))},[he.length,L,B]),c(()=>{L&&ge&&_e(!1)},[L,ge]);let ve=u(()=>{ne(!0),B(`smooth`)},[B]),ye=u(()=>{if(R.current){R.current=!1;return}let e=ue.current;if(!e)return;let t=dQ(e,40);ne(e=>e===t?e:t)},[]),be=o(()=>he.filter(e=>e.tags&&Object.keys(e.tags).length>0||e.meta&&Object.keys(e.meta).length>0).map(e=>`${e.timestamp}|${e.level}|${e.scope??``}|${e.message}`),[he]),xe=u(()=>{ie(e=>(e&&se(new Set),!e))},[]),Se=u(()=>{let e=he.map(e=>{let t=new Date(e.timestamp).toLocaleTimeString(),n=e.tags?` `+Object.entries(e.tags).filter(([,e])=>e).map(([e,t])=>`${e}=${t}`).join(` `):``;return`${t} [${e.level.toUpperCase()}]${e.scope?` [${e.scope}]`:``}${n} ${e.message}`});navigator.clipboard.writeText(e.join(`
74
- `)).then(()=>{z(!0),setTimeout(()=>z(!1),1500)})},[he]),Ce=q.logs.clear.useMutation(),we=u(()=>{I(Date.now()),ee.reset(),Ce.mutate(N?{tags:N}:{})},[ee,Ce,N]),Te=u(e=>{se(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),[Ee,De]=h(null),Oe=u((e,t)=>{let n=new Date(e.timestamp).toISOString(),r=e.tags?` `+Object.entries(e.tags).filter(([,e])=>e).map(([e,t])=>`${e}=${t}`).join(` `):``,i=e.meta&&Object.keys(e.meta).length>0?` meta=${JSON.stringify(e.meta)}`:``,a=`${n} [${e.level.toUpperCase()}]${e.scope?` [${e.scope}]`:``}${r} ${e.message}${i}`;navigator.clipboard.writeText(a).then(()=>{De(t),setTimeout(()=>De(e=>e===t?null:e),1200)})},[]),H=u(e=>`${e.timestamp}|${e.level}|${e.scope??``}|${e.message}`,[]);return T(`div`,{className:G(`h-full min-h-0 flex flex-col`,b),onClick:e=>e.stopPropagation(),children:[T(`div`,{className:`flex items-center justify-between px-3 py-1.5 bg-surface-hover/30 gap-2 shrink-0`,children:[T(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[v(`span`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle font-medium`,children:`Logs`}),O&&v(bQ,{label:`agent`,value:O}),k&&v(bQ,{label:`addon`,value:k}),A!==void 0&&v(bQ,{label:`device`,value:`#${A}`}),v(`div`,{className:`flex rounded border border-border overflow-hidden text-[9px]`,children:hQ.map(e=>T(`button`,{type:`button`,onClick:()=>D(e===`all`?void 0:e),className:G(`px-1.5 py-0.5 capitalize transition-colors`,e===`all`&&!E||E===e?`bg-primary/10 text-primary`:`text-foreground-subtle hover:bg-surface-hover`,e!==`all`&&`border-l border-border`),children:[e,e===`all`?``:`+`]},e))}),v(SQ,{icon:ks,label:L?`Following`:`Paused`,active:L,onClick:()=>{L?ne(!1):ve()}}),v(SQ,{icon:re?ec:tc,label:re?`Collapse`:`Expand`,active:re,onClick:xe,disabled:be.length===0}),v(SQ,{icon:vc,label:ae?`Copied!`:`Copy`,onClick:Se,disabled:he.length===0}),v(SQ,{icon:au,label:`Clear`,onClick:we}),T(`div`,{className:`relative`,children:[v(`input`,{type:`text`,value:ce,onChange:e=>le(e.target.value),placeholder:`Search…`,className:`w-32 pl-1.5 pr-5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50`}),ce&&v(`button`,{type:`button`,onClick:()=>le(``),className:`absolute right-1 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground`,title:`Clear search`,children:v(xu,{className:`h-2.5 w-2.5`})})]}),F.length>0&&T(`span`,{className:`text-[9px] text-emerald-400 font-medium`,children:[`+`,F.length,` live`]})]}),y&&v(`button`,{type:`button`,onClick:y,className:`text-foreground-subtle hover:text-foreground`,children:v(xu,{className:`h-3.5 w-3.5`})})]}),f&&(!t||!n)&&T(`div`,{className:`flex items-center gap-2 px-3 py-1 border-b border-border/50 bg-surface/50 text-[10px]`,children:[!t&&T(`label`,{className:`flex items-center gap-1`,children:[v(`span`,{className:`text-foreground-subtle`,children:`Addon:`}),v(`input`,{type:`text`,value:x,onChange:e=>S(e.target.value),placeholder:`all`,className:`w-28 px-1.5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50`})]}),!n&&T(`label`,{className:`flex items-center gap-1`,children:[v(`span`,{className:`text-foreground-subtle`,children:`Device:`}),v(`input`,{type:`text`,inputMode:`numeric`,value:C,onChange:e=>w(e.target.value),placeholder:`all`,className:`w-16 px-1.5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50`})]})]}),T(`div`,{className:`relative flex-1 min-h-0 flex flex-col`,children:[!L&&ge&&T(`button`,{type:`button`,onClick:ve,className:`absolute bottom-2 left-1/2 -translate-x-1/2 z-10 inline-flex items-center gap-1 px-2 py-1 rounded-full border border-primary/40 bg-primary/15 text-primary text-[10px] font-medium shadow-md backdrop-blur-sm hover:bg-primary/25 transition-colors`,title:`Jump to the newest log line and resume following`,children:[v(ks,{className:`h-3 w-3`}),`Jump to latest`]}),T(`div`,{ref:ue,onScroll:ye,className:G(`flex-1 min-h-0 overflow-auto font-mono text-[10px]`,l),children:[me&&T(`div`,{className:`flex items-center justify-center gap-2 py-6 text-foreground-subtle`,children:[v(el,{className:`h-3.5 w-3.5 animate-spin`}),`Loading logs...`]}),!me&&he.length===0&&v(`div`,{className:`py-4 text-center text-foreground-subtle`,children:`No logs found`}),he.length>0&&v(`table`,{className:`w-full`,children:v(`tbody`,{children:he.map(e=>{let t=pQ[e.level]??pQ.info,n=t.icon,r=H(e),i=re||oe.has(r),a=e.tags&&Object.keys(e.tags).length>0,o=e.meta&&Object.keys(e.meta).length>0,s=a||o;return T(`tr`,{className:G(`hover:bg-surface-hover/30 border-b border-border/30`,s&&`cursor-pointer`),onClick:s?()=>Te(r):void 0,children:[v(`td`,{className:`px-2 py-1 text-foreground-subtle whitespace-nowrap align-top w-[70px]`,children:new Date(e.timestamp).toLocaleTimeString()}),v(`td`,{className:G(`px-1 py-1 align-top w-5`,t.color),children:v(n,{className:`h-3 w-3`})}),d&&v(`td`,{className:`px-2 py-1 text-foreground-subtle align-top truncate max-w-[120px]`,title:e.scope,children:e.scope?.replace(/^addon:/,``)??``}),v(`td`,{className:`px-2 py-1 text-foreground break-all`,children:T(`div`,{className:`flex items-start gap-1`,children:[s&&v(i?Xs:Qs,{className:`h-3 w-3 text-foreground-subtle shrink-0 mt-0.5`}),T(`div`,{className:`flex-1 min-w-0`,children:[e.message,i&&s&&T(`div`,{className:`mt-0.5 pl-3 text-[9px] leading-snug`,children:[o&&Object.entries(e.meta).filter(([,e])=>e!==void 0&&e!==``).map(([e,t])=>T(`div`,{className:`break-all`,children:[v(`span`,{className:`text-amber-400/80`,children:e}),v(`span`,{className:`text-foreground-subtle`,children:`=`}),v(`span`,{className:`text-foreground`,children:fQ(t)})]},`m-${e}`)),a&&Object.entries(e.tags).filter(([,e])=>e!==void 0).map(([e,t])=>T(`div`,{className:`break-all`,children:[v(`span`,{className:`text-primary/70`,children:e}),v(`span`,{className:`text-foreground-subtle`,children:`=`}),v(`span`,{className:`text-foreground`,children:t})]},`t-${e}`))]})]})]})}),v(`td`,{className:`px-1 py-1 align-top w-5`,children:v(xQ,{copied:Ee===r,onCopy:()=>Oe(e,r)})})]},r)})})})]})]})]})}function yQ({position:e=`bottom`,className:t,...n}){return v(`div`,{className:G(e===`bottom`?`absolute bottom-0 left-0 right-0 z-10 border-t border-border bg-surface/95 backdrop-blur-sm`:`absolute inset-x-2 bottom-2 z-10 rounded-lg border border-border bg-surface/95 backdrop-blur-sm shadow-xl`,t),children:v(vQ,{maxHeight:`max-h-48`,...n})})}function bQ({label:e,value:t}){return T(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium`,children:[e,`: `,t]})}function xQ({copied:e,onCopy:t}){return v(`button`,{type:`button`,title:`Copy this row`,onClick:e=>{e.stopPropagation(),t()},className:G(`rounded p-0.5 transition-colors`,e?`text-emerald-400`:`text-foreground-subtle/60 hover:text-foreground hover:bg-surface-hover`),children:v(e?Ys:vc,{className:`h-3 w-3`})})}function SQ({icon:e,label:t,onClick:n,disabled:r,active:i}){return T(`button`,{type:`button`,onClick:n,disabled:r,className:G(`inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors`,i?`border-amber-500/30 bg-amber-500/10 text-amber-400`:`border-border text-foreground-subtle hover:text-foreground`,r&&`opacity-40 cursor-not-allowed`),children:[v(e,{className:`h-2.5 w-2.5`}),t]})}function CQ(e,t,n,r){if(r!==void 0&&(e.source.deviceId??(e.source.type===`device`&&typeof e.source.id==`number`?e.source.id:void 0))!==r||n!==void 0&&(e.source.addonId??(e.source.type===`addon`&&typeof e.source.id==`string`?e.source.id:void 0))!==n)return!1;if(t!==void 0){let n=e.source.nodeId;if(!n||n!==t&&!n.startsWith(`${t}/`))return!1}return!0}var wQ={[B.AddonStarted]:{icon:Cl,color:`bg-emerald-500/15 text-emerald-400 border-emerald-500/30`,label:`Started`},[B.AddonInstalled]:{icon:wc,color:`bg-emerald-500/15 text-emerald-400 border-emerald-500/30`,label:`Installed`},[B.AddonRestarted]:{icon:jl,color:`bg-blue-500/15 text-blue-400 border-blue-500/30`,label:`Restarted`},[B.AddonUpdated]:{icon:du,color:`bg-blue-500/15 text-blue-400 border-blue-500/30`,label:`Updated`},[B.AddonStopped]:{icon:Zl,color:`bg-foreground-subtle/10 text-foreground-subtle border-border`,label:`Stopped`},[B.AddonUninstalled]:{icon:au,color:`bg-foreground-subtle/10 text-foreground-subtle border-border`,label:`Uninstalled`},[B.AddonCrashed]:{icon:nc,color:`bg-red-500/15 text-red-400 border-red-500/30`,label:`Crashed`},[B.AddonError]:{icon:cu,color:`bg-red-500/15 text-red-400 border-red-500/30`,label:`Error`},[B.DetectionPhaseTransition]:{icon:Ds,color:`bg-violet-500/15 text-violet-400 border-violet-500/30`,label:`Phase`},[B.DetectionResult]:{icon:Fl,color:`bg-purple-500/15 text-purple-400 border-purple-500/30`,label:`Detection`},[B.DetectionEvent]:{icon:Ac,color:`bg-blue-500/15 text-blue-400 border-blue-500/30`,label:`Event`},[B.DetectionCameraNative]:{icon:tu,color:`bg-cyan-500/15 text-cyan-400 border-cyan-500/30`,label:`Camera AI`},[B.ProviderMotion]:{icon:Su,color:`bg-orange-500/15 text-orange-400 border-orange-500/30`,label:`Motion`},[B.MotionOnMotionChanged]:{icon:Su,color:`bg-orange-500/15 text-orange-400 border-orange-500/30`,label:`Motion`},[B.MotionAnalysis]:{icon:Ds,color:`bg-orange-500/10 text-orange-300 border-orange-500/20`,label:`Motion analysis`},[B.MotionZonesRaw]:{icon:Ds,color:`bg-orange-500/10 text-orange-300 border-orange-500/20`,label:`Motion zones`},[B.ProviderDetection]:{icon:tu,color:`bg-cyan-500/15 text-cyan-400 border-cyan-500/30`,label:`Provider Det`},[B.PipelineAudioInferenceResult]:{icon:ul,color:`bg-pink-500/15 text-pink-400 border-pink-500/30`,label:`Audio`},[B.AgentOnline]:{icon:Cl,color:`bg-emerald-500/15 text-emerald-400 border-emerald-500/30`,label:`Agent Online`},[B.AgentOffline]:{icon:Zl,color:`bg-red-500/15 text-red-400 border-red-500/30`,label:`Agent Offline`},[B.DeviceRegistered]:{icon:wc,color:`bg-emerald-500/15 text-emerald-400 border-emerald-500/30`,label:`Registered`},[B.DeviceUnregistered]:{icon:au,color:`bg-red-500/15 text-red-400 border-red-500/30`,label:`Unregistered`},[B.DeviceStateChanged]:{icon:Ds,color:`bg-foreground-subtle/10 text-foreground-subtle border-border`,label:`State`},[B.EventEmitted]:{icon:Su,color:`bg-amber-500/15 text-amber-400 border-amber-500/30`,label:`Event`}};function TQ(e,t){let n=wQ[e]??{icon:Cl,color:`bg-foreground-subtle/10 text-foreground-subtle border-border`,label:e.split(`.`).pop()??e};if(e===B.DeviceStateChanged&&t&&typeof t.capName==`string`){let e=t.capName;return{...n,label:e}}return n}var EQ=Object.freeze([...new Set(Object.values(B))].toSorted()),DQ=Object.freeze([B.PipelineCameraMetricsSnapshot,B.PipelineRunnerLoadSnapshot,B.PipelineEngineMetricsSnapshot,B.PipelineInferenceResult,B.PipelineTrace,B.PipelineProgress,B.StreamBrokerMetricsSnapshot,B.MetricsNodeResourcesSnapshot,B.MetricsNodeProcessesSnapshot,B.ClusterTopologySnapshot,B.MotionAnalysis,B.MotionZonesRaw,B.DetectionResult,B.PipelineAudioInferenceResult,B.PlatformProbePhase,B.BenchmarkProgress,B.ModelDownloadProgress]),OQ=new Set(DQ),kQ=Object.freeze(EQ.filter(e=>!OQ.has(e)));function AQ(e,t){if(e===B.DetectionPhaseTransition){let e=t.to,n=t.from,r=typeof t.source==`string`?t.source:null,i=typeof t.cooldownMs==`number`?t.cooldownMs:null,a=r?` (${r}${i?`, ${Math.round(i/1e3)}s cooldown`:``})`:``;return e===`active`?`Motion detected — phase active${a}`:e===`watching`?`Cooldown expired — phase watching${a}`:`Phase: ${String(n)} → ${String(e)}${a}`}if(e===B.DetectionResult){let e=t.frame?.detections??[];if(e.length===0)return null;let n=new Map;for(let t of e){let e=t,r=e.class??e.macroClass,i=typeof r==`string`?r:``;i&&n.set(i,(n.get(i)??0)+1)}return[...n.entries()].map(([e,t])=>t>1?`${e} ×${t}`:e).join(`, `)}if(e===B.PipelineAudioInferenceResult){let e=t.frame?.detections??[];return e.length===0?null:e.map(e=>{let t=e,n=t.macroClass??t.class??t.label,r=typeof n==`string`?n:``,i=t.score;return i?`${r} (${Math.round(i*100)}%)`:r}).filter(Boolean).join(`, `)}if(e===B.DetectionEvent){let e=t.label??t.class,n=t.score??t.confidence,r=[];return typeof e==`string`&&r.push(e),typeof n==`number`&&r.push(`${Math.round(n*100)}%`),r.length>0?r.join(` — `):null}if(e===B.ProviderMotion)return t.active===!0?`motion start`:`motion stop`;if(e===B.DeviceStateChanged){let e=t.slice;if(e&&typeof e==`object`){let t=Object.keys(e).filter(e=>e!==`lastFetchedAt`&&e!==`ts`);if(t.length>0)return t.slice(0,4).join(`, `)+(t.length>4?`…`:``)}return null}if(e===B.EventEmitted)return(typeof t.eventType==`string`?t.eventType:null)??null;if(e===B.MotionOnMotionChanged){let e=t.detected,n=typeof t.source==`string`?t.source:null,r=e===!0?`motion start`:e===!1?`motion stop`:`motion`;return n?`${r} (${n})`:r}if(e===B.ProviderDetection||e===B.DetectionCameraNative){let e=t.detections??[];if(!Array.isArray(e)||e.length===0)return(typeof t.class==`string`?t.class:null)??null;let n=new Map;for(let t of e){let e=t,r=e.class??e.macroClass,i=typeof r==`string`?r:``;i&&n.set(i,(n.get(i)??0)+1)}return[...n.entries()].map(([e,t])=>t>1?`${e} ×${t}`:e).join(`, `)}let n=t.addonId;return t.error||(n?`addon: ${n}`:null)}function jQ(e){let t=e.category;return t===B.DetectionResult||t===B.PipelineAudioInferenceResult?AQ(t,e.data)!==null:!0}var MQ=300;function NQ({agentId:e,addonId:t,deviceId:n,defaultCategories:r,categories:i,category:a,maxHeight:s=`max-h-96`,limit:l=50,showCategoryFilter:d=!0,showFilters:f=!1,liveBuffer:m,onClose:g,className:_}){let y=o(()=>r??i??kQ,[r,i]),b=o(()=>[...y].toSorted().join(`,`),[y]),[x,S]=h(()=>new Set(y)),C=p(b);c(()=>{C.current!==b&&(C.current=b,S(new Set(y)))},[b,y]);let w=uQ(MQ),E=m??w,D=E.entries,[O,k]=h(!0),[A,j]=h(new Set),[M,N]=h(``),[P,ee]=h(!1),[F,te]=h(``),[I,L]=h(0),ne=p(null),R=p(null),re=`${e??``}:${t??``}:${String(n??``)}:${a??``}`,ie=p(re);c(()=>{ie.current!==re&&(ie.current=re,E.reset(),j(new Set),L(0))},[re,E]),c(()=>{if(!P)return;let e=e=>{let t=R.current;t&&e.target instanceof Node&&!t.contains(e.target)&&ee(!1)};return document.addEventListener(`mousedown`,e),()=>{document.removeEventListener(`mousedown`,e)}},[P]);let ae=o(()=>{let r={};return e&&(r.agentId=e),t&&(r.addonId=t),n!==void 0&&(r.deviceId=n),a&&(r.category=a),r},[e,t,n,a]),z=o(()=>[...x].toSorted(),[x]),oe=o(()=>{let e={...ae,limit:l};return z.length>0&&z.length<EQ.length&&(e.category=z),e},[ae,l,o(()=>z.join(`,`),[z]),z]),{data:se,isLoading:ce}=q.systemEvents.getRecent.useQuery(oe,{staleTime:3e4}),le=p(x);c(()=>{le.current=x},[x]);let ue=ae;q.systemEvents.subscribe.useSubscription(ue,{onData:r=>{let i=r;i?.id&&CQ(i,e,t,n)&&le.current.has(i.category)&&E.append(i)}});let de=p(D.length);c(()=>{let e=ne.current;if(!e){de.current=D.length;return}let t=de.current;if(de.current=D.length,!(D.length<=t)){if(O&&e.scrollTop<=8)e.scrollTo({top:0});else if(!O&&e.scrollTop>0){let n=e.firstElementChild?.firstElementChild,r=n instanceof HTMLElement?n.offsetHeight:28;e.scrollTop+=r*(D.length-t)}}},[D.length,O]);let fe=o(()=>{let e=new Map;for(let t of se??[])e.set(t.id,t);for(let t of D)e.set(t.id,t);let t=[...e.values()].filter(e=>x.has(e.category)).filter(jQ);I>0&&(t=t.filter(e=>new Date(e.timestamp).getTime()>I));let n=M.trim().toLowerCase();return n&&(t=t.filter(e=>{if(e.category.toLowerCase().includes(n)||TQ(e.category,e.data).label.toLowerCase().includes(n))return!0;let t=AQ(e.category,e.data);if(t&&t.toLowerCase().includes(n))return!0;try{if(new Date(e.timestamp).toLocaleTimeString().toLowerCase().includes(n))return!0}catch{}try{if(JSON.stringify(e.data).toLowerCase().includes(n)||JSON.stringify(e.source).toLowerCase().includes(n))return!0}catch{}return!1})),t.toSorted((e,t)=>new Date(t.timestamp).getTime()-new Date(e.timestamp).getTime())},[se,D,x,M,I]),pe=u(e=>{j(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),me=u(e=>{S(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),he=u(()=>{S(new Set(y)),N(``),L(0)},[y]),B=u(()=>{L(Date.now()),E.reset()},[E]),[ge,_e]=h(!1),[V,ve]=h(null),ye=u(e=>{let t=new Date(e.timestamp).toISOString(),n=AQ(e.category,e.data)??``,r=n?` ${n}`:``;return`${t} [${e.category}]${r} data=${JSON.stringify(e.data)}`},[]),be=u(()=>{let e=fe.map(ye);navigator.clipboard.writeText(e.join(`
75
- `)).then(()=>{_e(!0),setTimeout(()=>_e(!1),1500)})},[fe,ye]),xe=u(e=>{navigator.clipboard.writeText(ye(e)).then(()=>{ve(e.id),setTimeout(()=>ve(t=>t===e.id?null:t),1200)})},[ye]),Se=u(()=>{S(new Set(EQ))},[]),Ce=u(()=>{S(new Set)},[]),we=o(()=>{let e=F.trim().toLowerCase();return e?EQ.filter(t=>t.toLowerCase().includes(e)):EQ},[F]),Te=EQ.length,Ee=x.size,De=Ee===Te,Oe=De?`All`:`${Ee}/${Te}`;return T(`div`,{className:G(`h-full min-h-0 flex flex-col`,_),onClick:e=>e.stopPropagation(),children:[T(`div`,{className:`flex items-center justify-between px-3 py-1.5 bg-surface-hover/30 gap-2 shrink-0`,children:[T(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[v(`span`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle font-medium`,children:`Events`}),e&&v(IQ,{label:`agent`,value:e}),t&&v(IQ,{label:`addon`,value:t}),n!==void 0&&v(IQ,{label:`device`,value:`#${n}`}),a&&v(IQ,{label:`category`,value:a}),T(`button`,{type:`button`,onClick:()=>{k(e=>!e),!O&&ne.current&&ne.current.scrollTo({top:0,behavior:`smooth`})},className:G(`inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors`,O?`border-border text-foreground-subtle hover:text-foreground`:`border-amber-500/30 bg-amber-500/10 text-amber-400`),children:[v(Ns,{className:`h-2.5 w-2.5`}),O?`Auto`:`Paused`]}),d&&T(`div`,{className:`relative`,ref:R,children:[T(`button`,{type:`button`,onClick:()=>ee(e=>!e),className:G(`inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors`,De?`border-border text-foreground-subtle hover:text-foreground`:`border-violet-500/30 bg-violet-500/10 text-violet-400`),title:`Pick events to track`,children:[v(Lc,{className:`h-2.5 w-2.5`}),`Filter (`,Oe,`)`]}),P&&v(PQ,{search:F,onSearchChange:te,categories:we,active:x,onToggle:me,onSelectAll:Se,onSelectNone:Ce,onResetDefaults:he})]}),T(`button`,{type:`button`,onClick:he,className:`inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground transition-colors`,title:`Reset filters to defaults`,children:[v(Ml,{className:`h-2.5 w-2.5`}),`Reset`]}),T(`button`,{type:`button`,onClick:B,className:`inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground transition-colors`,title:`Clear visible entries`,children:[v(au,{className:`h-2.5 w-2.5`}),`Clear`]}),T(`button`,{type:`button`,onClick:be,disabled:fe.length===0,className:G(`inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors`,ge?`border-emerald-500/30 bg-emerald-500/10 text-emerald-400`:`border-border text-foreground-subtle hover:text-foreground`,fe.length===0&&`opacity-40 cursor-not-allowed`),title:`Copy all visible events`,children:[v(vc,{className:`h-2.5 w-2.5`}),ge?`Copied!`:`Copy`]}),T(`div`,{className:`relative`,children:[v(`input`,{type:`text`,value:M,onChange:e=>N(e.target.value),placeholder:`Search…`,className:`w-32 pl-1.5 pr-5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50`}),M&&v(`button`,{type:`button`,onClick:()=>N(``),className:`absolute right-1 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground`,title:`Clear search`,children:v(xu,{className:`h-2.5 w-2.5`})})]}),D.length>0&&T(`span`,{className:`text-[9px] text-emerald-400 font-medium`,children:[`+`,D.length,` live`]})]}),g&&v(`button`,{type:`button`,onClick:g,className:`text-foreground-subtle hover:text-foreground`,children:v(xu,{className:`h-3.5 w-3.5`})})]}),T(`div`,{ref:ne,className:G(`flex-1 min-h-0 overflow-auto text-[10px]`,s),children:[ce&&T(`div`,{className:`flex items-center justify-center gap-2 py-6 text-foreground-subtle`,children:[v(el,{className:`h-3.5 w-3.5 animate-spin`}),`Loading events...`]}),!ce&&fe.length===0&&v(`div`,{className:`py-4 text-center text-foreground-subtle`,children:`No events found`}),fe.length>0&&v(`div`,{className:`divide-y divide-border/30`,children:fe.map(e=>{let t=TQ(e.category,e.data),n=t.icon,r=AQ(e.category,e.data),i=A.has(e.id);return T(`div`,{className:`flex items-start gap-2 px-3 py-1.5 hover:bg-surface-hover/30 cursor-pointer`,onClick:()=>pe(e.id),children:[v(`span`,{className:`text-foreground-subtle whitespace-nowrap w-[70px] shrink-0 pt-0.5`,children:new Date(e.timestamp).toLocaleTimeString()}),v(LQ,{copied:V===e.id,onCopy:()=>xe(e)}),T(`div`,{className:`flex-1 min-w-0`,children:[T(`div`,{className:`flex items-center gap-1.5`,children:[v(i?Xs:Qs,{className:`h-3 w-3 text-foreground-subtle shrink-0`}),T(`span`,{className:G(`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[9px] font-medium`,t.color),children:[v(n,{className:`h-2.5 w-2.5`}),t.label]}),e.source.nodeId&&e.source.nodeId!==`hub`&&v(`span`,{className:`text-[9px] px-1 py-0.5 rounded bg-foreground-subtle/10 text-foreground-subtle font-mono`,children:e.source.nodeId})]}),r&&v(`p`,{className:`text-foreground-subtle text-[10px] mt-0.5 ml-5`,children:r}),i&&T(`div`,{className:`mt-1 ml-5 text-[9px] bg-surface rounded px-2 py-1.5 space-y-0.5 font-mono overflow-x-auto`,children:[T(`div`,{children:[v(`span`,{className:`text-primary/70`,children:`source`}),v(`span`,{className:`text-foreground-subtle`,children:`: `}),v(`span`,{className:`text-foreground`,children:JSON.stringify(e.source)})]}),T(`div`,{children:[v(`span`,{className:`text-primary/70`,children:`category`}),v(`span`,{className:`text-foreground-subtle`,children:`: `}),v(`span`,{className:`text-foreground`,children:e.category})]}),Object.entries(e.data).map(([e,t])=>T(`div`,{children:[v(`span`,{className:`text-primary/70`,children:e}),v(`span`,{className:`text-foreground-subtle`,children:`: `}),v(`span`,{className:`text-foreground break-all`,children:typeof t==`object`?JSON.stringify(t):String(t)})]},e))]})]})]},e.id)})})]})]})}function PQ({search:e,onSearchChange:t,categories:n,active:r,onToggle:i,onSelectAll:a,onSelectNone:o,onResetDefaults:s}){return T(`div`,{className:`absolute z-20 top-full mt-1 left-0 w-72 max-h-80 rounded-md border border-border bg-surface shadow-lg flex flex-col`,onClick:e=>e.stopPropagation(),children:[T(`div`,{className:`flex items-center gap-1 px-2 py-1.5 border-b border-border/50`,children:[v(Ll,{className:`h-3 w-3 text-foreground-subtle`}),v(`input`,{type:`text`,value:e,onChange:e=>t(e.target.value),placeholder:`Filter categories…`,className:`flex-1 bg-transparent text-[10px] focus:outline-none text-foreground placeholder:text-foreground-subtle`,autoFocus:!0}),e&&v(`button`,{type:`button`,onClick:()=>t(``),className:`text-foreground-subtle hover:text-foreground`,children:v(xu,{className:`h-2.5 w-2.5`})})]}),T(`div`,{className:`flex items-center gap-1 px-2 py-1 border-b border-border/50 text-[9px]`,children:[v(`button`,{type:`button`,onClick:a,className:`px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground`,children:`All`}),v(`button`,{type:`button`,onClick:o,className:`px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground`,children:`None`}),v(`button`,{type:`button`,onClick:s,className:`px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground`,children:`Defaults`})]}),T(`div`,{className:`overflow-y-auto flex-1`,children:[n.length===0&&v(`div`,{className:`text-[10px] text-foreground-subtle italic px-2 py-3 text-center`,children:`No matches`}),n.map(e=>{let t=r.has(e),n=TQ(e),a=n.icon;return T(`button`,{type:`button`,onClick:()=>i(e),className:`w-full flex items-center gap-2 px-2 py-1 text-left hover:bg-surface-hover/40 text-[10px]`,children:[v(`input`,{type:`checkbox`,readOnly:!0,checked:t,className:`accent-violet-500`}),T(`span`,{className:G(`inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[9px] font-medium shrink-0`,n.color),children:[v(a,{className:`h-2.5 w-2.5`}),n.label]}),v(`span`,{className:`text-foreground-subtle font-mono truncate`,children:e})]},e)})]})]})}function FQ({position:e=`bottom`,className:t,...n}){return v(`div`,{className:G(e===`bottom`?`absolute bottom-0 left-0 right-0 z-10 border-t border-border bg-surface/95 backdrop-blur-sm`:`absolute inset-x-2 bottom-2 z-10 rounded-lg border border-border bg-surface/95 backdrop-blur-sm shadow-xl`,t),children:v(NQ,{maxHeight:`max-h-48`,...n})})}function IQ({label:e,value:t}){return T(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium`,children:[e,`: `,t]})}function LQ({copied:e,onCopy:t}){return v(`button`,{type:`button`,title:`Copy this event`,onClick:e=>{e.stopPropagation(),t()},className:G(`rounded p-0.5 transition-colors mt-0.5`,e?`text-emerald-400`:`text-foreground-subtle/60 hover:text-foreground hover:bg-surface-hover`),children:v(e?Ys:vc,{className:`h-3 w-3`})})}function RQ({deviceId:e,className:t=``,onOpenChild:n}){let r=q.useUtils(),i=q.deviceDiscovery.listDiscovered.useQuery({deviceId:e},{refetchInterval:1e4,retry:!1}),a=q.deviceDiscovery.getStatus.useQuery({deviceId:e},{refetchInterval:1e4,retry:!1}),s=q.deviceDiscovery.refreshDiscovery.useMutation({onSuccess:()=>{r.deviceDiscovery.listDiscovered.invalidate({deviceId:e}),r.deviceDiscovery.getStatus.invalidate({deviceId:e})}}),c=q.deviceDiscovery.adoptDevice.useMutation({onSuccess:()=>{r.deviceDiscovery.listDiscovered.invalidate({deviceId:e})}}),l=q.deviceDiscovery.releaseDevice.useMutation({onSuccess:()=>{r.deviceDiscovery.listDiscovered.invalidate({deviceId:e})}}),[u,d]=h(null),{available:f,adopted:p}=o(()=>{let e=i.data??[],t=e=>typeof e.metadata.rtspChannel==`number`?e.metadata.rtspChannel:1/0,n=(e,n)=>{let r=t(e),i=t(n);return r===i?e.name.localeCompare(n.name):r-i};return{available:e.filter(e=>!e.alreadyAdopted).toSorted(n),adopted:e.filter(e=>e.alreadyAdopted).toSorted(n)}},[i.data]),m=a.data,g=m?.lastError??null,_=m?.lastDiscoveryAt??null;async function y(){await s.mutateAsync({deviceId:e}).catch(()=>{})}async function b(t){d(t.childNativeId);try{await c.mutateAsync({deviceId:e,childNativeId:t.childNativeId})}finally{d(null)}}async function x(t){if(t.adoptedDeviceId!=null){d(t.childNativeId);try{await l.mutateAsync({deviceId:e,childDeviceId:t.adoptedDeviceId})}finally{d(null)}}}return T(`div`,{className:`rounded-xl border border-border bg-surface ${t}`,children:[T(`div`,{className:`flex items-start justify-between gap-2 border-b border-border px-3 py-2 sm:px-5 sm:py-3`,children:[T(`div`,{className:`min-w-0`,children:[v(`h3`,{className:`text-sm font-semibold text-foreground`,children:`Discovered devices`}),T(`p`,{className:`text-[11px] text-foreground-subtle`,children:[`Channels behind this hub. Click `,v(`span`,{className:`font-medium`,children:`Add`}),` to promote a channel to a managed device, or `,v(`span`,{className:`font-medium`,children:`Remove`}),` to detach.`]})]}),T(`button`,{type:`button`,onClick:y,disabled:s.isPending,className:`inline-flex items-center gap-1.5 rounded-lg border border-border px-2 py-1.5 sm:px-3 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50 shrink-0`,children:[s.isPending?v(el,{className:`h-3.5 w-3.5 animate-spin`}):v(jl,{className:`h-3.5 w-3.5`}),v(`span`,{className:`hidden sm:inline`,children:`Refresh`})]})]}),g?T(`div`,{className:`flex items-start gap-2 border-b border-border bg-destructive/10 px-5 py-2 text-[11px] text-destructive`,children:[v(cu,{className:`h-3.5 w-3.5 mt-0.5 shrink-0`}),T(`span`,{children:[`Last refresh failed: `,g]})]}):null,i.isLoading?v(`div`,{className:`flex items-center justify-center py-8 text-foreground-subtle`,children:v(el,{className:`h-5 w-5 animate-spin`})}):f.length===0&&p.length===0?v(`div`,{className:`px-5 py-8 text-center text-xs text-foreground-subtle`,children:`No channels reported by the hub yet. Click Refresh to enumerate.`}):T(E,{children:[f.length>0?v(zQ,{title:`Available to add`,count:f.length,tone:`primary`,children:f.map(e=>v(BQ,{child:e,busy:u===e.childNativeId,onAdopt:b,onRelease:x,onOpenChild:n},e.childNativeId))}):null,p.length>0?v(zQ,{title:`Already adopted`,count:p.length,tone:`muted`,children:p.map(e=>v(BQ,{child:e,busy:u===e.childNativeId,onAdopt:b,onRelease:x,onOpenChild:n},e.childNativeId))}):null]}),_==null?null:T(`div`,{className:`border-t border-border px-5 py-2 text-[10px] text-foreground-subtle`,children:[`Last refreshed `,new Date(_).toLocaleString()]})]})}function zQ({title:e,count:t,tone:n,children:r}){return T(`div`,{className:`border-t border-border`,children:[T(`div`,{className:`flex items-center justify-between border-b px-3 sm:px-5 py-1.5 text-[10px] uppercase tracking-wider ${n===`primary`?`bg-primary/5 text-primary border-primary/30`:`bg-surface text-foreground-subtle border-border`}`,children:[v(`span`,{className:`font-semibold`,children:e}),v(`span`,{className:`font-mono`,children:t})]}),v(`div`,{className:`divide-y divide-border`,children:r})]})}function BQ({child:e,busy:t,onAdopt:n,onRelease:r,onOpenChild:i}){return T(`div`,{className:`flex flex-wrap items-center justify-between gap-2 px-3 py-2 sm:px-5 sm:py-3 sm:flex-nowrap sm:gap-3`,children:[T(`div`,{className:`min-w-0 flex-1`,children:[T(`div`,{className:`flex flex-wrap items-center gap-x-2 gap-y-1`,children:[v(VQ,{status:e.status}),v(`span`,{className:`truncate text-sm font-medium text-foreground`,children:e.name}),e.metadata.isDoorbell?v(`span`,{className:`rounded bg-surface-hover px-1.5 py-0.5 text-[9px] uppercase tracking-wide text-foreground-subtle`,children:`Doorbell`}):null,e.metadata.isBattery?v(`span`,{className:`rounded bg-surface-hover px-1.5 py-0.5 text-[9px] uppercase tracking-wide text-foreground-subtle`,children:`Battery`}):null,e.metadata.isMultifocal?v(`span`,{className:`rounded bg-surface-hover px-1.5 py-0.5 text-[9px] uppercase tracking-wide text-foreground-subtle`,children:`Multifocal`}):null]}),T(`div`,{className:`mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle`,children:[typeof e.metadata.rtspChannel==`number`?T(`span`,{children:[`ch `,v(`span`,{className:`font-mono`,children:e.metadata.rtspChannel})]}):null,e.metadata.model?v(`span`,{className:`truncate max-w-[160px]`,children:e.metadata.model}):null,e.metadata.uid?T(`span`,{className:`font-mono truncate max-w-[140px]`,children:[e.metadata.uid.slice(0,12),`…`]}):null]})]}),e.alreadyAdopted?T(`div`,{className:`flex items-center gap-2`,children:[i&&e.adoptedDeviceId!==null?T(`button`,{type:`button`,onClick:()=>i(e.adoptedDeviceId),className:`inline-flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors`,title:`Open device detail`,children:[v(Oc,{className:`h-3.5 w-3.5`}),`Open`]}):null,T(`button`,{type:`button`,onClick:()=>{r(e)},disabled:t,className:`inline-flex items-center gap-1.5 rounded-lg border border-destructive/30 px-3 py-1.5 text-xs text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50`,children:[t?v(el,{className:`h-3.5 w-3.5 animate-spin`}):v(au,{className:`h-3.5 w-3.5`}),`Remove`]})]}):T(`button`,{type:`button`,onClick:()=>{n(e)},disabled:t,className:`inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50`,children:[t?v(el,{className:`h-3.5 w-3.5 animate-spin`}):v(wl,{className:`h-3.5 w-3.5`}),`Add`]})]})}function VQ({status:e}){switch(e){case`online`:return T(`span`,{className:`inline-flex items-center gap-1 rounded-full border border-emerald-500/40 bg-emerald-500/10 px-2 py-0.5 text-[10px] font-medium text-emerald-500`,children:[v(_u,{className:`h-2.5 w-2.5`}),` online`]});case`sleeping`:return T(`span`,{className:`inline-flex items-center gap-1 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-500`,children:[v(ml,{className:`h-2.5 w-2.5`}),` sleeping`]});case`offline`:return T(`span`,{className:`inline-flex items-center gap-1 rounded-full border border-destructive/40 bg-destructive/10 px-2 py-0.5 text-[10px] font-medium text-destructive`,children:[v(gu,{className:`h-2.5 w-2.5`}),` offline`]});default:return T(`span`,{className:`inline-flex items-center gap-1 rounded-full border border-border bg-surface px-2 py-0.5 text-[10px] font-medium text-foreground-subtle`,children:[v(cc,{className:`h-2.5 w-2.5`}),` unknown`]})}}function HQ(e,t){if(!e||typeof e!=`object`)return null;let n=e;if(n.category!==B.DeviceStateChanged)return null;let r=n.data;return!r||typeof r!=`object`||r.deviceId!==t||typeof r.capName!=`string`||!r.slice||typeof r.slice!=`object`?null:{capName:r.capName,slice:r.slice}}function UQ(e){return!!e&&typeof e==`object`&&!Array.isArray(e)}function WQ(e){if(!e||typeof e!=`object`)return!1;let t=e;return typeof t.source==`string`?!!t.data&&typeof t.data==`object`&&!Array.isArray(t.data):!1}function GQ(e,t){let n=new Map;for(let[r,i]of Object.entries(e)){let e=i&&typeof i==`object`&&!Array.isArray(i)?i:{value:i};n.set(r,{slice:e,updatedAt:t})}return n}var KQ=Object.freeze([...new Set(be.filter(e=>e.scope===`device`).map(e=>e.name))].toSorted()),qQ=1;function JQ({deviceId:e,defaultCaps:t,maxHeight:n=`max-h-96`,onClose:r,className:i}){let[a,s]=h(o(()=>new Set(t??[]),[t])),[l,d]=h(``),[f,m]=h(!1),[g,y]=h(``),[b,x]=h(`normalized`),S=p(null),[C,w]=h(new Map),[D,O]=h(new Map),[,k]=h(0),A=p(e);c(()=>{A.current!==e&&(A.current=e,w(new Map),O(new Map))},[e]);let{data:j,isLoading:M}=q.deviceState.getAllSnapshots.useQuery({},{staleTime:3e4}),N=p(!1);c(()=>{if(N.current||!UQ(j))return;let t=j[String(e)];if(N.current=!0,!t)return;let n=Date.now();w(e=>{let r=new Map(e);for(let[e,i]of Object.entries(t))r.has(e)||r.set(e,{slice:i,updatedAt:n});return r})},[j,e]),c(()=>{N.current=!1},[e]);let P=u((e,t)=>{w(n=>{let r=new Map(n);return r.set(e,{slice:t,updatedAt:Date.now()}),r})},[]),ee=Xf(gf().trpcClient,e)?.deviceOps?.getRawState,F=_({queryKey:[`device-raw-state`,e],queryFn:()=>ee({deviceId:e}),enabled:ee!=null,staleTime:6e4}),te=WQ(F.data)?F.data:null,I=F.isFetched&&!F.isError&&te!=null;c(()=>{b===`raw`&&!I&&x(`normalized`)},[b,I]);let L=o(()=>te?GQ(te.data,F.dataUpdatedAt||Date.now()):new Map,[te,F.dataUpdatedAt]);c(()=>{let e=setInterval(()=>k(e=>e+1),5e3);return()=>clearInterval(e)},[]);let ne=o(()=>{let e=new Set(KQ);for(let t of C.keys())e.add(t);return[...e].toSorted()},[C]),R=o(()=>{let e=l.trim().toLowerCase();return[...C.keys()].toSorted().filter(t=>a.size>0&&!a.has(t)?!1:!e||t.toLowerCase().includes(e)?!0:a$(C.get(t)?.slice??{},e))},[C,a,l]),re=u(e=>{s(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},[]),ie=u(()=>{s(new Set(t??[])),d(``)},[t]),ae=u(()=>{s(new Set(ne))},[ne]),z=u(()=>{s(new Set)},[]),oe=u((e,t)=>{O(n=>{let r=new Map(n);return r.set(e,!t),r})},[]),se=u((e,t)=>{let n=D.get(e);return n===void 0?t<qQ:n},[D]),[ce,le]=h(!1),ue=u(()=>{let e={};for(let t of R){let n=C.get(t);n&&(e[t]=n.slice)}navigator.clipboard.writeText(JSON.stringify(e,null,2)).then(()=>{le(!0),setTimeout(()=>le(!1),1500)})},[R,C]),de=o(()=>{let e=g.trim().toLowerCase();return e?ne.filter(t=>t.toLowerCase().includes(e)):ne},[g,ne]),fe=ne.length,pe=a.size,me=pe===0||pe===fe,he=me?`All`:`${pe}/${fe}`;c(()=>{if(!f)return;let e=e=>{let t=S.current;t&&!t.contains(e.target)&&m(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[f]);let B=l.trim().toLowerCase();return T(`div`,{className:G(`h-full min-h-0 flex flex-col`,i),onClick:e=>e.stopPropagation(),children:[T(`div`,{className:`flex items-center justify-between px-3 py-1.5 bg-surface-hover/30 gap-2 shrink-0`,children:[T(`div`,{className:`flex items-center gap-2 flex-wrap`,children:[v(`span`,{className:`text-[10px] uppercase tracking-wide text-foreground-subtle font-medium`,children:`State`}),v(s$,{label:`device`,value:`#${e}`}),I&&v(YQ,{mode:b,onChange:x}),b===`normalized`&&T(E,{children:[T(`div`,{className:`relative`,ref:S,children:[T(`button`,{type:`button`,onClick:()=>m(e=>!e),className:G(`inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors`,me?`border-border text-foreground-subtle hover:text-foreground`:`border-violet-500/30 bg-violet-500/10 text-violet-400`),title:`Pick caps to show`,children:[v(Lc,{className:`h-2.5 w-2.5`}),`Filter (`,he,`)`]}),f&&v(c$,{search:g,onSearchChange:y,caps:de,active:a,onToggle:re,onSelectAll:ae,onSelectNone:z,onResetDefaults:ie})]}),T(`button`,{type:`button`,onClick:ie,className:`inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground transition-colors`,title:`Reset filters`,children:[v(Ml,{className:`h-2.5 w-2.5`}),`Reset`]}),T(`button`,{type:`button`,onClick:ue,disabled:R.length===0,className:G(`inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors`,ce?`border-emerald-500/30 bg-emerald-500/10 text-emerald-400`:`border-border text-foreground-subtle hover:text-foreground`,R.length===0&&`opacity-40 cursor-not-allowed`),title:`Copy visible state as JSON`,children:[v(vc,{className:`h-2.5 w-2.5`}),ce?`Copied!`:`Copy`]}),T(`div`,{className:`relative`,children:[v(`input`,{type:`text`,value:l,onChange:e=>d(e.target.value),placeholder:`Search…`,className:`w-32 pl-1.5 pr-5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50`}),l&&v(`button`,{type:`button`,onClick:()=>d(``),className:`absolute right-1 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground`,title:`Clear search`,children:v(xu,{className:`h-2.5 w-2.5`})})]}),T(`span`,{className:`text-[9px] text-emerald-400 font-medium inline-flex items-center gap-1`,children:[v(`span`,{className:`h-1.5 w-1.5 rounded-full bg-emerald-400 animate-pulse`}),`live`]})]}),b===`raw`&&te&&T(E,{children:[T(`span`,{className:`inline-flex items-center gap-1 rounded-full border border-sky-500/30 bg-sky-500/15 text-sky-400 px-2 py-0.5 text-[9px] font-medium font-sans`,children:[`source: `,te.source]}),T(`button`,{type:`button`,onClick:()=>F.refetch(),disabled:F.isFetching,className:G(`inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground transition-colors`,F.isFetching&&`opacity-60 cursor-wait`),title:`Re-read raw upstream state`,children:[v(Ml,{className:G(`h-2.5 w-2.5`,F.isFetching&&`animate-spin`)}),`Refresh`]})]})]}),b===`normalized`&&v(XQ,{deviceId:e,onPatch:P}),r&&v(`button`,{type:`button`,onClick:r,className:`text-foreground-subtle hover:text-foreground`,children:v(xu,{className:`h-3.5 w-3.5`})})]}),v(`div`,{className:G(`flex-1 min-h-0 overflow-auto text-[10px] font-mono`,n),children:b===`raw`?L.size===0?v(`div`,{className:`py-4 text-center text-foreground-subtle font-sans`,children:`No raw state`}):v(`div`,{className:`py-1`,children:[...L.entries()].map(([e,t])=>v(ZQ,{capName:e,slice:t.slice,updatedAt:t.updatedAt,searchNeedle:``,isPathOpen:se,onToggle:oe},e))}):T(E,{children:[M&&C.size===0&&T(`div`,{className:`flex items-center justify-center gap-2 py-6 text-foreground-subtle font-sans`,children:[v(el,{className:`h-3.5 w-3.5 animate-spin`}),`Loading device state...`]}),!M&&C.size===0&&v(`div`,{className:`py-4 text-center text-foreground-subtle font-sans`,children:`No runtime state`}),!M&&C.size>0&&R.length===0&&v(`div`,{className:`py-4 text-center text-foreground-subtle font-sans`,children:`No caps match the filter`}),R.length>0&&v(`div`,{className:`py-1`,children:R.map(e=>{let t=C.get(e);return t?v(ZQ,{capName:e,slice:t.slice,updatedAt:t.updatedAt,searchNeedle:B,isPathOpen:se,onToggle:oe},e):null})})]})})]})}function YQ({mode:e,onChange:t}){return v(`div`,{className:`inline-flex items-center rounded border border-border overflow-hidden`,children:[{value:`normalized`,label:`Normalized`},{value:`raw`,label:`Raw`}].map(n=>v(`button`,{type:`button`,onClick:()=>t(n.value),className:G(`text-[9px] px-1.5 py-0.5 transition-colors`,e===n.value?`bg-violet-500/15 text-violet-400`:`text-foreground-subtle hover:text-foreground`),children:n.label},n.value))})}function XQ({deviceId:e,onPatch:t}){return q.systemEvents.subscribe.useSubscription({deviceId:e,category:B.DeviceStateChanged},{onData:n=>{let r=HQ(n,e);r&&t(r.capName,r.slice)}}),null}function ZQ({capName:e,slice:t,updatedAt:n,searchNeedle:r,isPathOpen:i,onToggle:a}){let o=e,s=i(o,0),c=Object.entries(t);return T(`div`,{children:[T(`div`,{className:`flex items-center gap-1.5 px-3 py-1 hover:bg-surface-hover/30 cursor-pointer select-none`,onClick:()=>a(o,s),children:[v(e$,{open:s,hasChildren:c.length>0}),v(`span`,{className:`inline-flex items-center gap-1 rounded-full border border-violet-500/30 bg-violet-500/15 text-violet-400 px-2 py-0.5 text-[9px] font-medium font-sans`,children:e}),T(`span`,{className:`text-[9px] text-foreground-subtle font-sans`,children:[c.length,` `,c.length===1?`key`:`keys`]}),T(`span`,{className:`ml-auto text-[9px] text-foreground-subtle/70 font-sans tabular-nums`,children:[`updated `,o$(n)]})]}),s&&v(`div`,{children:c.length===0?v($Q,{depth:1,label:`empty slice`}):c.map(([e,t])=>v(QQ,{path:`${o}.${e}`,nodeKey:e,value:t,depth:1,searchNeedle:r,isPathOpen:i,onToggle:a},e))})]})}function QQ({path:e,nodeKey:t,value:n,depth:r,searchNeedle:i,isPathOpen:a,onToggle:o}){let s=t$(n),c={paddingLeft:`${12+r*14}px`};if(!s)return T(`div`,{className:`flex items-start gap-1 px-3 py-0.5`,style:c,children:[v(`span`,{className:G(`shrink-0`,i$(t,i,`text-primary/70`)),children:t}),v(`span`,{className:`text-foreground-subtle`,children:`:`}),v(`span`,{className:G(`break-all`,i$(n$(n),i,r$(n))),children:n$(n)})]});let l=a(e,r);return T(`div`,{children:[T(`div`,{className:`flex items-center gap-1 px-3 py-0.5 hover:bg-surface-hover/30 cursor-pointer select-none`,style:c,onClick:()=>o(e,l),children:[v(e$,{open:l,hasChildren:s.entries.length>0}),v(`span`,{className:i$(t,i,`text-primary/70`),children:t}),v(`span`,{className:`text-foreground-subtle/70 text-[9px]`,children:s.summary})]}),l&&(s.entries.length===0?v($Q,{depth:r+1,label:s.kind===`array`?`empty array`:`empty object`}):s.entries.map(([t,n])=>v(QQ,{path:`${e}.${t}`,nodeKey:t,value:n,depth:r+1,searchNeedle:i,isPathOpen:a,onToggle:o},t)))]})}function $Q({depth:e,label:t}){return v(`div`,{className:`px-3 py-0.5 text-foreground-subtle/60 italic`,style:{paddingLeft:`${12+e*14}px`},children:t})}function e$({open:e,hasChildren:t}){return t?v(e?Xs:Qs,{className:`h-3 w-3 text-foreground-subtle shrink-0`}):v(`span`,{className:`inline-block w-3 shrink-0`})}function t$(e){if(Array.isArray(e))return{kind:`array`,entries:e.map((e,t)=>[String(t),e]),summary:`[${e.length}]`};if(e&&typeof e==`object`){let t=Object.entries(e);return{kind:`object`,entries:t,summary:`{${t.length}}`}}return null}function n$(e){if(e===null)return`null`;if(e===void 0)return`undefined`;if(typeof e==`string`)return e;if(typeof e==`number`||typeof e==`boolean`)return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function r$(e){return e==null?`text-foreground-subtle/60`:typeof e==`number`?`text-amber-400`:typeof e==`boolean`?e?`text-emerald-400`:`text-rose-400`:`text-foreground`}function i$(e,t,n){return t&&e.toLowerCase().includes(t)?G(n,`bg-violet-500/20 rounded px-0.5`):n}function a$(e,t){if(Array.isArray(e))return e.some(e=>a$(e,t));if(e&&typeof e==`object`){for(let[n,r]of Object.entries(e))if(n.toLowerCase().includes(t)||a$(r,t))return!0;return!1}return n$(e).toLowerCase().includes(t)}function o$(e){let t=Date.now()-e;if(t<5e3)return`just now`;let n=Math.floor(t/1e3);if(n<60)return`${n}s ago`;let r=Math.floor(n/60);return r<60?`${r}m ago`:`${Math.floor(r/60)}h ago`}function s$({label:e,value:t}){return T(`span`,{className:`text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium font-sans`,children:[e,`: `,t]})}function c$({search:e,onSearchChange:t,caps:n,active:r,onToggle:i,onSelectAll:a,onSelectNone:o,onResetDefaults:s}){return T(`div`,{className:`absolute z-20 top-full mt-1 left-0 w-72 max-h-80 rounded-md border border-border bg-surface shadow-lg flex flex-col font-sans`,onClick:e=>e.stopPropagation(),children:[T(`div`,{className:`flex items-center gap-1 px-2 py-1.5 border-b border-border/50`,children:[v(Ll,{className:`h-3 w-3 text-foreground-subtle`}),v(`input`,{type:`text`,value:e,onChange:e=>t(e.target.value),placeholder:`Filter caps…`,className:`flex-1 bg-transparent text-[10px] focus:outline-none text-foreground placeholder:text-foreground-subtle`,autoFocus:!0}),e&&v(`button`,{type:`button`,onClick:()=>t(``),className:`text-foreground-subtle hover:text-foreground`,children:v(xu,{className:`h-2.5 w-2.5`})})]}),T(`div`,{className:`flex items-center gap-1 px-2 py-1 border-b border-border/50 text-[9px]`,children:[v(`button`,{type:`button`,onClick:a,className:`px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground`,children:`All`}),v(`button`,{type:`button`,onClick:o,className:`px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground`,children:`None`}),v(`button`,{type:`button`,onClick:s,className:`px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground`,children:`Defaults`})]}),T(`div`,{className:`overflow-y-auto flex-1`,children:[n.length===0&&v(`div`,{className:`text-[10px] text-foreground-subtle italic px-2 py-3 text-center`,children:`No matches`}),n.map(e=>T(`button`,{type:`button`,onClick:()=>i(e),className:`w-full flex items-center gap-2 px-2 py-1 text-left hover:bg-surface-hover/40 text-[10px]`,children:[v(`input`,{type:`checkbox`,readOnly:!0,checked:r.has(e),className:`accent-violet-500`}),v(`span`,{className:`inline-flex items-center gap-1 rounded-full border border-violet-500/30 bg-violet-500/15 text-violet-400 px-1.5 py-0.5 text-[9px] font-medium shrink-0`,children:e})]},e))]})]})}var l$=500,u$=[{id:`logs`,label:`Logs`,icon:Il},{id:`events`,label:`Events`,icon:Hs},{id:`state`,label:`State`,icon:xc}];function d$({deviceId:e,containerDeviceId:t,defaultEventCategories:n,defaultStateCaps:r,initialTab:i=`events`,className:a,maxHeight:o=`max-h-96`}){let[s,l]=h(i),u=uQ(l$),d=uQ(l$),f=uQ(l$),p=u.reset,m=d.reset,g=f.reset;return c(()=>{p(),m(),g()},[e,p,m,g]),T(`div`,{className:G(`flex flex-col h-full min-h-0`,a),children:[v(`div`,{className:`flex items-center gap-1 mb-2 shrink-0`,children:u$.map(({id:e,label:t,icon:n})=>T(`button`,{type:`button`,onClick:()=>l(e),className:G(`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[11px] font-medium transition-colors`,s===e?`bg-primary/15 text-primary border border-primary/30`:`text-foreground-subtle hover:text-foreground hover:bg-surface-hover border border-transparent`),children:[v(n,{className:`h-3.5 w-3.5`}),t]},e))}),T(`div`,{className:`flex-1 min-h-0 overflow-hidden`,children:[s===`logs`&&v(vQ,{...t===void 0?{deviceId:e}:{containerDeviceId:t},maxHeight:o,showFilters:!1,liveBuffer:u}),s===`events`&&v(NQ,{deviceId:e,defaultCategories:n,maxHeight:o,showCategoryFilter:!0,liveBuffer:d}),s===`state`&&v(JQ,{deviceId:e,defaultCaps:r,maxHeight:o,liveBuffer:f})]})]})}function f$({label:e,icon:t,title:n=`Confirm action`,description:r,confirmLabel:i,triggerVariant:a=`outline`,confirmVariant:o=`danger`,size:s=`sm`,disabled:c,className:l,action:u,onSuccess:d}){let[f,p]=h(!1),[m,g]=h(!1),[_,y]=h(null),b=async()=>{y(null),g(!0);try{let e=await u();d?.(e),p(!1)}catch(e){y(e instanceof Error?e.message:String(e))}finally{g(!1)}};return T(E,{children:[T(ju,{type:`button`,variant:a,size:s,disabled:c,onClick:()=>{y(null),p(!0)},className:l,children:[t&&v(t,{className:`h-3.5 w-3.5`}),e]}),v(Xu,{open:f,onOpenChange:e=>!m&&p(e),children:T($u,{children:[T(ed,{children:[T(nd,{className:`flex items-center gap-2`,children:[v(cu,{className:`h-4 w-4 text-amber-400`}),n]}),typeof r==`string`?v(rd,{children:r}):r]}),_&&v(`div`,{className:G(`mt-2 px-3 py-2 rounded border border-danger/40 bg-danger/10`,`text-xs text-danger`),children:_}),T(td,{children:[v(ju,{type:`button`,variant:`ghost`,size:s,disabled:m,onClick:()=>p(!1),children:`Cancel`}),T(ju,{type:`button`,variant:o,size:s,disabled:m,onClick:()=>{b()},children:[m&&v(el,{className:`h-3.5 w-3.5 animate-spin`}),i??e]})]})]})})]})}function p$(e,t){let n=document.createElement(`a`);n.href=t,n.download=e,document.body.appendChild(n),n.click(),document.body.removeChild(n)}function m$({trpc:e,deviceId:t,deviceName:n,size:r=`sm`,className:i}){let[a,o]=h(!1),[s,c]=h(!1),[l,d]=h(null),f=n.replace(/[^a-zA-Z0-9_.-]+/g,`_`),p=u(async n=>{o(!0),d(null),c(!1);try{let r=await e.snapshot.getSnapshot.query({deviceId:t,force:!0});if(!r)throw Error(`No snapshot available`);let i=`data:${r.contentType};base64,${r.base64}`;if(n===`copy`)try{await navigator.clipboard.writeText(i)}catch{throw Error(`Clipboard unavailable`)}else{let e=r.contentType.includes(`png`)?`png`:`jpg`;p$(`${f}-${new Date().toISOString().replace(/[:.]/g,`-`)}.${e}`,i)}c(!0),setTimeout(()=>c(!1),1500)}catch(e){d(e instanceof Error?e.message:String(e))}finally{o(!1)}},[e,t,f]),m=r===`md`?`h-9 px-3 text-sm gap-2`:`h-7 px-2.5 text-[11px] gap-1.5`,[g,_]=h(null),[y,b]=h(!1),x=()=>{b(!1),_(setTimeout(()=>{b(!0),p(`copy`)},600))},S=()=>{g&&(clearTimeout(g),_(null)),y||p(`download`)},C=()=>{g&&(clearTimeout(g),_(null))};return T(`button`,{type:`button`,title:`Click to download · long-press to copy`,disabled:a,onPointerDown:x,onPointerUp:S,onPointerLeave:C,onPointerCancel:C,className:G(`inline-flex items-center justify-center rounded-lg font-medium border border-border`,`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,`disabled:opacity-50 transition-colors`,m,l&&`border-danger/40 text-danger`,i),children:[a?v(el,{className:`h-3.5 w-3.5 animate-spin`}):s?v(Ys,{className:`h-3.5 w-3.5 text-success`}):v(qs,{className:`h-3.5 w-3.5`}),`Snapshot`]})}function h$(e){let t=Date.now()-e;return t<6e4?`just now`:t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function g$({history:e,limit:t=5,latestIsFresh:n,className:r}){if(e.length===0)return null;let i=n?Vs:Hs,a=e.slice(0,t);return T(`div`,{className:G(`rounded-lg border border-border bg-surface px-3 py-2`,r),children:[T(`div`,{className:`flex items-center gap-2 mb-2`,children:[v(i,{className:G(`h-4 w-4 text-amber-400`,n&&`animate-pulse`)}),v(`span`,{className:`text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle`,children:`Recent presses`}),v(`span`,{className:`ml-auto rounded-full bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-medium text-foreground-subtle border border-border`,children:e.length})]}),v(`ul`,{className:`space-y-1`,children:a.map(e=>T(`li`,{className:`flex items-center justify-between text-[11px]`,title:new Date(e.timestamp).toLocaleString(),children:[v(`span`,{className:`text-foreground`,children:h$(e.timestamp)}),v(`span`,{className:`text-foreground-subtle font-mono text-[10px]`,children:new Date(e.timestamp).toLocaleTimeString()})]},`${e.deviceId}-${e.timestamp}`))})]})}function _$({items:e,header:t,triggerClassName:n,title:r=`More actions`}){let[i,a]=h(!1),o=e.filter(e=>!e.hidden);return o.length===0?null:T(Td,{open:i,onOpenChange:a,children:[v(Ed,{title:r,className:G(`inline-flex items-center justify-center rounded-lg p-2`,`text-foreground-subtle hover:text-foreground hover:bg-surface-hover`,`border border-transparent transition-colors`,n),children:v(Dc,{className:`h-4 w-4`})}),T(Dd,{className:`left-auto right-0 mt-1 min-w-[200px] p-1`,children:[t&&v(`div`,{className:`px-2 py-1 text-[10px] uppercase tracking-wider text-foreground-subtle`,children:t}),v(`ul`,{className:`space-y-0.5`,children:o.map((e,t)=>T(`li`,{children:[e.separatorBefore&&t>0&&v(`div`,{className:`my-1 h-px bg-border`}),T(`button`,{type:`button`,disabled:e.disabled,onClick:()=>{e.disabled||(e.onClick(),a(!1))},className:G(`flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left text-[12px]`,`transition-colors disabled:opacity-40 disabled:cursor-not-allowed`,e.danger?`text-foreground hover:bg-danger/10 hover:text-danger`:`text-foreground hover:bg-surface-hover`),children:[e.icon&&v(e.icon,{className:G(`h-3.5 w-3.5 shrink-0 mt-0.5`,e.danger&&`text-danger/80`)}),T(`span`,{className:`flex-1 min-w-0`,children:[v(`span`,{className:`block leading-tight`,children:e.label}),e.description&&v(`span`,{className:`block mt-0.5 text-[10px] text-foreground-subtle leading-tight`,children:e.description})]})]})]},e.id))})]})]})}var v$=[{value:`view`,label:`View`,icon:Ac,hint:`Read-only — queries + subscriptions`},{value:`create`,label:`Create`,icon:xl,hint:`Mutations that create or update`},{value:`delete`,label:`Delete`,icon:au,hint:`Destructive ops (delete/revoke/reset/…)`}],y$=[`device`,`system`];function b$(){return{type:`capability`,target:``,access:[`view`]}}function x$(e){if(e==null)return[];let t=new Set;for(let n of e)if(n.type===`device`)for(let e of n.targets)t.add(e);return[...t]}function S$(e,t,n,r){let i;switch(e){case`addon`:i=n;break;case`capability`:i=r;break;case`category`:i=y$.map(e=>({value:e,label:e}));break}if(t==null)return i;let a=new Set(t.filter(t=>t.type!==`device`&&t.type===e).map(e=>e.target));return i.filter(e=>a.has(e.value))}function C$(e,t){if(t==null)return[`view`,`create`,`delete`];let n=t.filter(t=>t.type===e.type?t.type===`device`&&e.type===`device`?t.targets.some(t=>e.targets.includes(t)):t.type!==`device`&&e.type!==`device`?t.target===e.target:!1:!1);if(n.length===0)return[];let r=new Set;for(let e of n)for(let t of e.access)r.add(t);return[...r]}function w$({value:e,onChange:t,clampToParent:n,emptyHint:r}){let{data:i}=Tm(),{data:a}=pv({}),s=o(()=>(i??[]).map(e=>({value:e.manifest.id,label:e.manifest.id})).sort((e,t)=>e.label.localeCompare(t.label)),[i]),c=o(()=>[...Te].toSorted().map(e=>({value:e,label:e})),[]),l=o(()=>(a??[]).map(e=>({value:String(e.id),label:`${e.name} (#${e.id} · ${e.addonId})`})).sort((e,t)=>e.label.localeCompare(t.label)),[a]),u=o(()=>n==null?null:x$(n),[n]),d=(e,t)=>{let n=[...t];switch(e){case`category`:return{type:`category`,target:`device`,access:n};case`capability`:return{type:`capability`,target:``,access:n};case`addon`:return{type:`addon`,target:``,access:n};case`device`:return{type:`device`,targets:[],access:n}}},f=(n,r)=>{t(e.map((e,t)=>{if(t!==n)return e;if(r.type!==void 0&&r.type!==e.type)return d(r.type,r.access??e.access);let i=[...r.access??e.access];return e.type===`device`?{type:`device`,targets:[...r.targets??e.targets],access:i}:e.type===`category`?{type:`category`,target:r.target??e.target,access:i}:e.type===`capability`?{type:`capability`,target:r.target??e.target,access:i}:{type:`addon`,target:r.target??e.target,access:i}}))},p=n=>{t(e.filter((e,t)=>t!==n))};return T(`div`,{className:`space-y-2`,children:[e.length===0&&r&&v(`div`,{className:`text-[10px] text-foreground-subtle italic px-2 py-2`,children:r}),e.map((e,t)=>{let r=C$(e,n);return T(`div`,{className:`flex flex-wrap items-start gap-1.5 rounded border border-border bg-surface px-2 py-1.5`,children:[T(`select`,{value:e.type,onChange:e=>f(t,{type:e.target.value}),className:`rounded border border-border bg-background px-2 py-1 text-[11px] focus:outline-none focus:ring-1 focus:ring-primary`,children:[v(`option`,{value:`category`,children:`category`}),v(`option`,{value:`capability`,children:`capability`}),v(`option`,{value:`addon`,children:`addon`}),v(`option`,{value:`device`,children:`device`})]}),e.type===`device`?v(T$,{value:e.targets,choices:l,clampToParent:u,onChange:e=>f(t,{targets:e})}):T(`select`,{value:e.target,onChange:e=>f(t,{target:e.target.value}),className:`flex-1 min-w-[160px] rounded border border-border bg-background px-2 py-1 text-[11px] font-mono focus:outline-none focus:ring-1 focus:ring-primary`,children:[T(`option`,{value:``,children:[`— pick `,e.type,` —`]}),S$(e.type,n,s,c).map(e=>v(`option`,{value:e.value,children:e.label},e.value))]}),v(`div`,{className:`flex items-center gap-1`,children:v$.map(({value:i,label:a,icon:o,hint:s})=>{let c=e.access.includes(i),l=n!=null&&!r.includes(i)&&!c;return T(`label`,{title:l?`${s} — not granted by your scope`:s,className:`inline-flex items-center gap-1 rounded px-1.5 py-1 text-[10px] cursor-pointer transition-colors ${c?`bg-primary/15 text-primary font-medium`:`text-foreground-subtle hover:bg-foreground-subtle/10`} ${l?`opacity-40 cursor-not-allowed`:``}`,children:[v(`input`,{type:`checkbox`,checked:c,disabled:l,onChange:n=>{let r=new Set(e.access);n.target.checked?r.add(i):r.delete(i),f(t,{access:[...r]})},className:`sr-only`}),v(o,{className:`h-3 w-3`}),a]},i)})}),v(`button`,{type:`button`,onClick:()=>p(t),className:`rounded p-1 text-foreground-subtle hover:bg-danger/10 hover:text-danger transition-colors`,title:`Remove scope`,children:v(xu,{className:`h-3 w-3`})})]},t)}),T(`button`,{type:`button`,onClick:()=>{t([...e,b$()])},className:`inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:text-foreground hover:bg-foreground-subtle/10 transition-colors`,children:[v(wl,{className:`h-3 w-3`}),`Add scope`]})]})}function T$({value:e,choices:t,clampToParent:n,onChange:r}){let[i,a]=h(``),s=o(()=>{let r=n==null?t:t.filter(e=>n.includes(e.value)),i=new Set(e);return r.filter(e=>!i.has(e.value))},[t,n,e]),c=e=>t.find(t=>t.value===e)?.label??`#${e}`,l=t=>{t&&(r([...e,t]),a(``))},u=t=>{r(e.filter(e=>e!==t))};return T(`div`,{className:`flex-1 min-w-[160px] flex flex-wrap items-center gap-1`,children:[e.length===0&&v(`span`,{className:`text-[10px] text-foreground-subtle italic px-1`,children:`no devices selected`}),e.map(e=>T(`span`,{className:`inline-flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-mono text-primary`,children:[c(e),v(`button`,{type:`button`,onClick:()=>u(e),className:`hover:text-danger transition-colors`,title:`Remove device`,children:v(xu,{className:`h-2.5 w-2.5`})})]},e)),s.length>0&&T(`select`,{value:i,onChange:e=>l(e.target.value),className:`rounded border border-border bg-background px-1.5 py-0.5 text-[10px] focus:outline-none focus:ring-1 focus:ring-primary`,children:[v(`option`,{value:``,children:`+ add device…`}),s.map(e=>v(`option`,{value:e.value,children:e.label},e.value))]})]})}function E$(e){for(let t of e){if(t.type===`device`){if(t.targets.length===0)return`Scope device: pick at least one device`}else if(t.target.trim().length===0)return`Scope ${t.type}: pick a target`;if(t.access.length===0){let e=t.type===`device`?`[${t.targets.join(`,`)}]`:t.target;return`Scope ${t.type}:${e}: pick at least one access`}}return null}var D$=hr(`camstack:zone-editing`,null);function O$({children:e}){let[t,n]=h(!1),[r,i]=h(null),[a,s]=h(null),[c,l]=h(null),d=u(e=>{n(e),e||(i(null),s(null),l(null))},[]),f=u(e=>{i(e)},[]),p=u(e=>{s(e)},[]),m=u(e=>{n(!0),s(null),i(e),l(null)},[]),g=u(()=>{n(!1),i(null),s(null),l(null)},[]),_=u(e=>{s(e.id),l(e)},[]),y=u(e=>{l(t=>t===null?t:{...t,...e})},[]),b=u(()=>{l(null)},[]),x=o(()=>({editing:t,drawingKind:r,selectedZoneId:a,editingDraft:c,setEditing:d,setDrawingKind:f,setSelectedZoneId:p,startDrawing:m,exitEditing:g,enterDraft:_,updateDraft:y,discardDraft:b}),[t,r,a,c,d,f,p,m,g,_,y,b]);return v(D$.Provider,{value:x,children:e})}function k$(){return i(D$)}var A$=500,j$=800;function M$(e,t,n){try{let r=e.live;if(!r)return null;let i=r.onEvent;return!i||typeof i.subscribe!=`function`?null:i.subscribe({category:t},{onData:n})}catch{return null}}function N$(e,t){return e?.id===t}function P$(e,t){let[n,r]=h(null),[i,a]=h(null),[o,s]=h(null),[l,u]=h(`watching`),d=p(void 0),f=p(void 0),m=p(void 0);return c(()=>{if(t===null)return;let n=M$(e,`detection.motion-analysis`,e=>{let n=e;if(!N$(n?.source,t))return;let i=n.data;!i?.regions||i.regions.length===0||(r({zones:i.regions.map(e=>({...e.bbox,intensity:e.intensity})),frameWidth:i.frameWidth,frameHeight:i.frameHeight}),d.current&&clearTimeout(d.current),d.current=setTimeout(()=>r(null),A$))});return()=>{n?.unsubscribe(),d.current&&clearTimeout(d.current)}},[e,t]),c(()=>{if(t===null)return;let n=M$(e,`detection.motion-zones-raw`,e=>{let n=e;if(!N$(n?.source,t))return;let r=n.data;r?.zones&&(a({boxes:r.zones.map(e=>({bbox:e.bbox,changeScore:e.changeScore})),frameWidth:r.frameSize?.width??0,frameHeight:r.frameSize?.height??0,motionScore:r.zones.length>0?r.zones.reduce((e,t)=>e+t.changeScore,0)/r.zones.length:0}),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>a(null),A$))});return()=>{n?.unsubscribe(),f.current&&clearTimeout(f.current)}},[e,t]),c(()=>{if(t===null)return;let n=M$(e,`detection.result`,e=>{let n=e;if(!N$(n?.source,t))return;let r=n.data?.frame;r?.detections?.length&&(s({detections:r.detections,frameWidth:r.width,frameHeight:r.height}),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>s(null),j$))});return()=>{n?.unsubscribe(),m.current&&clearTimeout(m.current)}},[e,t]),c(()=>{if(t===null)return;let n=M$(e,`detection.phase-transition`,e=>{let n=e;N$(n?.source,t)&&n.data?.to&&u(n.data.to)});return()=>{n?.unsubscribe()}},[e,t]),{motion:n,motionRaw:i,detection:o,phase:l}}function F$(e,t,n=5e3){let[r,i]=h([]);c(()=>{if(t===null)return;let r=!1,a=()=>{e.webrtcSession.listStreams.query({deviceId:t}).then(e=>{r||i(e)}).catch(()=>{})};a();let o=setInterval(a,n);return()=>{r=!0,clearInterval(o)}},[e,t,n]);let[a,s]=h(null);c(()=>{if(t===null)return;let n=!1;return e.pipelineOrchestrator&&e.pipelineOrchestrator.getCameraMetrics.query({deviceId:t}).then(e=>{n||!e||s({phase:e.phase,detectionFps:e.actualFps,avgInferenceMs:e.avgInferenceTimeMs,droppedFrames:e.droppedFrames})}).catch(()=>{}),()=>{n=!0}},[e,t]),vf(`pipeline.camera-metrics-snapshot`,e=>{if(t===null)return;let n=e.data;n.deviceId!==t||!n.metrics||s({phase:n.metrics.phase,detectionFps:n.metrics.actualFps,avgInferenceMs:n.metrics.avgInferenceTimeMs,droppedFrames:n.metrics.droppedFrames})});let{streams:l,hasWebrtc:d}=o(()=>t===null||r.length===0?{streams:[],hasWebrtc:!1}:{streams:r.map(e=>({id:e.id,label:e.label,target:e.target,status:e.status,inputFps:e.inputFps,decodeFps:e.decodeFps,bitrateKbps:e.bitrateKbps})),hasWebrtc:!0},[t,r]),f=u(async()=>{if(e.turnProvider)try{return(await e.turnProvider.getTurnServers.query()).map(e=>({urls:typeof e.urls==`string`?e.urls:[...e.urls],...e.username===void 0?{}:{username:e.username},...e.credential===void 0?{}:{credential:e.credential}}))}catch{return}},[e]),p=u(async(n,r)=>{if(t===null)throw Error(`No device selected`);let i=await e.webrtcSession.createSession.mutate({deviceId:t,target:n,hints:r}),a=await f();return{sessionId:i.sessionId,sdpOffer:i.sdpOffer,...a?{iceServers:a}:{}}},[e,t,f]),m=u(async(n,r,i)=>{if(t===null)throw Error(`No device selected`);return e.webrtcSession.handleOffer.mutate({deviceId:t,target:n,sdpOffer:r,...i===void 0?{}:{sessionId:i}})},[e,t]),g=u(async(n,r)=>{if(t===null)throw Error(`No device selected`);await e.webrtcSession.handleAnswer.mutate({deviceId:t,sessionId:n,sdpAnswer:r})},[e,t]);return{streams:l,hasWebrtc:d,pipelineMetrics:a,createSession:p,handleOffer:m,getIceServers:f,addIceCandidate:u(async(n,r)=>{t!==null&&await e.webrtcSession.addIceCandidate.mutate({deviceId:t,sessionId:n,candidate:r.candidate??``,sdpMid:r.sdpMid??null,sdpMLineIndex:r.sdpMLineIndex??null}).catch(()=>{})},[e,t]),getIceCandidates:u(async n=>t===null?{candidates:[],done:!0}:e.webrtcSession.getIceCandidates.query({deviceId:t,sessionId:n}),[e,t]),sendAnswer:g,closeSession:u(async n=>{t!==null&&await e.webrtcSession.closeSession.mutate({deviceId:t,sessionId:n}).catch(()=>{})},[e,t]),getSessionState:u(async n=>{if(t===null)return{pendingRenegotiation:null};try{return await e.webrtcSession.getSessionState.query({deviceId:t,sessionId:n})}catch{return{pendingRenegotiation:null}}},[e,t])}}function I$(e){let t=e?.deviceId??null,n=e?.historyLimit??20,r=bf(`doorbell.onPressed`,t===null?void 0:e=>e.deviceId===t),[i,a]=h([]);return c(()=>{r&&a(e=>{if(e.length>0&&e[0].deviceId===r.deviceId&&e[0].timestamp===r.timestamp)return e;let t=[r,...e];return t.length>n?t.slice(0,n):t})},[r,n]),{latest:r??null,history:i}}function L$(e){let t=gf(),n=o(()=>e?JSON.stringify(e):``,[e]),[r,i]=h(()=>t.listDevices(e));return c(()=>{let n=()=>{i(t.listDevices(e))};n();let r=null,a=null;try{r=t.onDeviceAdded(n),a=t.onDeviceRemoved(n)}catch{}let o=t.subscribeConnectionEvents(e=>{e===`connected`&&n()});return()=>{r?.(),a?.(),o()}},[t,e,n]),r}function R$(e){let t=gf(),[n,r]=h(()=>e===null?null:t.getDevice(e));return c(()=>{if(e===null){r(null);return}let n=()=>{r(t.getDevice(e))};n();let i=null,a=null;try{i=t.onDeviceAdded(n),a=t.onDeviceRemoved(n)}catch{}let o=t.subscribeConnectionEvents(e=>{e===`connected`&&n()});return()=>{i?.(),a?.(),o()}},[t,e]),n}function z$(e,t,n){let r=gf();return _({queryKey:e,queryFn:()=>t(r)(),...n})}function B$(e,t){let n=gf();return S({mutationFn:t=>e(n)(t),...t})}function V$(e,t){let n=gf(),r=b(),[i,a]=h(n.connectionVersion);c(()=>n.subscribeConnectionEvents((e,t)=>{e===`connected`&&a(t)}),[n]);let o=t.join(`|`),s=JSON.stringify(e);c(()=>{let e=[],t=()=>{let e=JSON.parse(s),t=e.length===1&&Array.isArray(e[0])?e:[e];r.invalidateQueries({queryKey:t})};t();for(let r of o.split(`|`))if(r)try{e.push(n.subscribeEvent(r,t))}catch{}return()=>{for(let t of e)t()}},[n,r,o,s,i])}function H$(e,t,n){let r=p(null),i=p(null);(r.current===null||i.current!==e)&&(r.current=Se(e),i.current=e);let a=p(void 0),o=p(null),s=o.current;return t===null?(a.current=void 0,o.current=null):(a.current===void 0||s===null||s.source!==r.current||s.deviceId!==t||s.capName!==n)&&(a.current=ye(r.current,t,n),o.current={source:r.current,deviceId:t,capName:n}),Zf(a.current)}export{Jz as AddonGlobalSettingsForm,nf as AgentStepEditor,LA as AlarmHeroCard,IA as AlarmPanelInlineControl,Gf as AppShell,im as ArcKnob,oQ as AudioClassificationList,rQ as AudioLevelWaveform,nQ as AudioWaveform,sI as AutotrackSection,er as BTN_COMPACT,nr as BTN_COMPACT_DANGER,tr as BTN_COMPACT_PRIMARY,rr as BTN_COMPACT_WARNING,Fu as Badge,tM as BatteryBadge,Sd as BottomSheet,Ld as Breadcrumb,vk as BrightnessPanel,ju as Button,om as ButtonControl,sm as ButtonHeroCard,Yp as CENTER,or as CHIP_ACTIVE,ar as CHIP_BASE,sr as CHIP_INACTIVE,RN as CLASS_COLORS,lM as COLUMN_BREAKPOINT_CLASS,cM as COLUMN_PRIORITY,TN as CONTROL_CAP_NAMES,yj as CONTROL_FILLS,oB as CameraStreamPlayer,Lu as Card,Ku as Checkbox,xM as ChildSectionAccordion,Ck as ClimatePanel,Vf as CodeBlock,Ru as CollapsibleCard,Wz as ConfigFormBuilder,Bz as ConfigFormField,Xd as ConfigSchemaField,f$ as ConfirmActionButton,Rf as ConfirmDialogProvider,aI as ConsumablesPanel,Vp as ContainerChildrenProvider,AN as ContainerPrimaryHero,Xp as ControlColumn,QA as ControlHeroCard,ZA as ControlInlineControl,Lk as ControlPanel,GZ as CopyButton,ym as CoverHeroCard,mm as CoverInlineControl,CN as CoverPanel,EF as CustomFieldRenderersProvider,BN as DEFAULT_COLOR,aM as DEVICE_COLUMNS,MM as DEVICE_LIST_PAGE_SIZE_KEY,jM as DEVICE_LIST_PAGE_SIZE_OPTIONS,tp as DEVICE_ROLE_META,vj as DEVICE_TYPE_CONTROL,ep as DEVICE_TYPE_META,zd as DataTable,HN as DetectionCanvas,Yz as DetectionOverlay,qN as DetectionResultTree,CF as DevShell,d$ as DeviceActivityPanel,OM as DeviceBatchToolbar,qf as DeviceCard,kF as DeviceContextProvider,tQ as DeviceExportPanel,Jf as DeviceGrid,TM as DeviceItem,SN as DeviceList,Xu as Dialog,$u as DialogContent,rd as DialogDescription,td as DialogFooter,ed as DialogHeader,nd as DialogTitle,Zu as DialogTrigger,RQ as DiscoveryPanel,g$ as DoorbellRecentPanel,od as Dropdown,cd as DropdownContent,ld as DropdownItem,sd as DropdownTrigger,xm as DummyHeroCard,bm as DummyInline,Nf as EmptyState,Ff as ErrorBox,NQ as EventStream,qp as FILL,bA as FanHeroCard,GA as FanInlineControl,yk as FanPanel,Hf as FilterBar,FQ as FloatingEventStream,yQ as FloatingLogStream,Fd as FloatingPanel,jf as FormField,Un as GRID_GAP,Kn as GRID_PAIRED,Gn as GRID_QUICK_STATS,am as GripTrack,fR as HOST_WIDGETS,OZ as HlsVideo,dk as HoverZoomImage,HO as HumidifierHeroCard,BO as HumidifierInlineControl,ir as INPUT_COMPACT,Mj as IconAction,Nu as IconButton,mk as ImageHeroCard,pk as ImageInlineControl,$N as ImageSelector,tP as InferenceConfigSelector,Wu as Input,_$ as KebabMenu,Bf as KeyValueList,Wn as LIST_ROW,zu as Label,DO as LawnMowerHeroCard,TO as LawnMowerInlineControl,_A as LightHeroCard,UA as LightInlineControl,nA as LockHeroCard,HA as LockInlineControl,_k as LockPanel,vQ as LogStream,hF as LoginForm,bk as MODE_COLOR,RI as MaskShapeCanvas,DA as MediaPlayerHeroCard,YA as MediaPlayerInlineControl,Ak as MediaPlayerPanel,Id as MobileDrawer,QI as MotionZonesSettings,dz as NodeMultiSelectField,Cf as NodePicker,uz as NodeSelectField,kN as OfflineBadge,pr as PHASE_CONFIG,fp as PRIORITY,Kp as PTZOverlay,Mf as PageHeader,lQ as PhaseIcon,LN as PipelineBuilder,MN as PipelineRuntimeSelector,Kd as PipelineStep,ff as PipelineTreeMatrix,uI as PlayerOverlaysProvider,Td as Popover,Dd as PopoverContent,ON as PopoverRowAction,Ed as PopoverTrigger,Df as ProviderBadge,eI as PtzPanel,KR as QrCode,Jp as RIGHT,ID as ROLE_DESCRIPTOR,cA as RadialGauge,dR as RecordingPanel,sQ as ResponseLog,Vn as SECTION_BODY,zn as SECTION_CARD,Bn as SECTION_HEADER,qn as SPLIT_PANEL_OUTER,Jn as SPLIT_PANEL_SIDE,Hn as STACK_GAP,wk as STATE_COLOR,w$ as ScopePicker,Pd as ScrollArea,Gu as Select,kf as SemanticBadge,eO as SensorHeroCard,GD as SensorInlineControl,UD as SensorValueAtom,Vu as Separator,Wf as Sidebar,Uf as SidebarItem,Hu as Skeleton,Bd as SlideOverPanel,$p as SlideToggle,m$ as SnapshotButton,zf as StatCard,JQ as StateValuesStream,Tf as StatusBadge,QN as StepTimings,Ud as StepTreeMaster,Qp as Stepper,UZ as StreamBrokerSelector,zZ as StreamPanel,qu as Switch,xA as SwitchHeroCard,BA as SwitchInlineControl,hk as SwitchPanel,hf as SystemProvider,Xn as TEXT_FIELD_LABEL,Zn as TEXT_HINT,$n as TEXT_METRIC,Yn as TEXT_SECTION_LABEL,Qn as TEXT_VALUE,De as TIMEZONES,Ad as Tabs,Nd as TabsContent,jd as TabsList,Md as TabsTrigger,lA as TapToggle,Je as ThemeProvider,Yk as ThermostatHeroCard,qA as ThermostatInlineControl,JR as TimezoneSelector,fd as Tooltip,md as TooltipContent,pd as TooltipTrigger,vO as VacuumHeroCard,gO as VacuumInlineControl,Zp as ValueReadout,LO as ValveHeroCard,MO as ValveInlineControl,Af as VersionBadge,OL as VodPlaybackProvider,JO as WaterHeaterHeroCard,KO as WaterHeaterInlineControl,ak as WeatherHeroCard,ek as WeatherInlineControl,QF as WidgetMetricCard,ZF as WidgetPanel,UF as WidgetRegistryProvider,pR as WidgetSlot,O$ as ZoneEditingProvider,dp as allDeviceTypeFilterOptions,Wd as buildStepTreeFromSchema,hp as childEntityId,G as cn,sM as columnsForContext,gp as containerChildToRef,RM as countableDevices,dm as coverHighlight,hr as createSharedContext,Fe as createTheme,je as darkColors,Ne as defaultTheme,yp as deriveDeviceKind,sp as deviceRoleMeta,lp as deviceRoleMetaOf,op as deviceTypeMeta,cp as deviceTypeMetaOf,ys as ensureMfHostInit,ge as findTimezone,In as formatControlDateTime,An as formatLastSeen,HM as fuzzyMatch,VN as getClassColor,mr as getPhaseVisual,CM as groupChildrenByLayout,mM as hardwareLabel,RO as humidifierTint,Rn as isAbsentProvider,zz as isFieldVisible,yO as lawnMowerActivityMeta,Me as lightColors,zF as loadRemoteBundle,hM as metadataEntries,pM as metadataString,fr as mirror,wF as mountAddonPage,gN as nextSort,VM as normalizeForSearch,_p as overrideEntityIdFromLink,Tu as providerIcons,vp as resolveContainerPrimary,Sj as resolveControlAlign,xj as resolveDeviceControl,pp as resolvePrimaryChild,_N as sortRows,Eu as statusIcons,fO as tankAlert,He as themeToCss,q as trpc,Cm as useAccessoriesGetStatus,Sm as useAccessoriesSetChildHidden,wm as useAddonPagesListPages,sh as useAddonSettingsGetDeviceSettings,ah as useAddonSettingsGetGlobalSettings,ch as useAddonSettingsUpdateDeviceSettings,oh as useAddonSettingsUpdateGlobalSettings,lh as useAddonWidgetsListWidgets,nh as useAddonsApplyAutoUpdateToAll,qm as useAddonsCancelBulkUpdate,rh as useAddonsCustom,Rm as useAddonsForceRefresh,eh as useAddonsGetAddonAutoUpdate,Qm as useAddonsGetAutoUpdateSettings,Km as useAddonsGetBulkUpdateState,Bm as useAddonsGetLastRestart,Em as useAddonsGetLogs,Ym as useAddonsGetVersions,km as useAddonsInstallFromWorkspace,Om as useAddonsInstallPackage,Am as useAddonsIsWorkspaceAvailable,Tm as useAddonsList,Jm as useAddonsListActiveBulkUpdates,Hm as useAddonsListCapabilityProviders,Vm as useAddonsListFrameworkPackages,Dm as useAddonsListPackages,Fm as useAddonsListUpdates,jm as useAddonsListWorkspacePackages,ih as useAddonsOnAddonLogs,Nm as useAddonsReloadPackages,Xm as useAddonsRestartAddon,zm as useAddonsRestartServer,Zm as useAddonsRetryLoad,Lm as useAddonsRollbackPackage,Pm as useAddonsSearchAvailable,th as useAddonsSetAddonAutoUpdate,$m as useAddonsSetAutoUpdateSettings,Um as useAddonsSetCapabilityProviderEnabled,Gm as useAddonsStartBulkUpdate,Mm as useAddonsUninstallPackage,Wm as useAddonsUpdateFrameworkPackage,Im as useAddonsUpdatePackage,uh as useAirQualitySensorGetStatus,dh as useAlarmPanelArm,fh as useAlarmPanelDisarm,mh as useAlarmPanelGetStatus,ph as useAlarmPanelTrigger,xh as useAlertsDismiss,hh as useAlertsEmit,vh as useAlertsGetUnreadCount,_h as useAlertsList,bh as useAlertsMarkAllRead,yh as useAlertsMarkRead,gh as useAlertsUpdate,KF as useAllWidgets,Sh as useAmbientLightSensorGetStatus,Eh as useAudioAnalysisApplyDeviceSettingsPatch,Th as useAudioAnalysisGetDeviceLiveContribution,wh as useAudioAnalysisGetDeviceSettingsContribution,Ch as useAudioAnalysisResolveDeviceSettings,Dh as useAudioAnalyzerAnalyseChunk,Oh as useAudioAnalyzerClassify,Ah as useAudioAnalyzerDispose,kh as useAudioAnalyzerIsReady,jh as useAudioAnalyzerReprobeAudioEngine,Nh as useAudioCodecCanHandle,Ih as useAudioCodecCloseSession,Ph as useAudioCodecCreateDecodeSession,Fh as useAudioCodecCreateEncodeSession,Vh as useAudioCodecFlushEncode,Hh as useAudioCodecListActiveSessions,Mh as useAudioCodecListSupportedCodecs,Bh as useAudioCodecPullEncoded,Rh as useAudioCodecPullPcm,Lh as useAudioCodecPushEncodedFrame,zh as useAudioCodecPushPcm,Uh as useAudioMetricsGetCurrentSnapshot,Wh as useAudioMetricsGetHistory,Kh as useAutomationControlDisable,Gh as useAutomationControlEnable,Jh as useAutomationControlGetStatus,qh as useAutomationControlTrigger,tg as useBackupDelete,$h as useBackupGetEntries,Zh as useBackupList,ng as useBackupListArchives,Yh as useBackupListDestinations,Qh as useBackupListLocations,ig as useBackupPreviewSchedule,eg as useBackupRestore,Xh as useBackupTrigger,rg as useBackupUpsertDestinationPolicy,og as useBatteryGetStatus,ag as useBatteryWakeForStream,sg as useBinaryGetStatus,lg as useBrightnessGetStatus,cg as useBrightnessSetBrightness,pg as useBrokerAdd,dg as useBrokerGet,vg as useBrokerGetBrokerConfig,gg as useBrokerGetSettings,yg as useBrokerGetSettingsSchema,wg as useBrokerGetState,Tg as useBrokerGetStatus,ug as useBrokerList,fg as useBrokerListProviders,xg as useBrokerPublish,mg as useBrokerRemove,_g as useBrokerSetSettings,Sg as useBrokerSubscribe,hg as useBrokerTestConnection,bg as useBrokerTestSettings,Cg as useBrokerUnsubscribe,Eg as useButtonPress,Dg as useCameraCredentialsGetCredentials,Og as useCameraCredentialsGetStatus,jg as useCameraPipelineConfigApplyDeviceSettingsPatch,Ag as useCameraPipelineConfigGetDeviceLiveContribution,kg as useCameraPipelineConfigGetDeviceSettingsContribution,Ng as useCameraStreamsGetBrokerStreams,Mg as useCameraStreamsGetCameraStreams,Fg as useCameraStreamsGetProfileRtspEntries,Pg as useCameraStreamsGetRtspEntries,Ig as useCameraStreamsPickStream,Lg as useCarbonMonoxideGetStatus,Wg as useClimateControlGetStatus,zg as useClimateControlSetFanMode,Rg as useClimateControlSetMode,Bg as useClimateControlSetPreset,Vg as useClimateControlSetTarget,Ug as useClimateControlSetTargetHumidity,Hg as useClimateControlSetTargetRange,Sf as useClusterNodes,Kg as useColorGetStatus,Gg as useColorSetColor,Lf as useConfirm,qg as useConnectivityGetStatus,Yg as useConsumablesGetStatus,Jg as useConsumablesReset,Xg as useContactGetStatus,Hp as useContainerChildren,Qg as useControlGetStatus,Zg as useControlSetValue,e_ as useCoverClose,i_ as useCoverGetStatus,$g as useCoverOpen,n_ as useCoverSetPosition,r_ as useCoverSetTiltPosition,t_ as useCoverStop,DF as useCustomFieldRenderer,AM as useDebouncedString,s_ as useDecoderCreateSession,c_ as useDecoderDestroySession,p_ as useDecoderGetFrame,o_ as useDecoderGetInfo,m_ as useDecoderGetShmStats,g_ as useDecoderGetStats,__ as useDecoderListActiveSessions,u_ as useDecoderOpenStream,d_ as useDecoderPullFrames,f_ as useDecoderPullHandles,l_ as useDecoderPushPacket,v_ as useDecoderReprobeHwaccel,a_ as useDecoderSupportsCodec,h_ as useDecoderUpdateConfig,x_ as useDetectionPipelineApplyDeviceSettingsPatch,b_ as useDetectionPipelineGetDeviceLiveContribution,y_ as useDetectionPipelineGetDeviceSettingsContribution,vF as useDevShell,R$ as useDevice,E_ as useDeviceAdoptionAdopt,w_ as useDeviceAdoptionGetCandidate,k_ as useDeviceAdoptionGetStatus,S_ as useDeviceAdoptionListCandidateFilters,C_ as useDeviceAdoptionListCandidates,T_ as useDeviceAdoptionRefresh,D_ as useDeviceAdoptionRelease,O_ as useDeviceAdoptionResync,oI as useDeviceAutotrack,Xj as useDeviceBattery,H$ as useDeviceCapSlice,$f as useDeviceCapability,P$ as useDeviceDetections,M_ as useDeviceDiscoveryAdoptDevice,P_ as useDeviceDiscoveryGetStatus,A_ as useDeviceDiscoveryListDiscovered,j_ as useDeviceDiscoveryRefreshDiscovery,N_ as useDeviceDiscoveryReleaseDevice,H_ as useDeviceExportApplyDeviceSettingsPatch,R_ as useDeviceExportExposeDevice,V_ as useDeviceExportGetDeviceLiveContribution,B_ as useDeviceExportGetDeviceSettingsContribution,F_ as useDeviceExportGetStatus,L_ as useDeviceExportListExposedDevices,I_ as useDeviceExportListSupportedDeviceKinds,z_ as useDeviceExportUnexposeDevice,AF as useDeviceId,LM as useDeviceListPageSize,lv as useDeviceManagerAddLocation,zv as useDeviceManagerAdoptDevice,Gv as useDeviceManagerAdoptionAdopt,Uv as useDeviceManagerAdoptionListCandidates,Wv as useDeviceManagerAdoptionRefresh,Kv as useDeviceManagerAdoptionRelease,U_ as useDeviceManagerAllocateDeviceId,ov as useDeviceManagerApplyInitialMeta,Vv as useDeviceManagerCreateDevice,xv as useDeviceManagerDisable,Rv as useDeviceManagerDiscoverDevices,bv as useDeviceManagerEnable,Ov as useDeviceManagerGetAllBindings,Dv as useDeviceManagerGetBindings,hv as useDeviceManagerGetChildren,_v as useDeviceManagerGetConfigSchema,Bv as useDeviceManagerGetCreationSchema,mv as useDeviceManagerGetDevice,Pv as useDeviceManagerGetDeviceAggregate,Nv as useDeviceManagerGetDeviceLiveInfoAggregate,Mv as useDeviceManagerGetDeviceSettingsAggregate,Jv as useDeviceManagerGetDeviceStatusAggregate,vv as useDeviceManagerGetSettingsSchema,wv as useDeviceManagerGetStreamProfileMap,gv as useDeviceManagerGetStreamSources,iv as useDeviceManagerGetWireableFields,pv as useDeviceManagerListAll,jv as useDeviceManagerListBindableCapsForDeviceType,cv as useDeviceManagerListLocations,fv as useDeviceManagerListPersistedByAddon,Av as useDeviceManagerListWrappersForCap,q_ as useDeviceManagerLoadConfig,Y_ as useDeviceManagerLoadMeta,J_ as useDeviceManagerLoadRuntimeState,K_ as useDeviceManagerPersistConfig,Ev as useDeviceManagerProbeStreams,W_ as useDeviceManagerRegisterDevice,Sv as useDeviceManagerRemove,Cv as useDeviceManagerRemoveByIntegration,G_ as useDeviceManagerRemoveDevice,uv as useDeviceManagerRemoveLocation,Fv as useDeviceManagerRunDeviceAction,nv as useDeviceManagerSetChildLayout,rv as useDeviceManagerSetDeviceLinks,dv as useDeviceManagerSetDisabled,$_ as useDeviceManagerSetIntegrationId,ev as useDeviceManagerSetLinkDeviceId,Z_ as useDeviceManagerSetLocation,sv as useDeviceManagerSetMetadata,X_ as useDeviceManagerSetName,tv as useDeviceManagerSetPrimaryChildEntityId,av as useDeviceManagerSetRole,Tv as useDeviceManagerSetStreamProfileMap,Q_ as useDeviceManagerSetType,kv as useDeviceManagerSetWrapperActive,Hv as useDeviceManagerTestCreationField,qv as useDeviceManagerTestField,yv as useDeviceManagerUpdateConfig,Iv as useDeviceManagerUpdateDeviceField,Lv as useDeviceManagerUpdateDeviceFieldsBatch,Xv as useDeviceOpsGetConfigEntries,ty as useDeviceOpsGetRawState,ey as useDeviceOpsGetSettingsSchema,Yv as useDeviceOpsGetStreamSources,$v as useDeviceOpsRemoveDevice,Qv as useDeviceOpsRunAction,Zv as useDeviceOpsSetConfig,cy as useDeviceProviderAdoptDiscoveredDevice,dy as useDeviceProviderCreateDevice,sy as useDeviceProviderDiscoverDevices,uy as useDeviceProviderGetChildCreationSchema,ay as useDeviceProviderGetDevices,iy as useDeviceProviderGetStatus,ny as useDeviceProviderStart,ry as useDeviceProviderStop,oy as useDeviceProviderSupportsDiscovery,ly as useDeviceProviderSupportsManualCreation,fy as useDeviceProviderTestCreationField,Xf as useDeviceProxy,jF as useDeviceSnapshot,Zj as useDeviceSnapshotImage,Qf as useDeviceState,hy as useDeviceStateGetAllSnapshots,my as useDeviceStateGetCapSlice,py as useDeviceStateGetSnapshot,gy as useDeviceStateSetCapSlice,Zf as useDeviceStateSlice,_y as useDeviceStatusGetStatus,F$ as useDeviceWebrtc,L$ as useDevices,I$ as useDoorbellEvents,vy as useDoorbellGetStatus,yy as useEnumSensorGetStatus,by as useEventEmitterGetStatus,V$ as useEventInvalidation,bf as useEventStreamLatest,xf as useEventStreamMap,Cy as useEventsGetEventClipUrl,Sy as useEventsGetEventThumbnail,xy as useEventsGetEvents,Ny as useFaceGalleryAssignFace,Iy as useFaceGalleryAssignFaces,Ty as useFaceGalleryCreateIdentity,Fy as useFaceGalleryDeleteFace,Dy as useFaceGalleryDeleteIdentity,jy as useFaceGalleryGetFaceByTrack,My as useFaceGalleryGetFaceMedia,wy as useFaceGalleryListIdentities,Oy as useFaceGalleryListIdentitySamples,Ay as useFaceGalleryListRecentFaces,ky as useFaceGalleryRemoveSample,Ey as useFaceGalleryRenameIdentity,Ry as useFaceGallerySuggestFaceClusters,Py as useFaceGalleryUnassignFace,Ly as useFaceGalleryUnassignFaces,Uy as useFanControlGetStatus,Vy as useFanControlSetDirection,Hy as useFanControlSetOscillating,zy as useFanControlSetPercentage,By as useFanControlSetPreset,Wy as useFeatureProbeGetStatus,Gy as useFloodGetStatus,Ky as useGasGetStatus,Xy as useHumidifierGetStatus,Yy as useHumidifierSetMode,qy as useHumidifierSetOn,Jy as useHumidifierSetTargetHumidity,Zy as useHumiditySensorGetStatus,Qy as useImageGetStatus,nb as useIntegrationsCreate,ib as useIntegrationsDelete,eb as useIntegrationsGet,sb as useIntegrationsGetAvailableTypes,tb as useIntegrationsGetByAddonId,ab as useIntegrationsGetSettings,$y as useIntegrationsList,ob as useIntegrationsSetSettings,cb as useIntegrationsTestConnection,rb as useIntegrationsUpdate,mb as useIntercomEndTalkSession,hb as useIntercomGetStatus,ub as useIntercomHandleAnswer,pb as useIntercomPushTalkAudio,lb as useIntercomStartSession,fb as useIntercomStartTalkSession,db as useIntercomStopSession,xd as useIsMidWidth,bd as useIsMobile,vb as useLawnMowerControlDock,yb as useLawnMowerControlGetStatus,_b as useLawnMowerControlPause,gb as useLawnMowerControlStartMowing,uQ as useLiveBuffer,vf as useLiveEvent,Cb as useLocalNetworkGetAllowedAddresses,Sb as useLocalNetworkGetConnectionEndpoints,xb as useLocalNetworkGetPreferred,bb as useLocalNetworkList,Tb as useLocalNetworkResetAllowlistToBestMatch,wb as useLocalNetworkSetAllowedAddresses,kb as useLockControlGetStatus,Eb as useLockControlLock,Ob as useLockControlOpen,Db as useLockControlUnlock,Hb as useMediaPlayerGetStatus,Nb as useMediaPlayerNext,jb as useMediaPlayerPause,Ab as useMediaPlayerPlay,Vb as useMediaPlayerPlayMedia,Pb as useMediaPlayerPrevious,Fb as useMediaPlayerSeek,Bb as useMediaPlayerSelectSource,Lb as useMediaPlayerSetMute,zb as useMediaPlayerSetRepeat,Rb as useMediaPlayerSetShuffle,Ib as useMediaPlayerSetVolume,Mb as useMediaPlayerStop,Ub as useMeshNetworkGetStatus,Wb as useMeshNetworkJoin,Kb as useMeshNetworkLeave,Jb as useMeshNetworkListPeers,qb as useMeshNetworkLogout,Gb as useMeshNetworkStartLogin,Yb as useMeshNetworkTestConnection,Xb as useMetricsProviderCollectSnapshot,ix as useMetricsProviderGetAddonStats,Zb as useMetricsProviderGetCached,tx as useMetricsProviderGetCpuTemperature,Qb as useMetricsProviderGetCurrent,$b as useMetricsProviderGetDiskSpace,ex as useMetricsProviderGetGpuInfo,nx as useMetricsProviderGetProcessStats,ox as useMetricsProviderKillProcess,rx as useMetricsProviderListAddonInstances,ax as useMetricsProviderListNodeProcesses,lx as useMotionDetectionAnalyze,mx as useMotionDetectionApplyDeviceSettingsPatch,px as useMotionDetectionGetDeviceLiveContribution,fx as useMotionDetectionGetDeviceSettingsContribution,ux as useMotionDetectionRemoveCamera,dx as useMotionDetectionReset,cx as useMotionGetStatus,sx as useMotionIsDetected,gx as useMotionTriggerGetStatus,hx as useMotionTriggerSetMotionTrigger,_x as useMotionZonesGetOptions,yx as useMotionZonesGetStatus,vx as useMotionZonesSetZone,Sx as useMqttBrokerAddBroker,xx as useMqttBrokerGetBrokerConfig,Dx as useMqttBrokerGetStatus,bx as useMqttBrokerListBrokers,Cx as useMqttBrokerRemoveBroker,Tx as useMqttBrokerStartEmbeddedBroker,Ex as useMqttBrokerStopEmbeddedBroker,wx as useMqttBrokerTestConnection,kx as useNativeObjectDetectionGetStatus,Ox as useNativeObjectDetectionSetEnabled,Mx as useNetworkAccessGetEndpoint,Nx as useNetworkAccessGetStatus,Px as useNetworkAccessListEndpoints,Ax as useNetworkAccessStart,jx as useNetworkAccessStop,Ix as useNetworkQualityGetAllStats,Fx as useNetworkQualityGetDeviceStats,Lx as useNetworkQualityReportClientStats,Kx as useNodesClusterAddonStatus,zx as useNodesDeployAddon,Xx as useNodesExecuteQuery,qx as useNodesGetCapUsageGraph,Jx as useNodesGetNodeAddons,Gx as useNodesRenameNode,Vx as useNodesRestartAddon,Ux as useNodesRestartNode,Hx as useNodesRestartProcess,Yx as useNodesSetProcessLogLevel,Wx as useNodesShutdownNode,Rx as useNodesTopology,Bx as useNodesUndeployAddon,Zx as useNotificationOutputSend,Qx as useNotificationOutputSendTest,eS as useNotifierCancel,tS as useNotifierGetStatus,$x as useNotifierSend,nS as useNumericSensorGetStatus,um as useOptimisticSlice,_f as useOptionalSystem,YF as useOptionalWidgetRegistry,iS as useOsdGetStatus,rS as useOsdSetOverlay,Wp as usePTZ,vS as usePipelineAnalyticsApplyDeviceSettingsPatch,cS as usePipelineAnalyticsClearTracks,aS as usePipelineAnalyticsGetActiveTracks,dS as usePipelineAnalyticsGetAudioEvents,_S as usePipelineAnalyticsGetDeviceLiveContribution,gS as usePipelineAnalyticsGetDeviceSettingsContribution,fS as usePipelineAnalyticsGetEventDensity,mS as usePipelineAnalyticsGetEventMedia,lS as usePipelineAnalyticsGetMotionEvents,uS as usePipelineAnalyticsGetObjectEvents,oS as usePipelineAnalyticsGetTrack,hS as usePipelineAnalyticsGetTrackMedia,sS as usePipelineAnalyticsListTracks,pS as usePipelineAnalyticsPruneEventsBefore,BS as usePipelineExecutorCacheFrameInPool,IS as usePipelineExecutorDeleteModel,MS as usePipelineExecutorDeleteTemplate,LS as usePipelineExecutorDetect,FS as usePipelineExecutorDownloadModel,PS as usePipelineExecutorGetAddonModels,ZS as usePipelineExecutorGetAudioCapabilities,yS as usePipelineExecutorGetAvailableEngines,NS as usePipelineExecutorGetCapabilities,xS as usePipelineExecutorGetDefaultSteps,$S as usePipelineExecutorGetDetectionConfigSchema,US as usePipelineExecutorGetEffectiveTuning,DS as usePipelineExecutorGetGlobalPipelineConfig,ES as usePipelineExecutorGetGlobalSteps,OS as usePipelineExecutorGetOrchestratorConfigSchema,XS as usePipelineExecutorGetReferenceAudio,YS as usePipelineExecutorGetReferenceAudioFiles,JS as usePipelineExecutorGetReferenceImage,TS as usePipelineExecutorGetSchema,bS as usePipelineExecutorGetSelectedEngine,CS as usePipelineExecutorGetVideoPipelineSteps,VS as usePipelineExecutorInferCached,KS as usePipelineExecutorKillEngine,WS as usePipelineExecutorListLoadedEngines,qS as usePipelineExecutorListReferenceImages,kS as usePipelineExecutorListTemplates,SS as usePipelineExecutorReprobeEngine,QS as usePipelineExecutorRunAudioTest,RS as usePipelineExecutorRunPipeline,zS as usePipelineExecutorRunPipelineBatch,AS as usePipelineExecutorSaveTemplate,wS as usePipelineExecutorSetVideoPipelineSteps,GS as usePipelineExecutorSpinEngine,HS as usePipelineExecutorUncacheFrame,jS as usePipelineExecutorUpdateTemplate,FC as usePipelineOrchestratorApplyDeviceSettingsPatch,pC as usePipelineOrchestratorAssignAudio,uC as usePipelineOrchestratorAssignDecoder,eC as usePipelineOrchestratorAssignPipeline,MC as usePipelineOrchestratorDeleteTemplate,aC as usePipelineOrchestratorGetAgentLoad,yC as usePipelineOrchestratorGetAgentSettings,hC as usePipelineOrchestratorGetAudioAssignment,_C as usePipelineOrchestratorGetAudioAssignments,gC as usePipelineOrchestratorGetAudioNodeLoad,sC as usePipelineOrchestratorGetCameraMetrics,CC as usePipelineOrchestratorGetCameraSettings,TC as usePipelineOrchestratorGetCameraStepOverrides,cC as usePipelineOrchestratorGetCapabilityBindings,vC as usePipelineOrchestratorGetDecoderAssignment,fC as usePipelineOrchestratorGetDecoderAssignments,PC as usePipelineOrchestratorGetDeviceLiveContribution,NC as usePipelineOrchestratorGetDeviceSettingsContribution,oC as usePipelineOrchestratorGetGlobalMetrics,iC as usePipelineOrchestratorGetPipelineAssignment,rC as usePipelineOrchestratorGetPipelineAssignments,bC as usePipelineOrchestratorListAgentSettings,kC as usePipelineOrchestratorListTemplates,nC as usePipelineOrchestratorRebalance,SC as usePipelineOrchestratorRemoveAgentSettings,OC as usePipelineOrchestratorResolvePipeline,AC as usePipelineOrchestratorSaveTemplate,xC as usePipelineOrchestratorSetAgentAddonDefaults,DC as usePipelineOrchestratorSetCameraPipelineForAgent,EC as usePipelineOrchestratorSetCameraStepOverride,wC as usePipelineOrchestratorSetCameraStepToggle,lC as usePipelineOrchestratorSetCapabilityBinding,mC as usePipelineOrchestratorUnassignAudio,dC as usePipelineOrchestratorUnassignDecoder,tC as usePipelineOrchestratorUnassignPipeline,jC as usePipelineOrchestratorUpdateTemplate,IC as usePipelineRunnerAttachCamera,LC as usePipelineRunnerDetachCamera,HC as usePipelineRunnerGetAllCameraMetrics,VC as usePipelineRunnerGetCameraMetrics,UC as usePipelineRunnerGetLocalCameras,zC as usePipelineRunnerGetLocalLoad,BC as usePipelineRunnerGetLocalMetrics,RC as usePipelineRunnerReportMotion,YC as usePlateGalleryCorrectPlateText,XC as usePlateGalleryDeletePlate,GC as usePlateGalleryGetPlateByTrack,KC as usePlateGalleryGetPlateMedia,WC as usePlateGalleryListPlates,qC as usePlateGallerySearchPlates,JC as usePlateGallerySuggestPlateClusters,pI as usePlayerOverlayLayer,dI as usePlayerOverlayLayers,mI as usePlayerToolbarButton,fI as usePlayerToolbarButtons,ZC as usePowerMeterGetStatus,QC as usePresenceGetStatus,$C as usePressureSensorGetStatus,ew as usePrivacyMaskGetOptions,nw as usePrivacyMaskGetStatus,tw as usePrivacyMaskSetMask,_w as usePtzAutotrackGetSettings,hw as usePtzAutotrackGetStatus,gw as usePtzAutotrackSetEnabled,vw as usePtzAutotrackSetSettings,iw as usePtzContinuousMove,lw as usePtzDeletePreset,uw as usePtzGetOptions,fw as usePtzGetPosition,ow as usePtzGetPresets,mw as usePtzGetStatus,dw as usePtzGoHome,sw as usePtzGoToPreset,rw as usePtzMove,cw as usePtzSavePreset,pw as usePtzSetAutofocus,aw as usePtzStop,yw as useRebootReboot,Nw as useRecordingApplyDeviceSettingsPatch,bw as useRecordingGetAvailability,xw as useRecordingGetDaysWithRecordings,ww as useRecordingGetDeviceConfig,Mw as useRecordingGetDeviceLiveContribution,jw as useRecordingGetDeviceSettingsContribution,Sw as useRecordingGetPlaybackManifest,Aw as useRecordingGetStatus,Cw as useRecordingGetStorageUsage,Tw as useRecordingLocateSegment,kw as useRecordingPruneFootage,Ew as useRecordingReadSegmentBytes,Ow as useRecordingRescanStorage,Dw as useRecordingSetDeviceConfig,qF as useRemoteComponent,Iw as useScriptRunnerGetStatus,Pw as useScriptRunnerRun,Fw as useScriptRunnerStop,Uw as useSettingsStoreCount,Kw as useSettingsStoreDeclareCollection,Hw as useSettingsStoreDelete,Lw as useSettingsStoreGet,Ww as useSettingsStoreHistogram,Bw as useSettingsStoreInsert,Gw as useSettingsStoreIsEmpty,zw as useSettingsStoreQuery,Rw as useSettingsStoreSet,Vw as useSettingsStoreUpdate,qw as useSmokeGetStatus,$w as useSnapshotApplyDeviceSettingsPatch,Qw as useSnapshotGetDeviceLiveContribution,Zw as useSnapshotGetDeviceSettingsContribution,Jw as useSnapshotGetSnapshot,Xw as useSnapshotGetStatus,Yw as useSnapshotInvalidateCache,tT as useSnapshotProviderGetSnapshot,eT as useSnapshotProviderSupportsDevice,fT as useStorageAbortUpload,pT as useStorageBeginDownload,lT as useStorageBeginUpload,sT as useStorageDelete,bT as useStorageDeleteLocation,hT as useStorageEndDownload,aT as useStorageExists,dT as useStorageFinalizeUpload,cT as useStorageGetAvailableSpace,_T as useStorageGetDefaultLocation,oT as useStorageList,vT as useStorageListLocationDeclarations,gT as useStorageListLocations,ST as useStorageListProviders,iT as useStorageRead,mT as useStorageReadChunk,nT as useStorageResolve,CT as useStorageTestConfig,xT as useStorageTestLocation,yT as useStorageUpsertLocation,rT as useStorageWrite,uT as useStorageWriteChunk,eE as useStreamBrokerApplyDeviceSettingsPatch,ET as useStreamBrokerAssignProfile,qT as useStreamBrokerGetAllRtspEntries,AT as useStreamBrokerGetBrokerStats,$T as useStreamBrokerGetDeviceLiveContribution,QT as useStreamBrokerGetDeviceSettingsContribution,GT as useStreamBrokerGetPreBufferInfo,JT as useStreamBrokerGetRtspEntry,KT as useStreamBrokerGetRtspPort,FT as useStreamBrokerGetStreamUrl,IT as useStreamBrokerGetStreamWithCodec,ZT as useStreamBrokerIsRtspEnabled,NT as useStreamBrokerKillClient,OT as useStreamBrokerListAllCameraStreams,kT as useStreamBrokerListAllProfileSlots,MT as useStreamBrokerListClients,jT as useStreamBrokerProbeStream,wT as useStreamBrokerPublishCameraStream,zT as useStreamBrokerPullAudioChunks,HT as useStreamBrokerPullFrameHandles,YT as useStreamBrokerRegenerateRtspToken,LT as useStreamBrokerReleaseStreamWithCodec,PT as useStreamBrokerRestartProfile,TT as useStreamBrokerRetractCameraStream,WT as useStreamBrokerSetPreBufferDuration,XT as useStreamBrokerSetRtspEnabled,RT as useStreamBrokerSubscribeAudioChunks,VT as useStreamBrokerSubscribeFrames,DT as useStreamBrokerUnassignProfile,BT as useStreamBrokerUnsubscribeAudioChunks,UT as useStreamBrokerUnsubscribeFrames,tE as useStreamCatalogGetCatalog,iE as useStreamParamsGetConfigSchema,nE as useStreamParamsGetOptions,aE as useStreamParamsGetStatus,rE as useStreamParamsSetProfile,sE as useSwitchGetStatus,oE as useSwitchSetState,gf as useSystem,uE as useSystemFeatureFlags,mE as useSystemForceRetentionCleanup,fE as useSystemGetRetentionConfig,lE as useSystemHealth,cE as useSystemInfo,B$ as useSystemMutation,dE as useSystemNetworkAddresses,z$ as useSystemQuery,pE as useSystemSetRetentionConfig,hE as useTamperGetStatus,gE as useTemperatureSensorGetStatus,Ye as useThemeMode,_E as useToastOnToast,vE as useTurnProviderGetTurnServers,bE as useUpdateGetStatus,yE as useUpdateInstallUpdate,LE as useUserManagementConfirmTotp,kE as useUserManagementCreateApiKey,ME as useUserManagementCreateScopedToken,SE as useUserManagementCreateUser,wE as useUserManagementDeleteUser,RE as useUserManagementDisableTotp,zE as useUserManagementGetTotpStatus,OE as useUserManagementListApiKeys,GE as useUserManagementListOauthSessions,FE as useUserManagementListScopedTokens,xE as useUserManagementListUsers,HE as useUserManagementOauthExchangeCode,VE as useUserManagementOauthIssueCode,UE as useUserManagementOauthRefresh,WE as useUserManagementOauthVerifyAccessToken,TE as useUserManagementResetPassword,AE as useUserManagementRevokeApiKey,KE as useUserManagementRevokeOauthSession,NE as useUserManagementRevokeScopedToken,EE as useUserManagementSetUserScopes,IE as useUserManagementSetupTotp,CE as useUserManagementUpdateUser,jE as useUserManagementValidateApiKey,DE as useUserManagementValidateCredentials,PE as useUserManagementValidateScopedToken,BE as useUserManagementVerifyTotp,$E as useVacuumControlGetStatus,ZE as useVacuumControlLocate,JE as useVacuumControlPause,XE as useVacuumControlReturnToBase,QE as useVacuumControlSetFanSpeed,qE as useVacuumControlStart,YE as useVacuumControlStop,tD as useValveClose,iD as useValveGetStatus,eD as useValveOpen,rD as useValveSetPosition,nD as useValveStop,aD as useVibrationGetStatus,sD as useVideoclipsGetClipPlayback,oD as useVideoclipsListClips,kL as useVodPlayback,dD as useWaterHeaterGetStatus,uD as useWaterHeaterSetAway,lD as useWaterHeaterSetOperationMode,cD as useWaterHeaterSetTargetTemp,fD as useWeatherGetStatus,_D as useWebrtcSessionAddIceCandidate,yD as useWebrtcSessionCloseSession,mD as useWebrtcSessionCreateSession,vD as useWebrtcSessionGetIceCandidates,xD as useWebrtcSessionGetSessionState,gD as useWebrtcSessionHandleAnswer,hD as useWebrtcSessionHandleOffer,bD as useWebrtcSessionHasAdaptiveBitrate,pD as useWebrtcSessionListStreams,WF as useWidget,GF as useWidgetMetadata,JF as useWidgetRegistry,wD as useZoneAnalyticsGetCameraHistory,SD as useZoneAnalyticsGetCurrentSnapshot,TD as useZoneAnalyticsGetUnzonedHistory,CD as useZoneAnalyticsGetZoneHistory,k$ as useZoneEditing,ED as useZoneRulesListRules,DD as useZoneRulesSetRules,kD as useZonesAddZone,OD as useZonesListZones,AD as useZonesRemoveZone,jD as useZonesUpdateZone,aO as vacuumStateMeta,E$ as validateScopes,OO as valveStateMeta,WO as waterHeaterPhase,UO as waterHeaterTint,YO as weatherConditionMeta,XO as weatherTint};