@camstack/addon-admin-ui 0.1.39 → 0.1.40

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 (24) hide show
  1. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-TUicghXo.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-yD7UmaAo.js} +1 -1
  2. package/dist/assets/{devices-GLp7me2a.js → devices-a77yscD5.js} +1 -1
  3. package/dist/assets/{hostInit-94fVe_XD.js → hostInit-DaDF_bfJ.js} +1 -1
  4. package/dist/assets/index-C8NE-4Ma.js +1 -0
  5. package/dist/assets/{index-D6khiudP.js → index-CehI0ALS.js} +1 -1
  6. package/dist/assets/{index-WrAHDGEr.js → index-D4yaxCPF.js} +1 -1
  7. package/dist/assets/{index-DQFO9ZU6.js → index-DAMgd5aW.js} +1 -1
  8. package/dist/assets/{index-DNY_otk4.js → index-DAenO2kJ.js} +1 -1
  9. package/dist/assets/{index-JJ5NLHxC.js → index-DVUREV1A.js} +1 -1
  10. package/dist/assets/{index-ByRJWRUP.js → index-DWdPkQ_j.js} +1 -1
  11. package/dist/assets/{index-BM6aK9lG.js → index-Dj1ZxUR8.js} +1 -1
  12. package/dist/assets/{index-TiJwCuZx.js → index-DsOnjZM4.js} +1 -1
  13. package/dist/assets/{index-b0D9qthW.js → index-EjW6hqu2.js} +1 -1
  14. package/dist/assets/{index-CwF7Dxf8.js → index-IsVfuhTX.js} +1 -1
  15. package/dist/assets/{method-access-map-DLEhlu0x.js → method-access-map-BgqTQNPE.js} +1 -1
  16. package/dist/assets/{remoteEntry-JLETvOnh.js → remoteEntry-VsZWB5do.js} +1 -1
  17. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DM77_4pA.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-VQvlRqZ-.js} +2 -2
  18. package/dist/index.html +5 -5
  19. package/dist/mf-entry-bootstrap-0.js +2 -2
  20. package/dist/server/addon.js +22 -8
  21. package/dist/server/addon.js.map +1 -1
  22. package/dist/sw.js +1 -1
  23. package/package.json +1 -1
  24. package/dist/assets/index-CtHpLu0L.js +0 -1
@@ -1,4 +1,4 @@
1
- import"./virtualExposes-_ivNhQLP.js";import{d as xr}from"./virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-DM77_4pA.js";import{c as r,a as um,d as u,e as ue,g as cN}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs-C_6K4VBY.js";import{b as je,e as P,h as U,c as Y,f as V,d as xe,a as pm,n as qe,k as Ae,i as re,m as qn,o as fa,g as ma,R as Ge,p as nc,q as dN,r as uN,s as yr,t as Fe,j as pN,u as fN,v as mN,w as hN}from"./__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs-DC63qZbr.js";import{a as fm,b as To}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs-D3WbXy3O.js";import{a as mm,b as hm}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-CUc0oFNo.js";import{_ as gm,m as Dr,n as we,o as bm,p as xm,h as Hn,j as gN}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-Cv6qLu_-.js";import{_ as ym,c as vm,s as wm,n as bN,B as xN,F as yN}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_client__loadShare__.mjs-DIkg6-MH.js";import{_ as Nm,a as vN}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-C1BmHlGM.js";import{_ as km}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.mjs-CpGtTxci.js";import{_ as Sm}from"./__mfe_internal__admin_ui_host__loadShare__konva__loadShare__.mjs-g85Oidc0.js";import{c as wN,D as Cm,E as NN,a as ut,M as kN,W as Xi,b as Cs,N as SN,d as Mm,S as CN,e as Ms}from"./index-DQFO9ZU6.js";import{S as Ji,c as Am}from"./devices-GLp7me2a.js";import{a as MN}from"./schemas-BEt-CulV.js";import{E as ve,A as AN,K as EN}from"./method-access-map-DLEhlu0x.js";import{s as IN}from"./index-JJ5NLHxC.js";import{a as ru,C as Em,S as ou,s as PN}from"./index-b0D9qthW.js";import{r as Im}from"./__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs_commonjs-proxy-D2C49VyZ.js";import{_ as _N}from"./preload-helper-BlTxHScW.js";import"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-Csg6EbPB.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const i of a.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&o(i)}).observe(document,{childList:!0,subtree:!0});function n(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function o(s){if(s.ep)return;s.ep=!0;const a=n(s);fetch(s.href,a)}})();const Pm={frigate:"#3b82f6",scrypted:"#a855f7",reolink:"#06b6d4",homeAssistant:"#22d3ee",rtsp:"#78716c"},_m={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:Pm},$m={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:Pm},el={colors:{dark:_m,light:$m},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 Dm(e,t){const n={...e};for(const o in t){const s=t[o],a=e[o];s!==void 0&&typeof s=="object"&&s!==null&&!Array.isArray(s)&&typeof a=="object"&&a!==null?n[o]=Dm(a,s):s!==void 0&&(n[o]=s)}return n}function $N(e){return e?Dm(structuredClone(el),e):structuredClone(el)}function Lm(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function DN(e){return`--color-${Lm(e)}`}function su(e){const t=[];for(const[n,o]of Object.entries(e))n!=="provider"&&t.push(` ${DN(n)}: ${o};`);return t.join(`
1
+ import"./virtualExposes-_ivNhQLP.js";import{d as xr}from"./virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-VQvlRqZ-.js";import{c as r,a as um,d as u,e as ue,g as cN}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs-C_6K4VBY.js";import{b as je,e as P,h as U,c as Y,f as V,d as xe,a as pm,n as qe,k as Ae,i as re,m as qn,o as fa,g as ma,R as Ge,p as nc,q as dN,r as uN,s as yr,t as Fe,j as pN,u as fN,v as mN,w as hN}from"./__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs-DC63qZbr.js";import{a as fm,b as To}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs-D3WbXy3O.js";import{a as mm,b as hm}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-CUc0oFNo.js";import{_ as gm,m as Dr,n as we,o as bm,p as xm,h as Hn,j as gN}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-Cv6qLu_-.js";import{_ as ym,c as vm,s as wm,n as bN,B as xN,F as yN}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_client__loadShare__.mjs-DIkg6-MH.js";import{_ as Nm,a as vN}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-C1BmHlGM.js";import{_ as km}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.mjs-CpGtTxci.js";import{_ as Sm}from"./__mfe_internal__admin_ui_host__loadShare__konva__loadShare__.mjs-g85Oidc0.js";import{c as wN,D as Cm,E as NN,a as ut,M as kN,W as Xi,b as Cs,N as SN,d as Mm,S as CN,e as Ms}from"./index-DAMgd5aW.js";import{S as Ji,c as Am}from"./devices-a77yscD5.js";import{a as MN}from"./schemas-BEt-CulV.js";import{E as ve,A as AN,K as EN}from"./method-access-map-BgqTQNPE.js";import{s as IN}from"./index-DVUREV1A.js";import{a as ru,C as Em,S as ou,s as PN}from"./index-EjW6hqu2.js";import{r as Im}from"./__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs_commonjs-proxy-D2C49VyZ.js";import{_ as _N}from"./preload-helper-BlTxHScW.js";import"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-Csg6EbPB.js";(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const s of document.querySelectorAll('link[rel="modulepreload"]'))o(s);new MutationObserver(s=>{for(const a of s)if(a.type==="childList")for(const i of a.addedNodes)i.tagName==="LINK"&&i.rel==="modulepreload"&&o(i)}).observe(document,{childList:!0,subtree:!0});function n(s){const a={};return s.integrity&&(a.integrity=s.integrity),s.referrerPolicy&&(a.referrerPolicy=s.referrerPolicy),s.crossOrigin==="use-credentials"?a.credentials="include":s.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function o(s){if(s.ep)return;s.ep=!0;const a=n(s);fetch(s.href,a)}})();const Pm={frigate:"#3b82f6",scrypted:"#a855f7",reolink:"#06b6d4",homeAssistant:"#22d3ee",rtsp:"#78716c"},_m={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:Pm},$m={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:Pm},el={colors:{dark:_m,light:$m},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 Dm(e,t){const n={...e};for(const o in t){const s=t[o],a=e[o];s!==void 0&&typeof s=="object"&&s!==null&&!Array.isArray(s)&&typeof a=="object"&&a!==null?n[o]=Dm(a,s):s!==void 0&&(n[o]=s)}return n}function $N(e){return e?Dm(structuredClone(el),e):structuredClone(el)}function Lm(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function DN(e){return`--color-${Lm(e)}`}function su(e){const t=[];for(const[n,o]of Object.entries(e))n!=="provider"&&t.push(` ${DN(n)}: ${o};`);return t.join(`
2
2
  `)}function LN(e){const t=[];for(const[n,o]of Object.entries(e))t.push(` --color-provider-${Lm(n)}: ${o};`);return t.join(`
3
3
  `)}function TN(e){const t=[];for(const[n,o]of Object.entries(e))t.push(` --spacing-${n}: ${o}px;`);return t.join(`
4
4
  `)}function RN(e){const t=[];for(const[n,o]of Object.entries(e))t.push(` --radius-${n}: ${o}px;`);return t.join(`
@@ -1 +1 @@
1
- import{n as _e,c as x,F as be,s as ve}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_client__loadShare__.mjs-DIkg6-MH.js";import{f as V,g as Ee}from"./index-DQFO9ZU6.js";import"./schemas-BEt-CulV.js";class Pe{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(t,r){this.keyToValue.set(t,r),this.valueToKey.set(r,t)}getByKey(t){return this.keyToValue.get(t)}getByValue(t){return this.valueToKey.get(t)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}}class ${constructor(t){this.generateIdentifier=t,this.kv=new Pe}register(t,r){this.kv.getByValue(t)||(r||(r=this.generateIdentifier(t)),this.kv.set(r,t))}clear(){this.kv.clear()}getIdentifier(t){return this.kv.getByValue(t)}getValue(t){return this.kv.getByKey(t)}}class Ce extends ${constructor(){super(t=>t.name),this.classToAllowedProps=new Map}register(t,r){typeof r=="object"?(r.allowProps&&this.classToAllowedProps.set(t,r.allowProps),super.register(t,r.identifier)):super.register(t,r)}getAllowedProps(t){return this.classToAllowedProps.get(t)}}function ke(e){if("values"in Object)return Object.values(e);const t=[];for(const r in e)e.hasOwnProperty(r)&&t.push(e[r]);return t}function Se(e,t){const r=ke(e);if("find"in r)return r.find(t);const s=r;for(let n=0;n<s.length;n++){const i=s[n];if(t(i))return i}}function v(e,t){Object.entries(e).forEach(([r,s])=>t(s,r))}function S(e,t){return e.indexOf(t)!==-1}function B(e,t){for(let r=0;r<e.length;r++){const s=e[r];if(t(s))return s}}class Te{constructor(){this.transfomers={}}register(t){this.transfomers[t.name]=t}findApplicable(t){return Se(this.transfomers,r=>r.isApplicable(t))}findByName(t){return this.transfomers[t]}}const Re=e=>Object.prototype.toString.call(e).slice(8,-1),W=e=>typeof e>"u",Ie=e=>e===null,P=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,I=e=>P(e)&&Object.keys(e).length===0,g=e=>Array.isArray(e),Ae=e=>typeof e=="string",Me=e=>typeof e=="number"&&!isNaN(e),Oe=e=>typeof e=="boolean",De=e=>e instanceof RegExp,C=e=>e instanceof Map,k=e=>e instanceof Set,K=e=>Re(e)==="Symbol",Le=e=>e instanceof Date&&!isNaN(e.valueOf()),Y=e=>e instanceof Error,U=e=>typeof e=="number"&&isNaN(e),Ne=e=>Oe(e)||Ie(e)||W(e)||Me(e)||Ae(e)||K(e),xe=e=>typeof e=="bigint",Ve=e=>e===1/0||e===-1/0,Be=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Ue=e=>e instanceof URL,A=e=>e.replace(/\\/g,"\\\\").replace(/\./g,"\\."),R=e=>e.map(String).map(A).join("."),E=(e,t)=>{const r=[];let s="";for(let i=0;i<e.length;i++){let o=e.charAt(i);if(!t&&o==="\\"){const f=e.charAt(i+1);if(f==="\\"){s+="\\",i++;continue}else if(f!==".")throw Error("invalid path")}if(o==="\\"&&e.charAt(i+1)==="."){s+=".",i++;continue}if(o==="."){r.push(s),s="";continue}s+=o}const n=s;return r.push(n),r};function y(e,t,r,s){return{isApplicable:e,annotation:t,transform:r,untransform:s}}const G=[y(W,"undefined",()=>null,()=>{}),y(xe,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):(console.error("Please add a BigInt polyfill."),e)),y(Le,"Date",e=>e.toISOString(),e=>new Date(e)),y(Y,"Error",(e,t)=>{const r={name:e.name,message:e.message};return"cause"in e&&(r.cause=e.cause),t.allowedErrorProps.forEach(s=>{r[s]=e[s]}),r},(e,t)=>{const r=new Error(e.message,{cause:e.cause});return r.name=e.name,r.stack=e.stack,t.allowedErrorProps.forEach(s=>{r[s]=e[s]}),r}),y(De,"regexp",e=>""+e,e=>{const t=e.slice(1,e.lastIndexOf("/")),r=e.slice(e.lastIndexOf("/")+1);return new RegExp(t,r)}),y(k,"set",e=>[...e.values()],e=>new Set(e)),y(C,"map",e=>[...e.entries()],e=>new Map(e)),y(e=>U(e)||Ve(e),"number",e=>U(e)?"NaN":e>0?"Infinity":"-Infinity",Number),y(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),y(Ue,"URL",e=>e.toString(),e=>new URL(e))];function T(e,t,r,s){return{isApplicable:e,annotation:t,transform:r,untransform:s}}const H=T((e,t)=>K(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>["symbol",t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,r)=>{const s=r.symbolRegistry.getValue(t[1]);if(!s)throw new Error("Trying to deserialize unknown symbol");return s}),ze=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),X=T(Be,e=>["typed-array",e.constructor.name],e=>[...e],(e,t)=>{const r=ze[t[1]];if(!r)throw new Error("Trying to deserialize unknown typed array");return new r(e)});function Z(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}const j=T(Z,(e,t)=>["class",t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{const r=t.classRegistry.getAllowedProps(e.constructor);if(!r)return{...e};const s={};return r.forEach(n=>{s[n]=e[n]}),s},(e,t,r)=>{const s=r.classRegistry.getValue(t[1]);if(!s)throw new Error(`Trying to deserialize unknown class '${t[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(s.prototype),e)}),Q=T((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>["custom",t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,r)=>{const s=r.customTransformerRegistry.findByName(t[1]);if(!s)throw new Error("Trying to deserialize unknown custom value");return s.deserialize(e)}),Fe=[j,H,Q,X],z=(e,t)=>{const r=B(Fe,n=>n.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation(e,t)};const s=B(G,n=>n.isApplicable(e,t));if(s)return{value:s.transform(e,t),type:s.annotation}},J={};G.forEach(e=>{J[e.annotation]=e});const qe=(e,t,r)=>{if(g(t))switch(t[0]){case"symbol":return H.untransform(e,t,r);case"class":return j.untransform(e,t,r);case"custom":return Q.untransform(e,t,r);case"typed-array":return X.untransform(e,t,r);default:throw new Error("Unknown transformation: "+t)}else{const s=J[t];if(!s)throw new Error("Unknown transformation: "+t);return s.untransform(e,r)}},b=(e,t)=>{if(t>e.size)throw new Error("index out of bounds");const r=e.keys();for(;t>0;)r.next(),t--;return r.next().value};function ee(e){if(S(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(S(e,"prototype"))throw new Error("prototype is not allowed as a property");if(S(e,"constructor"))throw new Error("constructor is not allowed as a property")}const $e=(e,t)=>{ee(t);for(let r=0;r<t.length;r++){const s=t[r];if(k(e))e=b(e,+s);else if(C(e)){const n=+s,i=+t[++r]==0?"key":"value",o=b(e,n);switch(i){case"key":e=o;break;case"value":e=e.get(o);break}}else e=e[s]}return e},M=(e,t,r)=>{if(ee(t),t.length===0)return r(e);let s=e;for(let i=0;i<t.length-1;i++){const o=t[i];if(g(s)){const a=+o;s=s[a]}else if(P(s))s=s[o];else if(k(s)){const a=+o;s=b(s,a)}else if(C(s)){if(i===t.length-2)break;const c=+o,f=+t[++i]==0?"key":"value",p=b(s,c);switch(f){case"key":s=p;break;case"value":s=s.get(p);break}}}const n=t[t.length-1];if(g(s)?s[+n]=r(s[+n]):P(s)&&(s[n]=r(s[n])),k(s)){const i=b(s,+n),o=r(i);i!==o&&(s.delete(i),s.add(o))}if(C(s)){const i=+t[t.length-2],o=b(s,i);switch(+n==0?"key":"value"){case"key":{const c=r(o);s.set(c,s.get(o)),c!==o&&s.delete(o);break}case"value":{s.set(o,r(s.get(o)));break}}}return e},te=e=>e<1;function O(e,t,r,s=[]){if(!e)return;const n=te(r);if(!g(e)){v(e,(a,c)=>O(a,t,r,[...s,...E(c,n)]));return}const[i,o]=e;o&&v(o,(a,c)=>{O(a,t,r,[...s,...E(c,n)])}),t(i,s)}function We(e,t,r,s){return O(t,(n,i)=>{e=M(e,i,o=>qe(o,n,s))},r),e}function Ke(e,t,r){const s=te(r);function n(i,o){const a=$e(e,E(o,s));i.map(c=>E(c,s)).forEach(c=>{e=M(e,c,()=>a)})}if(g(t)){const[i,o]=t;i.forEach(a=>{e=M(e,E(a,s),()=>e)}),o&&v(o,n)}else v(t,n);return e}const Ye=(e,t)=>P(e)||g(e)||C(e)||k(e)||Y(e)||Z(e,t);function Ge(e,t,r){const s=r.get(e);s?s.push(t):r.set(e,[t])}function He(e,t){const r={};let s;return e.forEach(n=>{if(n.length<=1)return;t||(n=n.map(a=>a.map(String)).sort((a,c)=>a.length-c.length));const[i,...o]=n;i.length===0?s=o.map(R):r[R(i)]=o.map(R)}),s?I(r)?[s]:[s,r]:I(r)?void 0:r}const re=(e,t,r,s,n=[],i=[],o=new Map)=>{const a=Ne(e);if(!a){Ge(e,n,t);const u=o.get(e);if(u)return s?{transformedValue:null}:u}if(!Ye(e,r)){const u=z(e,r),m=u?{transformedValue:u.value,annotations:[u.type]}:{transformedValue:e};return a||o.set(e,m),m}if(S(i,e))return{transformedValue:null};const c=z(e,r),f=c?.value??e,p=g(f)?[]:{},h={};v(f,(u,m)=>{if(m==="__proto__"||m==="constructor"||m==="prototype")throw new Error(`Detected property ${m}. This is a prototype pollution risk, please remove it from your object.`);const _=re(u,t,r,s,[...n,m],[...i,e],o);p[m]=_.transformedValue,g(_.annotations)?h[A(m)]=_.annotations:P(_.annotations)&&v(_.annotations,(w,we)=>{h[A(m)+"."+we]=w})});const d=I(h)?{transformedValue:p,annotations:c?[c.type]:void 0}:{transformedValue:p,annotations:c?[c.type,h]:h};return a||o.set(e,d),d};function se(e){return Object.prototype.toString.call(e).slice(8,-1)}function F(e){return se(e)==="Array"}function Xe(e){if(se(e)!=="Object")return!1;const t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function Ze(e,t,r,s,n){const i={}.propertyIsEnumerable.call(s,t)?"enumerable":"nonenumerable";i==="enumerable"&&(e[t]=r),n&&i==="nonenumerable"&&Object.defineProperty(e,t,{value:r,enumerable:!1,writable:!0,configurable:!0})}function D(e,t={}){if(F(e))return e.map(n=>D(n,t));if(!Xe(e))return e;const r=Object.getOwnPropertyNames(e),s=Object.getOwnPropertySymbols(e);return[...r,...s].reduce((n,i)=>{if(i==="__proto__"||F(t.props)&&!t.props.includes(i))return n;const o=e[i],a=D(o,t);return Ze(n,i,a,e,t.nonenumerable),n},{})}class l{constructor({dedupe:t=!1}={}){this.classRegistry=new Ce,this.symbolRegistry=new $(r=>r.description??""),this.customTransformerRegistry=new Te,this.allowedErrorProps=[],this.dedupe=t}serialize(t){const r=new Map,s=re(t,r,this,this.dedupe),n={json:s.transformedValue};s.annotations&&(n.meta={...n.meta,values:s.annotations});const i=He(r,this.dedupe);return i&&(n.meta={...n.meta,referentialEqualities:i}),n.meta&&(n.meta.v=1),n}deserialize(t,r){const{json:s,meta:n}=t;let i=r?.inPlace?s:D(s);return n?.values&&(i=We(i,n.values,n.v??0,this)),n?.referentialEqualities&&(i=Ke(i,n.referentialEqualities,n.v??0)),i}stringify(t){return JSON.stringify(this.serialize(t))}parse(t){return this.deserialize(JSON.parse(t),{inPlace:!0})}registerClass(t,r){this.classRegistry.register(t,r)}registerSymbol(t,r){this.symbolRegistry.register(t,r)}registerCustom(t,r){this.customTransformerRegistry.register({name:r,...t})}allowErrorProps(...t){this.allowedErrorProps.push(...t)}}l.defaultInstance=new l;l.serialize=l.defaultInstance.serialize.bind(l.defaultInstance);l.deserialize=l.defaultInstance.deserialize.bind(l.defaultInstance);l.stringify=l.defaultInstance.stringify.bind(l.defaultInstance);l.parse=l.defaultInstance.parse.bind(l.defaultInstance);l.registerClass=l.defaultInstance.registerClass.bind(l.defaultInstance);l.registerSymbol=l.defaultInstance.registerSymbol.bind(l.defaultInstance);l.registerCustom=l.defaultInstance.registerCustom.bind(l.defaultInstance);l.allowErrorProps=l.defaultInstance.allowErrorProps.bind(l.defaultInstance);l.serialize;l.deserialize;l.stringify;l.parse;l.registerClass;l.registerCustom;l.registerSymbol;l.allowErrorProps;const je=1e4,Qe=3e3,Je=2e3,et=3e4;class tt{_serverUrl;useWs;baseRetryMs;maxRetryMs;onConnectionChange;token;_trpcClient;_wsClient=null;mirror=null;mirrorInit=null;connected=!1;connectedPromise=null;_systemProxy;_connectionVersion=0;connectionListeners=new Set;constructor(t){this._serverUrl=t.serverUrl.replace(/\/+$/,""),this.token=t.token;const r=typeof window<"u";this.useWs=t.useWebSocket??r,this.onConnectionChange=t.onConnectionChange,this.baseRetryMs=t.retryDelayMs??Je,this.maxRetryMs=t.maxRetryDelayMs??et,this._trpcClient=this.buildTrpcClient(),this._systemProxy=V(this._trpcClient)}get serverUrl(){return this._serverUrl}get connectionVersion(){return this._connectionVersion}subscribeConnectionEvents(t){return this.connectionListeners.add(t),()=>{this.connectionListeners.delete(t)}}emitConnectionEvent(t){try{this.onConnectionChange?.(t)}catch{}for(const r of this.connectionListeners)try{r(t,this._connectionVersion)}catch{}}async awaitConnected(t){if(this.connected)return;if(this.connectedPromise)return this.connectedPromise;const r=t??15e3;this.connectedPromise=(async()=>{const s=this._trpcClient.auth.me.query();Number.isFinite(r)?await new Promise((n,i)=>{const o=setTimeout(()=>i(new Error(`System.awaitConnected: probe timed out after ${r}ms`)),r);s.then(()=>{clearTimeout(o),n()},a=>{clearTimeout(o),i(a instanceof Error?a:new Error(String(a)))})}):await s,this.connected=!0})();try{await this.connectedPromise}finally{this.connectedPromise=null}}async init(t){if(this.mirror?.isReady())return;if(this.mirrorInit)return this.mirrorInit;const r=new Ee(this._trpcClient);return this.mirror=r,this.mirrorInit=(async()=>{await this.awaitConnected(t),await r.init(t)})().finally(()=>{this.mirrorInit=null}),this.mirrorInit}async awaitReady(){if(!this.mirror?.isReady())return this.mirrorInit?this.mirrorInit:this.init()}isReady(){return this.mirror?.isReady()??!1}isConnected(){return this.connected}reconnect(){this.useWs&&(this.emitConnectionEvent("connecting"),this._wsClient?.close(),this.disposeMirror(),this.connected=!1,this.connectedPromise=null,this._trpcClient=this.buildTrpcClient(),this._systemProxy=V(this._trpcClient))}switchServerUrl(t){const r=t.replace(/\/+$/,"");r!==this._serverUrl&&(this._serverUrl=r,this.reconnect())}async raceConnectionEndpoints(t){const r=t?.perCandidateTimeoutMs??1500,s=(()=>{try{return new URL(this._serverUrl)}catch{return null}})(),n=s?.port?Number(s.port):s?.protocol==="https:"?443:80,i=s?.protocol==="https:"?"https":"http",a=this._trpcClient.localNetwork?.getConnectionEndpoints;if(!a)return{winner:this._serverUrl,switched:!1};let c;try{c=(await a.query({port:n,ipv4Only:t?.ipv4Only,scheme:i})).endpoints}catch{return{winner:this._serverUrl,switched:!1}}if(c.length===0)return{winner:this._serverUrl,switched:!1};const f=await rt(c.map(p=>p.baseUrl),r);return!f||f===this._serverUrl?{winner:f??this._serverUrl,switched:!1}:(this.switchServerUrl(f),{winner:f,switched:!0})}close(){this.disposeMirror(),this.connected=!1,this.connectedPromise=null,this._wsClient?.close()}disposeMirror(){this.mirror?.dispose(),this.mirror=null,this.mirrorInit=null}async login(t,r){const s=await this._trpcClient.auth.login.mutate({username:t,password:r});if(typeof s=="object"&&s!==null&&"token"in s){const n=s,i=n.token;typeof i=="string"&&n.requiresTotp!==!0&&this.setToken(i)}return s}async loginVerifyTotp(t,r){const s=await this._trpcClient.auth.loginVerifyTotp.mutate({challengeToken:t,code:r});if(typeof s=="object"&&s!==null&&"token"in s){const n=s.token;typeof n=="string"&&this.setToken(n)}return s}async logout(){await this._trpcClient.auth.logout.mutate()}async getMe(){return await this._trpcClient.auth.me.query()}async changeOwnPassword(t){return await this._trpcClient.auth.changeOwnPassword.mutate(t)}async setupOwnTotp(){return await this._trpcClient.auth.setupOwnTotp.mutate()}async confirmOwnTotp(t){return await this._trpcClient.auth.confirmOwnTotp.mutate(t)}async disableOwnTotp(){return await this._trpcClient.auth.disableOwnTotp.mutate()}async getOwnTotpStatus(){return await this._trpcClient.auth.getOwnTotpStatus.query()}setToken(t){this.token=t}listDevices(t){return this.mirror?(t?this.mirror.query(t):this.mirror.getAllDevices()).map(s=>this.attachBinding(s)):[]}getDevice(t){const r=this.mirror?.getDeviceById(t)??null;return r?this.attachBinding(r):null}getDeviceByName(t){const r=this.mirror?.getDeviceByName(t)??null;return r?this.attachBinding(r):null}getDeviceByStableId(t){const r=this.mirror?.getDeviceByStableId(t)??null;return r?this.attachBinding(r):null}async waitForDevice(t,r){this.mirror||await this.init();const s=await this.mirror.waitForDevice(t,r??3e4);return this.attachBinding(s)}onDeviceAdded(t){if(!this.mirror)throw new Error("System.onDeviceAdded: call init() before subscribing");return this.mirror.onDeviceAdded(t)}onDeviceRemoved(t){if(!this.mirror)throw new Error("System.onDeviceRemoved: call init() before subscribing");return this.mirror.onDeviceRemoved(t)}attachBinding(t){const r=this.lookupBinding(t.deviceId);if(r===t.binding)return t;const s=t;return s.binding=r,t}lookupBinding(t){return this.mirror?this.mirror.getDeviceById(t)?.binding??null:null}get addonPages(){return this._systemProxy.addonPages}get addonSettings(){return this._systemProxy.addonSettings}get alerts(){return this._systemProxy.alerts}get audioAnalyzer(){return this._systemProxy.audioAnalyzer}get audioCodec(){return this._systemProxy.audioCodec}get backup(){return this._systemProxy.backup}get decoder(){return this._systemProxy.decoder}get deviceManager(){return this._systemProxy.deviceManager}get deviceProvider(){return this._systemProxy.deviceProvider}get deviceState(){return this._systemProxy.deviceState}get metricsProvider(){return this._systemProxy.metricsProvider}get notificationOutput(){return this._systemProxy.notificationOutput}get pipelineExecutor(){return this._systemProxy.pipelineExecutor}get pipelineOrchestrator(){return this._systemProxy.pipelineOrchestrator}get pipelineRunner(){return this._systemProxy.pipelineRunner}get platformProbe(){return this._systemProxy.platformProbe}get recordingEngine(){return this._systemProxy.recordingEngine}get settingsStore(){return this._systemProxy.settingsStore}get storage(){return this._systemProxy.storage}get streamBroker(){return this._systemProxy.streamBroker}get turnProvider(){return this._systemProxy.turnProvider}get userManagement(){return this._systemProxy.userManagement}subscribeEvent(t,r){const s=this._trpcClient.live.onEvent.subscribe({category:t},{onData:n=>{try{r(n)}catch{}}});return()=>{try{s.unsubscribe()}catch{}}}get trpcClient(){return this._trpcClient}get wsClient(){return this._wsClient}buildTrpcClient(){const t=()=>{const r={};return this.token&&(r.Authorization=`Bearer ${this.token}`),r};if(this.useWs){const r=this._serverUrl.replace(/^http/,"ws")+"/trpc",s=this.baseRetryMs,n=this.maxRetryMs;return this._wsClient=_e({url:r,connectionParams:()=>({token:this.token}),retryDelayMs:i=>Math.min(s*Math.pow(2,i),n),keepAlive:{enabled:!0,intervalMs:je,pongTimeoutMs:Qe},onOpen:()=>{this._connectionVersion+=1,this.emitConnectionEvent("connected")},onClose:()=>{this.emitConnectionEvent("disconnected")}}),x({links:[be({client:this._wsClient,transformer:l})]})}return this._wsClient=null,x({links:[ve({url:`${this._serverUrl}/trpc`,headers:t,transformer:l})]})}}function mt(e){return new tt(e)}async function rt(e,t){if(e.length===0)return null;if(typeof fetch!="function")return e[0]??null;const s=typeof window<"u"&&typeof window.location<"u"&&window.location.protocol==="https:"?e.filter(o=>o.toLowerCase().startsWith("https://")):e;if(s.length===0)return null;const n=s.map(()=>new AbortController),i=s.map(async(o,a)=>{const c=n[a],f=setTimeout(()=>c.abort(),t);try{const p=await fetch(`${o.replace(/\/+$/,"")}/trpc/health`,{method:"GET",signal:c.signal,credentials:"omit"});if(!p.ok)throw new Error(`${p.status}`);return o}finally{clearTimeout(f)}});try{const o=await Promise.any(i);for(const a of n)try{a.abort()}catch{}return o}catch{return null}}var ne=(e=>(e.Motion="motion",e.Person="person",e.Vehicle="vehicle",e.Animal="animal",e.Audio="audio",e.Face="face",e.Plate="plate",e.Package="package",e.Doorbell="doorbell",e.Sensor="sensor",e))(ne||{});const ie=["animal","dog_cat","dog","cat","horse","sheep","cow","elephant","bear","zebra","giraffe","mouse","rabbit","deer","lion","tiger","bird","eagle","owl","pigeon","fish","whale","dolphin","snake","turtle","lizard"],oe=["person","people","pedestrian","rider","driver","cyclist","skier","skateboarder","face","hand","head","body"],ae=["vehicle","car","truck","bus","motorcycle","bicycle","van","ambulance","police_car","fire_truck","train","subway","tram","airplane","boat","ship","helicopter"],le=["face","eyes","nose","mouth","ears","eyebrows","left_eye","right_eye","pupil","iris","eyelid","eye_corner","upper_lip","lower_lip","teeth","chin","cheek","forehead","jaw","glasses","sunglasses","facial_hair","beard","mustache","facial_landmark","facial_keypoint"],ce=["plate","license_plate","front_plate","rear_plate","motorcycle_plate","temporary_plate","dealer_plate","licensePlate","plate_number","plate_character","plate_digit","plate_letter","plate_symbol","plate_region","plate_country_identifier","plate_frame","plate_bolt","plate_sticker","plate_validation_tag","damaged_plate","obscured_plate","dirty_plate"],ue=["motion","movement","other"],de=["package","packet"],fe=["audio"],me=["speech","scream","babbling","yell","bellow","whoop","whispering","laughter","snicker","crying","cry","sigh","singing","choir","chant","mantra","child_singing","rapping","humming","groan","grunt","whistling","breathing","wheeze","snoring","gasp","pant","snort","cough","throat_clearing","sneeze","sniff","cheering","applause","chatter","crowd","children_playing","bark","yip","howl","bow-wow","growling","whimper_dog","purr","meow","hiss","caterwaul","pets","livestock","doorbell","ding-dong","door","slam","knock","alarm","telephone","music","dog","dogs"],pe=["doorbell","ring"],he=["lock","binary","flood","entry","door","leak","door_open","flooded","entry_open"],ye={...ie.reduce((e,t)=>({...e,[t]:"animal"}),{}),...oe.reduce((e,t)=>({...e,[t]:"person"}),{}),...ae.reduce((e,t)=>({...e,[t]:"vehicle"}),{}),...ue.reduce((e,t)=>({...e,[t]:"motion"}),{}),...de.reduce((e,t)=>({...e,[t]:"package"}),{}),...le.reduce((e,t)=>({...e,[t]:"face"}),{}),...ce.reduce((e,t)=>({...e,[t]:"plate"}),{}),...fe.reduce((e,t)=>({...e,[t]:"audio"}),{}),...me.reduce((e,t)=>({...e,[t]:"audio"}),{}),...pe.reduce((e,t)=>({...e,[t]:"doorbell"}),{}),...he.reduce((e,t)=>({...e,[t]:"sensor"}),{})},st=e=>le.includes(e),nt=e=>ce.includes(e),pt=e=>ie.includes(e),ht=e=>oe.includes(e),yt=e=>ae.includes(e),gt=e=>ue.includes(e),wt=e=>pe.includes(e),_t=e=>de.includes(e),bt=e=>fe.includes(e)||me.includes(e),vt=e=>he.includes(e),Et=e=>st(e)||nt(e),Pt=e=>ye[e],Ct=e=>{const{className:t}=e,r={face:"person",plate:"vehicle"},s=ye[t];return s&&s!==t?s:r[t]},it=Object.values(ne),L=it.filter(e=>e!=="motion"),ge=["person","doorbell","package"],ot=[...ge,"vehicle","animal","audio","face","plate"],at=[...L];function kt(e,t){switch(e){case"critical":return ge;case"important":return ot;case"all":return at;case"custom":return t?.length?t:L;default:return L}}const q={Light:"light",Switch:"switch",WindowCovering:"cover",Lock:"lock",SecuritySystem:"alarm",Buttons:"button",Select:"select",Siren:"siren",Sensor:"sensor",Entry:"entry",Program:"script",MediaPlayer:"media_player",Outlet:"switch",light:"light",switch:"switch",input_boolean:"switch",cover:"cover",lock:"lock",alarm_control_panel:"alarm",input_button:"button",button:"button",input_select:"select",select:"select",siren:"siren",sensor:"sensor",media_player:"media_player",script:"script"},St={light:"light",switch:"switch",input_boolean:"switch",cover:"cover",lock:"lock",alarm_control_panel:"alarm",input_button:"button",button:"button",input_select:"select",select:"select",siren:"siren",sensor:"sensor",binary_sensor:"sensor",media_player:"media_player",script:"script",climate:"climate",camera:"camera",fan:"fan",vacuum:"vacuum",automation:"automation",scene:"scene",input_number:"sensor",person:"person",device_tracker:"tracker",weather:"weather",water_heater:"climate"},Tt={Light:"light",Switch:"switch",WindowCovering:"cover",Lock:"lock",SecuritySystem:"alarm",Buttons:"button",Select:"select",Siren:"siren",Sensor:"sensor",Entry:"entry",Program:"script",MediaPlayer:"media_player",Camera:"camera",Doorbell:"doorbell",Fan:"fan",Outlet:"switch"};function Rt(e){const t=q[e];if(t)return t;const r=e.toLowerCase();return q[r]??null}const lt=["Entry","Light","Switch","Lock","SecuritySystem","Buttons","WindowCovering","Siren","Sensor","Select","Program"],It=new Set(lt),ct=["light","switch","input_boolean","cover","lock","alarm_control_panel","input_button","button","input_select","select","siren","media_player","script"],At=new Set(ct),N=[{id:"liveStream",label:"Live Stream",sources:{frigate:!0,scrypted:!0,rtsp:!0},adapterMethod:"getLiveStream"},{id:"multiResolution",label:"Multi-Resolution",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getResolutions"},{id:"motion",label:"Motion Detection",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getMotion"},{id:"objectDetection",label:"Object Detection",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getObjectDetections"},{id:"audioVolume",label:"Audio Level",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getAudioVolume"},{id:"audioVolumes",label:"Audio Volumes (dBFS)",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getAudioVolumes"},{id:"ptz",label:"PTZ Control",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getPTZ"},{id:"intercom",label:"Intercom (Mic)",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getIntercomSupport"},{id:"deviceStatus",label:"Device Status",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getStatus"},{id:"timeline",label:"Detection Timeline",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getCameraDayData"},{id:"clusteredTimeline",label:"Clustered Timeline",sources:{frigate:!0,scrypted:!0,rtsp:!1},requiresBackend:!0,adapterMethod:"getClusteredDayData"},{id:"detectionClasses",label:"Detection Classes",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getDetectionClasses"},{id:"videoClips",label:"Video Clips",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getVideoClips"},{id:"nvrPlayback",label:"NVR Playback",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getNvrPlaybackSupported"},{id:"nvrScrub",label:"NVR Scrub/Seek",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"seekRecordingStream"},{id:"recordingThumbnail",label:"Recording Thumbnails",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getRecordingStreamThumbnail"},{id:"nvrSeekToLive",label:"Seek to Live",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"seekNvrToLive"}];function Mt(e,t,r){const s=N.find(n=>n.id===e);return!(!s||!s.sources[t]||s.platforms&&s.platforms[r]===!1)}function Ot(e){return N.filter(t=>t.sources[e])}function Dt(){return N.filter(e=>e.requiresBackend)}function Lt(e,t,r){if(e.length===0)return null;const s=t.viewportWidth*t.viewportHeight*(t.pixelRatio??1),n=t.bandwidthMbps??100,i=t.packetLoss??0,o=t.rttMs??50;let a="high";t.maxResolution==="low"||t.isCellular||n<1||i>.05?a="low":t.maxResolution==="medium"||n<5||s<5e5||o>200?a="medium":(t.maxResolution==="high"||s>2e6)&&(a="high");const c={main:"high",sub:"medium",ext:"low"},f=r??"native",p=e.map(d=>{let u=0;const m=c[d.profile]??"medium";if(m===a?u+=100:(a==="high"&&m==="medium"||a==="medium"&&m==="high"||a==="medium"&&m==="low"||a==="low"&&m==="medium")&&(u+=50),d.transport===f?u+=30:d.transport==="native"?u+=20:d.transport==="rtsp"?u+=15:d.transport==="rtmp"&&(u+=10),d.metadata?.width&&d.metadata?.height){const w=d.metadata.width*d.metadata.height/Math.max(s,1);w>=.8&&w<=2?u+=25:w>=.5&&w<=3&&(u+=15),w>4&&n<10&&(u-=20)}return d.metadata?.codec&&(n<5&&d.metadata.codec.includes("265")&&(u+=10),n>=10&&d.metadata.codec.includes("264")&&(u+=5)),{...d,score:u,targetTier:a}});p.sort((d,u)=>u.score-d.score);const h=p[0];return{streamName:h.streamName,profile:h.profile,transport:h.transport,label:h.label,metadata:h.metadata,reason:`${h.targetTier} quality → ${h.profile}/${h.transport} (score: ${h.score})`}}function Nt(e,t){return t?10:e.isCellular||(e.packetLoss??0)>.02?15:30}export{L as DEFAULT_ENABLED_CLASSES,ne as DetectionClass,ct as ELIGIBLE_HA_DOMAINS,At as ELIGIBLE_HA_DOMAINS_SET,lt as ELIGIBLE_SCRYPTED_DEVICE_TYPES,It as ELIGIBLE_SCRYPTED_DEVICE_TYPES_SET,N as FEATURE_MATRIX,St as HA_DOMAIN_TYPE_MAP,q as RAW_TO_CANONICAL,Tt as SCRYPTED_TYPE_TO_CANONICAL,tt as System,at as TIMELINE_PRESET_ALL,ge as TIMELINE_PRESET_CRITICAL,ot as TIMELINE_PRESET_IMPORTANT,ie as animalClasses,fe as audioClasses,me as audioLabelClasses,mt as createSystem,it as defaultDetectionClasses,ye as detectionClassesDefaultMap,pe as doorbellClasses,le as faceClasses,Dt as getBackendRequiredFeatures,Rt as getCanonicalDeviceType,kt as getClassesForTimelinePreset,Nt as getNextEvalInterval,Pt as getParentClass,Ct as getParentDetectionClass,Ot as getSourceFeatures,pt as isAnimalClassname,bt as isAudioClassname,wt as isDoorbellClassname,st as isFaceClassname,Mt as isFeatureAvailable,Et as isLabelDetection,gt as isMotionClassname,_t as isPackageClassname,ht as isPersonClassname,nt as isPlateClassname,vt as isSensorLabelClassname,yt as isVehicleClassname,ce as licensePlateClasses,ue as motionClasses,de as packageClasses,oe as personClasses,rt as raceFastestEndpoint,Lt as selectOptimalStream,he as sensorLabelClasses,ae as vehicleClasses};
1
+ import{n as _e,c as x,F as be,s as ve}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_client__loadShare__.mjs-DIkg6-MH.js";import{f as V,g as Ee}from"./index-DAMgd5aW.js";import"./schemas-BEt-CulV.js";class Pe{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(t,r){this.keyToValue.set(t,r),this.valueToKey.set(r,t)}getByKey(t){return this.keyToValue.get(t)}getByValue(t){return this.valueToKey.get(t)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}}class ${constructor(t){this.generateIdentifier=t,this.kv=new Pe}register(t,r){this.kv.getByValue(t)||(r||(r=this.generateIdentifier(t)),this.kv.set(r,t))}clear(){this.kv.clear()}getIdentifier(t){return this.kv.getByValue(t)}getValue(t){return this.kv.getByKey(t)}}class Ce extends ${constructor(){super(t=>t.name),this.classToAllowedProps=new Map}register(t,r){typeof r=="object"?(r.allowProps&&this.classToAllowedProps.set(t,r.allowProps),super.register(t,r.identifier)):super.register(t,r)}getAllowedProps(t){return this.classToAllowedProps.get(t)}}function ke(e){if("values"in Object)return Object.values(e);const t=[];for(const r in e)e.hasOwnProperty(r)&&t.push(e[r]);return t}function Se(e,t){const r=ke(e);if("find"in r)return r.find(t);const s=r;for(let n=0;n<s.length;n++){const i=s[n];if(t(i))return i}}function v(e,t){Object.entries(e).forEach(([r,s])=>t(s,r))}function S(e,t){return e.indexOf(t)!==-1}function B(e,t){for(let r=0;r<e.length;r++){const s=e[r];if(t(s))return s}}class Te{constructor(){this.transfomers={}}register(t){this.transfomers[t.name]=t}findApplicable(t){return Se(this.transfomers,r=>r.isApplicable(t))}findByName(t){return this.transfomers[t]}}const Re=e=>Object.prototype.toString.call(e).slice(8,-1),W=e=>typeof e>"u",Ie=e=>e===null,P=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,I=e=>P(e)&&Object.keys(e).length===0,g=e=>Array.isArray(e),Ae=e=>typeof e=="string",Me=e=>typeof e=="number"&&!isNaN(e),Oe=e=>typeof e=="boolean",De=e=>e instanceof RegExp,C=e=>e instanceof Map,k=e=>e instanceof Set,K=e=>Re(e)==="Symbol",Le=e=>e instanceof Date&&!isNaN(e.valueOf()),Y=e=>e instanceof Error,U=e=>typeof e=="number"&&isNaN(e),Ne=e=>Oe(e)||Ie(e)||W(e)||Me(e)||Ae(e)||K(e),xe=e=>typeof e=="bigint",Ve=e=>e===1/0||e===-1/0,Be=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),Ue=e=>e instanceof URL,A=e=>e.replace(/\\/g,"\\\\").replace(/\./g,"\\."),R=e=>e.map(String).map(A).join("."),E=(e,t)=>{const r=[];let s="";for(let i=0;i<e.length;i++){let o=e.charAt(i);if(!t&&o==="\\"){const f=e.charAt(i+1);if(f==="\\"){s+="\\",i++;continue}else if(f!==".")throw Error("invalid path")}if(o==="\\"&&e.charAt(i+1)==="."){s+=".",i++;continue}if(o==="."){r.push(s),s="";continue}s+=o}const n=s;return r.push(n),r};function y(e,t,r,s){return{isApplicable:e,annotation:t,transform:r,untransform:s}}const G=[y(W,"undefined",()=>null,()=>{}),y(xe,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):(console.error("Please add a BigInt polyfill."),e)),y(Le,"Date",e=>e.toISOString(),e=>new Date(e)),y(Y,"Error",(e,t)=>{const r={name:e.name,message:e.message};return"cause"in e&&(r.cause=e.cause),t.allowedErrorProps.forEach(s=>{r[s]=e[s]}),r},(e,t)=>{const r=new Error(e.message,{cause:e.cause});return r.name=e.name,r.stack=e.stack,t.allowedErrorProps.forEach(s=>{r[s]=e[s]}),r}),y(De,"regexp",e=>""+e,e=>{const t=e.slice(1,e.lastIndexOf("/")),r=e.slice(e.lastIndexOf("/")+1);return new RegExp(t,r)}),y(k,"set",e=>[...e.values()],e=>new Set(e)),y(C,"map",e=>[...e.entries()],e=>new Map(e)),y(e=>U(e)||Ve(e),"number",e=>U(e)?"NaN":e>0?"Infinity":"-Infinity",Number),y(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),y(Ue,"URL",e=>e.toString(),e=>new URL(e))];function T(e,t,r,s){return{isApplicable:e,annotation:t,transform:r,untransform:s}}const H=T((e,t)=>K(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>["symbol",t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,r)=>{const s=r.symbolRegistry.getValue(t[1]);if(!s)throw new Error("Trying to deserialize unknown symbol");return s}),ze=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),X=T(Be,e=>["typed-array",e.constructor.name],e=>[...e],(e,t)=>{const r=ze[t[1]];if(!r)throw new Error("Trying to deserialize unknown typed array");return new r(e)});function Z(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}const j=T(Z,(e,t)=>["class",t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{const r=t.classRegistry.getAllowedProps(e.constructor);if(!r)return{...e};const s={};return r.forEach(n=>{s[n]=e[n]}),s},(e,t,r)=>{const s=r.classRegistry.getValue(t[1]);if(!s)throw new Error(`Trying to deserialize unknown class '${t[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);return Object.assign(Object.create(s.prototype),e)}),Q=T((e,t)=>!!t.customTransformerRegistry.findApplicable(e),(e,t)=>["custom",t.customTransformerRegistry.findApplicable(e).name],(e,t)=>t.customTransformerRegistry.findApplicable(e).serialize(e),(e,t,r)=>{const s=r.customTransformerRegistry.findByName(t[1]);if(!s)throw new Error("Trying to deserialize unknown custom value");return s.deserialize(e)}),Fe=[j,H,Q,X],z=(e,t)=>{const r=B(Fe,n=>n.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation(e,t)};const s=B(G,n=>n.isApplicable(e,t));if(s)return{value:s.transform(e,t),type:s.annotation}},J={};G.forEach(e=>{J[e.annotation]=e});const qe=(e,t,r)=>{if(g(t))switch(t[0]){case"symbol":return H.untransform(e,t,r);case"class":return j.untransform(e,t,r);case"custom":return Q.untransform(e,t,r);case"typed-array":return X.untransform(e,t,r);default:throw new Error("Unknown transformation: "+t)}else{const s=J[t];if(!s)throw new Error("Unknown transformation: "+t);return s.untransform(e,r)}},b=(e,t)=>{if(t>e.size)throw new Error("index out of bounds");const r=e.keys();for(;t>0;)r.next(),t--;return r.next().value};function ee(e){if(S(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(S(e,"prototype"))throw new Error("prototype is not allowed as a property");if(S(e,"constructor"))throw new Error("constructor is not allowed as a property")}const $e=(e,t)=>{ee(t);for(let r=0;r<t.length;r++){const s=t[r];if(k(e))e=b(e,+s);else if(C(e)){const n=+s,i=+t[++r]==0?"key":"value",o=b(e,n);switch(i){case"key":e=o;break;case"value":e=e.get(o);break}}else e=e[s]}return e},M=(e,t,r)=>{if(ee(t),t.length===0)return r(e);let s=e;for(let i=0;i<t.length-1;i++){const o=t[i];if(g(s)){const a=+o;s=s[a]}else if(P(s))s=s[o];else if(k(s)){const a=+o;s=b(s,a)}else if(C(s)){if(i===t.length-2)break;const c=+o,f=+t[++i]==0?"key":"value",p=b(s,c);switch(f){case"key":s=p;break;case"value":s=s.get(p);break}}}const n=t[t.length-1];if(g(s)?s[+n]=r(s[+n]):P(s)&&(s[n]=r(s[n])),k(s)){const i=b(s,+n),o=r(i);i!==o&&(s.delete(i),s.add(o))}if(C(s)){const i=+t[t.length-2],o=b(s,i);switch(+n==0?"key":"value"){case"key":{const c=r(o);s.set(c,s.get(o)),c!==o&&s.delete(o);break}case"value":{s.set(o,r(s.get(o)));break}}}return e},te=e=>e<1;function O(e,t,r,s=[]){if(!e)return;const n=te(r);if(!g(e)){v(e,(a,c)=>O(a,t,r,[...s,...E(c,n)]));return}const[i,o]=e;o&&v(o,(a,c)=>{O(a,t,r,[...s,...E(c,n)])}),t(i,s)}function We(e,t,r,s){return O(t,(n,i)=>{e=M(e,i,o=>qe(o,n,s))},r),e}function Ke(e,t,r){const s=te(r);function n(i,o){const a=$e(e,E(o,s));i.map(c=>E(c,s)).forEach(c=>{e=M(e,c,()=>a)})}if(g(t)){const[i,o]=t;i.forEach(a=>{e=M(e,E(a,s),()=>e)}),o&&v(o,n)}else v(t,n);return e}const Ye=(e,t)=>P(e)||g(e)||C(e)||k(e)||Y(e)||Z(e,t);function Ge(e,t,r){const s=r.get(e);s?s.push(t):r.set(e,[t])}function He(e,t){const r={};let s;return e.forEach(n=>{if(n.length<=1)return;t||(n=n.map(a=>a.map(String)).sort((a,c)=>a.length-c.length));const[i,...o]=n;i.length===0?s=o.map(R):r[R(i)]=o.map(R)}),s?I(r)?[s]:[s,r]:I(r)?void 0:r}const re=(e,t,r,s,n=[],i=[],o=new Map)=>{const a=Ne(e);if(!a){Ge(e,n,t);const u=o.get(e);if(u)return s?{transformedValue:null}:u}if(!Ye(e,r)){const u=z(e,r),m=u?{transformedValue:u.value,annotations:[u.type]}:{transformedValue:e};return a||o.set(e,m),m}if(S(i,e))return{transformedValue:null};const c=z(e,r),f=c?.value??e,p=g(f)?[]:{},h={};v(f,(u,m)=>{if(m==="__proto__"||m==="constructor"||m==="prototype")throw new Error(`Detected property ${m}. This is a prototype pollution risk, please remove it from your object.`);const _=re(u,t,r,s,[...n,m],[...i,e],o);p[m]=_.transformedValue,g(_.annotations)?h[A(m)]=_.annotations:P(_.annotations)&&v(_.annotations,(w,we)=>{h[A(m)+"."+we]=w})});const d=I(h)?{transformedValue:p,annotations:c?[c.type]:void 0}:{transformedValue:p,annotations:c?[c.type,h]:h};return a||o.set(e,d),d};function se(e){return Object.prototype.toString.call(e).slice(8,-1)}function F(e){return se(e)==="Array"}function Xe(e){if(se(e)!=="Object")return!1;const t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function Ze(e,t,r,s,n){const i={}.propertyIsEnumerable.call(s,t)?"enumerable":"nonenumerable";i==="enumerable"&&(e[t]=r),n&&i==="nonenumerable"&&Object.defineProperty(e,t,{value:r,enumerable:!1,writable:!0,configurable:!0})}function D(e,t={}){if(F(e))return e.map(n=>D(n,t));if(!Xe(e))return e;const r=Object.getOwnPropertyNames(e),s=Object.getOwnPropertySymbols(e);return[...r,...s].reduce((n,i)=>{if(i==="__proto__"||F(t.props)&&!t.props.includes(i))return n;const o=e[i],a=D(o,t);return Ze(n,i,a,e,t.nonenumerable),n},{})}class l{constructor({dedupe:t=!1}={}){this.classRegistry=new Ce,this.symbolRegistry=new $(r=>r.description??""),this.customTransformerRegistry=new Te,this.allowedErrorProps=[],this.dedupe=t}serialize(t){const r=new Map,s=re(t,r,this,this.dedupe),n={json:s.transformedValue};s.annotations&&(n.meta={...n.meta,values:s.annotations});const i=He(r,this.dedupe);return i&&(n.meta={...n.meta,referentialEqualities:i}),n.meta&&(n.meta.v=1),n}deserialize(t,r){const{json:s,meta:n}=t;let i=r?.inPlace?s:D(s);return n?.values&&(i=We(i,n.values,n.v??0,this)),n?.referentialEqualities&&(i=Ke(i,n.referentialEqualities,n.v??0)),i}stringify(t){return JSON.stringify(this.serialize(t))}parse(t){return this.deserialize(JSON.parse(t),{inPlace:!0})}registerClass(t,r){this.classRegistry.register(t,r)}registerSymbol(t,r){this.symbolRegistry.register(t,r)}registerCustom(t,r){this.customTransformerRegistry.register({name:r,...t})}allowErrorProps(...t){this.allowedErrorProps.push(...t)}}l.defaultInstance=new l;l.serialize=l.defaultInstance.serialize.bind(l.defaultInstance);l.deserialize=l.defaultInstance.deserialize.bind(l.defaultInstance);l.stringify=l.defaultInstance.stringify.bind(l.defaultInstance);l.parse=l.defaultInstance.parse.bind(l.defaultInstance);l.registerClass=l.defaultInstance.registerClass.bind(l.defaultInstance);l.registerSymbol=l.defaultInstance.registerSymbol.bind(l.defaultInstance);l.registerCustom=l.defaultInstance.registerCustom.bind(l.defaultInstance);l.allowErrorProps=l.defaultInstance.allowErrorProps.bind(l.defaultInstance);l.serialize;l.deserialize;l.stringify;l.parse;l.registerClass;l.registerCustom;l.registerSymbol;l.allowErrorProps;const je=1e4,Qe=3e3,Je=2e3,et=3e4;class tt{_serverUrl;useWs;baseRetryMs;maxRetryMs;onConnectionChange;token;_trpcClient;_wsClient=null;mirror=null;mirrorInit=null;connected=!1;connectedPromise=null;_systemProxy;_connectionVersion=0;connectionListeners=new Set;constructor(t){this._serverUrl=t.serverUrl.replace(/\/+$/,""),this.token=t.token;const r=typeof window<"u";this.useWs=t.useWebSocket??r,this.onConnectionChange=t.onConnectionChange,this.baseRetryMs=t.retryDelayMs??Je,this.maxRetryMs=t.maxRetryDelayMs??et,this._trpcClient=this.buildTrpcClient(),this._systemProxy=V(this._trpcClient)}get serverUrl(){return this._serverUrl}get connectionVersion(){return this._connectionVersion}subscribeConnectionEvents(t){return this.connectionListeners.add(t),()=>{this.connectionListeners.delete(t)}}emitConnectionEvent(t){try{this.onConnectionChange?.(t)}catch{}for(const r of this.connectionListeners)try{r(t,this._connectionVersion)}catch{}}async awaitConnected(t){if(this.connected)return;if(this.connectedPromise)return this.connectedPromise;const r=t??15e3;this.connectedPromise=(async()=>{const s=this._trpcClient.auth.me.query();Number.isFinite(r)?await new Promise((n,i)=>{const o=setTimeout(()=>i(new Error(`System.awaitConnected: probe timed out after ${r}ms`)),r);s.then(()=>{clearTimeout(o),n()},a=>{clearTimeout(o),i(a instanceof Error?a:new Error(String(a)))})}):await s,this.connected=!0})();try{await this.connectedPromise}finally{this.connectedPromise=null}}async init(t){if(this.mirror?.isReady())return;if(this.mirrorInit)return this.mirrorInit;const r=new Ee(this._trpcClient);return this.mirror=r,this.mirrorInit=(async()=>{await this.awaitConnected(t),await r.init(t)})().finally(()=>{this.mirrorInit=null}),this.mirrorInit}async awaitReady(){if(!this.mirror?.isReady())return this.mirrorInit?this.mirrorInit:this.init()}isReady(){return this.mirror?.isReady()??!1}isConnected(){return this.connected}reconnect(){this.useWs&&(this.emitConnectionEvent("connecting"),this._wsClient?.close(),this.disposeMirror(),this.connected=!1,this.connectedPromise=null,this._trpcClient=this.buildTrpcClient(),this._systemProxy=V(this._trpcClient))}switchServerUrl(t){const r=t.replace(/\/+$/,"");r!==this._serverUrl&&(this._serverUrl=r,this.reconnect())}async raceConnectionEndpoints(t){const r=t?.perCandidateTimeoutMs??1500,s=(()=>{try{return new URL(this._serverUrl)}catch{return null}})(),n=s?.port?Number(s.port):s?.protocol==="https:"?443:80,i=s?.protocol==="https:"?"https":"http",a=this._trpcClient.localNetwork?.getConnectionEndpoints;if(!a)return{winner:this._serverUrl,switched:!1};let c;try{c=(await a.query({port:n,ipv4Only:t?.ipv4Only,scheme:i})).endpoints}catch{return{winner:this._serverUrl,switched:!1}}if(c.length===0)return{winner:this._serverUrl,switched:!1};const f=await rt(c.map(p=>p.baseUrl),r);return!f||f===this._serverUrl?{winner:f??this._serverUrl,switched:!1}:(this.switchServerUrl(f),{winner:f,switched:!0})}close(){this.disposeMirror(),this.connected=!1,this.connectedPromise=null,this._wsClient?.close()}disposeMirror(){this.mirror?.dispose(),this.mirror=null,this.mirrorInit=null}async login(t,r){const s=await this._trpcClient.auth.login.mutate({username:t,password:r});if(typeof s=="object"&&s!==null&&"token"in s){const n=s,i=n.token;typeof i=="string"&&n.requiresTotp!==!0&&this.setToken(i)}return s}async loginVerifyTotp(t,r){const s=await this._trpcClient.auth.loginVerifyTotp.mutate({challengeToken:t,code:r});if(typeof s=="object"&&s!==null&&"token"in s){const n=s.token;typeof n=="string"&&this.setToken(n)}return s}async logout(){await this._trpcClient.auth.logout.mutate()}async getMe(){return await this._trpcClient.auth.me.query()}async changeOwnPassword(t){return await this._trpcClient.auth.changeOwnPassword.mutate(t)}async setupOwnTotp(){return await this._trpcClient.auth.setupOwnTotp.mutate()}async confirmOwnTotp(t){return await this._trpcClient.auth.confirmOwnTotp.mutate(t)}async disableOwnTotp(){return await this._trpcClient.auth.disableOwnTotp.mutate()}async getOwnTotpStatus(){return await this._trpcClient.auth.getOwnTotpStatus.query()}setToken(t){this.token=t}listDevices(t){return this.mirror?(t?this.mirror.query(t):this.mirror.getAllDevices()).map(s=>this.attachBinding(s)):[]}getDevice(t){const r=this.mirror?.getDeviceById(t)??null;return r?this.attachBinding(r):null}getDeviceByName(t){const r=this.mirror?.getDeviceByName(t)??null;return r?this.attachBinding(r):null}getDeviceByStableId(t){const r=this.mirror?.getDeviceByStableId(t)??null;return r?this.attachBinding(r):null}async waitForDevice(t,r){this.mirror||await this.init();const s=await this.mirror.waitForDevice(t,r??3e4);return this.attachBinding(s)}onDeviceAdded(t){if(!this.mirror)throw new Error("System.onDeviceAdded: call init() before subscribing");return this.mirror.onDeviceAdded(t)}onDeviceRemoved(t){if(!this.mirror)throw new Error("System.onDeviceRemoved: call init() before subscribing");return this.mirror.onDeviceRemoved(t)}attachBinding(t){const r=this.lookupBinding(t.deviceId);if(r===t.binding)return t;const s=t;return s.binding=r,t}lookupBinding(t){return this.mirror?this.mirror.getDeviceById(t)?.binding??null:null}get addonPages(){return this._systemProxy.addonPages}get addonSettings(){return this._systemProxy.addonSettings}get alerts(){return this._systemProxy.alerts}get audioAnalyzer(){return this._systemProxy.audioAnalyzer}get audioCodec(){return this._systemProxy.audioCodec}get backup(){return this._systemProxy.backup}get decoder(){return this._systemProxy.decoder}get deviceManager(){return this._systemProxy.deviceManager}get deviceProvider(){return this._systemProxy.deviceProvider}get deviceState(){return this._systemProxy.deviceState}get metricsProvider(){return this._systemProxy.metricsProvider}get notificationOutput(){return this._systemProxy.notificationOutput}get pipelineExecutor(){return this._systemProxy.pipelineExecutor}get pipelineOrchestrator(){return this._systemProxy.pipelineOrchestrator}get pipelineRunner(){return this._systemProxy.pipelineRunner}get platformProbe(){return this._systemProxy.platformProbe}get recordingEngine(){return this._systemProxy.recordingEngine}get settingsStore(){return this._systemProxy.settingsStore}get storage(){return this._systemProxy.storage}get streamBroker(){return this._systemProxy.streamBroker}get turnProvider(){return this._systemProxy.turnProvider}get userManagement(){return this._systemProxy.userManagement}subscribeEvent(t,r){const s=this._trpcClient.live.onEvent.subscribe({category:t},{onData:n=>{try{r(n)}catch{}}});return()=>{try{s.unsubscribe()}catch{}}}get trpcClient(){return this._trpcClient}get wsClient(){return this._wsClient}buildTrpcClient(){const t=()=>{const r={};return this.token&&(r.Authorization=`Bearer ${this.token}`),r};if(this.useWs){const r=this._serverUrl.replace(/^http/,"ws")+"/trpc",s=this.baseRetryMs,n=this.maxRetryMs;return this._wsClient=_e({url:r,connectionParams:()=>({token:this.token}),retryDelayMs:i=>Math.min(s*Math.pow(2,i),n),keepAlive:{enabled:!0,intervalMs:je,pongTimeoutMs:Qe},onOpen:()=>{this._connectionVersion+=1,this.emitConnectionEvent("connected")},onClose:()=>{this.emitConnectionEvent("disconnected")}}),x({links:[be({client:this._wsClient,transformer:l})]})}return this._wsClient=null,x({links:[ve({url:`${this._serverUrl}/trpc`,headers:t,transformer:l})]})}}function mt(e){return new tt(e)}async function rt(e,t){if(e.length===0)return null;if(typeof fetch!="function")return e[0]??null;const s=typeof window<"u"&&typeof window.location<"u"&&window.location.protocol==="https:"?e.filter(o=>o.toLowerCase().startsWith("https://")):e;if(s.length===0)return null;const n=s.map(()=>new AbortController),i=s.map(async(o,a)=>{const c=n[a],f=setTimeout(()=>c.abort(),t);try{const p=await fetch(`${o.replace(/\/+$/,"")}/trpc/health`,{method:"GET",signal:c.signal,credentials:"omit"});if(!p.ok)throw new Error(`${p.status}`);return o}finally{clearTimeout(f)}});try{const o=await Promise.any(i);for(const a of n)try{a.abort()}catch{}return o}catch{return null}}var ne=(e=>(e.Motion="motion",e.Person="person",e.Vehicle="vehicle",e.Animal="animal",e.Audio="audio",e.Face="face",e.Plate="plate",e.Package="package",e.Doorbell="doorbell",e.Sensor="sensor",e))(ne||{});const ie=["animal","dog_cat","dog","cat","horse","sheep","cow","elephant","bear","zebra","giraffe","mouse","rabbit","deer","lion","tiger","bird","eagle","owl","pigeon","fish","whale","dolphin","snake","turtle","lizard"],oe=["person","people","pedestrian","rider","driver","cyclist","skier","skateboarder","face","hand","head","body"],ae=["vehicle","car","truck","bus","motorcycle","bicycle","van","ambulance","police_car","fire_truck","train","subway","tram","airplane","boat","ship","helicopter"],le=["face","eyes","nose","mouth","ears","eyebrows","left_eye","right_eye","pupil","iris","eyelid","eye_corner","upper_lip","lower_lip","teeth","chin","cheek","forehead","jaw","glasses","sunglasses","facial_hair","beard","mustache","facial_landmark","facial_keypoint"],ce=["plate","license_plate","front_plate","rear_plate","motorcycle_plate","temporary_plate","dealer_plate","licensePlate","plate_number","plate_character","plate_digit","plate_letter","plate_symbol","plate_region","plate_country_identifier","plate_frame","plate_bolt","plate_sticker","plate_validation_tag","damaged_plate","obscured_plate","dirty_plate"],ue=["motion","movement","other"],de=["package","packet"],fe=["audio"],me=["speech","scream","babbling","yell","bellow","whoop","whispering","laughter","snicker","crying","cry","sigh","singing","choir","chant","mantra","child_singing","rapping","humming","groan","grunt","whistling","breathing","wheeze","snoring","gasp","pant","snort","cough","throat_clearing","sneeze","sniff","cheering","applause","chatter","crowd","children_playing","bark","yip","howl","bow-wow","growling","whimper_dog","purr","meow","hiss","caterwaul","pets","livestock","doorbell","ding-dong","door","slam","knock","alarm","telephone","music","dog","dogs"],pe=["doorbell","ring"],he=["lock","binary","flood","entry","door","leak","door_open","flooded","entry_open"],ye={...ie.reduce((e,t)=>({...e,[t]:"animal"}),{}),...oe.reduce((e,t)=>({...e,[t]:"person"}),{}),...ae.reduce((e,t)=>({...e,[t]:"vehicle"}),{}),...ue.reduce((e,t)=>({...e,[t]:"motion"}),{}),...de.reduce((e,t)=>({...e,[t]:"package"}),{}),...le.reduce((e,t)=>({...e,[t]:"face"}),{}),...ce.reduce((e,t)=>({...e,[t]:"plate"}),{}),...fe.reduce((e,t)=>({...e,[t]:"audio"}),{}),...me.reduce((e,t)=>({...e,[t]:"audio"}),{}),...pe.reduce((e,t)=>({...e,[t]:"doorbell"}),{}),...he.reduce((e,t)=>({...e,[t]:"sensor"}),{})},st=e=>le.includes(e),nt=e=>ce.includes(e),pt=e=>ie.includes(e),ht=e=>oe.includes(e),yt=e=>ae.includes(e),gt=e=>ue.includes(e),wt=e=>pe.includes(e),_t=e=>de.includes(e),bt=e=>fe.includes(e)||me.includes(e),vt=e=>he.includes(e),Et=e=>st(e)||nt(e),Pt=e=>ye[e],Ct=e=>{const{className:t}=e,r={face:"person",plate:"vehicle"},s=ye[t];return s&&s!==t?s:r[t]},it=Object.values(ne),L=it.filter(e=>e!=="motion"),ge=["person","doorbell","package"],ot=[...ge,"vehicle","animal","audio","face","plate"],at=[...L];function kt(e,t){switch(e){case"critical":return ge;case"important":return ot;case"all":return at;case"custom":return t?.length?t:L;default:return L}}const q={Light:"light",Switch:"switch",WindowCovering:"cover",Lock:"lock",SecuritySystem:"alarm",Buttons:"button",Select:"select",Siren:"siren",Sensor:"sensor",Entry:"entry",Program:"script",MediaPlayer:"media_player",Outlet:"switch",light:"light",switch:"switch",input_boolean:"switch",cover:"cover",lock:"lock",alarm_control_panel:"alarm",input_button:"button",button:"button",input_select:"select",select:"select",siren:"siren",sensor:"sensor",media_player:"media_player",script:"script"},St={light:"light",switch:"switch",input_boolean:"switch",cover:"cover",lock:"lock",alarm_control_panel:"alarm",input_button:"button",button:"button",input_select:"select",select:"select",siren:"siren",sensor:"sensor",binary_sensor:"sensor",media_player:"media_player",script:"script",climate:"climate",camera:"camera",fan:"fan",vacuum:"vacuum",automation:"automation",scene:"scene",input_number:"sensor",person:"person",device_tracker:"tracker",weather:"weather",water_heater:"climate"},Tt={Light:"light",Switch:"switch",WindowCovering:"cover",Lock:"lock",SecuritySystem:"alarm",Buttons:"button",Select:"select",Siren:"siren",Sensor:"sensor",Entry:"entry",Program:"script",MediaPlayer:"media_player",Camera:"camera",Doorbell:"doorbell",Fan:"fan",Outlet:"switch"};function Rt(e){const t=q[e];if(t)return t;const r=e.toLowerCase();return q[r]??null}const lt=["Entry","Light","Switch","Lock","SecuritySystem","Buttons","WindowCovering","Siren","Sensor","Select","Program"],It=new Set(lt),ct=["light","switch","input_boolean","cover","lock","alarm_control_panel","input_button","button","input_select","select","siren","media_player","script"],At=new Set(ct),N=[{id:"liveStream",label:"Live Stream",sources:{frigate:!0,scrypted:!0,rtsp:!0},adapterMethod:"getLiveStream"},{id:"multiResolution",label:"Multi-Resolution",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getResolutions"},{id:"motion",label:"Motion Detection",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getMotion"},{id:"objectDetection",label:"Object Detection",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getObjectDetections"},{id:"audioVolume",label:"Audio Level",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getAudioVolume"},{id:"audioVolumes",label:"Audio Volumes (dBFS)",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getAudioVolumes"},{id:"ptz",label:"PTZ Control",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getPTZ"},{id:"intercom",label:"Intercom (Mic)",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getIntercomSupport"},{id:"deviceStatus",label:"Device Status",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"getStatus"},{id:"timeline",label:"Detection Timeline",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getCameraDayData"},{id:"clusteredTimeline",label:"Clustered Timeline",sources:{frigate:!0,scrypted:!0,rtsp:!1},requiresBackend:!0,adapterMethod:"getClusteredDayData"},{id:"detectionClasses",label:"Detection Classes",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getDetectionClasses"},{id:"videoClips",label:"Video Clips",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getVideoClips"},{id:"nvrPlayback",label:"NVR Playback",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getNvrPlaybackSupported"},{id:"nvrScrub",label:"NVR Scrub/Seek",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"seekRecordingStream"},{id:"recordingThumbnail",label:"Recording Thumbnails",sources:{frigate:!0,scrypted:!0,rtsp:!1},adapterMethod:"getRecordingStreamThumbnail"},{id:"nvrSeekToLive",label:"Seek to Live",sources:{frigate:!1,scrypted:!0,rtsp:!1},adapterMethod:"seekNvrToLive"}];function Mt(e,t,r){const s=N.find(n=>n.id===e);return!(!s||!s.sources[t]||s.platforms&&s.platforms[r]===!1)}function Ot(e){return N.filter(t=>t.sources[e])}function Dt(){return N.filter(e=>e.requiresBackend)}function Lt(e,t,r){if(e.length===0)return null;const s=t.viewportWidth*t.viewportHeight*(t.pixelRatio??1),n=t.bandwidthMbps??100,i=t.packetLoss??0,o=t.rttMs??50;let a="high";t.maxResolution==="low"||t.isCellular||n<1||i>.05?a="low":t.maxResolution==="medium"||n<5||s<5e5||o>200?a="medium":(t.maxResolution==="high"||s>2e6)&&(a="high");const c={main:"high",sub:"medium",ext:"low"},f=r??"native",p=e.map(d=>{let u=0;const m=c[d.profile]??"medium";if(m===a?u+=100:(a==="high"&&m==="medium"||a==="medium"&&m==="high"||a==="medium"&&m==="low"||a==="low"&&m==="medium")&&(u+=50),d.transport===f?u+=30:d.transport==="native"?u+=20:d.transport==="rtsp"?u+=15:d.transport==="rtmp"&&(u+=10),d.metadata?.width&&d.metadata?.height){const w=d.metadata.width*d.metadata.height/Math.max(s,1);w>=.8&&w<=2?u+=25:w>=.5&&w<=3&&(u+=15),w>4&&n<10&&(u-=20)}return d.metadata?.codec&&(n<5&&d.metadata.codec.includes("265")&&(u+=10),n>=10&&d.metadata.codec.includes("264")&&(u+=5)),{...d,score:u,targetTier:a}});p.sort((d,u)=>u.score-d.score);const h=p[0];return{streamName:h.streamName,profile:h.profile,transport:h.transport,label:h.label,metadata:h.metadata,reason:`${h.targetTier} quality → ${h.profile}/${h.transport} (score: ${h.score})`}}function Nt(e,t){return t?10:e.isCellular||(e.packetLoss??0)>.02?15:30}export{L as DEFAULT_ENABLED_CLASSES,ne as DetectionClass,ct as ELIGIBLE_HA_DOMAINS,At as ELIGIBLE_HA_DOMAINS_SET,lt as ELIGIBLE_SCRYPTED_DEVICE_TYPES,It as ELIGIBLE_SCRYPTED_DEVICE_TYPES_SET,N as FEATURE_MATRIX,St as HA_DOMAIN_TYPE_MAP,q as RAW_TO_CANONICAL,Tt as SCRYPTED_TYPE_TO_CANONICAL,tt as System,at as TIMELINE_PRESET_ALL,ge as TIMELINE_PRESET_CRITICAL,ot as TIMELINE_PRESET_IMPORTANT,ie as animalClasses,fe as audioClasses,me as audioLabelClasses,mt as createSystem,it as defaultDetectionClasses,ye as detectionClassesDefaultMap,pe as doorbellClasses,le as faceClasses,Dt as getBackendRequiredFeatures,Rt as getCanonicalDeviceType,kt as getClassesForTimelinePreset,Nt as getNextEvalInterval,Pt as getParentClass,Ct as getParentDetectionClass,Ot as getSourceFeatures,pt as isAnimalClassname,bt as isAudioClassname,wt as isDoorbellClassname,st as isFaceClassname,Mt as isFeatureAvailable,Et as isLabelDetection,gt as isMotionClassname,_t as isPackageClassname,ht as isPersonClassname,nt as isPlateClassname,vt as isSensorLabelClassname,yt as isVehicleClassname,ce as licensePlateClasses,ue as motionClasses,de as packageClasses,oe as personClasses,rt as raceFastestEndpoint,Lt as selectOptimalStream,he as sensorLabelClasses,ae as vehicleClasses};
@@ -1 +1 @@
1
- import{h as P,z as L,i as F,j as $,s as U,k as z,p as K,m as W,l as H,n as j,o as D,q as Z,r as R,t as q,u as V,v as G,w as Y,x as J,y as Q,A as ye,B as ve,C as Ce,F as we,G as Ie,H as Ae,I as Ee,J as _e,K as ke,L as Pe,O as De,P as Re,Q as Ne,R as Te,T as xe,U as Oe,V as Me,X as Be,Y as Le,Z as Fe,_ as $e,$ as Ue,a0 as ze,a1 as Ke,a2 as We,a3 as He,a4 as je,a5 as Ze,a6 as qe,a7 as Ve,a8 as Ge,a9 as Ye,aa as Je,ab as Qe,ac as Xe,ad as et,ae as tt,af as at,ag as st,ah as it,ai as nt,aj as rt,ak as ot,al as ct,am as dt,an as lt,ao as ut,ap as ht,aq as mt,ar as pt,as as ft,at as gt,au as St,av as bt,aw as yt,ax as vt,ay as Ct,az as wt,aA as It,aB as At,aC as Et,aD as _t,aE as kt,aF as Pt,aG as Dt,aH as Rt,aI as Nt,aJ as Tt,aK as xt,aL as Ot,aM as Mt,aN as Bt,aO as Lt,aP as Ft,aQ as $t,aR as Ut,aS as zt,aT as Kt,aU as Wt,aV as Ht,aW as jt,aX as Zt,aY as qt,aZ as Vt,a_ as Gt,a$ as Yt,b0 as Jt,b1 as Qt,b2 as Xt,b3 as ea,b4 as ta,b5 as aa,b6 as sa,b7 as ia,D as na,b8 as ra,b as oa,b9 as ca,ba as da,bb as la,bc as ua,a as ha,bd as ma,be as pa,bf as fa,bg as ga,bh as Sa,bi as ba,bj as ya,bk as va,bl as Ca,bm as wa,bn as Ia,bo as Aa,bp as Ea,E as _a,bq as ka,br as Pa,bs as Da,bt as Ra,bu as Na,bv as Ta,bw as xa,bx as Oa,by as Ma,bz as Ba,bA as La,bB as Fa,bC as $a,bD as Ua,bE as za,bF as Ka,bG as Wa,bH as Ha,bI as ja,bJ as Za,bK as qa,M as Va,bL as Ga,bM as Ya,d as Ja,bN as Qa,bO as Xa,bP as es,bQ as ts,bR as as,bS as ss,bT as is,bU as ns,bV as rs,bW as os,bX as cs,bY as ds,bZ as ls,S as us,b_ as hs,b$ as ms,c0 as ps,N as fs,c1 as gs,c2 as Ss,c3 as bs,c4 as ys,c5 as vs,c6 as Cs,c7 as ws,c8 as Is,c9 as As,ca as Es,cb as _s,cc as ks,cd as Ps,ce as Ds,cf as Rs,cg as Ns,ch as Ts,ci as xs,cj as Os,ck as Ms,cl as Bs,cm as Ls,cn as Fs,co as $s,cp as Us,cq as zs,cr as Ks,cs as Ws,ct as Hs,cu as js,cv as Zs,cw as qs,cx as Vs,cy as Gs,cz as Ys,cA as Js,cB as Qs,cC as Xs,cD as ei,cE as ti,cF as ai,cG as si,cH as ii,cI as ni,cJ as ri,cK as oi,cL as ci,e as di,cM as li,cN as ui,cO as hi,cP as mi,cQ as pi,cR as fi,cS as gi,cT as Si,cU as bi,cV as yi,cW as vi,cX as Ci,cY as wi,cZ as Ii,c_ as Ai,c$ as Ei,d0 as _i,d1 as ki,d2 as Pi,d3 as Di,d4 as Ri,d5 as Ni,d6 as Ti,d7 as xi,d8 as Oi,d9 as Mi,da as Bi,db as Li,dc as Fi,dd as $i,de as Ui,df as zi,dg as Ki,dh as Wi,di as Hi,dj as ji,dk as Zi,dl as qi,dm as Vi,dn as Gi,dp as Yi,dq as Ji,dr as Qi,ds as Xi,dt as en,du as tn,dv as an,g as sn,dw as nn,dx as rn,dy as on,dz as cn,dA as dn,dB as ln,dC as un,dD as hn,dE as mn,dF as pn,dG as fn,dH as gn,dI as Sn,dJ as bn,dK as yn,W as vn,dL as Cn,dM as wn,dN as In,dO as An,dP as En,dQ as _n,dR as kn,dS as Pn,dT as Dn,dU as Rn,dV as Nn,dW as Tn,dX as xn,dY as On,dZ as Mn,d_ as Bn,d$ as Ln,e0 as Fn,e1 as $n,e2 as Un,e3 as zn,e4 as Kn,e5 as Wn,e6 as Hn,e7 as jn,e8 as Zn,e9 as qn,ea as Vn,eb as Gn,ec as Yn,ed as Jn,ee as Qn,c as Xn,ef as er,eg as tr,eh as ar,f as sr,ei as ir,ej as nr,ek as rr,el as or,em as cr,en as dr,eo as lr,ep as ur,eq as hr,er as mr,es as pr,et as fr,eu as gr,ev as Sr,ew as br,ex as yr,ey as vr,ez as Cr,eA as wr,eB as Ir,eC as Ar,eD as Er,eE as _r,eF as kr,eG as Pr,eH as Dr,eI as Rr,eJ as Nr,eK as Tr,eL as xr,eM as Or,eN as Mr,eO as Br,eP as Lr,eQ as Fr,eR as $r,eS as Ur,eT as zr,eU as Kr,eV as Wr,eW as Hr,eX as jr,eY as Zr,eZ as qr,e_ as Vr,e$ as Gr,f0 as Yr,f1 as Jr,f2 as Qr,f3 as Xr,f4 as eo,f5 as to,f6 as ao,f7 as so,f8 as io,f9 as no,fa as ro,fb as oo}from"./index-DQFO9ZU6.js";import{E as v,A as co,C as lo,a as uo,D as ho,K as mo,M as po,S as fo}from"./method-access-map-DLEhlu0x.js";import{Z as go,p as So,q as bo,v as yo,w as vo,x as Co,y as X,z as wo,A as Io}from"./schemas-BEt-CulV.js";class Ao{disposers=[];disposed=!1;onError;constructor(e={}){this.onError=e.onError??((t,s)=>{console.error(`[DisposerChain] disposer #${s} threw`,t)})}add(e){if(this.disposed){try{const t=e();t&&typeof t.then=="function"&&t.catch(s=>this.onError(s,-1))}catch(t){this.onError(t,-1)}return()=>{}}return this.disposers.push(e),()=>{const t=this.disposers.indexOf(e);t>=0&&this.disposers.splice(t,1)}}get isDisposed(){return this.disposed}get size(){return this.disposers.length}async dispose(){if(this.disposed)return;this.disposed=!0;const e=this.disposers.slice().reverse();this.disposers=[];for(let t=0;t<e.length;t++){const s=e[t];try{const i=s();i&&typeof i.then=="function"&&await i}catch(i){this.onError(i,e.length-1-t)}}}}const ee="hub-only";function y(a){return{placement:a.execution?.placement??ee,group:a.execution?.group}}function Eo(a){const e=y(a).placement;return e==="any-node"||e==="agent-only"}function _o(a){return y(a).placement==="agent-only"}function ko(a){return y(a).group}function Po(a,e){return a.execution?.group??e}function Do(a){return y(a).placement}function Ro(a,e){return a.category===e}function N(a,e,t){return{id:typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2),timestamp:new Date,source:e,category:a,data:t}}function te(a,e){const t=e.ts??Date.now();a.emit(N("system.ready-state",{type:"capability",id:e.capName,nodeId:e.sourceNodeId},{capName:e.capName,scope:e.scope,state:e.state,generation:e.generation,sourceNodeId:e.sourceNodeId,ts:t}))}class ae{_ctx=null;_config;_readinessGeneration=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2,14);_registeredCapNames=[];defaults;constructor(e){this.defaults=e,this._config={...e}}get autoEmitReadiness(){return!0}get ctx(){if(!this._ctx)throw new Error(`${this.constructor.name}: ctx accessed before initialize()`);return this._ctx}get ctxIfReady(){return this._ctx}get config(){return this._config}async initialize(e){this._ctx=e,await this.resolveConfig();const t=await this.onInitialize();this.emitLifecycle(v.AddonStarted);const s=se(t),i=s&&"providers"in s&&s.providers?s.providers:[];return this._registeredCapNames=i.map(n=>n.capability.name),s}postBrokerStart(){this.autoEmitReadiness&&this._registeredCapNames.length>0&&this.emitReadinessForProviders("ready")}async onHubReachable(){}async shutdown(){this.emitLifecycle(v.AddonStopped),this.autoEmitReadiness&&this.emitReadinessForProviders("down"),await this.onShutdown();for(const e of this._subscriptions)e();this._subscriptions=[],this._ctx=null}async onShutdown(){}async onConfigChanged(){}field(e){return e}schema(e){return e}globalSettingsSchema(){return null}deviceSettingsSchema(){return null}async getGlobalSettings(e){const t=this.globalSettingsSchema();if(!t)return{sections:[]};const s=await this._ctx?.settings?.readAddonStore()??{};return P(t,e?{...s,...e}:s)}async updateGlobalSettings(e){await this._ctx?.settings?.writeAddonStore(e),await this.resolveConfig(),await this.onConfigChanged(),this.emitLifecycle(v.AddonUpdated,{level:"global"}),this.maybeAutoRestart(e,this.globalSettingsSchema())}maybeAutoRestart(e,t){if(!t)return;const s=new Set;for(const o of t.sections)for(const c of o.fields)c.type==="separator"||c.type==="info"||c.requiresRestart&&s.add(c.key);if(s.size===0||!Object.keys(e).some(o=>s.has(o)))return;const n=this._ctx;if(!n)return;const r=n.id;setImmediate(()=>{n.api.addons?.restartAddon?.mutate({addonId:r}).then(()=>{n.logger.info("addon auto-restart triggered by restart-required setting change",{meta:{changedFields:Object.keys(e).filter(c=>s.has(c))}})}).catch(c=>{n.logger.error("addon auto-restart failed",{meta:{error:c instanceof Error?c.message:String(c)}})})})}async getDeviceSettings(e){const t=this.deviceSettingsSchema();if(!t)return{sections:[]};const s=await this._ctx?.settings?.readDeviceStore(e)??{};return P(t,s)}async updateDeviceSettings(e,t){await this._ctx?.settings?.writeDeviceStore(e,t)}_subscriptions=[];watchCapability(e,t){const s=Array.isArray(e)?e:[e],i=new Set(s);this.subscribe({category:"system.ready-state"},n=>{const r=n.data;if(typeof r.capName!="string"||!i.has(r.capName)||r.scope?.type!=="node")return;const o=r.scope.nodeId;if(typeof o!="string"||o.length===0)return;const c=r.capName;r.state==="down"?t.onDown?.(o,c):r.state==="ready"&&t.onReady?.(o,c)})}subscribe(e,t){const s=this.ctx.eventBus.subscribe(e,t);this._subscriptions.push(s)}emitLifecycle(e,t){try{this._ctx?.eventBus.emit({id:`${this._ctx.id}-${Date.now()}`,timestamp:new Date,source:{type:"addon",id:this._ctx.id,nodeId:this._ctx.kernel.localNodeId??"hub"},category:e,data:t??{}})}catch{}}emitReadinessForProviders(e){const t=this._ctx;if(!t||this._registeredCapNames.length===0)return;const s=t.kernel?.localNodeId??"hub",i=s.includes("/")?s.split("/")[0]:s;for(const n of this._registeredCapNames)try{te(t.eventBus,{capName:n,scope:{type:"node",nodeId:i},state:e,generation:this._readinessGeneration,sourceNodeId:i})}catch{}}async resolveModelsDir(){return this.ctx.api.storage.resolve.query({location:"models",relativePath:""}).catch(()=>"camstack-data/models")}get capabilities(){return this.ctx.capabilities??null}async resolveConfig(){const e=await this.readAddonStoreWithRetry(),t={...this.defaults};for(const s of Object.keys(this.defaults)){const i=e[s];if(i!=null){const n=typeof this.defaults[s];typeof i===n&&(t[s]=i)}}this._config=t}async readAddonStoreWithRetry(){const e=this._ctx?.settings;if(!e)return{};const t=[150,350,600,900];let s;for(let i=0;i<=t.length;i++)try{return await e.readAddonStore()??{}}catch(n){s=n;const r=n instanceof Error?n.message:String(n);if(!(r.includes("SqliteSettingsBackend not initialized")||r.includes("provider not available")))throw n;if(i===t.length)break;await new Promise(c=>setTimeout(c,t[i]))}return this._ctx?.logger?.warn?.("readAddonStore: settings-store unavailable after retries — using defaults",{meta:{error:s instanceof Error?s.message:String(s)}}),{}}}function se(a){if(a!=null)return Array.isArray(a)?{providers:a}:a}function No(a,e){return{id:a,getRoutes:()=>e,invoke:async t=>{const s=To(e,t.method,t.path);if(!s)return{status:404,headers:{},redirectUrl:null,body:{error:`No route matches ${t.method} ${t.path}`}};const i={status:200,headers:{},redirectUrl:null},n=Oo(i),r={params:{...t.params,...s.params},query:t.query,body:t.body,headers:t.headers,...t.user?{user:t.user}:{},...t.scopedToken!==void 0?{scopedToken:t.scopedToken}:{}};return await s.route.handler(r,n),i}}}function To(a,e,t){const s=e.toUpperCase();for(const i of a){if(i.method!==s)continue;const n=xo(i.path,t);if(n!==null)return{route:i,params:n}}return null}function xo(a,e){const t=a.split("/").filter(Boolean),s=e.split("/").filter(Boolean);if(t.length!==s.length)return null;const i={};for(let n=0;n<t.length;n++){const r=t[n],o=s[n];if(r.startsWith(":"))i[r.slice(1)]=o;else if(r!==o)return null}return i}function Oo(a){const e={status(t){return a.status=t,e},code(t){return a.status=t,e},send(t){a.body=t},redirect(t){a.redirectUrl=t,a.status===200&&(a.status=302)},header(t,s){return a.headers[t.toLowerCase()]=s,e},type(t){return a.contentType=t,e}};return e}class ie extends Error{capName;scope;waitedMs;constructor(e,t,s){super(`Timed out waiting for ${e} (${f(t)}) to become ready after ${s}ms`),this.name="ReadinessTimeoutError",this.capName=e,this.scope=t,this.waitedMs=s}}function C(a,e){return`${a}|${f(e)}`}function f(a){switch(a.type){case"global":return"global";case"node":return`node:${a.nodeId}`;case"device":return`device:${a.deviceId}`}}function _(a,e){return a.type!==e.type?!1:a.type==="global"||e.type==="global"?!0:a.type==="node"&&e.type==="node"?a.nodeId===e.nodeId:a.type==="device"&&e.type==="device"?a.deviceId===e.deviceId:!1}class Mo{bus;sourceNodeId;logger;now;generation;snapshot=new Map;subscriptions=new Set;unsubscribeBus;unsubscribeAgentOffline;constructor(e){if(this.bus=e.eventBus,this.sourceNodeId=e.sourceNodeId,this.logger=e.logger,this.now=e.now??(()=>Date.now()),this.generation=e.generation??Bo(),this.unsubscribeBus=this.bus.subscribe({category:"system.ready-state"},t=>this.ingest(t.data)),this.unsubscribeAgentOffline=this.bus.subscribe({category:"agent.offline"},t=>this.synthesizeDownForNode(t.data.agentId)),typeof this.bus.getRecent=="function")try{const t=this.bus.getRecent({category:"system.ready-state"});for(const s of t)this.ingest(s.data)}catch{}}close(){this.unsubscribeBus(),this.unsubscribeAgentOffline(),this.subscriptions.clear()}get(e,t){return this.snapshot.get(C(e,t))??null}getSnapshotForTransport(){return Array.from(this.snapshot.values())}hydrate(e){const t=this.now();for(const s of e){const i=C(s.capName,s.scope);if(this.snapshot.has(i))continue;const n={capName:s.capName,scope:s.scope,state:s.state,generation:s.generation,epoch:1,lastChange:t,sourceNodeId:s.sourceNodeId};this.snapshot.set(i,n),this.logger&&this.logger.debug(`readiness: ${s.capName} (${f(s.scope)}) → ${s.state} (hydrated, gen=${s.generation.slice(0,6)})`);const r={capName:s.capName,scope:s.scope,state:s.state,epoch:1,generation:s.generation,sourceNodeId:"hydrated",ts:t,durationInPrevState:0};for(const o of this.subscriptions)if(o.capName===s.capName&&_(o.scope,s.scope))try{o.handler(r)}catch(c){this.logger?.warn(`readiness hydrate handler threw for ${s.capName}: ${c.message??String(c)}`)}}}getAll(){return new Map(this.snapshot)}emitReady(e,t){this.emitTransition(e,t,"ready")}emitStarting(e,t){this.emitTransition(e,t,"starting")}emitDown(e,t){this.emitTransition(e,t,"down")}awaitReady(e,t,s={}){const i=s.timeoutMs??Number.POSITIVE_INFINITY,n=this.now();return this.get(e,t)?.state==="ready"?Promise.resolve():s.signal?.aborted?Promise.reject(s.signal.reason??new Error("aborted")):new Promise((o,c)=>{let l=!1;const d=this.onReadyState(e,t,A=>{A.state==="ready"&&(l||(l=!0,p(),o()))}),h=!Number.isFinite(i)?null:setTimeout(()=>{l||(l=!0,p(),c(new ie(e,t,this.now()-n)))},i),S=()=>{l||(l=!0,p(),c(s.signal?.reason??new Error("aborted")))};s.signal?.addEventListener("abort",S,{once:!0});function p(){d(),h!==null&&clearTimeout(h),s.signal?.removeEventListener("abort",S)}})}onReadyState(e,t,s){const i={capName:e,scope:t,handler:s};this.subscriptions.add(i);const n=this.get(e,t);return n!==null&&queueMicrotask(()=>{this.subscriptions.has(i)&&s({capName:e,scope:t,state:n.state,epoch:n.epoch,generation:n.generation,sourceNodeId:this.sourceNodeId,ts:n.lastChange,durationInPrevState:0})}),()=>{this.subscriptions.delete(i)}}emitTransition(e,t,s){const i=this.now();this.bus.emit(N("system.ready-state",{type:"capability",id:e,nodeId:this.sourceNodeId},{capName:e,scope:t,state:s,generation:this.generation,sourceNodeId:this.sourceNodeId,ts:i}))}ingest(e){if(typeof e?.capName!="string"||e.state!=="ready"&&e.state!=="starting"&&e.state!=="down"||typeof e.generation!="string"||e.scope?.type!=="global"&&e.scope?.type!=="node"&&e.scope?.type!=="device")return;const t=C(e.capName,e.scope),s=this.snapshot.get(t)??null,i=this.now();let n;if(s===null?n=e.state==="ready"?1:0:s.generation!==e.generation&&e.state==="ready"?n=s.epoch+1:n=s.epoch,s!==null&&s.generation===e.generation&&s.state===e.state)return;const r=s===null?0:Math.max(0,i-s.lastChange),o={capName:e.capName,scope:e.scope,state:e.state,generation:e.generation,epoch:n,lastChange:i,sourceNodeId:e.sourceNodeId};this.snapshot.set(t,o);const c={capName:e.capName,scope:e.scope,state:e.state,epoch:n,generation:e.generation,sourceNodeId:e.sourceNodeId,ts:e.ts,durationInPrevState:r};this.logger&&this.logger.debug(`readiness: ${e.capName} (${f(e.scope)}) → ${e.state} epoch=${n} gen=${e.generation.slice(0,6)} (prev ${r}ms)`);for(const l of this.subscriptions)if(l.capName===e.capName&&_(l.scope,e.scope))try{l.handler(c)}catch(d){this.logger?.warn(`readiness handler threw for ${e.capName}: ${d.message??String(d)}`)}}synthesizeDownForNode(e){const t=this.now();for(const[s,i]of this.snapshot){if(i.state==="down"||!(i.scope.type==="node"&&i.scope.nodeId===e||i.scope.type==="device"&&i.sourceNodeId===e))continue;const r=Math.max(0,t-i.lastChange),o={...i,state:"down",lastChange:t};this.snapshot.set(s,o);const c={capName:i.capName,scope:i.scope,state:"down",epoch:i.epoch,generation:i.generation,sourceNodeId:this.sourceNodeId,ts:t,durationInPrevState:r};this.logger&&this.logger.debug(`readiness: ${i.capName} (${f(i.scope)}) → down (synthesized from agent.offline ${e})`);for(const l of this.subscriptions)if(l.capName===i.capName&&_(l.scope,i.scope))try{l.handler(c)}catch(d){this.logger?.warn(`readiness handler threw during agent.offline demux for ${i.capName}: ${d.message??String(d)}`)}}}}function Bo(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2,14)}function Lo(a,e){for(const{capName:t,scope:s}of e)a.emitDown(t,s)}const Fo=["data","media","recordings","recordings-high","recordings-low","recordings-clips","event-images","models","addons-data","cache","logs","backups"],$o={data:"db",media:"media",recordings:"recordings","recordings-high":"recordings-high","recordings-low":"recordings-low","recordings-clips":"recordings-clips","event-images":"event-images",models:"models","addons-data":"addons-data",cache:"/tmp/camstack-cache",logs:"logs",backups:"backups"},ne={high:"High",mid:"Mid",low:"Low"};function Uo(a){return ne[a]??a.charAt(0).toUpperCase()+a.slice(1)}function re(a){return(a.width??0)*(a.height??0)}function oe(a){if(a.length===0)return[];const e=a.map((s,i)=>({s,i,px:re(s.metadata??{})})).sort((s,i)=>i.px-s.px),t=Array.from({length:a.length});for(let s=0;s<e.length;s++){const{s:i,i:n}=e[s];let r;s===0?r="high":s===e.length-1?r="low":r="mid",t[n]={...i,quality:r}}return t}function zo(a){const e=a.height??0,t=a.width??0;return e>=1080||t>=1920?"high":e>=480||t>=640?"mid":"low"}function Ko(a){const e=a.protocols.find(i=>i.type==="rtsp"&&i.url)??a.protocols.find(i=>i.url),t=e?.type,s=t==="rtsp"?"rtsp":t==="http"||t==="flv"?"http-mjpeg":"custom";return{id:a.id,label:a.label??a.id,protocol:s,url:e?.url,profileHint:a.quality}}function m(a){return typeof a=="string"}function Wo(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)}function Ho(a){return m(a)&&a.trim()?{url:a}:Wo(a)&&m(a.url)&&a.url.trim()?{url:a.url,label:m(a.label)?a.label:void 0}:null}function jo(a){const e=m(a.snapshot_url)?a.snapshot_url:void 0;if(Array.isArray(a.streams)){const r=[];for(const o of a.streams){const c=Ho(o);c&&r.push(c)}return{streams:r,snapshot_url:e}}const t=[],s=m(a.main_stream_url)?a.main_stream_url:void 0;s&&t.push({url:s,label:m(a.main_stream_name)?a.main_stream_name:void 0});const i=m(a.sub_stream_url)?a.sub_stream_url:void 0;i&&t.push({url:i,label:m(a.sub_stream_name)?a.sub_stream_name:void 0});const n=m(a.third_stream_url)?a.third_stream_url:void 0;return n&&t.push({url:n,label:m(a.third_stream_name)?a.third_stream_name:void 0}),{streams:t,snapshot_url:e}}function Zo(a){if(a.length===0)return{};const e=oe(a),t={},s=e.find(o=>o.quality==="high"),i=e.find(o=>o.quality==="mid"),n=e.find(o=>o.quality==="low");s&&(t.high=s.id),i&&(t.mid=i.id),n&&(t.low=n.id);const r=s??i??n??e[0];return r&&(t.high||(t.high=r.id),t.mid||(t.mid=r.id),t.low||(t.low=r.id)),t}const qo={streaming:!0,notifications:!0,objectDetection:!1,remoteAccess:!0,agentCluster:!1,smartHome:!0,recordings:!0,backup:!0,repl:!0},Vo=["face","plate"],Go=["face","plate","clip","custom"],Yo={cleanupIntervalMs:3600*1e3,detectionEventsDays:30,audioLevelsDays:7,snapshotsDays:14};var ce=(a=>(a.Addon="addon",a.Core="core",a.Device="device",a.Provider="provider",a.System="system",a))(ce||{});const de="camstack/camstack-models",Jo=`https://huggingface.co/${de}/resolve/main`,Qo={"features.streaming":!0,"features.notifications":!0,"features.objectDetection":!1,"features.remoteAccess":!0,"features.agentCluster":!1,"features.smartHome":!0,"features.recordings":!0,"features.backup":!0,"features.repl":!0,"retention.detectionEventsDays":30,"retention.audioLevelsDays":7,"logging.level":"info","logging.retentionDays":30,"eventBus.ringBufferSize":1e4,"storage.provider":"sqlite-storage","storage.locations":{data:"camstack-data/data",media:"camstack-data/media",recordings:"camstack-data/recordings",cache:"/tmp/camstack-cache",logs:"camstack-data/logs",models:"camstack-data/models"},providers:[],"recording.segmentDurationSeconds":4,"recording.defaultRetentionDays":30,"ffmpeg.binaryPath":"ffmpeg","ffmpeg.hwAccel":"auto","ffmpeg.threadCount":0,"auth.tokenExpiry":"24h"};function T(a){return JSON.parse(a)}function le(a){return a===null||typeof a!="object"||Array.isArray(a)?null:{...a}}function Xo(a){return Array.isArray(a)?a:[]}function ec(a,e=""){return typeof a=="string"?a:e}function tc(a,e=0){return typeof a=="number"?a:e}function ac(a,e=!1){return typeof a=="boolean"?a:e}function sc(a){try{return le(T(a))}catch{return null}}function ic(a){try{const e=T(a);return Array.isArray(e)?e:null}catch{return null}}function nc(a,e){return`https://huggingface.co/${a}/resolve/main/${e}`}function rc(a,e){if(a.length!==e.length)return 0;let t=0,s=0,i=0;for(let r=0;r<a.length;r++)t+=a[r]*e[r],s+=a[r]*a[r],i+=e[r]*e[r];const n=Math.sqrt(s)*Math.sqrt(i);return n===0?0:t/n}class oc{constructor(e,t){this.elementId=e,this.getBackend=typeof t=="function"?t:()=>t}cache={};listeners=new Set;loaded=!1;getBackend;async ensureLoaded(){if(this.loaded)return;const e=this.getBackend();if(!e)throw new Error(`ElementConfigStore(${this.elementId}): settings backend not available`);const t=await e.query({collection:"config",filter:{where:{id:this.elementId},limit:1}});t.length>0&&(this.cache=t[0].data??{}),this.loaded=!0}getAll(){return{...this.cache}}get(e){const t=e.split(".");let s=this.cache;for(const i of t){if(s===null||typeof s!="object"||Array.isArray(s))return;s=Reflect.get(s,i)}return s}async set(e,t){await this.ensureLoaded(),cc(this.cache,e,t),await this.persist(),this.notifyListeners()}async setAll(e){await this.ensureLoaded(),this.cache={...e},await this.persist(),this.notifyListeners()}onChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async load(){await this.ensureLoaded()}async loadDefaults(e){await this.ensureLoaded(),Object.keys(this.cache).length===0&&(this.cache={...e},await this.persist())}async persist(){const e=this.getBackend();if(!e)throw new Error(`ElementConfigStore(${this.elementId}): settings backend not available — cannot persist config`);await e.set({collection:"config",key:this.elementId,value:this.cache})}notifyListeners(){const e=this.getAll();for(const t of this.listeners)try{t(e)}catch{}}}function cc(a,e,t){const s=e.split(".");let i=a;for(let n=0;n<s.length-1;n++){const r=s[n],o=i[r];if(o===null||typeof o!="object"||Array.isArray(o)){const c={};i[r]=c,i=c}else i=o}i[s[s.length-1]]=t}const x={cpu:"onnx",coreml:"onnx",cuda:"onnx",tensorrt:"onnx","onnx-py":"onnx",pytorch:"pt",openvino:"openvino"},ue={onnx:"onnx",coreml:"coreml",openvino:"openvino",tflite:"tflite",pytorch:"pt"},he={coreml:"coreml_inference.py",pytorch:"pytorch_inference.py",openvino:"openvino_inference.py"};function me(a,e){return a==="node"?"onnx":{coreml:"coreml",openvino:"openvino",pytorch:"pytorch","onnx-py":"onnx",cpu:"onnx"}[e]??e}function dc(a,e){return a==="node"?x[e]??"onnx":{coreml:"coreml",openvino:"openvino",pytorch:"pt","onnx-py":"onnx",cpu:"onnx"}[e]??"onnx"}function lc(a,e){return!a||a==="auto"?"auto":me(a,e??"cpu")}function uc(a){return x[a]??"onnx"}function hc(a){return ue[a]}function mc(a){return he[a]}function pc(a){return a==="coreml"||a==="pytorch"||a==="openvino"}function pe(a){return a instanceof Error?a.message:typeof a=="string"?a:String(a)}async function fc(a,e){const t=performance.now();try{return{output:e!==void 0?await gc(a(),e):await a(),durationMs:M(performance.now()-t),ok:!0}}catch(s){return{output:void 0,durationMs:M(performance.now()-t),ok:!1,error:pe(s)}}}function M(a){return Math.round(a*100)/100}function gc(a,e){return new Promise((t,s)=>{const i=setTimeout(()=>s(new Error(`Inference timeout after ${e}ms`)),e);a.then(n=>{clearTimeout(i),t(n)}).catch(n=>{clearTimeout(i),s(n)})})}const Sc=[{id:"person",name:"Person"},{id:"bicycle",name:"Bicycle"},{id:"car",name:"Car"},{id:"motorcycle",name:"Motorcycle"},{id:"airplane",name:"Airplane"},{id:"bus",name:"Bus"},{id:"train",name:"Train"},{id:"truck",name:"Truck"},{id:"boat",name:"Boat"},{id:"traffic light",name:"Traffic Light"},{id:"fire hydrant",name:"Fire Hydrant"},{id:"stop sign",name:"Stop Sign"},{id:"parking meter",name:"Parking Meter"},{id:"bench",name:"Bench"},{id:"bird",name:"Bird"},{id:"cat",name:"Cat"},{id:"dog",name:"Dog"},{id:"horse",name:"Horse"},{id:"sheep",name:"Sheep"},{id:"cow",name:"Cow"},{id:"elephant",name:"Elephant"},{id:"bear",name:"Bear"},{id:"zebra",name:"Zebra"},{id:"giraffe",name:"Giraffe"},{id:"backpack",name:"Backpack"},{id:"umbrella",name:"Umbrella"},{id:"handbag",name:"Handbag"},{id:"tie",name:"Tie"},{id:"suitcase",name:"Suitcase"},{id:"frisbee",name:"Frisbee"},{id:"skis",name:"Skis"},{id:"snowboard",name:"Snowboard"},{id:"sports ball",name:"Sports Ball"},{id:"kite",name:"Kite"},{id:"baseball bat",name:"Baseball Bat"},{id:"baseball glove",name:"Baseball Glove"},{id:"skateboard",name:"Skateboard"},{id:"surfboard",name:"Surfboard"},{id:"tennis racket",name:"Tennis Racket"},{id:"bottle",name:"Bottle"},{id:"wine glass",name:"Wine Glass"},{id:"cup",name:"Cup"},{id:"fork",name:"Fork"},{id:"knife",name:"Knife"},{id:"spoon",name:"Spoon"},{id:"bowl",name:"Bowl"},{id:"banana",name:"Banana"},{id:"apple",name:"Apple"},{id:"sandwich",name:"Sandwich"},{id:"orange",name:"Orange"},{id:"broccoli",name:"Broccoli"},{id:"carrot",name:"Carrot"},{id:"hot dog",name:"Hot Dog"},{id:"pizza",name:"Pizza"},{id:"donut",name:"Donut"},{id:"cake",name:"Cake"},{id:"chair",name:"Chair"},{id:"couch",name:"Couch"},{id:"potted plant",name:"Potted Plant"},{id:"bed",name:"Bed"},{id:"dining table",name:"Dining Table"},{id:"toilet",name:"Toilet"},{id:"tv",name:"TV"},{id:"laptop",name:"Laptop"},{id:"mouse",name:"Mouse"},{id:"remote",name:"Remote"},{id:"keyboard",name:"Keyboard"},{id:"cell phone",name:"Cell Phone"},{id:"microwave",name:"Microwave"},{id:"oven",name:"Oven"},{id:"toaster",name:"Toaster"},{id:"sink",name:"Sink"},{id:"refrigerator",name:"Refrigerator"},{id:"book",name:"Book"},{id:"clock",name:"Clock"},{id:"vase",name:"Vase"},{id:"scissors",name:"Scissors"},{id:"teddy bear",name:"Teddy Bear"},{id:"hair drier",name:"Hair Drier"},{id:"toothbrush",name:"Toothbrush"}],bc=[{id:"person",name:"Person"},{id:"vehicle",name:"Vehicle"},{id:"animal",name:"Animal"}],yc={mapping:{person:"person",bicycle:"vehicle",car:"vehicle",motorcycle:"vehicle",airplane:"vehicle",bus:"vehicle",train:"vehicle",truck:"vehicle",boat:"vehicle",bird:"animal",cat:"animal",dog:"animal",horse:"animal",sheep:"animal",cow:"animal",elephant:"animal",bear:"animal",zebra:"animal",giraffe:"animal"},preserveOriginal:!1},vc={camera:{type:"camera",label:"Camera",icon:"camera"}};class g{schema;data;persistFn;constructor(e,t,s){this.schema=e,this.data=t,this.persistFn=s}static fromSchema(e,t,s={},i){const n=e.safeParse(s);if(n.success)return new g(e,n.data,t);const r=new Set;for(const d of n.error.issues){const u=d.path[0];typeof u=="string"&&r.add(u)}const o={...s};for(const d of r)delete o[d];const c=e.safeParse(o);if(i?.({droppedKeys:[...r],issues:n.error.issues}),c.success)return t(c.data).catch(()=>{}),new g(e,c.data,t);const l=e.parse({});return new g(e,l,t)}get values(){return this.data}get(e){return this.data[e]}async set(e,t){const s=this.schema.parse({...this.data,[e]:t});this.data=s,await this.persistFn(this.data)}async setAll(e){const t=this.schema.parse({...this.data,...e});this.data=t,await this.persistFn(this.data)}async deleteKey(e){const{[e]:t,...s}=this.data,i=this.schema.parse(s);this.data=i,await this.persistFn(this.data)}entries(){const e=this.schema.shape;return Object.entries(e).map(([t,s])=>({key:t,schema:s,value:this.data[t],description:s.description}))}}class I{writer;pendingWrites=new Set;slices;schemas=new Map;listeners=new Set;capListeners=new Map;constructor(e,t){this.writer=t,this.slices=new Map;for(const[s,i]of Object.entries(e))i&&typeof i=="object"&&!Array.isArray(i)&&this.slices.set(s,{...i})}static fromInitial(e,t){return new I(e,t)}installCapSchema(e,t){const s=this.schemas.get(e);if(s){if(s!==t)throw new Error(`[DeviceRuntimeState] capability "${e}" registered a different runtime-state schema; each cap must declare ONE shape across every provider`);return}this.schemas.set(e,t);const i=this.slices.get(e);if(i){const n=t.safeParse(i);n.success?this.slices.set(e,n.data):this.slices.delete(e)}}getCapState(e){const t=this.slices.get(e);if(t)return Object.freeze({...t})}getCapField(e,t){return this.slices.get(e)?.[t]}setCapState(e,t){this.applyCapWrite(e,t,!1)}patchCapState(e,t){this.applyCapWrite(e,t,!0)}applyCapWrite(e,t,s){const i=this.schemas.get(e);if(!i)throw new Error(`[DeviceRuntimeState] no schema registered for cap "${e}" — did the device register it via ctx.registerNativeCap before writing?`);const n=this.slices.get(e)??{},r=s?{...n,...t}:{...t},o=i.parse(r);if(Cc(n,o))return;this.slices.set(e,o),this.fireListeners([e]);const c=this.writer(e,{...o}).catch(()=>{});this.pendingWrites.add(c),c.finally(()=>{this.pendingWrites.delete(c)})}fireListeners(e){const t=this.snapshot();for(const s of this.listeners)try{s(e,t)}catch{}for(const s of e){const i=this.capListeners.get(s);if(!i)continue;const n=this.getCapState(s);for(const r of i)try{r(n)}catch{}}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}subscribeCap(e,t){let s=this.capListeners.get(e);s||(s=new Set,this.capListeners.set(e,s));const i=n=>{t(n)};return s.add(i),()=>{const n=this.capListeners.get(e);n&&(n.delete(i),n.size===0&&this.capListeners.delete(e))}}snapshot(){const e={};for(const[t,s]of this.slices)e[t]=Object.freeze({...s});return Object.freeze(e)}async flush(){if(this.pendingWrites.size===0)return;const e=[...this.pendingWrites];await Promise.allSettled(e)}}function Cc(a,e){const t=Object.keys(a),s=Object.keys(e);if(t.length!==s.length)return!1;for(const i of t)if(a[i]!==e[i])return!1;return!0}const k="lastFetchedAt";function wc(a){const{runtimeState:e,cap:t,ownDeviceId:s,refresh:i,staleMs:n,empty:r}=a,o=async()=>{const d=e.getCapState(t.name),u=typeof d?.[k]=="number"?d[k]:0;(!d||Date.now()-u>n)&&await i()},c=()=>{const d=e.getCapState(t.name);if(!d)return r();const{[k]:u,...h}=d;return h};return{ensureFresh:o,getStatus:async({deviceId:d})=>{if(d!==s)throw new Error(`${t.name}: deviceId mismatch, expected ${s}, got ${d}`);return await o(),c()}}}const Ic={audioMetrics:J,battery:Y,brightness:G,cameraStreams:V,deviceDiscovery:q,deviceStatus:R,doorbell:Z,featureProbe:D,motion:j,motionTrigger:H,motionZones:W,ptzAutotrack:K,streamParams:z,switch:U,zoneAnalytics:$,zoneRules:F,zones:L};class Ac{id;stableId;type;name;parentDeviceId;role;get online(){return this.runtimeState.getCapState("device-status")?.online??!1}set online(e){this.markOnline(e)}get state(){if(!this._stateProxyCache){const e={},t={get:(s,i)=>{const n=i;if(n in e)return e[n];const r=Ic[n];if(!r)return;const o=this.sliceProxy(r);return e[n]=o,o}};this._stateProxyCache=new Proxy(e,t)}return this._stateProxyCache}_stateProxyCache;config;runtimeState;ctx;location;disabled;constructor(e,t,s){if(this.ctx=e,this.id=e.id,this.stableId=e.stableId,this.type=s.type,!e.deviceMeta)throw new Error(`BaseDevice constructor: ctx.deviceMeta is required (id=${e.id} stableId=${e.stableId})`);this.name=e.deviceMeta.name,this.location=e.deviceMeta.location,this.disabled=e.deviceMeta.disabled,this.role=s.role,this.parentDeviceId=e.parentDeviceId;const i=e.persistedConfig??{};this.config=g.fromSchema(t,d=>e.persistConfig(d),i,({droppedKeys:d,issues:u})=>{e.logger.warn("Device config recovery: dropping invalid persisted fields",{tags:{deviceId:e.id,stableId:e.stableId},meta:{droppedKeys:[...d],firstIssue:u[0]?.message??null}})});let n=null;const r=async(d,u)=>{n||(n=e.fetchDevice(e.id)),await(await n).deviceState.setCapSlice({capName:d,slice:u})},o=e.initialRuntimeState??{};this.runtimeState=I.fromInitial(o,r),e.bindRuntimeState?.(this.runtimeState),e.registerNativeCap?.(R,{});const c={online:!1,lastChangedAt:Date.now()};this.runtimeState.setCapState("device-status",c),e.registerNativeCap?.(D,{});const l={flags:{},deviceType:null,model:null,channelCount:null,lastProbedAt:0,lastFetchedAt:0};this.runtimeState.setCapState("feature-probe",l)}async removeDevice(){}markOnline(e){if(this.online===e)return;const t={online:e,lastChangedAt:Date.now()};this.runtimeState.setCapState("device-status",t)}async refreshFeatures(){const t=this.ctx.api?.deviceManager?.registerDevice;if(t)try{await t.mutate({addonId:this.ctx.deviceMeta.addonId,stableId:this.stableId,id:this.id,type:this.type,name:this.name,parentDeviceId:this.parentDeviceId,features:[...this.features],config:{}})}catch{}}getCapSlice(e){return this.runtimeState.getCapState(e.name)??null}setCapSlice(e,t){this.runtimeState.setCapState(e.name,t)}sliceProxy(e){const t={},s={get:(i,n)=>this.runtimeState.getCapState(e.name)?.[n],set:(i,n,r)=>(this.runtimeState.patchCapState(e.name,{[n]:r}),!0),has:(i,n)=>{const r=this.runtimeState.getCapState(e.name);return r?n in r:!1},ownKeys:()=>{const i=this.runtimeState.getCapState(e.name);return i?Object.keys(i):[]},getOwnPropertyDescriptor:(i,n)=>{const r=this.runtimeState.getCapState(e.name);if(!(!r||!(n in r)))return{configurable:!0,enumerable:!0,value:r[n]}}};return new Proxy(t,s)}getSettingsUISchema(){return{sections:[]}}async applySettingsPatch(e){await this.config.setAll(e)}async onProbe(){}async onActivate(){}async reprobe(){this._kernelReprobe?await this._kernelReprobe():await this.onProbe()}_kernelReprobe;getAccessoryChildren(){return[]}getProbeFlags(){return this.runtimeState.getCapState("feature-probe")?.flags??{}}hasProbed(){return(this.runtimeState.getCapState("feature-probe")?.lastProbedAt??0)>0}}function fe(a,e){const t={};for(const s of a.config.entries())t[s.key]=s.value;return{id:a.id,stableId:a.stableId,addonId:e,type:String(a.type),name:a.name,parentDeviceId:a.parentDeviceId,online:a.online,features:[...a.features],config:t}}class Ec extends ae{async onInitialize(){return this.ctx.logger.info(`${this.providerName} Provider initialized`),[{capability:Q,provider:this}]}async onShutdown(){const e=await this.ctx.kernel.devices?.getAll()??[];for(const t of e)try{await this.ctx.kernel.devices?.decommission(t.id)}catch(s){this.ctx.logger.warn(`${this.providerName}: decommission failed`,{tags:{deviceId:t.id,stableId:t.stableId},meta:{error:s instanceof Error?s.message:String(s)}})}this.ctx.logger.info(`${this.providerName} Provider shut down`,{meta:{decommissionedCount:e.length}})}async start(){}async stop(){}async getStatus(){return{connected:!0,deviceCount:(await this.ctx.kernel.devices?.getAll()??[]).length}}async getDevices(){return(await this.ctx.kernel.devices?.getAll()??[]).map(t=>({id:t.stableId,name:t.name,type:String(t.type)}))}async supportsDiscovery(){return!1}async discoverDevices(){return[]}async adoptDiscoveredDevice(e){throw new Error(`${this.providerName} provider does not support discovery-based adoption`)}async supportsManualCreation(){return!0}async getChildCreationSchema(e){return this.onGetCreationSchema(e.type)}async createDevice(e){const t=await this.onCreateDevice(e.type,e.config),s=this.deviceClasses[t.meta.type];if(!s)throw new Error(`${this.providerName} provider: no device class registered for type "${t.meta.type}" — add it to the deviceClasses map`);const i=this.generateStableId(t.meta.type,t.config),n=await this.ctx.kernel.devices.create(i,s,t.config,null,t.meta);if(t.onAfterCreate)try{await t.onAfterCreate(n)}catch(r){this.ctx.logger.warn("createDevice: onAfterCreate hook threw — device is already registered",{tags:{deviceId:n.id,stableId:i},meta:{error:r instanceof Error?r.message:String(r)}})}return this.toSummary(n)}generateStableId(e,t){return`${this.addonId}-${Date.now()}`}async testCreationField(e){return{status:"ok",labels:["probe not implemented"]}}async restoreDevices(e){await this.onRestoreDevices(e),e.length>0&&this.ctx.logger.info(`Restored ${e.length} ${this.providerName} device(s)`)}async onRestoreDevices(e){const t=new Set;for(const i of e){if(i.parentDeviceId!==null)continue;const n=this.deviceClasses[i.type];if(!n){this.ctx.logger.warn("No device class registered for restored type — skipping",{tags:{stableId:i.stableId},meta:{type:i.type}});continue}try{await this.ctx.kernel.devices.create(i.stableId,n,{}),t.add(i.id)}catch(r){this.ctx.logger.warn("Failed to restore device",{tags:{stableId:i.stableId},meta:{type:i.type,error:r instanceof Error?r.message:String(r)}})}}const s=e.filter(i=>i.parentDeviceId!==null);for(const i of s){const n=this.deviceClasses[i.type];if(n&&i.parentDeviceId!==null&&t.has(i.parentDeviceId))try{await this.ctx.kernel.devices.create(i.stableId,n,{},i.parentDeviceId),t.add(i.id)}catch(r){this.ctx.logger.warn("Failed to restore hub-adopted child",{tags:{stableId:i.stableId,parentDeviceId:i.parentDeviceId},meta:{type:i.type,error:r instanceof Error?r.message:String(r)}})}}}toSummary(e){return fe(e,this.addonId)}}function b(a){return a.def}function _c(a,e="Configuration",t="main"){const s=a.map(i=>kc(i.key,i.schema,i.description));return{sections:[{id:t,title:e,fields:s}]}}function kc(a,e,t){const s=w(e),i=Tc(e),n=t??ge(a),r={key:a,label:n,description:t,default:i};return s instanceof go?Pc(a,r):s instanceof So?Dc(s,r):s instanceof bo?{...r,type:"boolean"}:s instanceof yo?Nc(s,r):s instanceof vo||s instanceof Co?{...r,type:"textarea",rows:6,isJson:!0}:{...r,type:"text"}}function Pc(a,e){const t=a.toLowerCase();return t.includes("password")||t.includes("secret")||t.includes("token")||t.includes("apikey")||t.includes("api_key")?{...e,type:"password",showToggle:!0}:{...e,type:"text"}}function Dc(a,e){const t=a,s=t.minValue,i=t.maxValue,n=s!=null&&isFinite(s)?s:void 0,r=i!=null&&isFinite(i)?i:void 0,o=Rc(a);return{...e,type:"number",...n!==void 0?{min:n}:{},...r!==void 0?{max:r}:{},...o!==void 0?{step:o}:{}}}function Rc(a){const t=b(a).checks??[];for(const s of t)if(s._zod?.def?.check==="multiple_of"&&s._zod.def.value!==void 0)return s._zod.def.value}function Nc(a,e){const t=a.options.map(i=>String(i));return{...e,type:"select",options:t.map(i=>({label:ge(i),value:i}))}}function w(a){return a instanceof X||a instanceof wo||a instanceof Io?w(b(a).innerType):a}function Tc(a){if(a instanceof X)return b(a).defaultValue}function ge(a){return a.replace(/([A-Z])/g," $1").replace(/[_-]/g," ").replace(/^\w/,e=>e.toUpperCase()).trim()}function xc(a,e,t,s,i){if(t.length===0||e.length===0)return{passed:a,excluded:[]};const n=t.filter(h=>h.enabled!==!1),r=n.filter(h=>h.mode==="include"),o=n.filter(h=>h.mode==="exclude"),c=r.length>0,l=new Map(e.map(h=>[h.id,h])),d=[],u=[];for(const h of a){const S=s(h),p=i?.(h),A=r.some(E=>B(E,S,p,l)),O=o.some(E=>B(E,S,p,l));c?A&&!O?d.push(h):u.push(h):O?u.push(h):d.push(h)}return{passed:d,excluded:u}}function B(a,e,t,s){if(a.classFilter&&a.classFilter.length>0&&t!==void 0&&!a.classFilter.includes(t))return!1;for(const i of a.zoneIds){const n=s.get(i);if(n&&Oc(e,n.polygon))return!0}return!1}function Oc(a,e){if(e.length<3)return!1;let t=!1;const{x:s,y:i}=a;for(let n=0,r=e.length-1;n<e.length;r=n++){const o=e[n],c=e[r];o.y>i!=c.y>i&&s<(c.x-o.x)*(i-o.y)/(c.y-o.y||Number.EPSILON)+o.x&&(t=!t)}return t}function Mc(a){return a}function Bc(a,e,t){return{input:a,output:e,kind:t?.kind??"query",auth:t?.auth??"protected",scope:t?.scope??{kind:"system"}}}const Se=[{profile:"main",prefix:"streamMain",label:"Main stream"},{profile:"sub",prefix:"streamSub",label:"Sub stream"},{profile:"ext",prefix:"streamExt",label:"Third stream"}];function Lc(a,e,t){const s=[];if(e.resolutions.length>0){const i=e.resolutions.map(r=>({value:`${String(r.width)}x${String(r.height)}`,label:`${String(r.width)}×${String(r.height)}`})),n=t?`${String(t.width)}x${String(t.height)}`:void 0;n&&!i.some(r=>r.value===n)&&i.unshift({value:n,label:`${n.replace("x","×")} (current)`}),s.push({type:"select",key:`${a.prefix}_resolution`,label:"Resolution",options:i,default:n??i[0]?.value??""})}if(e.codecs.length>0&&s.push({type:"select",key:`${a.prefix}_codec`,label:"Codec",options:e.codecs.map(i=>({value:i,label:i==="h264"?"H.264":"H.265"})),default:t?.codec??e.codecs[0]}),e.framerates.length>0){const i=e.framerates.map(r=>({value:String(r),label:`${String(r)} fps`})),n=t?.framerate;n!==void 0&&!e.framerates.includes(n)&&i.unshift({value:String(n),label:`${String(n)} fps (current)`}),s.push({type:"select",key:`${a.prefix}_framerate`,label:"Frame rate",options:i,default:n!==void 0?String(n):i[0]?.value??""})}if(e.bitrates.length>0){const i=e.bitrates.map(r=>({value:String(r),label:`${String(r)} kbps`})),n=t?.bitrate;n!==void 0&&!e.bitrates.includes(n)&&i.unshift({value:String(n),label:`${String(n)} kbps (current)`}),s.push({type:"select",key:`${a.prefix}_bitrate`,label:"Bitrate",options:i,default:n!==void 0?String(n):i[0]?.value??""})}else{const i=e.bitrateRange;s.push({type:"number",key:`${a.prefix}_bitrate`,label:"Bitrate",unit:"kbps",...i?{min:i[0],max:i[1]}:{},default:t?.bitrate??i?.[0]??0})}if(e.supportsBitrateMode&&s.push({type:"select",key:`${a.prefix}_bitrateMode`,label:"Bitrate mode",options:[{value:"vbr",label:"VBR (variable)"},{value:"cbr",label:"CBR (constant)"}],default:t?.bitrateMode??"vbr"}),e.supportsEncoderProfile&&s.push({type:"select",key:`${a.prefix}_encoderProfile`,label:"Encoder profile",options:[{value:"baseline",label:"Baseline"},{value:"main",label:"Main"},{value:"high",label:"High"}],default:t?.encoderProfile??"main"}),e.supportsGop){const i=e.gop;if(i){const n=[];for(let o=i.min;o<=i.max;o+=i.step)n.push({value:String(o),label:`${String(o)} s`});const r=t?.gop;r!==void 0&&!n.some(o=>o.value===String(r))&&n.unshift({value:String(r),label:`${String(r)} s (current)`}),s.push({type:"select",key:`${a.prefix}_gop`,label:"I-frame interval (GOP)",options:n,default:r!==void 0?String(r):n[0]?.value??""})}else s.push({type:"number",key:`${a.prefix}_gop`,label:"I-frame interval (GOP)",unit:"s",min:1,default:t?.gop??1})}return s.length===0?null:{id:`stream-${a.profile}`,tab:"streaming",title:a.label,description:"Encoder parameters pushed to the camera. Option lists are read live from the camera — fields the firmware doesn't expose are hidden.",columns:2,fields:s}}function Fc(a,e){const t=[];for(const s of Se){const i=a[s.profile];if(!i)continue;const n=Lc(s,i,e?.[s.profile]);n&&t.push(n)}return t.length===0?null:{sections:t}}function $c(a,e){const t={};let s=!1;const i=`${e}_resolution`;if(i in a&&typeof a[i]=="string"){const[u,h]=a[i].split("x").map(Number);Number.isFinite(u)&&Number.isFinite(h)&&(t.width=u,t.height=h,s=!0)}const n=`${e}_codec`;n in a&&(a[n]==="h264"||a[n]==="h265")&&(t.codec=a[n],s=!0);const r=`${e}_framerate`;if(r in a){const u=Number(a[r]);Number.isFinite(u)&&(t.framerate=u,s=!0)}const o=`${e}_bitrate`;if(o in a){const u=Number(a[o]);Number.isFinite(u)&&(t.bitrate=u,s=!0)}const c=`${e}_bitrateMode`;c in a&&(a[c]==="vbr"||a[c]==="cbr")&&(t.bitrateMode=a[c],s=!0);const l=`${e}_encoderProfile`;l in a&&(a[l]==="high"||a[l]==="main"||a[l]==="baseline")&&(t.encoderProfile=a[l],s=!0);const d=`${e}_gop`;if(d in a){const u=Number(a[d]);Number.isFinite(u)&&(t.gop=u,s=!0)}return s?t:null}const Uc=["accessories","battery","brightness","camera-credentials","device-discovery","device-export","device-status","doorbell","feature-probe","intercom","motion","motion-trigger","motion-zones","mqtt-broker","native-object-detection","osd","ptz","ptz-autotrack","snapshot","stream-params","switch"],zc=[{id:"camera-viewer",label:"Camera viewer",description:"Read-only over every device — live streams, recordings, motion events, battery state. Combine with `allowedDevices` to restrict to specific cameras.",rows:[{type:"category",target:"device",access:["view"]}]},{id:"camera-operator",label:"Camera operator",description:"Everything `camera-viewer` does plus PTZ control, intercom, snapshots and recording start/stop. Cannot delete devices or recordings.",rows:[{type:"category",target:"device",access:["view","create"]}]},{id:"cli-deployer",label:"CLI deployer",description:"Push addons to the hub and tail their logs. Used by the `camstack` CLI on dev machines. No delete access — a stolen token cannot uninstall.",rows:[{type:"capability",target:"addons",access:["view","create"]}]},{id:"event-listener",label:"Event listener",description:"Subscribe to motion / audio events. Used by webhook bridges and Home Assistant integrations.",rows:[{type:"capability",target:"events",access:["view"]},{type:"capability",target:"motion-detection",access:["view"]},{type:"capability",target:"audio-analysis",access:["view"]}]}],be=Object.freeze({"device-export":"device-export","mesh-network":"mesh","mqtt-broker":"broker","network-access":"ingress","smtp-provider":"email"}),Kc=["device-export","mesh-network","mqtt-broker","network-access","smtp-provider"];function Wc(a){const e=[];for(const[t,s]of Object.entries(be))s===a&&e.push(t);return e}function Hc(a){try{const e=new URL(a);return!e.username&&!e.password?a:(e.username="",e.password="",e.toString())}catch{return a}}class jc{constructor(e){this.capacity=e,this.items=Array.from({length:e})}items;head=0;tail=0;count=0;get size(){return this.count}push(e){this.items[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.count<this.capacity?this.count++:this.head=(this.head+1)%this.capacity}drain(e){const t=[],s=Math.min(e,this.count);for(let i=0;i<s;i++)t.push(this.items[this.head]),this.items[this.head]=void 0,this.head=(this.head+1)%this.capacity;return this.count-=s,t}}function Zc(a,e,t){const s={};for(const i of Object.keys(t))s[i]=n=>a.addons.custom.mutate({addonId:e,action:i,input:n});return s}const Yc=Object.freeze(Object.defineProperty({__proto__:null,ACCESSORY_LABEL:ye,ALL_CAPABILITY_DEFINITIONS:co,APPLE_SA_TO_MACRO:ve,AUDIO_BACKEND_CHOICES:Ce,AUDIO_MACRO_LABELS:we,AccessoriesStatusSchema:Ie,AccessoryKind:Ae,AddBrokerInputSchema:Ee,AddonAutoUpdateSchema:_e,AddonListItemSchema:ke,AddonPageDeclarationSchema:Pe,AddonPageInfoSchema:De,AgentLoadSummarySchema:Re,AlertSchema:Ne,AlertSeveritySchema:Te,AlertSourceSchema:xe,AlertStatusSchema:Oe,ApiKeyRecordSchema:Me,ApiKeySummarySchema:Be,ArchiveEntrySchema:Le,ArchiveManifestSchema:Fe,AudioAnalysisResultSchema:$e,AudioAnalysisSettingsSchema:Ue,AudioChunkInputSchema:ze,AudioClassSummarySchema:Ke,AudioClassificationLabelSchema:We,AudioClassificationResultSchema:He,AudioCodecInfoSchema:je,AudioDecodeSessionConfigSchema:Ze,AudioEncodeSessionConfigSchema:qe,AudioEncodedChunkSchema:Ve,AudioEventSchema:Ge,AudioLevelSchema:Ye,AudioMetricsHistoryPointSchema:Je,AudioMetricsHistorySchema:Qe,AudioMetricsSnapshotSchema:Xe,AudioPcmChunkSchema:et,AuthResultSchema:tt,AutoUpdateSettingsSchema:at,AvailableIntegrationTypeSchema:st,BACKEND_TO_FORMAT:x,BATTERY_DEVICE_PROFILE:it,BackupDestinationInfoSchema:nt,BackupEntrySchema:rt,BaseAddon:ae,BaseDevice:Ac,BaseDeviceProvider:Ec,BatteryStatusSchema:ot,BoundingBoxSchema:ct,BrightnessStatusSchema:dt,BrokerAudioClientSchema:lt,BrokerClientsSchema:ut,BrokerConnectionDetailsSchema:ht,BrokerDecodedClientSchema:mt,BrokerInfoSchema:pt,BrokerRtspClientSchema:ft,BrokerStatsSchema:gt,BrokerStatusSchema:St,CAM_PROFILE_ORDER:bt,CAPABILITY_NAMES:lo,CAPABILITY_ROUTER_KEYS:uo,CAP_NAMES_WITH_STATUS:Uc,CAP_PROVIDER_KIND_MAP:be,COCO_80_LABELS:Sc,COCO_TO_MACRO:yc,CamProfileSchema:yt,CamStreamKindSchema:vt,CamStreamResolutionSchema:Ct,CameraCredentialsSchema:wt,CameraCredentialsStatusSchema:It,CameraMetricsSchema:At,CameraMetricsWithDeviceIdSchema:Et,CameraStreamSchema:_t,CapScopeSchema:kt,CapabilityBindingsSchema:Pt,ChargingStatus:Dt,ClientNetworkStatsSchema:Rt,ClusterAddonNodeDeploymentSchema:Nt,ClusterAddonStatusEntrySchema:Tt,CollectionColumnSchema:xt,CollectionIndexSchema:Ot,ConfigEntrySchema:Mt,ConfigSectionWithValuesSchema:Bt,ConfigTabDeclarationSchema:Lt,CreateApiKeyInputSchema:Ft,CreateApiKeyResultSchema:$t,CreateIntegrationInputSchema:Ut,CreateScopedTokenInputSchema:zt,CreateScopedTokenResultSchema:Kt,CreateUserInputSchema:Wt,CustomActionInputSchema:Ht,DEFAULT_ADDON_PLACEMENT:ee,DEFAULT_AUDIO_ANALYZER_CONFIG:jt,DEFAULT_DECODER_HWACCEL_CONFIG:Zt,DEFAULT_FEATURES:qo,DEFAULT_LOCATION_SUBDIRS:$o,DEFAULT_RETENTION:Yo,DEVICE_CAP_NAMES:ho,DEVICE_PROFILES:qt,DEVICE_SETTINGS_CONTRIBUTION_METHODS:Vt,DEVICE_STATUS_METHOD:Gt,DEVICE_TYPE_INFO:vc,DecodedAudioChunkSchema:Yt,DecodedFrameSchema:Jt,DecoderAssignmentSchema:Qt,DecoderSessionConfigSchema:Xt,DecoderStatsSchema:ea,DeleteIntegrationResultSchema:ta,DetectorOutputSchema:aa,DeviceConfig:g,DeviceDiscoveryStatusSchema:sa,DeviceExportExposeInputSchema:ia,DeviceExportStatusSchema:na,DeviceExportUnexposeInputSchema:ra,DeviceFeature:oa,DeviceInfoSchema:ca,DeviceNetworkStatsSchema:da,DeviceRole:la,DeviceRuntimeState:I,DeviceStatusSchema:ua,DeviceType:ha,DiscoveredChildDeviceSchema:ma,DiscoveredChildStatusSchema:pa,DiscoveredDeviceSchema:fa,DisposerChain:Ao,DoorbellPressEventSchema:ga,DoorbellStatusSchema:Sa,ElementConfigStore:oc,EmbeddingInfoSchema:ba,EmbeddingResultSchema:ya,EncodedPacketSchema:va,EnrichedWidgetMetadataSchema:Ca,EventCategory:v,EventItemSchema:wa,EventKindSchema:Ia,EventSourceType:ce,ExportSetupFieldSchema:Aa,ExportSetupSchema:Ea,ExposedDeviceSchema:_a,ExposedResourceSchema:ka,FeatureManifestSchema:Pa,FeatureProbeStatusSchema:Da,FrameHandleFormatSchema:Ra,FrameHandleSchema:Na,FrameInputSchema:Ta,GetStreamWithCodecInputSchema:xa,GlobalMetricsSchema:Oa,HF_BASE_URL:Jo,HF_REPO:de,HWACCEL_OPTIONS:Ma,HealthStatusSchema:Ba,HistoryPointSchema:La,HistoryResolutionEnum:Fa,InstalledPackageSchema:$a,IntegrationLiteSchema:Ua,IntegrationWithStateSchema:za,IntercomAbilitySchema:Ka,IntercomStatusSchema:Wa,KNOWN_CAP_NAMES:mo,LocationStatSchema:Ha,LogEntrySchema:ja,LogLevelSchema:Za,LogStreamEntrySchema:qa,MACRO_LABELS:bc,METHOD_ACCESS_MAP:po,MODEL_FORMATS:Va,MediaFileSchema:Ga,MeshPeerSchema:Ya,MeshStatusSchema:Ja,MethodAccessSchema:Qa,MotionAnalysisResultSchema:Xa,MotionEventSchema:es,MotionOnMotionChangedDataSchema:ts,MotionRegionSchema:as,MotionSourceEnum:ss,MotionSourcesSchema:is,MotionStatusSchema:ns,MotionTriggerRuntimeStateSchema:rs,MotionTriggerStatusSchema:os,MotionZoneOptionsSchema:cs,MotionZonePatchSchema:ds,MotionZoneStatusSchema:ls,MqttBrokerStatusSchema:us,NativeDetectionSchema:hs,NativeObjectClassEnum:ms,NativeObjectDetectionStatusSchema:ps,NetworkAccessStatusSchema:fs,NetworkAddressSchema:gs,NetworkEndpointSchema:Ss,NotificationHistoryEntrySchema:bs,NotificationRuleSchema:ys,NotificationSchema:vs,OauthIntegrationDescriptorSchema:Cs,ObjectEventSchema:ws,OrchestratorMetricsSchema:Is,OsdOverlayKindEnum:As,OsdOverlayPatchSchema:Es,OsdOverlaySchema:_s,OsdPositionEnum:ks,OsdStatusSchema:Ps,PIPELINE_FLOW_CAPABILITY_NAMES:Ds,PIPELINE_OWNER_CAPABILITY_NAMES:Rs,PROVIDER_KIND_CAP_NAMES:Kc,PYTHON_SCRIPT:he,PackageUpdateSchema:Ns,PackageVersionInfoSchema:Ts,PasskeySummarySchema:xs,PcmSampleFormatSchema:Os,PerScopeBreakdownSchema:Ms,PipelineAssignmentSchema:Bs,PipelineDefaultStepSchema:Ls,PipelineEngineChoiceSchema:Fs,PipelineRunResultBridge:$s,PipelineStepInputSchema:Us,PlaceholderReasonSchema:zs,PolygonPointSchema:Ks,ProfileSlotSchema:Ws,ProfileSlotStatusSchema:Hs,ProviderStatusSchema:js,PtzAutotrackRuntimeStateSchema:Zs,PtzAutotrackSettingsSchema:qs,PtzAutotrackStatusSchema:Vs,PtzAutotrackTargetOptionSchema:Gs,PtzMoveCommandSchema:Ys,PtzPositionSchema:Js,PtzPresetSchema:Qs,PtzStatusSchema:Xs,QueryFilterSchema:ei,RECOGNITION_TYPES:Go,RUNTIME_DEFAULTS:Qo,RUNTIME_TO_FORMAT:ue,ReadinessRegistry:Mo,ReadinessTimeoutError:ie,RegisteredStreamSchema:ti,ReportMotionInputSchema:ai,RingBuffer:jc,RtpSourceSchema:si,RtspRestreamEntrySchema:ii,RunnerCameraConfigSchema:ni,RunnerCameraDeviceUIFields:ri,RunnerLocalLoadSchema:oi,RunnerLocalMetricsSchema:ci,SCOPE_PRESETS:zc,STORAGE_LOCATION_CARDINALITY:di,STORAGE_LOCATION_TYPES:Fo,STREAM_PROFILE_META:Se,STREAM_QUALITY_LABELS:ne,SUB_DETECTION_TYPES:Vo,SYSTEM_CAP_NAMES:fo,ScopedTokenSchema:li,ScopedTokenSummarySchema:ui,SearchResultSchema:hi,SegmentSchema:mi,SendEmailInputSchema:pi,SendEmailResultSchema:fi,SettingsPatchSchema:gi,SettingsRecordSchema:Si,SettingsSchemaWithValuesSchema:bi,SettingsUpdateResultSchema:yi,ShmRingStatsSchema:vi,SmtpStatusSchema:Ci,SnapshotImageSchema:wi,SpatialDetectionSchema:Ii,SsoBridgeClaimsSchema:Ai,StartEmbeddedInputSchema:Ei,StorageAbortUploadInputSchema:_i,StorageBeginDownloadInputSchema:ki,StorageBeginDownloadResultSchema:Pi,StorageBeginUploadInputSchema:Di,StorageBeginUploadResultSchema:Ri,StorageEndDownloadInputSchema:Ni,StorageFinalizeUploadInputSchema:Ti,StorageLocationRefSchema:xi,StorageLocationSchema:Oi,StorageLocationTypeSchema:Mi,StorageProviderInfoSchema:Bi,StorageReadChunkInputSchema:Li,StorageTestLocationResultSchema:Fi,StorageWriteChunkInputSchema:$i,StreamFormatSchema:Ui,StreamInfoSchema:zi,StreamNetworkStatsSchema:Ki,StreamParamsOptionsSchema:Wi,StreamParamsStatusSchema:Hi,StreamProfileConfigSchema:ji,StreamProfileOptionsSchema:Zi,StreamProfilePatchSchema:qi,StreamProfileSchema:Vi,StreamSourceEntrySchema:Gi,StreamSourceSchema:Yi,SubscribeAudioChunksInputSchema:Ji,SubscribeAudioChunksResultSchema:Qi,SubscribeFramesInputSchema:Xi,SubscribeFramesResultSchema:en,SwitchStatusSchema:tn,SystemMetricsSchema:an,SystemMirror:sn,TestConnectionResultSchema:nn,ToastSchema:rn,TokenScopeSchema:on,TopologyNodeSchema:cn,TopologyProcessSchema:dn,TopologyServiceSchema:ln,TrackSchema:un,TrackStateSchema:hn,TrackedDetectionSchema:mn,TurnServerSchema:pn,UpdateIntegrationInputSchema:fn,UpdateUserInputSchema:gn,UserRecordSchema:Sn,UserSummarySchema:bn,WELL_KNOWN_TABS:yn,WELL_KNOWN_TAB_MAP:vn,WebrtcStreamChoiceSchema:Cn,WebrtcStreamTargetSchema:wn,WidgetHostEnum:In,WidgetMetadataSchema:An,WidgetRemoteSchema:En,WidgetSizeEnum:_n,YAMNET_TO_MACRO:kn,ZoneKindEnum:Pn,ZoneRuleModeEnum:Dn,ZoneRuleSchema:Rn,ZoneRuleStageEnum:Nn,ZoneRulesArraySchema:Tn,ZoneSchema:xn,ZoneScopeBreakdownSchema:On,accessoriesCapability:Mn,accessoryStableId:Bn,addonPagesCapability:Ln,addonPagesSourceCapability:Fn,addonRoutesCapability:$n,addonSettingsCapability:Un,addonWidgetsCapability:zn,addonWidgetsSourceCapability:Kn,addonsCapability:Wn,adminUiCapability:Hn,advancedNotifierCapability:jn,alertsCapability:Zn,asBoolean:ac,asJsonArray:Xo,asJsonObject:le,asNumber:tc,asString:ec,audioAnalysisCapability:qn,audioAnalyzerCapability:Vn,audioCodecCapability:Gn,audioMetricsCapability:J,authProviderCapability:Yn,autoAssignProfiles:Zo,backupCapability:Jn,batteryCapability:Y,bindAddonActions:Zc,brightnessCapability:G,buildAddonRouteProvider:No,buildStreamParamsConfigSchema:Fc,cameraCredentialsCapability:Qn,cameraStreamsCapability:V,classifyStream:zo,classifyStreams:oe,cosineSimilarity:rc,createDeviceProxy:Xn,createEvent:N,createLazyTrpcSource:er,createMirrorSource:tr,createRuntimeStateBridge:wc,createSliceHandle:ar,createSystemProxy:sr,customAction:Bc,decoderCapability:ir,defineCustomActions:Mc,detectionPipelineCapability:nr,deviceDiscoveryCapability:q,deviceExportCapability:rr,deviceManagerCapability:or,deviceMatchesProfile:cr,deviceOpsCapability:dr,deviceProviderCapability:Q,deviceStateCapability:lr,deviceStatusCapability:R,doorbellCapability:Z,embeddingEncoderCapability:ur,emitDownForOwnedCaps:Lo,emitReadiness:te,errMsg:pe,evaluateZoneRules:xc,event:hr,eventsCapability:mr,expandCapMethods:pr,featureProbeCapability:D,formatForBackend:uc,formatForRuntime:hc,getAudioMacroClassIds:fr,getCapsByProviderKind:Wc,hfModelUrl:nc,hydrateSchema:P,integrationsCapability:gr,intercomCapability:Sr,isAgentOnlyPlacement:_o,isDeployableToAgent:Eo,isDeviceConfigCap:br,isEvent:Ro,localNetworkCapability:yr,logDestinationCapability:vr,mapAudioLabelToMacro:Cr,maskUrlCredentials:Hc,meshNetworkCapability:wr,method:Ir,metricsProviderCapability:Ar,motionCapability:j,motionDetectionCapability:Er,motionTriggerCapability:H,motionZonesCapability:W,mqttBrokerCapability:_r,nativeObjectDetectionCapability:kr,networkAccessCapability:Pr,networkQualityCapability:Dr,nodesCapability:Rr,normalizeAddonInitResult:se,notificationOutputCapability:Nr,oauthIntegrationCapability:Tr,osdCapability:xr,parseCameraStreamConfig:jo,parseJsonArray:ic,parseJsonObject:sc,parseJsonUnknown:T,parseStreamParamsFormPatch:$c,pipelineAnalyticsCapability:Or,pipelineExecutorCapability:Mr,pipelineOrchestratorCapability:Br,pipelineRunnerCapability:Lr,platformProbeCapability:Fr,ptzAutotrackCapability:K,ptzCapability:$r,pythonScriptForBackend:mc,readinessKey:C,rebootCapability:Ur,recordingCapability:zr,recordingEngineCapability:Kr,requiresPython:pc,resolveAddonExecution:y,resolveAddonGroup:ko,resolveAddonPlacement:Do,resolveAddonRuntime:lc,resolveDetectionRuntime:me,resolveDeviceProfile:Wr,resolveModelFormat:dc,resolveRunnerId:Po,restreamerCapability:Hr,runInferenceStep:fc,scopeKey:f,settingsStoreCapability:jr,smtpProviderCapability:Zr,snapshotCapability:qr,snapshotProviderCapability:Vr,ssoBridgeCapability:Gr,storageCapability:Yr,storageProviderCapability:Jr,streamBrokerCapability:Qr,streamParamsCapability:z,streamPixels:re,streamQualityLabel:Uo,streamingEngineCapability:Xr,switchCapability:U,systemCapability:eo,toDeviceSummary:fe,toStreamSourceEntry:Ko,toastCapability:to,turnProviderCapability:ao,userManagementCapability:so,userPasskeysCapability:io,webrtcCapability:no,webrtcClientHintsSchema:ro,webrtcSessionCapability:oo,zodEntriesToConfigUI:_c,zoneAnalyticsCapability:$,zoneRulesCapability:F,zonesCapability:L},Symbol.toStringTag,{value:"Module"}));export{be as C,Fo as S,le as a,Yc as s};
1
+ import{h as P,z as B,i as $,j as F,s as U,k as z,p as K,m as W,l as H,n as j,o as D,q as Z,r as R,t as q,u as V,v as G,w as Y,x as J,y as Q,A as ye,B as ve,C as Ce,F as we,G as Ie,H as Ae,I as Ee,J as _e,K as ke,L as Pe,O as De,P as Re,Q as Ne,R as Te,T as xe,U as Oe,V as Me,X as Le,Y as Be,Z as $e,_ as Fe,$ as Ue,a0 as ze,a1 as Ke,a2 as We,a3 as He,a4 as je,a5 as Ze,a6 as qe,a7 as Ve,a8 as Ge,a9 as Ye,aa as Je,ab as Qe,ac as Xe,ad as et,ae as tt,af as at,ag as st,ah as it,ai as nt,aj as rt,ak as ot,al as ct,am as dt,an as lt,ao as ut,ap as ht,aq as mt,ar as pt,as as ft,at as gt,au as St,av as bt,aw as yt,ax as vt,ay as Ct,az as wt,aA as It,aB as At,aC as Et,aD as _t,aE as kt,aF as Pt,aG as Dt,aH as Rt,aI as Nt,aJ as Tt,aK as xt,aL as Ot,aM as Mt,aN as Lt,aO as Bt,aP as $t,aQ as Ft,aR as Ut,aS as zt,aT as Kt,aU as Wt,aV as Ht,aW as jt,aX as Zt,aY as qt,aZ as Vt,a_ as Gt,a$ as Yt,b0 as Jt,b1 as Qt,b2 as Xt,b3 as ea,b4 as ta,b5 as aa,b6 as sa,b7 as ia,D as na,b8 as ra,b as oa,b9 as ca,ba as da,bb as la,bc as ua,a as ha,bd as ma,be as pa,bf as fa,bg as ga,bh as Sa,bi as ba,bj as ya,bk as va,bl as Ca,bm as wa,bn as Ia,bo as Aa,bp as Ea,E as _a,bq as ka,br as Pa,bs as Da,bt as Ra,bu as Na,bv as Ta,bw as xa,bx as Oa,by as Ma,bz as La,bA as Ba,bB as $a,bC as Fa,bD as Ua,bE as za,bF as Ka,bG as Wa,bH as Ha,bI as ja,bJ as Za,bK as qa,M as Va,bL as Ga,bM as Ya,d as Ja,bN as Qa,bO as Xa,bP as es,bQ as ts,bR as as,bS as ss,bT as is,bU as ns,bV as rs,bW as os,bX as cs,bY as ds,bZ as ls,S as us,b_ as hs,b$ as ms,c0 as ps,N as fs,c1 as gs,c2 as Ss,c3 as bs,c4 as ys,c5 as vs,c6 as Cs,c7 as ws,c8 as Is,c9 as As,ca as Es,cb as _s,cc as ks,cd as Ps,ce as Ds,cf as Rs,cg as Ns,ch as Ts,ci as xs,cj as Os,ck as Ms,cl as Ls,cm as Bs,cn as $s,co as Fs,cp as Us,cq as zs,cr as Ks,cs as Ws,ct as Hs,cu as js,cv as Zs,cw as qs,cx as Vs,cy as Gs,cz as Ys,cA as Js,cB as Qs,cC as Xs,cD as ei,cE as ti,cF as ai,cG as si,cH as ii,cI as ni,cJ as ri,cK as oi,cL as ci,e as di,cM as li,cN as ui,cO as hi,cP as mi,cQ as pi,cR as fi,cS as gi,cT as Si,cU as bi,cV as yi,cW as vi,cX as Ci,cY as wi,cZ as Ii,c_ as Ai,c$ as Ei,d0 as _i,d1 as ki,d2 as Pi,d3 as Di,d4 as Ri,d5 as Ni,d6 as Ti,d7 as xi,d8 as Oi,d9 as Mi,da as Li,db as Bi,dc as $i,dd as Fi,de as Ui,df as zi,dg as Ki,dh as Wi,di as Hi,dj as ji,dk as Zi,dl as qi,dm as Vi,dn as Gi,dp as Yi,dq as Ji,dr as Qi,ds as Xi,dt as en,du as tn,dv as an,g as sn,dw as nn,dx as rn,dy as on,dz as cn,dA as dn,dB as ln,dC as un,dD as hn,dE as mn,dF as pn,dG as fn,dH as gn,dI as Sn,dJ as bn,dK as yn,W as vn,dL as Cn,dM as wn,dN as In,dO as An,dP as En,dQ as _n,dR as kn,dS as Pn,dT as Dn,dU as Rn,dV as Nn,dW as Tn,dX as xn,dY as On,dZ as Mn,d_ as Ln,d$ as Bn,e0 as $n,e1 as Fn,e2 as Un,e3 as zn,e4 as Kn,e5 as Wn,e6 as Hn,e7 as jn,e8 as Zn,e9 as qn,ea as Vn,eb as Gn,ec as Yn,ed as Jn,ee as Qn,c as Xn,ef as er,eg as tr,eh as ar,f as sr,ei as ir,ej as nr,ek as rr,el as or,em as cr,en as dr,eo as lr,ep as ur,eq as hr,er as mr,es as pr,et as fr,eu as gr,ev as Sr,ew as br,ex as yr,ey as vr,ez as Cr,eA as wr,eB as Ir,eC as Ar,eD as Er,eE as _r,eF as kr,eG as Pr,eH as Dr,eI as Rr,eJ as Nr,eK as Tr,eL as xr,eM as Or,eN as Mr,eO as Lr,eP as Br,eQ as $r,eR as Fr,eS as Ur,eT as zr,eU as Kr,eV as Wr,eW as Hr,eX as jr,eY as Zr,eZ as qr,e_ as Vr,e$ as Gr,f0 as Yr,f1 as Jr,f2 as Qr,f3 as Xr,f4 as eo,f5 as to,f6 as ao,f7 as so,f8 as io,f9 as no,fa as ro,fb as oo}from"./index-DAMgd5aW.js";import{E as v,A as co,C as lo,a as uo,D as ho,K as mo,M as po,S as fo}from"./method-access-map-BgqTQNPE.js";import{Z as go,p as So,q as bo,v as yo,w as vo,x as Co,y as X,z as wo,A as Io}from"./schemas-BEt-CulV.js";class Ao{disposers=[];disposed=!1;onError;constructor(e={}){this.onError=e.onError??((t,s)=>{console.error(`[DisposerChain] disposer #${s} threw`,t)})}add(e){if(this.disposed){try{const t=e();t&&typeof t.then=="function"&&t.catch(s=>this.onError(s,-1))}catch(t){this.onError(t,-1)}return()=>{}}return this.disposers.push(e),()=>{const t=this.disposers.indexOf(e);t>=0&&this.disposers.splice(t,1)}}get isDisposed(){return this.disposed}get size(){return this.disposers.length}async dispose(){if(this.disposed)return;this.disposed=!0;const e=this.disposers.slice().reverse();this.disposers=[];for(let t=0;t<e.length;t++){const s=e[t];try{const i=s();i&&typeof i.then=="function"&&await i}catch(i){this.onError(i,e.length-1-t)}}}}const ee="hub-only";function y(a){return{placement:a.execution?.placement??ee,group:a.execution?.group}}function Eo(a){const e=y(a).placement;return e==="any-node"||e==="agent-only"}function _o(a){return y(a).placement==="agent-only"}function ko(a){return y(a).group}function Po(a,e){return a.execution?.group??e}function Do(a){return y(a).placement}function Ro(a,e){return a.category===e}function N(a,e,t){return{id:typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2),timestamp:new Date,source:e,category:a,data:t}}function te(a,e){const t=e.ts??Date.now();a.emit(N("system.ready-state",{type:"capability",id:e.capName,nodeId:e.sourceNodeId},{capName:e.capName,scope:e.scope,state:e.state,generation:e.generation,sourceNodeId:e.sourceNodeId,ts:t}))}class ae{_ctx=null;_config;_readinessGeneration=typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2,14);_registeredCapNames=[];defaults;constructor(e){this.defaults=e,this._config={...e}}get autoEmitReadiness(){return!0}get ctx(){if(!this._ctx)throw new Error(`${this.constructor.name}: ctx accessed before initialize()`);return this._ctx}get ctxIfReady(){return this._ctx}get config(){return this._config}async initialize(e){this._ctx=e,await this.resolveConfig();const t=await this.onInitialize();this.emitLifecycle(v.AddonStarted);const s=se(t),i=s&&"providers"in s&&s.providers?s.providers:[];return this._registeredCapNames=i.map(n=>n.capability.name),s}postBrokerStart(){this.autoEmitReadiness&&this._registeredCapNames.length>0&&this.emitReadinessForProviders("ready")}async onHubReachable(){}async shutdown(){this.emitLifecycle(v.AddonStopped),this.autoEmitReadiness&&this.emitReadinessForProviders("down"),await this.onShutdown();for(const e of this._subscriptions)e();this._subscriptions=[],this._ctx=null}async onShutdown(){}async onConfigChanged(){}field(e){return e}schema(e){return e}globalSettingsSchema(){return null}deviceSettingsSchema(){return null}async getGlobalSettings(e){const t=this.globalSettingsSchema();if(!t)return{sections:[]};const s=await this._ctx?.settings?.readAddonStore()??{};return P(t,e?{...s,...e}:s)}async updateGlobalSettings(e){await this._ctx?.settings?.writeAddonStore(e),await this.resolveConfig(),await this.onConfigChanged(),this.emitLifecycle(v.AddonUpdated,{level:"global"}),this.maybeAutoRestart(e,this.globalSettingsSchema())}maybeAutoRestart(e,t){if(!t)return;const s=new Set;for(const o of t.sections)for(const c of o.fields)c.type==="separator"||c.type==="info"||c.requiresRestart&&s.add(c.key);if(s.size===0||!Object.keys(e).some(o=>s.has(o)))return;const n=this._ctx;if(!n)return;const r=n.id;setImmediate(()=>{n.api.addons?.restartAddon?.mutate({addonId:r}).then(()=>{n.logger.info("addon auto-restart triggered by restart-required setting change",{meta:{changedFields:Object.keys(e).filter(c=>s.has(c))}})}).catch(c=>{n.logger.error("addon auto-restart failed",{meta:{error:c instanceof Error?c.message:String(c)}})})})}async getDeviceSettings(e){const t=this.deviceSettingsSchema();if(!t)return{sections:[]};const s=await this._ctx?.settings?.readDeviceStore(e)??{};return P(t,s)}async updateDeviceSettings(e,t){await this._ctx?.settings?.writeDeviceStore(e,t)}_subscriptions=[];watchCapability(e,t){const s=Array.isArray(e)?e:[e],i=new Set(s);this.subscribe({category:"system.ready-state"},n=>{const r=n.data;if(typeof r.capName!="string"||!i.has(r.capName)||r.scope?.type!=="node")return;const o=r.scope.nodeId;if(typeof o!="string"||o.length===0)return;const c=r.capName;r.state==="down"?t.onDown?.(o,c):r.state==="ready"&&t.onReady?.(o,c)})}subscribe(e,t){const s=this.ctx.eventBus.subscribe(e,t);this._subscriptions.push(s)}emitLifecycle(e,t){try{this._ctx?.eventBus.emit({id:`${this._ctx.id}-${Date.now()}`,timestamp:new Date,source:{type:"addon",id:this._ctx.id,nodeId:this._ctx.kernel.localNodeId??"hub"},category:e,data:t??{}})}catch{}}emitReadinessForProviders(e){const t=this._ctx;if(!t||this._registeredCapNames.length===0)return;const s=t.kernel?.localNodeId??"hub",i=s.includes("/")?s.split("/")[0]:s;for(const n of this._registeredCapNames)try{te(t.eventBus,{capName:n,scope:{type:"node",nodeId:i},state:e,generation:this._readinessGeneration,sourceNodeId:i})}catch{}}async resolveModelsDir(){return this.ctx.api.storage.resolve.query({location:"models",relativePath:""}).catch(()=>"camstack-data/models")}get capabilities(){return this.ctx.capabilities??null}async resolveConfig(){const e=await this.readAddonStoreWithRetry(),t={...this.defaults};for(const s of Object.keys(this.defaults)){const i=e[s];if(i!=null){const n=typeof this.defaults[s];typeof i===n&&(t[s]=i)}}this._config=t}async readAddonStoreWithRetry(){const e=this._ctx?.settings;if(!e)return{};const t=[150,350,600,900];let s;for(let i=0;i<=t.length;i++)try{return await e.readAddonStore()??{}}catch(n){s=n;const r=n instanceof Error?n.message:String(n);if(!(r.includes("SqliteSettingsBackend not initialized")||r.includes("provider not available")))throw n;if(i===t.length)break;await new Promise(c=>setTimeout(c,t[i]))}return this._ctx?.logger?.warn?.("readAddonStore: settings-store unavailable after retries — using defaults",{meta:{error:s instanceof Error?s.message:String(s)}}),{}}}function se(a){if(a!=null)return Array.isArray(a)?{providers:a}:a}function No(a,e){return{id:a,getRoutes:()=>e,invoke:async t=>{const s=To(e,t.method,t.path);if(!s)return{status:404,headers:{},redirectUrl:null,body:{error:`No route matches ${t.method} ${t.path}`}};const i={status:200,headers:{},redirectUrl:null},n=Oo(i),r={params:{...t.params,...s.params},query:t.query,body:t.body,headers:t.headers,...t.user?{user:t.user}:{},...t.scopedToken!==void 0?{scopedToken:t.scopedToken}:{}};return await s.route.handler(r,n),i}}}function To(a,e,t){const s=e.toUpperCase();for(const i of a){if(i.method!==s)continue;const n=xo(i.path,t);if(n!==null)return{route:i,params:n}}return null}function xo(a,e){const t=a.split("/").filter(Boolean),s=e.split("/").filter(Boolean);if(t.length!==s.length)return null;const i={};for(let n=0;n<t.length;n++){const r=t[n],o=s[n];if(r.startsWith(":"))i[r.slice(1)]=o;else if(r!==o)return null}return i}function Oo(a){const e={status(t){return a.status=t,e},code(t){return a.status=t,e},send(t){a.body=t},redirect(t){a.redirectUrl=t,a.status===200&&(a.status=302)},header(t,s){return a.headers[t.toLowerCase()]=s,e},type(t){return a.contentType=t,e}};return e}class ie extends Error{capName;scope;waitedMs;constructor(e,t,s){super(`Timed out waiting for ${e} (${f(t)}) to become ready after ${s}ms`),this.name="ReadinessTimeoutError",this.capName=e,this.scope=t,this.waitedMs=s}}function C(a,e){return`${a}|${f(e)}`}function f(a){switch(a.type){case"global":return"global";case"node":return`node:${a.nodeId}`;case"device":return`device:${a.deviceId}`}}function _(a,e){return a.type!==e.type?!1:a.type==="global"||e.type==="global"?!0:a.type==="node"&&e.type==="node"?a.nodeId===e.nodeId:a.type==="device"&&e.type==="device"?a.deviceId===e.deviceId:!1}class Mo{bus;sourceNodeId;logger;now;generation;snapshot=new Map;subscriptions=new Set;unsubscribeBus;unsubscribeAgentOffline;constructor(e){if(this.bus=e.eventBus,this.sourceNodeId=e.sourceNodeId,this.logger=e.logger,this.now=e.now??(()=>Date.now()),this.generation=e.generation??Lo(),this.unsubscribeBus=this.bus.subscribe({category:"system.ready-state"},t=>this.ingest(t.data)),this.unsubscribeAgentOffline=this.bus.subscribe({category:"agent.offline"},t=>this.synthesizeDownForNode(t.data.agentId)),typeof this.bus.getRecent=="function")try{const t=this.bus.getRecent({category:"system.ready-state"});for(const s of t)this.ingest(s.data)}catch{}}close(){this.unsubscribeBus(),this.unsubscribeAgentOffline(),this.subscriptions.clear()}get(e,t){return this.snapshot.get(C(e,t))??null}getSnapshotForTransport(){return Array.from(this.snapshot.values())}hydrate(e){const t=this.now();for(const s of e){const i=C(s.capName,s.scope);if(this.snapshot.has(i))continue;const n={capName:s.capName,scope:s.scope,state:s.state,generation:s.generation,epoch:1,lastChange:t,sourceNodeId:s.sourceNodeId};this.snapshot.set(i,n),this.logger&&this.logger.debug(`readiness: ${s.capName} (${f(s.scope)}) → ${s.state} (hydrated, gen=${s.generation.slice(0,6)})`);const r={capName:s.capName,scope:s.scope,state:s.state,epoch:1,generation:s.generation,sourceNodeId:"hydrated",ts:t,durationInPrevState:0};for(const o of this.subscriptions)if(o.capName===s.capName&&_(o.scope,s.scope))try{o.handler(r)}catch(c){this.logger?.warn(`readiness hydrate handler threw for ${s.capName}: ${c.message??String(c)}`)}}}getAll(){return new Map(this.snapshot)}emitReady(e,t){this.emitTransition(e,t,"ready")}emitStarting(e,t){this.emitTransition(e,t,"starting")}emitDown(e,t){this.emitTransition(e,t,"down")}awaitReady(e,t,s={}){const i=s.timeoutMs??Number.POSITIVE_INFINITY,n=this.now();return this.get(e,t)?.state==="ready"?Promise.resolve():s.signal?.aborted?Promise.reject(s.signal.reason??new Error("aborted")):new Promise((o,c)=>{let l=!1;const d=this.onReadyState(e,t,A=>{A.state==="ready"&&(l||(l=!0,p(),o()))}),h=!Number.isFinite(i)?null:setTimeout(()=>{l||(l=!0,p(),c(new ie(e,t,this.now()-n)))},i),S=()=>{l||(l=!0,p(),c(s.signal?.reason??new Error("aborted")))};s.signal?.addEventListener("abort",S,{once:!0});function p(){d(),h!==null&&clearTimeout(h),s.signal?.removeEventListener("abort",S)}})}onReadyState(e,t,s){const i={capName:e,scope:t,handler:s};this.subscriptions.add(i);const n=this.get(e,t);return n!==null&&queueMicrotask(()=>{this.subscriptions.has(i)&&s({capName:e,scope:t,state:n.state,epoch:n.epoch,generation:n.generation,sourceNodeId:this.sourceNodeId,ts:n.lastChange,durationInPrevState:0})}),()=>{this.subscriptions.delete(i)}}emitTransition(e,t,s){const i=this.now();this.bus.emit(N("system.ready-state",{type:"capability",id:e,nodeId:this.sourceNodeId},{capName:e,scope:t,state:s,generation:this.generation,sourceNodeId:this.sourceNodeId,ts:i}))}ingest(e){if(typeof e?.capName!="string"||e.state!=="ready"&&e.state!=="starting"&&e.state!=="down"||typeof e.generation!="string"||e.scope?.type!=="global"&&e.scope?.type!=="node"&&e.scope?.type!=="device")return;const t=C(e.capName,e.scope),s=this.snapshot.get(t)??null,i=this.now();let n;if(s===null?n=e.state==="ready"?1:0:s.generation!==e.generation&&e.state==="ready"?n=s.epoch+1:n=s.epoch,s!==null&&s.generation===e.generation&&s.state===e.state)return;const r=s===null?0:Math.max(0,i-s.lastChange),o={capName:e.capName,scope:e.scope,state:e.state,generation:e.generation,epoch:n,lastChange:i,sourceNodeId:e.sourceNodeId};this.snapshot.set(t,o);const c={capName:e.capName,scope:e.scope,state:e.state,epoch:n,generation:e.generation,sourceNodeId:e.sourceNodeId,ts:e.ts,durationInPrevState:r};this.logger&&this.logger.debug(`readiness: ${e.capName} (${f(e.scope)}) → ${e.state} epoch=${n} gen=${e.generation.slice(0,6)} (prev ${r}ms)`);for(const l of this.subscriptions)if(l.capName===e.capName&&_(l.scope,e.scope))try{l.handler(c)}catch(d){this.logger?.warn(`readiness handler threw for ${e.capName}: ${d.message??String(d)}`)}}synthesizeDownForNode(e){const t=this.now();for(const[s,i]of this.snapshot){if(i.state==="down"||!(i.scope.type==="node"&&i.scope.nodeId===e||i.scope.type==="device"&&i.sourceNodeId===e))continue;const r=Math.max(0,t-i.lastChange),o={...i,state:"down",lastChange:t};this.snapshot.set(s,o);const c={capName:i.capName,scope:i.scope,state:"down",epoch:i.epoch,generation:i.generation,sourceNodeId:this.sourceNodeId,ts:t,durationInPrevState:r};this.logger&&this.logger.debug(`readiness: ${i.capName} (${f(i.scope)}) → down (synthesized from agent.offline ${e})`);for(const l of this.subscriptions)if(l.capName===i.capName&&_(l.scope,i.scope))try{l.handler(c)}catch(d){this.logger?.warn(`readiness handler threw during agent.offline demux for ${i.capName}: ${d.message??String(d)}`)}}}}function Lo(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():Math.random().toString(36).slice(2,14)}function Bo(a,e){for(const{capName:t,scope:s}of e)a.emitDown(t,s)}const $o=["data","media","recordings","recordings-high","recordings-low","recordings-clips","event-images","models","addons-data","cache","logs","backups"],Fo={data:"db",media:"media",recordings:"recordings","recordings-high":"recordings-high","recordings-low":"recordings-low","recordings-clips":"recordings-clips","event-images":"event-images",models:"models","addons-data":"addons-data",cache:"/tmp/camstack-cache",logs:"logs",backups:"backups"},ne={high:"High",mid:"Mid",low:"Low"};function Uo(a){return ne[a]??a.charAt(0).toUpperCase()+a.slice(1)}function re(a){return(a.width??0)*(a.height??0)}function oe(a){if(a.length===0)return[];const e=a.map((s,i)=>({s,i,px:re(s.metadata??{})})).sort((s,i)=>i.px-s.px),t=Array.from({length:a.length});for(let s=0;s<e.length;s++){const{s:i,i:n}=e[s];let r;s===0?r="high":s===e.length-1?r="low":r="mid",t[n]={...i,quality:r}}return t}function zo(a){const e=a.height??0,t=a.width??0;return e>=1080||t>=1920?"high":e>=480||t>=640?"mid":"low"}function Ko(a){const e=a.protocols.find(i=>i.type==="rtsp"&&i.url)??a.protocols.find(i=>i.url),t=e?.type,s=t==="rtsp"?"rtsp":t==="http"||t==="flv"?"http-mjpeg":"custom";return{id:a.id,label:a.label??a.id,protocol:s,url:e?.url,profileHint:a.quality}}function m(a){return typeof a=="string"}function Wo(a){return typeof a=="object"&&a!==null&&!Array.isArray(a)}function Ho(a){return m(a)&&a.trim()?{url:a}:Wo(a)&&m(a.url)&&a.url.trim()?{url:a.url,label:m(a.label)?a.label:void 0}:null}function jo(a){const e=m(a.snapshot_url)?a.snapshot_url:void 0;if(Array.isArray(a.streams)){const r=[];for(const o of a.streams){const c=Ho(o);c&&r.push(c)}return{streams:r,snapshot_url:e}}const t=[],s=m(a.main_stream_url)?a.main_stream_url:void 0;s&&t.push({url:s,label:m(a.main_stream_name)?a.main_stream_name:void 0});const i=m(a.sub_stream_url)?a.sub_stream_url:void 0;i&&t.push({url:i,label:m(a.sub_stream_name)?a.sub_stream_name:void 0});const n=m(a.third_stream_url)?a.third_stream_url:void 0;return n&&t.push({url:n,label:m(a.third_stream_name)?a.third_stream_name:void 0}),{streams:t,snapshot_url:e}}function Zo(a){if(a.length===0)return{};const e=oe(a),t={},s=e.find(o=>o.quality==="high"),i=e.find(o=>o.quality==="mid"),n=e.find(o=>o.quality==="low");s&&(t.high=s.id),i&&(t.mid=i.id),n&&(t.low=n.id);const r=s??i??n??e[0];return r&&(t.high||(t.high=r.id),t.mid||(t.mid=r.id),t.low||(t.low=r.id)),t}const qo={streaming:!0,notifications:!0,objectDetection:!1,remoteAccess:!0,agentCluster:!1,smartHome:!0,recordings:!0,backup:!0,repl:!0},Vo=["face","plate"],Go=["face","plate","clip","custom"],Yo={cleanupIntervalMs:3600*1e3,detectionEventsDays:30,audioLevelsDays:7,snapshotsDays:14};var ce=(a=>(a.Addon="addon",a.Core="core",a.Device="device",a.Provider="provider",a.System="system",a))(ce||{});const de="camstack/camstack-models",Jo=`https://huggingface.co/${de}/resolve/main`,Qo={"features.streaming":!0,"features.notifications":!0,"features.objectDetection":!1,"features.remoteAccess":!0,"features.agentCluster":!1,"features.smartHome":!0,"features.recordings":!0,"features.backup":!0,"features.repl":!0,"retention.detectionEventsDays":30,"retention.audioLevelsDays":7,"logging.level":"info","logging.retentionDays":30,"eventBus.ringBufferSize":1e4,"storage.provider":"sqlite-storage","storage.locations":{data:"camstack-data/data",media:"camstack-data/media",recordings:"camstack-data/recordings",cache:"/tmp/camstack-cache",logs:"camstack-data/logs",models:"camstack-data/models"},providers:[],"recording.segmentDurationSeconds":4,"recording.defaultRetentionDays":30,"ffmpeg.binaryPath":"ffmpeg","ffmpeg.hwAccel":"auto","ffmpeg.threadCount":0,"auth.tokenExpiry":"24h"};function T(a){return JSON.parse(a)}function le(a){return a===null||typeof a!="object"||Array.isArray(a)?null:{...a}}function Xo(a){return Array.isArray(a)?a:[]}function ec(a,e=""){return typeof a=="string"?a:e}function tc(a,e=0){return typeof a=="number"?a:e}function ac(a,e=!1){return typeof a=="boolean"?a:e}function sc(a){try{return le(T(a))}catch{return null}}function ic(a){try{const e=T(a);return Array.isArray(e)?e:null}catch{return null}}function nc(a,e){return`https://huggingface.co/${a}/resolve/main/${e}`}function rc(a,e){if(a.length!==e.length)return 0;let t=0,s=0,i=0;for(let r=0;r<a.length;r++)t+=a[r]*e[r],s+=a[r]*a[r],i+=e[r]*e[r];const n=Math.sqrt(s)*Math.sqrt(i);return n===0?0:t/n}class oc{constructor(e,t){this.elementId=e,this.getBackend=typeof t=="function"?t:()=>t}cache={};listeners=new Set;loaded=!1;getBackend;async ensureLoaded(){if(this.loaded)return;const e=this.getBackend();if(!e)throw new Error(`ElementConfigStore(${this.elementId}): settings backend not available`);const t=await e.query({collection:"config",filter:{where:{id:this.elementId},limit:1}});t.length>0&&(this.cache=t[0].data??{}),this.loaded=!0}getAll(){return{...this.cache}}get(e){const t=e.split(".");let s=this.cache;for(const i of t){if(s===null||typeof s!="object"||Array.isArray(s))return;s=Reflect.get(s,i)}return s}async set(e,t){await this.ensureLoaded(),cc(this.cache,e,t),await this.persist(),this.notifyListeners()}async setAll(e){await this.ensureLoaded(),this.cache={...e},await this.persist(),this.notifyListeners()}onChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async load(){await this.ensureLoaded()}async loadDefaults(e){await this.ensureLoaded(),Object.keys(this.cache).length===0&&(this.cache={...e},await this.persist())}async persist(){const e=this.getBackend();if(!e)throw new Error(`ElementConfigStore(${this.elementId}): settings backend not available — cannot persist config`);await e.set({collection:"config",key:this.elementId,value:this.cache})}notifyListeners(){const e=this.getAll();for(const t of this.listeners)try{t(e)}catch{}}}function cc(a,e,t){const s=e.split(".");let i=a;for(let n=0;n<s.length-1;n++){const r=s[n],o=i[r];if(o===null||typeof o!="object"||Array.isArray(o)){const c={};i[r]=c,i=c}else i=o}i[s[s.length-1]]=t}const x={cpu:"onnx",coreml:"onnx",cuda:"onnx",tensorrt:"onnx","onnx-py":"onnx",pytorch:"pt",openvino:"openvino"},ue={onnx:"onnx",coreml:"coreml",openvino:"openvino",tflite:"tflite",pytorch:"pt"},he={coreml:"coreml_inference.py",pytorch:"pytorch_inference.py",openvino:"openvino_inference.py"};function me(a,e){return a==="node"?"onnx":{coreml:"coreml",openvino:"openvino",pytorch:"pytorch","onnx-py":"onnx",cpu:"onnx"}[e]??e}function dc(a,e){return a==="node"?x[e]??"onnx":{coreml:"coreml",openvino:"openvino",pytorch:"pt","onnx-py":"onnx",cpu:"onnx"}[e]??"onnx"}function lc(a,e){return!a||a==="auto"?"auto":me(a,e??"cpu")}function uc(a){return x[a]??"onnx"}function hc(a){return ue[a]}function mc(a){return he[a]}function pc(a){return a==="coreml"||a==="pytorch"||a==="openvino"}function pe(a){return a instanceof Error?a.message:typeof a=="string"?a:String(a)}async function fc(a,e){const t=performance.now();try{return{output:e!==void 0?await gc(a(),e):await a(),durationMs:M(performance.now()-t),ok:!0}}catch(s){return{output:void 0,durationMs:M(performance.now()-t),ok:!1,error:pe(s)}}}function M(a){return Math.round(a*100)/100}function gc(a,e){return new Promise((t,s)=>{const i=setTimeout(()=>s(new Error(`Inference timeout after ${e}ms`)),e);a.then(n=>{clearTimeout(i),t(n)}).catch(n=>{clearTimeout(i),s(n)})})}const Sc=[{id:"person",name:"Person"},{id:"bicycle",name:"Bicycle"},{id:"car",name:"Car"},{id:"motorcycle",name:"Motorcycle"},{id:"airplane",name:"Airplane"},{id:"bus",name:"Bus"},{id:"train",name:"Train"},{id:"truck",name:"Truck"},{id:"boat",name:"Boat"},{id:"traffic light",name:"Traffic Light"},{id:"fire hydrant",name:"Fire Hydrant"},{id:"stop sign",name:"Stop Sign"},{id:"parking meter",name:"Parking Meter"},{id:"bench",name:"Bench"},{id:"bird",name:"Bird"},{id:"cat",name:"Cat"},{id:"dog",name:"Dog"},{id:"horse",name:"Horse"},{id:"sheep",name:"Sheep"},{id:"cow",name:"Cow"},{id:"elephant",name:"Elephant"},{id:"bear",name:"Bear"},{id:"zebra",name:"Zebra"},{id:"giraffe",name:"Giraffe"},{id:"backpack",name:"Backpack"},{id:"umbrella",name:"Umbrella"},{id:"handbag",name:"Handbag"},{id:"tie",name:"Tie"},{id:"suitcase",name:"Suitcase"},{id:"frisbee",name:"Frisbee"},{id:"skis",name:"Skis"},{id:"snowboard",name:"Snowboard"},{id:"sports ball",name:"Sports Ball"},{id:"kite",name:"Kite"},{id:"baseball bat",name:"Baseball Bat"},{id:"baseball glove",name:"Baseball Glove"},{id:"skateboard",name:"Skateboard"},{id:"surfboard",name:"Surfboard"},{id:"tennis racket",name:"Tennis Racket"},{id:"bottle",name:"Bottle"},{id:"wine glass",name:"Wine Glass"},{id:"cup",name:"Cup"},{id:"fork",name:"Fork"},{id:"knife",name:"Knife"},{id:"spoon",name:"Spoon"},{id:"bowl",name:"Bowl"},{id:"banana",name:"Banana"},{id:"apple",name:"Apple"},{id:"sandwich",name:"Sandwich"},{id:"orange",name:"Orange"},{id:"broccoli",name:"Broccoli"},{id:"carrot",name:"Carrot"},{id:"hot dog",name:"Hot Dog"},{id:"pizza",name:"Pizza"},{id:"donut",name:"Donut"},{id:"cake",name:"Cake"},{id:"chair",name:"Chair"},{id:"couch",name:"Couch"},{id:"potted plant",name:"Potted Plant"},{id:"bed",name:"Bed"},{id:"dining table",name:"Dining Table"},{id:"toilet",name:"Toilet"},{id:"tv",name:"TV"},{id:"laptop",name:"Laptop"},{id:"mouse",name:"Mouse"},{id:"remote",name:"Remote"},{id:"keyboard",name:"Keyboard"},{id:"cell phone",name:"Cell Phone"},{id:"microwave",name:"Microwave"},{id:"oven",name:"Oven"},{id:"toaster",name:"Toaster"},{id:"sink",name:"Sink"},{id:"refrigerator",name:"Refrigerator"},{id:"book",name:"Book"},{id:"clock",name:"Clock"},{id:"vase",name:"Vase"},{id:"scissors",name:"Scissors"},{id:"teddy bear",name:"Teddy Bear"},{id:"hair drier",name:"Hair Drier"},{id:"toothbrush",name:"Toothbrush"}],bc=[{id:"person",name:"Person"},{id:"vehicle",name:"Vehicle"},{id:"animal",name:"Animal"}],yc={mapping:{person:"person",bicycle:"vehicle",car:"vehicle",motorcycle:"vehicle",airplane:"vehicle",bus:"vehicle",train:"vehicle",truck:"vehicle",boat:"vehicle",bird:"animal",cat:"animal",dog:"animal",horse:"animal",sheep:"animal",cow:"animal",elephant:"animal",bear:"animal",zebra:"animal",giraffe:"animal"},preserveOriginal:!1},vc={camera:{type:"camera",label:"Camera",icon:"camera"}};class g{schema;data;persistFn;constructor(e,t,s){this.schema=e,this.data=t,this.persistFn=s}static fromSchema(e,t,s={},i){const n=e.safeParse(s);if(n.success)return new g(e,n.data,t);const r=new Set;for(const d of n.error.issues){const u=d.path[0];typeof u=="string"&&r.add(u)}const o={...s};for(const d of r)delete o[d];const c=e.safeParse(o);if(i?.({droppedKeys:[...r],issues:n.error.issues}),c.success)return t(c.data).catch(()=>{}),new g(e,c.data,t);const l=e.parse({});return new g(e,l,t)}get values(){return this.data}get(e){return this.data[e]}async set(e,t){const s=this.schema.parse({...this.data,[e]:t});this.data=s,await this.persistFn(this.data)}async setAll(e){const t=this.schema.parse({...this.data,...e});this.data=t,await this.persistFn(this.data)}async deleteKey(e){const{[e]:t,...s}=this.data,i=this.schema.parse(s);this.data=i,await this.persistFn(this.data)}entries(){const e=this.schema.shape;return Object.entries(e).map(([t,s])=>({key:t,schema:s,value:this.data[t],description:s.description}))}}class I{writer;pendingWrites=new Set;slices;schemas=new Map;listeners=new Set;capListeners=new Map;constructor(e,t){this.writer=t,this.slices=new Map;for(const[s,i]of Object.entries(e))i&&typeof i=="object"&&!Array.isArray(i)&&this.slices.set(s,{...i})}static fromInitial(e,t){return new I(e,t)}installCapSchema(e,t){const s=this.schemas.get(e);if(s){if(s!==t)throw new Error(`[DeviceRuntimeState] capability "${e}" registered a different runtime-state schema; each cap must declare ONE shape across every provider`);return}this.schemas.set(e,t);const i=this.slices.get(e);if(i){const n=t.safeParse(i);n.success?this.slices.set(e,n.data):this.slices.delete(e)}}getCapState(e){const t=this.slices.get(e);if(t)return Object.freeze({...t})}getCapField(e,t){return this.slices.get(e)?.[t]}setCapState(e,t){this.applyCapWrite(e,t,!1)}patchCapState(e,t){this.applyCapWrite(e,t,!0)}applyCapWrite(e,t,s){const i=this.schemas.get(e);if(!i)throw new Error(`[DeviceRuntimeState] no schema registered for cap "${e}" — did the device register it via ctx.registerNativeCap before writing?`);const n=this.slices.get(e)??{},r=s?{...n,...t}:{...t},o=i.parse(r);if(Cc(n,o))return;this.slices.set(e,o),this.fireListeners([e]);const c=this.writer(e,{...o}).catch(()=>{});this.pendingWrites.add(c),c.finally(()=>{this.pendingWrites.delete(c)})}fireListeners(e){const t=this.snapshot();for(const s of this.listeners)try{s(e,t)}catch{}for(const s of e){const i=this.capListeners.get(s);if(!i)continue;const n=this.getCapState(s);for(const r of i)try{r(n)}catch{}}}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}subscribeCap(e,t){let s=this.capListeners.get(e);s||(s=new Set,this.capListeners.set(e,s));const i=n=>{t(n)};return s.add(i),()=>{const n=this.capListeners.get(e);n&&(n.delete(i),n.size===0&&this.capListeners.delete(e))}}snapshot(){const e={};for(const[t,s]of this.slices)e[t]=Object.freeze({...s});return Object.freeze(e)}async flush(){if(this.pendingWrites.size===0)return;const e=[...this.pendingWrites];await Promise.allSettled(e)}}function Cc(a,e){const t=Object.keys(a),s=Object.keys(e);if(t.length!==s.length)return!1;for(const i of t)if(a[i]!==e[i])return!1;return!0}const k="lastFetchedAt";function wc(a){const{runtimeState:e,cap:t,ownDeviceId:s,refresh:i,staleMs:n,empty:r}=a,o=async()=>{const d=e.getCapState(t.name),u=typeof d?.[k]=="number"?d[k]:0;(!d||Date.now()-u>n)&&await i()},c=()=>{const d=e.getCapState(t.name);if(!d)return r();const{[k]:u,...h}=d;return h};return{ensureFresh:o,getStatus:async({deviceId:d})=>{if(d!==s)throw new Error(`${t.name}: deviceId mismatch, expected ${s}, got ${d}`);return await o(),c()}}}const Ic={audioMetrics:J,battery:Y,brightness:G,cameraStreams:V,deviceDiscovery:q,deviceStatus:R,doorbell:Z,featureProbe:D,motion:j,motionTrigger:H,motionZones:W,ptzAutotrack:K,streamParams:z,switch:U,zoneAnalytics:F,zoneRules:$,zones:B};class Ac{id;stableId;type;name;parentDeviceId;role;get online(){return this.runtimeState.getCapState("device-status")?.online??!1}set online(e){this.markOnline(e)}get state(){if(!this._stateProxyCache){const e={},t={get:(s,i)=>{const n=i;if(n in e)return e[n];const r=Ic[n];if(!r)return;const o=this.sliceProxy(r);return e[n]=o,o}};this._stateProxyCache=new Proxy(e,t)}return this._stateProxyCache}_stateProxyCache;config;runtimeState;ctx;location;disabled;constructor(e,t,s){if(this.ctx=e,this.id=e.id,this.stableId=e.stableId,this.type=s.type,!e.deviceMeta)throw new Error(`BaseDevice constructor: ctx.deviceMeta is required (id=${e.id} stableId=${e.stableId})`);this.name=e.deviceMeta.name,this.location=e.deviceMeta.location,this.disabled=e.deviceMeta.disabled,this.role=s.role,this.parentDeviceId=e.parentDeviceId;const i=e.persistedConfig??{};this.config=g.fromSchema(t,d=>e.persistConfig(d),i,({droppedKeys:d,issues:u})=>{e.logger.warn("Device config recovery: dropping invalid persisted fields",{tags:{deviceId:e.id,stableId:e.stableId},meta:{droppedKeys:[...d],firstIssue:u[0]?.message??null}})});let n=null;const r=async(d,u)=>{n||(n=e.fetchDevice(e.id)),await(await n).deviceState.setCapSlice({capName:d,slice:u})},o=e.initialRuntimeState??{};this.runtimeState=I.fromInitial(o,r),e.bindRuntimeState?.(this.runtimeState),e.registerNativeCap?.(R,{});const c={online:!1,lastChangedAt:Date.now()};this.runtimeState.setCapState("device-status",c),e.registerNativeCap?.(D,{});const l={flags:{},deviceType:null,model:null,channelCount:null,lastProbedAt:0,lastFetchedAt:0};this.runtimeState.setCapState("feature-probe",l)}async removeDevice(){}markOnline(e){if(this.online===e)return;const t={online:e,lastChangedAt:Date.now()};this.runtimeState.setCapState("device-status",t)}async refreshFeatures(){const t=this.ctx.api?.deviceManager?.registerDevice;if(t)try{await t.mutate({addonId:this.ctx.deviceMeta.addonId,stableId:this.stableId,id:this.id,type:this.type,name:this.name,parentDeviceId:this.parentDeviceId,features:[...this.features],config:{}})}catch{}}getCapSlice(e){return this.runtimeState.getCapState(e.name)??null}setCapSlice(e,t){this.runtimeState.setCapState(e.name,t)}sliceProxy(e){const t={},s={get:(i,n)=>this.runtimeState.getCapState(e.name)?.[n],set:(i,n,r)=>(this.runtimeState.patchCapState(e.name,{[n]:r}),!0),has:(i,n)=>{const r=this.runtimeState.getCapState(e.name);return r?n in r:!1},ownKeys:()=>{const i=this.runtimeState.getCapState(e.name);return i?Object.keys(i):[]},getOwnPropertyDescriptor:(i,n)=>{const r=this.runtimeState.getCapState(e.name);if(!(!r||!(n in r)))return{configurable:!0,enumerable:!0,value:r[n]}}};return new Proxy(t,s)}getSettingsUISchema(){return{sections:[]}}async applySettingsPatch(e){await this.config.setAll(e)}async onProbe(){}async onActivate(){}async reprobe(){this._kernelReprobe?await this._kernelReprobe():await this.onProbe()}_kernelReprobe;getAccessoryChildren(){return[]}getProbeFlags(){return this.runtimeState.getCapState("feature-probe")?.flags??{}}hasProbed(){return(this.runtimeState.getCapState("feature-probe")?.lastProbedAt??0)>0}}function fe(a,e){const t={};for(const s of a.config.entries())t[s.key]=s.value;return{id:a.id,stableId:a.stableId,addonId:e,type:String(a.type),name:a.name,parentDeviceId:a.parentDeviceId,online:a.online,features:[...a.features],config:t}}class Ec extends ae{async onInitialize(){return this.ctx.logger.info(`${this.providerName} Provider initialized`),[{capability:Q,provider:this}]}async onShutdown(){const e=await this.ctx.kernel.devices?.getAll()??[];for(const t of e)try{await this.ctx.kernel.devices?.decommission(t.id)}catch(s){this.ctx.logger.warn(`${this.providerName}: decommission failed`,{tags:{deviceId:t.id,stableId:t.stableId},meta:{error:s instanceof Error?s.message:String(s)}})}this.ctx.logger.info(`${this.providerName} Provider shut down`,{meta:{decommissionedCount:e.length}})}async start(){}async stop(){}async getStatus(){return{connected:!0,deviceCount:(await this.ctx.kernel.devices?.getAll()??[]).length}}async getDevices(){return(await this.ctx.kernel.devices?.getAll()??[]).map(t=>({id:t.stableId,name:t.name,type:String(t.type)}))}async supportsDiscovery(){return!1}async discoverDevices(){return[]}async adoptDiscoveredDevice(e){throw new Error(`${this.providerName} provider does not support discovery-based adoption`)}async supportsManualCreation(){return!0}async getChildCreationSchema(e){return this.onGetCreationSchema(e.type)}async createDevice(e){const t=await this.onCreateDevice(e.type,e.config),s=this.deviceClasses[t.meta.type];if(!s)throw new Error(`${this.providerName} provider: no device class registered for type "${t.meta.type}" — add it to the deviceClasses map`);const i=this.generateStableId(t.meta.type,t.config),n=await this.ctx.kernel.devices.create(i,s,t.config,null,t.meta);if(t.onAfterCreate)try{await t.onAfterCreate(n)}catch(r){this.ctx.logger.warn("createDevice: onAfterCreate hook threw — device is already registered",{tags:{deviceId:n.id,stableId:i},meta:{error:r instanceof Error?r.message:String(r)}})}return this.toSummary(n)}generateStableId(e,t){return`${this.addonId}-${Date.now()}`}async testCreationField(e){return{status:"ok",labels:["probe not implemented"]}}async restoreDevices(e){await this.onRestoreDevices(e),e.length>0&&this.ctx.logger.info(`Restored ${e.length} ${this.providerName} device(s)`)}async onRestoreDevices(e){const t=new Set;for(const i of e){if(i.parentDeviceId!==null)continue;const n=this.deviceClasses[i.type];if(!n){this.ctx.logger.warn("No device class registered for restored type — skipping",{tags:{stableId:i.stableId},meta:{type:i.type}});continue}try{await this.ctx.kernel.devices.create(i.stableId,n,{}),t.add(i.id)}catch(r){this.ctx.logger.warn("Failed to restore device",{tags:{stableId:i.stableId},meta:{type:i.type,error:r instanceof Error?r.message:String(r)}})}}const s=e.filter(i=>i.parentDeviceId!==null);for(const i of s){const n=this.deviceClasses[i.type];if(n&&i.parentDeviceId!==null&&t.has(i.parentDeviceId))try{await this.ctx.kernel.devices.create(i.stableId,n,{},i.parentDeviceId),t.add(i.id)}catch(r){this.ctx.logger.warn("Failed to restore hub-adopted child",{tags:{stableId:i.stableId,parentDeviceId:i.parentDeviceId},meta:{type:i.type,error:r instanceof Error?r.message:String(r)}})}}}toSummary(e){return fe(e,this.addonId)}}function b(a){return a.def}function _c(a,e="Configuration",t="main"){const s=a.map(i=>kc(i.key,i.schema,i.description));return{sections:[{id:t,title:e,fields:s}]}}function kc(a,e,t){const s=w(e),i=Tc(e),n=t??ge(a),r={key:a,label:n,description:t,default:i};return s instanceof go?Pc(a,r):s instanceof So?Dc(s,r):s instanceof bo?{...r,type:"boolean"}:s instanceof yo?Nc(s,r):s instanceof vo||s instanceof Co?{...r,type:"textarea",rows:6,isJson:!0}:{...r,type:"text"}}function Pc(a,e){const t=a.toLowerCase();return t.includes("password")||t.includes("secret")||t.includes("token")||t.includes("apikey")||t.includes("api_key")?{...e,type:"password",showToggle:!0}:{...e,type:"text"}}function Dc(a,e){const t=a,s=t.minValue,i=t.maxValue,n=s!=null&&isFinite(s)?s:void 0,r=i!=null&&isFinite(i)?i:void 0,o=Rc(a);return{...e,type:"number",...n!==void 0?{min:n}:{},...r!==void 0?{max:r}:{},...o!==void 0?{step:o}:{}}}function Rc(a){const t=b(a).checks??[];for(const s of t)if(s._zod?.def?.check==="multiple_of"&&s._zod.def.value!==void 0)return s._zod.def.value}function Nc(a,e){const t=a.options.map(i=>String(i));return{...e,type:"select",options:t.map(i=>({label:ge(i),value:i}))}}function w(a){return a instanceof X||a instanceof wo||a instanceof Io?w(b(a).innerType):a}function Tc(a){if(a instanceof X)return b(a).defaultValue}function ge(a){return a.replace(/([A-Z])/g," $1").replace(/[_-]/g," ").replace(/^\w/,e=>e.toUpperCase()).trim()}function xc(a,e,t,s,i){if(t.length===0||e.length===0)return{passed:a,excluded:[]};const n=t.filter(h=>h.enabled!==!1),r=n.filter(h=>h.mode==="include"),o=n.filter(h=>h.mode==="exclude"),c=r.length>0,l=new Map(e.map(h=>[h.id,h])),d=[],u=[];for(const h of a){const S=s(h),p=i?.(h),A=r.some(E=>L(E,S,p,l)),O=o.some(E=>L(E,S,p,l));c?A&&!O?d.push(h):u.push(h):O?u.push(h):d.push(h)}return{passed:d,excluded:u}}function L(a,e,t,s){if(a.classFilter&&a.classFilter.length>0&&t!==void 0&&!a.classFilter.includes(t))return!1;for(const i of a.zoneIds){const n=s.get(i);if(n&&Oc(e,n.polygon))return!0}return!1}function Oc(a,e){if(e.length<3)return!1;let t=!1;const{x:s,y:i}=a;for(let n=0,r=e.length-1;n<e.length;r=n++){const o=e[n],c=e[r];o.y>i!=c.y>i&&s<(c.x-o.x)*(i-o.y)/(c.y-o.y||Number.EPSILON)+o.x&&(t=!t)}return t}function Mc(a){return a}function Lc(a,e,t){return{input:a,output:e,kind:t?.kind??"query",auth:t?.auth??"protected",scope:t?.scope??{kind:"system"}}}const Se=[{profile:"main",prefix:"streamMain",label:"Main stream"},{profile:"sub",prefix:"streamSub",label:"Sub stream"},{profile:"ext",prefix:"streamExt",label:"Third stream"}];function Bc(a,e,t){const s=[];if(e.resolutions.length>0){const i=e.resolutions.map(r=>({value:`${String(r.width)}x${String(r.height)}`,label:`${String(r.width)}×${String(r.height)}`})),n=t?`${String(t.width)}x${String(t.height)}`:void 0;n&&!i.some(r=>r.value===n)&&i.unshift({value:n,label:`${n.replace("x","×")} (current)`}),s.push({type:"select",key:`${a.prefix}_resolution`,label:"Resolution",options:i,default:n??i[0]?.value??""})}if(e.codecs.length>0&&s.push({type:"select",key:`${a.prefix}_codec`,label:"Codec",options:e.codecs.map(i=>({value:i,label:i==="h264"?"H.264":"H.265"})),default:t?.codec??e.codecs[0]}),e.framerates.length>0){const i=e.framerates.map(r=>({value:String(r),label:`${String(r)} fps`})),n=t?.framerate;n!==void 0&&!e.framerates.includes(n)&&i.unshift({value:String(n),label:`${String(n)} fps (current)`}),s.push({type:"select",key:`${a.prefix}_framerate`,label:"Frame rate",options:i,default:n!==void 0?String(n):i[0]?.value??""})}if(e.bitrates.length>0){const i=e.bitrates.map(r=>({value:String(r),label:`${String(r)} kbps`})),n=t?.bitrate;n!==void 0&&!e.bitrates.includes(n)&&i.unshift({value:String(n),label:`${String(n)} kbps (current)`}),s.push({type:"select",key:`${a.prefix}_bitrate`,label:"Bitrate",options:i,default:n!==void 0?String(n):i[0]?.value??""})}else{const i=e.bitrateRange;s.push({type:"number",key:`${a.prefix}_bitrate`,label:"Bitrate",unit:"kbps",...i?{min:i[0],max:i[1]}:{},default:t?.bitrate??i?.[0]??0})}if(e.supportsBitrateMode&&s.push({type:"select",key:`${a.prefix}_bitrateMode`,label:"Bitrate mode",options:[{value:"vbr",label:"VBR (variable)"},{value:"cbr",label:"CBR (constant)"}],default:t?.bitrateMode??"vbr"}),e.supportsEncoderProfile&&s.push({type:"select",key:`${a.prefix}_encoderProfile`,label:"Encoder profile",options:[{value:"baseline",label:"Baseline"},{value:"main",label:"Main"},{value:"high",label:"High"}],default:t?.encoderProfile??"main"}),e.supportsGop){const i=e.gop;if(i){const n=[];for(let o=i.min;o<=i.max;o+=i.step)n.push({value:String(o),label:`${String(o)} s`});const r=t?.gop;r!==void 0&&!n.some(o=>o.value===String(r))&&n.unshift({value:String(r),label:`${String(r)} s (current)`}),s.push({type:"select",key:`${a.prefix}_gop`,label:"I-frame interval (GOP)",options:n,default:r!==void 0?String(r):n[0]?.value??""})}else s.push({type:"number",key:`${a.prefix}_gop`,label:"I-frame interval (GOP)",unit:"s",min:1,default:t?.gop??1})}return s.length===0?null:{id:`stream-${a.profile}`,tab:"streaming",title:a.label,description:"Encoder parameters pushed to the camera. Option lists are read live from the camera — fields the firmware doesn't expose are hidden.",columns:2,fields:s}}function $c(a,e){const t=[];for(const s of Se){const i=a[s.profile];if(!i)continue;const n=Bc(s,i,e?.[s.profile]);n&&t.push(n)}return t.length===0?null:{sections:t}}function Fc(a,e){const t={};let s=!1;const i=`${e}_resolution`;if(i in a&&typeof a[i]=="string"){const[u,h]=a[i].split("x").map(Number);Number.isFinite(u)&&Number.isFinite(h)&&(t.width=u,t.height=h,s=!0)}const n=`${e}_codec`;n in a&&(a[n]==="h264"||a[n]==="h265")&&(t.codec=a[n],s=!0);const r=`${e}_framerate`;if(r in a){const u=Number(a[r]);Number.isFinite(u)&&(t.framerate=u,s=!0)}const o=`${e}_bitrate`;if(o in a){const u=Number(a[o]);Number.isFinite(u)&&(t.bitrate=u,s=!0)}const c=`${e}_bitrateMode`;c in a&&(a[c]==="vbr"||a[c]==="cbr")&&(t.bitrateMode=a[c],s=!0);const l=`${e}_encoderProfile`;l in a&&(a[l]==="high"||a[l]==="main"||a[l]==="baseline")&&(t.encoderProfile=a[l],s=!0);const d=`${e}_gop`;if(d in a){const u=Number(a[d]);Number.isFinite(u)&&(t.gop=u,s=!0)}return s?t:null}const Uc=["accessories","battery","brightness","camera-credentials","device-discovery","device-export","device-status","doorbell","feature-probe","intercom","motion","motion-trigger","motion-zones","mqtt-broker","native-object-detection","osd","ptz","ptz-autotrack","snapshot","stream-params","switch"],zc=[{id:"camera-viewer",label:"Camera viewer",description:"Read-only over every device — live streams, recordings, motion events, battery state. Combine with `allowedDevices` to restrict to specific cameras.",rows:[{type:"category",target:"device",access:["view"]}]},{id:"camera-operator",label:"Camera operator",description:"Everything `camera-viewer` does plus PTZ control, intercom, snapshots and recording start/stop. Cannot delete devices or recordings.",rows:[{type:"category",target:"device",access:["view","create"]}]},{id:"cli-deployer",label:"CLI deployer",description:"Push addons to the hub and tail their logs. Used by the `camstack` CLI on dev machines. No delete access — a stolen token cannot uninstall.",rows:[{type:"capability",target:"addons",access:["view","create"]}]},{id:"event-listener",label:"Event listener",description:"Subscribe to motion / audio events. Used by webhook bridges and Home Assistant integrations.",rows:[{type:"capability",target:"events",access:["view"]},{type:"capability",target:"motion-detection",access:["view"]},{type:"capability",target:"audio-analysis",access:["view"]}]}],be=Object.freeze({"device-export":"device-export","mesh-network":"mesh","mqtt-broker":"broker","network-access":"ingress","smtp-provider":"email"}),Kc=["device-export","mesh-network","mqtt-broker","network-access","smtp-provider"];function Wc(a){const e=[];for(const[t,s]of Object.entries(be))s===a&&e.push(t);return e}const Hc=[/^user$/i,/^usr$/i,/^username$/i,/^password$/i,/^pwd$/i,/^pass$/i,/^passwd$/i,/^secret$/i,/^token$/i,/^auth$/i,/^auth[_-]?token$/i,/^bearer$/i,/^api[_-]?key$/i,/^access[_-]?token$/i,/^refresh[_-]?token$/i];function jc(a){return Hc.some(e=>e.test(a))}function Zc(a){try{const e=new URL(a);let t=!1;(e.username||e.password)&&(e.username="",e.password="",t=!0);for(const s of[...e.searchParams.keys()])jc(s)&&(e.searchParams.set(s,"***"),t=!0);return t?e.toString():a}catch{return a}}class qc{constructor(e){this.capacity=e,this.items=Array.from({length:e})}items;head=0;tail=0;count=0;get size(){return this.count}push(e){this.items[this.tail]=e,this.tail=(this.tail+1)%this.capacity,this.count<this.capacity?this.count++:this.head=(this.head+1)%this.capacity}drain(e){const t=[],s=Math.min(e,this.count);for(let i=0;i<s;i++)t.push(this.items[this.head]),this.items[this.head]=void 0,this.head=(this.head+1)%this.capacity;return this.count-=s,t}}function Vc(a,e,t){const s={};for(const i of Object.keys(t))s[i]=n=>a.addons.custom.mutate({addonId:e,action:i,input:n});return s}const Qc=Object.freeze(Object.defineProperty({__proto__:null,ACCESSORY_LABEL:ye,ALL_CAPABILITY_DEFINITIONS:co,APPLE_SA_TO_MACRO:ve,AUDIO_BACKEND_CHOICES:Ce,AUDIO_MACRO_LABELS:we,AccessoriesStatusSchema:Ie,AccessoryKind:Ae,AddBrokerInputSchema:Ee,AddonAutoUpdateSchema:_e,AddonListItemSchema:ke,AddonPageDeclarationSchema:Pe,AddonPageInfoSchema:De,AgentLoadSummarySchema:Re,AlertSchema:Ne,AlertSeveritySchema:Te,AlertSourceSchema:xe,AlertStatusSchema:Oe,ApiKeyRecordSchema:Me,ApiKeySummarySchema:Le,ArchiveEntrySchema:Be,ArchiveManifestSchema:$e,AudioAnalysisResultSchema:Fe,AudioAnalysisSettingsSchema:Ue,AudioChunkInputSchema:ze,AudioClassSummarySchema:Ke,AudioClassificationLabelSchema:We,AudioClassificationResultSchema:He,AudioCodecInfoSchema:je,AudioDecodeSessionConfigSchema:Ze,AudioEncodeSessionConfigSchema:qe,AudioEncodedChunkSchema:Ve,AudioEventSchema:Ge,AudioLevelSchema:Ye,AudioMetricsHistoryPointSchema:Je,AudioMetricsHistorySchema:Qe,AudioMetricsSnapshotSchema:Xe,AudioPcmChunkSchema:et,AuthResultSchema:tt,AutoUpdateSettingsSchema:at,AvailableIntegrationTypeSchema:st,BACKEND_TO_FORMAT:x,BATTERY_DEVICE_PROFILE:it,BackupDestinationInfoSchema:nt,BackupEntrySchema:rt,BaseAddon:ae,BaseDevice:Ac,BaseDeviceProvider:Ec,BatteryStatusSchema:ot,BoundingBoxSchema:ct,BrightnessStatusSchema:dt,BrokerAudioClientSchema:lt,BrokerClientsSchema:ut,BrokerConnectionDetailsSchema:ht,BrokerDecodedClientSchema:mt,BrokerInfoSchema:pt,BrokerRtspClientSchema:ft,BrokerStatsSchema:gt,BrokerStatusSchema:St,CAM_PROFILE_ORDER:bt,CAPABILITY_NAMES:lo,CAPABILITY_ROUTER_KEYS:uo,CAP_NAMES_WITH_STATUS:Uc,CAP_PROVIDER_KIND_MAP:be,COCO_80_LABELS:Sc,COCO_TO_MACRO:yc,CamProfileSchema:yt,CamStreamKindSchema:vt,CamStreamResolutionSchema:Ct,CameraCredentialsSchema:wt,CameraCredentialsStatusSchema:It,CameraMetricsSchema:At,CameraMetricsWithDeviceIdSchema:Et,CameraStreamSchema:_t,CapScopeSchema:kt,CapabilityBindingsSchema:Pt,ChargingStatus:Dt,ClientNetworkStatsSchema:Rt,ClusterAddonNodeDeploymentSchema:Nt,ClusterAddonStatusEntrySchema:Tt,CollectionColumnSchema:xt,CollectionIndexSchema:Ot,ConfigEntrySchema:Mt,ConfigSectionWithValuesSchema:Lt,ConfigTabDeclarationSchema:Bt,CreateApiKeyInputSchema:$t,CreateApiKeyResultSchema:Ft,CreateIntegrationInputSchema:Ut,CreateScopedTokenInputSchema:zt,CreateScopedTokenResultSchema:Kt,CreateUserInputSchema:Wt,CustomActionInputSchema:Ht,DEFAULT_ADDON_PLACEMENT:ee,DEFAULT_AUDIO_ANALYZER_CONFIG:jt,DEFAULT_DECODER_HWACCEL_CONFIG:Zt,DEFAULT_FEATURES:qo,DEFAULT_LOCATION_SUBDIRS:Fo,DEFAULT_RETENTION:Yo,DEVICE_CAP_NAMES:ho,DEVICE_PROFILES:qt,DEVICE_SETTINGS_CONTRIBUTION_METHODS:Vt,DEVICE_STATUS_METHOD:Gt,DEVICE_TYPE_INFO:vc,DecodedAudioChunkSchema:Yt,DecodedFrameSchema:Jt,DecoderAssignmentSchema:Qt,DecoderSessionConfigSchema:Xt,DecoderStatsSchema:ea,DeleteIntegrationResultSchema:ta,DetectorOutputSchema:aa,DeviceConfig:g,DeviceDiscoveryStatusSchema:sa,DeviceExportExposeInputSchema:ia,DeviceExportStatusSchema:na,DeviceExportUnexposeInputSchema:ra,DeviceFeature:oa,DeviceInfoSchema:ca,DeviceNetworkStatsSchema:da,DeviceRole:la,DeviceRuntimeState:I,DeviceStatusSchema:ua,DeviceType:ha,DiscoveredChildDeviceSchema:ma,DiscoveredChildStatusSchema:pa,DiscoveredDeviceSchema:fa,DisposerChain:Ao,DoorbellPressEventSchema:ga,DoorbellStatusSchema:Sa,ElementConfigStore:oc,EmbeddingInfoSchema:ba,EmbeddingResultSchema:ya,EncodedPacketSchema:va,EnrichedWidgetMetadataSchema:Ca,EventCategory:v,EventItemSchema:wa,EventKindSchema:Ia,EventSourceType:ce,ExportSetupFieldSchema:Aa,ExportSetupSchema:Ea,ExposedDeviceSchema:_a,ExposedResourceSchema:ka,FeatureManifestSchema:Pa,FeatureProbeStatusSchema:Da,FrameHandleFormatSchema:Ra,FrameHandleSchema:Na,FrameInputSchema:Ta,GetStreamWithCodecInputSchema:xa,GlobalMetricsSchema:Oa,HF_BASE_URL:Jo,HF_REPO:de,HWACCEL_OPTIONS:Ma,HealthStatusSchema:La,HistoryPointSchema:Ba,HistoryResolutionEnum:$a,InstalledPackageSchema:Fa,IntegrationLiteSchema:Ua,IntegrationWithStateSchema:za,IntercomAbilitySchema:Ka,IntercomStatusSchema:Wa,KNOWN_CAP_NAMES:mo,LocationStatSchema:Ha,LogEntrySchema:ja,LogLevelSchema:Za,LogStreamEntrySchema:qa,MACRO_LABELS:bc,METHOD_ACCESS_MAP:po,MODEL_FORMATS:Va,MediaFileSchema:Ga,MeshPeerSchema:Ya,MeshStatusSchema:Ja,MethodAccessSchema:Qa,MotionAnalysisResultSchema:Xa,MotionEventSchema:es,MotionOnMotionChangedDataSchema:ts,MotionRegionSchema:as,MotionSourceEnum:ss,MotionSourcesSchema:is,MotionStatusSchema:ns,MotionTriggerRuntimeStateSchema:rs,MotionTriggerStatusSchema:os,MotionZoneOptionsSchema:cs,MotionZonePatchSchema:ds,MotionZoneStatusSchema:ls,MqttBrokerStatusSchema:us,NativeDetectionSchema:hs,NativeObjectClassEnum:ms,NativeObjectDetectionStatusSchema:ps,NetworkAccessStatusSchema:fs,NetworkAddressSchema:gs,NetworkEndpointSchema:Ss,NotificationHistoryEntrySchema:bs,NotificationRuleSchema:ys,NotificationSchema:vs,OauthIntegrationDescriptorSchema:Cs,ObjectEventSchema:ws,OrchestratorMetricsSchema:Is,OsdOverlayKindEnum:As,OsdOverlayPatchSchema:Es,OsdOverlaySchema:_s,OsdPositionEnum:ks,OsdStatusSchema:Ps,PIPELINE_FLOW_CAPABILITY_NAMES:Ds,PIPELINE_OWNER_CAPABILITY_NAMES:Rs,PROVIDER_KIND_CAP_NAMES:Kc,PYTHON_SCRIPT:he,PackageUpdateSchema:Ns,PackageVersionInfoSchema:Ts,PasskeySummarySchema:xs,PcmSampleFormatSchema:Os,PerScopeBreakdownSchema:Ms,PipelineAssignmentSchema:Ls,PipelineDefaultStepSchema:Bs,PipelineEngineChoiceSchema:$s,PipelineRunResultBridge:Fs,PipelineStepInputSchema:Us,PlaceholderReasonSchema:zs,PolygonPointSchema:Ks,ProfileSlotSchema:Ws,ProfileSlotStatusSchema:Hs,ProviderStatusSchema:js,PtzAutotrackRuntimeStateSchema:Zs,PtzAutotrackSettingsSchema:qs,PtzAutotrackStatusSchema:Vs,PtzAutotrackTargetOptionSchema:Gs,PtzMoveCommandSchema:Ys,PtzPositionSchema:Js,PtzPresetSchema:Qs,PtzStatusSchema:Xs,QueryFilterSchema:ei,RECOGNITION_TYPES:Go,RUNTIME_DEFAULTS:Qo,RUNTIME_TO_FORMAT:ue,ReadinessRegistry:Mo,ReadinessTimeoutError:ie,RegisteredStreamSchema:ti,ReportMotionInputSchema:ai,RingBuffer:qc,RtpSourceSchema:si,RtspRestreamEntrySchema:ii,RunnerCameraConfigSchema:ni,RunnerCameraDeviceUIFields:ri,RunnerLocalLoadSchema:oi,RunnerLocalMetricsSchema:ci,SCOPE_PRESETS:zc,STORAGE_LOCATION_CARDINALITY:di,STORAGE_LOCATION_TYPES:$o,STREAM_PROFILE_META:Se,STREAM_QUALITY_LABELS:ne,SUB_DETECTION_TYPES:Vo,SYSTEM_CAP_NAMES:fo,ScopedTokenSchema:li,ScopedTokenSummarySchema:ui,SearchResultSchema:hi,SegmentSchema:mi,SendEmailInputSchema:pi,SendEmailResultSchema:fi,SettingsPatchSchema:gi,SettingsRecordSchema:Si,SettingsSchemaWithValuesSchema:bi,SettingsUpdateResultSchema:yi,ShmRingStatsSchema:vi,SmtpStatusSchema:Ci,SnapshotImageSchema:wi,SpatialDetectionSchema:Ii,SsoBridgeClaimsSchema:Ai,StartEmbeddedInputSchema:Ei,StorageAbortUploadInputSchema:_i,StorageBeginDownloadInputSchema:ki,StorageBeginDownloadResultSchema:Pi,StorageBeginUploadInputSchema:Di,StorageBeginUploadResultSchema:Ri,StorageEndDownloadInputSchema:Ni,StorageFinalizeUploadInputSchema:Ti,StorageLocationRefSchema:xi,StorageLocationSchema:Oi,StorageLocationTypeSchema:Mi,StorageProviderInfoSchema:Li,StorageReadChunkInputSchema:Bi,StorageTestLocationResultSchema:$i,StorageWriteChunkInputSchema:Fi,StreamFormatSchema:Ui,StreamInfoSchema:zi,StreamNetworkStatsSchema:Ki,StreamParamsOptionsSchema:Wi,StreamParamsStatusSchema:Hi,StreamProfileConfigSchema:ji,StreamProfileOptionsSchema:Zi,StreamProfilePatchSchema:qi,StreamProfileSchema:Vi,StreamSourceEntrySchema:Gi,StreamSourceSchema:Yi,SubscribeAudioChunksInputSchema:Ji,SubscribeAudioChunksResultSchema:Qi,SubscribeFramesInputSchema:Xi,SubscribeFramesResultSchema:en,SwitchStatusSchema:tn,SystemMetricsSchema:an,SystemMirror:sn,TestConnectionResultSchema:nn,ToastSchema:rn,TokenScopeSchema:on,TopologyNodeSchema:cn,TopologyProcessSchema:dn,TopologyServiceSchema:ln,TrackSchema:un,TrackStateSchema:hn,TrackedDetectionSchema:mn,TurnServerSchema:pn,UpdateIntegrationInputSchema:fn,UpdateUserInputSchema:gn,UserRecordSchema:Sn,UserSummarySchema:bn,WELL_KNOWN_TABS:yn,WELL_KNOWN_TAB_MAP:vn,WebrtcStreamChoiceSchema:Cn,WebrtcStreamTargetSchema:wn,WidgetHostEnum:In,WidgetMetadataSchema:An,WidgetRemoteSchema:En,WidgetSizeEnum:_n,YAMNET_TO_MACRO:kn,ZoneKindEnum:Pn,ZoneRuleModeEnum:Dn,ZoneRuleSchema:Rn,ZoneRuleStageEnum:Nn,ZoneRulesArraySchema:Tn,ZoneSchema:xn,ZoneScopeBreakdownSchema:On,accessoriesCapability:Mn,accessoryStableId:Ln,addonPagesCapability:Bn,addonPagesSourceCapability:$n,addonRoutesCapability:Fn,addonSettingsCapability:Un,addonWidgetsCapability:zn,addonWidgetsSourceCapability:Kn,addonsCapability:Wn,adminUiCapability:Hn,advancedNotifierCapability:jn,alertsCapability:Zn,asBoolean:ac,asJsonArray:Xo,asJsonObject:le,asNumber:tc,asString:ec,audioAnalysisCapability:qn,audioAnalyzerCapability:Vn,audioCodecCapability:Gn,audioMetricsCapability:J,authProviderCapability:Yn,autoAssignProfiles:Zo,backupCapability:Jn,batteryCapability:Y,bindAddonActions:Vc,brightnessCapability:G,buildAddonRouteProvider:No,buildStreamParamsConfigSchema:$c,cameraCredentialsCapability:Qn,cameraStreamsCapability:V,classifyStream:zo,classifyStreams:oe,cosineSimilarity:rc,createDeviceProxy:Xn,createEvent:N,createLazyTrpcSource:er,createMirrorSource:tr,createRuntimeStateBridge:wc,createSliceHandle:ar,createSystemProxy:sr,customAction:Lc,decoderCapability:ir,defineCustomActions:Mc,detectionPipelineCapability:nr,deviceDiscoveryCapability:q,deviceExportCapability:rr,deviceManagerCapability:or,deviceMatchesProfile:cr,deviceOpsCapability:dr,deviceProviderCapability:Q,deviceStateCapability:lr,deviceStatusCapability:R,doorbellCapability:Z,embeddingEncoderCapability:ur,emitDownForOwnedCaps:Bo,emitReadiness:te,errMsg:pe,evaluateZoneRules:xc,event:hr,eventsCapability:mr,expandCapMethods:pr,featureProbeCapability:D,formatForBackend:uc,formatForRuntime:hc,getAudioMacroClassIds:fr,getCapsByProviderKind:Wc,hfModelUrl:nc,hydrateSchema:P,integrationsCapability:gr,intercomCapability:Sr,isAgentOnlyPlacement:_o,isDeployableToAgent:Eo,isDeviceConfigCap:br,isEvent:Ro,localNetworkCapability:yr,logDestinationCapability:vr,mapAudioLabelToMacro:Cr,maskUrlCredentials:Zc,meshNetworkCapability:wr,method:Ir,metricsProviderCapability:Ar,motionCapability:j,motionDetectionCapability:Er,motionTriggerCapability:H,motionZonesCapability:W,mqttBrokerCapability:_r,nativeObjectDetectionCapability:kr,networkAccessCapability:Pr,networkQualityCapability:Dr,nodesCapability:Rr,normalizeAddonInitResult:se,notificationOutputCapability:Nr,oauthIntegrationCapability:Tr,osdCapability:xr,parseCameraStreamConfig:jo,parseJsonArray:ic,parseJsonObject:sc,parseJsonUnknown:T,parseStreamParamsFormPatch:Fc,pipelineAnalyticsCapability:Or,pipelineExecutorCapability:Mr,pipelineOrchestratorCapability:Lr,pipelineRunnerCapability:Br,platformProbeCapability:$r,ptzAutotrackCapability:K,ptzCapability:Fr,pythonScriptForBackend:mc,readinessKey:C,rebootCapability:Ur,recordingCapability:zr,recordingEngineCapability:Kr,requiresPython:pc,resolveAddonExecution:y,resolveAddonGroup:ko,resolveAddonPlacement:Do,resolveAddonRuntime:lc,resolveDetectionRuntime:me,resolveDeviceProfile:Wr,resolveModelFormat:dc,resolveRunnerId:Po,restreamerCapability:Hr,runInferenceStep:fc,scopeKey:f,settingsStoreCapability:jr,smtpProviderCapability:Zr,snapshotCapability:qr,snapshotProviderCapability:Vr,ssoBridgeCapability:Gr,storageCapability:Yr,storageProviderCapability:Jr,streamBrokerCapability:Qr,streamParamsCapability:z,streamPixels:re,streamQualityLabel:Uo,streamingEngineCapability:Xr,switchCapability:U,systemCapability:eo,toDeviceSummary:fe,toStreamSourceEntry:Ko,toastCapability:to,turnProviderCapability:ao,userManagementCapability:so,userPasskeysCapability:io,webrtcCapability:no,webrtcClientHintsSchema:ro,webrtcSessionCapability:oo,zodEntriesToConfigUI:_c,zoneAnalyticsCapability:F,zoneRulesCapability:$,zonesCapability:B},Symbol.toStringTag,{value:"Module"}));export{be as C,$o as S,le as a,Qc as s};