@camstack/addon-admin-ui 0.1.40 → 0.1.47

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 (50) hide show
  1. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-Cv6qLu_-.js → __mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs-CawbgE5L.js} +1 -1
  2. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-CChEG9e0.js → __mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-GKALXIcl.js} +1 -1
  3. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-C1BmHlGM.js → __mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs-JVZxVBTk.js} +1 -1
  4. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-Bxv_3KWz.js → __mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-fDAP1KhM.js} +1 -1
  5. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs-DC63qZbr.js → __mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs-hk6goaRc.js} +1 -1
  6. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs_commonjs-proxy-D2C49VyZ.js → __mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs_commonjs-proxy-CKOygvIQ.js} +1 -1
  7. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs-D3WbXy3O.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs-DGvrhOC3.js} +1 -1
  8. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-Csg6EbPB.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-DG9hE2tk.js} +1 -1
  9. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-CUc0oFNo.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs-ByazpYAv.js} +1 -1
  10. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs_commonjs-proxy-vh0hhA5d.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs_commonjs-proxy-CxaW4xr1.js} +1 -1
  11. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.mjs-CpGtTxci.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.mjs-BLBZm4ju.js} +2 -2
  12. package/dist/assets/{__mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.mjs_commonjs-proxy-RUDPE9aM.js → __mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.mjs_commonjs-proxy-LyTotJxo.js} +1 -1
  13. package/dist/assets/{_virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-yD7UmaAo.js → _virtual_mf-localSharedImportMap___mfe_internal__admin_ui_host-C3ppGtyE.js} +1 -1
  14. package/dist/assets/{devices-a77yscD5.js → devices-DmCyuEuQ.js} +1 -1
  15. package/dist/assets/{hostInit-DaDF_bfJ.js → hostInit-BhyqZ3AI.js} +1 -1
  16. package/dist/assets/index-BH5Ezf7x.js +1 -0
  17. package/dist/assets/index-BPRNeJ5M.js +126 -0
  18. package/dist/assets/index-BViRW9IB.js +1 -0
  19. package/dist/assets/index-BpGkKz46.js +1 -0
  20. package/dist/assets/index-C2d2NdfQ.css +1 -0
  21. package/dist/assets/index-C9MS3ovr.js +1 -0
  22. package/dist/assets/index-CAZNi1Jm.js +1 -0
  23. package/dist/assets/index-CDGj60rb.js +190 -0
  24. package/dist/assets/index-DBG7Fygw.js +1 -0
  25. package/dist/assets/index-DeFTFjpg.js +1514 -0
  26. package/dist/assets/{index-CehI0ALS.js → index-DuP0eN9F.js} +1 -1
  27. package/dist/assets/index-na_oszC9.js +1 -0
  28. package/dist/assets/method-access-map-BCPBTC0g.js +1 -0
  29. package/dist/assets/{remoteEntry-VsZWB5do.js → remoteEntry-0I-ik-5b.js} +1 -1
  30. package/dist/assets/{schemas-BEt-CulV.js → schemas-DSjJ1TGP.js} +5 -5
  31. package/dist/assets/{virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-VQvlRqZ-.js → virtual_mf-REMOTE_ENTRY_ID___mfe_internal__admin_ui_host__remoteEntry-_hash_-ChhI9HQF.js} +2 -2
  32. package/dist/index.html +172 -9
  33. package/dist/mf-entry-bootstrap-0.js +2 -2
  34. package/dist/server/addon.js +3975 -838
  35. package/dist/server/addon.js.map +1 -1
  36. package/dist/sw.js +1 -1
  37. package/package.json +2 -1
  38. package/dist/assets/index-C8NE-4Ma.js +0 -1
  39. package/dist/assets/index-COoei6lw.css +0 -1
  40. package/dist/assets/index-D4yaxCPF.js +0 -87
  41. package/dist/assets/index-DAMgd5aW.js +0 -1
  42. package/dist/assets/index-DAenO2kJ.js +0 -151
  43. package/dist/assets/index-DVUREV1A.js +0 -1
  44. package/dist/assets/index-DWdPkQ_j.js +0 -1
  45. package/dist/assets/index-Dj1ZxUR8.js +0 -1150
  46. package/dist/assets/index-DsOnjZM4.js +0 -1
  47. package/dist/assets/index-EjW6hqu2.js +0 -1
  48. package/dist/assets/index-IsVfuhTX.js +0 -1
  49. package/dist/assets/method-access-map-BgqTQNPE.js +0 -1
  50. package/dist/registerSW.js +0 -1
@@ -0,0 +1,190 @@
1
+ import{b as KH,g as WH}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs-C_6K4VBY.js";import{r as Sw}from"./__mfe_internal__admin_ui_host__loadShare__react__loadShare__.mjs_commonjs-proxy-CKOygvIQ.js";import{r as _w}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_1_jsx_mf_2_runtime__loadShare__.mjs_commonjs-proxy-DrLZNXOX.js";import{r as qH}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom__loadShare__.mjs_commonjs-proxy-DG9hE2tk.js";import{r as QH}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_dom_mf_1_client__loadShare__.mjs_commonjs-proxy-CxaW4xr1.js";import{r as YH}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_tanstack_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-GKALXIcl.js";import{r as XH}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_client__loadShare__.mjs_commonjs-proxy-WD2WouMQ.js";import{r as JH}from"./__mfe_internal__admin_ui_host__loadShare___mf_0_trpc_mf_1_react_mf_2_query__loadShare__.mjs_commonjs-proxy-fDAP1KhM.js";import{r as eK}from"./__mfe_internal__admin_ui_host__loadShare__react_mf_2_konva__loadShare__.mjs_commonjs-proxy-LyTotJxo.js";import{r as tK}from"./__mfe_internal__admin_ui_host__loadShare__konva__loadShare__.mjs_commonjs-proxy-Bqeq2Zwj.js";import{r as rK}from"./index-DuP0eN9F.js";import{s as nK}from"./index-C9MS3ovr.js";function iK(o,_){for(var R=0;R<_.length;R++){const F=_[R];if(typeof F!="string"&&!Array.isArray(F)){for(const P in F)if(P!=="default"&&!(P in o)){const D=Object.getOwnPropertyDescriptor(F,P);D&&Object.defineProperty(o,P,D.get?D:{enumerable:!0,get:()=>F[P]})}}}return Object.freeze(Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}))}var vg={},bg={},fw;function sK(){return fw||(fw=1,(function(o){Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),Vw();let _=Sw,R=_w;var F={frigate:"#3b82f6",scrypted:"#a855f7",reolink:"#06b6d4",homeAssistant:"#22d3ee",rtsp:"#78716c"},P={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:F},D={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:F},V={colors:{dark:P,light:D},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 J(Le,ot){const tt={...Le};for(const _t in ot){const Kt=ot[_t],cr=Le[_t];Kt!==void 0&&typeof Kt=="object"&&Kt!==null&&!Array.isArray(Kt)&&typeof cr=="object"&&cr!==null?tt[_t]=J(cr,Kt):Kt!==void 0&&(tt[_t]=Kt)}return tt}function b(Le){return Le?J(structuredClone(V),Le):structuredClone(V)}function v(Le){return Le.replace(/[A-Z]/g,ot=>`-${ot.toLowerCase()}`)}function x(Le){return`--color-${v(Le)}`}function w(Le){const ot=[];for(const[tt,_t]of Object.entries(Le))tt!=="provider"&&ot.push(` ${x(tt)}: ${_t};`);return ot.join(`
2
+ `)}function l(Le){const ot=[];for(const[tt,_t]of Object.entries(Le))ot.push(` --color-provider-${v(tt)}: ${_t};`);return ot.join(`
3
+ `)}function i(Le){const ot=[];for(const[tt,_t]of Object.entries(Le))ot.push(` --spacing-${tt}: ${_t}px;`);return ot.join(`
4
+ `)}function I(Le){const ot=[];for(const[tt,_t]of Object.entries(Le))ot.push(` --radius-${tt}: ${_t}px;`);return ot.join(`
5
+ `)}function Z(Le){const ot=w(Le.colors.dark),tt=w(Le.colors.light);return`@theme {
6
+ ${l(Le.colors.dark.provider)}
7
+ ${i(Le.spacing)}
8
+ ${I(Le.radius)}
9
+ }
10
+
11
+ .dark {
12
+ ${ot}
13
+ }
14
+
15
+ .light {
16
+ ${tt}
17
+ }
18
+
19
+ @media (prefers-color-scheme: dark) {
20
+ :root {
21
+ ${ot.replace(/^ {2}/gm," ")}
22
+ }
23
+ }
24
+
25
+ @media (prefers-color-scheme: light) {
26
+ :root {
27
+ ${tt.replace(/^ {2}/gm," ")}
28
+ }
29
+ }
30
+ `}var ye=(0,_.createContext)(null),ve=["dark","light","system"];function Te(){return typeof window>"u"||window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}function _e(Le,ot){if(typeof window>"u")return ot;const tt=localStorage.getItem(Le);return tt==="dark"||tt==="light"||tt==="system"?tt:ot}function Oe(Le){return Le==="system"?Te():Le}function W({children:Le,defaultMode:ot="system",storageKey:tt="camstack-theme-mode"}){const[_t,Kt]=(0,_.useState)(()=>_e(tt,ot)),[cr,kr]=(0,_.useState)(()=>Oe(_t)),Tr=(0,_.useCallback)(Qt=>{Kt(Qt),kr(Oe(Qt)),typeof window<"u"&&localStorage.setItem(tt,Qt)},[tt]),Ir=(0,_.useCallback)(()=>{Tr(ve[(ve.indexOf(_t)+1)%ve.length]??"dark")},[_t,Tr]);(0,_.useEffect)(()=>{if(typeof document>"u")return;const Qt=document.documentElement;Qt.classList.remove("dark","light"),Qt.classList.add(cr)},[_t,cr]),(0,_.useEffect)(()=>{if(typeof window>"u"||_t!=="system")return;const Qt=window.matchMedia("(prefers-color-scheme: dark)"),Or=()=>{kr(Te())};return Qt.addEventListener("change",Or),()=>Qt.removeEventListener("change",Or)},[_t]);const Dr=(0,_.useMemo)(()=>({mode:_t,resolvedMode:cr,setMode:Tr,toggleMode:Ir}),[_t,cr,Tr,Ir]);return(0,R.jsx)(ye.Provider,{value:Dr,children:Le})}function Ze(){const Le=(0,_.useContext)(ye);if(!Le)throw new Error("useThemeMode must be used within a ThemeProvider");return Le}o.ThemeProvider=W,o.ThemeProvider$1=W,o.createTheme=b,o.createTheme$1=b,o.darkColors=P,o.darkColors$1=P,o.defaultTheme=V,o.defaultTheme$1=V,o.lightColors=D,o.lightColors$1=D,o.themeToCss=Z,o.themeToCss$1=Z,o.useThemeMode=Ze,o.useThemeMode$1=Ze})(bg)),bg}const aK=KH(nK);var Dn={},Wr={},sr={},Ki={};(function(o){var _;Object.defineProperty(o,"__esModule",{value:!0}),o.globalConfig=o.$ZodEncodeError=o.$ZodAsyncError=o.$brand=o.NEVER=void 0,o.$constructor=R,o.config=D,o.NEVER=Object.freeze({status:"aborted"});function R(V,J,b){function v(i,I){if(i._zod||Object.defineProperty(i,"_zod",{value:{def:I,constr:l,traits:new Set},enumerable:!1}),i._zod.traits.has(V))return;i._zod.traits.add(V),J(i,I);const Z=l.prototype,ye=Object.keys(Z);for(let ve=0;ve<ye.length;ve++){const Te=ye[ve];Te in i||(i[Te]=Z[Te].bind(i))}}const x=b?.Parent??Object;class w extends x{}Object.defineProperty(w,"name",{value:V});function l(i){var I;const Z=b?.Parent?new w:this;v(Z,i),(I=Z._zod).deferred??(I.deferred=[]);for(const ye of Z._zod.deferred)ye();return Z}return Object.defineProperty(l,"init",{value:v}),Object.defineProperty(l,Symbol.hasInstance,{value:i=>b?.Parent&&i instanceof b.Parent?!0:i?._zod?.traits?.has(V)}),Object.defineProperty(l,"name",{value:V}),l}o.$brand=Symbol("zod_brand");class F extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}o.$ZodAsyncError=F;class P extends Error{constructor(J){super(`Encountered unidirectional transform during encode: ${J}`),this.name="ZodEncodeError"}}o.$ZodEncodeError=P,(_=globalThis).__zod_globalConfig??(_.__zod_globalConfig={}),o.globalConfig=globalThis.__zod_globalConfig;function D(V){return V&&Object.assign(o.globalConfig,V),o.globalConfig}})(Ki);var Yn={},yr={},Ie={};Object.defineProperty(Ie,"__esModule",{value:!0});Ie.Class=Ie.BIGINT_FORMAT_RANGES=Ie.NUMBER_FORMAT_RANGES=Ie.primitiveTypes=Ie.propertyKeyTypes=Ie.getParsedType=Ie.allowsEval=Ie.captureStackTrace=void 0;Ie.assertEqual=lK;Ie.assertNotEqual=cK;Ie.assertIs=uK;Ie.assertNever=dK;Ie.assert=fK;Ie.getEnumValues=hK;Ie.joinValues=mK;Ie.jsonStringifyReplacer=gK;Ie.cached=ww;Ie.nullish=pK;Ie.cleanRegex=vK;Ie.floatSafeRemainder=bK;Ie.defineLazy=yK;Ie.objectClone=xK;Ie.assignProp=bi;Ie.mergeDefs=ei;Ie.cloneDef=SK;Ie.getElementAtPath=_K;Ie.promiseAllObject=wK;Ie.randomString=EK;Ie.esc=kK;Ie.slugify=TK;Ie.isObject=yg;Ie.isPlainObject=Xu;Ie.shallowClone=CK;Ie.numKeys=IK;Ie.escapeRegex=AK;Ie.clone=yi;Ie.normalizeParams=jK;Ie.createTransparentProxy=NK;Ie.stringifyPrimitive=Ew;Ie.optionalKeys=DK;Ie.pick=MK;Ie.omit=$K;Ie.extend=RK;Ie.safeExtend=LK;Ie.merge=OK;Ie.partial=FK;Ie.required=UK;Ie.aborted=BK;Ie.explicitlyAborted=zK;Ie.prefixIssues=GK;Ie.unwrapMessage=Fo;Ie.finalizeIssue=ZK;Ie.getSizableOrigin=VK;Ie.getLengthableOrigin=HK;Ie.parsedType=KK;Ie.issue=WK;Ie.cleanEnum=qK;Ie.base64ToUint8Array=kw;Ie.uint8ArrayToBase64=Tw;Ie.base64urlToUint8Array=QK;Ie.uint8ArrayToBase64url=YK;Ie.hexToUint8Array=XK;Ie.uint8ArrayToHex=JK;const oK=Ki;function lK(o){return o}function cK(o){return o}function uK(o){}function dK(o){throw new Error("Unexpected value in exhaustive check")}function fK(o){}function hK(o){const _=Object.values(o).filter(F=>typeof F=="number");return Object.entries(o).filter(([F,P])=>_.indexOf(+F)===-1).map(([F,P])=>P)}function mK(o,_="|"){return o.map(R=>Ew(R)).join(_)}function gK(o,_){return typeof _=="bigint"?_.toString():_}function ww(o){return{get value(){{const _=o();return Object.defineProperty(this,"value",{value:_}),_}}}}function pK(o){return o==null}function vK(o){const _=o.startsWith("^")?1:0,R=o.endsWith("$")?o.length-1:o.length;return o.slice(_,R)}function bK(o,_){const R=o/_,F=Math.round(R),P=Number.EPSILON*Math.max(Math.abs(R),1);return Math.abs(R-F)<P?0:R-F}const hw=Symbol("evaluating");function yK(o,_,R){let F;Object.defineProperty(o,_,{get(){if(F!==hw)return F===void 0&&(F=hw,F=R()),F},set(P){Object.defineProperty(o,_,{value:P})},configurable:!0})}function xK(o){return Object.create(Object.getPrototypeOf(o),Object.getOwnPropertyDescriptors(o))}function bi(o,_,R){Object.defineProperty(o,_,{value:R,writable:!0,enumerable:!0,configurable:!0})}function ei(...o){const _={};for(const R of o){const F=Object.getOwnPropertyDescriptors(R);Object.assign(_,F)}return Object.defineProperties({},_)}function SK(o){return ei(o._zod.def)}function _K(o,_){return _?_.reduce((R,F)=>R?.[F],o):o}function wK(o){const _=Object.keys(o),R=_.map(F=>o[F]);return Promise.all(R).then(F=>{const P={};for(let D=0;D<_.length;D++)P[_[D]]=F[D];return P})}function EK(o=10){const _="abcdefghijklmnopqrstuvwxyz";let R="";for(let F=0;F<o;F++)R+=_[Math.floor(Math.random()*_.length)];return R}function kK(o){return JSON.stringify(o)}function TK(o){return o.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}Ie.captureStackTrace="captureStackTrace"in Error?Error.captureStackTrace:(...o)=>{};function yg(o){return typeof o=="object"&&o!==null&&!Array.isArray(o)}Ie.allowsEval=ww(()=>{if(oK.globalConfig.jitless||typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{const o=Function;return new o(""),!0}catch{return!1}});function Xu(o){if(yg(o)===!1)return!1;const _=o.constructor;if(_===void 0||typeof _!="function")return!0;const R=_.prototype;return!(yg(R)===!1||Object.prototype.hasOwnProperty.call(R,"isPrototypeOf")===!1)}function CK(o){return Xu(o)?{...o}:Array.isArray(o)?[...o]:o instanceof Map?new Map(o):o instanceof Set?new Set(o):o}function IK(o){let _=0;for(const R in o)Object.prototype.hasOwnProperty.call(o,R)&&_++;return _}const PK=o=>{const _=typeof o;switch(_){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(o)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(o)?"array":o===null?"null":o.then&&typeof o.then=="function"&&o.catch&&typeof o.catch=="function"?"promise":typeof Map<"u"&&o instanceof Map?"map":typeof Set<"u"&&o instanceof Set?"set":typeof Date<"u"&&o instanceof Date?"date":typeof File<"u"&&o instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${_}`)}};Ie.getParsedType=PK;Ie.propertyKeyTypes=new Set(["string","number","symbol"]);Ie.primitiveTypes=new Set(["string","number","bigint","boolean","symbol","undefined"]);function AK(o){return o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yi(o,_,R){const F=new o._zod.constr(_??o._zod.def);return(!_||R?.parent)&&(F._zod.parent=o),F}function jK(o){const _=o;if(!_)return{};if(typeof _=="string")return{error:()=>_};if(_?.message!==void 0){if(_?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");_.error=_.message}return delete _.message,typeof _.error=="string"?{..._,error:()=>_.error}:_}function NK(o){let _;return new Proxy({},{get(R,F,P){return _??(_=o()),Reflect.get(_,F,P)},set(R,F,P,D){return _??(_=o()),Reflect.set(_,F,P,D)},has(R,F){return _??(_=o()),Reflect.has(_,F)},deleteProperty(R,F){return _??(_=o()),Reflect.deleteProperty(_,F)},ownKeys(R){return _??(_=o()),Reflect.ownKeys(_)},getOwnPropertyDescriptor(R,F){return _??(_=o()),Reflect.getOwnPropertyDescriptor(_,F)},defineProperty(R,F,P){return _??(_=o()),Reflect.defineProperty(_,F,P)}})}function Ew(o){return typeof o=="bigint"?o.toString()+"n":typeof o=="string"?`"${o}"`:`${o}`}function DK(o){return Object.keys(o).filter(_=>o[_]._zod.optin==="optional"&&o[_]._zod.optout==="optional")}Ie.NUMBER_FORMAT_RANGES={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};Ie.BIGINT_FORMAT_RANGES={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function MK(o,_){const R=o._zod.def,F=R.checks;if(F&&F.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const D=ei(o._zod.def,{get shape(){const V={};for(const J in _){if(!(J in R.shape))throw new Error(`Unrecognized key: "${J}"`);_[J]&&(V[J]=R.shape[J])}return bi(this,"shape",V),V},checks:[]});return yi(o,D)}function $K(o,_){const R=o._zod.def,F=R.checks;if(F&&F.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const D=ei(o._zod.def,{get shape(){const V={...o._zod.def.shape};for(const J in _){if(!(J in R.shape))throw new Error(`Unrecognized key: "${J}"`);_[J]&&delete V[J]}return bi(this,"shape",V),V},checks:[]});return yi(o,D)}function RK(o,_){if(!Xu(_))throw new Error("Invalid input to extend: expected a plain object");const R=o._zod.def.checks;if(R&&R.length>0){const D=o._zod.def.shape;for(const V in _)if(Object.getOwnPropertyDescriptor(D,V)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const P=ei(o._zod.def,{get shape(){const D={...o._zod.def.shape,..._};return bi(this,"shape",D),D}});return yi(o,P)}function LK(o,_){if(!Xu(_))throw new Error("Invalid input to safeExtend: expected a plain object");const R=ei(o._zod.def,{get shape(){const F={...o._zod.def.shape,..._};return bi(this,"shape",F),F}});return yi(o,R)}function OK(o,_){if(o._zod.def.checks?.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const R=ei(o._zod.def,{get shape(){const F={...o._zod.def.shape,..._._zod.def.shape};return bi(this,"shape",F),F},get catchall(){return _._zod.def.catchall},checks:_._zod.def.checks??[]});return yi(o,R)}function FK(o,_,R){const P=_._zod.def.checks;if(P&&P.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const V=ei(_._zod.def,{get shape(){const J=_._zod.def.shape,b={...J};if(R)for(const v in R){if(!(v in J))throw new Error(`Unrecognized key: "${v}"`);R[v]&&(b[v]=o?new o({type:"optional",innerType:J[v]}):J[v])}else for(const v in J)b[v]=o?new o({type:"optional",innerType:J[v]}):J[v];return bi(this,"shape",b),b},checks:[]});return yi(_,V)}function UK(o,_,R){const F=ei(_._zod.def,{get shape(){const P=_._zod.def.shape,D={...P};if(R)for(const V in R){if(!(V in D))throw new Error(`Unrecognized key: "${V}"`);R[V]&&(D[V]=new o({type:"nonoptional",innerType:P[V]}))}else for(const V in P)D[V]=new o({type:"nonoptional",innerType:P[V]});return bi(this,"shape",D),D}});return yi(_,F)}function BK(o,_=0){if(o.aborted===!0)return!0;for(let R=_;R<o.issues.length;R++)if(o.issues[R]?.continue!==!0)return!0;return!1}function zK(o,_=0){if(o.aborted===!0)return!0;for(let R=_;R<o.issues.length;R++)if(o.issues[R]?.continue===!1)return!0;return!1}function GK(o,_){return _.map(R=>{var F;return(F=R).path??(F.path=[]),R.path.unshift(o),R})}function Fo(o){return typeof o=="string"?o:o?.message}function ZK(o,_,R){const F=o.message?o.message:Fo(o.inst?._zod.def?.error?.(o))??Fo(_?.error?.(o))??Fo(R.customError?.(o))??Fo(R.localeError?.(o))??"Invalid input",{inst:P,continue:D,input:V,...J}=o;return J.path??(J.path=[]),J.message=F,_?.reportInput&&(J.input=V),J}function VK(o){return o instanceof Set?"set":o instanceof Map?"map":o instanceof File?"file":"unknown"}function HK(o){return Array.isArray(o)?"array":typeof o=="string"?"string":"unknown"}function KK(o){const _=typeof o;switch(_){case"number":return Number.isNaN(o)?"nan":"number";case"object":{if(o===null)return"null";if(Array.isArray(o))return"array";const R=o;if(R&&Object.getPrototypeOf(R)!==Object.prototype&&"constructor"in R&&R.constructor)return R.constructor.name}}return _}function WK(...o){const[_,R,F]=o;return typeof _=="string"?{message:_,code:"custom",input:R,inst:F}:{..._}}function qK(o){return Object.entries(o).filter(([_,R])=>Number.isNaN(Number.parseInt(_,10))).map(_=>_[1])}function kw(o){const _=atob(o),R=new Uint8Array(_.length);for(let F=0;F<_.length;F++)R[F]=_.charCodeAt(F);return R}function Tw(o){let _="";for(let R=0;R<o.length;R++)_+=String.fromCharCode(o[R]);return btoa(_)}function QK(o){const _=o.replace(/-/g,"+").replace(/_/g,"/"),R="=".repeat((4-_.length%4)%4);return kw(_+R)}function YK(o){return Tw(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function XK(o){const _=o.replace(/^0x/,"");if(_.length%2!==0)throw new Error("Invalid hex string length");const R=new Uint8Array(_.length/2);for(let F=0;F<_.length;F+=2)R[F/2]=Number.parseInt(_.slice(F,F+2),16);return R}function JK(o){return Array.from(o).map(_=>_.toString(16).padStart(2,"0")).join("")}class eW{constructor(..._){}}Ie.Class=eW;var tW=yr&&yr.__createBinding||(Object.create?(function(o,_,R,F){F===void 0&&(F=R);var P=Object.getOwnPropertyDescriptor(_,R);(!P||("get"in P?!_.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return _[R]}}),Object.defineProperty(o,F,P)}):(function(o,_,R,F){F===void 0&&(F=R),o[F]=_[R]})),rW=yr&&yr.__setModuleDefault||(Object.create?(function(o,_){Object.defineProperty(o,"default",{enumerable:!0,value:_})}):function(o,_){o.default=_}),nW=yr&&yr.__importStar||function(o){if(o&&o.__esModule)return o;var _={};if(o!=null)for(var R in o)R!=="default"&&Object.prototype.hasOwnProperty.call(o,R)&&tW(_,o,R);return rW(_,o),_};Object.defineProperty(yr,"__esModule",{value:!0});yr.$ZodRealError=yr.$ZodError=void 0;yr.flattenError=sW;yr.formatError=aW;yr.treeifyError=oW;yr.toDotPath=Pw;yr.prettifyError=lW;const Cw=Ki,iW=nW(Ie),Iw=(o,_)=>{o.name="$ZodError",Object.defineProperty(o,"_zod",{value:o._zod,enumerable:!1}),Object.defineProperty(o,"issues",{value:_,enumerable:!1}),o.message=JSON.stringify(_,iW.jsonStringifyReplacer,2),Object.defineProperty(o,"toString",{value:()=>o.message,enumerable:!1})};yr.$ZodError=(0,Cw.$constructor)("$ZodError",Iw);yr.$ZodRealError=(0,Cw.$constructor)("$ZodError",Iw,{Parent:Error});function sW(o,_=R=>R.message){const R={},F=[];for(const P of o.issues)P.path.length>0?(R[P.path[0]]=R[P.path[0]]||[],R[P.path[0]].push(_(P))):F.push(_(P));return{formErrors:F,fieldErrors:R}}function aW(o,_=R=>R.message){const R={_errors:[]},F=(P,D=[])=>{for(const V of P.issues)if(V.code==="invalid_union"&&V.errors.length)V.errors.map(J=>F({issues:J},[...D,...V.path]));else if(V.code==="invalid_key")F({issues:V.issues},[...D,...V.path]);else if(V.code==="invalid_element")F({issues:V.issues},[...D,...V.path]);else{const J=[...D,...V.path];if(J.length===0)R._errors.push(_(V));else{let b=R,v=0;for(;v<J.length;){const x=J[v];v===J.length-1?(b[x]=b[x]||{_errors:[]},b[x]._errors.push(_(V))):b[x]=b[x]||{_errors:[]},b=b[x],v++}}}};return F(o),R}function oW(o,_=R=>R.message){const R={errors:[]},F=(P,D=[])=>{var V,J;for(const b of P.issues)if(b.code==="invalid_union"&&b.errors.length)b.errors.map(v=>F({issues:v},[...D,...b.path]));else if(b.code==="invalid_key")F({issues:b.issues},[...D,...b.path]);else if(b.code==="invalid_element")F({issues:b.issues},[...D,...b.path]);else{const v=[...D,...b.path];if(v.length===0){R.errors.push(_(b));continue}let x=R,w=0;for(;w<v.length;){const l=v[w],i=w===v.length-1;typeof l=="string"?(x.properties??(x.properties={}),(V=x.properties)[l]??(V[l]={errors:[]}),x=x.properties[l]):(x.items??(x.items=[]),(J=x.items)[l]??(J[l]={errors:[]}),x=x.items[l]),i&&x.errors.push(_(b)),w++}}};return F(o),R}function Pw(o){const _=[],R=o.map(F=>typeof F=="object"?F.key:F);for(const F of R)typeof F=="number"?_.push(`[${F}]`):typeof F=="symbol"?_.push(`[${JSON.stringify(String(F))}]`):/[^\w$]/.test(F)?_.push(`[${JSON.stringify(F)}]`):(_.length&&_.push("."),_.push(F));return _.join("")}function lW(o){const _=[],R=[...o.issues].sort((F,P)=>(F.path??[]).length-(P.path??[]).length);for(const F of R)_.push(`✖ ${F.message}`),F.path?.length&&_.push(` → at ${Pw(F.path)}`);return _.join(`
31
+ `)}(function(o){var _=Yn&&Yn.__createBinding||(Object.create?(function(_e,Oe,W,Ze){Ze===void 0&&(Ze=W);var Le=Object.getOwnPropertyDescriptor(Oe,W);(!Le||("get"in Le?!Oe.__esModule:Le.writable||Le.configurable))&&(Le={enumerable:!0,get:function(){return Oe[W]}}),Object.defineProperty(_e,Ze,Le)}):(function(_e,Oe,W,Ze){Ze===void 0&&(Ze=W),_e[Ze]=Oe[W]})),R=Yn&&Yn.__setModuleDefault||(Object.create?(function(_e,Oe){Object.defineProperty(_e,"default",{enumerable:!0,value:Oe})}):function(_e,Oe){_e.default=Oe}),F=Yn&&Yn.__importStar||function(_e){if(_e&&_e.__esModule)return _e;var Oe={};if(_e!=null)for(var W in _e)W!=="default"&&Object.prototype.hasOwnProperty.call(_e,W)&&_(Oe,_e,W);return R(Oe,_e),Oe};Object.defineProperty(o,"__esModule",{value:!0}),o.safeDecodeAsync=o._safeDecodeAsync=o.safeEncodeAsync=o._safeEncodeAsync=o.safeDecode=o._safeDecode=o.safeEncode=o._safeEncode=o.decodeAsync=o._decodeAsync=o.encodeAsync=o._encodeAsync=o.decode=o._decode=o.encode=o._encode=o.safeParseAsync=o._safeParseAsync=o.safeParse=o._safeParse=o.parseAsync=o._parseAsync=o.parse=o._parse=void 0;const P=F(Ki),D=F(yr),V=F(Ie),J=_e=>(Oe,W,Ze,Le)=>{const ot=Ze?{...Ze,async:!1}:{async:!1},tt=Oe._zod.run({value:W,issues:[]},ot);if(tt instanceof Promise)throw new P.$ZodAsyncError;if(tt.issues.length){const _t=new(Le?.Err??_e)(tt.issues.map(Kt=>V.finalizeIssue(Kt,ot,P.config())));throw V.captureStackTrace(_t,Le?.callee),_t}return tt.value};o._parse=J,o.parse=(0,o._parse)(D.$ZodRealError);const b=_e=>async(Oe,W,Ze,Le)=>{const ot=Ze?{...Ze,async:!0}:{async:!0};let tt=Oe._zod.run({value:W,issues:[]},ot);if(tt instanceof Promise&&(tt=await tt),tt.issues.length){const _t=new(Le?.Err??_e)(tt.issues.map(Kt=>V.finalizeIssue(Kt,ot,P.config())));throw V.captureStackTrace(_t,Le?.callee),_t}return tt.value};o._parseAsync=b,o.parseAsync=(0,o._parseAsync)(D.$ZodRealError);const v=_e=>(Oe,W,Ze)=>{const Le=Ze?{...Ze,async:!1}:{async:!1},ot=Oe._zod.run({value:W,issues:[]},Le);if(ot instanceof Promise)throw new P.$ZodAsyncError;return ot.issues.length?{success:!1,error:new(_e??D.$ZodError)(ot.issues.map(tt=>V.finalizeIssue(tt,Le,P.config())))}:{success:!0,data:ot.value}};o._safeParse=v,o.safeParse=(0,o._safeParse)(D.$ZodRealError);const x=_e=>async(Oe,W,Ze)=>{const Le=Ze?{...Ze,async:!0}:{async:!0};let ot=Oe._zod.run({value:W,issues:[]},Le);return ot instanceof Promise&&(ot=await ot),ot.issues.length?{success:!1,error:new _e(ot.issues.map(tt=>V.finalizeIssue(tt,Le,P.config())))}:{success:!0,data:ot.value}};o._safeParseAsync=x,o.safeParseAsync=(0,o._safeParseAsync)(D.$ZodRealError);const w=_e=>(Oe,W,Ze)=>{const Le=Ze?{...Ze,direction:"backward"}:{direction:"backward"};return(0,o._parse)(_e)(Oe,W,Le)};o._encode=w,o.encode=(0,o._encode)(D.$ZodRealError);const l=_e=>(Oe,W,Ze)=>(0,o._parse)(_e)(Oe,W,Ze);o._decode=l,o.decode=(0,o._decode)(D.$ZodRealError);const i=_e=>async(Oe,W,Ze)=>{const Le=Ze?{...Ze,direction:"backward"}:{direction:"backward"};return(0,o._parseAsync)(_e)(Oe,W,Le)};o._encodeAsync=i,o.encodeAsync=(0,o._encodeAsync)(D.$ZodRealError);const I=_e=>async(Oe,W,Ze)=>(0,o._parseAsync)(_e)(Oe,W,Ze);o._decodeAsync=I,o.decodeAsync=(0,o._decodeAsync)(D.$ZodRealError);const Z=_e=>(Oe,W,Ze)=>{const Le=Ze?{...Ze,direction:"backward"}:{direction:"backward"};return(0,o._safeParse)(_e)(Oe,W,Le)};o._safeEncode=Z,o.safeEncode=(0,o._safeEncode)(D.$ZodRealError);const ye=_e=>(Oe,W,Ze)=>(0,o._safeParse)(_e)(Oe,W,Ze);o._safeDecode=ye,o.safeDecode=(0,o._safeDecode)(D.$ZodRealError);const ve=_e=>async(Oe,W,Ze)=>{const Le=Ze?{...Ze,direction:"backward"}:{direction:"backward"};return(0,o._safeParseAsync)(_e)(Oe,W,Le)};o._safeEncodeAsync=ve,o.safeEncodeAsync=(0,o._safeEncodeAsync)(D.$ZodRealError);const Te=_e=>async(Oe,W,Ze)=>(0,o._safeParseAsync)(_e)(Oe,W,Ze);o._safeDecodeAsync=Te,o.safeDecodeAsync=(0,o._safeDecodeAsync)(D.$ZodRealError)})(Yn);var Xn={},Mn={},$n={};(function(o){var _=$n&&$n.__createBinding||(Object.create?(function(Te,_e,Oe,W){W===void 0&&(W=Oe);var Ze=Object.getOwnPropertyDescriptor(_e,Oe);(!Ze||("get"in Ze?!_e.__esModule:Ze.writable||Ze.configurable))&&(Ze={enumerable:!0,get:function(){return _e[Oe]}}),Object.defineProperty(Te,W,Ze)}):(function(Te,_e,Oe,W){W===void 0&&(W=Oe),Te[W]=_e[Oe]})),R=$n&&$n.__setModuleDefault||(Object.create?(function(Te,_e){Object.defineProperty(Te,"default",{enumerable:!0,value:_e})}):function(Te,_e){Te.default=_e}),F=$n&&$n.__importStar||function(Te){if(Te&&Te.__esModule)return Te;var _e={};if(Te!=null)for(var Oe in Te)Oe!=="default"&&Object.prototype.hasOwnProperty.call(Te,Oe)&&_(_e,Te,Oe);return R(_e,Te),_e};Object.defineProperty(o,"__esModule",{value:!0}),o.sha256_base64url=o.sha256_base64=o.sha256_hex=o.sha1_base64url=o.sha1_base64=o.sha1_hex=o.md5_base64url=o.md5_base64=o.md5_hex=o.hex=o.uppercase=o.lowercase=o.undefined=o.null=o.boolean=o.number=o.integer=o.bigint=o.string=o.date=o.e164=o.httpProtocol=o.domain=o.hostname=o.base64url=o.base64=o.cidrv6=o.cidrv4=o.mac=o.ipv6=o.ipv4=o.browserEmail=o.idnEmail=o.unicodeEmail=o.rfc5322Email=o.html5Email=o.email=o.uuid7=o.uuid6=o.uuid4=o.uuid=o.guid=o.extendedDuration=o.duration=o.nanoid=o.ksuid=o.xid=o.ulid=o.cuid2=o.cuid=void 0,o.sha512_base64url=o.sha512_base64=o.sha512_hex=o.sha384_base64url=o.sha384_base64=o.sha384_hex=void 0,o.emoji=J,o.time=w,o.datetime=l;const P=F(Ie);o.cuid=/^[cC][0-9a-z]{6,}$/,o.cuid2=/^[0-9a-z]+$/,o.ulid=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,o.xid=/^[0-9a-vA-V]{20}$/,o.ksuid=/^[A-Za-z0-9]{27}$/,o.nanoid=/^[a-zA-Z0-9_-]{21}$/,o.duration=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,o.extendedDuration=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,o.guid=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/;const D=Te=>Te?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${Te}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;o.uuid=D,o.uuid4=(0,o.uuid)(4),o.uuid6=(0,o.uuid)(6),o.uuid7=(0,o.uuid)(7),o.email=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,o.html5Email=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,o.rfc5322Email=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,o.unicodeEmail=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,o.idnEmail=o.unicodeEmail,o.browserEmail=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;const V="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function J(){return new RegExp(V,"u")}o.ipv4=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,o.ipv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;const b=Te=>{const _e=P.escapeRegex(Te??":");return new RegExp(`^(?:[0-9A-F]{2}${_e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${_e}){5}[0-9a-f]{2}$`)};o.mac=b,o.cidrv4=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,o.cidrv6=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,o.base64=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,o.base64url=/^[A-Za-z0-9_-]*$/,o.hostname=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,o.domain=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,o.httpProtocol=/^https?$/,o.e164=/^\+[1-9]\d{6,14}$/;const v="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";o.date=new RegExp(`^${v}$`);function x(Te){const _e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof Te.precision=="number"?Te.precision===-1?`${_e}`:Te.precision===0?`${_e}:[0-5]\\d`:`${_e}:[0-5]\\d\\.\\d{${Te.precision}}`:`${_e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function w(Te){return new RegExp(`^${x(Te)}$`)}function l(Te){const _e=x({precision:Te.precision}),Oe=["Z"];Te.local&&Oe.push(""),Te.offset&&Oe.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const W=`${_e}(?:${Oe.join("|")})`;return new RegExp(`^${v}T(?:${W})$`)}const i=Te=>{const _e=Te?`[\\s\\S]{${Te?.minimum??0},${Te?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${_e}$`)};o.string=i,o.bigint=/^-?\d+n?$/,o.integer=/^-?\d+$/,o.number=/^-?\d+(?:\.\d+)?$/,o.boolean=/^(?:true|false)$/i;const I=/^null$/i;o.null=I;const Z=/^undefined$/i;o.undefined=Z,o.lowercase=/^[^A-Z]*$/,o.uppercase=/^[^a-z]*$/,o.hex=/^[0-9a-fA-F]*$/;function ye(Te,_e){return new RegExp(`^[A-Za-z0-9+/]{${Te}}${_e}$`)}function ve(Te){return new RegExp(`^[A-Za-z0-9_-]{${Te}}$`)}o.md5_hex=/^[0-9a-fA-F]{32}$/,o.md5_base64=ye(22,"=="),o.md5_base64url=ve(22),o.sha1_hex=/^[0-9a-fA-F]{40}$/,o.sha1_base64=ye(27,"="),o.sha1_base64url=ve(27),o.sha256_hex=/^[0-9a-fA-F]{64}$/,o.sha256_base64=ye(43,"="),o.sha256_base64url=ve(43),o.sha384_hex=/^[0-9a-fA-F]{96}$/,o.sha384_base64=ye(64,""),o.sha384_base64url=ve(64),o.sha512_hex=/^[0-9a-fA-F]{128}$/,o.sha512_base64=ye(86,"=="),o.sha512_base64url=ve(86)})($n);(function(o){var _=Mn&&Mn.__createBinding||(Object.create?(function(v,x,w,l){l===void 0&&(l=w);var i=Object.getOwnPropertyDescriptor(x,w);(!i||("get"in i?!x.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return x[w]}}),Object.defineProperty(v,l,i)}):(function(v,x,w,l){l===void 0&&(l=w),v[l]=x[w]})),R=Mn&&Mn.__setModuleDefault||(Object.create?(function(v,x){Object.defineProperty(v,"default",{enumerable:!0,value:x})}):function(v,x){v.default=x}),F=Mn&&Mn.__importStar||function(v){if(v&&v.__esModule)return v;var x={};if(v!=null)for(var w in v)w!=="default"&&Object.prototype.hasOwnProperty.call(v,w)&&_(x,v,w);return R(x,v),x};Object.defineProperty(o,"__esModule",{value:!0}),o.$ZodCheckOverwrite=o.$ZodCheckMimeType=o.$ZodCheckProperty=o.$ZodCheckEndsWith=o.$ZodCheckStartsWith=o.$ZodCheckIncludes=o.$ZodCheckUpperCase=o.$ZodCheckLowerCase=o.$ZodCheckRegex=o.$ZodCheckStringFormat=o.$ZodCheckLengthEquals=o.$ZodCheckMinLength=o.$ZodCheckMaxLength=o.$ZodCheckSizeEquals=o.$ZodCheckMinSize=o.$ZodCheckMaxSize=o.$ZodCheckBigIntFormat=o.$ZodCheckNumberFormat=o.$ZodCheckMultipleOf=o.$ZodCheckGreaterThan=o.$ZodCheckLessThan=o.$ZodCheck=void 0;const P=F(Ki),D=F($n),V=F(Ie);o.$ZodCheck=P.$constructor("$ZodCheck",(v,x)=>{var w;v._zod??(v._zod={}),v._zod.def=x,(w=v._zod).onattach??(w.onattach=[])});const J={number:"number",bigint:"bigint",object:"date"};o.$ZodCheckLessThan=P.$constructor("$ZodCheckLessThan",(v,x)=>{o.$ZodCheck.init(v,x);const w=J[typeof x.value];v._zod.onattach.push(l=>{const i=l._zod.bag,I=(x.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;x.value<I&&(x.inclusive?i.maximum=x.value:i.exclusiveMaximum=x.value)}),v._zod.check=l=>{(x.inclusive?l.value<=x.value:l.value<x.value)||l.issues.push({origin:w,code:"too_big",maximum:typeof x.value=="object"?x.value.getTime():x.value,input:l.value,inclusive:x.inclusive,inst:v,continue:!x.abort})}}),o.$ZodCheckGreaterThan=P.$constructor("$ZodCheckGreaterThan",(v,x)=>{o.$ZodCheck.init(v,x);const w=J[typeof x.value];v._zod.onattach.push(l=>{const i=l._zod.bag,I=(x.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;x.value>I&&(x.inclusive?i.minimum=x.value:i.exclusiveMinimum=x.value)}),v._zod.check=l=>{(x.inclusive?l.value>=x.value:l.value>x.value)||l.issues.push({origin:w,code:"too_small",minimum:typeof x.value=="object"?x.value.getTime():x.value,input:l.value,inclusive:x.inclusive,inst:v,continue:!x.abort})}}),o.$ZodCheckMultipleOf=P.$constructor("$ZodCheckMultipleOf",(v,x)=>{o.$ZodCheck.init(v,x),v._zod.onattach.push(w=>{var l;(l=w._zod.bag).multipleOf??(l.multipleOf=x.value)}),v._zod.check=w=>{if(typeof w.value!=typeof x.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof w.value=="bigint"?w.value%x.value===BigInt(0):V.floatSafeRemainder(w.value,x.value)===0)||w.issues.push({origin:typeof w.value,code:"not_multiple_of",divisor:x.value,input:w.value,inst:v,continue:!x.abort})}}),o.$ZodCheckNumberFormat=P.$constructor("$ZodCheckNumberFormat",(v,x)=>{o.$ZodCheck.init(v,x),x.format=x.format||"float64";const w=x.format?.includes("int"),l=w?"int":"number",[i,I]=V.NUMBER_FORMAT_RANGES[x.format];v._zod.onattach.push(Z=>{const ye=Z._zod.bag;ye.format=x.format,ye.minimum=i,ye.maximum=I,w&&(ye.pattern=D.integer)}),v._zod.check=Z=>{const ye=Z.value;if(w){if(!Number.isInteger(ye)){Z.issues.push({expected:l,format:x.format,code:"invalid_type",continue:!1,input:ye,inst:v});return}if(!Number.isSafeInteger(ye)){ye>0?Z.issues.push({input:ye,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:v,origin:l,inclusive:!0,continue:!x.abort}):Z.issues.push({input:ye,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:v,origin:l,inclusive:!0,continue:!x.abort});return}}ye<i&&Z.issues.push({origin:"number",input:ye,code:"too_small",minimum:i,inclusive:!0,inst:v,continue:!x.abort}),ye>I&&Z.issues.push({origin:"number",input:ye,code:"too_big",maximum:I,inclusive:!0,inst:v,continue:!x.abort})}}),o.$ZodCheckBigIntFormat=P.$constructor("$ZodCheckBigIntFormat",(v,x)=>{o.$ZodCheck.init(v,x);const[w,l]=V.BIGINT_FORMAT_RANGES[x.format];v._zod.onattach.push(i=>{const I=i._zod.bag;I.format=x.format,I.minimum=w,I.maximum=l}),v._zod.check=i=>{const I=i.value;I<w&&i.issues.push({origin:"bigint",input:I,code:"too_small",minimum:w,inclusive:!0,inst:v,continue:!x.abort}),I>l&&i.issues.push({origin:"bigint",input:I,code:"too_big",maximum:l,inclusive:!0,inst:v,continue:!x.abort})}}),o.$ZodCheckMaxSize=P.$constructor("$ZodCheckMaxSize",(v,x)=>{var w;o.$ZodCheck.init(v,x),(w=v._zod.def).when??(w.when=l=>{const i=l.value;return!V.nullish(i)&&i.size!==void 0}),v._zod.onattach.push(l=>{const i=l._zod.bag.maximum??Number.POSITIVE_INFINITY;x.maximum<i&&(l._zod.bag.maximum=x.maximum)}),v._zod.check=l=>{const i=l.value;i.size<=x.maximum||l.issues.push({origin:V.getSizableOrigin(i),code:"too_big",maximum:x.maximum,inclusive:!0,input:i,inst:v,continue:!x.abort})}}),o.$ZodCheckMinSize=P.$constructor("$ZodCheckMinSize",(v,x)=>{var w;o.$ZodCheck.init(v,x),(w=v._zod.def).when??(w.when=l=>{const i=l.value;return!V.nullish(i)&&i.size!==void 0}),v._zod.onattach.push(l=>{const i=l._zod.bag.minimum??Number.NEGATIVE_INFINITY;x.minimum>i&&(l._zod.bag.minimum=x.minimum)}),v._zod.check=l=>{const i=l.value;i.size>=x.minimum||l.issues.push({origin:V.getSizableOrigin(i),code:"too_small",minimum:x.minimum,inclusive:!0,input:i,inst:v,continue:!x.abort})}}),o.$ZodCheckSizeEquals=P.$constructor("$ZodCheckSizeEquals",(v,x)=>{var w;o.$ZodCheck.init(v,x),(w=v._zod.def).when??(w.when=l=>{const i=l.value;return!V.nullish(i)&&i.size!==void 0}),v._zod.onattach.push(l=>{const i=l._zod.bag;i.minimum=x.size,i.maximum=x.size,i.size=x.size}),v._zod.check=l=>{const i=l.value,I=i.size;if(I===x.size)return;const Z=I>x.size;l.issues.push({origin:V.getSizableOrigin(i),...Z?{code:"too_big",maximum:x.size}:{code:"too_small",minimum:x.size},inclusive:!0,exact:!0,input:l.value,inst:v,continue:!x.abort})}}),o.$ZodCheckMaxLength=P.$constructor("$ZodCheckMaxLength",(v,x)=>{var w;o.$ZodCheck.init(v,x),(w=v._zod.def).when??(w.when=l=>{const i=l.value;return!V.nullish(i)&&i.length!==void 0}),v._zod.onattach.push(l=>{const i=l._zod.bag.maximum??Number.POSITIVE_INFINITY;x.maximum<i&&(l._zod.bag.maximum=x.maximum)}),v._zod.check=l=>{const i=l.value;if(i.length<=x.maximum)return;const Z=V.getLengthableOrigin(i);l.issues.push({origin:Z,code:"too_big",maximum:x.maximum,inclusive:!0,input:i,inst:v,continue:!x.abort})}}),o.$ZodCheckMinLength=P.$constructor("$ZodCheckMinLength",(v,x)=>{var w;o.$ZodCheck.init(v,x),(w=v._zod.def).when??(w.when=l=>{const i=l.value;return!V.nullish(i)&&i.length!==void 0}),v._zod.onattach.push(l=>{const i=l._zod.bag.minimum??Number.NEGATIVE_INFINITY;x.minimum>i&&(l._zod.bag.minimum=x.minimum)}),v._zod.check=l=>{const i=l.value;if(i.length>=x.minimum)return;const Z=V.getLengthableOrigin(i);l.issues.push({origin:Z,code:"too_small",minimum:x.minimum,inclusive:!0,input:i,inst:v,continue:!x.abort})}}),o.$ZodCheckLengthEquals=P.$constructor("$ZodCheckLengthEquals",(v,x)=>{var w;o.$ZodCheck.init(v,x),(w=v._zod.def).when??(w.when=l=>{const i=l.value;return!V.nullish(i)&&i.length!==void 0}),v._zod.onattach.push(l=>{const i=l._zod.bag;i.minimum=x.length,i.maximum=x.length,i.length=x.length}),v._zod.check=l=>{const i=l.value,I=i.length;if(I===x.length)return;const Z=V.getLengthableOrigin(i),ye=I>x.length;l.issues.push({origin:Z,...ye?{code:"too_big",maximum:x.length}:{code:"too_small",minimum:x.length},inclusive:!0,exact:!0,input:l.value,inst:v,continue:!x.abort})}}),o.$ZodCheckStringFormat=P.$constructor("$ZodCheckStringFormat",(v,x)=>{var w,l;o.$ZodCheck.init(v,x),v._zod.onattach.push(i=>{const I=i._zod.bag;I.format=x.format,x.pattern&&(I.patterns??(I.patterns=new Set),I.patterns.add(x.pattern))}),x.pattern?(w=v._zod).check??(w.check=i=>{x.pattern.lastIndex=0,!x.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:x.format,input:i.value,...x.pattern?{pattern:x.pattern.toString()}:{},inst:v,continue:!x.abort})}):(l=v._zod).check??(l.check=()=>{})}),o.$ZodCheckRegex=P.$constructor("$ZodCheckRegex",(v,x)=>{o.$ZodCheckStringFormat.init(v,x),v._zod.check=w=>{x.pattern.lastIndex=0,!x.pattern.test(w.value)&&w.issues.push({origin:"string",code:"invalid_format",format:"regex",input:w.value,pattern:x.pattern.toString(),inst:v,continue:!x.abort})}}),o.$ZodCheckLowerCase=P.$constructor("$ZodCheckLowerCase",(v,x)=>{x.pattern??(x.pattern=D.lowercase),o.$ZodCheckStringFormat.init(v,x)}),o.$ZodCheckUpperCase=P.$constructor("$ZodCheckUpperCase",(v,x)=>{x.pattern??(x.pattern=D.uppercase),o.$ZodCheckStringFormat.init(v,x)}),o.$ZodCheckIncludes=P.$constructor("$ZodCheckIncludes",(v,x)=>{o.$ZodCheck.init(v,x);const w=V.escapeRegex(x.includes),l=new RegExp(typeof x.position=="number"?`^.{${x.position}}${w}`:w);x.pattern=l,v._zod.onattach.push(i=>{const I=i._zod.bag;I.patterns??(I.patterns=new Set),I.patterns.add(l)}),v._zod.check=i=>{i.value.includes(x.includes,x.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:x.includes,input:i.value,inst:v,continue:!x.abort})}}),o.$ZodCheckStartsWith=P.$constructor("$ZodCheckStartsWith",(v,x)=>{o.$ZodCheck.init(v,x);const w=new RegExp(`^${V.escapeRegex(x.prefix)}.*`);x.pattern??(x.pattern=w),v._zod.onattach.push(l=>{const i=l._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(w)}),v._zod.check=l=>{l.value.startsWith(x.prefix)||l.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:x.prefix,input:l.value,inst:v,continue:!x.abort})}}),o.$ZodCheckEndsWith=P.$constructor("$ZodCheckEndsWith",(v,x)=>{o.$ZodCheck.init(v,x);const w=new RegExp(`.*${V.escapeRegex(x.suffix)}$`);x.pattern??(x.pattern=w),v._zod.onattach.push(l=>{const i=l._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(w)}),v._zod.check=l=>{l.value.endsWith(x.suffix)||l.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:x.suffix,input:l.value,inst:v,continue:!x.abort})}});function b(v,x,w){v.issues.length&&x.issues.push(...V.prefixIssues(w,v.issues))}o.$ZodCheckProperty=P.$constructor("$ZodCheckProperty",(v,x)=>{o.$ZodCheck.init(v,x),v._zod.check=w=>{const l=x.schema._zod.run({value:w.value[x.property],issues:[]},{});if(l instanceof Promise)return l.then(i=>b(i,w,x.property));b(l,w,x.property)}}),o.$ZodCheckMimeType=P.$constructor("$ZodCheckMimeType",(v,x)=>{o.$ZodCheck.init(v,x);const w=new Set(x.mime);v._zod.onattach.push(l=>{l._zod.bag.mime=x.mime}),v._zod.check=l=>{w.has(l.value.type)||l.issues.push({code:"invalid_value",values:x.mime,input:l.value.type,inst:v,continue:!x.abort})}}),o.$ZodCheckOverwrite=P.$constructor("$ZodCheckOverwrite",(v,x)=>{o.$ZodCheck.init(v,x),v._zod.check=w=>{w.value=x.tx(w.value)}})})(Mn);var zo={};Object.defineProperty(zo,"__esModule",{value:!0});zo.Doc=void 0;class cW{constructor(_=[]){this.content=[],this.indent=0,this&&(this.args=_)}indented(_){this.indent+=1,_(this),this.indent-=1}write(_){if(typeof _=="function"){_(this,{execution:"sync"}),_(this,{execution:"async"});return}const F=_.split(`
32
+ `).filter(V=>V),P=Math.min(...F.map(V=>V.length-V.trimStart().length)),D=F.map(V=>V.slice(P)).map(V=>" ".repeat(this.indent*2)+V);for(const V of D)this.content.push(V)}compile(){const _=Function,R=this?.args,P=[...(this?.content??[""]).map(D=>` ${D}`)];return new _(...R,P.join(`
33
+ `))}}zo.Doc=cW;var Go={};Object.defineProperty(Go,"__esModule",{value:!0});Go.version=void 0;Go.version={major:4,minor:4,patch:3};(function(o){var _=Xn&&Xn.__createBinding||(Object.create?(function(M,L,B,Y){Y===void 0&&(Y=B);var re=Object.getOwnPropertyDescriptor(L,B);(!re||("get"in re?!L.__esModule:re.writable||re.configurable))&&(re={enumerable:!0,get:function(){return L[B]}}),Object.defineProperty(M,Y,re)}):(function(M,L,B,Y){Y===void 0&&(Y=B),M[Y]=L[B]})),R=Xn&&Xn.__setModuleDefault||(Object.create?(function(M,L){Object.defineProperty(M,"default",{enumerable:!0,value:L})}):function(M,L){M.default=L}),F=Xn&&Xn.__importStar||function(M){if(M&&M.__esModule)return M;var L={};if(M!=null)for(var B in M)B!=="default"&&Object.prototype.hasOwnProperty.call(M,B)&&_(L,M,B);return R(L,M),L};Object.defineProperty(o,"__esModule",{value:!0}),o.$ZodTuple=o.$ZodIntersection=o.$ZodDiscriminatedUnion=o.$ZodXor=o.$ZodUnion=o.$ZodObjectJIT=o.$ZodObject=o.$ZodArray=o.$ZodDate=o.$ZodVoid=o.$ZodNever=o.$ZodUnknown=o.$ZodAny=o.$ZodNull=o.$ZodUndefined=o.$ZodSymbol=o.$ZodBigIntFormat=o.$ZodBigInt=o.$ZodBoolean=o.$ZodNumberFormat=o.$ZodNumber=o.$ZodCustomStringFormat=o.$ZodJWT=o.$ZodE164=o.$ZodBase64URL=o.$ZodBase64=o.$ZodCIDRv6=o.$ZodCIDRv4=o.$ZodMAC=o.$ZodIPv6=o.$ZodIPv4=o.$ZodISODuration=o.$ZodISOTime=o.$ZodISODate=o.$ZodISODateTime=o.$ZodKSUID=o.$ZodXID=o.$ZodULID=o.$ZodCUID2=o.$ZodCUID=o.$ZodNanoID=o.$ZodEmoji=o.$ZodURL=o.$ZodEmail=o.$ZodUUID=o.$ZodGUID=o.$ZodStringFormat=o.$ZodString=o.clone=o.$ZodType=void 0,o.$ZodCustom=o.$ZodLazy=o.$ZodPromise=o.$ZodFunction=o.$ZodTemplateLiteral=o.$ZodReadonly=o.$ZodPreprocess=o.$ZodCodec=o.$ZodPipe=o.$ZodNaN=o.$ZodCatch=o.$ZodSuccess=o.$ZodNonOptional=o.$ZodPrefault=o.$ZodDefault=o.$ZodNullable=o.$ZodExactOptional=o.$ZodOptional=o.$ZodTransform=o.$ZodFile=o.$ZodLiteral=o.$ZodEnum=o.$ZodSet=o.$ZodMap=o.$ZodRecord=void 0,o.isValidBase64=l,o.isValidBase64URL=i,o.isValidJWT=I;const P=F(Mn),D=F(Ki),V=zo,J=Yn,b=F($n),v=F(Ie),x=Go;o.$ZodType=D.$constructor("$ZodType",(M,L)=>{var B;M??(M={}),M._zod.def=L,M._zod.bag=M._zod.bag||{},M._zod.version=x.version;const Y=[...M._zod.def.checks??[]];M._zod.traits.has("$ZodCheck")&&Y.unshift(M);for(const re of Y)for(const ue of re._zod.onattach)ue(M);if(Y.length===0)(B=M._zod).deferred??(B.deferred=[]),M._zod.deferred?.push(()=>{M._zod.run=M._zod.parse});else{const re=(ke,Me,de)=>{let ce=v.aborted(ke),Pe;for(const De of Me){if(De._zod.def.when){if(v.explicitlyAborted(ke)||!De._zod.def.when(ke))continue}else if(ce)continue;const me=ke.issues.length,je=De._zod.check(ke);if(je instanceof Promise&&de?.async===!1)throw new D.$ZodAsyncError;if(Pe||je instanceof Promise)Pe=(Pe??Promise.resolve()).then(async()=>{await je,ke.issues.length!==me&&(ce||(ce=v.aborted(ke,me)))});else{if(ke.issues.length===me)continue;ce||(ce=v.aborted(ke,me))}}return Pe?Pe.then(()=>ke):ke},ue=(ke,Me,de)=>{if(v.aborted(ke))return ke.aborted=!0,ke;const ce=re(Me,Y,de);if(ce instanceof Promise){if(de.async===!1)throw new D.$ZodAsyncError;return ce.then(Pe=>M._zod.parse(Pe,de))}return M._zod.parse(ce,de)};M._zod.run=(ke,Me)=>{if(Me.skipChecks)return M._zod.parse(ke,Me);if(Me.direction==="backward"){const ce=M._zod.parse({value:ke.value,issues:[]},{...Me,skipChecks:!0});return ce instanceof Promise?ce.then(Pe=>ue(Pe,ke,Me)):ue(ce,ke,Me)}const de=M._zod.parse(ke,Me);if(de instanceof Promise){if(Me.async===!1)throw new D.$ZodAsyncError;return de.then(ce=>re(ce,Y,Me))}return re(de,Y,Me)}}v.defineLazy(M,"~standard",()=>({validate:re=>{try{const ue=(0,J.safeParse)(M,re);return ue.success?{value:ue.data}:{issues:ue.error?.issues}}catch{return(0,J.safeParseAsync)(M,re).then(ke=>ke.success?{value:ke.data}:{issues:ke.error?.issues})}},vendor:"zod",version:1}))});var w=Ie;Object.defineProperty(o,"clone",{enumerable:!0,get:function(){return w.clone}}),o.$ZodString=D.$constructor("$ZodString",(M,L)=>{o.$ZodType.init(M,L),M._zod.pattern=[...M?._zod.bag?.patterns??[]].pop()??b.string(M._zod.bag),M._zod.parse=(B,Y)=>{if(L.coerce)try{B.value=String(B.value)}catch{}return typeof B.value=="string"||B.issues.push({expected:"string",code:"invalid_type",input:B.value,inst:M}),B}}),o.$ZodStringFormat=D.$constructor("$ZodStringFormat",(M,L)=>{P.$ZodCheckStringFormat.init(M,L),o.$ZodString.init(M,L)}),o.$ZodGUID=D.$constructor("$ZodGUID",(M,L)=>{L.pattern??(L.pattern=b.guid),o.$ZodStringFormat.init(M,L)}),o.$ZodUUID=D.$constructor("$ZodUUID",(M,L)=>{if(L.version){const Y={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[L.version];if(Y===void 0)throw new Error(`Invalid UUID version: "${L.version}"`);L.pattern??(L.pattern=b.uuid(Y))}else L.pattern??(L.pattern=b.uuid());o.$ZodStringFormat.init(M,L)}),o.$ZodEmail=D.$constructor("$ZodEmail",(M,L)=>{L.pattern??(L.pattern=b.email),o.$ZodStringFormat.init(M,L)}),o.$ZodURL=D.$constructor("$ZodURL",(M,L)=>{o.$ZodStringFormat.init(M,L),M._zod.check=B=>{try{const Y=B.value.trim();if(!L.normalize&&L.protocol?.source===b.httpProtocol.source&&!/^https?:\/\//i.test(Y)){B.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:B.value,inst:M,continue:!L.abort});return}const re=new URL(Y);L.hostname&&(L.hostname.lastIndex=0,L.hostname.test(re.hostname)||B.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:L.hostname.source,input:B.value,inst:M,continue:!L.abort})),L.protocol&&(L.protocol.lastIndex=0,L.protocol.test(re.protocol.endsWith(":")?re.protocol.slice(0,-1):re.protocol)||B.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:L.protocol.source,input:B.value,inst:M,continue:!L.abort})),L.normalize?B.value=re.href:B.value=Y;return}catch{B.issues.push({code:"invalid_format",format:"url",input:B.value,inst:M,continue:!L.abort})}}}),o.$ZodEmoji=D.$constructor("$ZodEmoji",(M,L)=>{L.pattern??(L.pattern=b.emoji()),o.$ZodStringFormat.init(M,L)}),o.$ZodNanoID=D.$constructor("$ZodNanoID",(M,L)=>{L.pattern??(L.pattern=b.nanoid),o.$ZodStringFormat.init(M,L)}),o.$ZodCUID=D.$constructor("$ZodCUID",(M,L)=>{L.pattern??(L.pattern=b.cuid),o.$ZodStringFormat.init(M,L)}),o.$ZodCUID2=D.$constructor("$ZodCUID2",(M,L)=>{L.pattern??(L.pattern=b.cuid2),o.$ZodStringFormat.init(M,L)}),o.$ZodULID=D.$constructor("$ZodULID",(M,L)=>{L.pattern??(L.pattern=b.ulid),o.$ZodStringFormat.init(M,L)}),o.$ZodXID=D.$constructor("$ZodXID",(M,L)=>{L.pattern??(L.pattern=b.xid),o.$ZodStringFormat.init(M,L)}),o.$ZodKSUID=D.$constructor("$ZodKSUID",(M,L)=>{L.pattern??(L.pattern=b.ksuid),o.$ZodStringFormat.init(M,L)}),o.$ZodISODateTime=D.$constructor("$ZodISODateTime",(M,L)=>{L.pattern??(L.pattern=b.datetime(L)),o.$ZodStringFormat.init(M,L)}),o.$ZodISODate=D.$constructor("$ZodISODate",(M,L)=>{L.pattern??(L.pattern=b.date),o.$ZodStringFormat.init(M,L)}),o.$ZodISOTime=D.$constructor("$ZodISOTime",(M,L)=>{L.pattern??(L.pattern=b.time(L)),o.$ZodStringFormat.init(M,L)}),o.$ZodISODuration=D.$constructor("$ZodISODuration",(M,L)=>{L.pattern??(L.pattern=b.duration),o.$ZodStringFormat.init(M,L)}),o.$ZodIPv4=D.$constructor("$ZodIPv4",(M,L)=>{L.pattern??(L.pattern=b.ipv4),o.$ZodStringFormat.init(M,L),M._zod.bag.format="ipv4"}),o.$ZodIPv6=D.$constructor("$ZodIPv6",(M,L)=>{L.pattern??(L.pattern=b.ipv6),o.$ZodStringFormat.init(M,L),M._zod.bag.format="ipv6",M._zod.check=B=>{try{new URL(`http://[${B.value}]`)}catch{B.issues.push({code:"invalid_format",format:"ipv6",input:B.value,inst:M,continue:!L.abort})}}}),o.$ZodMAC=D.$constructor("$ZodMAC",(M,L)=>{L.pattern??(L.pattern=b.mac(L.delimiter)),o.$ZodStringFormat.init(M,L),M._zod.bag.format="mac"}),o.$ZodCIDRv4=D.$constructor("$ZodCIDRv4",(M,L)=>{L.pattern??(L.pattern=b.cidrv4),o.$ZodStringFormat.init(M,L)}),o.$ZodCIDRv6=D.$constructor("$ZodCIDRv6",(M,L)=>{L.pattern??(L.pattern=b.cidrv6),o.$ZodStringFormat.init(M,L),M._zod.check=B=>{const Y=B.value.split("/");try{if(Y.length!==2)throw new Error;const[re,ue]=Y;if(!ue)throw new Error;const ke=Number(ue);if(`${ke}`!==ue)throw new Error;if(ke<0||ke>128)throw new Error;new URL(`http://[${re}]`)}catch{B.issues.push({code:"invalid_format",format:"cidrv6",input:B.value,inst:M,continue:!L.abort})}}});function l(M){if(M==="")return!0;if(/\s/.test(M)||M.length%4!==0)return!1;try{return atob(M),!0}catch{return!1}}o.$ZodBase64=D.$constructor("$ZodBase64",(M,L)=>{L.pattern??(L.pattern=b.base64),o.$ZodStringFormat.init(M,L),M._zod.bag.contentEncoding="base64",M._zod.check=B=>{l(B.value)||B.issues.push({code:"invalid_format",format:"base64",input:B.value,inst:M,continue:!L.abort})}});function i(M){if(!b.base64url.test(M))return!1;const L=M.replace(/[-_]/g,Y=>Y==="-"?"+":"/"),B=L.padEnd(Math.ceil(L.length/4)*4,"=");return l(B)}o.$ZodBase64URL=D.$constructor("$ZodBase64URL",(M,L)=>{L.pattern??(L.pattern=b.base64url),o.$ZodStringFormat.init(M,L),M._zod.bag.contentEncoding="base64url",M._zod.check=B=>{i(B.value)||B.issues.push({code:"invalid_format",format:"base64url",input:B.value,inst:M,continue:!L.abort})}}),o.$ZodE164=D.$constructor("$ZodE164",(M,L)=>{L.pattern??(L.pattern=b.e164),o.$ZodStringFormat.init(M,L)});function I(M,L=null){try{const B=M.split(".");if(B.length!==3)return!1;const[Y]=B;if(!Y)return!1;const re=JSON.parse(atob(Y));return!("typ"in re&&re?.typ!=="JWT"||!re.alg||L&&(!("alg"in re)||re.alg!==L))}catch{return!1}}o.$ZodJWT=D.$constructor("$ZodJWT",(M,L)=>{o.$ZodStringFormat.init(M,L),M._zod.check=B=>{I(B.value,L.alg)||B.issues.push({code:"invalid_format",format:"jwt",input:B.value,inst:M,continue:!L.abort})}}),o.$ZodCustomStringFormat=D.$constructor("$ZodCustomStringFormat",(M,L)=>{o.$ZodStringFormat.init(M,L),M._zod.check=B=>{L.fn(B.value)||B.issues.push({code:"invalid_format",format:L.format,input:B.value,inst:M,continue:!L.abort})}}),o.$ZodNumber=D.$constructor("$ZodNumber",(M,L)=>{o.$ZodType.init(M,L),M._zod.pattern=M._zod.bag.pattern??b.number,M._zod.parse=(B,Y)=>{if(L.coerce)try{B.value=Number(B.value)}catch{}const re=B.value;if(typeof re=="number"&&!Number.isNaN(re)&&Number.isFinite(re))return B;const ue=typeof re=="number"?Number.isNaN(re)?"NaN":Number.isFinite(re)?void 0:"Infinity":void 0;return B.issues.push({expected:"number",code:"invalid_type",input:re,inst:M,...ue?{received:ue}:{}}),B}}),o.$ZodNumberFormat=D.$constructor("$ZodNumberFormat",(M,L)=>{P.$ZodCheckNumberFormat.init(M,L),o.$ZodNumber.init(M,L)}),o.$ZodBoolean=D.$constructor("$ZodBoolean",(M,L)=>{o.$ZodType.init(M,L),M._zod.pattern=b.boolean,M._zod.parse=(B,Y)=>{if(L.coerce)try{B.value=!!B.value}catch{}const re=B.value;return typeof re=="boolean"||B.issues.push({expected:"boolean",code:"invalid_type",input:re,inst:M}),B}}),o.$ZodBigInt=D.$constructor("$ZodBigInt",(M,L)=>{o.$ZodType.init(M,L),M._zod.pattern=b.bigint,M._zod.parse=(B,Y)=>{if(L.coerce)try{B.value=BigInt(B.value)}catch{}return typeof B.value=="bigint"||B.issues.push({expected:"bigint",code:"invalid_type",input:B.value,inst:M}),B}}),o.$ZodBigIntFormat=D.$constructor("$ZodBigIntFormat",(M,L)=>{P.$ZodCheckBigIntFormat.init(M,L),o.$ZodBigInt.init(M,L)}),o.$ZodSymbol=D.$constructor("$ZodSymbol",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>{const re=B.value;return typeof re=="symbol"||B.issues.push({expected:"symbol",code:"invalid_type",input:re,inst:M}),B}}),o.$ZodUndefined=D.$constructor("$ZodUndefined",(M,L)=>{o.$ZodType.init(M,L),M._zod.pattern=b.undefined,M._zod.values=new Set([void 0]),M._zod.parse=(B,Y)=>{const re=B.value;return typeof re>"u"||B.issues.push({expected:"undefined",code:"invalid_type",input:re,inst:M}),B}}),o.$ZodNull=D.$constructor("$ZodNull",(M,L)=>{o.$ZodType.init(M,L),M._zod.pattern=b.null,M._zod.values=new Set([null]),M._zod.parse=(B,Y)=>{const re=B.value;return re===null||B.issues.push({expected:"null",code:"invalid_type",input:re,inst:M}),B}}),o.$ZodAny=D.$constructor("$ZodAny",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=B=>B}),o.$ZodUnknown=D.$constructor("$ZodUnknown",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=B=>B}),o.$ZodNever=D.$constructor("$ZodNever",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>(B.issues.push({expected:"never",code:"invalid_type",input:B.value,inst:M}),B)}),o.$ZodVoid=D.$constructor("$ZodVoid",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>{const re=B.value;return typeof re>"u"||B.issues.push({expected:"void",code:"invalid_type",input:re,inst:M}),B}}),o.$ZodDate=D.$constructor("$ZodDate",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>{if(L.coerce)try{B.value=new Date(B.value)}catch{}const re=B.value,ue=re instanceof Date;return ue&&!Number.isNaN(re.getTime())||B.issues.push({expected:"date",code:"invalid_type",input:re,...ue?{received:"Invalid Date"}:{},inst:M}),B}});function Z(M,L,B){M.issues.length&&L.issues.push(...v.prefixIssues(B,M.issues)),L.value[B]=M.value}o.$ZodArray=D.$constructor("$ZodArray",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>{const re=B.value;if(!Array.isArray(re))return B.issues.push({expected:"array",code:"invalid_type",input:re,inst:M}),B;B.value=Array(re.length);const ue=[];for(let ke=0;ke<re.length;ke++){const Me=re[ke],de=L.element._zod.run({value:Me,issues:[]},Y);de instanceof Promise?ue.push(de.then(ce=>Z(ce,B,ke))):Z(de,B,ke)}return ue.length?Promise.all(ue).then(()=>B):B}});function ye(M,L,B,Y,re,ue){const ke=B in Y;if(M.issues.length){if(re&&ue&&!ke)return;L.issues.push(...v.prefixIssues(B,M.issues))}if(!ke&&!re){M.issues.length||L.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[B]});return}M.value===void 0?ke&&(L.value[B]=void 0):L.value[B]=M.value}function ve(M){const L=Object.keys(M.shape);for(const Y of L)if(!M.shape?.[Y]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${Y}": expected a Zod schema`);const B=v.optionalKeys(M.shape);return{...M,keys:L,keySet:new Set(L),numKeys:L.length,optionalKeys:new Set(B)}}function Te(M,L,B,Y,re,ue){const ke=[],Me=re.keySet,de=re.catchall._zod,ce=de.def.type,Pe=de.optin==="optional",De=de.optout==="optional";for(const me in L){if(me==="__proto__"||Me.has(me))continue;if(ce==="never"){ke.push(me);continue}const je=de.run({value:L[me],issues:[]},Y);je instanceof Promise?M.push(je.then(Ve=>ye(Ve,B,me,L,Pe,De))):ye(je,B,me,L,Pe,De)}return ke.length&&B.issues.push({code:"unrecognized_keys",keys:ke,input:L,inst:ue}),M.length?Promise.all(M).then(()=>B):B}o.$ZodObject=D.$constructor("$ZodObject",(M,L)=>{if(o.$ZodType.init(M,L),!Object.getOwnPropertyDescriptor(L,"shape")?.get){const Me=L.shape;Object.defineProperty(L,"shape",{get:()=>{const de={...Me};return Object.defineProperty(L,"shape",{value:de}),de}})}const Y=v.cached(()=>ve(L));v.defineLazy(M._zod,"propValues",()=>{const Me=L.shape,de={};for(const ce in Me){const Pe=Me[ce]._zod;if(Pe.values){de[ce]??(de[ce]=new Set);for(const De of Pe.values)de[ce].add(De)}}return de});const re=v.isObject,ue=L.catchall;let ke;M._zod.parse=(Me,de)=>{ke??(ke=Y.value);const ce=Me.value;if(!re(ce))return Me.issues.push({expected:"object",code:"invalid_type",input:ce,inst:M}),Me;Me.value={};const Pe=[],De=ke.shape;for(const me of ke.keys){const je=De[me],Ve=je._zod.optin==="optional",wt=je._zod.optout==="optional",ht=je._zod.run({value:ce[me],issues:[]},de);ht instanceof Promise?Pe.push(ht.then(pt=>ye(pt,Me,me,ce,Ve,wt))):ye(ht,Me,me,ce,Ve,wt)}return ue?Te(Pe,ce,Me,de,Y.value,M):Pe.length?Promise.all(Pe).then(()=>Me):Me}}),o.$ZodObjectJIT=D.$constructor("$ZodObjectJIT",(M,L)=>{o.$ZodObject.init(M,L);const B=M._zod.parse,Y=v.cached(()=>ve(L)),re=me=>{const je=new V.Doc(["shape","payload","ctx"]),Ve=Y.value,wt=Ut=>{const Pt=v.esc(Ut);return`shape[${Pt}]._zod.run({ value: input[${Pt}], issues: [] }, ctx)`};je.write("const input = payload.value;");const ht=Object.create(null);let pt=0;for(const Ut of Ve.keys)ht[Ut]=`key_${pt++}`;je.write("const newResult = {};");for(const Ut of Ve.keys){const Pt=ht[Ut],Ot=v.esc(Ut),Wt=me[Ut],xi=Wt?._zod?.optin==="optional",Rn=Wt?._zod?.optout==="optional";je.write(`const ${Pt} = ${wt(Ut)};`),xi&&Rn?je.write(`
34
+ if (${Pt}.issues.length) {
35
+ if (${Ot} in input) {
36
+ payload.issues = payload.issues.concat(${Pt}.issues.map(iss => ({
37
+ ...iss,
38
+ path: iss.path ? [${Ot}, ...iss.path] : [${Ot}]
39
+ })));
40
+ }
41
+ }
42
+
43
+ if (${Pt}.value === undefined) {
44
+ if (${Ot} in input) {
45
+ newResult[${Ot}] = undefined;
46
+ }
47
+ } else {
48
+ newResult[${Ot}] = ${Pt}.value;
49
+ }
50
+
51
+ `):xi?je.write(`
52
+ if (${Pt}.issues.length) {
53
+ payload.issues = payload.issues.concat(${Pt}.issues.map(iss => ({
54
+ ...iss,
55
+ path: iss.path ? [${Ot}, ...iss.path] : [${Ot}]
56
+ })));
57
+ }
58
+
59
+ if (${Pt}.value === undefined) {
60
+ if (${Ot} in input) {
61
+ newResult[${Ot}] = undefined;
62
+ }
63
+ } else {
64
+ newResult[${Ot}] = ${Pt}.value;
65
+ }
66
+
67
+ `):je.write(`
68
+ const ${Pt}_present = ${Ot} in input;
69
+ if (${Pt}.issues.length) {
70
+ payload.issues = payload.issues.concat(${Pt}.issues.map(iss => ({
71
+ ...iss,
72
+ path: iss.path ? [${Ot}, ...iss.path] : [${Ot}]
73
+ })));
74
+ }
75
+ if (!${Pt}_present && !${Pt}.issues.length) {
76
+ payload.issues.push({
77
+ code: "invalid_type",
78
+ expected: "nonoptional",
79
+ input: undefined,
80
+ path: [${Ot}]
81
+ });
82
+ }
83
+
84
+ if (${Pt}_present) {
85
+ if (${Pt}.value === undefined) {
86
+ newResult[${Ot}] = undefined;
87
+ } else {
88
+ newResult[${Ot}] = ${Pt}.value;
89
+ }
90
+ }
91
+
92
+ `)}je.write("payload.value = newResult;"),je.write("return payload;");const Tt=je.compile();return(Ut,Pt)=>Tt(me,Ut,Pt)};let ue;const ke=v.isObject,Me=!D.globalConfig.jitless,de=v.allowsEval,ce=Me&&de.value,Pe=L.catchall;let De;M._zod.parse=(me,je)=>{De??(De=Y.value);const Ve=me.value;return ke(Ve)?Me&&ce&&je?.async===!1&&je.jitless!==!0?(ue||(ue=re(L.shape)),me=ue(me,je),Pe?Te([],Ve,me,je,De,M):me):B(me,je):(me.issues.push({expected:"object",code:"invalid_type",input:Ve,inst:M}),me)}});function _e(M,L,B,Y){for(const ue of M)if(ue.issues.length===0)return L.value=ue.value,L;const re=M.filter(ue=>!v.aborted(ue));return re.length===1?(L.value=re[0].value,re[0]):(L.issues.push({code:"invalid_union",input:L.value,inst:B,errors:M.map(ue=>ue.issues.map(ke=>v.finalizeIssue(ke,Y,D.config())))}),L)}o.$ZodUnion=D.$constructor("$ZodUnion",(M,L)=>{o.$ZodType.init(M,L),v.defineLazy(M._zod,"optin",()=>L.options.some(Y=>Y._zod.optin==="optional")?"optional":void 0),v.defineLazy(M._zod,"optout",()=>L.options.some(Y=>Y._zod.optout==="optional")?"optional":void 0),v.defineLazy(M._zod,"values",()=>{if(L.options.every(Y=>Y._zod.values))return new Set(L.options.flatMap(Y=>Array.from(Y._zod.values)))}),v.defineLazy(M._zod,"pattern",()=>{if(L.options.every(Y=>Y._zod.pattern)){const Y=L.options.map(re=>re._zod.pattern);return new RegExp(`^(${Y.map(re=>v.cleanRegex(re.source)).join("|")})$`)}});const B=L.options.length===1?L.options[0]._zod.run:null;M._zod.parse=(Y,re)=>{if(B)return B(Y,re);let ue=!1;const ke=[];for(const Me of L.options){const de=Me._zod.run({value:Y.value,issues:[]},re);if(de instanceof Promise)ke.push(de),ue=!0;else{if(de.issues.length===0)return de;ke.push(de)}}return ue?Promise.all(ke).then(Me=>_e(Me,Y,M,re)):_e(ke,Y,M,re)}});function Oe(M,L,B,Y){const re=M.filter(ue=>ue.issues.length===0);return re.length===1?(L.value=re[0].value,L):(re.length===0?L.issues.push({code:"invalid_union",input:L.value,inst:B,errors:M.map(ue=>ue.issues.map(ke=>v.finalizeIssue(ke,Y,D.config())))}):L.issues.push({code:"invalid_union",input:L.value,inst:B,errors:[],inclusive:!1}),L)}o.$ZodXor=D.$constructor("$ZodXor",(M,L)=>{o.$ZodUnion.init(M,L),L.inclusive=!1;const B=L.options.length===1?L.options[0]._zod.run:null;M._zod.parse=(Y,re)=>{if(B)return B(Y,re);let ue=!1;const ke=[];for(const Me of L.options){const de=Me._zod.run({value:Y.value,issues:[]},re);de instanceof Promise?(ke.push(de),ue=!0):ke.push(de)}return ue?Promise.all(ke).then(Me=>Oe(Me,Y,M,re)):Oe(ke,Y,M,re)}}),o.$ZodDiscriminatedUnion=D.$constructor("$ZodDiscriminatedUnion",(M,L)=>{L.inclusive=!1,o.$ZodUnion.init(M,L);const B=M._zod.parse;v.defineLazy(M._zod,"propValues",()=>{const re={};for(const ue of L.options){const ke=ue._zod.propValues;if(!ke||Object.keys(ke).length===0)throw new Error(`Invalid discriminated union option at index "${L.options.indexOf(ue)}"`);for(const[Me,de]of Object.entries(ke)){re[Me]||(re[Me]=new Set);for(const ce of de)re[Me].add(ce)}}return re});const Y=v.cached(()=>{const re=L.options,ue=new Map;for(const ke of re){const Me=ke._zod.propValues?.[L.discriminator];if(!Me||Me.size===0)throw new Error(`Invalid discriminated union option at index "${L.options.indexOf(ke)}"`);for(const de of Me){if(ue.has(de))throw new Error(`Duplicate discriminator value "${String(de)}"`);ue.set(de,ke)}}return ue});M._zod.parse=(re,ue)=>{const ke=re.value;if(!v.isObject(ke))return re.issues.push({code:"invalid_type",expected:"object",input:ke,inst:M}),re;const Me=Y.value.get(ke?.[L.discriminator]);return Me?Me._zod.run(re,ue):L.unionFallback||ue.direction==="backward"?B(re,ue):(re.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:L.discriminator,options:Array.from(Y.value.keys()),input:ke,path:[L.discriminator],inst:M}),re)}}),o.$ZodIntersection=D.$constructor("$ZodIntersection",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>{const re=B.value,ue=L.left._zod.run({value:re,issues:[]},Y),ke=L.right._zod.run({value:re,issues:[]},Y);return ue instanceof Promise||ke instanceof Promise?Promise.all([ue,ke]).then(([de,ce])=>Ze(B,de,ce)):Ze(B,ue,ke)}});function W(M,L){if(M===L)return{valid:!0,data:M};if(M instanceof Date&&L instanceof Date&&+M==+L)return{valid:!0,data:M};if(v.isPlainObject(M)&&v.isPlainObject(L)){const B=Object.keys(L),Y=Object.keys(M).filter(ue=>B.indexOf(ue)!==-1),re={...M,...L};for(const ue of Y){const ke=W(M[ue],L[ue]);if(!ke.valid)return{valid:!1,mergeErrorPath:[ue,...ke.mergeErrorPath]};re[ue]=ke.data}return{valid:!0,data:re}}if(Array.isArray(M)&&Array.isArray(L)){if(M.length!==L.length)return{valid:!1,mergeErrorPath:[]};const B=[];for(let Y=0;Y<M.length;Y++){const re=M[Y],ue=L[Y],ke=W(re,ue);if(!ke.valid)return{valid:!1,mergeErrorPath:[Y,...ke.mergeErrorPath]};B.push(ke.data)}return{valid:!0,data:B}}return{valid:!1,mergeErrorPath:[]}}function Ze(M,L,B){const Y=new Map;let re;for(const Me of L.issues)if(Me.code==="unrecognized_keys"){re??(re=Me);for(const de of Me.keys)Y.has(de)||Y.set(de,{}),Y.get(de).l=!0}else M.issues.push(Me);for(const Me of B.issues)if(Me.code==="unrecognized_keys")for(const de of Me.keys)Y.has(de)||Y.set(de,{}),Y.get(de).r=!0;else M.issues.push(Me);const ue=[...Y].filter(([,Me])=>Me.l&&Me.r).map(([Me])=>Me);if(ue.length&&re&&M.issues.push({...re,keys:ue}),v.aborted(M))return M;const ke=W(L.value,B.value);if(!ke.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(ke.mergeErrorPath)}`);return M.value=ke.data,M}o.$ZodTuple=D.$constructor("$ZodTuple",(M,L)=>{o.$ZodType.init(M,L);const B=L.items;M._zod.parse=(Y,re)=>{const ue=Y.value;if(!Array.isArray(ue))return Y.issues.push({input:ue,inst:M,expected:"tuple",code:"invalid_type"}),Y;Y.value=[];const ke=[],Me=Le(B,"optin"),de=Le(B,"optout");if(!L.rest){if(ue.length<Me)return Y.issues.push({code:"too_small",minimum:Me,inclusive:!0,input:ue,inst:M,origin:"array"}),Y;ue.length>B.length&&Y.issues.push({code:"too_big",maximum:B.length,inclusive:!0,input:ue,inst:M,origin:"array"})}const ce=new Array(B.length);for(let Pe=0;Pe<B.length;Pe++){const De=B[Pe]._zod.run({value:ue[Pe],issues:[]},re);De instanceof Promise?ke.push(De.then(me=>{ce[Pe]=me})):ce[Pe]=De}if(L.rest){let Pe=B.length-1;const De=ue.slice(B.length);for(const me of De){Pe++;const je=L.rest._zod.run({value:me,issues:[]},re);je instanceof Promise?ke.push(je.then(Ve=>ot(Ve,Y,Pe))):ot(je,Y,Pe)}}return ke.length?Promise.all(ke).then(()=>tt(ce,Y,B,ue,de)):tt(ce,Y,B,ue,de)}});function Le(M,L){for(let B=M.length-1;B>=0;B--)if(M[B]._zod[L]!=="optional")return B+1;return 0}function ot(M,L,B){M.issues.length&&L.issues.push(...v.prefixIssues(B,M.issues)),L.value[B]=M.value}function tt(M,L,B,Y,re){for(let ue=0;ue<B.length;ue++){const ke=M[ue],Me=ue<Y.length;if(ke.issues.length){if(!Me&&ue>=re){L.value.length=ue;break}L.issues.push(...v.prefixIssues(ue,ke.issues))}L.value[ue]=ke.value}for(let ue=L.value.length-1;ue>=Y.length&&(B[ue]._zod.optout==="optional"&&L.value[ue]===void 0);ue--)L.value.length=ue;return L}o.$ZodRecord=D.$constructor("$ZodRecord",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>{const re=B.value;if(!v.isPlainObject(re))return B.issues.push({expected:"record",code:"invalid_type",input:re,inst:M}),B;const ue=[],ke=L.keyType._zod.values;if(ke){B.value={};const Me=new Set;for(const ce of ke)if(typeof ce=="string"||typeof ce=="number"||typeof ce=="symbol"){Me.add(typeof ce=="number"?ce.toString():ce);const Pe=L.keyType._zod.run({value:ce,issues:[]},Y);if(Pe instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(Pe.issues.length){B.issues.push({code:"invalid_key",origin:"record",issues:Pe.issues.map(je=>v.finalizeIssue(je,Y,D.config())),input:ce,path:[ce],inst:M});continue}const De=Pe.value,me=L.valueType._zod.run({value:re[ce],issues:[]},Y);me instanceof Promise?ue.push(me.then(je=>{je.issues.length&&B.issues.push(...v.prefixIssues(ce,je.issues)),B.value[De]=je.value})):(me.issues.length&&B.issues.push(...v.prefixIssues(ce,me.issues)),B.value[De]=me.value)}let de;for(const ce in re)Me.has(ce)||(de=de??[],de.push(ce));de&&de.length>0&&B.issues.push({code:"unrecognized_keys",input:re,inst:M,keys:de})}else{B.value={};for(const Me of Reflect.ownKeys(re)){if(Me==="__proto__"||!Object.prototype.propertyIsEnumerable.call(re,Me))continue;let de=L.keyType._zod.run({value:Me,issues:[]},Y);if(de instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof Me=="string"&&b.number.test(Me)&&de.issues.length){const De=L.keyType._zod.run({value:Number(Me),issues:[]},Y);if(De instanceof Promise)throw new Error("Async schemas not supported in object keys currently");De.issues.length===0&&(de=De)}if(de.issues.length){L.mode==="loose"?B.value[Me]=re[Me]:B.issues.push({code:"invalid_key",origin:"record",issues:de.issues.map(De=>v.finalizeIssue(De,Y,D.config())),input:Me,path:[Me],inst:M});continue}const Pe=L.valueType._zod.run({value:re[Me],issues:[]},Y);Pe instanceof Promise?ue.push(Pe.then(De=>{De.issues.length&&B.issues.push(...v.prefixIssues(Me,De.issues)),B.value[de.value]=De.value})):(Pe.issues.length&&B.issues.push(...v.prefixIssues(Me,Pe.issues)),B.value[de.value]=Pe.value)}}return ue.length?Promise.all(ue).then(()=>B):B}}),o.$ZodMap=D.$constructor("$ZodMap",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>{const re=B.value;if(!(re instanceof Map))return B.issues.push({expected:"map",code:"invalid_type",input:re,inst:M}),B;const ue=[];B.value=new Map;for(const[ke,Me]of re){const de=L.keyType._zod.run({value:ke,issues:[]},Y),ce=L.valueType._zod.run({value:Me,issues:[]},Y);de instanceof Promise||ce instanceof Promise?ue.push(Promise.all([de,ce]).then(([Pe,De])=>{_t(Pe,De,B,ke,re,M,Y)})):_t(de,ce,B,ke,re,M,Y)}return ue.length?Promise.all(ue).then(()=>B):B}});function _t(M,L,B,Y,re,ue,ke){M.issues.length&&(v.propertyKeyTypes.has(typeof Y)?B.issues.push(...v.prefixIssues(Y,M.issues)):B.issues.push({code:"invalid_key",origin:"map",input:re,inst:ue,issues:M.issues.map(Me=>v.finalizeIssue(Me,ke,D.config()))})),L.issues.length&&(v.propertyKeyTypes.has(typeof Y)?B.issues.push(...v.prefixIssues(Y,L.issues)):B.issues.push({origin:"map",code:"invalid_element",input:re,inst:ue,key:Y,issues:L.issues.map(Me=>v.finalizeIssue(Me,ke,D.config()))})),B.value.set(M.value,L.value)}o.$ZodSet=D.$constructor("$ZodSet",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>{const re=B.value;if(!(re instanceof Set))return B.issues.push({input:re,inst:M,expected:"set",code:"invalid_type"}),B;const ue=[];B.value=new Set;for(const ke of re){const Me=L.valueType._zod.run({value:ke,issues:[]},Y);Me instanceof Promise?ue.push(Me.then(de=>Kt(de,B))):Kt(Me,B)}return ue.length?Promise.all(ue).then(()=>B):B}});function Kt(M,L){M.issues.length&&L.issues.push(...M.issues),L.value.add(M.value)}o.$ZodEnum=D.$constructor("$ZodEnum",(M,L)=>{o.$ZodType.init(M,L);const B=v.getEnumValues(L.entries),Y=new Set(B);M._zod.values=Y,M._zod.pattern=new RegExp(`^(${B.filter(re=>v.propertyKeyTypes.has(typeof re)).map(re=>typeof re=="string"?v.escapeRegex(re):re.toString()).join("|")})$`),M._zod.parse=(re,ue)=>{const ke=re.value;return Y.has(ke)||re.issues.push({code:"invalid_value",values:B,input:ke,inst:M}),re}}),o.$ZodLiteral=D.$constructor("$ZodLiteral",(M,L)=>{if(o.$ZodType.init(M,L),L.values.length===0)throw new Error("Cannot create literal schema with no valid values");const B=new Set(L.values);M._zod.values=B,M._zod.pattern=new RegExp(`^(${L.values.map(Y=>typeof Y=="string"?v.escapeRegex(Y):Y?v.escapeRegex(Y.toString()):String(Y)).join("|")})$`),M._zod.parse=(Y,re)=>{const ue=Y.value;return B.has(ue)||Y.issues.push({code:"invalid_value",values:L.values,input:ue,inst:M}),Y}}),o.$ZodFile=D.$constructor("$ZodFile",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>{const re=B.value;return re instanceof File||B.issues.push({expected:"file",code:"invalid_type",input:re,inst:M}),B}}),o.$ZodTransform=D.$constructor("$ZodTransform",(M,L)=>{o.$ZodType.init(M,L),M._zod.optin="optional",M._zod.parse=(B,Y)=>{if(Y.direction==="backward")throw new D.$ZodEncodeError(M.constructor.name);const re=L.transform(B.value,B);if(Y.async)return(re instanceof Promise?re:Promise.resolve(re)).then(ke=>(B.value=ke,B.fallback=!0,B));if(re instanceof Promise)throw new D.$ZodAsyncError;return B.value=re,B.fallback=!0,B}});function cr(M,L){return L===void 0&&(M.issues.length||M.fallback)?{issues:[],value:void 0}:M}o.$ZodOptional=D.$constructor("$ZodOptional",(M,L)=>{o.$ZodType.init(M,L),M._zod.optin="optional",M._zod.optout="optional",v.defineLazy(M._zod,"values",()=>L.innerType._zod.values?new Set([...L.innerType._zod.values,void 0]):void 0),v.defineLazy(M._zod,"pattern",()=>{const B=L.innerType._zod.pattern;return B?new RegExp(`^(${v.cleanRegex(B.source)})?$`):void 0}),M._zod.parse=(B,Y)=>{if(L.innerType._zod.optin==="optional"){const re=B.value,ue=L.innerType._zod.run(B,Y);return ue instanceof Promise?ue.then(ke=>cr(ke,re)):cr(ue,re)}return B.value===void 0?B:L.innerType._zod.run(B,Y)}}),o.$ZodExactOptional=D.$constructor("$ZodExactOptional",(M,L)=>{o.$ZodOptional.init(M,L),v.defineLazy(M._zod,"values",()=>L.innerType._zod.values),v.defineLazy(M._zod,"pattern",()=>L.innerType._zod.pattern),M._zod.parse=(B,Y)=>L.innerType._zod.run(B,Y)}),o.$ZodNullable=D.$constructor("$ZodNullable",(M,L)=>{o.$ZodType.init(M,L),v.defineLazy(M._zod,"optin",()=>L.innerType._zod.optin),v.defineLazy(M._zod,"optout",()=>L.innerType._zod.optout),v.defineLazy(M._zod,"pattern",()=>{const B=L.innerType._zod.pattern;return B?new RegExp(`^(${v.cleanRegex(B.source)}|null)$`):void 0}),v.defineLazy(M._zod,"values",()=>L.innerType._zod.values?new Set([...L.innerType._zod.values,null]):void 0),M._zod.parse=(B,Y)=>B.value===null?B:L.innerType._zod.run(B,Y)}),o.$ZodDefault=D.$constructor("$ZodDefault",(M,L)=>{o.$ZodType.init(M,L),M._zod.optin="optional",v.defineLazy(M._zod,"values",()=>L.innerType._zod.values),M._zod.parse=(B,Y)=>{if(Y.direction==="backward")return L.innerType._zod.run(B,Y);if(B.value===void 0)return B.value=L.defaultValue,B;const re=L.innerType._zod.run(B,Y);return re instanceof Promise?re.then(ue=>kr(ue,L)):kr(re,L)}});function kr(M,L){return M.value===void 0&&(M.value=L.defaultValue),M}o.$ZodPrefault=D.$constructor("$ZodPrefault",(M,L)=>{o.$ZodType.init(M,L),M._zod.optin="optional",v.defineLazy(M._zod,"values",()=>L.innerType._zod.values),M._zod.parse=(B,Y)=>(Y.direction==="backward"||B.value===void 0&&(B.value=L.defaultValue),L.innerType._zod.run(B,Y))}),o.$ZodNonOptional=D.$constructor("$ZodNonOptional",(M,L)=>{o.$ZodType.init(M,L),v.defineLazy(M._zod,"values",()=>{const B=L.innerType._zod.values;return B?new Set([...B].filter(Y=>Y!==void 0)):void 0}),M._zod.parse=(B,Y)=>{const re=L.innerType._zod.run(B,Y);return re instanceof Promise?re.then(ue=>Tr(ue,M)):Tr(re,M)}});function Tr(M,L){return!M.issues.length&&M.value===void 0&&M.issues.push({code:"invalid_type",expected:"nonoptional",input:M.value,inst:L}),M}o.$ZodSuccess=D.$constructor("$ZodSuccess",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>{if(Y.direction==="backward")throw new D.$ZodEncodeError("ZodSuccess");const re=L.innerType._zod.run(B,Y);return re instanceof Promise?re.then(ue=>(B.value=ue.issues.length===0,B)):(B.value=re.issues.length===0,B)}}),o.$ZodCatch=D.$constructor("$ZodCatch",(M,L)=>{o.$ZodType.init(M,L),M._zod.optin="optional",v.defineLazy(M._zod,"optout",()=>L.innerType._zod.optout),v.defineLazy(M._zod,"values",()=>L.innerType._zod.values),M._zod.parse=(B,Y)=>{if(Y.direction==="backward")return L.innerType._zod.run(B,Y);const re=L.innerType._zod.run(B,Y);return re instanceof Promise?re.then(ue=>(B.value=ue.value,ue.issues.length&&(B.value=L.catchValue({...B,error:{issues:ue.issues.map(ke=>v.finalizeIssue(ke,Y,D.config()))},input:B.value}),B.issues=[],B.fallback=!0),B)):(B.value=re.value,re.issues.length&&(B.value=L.catchValue({...B,error:{issues:re.issues.map(ue=>v.finalizeIssue(ue,Y,D.config()))},input:B.value}),B.issues=[],B.fallback=!0),B)}}),o.$ZodNaN=D.$constructor("$ZodNaN",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>((typeof B.value!="number"||!Number.isNaN(B.value))&&B.issues.push({input:B.value,inst:M,expected:"nan",code:"invalid_type"}),B)}),o.$ZodPipe=D.$constructor("$ZodPipe",(M,L)=>{o.$ZodType.init(M,L),v.defineLazy(M._zod,"values",()=>L.in._zod.values),v.defineLazy(M._zod,"optin",()=>L.in._zod.optin),v.defineLazy(M._zod,"optout",()=>L.out._zod.optout),v.defineLazy(M._zod,"propValues",()=>L.in._zod.propValues),M._zod.parse=(B,Y)=>{if(Y.direction==="backward"){const ue=L.out._zod.run(B,Y);return ue instanceof Promise?ue.then(ke=>Ir(ke,L.in,Y)):Ir(ue,L.in,Y)}const re=L.in._zod.run(B,Y);return re instanceof Promise?re.then(ue=>Ir(ue,L.out,Y)):Ir(re,L.out,Y)}});function Ir(M,L,B){return M.issues.length?(M.aborted=!0,M):L._zod.run({value:M.value,issues:M.issues,fallback:M.fallback},B)}o.$ZodCodec=D.$constructor("$ZodCodec",(M,L)=>{o.$ZodType.init(M,L),v.defineLazy(M._zod,"values",()=>L.in._zod.values),v.defineLazy(M._zod,"optin",()=>L.in._zod.optin),v.defineLazy(M._zod,"optout",()=>L.out._zod.optout),v.defineLazy(M._zod,"propValues",()=>L.in._zod.propValues),M._zod.parse=(B,Y)=>{if((Y.direction||"forward")==="forward"){const ue=L.in._zod.run(B,Y);return ue instanceof Promise?ue.then(ke=>Dr(ke,L,Y)):Dr(ue,L,Y)}else{const ue=L.out._zod.run(B,Y);return ue instanceof Promise?ue.then(ke=>Dr(ke,L,Y)):Dr(ue,L,Y)}}});function Dr(M,L,B){if(M.issues.length)return M.aborted=!0,M;if((B.direction||"forward")==="forward"){const re=L.transform(M.value,M);return re instanceof Promise?re.then(ue=>Qt(M,ue,L.out,B)):Qt(M,re,L.out,B)}else{const re=L.reverseTransform(M.value,M);return re instanceof Promise?re.then(ue=>Qt(M,ue,L.in,B)):Qt(M,re,L.in,B)}}function Qt(M,L,B,Y){return M.issues.length?(M.aborted=!0,M):B._zod.run({value:L,issues:M.issues},Y)}o.$ZodPreprocess=D.$constructor("$ZodPreprocess",(M,L)=>{o.$ZodPipe.init(M,L)}),o.$ZodReadonly=D.$constructor("$ZodReadonly",(M,L)=>{o.$ZodType.init(M,L),v.defineLazy(M._zod,"propValues",()=>L.innerType._zod.propValues),v.defineLazy(M._zod,"values",()=>L.innerType._zod.values),v.defineLazy(M._zod,"optin",()=>L.innerType?._zod?.optin),v.defineLazy(M._zod,"optout",()=>L.innerType?._zod?.optout),M._zod.parse=(B,Y)=>{if(Y.direction==="backward")return L.innerType._zod.run(B,Y);const re=L.innerType._zod.run(B,Y);return re instanceof Promise?re.then(Or):Or(re)}});function Or(M){return M.value=Object.freeze(M.value),M}o.$ZodTemplateLiteral=D.$constructor("$ZodTemplateLiteral",(M,L)=>{o.$ZodType.init(M,L);const B=[];for(const Y of L.parts)if(typeof Y=="object"&&Y!==null){if(!Y._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...Y._zod.traits].shift()}`);const re=Y._zod.pattern instanceof RegExp?Y._zod.pattern.source:Y._zod.pattern;if(!re)throw new Error(`Invalid template literal part: ${Y._zod.traits}`);const ue=re.startsWith("^")?1:0,ke=re.endsWith("$")?re.length-1:re.length;B.push(re.slice(ue,ke))}else if(Y===null||v.primitiveTypes.has(typeof Y))B.push(v.escapeRegex(`${Y}`));else throw new Error(`Invalid template literal part: ${Y}`);M._zod.pattern=new RegExp(`^${B.join("")}$`),M._zod.parse=(Y,re)=>typeof Y.value!="string"?(Y.issues.push({input:Y.value,inst:M,expected:"string",code:"invalid_type"}),Y):(M._zod.pattern.lastIndex=0,M._zod.pattern.test(Y.value)||Y.issues.push({input:Y.value,inst:M,code:"invalid_format",format:L.format??"template_literal",pattern:M._zod.pattern.source}),Y)}),o.$ZodFunction=D.$constructor("$ZodFunction",(M,L)=>(o.$ZodType.init(M,L),M._def=L,M._zod.def=L,M.implement=B=>{if(typeof B!="function")throw new Error("implement() must be called with a function");return function(...Y){const re=M._def.input?(0,J.parse)(M._def.input,Y):Y,ue=Reflect.apply(B,this,re);return M._def.output?(0,J.parse)(M._def.output,ue):ue}},M.implementAsync=B=>{if(typeof B!="function")throw new Error("implementAsync() must be called with a function");return async function(...Y){const re=M._def.input?await(0,J.parseAsync)(M._def.input,Y):Y,ue=await Reflect.apply(B,this,re);return M._def.output?await(0,J.parseAsync)(M._def.output,ue):ue}},M._zod.parse=(B,Y)=>typeof B.value!="function"?(B.issues.push({code:"invalid_type",expected:"function",input:B.value,inst:M}),B):(M._def.output&&M._def.output._zod.def.type==="promise"?B.value=M.implementAsync(B.value):B.value=M.implement(B.value),B),M.input=(...B)=>{const Y=M.constructor;return Array.isArray(B[0])?new Y({type:"function",input:new o.$ZodTuple({type:"tuple",items:B[0],rest:B[1]}),output:M._def.output}):new Y({type:"function",input:B[0],output:M._def.output})},M.output=B=>{const Y=M.constructor;return new Y({type:"function",input:M._def.input,output:B})},M)),o.$ZodPromise=D.$constructor("$ZodPromise",(M,L)=>{o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>Promise.resolve(B.value).then(re=>L.innerType._zod.run({value:re,issues:[]},Y))}),o.$ZodLazy=D.$constructor("$ZodLazy",(M,L)=>{o.$ZodType.init(M,L),v.defineLazy(M._zod,"innerType",()=>{const B=L;return B._cachedInner||(B._cachedInner=L.getter()),B._cachedInner}),v.defineLazy(M._zod,"pattern",()=>M._zod.innerType?._zod?.pattern),v.defineLazy(M._zod,"propValues",()=>M._zod.innerType?._zod?.propValues),v.defineLazy(M._zod,"optin",()=>M._zod.innerType?._zod?.optin??void 0),v.defineLazy(M._zod,"optout",()=>M._zod.innerType?._zod?.optout??void 0),M._zod.parse=(B,Y)=>M._zod.innerType._zod.run(B,Y)}),o.$ZodCustom=D.$constructor("$ZodCustom",(M,L)=>{P.$ZodCheck.init(M,L),o.$ZodType.init(M,L),M._zod.parse=(B,Y)=>B,M._zod.check=B=>{const Y=B.value,re=L.fn(Y);if(re instanceof Promise)return re.then(ue=>bn(ue,B,Y,M));bn(re,B,Y,M)}});function bn(M,L,B,Y){if(!M){const re={code:"custom",input:B,inst:Y,path:[...Y._zod.def.path??[]],continue:!Y._zod.def.abort};Y._zod.def.params&&(re.params=Y._zod.def.params),L.issues.push(v.issue(re))}}})(Xn);var Bo={},Yc={exports:{}},Ls=Yc.exports;(function(o,_){var R=Ls&&Ls.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Ls&&Ls.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Ls&&Ls.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"حرف",verb:"أن يحوي"},file:{unit:"بايت",verb:"أن يحوي"},array:{unit:"عنصر",verb:"أن يحوي"},set:{unit:"عنصر",verb:"أن يحوي"}};function v(l){return b[l]??null}const x={regex:"مدخل",email:"بريد إلكتروني",url:"رابط",emoji:"إيموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاريخ ووقت بمعيار ISO",date:"تاريخ بمعيار ISO",time:"وقت بمعيار ISO",duration:"مدة بمعيار ISO",ipv4:"عنوان IPv4",ipv6:"عنوان IPv6",cidrv4:"مدى عناوين بصيغة IPv4",cidrv6:"مدى عناوين بصيغة IPv6",base64:"نَص بترميز base64-encoded",base64url:"نَص بترميز base64url-encoded",json_string:"نَص على هيئة JSON",e164:"رقم هاتف بمعيار E.164",jwt:"JWT",template_literal:"مدخل"},w={nan:"NaN"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`مدخلات غير مقبولة: يفترض إدخال instanceof ${l.expected}، ولكن تم إدخال ${Z}`:`مدخلات غير مقبولة: يفترض إدخال ${i}، ولكن تم إدخال ${Z}`}case"invalid_value":return l.values.length===1?`مدخلات غير مقبولة: يفترض إدخال ${D.stringifyPrimitive(l.values[0])}`:`اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?` أكبر من اللازم: يفترض أن تكون ${l.origin??"القيمة"} ${i} ${l.maximum.toString()} ${I.unit??"عنصر"}`:`أكبر من اللازم: يفترض أن تكون ${l.origin??"القيمة"} ${i} ${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`أصغر من اللازم: يفترض لـ ${l.origin} أن يكون ${i} ${l.minimum.toString()} ${I.unit}`:`أصغر من اللازم: يفترض لـ ${l.origin} أن يكون ${i} ${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`نَص غير مقبول: يجب أن يبدأ بـ "${l.prefix}"`:i.format==="ends_with"?`نَص غير مقبول: يجب أن ينتهي بـ "${i.suffix}"`:i.format==="includes"?`نَص غير مقبول: يجب أن يتضمَّن "${i.includes}"`:i.format==="regex"?`نَص غير مقبول: يجب أن يطابق النمط ${i.pattern}`:`${x[i.format]??l.format} غير مقبول`}case"not_multiple_of":return`رقم غير مقبول: يجب أن يكون من مضاعفات ${l.divisor}`;case"unrecognized_keys":return`معرف${l.keys.length>1?"ات":""} غريب${l.keys.length>1?"ة":""}: ${D.joinValues(l.keys,"، ")}`;case"invalid_key":return`معرف غير مقبول في ${l.origin}`;case"invalid_union":return"مدخل غير مقبول";case"invalid_element":return`مدخل غير مقبول في ${l.origin}`;default:return"مدخل غير مقبول"}}};function J(){return{localeError:V()}}o.exports=_.default})(Yc,Yc.exports);var uW=Yc.exports,Xc={exports:{}},Os=Xc.exports;(function(o,_){var R=Os&&Os.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Os&&Os.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Os&&Os.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"simvol",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"element",verb:"olmalıdır"},set:{unit:"element",verb:"olmalıdır"}};function v(l){return b[l]??null}const x={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},w={nan:"NaN"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Yanlış dəyər: gözlənilən instanceof ${l.expected}, daxil olan ${Z}`:`Yanlış dəyər: gözlənilən ${i}, daxil olan ${Z}`}case"invalid_value":return l.values.length===1?`Yanlış dəyər: gözlənilən ${D.stringifyPrimitive(l.values[0])}`:`Yanlış seçim: aşağıdakılardan biri olmalıdır: ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Çox böyük: gözlənilən ${l.origin??"dəyər"} ${i}${l.maximum.toString()} ${I.unit??"element"}`:`Çox böyük: gözlənilən ${l.origin??"dəyər"} ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Çox kiçik: gözlənilən ${l.origin} ${i}${l.minimum.toString()} ${I.unit}`:`Çox kiçik: gözlənilən ${l.origin} ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Yanlış mətn: "${i.prefix}" ilə başlamalıdır`:i.format==="ends_with"?`Yanlış mətn: "${i.suffix}" ilə bitməlidir`:i.format==="includes"?`Yanlış mətn: "${i.includes}" daxil olmalıdır`:i.format==="regex"?`Yanlış mətn: ${i.pattern} şablonuna uyğun olmalıdır`:`Yanlış ${x[i.format]??l.format}`}case"not_multiple_of":return`Yanlış ədəd: ${l.divisor} ilə bölünə bilən olmalıdır`;case"unrecognized_keys":return`Tanınmayan açar${l.keys.length>1?"lar":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`${l.origin} daxilində yanlış açar`;case"invalid_union":return"Yanlış dəyər";case"invalid_element":return`${l.origin} daxilində yanlış dəyər`;default:return"Yanlış dəyər"}}};function J(){return{localeError:V()}}o.exports=_.default})(Xc,Xc.exports);var dW=Xc.exports,Jc={exports:{}},Fs=Jc.exports;(function(o,_){var R=Fs&&Fs.__createBinding||(Object.create?(function(v,x,w,l){l===void 0&&(l=w);var i=Object.getOwnPropertyDescriptor(x,w);(!i||("get"in i?!x.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return x[w]}}),Object.defineProperty(v,l,i)}):(function(v,x,w,l){l===void 0&&(l=w),v[l]=x[w]})),F=Fs&&Fs.__setModuleDefault||(Object.create?(function(v,x){Object.defineProperty(v,"default",{enumerable:!0,value:x})}):function(v,x){v.default=x}),P=Fs&&Fs.__importStar||function(v){if(v&&v.__esModule)return v;var x={};if(v!=null)for(var w in v)w!=="default"&&Object.prototype.hasOwnProperty.call(v,w)&&R(x,v,w);return F(x,v),x};Object.defineProperty(_,"__esModule",{value:!0}),_.default=b;const D=P(Ie);function V(v,x,w,l){const i=Math.abs(v),I=i%10,Z=i%100;return Z>=11&&Z<=19?l:I===1?x:I>=2&&I<=4?w:l}const J=()=>{const v={string:{unit:{one:"сімвал",few:"сімвалы",many:"сімвалаў"},verb:"мець"},array:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},set:{unit:{one:"элемент",few:"элементы",many:"элементаў"},verb:"мець"},file:{unit:{one:"байт",few:"байты",many:"байтаў"},verb:"мець"}};function x(i){return v[i]??null}const w={regex:"увод",email:"email адрас",url:"URL",emoji:"эмодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата і час",date:"ISO дата",time:"ISO час",duration:"ISO працягласць",ipv4:"IPv4 адрас",ipv6:"IPv6 адрас",cidrv4:"IPv4 дыяпазон",cidrv6:"IPv6 дыяпазон",base64:"радок у фармаце base64",base64url:"радок у фармаце base64url",json_string:"JSON радок",e164:"нумар E.164",jwt:"JWT",template_literal:"увод"},l={nan:"NaN",number:"лік",array:"масіў"};return i=>{switch(i.code){case"invalid_type":{const I=l[i.expected]??i.expected,Z=D.parsedType(i.input),ye=l[Z]??Z;return/^[A-Z]/.test(i.expected)?`Няправільны ўвод: чакаўся instanceof ${i.expected}, атрымана ${ye}`:`Няправільны ўвод: чакаўся ${I}, атрымана ${ye}`}case"invalid_value":return i.values.length===1?`Няправільны ўвод: чакалася ${D.stringifyPrimitive(i.values[0])}`:`Няправільны варыянт: чакаўся адзін з ${D.joinValues(i.values,"|")}`;case"too_big":{const I=i.inclusive?"<=":"<",Z=x(i.origin);if(Z){const ye=Number(i.maximum),ve=V(ye,Z.unit.one,Z.unit.few,Z.unit.many);return`Занадта вялікі: чакалася, што ${i.origin??"значэнне"} павінна ${Z.verb} ${I}${i.maximum.toString()} ${ve}`}return`Занадта вялікі: чакалася, што ${i.origin??"значэнне"} павінна быць ${I}${i.maximum.toString()}`}case"too_small":{const I=i.inclusive?">=":">",Z=x(i.origin);if(Z){const ye=Number(i.minimum),ve=V(ye,Z.unit.one,Z.unit.few,Z.unit.many);return`Занадта малы: чакалася, што ${i.origin} павінна ${Z.verb} ${I}${i.minimum.toString()} ${ve}`}return`Занадта малы: чакалася, што ${i.origin} павінна быць ${I}${i.minimum.toString()}`}case"invalid_format":{const I=i;return I.format==="starts_with"?`Няправільны радок: павінен пачынацца з "${I.prefix}"`:I.format==="ends_with"?`Няправільны радок: павінен заканчвацца на "${I.suffix}"`:I.format==="includes"?`Няправільны радок: павінен змяшчаць "${I.includes}"`:I.format==="regex"?`Няправільны радок: павінен адпавядаць шаблону ${I.pattern}`:`Няправільны ${w[I.format]??i.format}`}case"not_multiple_of":return`Няправільны лік: павінен быць кратным ${i.divisor}`;case"unrecognized_keys":return`Нераспазнаны ${i.keys.length>1?"ключы":"ключ"}: ${D.joinValues(i.keys,", ")}`;case"invalid_key":return`Няправільны ключ у ${i.origin}`;case"invalid_union":return"Няправільны ўвод";case"invalid_element":return`Няправільнае значэнне ў ${i.origin}`;default:return"Няправільны ўвод"}}};function b(){return{localeError:J()}}o.exports=_.default})(Jc,Jc.exports);var fW=Jc.exports,eu={exports:{}},Us=eu.exports;(function(o,_){var R=Us&&Us.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Us&&Us.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Us&&Us.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"символа",verb:"да съдържа"},file:{unit:"байта",verb:"да съдържа"},array:{unit:"елемента",verb:"да съдържа"},set:{unit:"елемента",verb:"да съдържа"}};function v(l){return b[l]??null}const x={regex:"вход",email:"имейл адрес",url:"URL",emoji:"емоджи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO време",date:"ISO дата",time:"ISO време",duration:"ISO продължителност",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"base64-кодиран низ",base64url:"base64url-кодиран низ",json_string:"JSON низ",e164:"E.164 номер",jwt:"JWT",template_literal:"вход"},w={nan:"NaN",number:"число",array:"масив"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Невалиден вход: очакван instanceof ${l.expected}, получен ${Z}`:`Невалиден вход: очакван ${i}, получен ${Z}`}case"invalid_value":return l.values.length===1?`Невалиден вход: очакван ${D.stringifyPrimitive(l.values[0])}`:`Невалидна опция: очаквано едно от ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Твърде голямо: очаква се ${l.origin??"стойност"} да съдържа ${i}${l.maximum.toString()} ${I.unit??"елемента"}`:`Твърде голямо: очаква се ${l.origin??"стойност"} да бъде ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Твърде малко: очаква се ${l.origin} да съдържа ${i}${l.minimum.toString()} ${I.unit}`:`Твърде малко: очаква се ${l.origin} да бъде ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;if(i.format==="starts_with")return`Невалиден низ: трябва да започва с "${i.prefix}"`;if(i.format==="ends_with")return`Невалиден низ: трябва да завършва с "${i.suffix}"`;if(i.format==="includes")return`Невалиден низ: трябва да включва "${i.includes}"`;if(i.format==="regex")return`Невалиден низ: трябва да съвпада с ${i.pattern}`;let I="Невалиден";return i.format==="emoji"&&(I="Невалидно"),i.format==="datetime"&&(I="Невалидно"),i.format==="date"&&(I="Невалидна"),i.format==="time"&&(I="Невалидно"),i.format==="duration"&&(I="Невалидна"),`${I} ${x[i.format]??l.format}`}case"not_multiple_of":return`Невалидно число: трябва да бъде кратно на ${l.divisor}`;case"unrecognized_keys":return`Неразпознат${l.keys.length>1?"и":""} ключ${l.keys.length>1?"ове":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Невалиден ключ в ${l.origin}`;case"invalid_union":return"Невалиден вход";case"invalid_element":return`Невалидна стойност в ${l.origin}`;default:return"Невалиден вход"}}};function J(){return{localeError:V()}}o.exports=_.default})(eu,eu.exports);var hW=eu.exports,tu={exports:{}},Bs=tu.exports;(function(o,_){var R=Bs&&Bs.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Bs&&Bs.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Bs&&Bs.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"caràcters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function v(l){return b[l]??null}const x={regex:"entrada",email:"adreça electrònica",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adreça IPv4",ipv6:"adreça IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},w={nan:"NaN"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Tipus invàlid: s'esperava instanceof ${l.expected}, s'ha rebut ${Z}`:`Tipus invàlid: s'esperava ${i}, s'ha rebut ${Z}`}case"invalid_value":return l.values.length===1?`Valor invàlid: s'esperava ${D.stringifyPrimitive(l.values[0])}`:`Opció invàlida: s'esperava una de ${D.joinValues(l.values," o ")}`;case"too_big":{const i=l.inclusive?"com a màxim":"menys de",I=v(l.origin);return I?`Massa gran: s'esperava que ${l.origin??"el valor"} contingués ${i} ${l.maximum.toString()} ${I.unit??"elements"}`:`Massa gran: s'esperava que ${l.origin??"el valor"} fos ${i} ${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?"com a mínim":"més de",I=v(l.origin);return I?`Massa petit: s'esperava que ${l.origin} contingués ${i} ${l.minimum.toString()} ${I.unit}`:`Massa petit: s'esperava que ${l.origin} fos ${i} ${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Format invàlid: ha de començar amb "${i.prefix}"`:i.format==="ends_with"?`Format invàlid: ha d'acabar amb "${i.suffix}"`:i.format==="includes"?`Format invàlid: ha d'incloure "${i.includes}"`:i.format==="regex"?`Format invàlid: ha de coincidir amb el patró ${i.pattern}`:`Format invàlid per a ${x[i.format]??l.format}`}case"not_multiple_of":return`Número invàlid: ha de ser múltiple de ${l.divisor}`;case"unrecognized_keys":return`Clau${l.keys.length>1?"s":""} no reconeguda${l.keys.length>1?"s":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Clau invàlida a ${l.origin}`;case"invalid_union":return"Entrada invàlida";case"invalid_element":return`Element invàlid a ${l.origin}`;default:return"Entrada invàlida"}}};function J(){return{localeError:V()}}o.exports=_.default})(tu,tu.exports);var mW=tu.exports,ru={exports:{}},zs=ru.exports;(function(o,_){var R=zs&&zs.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=zs&&zs.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=zs&&zs.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"znaků",verb:"mít"},file:{unit:"bajtů",verb:"mít"},array:{unit:"prvků",verb:"mít"},set:{unit:"prvků",verb:"mít"}};function v(l){return b[l]??null}const x={regex:"regulární výraz",email:"e-mailová adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"datum a čas ve formátu ISO",date:"datum ve formátu ISO",time:"čas ve formátu ISO",duration:"doba trvání ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"řetězec zakódovaný ve formátu base64",base64url:"řetězec zakódovaný ve formátu base64url",json_string:"řetězec ve formátu JSON",e164:"číslo E.164",jwt:"JWT",template_literal:"vstup"},w={nan:"NaN",number:"číslo",string:"řetězec",function:"funkce",array:"pole"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Neplatný vstup: očekáváno instanceof ${l.expected}, obdrženo ${Z}`:`Neplatný vstup: očekáváno ${i}, obdrženo ${Z}`}case"invalid_value":return l.values.length===1?`Neplatný vstup: očekáváno ${D.stringifyPrimitive(l.values[0])}`:`Neplatná možnost: očekávána jedna z hodnot ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Hodnota je příliš velká: ${l.origin??"hodnota"} musí mít ${i}${l.maximum.toString()} ${I.unit??"prvků"}`:`Hodnota je příliš velká: ${l.origin??"hodnota"} musí být ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Hodnota je příliš malá: ${l.origin??"hodnota"} musí mít ${i}${l.minimum.toString()} ${I.unit??"prvků"}`:`Hodnota je příliš malá: ${l.origin??"hodnota"} musí být ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Neplatný řetězec: musí začínat na "${i.prefix}"`:i.format==="ends_with"?`Neplatný řetězec: musí končit na "${i.suffix}"`:i.format==="includes"?`Neplatný řetězec: musí obsahovat "${i.includes}"`:i.format==="regex"?`Neplatný řetězec: musí odpovídat vzoru ${i.pattern}`:`Neplatný formát ${x[i.format]??l.format}`}case"not_multiple_of":return`Neplatné číslo: musí být násobkem ${l.divisor}`;case"unrecognized_keys":return`Neznámé klíče: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Neplatný klíč v ${l.origin}`;case"invalid_union":return"Neplatný vstup";case"invalid_element":return`Neplatná hodnota v ${l.origin}`;default:return"Neplatný vstup"}}};function J(){return{localeError:V()}}o.exports=_.default})(ru,ru.exports);var gW=ru.exports,nu={exports:{}},Gs=nu.exports;(function(o,_){var R=Gs&&Gs.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Gs&&Gs.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Gs&&Gs.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function v(l){return b[l]??null}const x={regex:"input",email:"e-mailadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslæt",date:"ISO-dato",time:"ISO-klokkeslæt",duration:"ISO-varighed",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},w={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"sæt",file:"fil"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Ugyldigt input: forventede instanceof ${l.expected}, fik ${Z}`:`Ugyldigt input: forventede ${i}, fik ${Z}`}case"invalid_value":return l.values.length===1?`Ugyldig værdi: forventede ${D.stringifyPrimitive(l.values[0])}`:`Ugyldigt valg: forventede en af følgende ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin),Z=w[l.origin]??l.origin;return I?`For stor: forventede ${Z??"value"} ${I.verb} ${i} ${l.maximum.toString()} ${I.unit??"elementer"}`:`For stor: forventede ${Z??"value"} havde ${i} ${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin),Z=w[l.origin]??l.origin;return I?`For lille: forventede ${Z} ${I.verb} ${i} ${l.minimum.toString()} ${I.unit}`:`For lille: forventede ${Z} havde ${i} ${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Ugyldig streng: skal starte med "${i.prefix}"`:i.format==="ends_with"?`Ugyldig streng: skal ende med "${i.suffix}"`:i.format==="includes"?`Ugyldig streng: skal indeholde "${i.includes}"`:i.format==="regex"?`Ugyldig streng: skal matche mønsteret ${i.pattern}`:`Ugyldig ${x[i.format]??l.format}`}case"not_multiple_of":return`Ugyldigt tal: skal være deleligt med ${l.divisor}`;case"unrecognized_keys":return`${l.keys.length>1?"Ukendte nøgler":"Ukendt nøgle"}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Ugyldig nøgle i ${l.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig værdi i ${l.origin}`;default:return"Ugyldigt input"}}};function J(){return{localeError:V()}}o.exports=_.default})(nu,nu.exports);var pW=nu.exports,iu={exports:{}},Zs=iu.exports;(function(o,_){var R=Zs&&Zs.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Zs&&Zs.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Zs&&Zs.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function v(l){return b[l]??null}const x={regex:"Eingabe",email:"E-Mail-Adresse",url:"URL",emoji:"Emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},w={nan:"NaN",number:"Zahl",array:"Array"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Ungültige Eingabe: erwartet instanceof ${l.expected}, erhalten ${Z}`:`Ungültige Eingabe: erwartet ${i}, erhalten ${Z}`}case"invalid_value":return l.values.length===1?`Ungültige Eingabe: erwartet ${D.stringifyPrimitive(l.values[0])}`:`Ungültige Option: erwartet eine von ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Zu groß: erwartet, dass ${l.origin??"Wert"} ${i}${l.maximum.toString()} ${I.unit??"Elemente"} hat`:`Zu groß: erwartet, dass ${l.origin??"Wert"} ${i}${l.maximum.toString()} ist`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Zu klein: erwartet, dass ${l.origin} ${i}${l.minimum.toString()} ${I.unit} hat`:`Zu klein: erwartet, dass ${l.origin} ${i}${l.minimum.toString()} ist`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Ungültiger String: muss mit "${i.prefix}" beginnen`:i.format==="ends_with"?`Ungültiger String: muss mit "${i.suffix}" enden`:i.format==="includes"?`Ungültiger String: muss "${i.includes}" enthalten`:i.format==="regex"?`Ungültiger String: muss dem Muster ${i.pattern} entsprechen`:`Ungültig: ${x[i.format]??l.format}`}case"not_multiple_of":return`Ungültige Zahl: muss ein Vielfaches von ${l.divisor} sein`;case"unrecognized_keys":return`${l.keys.length>1?"Unbekannte Schlüssel":"Unbekannter Schlüssel"}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Ungültiger Schlüssel in ${l.origin}`;case"invalid_union":return"Ungültige Eingabe";case"invalid_element":return`Ungültiger Wert in ${l.origin}`;default:return"Ungültige Eingabe"}}};function J(){return{localeError:V()}}o.exports=_.default})(iu,iu.exports);var vW=iu.exports,su={exports:{}},Vs=su.exports;(function(o,_){var R=Vs&&Vs.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Vs&&Vs.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Vs&&Vs.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"χαρακτήρες",verb:"να έχει"},file:{unit:"bytes",verb:"να έχει"},array:{unit:"στοιχεία",verb:"να έχει"},set:{unit:"στοιχεία",verb:"να έχει"},map:{unit:"καταχωρήσεις",verb:"να έχει"}};function v(l){return b[l]??null}const x={regex:"είσοδος",email:"διεύθυνση email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ημερομηνία και ώρα",date:"ISO ημερομηνία",time:"ISO ώρα",duration:"ISO διάρκεια",ipv4:"διεύθυνση IPv4",ipv6:"διεύθυνση IPv6",mac:"διεύθυνση MAC",cidrv4:"εύρος IPv4",cidrv6:"εύρος IPv6",base64:"συμβολοσειρά κωδικοποιημένη σε base64",base64url:"συμβολοσειρά κωδικοποιημένη σε base64url",json_string:"συμβολοσειρά JSON",e164:"αριθμός E.164",jwt:"JWT",template_literal:"είσοδος"},w={nan:"NaN"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return typeof l.expected=="string"&&/^[A-Z]/.test(l.expected)?`Μη έγκυρη είσοδος: αναμενόταν instanceof ${l.expected}, λήφθηκε ${Z}`:`Μη έγκυρη είσοδος: αναμενόταν ${i}, λήφθηκε ${Z}`}case"invalid_value":return l.values.length===1?`Μη έγκυρη είσοδος: αναμενόταν ${D.stringifyPrimitive(l.values[0])}`:`Μη έγκυρη επιλογή: αναμενόταν ένα από ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Πολύ μεγάλο: αναμενόταν ${l.origin??"τιμή"} να έχει ${i}${l.maximum.toString()} ${I.unit??"στοιχεία"}`:`Πολύ μεγάλο: αναμενόταν ${l.origin??"τιμή"} να είναι ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Πολύ μικρό: αναμενόταν ${l.origin} να έχει ${i}${l.minimum.toString()} ${I.unit}`:`Πολύ μικρό: αναμενόταν ${l.origin} να είναι ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Μη έγκυρη συμβολοσειρά: πρέπει να ξεκινά με "${i.prefix}"`:i.format==="ends_with"?`Μη έγκυρη συμβολοσειρά: πρέπει να τελειώνει με "${i.suffix}"`:i.format==="includes"?`Μη έγκυρη συμβολοσειρά: πρέπει να περιέχει "${i.includes}"`:i.format==="regex"?`Μη έγκυρη συμβολοσειρά: πρέπει να ταιριάζει με το μοτίβο ${i.pattern}`:`Μη έγκυρο: ${x[i.format]??l.format}`}case"not_multiple_of":return`Μη έγκυρος αριθμός: πρέπει να είναι πολλαπλάσιο του ${l.divisor}`;case"unrecognized_keys":return`Άγνωστ${l.keys.length>1?"α":"ο"} κλειδ${l.keys.length>1?"ιά":"ί"}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Μη έγκυρο κλειδί στο ${l.origin}`;case"invalid_union":return"Μη έγκυρη είσοδος";case"invalid_element":return`Μη έγκυρη τιμή στο ${l.origin}`;default:return"Μη έγκυρη είσοδος"}}};function J(){return{localeError:V()}}o.exports=_.default})(su,su.exports);var bW=su.exports,au={exports:{}},Hs=au.exports;(function(o,_){var R=Hs&&Hs.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Hs&&Hs.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Hs&&Hs.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function v(l){return b[l]??null}const x={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},w={nan:"NaN"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return`Invalid input: expected ${i}, received ${Z}`}case"invalid_value":return l.values.length===1?`Invalid input: expected ${D.stringifyPrimitive(l.values[0])}`:`Invalid option: expected one of ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Too big: expected ${l.origin??"value"} to have ${i}${l.maximum.toString()} ${I.unit??"elements"}`:`Too big: expected ${l.origin??"value"} to be ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Too small: expected ${l.origin} to have ${i}${l.minimum.toString()} ${I.unit}`:`Too small: expected ${l.origin} to be ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Invalid string: must start with "${i.prefix}"`:i.format==="ends_with"?`Invalid string: must end with "${i.suffix}"`:i.format==="includes"?`Invalid string: must include "${i.includes}"`:i.format==="regex"?`Invalid string: must match pattern ${i.pattern}`:`Invalid ${x[i.format]??l.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${l.divisor}`;case"unrecognized_keys":return`Unrecognized key${l.keys.length>1?"s":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Invalid key in ${l.origin}`;case"invalid_union":return l.options&&Array.isArray(l.options)&&l.options.length>0?`Invalid discriminator value. Expected ${l.options.map(I=>`'${I}'`).join(" | ")}`:"Invalid input";case"invalid_element":return`Invalid value in ${l.origin}`;default:return"Invalid input"}}};function J(){return{localeError:V()}}o.exports=_.default})(au,au.exports);var Aw=au.exports,ou={exports:{}},Ks=ou.exports;(function(o,_){var R=Ks&&Ks.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Ks&&Ks.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Ks&&Ks.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function v(l){return b[l]??null}const x={regex:"enigo",email:"retadreso",url:"URL",emoji:"emoĝio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-daŭro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},w={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Nevalida enigo: atendiĝis instanceof ${l.expected}, riceviĝis ${Z}`:`Nevalida enigo: atendiĝis ${i}, riceviĝis ${Z}`}case"invalid_value":return l.values.length===1?`Nevalida enigo: atendiĝis ${D.stringifyPrimitive(l.values[0])}`:`Nevalida opcio: atendiĝis unu el ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Tro granda: atendiĝis ke ${l.origin??"valoro"} havu ${i}${l.maximum.toString()} ${I.unit??"elementojn"}`:`Tro granda: atendiĝis ke ${l.origin??"valoro"} havu ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Tro malgranda: atendiĝis ke ${l.origin} havu ${i}${l.minimum.toString()} ${I.unit}`:`Tro malgranda: atendiĝis ke ${l.origin} estu ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Nevalida karaktraro: devas komenciĝi per "${i.prefix}"`:i.format==="ends_with"?`Nevalida karaktraro: devas finiĝi per "${i.suffix}"`:i.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${i.includes}"`:i.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${i.pattern}`:`Nevalida ${x[i.format]??l.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${l.divisor}`;case"unrecognized_keys":return`Nekonata${l.keys.length>1?"j":""} ŝlosilo${l.keys.length>1?"j":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Nevalida ŝlosilo en ${l.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${l.origin}`;default:return"Nevalida enigo"}}};function J(){return{localeError:V()}}o.exports=_.default})(ou,ou.exports);var yW=ou.exports,lu={exports:{}},Ws=lu.exports;(function(o,_){var R=Ws&&Ws.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Ws&&Ws.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Ws&&Ws.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function v(l){return b[l]??null}const x={regex:"entrada",email:"dirección de correo electrónico",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duración ISO",ipv4:"dirección IPv4",ipv6:"dirección IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},w={nan:"NaN",string:"texto",number:"número",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"número grande",symbol:"símbolo",undefined:"indefinido",null:"nulo",function:"función",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeración",union:"unión",literal:"literal",promise:"promesa",void:"vacío",never:"nunca",unknown:"desconocido",any:"cualquiera"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Entrada inválida: se esperaba instanceof ${l.expected}, recibido ${Z}`:`Entrada inválida: se esperaba ${i}, recibido ${Z}`}case"invalid_value":return l.values.length===1?`Entrada inválida: se esperaba ${D.stringifyPrimitive(l.values[0])}`:`Opción inválida: se esperaba una de ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin),Z=w[l.origin]??l.origin;return I?`Demasiado grande: se esperaba que ${Z??"valor"} tuviera ${i}${l.maximum.toString()} ${I.unit??"elementos"}`:`Demasiado grande: se esperaba que ${Z??"valor"} fuera ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin),Z=w[l.origin]??l.origin;return I?`Demasiado pequeño: se esperaba que ${Z} tuviera ${i}${l.minimum.toString()} ${I.unit}`:`Demasiado pequeño: se esperaba que ${Z} fuera ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Cadena inválida: debe comenzar con "${i.prefix}"`:i.format==="ends_with"?`Cadena inválida: debe terminar en "${i.suffix}"`:i.format==="includes"?`Cadena inválida: debe incluir "${i.includes}"`:i.format==="regex"?`Cadena inválida: debe coincidir con el patrón ${i.pattern}`:`Inválido ${x[i.format]??l.format}`}case"not_multiple_of":return`Número inválido: debe ser múltiplo de ${l.divisor}`;case"unrecognized_keys":return`Llave${l.keys.length>1?"s":""} desconocida${l.keys.length>1?"s":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Llave inválida en ${w[l.origin]??l.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido en ${w[l.origin]??l.origin}`;default:return"Entrada inválida"}}};function J(){return{localeError:V()}}o.exports=_.default})(lu,lu.exports);var xW=lu.exports,cu={exports:{}},qs=cu.exports;(function(o,_){var R=qs&&qs.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=qs&&qs.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=qs&&qs.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"کاراکتر",verb:"داشته باشد"},file:{unit:"بایت",verb:"داشته باشد"},array:{unit:"آیتم",verb:"داشته باشد"},set:{unit:"آیتم",verb:"داشته باشد"}};function v(l){return b[l]??null}const x={regex:"ورودی",email:"آدرس ایمیل",url:"URL",emoji:"ایموجی",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"تاریخ و زمان ایزو",date:"تاریخ ایزو",time:"زمان ایزو",duration:"مدت زمان ایزو",ipv4:"IPv4 آدرس",ipv6:"IPv6 آدرس",cidrv4:"IPv4 دامنه",cidrv6:"IPv6 دامنه",base64:"base64-encoded رشته",base64url:"base64url-encoded رشته",json_string:"JSON رشته",e164:"E.164 عدد",jwt:"JWT",template_literal:"ورودی"},w={nan:"NaN",number:"عدد",array:"آرایه"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`ورودی نامعتبر: می‌بایست instanceof ${l.expected} می‌بود، ${Z} دریافت شد`:`ورودی نامعتبر: می‌بایست ${i} می‌بود، ${Z} دریافت شد`}case"invalid_value":return l.values.length===1?`ورودی نامعتبر: می‌بایست ${D.stringifyPrimitive(l.values[0])} می‌بود`:`گزینه نامعتبر: می‌بایست یکی از ${D.joinValues(l.values,"|")} می‌بود`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`خیلی بزرگ: ${l.origin??"مقدار"} باید ${i}${l.maximum.toString()} ${I.unit??"عنصر"} باشد`:`خیلی بزرگ: ${l.origin??"مقدار"} باید ${i}${l.maximum.toString()} باشد`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`خیلی کوچک: ${l.origin} باید ${i}${l.minimum.toString()} ${I.unit} باشد`:`خیلی کوچک: ${l.origin} باید ${i}${l.minimum.toString()} باشد`}case"invalid_format":{const i=l;return i.format==="starts_with"?`رشته نامعتبر: باید با "${i.prefix}" شروع شود`:i.format==="ends_with"?`رشته نامعتبر: باید با "${i.suffix}" تمام شود`:i.format==="includes"?`رشته نامعتبر: باید شامل "${i.includes}" باشد`:i.format==="regex"?`رشته نامعتبر: باید با الگوی ${i.pattern} مطابقت داشته باشد`:`${x[i.format]??l.format} نامعتبر`}case"not_multiple_of":return`عدد نامعتبر: باید مضرب ${l.divisor} باشد`;case"unrecognized_keys":return`کلید${l.keys.length>1?"های":""} ناشناس: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`کلید ناشناس در ${l.origin}`;case"invalid_union":return"ورودی نامعتبر";case"invalid_element":return`مقدار نامعتبر در ${l.origin}`;default:return"ورودی نامعتبر"}}};function J(){return{localeError:V()}}o.exports=_.default})(cu,cu.exports);var SW=cu.exports,uu={exports:{}},Qs=uu.exports;(function(o,_){var R=Qs&&Qs.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Qs&&Qs.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Qs&&Qs.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"merkkiä",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"päivämäärän"}};function v(l){return b[l]??null}const x={regex:"säännöllinen lauseke",email:"sähköpostiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-päivämäärä",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},w={nan:"NaN"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Virheellinen tyyppi: odotettiin instanceof ${l.expected}, oli ${Z}`:`Virheellinen tyyppi: odotettiin ${i}, oli ${Z}`}case"invalid_value":return l.values.length===1?`Virheellinen syöte: täytyy olla ${D.stringifyPrimitive(l.values[0])}`:`Virheellinen valinta: täytyy olla yksi seuraavista: ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Liian suuri: ${I.subject} täytyy olla ${i}${l.maximum.toString()} ${I.unit}`.trim():`Liian suuri: arvon täytyy olla ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Liian pieni: ${I.subject} täytyy olla ${i}${l.minimum.toString()} ${I.unit}`.trim():`Liian pieni: arvon täytyy olla ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Virheellinen syöte: täytyy alkaa "${i.prefix}"`:i.format==="ends_with"?`Virheellinen syöte: täytyy loppua "${i.suffix}"`:i.format==="includes"?`Virheellinen syöte: täytyy sisältää "${i.includes}"`:i.format==="regex"?`Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${i.pattern}`:`Virheellinen ${x[i.format]??l.format}`}case"not_multiple_of":return`Virheellinen luku: täytyy olla luvun ${l.divisor} monikerta`;case"unrecognized_keys":return`${l.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen syöte"}}};function J(){return{localeError:V()}}o.exports=_.default})(uu,uu.exports);var _W=uu.exports,du={exports:{}},Ys=du.exports;(function(o,_){var R=Ys&&Ys.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Ys&&Ys.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Ys&&Ys.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function v(l){return b[l]??null}const x={regex:"entrée",email:"adresse e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},w={string:"chaîne",number:"nombre",int:"entier",boolean:"booléen",bigint:"grand entier",symbol:"symbole",undefined:"indéfini",null:"null",never:"jamais",void:"vide",date:"date",array:"tableau",object:"objet",tuple:"tuple",record:"enregistrement",map:"carte",set:"ensemble",file:"fichier",nonoptional:"non-optionnel",nan:"NaN",function:"fonction"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Entrée invalide : instanceof ${l.expected} attendu, ${Z} reçu`:`Entrée invalide : ${i} attendu, ${Z} reçu`}case"invalid_value":return l.values.length===1?`Entrée invalide : ${D.stringifyPrimitive(l.values[0])} attendu`:`Option invalide : une valeur parmi ${D.joinValues(l.values,"|")} attendue`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Trop grand : ${w[l.origin]??"valeur"} doit ${I.verb} ${i}${l.maximum.toString()} ${I.unit??"élément(s)"}`:`Trop grand : ${w[l.origin]??"valeur"} doit être ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Trop petit : ${w[l.origin]??"valeur"} doit ${I.verb} ${i}${l.minimum.toString()} ${I.unit}`:`Trop petit : ${w[l.origin]??"valeur"} doit être ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Chaîne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Chaîne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Chaîne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Chaîne invalide : doit correspondre au modèle ${i.pattern}`:`${x[i.format]??l.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${l.divisor}`;case"unrecognized_keys":return`Clé${l.keys.length>1?"s":""} non reconnue${l.keys.length>1?"s":""} : ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${l.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${l.origin}`;default:return"Entrée invalide"}}};function J(){return{localeError:V()}}o.exports=_.default})(du,du.exports);var wW=du.exports,fu={exports:{}},Xs=fu.exports;(function(o,_){var R=Xs&&Xs.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Xs&&Xs.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Xs&&Xs.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"caractères",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"éléments",verb:"avoir"},set:{unit:"éléments",verb:"avoir"}};function v(l){return b[l]??null}const x={regex:"entrée",email:"adresse courriel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"durée ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"chaîne encodée en base64",base64url:"chaîne encodée en base64url",json_string:"chaîne JSON",e164:"numéro E.164",jwt:"JWT",template_literal:"entrée"},w={nan:"NaN"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Entrée invalide : attendu instanceof ${l.expected}, reçu ${Z}`:`Entrée invalide : attendu ${i}, reçu ${Z}`}case"invalid_value":return l.values.length===1?`Entrée invalide : attendu ${D.stringifyPrimitive(l.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"≤":"<",I=v(l.origin);return I?`Trop grand : attendu que ${l.origin??"la valeur"} ait ${i}${l.maximum.toString()} ${I.unit}`:`Trop grand : attendu que ${l.origin??"la valeur"} soit ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?"≥":">",I=v(l.origin);return I?`Trop petit : attendu que ${l.origin} ait ${i}${l.minimum.toString()} ${I.unit}`:`Trop petit : attendu que ${l.origin} soit ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Chaîne invalide : doit commencer par "${i.prefix}"`:i.format==="ends_with"?`Chaîne invalide : doit se terminer par "${i.suffix}"`:i.format==="includes"?`Chaîne invalide : doit inclure "${i.includes}"`:i.format==="regex"?`Chaîne invalide : doit correspondre au motif ${i.pattern}`:`${x[i.format]??l.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit être un multiple de ${l.divisor}`;case"unrecognized_keys":return`Clé${l.keys.length>1?"s":""} non reconnue${l.keys.length>1?"s":""} : ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Clé invalide dans ${l.origin}`;case"invalid_union":return"Entrée invalide";case"invalid_element":return`Valeur invalide dans ${l.origin}`;default:return"Entrée invalide"}}};function J(){return{localeError:V()}}o.exports=_.default})(fu,fu.exports);var EW=fu.exports,hu={exports:{}},Js=hu.exports;(function(o,_){var R=Js&&Js.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Js&&Js.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Js&&Js.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{label:"מחרוזת",gender:"f"},number:{label:"מספר",gender:"m"},boolean:{label:"ערך בוליאני",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"תאריך",gender:"m"},array:{label:"מערך",gender:"m"},object:{label:"אובייקט",gender:"m"},null:{label:"ערך ריק (null)",gender:"m"},undefined:{label:"ערך לא מוגדר (undefined)",gender:"m"},symbol:{label:"סימבול (Symbol)",gender:"m"},function:{label:"פונקציה",gender:"f"},map:{label:"מפה (Map)",gender:"f"},set:{label:"קבוצה (Set)",gender:"f"},file:{label:"קובץ",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"ערך לא ידוע",gender:"m"},value:{label:"ערך",gender:"m"}},v={string:{unit:"תווים",shortLabel:"קצר",longLabel:"ארוך"},file:{unit:"בייטים",shortLabel:"קטן",longLabel:"גדול"},array:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},set:{unit:"פריטים",shortLabel:"קטן",longLabel:"גדול"},number:{unit:"",shortLabel:"קטן",longLabel:"גדול"}},x=ve=>ve?b[ve]:void 0,w=ve=>{const Te=x(ve);return Te?Te.label:ve??b.unknown.label},l=ve=>`ה${w(ve)}`,i=ve=>(x(ve)?.gender??"m")==="f"?"צריכה להיות":"צריך להיות",I=ve=>ve?v[ve]??null:null,Z={regex:{label:"קלט",gender:"m"},email:{label:"כתובת אימייל",gender:"f"},url:{label:"כתובת רשת",gender:"f"},emoji:{label:"אימוג'י",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"תאריך וזמן ISO",gender:"m"},date:{label:"תאריך ISO",gender:"m"},time:{label:"זמן ISO",gender:"m"},duration:{label:"משך זמן ISO",gender:"m"},ipv4:{label:"כתובת IPv4",gender:"f"},ipv6:{label:"כתובת IPv6",gender:"f"},cidrv4:{label:"טווח IPv4",gender:"m"},cidrv6:{label:"טווח IPv6",gender:"m"},base64:{label:"מחרוזת בבסיס 64",gender:"f"},base64url:{label:"מחרוזת בבסיס 64 לכתובות רשת",gender:"f"},json_string:{label:"מחרוזת JSON",gender:"f"},e164:{label:"מספר E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"קלט",gender:"m"},includes:{label:"קלט",gender:"m"},lowercase:{label:"קלט",gender:"m"},starts_with:{label:"קלט",gender:"m"},uppercase:{label:"קלט",gender:"m"}},ye={nan:"NaN"};return ve=>{switch(ve.code){case"invalid_type":{const Te=ve.expected,_e=ye[Te??""]??w(Te),Oe=D.parsedType(ve.input),W=ye[Oe]??b[Oe]?.label??Oe;return/^[A-Z]/.test(ve.expected)?`קלט לא תקין: צריך להיות instanceof ${ve.expected}, התקבל ${W}`:`קלט לא תקין: צריך להיות ${_e}, התקבל ${W}`}case"invalid_value":{if(ve.values.length===1)return`ערך לא תקין: הערך חייב להיות ${D.stringifyPrimitive(ve.values[0])}`;const Te=ve.values.map(W=>D.stringifyPrimitive(W));if(ve.values.length===2)return`ערך לא תקין: האפשרויות המתאימות הן ${Te[0]} או ${Te[1]}`;const _e=Te[Te.length-1];return`ערך לא תקין: האפשרויות המתאימות הן ${Te.slice(0,-1).join(", ")} או ${_e}`}case"too_big":{const Te=I(ve.origin),_e=l(ve.origin??"value");if(ve.origin==="string")return`${Te?.longLabel??"ארוך"} מדי: ${_e} צריכה להכיל ${ve.maximum.toString()} ${Te?.unit??""} ${ve.inclusive?"או פחות":"לכל היותר"}`.trim();if(ve.origin==="number"){const Ze=ve.inclusive?`קטן או שווה ל-${ve.maximum}`:`קטן מ-${ve.maximum}`;return`גדול מדי: ${_e} צריך להיות ${Ze}`}if(ve.origin==="array"||ve.origin==="set"){const Ze=ve.origin==="set"?"צריכה":"צריך",Le=ve.inclusive?`${ve.maximum} ${Te?.unit??""} או פחות`:`פחות מ-${ve.maximum} ${Te?.unit??""}`;return`גדול מדי: ${_e} ${Ze} להכיל ${Le}`.trim()}const Oe=ve.inclusive?"<=":"<",W=i(ve.origin??"value");return Te?.unit?`${Te.longLabel} מדי: ${_e} ${W} ${Oe}${ve.maximum.toString()} ${Te.unit}`:`${Te?.longLabel??"גדול"} מדי: ${_e} ${W} ${Oe}${ve.maximum.toString()}`}case"too_small":{const Te=I(ve.origin),_e=l(ve.origin??"value");if(ve.origin==="string")return`${Te?.shortLabel??"קצר"} מדי: ${_e} צריכה להכיל ${ve.minimum.toString()} ${Te?.unit??""} ${ve.inclusive?"או יותר":"לפחות"}`.trim();if(ve.origin==="number"){const Ze=ve.inclusive?`גדול או שווה ל-${ve.minimum}`:`גדול מ-${ve.minimum}`;return`קטן מדי: ${_e} צריך להיות ${Ze}`}if(ve.origin==="array"||ve.origin==="set"){const Ze=ve.origin==="set"?"צריכה":"צריך";if(ve.minimum===1&&ve.inclusive){const ot=(ve.origin==="set","לפחות פריט אחד");return`קטן מדי: ${_e} ${Ze} להכיל ${ot}`}const Le=ve.inclusive?`${ve.minimum} ${Te?.unit??""} או יותר`:`יותר מ-${ve.minimum} ${Te?.unit??""}`;return`קטן מדי: ${_e} ${Ze} להכיל ${Le}`.trim()}const Oe=ve.inclusive?">=":">",W=i(ve.origin??"value");return Te?.unit?`${Te.shortLabel} מדי: ${_e} ${W} ${Oe}${ve.minimum.toString()} ${Te.unit}`:`${Te?.shortLabel??"קטן"} מדי: ${_e} ${W} ${Oe}${ve.minimum.toString()}`}case"invalid_format":{const Te=ve;if(Te.format==="starts_with")return`המחרוזת חייבת להתחיל ב "${Te.prefix}"`;if(Te.format==="ends_with")return`המחרוזת חייבת להסתיים ב "${Te.suffix}"`;if(Te.format==="includes")return`המחרוזת חייבת לכלול "${Te.includes}"`;if(Te.format==="regex")return`המחרוזת חייבת להתאים לתבנית ${Te.pattern}`;const _e=Z[Te.format],Oe=_e?.label??Te.format,Ze=(_e?.gender??"m")==="f"?"תקינה":"תקין";return`${Oe} לא ${Ze}`}case"not_multiple_of":return`מספר לא תקין: חייב להיות מכפלה של ${ve.divisor}`;case"unrecognized_keys":return`מפתח${ve.keys.length>1?"ות":""} לא מזוה${ve.keys.length>1?"ים":"ה"}: ${D.joinValues(ve.keys,", ")}`;case"invalid_key":return"שדה לא תקין באובייקט";case"invalid_union":return"קלט לא תקין";case"invalid_element":return`ערך לא תקין ב${l(ve.origin??"array")}`;default:return"קלט לא תקין"}}};function J(){return{localeError:V()}}o.exports=_.default})(hu,hu.exports);var kW=hu.exports,mu={exports:{}},ea=mu.exports;(function(o,_){var R=ea&&ea.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=ea&&ea.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=ea&&ea.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"znakova",verb:"imati"},file:{unit:"bajtova",verb:"imati"},array:{unit:"stavki",verb:"imati"},set:{unit:"stavki",verb:"imati"}};function v(l){return b[l]??null}const x={regex:"unos",email:"email adresa",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum i vrijeme",date:"ISO datum",time:"ISO vrijeme",duration:"ISO trajanje",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"IPv4 raspon",cidrv6:"IPv6 raspon",base64:"base64 kodirani tekst",base64url:"base64url kodirani tekst",json_string:"JSON tekst",e164:"E.164 broj",jwt:"JWT",template_literal:"unos"},w={nan:"NaN",string:"tekst",number:"broj",boolean:"boolean",array:"niz",object:"objekt",set:"skup",file:"datoteka",date:"datum",bigint:"bigint",symbol:"simbol",undefined:"undefined",null:"null",function:"funkcija",map:"mapa"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Neispravan unos: očekuje se instanceof ${l.expected}, a primljeno je ${Z}`:`Neispravan unos: očekuje se ${i}, a primljeno je ${Z}`}case"invalid_value":return l.values.length===1?`Neispravna vrijednost: očekivano ${D.stringifyPrimitive(l.values[0])}`:`Neispravna opcija: očekivano jedno od ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin),Z=w[l.origin]??l.origin;return I?`Preveliko: očekivano da ${Z??"vrijednost"} ima ${i}${l.maximum.toString()} ${I.unit??"elemenata"}`:`Preveliko: očekivano da ${Z??"vrijednost"} bude ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin),Z=w[l.origin]??l.origin;return I?`Premalo: očekivano da ${Z} ima ${i}${l.minimum.toString()} ${I.unit}`:`Premalo: očekivano da ${Z} bude ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Neispravan tekst: mora započinjati s "${i.prefix}"`:i.format==="ends_with"?`Neispravan tekst: mora završavati s "${i.suffix}"`:i.format==="includes"?`Neispravan tekst: mora sadržavati "${i.includes}"`:i.format==="regex"?`Neispravan tekst: mora odgovarati uzorku ${i.pattern}`:`Neispravna ${x[i.format]??l.format}`}case"not_multiple_of":return`Neispravan broj: mora biti višekratnik od ${l.divisor}`;case"unrecognized_keys":return`Neprepoznat${l.keys.length>1?"i ključevi":" ključ"}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Neispravan ključ u ${w[l.origin]??l.origin}`;case"invalid_union":return"Neispravan unos";case"invalid_element":return`Neispravna vrijednost u ${w[l.origin]??l.origin}`;default:return"Neispravan unos"}}};function J(){return{localeError:V()}}o.exports=_.default})(mu,mu.exports);var TW=mu.exports,gu={exports:{}},ta=gu.exports;(function(o,_){var R=ta&&ta.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=ta&&ta.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=ta&&ta.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function v(l){return b[l]??null}const x={regex:"bemenet",email:"email cím",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO időbélyeg",date:"ISO dátum",time:"ISO idő",duration:"ISO időintervallum",ipv4:"IPv4 cím",ipv6:"IPv6 cím",cidrv4:"IPv4 tartomány",cidrv6:"IPv6 tartomány",base64:"base64-kódolt string",base64url:"base64url-kódolt string",json_string:"JSON string",e164:"E.164 szám",jwt:"JWT",template_literal:"bemenet"},w={nan:"NaN",number:"szám",array:"tömb"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Érvénytelen bemenet: a várt érték instanceof ${l.expected}, a kapott érték ${Z}`:`Érvénytelen bemenet: a várt érték ${i}, a kapott érték ${Z}`}case"invalid_value":return l.values.length===1?`Érvénytelen bemenet: a várt érték ${D.stringifyPrimitive(l.values[0])}`:`Érvénytelen opció: valamelyik érték várt ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Túl nagy: ${l.origin??"érték"} mérete túl nagy ${i}${l.maximum.toString()} ${I.unit??"elem"}`:`Túl nagy: a bemeneti érték ${l.origin??"érték"} túl nagy: ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Túl kicsi: a bemeneti érték ${l.origin} mérete túl kicsi ${i}${l.minimum.toString()} ${I.unit}`:`Túl kicsi: a bemeneti érték ${l.origin} túl kicsi ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Érvénytelen string: "${i.prefix}" értékkel kell kezdődnie`:i.format==="ends_with"?`Érvénytelen string: "${i.suffix}" értékkel kell végződnie`:i.format==="includes"?`Érvénytelen string: "${i.includes}" értéket kell tartalmaznia`:i.format==="regex"?`Érvénytelen string: ${i.pattern} mintának kell megfelelnie`:`Érvénytelen ${x[i.format]??l.format}`}case"not_multiple_of":return`Érvénytelen szám: ${l.divisor} többszörösének kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${l.keys.length>1?"s":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Érvénytelen kulcs ${l.origin}`;case"invalid_union":return"Érvénytelen bemenet";case"invalid_element":return`Érvénytelen érték: ${l.origin}`;default:return"Érvénytelen bemenet"}}};function J(){return{localeError:V()}}o.exports=_.default})(gu,gu.exports);var CW=gu.exports,pu={exports:{}},ra=pu.exports;(function(o,_){var R=ra&&ra.__createBinding||(Object.create?(function(x,w,l,i){i===void 0&&(i=l);var I=Object.getOwnPropertyDescriptor(w,l);(!I||("get"in I?!w.__esModule:I.writable||I.configurable))&&(I={enumerable:!0,get:function(){return w[l]}}),Object.defineProperty(x,i,I)}):(function(x,w,l,i){i===void 0&&(i=l),x[i]=w[l]})),F=ra&&ra.__setModuleDefault||(Object.create?(function(x,w){Object.defineProperty(x,"default",{enumerable:!0,value:w})}):function(x,w){x.default=w}),P=ra&&ra.__importStar||function(x){if(x&&x.__esModule)return x;var w={};if(x!=null)for(var l in x)l!=="default"&&Object.prototype.hasOwnProperty.call(x,l)&&R(w,x,l);return F(w,x),w};Object.defineProperty(_,"__esModule",{value:!0}),_.default=v;const D=P(Ie);function V(x,w,l){return Math.abs(x)===1?w:l}function J(x){if(!x)return"";const w=["ա","ե","ը","ի","ո","ու","օ"],l=x[x.length-1];return x+(w.includes(l)?"ն":"ը")}const b=()=>{const x={string:{unit:{one:"նշան",many:"նշաններ"},verb:"ունենալ"},file:{unit:{one:"բայթ",many:"բայթեր"},verb:"ունենալ"},array:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"},set:{unit:{one:"տարր",many:"տարրեր"},verb:"ունենալ"}};function w(I){return x[I]??null}const l={regex:"մուտք",email:"էլ. հասցե",url:"URL",emoji:"էմոջի",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO ամսաթիվ և ժամ",date:"ISO ամսաթիվ",time:"ISO ժամ",duration:"ISO տևողություն",ipv4:"IPv4 հասցե",ipv6:"IPv6 հասցե",cidrv4:"IPv4 միջակայք",cidrv6:"IPv6 միջակայք",base64:"base64 ձևաչափով տող",base64url:"base64url ձևաչափով տող",json_string:"JSON տող",e164:"E.164 համար",jwt:"JWT",template_literal:"մուտք"},i={nan:"NaN",number:"թիվ",array:"զանգված"};return I=>{switch(I.code){case"invalid_type":{const Z=i[I.expected]??I.expected,ye=D.parsedType(I.input),ve=i[ye]??ye;return/^[A-Z]/.test(I.expected)?`Սխալ մուտքագրում․ սպասվում էր instanceof ${I.expected}, ստացվել է ${ve}`:`Սխալ մուտքագրում․ սպասվում էր ${Z}, ստացվել է ${ve}`}case"invalid_value":return I.values.length===1?`Սխալ մուտքագրում․ սպասվում էր ${D.stringifyPrimitive(I.values[1])}`:`Սխալ տարբերակ․ սպասվում էր հետևյալներից մեկը՝ ${D.joinValues(I.values,"|")}`;case"too_big":{const Z=I.inclusive?"<=":"<",ye=w(I.origin);if(ye){const ve=Number(I.maximum),Te=V(ve,ye.unit.one,ye.unit.many);return`Չափազանց մեծ արժեք․ սպասվում է, որ ${J(I.origin??"արժեք")} կունենա ${Z}${I.maximum.toString()} ${Te}`}return`Չափազանց մեծ արժեք․ սպասվում է, որ ${J(I.origin??"արժեք")} լինի ${Z}${I.maximum.toString()}`}case"too_small":{const Z=I.inclusive?">=":">",ye=w(I.origin);if(ye){const ve=Number(I.minimum),Te=V(ve,ye.unit.one,ye.unit.many);return`Չափազանց փոքր արժեք․ սպասվում է, որ ${J(I.origin)} կունենա ${Z}${I.minimum.toString()} ${Te}`}return`Չափազանց փոքր արժեք․ սպասվում է, որ ${J(I.origin)} լինի ${Z}${I.minimum.toString()}`}case"invalid_format":{const Z=I;return Z.format==="starts_with"?`Սխալ տող․ պետք է սկսվի "${Z.prefix}"-ով`:Z.format==="ends_with"?`Սխալ տող․ պետք է ավարտվի "${Z.suffix}"-ով`:Z.format==="includes"?`Սխալ տող․ պետք է պարունակի "${Z.includes}"`:Z.format==="regex"?`Սխալ տող․ պետք է համապատասխանի ${Z.pattern} ձևաչափին`:`Սխալ ${l[Z.format]??I.format}`}case"not_multiple_of":return`Սխալ թիվ․ պետք է բազմապատիկ լինի ${I.divisor}-ի`;case"unrecognized_keys":return`Չճանաչված բանալի${I.keys.length>1?"ներ":""}. ${D.joinValues(I.keys,", ")}`;case"invalid_key":return`Սխալ բանալի ${J(I.origin)}-ում`;case"invalid_union":return"Սխալ մուտքագրում";case"invalid_element":return`Սխալ արժեք ${J(I.origin)}-ում`;default:return"Սխալ մուտքագրում"}}};function v(){return{localeError:b()}}o.exports=_.default})(pu,pu.exports);var IW=pu.exports,vu={exports:{}},na=vu.exports;(function(o,_){var R=na&&na.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=na&&na.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=na&&na.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function v(l){return b[l]??null}const x={regex:"input",email:"alamat email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},w={nan:"NaN"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Input tidak valid: diharapkan instanceof ${l.expected}, diterima ${Z}`:`Input tidak valid: diharapkan ${i}, diterima ${Z}`}case"invalid_value":return l.values.length===1?`Input tidak valid: diharapkan ${D.stringifyPrimitive(l.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Terlalu besar: diharapkan ${l.origin??"value"} memiliki ${i}${l.maximum.toString()} ${I.unit??"elemen"}`:`Terlalu besar: diharapkan ${l.origin??"value"} menjadi ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Terlalu kecil: diharapkan ${l.origin} memiliki ${i}${l.minimum.toString()} ${I.unit}`:`Terlalu kecil: diharapkan ${l.origin} menjadi ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`String tidak valid: harus dimulai dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak valid: harus berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak valid: harus menyertakan "${i.includes}"`:i.format==="regex"?`String tidak valid: harus sesuai pola ${i.pattern}`:`${x[i.format]??l.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${l.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${l.keys.length>1?"s":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${l.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${l.origin}`;default:return"Input tidak valid"}}};function J(){return{localeError:V()}}o.exports=_.default})(vu,vu.exports);var PW=vu.exports,bu={exports:{}},ia=bu.exports;(function(o,_){var R=ia&&ia.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=ia&&ia.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=ia&&ia.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"stafi",verb:"að hafa"},file:{unit:"bæti",verb:"að hafa"},array:{unit:"hluti",verb:"að hafa"},set:{unit:"hluti",verb:"að hafa"}};function v(l){return b[l]??null}const x={regex:"gildi",email:"netfang",url:"vefslóð",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og tími",date:"ISO dagsetning",time:"ISO tími",duration:"ISO tímalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 tölugildi",jwt:"JWT",template_literal:"gildi"},w={nan:"NaN",number:"númer",array:"fylki"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Rangt gildi: Þú slóst inn ${Z} þar sem á að vera instanceof ${l.expected}`:`Rangt gildi: Þú slóst inn ${Z} þar sem á að vera ${i}`}case"invalid_value":return l.values.length===1?`Rangt gildi: gert ráð fyrir ${D.stringifyPrimitive(l.values[0])}`:`Ógilt val: má vera eitt af eftirfarandi ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Of stórt: gert er ráð fyrir að ${l.origin??"gildi"} hafi ${i}${l.maximum.toString()} ${I.unit??"hluti"}`:`Of stórt: gert er ráð fyrir að ${l.origin??"gildi"} sé ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Of lítið: gert er ráð fyrir að ${l.origin} hafi ${i}${l.minimum.toString()} ${I.unit}`:`Of lítið: gert er ráð fyrir að ${l.origin} sé ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Ógildur strengur: verður að byrja á "${i.prefix}"`:i.format==="ends_with"?`Ógildur strengur: verður að enda á "${i.suffix}"`:i.format==="includes"?`Ógildur strengur: verður að innihalda "${i.includes}"`:i.format==="regex"?`Ógildur strengur: verður að fylgja mynstri ${i.pattern}`:`Rangt ${x[i.format]??l.format}`}case"not_multiple_of":return`Röng tala: verður að vera margfeldi af ${l.divisor}`;case"unrecognized_keys":return`Óþekkt ${l.keys.length>1?"ir lyklar":"ur lykill"}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Rangur lykill í ${l.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi í ${l.origin}`;default:return"Rangt gildi"}}};function J(){return{localeError:V()}}o.exports=_.default})(bu,bu.exports);var AW=bu.exports,yu={exports:{}},sa=yu.exports;(function(o,_){var R=sa&&sa.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=sa&&sa.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=sa&&sa.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function v(l){return b[l]??null}const x={regex:"input",email:"indirizzo email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},w={nan:"NaN",number:"numero",array:"vettore"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Input non valido: atteso instanceof ${l.expected}, ricevuto ${Z}`:`Input non valido: atteso ${i}, ricevuto ${Z}`}case"invalid_value":return l.values.length===1?`Input non valido: atteso ${D.stringifyPrimitive(l.values[0])}`:`Opzione non valida: atteso uno tra ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Troppo grande: ${l.origin??"valore"} deve avere ${i}${l.maximum.toString()} ${I.unit??"elementi"}`:`Troppo grande: ${l.origin??"valore"} deve essere ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Troppo piccolo: ${l.origin} deve avere ${i}${l.minimum.toString()} ${I.unit}`:`Troppo piccolo: ${l.origin} deve essere ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Stringa non valida: deve iniziare con "${i.prefix}"`:i.format==="ends_with"?`Stringa non valida: deve terminare con "${i.suffix}"`:i.format==="includes"?`Stringa non valida: deve includere "${i.includes}"`:i.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${i.pattern}`:`Input non valido: ${x[i.format]??l.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${l.divisor}`;case"unrecognized_keys":return`Chiav${l.keys.length>1?"i":"e"} non riconosciut${l.keys.length>1?"e":"a"}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${l.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${l.origin}`;default:return"Input non valido"}}};function J(){return{localeError:V()}}o.exports=_.default})(yu,yu.exports);var jW=yu.exports,xu={exports:{}},aa=xu.exports;(function(o,_){var R=aa&&aa.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=aa&&aa.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=aa&&aa.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"文字",verb:"である"},file:{unit:"バイト",verb:"である"},array:{unit:"要素",verb:"である"},set:{unit:"要素",verb:"である"}};function v(l){return b[l]??null}const x={regex:"入力値",email:"メールアドレス",url:"URL",emoji:"絵文字",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日時",date:"ISO日付",time:"ISO時刻",duration:"ISO期間",ipv4:"IPv4アドレス",ipv6:"IPv6アドレス",cidrv4:"IPv4範囲",cidrv6:"IPv6範囲",base64:"base64エンコード文字列",base64url:"base64urlエンコード文字列",json_string:"JSON文字列",e164:"E.164番号",jwt:"JWT",template_literal:"入力値"},w={nan:"NaN",number:"数値",array:"配列"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`無効な入力: instanceof ${l.expected}が期待されましたが、${Z}が入力されました`:`無効な入力: ${i}が期待されましたが、${Z}が入力されました`}case"invalid_value":return l.values.length===1?`無効な入力: ${D.stringifyPrimitive(l.values[0])}が期待されました`:`無効な選択: ${D.joinValues(l.values,"、")}のいずれかである必要があります`;case"too_big":{const i=l.inclusive?"以下である":"より小さい",I=v(l.origin);return I?`大きすぎる値: ${l.origin??"値"}は${l.maximum.toString()}${I.unit??"要素"}${i}必要があります`:`大きすぎる値: ${l.origin??"値"}は${l.maximum.toString()}${i}必要があります`}case"too_small":{const i=l.inclusive?"以上である":"より大きい",I=v(l.origin);return I?`小さすぎる値: ${l.origin}は${l.minimum.toString()}${I.unit}${i}必要があります`:`小さすぎる値: ${l.origin}は${l.minimum.toString()}${i}必要があります`}case"invalid_format":{const i=l;return i.format==="starts_with"?`無効な文字列: "${i.prefix}"で始まる必要があります`:i.format==="ends_with"?`無効な文字列: "${i.suffix}"で終わる必要があります`:i.format==="includes"?`無効な文字列: "${i.includes}"を含む必要があります`:i.format==="regex"?`無効な文字列: パターン${i.pattern}に一致する必要があります`:`無効な${x[i.format]??l.format}`}case"not_multiple_of":return`無効な数値: ${l.divisor}の倍数である必要があります`;case"unrecognized_keys":return`認識されていないキー${l.keys.length>1?"群":""}: ${D.joinValues(l.keys,"、")}`;case"invalid_key":return`${l.origin}内の無効なキー`;case"invalid_union":return"無効な入力";case"invalid_element":return`${l.origin}内の無効な値`;default:return"無効な入力"}}};function J(){return{localeError:V()}}o.exports=_.default})(xu,xu.exports);var NW=xu.exports,Su={exports:{}},oa=Su.exports;(function(o,_){var R=oa&&oa.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=oa&&oa.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=oa&&oa.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"სიმბოლო",verb:"უნდა შეიცავდეს"},file:{unit:"ბაიტი",verb:"უნდა შეიცავდეს"},array:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"},set:{unit:"ელემენტი",verb:"უნდა შეიცავდეს"}};function v(l){return b[l]??null}const x={regex:"შეყვანა",email:"ელ-ფოსტის მისამართი",url:"URL",emoji:"ემოჯი",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"თარიღი-დრო",date:"თარიღი",time:"დრო",duration:"ხანგრძლივობა",ipv4:"IPv4 მისამართი",ipv6:"IPv6 მისამართი",cidrv4:"IPv4 დიაპაზონი",cidrv6:"IPv6 დიაპაზონი",base64:"base64-კოდირებული ველი",base64url:"base64url-კოდირებული ველი",json_string:"JSON ველი",e164:"E.164 ნომერი",jwt:"JWT",template_literal:"შეყვანა"},w={nan:"NaN",number:"რიცხვი",string:"ველი",boolean:"ბულეანი",function:"ფუნქცია",array:"მასივი"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`არასწორი შეყვანა: მოსალოდნელი instanceof ${l.expected}, მიღებული ${Z}`:`არასწორი შეყვანა: მოსალოდნელი ${i}, მიღებული ${Z}`}case"invalid_value":return l.values.length===1?`არასწორი შეყვანა: მოსალოდნელი ${D.stringifyPrimitive(l.values[0])}`:`არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${D.joinValues(l.values,"|")}-დან`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`ზედმეტად დიდი: მოსალოდნელი ${l.origin??"მნიშვნელობა"} ${I.verb} ${i}${l.maximum.toString()} ${I.unit}`:`ზედმეტად დიდი: მოსალოდნელი ${l.origin??"მნიშვნელობა"} იყოს ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`ზედმეტად პატარა: მოსალოდნელი ${l.origin} ${I.verb} ${i}${l.minimum.toString()} ${I.unit}`:`ზედმეტად პატარა: მოსალოდნელი ${l.origin} იყოს ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`არასწორი ველი: უნდა იწყებოდეს "${i.prefix}"-ით`:i.format==="ends_with"?`არასწორი ველი: უნდა მთავრდებოდეს "${i.suffix}"-ით`:i.format==="includes"?`არასწორი ველი: უნდა შეიცავდეს "${i.includes}"-ს`:i.format==="regex"?`არასწორი ველი: უნდა შეესაბამებოდეს შაბლონს ${i.pattern}`:`არასწორი ${x[i.format]??l.format}`}case"not_multiple_of":return`არასწორი რიცხვი: უნდა იყოს ${l.divisor}-ის ჯერადი`;case"unrecognized_keys":return`უცნობი გასაღებ${l.keys.length>1?"ები":"ი"}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`არასწორი გასაღები ${l.origin}-ში`;case"invalid_union":return"არასწორი შეყვანა";case"invalid_element":return`არასწორი მნიშვნელობა ${l.origin}-ში`;default:return"არასწორი შეყვანა"}}};function J(){return{localeError:V()}}o.exports=_.default})(Su,Su.exports);var DW=Su.exports,_u={exports:{}},wu={exports:{}},la=wu.exports;(function(o,_){var R=la&&la.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=la&&la.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=la&&la.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"តួអក្សរ",verb:"គួរមាន"},file:{unit:"បៃ",verb:"គួរមាន"},array:{unit:"ធាតុ",verb:"គួរមាន"},set:{unit:"ធាតុ",verb:"គួរមាន"}};function v(l){return b[l]??null}const x={regex:"ទិន្នន័យបញ្ចូល",email:"អាសយដ្ឋានអ៊ីមែល",url:"URL",emoji:"សញ្ញាអារម្មណ៍",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"កាលបរិច្ឆេទ និងម៉ោង ISO",date:"កាលបរិច្ឆេទ ISO",time:"ម៉ោង ISO",duration:"រយៈពេល ISO",ipv4:"អាសយដ្ឋាន IPv4",ipv6:"អាសយដ្ឋាន IPv6",cidrv4:"ដែនអាសយដ្ឋាន IPv4",cidrv6:"ដែនអាសយដ្ឋាន IPv6",base64:"ខ្សែអក្សរអ៊ិកូដ base64",base64url:"ខ្សែអក្សរអ៊ិកូដ base64url",json_string:"ខ្សែអក្សរ JSON",e164:"លេខ E.164",jwt:"JWT",template_literal:"ទិន្នន័យបញ្ចូល"},w={nan:"NaN",number:"លេខ",array:"អារេ (Array)",null:"គ្មានតម្លៃ (null)"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ instanceof ${l.expected} ប៉ុន្តែទទួលបាន ${Z}`:`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${i} ប៉ុន្តែទទួលបាន ${Z}`}case"invalid_value":return l.values.length===1?`ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${D.stringifyPrimitive(l.values[0])}`:`ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`ធំពេក៖ ត្រូវការ ${l.origin??"តម្លៃ"} ${i} ${l.maximum.toString()} ${I.unit??"ធាតុ"}`:`ធំពេក៖ ត្រូវការ ${l.origin??"តម្លៃ"} ${i} ${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`តូចពេក៖ ត្រូវការ ${l.origin} ${i} ${l.minimum.toString()} ${I.unit}`:`តូចពេក៖ ត្រូវការ ${l.origin} ${i} ${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${i.prefix}"`:i.format==="ends_with"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${i.suffix}"`:i.format==="includes"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${i.includes}"`:i.format==="regex"?`ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${i.pattern}`:`មិនត្រឹមត្រូវ៖ ${x[i.format]??l.format}`}case"not_multiple_of":return`លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${l.divisor}`;case"unrecognized_keys":return`រកឃើញសោមិនស្គាល់៖ ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`សោមិនត្រឹមត្រូវនៅក្នុង ${l.origin}`;case"invalid_union":return"ទិន្នន័យមិនត្រឹមត្រូវ";case"invalid_element":return`ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${l.origin}`;default:return"ទិន្នន័យមិនត្រឹមត្រូវ"}}};function J(){return{localeError:V()}}o.exports=_.default})(wu,wu.exports);var jw=wu.exports,mw=_u.exports;(function(o,_){var R=mw&&mw.__importDefault||function(D){return D&&D.__esModule?D:{default:D}};Object.defineProperty(_,"__esModule",{value:!0}),_.default=P;const F=R(jw);function P(){return(0,F.default)()}o.exports=_.default})(_u,_u.exports);var MW=_u.exports,Eu={exports:{}},ca=Eu.exports;(function(o,_){var R=ca&&ca.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=ca&&ca.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=ca&&ca.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"문자",verb:"to have"},file:{unit:"바이트",verb:"to have"},array:{unit:"개",verb:"to have"},set:{unit:"개",verb:"to have"}};function v(l){return b[l]??null}const x={regex:"입력",email:"이메일 주소",url:"URL",emoji:"이모지",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 날짜시간",date:"ISO 날짜",time:"ISO 시간",duration:"ISO 기간",ipv4:"IPv4 주소",ipv6:"IPv6 주소",cidrv4:"IPv4 범위",cidrv6:"IPv6 범위",base64:"base64 인코딩 문자열",base64url:"base64url 인코딩 문자열",json_string:"JSON 문자열",e164:"E.164 번호",jwt:"JWT",template_literal:"입력"},w={nan:"NaN"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`잘못된 입력: 예상 타입은 instanceof ${l.expected}, 받은 타입은 ${Z}입니다`:`잘못된 입력: 예상 타입은 ${i}, 받은 타입은 ${Z}입니다`}case"invalid_value":return l.values.length===1?`잘못된 입력: 값은 ${D.stringifyPrimitive(l.values[0])} 이어야 합니다`:`잘못된 옵션: ${D.joinValues(l.values,"또는 ")} 중 하나여야 합니다`;case"too_big":{const i=l.inclusive?"이하":"미만",I=i==="미만"?"이어야 합니다":"여야 합니다",Z=v(l.origin),ye=Z?.unit??"요소";return Z?`${l.origin??"값"}이 너무 큽니다: ${l.maximum.toString()}${ye} ${i}${I}`:`${l.origin??"값"}이 너무 큽니다: ${l.maximum.toString()} ${i}${I}`}case"too_small":{const i=l.inclusive?"이상":"초과",I=i==="이상"?"이어야 합니다":"여야 합니다",Z=v(l.origin),ye=Z?.unit??"요소";return Z?`${l.origin??"값"}이 너무 작습니다: ${l.minimum.toString()}${ye} ${i}${I}`:`${l.origin??"값"}이 너무 작습니다: ${l.minimum.toString()} ${i}${I}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`잘못된 문자열: "${i.prefix}"(으)로 시작해야 합니다`:i.format==="ends_with"?`잘못된 문자열: "${i.suffix}"(으)로 끝나야 합니다`:i.format==="includes"?`잘못된 문자열: "${i.includes}"을(를) 포함해야 합니다`:i.format==="regex"?`잘못된 문자열: 정규식 ${i.pattern} 패턴과 일치해야 합니다`:`잘못된 ${x[i.format]??l.format}`}case"not_multiple_of":return`잘못된 숫자: ${l.divisor}의 배수여야 합니다`;case"unrecognized_keys":return`인식할 수 없는 키: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`잘못된 키: ${l.origin}`;case"invalid_union":return"잘못된 입력";case"invalid_element":return`잘못된 값: ${l.origin}`;default:return"잘못된 입력"}}};function J(){return{localeError:V()}}o.exports=_.default})(Eu,Eu.exports);var $W=Eu.exports,ku={exports:{}},ua=ku.exports;(function(o,_){var R=ua&&ua.__createBinding||(Object.create?(function(x,w,l,i){i===void 0&&(i=l);var I=Object.getOwnPropertyDescriptor(w,l);(!I||("get"in I?!w.__esModule:I.writable||I.configurable))&&(I={enumerable:!0,get:function(){return w[l]}}),Object.defineProperty(x,i,I)}):(function(x,w,l,i){i===void 0&&(i=l),x[i]=w[l]})),F=ua&&ua.__setModuleDefault||(Object.create?(function(x,w){Object.defineProperty(x,"default",{enumerable:!0,value:w})}):function(x,w){x.default=w}),P=ua&&ua.__importStar||function(x){if(x&&x.__esModule)return x;var w={};if(x!=null)for(var l in x)l!=="default"&&Object.prototype.hasOwnProperty.call(x,l)&&R(w,x,l);return F(w,x),w};Object.defineProperty(_,"__esModule",{value:!0}),_.default=v;const D=P(Ie),V=x=>x.charAt(0).toUpperCase()+x.slice(1);function J(x){const w=Math.abs(x),l=w%10,i=w%100;return i>=11&&i<=19||l===0?"many":l===1?"one":"few"}const b=()=>{const x={string:{unit:{one:"simbolis",few:"simboliai",many:"simbolių"},verb:{smaller:{inclusive:"turi būti ne ilgesnė kaip",notInclusive:"turi būti trumpesnė kaip"},bigger:{inclusive:"turi būti ne trumpesnė kaip",notInclusive:"turi būti ilgesnė kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"baitų"},verb:{smaller:{inclusive:"turi būti ne didesnis kaip",notInclusive:"turi būti mažesnis kaip"},bigger:{inclusive:"turi būti ne mažesnis kaip",notInclusive:"turi būti didesnis kaip"}}},array:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}},set:{unit:{one:"elementą",few:"elementus",many:"elementų"},verb:{smaller:{inclusive:"turi turėti ne daugiau kaip",notInclusive:"turi turėti mažiau kaip"},bigger:{inclusive:"turi turėti ne mažiau kaip",notInclusive:"turi turėti daugiau kaip"}}}};function w(I,Z,ye,ve){const Te=x[I]??null;return Te===null?Te:{unit:Te.unit[Z],verb:Te.verb[ve][ye?"inclusive":"notInclusive"]}}const l={regex:"įvestis",email:"el. pašto adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukmė",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 užkoduota eilutė",base64url:"base64url užkoduota eilutė",json_string:"JSON eilutė",e164:"E.164 numeris",jwt:"JWT",template_literal:"įvestis"},i={nan:"NaN",number:"skaičius",bigint:"sveikasis skaičius",string:"eilutė",boolean:"loginė reikšmė",undefined:"neapibrėžta reikšmė",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulinė reikšmė"};return I=>{switch(I.code){case"invalid_type":{const Z=i[I.expected]??I.expected,ye=D.parsedType(I.input),ve=i[ye]??ye;return/^[A-Z]/.test(I.expected)?`Gautas tipas ${ve}, o tikėtasi - instanceof ${I.expected}`:`Gautas tipas ${ve}, o tikėtasi - ${Z}`}case"invalid_value":return I.values.length===1?`Privalo būti ${D.stringifyPrimitive(I.values[0])}`:`Privalo būti vienas iš ${D.joinValues(I.values,"|")} pasirinkimų`;case"too_big":{const Z=i[I.origin]??I.origin,ye=w(I.origin,J(Number(I.maximum)),I.inclusive??!1,"smaller");if(ye?.verb)return`${V(Z??I.origin??"reikšmė")} ${ye.verb} ${I.maximum.toString()} ${ye.unit??"elementų"}`;const ve=I.inclusive?"ne didesnis kaip":"mažesnis kaip";return`${V(Z??I.origin??"reikšmė")} turi būti ${ve} ${I.maximum.toString()} ${ye?.unit}`}case"too_small":{const Z=i[I.origin]??I.origin,ye=w(I.origin,J(Number(I.minimum)),I.inclusive??!1,"bigger");if(ye?.verb)return`${V(Z??I.origin??"reikšmė")} ${ye.verb} ${I.minimum.toString()} ${ye.unit??"elementų"}`;const ve=I.inclusive?"ne mažesnis kaip":"didesnis kaip";return`${V(Z??I.origin??"reikšmė")} turi būti ${ve} ${I.minimum.toString()} ${ye?.unit}`}case"invalid_format":{const Z=I;return Z.format==="starts_with"?`Eilutė privalo prasidėti "${Z.prefix}"`:Z.format==="ends_with"?`Eilutė privalo pasibaigti "${Z.suffix}"`:Z.format==="includes"?`Eilutė privalo įtraukti "${Z.includes}"`:Z.format==="regex"?`Eilutė privalo atitikti ${Z.pattern}`:`Neteisingas ${l[Z.format]??I.format}`}case"not_multiple_of":return`Skaičius privalo būti ${I.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpažint${I.keys.length>1?"i":"as"} rakt${I.keys.length>1?"ai":"as"}: ${D.joinValues(I.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga įvestis";case"invalid_element":{const Z=i[I.origin]??I.origin;return`${V(Z??I.origin??"reikšmė")} turi klaidingą įvestį`}default:return"Klaidinga įvestis"}}};function v(){return{localeError:b()}}o.exports=_.default})(ku,ku.exports);var RW=ku.exports,Tu={exports:{}},da=Tu.exports;(function(o,_){var R=da&&da.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=da&&da.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=da&&da.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"знаци",verb:"да имаат"},file:{unit:"бајти",verb:"да имаат"},array:{unit:"ставки",verb:"да имаат"},set:{unit:"ставки",verb:"да имаат"}};function v(l){return b[l]??null}const x={regex:"внес",email:"адреса на е-пошта",url:"URL",emoji:"емоџи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO датум и време",date:"ISO датум",time:"ISO време",duration:"ISO времетраење",ipv4:"IPv4 адреса",ipv6:"IPv6 адреса",cidrv4:"IPv4 опсег",cidrv6:"IPv6 опсег",base64:"base64-енкодирана низа",base64url:"base64url-енкодирана низа",json_string:"JSON низа",e164:"E.164 број",jwt:"JWT",template_literal:"внес"},w={nan:"NaN",number:"број",array:"низа"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Грешен внес: се очекува instanceof ${l.expected}, примено ${Z}`:`Грешен внес: се очекува ${i}, примено ${Z}`}case"invalid_value":return l.values.length===1?`Invalid input: expected ${D.stringifyPrimitive(l.values[0])}`:`Грешана опција: се очекува една ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Премногу голем: се очекува ${l.origin??"вредноста"} да има ${i}${l.maximum.toString()} ${I.unit??"елементи"}`:`Премногу голем: се очекува ${l.origin??"вредноста"} да биде ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Премногу мал: се очекува ${l.origin} да има ${i}${l.minimum.toString()} ${I.unit}`:`Премногу мал: се очекува ${l.origin} да биде ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Неважечка низа: мора да започнува со "${i.prefix}"`:i.format==="ends_with"?`Неважечка низа: мора да завршува со "${i.suffix}"`:i.format==="includes"?`Неважечка низа: мора да вклучува "${i.includes}"`:i.format==="regex"?`Неважечка низа: мора да одгоара на патернот ${i.pattern}`:`Invalid ${x[i.format]??l.format}`}case"not_multiple_of":return`Грешен број: мора да биде делив со ${l.divisor}`;case"unrecognized_keys":return`${l.keys.length>1?"Непрепознаени клучеви":"Непрепознаен клуч"}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Грешен клуч во ${l.origin}`;case"invalid_union":return"Грешен внес";case"invalid_element":return`Грешна вредност во ${l.origin}`;default:return"Грешен внес"}}};function J(){return{localeError:V()}}o.exports=_.default})(Tu,Tu.exports);var LW=Tu.exports,Cu={exports:{}},fa=Cu.exports;(function(o,_){var R=fa&&fa.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=fa&&fa.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=fa&&fa.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function v(l){return b[l]??null}const x={regex:"input",email:"alamat e-mel",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},w={nan:"NaN",number:"nombor"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Input tidak sah: dijangka instanceof ${l.expected}, diterima ${Z}`:`Input tidak sah: dijangka ${i}, diterima ${Z}`}case"invalid_value":return l.values.length===1?`Input tidak sah: dijangka ${D.stringifyPrimitive(l.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Terlalu besar: dijangka ${l.origin??"nilai"} ${I.verb} ${i}${l.maximum.toString()} ${I.unit??"elemen"}`:`Terlalu besar: dijangka ${l.origin??"nilai"} adalah ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Terlalu kecil: dijangka ${l.origin} ${I.verb} ${i}${l.minimum.toString()} ${I.unit}`:`Terlalu kecil: dijangka ${l.origin} adalah ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`String tidak sah: mesti bermula dengan "${i.prefix}"`:i.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${i.suffix}"`:i.format==="includes"?`String tidak sah: mesti mengandungi "${i.includes}"`:i.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${i.pattern}`:`${x[i.format]??l.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${l.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${l.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${l.origin}`;default:return"Input tidak sah"}}};function J(){return{localeError:V()}}o.exports=_.default})(Cu,Cu.exports);var OW=Cu.exports,Iu={exports:{}},ha=Iu.exports;(function(o,_){var R=ha&&ha.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=ha&&ha.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=ha&&ha.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function v(l){return b[l]??null}const x={regex:"invoer",email:"emailadres",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},w={nan:"NaN",number:"getal"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Ongeldige invoer: verwacht instanceof ${l.expected}, ontving ${Z}`:`Ongeldige invoer: verwacht ${i}, ontving ${Z}`}case"invalid_value":return l.values.length===1?`Ongeldige invoer: verwacht ${D.stringifyPrimitive(l.values[0])}`:`Ongeldige optie: verwacht één van ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin),Z=l.origin==="date"?"laat":l.origin==="string"?"lang":"groot";return I?`Te ${Z}: verwacht dat ${l.origin??"waarde"} ${i}${l.maximum.toString()} ${I.unit??"elementen"} ${I.verb}`:`Te ${Z}: verwacht dat ${l.origin??"waarde"} ${i}${l.maximum.toString()} is`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin),Z=l.origin==="date"?"vroeg":l.origin==="string"?"kort":"klein";return I?`Te ${Z}: verwacht dat ${l.origin} ${i}${l.minimum.toString()} ${I.unit} ${I.verb}`:`Te ${Z}: verwacht dat ${l.origin} ${i}${l.minimum.toString()} is`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Ongeldige tekst: moet met "${i.prefix}" beginnen`:i.format==="ends_with"?`Ongeldige tekst: moet op "${i.suffix}" eindigen`:i.format==="includes"?`Ongeldige tekst: moet "${i.includes}" bevatten`:i.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${i.pattern}`:`Ongeldig: ${x[i.format]??l.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${l.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${l.keys.length>1?"s":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${l.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${l.origin}`;default:return"Ongeldige invoer"}}};function J(){return{localeError:V()}}o.exports=_.default})(Iu,Iu.exports);var FW=Iu.exports,Pu={exports:{}},ma=Pu.exports;(function(o,_){var R=ma&&ma.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=ma&&ma.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=ma&&ma.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"tegn",verb:"å ha"},file:{unit:"bytes",verb:"å ha"},array:{unit:"elementer",verb:"å inneholde"},set:{unit:"elementer",verb:"å inneholde"}};function v(l){return b[l]??null}const x={regex:"input",email:"e-postadresse",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-område",ipv6:"IPv6-område",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},w={nan:"NaN",number:"tall",array:"liste"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Ugyldig input: forventet instanceof ${l.expected}, fikk ${Z}`:`Ugyldig input: forventet ${i}, fikk ${Z}`}case"invalid_value":return l.values.length===1?`Ugyldig verdi: forventet ${D.stringifyPrimitive(l.values[0])}`:`Ugyldig valg: forventet en av ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`For stor(t): forventet ${l.origin??"value"} til å ha ${i}${l.maximum.toString()} ${I.unit??"elementer"}`:`For stor(t): forventet ${l.origin??"value"} til å ha ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`For lite(n): forventet ${l.origin} til å ha ${i}${l.minimum.toString()} ${I.unit}`:`For lite(n): forventet ${l.origin} til å ha ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Ugyldig streng: må starte med "${i.prefix}"`:i.format==="ends_with"?`Ugyldig streng: må ende med "${i.suffix}"`:i.format==="includes"?`Ugyldig streng: må inneholde "${i.includes}"`:i.format==="regex"?`Ugyldig streng: må matche mønsteret ${i.pattern}`:`Ugyldig ${x[i.format]??l.format}`}case"not_multiple_of":return`Ugyldig tall: må være et multiplum av ${l.divisor}`;case"unrecognized_keys":return`${l.keys.length>1?"Ukjente nøkler":"Ukjent nøkkel"}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Ugyldig nøkkel i ${l.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${l.origin}`;default:return"Ugyldig input"}}};function J(){return{localeError:V()}}o.exports=_.default})(Pu,Pu.exports);var UW=Pu.exports,Au={exports:{}},ga=Au.exports;(function(o,_){var R=ga&&ga.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=ga&&ga.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=ga&&ga.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"harf",verb:"olmalıdır"},file:{unit:"bayt",verb:"olmalıdır"},array:{unit:"unsur",verb:"olmalıdır"},set:{unit:"unsur",verb:"olmalıdır"}};function v(l){return b[l]??null}const x={regex:"giren",email:"epostagâh",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO hengâmı",date:"ISO tarihi",time:"ISO zamanı",duration:"ISO müddeti",ipv4:"IPv4 nişânı",ipv6:"IPv6 nişânı",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-şifreli metin",base64url:"base64url-şifreli metin",json_string:"JSON metin",e164:"E.164 sayısı",jwt:"JWT",template_literal:"giren"},w={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Fâsit giren: umulan instanceof ${l.expected}, alınan ${Z}`:`Fâsit giren: umulan ${i}, alınan ${Z}`}case"invalid_value":return l.values.length===1?`Fâsit giren: umulan ${D.stringifyPrimitive(l.values[0])}`:`Fâsit tercih: mûteberler ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Fazla büyük: ${l.origin??"value"}, ${i}${l.maximum.toString()} ${I.unit??"elements"} sahip olmalıydı.`:`Fazla büyük: ${l.origin??"value"}, ${i}${l.maximum.toString()} olmalıydı.`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Fazla küçük: ${l.origin}, ${i}${l.minimum.toString()} ${I.unit} sahip olmalıydı.`:`Fazla küçük: ${l.origin}, ${i}${l.minimum.toString()} olmalıydı.`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Fâsit metin: "${i.prefix}" ile başlamalı.`:i.format==="ends_with"?`Fâsit metin: "${i.suffix}" ile bitmeli.`:i.format==="includes"?`Fâsit metin: "${i.includes}" ihtivâ etmeli.`:i.format==="regex"?`Fâsit metin: ${i.pattern} nakşına uymalı.`:`Fâsit ${x[i.format]??l.format}`}case"not_multiple_of":return`Fâsit sayı: ${l.divisor} katı olmalıydı.`;case"unrecognized_keys":return`Tanınmayan anahtar ${l.keys.length>1?"s":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`${l.origin} için tanınmayan anahtar var.`;case"invalid_union":return"Giren tanınamadı.";case"invalid_element":return`${l.origin} için tanınmayan kıymet var.`;default:return"Kıymet tanınamadı."}}};function J(){return{localeError:V()}}o.exports=_.default})(Au,Au.exports);var BW=Au.exports,ju={exports:{}},pa=ju.exports;(function(o,_){var R=pa&&pa.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=pa&&pa.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=pa&&pa.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"توکي",verb:"ولري"},file:{unit:"بایټس",verb:"ولري"},array:{unit:"توکي",verb:"ولري"},set:{unit:"توکي",verb:"ولري"}};function v(l){return b[l]??null}const x={regex:"ورودي",email:"بریښنالیک",url:"یو آر ال",emoji:"ایموجي",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"نیټه او وخت",date:"نېټه",time:"وخت",duration:"موده",ipv4:"د IPv4 پته",ipv6:"د IPv6 پته",cidrv4:"د IPv4 ساحه",cidrv6:"د IPv6 ساحه",base64:"base64-encoded متن",base64url:"base64url-encoded متن",json_string:"JSON متن",e164:"د E.164 شمېره",jwt:"JWT",template_literal:"ورودي"},w={nan:"NaN",number:"عدد",array:"ارې"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`ناسم ورودي: باید instanceof ${l.expected} وای, مګر ${Z} ترلاسه شو`:`ناسم ورودي: باید ${i} وای, مګر ${Z} ترلاسه شو`}case"invalid_value":return l.values.length===1?`ناسم ورودي: باید ${D.stringifyPrimitive(l.values[0])} وای`:`ناسم انتخاب: باید یو له ${D.joinValues(l.values,"|")} څخه وای`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`ډیر لوی: ${l.origin??"ارزښت"} باید ${i}${l.maximum.toString()} ${I.unit??"عنصرونه"} ولري`:`ډیر لوی: ${l.origin??"ارزښت"} باید ${i}${l.maximum.toString()} وي`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`ډیر کوچنی: ${l.origin} باید ${i}${l.minimum.toString()} ${I.unit} ولري`:`ډیر کوچنی: ${l.origin} باید ${i}${l.minimum.toString()} وي`}case"invalid_format":{const i=l;return i.format==="starts_with"?`ناسم متن: باید د "${i.prefix}" سره پیل شي`:i.format==="ends_with"?`ناسم متن: باید د "${i.suffix}" سره پای ته ورسيږي`:i.format==="includes"?`ناسم متن: باید "${i.includes}" ولري`:i.format==="regex"?`ناسم متن: باید د ${i.pattern} سره مطابقت ولري`:`${x[i.format]??l.format} ناسم دی`}case"not_multiple_of":return`ناسم عدد: باید د ${l.divisor} مضرب وي`;case"unrecognized_keys":return`ناسم ${l.keys.length>1?"کلیډونه":"کلیډ"}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`ناسم کلیډ په ${l.origin} کې`;case"invalid_union":return"ناسمه ورودي";case"invalid_element":return`ناسم عنصر په ${l.origin} کې`;default:return"ناسمه ورودي"}}};function J(){return{localeError:V()}}o.exports=_.default})(ju,ju.exports);var zW=ju.exports,Nu={exports:{}},va=Nu.exports;(function(o,_){var R=va&&va.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=va&&va.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=va&&va.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"znaków",verb:"mieć"},file:{unit:"bajtów",verb:"mieć"},array:{unit:"elementów",verb:"mieć"},set:{unit:"elementów",verb:"mieć"}};function v(l){return b[l]??null}const x={regex:"wyrażenie",email:"adres email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ciąg znaków zakodowany w formacie base64",base64url:"ciąg znaków zakodowany w formacie base64url",json_string:"ciąg znaków w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wejście"},w={nan:"NaN",number:"liczba",array:"tablica"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Nieprawidłowe dane wejściowe: oczekiwano instanceof ${l.expected}, otrzymano ${Z}`:`Nieprawidłowe dane wejściowe: oczekiwano ${i}, otrzymano ${Z}`}case"invalid_value":return l.values.length===1?`Nieprawidłowe dane wejściowe: oczekiwano ${D.stringifyPrimitive(l.values[0])}`:`Nieprawidłowa opcja: oczekiwano jednej z wartości ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Za duża wartość: oczekiwano, że ${l.origin??"wartość"} będzie mieć ${i}${l.maximum.toString()} ${I.unit??"elementów"}`:`Zbyt duż(y/a/e): oczekiwano, że ${l.origin??"wartość"} będzie wynosić ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Za mała wartość: oczekiwano, że ${l.origin??"wartość"} będzie mieć ${i}${l.minimum.toString()} ${I.unit??"elementów"}`:`Zbyt mał(y/a/e): oczekiwano, że ${l.origin??"wartość"} będzie wynosić ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Nieprawidłowy ciąg znaków: musi zaczynać się od "${i.prefix}"`:i.format==="ends_with"?`Nieprawidłowy ciąg znaków: musi kończyć się na "${i.suffix}"`:i.format==="includes"?`Nieprawidłowy ciąg znaków: musi zawierać "${i.includes}"`:i.format==="regex"?`Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${i.pattern}`:`Nieprawidłow(y/a/e) ${x[i.format]??l.format}`}case"not_multiple_of":return`Nieprawidłowa liczba: musi być wielokrotnością ${l.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${l.keys.length>1?"s":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Nieprawidłowy klucz w ${l.origin}`;case"invalid_union":return"Nieprawidłowe dane wejściowe";case"invalid_element":return`Nieprawidłowa wartość w ${l.origin}`;default:return"Nieprawidłowe dane wejściowe"}}};function J(){return{localeError:V()}}o.exports=_.default})(Nu,Nu.exports);var GW=Nu.exports,Du={exports:{}},ba=Du.exports;(function(o,_){var R=ba&&ba.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=ba&&ba.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=ba&&ba.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function v(l){return b[l]??null}const x={regex:"padrão",email:"endereço de e-mail",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"duração ISO",ipv4:"endereço IPv4",ipv6:"endereço IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"número E.164",jwt:"JWT",template_literal:"entrada"},w={nan:"NaN",number:"número",null:"nulo"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Tipo inválido: esperado instanceof ${l.expected}, recebido ${Z}`:`Tipo inválido: esperado ${i}, recebido ${Z}`}case"invalid_value":return l.values.length===1?`Entrada inválida: esperado ${D.stringifyPrimitive(l.values[0])}`:`Opção inválida: esperada uma das ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Muito grande: esperado que ${l.origin??"valor"} tivesse ${i}${l.maximum.toString()} ${I.unit??"elementos"}`:`Muito grande: esperado que ${l.origin??"valor"} fosse ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Muito pequeno: esperado que ${l.origin} tivesse ${i}${l.minimum.toString()} ${I.unit}`:`Muito pequeno: esperado que ${l.origin} fosse ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Texto inválido: deve começar com "${i.prefix}"`:i.format==="ends_with"?`Texto inválido: deve terminar com "${i.suffix}"`:i.format==="includes"?`Texto inválido: deve incluir "${i.includes}"`:i.format==="regex"?`Texto inválido: deve corresponder ao padrão ${i.pattern}`:`${x[i.format]??l.format} inválido`}case"not_multiple_of":return`Número inválido: deve ser múltiplo de ${l.divisor}`;case"unrecognized_keys":return`Chave${l.keys.length>1?"s":""} desconhecida${l.keys.length>1?"s":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Chave inválida em ${l.origin}`;case"invalid_union":return"Entrada inválida";case"invalid_element":return`Valor inválido em ${l.origin}`;default:return"Campo inválido"}}};function J(){return{localeError:V()}}o.exports=_.default})(Du,Du.exports);var ZW=Du.exports,Mu={exports:{}},ya=Mu.exports;(function(o,_){var R=ya&&ya.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=ya&&ya.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=ya&&ya.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"caractere",verb:"să aibă"},file:{unit:"octeți",verb:"să aibă"},array:{unit:"elemente",verb:"să aibă"},set:{unit:"elemente",verb:"să aibă"},map:{unit:"intrări",verb:"să aibă"}};function v(l){return b[l]??null}const x={regex:"intrare",email:"adresă de email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"dată și oră ISO",date:"dată ISO",time:"oră ISO",duration:"durată ISO",ipv4:"adresă IPv4",ipv6:"adresă IPv6",mac:"adresă MAC",cidrv4:"interval IPv4",cidrv6:"interval IPv6",base64:"șir codat base64",base64url:"șir codat base64url",json_string:"șir JSON",e164:"număr E.164",jwt:"JWT",template_literal:"intrare"},w={nan:"NaN",string:"șir",number:"număr",boolean:"boolean",function:"funcție",array:"matrice",object:"obiect",undefined:"nedefinit",symbol:"simbol",bigint:"număr mare",void:"void",never:"never",map:"hartă",set:"set"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return`Intrare invalidă: așteptat ${i}, primit ${Z}`}case"invalid_value":return l.values.length===1?`Intrare invalidă: așteptat ${D.stringifyPrimitive(l.values[0])}`:`Opțiune invalidă: așteptat una dintre ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Prea mare: așteptat ca ${l.origin??"valoarea"} ${I.verb} ${i}${l.maximum.toString()} ${I.unit??"elemente"}`:`Prea mare: așteptat ca ${l.origin??"valoarea"} să fie ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Prea mic: așteptat ca ${l.origin} ${I.verb} ${i}${l.minimum.toString()} ${I.unit}`:`Prea mic: așteptat ca ${l.origin} să fie ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Șir invalid: trebuie să înceapă cu "${i.prefix}"`:i.format==="ends_with"?`Șir invalid: trebuie să se termine cu "${i.suffix}"`:i.format==="includes"?`Șir invalid: trebuie să includă "${i.includes}"`:i.format==="regex"?`Șir invalid: trebuie să se potrivească cu modelul ${i.pattern}`:`Format invalid: ${x[i.format]??l.format}`}case"not_multiple_of":return`Număr invalid: trebuie să fie multiplu de ${l.divisor}`;case"unrecognized_keys":return`Chei nerecunoscute: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Cheie invalidă în ${l.origin}`;case"invalid_union":return"Intrare invalidă";case"invalid_element":return`Valoare invalidă în ${l.origin}`;default:return"Intrare invalidă"}}};function J(){return{localeError:V()}}o.exports=_.default})(Mu,Mu.exports);var VW=Mu.exports,$u={exports:{}},xa=$u.exports;(function(o,_){var R=xa&&xa.__createBinding||(Object.create?(function(v,x,w,l){l===void 0&&(l=w);var i=Object.getOwnPropertyDescriptor(x,w);(!i||("get"in i?!x.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return x[w]}}),Object.defineProperty(v,l,i)}):(function(v,x,w,l){l===void 0&&(l=w),v[l]=x[w]})),F=xa&&xa.__setModuleDefault||(Object.create?(function(v,x){Object.defineProperty(v,"default",{enumerable:!0,value:x})}):function(v,x){v.default=x}),P=xa&&xa.__importStar||function(v){if(v&&v.__esModule)return v;var x={};if(v!=null)for(var w in v)w!=="default"&&Object.prototype.hasOwnProperty.call(v,w)&&R(x,v,w);return F(x,v),x};Object.defineProperty(_,"__esModule",{value:!0}),_.default=b;const D=P(Ie);function V(v,x,w,l){const i=Math.abs(v),I=i%10,Z=i%100;return Z>=11&&Z<=19?l:I===1?x:I>=2&&I<=4?w:l}const J=()=>{const v={string:{unit:{one:"символ",few:"символа",many:"символов"},verb:"иметь"},file:{unit:{one:"байт",few:"байта",many:"байт"},verb:"иметь"},array:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"},set:{unit:{one:"элемент",few:"элемента",many:"элементов"},verb:"иметь"}};function x(i){return v[i]??null}const w={regex:"ввод",email:"email адрес",url:"URL",emoji:"эмодзи",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO дата и время",date:"ISO дата",time:"ISO время",duration:"ISO длительность",ipv4:"IPv4 адрес",ipv6:"IPv6 адрес",cidrv4:"IPv4 диапазон",cidrv6:"IPv6 диапазон",base64:"строка в формате base64",base64url:"строка в формате base64url",json_string:"JSON строка",e164:"номер E.164",jwt:"JWT",template_literal:"ввод"},l={nan:"NaN",number:"число",array:"массив"};return i=>{switch(i.code){case"invalid_type":{const I=l[i.expected]??i.expected,Z=D.parsedType(i.input),ye=l[Z]??Z;return/^[A-Z]/.test(i.expected)?`Неверный ввод: ожидалось instanceof ${i.expected}, получено ${ye}`:`Неверный ввод: ожидалось ${I}, получено ${ye}`}case"invalid_value":return i.values.length===1?`Неверный ввод: ожидалось ${D.stringifyPrimitive(i.values[0])}`:`Неверный вариант: ожидалось одно из ${D.joinValues(i.values,"|")}`;case"too_big":{const I=i.inclusive?"<=":"<",Z=x(i.origin);if(Z){const ye=Number(i.maximum),ve=V(ye,Z.unit.one,Z.unit.few,Z.unit.many);return`Слишком большое значение: ожидалось, что ${i.origin??"значение"} будет иметь ${I}${i.maximum.toString()} ${ve}`}return`Слишком большое значение: ожидалось, что ${i.origin??"значение"} будет ${I}${i.maximum.toString()}`}case"too_small":{const I=i.inclusive?">=":">",Z=x(i.origin);if(Z){const ye=Number(i.minimum),ve=V(ye,Z.unit.one,Z.unit.few,Z.unit.many);return`Слишком маленькое значение: ожидалось, что ${i.origin} будет иметь ${I}${i.minimum.toString()} ${ve}`}return`Слишком маленькое значение: ожидалось, что ${i.origin} будет ${I}${i.minimum.toString()}`}case"invalid_format":{const I=i;return I.format==="starts_with"?`Неверная строка: должна начинаться с "${I.prefix}"`:I.format==="ends_with"?`Неверная строка: должна заканчиваться на "${I.suffix}"`:I.format==="includes"?`Неверная строка: должна содержать "${I.includes}"`:I.format==="regex"?`Неверная строка: должна соответствовать шаблону ${I.pattern}`:`Неверный ${w[I.format]??i.format}`}case"not_multiple_of":return`Неверное число: должно быть кратным ${i.divisor}`;case"unrecognized_keys":return`Нераспознанн${i.keys.length>1?"ые":"ый"} ключ${i.keys.length>1?"и":""}: ${D.joinValues(i.keys,", ")}`;case"invalid_key":return`Неверный ключ в ${i.origin}`;case"invalid_union":return"Неверные входные данные";case"invalid_element":return`Неверное значение в ${i.origin}`;default:return"Неверные входные данные"}}};function b(){return{localeError:J()}}o.exports=_.default})($u,$u.exports);var HW=$u.exports,Ru={exports:{}},Sa=Ru.exports;(function(o,_){var R=Sa&&Sa.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Sa&&Sa.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Sa&&Sa.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function v(l){return b[l]??null}const x={regex:"vnos",email:"e-poštni naslov",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datum in čas",date:"ISO datum",time:"ISO čas",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 številka",jwt:"JWT",template_literal:"vnos"},w={nan:"NaN",number:"število",array:"tabela"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Neveljaven vnos: pričakovano instanceof ${l.expected}, prejeto ${Z}`:`Neveljaven vnos: pričakovano ${i}, prejeto ${Z}`}case"invalid_value":return l.values.length===1?`Neveljaven vnos: pričakovano ${D.stringifyPrimitive(l.values[0])}`:`Neveljavna možnost: pričakovano eno izmed ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Preveliko: pričakovano, da bo ${l.origin??"vrednost"} imelo ${i}${l.maximum.toString()} ${I.unit??"elementov"}`:`Preveliko: pričakovano, da bo ${l.origin??"vrednost"} ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Premajhno: pričakovano, da bo ${l.origin} imelo ${i}${l.minimum.toString()} ${I.unit}`:`Premajhno: pričakovano, da bo ${l.origin} ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Neveljaven niz: mora se začeti z "${i.prefix}"`:i.format==="ends_with"?`Neveljaven niz: mora se končati z "${i.suffix}"`:i.format==="includes"?`Neveljaven niz: mora vsebovati "${i.includes}"`:i.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${i.pattern}`:`Neveljaven ${x[i.format]??l.format}`}case"not_multiple_of":return`Neveljavno število: mora biti večkratnik ${l.divisor}`;case"unrecognized_keys":return`Neprepoznan${l.keys.length>1?"i ključi":" ključ"}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Neveljaven ključ v ${l.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${l.origin}`;default:return"Neveljaven vnos"}}};function J(){return{localeError:V()}}o.exports=_.default})(Ru,Ru.exports);var KW=Ru.exports,Lu={exports:{}},_a=Lu.exports;(function(o,_){var R=_a&&_a.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=_a&&_a.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=_a&&_a.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att innehålla"},set:{unit:"objekt",verb:"att innehålla"}};function v(l){return b[l]??null}const x={regex:"reguljärt uttryck",email:"e-postadress",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad sträng",base64url:"base64url-kodad sträng",json_string:"JSON-sträng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},w={nan:"NaN",number:"antal",array:"lista"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Ogiltig inmatning: förväntat instanceof ${l.expected}, fick ${Z}`:`Ogiltig inmatning: förväntat ${i}, fick ${Z}`}case"invalid_value":return l.values.length===1?`Ogiltig inmatning: förväntat ${D.stringifyPrimitive(l.values[0])}`:`Ogiltigt val: förväntade en av ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`För stor(t): förväntade ${l.origin??"värdet"} att ha ${i}${l.maximum.toString()} ${I.unit??"element"}`:`För stor(t): förväntat ${l.origin??"värdet"} att ha ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`För lite(t): förväntade ${l.origin??"värdet"} att ha ${i}${l.minimum.toString()} ${I.unit}`:`För lite(t): förväntade ${l.origin??"värdet"} att ha ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Ogiltig sträng: måste börja med "${i.prefix}"`:i.format==="ends_with"?`Ogiltig sträng: måste sluta med "${i.suffix}"`:i.format==="includes"?`Ogiltig sträng: måste innehålla "${i.includes}"`:i.format==="regex"?`Ogiltig sträng: måste matcha mönstret "${i.pattern}"`:`Ogiltig(t) ${x[i.format]??l.format}`}case"not_multiple_of":return`Ogiltigt tal: måste vara en multipel av ${l.divisor}`;case"unrecognized_keys":return`${l.keys.length>1?"Okända nycklar":"Okänd nyckel"}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${l.origin??"värdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt värde i ${l.origin??"värdet"}`;default:return"Ogiltig input"}}};function J(){return{localeError:V()}}o.exports=_.default})(Lu,Lu.exports);var WW=Lu.exports,Ou={exports:{}},wa=Ou.exports;(function(o,_){var R=wa&&wa.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=wa&&wa.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=wa&&wa.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"எழுத்துக்கள்",verb:"கொண்டிருக்க வேண்டும்"},file:{unit:"பைட்டுகள்",verb:"கொண்டிருக்க வேண்டும்"},array:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"},set:{unit:"உறுப்புகள்",verb:"கொண்டிருக்க வேண்டும்"}};function v(l){return b[l]??null}const x={regex:"உள்ளீடு",email:"மின்னஞ்சல் முகவரி",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO தேதி நேரம்",date:"ISO தேதி",time:"ISO நேரம்",duration:"ISO கால அளவு",ipv4:"IPv4 முகவரி",ipv6:"IPv6 முகவரி",cidrv4:"IPv4 வரம்பு",cidrv6:"IPv6 வரம்பு",base64:"base64-encoded சரம்",base64url:"base64url-encoded சரம்",json_string:"JSON சரம்",e164:"E.164 எண்",jwt:"JWT",template_literal:"input"},w={nan:"NaN",number:"எண்",array:"அணி",null:"வெறுமை"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது instanceof ${l.expected}, பெறப்பட்டது ${Z}`:`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${i}, பெறப்பட்டது ${Z}`}case"invalid_value":return l.values.length===1?`தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${D.stringifyPrimitive(l.values[0])}`:`தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${D.joinValues(l.values,"|")} இல் ஒன்று`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${l.origin??"மதிப்பு"} ${i}${l.maximum.toString()} ${I.unit??"உறுப்புகள்"} ஆக இருக்க வேண்டும்`:`மிக பெரியது: எதிர்பார்க்கப்பட்டது ${l.origin??"மதிப்பு"} ${i}${l.maximum.toString()} ஆக இருக்க வேண்டும்`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${l.origin} ${i}${l.minimum.toString()} ${I.unit} ஆக இருக்க வேண்டும்`:`மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${l.origin} ${i}${l.minimum.toString()} ஆக இருக்க வேண்டும்`}case"invalid_format":{const i=l;return i.format==="starts_with"?`தவறான சரம்: "${i.prefix}" இல் தொடங்க வேண்டும்`:i.format==="ends_with"?`தவறான சரம்: "${i.suffix}" இல் முடிவடைய வேண்டும்`:i.format==="includes"?`தவறான சரம்: "${i.includes}" ஐ உள்ளடக்க வேண்டும்`:i.format==="regex"?`தவறான சரம்: ${i.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`:`தவறான ${x[i.format]??l.format}`}case"not_multiple_of":return`தவறான எண்: ${l.divisor} இன் பலமாக இருக்க வேண்டும்`;case"unrecognized_keys":return`அடையாளம் தெரியாத விசை${l.keys.length>1?"கள்":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`${l.origin} இல் தவறான விசை`;case"invalid_union":return"தவறான உள்ளீடு";case"invalid_element":return`${l.origin} இல் தவறான மதிப்பு`;default:return"தவறான உள்ளீடு"}}};function J(){return{localeError:V()}}o.exports=_.default})(Ou,Ou.exports);var qW=Ou.exports,Fu={exports:{}},Ea=Fu.exports;(function(o,_){var R=Ea&&Ea.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Ea&&Ea.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Ea&&Ea.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"ตัวอักษร",verb:"ควรมี"},file:{unit:"ไบต์",verb:"ควรมี"},array:{unit:"รายการ",verb:"ควรมี"},set:{unit:"รายการ",verb:"ควรมี"}};function v(l){return b[l]??null}const x={regex:"ข้อมูลที่ป้อน",email:"ที่อยู่อีเมล",url:"URL",emoji:"อิโมจิ",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"วันที่เวลาแบบ ISO",date:"วันที่แบบ ISO",time:"เวลาแบบ ISO",duration:"ช่วงเวลาแบบ ISO",ipv4:"ที่อยู่ IPv4",ipv6:"ที่อยู่ IPv6",cidrv4:"ช่วง IP แบบ IPv4",cidrv6:"ช่วง IP แบบ IPv6",base64:"ข้อความแบบ Base64",base64url:"ข้อความแบบ Base64 สำหรับ URL",json_string:"ข้อความแบบ JSON",e164:"เบอร์โทรศัพท์ระหว่างประเทศ (E.164)",jwt:"โทเคน JWT",template_literal:"ข้อมูลที่ป้อน"},w={nan:"NaN",number:"ตัวเลข",array:"อาร์เรย์ (Array)",null:"ไม่มีค่า (null)"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น instanceof ${l.expected} แต่ได้รับ ${Z}`:`ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${i} แต่ได้รับ ${Z}`}case"invalid_value":return l.values.length===1?`ค่าไม่ถูกต้อง: ควรเป็น ${D.stringifyPrimitive(l.values[0])}`:`ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"ไม่เกิน":"น้อยกว่า",I=v(l.origin);return I?`เกินกำหนด: ${l.origin??"ค่า"} ควรมี${i} ${l.maximum.toString()} ${I.unit??"รายการ"}`:`เกินกำหนด: ${l.origin??"ค่า"} ควรมี${i} ${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?"อย่างน้อย":"มากกว่า",I=v(l.origin);return I?`น้อยกว่ากำหนด: ${l.origin} ควรมี${i} ${l.minimum.toString()} ${I.unit}`:`น้อยกว่ากำหนด: ${l.origin} ควรมี${i} ${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${i.prefix}"`:i.format==="ends_with"?`รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${i.suffix}"`:i.format==="includes"?`รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${i.includes}" อยู่ในข้อความ`:i.format==="regex"?`รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${i.pattern}`:`รูปแบบไม่ถูกต้อง: ${x[i.format]??l.format}`}case"not_multiple_of":return`ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${l.divisor} ได้ลงตัว`;case"unrecognized_keys":return`พบคีย์ที่ไม่รู้จัก: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`คีย์ไม่ถูกต้องใน ${l.origin}`;case"invalid_union":return"ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้";case"invalid_element":return`ข้อมูลไม่ถูกต้องใน ${l.origin}`;default:return"ข้อมูลไม่ถูกต้อง"}}};function J(){return{localeError:V()}}o.exports=_.default})(Fu,Fu.exports);var QW=Fu.exports,Uu={exports:{}},ka=Uu.exports;(function(o,_){var R=ka&&ka.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=ka&&ka.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=ka&&ka.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"karakter",verb:"olmalı"},file:{unit:"bayt",verb:"olmalı"},array:{unit:"öğe",verb:"olmalı"},set:{unit:"öğe",verb:"olmalı"}};function v(l){return b[l]??null}const x={regex:"girdi",email:"e-posta adresi",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO süre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aralığı",cidrv6:"IPv6 aralığı",base64:"base64 ile şifrelenmiş metin",base64url:"base64url ile şifrelenmiş metin",json_string:"JSON dizesi",e164:"E.164 sayısı",jwt:"JWT",template_literal:"Şablon dizesi"},w={nan:"NaN"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Geçersiz değer: beklenen instanceof ${l.expected}, alınan ${Z}`:`Geçersiz değer: beklenen ${i}, alınan ${Z}`}case"invalid_value":return l.values.length===1?`Geçersiz değer: beklenen ${D.stringifyPrimitive(l.values[0])}`:`Geçersiz seçenek: aşağıdakilerden biri olmalı: ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Çok büyük: beklenen ${l.origin??"değer"} ${i}${l.maximum.toString()} ${I.unit??"öğe"}`:`Çok büyük: beklenen ${l.origin??"değer"} ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Çok küçük: beklenen ${l.origin} ${i}${l.minimum.toString()} ${I.unit}`:`Çok küçük: beklenen ${l.origin} ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Geçersiz metin: "${i.prefix}" ile başlamalı`:i.format==="ends_with"?`Geçersiz metin: "${i.suffix}" ile bitmeli`:i.format==="includes"?`Geçersiz metin: "${i.includes}" içermeli`:i.format==="regex"?`Geçersiz metin: ${i.pattern} desenine uymalı`:`Geçersiz ${x[i.format]??l.format}`}case"not_multiple_of":return`Geçersiz sayı: ${l.divisor} ile tam bölünebilmeli`;case"unrecognized_keys":return`Tanınmayan anahtar${l.keys.length>1?"lar":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`${l.origin} içinde geçersiz anahtar`;case"invalid_union":return"Geçersiz değer";case"invalid_element":return`${l.origin} içinde geçersiz değer`;default:return"Geçersiz değer"}}};function J(){return{localeError:V()}}o.exports=_.default})(Uu,Uu.exports);var YW=Uu.exports,Bu={exports:{}},zu={exports:{}},Ta=zu.exports;(function(o,_){var R=Ta&&Ta.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Ta&&Ta.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Ta&&Ta.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"символів",verb:"матиме"},file:{unit:"байтів",verb:"матиме"},array:{unit:"елементів",verb:"матиме"},set:{unit:"елементів",verb:"матиме"}};function v(l){return b[l]??null}const x={regex:"вхідні дані",email:"адреса електронної пошти",url:"URL",emoji:"емодзі",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"дата та час ISO",date:"дата ISO",time:"час ISO",duration:"тривалість ISO",ipv4:"адреса IPv4",ipv6:"адреса IPv6",cidrv4:"діапазон IPv4",cidrv6:"діапазон IPv6",base64:"рядок у кодуванні base64",base64url:"рядок у кодуванні base64url",json_string:"рядок JSON",e164:"номер E.164",jwt:"JWT",template_literal:"вхідні дані"},w={nan:"NaN",number:"число",array:"масив"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Неправильні вхідні дані: очікується instanceof ${l.expected}, отримано ${Z}`:`Неправильні вхідні дані: очікується ${i}, отримано ${Z}`}case"invalid_value":return l.values.length===1?`Неправильні вхідні дані: очікується ${D.stringifyPrimitive(l.values[0])}`:`Неправильна опція: очікується одне з ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Занадто велике: очікується, що ${l.origin??"значення"} ${I.verb} ${i}${l.maximum.toString()} ${I.unit??"елементів"}`:`Занадто велике: очікується, що ${l.origin??"значення"} буде ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Занадто мале: очікується, що ${l.origin} ${I.verb} ${i}${l.minimum.toString()} ${I.unit}`:`Занадто мале: очікується, що ${l.origin} буде ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Неправильний рядок: повинен починатися з "${i.prefix}"`:i.format==="ends_with"?`Неправильний рядок: повинен закінчуватися на "${i.suffix}"`:i.format==="includes"?`Неправильний рядок: повинен містити "${i.includes}"`:i.format==="regex"?`Неправильний рядок: повинен відповідати шаблону ${i.pattern}`:`Неправильний ${x[i.format]??l.format}`}case"not_multiple_of":return`Неправильне число: повинно бути кратним ${l.divisor}`;case"unrecognized_keys":return`Нерозпізнаний ключ${l.keys.length>1?"і":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Неправильний ключ у ${l.origin}`;case"invalid_union":return"Неправильні вхідні дані";case"invalid_element":return`Неправильне значення у ${l.origin}`;default:return"Неправильні вхідні дані"}}};function J(){return{localeError:V()}}o.exports=_.default})(zu,zu.exports);var Nw=zu.exports,gw=Bu.exports;(function(o,_){var R=gw&&gw.__importDefault||function(D){return D&&D.__esModule?D:{default:D}};Object.defineProperty(_,"__esModule",{value:!0}),_.default=P;const F=R(Nw);function P(){return(0,F.default)()}o.exports=_.default})(Bu,Bu.exports);var XW=Bu.exports,Gu={exports:{}},Ca=Gu.exports;(function(o,_){var R=Ca&&Ca.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Ca&&Ca.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Ca&&Ca.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"حروف",verb:"ہونا"},file:{unit:"بائٹس",verb:"ہونا"},array:{unit:"آئٹمز",verb:"ہونا"},set:{unit:"آئٹمز",verb:"ہونا"}};function v(l){return b[l]??null}const x={regex:"ان پٹ",email:"ای میل ایڈریس",url:"یو آر ایل",emoji:"ایموجی",uuid:"یو یو آئی ڈی",uuidv4:"یو یو آئی ڈی وی 4",uuidv6:"یو یو آئی ڈی وی 6",nanoid:"نینو آئی ڈی",guid:"جی یو آئی ڈی",cuid:"سی یو آئی ڈی",cuid2:"سی یو آئی ڈی 2",ulid:"یو ایل آئی ڈی",xid:"ایکس آئی ڈی",ksuid:"کے ایس یو آئی ڈی",datetime:"آئی ایس او ڈیٹ ٹائم",date:"آئی ایس او تاریخ",time:"آئی ایس او وقت",duration:"آئی ایس او مدت",ipv4:"آئی پی وی 4 ایڈریس",ipv6:"آئی پی وی 6 ایڈریس",cidrv4:"آئی پی وی 4 رینج",cidrv6:"آئی پی وی 6 رینج",base64:"بیس 64 ان کوڈڈ سٹرنگ",base64url:"بیس 64 یو آر ایل ان کوڈڈ سٹرنگ",json_string:"جے ایس او این سٹرنگ",e164:"ای 164 نمبر",jwt:"جے ڈبلیو ٹی",template_literal:"ان پٹ"},w={nan:"NaN",number:"نمبر",array:"آرے",null:"نل"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`غلط ان پٹ: instanceof ${l.expected} متوقع تھا، ${Z} موصول ہوا`:`غلط ان پٹ: ${i} متوقع تھا، ${Z} موصول ہوا`}case"invalid_value":return l.values.length===1?`غلط ان پٹ: ${D.stringifyPrimitive(l.values[0])} متوقع تھا`:`غلط آپشن: ${D.joinValues(l.values,"|")} میں سے ایک متوقع تھا`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`بہت بڑا: ${l.origin??"ویلیو"} کے ${i}${l.maximum.toString()} ${I.unit??"عناصر"} ہونے متوقع تھے`:`بہت بڑا: ${l.origin??"ویلیو"} کا ${i}${l.maximum.toString()} ہونا متوقع تھا`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`بہت چھوٹا: ${l.origin} کے ${i}${l.minimum.toString()} ${I.unit} ہونے متوقع تھے`:`بہت چھوٹا: ${l.origin} کا ${i}${l.minimum.toString()} ہونا متوقع تھا`}case"invalid_format":{const i=l;return i.format==="starts_with"?`غلط سٹرنگ: "${i.prefix}" سے شروع ہونا چاہیے`:i.format==="ends_with"?`غلط سٹرنگ: "${i.suffix}" پر ختم ہونا چاہیے`:i.format==="includes"?`غلط سٹرنگ: "${i.includes}" شامل ہونا چاہیے`:i.format==="regex"?`غلط سٹرنگ: پیٹرن ${i.pattern} سے میچ ہونا چاہیے`:`غلط ${x[i.format]??l.format}`}case"not_multiple_of":return`غلط نمبر: ${l.divisor} کا مضاعف ہونا چاہیے`;case"unrecognized_keys":return`غیر تسلیم شدہ کی${l.keys.length>1?"ز":""}: ${D.joinValues(l.keys,"، ")}`;case"invalid_key":return`${l.origin} میں غلط کی`;case"invalid_union":return"غلط ان پٹ";case"invalid_element":return`${l.origin} میں غلط ویلیو`;default:return"غلط ان پٹ"}}};function J(){return{localeError:V()}}o.exports=_.default})(Gu,Gu.exports);var JW=Gu.exports,Zu={exports:{}},Ia=Zu.exports;(function(o,_){var R=Ia&&Ia.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Ia&&Ia.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Ia&&Ia.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"belgi",verb:"bo‘lishi kerak"},file:{unit:"bayt",verb:"bo‘lishi kerak"},array:{unit:"element",verb:"bo‘lishi kerak"},set:{unit:"element",verb:"bo‘lishi kerak"},map:{unit:"yozuv",verb:"bo‘lishi kerak"}};function v(l){return b[l]??null}const x={regex:"kirish",email:"elektron pochta manzili",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},w={nan:"NaN",number:"raqam",array:"massiv"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Noto‘g‘ri kirish: kutilgan instanceof ${l.expected}, qabul qilingan ${Z}`:`Noto‘g‘ri kirish: kutilgan ${i}, qabul qilingan ${Z}`}case"invalid_value":return l.values.length===1?`Noto‘g‘ri kirish: kutilgan ${D.stringifyPrimitive(l.values[0])}`:`Noto‘g‘ri variant: quyidagilardan biri kutilgan ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Juda katta: kutilgan ${l.origin??"qiymat"} ${i}${l.maximum.toString()} ${I.unit} ${I.verb}`:`Juda katta: kutilgan ${l.origin??"qiymat"} ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Juda kichik: kutilgan ${l.origin} ${i}${l.minimum.toString()} ${I.unit} ${I.verb}`:`Juda kichik: kutilgan ${l.origin} ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Noto‘g‘ri satr: "${i.prefix}" bilan boshlanishi kerak`:i.format==="ends_with"?`Noto‘g‘ri satr: "${i.suffix}" bilan tugashi kerak`:i.format==="includes"?`Noto‘g‘ri satr: "${i.includes}" ni o‘z ichiga olishi kerak`:i.format==="regex"?`Noto‘g‘ri satr: ${i.pattern} shabloniga mos kelishi kerak`:`Noto‘g‘ri ${x[i.format]??l.format}`}case"not_multiple_of":return`Noto‘g‘ri raqam: ${l.divisor} ning karralisi bo‘lishi kerak`;case"unrecognized_keys":return`Noma’lum kalit${l.keys.length>1?"lar":""}: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`${l.origin} dagi kalit noto‘g‘ri`;case"invalid_union":return"Noto‘g‘ri kirish";case"invalid_element":return`${l.origin} da noto‘g‘ri qiymat`;default:return"Noto‘g‘ri kirish"}}};function J(){return{localeError:V()}}o.exports=_.default})(Zu,Zu.exports);var eq=Zu.exports,Vu={exports:{}},Pa=Vu.exports;(function(o,_){var R=Pa&&Pa.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Pa&&Pa.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Pa&&Pa.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"ký tự",verb:"có"},file:{unit:"byte",verb:"có"},array:{unit:"phần tử",verb:"có"},set:{unit:"phần tử",verb:"có"}};function v(l){return b[l]??null}const x={regex:"đầu vào",email:"địa chỉ email",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ngày giờ ISO",date:"ngày ISO",time:"giờ ISO",duration:"khoảng thời gian ISO",ipv4:"địa chỉ IPv4",ipv6:"địa chỉ IPv6",cidrv4:"dải IPv4",cidrv6:"dải IPv6",base64:"chuỗi mã hóa base64",base64url:"chuỗi mã hóa base64url",json_string:"chuỗi JSON",e164:"số E.164",jwt:"JWT",template_literal:"đầu vào"},w={nan:"NaN",number:"số",array:"mảng"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Đầu vào không hợp lệ: mong đợi instanceof ${l.expected}, nhận được ${Z}`:`Đầu vào không hợp lệ: mong đợi ${i}, nhận được ${Z}`}case"invalid_value":return l.values.length===1?`Đầu vào không hợp lệ: mong đợi ${D.stringifyPrimitive(l.values[0])}`:`Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Quá lớn: mong đợi ${l.origin??"giá trị"} ${I.verb} ${i}${l.maximum.toString()} ${I.unit??"phần tử"}`:`Quá lớn: mong đợi ${l.origin??"giá trị"} ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Quá nhỏ: mong đợi ${l.origin} ${I.verb} ${i}${l.minimum.toString()} ${I.unit}`:`Quá nhỏ: mong đợi ${l.origin} ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Chuỗi không hợp lệ: phải bắt đầu bằng "${i.prefix}"`:i.format==="ends_with"?`Chuỗi không hợp lệ: phải kết thúc bằng "${i.suffix}"`:i.format==="includes"?`Chuỗi không hợp lệ: phải bao gồm "${i.includes}"`:i.format==="regex"?`Chuỗi không hợp lệ: phải khớp với mẫu ${i.pattern}`:`${x[i.format]??l.format} không hợp lệ`}case"not_multiple_of":return`Số không hợp lệ: phải là bội số của ${l.divisor}`;case"unrecognized_keys":return`Khóa không được nhận dạng: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Khóa không hợp lệ trong ${l.origin}`;case"invalid_union":return"Đầu vào không hợp lệ";case"invalid_element":return`Giá trị không hợp lệ trong ${l.origin}`;default:return"Đầu vào không hợp lệ"}}};function J(){return{localeError:V()}}o.exports=_.default})(Vu,Vu.exports);var tq=Vu.exports,Hu={exports:{}},Aa=Hu.exports;(function(o,_){var R=Aa&&Aa.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Aa&&Aa.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Aa&&Aa.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"字符",verb:"包含"},file:{unit:"字节",verb:"包含"},array:{unit:"项",verb:"包含"},set:{unit:"项",verb:"包含"}};function v(l){return b[l]??null}const x={regex:"输入",email:"电子邮件",url:"URL",emoji:"表情符号",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO日期时间",date:"ISO日期",time:"ISO时间",duration:"ISO时长",ipv4:"IPv4地址",ipv6:"IPv6地址",cidrv4:"IPv4网段",cidrv6:"IPv6网段",base64:"base64编码字符串",base64url:"base64url编码字符串",json_string:"JSON字符串",e164:"E.164号码",jwt:"JWT",template_literal:"输入"},w={nan:"NaN",number:"数字",array:"数组",null:"空值(null)"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`无效输入:期望 instanceof ${l.expected},实际接收 ${Z}`:`无效输入:期望 ${i},实际接收 ${Z}`}case"invalid_value":return l.values.length===1?`无效输入:期望 ${D.stringifyPrimitive(l.values[0])}`:`无效选项:期望以下之一 ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`数值过大:期望 ${l.origin??"值"} ${i}${l.maximum.toString()} ${I.unit??"个元素"}`:`数值过大:期望 ${l.origin??"值"} ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`数值过小:期望 ${l.origin} ${i}${l.minimum.toString()} ${I.unit}`:`数值过小:期望 ${l.origin} ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`无效字符串:必须以 "${i.prefix}" 开头`:i.format==="ends_with"?`无效字符串:必须以 "${i.suffix}" 结尾`:i.format==="includes"?`无效字符串:必须包含 "${i.includes}"`:i.format==="regex"?`无效字符串:必须满足正则表达式 ${i.pattern}`:`无效${x[i.format]??l.format}`}case"not_multiple_of":return`无效数字:必须是 ${l.divisor} 的倍数`;case"unrecognized_keys":return`出现未知的键(key): ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`${l.origin} 中的键(key)无效`;case"invalid_union":return"无效输入";case"invalid_element":return`${l.origin} 中包含无效值(value)`;default:return"无效输入"}}};function J(){return{localeError:V()}}o.exports=_.default})(Hu,Hu.exports);var rq=Hu.exports,Ku={exports:{}},ja=Ku.exports;(function(o,_){var R=ja&&ja.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=ja&&ja.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=ja&&ja.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"字元",verb:"擁有"},file:{unit:"位元組",verb:"擁有"},array:{unit:"項目",verb:"擁有"},set:{unit:"項目",verb:"擁有"}};function v(l){return b[l]??null}const x={regex:"輸入",email:"郵件地址",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO 日期時間",date:"ISO 日期",time:"ISO 時間",duration:"ISO 期間",ipv4:"IPv4 位址",ipv6:"IPv6 位址",cidrv4:"IPv4 範圍",cidrv6:"IPv6 範圍",base64:"base64 編碼字串",base64url:"base64url 編碼字串",json_string:"JSON 字串",e164:"E.164 數值",jwt:"JWT",template_literal:"輸入"},w={nan:"NaN"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`無效的輸入值:預期為 instanceof ${l.expected},但收到 ${Z}`:`無效的輸入值:預期為 ${i},但收到 ${Z}`}case"invalid_value":return l.values.length===1?`無效的輸入值:預期為 ${D.stringifyPrimitive(l.values[0])}`:`無效的選項:預期為以下其中之一 ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`數值過大:預期 ${l.origin??"值"} 應為 ${i}${l.maximum.toString()} ${I.unit??"個元素"}`:`數值過大:預期 ${l.origin??"值"} 應為 ${i}${l.maximum.toString()}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`數值過小:預期 ${l.origin} 應為 ${i}${l.minimum.toString()} ${I.unit}`:`數值過小:預期 ${l.origin} 應為 ${i}${l.minimum.toString()}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`無效的字串:必須以 "${i.prefix}" 開頭`:i.format==="ends_with"?`無效的字串:必須以 "${i.suffix}" 結尾`:i.format==="includes"?`無效的字串:必須包含 "${i.includes}"`:i.format==="regex"?`無效的字串:必須符合格式 ${i.pattern}`:`無效的 ${x[i.format]??l.format}`}case"not_multiple_of":return`無效的數字:必須為 ${l.divisor} 的倍數`;case"unrecognized_keys":return`無法識別的鍵值${l.keys.length>1?"們":""}:${D.joinValues(l.keys,"、")}`;case"invalid_key":return`${l.origin} 中有無效的鍵值`;case"invalid_union":return"無效的輸入值";case"invalid_element":return`${l.origin} 中有無效的值`;default:return"無效的輸入值"}}};function J(){return{localeError:V()}}o.exports=_.default})(Ku,Ku.exports);var nq=Ku.exports,Wu={exports:{}},Na=Wu.exports;(function(o,_){var R=Na&&Na.__createBinding||(Object.create?(function(b,v,x,w){w===void 0&&(w=x);var l=Object.getOwnPropertyDescriptor(v,x);(!l||("get"in l?!v.__esModule:l.writable||l.configurable))&&(l={enumerable:!0,get:function(){return v[x]}}),Object.defineProperty(b,w,l)}):(function(b,v,x,w){w===void 0&&(w=x),b[w]=v[x]})),F=Na&&Na.__setModuleDefault||(Object.create?(function(b,v){Object.defineProperty(b,"default",{enumerable:!0,value:v})}):function(b,v){b.default=v}),P=Na&&Na.__importStar||function(b){if(b&&b.__esModule)return b;var v={};if(b!=null)for(var x in b)x!=="default"&&Object.prototype.hasOwnProperty.call(b,x)&&R(v,b,x);return F(v,b),v};Object.defineProperty(_,"__esModule",{value:!0}),_.default=J;const D=P(Ie),V=()=>{const b={string:{unit:"àmi",verb:"ní"},file:{unit:"bytes",verb:"ní"},array:{unit:"nkan",verb:"ní"},set:{unit:"nkan",verb:"ní"}};function v(l){return b[l]??null}const x={regex:"ẹ̀rọ ìbáwọlé",email:"àdírẹ́sì ìmẹ́lì",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"àkókò ISO",date:"ọjọ́ ISO",time:"àkókò ISO",duration:"àkókò tó pé ISO",ipv4:"àdírẹ́sì IPv4",ipv6:"àdírẹ́sì IPv6",cidrv4:"àgbègbè IPv4",cidrv6:"àgbègbè IPv6",base64:"ọ̀rọ̀ tí a kọ́ ní base64",base64url:"ọ̀rọ̀ base64url",json_string:"ọ̀rọ̀ JSON",e164:"nọ́mbà E.164",jwt:"JWT",template_literal:"ẹ̀rọ ìbáwọlé"},w={nan:"NaN",number:"nọ́mbà",array:"akopọ"};return l=>{switch(l.code){case"invalid_type":{const i=w[l.expected]??l.expected,I=D.parsedType(l.input),Z=w[I]??I;return/^[A-Z]/.test(l.expected)?`Ìbáwọlé aṣìṣe: a ní láti fi instanceof ${l.expected}, àmọ̀ a rí ${Z}`:`Ìbáwọlé aṣìṣe: a ní láti fi ${i}, àmọ̀ a rí ${Z}`}case"invalid_value":return l.values.length===1?`Ìbáwọlé aṣìṣe: a ní láti fi ${D.stringifyPrimitive(l.values[0])}`:`Àṣàyàn aṣìṣe: yan ọ̀kan lára ${D.joinValues(l.values,"|")}`;case"too_big":{const i=l.inclusive?"<=":"<",I=v(l.origin);return I?`Tó pọ̀ jù: a ní láti jẹ́ pé ${l.origin??"iye"} ${I.verb} ${i}${l.maximum} ${I.unit}`:`Tó pọ̀ jù: a ní láti jẹ́ ${i}${l.maximum}`}case"too_small":{const i=l.inclusive?">=":">",I=v(l.origin);return I?`Kéré ju: a ní láti jẹ́ pé ${l.origin} ${I.verb} ${i}${l.minimum} ${I.unit}`:`Kéré ju: a ní láti jẹ́ ${i}${l.minimum}`}case"invalid_format":{const i=l;return i.format==="starts_with"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${i.prefix}"`:i.format==="ends_with"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${i.suffix}"`:i.format==="includes"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${i.includes}"`:i.format==="regex"?`Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${i.pattern}`:`Aṣìṣe: ${x[i.format]??l.format}`}case"not_multiple_of":return`Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${l.divisor}`;case"unrecognized_keys":return`Bọtìnì àìmọ̀: ${D.joinValues(l.keys,", ")}`;case"invalid_key":return`Bọtìnì aṣìṣe nínú ${l.origin}`;case"invalid_union":return"Ìbáwọlé aṣìṣe";case"invalid_element":return`Iye aṣìṣe nínú ${l.origin}`;default:return"Ìbáwọlé aṣìṣe"}}};function J(){return{localeError:V()}}o.exports=_.default})(Wu,Wu.exports);var iq=Wu.exports;(function(o){var _=Bo&&Bo.__importDefault||function(Tt){return Tt&&Tt.__esModule?Tt:{default:Tt}};Object.defineProperty(o,"__esModule",{value:!0}),o.zhCN=o.vi=o.uz=o.ur=o.uk=o.ua=o.tr=o.th=o.ta=o.sv=o.sl=o.ru=o.ro=o.pt=o.pl=o.ps=o.ota=o.no=o.nl=o.ms=o.mk=o.lt=o.ko=o.km=o.kh=o.ka=o.ja=o.it=o.is=o.id=o.hy=o.hu=o.hr=o.he=o.frCA=o.fr=o.fi=o.fa=o.es=o.eo=o.en=o.el=o.de=o.da=o.cs=o.ca=o.bg=o.be=o.az=o.ar=void 0,o.yo=o.zhTW=void 0;var R=uW;Object.defineProperty(o,"ar",{enumerable:!0,get:function(){return _(R).default}});var F=dW;Object.defineProperty(o,"az",{enumerable:!0,get:function(){return _(F).default}});var P=fW;Object.defineProperty(o,"be",{enumerable:!0,get:function(){return _(P).default}});var D=hW;Object.defineProperty(o,"bg",{enumerable:!0,get:function(){return _(D).default}});var V=mW;Object.defineProperty(o,"ca",{enumerable:!0,get:function(){return _(V).default}});var J=gW;Object.defineProperty(o,"cs",{enumerable:!0,get:function(){return _(J).default}});var b=pW;Object.defineProperty(o,"da",{enumerable:!0,get:function(){return _(b).default}});var v=vW;Object.defineProperty(o,"de",{enumerable:!0,get:function(){return _(v).default}});var x=bW;Object.defineProperty(o,"el",{enumerable:!0,get:function(){return _(x).default}});var w=Aw;Object.defineProperty(o,"en",{enumerable:!0,get:function(){return _(w).default}});var l=yW;Object.defineProperty(o,"eo",{enumerable:!0,get:function(){return _(l).default}});var i=xW;Object.defineProperty(o,"es",{enumerable:!0,get:function(){return _(i).default}});var I=SW;Object.defineProperty(o,"fa",{enumerable:!0,get:function(){return _(I).default}});var Z=_W;Object.defineProperty(o,"fi",{enumerable:!0,get:function(){return _(Z).default}});var ye=wW;Object.defineProperty(o,"fr",{enumerable:!0,get:function(){return _(ye).default}});var ve=EW;Object.defineProperty(o,"frCA",{enumerable:!0,get:function(){return _(ve).default}});var Te=kW;Object.defineProperty(o,"he",{enumerable:!0,get:function(){return _(Te).default}});var _e=TW;Object.defineProperty(o,"hr",{enumerable:!0,get:function(){return _(_e).default}});var Oe=CW;Object.defineProperty(o,"hu",{enumerable:!0,get:function(){return _(Oe).default}});var W=IW;Object.defineProperty(o,"hy",{enumerable:!0,get:function(){return _(W).default}});var Ze=PW;Object.defineProperty(o,"id",{enumerable:!0,get:function(){return _(Ze).default}});var Le=AW;Object.defineProperty(o,"is",{enumerable:!0,get:function(){return _(Le).default}});var ot=jW;Object.defineProperty(o,"it",{enumerable:!0,get:function(){return _(ot).default}});var tt=NW;Object.defineProperty(o,"ja",{enumerable:!0,get:function(){return _(tt).default}});var _t=DW;Object.defineProperty(o,"ka",{enumerable:!0,get:function(){return _(_t).default}});var Kt=MW;Object.defineProperty(o,"kh",{enumerable:!0,get:function(){return _(Kt).default}});var cr=jw;Object.defineProperty(o,"km",{enumerable:!0,get:function(){return _(cr).default}});var kr=$W;Object.defineProperty(o,"ko",{enumerable:!0,get:function(){return _(kr).default}});var Tr=RW;Object.defineProperty(o,"lt",{enumerable:!0,get:function(){return _(Tr).default}});var Ir=LW;Object.defineProperty(o,"mk",{enumerable:!0,get:function(){return _(Ir).default}});var Dr=OW;Object.defineProperty(o,"ms",{enumerable:!0,get:function(){return _(Dr).default}});var Qt=FW;Object.defineProperty(o,"nl",{enumerable:!0,get:function(){return _(Qt).default}});var Or=UW;Object.defineProperty(o,"no",{enumerable:!0,get:function(){return _(Or).default}});var bn=BW;Object.defineProperty(o,"ota",{enumerable:!0,get:function(){return _(bn).default}});var M=zW;Object.defineProperty(o,"ps",{enumerable:!0,get:function(){return _(M).default}});var L=GW;Object.defineProperty(o,"pl",{enumerable:!0,get:function(){return _(L).default}});var B=ZW;Object.defineProperty(o,"pt",{enumerable:!0,get:function(){return _(B).default}});var Y=VW;Object.defineProperty(o,"ro",{enumerable:!0,get:function(){return _(Y).default}});var re=HW;Object.defineProperty(o,"ru",{enumerable:!0,get:function(){return _(re).default}});var ue=KW;Object.defineProperty(o,"sl",{enumerable:!0,get:function(){return _(ue).default}});var ke=WW;Object.defineProperty(o,"sv",{enumerable:!0,get:function(){return _(ke).default}});var Me=qW;Object.defineProperty(o,"ta",{enumerable:!0,get:function(){return _(Me).default}});var de=QW;Object.defineProperty(o,"th",{enumerable:!0,get:function(){return _(de).default}});var ce=YW;Object.defineProperty(o,"tr",{enumerable:!0,get:function(){return _(ce).default}});var Pe=XW;Object.defineProperty(o,"ua",{enumerable:!0,get:function(){return _(Pe).default}});var De=Nw;Object.defineProperty(o,"uk",{enumerable:!0,get:function(){return _(De).default}});var me=JW;Object.defineProperty(o,"ur",{enumerable:!0,get:function(){return _(me).default}});var je=eq;Object.defineProperty(o,"uz",{enumerable:!0,get:function(){return _(je).default}});var Ve=tq;Object.defineProperty(o,"vi",{enumerable:!0,get:function(){return _(Ve).default}});var wt=rq;Object.defineProperty(o,"zhCN",{enumerable:!0,get:function(){return _(wt).default}});var ht=nq;Object.defineProperty(o,"zhTW",{enumerable:!0,get:function(){return _(ht).default}});var pt=iq;Object.defineProperty(o,"yo",{enumerable:!0,get:function(){return _(pt).default}})})(Bo);var Lr={},pw;Object.defineProperty(Lr,"__esModule",{value:!0});Lr.globalRegistry=Lr.$ZodRegistry=Lr.$input=Lr.$output=void 0;Lr.registry=Mw;Lr.$output=Symbol("ZodOutput");Lr.$input=Symbol("ZodInput");class Dw{constructor(){this._map=new WeakMap,this._idmap=new Map}add(_,...R){const F=R[0];return this._map.set(_,F),F&&typeof F=="object"&&"id"in F&&this._idmap.set(F.id,_),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(_){const R=this._map.get(_);return R&&typeof R=="object"&&"id"in R&&this._idmap.delete(R.id),this._map.delete(_),this}get(_){const R=_._zod.parent;if(R){const F={...this.get(R)??{}};delete F.id;const P={...F,...this._map.get(_)};return Object.keys(P).length?P:void 0}return this._map.get(_)}has(_){return this._map.has(_)}}Lr.$ZodRegistry=Dw;function Mw(){return new Dw}(pw=globalThis).__zod_globalRegistry??(pw.__zod_globalRegistry=Mw());Lr.globalRegistry=globalThis.__zod_globalRegistry;var Ae={},sq=Ae&&Ae.__createBinding||(Object.create?(function(o,_,R,F){F===void 0&&(F=R);var P=Object.getOwnPropertyDescriptor(_,R);(!P||("get"in P?!_.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return _[R]}}),Object.defineProperty(o,F,P)}):(function(o,_,R,F){F===void 0&&(F=R),o[F]=_[R]})),aq=Ae&&Ae.__setModuleDefault||(Object.create?(function(o,_){Object.defineProperty(o,"default",{enumerable:!0,value:_})}):function(o,_){o.default=_}),Ju=Ae&&Ae.__importStar||function(o){if(o&&o.__esModule)return o;var _={};if(o!=null)for(var R in o)R!=="default"&&Object.prototype.hasOwnProperty.call(o,R)&&sq(_,o,R);return aq(_,o),_};Object.defineProperty(Ae,"__esModule",{value:!0});Ae.TimePrecision=void 0;Ae._string=oq;Ae._coercedString=lq;Ae._email=cq;Ae._guid=uq;Ae._uuid=dq;Ae._uuidv4=fq;Ae._uuidv6=hq;Ae._uuidv7=mq;Ae._url=gq;Ae._emoji=pq;Ae._nanoid=vq;Ae._cuid=bq;Ae._cuid2=yq;Ae._ulid=xq;Ae._xid=Sq;Ae._ksuid=_q;Ae._ipv4=wq;Ae._ipv6=Eq;Ae._mac=kq;Ae._cidrv4=Tq;Ae._cidrv6=Cq;Ae._base64=Iq;Ae._base64url=Pq;Ae._e164=Aq;Ae._jwt=jq;Ae._isoDateTime=Nq;Ae._isoDate=Dq;Ae._isoTime=Mq;Ae._isoDuration=$q;Ae._number=Rq;Ae._coercedNumber=Lq;Ae._int=Oq;Ae._float32=Fq;Ae._float64=Uq;Ae._int32=Bq;Ae._uint32=zq;Ae._boolean=Gq;Ae._coercedBoolean=Zq;Ae._bigint=Vq;Ae._coercedBigint=Hq;Ae._int64=Kq;Ae._uint64=Wq;Ae._symbol=qq;Ae._undefined=Qq;Ae._null=Yq;Ae._any=Xq;Ae._unknown=Jq;Ae._never=eQ;Ae._void=tQ;Ae._date=rQ;Ae._coercedDate=nQ;Ae._nan=iQ;Ae._lt=$w;Ae._lte=Zo;Ae._max=Zo;Ae._lte=Zo;Ae._max=Zo;Ae._gt=Rw;Ae._gte=Vo;Ae._min=Vo;Ae._gte=Vo;Ae._min=Vo;Ae._positive=sQ;Ae._negative=aQ;Ae._nonpositive=oQ;Ae._nonnegative=lQ;Ae._multipleOf=cQ;Ae._maxSize=uQ;Ae._minSize=dQ;Ae._size=fQ;Ae._maxLength=hQ;Ae._minLength=mQ;Ae._length=gQ;Ae._regex=pQ;Ae._lowercase=vQ;Ae._uppercase=bQ;Ae._includes=yQ;Ae._startsWith=xQ;Ae._endsWith=SQ;Ae._property=_Q;Ae._mime=wQ;Ae._overwrite=$a;Ae._normalize=EQ;Ae._trim=kQ;Ae._toLowerCase=TQ;Ae._toUpperCase=CQ;Ae._slugify=IQ;Ae._array=PQ;Ae._union=AQ;Ae._xor=jQ;Ae._discriminatedUnion=NQ;Ae._intersection=DQ;Ae._tuple=MQ;Ae._record=$Q;Ae._map=RQ;Ae._set=LQ;Ae._enum=OQ;Ae._nativeEnum=FQ;Ae._literal=UQ;Ae._file=BQ;Ae._transform=zQ;Ae._optional=GQ;Ae._nullable=ZQ;Ae._default=VQ;Ae._nonoptional=HQ;Ae._success=KQ;Ae._catch=WQ;Ae._pipe=qQ;Ae._readonly=QQ;Ae._templateLiteral=YQ;Ae._lazy=XQ;Ae._promise=JQ;Ae._custom=eY;Ae._refine=tY;Ae._superRefine=rY;Ae._check=Lw;Ae.describe=nY;Ae.meta=iY;Ae._stringbool=sY;Ae._stringFormat=aY;const Xt=Ju(Mn),qu=Ju(Lr),Wc=Ju(Xn),ze=Ju(Ie);function oq(o,_){return new o({type:"string",...ze.normalizeParams(_)})}function lq(o,_){return new o({type:"string",coerce:!0,...ze.normalizeParams(_)})}function cq(o,_){return new o({type:"string",format:"email",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function uq(o,_){return new o({type:"string",format:"guid",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function dq(o,_){return new o({type:"string",format:"uuid",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function fq(o,_){return new o({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ze.normalizeParams(_)})}function hq(o,_){return new o({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ze.normalizeParams(_)})}function mq(o,_){return new o({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ze.normalizeParams(_)})}function gq(o,_){return new o({type:"string",format:"url",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function pq(o,_){return new o({type:"string",format:"emoji",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function vq(o,_){return new o({type:"string",format:"nanoid",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function bq(o,_){return new o({type:"string",format:"cuid",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function yq(o,_){return new o({type:"string",format:"cuid2",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function xq(o,_){return new o({type:"string",format:"ulid",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function Sq(o,_){return new o({type:"string",format:"xid",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function _q(o,_){return new o({type:"string",format:"ksuid",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function wq(o,_){return new o({type:"string",format:"ipv4",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function Eq(o,_){return new o({type:"string",format:"ipv6",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function kq(o,_){return new o({type:"string",format:"mac",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function Tq(o,_){return new o({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function Cq(o,_){return new o({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function Iq(o,_){return new o({type:"string",format:"base64",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function Pq(o,_){return new o({type:"string",format:"base64url",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function Aq(o,_){return new o({type:"string",format:"e164",check:"string_format",abort:!1,...ze.normalizeParams(_)})}function jq(o,_){return new o({type:"string",format:"jwt",check:"string_format",abort:!1,...ze.normalizeParams(_)})}Ae.TimePrecision={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6};function Nq(o,_){return new o({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ze.normalizeParams(_)})}function Dq(o,_){return new o({type:"string",format:"date",check:"string_format",...ze.normalizeParams(_)})}function Mq(o,_){return new o({type:"string",format:"time",check:"string_format",precision:null,...ze.normalizeParams(_)})}function $q(o,_){return new o({type:"string",format:"duration",check:"string_format",...ze.normalizeParams(_)})}function Rq(o,_){return new o({type:"number",checks:[],...ze.normalizeParams(_)})}function Lq(o,_){return new o({type:"number",coerce:!0,checks:[],...ze.normalizeParams(_)})}function Oq(o,_){return new o({type:"number",check:"number_format",abort:!1,format:"safeint",...ze.normalizeParams(_)})}function Fq(o,_){return new o({type:"number",check:"number_format",abort:!1,format:"float32",...ze.normalizeParams(_)})}function Uq(o,_){return new o({type:"number",check:"number_format",abort:!1,format:"float64",...ze.normalizeParams(_)})}function Bq(o,_){return new o({type:"number",check:"number_format",abort:!1,format:"int32",...ze.normalizeParams(_)})}function zq(o,_){return new o({type:"number",check:"number_format",abort:!1,format:"uint32",...ze.normalizeParams(_)})}function Gq(o,_){return new o({type:"boolean",...ze.normalizeParams(_)})}function Zq(o,_){return new o({type:"boolean",coerce:!0,...ze.normalizeParams(_)})}function Vq(o,_){return new o({type:"bigint",...ze.normalizeParams(_)})}function Hq(o,_){return new o({type:"bigint",coerce:!0,...ze.normalizeParams(_)})}function Kq(o,_){return new o({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...ze.normalizeParams(_)})}function Wq(o,_){return new o({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...ze.normalizeParams(_)})}function qq(o,_){return new o({type:"symbol",...ze.normalizeParams(_)})}function Qq(o,_){return new o({type:"undefined",...ze.normalizeParams(_)})}function Yq(o,_){return new o({type:"null",...ze.normalizeParams(_)})}function Xq(o){return new o({type:"any"})}function Jq(o){return new o({type:"unknown"})}function eQ(o,_){return new o({type:"never",...ze.normalizeParams(_)})}function tQ(o,_){return new o({type:"void",...ze.normalizeParams(_)})}function rQ(o,_){return new o({type:"date",...ze.normalizeParams(_)})}function nQ(o,_){return new o({type:"date",coerce:!0,...ze.normalizeParams(_)})}function iQ(o,_){return new o({type:"nan",...ze.normalizeParams(_)})}function $w(o,_){return new Xt.$ZodCheckLessThan({check:"less_than",...ze.normalizeParams(_),value:o,inclusive:!1})}function Zo(o,_){return new Xt.$ZodCheckLessThan({check:"less_than",...ze.normalizeParams(_),value:o,inclusive:!0})}function Rw(o,_){return new Xt.$ZodCheckGreaterThan({check:"greater_than",...ze.normalizeParams(_),value:o,inclusive:!1})}function Vo(o,_){return new Xt.$ZodCheckGreaterThan({check:"greater_than",...ze.normalizeParams(_),value:o,inclusive:!0})}function sQ(o){return Rw(0,o)}function aQ(o){return $w(0,o)}function oQ(o){return Zo(0,o)}function lQ(o){return Vo(0,o)}function cQ(o,_){return new Xt.$ZodCheckMultipleOf({check:"multiple_of",...ze.normalizeParams(_),value:o})}function uQ(o,_){return new Xt.$ZodCheckMaxSize({check:"max_size",...ze.normalizeParams(_),maximum:o})}function dQ(o,_){return new Xt.$ZodCheckMinSize({check:"min_size",...ze.normalizeParams(_),minimum:o})}function fQ(o,_){return new Xt.$ZodCheckSizeEquals({check:"size_equals",...ze.normalizeParams(_),size:o})}function hQ(o,_){return new Xt.$ZodCheckMaxLength({check:"max_length",...ze.normalizeParams(_),maximum:o})}function mQ(o,_){return new Xt.$ZodCheckMinLength({check:"min_length",...ze.normalizeParams(_),minimum:o})}function gQ(o,_){return new Xt.$ZodCheckLengthEquals({check:"length_equals",...ze.normalizeParams(_),length:o})}function pQ(o,_){return new Xt.$ZodCheckRegex({check:"string_format",format:"regex",...ze.normalizeParams(_),pattern:o})}function vQ(o){return new Xt.$ZodCheckLowerCase({check:"string_format",format:"lowercase",...ze.normalizeParams(o)})}function bQ(o){return new Xt.$ZodCheckUpperCase({check:"string_format",format:"uppercase",...ze.normalizeParams(o)})}function yQ(o,_){return new Xt.$ZodCheckIncludes({check:"string_format",format:"includes",...ze.normalizeParams(_),includes:o})}function xQ(o,_){return new Xt.$ZodCheckStartsWith({check:"string_format",format:"starts_with",...ze.normalizeParams(_),prefix:o})}function SQ(o,_){return new Xt.$ZodCheckEndsWith({check:"string_format",format:"ends_with",...ze.normalizeParams(_),suffix:o})}function _Q(o,_,R){return new Xt.$ZodCheckProperty({check:"property",property:o,schema:_,...ze.normalizeParams(R)})}function wQ(o,_){return new Xt.$ZodCheckMimeType({check:"mime_type",mime:o,...ze.normalizeParams(_)})}function $a(o){return new Xt.$ZodCheckOverwrite({check:"overwrite",tx:o})}function EQ(o){return $a(_=>_.normalize(o))}function kQ(){return $a(o=>o.trim())}function TQ(){return $a(o=>o.toLowerCase())}function CQ(){return $a(o=>o.toUpperCase())}function IQ(){return $a(o=>ze.slugify(o))}function PQ(o,_,R){return new o({type:"array",element:_,...ze.normalizeParams(R)})}function AQ(o,_,R){return new o({type:"union",options:_,...ze.normalizeParams(R)})}function jQ(o,_,R){return new o({type:"union",options:_,inclusive:!1,...ze.normalizeParams(R)})}function NQ(o,_,R,F){return new o({type:"union",options:R,discriminator:_,...ze.normalizeParams(F)})}function DQ(o,_,R){return new o({type:"intersection",left:_,right:R})}function MQ(o,_,R,F){const P=R instanceof Wc.$ZodType,D=P?F:R,V=P?R:null;return new o({type:"tuple",items:_,rest:V,...ze.normalizeParams(D)})}function $Q(o,_,R,F){return new o({type:"record",keyType:_,valueType:R,...ze.normalizeParams(F)})}function RQ(o,_,R,F){return new o({type:"map",keyType:_,valueType:R,...ze.normalizeParams(F)})}function LQ(o,_,R){return new o({type:"set",valueType:_,...ze.normalizeParams(R)})}function OQ(o,_,R){const F=Array.isArray(_)?Object.fromEntries(_.map(P=>[P,P])):_;return new o({type:"enum",entries:F,...ze.normalizeParams(R)})}function FQ(o,_,R){return new o({type:"enum",entries:_,...ze.normalizeParams(R)})}function UQ(o,_,R){return new o({type:"literal",values:Array.isArray(_)?_:[_],...ze.normalizeParams(R)})}function BQ(o,_){return new o({type:"file",...ze.normalizeParams(_)})}function zQ(o,_){return new o({type:"transform",transform:_})}function GQ(o,_){return new o({type:"optional",innerType:_})}function ZQ(o,_){return new o({type:"nullable",innerType:_})}function VQ(o,_,R){return new o({type:"default",innerType:_,get defaultValue(){return typeof R=="function"?R():ze.shallowClone(R)}})}function HQ(o,_,R){return new o({type:"nonoptional",innerType:_,...ze.normalizeParams(R)})}function KQ(o,_){return new o({type:"success",innerType:_})}function WQ(o,_,R){return new o({type:"catch",innerType:_,catchValue:typeof R=="function"?R:()=>R})}function qQ(o,_,R){return new o({type:"pipe",in:_,out:R})}function QQ(o,_){return new o({type:"readonly",innerType:_})}function YQ(o,_,R){return new o({type:"template_literal",parts:_,...ze.normalizeParams(R)})}function XQ(o,_){return new o({type:"lazy",getter:_})}function JQ(o,_){return new o({type:"promise",innerType:_})}function eY(o,_,R){const F=ze.normalizeParams(R);return F.abort??(F.abort=!0),new o({type:"custom",check:"custom",fn:_,...F})}function tY(o,_,R){return new o({type:"custom",check:"custom",fn:_,...ze.normalizeParams(R)})}function rY(o,_){const R=Lw(F=>(F.addIssue=P=>{if(typeof P=="string")F.issues.push(ze.issue(P,F.value,R._zod.def));else{const D=P;D.fatal&&(D.continue=!1),D.code??(D.code="custom"),D.input??(D.input=F.value),D.inst??(D.inst=R),D.continue??(D.continue=!R._zod.def.abort),F.issues.push(ze.issue(D))}},o(F.value,F)),_);return R}function Lw(o,_){const R=new Xt.$ZodCheck({check:"custom",...ze.normalizeParams(_)});return R._zod.check=o,R}function nY(o){const _=new Xt.$ZodCheck({check:"describe"});return _._zod.onattach=[R=>{const F=qu.globalRegistry.get(R)??{};qu.globalRegistry.add(R,{...F,description:o})}],_._zod.check=()=>{},_}function iY(o){const _=new Xt.$ZodCheck({check:"meta"});return _._zod.onattach=[R=>{const F=qu.globalRegistry.get(R)??{};qu.globalRegistry.add(R,{...F,...o})}],_._zod.check=()=>{},_}function sY(o,_){const R=ze.normalizeParams(_);let F=R.truthy??["true","1","yes","on","y","enabled"],P=R.falsy??["false","0","no","off","n","disabled"];R.case!=="sensitive"&&(F=F.map(i=>typeof i=="string"?i.toLowerCase():i),P=P.map(i=>typeof i=="string"?i.toLowerCase():i));const D=new Set(F),V=new Set(P),J=o.Codec??Wc.$ZodCodec,b=o.Boolean??Wc.$ZodBoolean,v=o.String??Wc.$ZodString,x=new v({type:"string",error:R.error}),w=new b({type:"boolean",error:R.error}),l=new J({type:"pipe",in:x,out:w,transform:((i,I)=>{let Z=i;return R.case!=="sensitive"&&(Z=Z.toLowerCase()),D.has(Z)?!0:V.has(Z)?!1:(I.issues.push({code:"invalid_value",expected:"stringbool",values:[...D,...V],input:I.value,inst:l,continue:!1}),{})}),reverseTransform:((i,I)=>i===!0?F[0]||"true":P[0]||"false"),error:R.error});return l}function aY(o,_,R,F={}){const P=ze.normalizeParams(F),D={...ze.normalizeParams(F),check:"string_format",type:"string",format:_,fn:typeof R=="function"?R:J=>R.test(J),...P};return R instanceof RegExp&&(D.pattern=R),new o(D)}var Ho={};(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.createStandardJSONSchemaMethod=o.createToJSONSchemaMethod=void 0,o.initializeContext=R,o.process=F,o.extractDefs=P,o.finalize=D;const _=Lr;function R(v){let x=v?.target??"draft-2020-12";return x==="draft-4"&&(x="draft-04"),x==="draft-7"&&(x="draft-07"),{processors:v.processors??{},metadataRegistry:v?.metadata??_.globalRegistry,target:x,unrepresentable:v?.unrepresentable??"throw",override:v?.override??(()=>{}),io:v?.io??"output",counter:0,seen:new Map,cycles:v?.cycles??"ref",reused:v?.reused??"inline",external:v?.external??void 0}}function F(v,x,w={path:[],schemaPath:[]}){var l;const i=v._zod.def,I=x.seen.get(v);if(I)return I.count++,w.schemaPath.includes(v)&&(I.cycle=w.path),I.schema;const Z={schema:{},count:1,cycle:void 0,path:w.path};x.seen.set(v,Z);const ye=v._zod.toJSONSchema?.();if(ye)Z.schema=ye;else{const _e={...w,schemaPath:[...w.schemaPath,v],path:w.path};if(v._zod.processJSONSchema)v._zod.processJSONSchema(x,Z.schema,_e);else{const W=Z.schema,Ze=x.processors[i.type];if(!Ze)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);Ze(v,x,W,_e)}const Oe=v._zod.parent;Oe&&(Z.ref||(Z.ref=Oe),F(Oe,x,_e),x.seen.get(Oe).isParent=!0)}const ve=x.metadataRegistry.get(v);return ve&&Object.assign(Z.schema,ve),x.io==="input"&&V(v)&&(delete Z.schema.examples,delete Z.schema.default),x.io==="input"&&"_prefault"in Z.schema&&((l=Z.schema).default??(l.default=Z.schema._prefault)),delete Z.schema._prefault,x.seen.get(v).schema}function P(v,x){const w=v.seen.get(x);if(!w)throw new Error("Unprocessed schema. This is a bug in Zod.");const l=new Map;for(const Z of v.seen.entries()){const ye=v.metadataRegistry.get(Z[0])?.id;if(ye){const ve=l.get(ye);if(ve&&ve!==Z[0])throw new Error(`Duplicate schema id "${ye}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);l.set(ye,Z[0])}}const i=Z=>{const ye=v.target==="draft-2020-12"?"$defs":"definitions";if(v.external){const Oe=v.external.registry.get(Z[0])?.id,W=v.external.uri??(Le=>Le);if(Oe)return{ref:W(Oe)};const Ze=Z[1].defId??Z[1].schema.id??`schema${v.counter++}`;return Z[1].defId=Ze,{defId:Ze,ref:`${W("__shared")}#/${ye}/${Ze}`}}if(Z[1]===w)return{ref:"#"};const Te=`#/${ye}/`,_e=Z[1].schema.id??`__schema${v.counter++}`;return{defId:_e,ref:Te+_e}},I=Z=>{if(Z[1].schema.$ref)return;const ye=Z[1],{ref:ve,defId:Te}=i(Z);ye.def={...ye.schema},Te&&(ye.defId=Te);const _e=ye.schema;for(const Oe in _e)delete _e[Oe];_e.$ref=ve};if(v.cycles==="throw")for(const Z of v.seen.entries()){const ye=Z[1];if(ye.cycle)throw new Error(`Cycle detected: #/${ye.cycle?.join("/")}/<root>
93
+
94
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const Z of v.seen.entries()){const ye=Z[1];if(x===Z[0]){I(Z);continue}if(v.external){const Te=v.external.registry.get(Z[0])?.id;if(x!==Z[0]&&Te){I(Z);continue}}if(v.metadataRegistry.get(Z[0])?.id){I(Z);continue}if(ye.cycle){I(Z);continue}if(ye.count>1&&v.reused==="ref"){I(Z);continue}}}function D(v,x){const w=v.seen.get(x);if(!w)throw new Error("Unprocessed schema. This is a bug in Zod.");const l=ye=>{const ve=v.seen.get(ye);if(ve.ref===null)return;const Te=ve.def??ve.schema,_e={...Te},Oe=ve.ref;if(ve.ref=null,Oe){l(Oe);const Ze=v.seen.get(Oe),Le=Ze.schema;if(Le.$ref&&(v.target==="draft-07"||v.target==="draft-04"||v.target==="openapi-3.0")?(Te.allOf=Te.allOf??[],Te.allOf.push(Le)):Object.assign(Te,Le),Object.assign(Te,_e),ye._zod.parent===Oe)for(const tt in Te)tt==="$ref"||tt==="allOf"||tt in _e||delete Te[tt];if(Le.$ref&&Ze.def)for(const tt in Te)tt==="$ref"||tt==="allOf"||tt in Ze.def&&JSON.stringify(Te[tt])===JSON.stringify(Ze.def[tt])&&delete Te[tt]}const W=ye._zod.parent;if(W&&W!==Oe){l(W);const Ze=v.seen.get(W);if(Ze?.schema.$ref&&(Te.$ref=Ze.schema.$ref,Ze.def))for(const Le in Te)Le==="$ref"||Le==="allOf"||Le in Ze.def&&JSON.stringify(Te[Le])===JSON.stringify(Ze.def[Le])&&delete Te[Le]}v.override({zodSchema:ye,jsonSchema:Te,path:ve.path??[]})};for(const ye of[...v.seen.entries()].reverse())l(ye[0]);const i={};if(v.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":v.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":v.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":v.target,v.external?.uri){const ye=v.external.registry.get(x)?.id;if(!ye)throw new Error("Schema is missing an `id` property");i.$id=v.external.uri(ye)}Object.assign(i,w.def??w.schema);const I=v.metadataRegistry.get(x)?.id;I!==void 0&&i.id===I&&delete i.id;const Z=v.external?.defs??{};for(const ye of v.seen.entries()){const ve=ye[1];ve.def&&ve.defId&&(ve.def.id===ve.defId&&delete ve.def.id,Z[ve.defId]=ve.def)}v.external||Object.keys(Z).length>0&&(v.target==="draft-2020-12"?i.$defs=Z:i.definitions=Z);try{const ye=JSON.parse(JSON.stringify(i));return Object.defineProperty(ye,"~standard",{value:{...x["~standard"],jsonSchema:{input:(0,o.createStandardJSONSchemaMethod)(x,"input",v.processors),output:(0,o.createStandardJSONSchemaMethod)(x,"output",v.processors)}},enumerable:!1,writable:!1}),ye}catch{throw new Error("Error converting schema to JSON.")}}function V(v,x){const w=x??{seen:new Set};if(w.seen.has(v))return!1;w.seen.add(v);const l=v._zod.def;if(l.type==="transform")return!0;if(l.type==="array")return V(l.element,w);if(l.type==="set")return V(l.valueType,w);if(l.type==="lazy")return V(l.getter(),w);if(l.type==="promise"||l.type==="optional"||l.type==="nonoptional"||l.type==="nullable"||l.type==="readonly"||l.type==="default"||l.type==="prefault")return V(l.innerType,w);if(l.type==="intersection")return V(l.left,w)||V(l.right,w);if(l.type==="record"||l.type==="map")return V(l.keyType,w)||V(l.valueType,w);if(l.type==="pipe")return v._zod.traits.has("$ZodCodec")?!0:V(l.in,w)||V(l.out,w);if(l.type==="object"){for(const i in l.shape)if(V(l.shape[i],w))return!0;return!1}if(l.type==="union"){for(const i of l.options)if(V(i,w))return!0;return!1}if(l.type==="tuple"){for(const i of l.items)if(V(i,w))return!0;return!!(l.rest&&V(l.rest,w))}return!1}const J=(v,x={})=>w=>{const l=R({...w,processors:x});return F(v,l),P(l,v),D(l,v)};o.createToJSONSchemaMethod=J;const b=(v,x,w={})=>l=>{const{libraryOptions:i,target:I}=l??{},Z=R({...i??{},target:I,io:x,processors:w});return F(v,Z),P(Z,v),D(Z,v)};o.createStandardJSONSchemaMethod=b})(Ho);var Ko={};(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.allProcessors=o.lazyProcessor=o.optionalProcessor=o.promiseProcessor=o.readonlyProcessor=o.pipeProcessor=o.catchProcessor=o.prefaultProcessor=o.defaultProcessor=o.nonoptionalProcessor=o.nullableProcessor=o.recordProcessor=o.tupleProcessor=o.intersectionProcessor=o.unionProcessor=o.objectProcessor=o.arrayProcessor=o.setProcessor=o.mapProcessor=o.transformProcessor=o.functionProcessor=o.customProcessor=o.successProcessor=o.fileProcessor=o.templateLiteralProcessor=o.nanProcessor=o.literalProcessor=o.enumProcessor=o.dateProcessor=o.unknownProcessor=o.anyProcessor=o.neverProcessor=o.voidProcessor=o.undefinedProcessor=o.nullProcessor=o.symbolProcessor=o.bigintProcessor=o.booleanProcessor=o.numberProcessor=o.stringProcessor=void 0,o.toJSONSchema=Me;const _=Ho,R=Ie,F={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},P=(de,ce,Pe,De)=>{const me=Pe;me.type="string";const{minimum:je,maximum:Ve,format:wt,patterns:ht,contentEncoding:pt}=de._zod.bag;if(typeof je=="number"&&(me.minLength=je),typeof Ve=="number"&&(me.maxLength=Ve),wt&&(me.format=F[wt]??wt,me.format===""&&delete me.format,wt==="time"&&delete me.format),pt&&(me.contentEncoding=pt),ht&&ht.size>0){const Tt=[...ht];Tt.length===1?me.pattern=Tt[0].source:Tt.length>1&&(me.allOf=[...Tt.map(Ut=>({...ce.target==="draft-07"||ce.target==="draft-04"||ce.target==="openapi-3.0"?{type:"string"}:{},pattern:Ut.source}))])}};o.stringProcessor=P;const D=(de,ce,Pe,De)=>{const me=Pe,{minimum:je,maximum:Ve,format:wt,multipleOf:ht,exclusiveMaximum:pt,exclusiveMinimum:Tt}=de._zod.bag;typeof wt=="string"&&wt.includes("int")?me.type="integer":me.type="number";const Ut=typeof Tt=="number"&&Tt>=(je??Number.NEGATIVE_INFINITY),Pt=typeof pt=="number"&&pt<=(Ve??Number.POSITIVE_INFINITY),Ot=ce.target==="draft-04"||ce.target==="openapi-3.0";Ut?Ot?(me.minimum=Tt,me.exclusiveMinimum=!0):me.exclusiveMinimum=Tt:typeof je=="number"&&(me.minimum=je),Pt?Ot?(me.maximum=pt,me.exclusiveMaximum=!0):me.exclusiveMaximum=pt:typeof Ve=="number"&&(me.maximum=Ve),typeof ht=="number"&&(me.multipleOf=ht)};o.numberProcessor=D;const V=(de,ce,Pe,De)=>{Pe.type="boolean"};o.booleanProcessor=V;const J=(de,ce,Pe,De)=>{if(ce.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")};o.bigintProcessor=J;const b=(de,ce,Pe,De)=>{if(ce.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")};o.symbolProcessor=b;const v=(de,ce,Pe,De)=>{ce.target==="openapi-3.0"?(Pe.type="string",Pe.nullable=!0,Pe.enum=[null]):Pe.type="null"};o.nullProcessor=v;const x=(de,ce,Pe,De)=>{if(ce.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")};o.undefinedProcessor=x;const w=(de,ce,Pe,De)=>{if(ce.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")};o.voidProcessor=w;const l=(de,ce,Pe,De)=>{Pe.not={}};o.neverProcessor=l;const i=(de,ce,Pe,De)=>{};o.anyProcessor=i;const I=(de,ce,Pe,De)=>{};o.unknownProcessor=I;const Z=(de,ce,Pe,De)=>{if(ce.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")};o.dateProcessor=Z;const ye=(de,ce,Pe,De)=>{const me=de._zod.def,je=(0,R.getEnumValues)(me.entries);je.every(Ve=>typeof Ve=="number")&&(Pe.type="number"),je.every(Ve=>typeof Ve=="string")&&(Pe.type="string"),Pe.enum=je};o.enumProcessor=ye;const ve=(de,ce,Pe,De)=>{const me=de._zod.def,je=[];for(const Ve of me.values)if(Ve===void 0){if(ce.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof Ve=="bigint"){if(ce.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");je.push(Number(Ve))}else je.push(Ve);if(je.length!==0)if(je.length===1){const Ve=je[0];Pe.type=Ve===null?"null":typeof Ve,ce.target==="draft-04"||ce.target==="openapi-3.0"?Pe.enum=[Ve]:Pe.const=Ve}else je.every(Ve=>typeof Ve=="number")&&(Pe.type="number"),je.every(Ve=>typeof Ve=="string")&&(Pe.type="string"),je.every(Ve=>typeof Ve=="boolean")&&(Pe.type="boolean"),je.every(Ve=>Ve===null)&&(Pe.type="null"),Pe.enum=je};o.literalProcessor=ve;const Te=(de,ce,Pe,De)=>{if(ce.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")};o.nanProcessor=Te;const _e=(de,ce,Pe,De)=>{const me=Pe,je=de._zod.pattern;if(!je)throw new Error("Pattern not found in template literal");me.type="string",me.pattern=je.source};o.templateLiteralProcessor=_e;const Oe=(de,ce,Pe,De)=>{const me=Pe,je={type:"string",format:"binary",contentEncoding:"binary"},{minimum:Ve,maximum:wt,mime:ht}=de._zod.bag;Ve!==void 0&&(je.minLength=Ve),wt!==void 0&&(je.maxLength=wt),ht?ht.length===1?(je.contentMediaType=ht[0],Object.assign(me,je)):(Object.assign(me,je),me.anyOf=ht.map(pt=>({contentMediaType:pt}))):Object.assign(me,je)};o.fileProcessor=Oe;const W=(de,ce,Pe,De)=>{Pe.type="boolean"};o.successProcessor=W;const Ze=(de,ce,Pe,De)=>{if(ce.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")};o.customProcessor=Ze;const Le=(de,ce,Pe,De)=>{if(ce.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")};o.functionProcessor=Le;const ot=(de,ce,Pe,De)=>{if(ce.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")};o.transformProcessor=ot;const tt=(de,ce,Pe,De)=>{if(ce.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")};o.mapProcessor=tt;const _t=(de,ce,Pe,De)=>{if(ce.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")};o.setProcessor=_t;const Kt=(de,ce,Pe,De)=>{const me=Pe,je=de._zod.def,{minimum:Ve,maximum:wt}=de._zod.bag;typeof Ve=="number"&&(me.minItems=Ve),typeof wt=="number"&&(me.maxItems=wt),me.type="array",me.items=(0,_.process)(je.element,ce,{...De,path:[...De.path,"items"]})};o.arrayProcessor=Kt;const cr=(de,ce,Pe,De)=>{const me=Pe,je=de._zod.def;me.type="object",me.properties={};const Ve=je.shape;for(const pt in Ve)me.properties[pt]=(0,_.process)(Ve[pt],ce,{...De,path:[...De.path,"properties",pt]});const wt=new Set(Object.keys(Ve)),ht=new Set([...wt].filter(pt=>{const Tt=je.shape[pt]._zod;return ce.io==="input"?Tt.optin===void 0:Tt.optout===void 0}));ht.size>0&&(me.required=Array.from(ht)),je.catchall?._zod.def.type==="never"?me.additionalProperties=!1:je.catchall?je.catchall&&(me.additionalProperties=(0,_.process)(je.catchall,ce,{...De,path:[...De.path,"additionalProperties"]})):ce.io==="output"&&(me.additionalProperties=!1)};o.objectProcessor=cr;const kr=(de,ce,Pe,De)=>{const me=de._zod.def,je=me.inclusive===!1,Ve=me.options.map((wt,ht)=>(0,_.process)(wt,ce,{...De,path:[...De.path,je?"oneOf":"anyOf",ht]}));je?Pe.oneOf=Ve:Pe.anyOf=Ve};o.unionProcessor=kr;const Tr=(de,ce,Pe,De)=>{const me=de._zod.def,je=(0,_.process)(me.left,ce,{...De,path:[...De.path,"allOf",0]}),Ve=(0,_.process)(me.right,ce,{...De,path:[...De.path,"allOf",1]}),wt=pt=>"allOf"in pt&&Object.keys(pt).length===1,ht=[...wt(je)?je.allOf:[je],...wt(Ve)?Ve.allOf:[Ve]];Pe.allOf=ht};o.intersectionProcessor=Tr;const Ir=(de,ce,Pe,De)=>{const me=Pe,je=de._zod.def;me.type="array";const Ve=ce.target==="draft-2020-12"?"prefixItems":"items",wt=ce.target==="draft-2020-12"||ce.target==="openapi-3.0"?"items":"additionalItems",ht=je.items.map((Pt,Ot)=>(0,_.process)(Pt,ce,{...De,path:[...De.path,Ve,Ot]})),pt=je.rest?(0,_.process)(je.rest,ce,{...De,path:[...De.path,wt,...ce.target==="openapi-3.0"?[je.items.length]:[]]}):null;ce.target==="draft-2020-12"?(me.prefixItems=ht,pt&&(me.items=pt)):ce.target==="openapi-3.0"?(me.items={anyOf:ht},pt&&me.items.anyOf.push(pt),me.minItems=ht.length,pt||(me.maxItems=ht.length)):(me.items=ht,pt&&(me.additionalItems=pt));const{minimum:Tt,maximum:Ut}=de._zod.bag;typeof Tt=="number"&&(me.minItems=Tt),typeof Ut=="number"&&(me.maxItems=Ut)};o.tupleProcessor=Ir;const Dr=(de,ce,Pe,De)=>{const me=Pe,je=de._zod.def;me.type="object";const Ve=je.keyType,ht=Ve._zod.bag?.patterns;if(je.mode==="loose"&&ht&&ht.size>0){const Tt=(0,_.process)(je.valueType,ce,{...De,path:[...De.path,"patternProperties","*"]});me.patternProperties={};for(const Ut of ht)me.patternProperties[Ut.source]=Tt}else(ce.target==="draft-07"||ce.target==="draft-2020-12")&&(me.propertyNames=(0,_.process)(je.keyType,ce,{...De,path:[...De.path,"propertyNames"]})),me.additionalProperties=(0,_.process)(je.valueType,ce,{...De,path:[...De.path,"additionalProperties"]});const pt=Ve._zod.values;if(pt){const Tt=[...pt].filter(Ut=>typeof Ut=="string"||typeof Ut=="number");Tt.length>0&&(me.required=Tt)}};o.recordProcessor=Dr;const Qt=(de,ce,Pe,De)=>{const me=de._zod.def,je=(0,_.process)(me.innerType,ce,De),Ve=ce.seen.get(de);ce.target==="openapi-3.0"?(Ve.ref=me.innerType,Pe.nullable=!0):Pe.anyOf=[je,{type:"null"}]};o.nullableProcessor=Qt;const Or=(de,ce,Pe,De)=>{const me=de._zod.def;(0,_.process)(me.innerType,ce,De);const je=ce.seen.get(de);je.ref=me.innerType};o.nonoptionalProcessor=Or;const bn=(de,ce,Pe,De)=>{const me=de._zod.def;(0,_.process)(me.innerType,ce,De);const je=ce.seen.get(de);je.ref=me.innerType,Pe.default=JSON.parse(JSON.stringify(me.defaultValue))};o.defaultProcessor=bn;const M=(de,ce,Pe,De)=>{const me=de._zod.def;(0,_.process)(me.innerType,ce,De);const je=ce.seen.get(de);je.ref=me.innerType,ce.io==="input"&&(Pe._prefault=JSON.parse(JSON.stringify(me.defaultValue)))};o.prefaultProcessor=M;const L=(de,ce,Pe,De)=>{const me=de._zod.def;(0,_.process)(me.innerType,ce,De);const je=ce.seen.get(de);je.ref=me.innerType;let Ve;try{Ve=me.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}Pe.default=Ve};o.catchProcessor=L;const B=(de,ce,Pe,De)=>{const me=de._zod.def,je=me.in._zod.traits.has("$ZodTransform"),Ve=ce.io==="input"?je?me.out:me.in:me.out;(0,_.process)(Ve,ce,De);const wt=ce.seen.get(de);wt.ref=Ve};o.pipeProcessor=B;const Y=(de,ce,Pe,De)=>{const me=de._zod.def;(0,_.process)(me.innerType,ce,De);const je=ce.seen.get(de);je.ref=me.innerType,Pe.readOnly=!0};o.readonlyProcessor=Y;const re=(de,ce,Pe,De)=>{const me=de._zod.def;(0,_.process)(me.innerType,ce,De);const je=ce.seen.get(de);je.ref=me.innerType};o.promiseProcessor=re;const ue=(de,ce,Pe,De)=>{const me=de._zod.def;(0,_.process)(me.innerType,ce,De);const je=ce.seen.get(de);je.ref=me.innerType};o.optionalProcessor=ue;const ke=(de,ce,Pe,De)=>{const me=de._zod.innerType;(0,_.process)(me,ce,De);const je=ce.seen.get(de);je.ref=me};o.lazyProcessor=ke,o.allProcessors={string:o.stringProcessor,number:o.numberProcessor,boolean:o.booleanProcessor,bigint:o.bigintProcessor,symbol:o.symbolProcessor,null:o.nullProcessor,undefined:o.undefinedProcessor,void:o.voidProcessor,never:o.neverProcessor,any:o.anyProcessor,unknown:o.unknownProcessor,date:o.dateProcessor,enum:o.enumProcessor,literal:o.literalProcessor,nan:o.nanProcessor,template_literal:o.templateLiteralProcessor,file:o.fileProcessor,success:o.successProcessor,custom:o.customProcessor,function:o.functionProcessor,transform:o.transformProcessor,map:o.mapProcessor,set:o.setProcessor,array:o.arrayProcessor,object:o.objectProcessor,union:o.unionProcessor,intersection:o.intersectionProcessor,tuple:o.tupleProcessor,record:o.recordProcessor,nullable:o.nullableProcessor,nonoptional:o.nonoptionalProcessor,default:o.defaultProcessor,prefault:o.prefaultProcessor,catch:o.catchProcessor,pipe:o.pipeProcessor,readonly:o.readonlyProcessor,promise:o.promiseProcessor,optional:o.optionalProcessor,lazy:o.lazyProcessor};function Me(de,ce){if("_idmap"in de){const De=de,me=(0,_.initializeContext)({...ce,processors:o.allProcessors}),je={};for(const ht of De._idmap.entries()){const[pt,Tt]=ht;(0,_.process)(Tt,me)}const Ve={},wt={registry:De,uri:ce?.uri,defs:je};me.external=wt;for(const ht of De._idmap.entries()){const[pt,Tt]=ht;(0,_.extractDefs)(me,Tt),Ve[pt]=(0,_.finalize)(me,Tt)}if(Object.keys(je).length>0){const ht=me.target==="draft-2020-12"?"$defs":"definitions";Ve.__shared={[ht]:je}}return{schemas:Ve}}const Pe=(0,_.initializeContext)({...ce,processors:o.allProcessors});return(0,_.process)(de,Pe),(0,_.extractDefs)(Pe,de),(0,_.finalize)(Pe,de)}})(Ko);var ed={};Object.defineProperty(ed,"__esModule",{value:!0});ed.JSONSchemaGenerator=void 0;const oY=Ko,Kc=Ho;class lY{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(_){this.ctx.counter=_}get seen(){return this.ctx.seen}constructor(_){let R=_?.target??"draft-2020-12";R==="draft-4"&&(R="draft-04"),R==="draft-7"&&(R="draft-07"),this.ctx=(0,Kc.initializeContext)({processors:oY.allProcessors,target:R,..._?.metadata&&{metadata:_.metadata},..._?.unrepresentable&&{unrepresentable:_.unrepresentable},..._?.override&&{override:_.override},..._?.io&&{io:_.io}})}process(_,R={path:[],schemaPath:[]}){return(0,Kc.process)(_,this.ctx,R)}emit(_,R){R&&(R.cycles&&(this.ctx.cycles=R.cycles),R.reused&&(this.ctx.reused=R.reused),R.external&&(this.ctx.external=R.external)),(0,Kc.extractDefs)(this.ctx,_);const F=(0,Kc.finalize)(this.ctx,_),{"~standard":P,...D}=F;return D}}ed.JSONSchemaGenerator=lY;var Ow={};Object.defineProperty(Ow,"__esModule",{value:!0});(function(o){var _=sr&&sr.__createBinding||(Object.create?(function(J,b,v,x){x===void 0&&(x=v);var w=Object.getOwnPropertyDescriptor(b,v);(!w||("get"in w?!b.__esModule:w.writable||w.configurable))&&(w={enumerable:!0,get:function(){return b[v]}}),Object.defineProperty(J,x,w)}):(function(J,b,v,x){x===void 0&&(x=v),J[x]=b[v]})),R=sr&&sr.__setModuleDefault||(Object.create?(function(J,b){Object.defineProperty(J,"default",{enumerable:!0,value:b})}):function(J,b){J.default=b}),F=sr&&sr.__exportStar||function(J,b){for(var v in J)v!=="default"&&!Object.prototype.hasOwnProperty.call(b,v)&&_(b,J,v)},P=sr&&sr.__importStar||function(J){if(J&&J.__esModule)return J;var b={};if(J!=null)for(var v in J)v!=="default"&&Object.prototype.hasOwnProperty.call(J,v)&&_(b,J,v);return R(b,J),b};Object.defineProperty(o,"__esModule",{value:!0}),o.JSONSchema=o.JSONSchemaGenerator=o.toJSONSchema=o.locales=o.regexes=o.util=void 0,F(Ki,o),F(Yn,o),F(yr,o),F(Xn,o),F(Mn,o),F(Go,o),o.util=P(Ie),o.regexes=P($n),o.locales=P(Bo),F(Lr,o),F(zo,o),F(Ae,o),F(Ho,o);var D=Ko;Object.defineProperty(o,"toJSONSchema",{enumerable:!0,get:function(){return D.toJSONSchema}});var V=ed;Object.defineProperty(o,"JSONSchemaGenerator",{enumerable:!0,get:function(){return V.JSONSchemaGenerator}}),o.JSONSchema=P(Ow)})(sr);var qn={},td={};(function(o){Object.defineProperty(o,"__esModule",{value:!0}),o.slugify=o.toUpperCase=o.toLowerCase=o.trim=o.normalize=o.overwrite=o.mime=o.property=o.endsWith=o.startsWith=o.includes=o.uppercase=o.lowercase=o.regex=o.length=o.minLength=o.maxLength=o.size=o.minSize=o.maxSize=o.multipleOf=o.nonnegative=o.nonpositive=o.negative=o.positive=o.gte=o.gt=o.lte=o.lt=void 0;var _=sr;Object.defineProperty(o,"lt",{enumerable:!0,get:function(){return _._lt}}),Object.defineProperty(o,"lte",{enumerable:!0,get:function(){return _._lte}}),Object.defineProperty(o,"gt",{enumerable:!0,get:function(){return _._gt}}),Object.defineProperty(o,"gte",{enumerable:!0,get:function(){return _._gte}}),Object.defineProperty(o,"positive",{enumerable:!0,get:function(){return _._positive}}),Object.defineProperty(o,"negative",{enumerable:!0,get:function(){return _._negative}}),Object.defineProperty(o,"nonpositive",{enumerable:!0,get:function(){return _._nonpositive}}),Object.defineProperty(o,"nonnegative",{enumerable:!0,get:function(){return _._nonnegative}}),Object.defineProperty(o,"multipleOf",{enumerable:!0,get:function(){return _._multipleOf}}),Object.defineProperty(o,"maxSize",{enumerable:!0,get:function(){return _._maxSize}}),Object.defineProperty(o,"minSize",{enumerable:!0,get:function(){return _._minSize}}),Object.defineProperty(o,"size",{enumerable:!0,get:function(){return _._size}}),Object.defineProperty(o,"maxLength",{enumerable:!0,get:function(){return _._maxLength}}),Object.defineProperty(o,"minLength",{enumerable:!0,get:function(){return _._minLength}}),Object.defineProperty(o,"length",{enumerable:!0,get:function(){return _._length}}),Object.defineProperty(o,"regex",{enumerable:!0,get:function(){return _._regex}}),Object.defineProperty(o,"lowercase",{enumerable:!0,get:function(){return _._lowercase}}),Object.defineProperty(o,"uppercase",{enumerable:!0,get:function(){return _._uppercase}}),Object.defineProperty(o,"includes",{enumerable:!0,get:function(){return _._includes}}),Object.defineProperty(o,"startsWith",{enumerable:!0,get:function(){return _._startsWith}}),Object.defineProperty(o,"endsWith",{enumerable:!0,get:function(){return _._endsWith}}),Object.defineProperty(o,"property",{enumerable:!0,get:function(){return _._property}}),Object.defineProperty(o,"mime",{enumerable:!0,get:function(){return _._mime}}),Object.defineProperty(o,"overwrite",{enumerable:!0,get:function(){return _._overwrite}}),Object.defineProperty(o,"normalize",{enumerable:!0,get:function(){return _._normalize}}),Object.defineProperty(o,"trim",{enumerable:!0,get:function(){return _._trim}}),Object.defineProperty(o,"toLowerCase",{enumerable:!0,get:function(){return _._toLowerCase}}),Object.defineProperty(o,"toUpperCase",{enumerable:!0,get:function(){return _._toUpperCase}}),Object.defineProperty(o,"slugify",{enumerable:!0,get:function(){return _._slugify}})})(td);var Qn={},vw;function Qu(){return vw||(vw=1,(function(o){var _=Qn&&Qn.__createBinding||(Object.create?(function(x,w,l,i){i===void 0&&(i=l);var I=Object.getOwnPropertyDescriptor(w,l);(!I||("get"in I?!w.__esModule:I.writable||I.configurable))&&(I={enumerable:!0,get:function(){return w[l]}}),Object.defineProperty(x,i,I)}):(function(x,w,l,i){i===void 0&&(i=l),x[i]=w[l]})),R=Qn&&Qn.__setModuleDefault||(Object.create?(function(x,w){Object.defineProperty(x,"default",{enumerable:!0,value:w})}):function(x,w){x.default=w}),F=Qn&&Qn.__importStar||function(x){if(x&&x.__esModule)return x;var w={};if(x!=null)for(var l in x)l!=="default"&&Object.prototype.hasOwnProperty.call(x,l)&&_(w,x,l);return R(w,x),w};Object.defineProperty(o,"__esModule",{value:!0}),o.ZodISODuration=o.ZodISOTime=o.ZodISODate=o.ZodISODateTime=void 0,o.datetime=V,o.date=J,o.time=b,o.duration=v;const P=F(sr),D=F(rd());o.ZodISODateTime=P.$constructor("ZodISODateTime",(x,w)=>{P.$ZodISODateTime.init(x,w),D.ZodStringFormat.init(x,w)});function V(x){return P._isoDateTime(o.ZodISODateTime,x)}o.ZodISODate=P.$constructor("ZodISODate",(x,w)=>{P.$ZodISODate.init(x,w),D.ZodStringFormat.init(x,w)});function J(x){return P._isoDate(o.ZodISODate,x)}o.ZodISOTime=P.$constructor("ZodISOTime",(x,w)=>{P.$ZodISOTime.init(x,w),D.ZodStringFormat.init(x,w)});function b(x){return P._isoTime(o.ZodISOTime,x)}o.ZodISODuration=P.$constructor("ZodISODuration",(x,w)=>{P.$ZodISODuration.init(x,w),D.ZodStringFormat.init(x,w)});function v(x){return P._isoDuration(o.ZodISODuration,x)}})(Qn)),Qn}var Nt={},qr={},cY=qr&&qr.__createBinding||(Object.create?(function(o,_,R,F){F===void 0&&(F=R);var P=Object.getOwnPropertyDescriptor(_,R);(!P||("get"in P?!_.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return _[R]}}),Object.defineProperty(o,F,P)}):(function(o,_,R,F){F===void 0&&(F=R),o[F]=_[R]})),uY=qr&&qr.__setModuleDefault||(Object.create?(function(o,_){Object.defineProperty(o,"default",{enumerable:!0,value:_})}):function(o,_){o.default=_}),Fw=qr&&qr.__importStar||function(o){if(o&&o.__esModule)return o;var _={};if(o!=null)for(var R in o)R!=="default"&&Object.prototype.hasOwnProperty.call(o,R)&&cY(_,o,R);return uY(_,o),_};Object.defineProperty(qr,"__esModule",{value:!0});qr.ZodRealError=qr.ZodError=void 0;const Yu=Fw(sr),dY=sr,bw=Fw(Ie),Uw=(o,_)=>{dY.$ZodError.init(o,_),o.name="ZodError",Object.defineProperties(o,{format:{value:R=>Yu.formatError(o,R)},flatten:{value:R=>Yu.flattenError(o,R)},addIssue:{value:R=>{o.issues.push(R),o.message=JSON.stringify(o.issues,bw.jsonStringifyReplacer,2)}},addIssues:{value:R=>{o.issues.push(...R),o.message=JSON.stringify(o.issues,bw.jsonStringifyReplacer,2)}},isEmpty:{get(){return o.issues.length===0}}})};qr.ZodError=Yu.$constructor("ZodError",Uw);qr.ZodRealError=Yu.$constructor("ZodError",Uw,{Parent:Error});var fY=Nt&&Nt.__createBinding||(Object.create?(function(o,_,R,F){F===void 0&&(F=R);var P=Object.getOwnPropertyDescriptor(_,R);(!P||("get"in P?!_.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return _[R]}}),Object.defineProperty(o,F,P)}):(function(o,_,R,F){F===void 0&&(F=R),o[F]=_[R]})),hY=Nt&&Nt.__setModuleDefault||(Object.create?(function(o,_){Object.defineProperty(o,"default",{enumerable:!0,value:_})}):function(o,_){o.default=_}),mY=Nt&&Nt.__importStar||function(o){if(o&&o.__esModule)return o;var _={};if(o!=null)for(var R in o)R!=="default"&&Object.prototype.hasOwnProperty.call(o,R)&&fY(_,o,R);return hY(_,o),_};Object.defineProperty(Nt,"__esModule",{value:!0});Nt.safeDecodeAsync=Nt.safeEncodeAsync=Nt.safeDecode=Nt.safeEncode=Nt.decodeAsync=Nt.encodeAsync=Nt.decode=Nt.encode=Nt.safeParseAsync=Nt.safeParse=Nt.parseAsync=Nt.parse=void 0;const an=mY(sr),on=qr;Nt.parse=an._parse(on.ZodRealError);Nt.parseAsync=an._parseAsync(on.ZodRealError);Nt.safeParse=an._safeParse(on.ZodRealError);Nt.safeParseAsync=an._safeParseAsync(on.ZodRealError);Nt.encode=an._encode(on.ZodRealError);Nt.decode=an._decode(on.ZodRealError);Nt.encodeAsync=an._encodeAsync(on.ZodRealError);Nt.decodeAsync=an._decodeAsync(on.ZodRealError);Nt.safeEncode=an._safeEncode(on.ZodRealError);Nt.safeDecode=an._safeDecode(on.ZodRealError);Nt.safeEncodeAsync=an._safeEncodeAsync(on.ZodRealError);Nt.safeDecodeAsync=an._safeDecodeAsync(on.ZodRealError);var yw;function rd(){return yw||(yw=1,(function(o){var _=qn&&qn.__createBinding||(Object.create?(function(k,A,H,ee){ee===void 0&&(ee=H);var xe=Object.getOwnPropertyDescriptor(A,H);(!xe||("get"in xe?!A.__esModule:xe.writable||xe.configurable))&&(xe={enumerable:!0,get:function(){return A[H]}}),Object.defineProperty(k,ee,xe)}):(function(k,A,H,ee){ee===void 0&&(ee=H),k[ee]=A[H]})),R=qn&&qn.__setModuleDefault||(Object.create?(function(k,A){Object.defineProperty(k,"default",{enumerable:!0,value:A})}):function(k,A){k.default=A}),F=qn&&qn.__importStar||function(k){if(k&&k.__esModule)return k;var A={};if(k!=null)for(var H in k)H!=="default"&&Object.prototype.hasOwnProperty.call(k,H)&&_(A,k,H);return R(A,k),A};Object.defineProperty(o,"__esModule",{value:!0}),o.ZodLiteral=o.ZodEnum=o.ZodSet=o.ZodMap=o.ZodRecord=o.ZodTuple=o.ZodIntersection=o.ZodDiscriminatedUnion=o.ZodXor=o.ZodUnion=o.ZodObject=o.ZodArray=o.ZodDate=o.ZodVoid=o.ZodNever=o.ZodUnknown=o.ZodAny=o.ZodNull=o.ZodUndefined=o.ZodSymbol=o.ZodBigIntFormat=o.ZodBigInt=o.ZodBoolean=o.ZodNumberFormat=o.ZodNumber=o.ZodCustomStringFormat=o.ZodJWT=o.ZodE164=o.ZodBase64URL=o.ZodBase64=o.ZodCIDRv6=o.ZodCIDRv4=o.ZodIPv6=o.ZodMAC=o.ZodIPv4=o.ZodKSUID=o.ZodXID=o.ZodULID=o.ZodCUID2=o.ZodCUID=o.ZodNanoID=o.ZodEmoji=o.ZodURL=o.ZodUUID=o.ZodGUID=o.ZodEmail=o.ZodStringFormat=o.ZodString=o._ZodString=o.ZodType=void 0,o.stringbool=o.meta=o.describe=o.ZodCustom=o.ZodFunction=o.ZodPromise=o.ZodLazy=o.ZodTemplateLiteral=o.ZodReadonly=o.ZodPreprocess=o.ZodCodec=o.ZodPipe=o.ZodNaN=o.ZodCatch=o.ZodSuccess=o.ZodNonOptional=o.ZodPrefault=o.ZodDefault=o.ZodNullable=o.ZodExactOptional=o.ZodOptional=o.ZodTransform=o.ZodFile=void 0,o.string=i,o.email=I,o.guid=Z,o.uuid=ye,o.uuidv4=ve,o.uuidv6=Te,o.uuidv7=_e,o.url=Oe,o.httpUrl=W,o.emoji=Ze,o.nanoid=Le,o.cuid=ot,o.cuid2=tt,o.ulid=_t,o.xid=Kt,o.ksuid=cr,o.ipv4=kr,o.mac=Tr,o.ipv6=Ir,o.cidrv4=Dr,o.cidrv6=Qt,o.base64=Or,o.base64url=bn,o.e164=M,o.jwt=L,o.stringFormat=B,o.hostname=Y,o.hex=re,o.hash=ue,o.number=ke,o.int=Me,o.float32=de,o.float64=ce,o.int32=Pe,o.uint32=De,o.boolean=me,o.bigint=je,o.int64=Ve,o.uint64=wt,o.symbol=ht,o.undefined=pt,o.null=Tt,o.any=Ut,o.unknown=Pt,o.never=Ot,o.void=Wt,o.date=xi,o.array=Rn,o.keyof=nd,o.object=id,o.strictObject=sd,o.looseObject=ad,o.union=Ra,o.xor=od,o.discriminatedUnion=yn,o.intersection=vt,o.tuple=ln,o.record=Wi,o.partialRecord=cn,o.looseRecord=Qo,o.map=ld,o.set=La,o.enum=Oa,o.nativeEnum=cd,o.literal=ud,o.file=dd,o.transform=Xe,o.optional=Yr,o.exactOptional=Fa,o.nullable=qi,o.nullish=fd,o._default=Ua,o.prefault=Yo,o.nonoptional=Si,o.success=et,o.catch=ti,o.nan=hd,o.pipe=Qi,o.codec=md,o.invertCodec=gd,o.readonly=_i,o.templateLiteral=pd,o.lazy=un,o.promise=Ln,o._function=wi,o.function=wi,o._function=wi,o.function=wi,o.check=Xo,o.custom=Jo,o.refine=Ba,o.superRefine=el,o.instanceof=tl,o.json=nl,o.preprocess=vd;const P=F(sr),D=sr,V=F(Ko),J=Ho,b=F(td),v=F(Qu()),x=F(Nt),w=new WeakMap;function l(k,A,H){const ee=Object.getPrototypeOf(k);let xe=w.get(ee);if(xe||(xe=new Set,w.set(ee,xe)),!xe.has(A)){xe.add(A);for(const Dt in H){const Jt=H[Dt];Object.defineProperty(ee,Dt,{configurable:!0,enumerable:!1,get(){const ri=Jt.bind(this);return Object.defineProperty(this,Dt,{configurable:!0,writable:!0,enumerable:!0,value:ri}),ri},set(ri){Object.defineProperty(this,Dt,{configurable:!0,writable:!0,enumerable:!0,value:ri})}})}}}o.ZodType=P.$constructor("ZodType",(k,A)=>(P.$ZodType.init(k,A),Object.assign(k["~standard"],{jsonSchema:{input:(0,J.createStandardJSONSchemaMethod)(k,"input"),output:(0,J.createStandardJSONSchemaMethod)(k,"output")}}),k.toJSONSchema=(0,J.createToJSONSchemaMethod)(k,{}),k.def=A,k.type=A.type,Object.defineProperty(k,"_def",{value:A}),k.parse=(H,ee)=>x.parse(k,H,ee,{callee:k.parse}),k.safeParse=(H,ee)=>x.safeParse(k,H,ee),k.parseAsync=async(H,ee)=>x.parseAsync(k,H,ee,{callee:k.parseAsync}),k.safeParseAsync=async(H,ee)=>x.safeParseAsync(k,H,ee),k.spa=k.safeParseAsync,k.encode=(H,ee)=>x.encode(k,H,ee),k.decode=(H,ee)=>x.decode(k,H,ee),k.encodeAsync=async(H,ee)=>x.encodeAsync(k,H,ee),k.decodeAsync=async(H,ee)=>x.decodeAsync(k,H,ee),k.safeEncode=(H,ee)=>x.safeEncode(k,H,ee),k.safeDecode=(H,ee)=>x.safeDecode(k,H,ee),k.safeEncodeAsync=async(H,ee)=>x.safeEncodeAsync(k,H,ee),k.safeDecodeAsync=async(H,ee)=>x.safeDecodeAsync(k,H,ee),l(k,"ZodType",{check(...H){const ee=this.def;return this.clone(D.util.mergeDefs(ee,{checks:[...ee.checks??[],...H.map(xe=>typeof xe=="function"?{_zod:{check:xe,def:{check:"custom"},onattach:[]}}:xe)]}),{parent:!0})},with(...H){return this.check(...H)},clone(H,ee){return P.clone(this,H,ee)},brand(){return this},register(H,ee){return H.add(this,ee),this},refine(H,ee){return this.check(Ba(H,ee))},superRefine(H,ee){return this.check(el(H,ee))},overwrite(H){return this.check(b.overwrite(H))},optional(){return Yr(this)},exactOptional(){return Fa(this)},nullable(){return qi(this)},nullish(){return Yr(qi(this))},nonoptional(H){return Si(this,H)},array(){return Rn(this)},or(H){return Ra([this,H])},and(H){return vt(this,H)},transform(H){return Qi(this,Xe(H))},default(H){return Ua(this,H)},prefault(H){return Yo(this,H)},catch(H){return ti(this,H)},pipe(H){return Qi(this,H)},readonly(){return _i(this)},describe(H){const ee=this.clone();return P.globalRegistry.add(ee,{description:H}),ee},meta(...H){if(H.length===0)return P.globalRegistry.get(this);const ee=this.clone();return P.globalRegistry.add(ee,H[0]),ee},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(H){return H(this)}}),Object.defineProperty(k,"description",{get(){return P.globalRegistry.get(k)?.description},configurable:!0}),k)),o._ZodString=P.$constructor("_ZodString",(k,A)=>{P.$ZodString.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(ee,xe,Dt)=>V.stringProcessor(k,ee,xe,Dt);const H=k._zod.bag;k.format=H.format??null,k.minLength=H.minimum??null,k.maxLength=H.maximum??null,l(k,"_ZodString",{regex(...ee){return this.check(b.regex(...ee))},includes(...ee){return this.check(b.includes(...ee))},startsWith(...ee){return this.check(b.startsWith(...ee))},endsWith(...ee){return this.check(b.endsWith(...ee))},min(...ee){return this.check(b.minLength(...ee))},max(...ee){return this.check(b.maxLength(...ee))},length(...ee){return this.check(b.length(...ee))},nonempty(...ee){return this.check(b.minLength(1,...ee))},lowercase(ee){return this.check(b.lowercase(ee))},uppercase(ee){return this.check(b.uppercase(ee))},trim(){return this.check(b.trim())},normalize(...ee){return this.check(b.normalize(...ee))},toLowerCase(){return this.check(b.toLowerCase())},toUpperCase(){return this.check(b.toUpperCase())},slugify(){return this.check(b.slugify())}})}),o.ZodString=P.$constructor("ZodString",(k,A)=>{P.$ZodString.init(k,A),o._ZodString.init(k,A),k.email=H=>k.check(P._email(o.ZodEmail,H)),k.url=H=>k.check(P._url(o.ZodURL,H)),k.jwt=H=>k.check(P._jwt(o.ZodJWT,H)),k.emoji=H=>k.check(P._emoji(o.ZodEmoji,H)),k.guid=H=>k.check(P._guid(o.ZodGUID,H)),k.uuid=H=>k.check(P._uuid(o.ZodUUID,H)),k.uuidv4=H=>k.check(P._uuidv4(o.ZodUUID,H)),k.uuidv6=H=>k.check(P._uuidv6(o.ZodUUID,H)),k.uuidv7=H=>k.check(P._uuidv7(o.ZodUUID,H)),k.nanoid=H=>k.check(P._nanoid(o.ZodNanoID,H)),k.guid=H=>k.check(P._guid(o.ZodGUID,H)),k.cuid=H=>k.check(P._cuid(o.ZodCUID,H)),k.cuid2=H=>k.check(P._cuid2(o.ZodCUID2,H)),k.ulid=H=>k.check(P._ulid(o.ZodULID,H)),k.base64=H=>k.check(P._base64(o.ZodBase64,H)),k.base64url=H=>k.check(P._base64url(o.ZodBase64URL,H)),k.xid=H=>k.check(P._xid(o.ZodXID,H)),k.ksuid=H=>k.check(P._ksuid(o.ZodKSUID,H)),k.ipv4=H=>k.check(P._ipv4(o.ZodIPv4,H)),k.ipv6=H=>k.check(P._ipv6(o.ZodIPv6,H)),k.cidrv4=H=>k.check(P._cidrv4(o.ZodCIDRv4,H)),k.cidrv6=H=>k.check(P._cidrv6(o.ZodCIDRv6,H)),k.e164=H=>k.check(P._e164(o.ZodE164,H)),k.datetime=H=>k.check(v.datetime(H)),k.date=H=>k.check(v.date(H)),k.time=H=>k.check(v.time(H)),k.duration=H=>k.check(v.duration(H))});function i(k){return P._string(o.ZodString,k)}o.ZodStringFormat=P.$constructor("ZodStringFormat",(k,A)=>{P.$ZodStringFormat.init(k,A),o._ZodString.init(k,A)}),o.ZodEmail=P.$constructor("ZodEmail",(k,A)=>{P.$ZodEmail.init(k,A),o.ZodStringFormat.init(k,A)});function I(k){return P._email(o.ZodEmail,k)}o.ZodGUID=P.$constructor("ZodGUID",(k,A)=>{P.$ZodGUID.init(k,A),o.ZodStringFormat.init(k,A)});function Z(k){return P._guid(o.ZodGUID,k)}o.ZodUUID=P.$constructor("ZodUUID",(k,A)=>{P.$ZodUUID.init(k,A),o.ZodStringFormat.init(k,A)});function ye(k){return P._uuid(o.ZodUUID,k)}function ve(k){return P._uuidv4(o.ZodUUID,k)}function Te(k){return P._uuidv6(o.ZodUUID,k)}function _e(k){return P._uuidv7(o.ZodUUID,k)}o.ZodURL=P.$constructor("ZodURL",(k,A)=>{P.$ZodURL.init(k,A),o.ZodStringFormat.init(k,A)});function Oe(k){return P._url(o.ZodURL,k)}function W(k){return P._url(o.ZodURL,{protocol:P.regexes.httpProtocol,hostname:P.regexes.domain,...D.util.normalizeParams(k)})}o.ZodEmoji=P.$constructor("ZodEmoji",(k,A)=>{P.$ZodEmoji.init(k,A),o.ZodStringFormat.init(k,A)});function Ze(k){return P._emoji(o.ZodEmoji,k)}o.ZodNanoID=P.$constructor("ZodNanoID",(k,A)=>{P.$ZodNanoID.init(k,A),o.ZodStringFormat.init(k,A)});function Le(k){return P._nanoid(o.ZodNanoID,k)}o.ZodCUID=P.$constructor("ZodCUID",(k,A)=>{P.$ZodCUID.init(k,A),o.ZodStringFormat.init(k,A)});function ot(k){return P._cuid(o.ZodCUID,k)}o.ZodCUID2=P.$constructor("ZodCUID2",(k,A)=>{P.$ZodCUID2.init(k,A),o.ZodStringFormat.init(k,A)});function tt(k){return P._cuid2(o.ZodCUID2,k)}o.ZodULID=P.$constructor("ZodULID",(k,A)=>{P.$ZodULID.init(k,A),o.ZodStringFormat.init(k,A)});function _t(k){return P._ulid(o.ZodULID,k)}o.ZodXID=P.$constructor("ZodXID",(k,A)=>{P.$ZodXID.init(k,A),o.ZodStringFormat.init(k,A)});function Kt(k){return P._xid(o.ZodXID,k)}o.ZodKSUID=P.$constructor("ZodKSUID",(k,A)=>{P.$ZodKSUID.init(k,A),o.ZodStringFormat.init(k,A)});function cr(k){return P._ksuid(o.ZodKSUID,k)}o.ZodIPv4=P.$constructor("ZodIPv4",(k,A)=>{P.$ZodIPv4.init(k,A),o.ZodStringFormat.init(k,A)});function kr(k){return P._ipv4(o.ZodIPv4,k)}o.ZodMAC=P.$constructor("ZodMAC",(k,A)=>{P.$ZodMAC.init(k,A),o.ZodStringFormat.init(k,A)});function Tr(k){return P._mac(o.ZodMAC,k)}o.ZodIPv6=P.$constructor("ZodIPv6",(k,A)=>{P.$ZodIPv6.init(k,A),o.ZodStringFormat.init(k,A)});function Ir(k){return P._ipv6(o.ZodIPv6,k)}o.ZodCIDRv4=P.$constructor("ZodCIDRv4",(k,A)=>{P.$ZodCIDRv4.init(k,A),o.ZodStringFormat.init(k,A)});function Dr(k){return P._cidrv4(o.ZodCIDRv4,k)}o.ZodCIDRv6=P.$constructor("ZodCIDRv6",(k,A)=>{P.$ZodCIDRv6.init(k,A),o.ZodStringFormat.init(k,A)});function Qt(k){return P._cidrv6(o.ZodCIDRv6,k)}o.ZodBase64=P.$constructor("ZodBase64",(k,A)=>{P.$ZodBase64.init(k,A),o.ZodStringFormat.init(k,A)});function Or(k){return P._base64(o.ZodBase64,k)}o.ZodBase64URL=P.$constructor("ZodBase64URL",(k,A)=>{P.$ZodBase64URL.init(k,A),o.ZodStringFormat.init(k,A)});function bn(k){return P._base64url(o.ZodBase64URL,k)}o.ZodE164=P.$constructor("ZodE164",(k,A)=>{P.$ZodE164.init(k,A),o.ZodStringFormat.init(k,A)});function M(k){return P._e164(o.ZodE164,k)}o.ZodJWT=P.$constructor("ZodJWT",(k,A)=>{P.$ZodJWT.init(k,A),o.ZodStringFormat.init(k,A)});function L(k){return P._jwt(o.ZodJWT,k)}o.ZodCustomStringFormat=P.$constructor("ZodCustomStringFormat",(k,A)=>{P.$ZodCustomStringFormat.init(k,A),o.ZodStringFormat.init(k,A)});function B(k,A,H={}){return P._stringFormat(o.ZodCustomStringFormat,k,A,H)}function Y(k){return P._stringFormat(o.ZodCustomStringFormat,"hostname",P.regexes.hostname,k)}function re(k){return P._stringFormat(o.ZodCustomStringFormat,"hex",P.regexes.hex,k)}function ue(k,A){const H=A?.enc??"hex",ee=`${k}_${H}`,xe=P.regexes[ee];if(!xe)throw new Error(`Unrecognized hash format: ${ee}`);return P._stringFormat(o.ZodCustomStringFormat,ee,xe,A)}o.ZodNumber=P.$constructor("ZodNumber",(k,A)=>{P.$ZodNumber.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(ee,xe,Dt)=>V.numberProcessor(k,ee,xe,Dt),l(k,"ZodNumber",{gt(ee,xe){return this.check(b.gt(ee,xe))},gte(ee,xe){return this.check(b.gte(ee,xe))},min(ee,xe){return this.check(b.gte(ee,xe))},lt(ee,xe){return this.check(b.lt(ee,xe))},lte(ee,xe){return this.check(b.lte(ee,xe))},max(ee,xe){return this.check(b.lte(ee,xe))},int(ee){return this.check(Me(ee))},safe(ee){return this.check(Me(ee))},positive(ee){return this.check(b.gt(0,ee))},nonnegative(ee){return this.check(b.gte(0,ee))},negative(ee){return this.check(b.lt(0,ee))},nonpositive(ee){return this.check(b.lte(0,ee))},multipleOf(ee,xe){return this.check(b.multipleOf(ee,xe))},step(ee,xe){return this.check(b.multipleOf(ee,xe))},finite(){return this}});const H=k._zod.bag;k.minValue=Math.max(H.minimum??Number.NEGATIVE_INFINITY,H.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,k.maxValue=Math.min(H.maximum??Number.POSITIVE_INFINITY,H.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,k.isInt=(H.format??"").includes("int")||Number.isSafeInteger(H.multipleOf??.5),k.isFinite=!0,k.format=H.format??null});function ke(k){return P._number(o.ZodNumber,k)}o.ZodNumberFormat=P.$constructor("ZodNumberFormat",(k,A)=>{P.$ZodNumberFormat.init(k,A),o.ZodNumber.init(k,A)});function Me(k){return P._int(o.ZodNumberFormat,k)}function de(k){return P._float32(o.ZodNumberFormat,k)}function ce(k){return P._float64(o.ZodNumberFormat,k)}function Pe(k){return P._int32(o.ZodNumberFormat,k)}function De(k){return P._uint32(o.ZodNumberFormat,k)}o.ZodBoolean=P.$constructor("ZodBoolean",(k,A)=>{P.$ZodBoolean.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.booleanProcessor(k,H,ee,xe)});function me(k){return P._boolean(o.ZodBoolean,k)}o.ZodBigInt=P.$constructor("ZodBigInt",(k,A)=>{P.$ZodBigInt.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(ee,xe,Dt)=>V.bigintProcessor(k,ee,xe,Dt),k.gte=(ee,xe)=>k.check(b.gte(ee,xe)),k.min=(ee,xe)=>k.check(b.gte(ee,xe)),k.gt=(ee,xe)=>k.check(b.gt(ee,xe)),k.gte=(ee,xe)=>k.check(b.gte(ee,xe)),k.min=(ee,xe)=>k.check(b.gte(ee,xe)),k.lt=(ee,xe)=>k.check(b.lt(ee,xe)),k.lte=(ee,xe)=>k.check(b.lte(ee,xe)),k.max=(ee,xe)=>k.check(b.lte(ee,xe)),k.positive=ee=>k.check(b.gt(BigInt(0),ee)),k.negative=ee=>k.check(b.lt(BigInt(0),ee)),k.nonpositive=ee=>k.check(b.lte(BigInt(0),ee)),k.nonnegative=ee=>k.check(b.gte(BigInt(0),ee)),k.multipleOf=(ee,xe)=>k.check(b.multipleOf(ee,xe));const H=k._zod.bag;k.minValue=H.minimum??null,k.maxValue=H.maximum??null,k.format=H.format??null});function je(k){return P._bigint(o.ZodBigInt,k)}o.ZodBigIntFormat=P.$constructor("ZodBigIntFormat",(k,A)=>{P.$ZodBigIntFormat.init(k,A),o.ZodBigInt.init(k,A)});function Ve(k){return P._int64(o.ZodBigIntFormat,k)}function wt(k){return P._uint64(o.ZodBigIntFormat,k)}o.ZodSymbol=P.$constructor("ZodSymbol",(k,A)=>{P.$ZodSymbol.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.symbolProcessor(k,H,ee,xe)});function ht(k){return P._symbol(o.ZodSymbol,k)}o.ZodUndefined=P.$constructor("ZodUndefined",(k,A)=>{P.$ZodUndefined.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.undefinedProcessor(k,H,ee,xe)});function pt(k){return P._undefined(o.ZodUndefined,k)}o.ZodNull=P.$constructor("ZodNull",(k,A)=>{P.$ZodNull.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.nullProcessor(k,H,ee,xe)});function Tt(k){return P._null(o.ZodNull,k)}o.ZodAny=P.$constructor("ZodAny",(k,A)=>{P.$ZodAny.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.anyProcessor(k,H,ee,xe)});function Ut(){return P._any(o.ZodAny)}o.ZodUnknown=P.$constructor("ZodUnknown",(k,A)=>{P.$ZodUnknown.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.unknownProcessor(k,H,ee,xe)});function Pt(){return P._unknown(o.ZodUnknown)}o.ZodNever=P.$constructor("ZodNever",(k,A)=>{P.$ZodNever.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.neverProcessor(k,H,ee,xe)});function Ot(k){return P._never(o.ZodNever,k)}o.ZodVoid=P.$constructor("ZodVoid",(k,A)=>{P.$ZodVoid.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.voidProcessor(k,H,ee,xe)});function Wt(k){return P._void(o.ZodVoid,k)}o.ZodDate=P.$constructor("ZodDate",(k,A)=>{P.$ZodDate.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(ee,xe,Dt)=>V.dateProcessor(k,ee,xe,Dt),k.min=(ee,xe)=>k.check(b.gte(ee,xe)),k.max=(ee,xe)=>k.check(b.lte(ee,xe));const H=k._zod.bag;k.minDate=H.minimum?new Date(H.minimum):null,k.maxDate=H.maximum?new Date(H.maximum):null});function xi(k){return P._date(o.ZodDate,k)}o.ZodArray=P.$constructor("ZodArray",(k,A)=>{P.$ZodArray.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.arrayProcessor(k,H,ee,xe),k.element=A.element,l(k,"ZodArray",{min(H,ee){return this.check(b.minLength(H,ee))},nonempty(H){return this.check(b.minLength(1,H))},max(H,ee){return this.check(b.maxLength(H,ee))},length(H,ee){return this.check(b.length(H,ee))},unwrap(){return this.element}})});function Rn(k,A){return P._array(o.ZodArray,k,A)}function nd(k){const A=k._zod.def.shape;return Oa(Object.keys(A))}o.ZodObject=P.$constructor("ZodObject",(k,A)=>{P.$ZodObjectJIT.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.objectProcessor(k,H,ee,xe),D.util.defineLazy(k,"shape",()=>A.shape),l(k,"ZodObject",{keyof(){return Oa(Object.keys(this._zod.def.shape))},catchall(H){return this.clone({...this._zod.def,catchall:H})},passthrough(){return this.clone({...this._zod.def,catchall:Pt()})},loose(){return this.clone({...this._zod.def,catchall:Pt()})},strict(){return this.clone({...this._zod.def,catchall:Ot()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(H){return D.util.extend(this,H)},safeExtend(H){return D.util.safeExtend(this,H)},merge(H){return D.util.merge(this,H)},pick(H){return D.util.pick(this,H)},omit(H){return D.util.omit(this,H)},partial(...H){return D.util.partial(o.ZodOptional,this,H[0])},required(...H){return D.util.required(o.ZodNonOptional,this,H[0])}})});function id(k,A){const H={type:"object",shape:k??{},...D.util.normalizeParams(A)};return new o.ZodObject(H)}function sd(k,A){return new o.ZodObject({type:"object",shape:k,catchall:Ot(),...D.util.normalizeParams(A)})}function ad(k,A){return new o.ZodObject({type:"object",shape:k,catchall:Pt(),...D.util.normalizeParams(A)})}o.ZodUnion=P.$constructor("ZodUnion",(k,A)=>{P.$ZodUnion.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.unionProcessor(k,H,ee,xe),k.options=A.options});function Ra(k,A){return new o.ZodUnion({type:"union",options:k,...D.util.normalizeParams(A)})}o.ZodXor=P.$constructor("ZodXor",(k,A)=>{o.ZodUnion.init(k,A),P.$ZodXor.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.unionProcessor(k,H,ee,xe),k.options=A.options});function od(k,A){return new o.ZodXor({type:"union",options:k,inclusive:!1,...D.util.normalizeParams(A)})}o.ZodDiscriminatedUnion=P.$constructor("ZodDiscriminatedUnion",(k,A)=>{o.ZodUnion.init(k,A),P.$ZodDiscriminatedUnion.init(k,A)});function yn(k,A,H){return new o.ZodDiscriminatedUnion({type:"union",options:A,discriminator:k,...D.util.normalizeParams(H)})}o.ZodIntersection=P.$constructor("ZodIntersection",(k,A)=>{P.$ZodIntersection.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.intersectionProcessor(k,H,ee,xe)});function vt(k,A){return new o.ZodIntersection({type:"intersection",left:k,right:A})}o.ZodTuple=P.$constructor("ZodTuple",(k,A)=>{P.$ZodTuple.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.tupleProcessor(k,H,ee,xe),k.rest=H=>k.clone({...k._zod.def,rest:H})});function ln(k,A,H){const ee=A instanceof P.$ZodType,xe=ee?H:A,Dt=ee?A:null;return new o.ZodTuple({type:"tuple",items:k,rest:Dt,...D.util.normalizeParams(xe)})}o.ZodRecord=P.$constructor("ZodRecord",(k,A)=>{P.$ZodRecord.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.recordProcessor(k,H,ee,xe),k.keyType=A.keyType,k.valueType=A.valueType});function Wi(k,A,H){return!A||!A._zod?new o.ZodRecord({type:"record",keyType:i(),valueType:k,...D.util.normalizeParams(A)}):new o.ZodRecord({type:"record",keyType:k,valueType:A,...D.util.normalizeParams(H)})}function cn(k,A,H){const ee=P.clone(k);return ee._zod.values=void 0,new o.ZodRecord({type:"record",keyType:ee,valueType:A,...D.util.normalizeParams(H)})}function Qo(k,A,H){return new o.ZodRecord({type:"record",keyType:k,valueType:A,mode:"loose",...D.util.normalizeParams(H)})}o.ZodMap=P.$constructor("ZodMap",(k,A)=>{P.$ZodMap.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.mapProcessor(k,H,ee,xe),k.keyType=A.keyType,k.valueType=A.valueType,k.min=(...H)=>k.check(P._minSize(...H)),k.nonempty=H=>k.check(P._minSize(1,H)),k.max=(...H)=>k.check(P._maxSize(...H)),k.size=(...H)=>k.check(P._size(...H))});function ld(k,A,H){return new o.ZodMap({type:"map",keyType:k,valueType:A,...D.util.normalizeParams(H)})}o.ZodSet=P.$constructor("ZodSet",(k,A)=>{P.$ZodSet.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.setProcessor(k,H,ee,xe),k.min=(...H)=>k.check(P._minSize(...H)),k.nonempty=H=>k.check(P._minSize(1,H)),k.max=(...H)=>k.check(P._maxSize(...H)),k.size=(...H)=>k.check(P._size(...H))});function La(k,A){return new o.ZodSet({type:"set",valueType:k,...D.util.normalizeParams(A)})}o.ZodEnum=P.$constructor("ZodEnum",(k,A)=>{P.$ZodEnum.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(ee,xe,Dt)=>V.enumProcessor(k,ee,xe,Dt),k.enum=A.entries,k.options=Object.values(A.entries);const H=new Set(Object.keys(A.entries));k.extract=(ee,xe)=>{const Dt={};for(const Jt of ee)if(H.has(Jt))Dt[Jt]=A.entries[Jt];else throw new Error(`Key ${Jt} not found in enum`);return new o.ZodEnum({...A,checks:[],...D.util.normalizeParams(xe),entries:Dt})},k.exclude=(ee,xe)=>{const Dt={...A.entries};for(const Jt of ee)if(H.has(Jt))delete Dt[Jt];else throw new Error(`Key ${Jt} not found in enum`);return new o.ZodEnum({...A,checks:[],...D.util.normalizeParams(xe),entries:Dt})}});function Oa(k,A){const H=Array.isArray(k)?Object.fromEntries(k.map(ee=>[ee,ee])):k;return new o.ZodEnum({type:"enum",entries:H,...D.util.normalizeParams(A)})}function cd(k,A){return new o.ZodEnum({type:"enum",entries:k,...D.util.normalizeParams(A)})}o.ZodLiteral=P.$constructor("ZodLiteral",(k,A)=>{P.$ZodLiteral.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.literalProcessor(k,H,ee,xe),k.values=new Set(A.values),Object.defineProperty(k,"value",{get(){if(A.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return A.values[0]}})});function ud(k,A){return new o.ZodLiteral({type:"literal",values:Array.isArray(k)?k:[k],...D.util.normalizeParams(A)})}o.ZodFile=P.$constructor("ZodFile",(k,A)=>{P.$ZodFile.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.fileProcessor(k,H,ee,xe),k.min=(H,ee)=>k.check(P._minSize(H,ee)),k.max=(H,ee)=>k.check(P._maxSize(H,ee)),k.mime=(H,ee)=>k.check(P._mime(Array.isArray(H)?H:[H],ee))});function dd(k){return P._file(o.ZodFile,k)}o.ZodTransform=P.$constructor("ZodTransform",(k,A)=>{P.$ZodTransform.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.transformProcessor(k,H,ee,xe),k._zod.parse=(H,ee)=>{if(ee.direction==="backward")throw new P.$ZodEncodeError(k.constructor.name);H.addIssue=Dt=>{if(typeof Dt=="string")H.issues.push(D.util.issue(Dt,H.value,A));else{const Jt=Dt;Jt.fatal&&(Jt.continue=!1),Jt.code??(Jt.code="custom"),Jt.input??(Jt.input=H.value),Jt.inst??(Jt.inst=k),H.issues.push(D.util.issue(Jt))}};const xe=A.transform(H.value,H);return xe instanceof Promise?xe.then(Dt=>(H.value=Dt,H.fallback=!0,H)):(H.value=xe,H.fallback=!0,H)}});function Xe(k){return new o.ZodTransform({type:"transform",transform:k})}o.ZodOptional=P.$constructor("ZodOptional",(k,A)=>{P.$ZodOptional.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.optionalProcessor(k,H,ee,xe),k.unwrap=()=>k._zod.def.innerType});function Yr(k){return new o.ZodOptional({type:"optional",innerType:k})}o.ZodExactOptional=P.$constructor("ZodExactOptional",(k,A)=>{P.$ZodExactOptional.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.optionalProcessor(k,H,ee,xe),k.unwrap=()=>k._zod.def.innerType});function Fa(k){return new o.ZodExactOptional({type:"optional",innerType:k})}o.ZodNullable=P.$constructor("ZodNullable",(k,A)=>{P.$ZodNullable.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.nullableProcessor(k,H,ee,xe),k.unwrap=()=>k._zod.def.innerType});function qi(k){return new o.ZodNullable({type:"nullable",innerType:k})}function fd(k){return Yr(qi(k))}o.ZodDefault=P.$constructor("ZodDefault",(k,A)=>{P.$ZodDefault.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.defaultProcessor(k,H,ee,xe),k.unwrap=()=>k._zod.def.innerType,k.removeDefault=k.unwrap});function Ua(k,A){return new o.ZodDefault({type:"default",innerType:k,get defaultValue(){return typeof A=="function"?A():D.util.shallowClone(A)}})}o.ZodPrefault=P.$constructor("ZodPrefault",(k,A)=>{P.$ZodPrefault.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.prefaultProcessor(k,H,ee,xe),k.unwrap=()=>k._zod.def.innerType});function Yo(k,A){return new o.ZodPrefault({type:"prefault",innerType:k,get defaultValue(){return typeof A=="function"?A():D.util.shallowClone(A)}})}o.ZodNonOptional=P.$constructor("ZodNonOptional",(k,A)=>{P.$ZodNonOptional.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.nonoptionalProcessor(k,H,ee,xe),k.unwrap=()=>k._zod.def.innerType});function Si(k,A){return new o.ZodNonOptional({type:"nonoptional",innerType:k,...D.util.normalizeParams(A)})}o.ZodSuccess=P.$constructor("ZodSuccess",(k,A)=>{P.$ZodSuccess.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.successProcessor(k,H,ee,xe),k.unwrap=()=>k._zod.def.innerType});function et(k){return new o.ZodSuccess({type:"success",innerType:k})}o.ZodCatch=P.$constructor("ZodCatch",(k,A)=>{P.$ZodCatch.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.catchProcessor(k,H,ee,xe),k.unwrap=()=>k._zod.def.innerType,k.removeCatch=k.unwrap});function ti(k,A){return new o.ZodCatch({type:"catch",innerType:k,catchValue:typeof A=="function"?A:()=>A})}o.ZodNaN=P.$constructor("ZodNaN",(k,A)=>{P.$ZodNaN.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.nanProcessor(k,H,ee,xe)});function hd(k){return P._nan(o.ZodNaN,k)}o.ZodPipe=P.$constructor("ZodPipe",(k,A)=>{P.$ZodPipe.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.pipeProcessor(k,H,ee,xe),k.in=A.in,k.out=A.out});function Qi(k,A){return new o.ZodPipe({type:"pipe",in:k,out:A})}o.ZodCodec=P.$constructor("ZodCodec",(k,A)=>{o.ZodPipe.init(k,A),P.$ZodCodec.init(k,A)});function md(k,A,H){return new o.ZodCodec({type:"pipe",in:k,out:A,transform:H.decode,reverseTransform:H.encode})}function gd(k){const A=k._zod.def;return new o.ZodCodec({type:"pipe",in:A.out,out:A.in,transform:A.reverseTransform,reverseTransform:A.transform})}o.ZodPreprocess=P.$constructor("ZodPreprocess",(k,A)=>{o.ZodPipe.init(k,A),P.$ZodPreprocess.init(k,A)}),o.ZodReadonly=P.$constructor("ZodReadonly",(k,A)=>{P.$ZodReadonly.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.readonlyProcessor(k,H,ee,xe),k.unwrap=()=>k._zod.def.innerType});function _i(k){return new o.ZodReadonly({type:"readonly",innerType:k})}o.ZodTemplateLiteral=P.$constructor("ZodTemplateLiteral",(k,A)=>{P.$ZodTemplateLiteral.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.templateLiteralProcessor(k,H,ee,xe)});function pd(k,A){return new o.ZodTemplateLiteral({type:"template_literal",parts:k,...D.util.normalizeParams(A)})}o.ZodLazy=P.$constructor("ZodLazy",(k,A)=>{P.$ZodLazy.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.lazyProcessor(k,H,ee,xe),k.unwrap=()=>k._zod.def.getter()});function un(k){return new o.ZodLazy({type:"lazy",getter:k})}o.ZodPromise=P.$constructor("ZodPromise",(k,A)=>{P.$ZodPromise.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.promiseProcessor(k,H,ee,xe),k.unwrap=()=>k._zod.def.innerType});function Ln(k){return new o.ZodPromise({type:"promise",innerType:k})}o.ZodFunction=P.$constructor("ZodFunction",(k,A)=>{P.$ZodFunction.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.functionProcessor(k,H,ee,xe)});function wi(k){return new o.ZodFunction({type:"function",input:Array.isArray(k?.input)?ln(k?.input):k?.input??Rn(Pt()),output:k?.output??Pt()})}o.ZodCustom=P.$constructor("ZodCustom",(k,A)=>{P.$ZodCustom.init(k,A),o.ZodType.init(k,A),k._zod.processJSONSchema=(H,ee,xe)=>V.customProcessor(k,H,ee,xe)});function Xo(k){const A=new P.$ZodCheck({check:"custom"});return A._zod.check=k,A}function Jo(k,A){return P._custom(o.ZodCustom,k??(()=>!0),A)}function Ba(k,A={}){return P._refine(o.ZodCustom,k,A)}function el(k,A){return P._superRefine(k,A)}o.describe=P.describe,o.meta=P.meta;function tl(k,A={}){const H=new o.ZodCustom({type:"custom",check:"custom",fn:ee=>ee instanceof k,abort:!0,...D.util.normalizeParams(A)});return H._zod.bag.Class=k,H._zod.check=ee=>{ee.value instanceof k||ee.issues.push({code:"invalid_type",expected:k.name,input:ee.value,inst:H,path:[...H._zod.def.path??[]]})},H}const rl=(...k)=>P._stringbool({Codec:o.ZodCodec,Boolean:o.ZodBoolean,String:o.ZodString},...k);o.stringbool=rl;function nl(k){const A=un(()=>Ra([i(k),ke(),me(),Tt(),Rn(A),Wi(i(),A)]));return A}function vd(k,A){return new o.ZodPreprocess({type:"pipe",in:Xe(k),out:A})}})(qn)),qn}var vi={};(function(o){var _=vi&&vi.__createBinding||(Object.create?(function(v,x,w,l){l===void 0&&(l=w);var i=Object.getOwnPropertyDescriptor(x,w);(!i||("get"in i?!x.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return x[w]}}),Object.defineProperty(v,l,i)}):(function(v,x,w,l){l===void 0&&(l=w),v[l]=x[w]})),R=vi&&vi.__setModuleDefault||(Object.create?(function(v,x){Object.defineProperty(v,"default",{enumerable:!0,value:x})}):function(v,x){v.default=x}),F=vi&&vi.__importStar||function(v){if(v&&v.__esModule)return v;var x={};if(v!=null)for(var w in v)w!=="default"&&Object.prototype.hasOwnProperty.call(v,w)&&_(x,v,w);return R(x,v),x};Object.defineProperty(o,"__esModule",{value:!0}),o.ZodFirstPartyTypeKind=o.config=o.$brand=o.ZodIssueCode=void 0,o.setErrorMap=V,o.getErrorMap=J;const P=F(sr);o.ZodIssueCode={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};var D=sr;Object.defineProperty(o,"$brand",{enumerable:!0,get:function(){return D.$brand}}),Object.defineProperty(o,"config",{enumerable:!0,get:function(){return D.config}});function V(v){P.config({customError:v})}function J(){return P.config().customError}var b;b||(o.ZodFirstPartyTypeKind=b={})})(vi);var Jn={},gY=Jn&&Jn.__createBinding||(Object.create?(function(o,_,R,F){F===void 0&&(F=R);var P=Object.getOwnPropertyDescriptor(_,R);(!P||("get"in P?!_.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return _[R]}}),Object.defineProperty(o,F,P)}):(function(o,_,R,F){F===void 0&&(F=R),o[F]=_[R]})),pY=Jn&&Jn.__setModuleDefault||(Object.create?(function(o,_){Object.defineProperty(o,"default",{enumerable:!0,value:_})}):function(o,_){o.default=_}),Sg=Jn&&Jn.__importStar||function(o){if(o&&o.__esModule)return o;var _={};if(o!=null)for(var R in o)R!=="default"&&Object.prototype.hasOwnProperty.call(o,R)&&gY(_,o,R);return pY(_,o),_};Object.defineProperty(Jn,"__esModule",{value:!0});Jn.fromJSONSchema=EY;const vY=Lr,bY=Sg(td),yY=Sg(Qu()),xY=Sg(rd()),Qe={...xY,...bY,iso:yY},SY=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"]);function _Y(o,_){const R=o.$schema;return R==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":R==="http://json-schema.org/draft-07/schema#"?"draft-7":R==="http://json-schema.org/draft-04/schema#"?"draft-4":_??"draft-2020-12"}function wY(o,_){if(!o.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");const R=o.slice(1).split("/").filter(Boolean);if(R.length===0)return _.rootSchema;const F=_.version==="draft-2020-12"?"$defs":"definitions";if(R[0]===F){const P=R[1];if(!P||!_.defs[P])throw new Error(`Reference not found: ${o}`);return _.defs[P]}throw new Error(`Reference not found: ${o}`)}function Bw(o,_){if(o.not!==void 0){if(typeof o.not=="object"&&Object.keys(o.not).length===0)return Qe.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(o.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(o.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(o.if!==void 0||o.then!==void 0||o.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(o.dependentSchemas!==void 0||o.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(o.$ref){const P=o.$ref;if(_.refs.has(P))return _.refs.get(P);if(_.processing.has(P))return Qe.lazy(()=>{if(!_.refs.has(P))throw new Error(`Circular reference not resolved: ${P}`);return _.refs.get(P)});_.processing.add(P);const D=wY(P,_),V=Cr(D,_);return _.refs.set(P,V),_.processing.delete(P),V}if(o.enum!==void 0){const P=o.enum;if(_.version==="openapi-3.0"&&o.nullable===!0&&P.length===1&&P[0]===null)return Qe.null();if(P.length===0)return Qe.never();if(P.length===1)return Qe.literal(P[0]);if(P.every(V=>typeof V=="string"))return Qe.enum(P);const D=P.map(V=>Qe.literal(V));return D.length<2?D[0]:Qe.union([D[0],D[1],...D.slice(2)])}if(o.const!==void 0)return Qe.literal(o.const);const R=o.type;if(Array.isArray(R)){const P=R.map(D=>{const V={...o,type:D};return Bw(V,_)});return P.length===0?Qe.never():P.length===1?P[0]:Qe.union(P)}if(!R)return Qe.any();let F;switch(R){case"string":{let P=Qe.string();if(o.format){const D=o.format;D==="email"?P=P.check(Qe.email()):D==="uri"||D==="uri-reference"?P=P.check(Qe.url()):D==="uuid"||D==="guid"?P=P.check(Qe.uuid()):D==="date-time"?P=P.check(Qe.iso.datetime()):D==="date"?P=P.check(Qe.iso.date()):D==="time"?P=P.check(Qe.iso.time()):D==="duration"?P=P.check(Qe.iso.duration()):D==="ipv4"?P=P.check(Qe.ipv4()):D==="ipv6"?P=P.check(Qe.ipv6()):D==="mac"?P=P.check(Qe.mac()):D==="cidr"?P=P.check(Qe.cidrv4()):D==="cidr-v6"?P=P.check(Qe.cidrv6()):D==="base64"?P=P.check(Qe.base64()):D==="base64url"?P=P.check(Qe.base64url()):D==="e164"?P=P.check(Qe.e164()):D==="jwt"?P=P.check(Qe.jwt()):D==="emoji"?P=P.check(Qe.emoji()):D==="nanoid"?P=P.check(Qe.nanoid()):D==="cuid"?P=P.check(Qe.cuid()):D==="cuid2"?P=P.check(Qe.cuid2()):D==="ulid"?P=P.check(Qe.ulid()):D==="xid"?P=P.check(Qe.xid()):D==="ksuid"&&(P=P.check(Qe.ksuid()))}typeof o.minLength=="number"&&(P=P.min(o.minLength)),typeof o.maxLength=="number"&&(P=P.max(o.maxLength)),o.pattern&&(P=P.regex(new RegExp(o.pattern))),F=P;break}case"number":case"integer":{let P=R==="integer"?Qe.number().int():Qe.number();typeof o.minimum=="number"&&(P=P.min(o.minimum)),typeof o.maximum=="number"&&(P=P.max(o.maximum)),typeof o.exclusiveMinimum=="number"?P=P.gt(o.exclusiveMinimum):o.exclusiveMinimum===!0&&typeof o.minimum=="number"&&(P=P.gt(o.minimum)),typeof o.exclusiveMaximum=="number"?P=P.lt(o.exclusiveMaximum):o.exclusiveMaximum===!0&&typeof o.maximum=="number"&&(P=P.lt(o.maximum)),typeof o.multipleOf=="number"&&(P=P.multipleOf(o.multipleOf)),F=P;break}case"boolean":{F=Qe.boolean();break}case"null":{F=Qe.null();break}case"object":{const P={},D=o.properties||{},V=new Set(o.required||[]);for(const[b,v]of Object.entries(D)){const x=Cr(v,_);P[b]=V.has(b)?x:x.optional()}if(o.propertyNames){const b=Cr(o.propertyNames,_),v=o.additionalProperties&&typeof o.additionalProperties=="object"?Cr(o.additionalProperties,_):Qe.any();if(Object.keys(P).length===0){F=Qe.record(b,v);break}const x=Qe.object(P).passthrough(),w=Qe.looseRecord(b,v);F=Qe.intersection(x,w);break}if(o.patternProperties){const b=o.patternProperties,v=Object.keys(b),x=[];for(const l of v){const i=Cr(b[l],_),I=Qe.string().regex(new RegExp(l));x.push(Qe.looseRecord(I,i))}const w=[];if(Object.keys(P).length>0&&w.push(Qe.object(P).passthrough()),w.push(...x),w.length===0)F=Qe.object({}).passthrough();else if(w.length===1)F=w[0];else{let l=Qe.intersection(w[0],w[1]);for(let i=2;i<w.length;i++)l=Qe.intersection(l,w[i]);F=l}break}const J=Qe.object(P);o.additionalProperties===!1?F=J.strict():typeof o.additionalProperties=="object"?F=J.catchall(Cr(o.additionalProperties,_)):F=J.passthrough();break}case"array":{const P=o.prefixItems,D=o.items;if(P&&Array.isArray(P)){const V=P.map(b=>Cr(b,_)),J=D&&typeof D=="object"&&!Array.isArray(D)?Cr(D,_):void 0;J?F=Qe.tuple(V).rest(J):F=Qe.tuple(V),typeof o.minItems=="number"&&(F=F.check(Qe.minLength(o.minItems))),typeof o.maxItems=="number"&&(F=F.check(Qe.maxLength(o.maxItems)))}else if(Array.isArray(D)){const V=D.map(b=>Cr(b,_)),J=o.additionalItems&&typeof o.additionalItems=="object"?Cr(o.additionalItems,_):void 0;J?F=Qe.tuple(V).rest(J):F=Qe.tuple(V),typeof o.minItems=="number"&&(F=F.check(Qe.minLength(o.minItems))),typeof o.maxItems=="number"&&(F=F.check(Qe.maxLength(o.maxItems)))}else if(D!==void 0){const V=Cr(D,_);let J=Qe.array(V);typeof o.minItems=="number"&&(J=J.min(o.minItems)),typeof o.maxItems=="number"&&(J=J.max(o.maxItems)),F=J}else F=Qe.array(Qe.any());break}default:throw new Error(`Unsupported type: ${R}`)}return F}function Cr(o,_){if(typeof o=="boolean")return o?Qe.any():Qe.never();let R=Bw(o,_);const F=o.type||o.enum!==void 0||o.const!==void 0;if(o.anyOf&&Array.isArray(o.anyOf)){const J=o.anyOf.map(v=>Cr(v,_)),b=Qe.union(J);R=F?Qe.intersection(R,b):b}if(o.oneOf&&Array.isArray(o.oneOf)){const J=o.oneOf.map(v=>Cr(v,_)),b=Qe.xor(J);R=F?Qe.intersection(R,b):b}if(o.allOf&&Array.isArray(o.allOf))if(o.allOf.length===0)R=F?R:Qe.any();else{let J=F?R:Cr(o.allOf[0],_);const b=F?0:1;for(let v=b;v<o.allOf.length;v++)J=Qe.intersection(J,Cr(o.allOf[v],_));R=J}o.nullable===!0&&_.version==="openapi-3.0"&&(R=Qe.nullable(R)),o.readOnly===!0&&(R=Qe.readonly(R)),o.default!==void 0&&(R=R.default(o.default));const P={},D=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(const J of D)J in o&&(P[J]=o[J]);const V=["contentEncoding","contentMediaType","contentSchema"];for(const J of V)J in o&&(P[J]=o[J]);for(const J of Object.keys(o))SY.has(J)||(P[J]=o[J]);return Object.keys(P).length>0&&_.registry.add(R,P),o.description&&(R=R.describe(o.description)),R}function EY(o,_){if(typeof o=="boolean")return o?Qe.any():Qe.never();let R;try{R=JSON.parse(JSON.stringify(o))}catch{throw new Error("fromJSONSchema input is not valid JSON (possibly cyclic); use $defs/$ref for recursive schemas")}const F=_Y(R,_?.defaultTarget),P=R.$defs||R.definitions||{},D={version:F,defs:P,refs:new Map,processing:new Set,rootSchema:R,registry:_?.registry??vY.globalRegistry};return Cr(R,D)}var Qr={},kY=Qr&&Qr.__createBinding||(Object.create?(function(o,_,R,F){F===void 0&&(F=R);var P=Object.getOwnPropertyDescriptor(_,R);(!P||("get"in P?!_.__esModule:P.writable||P.configurable))&&(P={enumerable:!0,get:function(){return _[R]}}),Object.defineProperty(o,F,P)}):(function(o,_,R,F){F===void 0&&(F=R),o[F]=_[R]})),TY=Qr&&Qr.__setModuleDefault||(Object.create?(function(o,_){Object.defineProperty(o,"default",{enumerable:!0,value:_})}):function(o,_){o.default=_}),zw=Qr&&Qr.__importStar||function(o){if(o&&o.__esModule)return o;var _={};if(o!=null)for(var R in o)R!=="default"&&Object.prototype.hasOwnProperty.call(o,R)&&kY(_,o,R);return TY(_,o),_};Object.defineProperty(Qr,"__esModule",{value:!0});Qr.string=CY;Qr.number=IY;Qr.boolean=PY;Qr.bigint=AY;Qr.date=jY;const Wo=zw(sr),qo=zw(rd());function CY(o){return Wo._coercedString(qo.ZodString,o)}function IY(o){return Wo._coercedNumber(qo.ZodNumber,o)}function PY(o){return Wo._coercedBoolean(qo.ZodBoolean,o)}function AY(o){return Wo._coercedBigint(qo.ZodBigInt,o)}function jY(o){return Wo._coercedDate(qo.ZodDate,o)}(function(o){var _=Wr&&Wr.__createBinding||(Object.create?(function(l,i,I,Z){Z===void 0&&(Z=I);var ye=Object.getOwnPropertyDescriptor(i,I);(!ye||("get"in ye?!i.__esModule:ye.writable||ye.configurable))&&(ye={enumerable:!0,get:function(){return i[I]}}),Object.defineProperty(l,Z,ye)}):(function(l,i,I,Z){Z===void 0&&(Z=I),l[Z]=i[I]})),R=Wr&&Wr.__setModuleDefault||(Object.create?(function(l,i){Object.defineProperty(l,"default",{enumerable:!0,value:i})}):function(l,i){l.default=i}),F=Wr&&Wr.__importStar||function(l){if(l&&l.__esModule)return l;var i={};if(l!=null)for(var I in l)I!=="default"&&Object.prototype.hasOwnProperty.call(l,I)&&_(i,l,I);return R(i,l),i},P=Wr&&Wr.__exportStar||function(l,i){for(var I in l)I!=="default"&&!Object.prototype.hasOwnProperty.call(i,I)&&_(i,l,I)},D=Wr&&Wr.__importDefault||function(l){return l&&l.__esModule?l:{default:l}};Object.defineProperty(o,"__esModule",{value:!0}),o.coerce=o.iso=o.ZodISODuration=o.ZodISOTime=o.ZodISODate=o.ZodISODateTime=o.locales=o.fromJSONSchema=o.toJSONSchema=o.NEVER=o.util=o.TimePrecision=o.flattenError=o.formatError=o.prettifyError=o.treeifyError=o.regexes=o.clone=o.$brand=o.$input=o.$output=o.config=o.registry=o.globalRegistry=o.core=void 0,o.core=F(sr),P(rd(),o),P(td,o),P(qr,o),P(Nt,o),P(vi,o);const V=sr,J=D(Aw);(0,V.config)((0,J.default)());var b=sr;Object.defineProperty(o,"globalRegistry",{enumerable:!0,get:function(){return b.globalRegistry}}),Object.defineProperty(o,"registry",{enumerable:!0,get:function(){return b.registry}}),Object.defineProperty(o,"config",{enumerable:!0,get:function(){return b.config}}),Object.defineProperty(o,"$output",{enumerable:!0,get:function(){return b.$output}}),Object.defineProperty(o,"$input",{enumerable:!0,get:function(){return b.$input}}),Object.defineProperty(o,"$brand",{enumerable:!0,get:function(){return b.$brand}}),Object.defineProperty(o,"clone",{enumerable:!0,get:function(){return b.clone}}),Object.defineProperty(o,"regexes",{enumerable:!0,get:function(){return b.regexes}}),Object.defineProperty(o,"treeifyError",{enumerable:!0,get:function(){return b.treeifyError}}),Object.defineProperty(o,"prettifyError",{enumerable:!0,get:function(){return b.prettifyError}}),Object.defineProperty(o,"formatError",{enumerable:!0,get:function(){return b.formatError}}),Object.defineProperty(o,"flattenError",{enumerable:!0,get:function(){return b.flattenError}}),Object.defineProperty(o,"TimePrecision",{enumerable:!0,get:function(){return b.TimePrecision}}),Object.defineProperty(o,"util",{enumerable:!0,get:function(){return b.util}}),Object.defineProperty(o,"NEVER",{enumerable:!0,get:function(){return b.NEVER}});var v=Ko;Object.defineProperty(o,"toJSONSchema",{enumerable:!0,get:function(){return v.toJSONSchema}});var x=Jn;Object.defineProperty(o,"fromJSONSchema",{enumerable:!0,get:function(){return x.fromJSONSchema}}),o.locales=F(Bo);var w=Qu();Object.defineProperty(o,"ZodISODateTime",{enumerable:!0,get:function(){return w.ZodISODateTime}}),Object.defineProperty(o,"ZodISODate",{enumerable:!0,get:function(){return w.ZodISODate}}),Object.defineProperty(o,"ZodISOTime",{enumerable:!0,get:function(){return w.ZodISOTime}}),Object.defineProperty(o,"ZodISODuration",{enumerable:!0,get:function(){return w.ZodISODuration}}),o.iso=F(Qu()),o.coerce=F(Qr)})(Wr);(function(o){var _=Dn&&Dn.__createBinding||(Object.create?(function(V,J,b,v){v===void 0&&(v=b);var x=Object.getOwnPropertyDescriptor(J,b);(!x||("get"in x?!J.__esModule:x.writable||x.configurable))&&(x={enumerable:!0,get:function(){return J[b]}}),Object.defineProperty(V,v,x)}):(function(V,J,b,v){v===void 0&&(v=b),V[v]=J[b]})),R=Dn&&Dn.__setModuleDefault||(Object.create?(function(V,J){Object.defineProperty(V,"default",{enumerable:!0,value:J})}):function(V,J){V.default=J}),F=Dn&&Dn.__importStar||function(V){if(V&&V.__esModule)return V;var J={};if(V!=null)for(var b in V)b!=="default"&&Object.prototype.hasOwnProperty.call(V,b)&&_(J,V,b);return R(J,V),J},P=Dn&&Dn.__exportStar||function(V,J){for(var b in V)b!=="default"&&!Object.prototype.hasOwnProperty.call(J,b)&&_(J,V,b)};Object.defineProperty(o,"__esModule",{value:!0}),o.z=void 0;const D=F(Wr);o.z=D,P(Wr,o),o.default=D})(Dn);var xw;function Vw(){return xw||(xw=1,(function(o){var _={};Object.defineProperty(o,Symbol.toStringTag,{value:"Module"});var R=Object.create,F=Object.defineProperty,P=Object.getOwnPropertyDescriptor,D=Object.getOwnPropertyNames,V=Object.getPrototypeOf,J=Object.prototype.hasOwnProperty,b=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(var s=D(t),a=0,c=s.length,d;a<c;a++)d=s[a],!J.call(e,d)&&d!==r&&F(e,d,{get:(u=>t[u]).bind(null,d),enumerable:!(n=P(t,d))||n.enumerable});return e},v=(e,t,r)=>(r=e!=null?R(V(e)):{},b(t||!e||!e.__esModule?F(r,"default",{value:e,enumerable:!0}):r,e));const x=sK();let w=Sw,l=v(w,1);w=v(w);let i=_w;i=v(i,1);let I=qH;I=v(I,1);let Z=QH;Z=v(Z,1);let ye=YH;ye=v(ye,1);let ve=XH;ve=v(ve,1);let Te=JH;Te=v(Te,1);let _e=eK;_e=v(_e,1);let Oe=tK;Oe=v(Oe,1);let W=rK,Ze=aK,Le=Dn;function ot(e){var t,r,n="";if(typeof e=="string"||typeof e=="number")n+=e;else if(typeof e=="object")if(Array.isArray(e)){var s=e.length;for(t=0;t<s;t++)e[t]&&(r=ot(e[t]))&&(n&&(n+=" "),n+=r)}else for(r in e)e[r]&&(n&&(n+=" "),n+=r);return n}function tt(){for(var e,t,r=0,n="",s=arguments.length;r<s;r++)(e=arguments[r])&&(t=ot(e))&&(n&&(n+=" "),n+=t);return n}var _t=(e,t)=>{const r=new Array(e.length+t.length);for(let n=0;n<e.length;n++)r[n]=e[n];for(let n=0;n<t.length;n++)r[e.length+n]=t[n];return r},Kt=(e,t)=>({classGroupId:e,validator:t}),cr=(e=new Map,t=null,r)=>({nextPart:e,validators:t,classGroupId:r}),kr="-",Tr=[],Ir="arbitrary..",Dr=e=>{const t=bn(e),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=e;return{getClassGroupId:c=>{if(c.startsWith("[")&&c.endsWith("]"))return Or(c);const d=c.split(kr);return Qt(d,d[0]===""&&d.length>1?1:0,t)},getConflictingClassGroupIds:(c,d)=>{if(d){const u=n[c],f=r[c];return u?f?_t(f,u):u:f||Tr}return r[c]||Tr}}},Qt=(e,t,r)=>{if(e.length-t===0)return r.classGroupId;const n=e[t],s=r.nextPart.get(n);if(s){const u=Qt(e,t+1,s);if(u)return u}const a=r.validators;if(a===null)return;const c=t===0?e.join(kr):e.slice(t).join(kr),d=a.length;for(let u=0;u<d;u++){const f=a[u];if(f.validator(c))return f.classGroupId}},Or=e=>e.slice(1,-1).indexOf(":")===-1?void 0:(()=>{const t=e.slice(1,-1),r=t.indexOf(":"),n=t.slice(0,r);return n?Ir+n:void 0})(),bn=e=>{const{theme:t,classGroups:r}=e;return M(r,t)},M=(e,t)=>{const r=cr();for(const n in e){const s=e[n];L(s,r,n,t)}return r},L=(e,t,r,n)=>{const s=e.length;for(let a=0;a<s;a++){const c=e[a];B(c,t,r,n)}},B=(e,t,r,n)=>{if(typeof e=="string"){Y(e,t,r);return}if(typeof e=="function"){re(e,t,r,n);return}ue(e,t,r,n)},Y=(e,t,r)=>{const n=e===""?t:ke(t,e);n.classGroupId=r},re=(e,t,r,n)=>{if(Me(e)){L(e(n),t,r,n);return}t.validators===null&&(t.validators=[]),t.validators.push(Kt(r,e))},ue=(e,t,r,n)=>{const s=Object.entries(e),a=s.length;for(let c=0;c<a;c++){const[d,u]=s[c];L(u,ke(t,d),r,n)}},ke=(e,t)=>{let r=e;const n=t.split(kr),s=n.length;for(let a=0;a<s;a++){const c=n[a];let d=r.nextPart.get(c);d||(d=cr(),r.nextPart.set(c,d)),r=d}return r},Me=e=>"isThemeGetter"in e&&e.isThemeGetter===!0,de=e=>{if(e<1)return{get:()=>{},set:()=>{}};let t=0,r=Object.create(null),n=Object.create(null);const s=(a,c)=>{r[a]=c,t++,t>e&&(t=0,n=r,r=Object.create(null))};return{get(a){let c=r[a];if(c!==void 0)return c;if((c=n[a])!==void 0)return s(a,c),c},set(a,c){a in r?r[a]=c:s(a,c)}}},ce="!",Pe=":",De=[],me=(e,t,r,n,s)=>({modifiers:e,hasImportantModifier:t,baseClassName:r,maybePostfixModifierPosition:n,isExternal:s}),je=e=>{const{prefix:t,experimentalParseClassName:r}=e;let n=s=>{const a=[];let c=0,d=0,u=0,f;const h=s.length;for(let S=0;S<h;S++){const E=s[S];if(c===0&&d===0){if(E===Pe){a.push(s.slice(u,S)),u=S+1;continue}if(E==="/"){f=S;continue}}E==="["?c++:E==="]"?c--:E==="("?d++:E===")"&&d--}const m=a.length===0?s:s.slice(u);let g=m,p=!1;m.endsWith(ce)?(g=m.slice(0,-1),p=!0):m.startsWith(ce)&&(g=m.slice(1),p=!0);const y=f&&f>u?f-u:void 0;return me(a,p,g,y)};if(t){const s=t+Pe,a=n;n=c=>c.startsWith(s)?a(c.slice(s.length)):me(De,!1,c,void 0,!0)}if(r){const s=n;n=a=>r({className:a,parseClassName:s})}return n},Ve=e=>{const t=new Map;return e.orderSensitiveModifiers.forEach((r,n)=>{t.set(r,1e6+n)}),r=>{const n=[];let s=[];for(let a=0;a<r.length;a++){const c=r[a],d=c[0]==="[",u=t.has(c);d||u?(s.length>0&&(s.sort(),n.push(...s),s=[]),n.push(c)):s.push(c)}return s.length>0&&(s.sort(),n.push(...s)),n}},wt=e=>({cache:de(e.cacheSize),parseClassName:je(e),sortModifiers:Ve(e),...Dr(e)}),ht=/\s+/,pt=(e,t)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:s,sortModifiers:a}=t,c=[],d=e.trim().split(ht);let u="";for(let f=d.length-1;f>=0;f-=1){const h=d[f],{isExternal:m,modifiers:g,hasImportantModifier:p,baseClassName:y,maybePostfixModifierPosition:S}=r(h);if(m){u=h+(u.length>0?" "+u:u);continue}let E=!!S,T=n(E?y.substring(0,S):y);if(!T){if(!E){u=h+(u.length>0?" "+u:u);continue}if(T=n(y),!T){u=h+(u.length>0?" "+u:u);continue}E=!1}const j=g.length===0?"":g.length===1?g[0]:a(g).join(":"),N=p?j+ce:j,O=N+T;if(c.indexOf(O)>-1)continue;c.push(O);const U=s(T,E);for(let z=0;z<U.length;++z){const K=U[z];c.push(N+K)}u=h+(u.length>0?" "+u:u)}return u},Tt=(...e)=>{let t=0,r,n,s="";for(;t<e.length;)(r=e[t++])&&(n=Ut(r))&&(s&&(s+=" "),s+=n);return s},Ut=e=>{if(typeof e=="string")return e;let t,r="";for(let n=0;n<e.length;n++)e[n]&&(t=Ut(e[n]))&&(r&&(r+=" "),r+=t);return r},Pt=(e,...t)=>{let r,n,s,a;const c=u=>(r=wt(t.reduce((f,h)=>h(f),e())),n=r.cache.get,s=r.cache.set,a=d,d(u)),d=u=>{const f=n(u);if(f)return f;const h=pt(u,r);return s(u,h),h};return a=c,(...u)=>a(Tt(...u))},Ot=[],Wt=e=>{const t=r=>r[e]||Ot;return t.isThemeGetter=!0,t},xi=/^\[(?:(\w[\w-]*):)?(.+)\]$/i,Rn=/^\((?:(\w[\w-]*):)?(.+)\)$/i,nd=/^\d+(?:\.\d+)?\/\d+(?:\.\d+)?$/,id=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,sd=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,ad=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Ra=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,od=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,yn=e=>nd.test(e),vt=e=>!!e&&!Number.isNaN(Number(e)),ln=e=>!!e&&Number.isInteger(Number(e)),Wi=e=>e.endsWith("%")&&vt(e.slice(0,-1)),cn=e=>id.test(e),Qo=()=>!0,ld=e=>sd.test(e)&&!ad.test(e),La=()=>!1,Oa=e=>Ra.test(e),cd=e=>od.test(e),ud=e=>!Xe(e)&&!et(e),dd=e=>un(e,Jo,La),Xe=e=>xi.test(e),Yr=e=>un(e,Ba,ld),Fa=e=>un(e,el,vt),qi=e=>un(e,rl,Qo),fd=e=>un(e,tl,La),Ua=e=>un(e,wi,La),Yo=e=>un(e,Xo,cd),Si=e=>un(e,nl,Oa),et=e=>Rn.test(e),ti=e=>Ln(e,Ba),hd=e=>Ln(e,tl),Qi=e=>Ln(e,wi),md=e=>Ln(e,Jo),gd=e=>Ln(e,Xo),_i=e=>Ln(e,nl,!0),pd=e=>Ln(e,rl,!0),un=(e,t,r)=>{const n=xi.exec(e);return n?n[1]?t(n[1]):r(n[2]):!1},Ln=(e,t,r=!1)=>{const n=Rn.exec(e);return n?n[1]?t(n[1]):r:!1},wi=e=>e==="position"||e==="percentage",Xo=e=>e==="image"||e==="url",Jo=e=>e==="length"||e==="size"||e==="bg-size",Ba=e=>e==="length",el=e=>e==="number",tl=e=>e==="family-name",rl=e=>e==="number"||e==="weight",nl=e=>e==="shadow",vd=()=>{const e=Wt("color"),t=Wt("font"),r=Wt("text"),n=Wt("font-weight"),s=Wt("tracking"),a=Wt("leading"),c=Wt("breakpoint"),d=Wt("container"),u=Wt("spacing"),f=Wt("radius"),h=Wt("shadow"),m=Wt("inset-shadow"),g=Wt("text-shadow"),p=Wt("drop-shadow"),y=Wt("blur"),S=Wt("perspective"),E=Wt("aspect"),T=Wt("ease"),j=Wt("animate"),N=()=>["auto","avoid","all","avoid-page","page","left","right","column"],O=()=>["center","top","bottom","left","right","top-left","left-top","top-right","right-top","bottom-right","right-bottom","bottom-left","left-bottom"],U=()=>[...O(),et,Xe],z=()=>["auto","hidden","clip","visible","scroll"],K=()=>["auto","contain","none"],G=()=>[et,Xe,u],X=()=>[yn,"full","auto",...G()],te=()=>[ln,"none","subgrid",et,Xe],ne=()=>["auto",{span:["full",ln,et,Xe]},ln,et,Xe],ae=()=>[ln,"auto",et,Xe],oe=()=>["auto","min","max","fr",et,Xe],pe=()=>["start","end","center","between","around","evenly","stretch","baseline","center-safe","end-safe"],le=()=>["start","end","center","stretch","center-safe","end-safe"],se=()=>["auto",...G()],Ce=()=>[yn,"auto","full","dvw","dvh","lvw","lvh","svw","svh","min","max","fit",...G()],q=()=>[yn,"screen","full","dvw","lvw","svw","min","max","fit",...G()],Q=()=>[yn,"screen","full","lh","dvh","lvh","svh","min","max","fit",...G()],ie=()=>[e,et,Xe],be=()=>[...O(),Qi,Ua,{position:[et,Xe]}],we=()=>["no-repeat",{repeat:["","x","y","space","round"]}],Re=()=>["auto","cover","contain",md,dd,{size:[et,Xe]}],Ee=()=>[Wi,ti,Yr],Fe=()=>["","none","full",f,et,Xe],Ge=()=>["",vt,ti,Yr],Be=()=>["solid","dashed","dotted","double"],st=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],at=()=>[vt,Wi,Qi,Ua],We=()=>["","none",y,et,Xe],ct=()=>["none",vt,et,Xe],He=()=>["none",vt,et,Xe],$e=()=>[vt,et,Xe],Ke=()=>[yn,"full",...G()];return{cacheSize:500,theme:{animate:["spin","ping","pulse","bounce"],aspect:["video"],blur:[cn],breakpoint:[cn],color:[Qo],container:[cn],"drop-shadow":[cn],ease:["in","out","in-out"],font:[ud],"font-weight":["thin","extralight","light","normal","medium","semibold","bold","extrabold","black"],"inset-shadow":[cn],leading:["none","tight","snug","normal","relaxed","loose"],perspective:["dramatic","near","normal","midrange","distant","none"],radius:[cn],shadow:[cn],spacing:["px",vt],text:[cn],"text-shadow":[cn],tracking:["tighter","tight","normal","wide","wider","widest"]},classGroups:{aspect:[{aspect:["auto","square",yn,Xe,et,E]}],container:["container"],columns:[{columns:[vt,Xe,et,d]}],"break-after":[{"break-after":N()}],"break-before":[{"break-before":N()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],sr:["sr-only","not-sr-only"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:U()}],overflow:[{overflow:z()}],"overflow-x":[{"overflow-x":z()}],"overflow-y":[{"overflow-y":z()}],overscroll:[{overscroll:K()}],"overscroll-x":[{"overscroll-x":K()}],"overscroll-y":[{"overscroll-y":K()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:X()}],"inset-x":[{"inset-x":X()}],"inset-y":[{"inset-y":X()}],start:[{"inset-s":X(),start:X()}],end:[{"inset-e":X(),end:X()}],"inset-bs":[{"inset-bs":X()}],"inset-be":[{"inset-be":X()}],top:[{top:X()}],right:[{right:X()}],bottom:[{bottom:X()}],left:[{left:X()}],visibility:["visible","invisible","collapse"],z:[{z:[ln,"auto",et,Xe]}],basis:[{basis:[yn,"full","auto",d,...G()]}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["nowrap","wrap","wrap-reverse"]}],flex:[{flex:[vt,yn,"auto","initial","none",Xe]}],grow:[{grow:["",vt,et,Xe]}],shrink:[{shrink:["",vt,et,Xe]}],order:[{order:[ln,"first","last","none",et,Xe]}],"grid-cols":[{"grid-cols":te()}],"col-start-end":[{col:ne()}],"col-start":[{"col-start":ae()}],"col-end":[{"col-end":ae()}],"grid-rows":[{"grid-rows":te()}],"row-start-end":[{row:ne()}],"row-start":[{"row-start":ae()}],"row-end":[{"row-end":ae()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":oe()}],"auto-rows":[{"auto-rows":oe()}],gap:[{gap:G()}],"gap-x":[{"gap-x":G()}],"gap-y":[{"gap-y":G()}],"justify-content":[{justify:[...pe(),"normal"]}],"justify-items":[{"justify-items":[...le(),"normal"]}],"justify-self":[{"justify-self":["auto",...le()]}],"align-content":[{content:["normal",...pe()]}],"align-items":[{items:[...le(),{baseline:["","last"]}]}],"align-self":[{self:["auto",...le(),{baseline:["","last"]}]}],"place-content":[{"place-content":pe()}],"place-items":[{"place-items":[...le(),"baseline"]}],"place-self":[{"place-self":["auto",...le()]}],p:[{p:G()}],px:[{px:G()}],py:[{py:G()}],ps:[{ps:G()}],pe:[{pe:G()}],pbs:[{pbs:G()}],pbe:[{pbe:G()}],pt:[{pt:G()}],pr:[{pr:G()}],pb:[{pb:G()}],pl:[{pl:G()}],m:[{m:se()}],mx:[{mx:se()}],my:[{my:se()}],ms:[{ms:se()}],me:[{me:se()}],mbs:[{mbs:se()}],mbe:[{mbe:se()}],mt:[{mt:se()}],mr:[{mr:se()}],mb:[{mb:se()}],ml:[{ml:se()}],"space-x":[{"space-x":G()}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":G()}],"space-y-reverse":["space-y-reverse"],size:[{size:Ce()}],"inline-size":[{inline:["auto",...q()]}],"min-inline-size":[{"min-inline":["auto",...q()]}],"max-inline-size":[{"max-inline":["none",...q()]}],"block-size":[{block:["auto",...Q()]}],"min-block-size":[{"min-block":["auto",...Q()]}],"max-block-size":[{"max-block":["none",...Q()]}],w:[{w:[d,"screen",...Ce()]}],"min-w":[{"min-w":[d,"screen","none",...Ce()]}],"max-w":[{"max-w":[d,"screen","none","prose",{screen:[c]},...Ce()]}],h:[{h:["screen","lh",...Ce()]}],"min-h":[{"min-h":["screen","lh","none",...Ce()]}],"max-h":[{"max-h":["screen","lh",...Ce()]}],"font-size":[{text:["base",r,ti,Yr]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:[n,pd,qi]}],"font-stretch":[{"font-stretch":["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded",Wi,Xe]}],"font-family":[{font:[hd,fd,t]}],"font-features":[{"font-features":[Xe]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:[s,et,Xe]}],"line-clamp":[{"line-clamp":[vt,"none",et,Fa]}],leading:[{leading:[a,...G()]}],"list-image":[{"list-image":["none",et,Xe]}],"list-style-position":[{list:["inside","outside"]}],"list-style-type":[{list:["disc","decimal","none",et,Xe]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"placeholder-color":[{placeholder:ie()}],"text-color":[{text:ie()}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...Be(),"wavy"]}],"text-decoration-thickness":[{decoration:[vt,"from-font","auto",et,Yr]}],"text-decoration-color":[{decoration:ie()}],"underline-offset":[{"underline-offset":[vt,"auto",et,Xe]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:G()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",et,Xe]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],wrap:[{wrap:["break-word","anywhere","normal"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",et,Xe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:be()}],"bg-repeat":[{bg:we()}],"bg-size":[{bg:Re()}],"bg-image":[{bg:["none",{linear:[{to:["t","tr","r","br","b","bl","l","tl"]},ln,et,Xe],radial:["",et,Xe],conic:[ln,et,Xe]},gd,Yo]}],"bg-color":[{bg:ie()}],"gradient-from-pos":[{from:Ee()}],"gradient-via-pos":[{via:Ee()}],"gradient-to-pos":[{to:Ee()}],"gradient-from":[{from:ie()}],"gradient-via":[{via:ie()}],"gradient-to":[{to:ie()}],rounded:[{rounded:Fe()}],"rounded-s":[{"rounded-s":Fe()}],"rounded-e":[{"rounded-e":Fe()}],"rounded-t":[{"rounded-t":Fe()}],"rounded-r":[{"rounded-r":Fe()}],"rounded-b":[{"rounded-b":Fe()}],"rounded-l":[{"rounded-l":Fe()}],"rounded-ss":[{"rounded-ss":Fe()}],"rounded-se":[{"rounded-se":Fe()}],"rounded-ee":[{"rounded-ee":Fe()}],"rounded-es":[{"rounded-es":Fe()}],"rounded-tl":[{"rounded-tl":Fe()}],"rounded-tr":[{"rounded-tr":Fe()}],"rounded-br":[{"rounded-br":Fe()}],"rounded-bl":[{"rounded-bl":Fe()}],"border-w":[{border:Ge()}],"border-w-x":[{"border-x":Ge()}],"border-w-y":[{"border-y":Ge()}],"border-w-s":[{"border-s":Ge()}],"border-w-e":[{"border-e":Ge()}],"border-w-bs":[{"border-bs":Ge()}],"border-w-be":[{"border-be":Ge()}],"border-w-t":[{"border-t":Ge()}],"border-w-r":[{"border-r":Ge()}],"border-w-b":[{"border-b":Ge()}],"border-w-l":[{"border-l":Ge()}],"divide-x":[{"divide-x":Ge()}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":Ge()}],"divide-y-reverse":["divide-y-reverse"],"border-style":[{border:[...Be(),"hidden","none"]}],"divide-style":[{divide:[...Be(),"hidden","none"]}],"border-color":[{border:ie()}],"border-color-x":[{"border-x":ie()}],"border-color-y":[{"border-y":ie()}],"border-color-s":[{"border-s":ie()}],"border-color-e":[{"border-e":ie()}],"border-color-bs":[{"border-bs":ie()}],"border-color-be":[{"border-be":ie()}],"border-color-t":[{"border-t":ie()}],"border-color-r":[{"border-r":ie()}],"border-color-b":[{"border-b":ie()}],"border-color-l":[{"border-l":ie()}],"divide-color":[{divide:ie()}],"outline-style":[{outline:[...Be(),"none","hidden"]}],"outline-offset":[{"outline-offset":[vt,et,Xe]}],"outline-w":[{outline:["",vt,ti,Yr]}],"outline-color":[{outline:ie()}],shadow:[{shadow:["","none",h,_i,Si]}],"shadow-color":[{shadow:ie()}],"inset-shadow":[{"inset-shadow":["none",m,_i,Si]}],"inset-shadow-color":[{"inset-shadow":ie()}],"ring-w":[{ring:Ge()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:ie()}],"ring-offset-w":[{"ring-offset":[vt,Yr]}],"ring-offset-color":[{"ring-offset":ie()}],"inset-ring-w":[{"inset-ring":Ge()}],"inset-ring-color":[{"inset-ring":ie()}],"text-shadow":[{"text-shadow":["none",g,_i,Si]}],"text-shadow-color":[{"text-shadow":ie()}],opacity:[{opacity:[vt,et,Xe]}],"mix-blend":[{"mix-blend":[...st(),"plus-darker","plus-lighter"]}],"bg-blend":[{"bg-blend":st()}],"mask-clip":[{"mask-clip":["border","padding","content","fill","stroke","view"]},"mask-no-clip"],"mask-composite":[{mask:["add","subtract","intersect","exclude"]}],"mask-image-linear-pos":[{"mask-linear":[vt]}],"mask-image-linear-from-pos":[{"mask-linear-from":at()}],"mask-image-linear-to-pos":[{"mask-linear-to":at()}],"mask-image-linear-from-color":[{"mask-linear-from":ie()}],"mask-image-linear-to-color":[{"mask-linear-to":ie()}],"mask-image-t-from-pos":[{"mask-t-from":at()}],"mask-image-t-to-pos":[{"mask-t-to":at()}],"mask-image-t-from-color":[{"mask-t-from":ie()}],"mask-image-t-to-color":[{"mask-t-to":ie()}],"mask-image-r-from-pos":[{"mask-r-from":at()}],"mask-image-r-to-pos":[{"mask-r-to":at()}],"mask-image-r-from-color":[{"mask-r-from":ie()}],"mask-image-r-to-color":[{"mask-r-to":ie()}],"mask-image-b-from-pos":[{"mask-b-from":at()}],"mask-image-b-to-pos":[{"mask-b-to":at()}],"mask-image-b-from-color":[{"mask-b-from":ie()}],"mask-image-b-to-color":[{"mask-b-to":ie()}],"mask-image-l-from-pos":[{"mask-l-from":at()}],"mask-image-l-to-pos":[{"mask-l-to":at()}],"mask-image-l-from-color":[{"mask-l-from":ie()}],"mask-image-l-to-color":[{"mask-l-to":ie()}],"mask-image-x-from-pos":[{"mask-x-from":at()}],"mask-image-x-to-pos":[{"mask-x-to":at()}],"mask-image-x-from-color":[{"mask-x-from":ie()}],"mask-image-x-to-color":[{"mask-x-to":ie()}],"mask-image-y-from-pos":[{"mask-y-from":at()}],"mask-image-y-to-pos":[{"mask-y-to":at()}],"mask-image-y-from-color":[{"mask-y-from":ie()}],"mask-image-y-to-color":[{"mask-y-to":ie()}],"mask-image-radial":[{"mask-radial":[et,Xe]}],"mask-image-radial-from-pos":[{"mask-radial-from":at()}],"mask-image-radial-to-pos":[{"mask-radial-to":at()}],"mask-image-radial-from-color":[{"mask-radial-from":ie()}],"mask-image-radial-to-color":[{"mask-radial-to":ie()}],"mask-image-radial-shape":[{"mask-radial":["circle","ellipse"]}],"mask-image-radial-size":[{"mask-radial":[{closest:["side","corner"],farthest:["side","corner"]}]}],"mask-image-radial-pos":[{"mask-radial-at":O()}],"mask-image-conic-pos":[{"mask-conic":[vt]}],"mask-image-conic-from-pos":[{"mask-conic-from":at()}],"mask-image-conic-to-pos":[{"mask-conic-to":at()}],"mask-image-conic-from-color":[{"mask-conic-from":ie()}],"mask-image-conic-to-color":[{"mask-conic-to":ie()}],"mask-mode":[{mask:["alpha","luminance","match"]}],"mask-origin":[{"mask-origin":["border","padding","content","fill","stroke","view"]}],"mask-position":[{mask:be()}],"mask-repeat":[{mask:we()}],"mask-size":[{mask:Re()}],"mask-type":[{"mask-type":["alpha","luminance"]}],"mask-image":[{mask:["none",et,Xe]}],filter:[{filter:["","none",et,Xe]}],blur:[{blur:We()}],brightness:[{brightness:[vt,et,Xe]}],contrast:[{contrast:[vt,et,Xe]}],"drop-shadow":[{"drop-shadow":["","none",p,_i,Si]}],"drop-shadow-color":[{"drop-shadow":ie()}],grayscale:[{grayscale:["",vt,et,Xe]}],"hue-rotate":[{"hue-rotate":[vt,et,Xe]}],invert:[{invert:["",vt,et,Xe]}],saturate:[{saturate:[vt,et,Xe]}],sepia:[{sepia:["",vt,et,Xe]}],"backdrop-filter":[{"backdrop-filter":["","none",et,Xe]}],"backdrop-blur":[{"backdrop-blur":We()}],"backdrop-brightness":[{"backdrop-brightness":[vt,et,Xe]}],"backdrop-contrast":[{"backdrop-contrast":[vt,et,Xe]}],"backdrop-grayscale":[{"backdrop-grayscale":["",vt,et,Xe]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[vt,et,Xe]}],"backdrop-invert":[{"backdrop-invert":["",vt,et,Xe]}],"backdrop-opacity":[{"backdrop-opacity":[vt,et,Xe]}],"backdrop-saturate":[{"backdrop-saturate":[vt,et,Xe]}],"backdrop-sepia":[{"backdrop-sepia":["",vt,et,Xe]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":G()}],"border-spacing-x":[{"border-spacing-x":G()}],"border-spacing-y":[{"border-spacing-y":G()}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["","all","colors","opacity","shadow","transform","none",et,Xe]}],"transition-behavior":[{transition:["normal","discrete"]}],duration:[{duration:[vt,"initial",et,Xe]}],ease:[{ease:["linear","initial",T,et,Xe]}],delay:[{delay:[vt,et,Xe]}],animate:[{animate:["none",j,et,Xe]}],backface:[{backface:["hidden","visible"]}],perspective:[{perspective:[S,et,Xe]}],"perspective-origin":[{"perspective-origin":U()}],rotate:[{rotate:ct()}],"rotate-x":[{"rotate-x":ct()}],"rotate-y":[{"rotate-y":ct()}],"rotate-z":[{"rotate-z":ct()}],scale:[{scale:He()}],"scale-x":[{"scale-x":He()}],"scale-y":[{"scale-y":He()}],"scale-z":[{"scale-z":He()}],"scale-3d":["scale-3d"],skew:[{skew:$e()}],"skew-x":[{"skew-x":$e()}],"skew-y":[{"skew-y":$e()}],transform:[{transform:[et,Xe,"","none","gpu","cpu"]}],"transform-origin":[{origin:U()}],"transform-style":[{transform:["3d","flat"]}],translate:[{translate:Ke()}],"translate-x":[{"translate-x":Ke()}],"translate-y":[{"translate-y":Ke()}],"translate-z":[{"translate-z":Ke()}],"translate-none":["translate-none"],accent:[{accent:ie()}],appearance:[{appearance:["none","auto"]}],"caret-color":[{caret:ie()}],"color-scheme":[{scheme:["normal","dark","light","light-dark","only-dark","only-light"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",et,Xe]}],"field-sizing":[{"field-sizing":["fixed","content"]}],"pointer-events":[{"pointer-events":["auto","none"]}],resize:[{resize:["none","","y","x"]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":G()}],"scroll-mx":[{"scroll-mx":G()}],"scroll-my":[{"scroll-my":G()}],"scroll-ms":[{"scroll-ms":G()}],"scroll-me":[{"scroll-me":G()}],"scroll-mbs":[{"scroll-mbs":G()}],"scroll-mbe":[{"scroll-mbe":G()}],"scroll-mt":[{"scroll-mt":G()}],"scroll-mr":[{"scroll-mr":G()}],"scroll-mb":[{"scroll-mb":G()}],"scroll-ml":[{"scroll-ml":G()}],"scroll-p":[{"scroll-p":G()}],"scroll-px":[{"scroll-px":G()}],"scroll-py":[{"scroll-py":G()}],"scroll-ps":[{"scroll-ps":G()}],"scroll-pe":[{"scroll-pe":G()}],"scroll-pbs":[{"scroll-pbs":G()}],"scroll-pbe":[{"scroll-pbe":G()}],"scroll-pt":[{"scroll-pt":G()}],"scroll-pr":[{"scroll-pr":G()}],"scroll-pb":[{"scroll-pb":G()}],"scroll-pl":[{"scroll-pl":G()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",et,Xe]}],fill:[{fill:["none",...ie()]}],"stroke-w":[{stroke:[vt,ti,Yr,Fa]}],stroke:[{stroke:["none",...ie()]}],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","inset-bs","inset-be","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pbs","pbe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mbs","mbe","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-x","border-w-y","border-w-s","border-w-e","border-w-bs","border-w-be","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-x","border-color-y","border-color-s","border-color-e","border-color-bs","border-color-be","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],translate:["translate-x","translate-y","translate-none"],"translate-none":["translate","translate-x","translate-y","translate-z"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mbs","scroll-mbe","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pbs","scroll-pbe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]},orderSensitiveModifiers:["*","**","after","backdrop","before","details-content","file","first-letter","first-line","marker","placeholder","selection"]}},k=Pt(vd);function A(...e){return k(tt(e))}var H=1e3,ee=60*H,xe=60*ee,Dt=24*xe,Jt=30*H;function ri(e){if(e==null||e<=0)return null;const t=Date.now()-e;return t<Jt?"just now":t<xe?`${String(Math.floor(t/ee))}m ago`:t<Dt?`${String(Math.floor(t/xe))}h ago`:`${String(Math.floor(t/Dt))}d ago`}var Kw=/^(\d{4})-(\d{2})-(\d{2})/,Ww=/^(\d{2}):(\d{2})(?::(\d{2}))?$/;function qw(e,t){const r=Kw.exec(e);if(r===null)return e;const n=Number(r[1]),s=Number(r[2]),a=Number(r[3]),c=new Date(n,s-1,a);if(Number.isNaN(c.getTime()))return e;try{return c.toLocaleDateString(t)}catch{return e}}function Qw(e,t){const r=Ww.exec(e);if(r===null)return e;const n=new Date(1970,0,1,Number(r[1]),Number(r[2]),r[3]!==void 0?Number(r[3]):0);if(Number.isNaN(n.getTime()))return e;try{return n.toLocaleTimeString(t,{hour:"2-digit",minute:"2-digit"})}catch{return e}}function Yw(e,t){const r=e.includes("T")?e:e.replace(" ","T"),n=new Date(r);if(Number.isNaN(n.getTime()))return e;try{return n.toLocaleString(t,{dateStyle:"medium",timeStyle:"short"})}catch{return e}}function il(e,t,r){return e===""?e:t==="date"?qw(e,r):t==="time"?Qw(e,r):Yw(e,r)}function Xw(e){if(e==null||typeof e!="object")return null;const t=Reflect.get(e,"data");if(t!=null&&typeof t=="object"){const r=Reflect.get(t,"capRouteReason");if(typeof r=="string")return r}return null}function za(e){const t=Xw(e);return t!==null?t==="no-provider"||t==="node-offline":(e instanceof Error?e.message:String(e)).includes("provider not available")}var Jw="rounded-lg border border-border bg-surface overflow-hidden",eE="border-b border-border px-3 sm:px-4 py-1.5 sm:py-2",tE="p-2 sm:p-3 lg:p-4",rE="space-y-3 sm:space-y-4",nE="gap-2 sm:gap-3",iE="px-3 sm:px-4 py-1.5 sm:py-2",sE="grid grid-cols-2 sm:grid-cols-2 lg:grid-cols-4",aE="grid grid-cols-1 lg:grid-cols-2",oE="flex flex-col-reverse md:flex-row",lE="w-full md:w-44 lg:w-52 md:flex-shrink-0 border-b md:border-b-0 md:border-l border-border",cE="text-[10px] sm:text-[11px] font-semibold text-foreground uppercase tracking-wider",uE="text-[11px] sm:text-xs text-foreground",xn="text-[10px] text-foreground-subtle",dE="text-[11px] sm:text-xs font-medium text-foreground",fE="text-base sm:text-lg font-semibold leading-tight text-foreground",hE="inline-flex items-center justify-center gap-1 rounded border border-border bg-surface px-1.5 py-0.5 sm:px-2 sm:py-1 text-[10px] sm:text-[11px] font-medium text-foreground hover:bg-surface-hover transition-colors disabled:opacity-40",mE="inline-flex items-center justify-center gap-1 rounded border border-primary/40 bg-primary/15 px-1.5 py-0.5 sm:px-2 sm:py-1 text-[10px] sm:text-[11px] font-medium text-primary hover:bg-primary/25 transition-colors disabled:opacity-40",gE="inline-flex items-center justify-center gap-1 rounded border border-danger/40 bg-danger/10 px-1.5 py-0.5 sm:px-2 sm:py-1 text-[10px] sm:text-[11px] font-medium text-danger hover:bg-danger/20 transition-colors disabled:opacity-40",pE="inline-flex items-center justify-center gap-1 rounded border border-warning/40 bg-warning/10 px-1.5 py-0.5 sm:px-2 sm:py-1 text-[10px] sm:text-[11px] font-medium text-warning hover:bg-warning/20 transition-colors disabled:opacity-40",vE="w-full rounded border border-border bg-background px-1.5 py-0.5 sm:px-2 sm:py-1 text-[11px] sm:text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none",bE="inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[10px] font-medium transition-colors",yE="border-primary/50 bg-primary/15 text-primary",xE="border-border bg-surface text-foreground-subtle hover:bg-surface-hover";function SE(e,t){for(const r of e.slots)for(const n of r.addons)if(n.id===t)return n;return null}function _E(e,t){return e.models.find(r=>r.id===t)??null}function wE(e,t){return e.models.find(r=>!!r.formats[t])??null}function EE(e,t){const r=new Set((t.configSchema??[]).map(s=>s.key)),n={};for(const[s,a]of Object.entries(e))r.has(s)&&(n[s]=a);return n}function kE(e){const{source:t,target:r,catalog:n,addonIds:s}=e,a=[];for(const c of s){const d=t.defaults[c];if(!d){a.push({addonId:c,outcome:"skip",modelId:null,reason:"no source entry",patch:null});continue}const u=SE(n,c);if(!u){a.push({addonId:c,outcome:"skip",modelId:null,reason:"addon not in target catalog",patch:null});continue}const f=_E(u,d.modelId),h=f!==null&&!!f.formats[r.engine.format];let m,g;if(h)m=d.modelId,g="exact";else{const y=wE(u,r.engine.format);if(!y){a.push({addonId:c,outcome:"skip",modelId:null,reason:"no compatible model for target format",patch:null});continue}m=y.id,g="mapped"}const p={enabled:d.enabled,modelId:m,settings:EE(d.settings,u)};a.push({addonId:c,outcome:g,modelId:m,patch:p})}return a}var bd={idle:{label:"Idle",textColor:"text-foreground-subtle",badgeClass:"border-border bg-surface-hover text-foreground-subtle",dotClass:"bg-gray-400",icon:"PowerOff"},active:{label:"Active",textColor:"text-success",badgeClass:"border-success/40 bg-success/10 text-success",dotClass:"bg-red-500 animate-pulse",icon:"Activity"},watching:{label:"Watching",textColor:"text-foreground-subtle",badgeClass:"border-border bg-surface-hover text-foreground-subtle",dotClass:"bg-emerald-500",icon:"Eye"},"load-shed":{label:"Load-Shed",textColor:"text-amber-500",badgeClass:"border-amber-500/40 bg-amber-500/10 text-amber-500",dotClass:"bg-amber-500",icon:"AlertTriangle"},paused:{label:"Paused",textColor:"text-gray-400",badgeClass:"border-gray-500/40 bg-gray-500/10 text-gray-400",dotClass:"bg-gray-400",icon:"PauseCircle"}};function yd(e){return bd[e]??bd.watching}function Sn(e,t){if(typeof globalThis>"u")return(0,l.createContext)(t);const r=globalThis.__camstackSharedContexts,n=r??new Map;r||(globalThis.__camstackSharedContexts=n);const s=n.get(e);if(s)return s;const a=(0,l.createContext)(t);return n.set(e,a),a}var TE="FEDERATION_DEBUG",xd=(function(e){return e[e.UNKNOWN=1]="UNKNOWN",e[e.CALCULATED=2]="CALCULATED",e[e.NO_USE=0]="NO_USE",e})({}),_g=!0;function CE(){return _g}function IE(){try{if(CE()&&window.localStorage)return!!localStorage.getItem(TE)}catch{return!1}return!1}function Sd(){return typeof process<"u"&&_&&_.FEDERATION_DEBUG?!!_.FEDERATION_DEBUG:typeof FEDERATION_DEBUG<"u"&&FEDERATION_DEBUG?!0:IE()}var PE="[ Federation Runtime ]",wg=function(...e){return e.length?e.reduce((t,r)=>r?t?`${t}:${r}`:r:t,""):""},_d=(e,t)=>{if("getPublicPath"in e){let r;return e.getPublicPath.startsWith("function")?r=new Function("return "+e.getPublicPath)()():r=new Function(e.getPublicPath)(),`${r}${t}`}else return"publicPath"in e?`${e.publicPath}${t}`:(console.warn("Cannot get resource URL. If in debug mode, please ignore.",e,t),"")},Eg=e=>{console.warn(`${PE}: ${e}`)};function kg(e){try{return JSON.stringify(e,null,2)}catch{return""}}var wd=(e,t)=>{if(!e)return t;const n=(s=>{if(s===".")return"";if(s.startsWith("./"))return s.replace("./","");if(s.startsWith("/")){const a=s.slice(1);return a.endsWith("/")?a.slice(0,-1):a}return s})(e);return n?n.endsWith("/")?`${n}${t}`:`${n}/${t}`:t};function AE(e){return e.replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/")}function jE(e,t={}){const{remotes:r={},overrides:n={},version:s}=t;let a;const c=()=>"publicPath"in e.metaData?(e.metaData.publicPath==="auto"||e.metaData.publicPath==="")&&s?AE(s):e.metaData.publicPath:e.metaData.getPublicPath,d=Object.keys(n);let u={};Object.keys(r).length||(u=e.remotes?.reduce((j,N)=>{let O;const U=N.federationContainerName;return d.includes(U)?O=n[U]:"version"in N?O=N.version:O=N.entry,j[U]={matchedVersion:O},j},{})||{}),Object.keys(r).forEach(j=>u[j]={matchedVersion:d.includes(j)?n[j]:r[j]});const{remoteEntry:{path:f,name:h,type:m},types:g={path:"",name:"",zip:"",api:""},buildInfo:{buildVersion:p},globalName:y,ssrRemoteEntry:S}=e.metaData,{exposes:E}=e;let T={version:s||"",buildVersion:p,globalName:y,remoteEntry:wd(f,h),remoteEntryType:m,remoteTypes:wd(g.path,g.name),remoteTypesZip:g.zip||"",remoteTypesAPI:g.api||"",remotesInfo:u,shared:e?.shared.map(j=>({assets:j.assets,sharedName:j.name,version:j.version,usedExports:j.referenceExports||[]})),modules:E?.map(j=>({moduleName:j.name,modulePath:j.path,assets:j.assets}))};if("publicPath"in e.metaData?(a={...T,publicPath:c()},typeof e.metaData.ssrPublicPath=="string"&&(a.ssrPublicPath=e.metaData.ssrPublicPath)):a={...T,getPublicPath:c()},S){const j=wd(S.path,S.name);a.ssrRemoteEntry=j,a.ssrRemoteEntryType=S.type||"commonjs-module"}return a}function Tg(e){return!!("remoteEntry"in e&&e.remoteEntry.includes(".json"))}var NE="[ Module Federation ]",Ga=console,DE=["logger.ts","logger.js","captureStackTrace","Logger.emit","Logger.log","Logger.info","Logger.warn","Logger.error","Logger.debug"];function ME(){try{const e=new Error().stack;if(!e)return;const[,...t]=e.split(`
95
+ `),r=t.filter(n=>!DE.some(s=>n.includes(s)));return r.length?`Stack trace:
96
+ ${r.slice(0,5).join(`
97
+ `)}`:void 0}catch{return}}var Cg=class{constructor(e,t=Ga){this.prefix=e,this.delegate=t??Ga}setPrefix(e){this.prefix=e}setDelegate(e){this.delegate=e??Ga}emit(e,t){const r=this.delegate,n=Sd()?ME():void 0,s=n?[...t,n]:t,a=(()=>{switch(e){case"log":return["log","info"];case"info":return["info","log"];case"warn":return["warn","info","log"];case"error":return["error","warn","log"];default:return["debug","log"]}})();for(const c of a){const d=r[c];if(typeof d=="function"){d.call(r,this.prefix,...s);return}}for(const c of a){const d=Ga[c];if(typeof d=="function"){d.call(Ga,this.prefix,...s);return}}}log(...e){this.emit("log",e)}warn(...e){this.emit("warn",e)}error(...e){this.emit("error",e)}success(...e){this.emit("info",e)}info(...e){this.emit("info",e)}ready(...e){this.emit("info",e)}debug(...e){Sd()&&this.emit("debug",e)}};function $E(e){return new Cg(e)}function RE(e){const t=new Cg(e);return Object.defineProperty(t,"__mf_infrastructure_logger__",{value:!0,enumerable:!1,configurable:!1}),t}RE(NE);async function Ig(e,t){try{return await e()}catch(r){Eg(r);return}}function Ed(e,t){const r=/^(https?:)?\/\//i;return e.replace(r,"").replace(/\/$/,"")===t.replace(r,"").replace(/\/$/,"")}function Pg(e){let t=null,r=!0,n=2e4,s;const a=document.getElementsByTagName("script");for(let f=0;f<a.length;f++){const h=a[f],m=h.getAttribute("src");if(m&&Ed(m,e.url)){t=h,r=!1;break}}if(!t){const f=e.attrs;t=document.createElement("script"),t.type=f?.type==="module"?"module":"text/javascript";let h;e.createScriptHook&&(h=e.createScriptHook(e.url,e.attrs),h instanceof HTMLScriptElement?t=h:typeof h=="object"&&("script"in h&&h.script&&(t=h.script),"timeout"in h&&h.timeout&&(n=h.timeout))),t.src||(t.src=e.url),f&&!h&&Object.keys(f).forEach(m=>{t&&(m==="async"||m==="defer"?t[m]=f[m]:t.getAttribute(m)||t.setAttribute(m,f[m]))})}let c=null;const d=typeof window<"u"?f=>{if(f.filename&&Ed(f.filename,e.url)){const h=new Error(`ScriptExecutionError: Script "${e.url}" loaded but threw a runtime error during execution: ${f.message} (${f.filename}:${f.lineno}:${f.colno})`);h.name="ScriptExecutionError",c=h}}:null;d&&window.addEventListener("error",d);const u=async(f,h)=>{clearTimeout(s),d&&window.removeEventListener("error",d);const m=()=>{if(h?.type==="error"){const g=new Error(h?.isTimeout?`ScriptNetworkError: Script "${e.url}" timed out.`:`ScriptNetworkError: Failed to load script "${e.url}" - the script URL is unreachable or the server returned an error (network failure, 404, CORS, etc.)`);g.name="ScriptNetworkError",e?.onErrorCallback&&e?.onErrorCallback(g)}else c?e?.onErrorCallback&&e?.onErrorCallback(c):e?.cb&&e?.cb()};if(t&&(t.onerror=null,t.onload=null,Ig(()=>{const{needDeleteScript:g=!0}=e;g&&t?.parentNode&&t.parentNode.removeChild(t)}),f&&typeof f=="function")){const g=f(h);if(g instanceof Promise){const p=await g;return m(),p}return m(),g}m()};return t.onerror=u.bind(null,t.onerror),t.onload=u.bind(null,t.onload),s=setTimeout(()=>{u(null,{type:"error",isTimeout:!0})},n),{script:t,needAttach:r}}function kd(e){let t=null,r=!0;const n=document.getElementsByTagName("link");for(let a=0;a<n.length;a++){const c=n[a],d=c.getAttribute("href"),u=c.getAttribute("rel");if(d&&Ed(d,e.url)&&u===e.attrs.rel){t=c,r=!1;break}}if(!t){t=document.createElement("link"),t.setAttribute("href",e.url);let a;const c=e.attrs;e.createLinkHook&&(a=e.createLinkHook(e.url,c),a instanceof HTMLLinkElement&&(t=a)),c&&!a&&Object.keys(c).forEach(d=>{t&&!t.getAttribute(d)&&t.setAttribute(d,c[d])})}const s=(a,c)=>{const d=()=>{c?.type==="error"?e?.onErrorCallback&&e?.onErrorCallback(c):e?.cb&&e?.cb()};if(t&&(t.onerror=null,t.onload=null,Ig(()=>{const{needDeleteLink:u=!0}=e;u&&t?.parentNode&&t.parentNode.removeChild(t)}),a)){const u=a(c);return d(),u}d()};return t.onerror=s.bind(null,t.onerror),t.onload=s.bind(null,t.onload),{link:t,needAttach:r}}function LE(e,t){const{attrs:r={},createScriptHook:n}=t;return new Promise((s,a)=>{const{script:c,needAttach:d}=Pg({url:e,cb:s,onErrorCallback:a,attrs:{fetchpriority:"high",...r},createScriptHook:n,needDeleteScript:!0});d&&document.head.appendChild(c)})}var OE=e=>`View the docs to see how to solve: https://module-federation.io/guide/troubleshooting/${e.split("-")[0].toLowerCase()}#${e.toLowerCase()}`,Ag=(e,t,r,n)=>{const s=[`${[t[e]]} #${e}`];return r&&s.push(`args: ${JSON.stringify(r)}`),s.push(OE(e)),n&&s.push(`Original Error Message:
98
+ ${n}`),s.join(`
99
+ `)};function FE(e,t,r,n,s,a){return n(Ag(e,t,r,s))}var Ei="[ Federation Runtime ]",Td=$E(Ei);function Fr(e,t,r,n,s){e||(r!==void 0?er(t,r,n,void 0):er(t))}function er(e,t,r,n,s){if(t!==void 0)return FE(e,t,r??{},c=>{throw new Error(`${Ei}: ${c}`)},n);const a=e;throw a instanceof Error?(a.message.startsWith(Ei)||(a.message=`${Ei}: ${a.message}`),a):new Error(`${Ei}: ${a}`)}function Cd(e){e instanceof Error&&(e.message.startsWith(Ei)||(e.message=`${Ei}: ${e.message}`)),Td.warn(e)}function UE(e,t){return e.findIndex(r=>r===t)===-1&&e.push(t),e}function Za(e){return"version"in e&&e.version?`${e.name}:${e.version}`:"entry"in e&&e.entry?`${e.name}:${e.entry}`:`${e.name}`}function Id(e){return typeof e.entry<"u"}function jg(e){return!e.entry.includes(".json")}function Pd(e){return e&&typeof e=="object"}var BE=Object.prototype.toString;function zE(e){return BE.call(e)==="[object Object]"}function Ng(e){return Array.isArray(e)?e:[e]}function Dg(e){const t={url:"",type:"global",globalName:""};return"remoteEntry"in e?{url:e.remoteEntry,type:e.remoteEntryType,globalName:e.globalName}:t}var GE=(e,t)=>{let r;return e.endsWith("/")?r=e.slice(0,-1):r=e,t.startsWith(".")&&(t=t.slice(1)),r=r+t,r},ur=typeof globalThis=="object"?globalThis:window,dn=(()=>{try{return document.defaultView}catch{return ur}})(),Va=dn;function sl(e,t,r){Object.defineProperty(e,t,{value:r,configurable:!1,writable:!0})}function al(e,t){return Object.hasOwnProperty.call(e,t)}al(ur,"__GLOBAL_LOADING_REMOTE_ENTRY__")||sl(ur,"__GLOBAL_LOADING_REMOTE_ENTRY__",{});var Yi=ur.__GLOBAL_LOADING_REMOTE_ENTRY__;function Mg(e){al(e,"__VMOK__")&&!al(e,"__FEDERATION__")&&sl(e,"__FEDERATION__",e.__VMOK__),al(e,"__FEDERATION__")||(sl(e,"__FEDERATION__",{__GLOBAL_PLUGIN__:[],__INSTANCES__:[],moduleInfo:{},__SHARE__:{},__MANIFEST_LOADING__:{},__PRELOADED_MAP__:new Map}),sl(e,"__VMOK__",e.__FEDERATION__)),e.__FEDERATION__.__GLOBAL_PLUGIN__??=[],e.__FEDERATION__.__INSTANCES__??=[],e.__FEDERATION__.moduleInfo??={},e.__FEDERATION__.__SHARE__??={},e.__FEDERATION__.__MANIFEST_LOADING__??={},e.__FEDERATION__.__PRELOADED_MAP__??=new Map}Mg(ur),Mg(dn);function ZE(e){ur.__FEDERATION__.__INSTANCES__.push(e)}function VE(){return ur.__FEDERATION__.__DEBUG_CONSTRUCTOR__}function HE(e,t=Sd()){t&&(ur.__FEDERATION__.__DEBUG_CONSTRUCTOR__=e,ur.__FEDERATION__.__DEBUG_CONSTRUCTOR_VERSION__="2.4.0")}function Xi(e,t){if(typeof t=="string"){if(e[t])return{value:e[t],key:t};{const r=Object.keys(e);for(const n of r){const[s,a]=n.split(":"),c=`${s}:${t}`,d=e[c];if(d)return{value:d,key:c}}return{value:void 0,key:t}}}else er(`getInfoWithoutType: "key" must be a string, got ${typeof t} (${JSON.stringify(t)}).`)}var $g=()=>dn.__FEDERATION__.moduleInfo,KE=(e,t)=>{const r=Xi(t,Za(e)).value;if(r&&!r.version&&"version"in e&&e.version&&(r.version=e.version),r)return r;if("version"in e&&e.version){const{version:n,...s}=e,a=Za(s),c=Xi(dn.__FEDERATION__.moduleInfo,a).value;if(c?.version===n)return c}},ol=e=>KE(e,dn.__FEDERATION__.moduleInfo),Rg=(e,t)=>{const r=Za(e);return dn.__FEDERATION__.moduleInfo[r]=t,dn.__FEDERATION__.moduleInfo},WE=e=>(dn.__FEDERATION__.moduleInfo={...dn.__FEDERATION__.moduleInfo,...e},()=>{const t=Object.keys(e);for(const r of t)delete dn.__FEDERATION__.moduleInfo[r]}),Lg=(e,t)=>{const r=t||`__FEDERATION_${e}:custom__`;return{remoteEntryKey:r,entryExports:ur[r]}},qE=()=>dn.__FEDERATION__.__GLOBAL_PLUGIN__,QE=e=>ur.__FEDERATION__.__PRELOADED_MAP__.get(e),YE=e=>ur.__FEDERATION__.__PRELOADED_MAP__.set(e,!0),Og="[0-9A-Za-z-]+",Ad=`(?:\\+(${Og}(?:\\.${Og})*))`,Ha="0|[1-9]\\d*",ll="[0-9]+",Fg="\\d*[a-zA-Z-][a-zA-Z0-9-]*",Ug=`(?:${ll}|${Fg})`,XE=`(?:-?(${Ug}(?:\\.${Ug})*))`,Bg=`(?:${Ha}|${Fg})`,zg=`(?:-(${Bg}(?:\\.${Bg})*))`,jd=`${Ha}|x|X|\\*`,Ji=`[v=\\s]*(${jd})(?:\\.(${jd})(?:\\.(${jd})(?:${zg})?${Ad}?)?)?`,JE=`^\\s*(${Ji})\\s+-\\s+(${Ji})\\s*$`,ek=`[v=\\s]*${`(${ll})\\.(${ll})\\.(${ll})`}${XE}?${Ad}?`,Nd="((?:<|>)?=?)",tk=`(\\s*)${Nd}\\s*(${ek}|${Ji})`,Gg="(?:~>?)",rk=`(\\s*)${Gg}\\s+`,Zg="(?:\\^)",nk=`(\\s*)${Zg}\\s+`,ik="(<|>)?=?\\s*\\*",sk=`^${Zg}${Ji}$`,ak=`v?${`(${Ha})\\.(${Ha})\\.(${Ha})`}${zg}?${Ad}?`,ok=`^${Gg}${Ji}$`,lk=`^${Nd}\\s*${Ji}$`,ck=`^${Nd}\\s*(${ak})$|^$`,uk="^\\s*>=\\s*0.0.0\\s*$";function _n(e){return new RegExp(e)}function Pr(e){return!e||e.toLowerCase()==="x"||e==="*"}function Vg(...e){return t=>e.reduce((r,n)=>n(r),t)}function Hg(e){return e.match(_n(ck))}function Kg(e,t,r,n){const s=`${e}.${t}.${r}`;return n?`${s}-${n}`:s}function dk(e){return e.replace(_n(JE),(t,r,n,s,a,c,d,u,f,h,m,g)=>(Pr(n)?r="":Pr(s)?r=`>=${n}.0.0`:Pr(a)?r=`>=${n}.${s}.0`:r=`>=${r}`,Pr(f)?u="":Pr(h)?u=`<${Number(f)+1}.0.0-0`:Pr(m)?u=`<${f}.${Number(h)+1}.0-0`:g?u=`<=${f}.${h}.${m}-${g}`:u=`<=${u}`,`${r} ${u}`.trim()))}function fk(e){return e.replace(_n(tk),"$1$2$3")}function hk(e){return e.replace(_n(rk),"$1~")}function mk(e){return e.replace(_n(nk),"$1^")}function gk(e){return e.trim().split(/\s+/).map(t=>t.replace(_n(sk),(r,n,s,a,c)=>Pr(n)?"":Pr(s)?`>=${n}.0.0 <${Number(n)+1}.0.0-0`:Pr(a)?n==="0"?`>=${n}.${s}.0 <${n}.${Number(s)+1}.0-0`:`>=${n}.${s}.0 <${Number(n)+1}.0.0-0`:c?n==="0"?s==="0"?`>=${n}.${s}.${a}-${c} <${n}.${s}.${Number(a)+1}-0`:`>=${n}.${s}.${a}-${c} <${n}.${Number(s)+1}.0-0`:`>=${n}.${s}.${a}-${c} <${Number(n)+1}.0.0-0`:n==="0"?s==="0"?`>=${n}.${s}.${a} <${n}.${s}.${Number(a)+1}-0`:`>=${n}.${s}.${a} <${n}.${Number(s)+1}.0-0`:`>=${n}.${s}.${a} <${Number(n)+1}.0.0-0`)).join(" ")}function pk(e){return e.trim().split(/\s+/).map(t=>t.replace(_n(ok),(r,n,s,a,c)=>Pr(n)?"":Pr(s)?`>=${n}.0.0 <${Number(n)+1}.0.0-0`:Pr(a)?`>=${n}.${s}.0 <${n}.${Number(s)+1}.0-0`:c?`>=${n}.${s}.${a}-${c} <${n}.${Number(s)+1}.0-0`:`>=${n}.${s}.${a} <${n}.${Number(s)+1}.0-0`)).join(" ")}function vk(e){return e.split(/\s+/).map(t=>t.trim().replace(_n(lk),(r,n,s,a,c,d)=>{const u=Pr(s),f=u||Pr(a),h=f||Pr(c);return n==="="&&h&&(n=""),d="",u?n===">"||n==="<"?"<0.0.0-0":"*":n&&h?(f&&(a=0),c=0,n===">"?(n=">=",f?(s=Number(s)+1,a=0,c=0):(a=Number(a)+1,c=0)):n==="<="&&(n="<",f?s=Number(s)+1:a=Number(a)+1),n==="<"&&(d="-0"),`${n+s}.${a}.${c}${d}`):f?`>=${s}.0.0${d} <${Number(s)+1}.0.0-0`:h?`>=${s}.${a}.0${d} <${s}.${Number(a)+1}.0-0`:r})).join(" ")}function bk(e){return e.trim().replace(_n(ik),"")}function yk(e){return e.trim().replace(_n(uk),"")}function cl(e,t){return e=Number(e)||e,t=Number(t)||t,e>t?1:e===t?0:-1}function xk(e,t){const{preRelease:r}=e,{preRelease:n}=t;if(r===void 0&&n)return 1;if(r&&n===void 0)return-1;if(r===void 0&&n===void 0)return 0;for(let s=0,a=r.length;s<=a;s++){const c=r[s],d=n[s];if(c!==d)return c===void 0&&d===void 0?0:c?d?cl(c,d):-1:1}return 0}function ul(e,t){return cl(e.major,t.major)||cl(e.minor,t.minor)||cl(e.patch,t.patch)||xk(e,t)}function Dd(e,t){return e.version===t.version}function Sk(e,t){switch(e.operator){case"":case"=":return Dd(e,t);case">":return ul(e,t)<0;case">=":return Dd(e,t)||ul(e,t)<0;case"<":return ul(e,t)>0;case"<=":return Dd(e,t)||ul(e,t)>0;case void 0:return!0;default:return!1}}function _k(e){return Vg(gk,pk,vk,bk)(e)}function wk(e){return Vg(dk,fk,hk,mk)(e.trim()).split(/\s+/).join(" ")}function Ka(e,t){if(!e)return!1;const r=Hg(e);if(!r)return!1;const[,n,,s,a,c,d]=r,u={operator:n,version:Kg(s,a,c,d),major:s,minor:a,patch:c,preRelease:d?.split(".")},f=t.split("||");for(const h of f){const m=h.trim();if(!m||m==="*"||m==="x")return!0;try{const g=wk(m);if(!g.trim())return!0;const p=g.split(" ").map(E=>_k(E)).join(" ");if(!p.trim())return!0;const y=p.split(/\s+/).map(E=>yk(E)).filter(Boolean);if(y.length===0)continue;let S=!0;for(const E of y){const T=Hg(E);if(!T){S=!1;break}const[,j,,N,O,U,z]=T;if(!Sk({operator:j,version:Kg(N,O,U,z),major:N,minor:O,patch:U,preRelease:z?.split(".")},u)){S=!1;break}}if(S)return!0}catch(g){console.error(`[semver] Error processing range part "${m}":`,g);continue}}return!1}var dl="default",Ek="global";function kk(e,t,r,n){let s;return"get"in e?s=e.get:"lib"in e?s=()=>Promise.resolve(e.lib):s=()=>Promise.resolve(()=>{er(`Cannot get shared "${r}" from "${t}": neither "get" nor "lib" is provided in the share config.`)}),e.shareConfig?.eager&&e.treeShaking?.mode&&er(`Invalid shared config for "${r}" from "${t}": cannot use both "eager: true" and "treeShaking.mode" simultaneously. Choose one strategy.`),{deps:[],useIn:[],from:t,loading:null,...e,shareConfig:{requiredVersion:`^${e.version}`,singleton:!1,eager:!1,strictVersion:!1,...e.shareConfig},get:s,loaded:e?.loaded||"lib"in e?!0:void 0,version:e.version??"0",scope:Array.isArray(e.scope)?e.scope:[e.scope??"default"],strategy:(e.strategy??n)||"version-first",treeShaking:e.treeShaking?{...e.treeShaking,mode:e.treeShaking.mode??"server-calc",status:e.treeShaking.status??xd.UNKNOWN,useIn:[]}:void 0}}function Wg(e,t){const r=t.shared||{},n=t.name,s=Object.keys(r).reduce((c,d)=>{const u=Ng(r[d]);return c[d]=c[d]||[],u.forEach(f=>{c[d].push(kk(f,n,d,t.shareStrategy))}),c},{}),a={...e.shared};return Object.keys(s).forEach(c=>{a[c]?s[c].forEach(d=>{a[c].find(u=>u.version===d.version)||a[c].push(d)}):a[c]=s[c]}),{allShareInfos:a,newShareInfos:s}}function Wa(e,t){if(!e)return!1;const{status:r,mode:n}=e;return r===xd.NO_USE?!1:r===xd.CALCULATED?!0:n==="runtime-infer"?t?Ck(e,t):!0:!1}function ki(e,t){const r=n=>{if(!Number.isNaN(Number(n))){const s=n.split(".");let a=n;for(let c=0;c<3-s.length;c++)a+=".0";return a}return n};return!!Ka(r(e),`<=${r(t)}`)}var qa=(e,t)=>{const r=t||function(n,s){return ki(n,s)};return Object.keys(e).reduce((n,s)=>!n||r(n,s)||n==="0"?s:n,0)},fl=e=>!!e.loaded||typeof e.lib=="function",Tk=e=>!!e.loading,Ck=(e,t)=>{if(!e||!t)return!1;const{usedExports:r}=e;return r?!!t.every(n=>r.includes(n)):!1};function Ik(e,t,r,n){const s=e[t][r];let a="",c=Wa(n);const d=function(u,f){return c?s[u].treeShaking?s[f].treeShaking?!fl(s[u].treeShaking)&&ki(u,f):!1:!0:!fl(s[u])&&ki(u,f)};if(c){if(a=qa(e[t][r],d),a)return{version:a,useTreesShaking:c};c=!1}return{version:qa(e[t][r],d),useTreesShaking:c}}var es=e=>fl(e)||Tk(e);function Pk(e,t,r,n){const s=e[t][r];let a="",c=Wa(n);const d=function(u,f){if(c){if(!s[u].treeShaking)return!0;if(!s[f].treeShaking)return!1;if(es(s[f].treeShaking))return es(s[u].treeShaking)?!!ki(u,f):!0;if(es(s[u].treeShaking))return!1}return es(s[f])?es(s[u])?!!ki(u,f):!0:es(s[u])?!1:ki(u,f)};if(c){if(a=qa(e[t][r],d),a)return{version:a,useTreesShaking:c};c=!1}return{version:qa(e[t][r],d),useTreesShaking:c}}function Ak(e){return e==="loaded-first"?Pk:Ik}function hl(e,t,r,n){if(!e)return;const{shareConfig:s,scope:a=dl,strategy:c,treeShaking:d}=r,u=Array.isArray(a)?a:[a];for(const f of u)if(s&&e[f]&&e[f][t]){const{requiredVersion:h}=s,{version:m,useTreesShaking:g}=Ak(c)(e,f,t,d),p=()=>{const S=e[f][t][m];if(s.singleton){if(typeof h=="string"&&!Ka(m,h)){const E=`Version ${m} from ${m&&S.from} of shared singleton module ${t} does not satisfy the requirement of ${r.from} which needs ${h})`;s.strictVersion?er(E):Cd(E)}return{shared:S,useTreesShaking:g}}else{if(h===!1||h==="*")return{shared:S,useTreesShaking:g};if(Ka(m,h))return{shared:S,useTreesShaking:g};const E=Wa(d);if(E){for(const[T,j]of Object.entries(e[f][t]))if(Wa(j.treeShaking,d?.usedExports)&&Ka(T,h))return{shared:j,useTreesShaking:E}}for(const[T,j]of Object.entries(e[f][t]))if(Ka(T,h))return{shared:j,useTreesShaking:!1}}},y={shareScopeMap:e,scope:f,pkgName:t,version:m,GlobalFederation:Va.__FEDERATION__,shareInfo:r,resolver:p};return(n.emit(y)||y).resolver()}}function qg(){return Va.__FEDERATION__.__SHARE__}function Qg(e){const{pkgName:t,extraOptions:r,shareInfos:n}=e,s=u=>{if(!u)return;const f={};return u.forEach(m=>{f[m.version]=m}),f[qa(f,function(m,g){return!fl(f[m])&&ki(m,g)})]},a=r?.resolver??s,c=u=>u!==null&&typeof u=="object"&&!Array.isArray(u),d=(...u)=>{const f={};for(const h of u)if(h)for(const[m,g]of Object.entries(h)){const p=f[m];c(p)&&c(g)?f[m]=d(p,g):g!==void 0&&(f[m]=g)}return f};return d(a(n[t]),r?.customShareInfo)}var ts=(e,t)=>{e.useIn||(e.useIn=[]),UE(e.useIn,t)};function ml(e,t){return t&&e.treeShaking?e.treeShaking:e}function jk(e,t){for(const r of e){const n=t.startsWith(r.name);let s=t.replace(r.name,"");if(n){if(s.startsWith("/")){const d=r.name;return s=`.${s}`,{pkgNameOrAlias:d,expose:s,remote:r}}else if(s==="")return{pkgNameOrAlias:r.name,expose:".",remote:r}}const a=r.alias&&t.startsWith(r.alias);let c=r.alias&&t.replace(r.alias,"");if(r.alias&&a){if(c&&c.startsWith("/")){const d=r.alias;return c=`.${c}`,{pkgNameOrAlias:d,expose:c,remote:r}}else if(c==="")return{pkgNameOrAlias:r.alias,expose:".",remote:r}}}}function Nk(e,t){for(const r of e)if(t===r.name||r.alias&&t===r.alias)return r}var Yg="RUNTIME-001",Xg="RUNTIME-002",Jg="RUNTIME-003",ep="RUNTIME-004",tp="RUNTIME-005",Md="RUNTIME-006",rp="RUNTIME-007",np="RUNTIME-008",$d="RUNTIME-009",ip="RUNTIME-010",sp="RUNTIME-011",Dk="RUNTIME-012",Ur={[Yg]:"Failed to get remoteEntry exports.",[Xg]:'The remote entry interface does not contain "init"',[Jg]:"Failed to get manifest.",[ep]:"Failed to locate remote.",[tp]:"Invalid loadShareSync function call from bundler runtime",[Md]:"Invalid loadShareSync function call from runtime",[rp]:"Failed to get remote snapshot.",[np]:"Failed to load script resources.",[$d]:"Please call createInstance first.",[ip]:'The name option cannot be changed after initialization. If you want to create a new instance with a different name, please use "createInstance" api.',[sp]:"The remoteEntry URL is missing from the remote snapshot.",[Dk]:'The getter for the shared module is not a function. This may be caused by setting "shared.import: false" without the host providing the corresponding lib.'};({...Ur});var ap=".then(callbacks[0]).catch(callbacks[1])";async function Mk({entry:e,remoteEntryExports:t}){return new Promise((r,n)=>{try{t?r(t):typeof FEDERATION_ALLOW_NEW_FUNCTION<"u"?new Function("callbacks",`import("${e}")${ap}`)([r,n]):import(e).then(r).catch(n)}catch(s){er(`Failed to load ESM entry from "${e}". ${s instanceof Error?s.message:String(s)}`)}})}async function $k({entry:e,remoteEntryExports:t}){return new Promise((r,n)=>{try{t?r(t):typeof __system_context__>"u"?System.import(e).then(r).catch(n):new Function("callbacks",`System.import("${e}")${ap}`)([r,n])}catch(s){er(`Failed to load SystemJS entry from "${e}". ${s instanceof Error?s.message:String(s)}`)}})}function Rk(e,t,r){const{remoteEntryKey:n,entryExports:s}=Lg(e,t);return s||er(Yg,Ur,{remoteName:e,remoteEntryUrl:r,remoteEntryKey:n}),s}async function Lk({name:e,globalName:t,entry:r,remoteInfo:n,loaderHook:s,getEntryUrl:a}){const{entryExports:c}=Lg(e,t);if(c)return c;const d=a?a(r):r;return LE(d,{attrs:{},createScriptHook:(u,f)=>{const h=s.lifecycle.createScript.emit({url:u,attrs:f,remoteInfo:n});if(h&&(h instanceof HTMLScriptElement||"script"in h||"timeout"in h))return h}}).then(()=>Rk(e,t,r),u=>{const f=u instanceof Error?u.message:String(u);er(np,Ur,{remoteName:e,resourceUrl:d},f)})}async function Ok({remoteInfo:e,remoteEntryExports:t,loaderHook:r,getEntryUrl:n}){const{entry:s,entryGlobalName:a,name:c,type:d}=e;switch(d){case"esm":case"module":return Mk({entry:s,remoteEntryExports:t});case"system":return $k({entry:s,remoteEntryExports:t});default:return Lk({entry:s,globalName:a,name:c,remoteInfo:e,loaderHook:r,getEntryUrl:n})}}function Rd(e){const{entry:t,name:r}=e;return wg(r,t)}async function gl(e){const{origin:t,remoteEntryExports:r,remoteInfo:n,getEntryUrl:s,_inErrorHandling:a=!1}=e,c=Rd(n);if(r)return r;if(!Yi[c]){const d=t.remoteHandler.hooks.lifecycle.loadEntry,u=t.loaderHook;Yi[c]=d.emit({loaderHook:u,remoteInfo:n,remoteEntryExports:r}).then(f=>f||Ok({remoteInfo:n,remoteEntryExports:r,loaderHook:u,getEntryUrl:s})).catch(async f=>{const h=Rd(n),m=f instanceof Error&&f.message.includes("ScriptExecutionError");if(f instanceof Error&&f.message.includes("RUNTIME-008")&&!m&&!a){const g=y=>gl({...y,_inErrorHandling:!0}),p=await t.loaderHook.lifecycle.loadEntryError.emit({getRemoteEntry:g,origin:t,remoteInfo:n,remoteEntryExports:r,globalLoading:Yi,uniqueKey:h});if(p)return p}throw f})}return Yi[c]}function pl(e){return{...e,entry:"entry"in e?e.entry:"",type:e.type||"global",entryGlobalName:e.entryGlobalName||e.name,shareScope:e.shareScope||"default"}}function Fk(){return typeof FEDERATION_BUILD_IDENTIFIER<"u"?FEDERATION_BUILD_IDENTIFIER:""}function Uk(e,t){const r=qE(),n=[t.hooks,t.remoteHandler.hooks,t.sharedHandler.hooks,t.snapshotHandler.hooks,t.loaderHook,t.bridgeHook];return r.length>0&&r.forEach(s=>{e?.find(a=>a.name!==s.name)&&e.push(s)}),e&&e.length>0&&e.forEach(s=>{n.forEach(a=>{a.applyPlugin(s,t)})}),e}function Bk(e){return{name:e.name,alias:e.alias,entry:"entry"in e?e.entry:void 0,version:"version"in e?e.version:void 0,type:e.type,entryGlobalName:e.entryGlobalName,shareScope:e.shareScope}}function rs(e){const t={};for(const[r,n]of Object.entries(e.shared)){const s=n[0];s&&(t[r]={version:s.version,singleton:s.shareConfig?.singleton,requiredVersion:s.shareConfig?.requiredVersion===!1?!1:s.shareConfig?.requiredVersion,eager:s.eager,strictVersion:s.shareConfig?.strictVersion})}return{project:{name:e.name,mfRole:e.remotes?.length>0?"host":"unknown"},mfConfig:{name:e.name,remotes:e.remotes?.map(Bk)??[],shared:t}}}function op(e){return{resourceCategory:"sync",share:!0,depsRemote:!0,...e}}function zk(e,t){return t.map(r=>{const n=Nk(e,r.nameOrAlias);return Fr(n,`Unable to preload ${r.nameOrAlias} as it is not included in ${!n&&kg({remoteInfo:n,remotes:e})}`),{remote:n,preloadConfig:op(r)}})}function Gk(e){return e?e.map(t=>t==="."?t:t.startsWith("./")?t.replace("./",""):t):[]}function lp(e,t,r,n=!0){const{cssAssets:s,jsAssetsWithoutEntry:a,entryAssets:c}=r;if(t.options.inBrowser){if(c.forEach(d=>{const{moduleInfo:u}=d,f=t.moduleCache.get(e.name);gl(f?{origin:t,remoteInfo:u,remoteEntryExports:f.remoteEntryExports}:{origin:t,remoteInfo:u,remoteEntryExports:void 0})}),n){const d={rel:"preload",as:"style"};s.forEach(u=>{const{link:f,needAttach:h}=kd({url:u,cb:()=>{},attrs:d,createLinkHook:(m,g)=>{const p=t.loaderHook.lifecycle.createLink.emit({url:m,attrs:g,remoteInfo:e});if(p instanceof HTMLLinkElement)return p}});h&&document.head.appendChild(f)})}else{const d={rel:"stylesheet",type:"text/css"};s.forEach(u=>{const{link:f,needAttach:h}=kd({url:u,cb:()=>{},attrs:d,createLinkHook:(m,g)=>{const p=t.loaderHook.lifecycle.createLink.emit({url:m,attrs:g,remoteInfo:e});if(p instanceof HTMLLinkElement)return p},needDeleteLink:!1});h&&document.head.appendChild(f)})}if(n){const d={rel:"preload",as:"script"};a.forEach(u=>{const{link:f,needAttach:h}=kd({url:u,cb:()=>{},attrs:d,createLinkHook:(m,g)=>{const p=t.loaderHook.lifecycle.createLink.emit({url:m,attrs:g,remoteInfo:e});if(p instanceof HTMLLinkElement)return p}});h&&document.head.appendChild(f)})}else{const d={fetchpriority:"high",type:e?.type==="module"?"module":"text/javascript"};a.forEach(u=>{const{script:f,needAttach:h}=Pg({url:u,cb:()=>{},attrs:d,createScriptHook:(m,g)=>{const p=t.loaderHook.lifecycle.createScript.emit({url:m,attrs:g,remoteInfo:e});if(p instanceof HTMLScriptElement)return p},needDeleteScript:!0});h&&document.head.appendChild(f)})}}}function Zk(e,t,r){const n=t,s=Array.isArray(e.shareScope)?e.shareScope:[e.shareScope];s.length||s.push("default"),s.forEach(c=>{n[c]||(n[c]={})});const a={version:e.version||"",shareScopeKeys:Array.isArray(e.shareScope)?s:e.shareScope||"default"};return Object.defineProperty(a,"shareScopeMap",{value:n,enumerable:!1}),{remoteEntryInitOptions:a,shareScope:n[s[0]],initScope:r??[]}}var cp=class{constructor({remoteInfo:e,host:t}){this.inited=!1,this.initing=!1,this.lib=void 0,this.remoteInfo=e,this.host=t}async getEntry(){if(this.remoteEntryExports)return this.remoteEntryExports;const e=await gl({origin:this.host,remoteInfo:this.remoteInfo,remoteEntryExports:this.remoteEntryExports});return Fr(e,`remoteEntryExports is undefined
100
+ ${kg(this.remoteInfo)}`),this.remoteEntryExports=e,this.remoteEntryExports}async init(e,t,r){const n=await this.getEntry();if(this.inited)return n;if(this.initPromise)return await this.initPromise,n;this.initing=!0,this.initPromise=(async()=>{const{remoteEntryInitOptions:s,shareScope:a,initScope:c}=Zk(this.remoteInfo,this.host.shareScopeMap,r),d=await this.host.hooks.lifecycle.beforeInitContainer.emit({shareScope:a,remoteEntryInitOptions:s,initScope:c,remoteInfo:this.remoteInfo,origin:this.host});typeof n?.init>"u"&&er(Xg,Ur,{hostName:this.host.name,remoteName:this.remoteInfo.name,remoteEntryUrl:this.remoteInfo.entry,remoteEntryKey:this.remoteInfo.entryGlobalName},void 0,rs(this.host.options)),await n.init(d.shareScope,d.initScope,d.remoteEntryInitOptions),await this.host.hooks.lifecycle.initContainer.emit({...d,id:e,remoteSnapshot:t,remoteEntryExports:n}),this.inited=!0})();try{await this.initPromise}finally{this.initing=!1,this.initPromise=void 0}return n}async get(e,t,r,n){const{loadFactory:s=!0}=r||{loadFactory:!0},a=await this.init(e,n);this.lib=a;let c;c=await this.host.loaderHook.lifecycle.getModuleFactory.emit({remoteEntryExports:a,expose:t,moduleInfo:this.remoteInfo}),c||(c=await a.get(t)),Fr(c,`${Za(this.remoteInfo)} remote don't export ${t}.`);const d=GE(this.remoteInfo.name,t),u=this.wraperFactory(c,d);return s?await u():u}wraperFactory(e,t){function r(n,s){n&&typeof n=="object"&&Object.isExtensible(n)&&!Object.getOwnPropertyDescriptor(n,Symbol.for("mf_module_id"))&&Object.defineProperty(n,Symbol.for("mf_module_id"),{value:s,enumerable:!1})}return e instanceof Promise?async()=>{const n=await e();return r(n,t),n}:()=>{const n=e();return r(n,t),n}}},Xr=class{constructor(e){this.type="",this.listeners=new Set,e&&(this.type=e)}on(e){typeof e=="function"&&this.listeners.add(e)}once(e){const t=this;this.on(function r(...n){return t.remove(r),e.apply(null,n)})}emit(...e){let t;return this.listeners.size>0&&this.listeners.forEach(r=>{t=r(...e)}),t}remove(e){this.listeners.delete(e)}removeAll(){this.listeners.clear()}},fn=class extends Xr{emit(...e){let t;const r=Array.from(this.listeners);if(r.length>0){let n=0;const s=a=>a===!1?!1:n<r.length?Promise.resolve(r[n++].apply(null,e)).then(s):a;t=s()}return Promise.resolve(t)}};function up(e,t){if(!Pd(t))return!1;if(e!==t){for(const r in e)if(!(r in t))return!1}return!0}var ns=class extends Xr{constructor(e){super(),this.onerror=er,this.type=e}emit(e){Pd(e)||er(`The data for the "${this.type}" hook should be an object.`);for(const t of this.listeners)try{const r=t(e);if(up(e,r))e=r;else{this.onerror(`A plugin returned an unacceptable value for the "${this.type}" type.`);break}}catch(r){Cd(r),this.onerror(r)}return e}},ni=class extends Xr{constructor(e){super(),this.onerror=er,this.type=e}emit(e){Pd(e)||er(`The response data for the "${this.type}" hook must be an object.`);const t=Array.from(this.listeners);if(t.length>0){let r=0;const n=a=>(Cd(a),this.onerror(a),e),s=a=>{if(up(e,a)){if(e=a,r<t.length)try{return Promise.resolve(t[r++](e)).then(s,n)}catch(c){return n(c)}}else this.onerror(`A plugin returned an incorrect value for the "${this.type}" type.`);return e};return Promise.resolve(s(e))}return Promise.resolve(e)}},is=class{constructor(e){this.registerPlugins={},this.lifecycle=e,this.lifecycleKeys=Object.keys(e)}applyPlugin(e,t){Fr(zE(e),"Plugin configuration is invalid.");const r=e.name;Fr(r,"A name must be provided by the plugin."),this.registerPlugins[r]||(this.registerPlugins[r]=e,e.apply?.(t),Object.keys(this.lifecycle).forEach(n=>{const s=e[n];s&&this.lifecycle[n].on(s)}))}removePlugin(e){Fr(e,"A name is required.");const t=this.registerPlugins[e];Fr(t,`The plugin "${e}" is not registered.`),Object.keys(t).forEach(r=>{r!=="name"&&this.lifecycle[r].remove(t[r])})}};function dp(e,t){const r=Dg(t);r.url||er(sp,Ur,{remoteName:e.name});let n=_d(t,r.url);e.type=r.type,e.entryGlobalName=r.globalName,e.entry=n,e.version=t.version,e.buildVersion=t.buildVersion}function Vk(){return{name:"snapshot-plugin",async afterResolve(e){const{remote:t,pkgNameOrAlias:r,expose:n,origin:s,remoteInfo:a,id:c}=e;if(!Id(t)||!jg(t)){const{remoteSnapshot:d,globalSnapshot:u}=await s.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:t,id:c});dp(a,d);const f={remote:t,preloadConfig:{nameOrAlias:r,exposes:[n],resourceCategory:"sync",share:!1,depsRemote:!1}},h=await s.remoteHandler.hooks.lifecycle.generatePreloadAssets.emit({origin:s,preloadOptions:f,remoteInfo:a,remote:t,remoteSnapshot:d,globalSnapshot:u});return h&&lp(a,s,h,!1),{...e,remoteSnapshot:d}}return e}}}function Hk(e){const t=e.split(":");return t.length===1?{name:t[0],version:void 0}:t.length===2?{name:t[0],version:t[1]}:{name:t[1],version:t[2]}}function fp(e,t,r,n,s={},a){const{value:c}=Xi(e,Za(t)),d=a||c;if(d&&!Tg(d)&&(r(d,t,n),d.remotesInfo)){const u=Object.keys(d.remotesInfo);for(const f of u){if(s[f])continue;s[f]=!0;const h=Hk(f),m=d.remotesInfo[f];fp(e,{name:h.name,version:m.matchedVersion},r,!1,s,void 0)}}}var Ld=(e,t)=>document.querySelector(`${e}[${e==="link"?"href":"src"}="${t}"]`);function Kk(e,t,r,n,s){const a=[],c=[],d=[],u=new Set,f=new Set,{options:h}=e,{preloadConfig:m}=t,{depsRemote:g}=m;if(fp(n,r,(y,S,E)=>{let T;if(E)T=m;else if(Array.isArray(g)){const z=g.find(K=>K.nameOrAlias===S.name||K.nameOrAlias===S.alias);if(!z)return;T=op(z)}else if(g===!0)T=m;else return;const j=_d(y,Dg(y).url);j&&d.push({name:S.name,moduleInfo:{name:S.name,entry:j,type:"remoteEntryType"in y?y.remoteEntryType:"global",entryGlobalName:"globalName"in y?y.globalName:S.name,shareScope:"",version:"version"in y?y.version:void 0},url:j});let N="modules"in y?y.modules:[];const O=Gk(T.exposes);O.length&&"modules"in y&&(N=y?.modules?.reduce((z,K)=>(O?.indexOf(K.moduleName)!==-1&&z.push(K),z),[]));function U(z){const K=z.map(G=>_d(y,G));return T.filter?K.filter(T.filter):K}if(N){const z=N.length;for(let K=0;K<z;K++){const G=N[K],X=`${S.name}/${G.moduleName}`;e.remoteHandler.hooks.lifecycle.handlePreloadModule.emit({id:G.moduleName==="."?S.name:X,name:S.name,remoteSnapshot:y,preloadConfig:T,remote:S,origin:e}),!QE(X)&&(T.resourceCategory==="all"?(a.push(...U(G.assets.css.async)),a.push(...U(G.assets.css.sync)),c.push(...U(G.assets.js.async)),c.push(...U(G.assets.js.sync))):T.resourceCategory==="sync"&&(a.push(...U(G.assets.css.sync)),c.push(...U(G.assets.js.sync))),YE(X))}}},!0,{},s),s.shared&&s.shared.length>0){const y=(S,E)=>{const{shared:T}=hl(e.shareScopeMap,E.sharedName,S,e.sharedHandler.hooks.lifecycle.resolveShare)||{};T&&typeof T.lib=="function"&&(E.assets.js.sync.forEach(j=>{u.add(j)}),E.assets.css.sync.forEach(j=>{f.add(j)}))};s.shared.forEach(S=>{const E=h.shared?.[S.sharedName];if(!E)return;const T=S.version?E.find(j=>j.version===S.version):E;T&&Ng(T).forEach(j=>{y(j,S)})})}const p=c.filter(y=>!u.has(y)&&!Ld("script",y));return{cssAssets:a.filter(y=>!f.has(y)&&!Ld("link",y)),jsAssetsWithoutEntry:p,entryAssets:d.filter(y=>!Ld("script",y.url))}}var Wk=function(){return{name:"generate-preload-assets-plugin",async generatePreloadAssets(e){const{origin:t,preloadOptions:r,remoteInfo:n,remote:s,globalSnapshot:a,remoteSnapshot:c}=e;return Id(s)&&jg(s)?{cssAssets:[],jsAssetsWithoutEntry:[],entryAssets:[{name:s.name,url:s.entry,moduleInfo:{name:n.name,entry:s.entry,type:n.type||"global",entryGlobalName:"",shareScope:""}}]}:(dp(n,c),Kk(t,r,n,a,c))}}};function hp(e,t){const r=ol({name:t.name,version:t.options.version}),n=r&&"remotesInfo"in r&&r.remotesInfo&&Xi(r.remotesInfo,e.name).value;return n&&n.matchedVersion?{hostGlobalSnapshot:r,globalSnapshot:$g(),remoteSnapshot:ol({name:e.name,version:n.matchedVersion})}:{hostGlobalSnapshot:void 0,globalSnapshot:$g(),remoteSnapshot:ol({name:e.name,version:"version"in e?e.version:void 0})}}var qk=class{constructor(e){this.loadingHostSnapshot=null,this.manifestCache=new Map,this.hooks=new is({beforeLoadRemoteSnapshot:new fn("beforeLoadRemoteSnapshot"),loadSnapshot:new ni("loadGlobalSnapshot"),loadRemoteSnapshot:new ni("loadRemoteSnapshot"),afterLoadSnapshot:new ni("afterLoadSnapshot")}),this.manifestLoading=Va.__FEDERATION__.__MANIFEST_LOADING__,this.HostInstance=e,this.loaderHook=e.loaderHook}async loadRemoteSnapshotInfo({moduleInfo:e,id:t,expose:r}){const{options:n}=this.HostInstance;await this.hooks.lifecycle.beforeLoadRemoteSnapshot.emit({options:n,moduleInfo:e});let s=ol({name:this.HostInstance.options.name,version:this.HostInstance.options.version});s||(s={version:this.HostInstance.options.version||"",remoteEntry:"",remotesInfo:{}},WE({[this.HostInstance.options.name]:s})),s&&"remotesInfo"in s&&!Xi(s.remotesInfo,e.name).value&&("version"in e||"entry"in e)&&(s.remotesInfo={...s?.remotesInfo,[e.name]:{matchedVersion:"version"in e?e.version:e.entry}});const{hostGlobalSnapshot:a,remoteSnapshot:c,globalSnapshot:d}=this.getGlobalRemoteInfo(e),{remoteSnapshot:u,globalSnapshot:f}=await this.hooks.lifecycle.loadSnapshot.emit({options:n,moduleInfo:e,hostGlobalSnapshot:a,remoteSnapshot:c,globalSnapshot:d});let h,m;if(u)if(Tg(u)){const g=u.remoteEntry,p=await this.getManifestJson(g,e,{}),y=Rg({...e,entry:g},p);h=p,m=y}else{const{remoteSnapshot:g}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:e,remoteSnapshot:u,from:"global"});h=g,m=f}else if(Id(e)){const g=await this.getManifestJson(e.entry,e,{}),p=Rg(e,g),{remoteSnapshot:y}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:e,remoteSnapshot:g,from:"global"});h=y,m=p}else er(rp,Ur,{remoteName:e.name,remoteVersion:e.version,hostName:this.HostInstance.options.name,globalSnapshot:JSON.stringify(f)},void 0,rs(this.HostInstance.options));return await this.hooks.lifecycle.afterLoadSnapshot.emit({id:t,host:this.HostInstance,options:n,moduleInfo:e,remoteSnapshot:h}),{remoteSnapshot:h,globalSnapshot:m}}getGlobalRemoteInfo(e){return hp(e,this.HostInstance)}async getManifestJson(e,t,r){const n=async()=>{let a=this.manifestCache.get(e);if(a)return a;try{let c=await this.loaderHook.lifecycle.fetch.emit(e,{},pl(t));(!c||!(c instanceof Response))&&(c=await fetch(e,{})),a=await c.json()}catch(c){a=await this.HostInstance.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:e,error:c,from:"runtime",lifecycle:"afterResolve",origin:this.HostInstance}),a||(delete this.manifestLoading[e],er(Jg,Ur,{manifestUrl:e,moduleName:t.name,hostName:this.HostInstance.options.name},`${c}`,rs(this.HostInstance.options)))}return Fr(a.metaData&&a.exposes&&a.shared,`"${e}" is not a valid federation manifest for remote "${t.name}". Missing required fields: ${[!a.metaData&&"metaData",!a.exposes&&"exposes",!a.shared&&"shared"].filter(Boolean).join(", ")}.`),this.manifestCache.set(e,a),a},s=async()=>{const a=await n(),c=jE(a,{version:e}),{remoteSnapshot:d}=await this.hooks.lifecycle.loadRemoteSnapshot.emit({options:this.HostInstance.options,moduleInfo:t,manifestJson:a,remoteSnapshot:c,manifestUrl:e,from:"manifest"});return d};return this.manifestLoading[e]||(this.manifestLoading[e]=s().then(a=>a)),this.manifestLoading[e]}},Qk=class{constructor(e){this.hooks=new is({beforeRegisterShare:new ns("beforeRegisterShare"),afterResolve:new ni("afterResolve"),beforeLoadShare:new ni("beforeLoadShare"),loadShare:new fn,resolveShare:new ns("resolveShare"),initContainerShareScopeMap:new ns("initContainerShareScopeMap")}),this.host=e,this.shareScopeMap={},this.initTokens={},this._setGlobalShareScopeMap(e.options)}registerShared(e,t){const{newShareInfos:r,allShareInfos:n}=Wg(e,t);return Object.keys(r).forEach(s=>{r[s].forEach(a=>{a.scope.forEach(c=>{this.hooks.lifecycle.beforeRegisterShare.emit({origin:this.host,pkgName:s,shared:a}),this.shareScopeMap[c]?.[s]||this.setShared({pkgName:s,lib:a.lib,get:a.get,loaded:a.loaded||!!a.lib,shared:a,from:t.name})})})}),{newShareInfos:r,allShareInfos:n}}async loadShare(e,t){const{host:r}=this,n=Qg({pkgName:e,extraOptions:t,shareInfos:r.options.shared});n?.scope&&await Promise.all(n.scope.map(async d=>{await Promise.all(this.initializeSharing(d,{strategy:n.strategy}))}));const{shareInfo:s}=await this.hooks.lifecycle.beforeLoadShare.emit({pkgName:e,shareInfo:n,shared:r.options.shared,origin:r});Fr(s,`Cannot find shared "${e}" in host "${r.options.name}". Ensure the shared config for "${e}" is declared in the federation plugin options and the host has been initialized before loading shares.`);const{shared:a,useTreesShaking:c}=hl(this.shareScopeMap,e,s,this.hooks.lifecycle.resolveShare)||{};if(a){const d=ml(a,c);if(d.lib)return ts(d,r.options.name),d.lib;if(d.loading&&!d.loaded){const u=await d.loading;return d.loaded=!0,d.lib||(d.lib=u),ts(d,r.options.name),u}else{const f=(async()=>{const h=await d.get();return ts(d,r.options.name),d.loaded=!0,d.lib=h,h})();return this.setShared({pkgName:e,loaded:!1,shared:a,from:r.options.name,lib:null,loading:f,treeShaking:c?d:void 0}),f}}else{if(t?.customShareInfo)return!1;const d=Wa(s.treeShaking),u=ml(s,d),h=(async()=>{const m=await u.get();u.lib=m,u.loaded=!0,ts(u,r.options.name);const{shared:g,useTreesShaking:p}=hl(this.shareScopeMap,e,s,this.hooks.lifecycle.resolveShare)||{};if(g){const y=ml(g,p);y.lib=m,y.loaded=!0,g.from=s.from}return m})();return this.setShared({pkgName:e,loaded:!1,shared:s,from:r.options.name,lib:null,loading:h,treeShaking:d?u:void 0}),h}}initializeSharing(e=dl,t){const{host:r}=this,n=t?.from,s=t?.strategy;let a=t?.initScope;const c=[];if(n!=="build"){const{initTokens:g}=this;a||(a=[]);let p=g[e];if(p||(p=g[e]={from:this.host.name}),a.indexOf(p)>=0)return c;a.push(p)}const d=this.shareScopeMap,u=r.options.name;d[e]||(d[e]={});const f=d[e],h=(g,p)=>{const{version:y,eager:S}=p;f[g]=f[g]||{};const E=f[g],T=E[y]&&ml(E[y]),j=!!(T&&("eager"in T&&T.eager||"shareConfig"in T&&T.shareConfig?.eager));(!T||T.strategy!=="loaded-first"&&!T.loaded&&(!S!=!j?S:u>E[y].from))&&(E[y]=p)},m=async g=>{const{module:p}=await r.remoteHandler.getRemoteModuleAndOptions({id:g});let y;try{y=await p.getEntry()}catch(S){if(y=await r.remoteHandler.hooks.lifecycle.errorLoadRemote.emit({id:g,error:S,from:"runtime",lifecycle:"beforeLoadShare",origin:r}),!y)return}finally{y?.init&&!p.initing&&(p.remoteEntryExports=y,await p.init(void 0,void 0,a))}};return Object.keys(r.options.shared).forEach(g=>{r.options.shared[g].forEach(p=>{p.scope.includes(e)&&h(g,p)})}),(r.options.shareStrategy==="version-first"||s==="version-first")&&r.options.remotes.forEach(g=>{g.shareScope===e&&c.push(m(g.name))}),c}loadShareSync(e,t){const{host:r}=this,n=Qg({pkgName:e,extraOptions:t,shareInfos:r.options.shared});n?.scope&&n.scope.forEach(c=>{this.initializeSharing(c,{strategy:n.strategy})});const{shared:s,useTreesShaking:a}=hl(this.shareScopeMap,e,n,this.hooks.lifecycle.resolveShare)||{};if(s){if(typeof s.lib=="function")return ts(s,r.options.name),s.loaded||(s.loaded=!0,s.from===r.options.name&&(n.loaded=!0)),s.lib;if(typeof s.get=="function"){const c=s.get();if(!(c instanceof Promise))return ts(s,r.options.name),this.setShared({pkgName:e,loaded:!0,from:r.options.name,lib:c,shared:s}),c}}if(n.lib)return n.loaded||(n.loaded=!0),n.lib;if(n.get){const c=n.get();return c instanceof Promise&&er(t?.from==="build"?tp:Md,Ur,{hostName:r.options.name,sharedPkgName:e},void 0,rs(r.options)),n.lib=c,this.setShared({pkgName:e,loaded:!0,from:r.options.name,lib:n.lib,shared:n}),n.lib}er(Md,Ur,{hostName:r.options.name,sharedPkgName:e},void 0,rs(r.options))}initShareScopeMap(e,t,r={}){const{host:n}=this;this.shareScopeMap[e]=t,this.hooks.lifecycle.initContainerShareScopeMap.emit({shareScope:t,options:n.options,origin:n,scopeName:e,hostShareScopeMap:r.hostShareScopeMap})}setShared({pkgName:e,shared:t,from:r,lib:n,loading:s,loaded:a,get:c,treeShaking:d}){const{version:u,scope:f="default",...h}=t,m=Array.isArray(f)?f:[f],g=p=>{const y=(E,T,j)=>{j&&!E[T]&&(E[T]=j)},S=d?p.treeShaking:p;y(S,"loaded",a),y(S,"loading",s),y(S,"get",c)};m.forEach(p=>{this.shareScopeMap[p]||(this.shareScopeMap[p]={}),this.shareScopeMap[p][e]||(this.shareScopeMap[p][e]={}),this.shareScopeMap[p][e][u]||(this.shareScopeMap[p][e][u]={version:u,scope:[p],...h,lib:n});const y=this.shareScopeMap[p][e][u];g(y),r&&y.from!==r&&(y.from=r)})}_setGlobalShareScopeMap(e){const t=qg(),r=e.id||e.name;r&&!t[r]&&(t[r]=this.shareScopeMap)}},Yk=class{constructor(e){this.hooks=new is({beforeRegisterRemote:new ns("beforeRegisterRemote"),registerRemote:new ns("registerRemote"),beforeRequest:new ni("beforeRequest"),onLoad:new fn("onLoad"),handlePreloadModule:new Xr("handlePreloadModule"),errorLoadRemote:new fn("errorLoadRemote"),beforePreloadRemote:new fn("beforePreloadRemote"),generatePreloadAssets:new fn("generatePreloadAssets"),afterPreloadRemote:new fn,loadEntry:new fn}),this.host=e,this.idToRemoteMap={}}formatAndRegisterRemote(e,t){return(t.remotes||[]).reduce((r,n)=>(this.registerRemote(n,r,{force:!1}),r),e.remotes)}setIdToRemoteMap(e,t){const{remote:r,expose:n}=t,{name:s,alias:a}=r;if(this.idToRemoteMap[e]={name:r.name,expose:n},a&&e.startsWith(s)){const c=e.replace(s,a);this.idToRemoteMap[c]={name:r.name,expose:n};return}if(a&&e.startsWith(a)){const c=e.replace(a,s);this.idToRemoteMap[c]={name:r.name,expose:n}}}async loadRemote(e,t){const{host:r}=this;try{const{loadFactory:n=!0}=t||{loadFactory:!0},{module:s,moduleOptions:a,remoteMatchInfo:c}=await this.getRemoteModuleAndOptions({id:e}),{pkgNameOrAlias:d,remote:u,expose:f,id:h,remoteSnapshot:m}=c,g=await s.get(h,f,t,m),p=await this.hooks.lifecycle.onLoad.emit({id:h,pkgNameOrAlias:d,expose:f,exposeModule:n?g:void 0,exposeModuleFactory:n?void 0:g,remote:u,options:a,moduleInstance:s,origin:r});return this.setIdToRemoteMap(e,c),typeof p=="function"?p:g}catch(n){const{from:s="runtime"}=t||{from:"runtime"},a=await this.hooks.lifecycle.errorLoadRemote.emit({id:e,error:n,from:s,lifecycle:"onLoad",origin:r});if(!a)throw n;return a}}async preloadRemote(e){const{host:t}=this;await this.hooks.lifecycle.beforePreloadRemote.emit({preloadOps:e,options:t.options,origin:t});const r=zk(t.options.remotes,e);await Promise.all(r.map(async n=>{const{remote:s}=n,a=pl(s),{globalSnapshot:c,remoteSnapshot:d}=await t.snapshotHandler.loadRemoteSnapshotInfo({moduleInfo:s}),u=await this.hooks.lifecycle.generatePreloadAssets.emit({origin:t,preloadOptions:n,remote:s,remoteInfo:a,globalSnapshot:c,remoteSnapshot:d});u&&lp(a,t,u)}))}registerRemotes(e,t){const{host:r}=this;e.forEach(n=>{this.registerRemote(n,r.options.remotes,{force:t?.force})})}async getRemoteModuleAndOptions(e){const{host:t}=this,{id:r}=e;let n;try{n=await this.hooks.lifecycle.beforeRequest.emit({id:r,options:t.options,origin:t})}catch(p){if(n=await this.hooks.lifecycle.errorLoadRemote.emit({id:r,options:t.options,origin:t,from:"runtime",error:p,lifecycle:"beforeRequest"}),!n)throw p}const{id:s}=n,a=jk(t.options.remotes,s);a||er(ep,Ur,{hostName:t.options.name,requestId:s},void 0,rs(t.options));const{remote:c}=a,d=pl(c),u=await t.sharedHandler.hooks.lifecycle.afterResolve.emit({id:s,...a,options:t.options,origin:t,remoteInfo:d}),{remote:f,expose:h}=u;Fr(f&&h,`The 'beforeRequest' hook was executed, but it failed to return the correct 'remote' and 'expose' values while loading ${s}.`);let m=t.moduleCache.get(f.name);const g={host:t,remoteInfo:d};return m||(m=new cp(g),t.moduleCache.set(f.name,m)),{module:m,moduleOptions:g,remoteMatchInfo:u}}registerRemote(e,t,r){const{host:n}=this,s=()=>{if(e.alias){const c=t.find(d=>e.alias&&(d.name.startsWith(e.alias)||d.alias?.startsWith(e.alias)));Fr(!c,`The alias ${e.alias} of remote ${e.name} is not allowed to be the prefix of ${c&&c.name} name or alias`)}"entry"in e&&typeof window<"u"&&!e.entry.startsWith("http")&&(e.entry=new URL(e.entry,window.location.origin).href),e.shareScope||(e.shareScope=dl),e.type||(e.type=Ek)};this.hooks.lifecycle.beforeRegisterRemote.emit({remote:e,origin:n});const a=t.find(c=>c.name===e.name);if(!a)s(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:n});else{const c=[`The remote "${e.name}" is already registered.`,"Please note that overriding it may cause unexpected errors."];r?.force&&(this.removeRemote(a),s(),t.push(e),this.hooks.lifecycle.registerRemote.emit({remote:e,origin:n}),Eg(c.join(" ")))}}removeRemote(e){try{const{host:t}=this,{name:r}=e,n=t.options.remotes.findIndex(a=>a.name===r);n!==-1&&t.options.remotes.splice(n,1);const s=t.moduleCache.get(e.name);if(s){const a=s.remoteInfo,c=a.entryGlobalName;ur[c]&&(Object.getOwnPropertyDescriptor(ur,c)?.configurable?delete ur[c]:ur[c]=void 0);const d=Rd(s.remoteInfo);Yi[d]&&delete Yi[d],t.snapshotHandler.manifestCache.delete(a.entry);let u=a.buildVersion?wg(a.name,a.buildVersion):a.name;const f=ur.__FEDERATION__.__INSTANCES__.findIndex(m=>a.buildVersion?m.options.id===u:m.name===u);if(f!==-1){const m=ur.__FEDERATION__.__INSTANCES__[f];u=m.options.id||u;const g=qg();let p=!0;const y=[];Object.keys(g).forEach(S=>{const E=g[S];E&&Object.keys(E).forEach(T=>{const j=E[T];j&&Object.keys(j).forEach(N=>{const O=j[N];O&&Object.keys(O).forEach(U=>{const z=O[U];z&&typeof z=="object"&&z.from===a.name&&(z.loaded||z.loading?(z.useIn=z.useIn.filter(K=>K!==a.name),z.useIn.length?p=!1:y.push([S,T,N,U])):y.push([S,T,N,U]))})})})}),p&&(m.shareScopeMap={},delete g[u]),y.forEach(([S,E,T,j])=>{delete g[S]?.[E]?.[T]?.[j]}),ur.__FEDERATION__.__INSTANCES__.splice(f,1)}const{hostGlobalSnapshot:h}=hp(e,t);if(h){const m=h&&"remotesInfo"in h&&h.remotesInfo&&Xi(h.remotesInfo,e.name).key;m&&(delete h.remotesInfo[m],Va.__FEDERATION__.__MANIFEST_LOADING__[m]&&delete Va.__FEDERATION__.__MANIFEST_LOADING__[m])}t.moduleCache.delete(e.name)}}catch(t){Td.error(`removeRemote failed: ${t instanceof Error?t.message:String(t)}`)}}},Xk=typeof FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN=="boolean"?!FEDERATION_OPTIMIZE_NO_SNAPSHOT_PLUGIN:!0,mp=class{constructor(e){this.hooks=new is({beforeInit:new ns("beforeInit"),init:new Xr,beforeInitContainer:new ni("beforeInitContainer"),initContainer:new ni("initContainer")}),this.version="2.4.0",this.moduleCache=new Map,this.loaderHook=new is({getModuleInfo:new Xr,createScript:new Xr,createLink:new Xr,fetch:new fn,loadEntryError:new fn,getModuleFactory:new fn}),this.bridgeHook=new is({beforeBridgeRender:new Xr,afterBridgeRender:new Xr,beforeBridgeDestroy:new Xr,afterBridgeDestroy:new Xr});const t=Xk?[Vk(),Wk()]:[],r={id:Fk(),name:e.name,plugins:t,remotes:[],shared:{},inBrowser:_g};this.name=e.name,this.options=r,this.snapshotHandler=new qk(this),this.sharedHandler=new Qk(this),this.remoteHandler=new Yk(this),this.shareScopeMap=this.sharedHandler.shareScopeMap,this.registerPlugins([...r.plugins,...e.plugins||[]]),this.options=this.formatOptions(r,e)}initOptions(e){e.name&&e.name!==this.options.name&&er(Ag(ip,Ur)),this.registerPlugins(e.plugins);const t=this.formatOptions(this.options,e);return this.options=t,t}async loadShare(e,t){return this.sharedHandler.loadShare(e,t)}loadShareSync(e,t){return this.sharedHandler.loadShareSync(e,t)}initializeSharing(e=dl,t){return this.sharedHandler.initializeSharing(e,t)}initRawContainer(e,t,r){const n=pl({name:e,entry:t}),s=new cp({host:this,remoteInfo:n});return s.remoteEntryExports=r,this.moduleCache.set(e,s),s}async loadRemote(e,t){return this.remoteHandler.loadRemote(e,t)}async preloadRemote(e){return this.remoteHandler.preloadRemote(e)}initShareScopeMap(e,t,r={}){this.sharedHandler.initShareScopeMap(e,t,r)}formatOptions(e,t){const{allShareInfos:r}=Wg(e,t),{userOptions:n,options:s}=this.hooks.lifecycle.beforeInit.emit({origin:this,userOptions:t,options:e,shareInfo:r}),a=this.remoteHandler.formatAndRegisterRemote(s,n),{allShareInfos:c}=this.sharedHandler.registerShared(s,n),d=[...s.plugins];n.plugins&&n.plugins.forEach(f=>{d.includes(f)||d.push(f)});const u={...e,...t,plugins:d,remotes:a,shared:c,id:n.id||e.id};return this.hooks.lifecycle.init.emit({origin:this,options:u}),u}registerPlugins(e){const t=Uk(e,this);this.options.plugins=this.options.plugins.reduce((r,n)=>(n&&r&&!r.find(s=>s.name===n.name)&&r.push(n),r),t||[])}registerRemotes(e,t){return this.remoteHandler.registerRemotes(e,t)}registerShared(e){this.sharedHandler.registerShared(this.options,{...this.options,shared:e})}};function Jk(){return typeof FEDERATION_BUILD_IDENTIFIER<"u"?FEDERATION_BUILD_IDENTIFIER:""}function eT(e,t){const r=Jk();return ur.__FEDERATION__.__INSTANCES__.find(n=>!!(r&&n.options.id===r||n.options.name===e&&!n.options.version&&!t||n.options.name===e&&t&&n.options.version===t))}function tT(e){const t=new(VE()||mp)({id:`${e.name}@${e.version||Date.now()}`,...e});return ZE(t),t}var hn=null;function rT(e){const t=eT(e.name,e.version),r={...e,id:e.id||""};return t?(t.initOptions(r),hn||(hn=t),t):(hn=tT(r),hn)}function nT(...e){return Fr(hn,$d,Ur),hn.loadRemote.apply(hn,e)}function iT(...e){return Fr(hn,$d,Ur),hn.registerRemotes.apply(hn,e)}function sT(){return hn}HE(mp);function ss(e){const t=(typeof globalThis<"u"?globalThis:void 0)?.[e];return t&&typeof t=="object"?t:{}}var aT={singleton:!0,requiredVersion:!1,eager:!0},Jr=e=>({version:"0.0.0",scope:"default",lib:e,shareConfig:aT}),gp="__mf_module_cache__";function oT(){const e=globalThis,t=e[gp];if(t&&typeof t=="object"){const n=t;return n.share??={},n.remote??={},n}const r={share:{},remote:{}};return e[gp]=r,r}function lT(){const e=oT();e.share.react??=l,e.share["react-dom"]??=I,e.share["react-dom/client"]??=Z,e.share["react/jsx-runtime"]??=i,e.share["@tanstack/react-query"]??=ye,e.share["@trpc/client"]??=ve,e.share["@trpc/react-query"]??=Te,e.share["react-konva"]??=_e,e.share.konva??=Oe,e.share["@camstack/ui-library"]??=ss("__camstackUiLibrary"),e.share["@camstack/sdk"]??=ss("__camstackSdk"),e.share["@camstack/types"]??=ss("__camstackTypes")}function pp(){lT(),sT()===null&&rT({name:"admin_ui_host",remotes:[],shared:{react:Jr(()=>l),"react-dom":Jr(()=>I),"react-dom/client":Jr(()=>Z),"react/jsx-runtime":Jr(()=>i),"@tanstack/react-query":Jr(()=>ye),"@trpc/client":Jr(()=>ve),"@trpc/react-query":Jr(()=>Te),"react-konva":Jr(()=>_e),konva:Jr(()=>Oe),"@camstack/ui-library":Jr(()=>ss("__camstackUiLibrary")),"@camstack/sdk":Jr(()=>ss("__camstackSdk")),"@camstack/types":Jr(()=>ss("__camstackTypes"))}})}/**
101
+ * @license lucide-react v0.576.0 - ISC
102
+ *
103
+ * This source code is licensed under the ISC license.
104
+ * See the LICENSE file in the root directory of this source tree.
105
+ */var vp=(...e)=>e.filter((t,r,n)=>!!t&&t.trim()!==""&&n.indexOf(t)===r).join(" ").trim();/**
106
+ * @license lucide-react v0.576.0 - ISC
107
+ *
108
+ * This source code is licensed under the ISC license.
109
+ * See the LICENSE file in the root directory of this source tree.
110
+ */var cT=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase();/**
111
+ * @license lucide-react v0.576.0 - ISC
112
+ *
113
+ * This source code is licensed under the ISC license.
114
+ * See the LICENSE file in the root directory of this source tree.
115
+ */var uT=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(t,r,n)=>n?n.toUpperCase():r.toLowerCase());/**
116
+ * @license lucide-react v0.576.0 - ISC
117
+ *
118
+ * This source code is licensed under the ISC license.
119
+ * See the LICENSE file in the root directory of this source tree.
120
+ */var bp=e=>{const t=uT(e);return t.charAt(0).toUpperCase()+t.slice(1)};/**
121
+ * @license lucide-react v0.576.0 - ISC
122
+ *
123
+ * This source code is licensed under the ISC license.
124
+ * See the LICENSE file in the root directory of this source tree.
125
+ */var dT={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/**
126
+ * @license lucide-react v0.576.0 - ISC
127
+ *
128
+ * This source code is licensed under the ISC license.
129
+ * See the LICENSE file in the root directory of this source tree.
130
+ */var fT=e=>{for(const t in e)if(t.startsWith("aria-")||t==="role"||t==="title")return!0;return!1};/**
131
+ * @license lucide-react v0.576.0 - ISC
132
+ *
133
+ * This source code is licensed under the ISC license.
134
+ * See the LICENSE file in the root directory of this source tree.
135
+ */var hT=(0,w.forwardRef)(({color:e="currentColor",size:t=24,strokeWidth:r=2,absoluteStrokeWidth:n,className:s="",children:a,iconNode:c,...d},u)=>(0,w.createElement)("svg",{ref:u,...dT,width:t,height:t,stroke:e,strokeWidth:n?Number(r)*24/Number(t):r,className:vp("lucide",s),...!a&&!fT(d)&&{"aria-hidden":"true"},...d},[...c.map(([f,h])=>(0,w.createElement)(f,h)),...Array.isArray(a)?a:[a]]));/**
136
+ * @license lucide-react v0.576.0 - ISC
137
+ *
138
+ * This source code is licensed under the ISC license.
139
+ * See the LICENSE file in the root directory of this source tree.
140
+ */var ge=(e,t)=>{const r=(0,w.forwardRef)(({className:n,...s},a)=>(0,w.createElement)(hT,{ref:a,iconNode:t,className:vp(`lucide-${cT(bp(e))}`,`lucide-${e}`,n),...s}));return r.displayName=bp(e),r},wn=ge("activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]),mT=ge("alarm-smoke",[["path",{d:"M11 21c0-2.5 2-2.5 2-5",key:"1sicvv"}],["path",{d:"M16 21c0-2.5 2-2.5 2-5",key:"1o3eny"}],["path",{d:"m19 8-.8 3a1.25 1.25 0 0 1-1.2 1H7a1.25 1.25 0 0 1-1.2-1L5 8",key:"1bvca4"}],["path",{d:"M21 3a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V4a1 1 0 0 1 1-1z",key:"x3qr1j"}],["path",{d:"M6 21c0-2.5 2-2.5 2-5",key:"i3w1gp"}]]),yp=ge("arrow-down-to-line",[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]]),gT=ge("arrow-down",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]),pT=ge("arrow-left",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]),vT=ge("arrow-right",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]),bT=ge("arrow-up-to-line",[["path",{d:"M5 3h14",key:"7usisc"}],["path",{d:"m18 13-6-6-6 6",key:"1kf1n9"}],["path",{d:"M12 7v14",key:"1akyts"}]]),yT=ge("arrow-up",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]),xT=ge("bath",[["path",{d:"M10 4 8 6",key:"1rru8s"}],["path",{d:"M17 19v2",key:"ts1sot"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M7 19v2",key:"12npes"}],["path",{d:"M9 5 7.621 3.621A2.121 2.121 0 0 0 4 5v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5",key:"14ym8i"}]]),xp=ge("battery-full",[["path",{d:"M10 10v4",key:"1mb2ec"}],["path",{d:"M14 10v4",key:"1nt88p"}],["path",{d:"M22 14v-4",key:"14q9d5"}],["path",{d:"M6 10v4",key:"1n77qd"}],["rect",{x:"2",y:"6",width:"16",height:"12",rx:"2",key:"13zb55"}]]),ST=ge("battery-low",[["path",{d:"M22 14v-4",key:"14q9d5"}],["path",{d:"M6 14v-4",key:"14a6bd"}],["rect",{x:"2",y:"6",width:"16",height:"12",rx:"2",key:"13zb55"}]]),Od=ge("battery-medium",[["path",{d:"M10 14v-4",key:"suye4c"}],["path",{d:"M22 14v-4",key:"14q9d5"}],["path",{d:"M6 14v-4",key:"14a6bd"}],["rect",{x:"2",y:"6",width:"16",height:"12",rx:"2",key:"13zb55"}]]),Sp=ge("battery-warning",[["path",{d:"M10 17h.01",key:"nbq80n"}],["path",{d:"M10 7v6",key:"nne03l"}],["path",{d:"M14 6h2a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2",key:"1m83kb"}],["path",{d:"M22 14v-4",key:"14q9d5"}],["path",{d:"M6 18H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h2",key:"h8lgfh"}]]),_T=ge("battery",[["path",{d:"M 22 14 L 22 10",key:"nqc4tb"}],["rect",{x:"2",y:"6",width:"16",height:"12",rx:"2",key:"13zb55"}]]),wT=ge("bell-ring",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M22 8c0-2.3-.8-4.3-2-6",key:"5bb3ad"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}],["path",{d:"M4 2C2.8 3.7 2 5.7 2 8",key:"tap9e0"}]]),Qa=ge("bell",[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0",key:"vwvbt9"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326",key:"11g9vi"}]]),ET=ge("blinds",[["path",{d:"M3 3h18",key:"o7r712"}],["path",{d:"M20 7H8",key:"gd2fo2"}],["path",{d:"M20 11H8",key:"1ynp89"}],["path",{d:"M10 19h10",key:"19hjk5"}],["path",{d:"M8 15h12",key:"1yqzne"}],["path",{d:"M4 3v14",key:"fggqzn"}],["circle",{cx:"4",cy:"19",r:"2",key:"p3m9r0"}]]),kT=ge("bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]),Fd=ge("box",[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]),TT=ge("bug",[["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M14 7a4 4 0 0 1 4 4v3a6 6 0 0 1-12 0v-3a4 4 0 0 1 4-4z",key:"uouzyp"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M21 21a4 4 0 0 0-3.81-4",key:"1b0z45"}],["path",{d:"M21 5a4 4 0 0 1-3.55 3.97",key:"5cxbf6"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M3 21a4 4 0 0 1 3.81-4",key:"1fjd4g"}],["path",{d:"M3 5a4 4 0 0 0 3.55 3.97",key:"1d7oge"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13V6a3 3 0 1 1 6 0v1.13",key:"1vgav8"}]]),_p=ge("camera",[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z",key:"18u6gg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]),CT=ge("cast",[["path",{d:"M2 8V6a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-6",key:"3zrzxg"}],["path",{d:"M2 12a9 9 0 0 1 8 8",key:"g6cvee"}],["path",{d:"M2 16a5 5 0 0 1 4 4",key:"1y1dii"}],["line",{x1:"2",x2:"2.01",y1:"20",y2:"20",key:"xu2jvo"}]]),On=ge("check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]),fr=ge("chevron-down",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]),IT=ge("chevron-left",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]),mn=ge("chevron-right",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]),Ti=ge("chevron-up",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]),PT=ge("chevrons-down-up",[["path",{d:"m7 20 5-5 5 5",key:"13a0gw"}],["path",{d:"m7 4 5 5 5-5",key:"1kwcof"}]]),AT=ge("chevrons-up-down",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]),as=ge("circle-alert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]),jT=ge("circle-check-big",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]),NT=ge("circle-check",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]),wp=ge("circle-dot",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]),DT=ge("circle-pause",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"10",x2:"10",y1:"15",y2:"9",key:"c1nkhi"}],["line",{x1:"14",x2:"14",y1:"15",y2:"9",key:"h65svq"}]]),MT=ge("circle-plus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]),Ep=ge("circle-question-mark",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),$T=ge("circle-x",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]),Ud=ge("clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]]),RT=ge("cloud-fog",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M16 17H7",key:"pygtm1"}],["path",{d:"M17 21H9",key:"1u2q02"}]]),LT=ge("cloud-lightning",[["path",{d:"M6 16.326A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 .5 8.973",key:"1cez44"}],["path",{d:"m13 12-3 5h4l-3 5",key:"1t22er"}]]),OT=ge("cloud-rain",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M16 14v6",key:"1j4efv"}],["path",{d:"M8 14v6",key:"17c4r9"}],["path",{d:"M12 16v6",key:"c8a4gj"}]]),kp=ge("cloud-snow",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M8 19h.01",key:"puxtts"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M12 21h.01",key:"h35vbk"}],["path",{d:"M16 15h.01",key:"rnfrdf"}],["path",{d:"M16 19h.01",key:"1vcnzz"}]]),Tp=ge("cloud-sun",[["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}],["path",{d:"M15.947 12.65a4 4 0 0 0-5.925-4.128",key:"dpwdj0"}],["path",{d:"M13 22H7a5 5 0 1 1 4.9-6H13a3 3 0 0 1 0 6Z",key:"s09mg5"}]]),FT=ge("cloud",[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]]),UT=ge("copy-plus",[["line",{x1:"15",x2:"15",y1:"12",y2:"18",key:"1p7wdc"}],["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]),ii=ge("copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]),BT=ge("cpu",[["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M17 20v2",key:"1rnc9c"}],["path",{d:"M17 2v2",key:"11trls"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M2 17h2",key:"7oei6x"}],["path",{d:"M2 7h2",key:"asdhe0"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"M20 17h2",key:"1fpfkl"}],["path",{d:"M20 7h2",key:"1o8tra"}],["path",{d:"M7 20v2",key:"4gnj0m"}],["path",{d:"M7 2v2",key:"1i4yhu"}],["rect",{x:"4",y:"4",width:"16",height:"16",rx:"2",key:"1vbyd7"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]]),Bd=ge("crosshair",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"22",x2:"18",y1:"12",y2:"12",key:"l9bcsi"}],["line",{x1:"6",x2:"2",y1:"12",y2:"12",key:"13hhkx"}],["line",{x1:"12",x2:"12",y1:"6",y2:"2",key:"10w3f3"}],["line",{x1:"12",x2:"12",y1:"22",y2:"18",key:"15g9kq"}]]),zT=ge("database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]),GT=ge("door-closed",[["path",{d:"M10 12h.01",key:"1kxr2c"}],["path",{d:"M18 20V6a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v14",key:"36qu9e"}],["path",{d:"M2 20h20",key:"owomy5"}]]),Ya=ge("door-open",[["path",{d:"M11 20H2",key:"nlcfvz"}],["path",{d:"M11 4.562v16.157a1 1 0 0 0 1.242.97L19 20V5.562a2 2 0 0 0-1.515-1.94l-4-1A2 2 0 0 0 11 4.561z",key:"au4z13"}],["path",{d:"M11 4H8a2 2 0 0 0-2 2v14",key:"74r1mk"}],["path",{d:"M14 12h.01",key:"1jfl7z"}],["path",{d:"M22 20h-3",key:"vhrsz"}]]),Xa=ge("download",[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]]),Cp=ge("droplet",[["path",{d:"M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z",key:"c7niix"}]]),zd=ge("droplets",[["path",{d:"M7 16.3c2.2 0 4-1.83 4-4.05 0-1.16-.57-2.26-1.71-3.19S7.29 6.75 7 5.3c-.29 1.45-1.14 2.84-2.29 3.76S3 11.1 3 12.25c0 2.22 1.8 4.05 4 4.05z",key:"1ptgy4"}],["path",{d:"M12.56 6.6A10.97 10.97 0 0 0 14 3.02c.5 2.5 2 4.9 4 6.5s3 3.5 3 5.5a6.98 6.98 0 0 1-11.91 4.97",key:"1sl1rz"}]]),ZT=ge("ellipsis-vertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]),Ip=ge("external-link",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]),vl=ge("eye-off",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),Ja=ge("eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),Gd=ge("fan",[["path",{d:"M10.827 16.379a6.082 6.082 0 0 1-8.618-7.002l5.412 1.45a6.082 6.082 0 0 1 7.002-8.618l-1.45 5.412a6.082 6.082 0 0 1 8.618 7.002l-5.412-1.45a6.082 6.082 0 0 1-7.002 8.618l1.45-5.412Z",key:"484a7f"}],["path",{d:"M12 12v.01",key:"u5ubse"}]]),Pp=ge("film",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]]),VT=ge("flame",[["path",{d:"M12 3q1 4 4 6.5t3 5.5a1 1 0 0 1-14 0 5 5 0 0 1 1-3 1 1 0 0 0 5 0c0-2-1.5-3-1.5-5q0-2 2.5-4",key:"1slcih"}]]),HT=ge("flashlight",[["path",{d:"M12 13v1",key:"176q98"}],["path",{d:"M17 2a1 1 0 0 1 1 1v4a3 3 0 0 1-.6 1.8l-.6.8A4 4 0 0 0 16 12v8a2 2 0 0 1-2 2H10a2 2 0 0 1-2-2v-8a4 4 0 0 0-.8-2.4l-.6-.8A3 3 0 0 1 6 7V3a1 1 0 0 1 1-1z",key:"17vh7j"}],["path",{d:"M6 6h12",key:"n6hhss"}]]),KT=ge("flask-conical",[["path",{d:"M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2",key:"18mbvz"}],["path",{d:"M6.453 15h11.094",key:"3shlmq"}],["path",{d:"M8.5 2h7",key:"csnxdl"}]]),WT=ge("footprints",[["path",{d:"M4 16v-2.38C4 11.5 2.97 10.5 3 8c.03-2.72 1.49-6 4.5-6C9.37 2 10 3.8 10 5.5c0 3.11-2 5.66-2 8.68V16a2 2 0 1 1-4 0Z",key:"1dudjm"}],["path",{d:"M20 20v-2.38c0-2.12 1.03-3.12 1-5.62-.03-2.72-1.49-6-4.5-6C14.63 6 14 7.8 14 9.5c0 3.11 2 5.66 2 8.68V20a2 2 0 1 0 4 0Z",key:"l2t8xc"}],["path",{d:"M16 17h4",key:"1dejxt"}],["path",{d:"M4 13h4",key:"1bwh8b"}]]),Ap=ge("funnel",[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]]),qT=ge("gamepad-2",[["line",{x1:"6",x2:"10",y1:"11",y2:"11",key:"1gktln"}],["line",{x1:"8",x2:"8",y1:"9",y2:"13",key:"qnk9ow"}],["line",{x1:"15",x2:"15.01",y1:"12",y2:"12",key:"krot7o"}],["line",{x1:"18",x2:"18.01",y1:"10",y2:"10",key:"1lcuu1"}],["path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z",key:"mfqc10"}]]),eo=ge("gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]),QT=ge("grid-2x2",[["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 12h18",key:"1i2n21"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]]),YT=ge("grip-horizontal",[["circle",{cx:"12",cy:"9",r:"1",key:"124mty"}],["circle",{cx:"19",cy:"9",r:"1",key:"1ruzo2"}],["circle",{cx:"5",cy:"9",r:"1",key:"1a8b28"}],["circle",{cx:"12",cy:"15",r:"1",key:"1e56xg"}],["circle",{cx:"19",cy:"15",r:"1",key:"1a92ep"}],["circle",{cx:"5",cy:"15",r:"1",key:"5r1jwy"}]]),XT=ge("hard-drive",[["path",{d:"M10 16h.01",key:"1bzywj"}],["path",{d:"M2.212 11.577a2 2 0 0 0-.212.896V18a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5.527a2 2 0 0 0-.212-.896L18.55 5.11A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"18tbho"}],["path",{d:"M21.946 12.013H2.054",key:"zqlbp7"}],["path",{d:"M6 16h.01",key:"1pmjb7"}]]),JT=ge("hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]),eC=ge("hexagon",[["path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}]]),os=ge("house",[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"r6nss1"}]]),jp=ge("image-off",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]),Np=ge("image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]),tC=ge("inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]),rC=ge("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]),nC=ge("layout-grid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]),Zd=ge("lightbulb",[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]]),Dp=ge("list-checks",[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}]]),iC=ge("list",[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]]),hr=ge("loader-circle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]),sC=ge("locate-fixed",[["line",{x1:"2",x2:"5",y1:"12",y2:"12",key:"bvdh0s"}],["line",{x1:"19",x2:"22",y1:"12",y2:"12",key:"1tbv5k"}],["line",{x1:"12",x2:"12",y1:"2",y2:"5",key:"11lu5j"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}],["circle",{cx:"12",cy:"12",r:"7",key:"fim9np"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),Vd=ge("lock-open",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]]),Hd=ge("lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]),aC=ge("mail",[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7",key:"132q7q"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}]]),oC=ge("map-pin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]),Mp=ge("maximize-2",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]),lC=ge("megaphone",[["path",{d:"M11 6a13 13 0 0 0 8.4-2.8A1 1 0 0 1 21 4v12a1 1 0 0 1-1.6.8A13 13 0 0 0 11 14H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2z",key:"q8bfy3"}],["path",{d:"M6 14a12 12 0 0 0 2.4 7.2 2 2 0 0 0 3.2-2.4A8 8 0 0 1 10 14",key:"1853fq"}],["path",{d:"M8 6v8",key:"15ugcq"}]]),cC=ge("menu",[["path",{d:"M4 5h16",key:"1tepv9"}],["path",{d:"M4 12h16",key:"1lakjw"}],["path",{d:"M4 19h16",key:"1djgab"}]]),uC=ge("message-square",[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]]),$p=ge("mic",[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]]),Rp=ge("minimize-2",[["path",{d:"m14 10 7-7",key:"oa77jy"}],["path",{d:"M20 10h-6V4",key:"mjg0md"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M4 14h6v6",key:"rmj7iw"}]]),Lp=ge("minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]),dC=ge("monitor-play",[["path",{d:"M15.033 9.44a.647.647 0 0 1 0 1.12l-4.065 2.352a.645.645 0 0 1-.968-.56V7.648a.645.645 0 0 1 .967-.56z",key:"vbtd3f"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",key:"x3v2xh"}]]),bl=ge("moon",[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401",key:"kfwtm"}]]),Op=ge("mouse-pointer-click",[["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z",key:"s0h3yz"}]]),fC=ge("move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]),hC=ge("music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]),mC=ge("navigation",[["polygon",{points:"3 11 22 2 13 21 11 13 3 11",key:"1ltx0t"}]]),Fp=ge("network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]),to=ge("pause",[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1",key:"kaeet6"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1",key:"1wsw3u"}]]),gC=ge("pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]),pC=ge("pipette",[["path",{d:"m12 9-8.414 8.414A2 2 0 0 0 3 18.828v1.344a2 2 0 0 1-.586 1.414A2 2 0 0 1 3.828 21h1.344a2 2 0 0 0 1.414-.586L15 12",key:"1y3wsu"}],["path",{d:"m18 9 .4.4a1 1 0 1 1-3 3l-3.8-3.8a1 1 0 1 1 3-3l.4.4 3.4-3.4a1 1 0 1 1 3 3z",key:"110lr1"}],["path",{d:"m2 22 .414-.414",key:"jhxm08"}]]),Fn=ge("play",[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z",key:"10ikf1"}]]),Ci=ge("plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]),vC=ge("plug",[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]]),bC=ge("power-off",[["path",{d:"M18.36 6.64A9 9 0 0 1 20.77 15",key:"dxknvb"}],["path",{d:"M6.16 6.16a9 9 0 1 0 12.68 12.68",key:"1x7qb5"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),yl=ge("power",[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]]),yC=ge("qr-code",[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]]),xC=ge("radar",[["path",{d:"M19.07 4.93A10 10 0 0 0 6.99 3.34",key:"z3du51"}],["path",{d:"M4 6h.01",key:"oypzma"}],["path",{d:"M2.29 9.62A10 10 0 1 0 21.31 8.35",key:"qzzz0"}],["path",{d:"M16.24 7.76A6 6 0 1 0 8.23 16.67",key:"1yjesh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M17.99 11.66A6 6 0 0 1 15.77 16.67",key:"1u2y91"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"m13.41 10.59 5.66-5.66",key:"mhq4k0"}]]),Up=ge("radio",[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]),Ii=ge("refresh-cw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]),Kd=ge("rotate-ccw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]),Wd=ge("rotate-cw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]),Bp=ge("save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]),SC=ge("scan",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}]]),zp=ge("scroll-text",[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]]),ls=ge("search",[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]),_C=ge("server",[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]]),wC=ge("settings",[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915",key:"1i5ecw"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]),qd=ge("share-2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]),Qd=ge("shield-alert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]),EC=ge("shield-check",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]),kC=ge("shield-off",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]]),Gp=ge("shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]),TC=ge("ship",[["path",{d:"M12 10.189V14",key:"1p8cqu"}],["path",{d:"M12 2v3",key:"qbqxhf"}],["path",{d:"M19 13V7a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v6",key:"qpkstq"}],["path",{d:"M19.38 20A11.6 11.6 0 0 0 21 14l-8.188-3.639a2 2 0 0 0-1.624 0L3 14a11.6 11.6 0 0 0 2.81 7.76",key:"7tigtc"}],["path",{d:"M2 21c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1s1.2 1 2.5 1c2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"1924j5"}]]),Zp=ge("siren",[["path",{d:"M7 18v-6a5 5 0 1 1 10 0v6",key:"pcx96s"}],["path",{d:"M5 21a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2z",key:"1b4s83"}],["path",{d:"M21 12h1",key:"jtio3y"}],["path",{d:"M18.5 4.5 18 5",key:"g5sp9y"}],["path",{d:"M2 12h1",key:"1uaihz"}],["path",{d:"M12 2v1",key:"11qlp1"}],["path",{d:"m4.929 4.929.707.707",key:"1i51kw"}],["path",{d:"M12 12v6",key:"3ahymv"}]]),CC=ge("skip-back",[["path",{d:"M17.971 4.285A2 2 0 0 1 21 6v12a2 2 0 0 1-3.029 1.715l-9.997-5.998a2 2 0 0 1-.003-3.432z",key:"15892j"}],["path",{d:"M3 20V4",key:"1ptbpl"}]]),IC=ge("skip-forward",[["path",{d:"M21 4v16",key:"7j8fe9"}],["path",{d:"M6.029 4.285A2 2 0 0 0 3 6v12a2 2 0 0 0 3.029 1.715l9.997-5.998a2 2 0 0 0 .003-3.432z",key:"zs4d6"}]]),Yd=ge("sliders-horizontal",[["path",{d:"M10 5H3",key:"1qgfaw"}],["path",{d:"M12 19H3",key:"yhmn1j"}],["path",{d:"M14 3v4",key:"1sua03"}],["path",{d:"M16 17v4",key:"1q0r14"}],["path",{d:"M21 12h-9",key:"1o4lsq"}],["path",{d:"M21 19h-5",key:"1rlt1p"}],["path",{d:"M21 5h-7",key:"1oszz2"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M8 12H3",key:"a7s4jb"}]]),PC=ge("smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]),Un=ge("square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]),AC=ge("star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]),Xd=ge("sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]),jC=ge("table-2",[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]]),Vp=ge("target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]),Jd=ge("thermometer",[["path",{d:"M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"17jzev"}]]),ef=ge("toggle-left",[["circle",{cx:"9",cy:"12",r:"3",key:"u3jwor"}],["rect",{width:"20",height:"14",x:"2",y:"5",rx:"7",key:"g7kal2"}]]),NC=ge("tractor",[["path",{d:"m10 11 11 .9a1 1 0 0 1 .8 1.1l-.665 4.158a1 1 0 0 1-.988.842H20",key:"she1j9"}],["path",{d:"M16 18h-5",key:"bq60fd"}],["path",{d:"M18 5a1 1 0 0 0-1 1v5.573",key:"1kv8ia"}],["path",{d:"M3 4h8.129a1 1 0 0 1 .99.863L13 11.246",key:"1q1ert"}],["path",{d:"M4 11V4",key:"9ft8pt"}],["path",{d:"M7 15h.01",key:"k5ht0j"}],["path",{d:"M8 10.1V4",key:"1jgyzo"}],["circle",{cx:"18",cy:"18",r:"2",key:"1emm8v"}],["circle",{cx:"7",cy:"15",r:"5",key:"ddtuc"}]]),en=ge("trash-2",[["path",{d:"M10 11v6",key:"nco0om"}],["path",{d:"M14 11v6",key:"outv1u"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6",key:"miytrc"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2",key:"e791ji"}]]),DC=ge("trending-up",[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]]),MC=ge("trending-down",[["path",{d:"M16 17h6v-6",key:"t6n2it"}],["path",{d:"m22 17-8.5-8.5-5 5L2 7",key:"x473p"}]]),cs=ge("triangle-alert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]),$C=ge("type",[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]]),RC=ge("unlink-2",[["path",{d:"M15 7h2a5 5 0 0 1 0 10h-2m-6 0H7A5 5 0 0 1 7 7h2",key:"1re2ne"}]]),Hp=ge("upload",[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m17 8-5-5-5 5",key:"7q97r8"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}]]),LC=ge("vibrate",[["path",{d:"m2 8 2 2-2 2 2 2-2 2",key:"sv1b1"}],["path",{d:"m22 8-2 2 2 2-2 2 2 2",key:"101i4y"}],["rect",{width:"8",height:"14",x:"8",y:"5",rx:"1",key:"1oyrl4"}]]),tf=ge("volume-2",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]),OC=ge("volume-x",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]]),FC=ge("waves",[["path",{d:"M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"knzxuh"}],["path",{d:"M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"2jd2cc"}],["path",{d:"M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"rd2r6e"}]]),Kp=ge("wifi-off",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]),rf=ge("wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]),xl=ge("wind",[["path",{d:"M12.8 19.6A2 2 0 1 0 14 16H2",key:"148xed"}],["path",{d:"M17.5 8a2.5 2.5 0 1 1 2 4H2",key:"1u4tom"}],["path",{d:"M9.8 4.4A2 2 0 1 1 11 8H2",key:"75valh"}]]),UC=ge("workflow",[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]]),BC=ge("wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]]),mr=ge("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]),si=ge("zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]),Wp=ge("zoom-in",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),qp=ge("zoom-out",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]),zC={frigate:TC,scrypted:Gp,reolink:Up,homeAssistant:os,rtsp:CT},GC={online:NT,offline:$T,degraded:as,unknown:Ep},Qp=e=>typeof e=="boolean"?`${e}`:e===0?"0":e,Yp=tt,Pi=(e,t)=>r=>{var n;if(t?.variants==null)return Yp(e,r?.class,r?.className);const{variants:s,defaultVariants:a}=t,c=Object.keys(s).map(u=>{const f=r?.[u],h=a?.[u];if(f===null)return null;const m=Qp(f)||Qp(h);return s[u][m]}),d=r&&Object.entries(r).reduce((u,f)=>{let[h,m]=f;return m===void 0||(u[h]=m),u},{});return Yp(e,c,t==null||(n=t.compoundVariants)===null||n===void 0?void 0:n.reduce((u,f)=>{let{class:h,className:m,...g}=f;return Object.entries(g).every(p=>{let[y,S]=p;return Array.isArray(S)?S.includes({...a,...d}[y]):{...a,...d}[y]===S})?[...u,h,m]:u},[]),r?.class,r?.className)},ZC=Pi("inline-flex items-center justify-center rounded-md font-medium transition-colors cursor-pointer disabled:opacity-50 disabled:pointer-events-none",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary/90",secondary:"bg-surface text-foreground hover:bg-surface-hover",ghost:"hover:bg-surface-hover text-foreground-muted",danger:"bg-danger text-white hover:bg-danger/90",outline:"border border-border bg-transparent hover:bg-surface-hover"},size:{sm:"h-7 px-2.5 text-xs gap-1.5",md:"h-8 px-3 text-sm gap-2",lg:"h-9 px-4 text-sm gap-2"}},defaultVariants:{variant:"primary",size:"sm"}}),tn=(0,l.forwardRef)(({className:e,variant:t,size:r,...n},s)=>(0,i.jsx)("button",{ref:s,className:A(ZC({variant:t,size:r}),e),...n}));tn.displayName="Button";var VC=Pi("inline-flex items-center justify-center rounded-md font-medium transition-colors cursor-pointer disabled:opacity-50 disabled:pointer-events-none",{variants:{variant:{primary:"bg-primary text-primary-foreground hover:bg-primary/90",secondary:"bg-surface text-foreground hover:bg-surface-hover",ghost:"hover:bg-surface-hover text-foreground-muted",danger:"bg-danger text-white hover:bg-danger/90",outline:"border border-border bg-transparent hover:bg-surface-hover"},size:{sm:"h-7 w-7",md:"h-8 w-8",lg:"h-9 w-9"}},defaultVariants:{variant:"primary",size:"sm"}}),nf=(0,l.forwardRef)(({className:e,variant:t,size:r,icon:n,...s},a)=>(0,i.jsx)("button",{ref:a,className:A(VC({variant:t,size:r}),e),...s,children:(0,i.jsx)(n,{className:"h-4 w-4"})}));nf.displayName="IconButton";var HC=Pi("inline-flex items-center rounded-full text-xs font-medium px-2 py-0.5",{variants:{variant:{default:"bg-surface-hover text-foreground",success:"bg-success/15 text-success",warning:"bg-warning/15 text-warning",danger:"bg-danger/15 text-danger",info:"bg-info/15 text-info"},styleVariant:{solid:"",outline:"border bg-transparent"}},defaultVariants:{variant:"default",styleVariant:"solid"}}),Ai=(0,l.forwardRef)(({className:e,variant:t,style:r,...n},s)=>(0,i.jsx)("span",{ref:s,className:A(HC({variant:t,styleVariant:r}),e),...n}));Ai.displayName="Badge";var KC=Pi("rounded-lg p-3",{variants:{variant:{flat:"bg-surface",bordered:"bg-surface border border-border"}},defaultVariants:{variant:"bordered"}}),sf=(0,l.forwardRef)(({className:e,variant:t,...r},n)=>(0,i.jsx)("div",{ref:n,className:A(KC({variant:t}),e),...r}));sf.displayName="Card";function Xp({expanded:e,onExpandedChange:t,header:r,children:n,dimmed:s=!1,hideChevron:a=!1,className:c}){return(0,i.jsxs)("div",{className:A("rounded-lg border border-border bg-surface overflow-hidden",s&&"opacity-[0.45]",c),children:[(0,i.jsxs)("div",{role:"button",tabIndex:0,className:"flex items-center gap-2.5 px-3 py-2.5 cursor-pointer select-none",onClick:()=>t(!e),onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),t(!e))},children:[!a&&(0,i.jsx)("span",{className:"text-foreground-subtle shrink-0",children:e?(0,i.jsx)(fr,{className:"h-4 w-4"}):(0,i.jsx)(mn,{className:"h-4 w-4"})}),r]}),e&&n&&(0,i.jsx)("div",{className:"border-t border-border px-3 py-3",children:n})]})}var af=(0,l.forwardRef)(({className:e,...t},r)=>(0,i.jsx)("label",{ref:r,className:A("text-[10px] uppercase tracking-wider text-foreground-muted font-medium",e),...t}));af.displayName="Label";var WC=Pi("",{variants:{orientation:{horizontal:"h-px w-full bg-border-subtle",vertical:"w-px h-full bg-border-subtle"}},defaultVariants:{orientation:"horizontal"}}),of=(0,l.forwardRef)(({className:e,orientation:t,...r},n)=>(0,i.jsx)("div",{ref:n,role:"separator",className:A(WC({orientation:t}),e),...r}));of.displayName="Separator";var Jp=(0,l.forwardRef)(({className:e,...t},r)=>(0,i.jsx)("div",{ref:r,className:A("animate-pulse bg-surface-hover rounded-md h-4 w-full",e),...t}));Jp.displayName="Skeleton";var ev=Pi("h-7 w-full px-2.5 text-xs bg-surface border rounded-md text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary transition-colors",{variants:{state:{default:"border-border",error:"border-danger"}},defaultVariants:{state:"default"}}),Sl=(0,l.forwardRef)(({className:e,state:t,leftSlot:r,rightSlot:n,...s},a)=>r||n?(0,i.jsxs)("div",{className:"relative flex items-center w-full",children:[r&&(0,i.jsx)("div",{className:"absolute left-2.5 flex items-center pointer-events-none",children:r}),(0,i.jsx)("input",{ref:a,className:A(ev({state:t}),r?"pl-7":"",n?"pr-7":"",e),...s}),n&&(0,i.jsx)("div",{className:"absolute right-2.5 flex items-center pointer-events-none",children:n})]}):(0,i.jsx)("input",{ref:a,className:A(ev({state:t}),e),...s}));Sl.displayName="Input";var ro=(0,l.forwardRef)(({className:e,options:t,...r},n)=>(0,i.jsxs)("div",{className:"relative w-full",children:[(0,i.jsx)("select",{ref:n,className:A("h-7 w-full px-2.5 text-xs bg-surface border border-border rounded-md text-foreground appearance-none pr-7 focus:outline-none focus:ring-1 focus:ring-primary",e),...r,children:t.map(s=>(0,i.jsx)("option",{value:s.value,children:s.label},s.value))}),(0,i.jsx)("div",{className:"absolute right-2 top-1/2 -translate-y-1/2 pointer-events-none text-foreground-muted",children:(0,i.jsx)(fr,{className:"h-3.5 w-3.5"})})]}));ro.displayName="Select";var tv=(0,l.forwardRef)(({className:e,...t},r)=>(0,i.jsx)("input",{ref:r,type:"checkbox",className:A("w-3.5 h-3.5 rounded-sm border border-border accent-primary",e),...t}));tv.displayName="Checkbox";var rv=(0,l.forwardRef)(({className:e,checked:t,onCheckedChange:r,label:n,...s},a)=>(0,i.jsxs)("button",{ref:a,role:"switch","aria-checked":t,type:"button",onClick:()=>r(!t),className:A("inline-flex items-center gap-2",e),...s,children:[(0,i.jsx)("span",{className:A("w-8 h-4 rounded-full transition-colors",t?"bg-primary":"bg-surface-hover"),children:(0,i.jsx)("span",{className:A("block w-3.5 h-3.5 rounded-full bg-white transition-transform",t?"translate-x-4":"translate-x-0.5")})}),n&&(0,i.jsx)("span",{className:"text-xs text-foreground",children:n})]}));rv.displayName="Switch";var nv=(0,l.createContext)(null);function iv(){const e=(0,l.useContext)(nv);if(!e)throw new Error("Dialog compound components must be used within <Dialog>");return e}function _l({children:e,open:t,onOpenChange:r}){const[n,s]=(0,l.useState)(!1),a=t??n,c=(0,l.useId)(),d=(0,l.useCallback)(u=>{r?.(u),t===void 0&&s(u)},[t,r]);return(0,i.jsx)(nv.Provider,{value:{open:a,setOpen:d,contentId:c},children:e})}function qC({children:e,...t}){const{setOpen:r}=iv();return(0,i.jsx)("button",{type:"button",onClick:()=>r(!0),...t,children:e})}var QC=Pi("fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 m-0 w-[calc(100vw-2rem)] bg-background-elevated border border-border rounded-lg p-4 backdrop:bg-black/50 backdrop:backdrop-blur-sm max-h-[calc(100dvh-2rem)] overflow-y-auto",{variants:{width:{sm:"max-w-sm",md:"max-w-md",lg:"max-w-lg"}},defaultVariants:{width:"md"}}),no=(0,l.forwardRef)(({className:e,width:t,children:r,...n},s)=>{const{open:a,setOpen:c,contentId:d}=iv(),u=(0,l.useRef)(null),f=s??u;(0,l.useEffect)(()=>{const m=f.current;m&&(a&&!m.open&&m.showModal(),!a&&m.open&&m.close())},[a,f]);const h=m=>{m.target===m.currentTarget&&c(!1)};return(0,i.jsx)("dialog",{ref:f,id:d,className:A(QC({width:t}),e),onClick:h,onClose:()=>c(!1),...n,children:r})});no.displayName="DialogContent";function wl({className:e,...t}){return(0,i.jsx)("div",{className:A("flex flex-col gap-1 mb-3",e),...t})}function El({className:e,...t}){return(0,i.jsx)("div",{className:A("flex justify-end gap-2 mt-4",e),...t})}function kl({className:e,...t}){return(0,i.jsx)("h2",{className:A("text-sm font-semibold text-foreground",e),...t})}function Tl({className:e,...t}){return(0,i.jsx)("p",{className:A("text-xs text-foreground-muted",e),...t})}var sv=(0,l.createContext)(null);function lf(){const e=(0,l.useContext)(sv);if(!e)throw new Error("Dropdown compound components must be used within <Dropdown>");return e}function YC({children:e}){const[t,r]=(0,l.useState)(!1),n=(0,l.useId)(),s=(0,l.useId)(),a=(0,l.useRef)(null);return(0,i.jsx)(sv.Provider,{value:{open:t,setOpen:r,triggerId:n,contentId:s,triggerRef:a},children:(0,i.jsx)("div",{className:"relative inline-block",children:e})})}function XC({children:e,...t}){const{open:r,setOpen:n,triggerId:s,contentId:a,triggerRef:c}=lf();return(0,i.jsx)("button",{type:"button",ref:c,id:s,"aria-haspopup":"menu","aria-expanded":r,"aria-controls":r?a:void 0,onClick:()=>n(!r),...t,children:e})}function JC({className:e,children:t,align:r="start",offset:n=4,...s}){const{open:a,setOpen:c,contentId:d,triggerId:u,triggerRef:f}=lf(),h=(0,l.useRef)(null),[m,g]=(0,l.useState)(null);return(0,l.useLayoutEffect)(()=>{if(!a){g(null);return}const p=()=>{const y=f.current;if(!y)return;const S=y.getBoundingClientRect(),E=r==="end"?S.right:S.left;g({top:S.bottom+n,left:E,minWidth:S.width})};return p(),window.addEventListener("resize",p),window.addEventListener("scroll",p,!0),()=>{window.removeEventListener("resize",p),window.removeEventListener("scroll",p,!0)}},[a,r,n,f]),(0,l.useEffect)(()=>{if(!a)return;const p=S=>{const E=h.current,T=f.current;E&&!E.contains(S.target)&&!T?.contains(S.target)&&c(!1)},y=S=>{S.key==="Escape"&&c(!1)};return document.addEventListener("mousedown",p),document.addEventListener("keydown",y),()=>{document.removeEventListener("mousedown",p),document.removeEventListener("keydown",y)}},[a,c,f]),!a||!m||typeof document>"u"?null:(0,I.createPortal)((0,i.jsx)("div",{ref:h,id:d,role:"menu","aria-labelledby":u,style:{position:"fixed",top:m.top,...r==="end"?{right:window.innerWidth-m.left}:{left:m.left},minWidth:m.minWidth},className:A("z-50 bg-background-elevated border border-border rounded-md shadow-lg py-1 min-w-[160px]",e),...s,children:t}),document.body)}function eI({className:e,icon:t,variant:r="default",children:n,onClick:s,...a}){const{setOpen:c}=lf(),d=(0,l.useCallback)(u=>{s?.(u),c(!1)},[s,c]);return(0,i.jsxs)("button",{type:"button",role:"menuitem",className:A("h-7 text-xs px-2 w-full text-left flex items-center gap-2",r==="danger"?"text-danger hover:bg-danger/10":"text-foreground hover:bg-surface-hover",e),onClick:d,...a,children:[t&&(0,i.jsx)(t,{size:14}),n]})}var av=(0,l.createContext)(null);function ov(){const e=(0,l.useContext)(av);if(!e)throw new Error("Tooltip compound components must be used within <Tooltip>");return e}function lv({children:e,className:t}){const[r,n]=(0,l.useState)(!1),s=(0,l.useRef)(null),a=(0,l.useId)(),c=()=>{s.current=setTimeout(()=>n(!0),300)},d=()=>{s.current&&clearTimeout(s.current),n(!1)};return(0,i.jsx)(av.Provider,{value:{open:r,show:c,hide:d,tooltipId:a},children:(0,i.jsx)("div",{className:A("relative",t??"inline-block"),children:e})})}function cv({children:e,...t}){const{show:r,hide:n,tooltipId:s,open:a}=ov();return(0,i.jsx)("div",{onMouseEnter:r,onMouseLeave:n,onFocus:r,onBlur:n,"aria-describedby":a?s:void 0,...t,children:e})}function uv({className:e,children:t,...r}){const{open:n,tooltipId:s}=ov();return(0,i.jsx)("div",{id:s,role:"tooltip",className:A("absolute bottom-full left-1/2 -translate-x-1/2 mb-2 bg-foreground text-background text-xs px-2 py-1 rounded-md shadow-md whitespace-nowrap pointer-events-none transition-opacity duration-150",n?"opacity-100":"opacity-0",e),...r,children:t})}var dv="(max-width: 767px)",fv="(min-width: 768px) and (max-width: 1023px)";function hv(e){return t=>{const r=window.matchMedia(e);return r.addEventListener("change",t),()=>r.removeEventListener("change",t)}}function mv(e){return()=>window.matchMedia(e).matches}function gv(){return!1}function io(){return(0,l.useSyncExternalStore)(hv(dv),mv(dv),gv)}function tI(){return(0,l.useSyncExternalStore)(hv(fv),mv(fv),gv)}function cf({open:e,onClose:t,title:r,children:n,className:s}){return(0,l.useEffect)(()=>{if(!e)return;const a=c=>{c.key==="Escape"&&t()};return document.addEventListener("keydown",a),document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",a),document.body.style.overflow=""}},[e,t]),(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("div",{className:A("fixed inset-0 z-40 bg-black/50 transition-opacity duration-200",e?"opacity-100":"pointer-events-none opacity-0"),onClick:t,"aria-hidden":"true"}),(0,i.jsxs)("div",{role:"dialog","aria-modal":"true",className:A("fixed inset-x-0 bottom-0 z-50 flex flex-col bg-background-elevated border-t border-border rounded-t-xl shadow-2xl transition-transform duration-200 ease-out","max-h-[80dvh]",e?"translate-y-0":"translate-y-full",s),children:[(0,i.jsx)("div",{className:"flex justify-center pt-2 pb-1",children:(0,i.jsx)("div",{className:"h-1 w-8 rounded-full bg-foreground-subtle/30"})}),r&&(0,i.jsxs)("div",{className:"flex items-center justify-between px-4 pb-2",children:[(0,i.jsx)("span",{className:"text-sm font-medium text-foreground",children:r}),(0,i.jsx)("button",{onClick:t,className:"p-1 rounded-md hover:bg-surface-hover text-foreground-muted transition-colors",children:(0,i.jsx)(mr,{className:"h-4 w-4"})})]}),(0,i.jsx)("div",{className:"flex-1 overflow-y-auto px-4 pb-4",children:n})]})]})}var pv=(0,l.createContext)(null);function vv(){const e=(0,l.useContext)(pv);if(!e)throw new Error("Popover compound components must be used within <Popover>");return e}function bv({children:e,open:t,onOpenChange:r}){const[n,s]=(0,l.useState)(!1),a=t??n,c=(0,l.useId)(),d=(0,l.useId)(),u=(0,l.useCallback)(f=>{r?.(f),t===void 0&&s(f)},[t,r]);return(0,i.jsx)(pv.Provider,{value:{open:a,setOpen:u,triggerId:c,contentId:d},children:(0,i.jsx)("div",{className:"relative inline-block",children:e})})}function yv({children:e,...t}){const{open:r,setOpen:n,triggerId:s,contentId:a}=vv();return(0,i.jsx)("button",{type:"button",id:s,"aria-haspopup":"dialog","aria-expanded":r,"aria-controls":r?a:void 0,onClick:()=>n(!r),...t,children:e})}function xv({className:e,children:t,...r}){const{open:n,setOpen:s,contentId:a,triggerId:c}=vv(),d=io(),u=(0,l.useRef)(null);return(0,l.useEffect)(()=>{if(!n||d)return;const f=m=>{const g=u.current,p=document.getElementById(c);g&&!g.contains(m.target)&&!p?.contains(m.target)&&s(!1)},h=m=>{m.key==="Escape"&&s(!1)};return document.addEventListener("mousedown",f),document.addEventListener("keydown",h),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("keydown",h)}},[n,s,c,d]),n?d?(0,i.jsx)(cf,{open:n,onClose:()=>s(!1),children:t}):(0,i.jsx)("div",{ref:u,id:a,role:"dialog","aria-labelledby":c,className:A("absolute left-0 top-full z-50 mt-1 bg-background-elevated border border-border rounded-lg shadow-lg p-3",e),...r,children:t}):null}var Sv=(0,l.createContext)(null);function _v(){const e=(0,l.useContext)(Sv);if(!e)throw new Error("Tabs compound components must be used within <Tabs>");return e}function rI({value:e,onValueChange:t,defaultValue:r="",className:n,...s}){const[a,c]=(0,l.useState)(r),d=e??a,u=(0,l.useCallback)(f=>{t?.(f),e===void 0&&c(f)},[e,t]);return(0,i.jsx)(Sv.Provider,{value:{value:d,setValue:u},children:(0,i.jsx)("div",{className:n,...s})})}function nI({className:e,...t}){return(0,i.jsx)("div",{role:"tablist",className:A("flex flex-row border-b border-border-subtle",e),...t})}function iI({value:e,className:t,...r}){const{value:n,setValue:s}=_v(),a=e===n;return(0,i.jsx)("button",{type:"button",role:"tab","aria-selected":a,"aria-controls":`tabpanel-${e}`,tabIndex:a?0:-1,className:A("h-7 text-xs px-3 transition-colors",a?"border-b-2 border-primary text-foreground font-medium":"text-foreground-muted hover:text-foreground",t),onClick:()=>s(e),...r})}function sI({value:e,className:t,...r}){const{value:n}=_v();return e!==n?null:(0,i.jsx)("div",{role:"tabpanel",id:`tabpanel-${e}`,className:A("pt-3",t),...r})}var uf=(0,l.forwardRef)(({className:e,...t},r)=>(0,i.jsx)("div",{ref:r,className:A("overflow-auto [&::-webkit-scrollbar]:w-1 [&::-webkit-scrollbar-track]:bg-transparent [&::-webkit-scrollbar-thumb]:bg-surface-hover [&::-webkit-scrollbar-thumb]:rounded-full",e),...t}));uf.displayName="ScrollArea";function aI({title:e,onClose:t,children:r,defaultWidth:n=360,defaultHeight:s=280,minWidth:a=280,minHeight:c=160,offsetIndex:d=0,className:u}){const[f,h]=(0,l.useState)({x:80+d*30,y:80+d*30}),[m,g]=(0,l.useState)({w:n,h:s}),[p,y]=(0,l.useState)(!1),S=(0,l.useRef)(!1),E=(0,l.useRef)(!1),T=(0,l.useRef)({x:0,y:0}),j=io(),N=(0,l.useCallback)(U=>{U.preventDefault(),S.current=!0,T.current={x:U.clientX-f.x,y:U.clientY-f.y}},[f]),O=(0,l.useCallback)(U=>{U.preventDefault(),U.stopPropagation(),E.current=!0,T.current={x:U.clientX,y:U.clientY}},[]);return(0,l.useEffect)(()=>{const U=K=>{if(S.current&&h({x:K.clientX-T.current.x,y:K.clientY-T.current.y}),E.current){const G=K.clientX-T.current.x,X=K.clientY-T.current.y;T.current={x:K.clientX,y:K.clientY},g(te=>({w:Math.max(a,te.w+G),h:Math.max(c,te.h+X)}))}},z=()=>{S.current=!1,E.current=!1};return window.addEventListener("mousemove",U),window.addEventListener("mouseup",z),()=>{window.removeEventListener("mousemove",U),window.removeEventListener("mouseup",z)}},[a,c]),j?(0,i.jsxs)("div",{className:A("fixed inset-x-0 bottom-0 z-50 rounded-t-xl border-t border-border bg-background-elevated shadow-2xl flex flex-col overflow-hidden",u),style:{maxHeight:"60dvh"},children:[(0,i.jsxs)("div",{className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border shrink-0 bg-surface",children:[(0,i.jsx)("span",{className:"text-[11px] font-medium truncate",children:e}),(0,i.jsxs)("div",{className:"flex items-center gap-1 shrink-0",children:[(0,i.jsx)("button",{onClick:()=>y(!p),className:"p-0.5 rounded hover:bg-surface-hover text-foreground-muted transition-colors",children:p?(0,i.jsx)(Mp,{size:12}):(0,i.jsx)(Rp,{size:12})}),(0,i.jsx)("button",{onClick:t,className:"p-0.5 rounded hover:bg-danger/20 text-foreground-muted hover:text-danger transition-colors",children:(0,i.jsx)(mr,{size:12})})]})]}),!p&&(0,i.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto",children:r})]}):(0,i.jsxs)("div",{className:A("fixed z-50 rounded-lg border border-border bg-background-elevated shadow-2xl flex flex-col overflow-hidden",u),style:{left:f.x,top:f.y,width:p?280:m.w,height:p?"auto":m.h},children:[(0,i.jsxs)("div",{onMouseDown:N,className:"flex items-center justify-between gap-2 px-3 py-2 border-b border-border cursor-move select-none shrink-0 bg-surface",children:[(0,i.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,i.jsx)(YT,{size:12,className:"text-foreground-subtle shrink-0"}),(0,i.jsx)("span",{className:"text-[11px] font-medium truncate",children:e})]}),(0,i.jsxs)("div",{className:"flex items-center gap-1 shrink-0",children:[(0,i.jsx)("button",{onClick:()=>y(!p),className:"p-0.5 rounded hover:bg-surface-hover text-foreground-muted transition-colors",title:p?"Restore":"Minimize",children:p?(0,i.jsx)(Mp,{size:12}):(0,i.jsx)(Rp,{size:12})}),(0,i.jsx)("button",{onClick:t,className:"p-0.5 rounded hover:bg-danger/20 text-foreground-muted hover:text-danger transition-colors",title:"Close",children:(0,i.jsx)(mr,{size:12})})]})]}),!p&&(0,i.jsxs)("div",{className:"flex-1 min-h-0 overflow-y-auto relative",children:[r,(0,i.jsx)("div",{onMouseDown:O,className:"absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize",style:{background:"linear-gradient(135deg, transparent 50%, var(--color-foreground-subtle) 50%)",opacity:.4}})]})]})}function wv({open:e,onClose:t,children:r,className:n,width:s="w-64"}){const a=(0,l.useRef)(null);return(0,l.useEffect)(()=>{if(!e)return;const c=d=>{d.key==="Escape"&&t()};return document.addEventListener("keydown",c),document.body.style.overflow="hidden",()=>{document.removeEventListener("keydown",c),document.body.style.overflow=""}},[e,t]),(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("div",{className:A("fixed inset-0 z-40 bg-black/50 backdrop-blur-sm transition-opacity duration-200",e?"opacity-100":"pointer-events-none opacity-0"),onClick:t,"aria-hidden":"true"}),(0,i.jsx)("div",{ref:a,role:"dialog","aria-modal":"true",className:A("fixed inset-y-0 left-0 z-50 flex flex-col bg-surface border-r border-border shadow-2xl transition-transform duration-200 ease-out pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]",s,e?"translate-x-0":"-translate-x-full",n),children:r})]})}function oI({items:e,className:t}){return(0,i.jsx)("nav",{className:`hidden md:flex items-center gap-1 text-[11px] text-foreground-subtle ${t??""}`,children:e.map((r,n)=>{const s=n===e.length-1,a=!s&&(r.onClick||r.href);return(0,i.jsxs)(l.default.Fragment,{children:[n>0&&(0,i.jsx)(mn,{className:"h-3 w-3 flex-shrink-0"}),a?r.onClick?(0,i.jsx)("button",{type:"button",onClick:r.onClick,className:"hover:text-foreground transition-colors",children:r.label}):(0,i.jsx)("a",{href:r.href,className:"hover:text-foreground transition-colors",children:r.label}):(0,i.jsx)("span",{className:s?"text-foreground font-medium":"",children:r.label})]},n)})})}var Ev={left:"text-left",right:"text-right",center:"text-center"};function lI({columns:e,rows:t,rowKey:r,onRowClick:n,minWidthPx:s=480,emptyMessage:a,className:c,bordered:d=!0,rowClassName:u}){return t.length===0&&a?(0,i.jsx)("div",{className:`rounded-lg ${d?"border border-border":""} bg-surface px-3 py-4 text-xs text-foreground-subtle text-center ${c??""}`,children:a}):t.length===0?null:(0,i.jsx)("div",{className:`rounded-lg ${d?"border border-border":""} bg-surface overflow-x-auto ${c??""}`,children:(0,i.jsxs)("table",{className:"w-full text-xs",style:{minWidth:`${s}px`},children:[(0,i.jsx)("thead",{className:"bg-surface",children:(0,i.jsx)("tr",{children:e.map(f=>{const h=f.align??"left",m=f.nowrap??!0;return(0,i.jsx)("th",{className:["px-3 py-2 text-foreground-subtle font-medium bg-surface border-b border-border",Ev[h],m?"whitespace-nowrap":"",f.width??""].filter(Boolean).join(" "),children:f.headerRender?f.headerRender():f.header},f.key)})})}),(0,i.jsx)("tbody",{children:t.map((f,h)=>{const m=r?r(f,h):h,g=u?.(f,h)??"",p=n!==void 0;return(0,i.jsx)("tr",{onClick:p?()=>n(f,h):void 0,className:[p?"cursor-pointer hover:bg-primary/5":"hover:bg-primary/5",g].filter(Boolean).join(" "),children:e.map(y=>{const S=y.align??"left",E=y.nowrap??!1;return(0,i.jsx)("td",{className:["px-3 py-2 text-foreground border-b border-border",Ev[S],E?"whitespace-nowrap":""].filter(Boolean).join(" "),children:y.render(f,h)},y.key)})},m)})})]})})}function cI({open:e,onClose:t,title:r,subtitle:n,footer:s,children:a,widthClass:c="w-[360px]"}){return(0,l.useEffect)(()=>{if(!e)return;const d=u=>{u.key==="Escape"&&t()};return window.addEventListener("keydown",d),()=>window.removeEventListener("keydown",d)},[e,t]),e?(0,i.jsxs)("aside",{className:A("absolute top-0 right-0 bottom-0 z-20 flex flex-col","bg-surface border-l border-border shadow-xl",c),role:"dialog","aria-modal":"false",children:[(0,i.jsxs)("header",{className:"flex items-start justify-between gap-2 px-4 py-3 border-b border-border",children:[(0,i.jsxs)("div",{className:"min-w-0",children:[(0,i.jsx)("div",{className:"text-sm font-semibold text-foreground truncate",children:r}),n!==void 0&&(0,i.jsx)("div",{className:"text-[11px] text-foreground-subtle mt-0.5 truncate",children:n})]}),(0,i.jsx)("button",{type:"button",onClick:t,className:"p-1 rounded hover:bg-muted text-foreground-subtle hover:text-foreground","aria-label":"Close panel",children:(0,i.jsx)(mr,{className:"w-4 h-4"})})]}),(0,i.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto px-4 py-3",children:a}),s!==void 0&&(0,i.jsx)("footer",{className:"flex items-center gap-2 justify-end px-4 py-3 border-t border-border",children:s})]}):null}var uI={inherit:"bg-muted",on:"bg-emerald-500",off:"bg-orange-500",na:"bg-gray-300 opacity-50"};function kv({node:e,depth:t,selectedAddonId:r,onSelect:n,agentDots:s}){const a=e.addonId===r,c=s?.[e.addonId]??[];return(0,i.jsxs)("div",{children:[(0,i.jsxs)("button",{type:"button",onClick:()=>n(e.addonId),className:A("w-full flex items-center justify-between gap-2 text-left px-3 py-1.5 text-xs","border-l-2",a?"bg-accent border-primary text-foreground font-medium":"border-transparent hover:bg-muted/40 text-foreground"),style:{paddingLeft:`${12+t*14}px`},children:[(0,i.jsx)("span",{className:"truncate",children:e.addonName}),c.length>0&&(0,i.jsx)("span",{className:"flex items-center gap-1 shrink-0",children:c.map(d=>(0,i.jsx)("span",{title:`${d.agentNodeId}: ${d.state}`,className:A("w-2 h-2 rounded-full",uI[d.state])},d.agentNodeId))})]}),e.children.map(d=>(0,i.jsx)(kv,{node:d,depth:t+1,selectedAddonId:r,onSelect:n,agentDots:s},d.addonId))]})}function dI({tree:e,selectedAddonId:t,onSelect:r,agentDots:n,className:s}){return(0,i.jsx)("div",{className:A("flex flex-col py-2",s),children:e.map(a=>(0,i.jsx)(kv,{node:a,depth:0,selectedAddonId:t,onSelect:r,agentDots:n},a.addonId))})}function fI(e){const t=[],r=[],n=new Map;for(const a of e.slots)for(const c of a.addons){const d={addonId:c.id,addonName:c.name,slot:c.slot,inputClasses:c.inputClasses,outputClasses:c.outputClasses,children:[]};c.slot==="audio-classifier"?t.push(d):(r.push(d),n.set(c.id,d))}const s=[];for(const a of r){if(a.inputClasses.length===0){s.push(a);continue}const c=r.find(d=>d.addonId!==a.addonId&&d.outputClasses.some(u=>a.inputClasses.includes(u)));c&&c.children.push(a)}return[...s,...t]}function hI(e){return e?e.models.map(t=>({id:t.id,name:t.name})):[]}function Cl({step:e,schema:t,allSchemas:r,depth:n=0,onChange:s,onDelete:a,readOnly:c=!1,toggleMode:d="simple",overrideState:u=null,onOverrideChange:f,inheritedEnabled:h,hideModelAndSettings:m=!1}){const[g,p]=(0,l.useState)(!1),y=hI(t);if(y.length>0&&!y.some(E=>E.id===e.modelId)&&!c){const E=(t?.defaultModelId?y.find(T=>T.id===t.defaultModelId):null)??y[0];E&&E.id!==e.modelId&&queueMicrotask(()=>s({...e,modelId:E.id}))}const S=(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,i.jsx)("span",{className:"text-[10px] uppercase tracking-wider font-medium text-foreground-subtle/60 block leading-none",children:e.slot}),(0,i.jsx)("span",{className:"text-sm font-semibold text-foreground truncate block leading-tight",children:e.addonName}),(0,i.jsxs)("div",{className:"flex items-center gap-1 mt-0.5 flex-wrap",children:[e.inputClasses.map(E=>(0,i.jsx)("span",{className:"text-[9px] uppercase font-semibold tracking-wide px-1.5 py-0.5 rounded bg-blue-500/12 text-blue-400",children:E},E)),e.inputClasses.length>0&&e.outputClasses.length>0&&(0,i.jsx)("span",{className:"text-foreground-subtle/40 text-[10px]",children:"→"}),e.outputClasses.map(E=>(0,i.jsx)("span",{className:"text-[9px] uppercase font-semibold tracking-wide px-1.5 py-0.5 rounded bg-green-500/12 text-green-400",children:E},E))]})]}),!c&&d==="simple"&&(0,i.jsx)("button",{onClick:E=>{E.stopPropagation(),s({...e,enabled:!e.enabled})},className:A("relative inline-flex h-6 w-11 shrink-0 items-center rounded-full transition-colors",e.enabled?"bg-success":"bg-foreground-subtle/30"),children:(0,i.jsx)("span",{className:A("inline-block h-4 w-4 rounded-full bg-white shadow transition-transform",e.enabled?"translate-x-6":"translate-x-1")})}),!c&&d==="threeState"&&f&&(0,i.jsxs)("div",{className:"flex items-center gap-0.5 rounded-md border border-border p-0.5",onClick:E=>E.stopPropagation(),children:[(0,i.jsx)(ff,{label:"Inherit",active:u===null,variant:"inherit",subtext:h===void 0?void 0:h?"on":"off",onClick:()=>f(null)}),(0,i.jsx)(ff,{label:"On",active:u===!0,variant:"on",onClick:()=>f(!0)}),(0,i.jsx)(ff,{label:"Off",active:u===!1,variant:"off",onClick:()=>f(!1)})]})]});return(0,i.jsx)(Xp,{expanded:g,onExpandedChange:p,dimmed:!e.enabled,header:S,children:m?(0,i.jsx)("p",{className:"text-[11px] text-foreground-subtle",children:"Model and detection settings are managed per agent — open the Pipeline page for this camera's agent to edit them."}):(0,i.jsxs)("div",{className:"space-y-3",children:[(0,i.jsx)(df,{label:"Model",value:e.modelId,disabled:c,options:y.map(E=>({value:E.id,label:E.name})),onChange:E=>s({...e,modelId:E})}),e.slot==="audio-classifier"&&e.engine&&(0,i.jsx)(df,{label:"Runtime",value:`${e.engine.runtime}/${e.engine.backend}`,disabled:c,options:[{value:"node/cpu",label:"Node.js — ONNX CPU"},{value:"node/coreml",label:"Node.js — Apple SoundAnalysis (macOS)"},{value:"python/cpu",label:"Python — ONNX CPU"}],onChange:E=>{const[T,j]=E.split("/");s({...e,engine:{runtime:T,backend:j,format:j==="coreml"?"coreml":"onnx"}})}}),t?.configSchema?.map(E=>(0,i.jsx)(Il,{field:E,allFields:t.configSchema??[],step:e,disabled:c,onChange:s},E.key))]})})}function df({label:e,value:t,options:r,disabled:n,onChange:s}){return(0,i.jsxs)("div",{children:[(0,i.jsx)("label",{className:"block text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-1.5",children:e}),(0,i.jsxs)("select",{value:t,onChange:a=>s(a.target.value),disabled:n,className:"w-full rounded-lg border border-border bg-surface px-3 py-2 text-xs text-foreground focus:outline-none focus:border-primary/50",children:[r.length===0&&(0,i.jsx)("option",{value:t,children:t||"default"}),r.map(a=>(0,i.jsx)("option",{value:a.value,disabled:a.disabled,children:a.label},a.value))]})]})}function mI({label:e,description:t,value:r,options:n,disabled:s,onChange:a}){function c(d){s||a(r.includes(d)?r.filter(u=>u!==d):[...r,d])}return(0,i.jsxs)("div",{children:[(0,i.jsx)("label",{className:"block text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-1",children:e}),t&&(0,i.jsx)("p",{className:"text-[10px] text-foreground-subtle/60 mb-1.5",children:t}),(0,i.jsx)("div",{className:"flex flex-wrap gap-1.5",children:n.map(d=>(0,i.jsx)("button",{type:"button",disabled:s,onClick:()=>c(d.value),className:A("text-[10px] font-medium px-2 py-1 rounded-md border transition-colors",r.includes(d.value)?"bg-primary/20 text-primary border-primary/40":"bg-surface text-foreground-subtle border-border hover:border-primary/30",s&&"opacity-50 cursor-not-allowed"),children:d.label},d.value))})]})}function gI(e,t,r){const n=t.settings?.[e];if(n!==void 0)return n;const s=r.find(a=>"key"in a&&a.key===e);return s&&"default"in s?s.default:void 0}function Il({field:e,allFields:t,step:r,disabled:n,onChange:s}){const a=e.type!=="separator"&&e.type!=="info"?e.showWhen:void 0;if(a){const{field:d,equals:u,notEquals:f,in:h,notIn:m}=a,g=gI(d,r,t);if(u!==void 0&&g!==u||f!==void 0&&g===f||h!==void 0&&!h.includes(g)||m!==void 0&&m.includes(g))return null}function c(d){s({...r,settings:{...r.settings,[e.key]:d}})}if(e.type==="select"){const d=r.settings?.[e.key],u=typeof d=="string"?d:e.default??"";return(0,i.jsx)(df,{label:e.label,value:u,disabled:n||e.disabled,options:e.options,onChange:c})}if(e.type==="multiselect"){const d=r.settings?.[e.key],u=Array.isArray(d)?d:Array.isArray(e.default)?e.default:[];return(0,i.jsx)(mI,{label:e.label,description:e.description,value:u,options:e.options,disabled:n||e.disabled,onChange:c})}if(e.type==="slider"||e.type==="number"){const d=r.settings?.[e.key],u=typeof e.default=="number"?e.default:e.min??0,f=typeof d=="number"?d:u,h=e.min??0,m=e.max??1,g=e.step??.01,p=e.type==="slider"?e.showValue:!0,y="unit"in e?e.unit:void 0,S=e.type==="slider"?e.displayScale:void 0,E=S?f/S:f;return(0,i.jsxs)("div",{children:[(0,i.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,i.jsx)("span",{className:"text-[10px] font-medium text-foreground-subtle uppercase tracking-wide",children:e.label}),p&&(0,i.jsxs)("span",{className:"text-xs font-medium text-foreground tabular-nums",children:[typeof E=="number"?E.toFixed(2).replace(/\.?0+$/,""):E,y?` ${y}`:""]})]}),e.description&&(0,i.jsx)("p",{className:"text-[10px] text-foreground-subtle/60 mb-1.5",children:e.description}),(0,i.jsx)("input",{type:"range",min:h,max:m,step:g,value:f,disabled:n||e.disabled,onChange:T=>c(Number(T.target.value)),className:"w-full accent-primary h-1.5"})]})}if(e.type==="boolean"){const d=r.settings?.[e.key];return(0,i.jsxs)("label",{className:"flex items-center gap-2",children:[(0,i.jsx)("input",{type:"checkbox",checked:typeof d=="boolean"?d:e.default===!0,disabled:n||e.disabled,onChange:u=>c(u.target.checked),className:"h-3.5 w-3.5 accent-primary"}),(0,i.jsx)("span",{className:"text-[10px] font-medium text-foreground-subtle uppercase tracking-wide",children:e.label})]})}if(e.type==="text"||e.type==="password"||e.type==="textarea"){const d=r.settings?.[e.key],u=typeof d=="string"?d:e.default??"",f=e.type==="password"?"password":"text";return(0,i.jsxs)("div",{children:[(0,i.jsx)("label",{className:"block text-[10px] font-medium text-foreground-subtle uppercase tracking-wide mb-1.5",children:e.label}),e.type==="textarea"?(0,i.jsx)("textarea",{value:u,disabled:n||e.disabled,placeholder:e.placeholder,onChange:h=>c(h.target.value),rows:3,className:"w-full rounded-lg border border-border bg-surface px-3 py-2 text-xs text-foreground focus:outline-none focus:border-primary/50 resize-y"}):(0,i.jsx)("input",{type:f,value:u,disabled:n||e.disabled,placeholder:e.placeholder,onChange:h=>c(h.target.value),className:"w-full rounded-lg border border-border bg-surface px-3 py-2 text-xs text-foreground focus:outline-none focus:border-primary/50"})]})}return e.type==="separator"?(0,i.jsx)("div",{className:"border-t border-border my-2"}):e.type==="info"?(0,i.jsx)("div",{className:"rounded-md border border-border bg-surface px-2 py-1.5 text-[10px] text-foreground-subtle",children:e.content}):null}function ff({label:e,active:t,variant:r,subtext:n,onClick:s}){return(0,i.jsxs)("button",{type:"button",onClick:s,className:A("px-2 py-1 text-[10px] font-medium rounded transition-colors",t?r==="on"?"bg-green-500/20 text-green-400":r==="off"?"bg-red-500/20 text-red-400":"bg-primary/20 text-primary":"text-foreground-subtle hover:bg-surface-hover"),children:[e,n&&t&&(0,i.jsxs)("span",{className:"ml-1 opacity-60",children:["(",n,")"]})]})}function Tv(e,t){return{addonId:e.id,addonName:e.name,slot:e.slot,inputClasses:[...e.inputClasses],outputClasses:[...e.outputClasses],enabled:t.enabled,modelId:t.modelId,children:[],settings:{...t.settings}}}function pI(e,t,r){return r?{enabled:r.enabled??t.enabled,modelId:r.modelId??t.modelId,settings:r.settings??t.settings}:t}function vI({addon:e,agentDefault:t,modelsForFormat:r,onChangeAgentConfig:n}){const s=a=>{n?.({...t,...a})};return(0,i.jsxs)("div",{className:"space-y-4 text-xs",children:[(0,i.jsxs)("label",{className:"flex items-center gap-2",children:[(0,i.jsx)("input",{type:"checkbox",checked:t.enabled,onChange:a=>s({enabled:a.target.checked})}),(0,i.jsxs)("span",{children:["Enabled on this agent (",e.name,")"]})]}),(0,i.jsxs)("div",{children:[(0,i.jsx)("div",{className:"text-[10px] uppercase tracking-widest text-foreground-subtle mb-1",children:"Model"}),(0,i.jsx)("select",{className:"w-full bg-surface border border-border rounded px-2 py-1 text-xs",value:t.modelId,onChange:a=>s({modelId:a.target.value}),children:r.map(a=>(0,i.jsx)("option",{value:a.id,children:a.name},a.id))})]}),(e.configSchema?.length??0)>0&&(0,i.jsxs)("div",{className:"pt-2 border-t border-border/50 space-y-3",children:[(0,i.jsx)("div",{className:"text-[10px] uppercase tracking-widest text-foreground-subtle",children:"Settings"}),e.configSchema?.map(a=>(0,i.jsx)(Il,{field:a,allFields:e.configSchema??[],step:Tv(e,t),disabled:!1,onChange:c=>s({settings:{...c.settings}})},a.key))]})]})}function bI({addon:e,agentDefault:t,agentNodeId:r,currentPatch:n,modelsForFormat:s,onChangePatch:a}){const c=pI("device",t,n),d=p=>{const y=p.enabled!==void 0||p.modelId!==void 0||p.settings!==void 0;a?.(y?p:null)},u=p=>{const{enabled:y,...S}=n??{};d(p==="inherit"?S:{...S,enabled:p==="on"})},f=p=>{const{modelId:y,...S}=n??{};d(p===void 0?S:{...S,modelId:p})},h=p=>{const{settings:y,...S}=n??{};d(p===void 0?S:{...S,settings:p})},m=n?.enabled===void 0?"inherit":n.enabled?"on":"off",g=n?.modelId!==void 0;return(0,i.jsxs)("div",{className:"space-y-4 text-xs",children:[(0,i.jsxs)("div",{className:"flex items-center gap-1",children:[["inherit","on","off"].map(p=>(0,i.jsx)("button",{type:"button",onClick:()=>u(p),className:A("px-3 py-1 border border-border rounded text-xs capitalize",m===p?"bg-primary text-primary-foreground border-primary":"bg-surface text-foreground hover:bg-muted"),children:p},p)),(0,i.jsxs)("span",{className:"ml-2 text-[10px] text-foreground-subtle",children:["agent default: ",(0,i.jsx)("span",{className:"font-semibold",children:t.enabled?"on":"off"})]})]}),(0,i.jsxs)("div",{children:[(0,i.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,i.jsx)("div",{className:"text-[10px] uppercase tracking-widest text-foreground-subtle",children:"Model"}),g?(0,i.jsx)("button",{type:"button",className:"text-[10px] text-foreground-subtle hover:text-foreground",onClick:()=>f(void 0),children:"Clear"}):(0,i.jsx)("button",{type:"button",className:"text-[10px] text-primary hover:underline",onClick:()=>f(t.modelId),children:"Override"})]}),(0,i.jsx)("select",{disabled:!g,className:"w-full bg-surface border border-border rounded px-2 py-1 text-xs disabled:opacity-50",value:g?n?.modelId??t.modelId:t.modelId,onChange:p=>f(p.target.value),children:s.map(p=>(0,i.jsx)("option",{value:p.id,children:p.name},p.id))}),!g&&(0,i.jsxs)("div",{className:"text-[10px] text-foreground-subtle mt-1",children:["inherits from ",r]})]}),(e.configSchema?.length??0)>0&&(()=>{const p=n?.settings!==void 0;return(0,i.jsxs)("div",{className:"pt-2 border-t border-border/50 space-y-3",children:[(0,i.jsxs)("div",{className:"flex items-center justify-between",children:[(0,i.jsx)("div",{className:"text-[10px] uppercase tracking-widest text-foreground-subtle",children:"Settings"}),p?(0,i.jsx)("button",{type:"button",className:"text-[10px] text-foreground-subtle hover:text-foreground",onClick:()=>h(void 0),children:"Clear"}):(0,i.jsx)("button",{type:"button",className:"text-[10px] text-primary hover:underline",onClick:()=>h({...t.settings}),children:"Override"})]}),e.configSchema?.map(y=>(0,i.jsx)(Il,{field:y,allFields:e.configSchema??[],step:Tv(e,c),disabled:!p,onChange:S=>h({...S.settings})},y.key)),!p&&(0,i.jsxs)("div",{className:"text-[10px] text-foreground-subtle",children:["inherits from ",r]})]})})(),(0,i.jsxs)("div",{className:"rounded bg-muted/40 px-3 py-2 text-[11px] text-foreground-subtle",children:[(0,i.jsx)("div",{className:"font-semibold text-foreground mb-0.5",children:"Effective config preview"}),(0,i.jsxs)("div",{className:"font-mono truncate",children:[e.id," · model: ",c.modelId," · ",c.enabled?"on":"off"]})]})]})}function yI(e){const{mode:t,addon:r,agentDefault:n,agentNodeId:s,currentPatch:a,onChangeAgentConfig:c,onChangePatch:d,engineFormat:u}=e,f=(0,l.useMemo)(()=>r.models.filter(h=>!!h.formats[u]),[r.models,u]);return t==="agent"?(0,i.jsx)(vI,{addon:r,agentDefault:n,modelsForFormat:f,onChangeAgentConfig:c}):(0,i.jsx)(bI,{addon:r,agentDefault:n,agentNodeId:s,currentPatch:a,modelsForFormat:f,onChangePatch:d})}function xI(e){const t=[],r=(n,s)=>{for(const a of n)t.push({node:a,depth:s}),r(a.children,s+1)};return r(e,0),t}var Cv={detector:{label:"detector",className:"text-emerald-500"},cropper:{label:"cropper",className:"text-blue-500"},classifier:{label:"classifier",className:"text-violet-500"},refiner:{label:"refiner",className:"text-amber-500"},"audio-classifier":{label:"audio classifier",className:"text-pink-500"}};function SI({slot:e}){const t=Cv[e]??Cv.classifier;return(0,i.jsx)("span",{className:A("text-[9px] font-semibold uppercase tracking-widest leading-none",t.className),children:t.label})}var Iv="inline-flex items-center rounded bg-muted px-1.5 py-px text-[9px] font-medium text-foreground-subtle";function _I({inputs:e,outputs:t}){return e.length===0&&t.length===0?null:(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 flex-wrap",children:[e.map(r=>(0,i.jsx)("span",{className:A(Iv,"bg-blue-500/10 text-blue-500"),children:r},`in-${r}`)),e.length>0&&t.length>0&&(0,i.jsx)("span",{className:"text-foreground-subtle/60 text-[9px]",children:"→"}),t.map(r=>(0,i.jsx)("span",{className:A(Iv,"bg-emerald-500/10 text-emerald-500"),children:r},`out-${r}`))]})}function wI({enabled:e,onChange:t,disabled:r}){return(0,i.jsx)("button",{type:"button",role:"switch","aria-checked":e,disabled:r,onClick:n=>{n.stopPropagation(),t(!e)},className:A("relative inline-flex h-3.5 w-7 shrink-0 items-center rounded-full transition-colors",e?"bg-emerald-500":"bg-foreground-subtle/30",r?"opacity-50 cursor-not-allowed":"cursor-pointer"),title:e?"Click to disable":"Click to enable",children:(0,i.jsx)("span",{className:A("inline-block h-3 w-3 rounded-full bg-white shadow transition-transform",e?"translate-x-3.5":"translate-x-0.5")})})}function EI(e){return e.kind==="enabled"?(0,i.jsxs)("span",{className:"inline-flex items-center gap-1",children:[(0,i.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-500 shrink-0"}),(0,i.jsx)("span",{className:"font-mono text-foreground",children:e.modelId})]}):e.kind==="disabled"?(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 text-foreground-subtle",children:[(0,i.jsx)("span",{className:"h-1.5 w-1.5 rounded-full border border-foreground-subtle/60 shrink-0"}),"off"]}):(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 text-foreground-subtle/70",children:[(0,i.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-muted shrink-0"}),"n/a"]})}function kI({node:e,depth:t,agents:r,getCellState:n,onCellClick:s,selectedCell:a,toggleProps:c}){return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("div",{className:"sticky left-0 z-10 bg-surface px-3 py-2 border-b border-border text-xs flex items-start gap-2",style:{paddingLeft:`${12+t*14}px`},children:[(0,i.jsxs)("div",{className:"flex flex-col gap-1 min-w-0 flex-1",children:[(0,i.jsx)(SI,{slot:e.slot}),(0,i.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,i.jsx)("span",{className:"font-semibold truncate",children:e.addonName}),(0,i.jsx)(_I,{inputs:e.inputClasses,outputs:e.outputClasses})]})]}),c&&(0,i.jsx)("span",{className:"pl-2 pt-0.5 shrink-0",children:(0,i.jsx)(wI,{enabled:c.enabled,onChange:c.onChange,disabled:c.disabled})})]}),r.map(d=>{const u=n(e.addonId,d.agentNodeId),f=a?.addonId===e.addonId&&a.agentNodeId===d.agentNodeId;return(0,i.jsx)("button",{type:"button",onClick:()=>s(e.addonId,d.agentNodeId),className:A("text-left px-3 py-1.5 border-b border-l border-border text-xs hover:bg-muted/40",u.kind==="enabled"&&"bg-emerald-500/5",u.kind==="na"&&"bg-muted/30",f&&"ring-2 ring-primary ring-inset"),children:EI(u)},d.agentNodeId)})]})}function TI({tree:e,agents:t,getCellState:r,onCellClick:n,selectedCell:s,onToggleEnabled:a}){const c=(0,l.useMemo)(()=>xI(e),[e]),d=`minmax(320px, 1fr) repeat(${t.length}, minmax(160px, 220px))`,u=a!==void 0&&t.length===1,f=t[0]?.agentNodeId;return(0,i.jsx)("div",{className:"overflow-auto border border-border rounded",children:(0,i.jsxs)("div",{className:"grid",style:{gridTemplateColumns:d},children:[(0,i.jsx)("div",{className:"sticky top-0 left-0 z-20 bg-muted/60 px-3 py-2 text-[10px] uppercase tracking-widest text-foreground-subtle border-b border-border",children:"Step"}),t.map(h=>(0,i.jsxs)("div",{className:"sticky top-0 z-10 bg-muted/60 px-3 py-2 border-b border-l border-border",children:[(0,i.jsx)("div",{className:"text-xs font-semibold text-foreground",children:h.agentNodeId}),(0,i.jsx)("div",{className:"text-[10px] text-foreground-subtle truncate",children:h.engineLabel})]},h.agentNodeId)),c.map(({node:h,depth:m})=>{const g=u&&f!==void 0?r(h.addonId,f):null;return(0,i.jsx)(kI,{node:h,depth:m,agents:t,getCellState:r,onCellClick:n,selectedCell:s,toggleProps:u&&g!==null?{enabled:g.kind==="enabled",onChange:p=>a?.(h.addonId,p),disabled:g.kind==="na"}:void 0},h.addonId)})]})})}var Pv=typeof globalThis<"u"?globalThis.__camstackTrpcReact:void 0,C=Pv??(0,Te.createTRPCReact)();typeof globalThis<"u"&&!Pv&&(globalThis.__camstackTrpcReact=C);var hf=Sn("camstack:system",null);function Av({system:e,children:t}){return(0,i.jsx)(hf.Provider,{value:e,children:t})}function Mr(){const e=(0,l.useContext)(hf);if(!e)throw new Error("useSystem(): no <SystemProvider> in tree");return e}function CI(){return(0,l.useContext)(hf)}function so(e,t){const r=Mr(),n=(0,l.useRef)(t);n.current=t;const[s,a]=(0,l.useState)(r.connectionVersion);(0,l.useEffect)(()=>r.subscribeConnectionEvents((c,d)=>{c==="connected"&&a(d)}),[r]),(0,l.useEffect)(()=>r.subscribeEvent(e,c=>{n.current(c)}),[r,e,s])}function mf(e){const t=(0,l.useRef)(e);return t.current=e,t}function gf(e,t){const[r,n]=(0,l.useState)(null),s=mf(t);return so(e,a=>{const c=a.data,d=s.current;d&&!d(c)||n(c)}),r}function II(e,t,r){const[n,s]=(0,l.useState)(()=>new Map),a=mf(t),c=mf(r);return so(e,d=>{const u=d.data,f=c.current;if(f&&!f(u))return;const h=a.current(u);s(m=>{const g=new Map(m);return g.set(h,u),g})}),{map:n,values:(0,l.useMemo)(()=>Array.from(n.values()),[n])}}function Pl(){const{data:e,isLoading:t}=C.nodes.topology.useQuery(void 0,{staleTime:6e4}),r=gf("cluster.topology-snapshot")?.nodes??e;return{nodes:(0,l.useMemo)(()=>{const n=[];for(const s of r??[])n.push({id:String(s.id??""),name:String(s.name??s.id??""),shortName:s.isHub?"HUB":String(s.name??s.id??""),isHub:!!s.isHub,isOnline:!!s.isOnline,localIps:s.localIps??[],addons:(s.addons??[]).map(a=>({addonId:a.id,capabilities:a.capabilities}))});return n.sort((s,a)=>s.isHub!==a.isHub?s.isHub?-1:1:s.name.localeCompare(a.name)),n},[r]),isLoading:t}}function PI({selectedNodeId:e,onSelect:t,label:r="Node",hideIcon:n=!1,alwaysShow:s=!1}){const{nodes:a}=Pl();return!s&&a.length<=1?null:(0,i.jsxs)("div",{className:"flex items-center gap-1.5",children:[!n&&(0,i.jsx)(_C,{className:"h-3.5 w-3.5 text-foreground-subtle"}),r&&(0,i.jsx)("span",{className:"text-[10px] uppercase tracking-wider text-foreground-subtle",children:r}),(0,i.jsx)("div",{className:"flex rounded-md border border-border overflow-hidden text-[11px] font-medium",children:a.map((c,d)=>{const u=e===c.id;return(0,i.jsx)("button",{type:"button",onClick:()=>t(c.id),disabled:!c.isOnline,title:c.isOnline?c.name:`${c.name} (offline)`,className:A("px-2.5 py-1 transition-colors",u?"bg-primary/15 text-primary":"bg-transparent text-foreground-subtle hover:bg-surface-hover hover:text-foreground",d>0&&"border-l border-border",!c.isOnline&&"opacity-50 cursor-not-allowed"),children:c.shortName},c.id)})})]})}var AI={online:{colorClass:"bg-success",label:"Online"},offline:{colorClass:"bg-danger",label:"Offline"},degraded:{colorClass:"bg-warning",label:"Degraded"},unknown:{colorClass:"bg-foreground-subtle",label:"Unknown"}};function jI({status:e,showDot:t=!0,showLabel:r=!0,size:n="sm",className:s}){const a=AI[e];return(0,i.jsxs)("span",{className:A("inline-flex items-center gap-1.5",n==="sm"?"text-xs":"text-sm",s),children:[t&&(0,i.jsx)("span",{className:A("h-1.5 w-1.5 shrink-0 rounded-full",a.colorClass),"aria-hidden":"true"}),r&&(0,i.jsx)("span",{className:"text-foreground",children:a.label})]})}var NI={frigate:{colorClass:"bg-provider-frigate",label:"Frigate"},scrypted:{colorClass:"bg-provider-scrypted",label:"Scrypted"},reolink:{colorClass:"bg-provider-reolink",label:"Reolink"},homeAssistant:{colorClass:"bg-provider-homeAssistant",label:"Home Assistant"},rtsp:{colorClass:"bg-provider-rtsp",label:"RTSP"}};function DI({provider:e,showLabel:t=!0,className:r}){const n=NI[e];return(0,i.jsxs)("span",{className:A("inline-flex items-center gap-1.5 text-xs",r),children:[(0,i.jsx)("span",{className:A("h-1.5 w-1.5 shrink-0 rounded-sm",n.colorClass),"aria-hidden":"true"}),t&&(0,i.jsx)("span",{className:"text-foreground",children:n.label})]})}var MI={success:"bg-emerald-400 text-emerald-950",warning:"bg-amber-400 text-amber-950",danger:"bg-red-400 text-red-950",info:"bg-blue-400 text-blue-950",neutral:"bg-foreground-subtle/20 text-foreground"};function jv({children:e,variant:t="neutral",mono:r,className:n}){return(0,i.jsx)("span",{className:A("inline-flex items-center rounded-md px-2 py-0.5 text-[11px] font-bold leading-tight",r&&"font-mono",MI[t],n),children:e})}function $I({version:e,preRelease:t,className:r}){return(0,i.jsx)(jv,{variant:t??/-(alpha|beta|rc|dev|canary|next)/i.test(e)?"warning":"success",mono:!0,className:r,children:e})}function RI({label:e,description:t,error:r,required:n,children:s,orientation:a="vertical",className:c}){const d=a==="horizontal";return(0,i.jsxs)("div",{className:A("flex gap-2",d?"flex-row items-center justify-between":"flex-col",c),children:[(0,i.jsxs)("div",{className:A(d?"flex-1":""),children:[(0,i.jsxs)(af,{children:[e,n&&(0,i.jsx)("span",{className:"text-danger ml-0.5",children:"*"})]}),t&&(0,i.jsx)("p",{className:"text-foreground-subtle text-xs mt-0.5",children:t})]}),(0,i.jsx)("div",{className:A(d?"shrink-0":""),children:s}),r&&(0,i.jsx)("p",{className:"text-danger text-xs",children:r})]})}function LI({title:e,subtitle:t,actions:r,className:n}){return(0,i.jsxs)("div",{className:A("flex flex-col gap-2 mb-3 sm:flex-row sm:items-center sm:justify-between",n),children:[(0,i.jsxs)("div",{children:[(0,i.jsx)("h1",{className:"text-sm font-semibold text-foreground",children:e}),t&&(0,i.jsx)("p",{className:"text-foreground-subtle text-xs",children:t})]}),r&&(0,i.jsx)("div",{className:"flex items-center gap-2 flex-wrap",children:r})]})}function pf({icon:e,title:t,description:r,action:n,className:s}){return(0,i.jsxs)("div",{className:A("flex flex-col items-center justify-center gap-3 py-12",s),children:[e&&(0,i.jsx)(e,{className:"h-12 w-12 text-foreground-subtle","aria-hidden":"true"}),(0,i.jsxs)("div",{className:"flex flex-col items-center gap-1 text-center",children:[(0,i.jsx)("p",{className:"text-foreground-muted text-sm font-medium",children:t}),r&&(0,i.jsx)("p",{className:"text-foreground-subtle text-xs max-w-xs",children:r})]}),n&&(0,i.jsx)("div",{className:"mt-1",children:n})]})}var OI={danger:{box:"border-danger/40 bg-danger/10",icon:"text-danger",title:"text-danger",message:"text-danger"},warning:{box:"border-amber-500/40 bg-amber-500/10",icon:"text-amber-600 dark:text-amber-400",title:"text-amber-700 dark:text-amber-300",message:"text-amber-700 dark:text-amber-300"}};function ao({message:e,title:t,onRetry:r,action:n,variant:s="danger",className:a}){const c=OI[s],d=s==="warning"?cs:as;return(0,i.jsxs)("div",{role:"alert",className:A("flex items-start gap-2.5 rounded border px-3 py-2.5",c.box,a),children:[(0,i.jsx)(d,{className:A("h-4 w-4 mt-0.5 shrink-0",c.icon),"aria-hidden":"true"}),(0,i.jsxs)("div",{className:"flex-1 min-w-0",children:[t&&(0,i.jsx)("p",{className:A("text-xs font-semibold",c.title),children:t}),(0,i.jsx)("div",{className:A("text-xs break-words",c.message,t?"mt-0.5":""),children:e})]}),n??(r&&(0,i.jsxs)("button",{type:"button",onClick:r,className:A("shrink-0 inline-flex items-center gap-1 rounded px-2 py-1 text-[11px] font-medium","border border-current/30 hover:bg-current/10 transition-colors",c.message),children:[(0,i.jsx)(Ii,{className:"h-3 w-3","aria-hidden":"true"}),"Retry"]}))]})}var Nv=Sn("camstack:confirm-dialog",null);function ji(){const e=(0,l.useContext)(Nv);if(!e)throw new Error("useConfirm must be used within ConfirmDialogProvider");return e.confirm}function FI({children:e}){const[t,r]=(0,l.useState)(null),n=(0,l.useCallback)(u=>new Promise(f=>{r({...u,resolve:f})}),[]),s=()=>{t?.resolve(!0),r(null)},a=()=>{t?.resolve(!1),r(null)},c={danger:{icon:"text-red-400",button:"bg-red-500 hover:bg-red-600 text-white"},warning:{icon:"text-orange-400",button:"bg-orange-500 hover:bg-orange-600 text-white"},default:{icon:"text-primary",button:"bg-primary hover:bg-primary/90 text-white"}},d=t?c[t.variant??"default"]:c.default;return(0,i.jsxs)(Nv.Provider,{value:{confirm:n},children:[e,t&&(0,i.jsxs)("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[(0,i.jsx)("div",{className:"absolute inset-0 bg-black/50 backdrop-blur-sm",onClick:a}),(0,i.jsxs)("div",{className:"relative z-10 w-full max-w-sm mx-4 rounded-xl border border-border bg-surface shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-150",onClick:u=>u.stopPropagation(),children:[(0,i.jsxs)("div",{className:"px-5 pt-5 pb-4",children:[(0,i.jsx)("h3",{className:"text-sm font-semibold text-foreground",children:t.title}),(0,i.jsx)("p",{className:"mt-2 text-xs text-foreground-subtle leading-relaxed",children:t.message})]}),(0,i.jsxs)("div",{className:"flex justify-end gap-2 px-5 py-3 border-t border-border bg-surface-hover/30",children:[(0,i.jsx)("button",{type:"button",onClick:a,className:"px-3 py-1.5 text-xs font-medium rounded-md border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:t.cancelLabel??"Cancel"}),(0,i.jsx)("button",{type:"button",onClick:s,className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors ${d.button}`,children:t.confirmLabel??"Confirm"})]})]})]})]})}function UI({value:e,label:t,trend:r,className:n}){return(0,i.jsxs)(sf,{className:A("flex flex-col gap-1",n),children:[(0,i.jsxs)("div",{className:"flex items-baseline gap-2",children:[(0,i.jsx)("span",{className:"text-2xl font-semibold text-foreground",children:e}),r&&(0,i.jsxs)("span",{className:A("inline-flex items-center gap-0.5 text-xs font-medium",r.direction==="up"?"text-success":"text-danger"),children:[r.direction==="up"?(0,i.jsx)(DC,{className:"h-3 w-3"}):(0,i.jsx)(MC,{className:"h-3 w-3"}),r.value,"%"]})]}),(0,i.jsx)("span",{className:"text-xs text-foreground-muted",children:t})]})}function BI({items:e,className:t}){return(0,i.jsx)("dl",{className:A("flex flex-col",t),children:e.map(r=>(0,i.jsxs)("div",{className:"flex items-center h-7",children:[(0,i.jsx)("dt",{className:"text-foreground-subtle text-xs w-1/3 shrink-0",children:r.key}),(0,i.jsx)("dd",{className:"text-foreground text-xs",children:r.value})]},r.key))})}function zI({children:e,maxHeight:t=300,className:r}){const[n,s]=(0,l.useState)(!1),a=(0,l.useCallback)(()=>{navigator.clipboard.writeText(e).then(()=>{s(!0),setTimeout(()=>s(!1),2e3)})},[e]);return(0,i.jsxs)("div",{className:A("relative group",r),children:[(0,i.jsx)(uf,{style:{maxHeight:t},children:(0,i.jsx)("pre",{className:"font-mono text-xs bg-surface p-3 rounded-md border border-border-subtle",children:(0,i.jsx)("code",{children:e})})}),(0,i.jsx)("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity",children:(0,i.jsx)(nf,{icon:n?On:ii,"aria-label":"Copy code",variant:"ghost",size:"sm",onClick:a})})]})}function GI({filters:e,values:t,onChange:r,className:n}){const s=io(),[a,c]=(0,l.useState)(!1),d=(f,h)=>{r({...t,[f]:h})},u=Object.values(t).filter(f=>f!==void 0&&f!=="").length;if(s){const f=e.find(m=>m.type==="search"),h=e.some(m=>m.type!=="search");return(0,i.jsxs)("div",{className:A("flex items-center gap-2",n),children:[f&&(0,i.jsx)(Sl,{placeholder:f.placeholder??"Search...",value:t[f.key]??"",onChange:m=>d(f.key,m.target.value),leftSlot:(0,i.jsx)(ls,{className:"h-3 w-3 text-foreground-subtle"}),className:"flex-1"}),h&&(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("button",{onClick:()=>c(!0),className:"flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1.5 text-xs text-foreground-muted hover:bg-surface-hover transition-colors shrink-0",children:[(0,i.jsx)(Yd,{className:"h-3.5 w-3.5"}),"Filters",u>0&&(0,i.jsx)(Ai,{variant:"info",className:"ml-1 text-[10px] px-1 py-0",children:u})]}),(0,i.jsx)(cf,{open:a,onClose:()=>c(!1),title:"Filters",children:(0,i.jsx)("div",{className:"flex flex-col gap-3",children:e.filter(m=>m.type!=="search").map(m=>{switch(m.type){case"select":return(0,i.jsxs)("div",{children:[(0,i.jsx)("label",{className:"text-xs text-foreground-muted mb-1 block",children:m.label}),(0,i.jsx)(ro,{options:m.options,value:t[m.key]??"",onChange:g=>d(m.key,g.target.value),className:"w-full"})]},m.key);case"badge-toggle":return(0,i.jsx)("div",{className:"flex items-center gap-1 flex-wrap",children:m.options.map(g=>{const p=t[m.key]===g.value;return(0,i.jsx)("button",{type:"button",onClick:()=>d(m.key,p?void 0:g.value),children:(0,i.jsx)(Ai,{variant:p?"info":"default",className:"cursor-pointer",children:g.label})},g.value)})},m.key);default:return null}})})})]})]})}return(0,i.jsx)("div",{className:A("flex items-center gap-2 flex-wrap",n),children:e.map(f=>{switch(f.type){case"search":return(0,i.jsx)(Sl,{placeholder:f.placeholder??"Search...",value:t[f.key]??"",onChange:h=>d(f.key,h.target.value),leftSlot:(0,i.jsx)(ls,{className:"h-3 w-3 text-foreground-subtle"}),className:"w-48"},f.key);case"select":return(0,i.jsx)(ro,{options:f.options,value:t[f.key]??"",onChange:h=>d(f.key,h.target.value),className:"w-36"},f.key);case"badge-toggle":return(0,i.jsx)("div",{className:"flex items-center gap-1",children:f.options.map(h=>{const m=t[f.key]===h.value;return(0,i.jsx)("button",{type:"button",onClick:()=>d(f.key,m?void 0:h.value),children:(0,i.jsx)(Ai,{variant:m?"info":"default",className:"cursor-pointer",children:h.label})},h.value)})},f.key);default:return null}})})}function vf({label:e,icon:t,href:r,badge:n,active:s=!1,className:a}){return(0,i.jsxs)("a",{href:r,className:A("flex items-center gap-2 h-7 px-2 text-[11px] transition-colors",s?"border-l-2 border-primary bg-primary/[0.08] text-foreground rounded-r-md":"text-foreground-subtle hover:bg-surface-hover rounded-md",a),children:[(0,i.jsx)(t,{className:"h-3.5 w-3.5 shrink-0"}),(0,i.jsx)("span",{className:"truncate flex-1",children:e}),n!==void 0&&(0,i.jsx)(Ai,{className:"ml-auto text-[10px] px-1.5 py-0",children:n})]})}function bf({logo:e,sections:t,footer:r,onNavigate:n,className:s}){return(0,i.jsxs)("nav",{className:A("bg-surface border-r border-border h-full flex flex-col",s),children:[e&&(0,i.jsx)("div",{className:"px-3 py-2 shrink-0",children:e}),(0,i.jsx)("div",{className:"flex-1 overflow-auto px-1 py-1",children:t.map((a,c)=>(0,i.jsxs)("div",{className:A(c>0?"mt-3":""),children:[a.label&&(0,i.jsx)("span",{className:"text-[10px] text-foreground-disabled uppercase tracking-wider px-2 mb-1 block",children:a.label}),(0,i.jsx)("div",{className:"flex flex-col gap-0.5",onClick:n,children:a.items.map(d=>(0,i.jsx)(vf,{...d},d.href))})]},c))}),r&&r.length>0&&(0,i.jsxs)("div",{className:"shrink-0 px-1 pb-1",children:[(0,i.jsx)(of,{className:"mb-1"}),(0,i.jsx)("div",{className:"flex flex-col gap-0.5",onClick:n,children:r.map(a=>(0,i.jsx)(vf,{...a},a.href))})]})]})}function ZI({sidebar:e,header:t,mobileLogo:r,mobileActions:n,children:s,className:a}){const c=io(),[d,u]=(0,l.useState)(!1);return(0,i.jsxs)("div",{className:A("flex h-screen",a),children:[!c&&(0,i.jsx)(bf,{...e,className:A("w-44",e.className)}),c&&(0,i.jsx)(wv,{open:d,onClose:()=>u(!1),width:"w-64",children:(0,i.jsx)(bf,{...e,onNavigate:()=>u(!1),className:"w-full border-r-0"})}),(0,i.jsxs)("div",{className:"flex flex-1 flex-col min-w-0",children:[c&&(0,i.jsxs)("header",{className:"flex items-center h-12 border-b border-border px-3 shrink-0 bg-surface/80 backdrop-blur-sm",children:[(0,i.jsx)("button",{onClick:()=>u(!0),className:"p-1.5 -ml-1.5 rounded-md hover:bg-surface-hover text-foreground-muted transition-colors","aria-label":"Open menu",children:(0,i.jsx)(cC,{className:"h-5 w-5"})}),r&&(0,i.jsx)("div",{className:"flex-1 flex justify-center",children:r}),n&&(0,i.jsx)("div",{className:"shrink-0",children:n})]}),!c&&t&&(0,i.jsxs)("header",{className:"flex items-center h-10 border-b border-border px-4 shrink-0",children:[t.breadcrumbs&&t.breadcrumbs.length>0&&(0,i.jsx)("nav",{className:"flex items-center gap-1 text-xs flex-1 min-w-0",children:t.breadcrumbs.map((f,h)=>{const m=h===t.breadcrumbs.length-1;return(0,i.jsxs)("span",{className:"flex items-center gap-1",children:[h>0&&(0,i.jsx)(mn,{className:"h-3 w-3 text-foreground-subtle shrink-0"}),f.href&&!m?(0,i.jsx)("a",{href:f.href,className:"text-foreground-subtle hover:text-foreground transition-colors truncate",children:f.label}):(0,i.jsx)("span",{className:"text-foreground truncate",children:f.label})]},h)})}),t.actions&&(0,i.jsx)("div",{className:"flex items-center gap-2 ml-auto shrink-0",children:t.actions})]}),(0,i.jsx)("main",{className:"flex-1 overflow-auto p-4",children:s})]})]})}var VI={online:"bg-success",offline:"bg-danger",warning:"bg-warning",unknown:"bg-foreground-subtle"};function HI({title:e,subtitle:t,status:r,selected:n,onClick:s,badges:a,actions:c,offlineAction:d,className:u}){const f=r==="offline";return(0,i.jsxs)("div",{onClick:s,className:A("w-full rounded-lg border p-3 text-left transition-colors",s&&"cursor-pointer",n?"border-primary bg-primary/10":"border-border bg-surface hover:bg-surface-hover",f&&!n&&"opacity-50",u),children:[(0,i.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,i.jsx)("span",{className:"text-sm font-medium truncate",children:e}),r&&(0,i.jsx)("span",{className:A("h-2 w-2 rounded-full shrink-0",VI[r])})]}),t&&(0,i.jsx)("div",{className:"text-[11px] text-foreground-muted",children:t}),a&&a.length>0&&(0,i.jsx)("div",{className:"flex flex-wrap gap-1 mt-2",children:a.map((h,m)=>{const g=A("rounded px-1.5 py-0.5 text-[10px] flex items-center gap-0.5",n?"bg-primary/20":"bg-surface-hover",h.onClick&&"hover:opacity-80 transition-opacity cursor-pointer");return h.onClick?(0,i.jsxs)("button",{onClick:p=>{p.stopPropagation(),h.onClick()},className:g,children:[h.icon,h.label]},m):(0,i.jsxs)("span",{className:g,children:[h.icon,h.label]},m)})}),!f&&c&&c.length>0&&(0,i.jsx)("div",{className:"flex items-center gap-0.5 mt-2 -mb-1",children:c.map((h,m)=>(0,i.jsx)("button",{onClick:g=>{g.stopPropagation(),h.onClick()},className:"p-1 rounded hover:bg-surface-hover text-foreground-subtle hover:text-foreground transition-colors",title:h.label,"aria-label":h.label,children:h.icon},m))}),f&&d&&(0,i.jsx)("div",{className:"mt-2",onClick:h=>h.stopPropagation(),children:d})]})}function KI({children:e,minCardWidth:t=220,gap:r=3,className:n}){return(0,i.jsx)("div",{className:A("p-4 overflow-y-auto flex-1 content-start",n),style:{display:"grid",gridTemplateColumns:`repeat(auto-fill, minmax(${t}px, 1fr))`,gap:`${r*4}px`},children:e})}var WI="capability.binding-changed";function Br(e,t){const[r,n]=(0,l.useState)(null);return(0,l.useEffect)(()=>{if(t===null){n(null);return}let s=!1;const a=async()=>{try{const d=await e.deviceManager.getBindings.query({deviceId:t});s||n(d)}catch{s||n(d=>d)}};a();const c=e.live?.onEvent.subscribe({category:WI},{onData:d=>{const u=d.data?.source;if(!u){a();return}u.type==="device"&&u.id===t&&a()}});return()=>{s=!0,c?.unsubscribe()}},[e,t]),(0,l.useMemo)(()=>r?(0,W.createDeviceProxy)(e,r):null,[e,r])}function En(e){const t=(0,l.useCallback)(n=>e?e.subscribe(()=>n()):()=>{},[e]),r=(0,l.useCallback)(()=>e?.value,[e]);return(0,l.useSyncExternalStore)(t,r,r)}function Dv(e,t,r){const n=Br(e,t);return En(n?r(n.state):void 0)}function bt(e){const t=Br(e.trpc,e.deviceId),r=En(t!==null?e.slice(t):void 0),n=t!==null?e.cap(t):void 0,s=En(t!==null?t.state.deviceStatus:void 0),a=s?.online??!0,c=a?null:s?.lastChangedAt??null;return{dev:t,cap:n,slice:r,available:(e.requireFeature===void 0||(e.deviceFeatures??[]).includes(e.requireFeature))&&n!==void 0&&r!==void 0&&a,online:a,offlineSince:c}}var us={[W.DeviceType.Camera]:{icon:_p,label:"Camera"},[W.DeviceType.Hub]:{icon:Fp,label:"Hub"},[W.DeviceType.Light]:{icon:Zd,label:"Light"},[W.DeviceType.Siren]:{icon:Zp,label:"Siren"},[W.DeviceType.Switch]:{icon:ef,label:"Switch"},[W.DeviceType.Sensor]:{icon:wn,label:"Sensor"},[W.DeviceType.Thermostat]:{icon:Jd,label:"Thermostat"},[W.DeviceType.Button]:{icon:wp,label:"Button"},[W.DeviceType.EventEmitter]:{icon:si,label:"Event Emitter"},[W.DeviceType.Update]:{icon:Ii,label:"Update"},[W.DeviceType.Generic]:{icon:Fd,label:"Generic"},[W.DeviceType.Notifier]:{icon:Qa,label:"Notifier"},[W.DeviceType.Script]:{icon:zp,label:"Script"},[W.DeviceType.Automation]:{icon:UC,label:"Automation"},[W.DeviceType.Lock]:{icon:Hd,label:"Lock"},[W.DeviceType.Cover]:{icon:ET,label:"Cover"},[W.DeviceType.Valve]:{icon:pC,label:"Valve"},[W.DeviceType.Humidifier]:{icon:FC,label:"Humidifier"},[W.DeviceType.WaterHeater]:{icon:xT,label:"Water heater"},[W.DeviceType.Fan]:{icon:Gd,label:"Fan"},[W.DeviceType.MediaPlayer]:{icon:dC,label:"Media player"},[W.DeviceType.AlarmPanel]:{icon:Qd,label:"Alarm panel"},[W.DeviceType.Control]:{icon:Yd,label:"Control"},[W.DeviceType.Presence]:{icon:oC,label:"Presence"},[W.DeviceType.Weather]:{icon:Tp,label:"Weather"},[W.DeviceType.Vacuum]:{icon:kT,label:"Vacuum"},[W.DeviceType.LawnMower]:{icon:NC,label:"Lawn mower"},[W.DeviceType.Container]:{icon:Fd,label:"Container"},[W.DeviceType.Image]:{icon:Np,label:"Image"}},Al={[W.DeviceRole.Siren]:{icon:Zp,label:"Siren"},[W.DeviceRole.Floodlight]:{icon:Zd,label:"Floodlight"},[W.DeviceRole.Spotlight]:{icon:HT,label:"Spotlight"},[W.DeviceRole.PirSensor]:{icon:xC,label:"PIR sensor"},[W.DeviceRole.Chime]:{icon:Qa,label:"Chime"},[W.DeviceRole.Autotrack]:{icon:Bd,label:"Auto-track"},[W.DeviceRole.Nightvision]:{icon:bl,label:"Night vision"},[W.DeviceRole.PrivacyMask]:{icon:vl,label:"Privacy mask"},[W.DeviceRole.Doorbell]:{icon:GT,label:"Doorbell"},[W.DeviceRole.BinaryHelper]:{icon:ef,label:"Binary helper"},[W.DeviceRole.MotionSensor]:{icon:WT,label:"Motion sensor"},[W.DeviceRole.ContactSensor]:{icon:Ya,label:"Contact sensor"},[W.DeviceRole.LeakSensor]:{icon:Cp,label:"Leak sensor"},[W.DeviceRole.SmokeSensor]:{icon:mT,label:"Smoke sensor"},[W.DeviceRole.COSensor]:{icon:xl,label:"CO sensor"},[W.DeviceRole.GasSensor]:{icon:VT,label:"Gas sensor"},[W.DeviceRole.TamperSensor]:{icon:Qd,label:"Tamper sensor"},[W.DeviceRole.VibrationSensor]:{icon:LC,label:"Vibration sensor"},[W.DeviceRole.ConnectivitySensor]:{icon:rf,label:"Connectivity"},[W.DeviceRole.SoundSensor]:{icon:tf,label:"Sound sensor"},[W.DeviceRole.BinarySensor]:{icon:ef,label:"Binary sensor"},[W.DeviceRole.TemperatureSensor]:{icon:Jd,label:"Temperature"},[W.DeviceRole.HumiditySensor]:{icon:zd,label:"Humidity"},[W.DeviceRole.AmbientLightSensor]:{icon:Xd,label:"Ambient light"},[W.DeviceRole.PressureSensor]:{icon:eo,label:"Pressure"},[W.DeviceRole.PowerSensor]:{icon:si,label:"Power"},[W.DeviceRole.EnergySensor]:{icon:si,label:"Energy"},[W.DeviceRole.VoltageSensor]:{icon:si,label:"Voltage"},[W.DeviceRole.CurrentSensor]:{icon:si,label:"Current"},[W.DeviceRole.AirQualitySensor]:{icon:xl,label:"Air quality"},[W.DeviceRole.BatterySensor]:{icon:eo,label:"Battery"},[W.DeviceRole.NumericSensor]:{icon:JT,label:"Numeric sensor"},[W.DeviceRole.EnumSensor]:{icon:iC,label:"Enum sensor"},[W.DeviceRole.DateTimeSensor]:{icon:Ud,label:"Date / time"},[W.DeviceRole.GenericSensor]:{icon:eo,label:"Sensor"},[W.DeviceRole.NumericControl]:{icon:Yd,label:"Numeric control"},[W.DeviceRole.SelectControl]:{icon:Dp,label:"Select control"},[W.DeviceRole.TextControl]:{icon:$C,label:"Text control"},[W.DeviceRole.DateTimeControl]:{icon:Ud,label:"Date / time control"},[W.DeviceRole.MobilePushNotifier]:{icon:PC,label:"Mobile push"},[W.DeviceRole.MessagingNotifier]:{icon:uC,label:"Messaging"},[W.DeviceRole.EmailNotifier]:{icon:aC,label:"Email"},[W.DeviceRole.GenericNotifier]:{icon:Qa,label:"Notifier"}},qI=new Set(Object.values(W.DeviceType)),QI=new Set(Object.values(W.DeviceRole));function YI(e){return qI.has(e)}function XI(e){return QI.has(e)}function JI(e){return us[e]}function eP(e){return Al[e]}function jl(e){return YI(e)?us[e]:us[W.DeviceType.Generic]}function Mv(e){return XI(e)?Al[e]:Al[W.DeviceRole.GenericSensor]}var tP=Object.values(W.DeviceType).map(e=>({id:e,label:us[e].label,icon:us[e].icon}));function $v(){return tP}var yf=["lock","climate","light","fan","cover","switch","sensor"];function Rv(e,t){if(t!==void 0){const r=e.find(n=>n.entityId===t);if(r!==void 0)return r}return[...e].sort((r,n)=>Lv(r.type)-Lv(n.type))[0]??null}function Lv(e){const t=yf.indexOf(e);return t===-1?yf.length:t}function Nl(e){return e.sourceInfo?.id??e.stableId}function Ov(e){return{id:e.id,entityId:Nl(e),type:e.type}}function Fv(e,t){if(t==null)return;const r=e.find(n=>n.id===t);return r===void 0?void 0:Nl(r)}function ds(e,t,r){return Rv(e.map(Ov),r!=null&&r!==""?r:Fv(e,t))}function rP(e){return e.parentDeviceId===null?"top-level":e.role?"accessory":"adopted"}var nP={minimal:{showIntegrationIcon:!1,showParentBadge:!1,showSnapshot:!1,showBattery:!1,showStableId:!1,showId:!1,showSwitchToggle:!0,showChildrenAccordion:!1},compact:{showIntegrationIcon:!0,showParentBadge:!0,showSnapshot:!0,showBattery:!0,showStableId:!1,showId:!1,showSwitchToggle:!0,showChildrenAccordion:!0},expanded:{showIntegrationIcon:!1,showParentBadge:!0,showSnapshot:!0,showBattery:!0,showStableId:!0,showId:!0,showSwitchToggle:!0,showChildrenAccordion:!0}};function iP(e){const t=nP[e.variant??"compact"];return{showIntegrationIcon:e.showIntegrationIcon??t.showIntegrationIcon,showParentBadge:e.showParentBadge??t.showParentBadge,showSnapshot:e.showSnapshot??t.showSnapshot,showBattery:e.showBattery??t.showBattery,showStableId:e.showStableId??t.showStableId,showId:e.showId??t.showId,showSwitchToggle:e.showSwitchToggle??t.showSwitchToggle,showChildrenAccordion:e.showChildrenAccordion??t.showChildrenAccordion}}function Uv(e){return e.role?Mv(e.role).icon:jl(e.type).icon}var Bv={"native-snapshot":Np,"two-way-audio":$p,"pan-tilt-zoom":Bd,"ptz-autotrack":sC,"doorbell-button":Ya,"motion-trigger":wn,"battery-operated":_T,rebootable:Wd},zv={"native-snapshot":"Native snapshot","two-way-audio":"Two-way audio","pan-tilt-zoom":"Pan-Tilt-Zoom","ptz-autotrack":"PTZ autotrack","doorbell-button":"Doorbell button","motion-trigger":"Motion trigger","battery-operated":"Battery operated",rebootable:"Rebootable"},sP={"native-snapshot":"snapshot",rebootable:"reboot","pan-tilt-zoom":"ptz","ptz-autotrack":"ptz-autotrack","two-way-audio":"intercom","motion-trigger":"motion-trigger"},Gv=new Set(["camera","hub","nvr"]);function aP(e){return!Gv.has(e.type.toLowerCase())}function Zv(e){return e.role?!0:!Gv.has(e.type.toLowerCase())}function Vv(e){return(e.features??[]).includes("motion-trigger")}function oP(e,t){if(e.type!==W.DeviceType.Container)return e.online;const r=t??[];if(r.length===0)return e.online;const n=ds(r,e.linkDeviceId,e.primaryChildEntityId);if(n===null)return e.online;const s=r.find(a=>a.id===n.id);return s===void 0?e.online:s.online}function Hv(e,t){if(e.type!==W.DeviceType.Container)return e.type;const r=t??[];if(r.length===0)return e.type;const n=ds(r,e.linkDeviceId,e.primaryChildEntityId);if(n===null)return e.type;const s=r.find(a=>a.id===n.id);return s===void 0?e.type:s.type}function lP(e,t){if(e.type!==W.DeviceType.Container)return e;const r=t??[];if(r.length===0)return e;const n=ds(r,e.linkDeviceId,e.primaryChildEntityId);return n===null?e:r.find(s=>s.id===n.id)??e}function cP(e){if(e.length<=24)return e;const t=e.lastIndexOf(":");if(t>=0&&t<e.length-4)return e.slice(t+1);const r=e.split("-");if(r.length>2){const n=r.slice(-2).join("-");if(n.length>=6)return n}return`…${e.slice(-18)}`}function Kv({trpc:e,accessoryChildren:t,adoptedChildren:r,onNavigate:n}){return(0,i.jsxs)("div",{className:"border-t border-border-subtle/50",children:[r.length>0&&(0,i.jsx)(Wv,{trpc:e,label:"Adopted devices",rows:r,onNavigate:n}),t.length>0&&(0,i.jsx)(Wv,{trpc:e,label:"Accessories",rows:t,onNavigate:n})]})}function Wv({trpc:e,label:t,rows:r,onNavigate:n}){return(0,i.jsxs)("div",{children:[(0,i.jsx)("div",{className:"px-3 pt-1.5 pb-1 text-[9px] font-semibold uppercase tracking-wide text-foreground-subtle",children:t}),(0,i.jsx)("ul",{children:r.map(s=>(0,i.jsx)(uP,{trpc:e,child:s,onNavigate:n},s.id))})]})}function uP({trpc:e,child:t,onNavigate:r}){const n=!t.disabled,s=n&&aP(t),a=n&&Vv(t);return(0,i.jsx)("li",{children:(0,i.jsxs)("div",{onClick:c=>{c.stopPropagation(),r(t.id)},className:"w-full flex items-center gap-2 px-3 py-1.5 text-left hover:bg-surface-hover transition-colors cursor-pointer",children:[(0,i.jsx)(Uv(t),{className:"h-3 w-3 text-foreground-subtle flex-shrink-0"}),(0,i.jsx)("span",{className:"text-[10.5px] text-foreground flex-1 truncate",children:t.name}),a&&(0,i.jsx)(fP,{trpc:e,deviceId:t.id,features:t.features}),s&&(0,i.jsx)(dP,{trpc:e,deviceId:t.id}),(0,i.jsx)("span",{className:A("h-1.5 w-1.5 rounded-full flex-shrink-0",t.online?"bg-success":"bg-foreground-subtle/40"),title:t.online?"Online":"Offline"})]})})}function dP({trpc:e,deviceId:t}){const{dev:r,cap:n,slice:s,available:a}=bt({trpc:e,deviceId:t,cap:m=>m.switch,slice:m=>m.state.switch}),[c,d]=(0,l.useState)(!1);if(r!==null&&!n)return null;const u=s?.on===!0,f={transform:u?"translateX(14px)":"translateX(2px)"},h=async m=>{if(m.stopPropagation(),!(c||!a||!n)){d(!0);try{await n.setState({on:!u})}finally{d(!1)}}};return(0,i.jsx)("button",{type:"button",onClick:m=>{h(m)},disabled:c||!a,className:A("relative inline-flex h-4 w-7 items-center rounded-full border transition-colors flex-shrink-0",u?"bg-success/30 border-success/50":"bg-surface-hover border-border",c&&"opacity-60",!a&&"opacity-40 cursor-not-allowed"),title:a?u?"Turn off":"Turn on":"Awaiting state…","aria-pressed":u,children:(0,i.jsx)("span",{className:A("absolute h-3 w-3 rounded-full transition-all",u?"bg-success":"bg-foreground-subtle"),style:f})})}function fP({trpc:e,deviceId:t,features:r}){const{dev:n,cap:s,slice:a,available:c}=bt({trpc:e,deviceId:t,cap:m=>m.motionTrigger,slice:m=>m.state.motionTrigger,requireFeature:"motion-trigger",deviceFeatures:r}),[d,u]=(0,l.useState)(!1);if(n!==null&&!s)return null;const f=a?.enabled===!0,h=async m=>{if(m.stopPropagation(),!(d||!c||!s)){u(!0);try{await s.setMotionTrigger({enabled:!f})}finally{u(!1)}}};return(0,i.jsx)("button",{type:"button",onClick:m=>{h(m)},disabled:d||!c,className:A("inline-flex h-4 w-4 items-center justify-center rounded transition-colors flex-shrink-0",f?"text-primary bg-primary/10":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",(d||!c)&&"opacity-50"),title:c?f?"Motion-trigger: on (click to disable)":"Motion-trigger: off (click to enable)":"Awaiting state…","aria-pressed":f,children:(0,i.jsx)(wn,{className:"h-2.5 w-2.5"})})}var hP=[],qv=(0,l.createContext)(null);function xf({value:e,children:t}){return(0,i.jsx)(qv.Provider,{value:e,children:t})}function Dl(e){return(0,l.useContext)(qv)?.get(e)??hP}var Qv={up:{pan:0,tilt:1},down:{pan:0,tilt:-1},left:{pan:-1,tilt:0},right:{pan:1,tilt:0},"up-left":{pan:-1,tilt:1},"up-right":{pan:1,tilt:1},"down-left":{pan:-1,tilt:-1},"down-right":{pan:1,tilt:-1}};function Sf(e,t,r){const n=r?.defaultSpeed??.5,s=r?.pulseMs??250,a=r?.enabled??!0,c=Br(e,a?t:null)?.ptz,[d,u]=(0,l.useState)([]),[f,h]=(0,l.useState)(null),[m,g]=(0,l.useState)(!1),[p,y]=(0,l.useState)(null),S=(0,l.useCallback)(async()=>{if(!(!a||!c))try{u(await c.getPresets({}))}catch(j){if(za(j))return;y(j instanceof Error?j.message:String(j))}},[c,a]),E=(0,l.useCallback)(async()=>{if(!(!a||!c))try{h(await c.getOptions({}))}catch(j){if(za(j))return;y(j instanceof Error?j.message:String(j))}},[c,a]);(0,l.useEffect)(()=>{S(),E()},[S,E]);const T=(0,l.useCallback)(async j=>{if(!(!a||!c)){y(null),g(!0);try{return await j()}catch(N){y(N instanceof Error?N.message:String(N));return}finally{g(!1)}}},[a,c]);return{move:(0,l.useCallback)(async(j,N)=>{if(!c)return;const O=Qv[j],U=N??n;await T(async()=>{await c.move({pan:O.pan,tilt:O.tilt,speed:U}),await new Promise(z=>setTimeout(z,s)),await c.stop({})})},[c,n,s,T]),startContinuous:(0,l.useCallback)(async(j,N)=>{if(!c)return;const O=Qv[j],U=N??n;await T(()=>c.continuousMove({pan:O.pan,tilt:O.tilt,speed:U}))},[c,n,T]),stopContinuous:(0,l.useCallback)(async()=>{c&&await T(()=>c.stop({}))},[c,T]),zoom:(0,l.useCallback)(async(j,N)=>{if(!c)return;const O=j==="in"?1:-1,U=N??n;await T(async()=>{await c.move({zoom:O,speed:U}),await new Promise(z=>setTimeout(z,s)),await c.stop({})})},[c,n,s,T]),goHome:(0,l.useCallback)(async()=>{c&&await T(()=>c.goHome({}))},[c,T]),goToPreset:(0,l.useCallback)(async j=>{c&&await T(()=>c.goToPreset({presetId:j}))},[c,T]),savePreset:(0,l.useCallback)(async j=>{if(c)return T(async()=>{const N=new Set(d.map(z=>Number(z.id)).filter(z=>Number.isInteger(z)&&z>=0));let O=0;for(;N.has(O);)O+=1;const U=String(O);return await c.savePreset({presetId:U,name:j}),await S(),U})},[c,d,S,T]),deletePreset:(0,l.useCallback)(async j=>{c&&await T(async()=>{await c.deletePreset({presetId:j}),await S()})},[c,S,T]),presets:d,refreshPresets:S,options:f,busy:m,error:p}}function Ml({direction:e,icon:t,disabled:r,className:n,variant:s,onMove:a,onStart:c,onStop:d}){const[u,f]=(0,l.useState)(null),[h,m]=(0,l.useState)(!1),g=(0,l.useCallback)(T=>{if(r)return;T.currentTarget.setPointerCapture(T.pointerId),f(Date.now()),m(!1);const j=setTimeout(()=>{m(!0),c(e)},250);T.currentTarget.dataset.timer=String(j)},[e,r,c]),p=(0,l.useCallback)(T=>{const j=Number(T.currentTarget.dataset.timer);j&&clearTimeout(j),T.currentTarget.dataset.timer="",h?d():u!==null&&a(e),f(null),m(!1)},[h,e,a,d,u]),y=(0,l.useCallback)(T=>{const j=Number(T.currentTarget.dataset.timer);j&&clearTimeout(j),T.currentTarget.dataset.timer="",h&&d(),f(null),m(!1)},[h,d]),S=s==="panel"?"h-9 w-9":"h-7 w-7",E=s==="panel"?"h-4 w-4":"h-3.5 w-3.5";return(0,i.jsx)("button",{type:"button",disabled:r,onPointerDown:g,onPointerUp:p,onPointerCancel:y,className:A("flex items-center justify-center rounded transition-colors disabled:opacity-40",s==="panel"?"text-foreground hover:bg-surface-hover active:bg-surface-hover/80":"text-white hover:bg-white/15 active:bg-white/25",S,n),title:e,children:(0,i.jsx)(t,{className:E})})}function _f({controls:e,mode:t="overlay",showPresets:r,showZoom:n=!0,showHome:s=!0,className:a}){const{move:c,startContinuous:d,stopContinuous:u,zoom:f,goHome:h,goToPreset:m,savePreset:g,deletePreset:p,presets:y,options:S,busy:E,error:T}=e,j=ji(),[N,O]=(0,l.useState)(!1),[U,z]=(0,l.useState)(""),K=(r??y.length>0)&&y.length>0,G=t==="panel",X=G&&(S?.supportsPresets??!1),te=S?.maxPresets!==void 0&&y.length>=S.maxPresets,ne=(0,l.useCallback)(async()=>{const Q=U.trim();!Q||E||te||await g(Q)!==void 0&&z("")},[U,E,te,g]),ae=(0,l.useCallback)(async(Q,ie)=>{await j({title:"Delete preset",message:`Delete PTZ preset "${ie}"? This removes it from the camera.`,confirmLabel:"Delete",variant:"danger"})&&await p(Q)},[j,p]),oe=G?"flex flex-col items-stretch gap-2 w-full h-full p-3":"pointer-events-auto absolute top-3 right-3 z-10 flex flex-col items-end gap-2",pe=A(G?"flex items-center gap-3 rounded-lg p-2":"flex items-center gap-2 rounded-lg border border-white/30 bg-zinc-900/90 backdrop-blur-md p-2 shadow-lg shadow-black/40",E&&"ring-1 ring-primary/40"),le=G?"h-9 w-9":"h-7 w-7",se=G?"h-4 w-4":"h-3.5 w-3.5",Ce=G?"text-foreground hover:bg-surface-hover":"text-white hover:bg-white/15",q=G?"h-12 w-px bg-border mx-1":"h-12 w-px bg-white/15 mx-1";return(0,i.jsxs)("div",{className:A(oe,a),children:[T&&(0,i.jsxs)("div",{className:"rounded bg-danger/90 px-2 py-1 text-[10px] font-medium text-white shadow-lg max-w-[200px] self-center",children:["PTZ: ",T]}),(0,i.jsxs)("div",{className:A(pe,G&&"justify-center"),children:[(0,i.jsxs)("div",{className:"grid grid-cols-3 gap-0.5",children:[(0,i.jsx)("span",{"aria-hidden":!0,className:G?"h-9 w-9":"h-7 w-7"}),(0,i.jsx)(Ml,{direction:"up",icon:yT,variant:t,onMove:c,onStart:d,onStop:u}),(0,i.jsx)("span",{"aria-hidden":!0,className:G?"h-9 w-9":"h-7 w-7"}),(0,i.jsx)(Ml,{direction:"left",icon:pT,variant:t,onMove:c,onStart:d,onStop:u}),(0,i.jsx)("span",{"aria-hidden":!0,className:G?"h-9 w-9":"h-7 w-7"}),(0,i.jsx)(Ml,{direction:"right",icon:vT,variant:t,onMove:c,onStart:d,onStop:u}),(0,i.jsx)("span",{"aria-hidden":!0,className:G?"h-9 w-9":"h-7 w-7"}),(0,i.jsx)(Ml,{direction:"down",icon:gT,variant:t,onMove:c,onStart:d,onStop:u}),(0,i.jsx)("span",{"aria-hidden":!0,className:G?"h-9 w-9":"h-7 w-7"})]}),(n||s)&&(0,i.jsx)("div",{className:q}),(0,i.jsxs)("div",{className:"flex flex-col gap-0.5",children:[n&&(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("button",{type:"button",onClick:()=>f("in"),disabled:E,title:"Zoom in",className:A("flex items-center justify-center rounded disabled:opacity-40",le,Ce),children:(0,i.jsx)(Wp,{className:se})}),(0,i.jsx)("button",{type:"button",onClick:()=>f("out"),disabled:E,title:"Zoom out",className:A("flex items-center justify-center rounded disabled:opacity-40",le,Ce),children:(0,i.jsx)(qp,{className:se})})]}),s&&(0,i.jsx)("button",{type:"button",onClick:()=>h(),disabled:E,title:"Go home",className:A("flex items-center justify-center rounded disabled:opacity-40",le,Ce),children:(0,i.jsx)(os,{className:se})})]}),K&&(0,i.jsxs)("div",{className:"relative",children:[(0,i.jsxs)("button",{type:"button",onClick:()=>O(Q=>!Q),disabled:E,className:A("flex items-center gap-1 rounded px-2 text-[10px] disabled:opacity-40",G?"h-9 text-foreground hover:bg-surface-hover":"h-7 text-white hover:bg-white/15"),title:"Presets",children:["Presets",(0,i.jsx)(fr,{className:A("h-3 w-3 transition-transform",N&&"rotate-180")})]}),N&&(0,i.jsx)("div",{className:A("absolute right-0 top-full mt-1 min-w-[140px] rounded-lg shadow-xl py-1 z-20",G?"bg-surface border border-border":"border border-white/30 bg-zinc-900/95 backdrop-blur-md"),children:y.map(Q=>(0,i.jsxs)("div",{className:A("group flex items-center",G?"hover:bg-surface-hover":"hover:bg-white/15"),children:[(0,i.jsx)("button",{type:"button",onClick:()=>{m(Q.id),O(!1)},disabled:E,className:A("flex-1 px-3 py-1.5 text-left text-[10px] disabled:opacity-40",G?"text-foreground":"text-white"),children:Q.name||Q.id}),X&&(0,i.jsx)("button",{type:"button",onClick:()=>void ae(Q.id,Q.name||Q.id),disabled:E,title:`Delete preset ${Q.name||Q.id}`,className:A("mr-1 flex h-5 w-5 shrink-0 items-center justify-center rounded","text-foreground-subtle hover:bg-danger/15 hover:text-danger disabled:opacity-40"),children:(0,i.jsx)(mr,{className:"h-3 w-3"})})]},Q.id))})]})]}),X&&(0,i.jsxs)("div",{className:"flex flex-col gap-1 rounded-lg border border-border p-2",children:[(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsx)("input",{type:"text",value:U,onChange:Q=>z(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"&&ne()},disabled:E||te,placeholder:"New preset name",maxLength:64,className:A("min-w-0 flex-1 rounded border border-border bg-surface px-2 py-1 text-[11px] text-foreground","placeholder:text-foreground-subtle focus:outline-none focus:ring-1 focus:ring-primary/50","disabled:opacity-40")}),(0,i.jsxs)("button",{type:"button",onClick:()=>void ne(),disabled:E||te||U.trim().length===0,title:te?`Camera preset limit reached (${S?.maxPresets})`:"Save current position as a new preset",className:A("flex h-7 shrink-0 items-center gap-1 rounded px-2 text-[10px] font-medium","bg-primary/15 text-primary hover:bg-primary/25 disabled:opacity-40"),children:[(0,i.jsx)(Ci,{className:"h-3 w-3"}),"Save current position"]})]}),te&&(0,i.jsxs)("span",{className:"text-[10px] text-foreground-subtle",children:["Camera preset limit reached (",S?.maxPresets,"). Delete a preset to add a new one."]})]})]})}var Yv="fill",Xv="right",Jv="center";function oo({align:e,children:t,className:r,...n}){if(e==="fit")return(0,i.jsx)("div",{...n,className:A("inline-flex items-center",r),children:t});const s=e==="center"?"justify-center":"justify-end";return(0,i.jsx)("div",{...n,className:A("w-[140px] shrink-0 flex items-center gap-1.5",s,e==="fill"?"[&>*:last-child]:w-full":"",r),children:t})}function mP({value:e,unit:t}){return(0,i.jsxs)("span",{className:"text-sm text-foreground",children:[e,t?(0,i.jsx)("span",{"data-unit":!0,className:"ml-0.5 text-[11px] text-foreground-subtle",children:t}):null]})}function wf({value:e,unit:t,onDelta:r}){return(0,i.jsxs)("div",{className:"flex h-8 w-full overflow-hidden rounded-lg border border-border bg-surface",children:[(0,i.jsx)("button",{type:"button","aria-label":"Decrement",className:"w-9 shrink-0 bg-surface-hover text-base text-foreground",onClick:()=>r(-1),children:"−"}),(0,i.jsxs)("span",{className:"flex flex-1 items-center justify-center gap-0.5 border-x border-border/60 text-sm",children:[e,t?(0,i.jsx)("span",{"data-unit":!0,className:"text-[11px] text-foreground-subtle",children:t}):null]}),(0,i.jsx)("button",{type:"button","aria-label":"Increment",className:"w-9 shrink-0 bg-surface-hover text-base text-foreground",onClick:()=>r(1),children:"+"})]})}function e0({on:e,targetLabel:t,onConfirm:r}){const n=(0,l.useRef)(null),s=(0,l.useRef)(!1);return(0,i.jsxs)("div",{className:A("relative h-12 w-full rounded-full border flex items-center",e?"bg-emerald-50 border-emerald-200 pl-4":"bg-amber-50 border-amber-200 justify-end pr-4"),children:[(0,i.jsx)("span",{className:"text-xs font-semibold opacity-60",children:t}),(0,i.jsx)("span",{"data-testid":"slide-thumb",className:"absolute top-1 left-1 h-10 w-14 rounded-[19px] bg-surface shadow flex items-center justify-center",onPointerDown:a=>{a.currentTarget.setPointerCapture?.(a.pointerId),n.current=a.clientX,s.current=!1},onPointerMove:a=>{n.current!==null&&Math.abs(a.clientX-n.current)>40&&(s.current=!0)},onPointerUp:()=>{s.current&&r(),s.current=!1,n.current=null},onPointerCancel:()=>{s.current=!1,n.current=null}})]})}var gP=2,t0=270,pP=315;function vP(e){const t=(e-135+360)%360;return t>t0?t<=pP?1:0:t/t0}function lo({fraction:e,color:t,knobTopPx:r,onDragFraction:n}){const s=-135+e*270,a=(0,l.useRef)(null),[c,d]=(0,l.useState)(!1),u=n!==void 0,f=r??gP,h=p=>{n!==void 0&&(p.preventDefault(),p.stopPropagation(),p.currentTarget.setPointerCapture?.(p.pointerId),d(!0))},m=p=>{if(n===void 0||!c)return;const y=a.current;if(y===null)return;const S=y.getBoundingClientRect(),E=S.left+S.width/2,T=S.top+S.height/2;n(vP(Math.atan2(p.clientY-T,p.clientX-E)*180/Math.PI))},g=p=>{n!==void 0&&(p.currentTarget.releasePointerCapture?.(p.pointerId),d(!1))};return(0,i.jsx)("div",{ref:a,className:"absolute inset-0",style:{transform:`rotate(${s}deg)`},children:(0,i.jsx)("div",{className:A("absolute left-1/2 h-5 w-5 -translate-x-1/2 rounded-full bg-white shadow",u&&(c?"cursor-grabbing":"cursor-grab")),style:{top:f,border:`3px solid ${t}`},...u?{onPointerDown:h,onPointerMove:m,onPointerUp:g,onPointerCancel:g}:{}})})}function $l({fraction:e,color:t}){return(0,i.jsxs)("div",{className:"relative h-2 w-full rounded-full bg-border",children:[(0,i.jsx)("div",{className:"absolute left-0 top-0 h-2 rounded-full",style:{width:`${e*100}%`,background:t??"var(--color-primary)"}}),(0,i.jsx)("div",{className:"absolute -top-1 h-4 w-4 rounded-full bg-white shadow",style:{left:`calc(${e*100}% - 8px)`}})]})}function r0({trpc:e,deviceId:t}){const r=Br(e,t),n=r!==null?r.button:void 0;if(n===void 0)return null;const s=()=>{n.press({deviceId:t})};return(0,i.jsxs)("button",{type:"button","aria-label":"Press",title:"Press",onClick:a=>{a.stopPropagation(),s()},className:A("inline-flex h-5 items-center gap-1 rounded px-1.5 text-xs","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors"),children:[(0,i.jsx)(Op,{className:"h-3 w-3"}),(0,i.jsx)("span",{children:"Press"})]})}function n0({trpc:e,deviceId:t}){const r=Br(e,t),n=r!==null?r.button:void 0;if(n===void 0)return null;const s=()=>{n.press({deviceId:t})};return(0,i.jsxs)("div",{className:"flex flex-col items-center justify-center gap-4 rounded-lg border border-border bg-surface p-6",children:[(0,i.jsx)("button",{type:"button","aria-label":"Press button",onClick:s,className:A("inline-flex h-14 w-14 items-center justify-center rounded-full","bg-primary text-primary-foreground hover:bg-primary/90 transition-colors","shadow-md"),children:(0,i.jsx)(Op,{className:"h-6 w-6"})}),(0,i.jsx)("span",{className:"text-sm font-medium text-foreground",children:"Press"})]})}var bP=4e3;function i0(e){if(e!==void 0)return e!==null&&typeof e=="object"&&"lastChangedAt"in e&&typeof e.lastChangedAt=="number"?e.lastChangedAt:e}function Zt(e,t){const r=t?.enabled!==!1,n=t?.timeoutMs??bP,[s,a]=(0,l.useState)(void 0),c=(0,l.useRef)(void 0),d=(0,l.useRef)(void 0),u=(0,l.useRef)(!1),f=(0,l.useRef)(void 0),h=(0,l.useCallback)(()=>{f.current!==void 0&&(clearTimeout(f.current),f.current=void 0),c.current=void 0,u.current=!1,d.current=void 0,a(void 0)},[]);(0,l.useEffect)(()=>{if(!r||!u.current)return;const g=i0(e),p=d.current;g!==void 0&&g!==p&&h()}),(0,l.useEffect)(()=>()=>{f.current!==void 0&&clearTimeout(f.current)},[]);const m=(0,l.useCallback)(g=>{if(!r)return;f.current!==void 0&&(clearTimeout(f.current),f.current=void 0);const p=c.current??e;if(p!==void 0){const y={...p,...g};c.current=y,a(y)}d.current=i0(e),u.current=!0,f.current=setTimeout(h,n)},[r,e,h,n]);return r?{display:s!==void 0?s:e,applyOptimistic:m}:{display:e,applyOptimistic:()=>{}}}function co(e){switch(e){case"opening":return{up:"accent",stop:"neutral",down:"neutral"};case"closing":return{up:"neutral",stop:"neutral",down:"accent"};case"open":return{up:"filled",stop:"neutral",down:"neutral"};case"closed":return{up:"neutral",stop:"neutral",down:"filled"};default:return{up:"neutral",stop:"neutral",down:"neutral"}}}function yP(e){switch(e){case"accent":return"bg-primary text-primary-foreground";case"filled":return"bg-primary/15 text-primary";case"neutral":return""}}function Ef({label:e,busy:t,variant:r,onClick:n,children:s}){return(0,i.jsx)("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:a=>{a.stopPropagation(),n()},className:A("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",yP(r),t&&"opacity-40 cursor-not-allowed"),children:s})}function s0({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:a}=bt({trpc:e,deviceId:t,cap:m=>m.cover,slice:m=>m.state.cover}),{display:c,applyOptimistic:d}=Zt(s,{enabled:r??!0});if(n===void 0)return null;const u=co(c?.state),f=!a,h=(m,g)=>{f||!m||(g!==void 0&&d(g),m({}))};return(0,i.jsxs)("div",{className:"inline-flex items-center gap-1",children:[(0,i.jsx)(Ef,{label:"Open",busy:f,variant:u.up,onClick:()=>h(n?.open,{state:"opening"}),children:(0,i.jsx)(Ti,{className:"h-3.5 w-3.5"})}),(0,i.jsx)(Ef,{label:"Stop",busy:f,variant:u.stop,onClick:()=>h(n?.stop,{state:"stopped"}),children:(0,i.jsx)(Un,{className:"h-3 w-3"})}),(0,i.jsx)(Ef,{label:"Close",busy:f,variant:u.down,onClick:()=>h(n?.close,{state:"closing"}),children:(0,i.jsx)(fr,{className:"h-3.5 w-3.5"})}),c!==void 0&&c.position!==null&&(0,i.jsxs)("span",{className:"tabular-nums text-xs text-foreground-subtle ml-1",children:[c.position,"%"]})]})}function kf({label:e,busy:t,variant:r,onClick:n,children:s}){return(0,i.jsx)("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:a=>{a.stopPropagation(),n()},className:A("inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",r==="accent"&&"bg-primary text-primary-foreground hover:bg-primary/90",r==="filled"&&"bg-primary/15 text-primary",t&&"opacity-40 cursor-not-allowed"),children:s})}function a0(){return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("div",{"aria-hidden":"true",className:"absolute inset-y-0 left-1/2 w-px -translate-x-px bg-white/60"}),(0,i.jsx)("div",{"aria-hidden":"true",className:"absolute inset-x-0 top-1/2 h-px -translate-y-px bg-white/60"})]})}function xP({position:e,interactive:t,onSetPosition:r}){const n=(1-e/100)*100,s=(0,l.useRef)(null),a=(0,l.useRef)(!1),c=(0,l.useRef)(null),d=g=>{const p=s.current;if(p===null)return e;const y=p.getBoundingClientRect();if(y.height<=0)return e;const S=(g-y.top)/y.height,E=Math.round(100-S*100);return Math.min(100,Math.max(0,E))},u=g=>{if(r===void 0)return;const p=d(g);c.current!==p&&(c.current=p,r(p))},f=g=>{t&&(g.stopPropagation(),g.preventDefault(),a.current=!0,c.current=null,g.currentTarget.setPointerCapture(g.pointerId),u(g.clientY))},h=g=>{!t||!a.current||(g.stopPropagation(),u(g.clientY))},m=g=>{!t||!a.current||(g.stopPropagation(),a.current=!1,c.current=null,g.currentTarget.hasPointerCapture(g.pointerId)&&g.currentTarget.releasePointerCapture(g.pointerId))};return(0,i.jsxs)("div",{ref:s,"data-testid":"cover-window",...t?{"aria-label":"Drag to set position",role:"slider","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":e}:{"aria-hidden":"true"},onPointerDown:t?f:void 0,onPointerMove:t?h:void 0,onPointerUp:t?m:void 0,onPointerCancel:t?m:void 0,className:A("relative w-28 h-36 rounded border-2 border-amber-700/60 bg-gradient-to-b from-sky-200 to-sky-50 overflow-hidden flex-shrink-0",t&&"cursor-ns-resize touch-none select-none"),style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.5)"},children:[(0,i.jsx)(a0,{}),(0,i.jsx)("div",{className:"absolute inset-x-0 top-0 transition-all duration-200",style:{height:`${n}%`,background:"repeating-linear-gradient(#c9cdd2, #c9cdd2 6px, #b7bcc2 6px, #b7bcc2 8px)",borderBottom:n>0?"1px solid #9aa":"none"}}),(0,i.jsxs)("div",{"data-testid":"cover-lever",className:A("absolute inset-x-0 h-4 flex items-center justify-center gap-1 z-10 transition-all duration-200",t&&"cursor-grab active:cursor-grabbing"),style:{top:`calc(${n}% - 8px)`},children:[(0,i.jsx)("div",{className:"absolute -inset-x-1.5 h-full rounded-lg bg-slate-600 shadow-md"}),(0,i.jsx)("span",{className:"h-1 w-1 rounded-full bg-white/70 relative z-10","aria-hidden":"true"}),(0,i.jsx)("span",{className:"h-1 w-1 rounded-full bg-white/70 relative z-10","aria-hidden":"true"}),(0,i.jsx)("span",{className:"h-1 w-1 rounded-full bg-white/70 relative z-10","aria-hidden":"true"}),(0,i.jsxs)("span",{"data-testid":"cover-position-pct",className:"absolute left-full ml-2 text-xs font-semibold text-foreground tabular-nums whitespace-nowrap",children:[e,"%"]})]})]})}function SP({isOpen:e}){return(0,i.jsxs)("div",{"data-testid":"cover-window","aria-hidden":"true",className:"relative w-28 h-36 rounded border-2 border-amber-700/60 bg-gradient-to-b from-sky-200 to-sky-50 overflow-hidden flex-shrink-0",style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.5)"},children:[(0,i.jsx)(a0,{}),!e&&(0,i.jsx)("div",{className:"absolute inset-0",style:{background:"repeating-linear-gradient(#c9cdd2, #c9cdd2 6px, #b7bcc2 6px, #b7bcc2 8px)"}})]})}function o0({trpc:e,deviceId:t,features:r,optimistic:n}){const{cap:s,slice:a,available:c}=bt({trpc:e,deviceId:t,cap:j=>j.cover,slice:j=>j.state.cover}),{display:d,applyOptimistic:u}=Zt(a,{enabled:n??!0});if(s===void 0)return null;const f=!c,h=(r??[]).includes(W.DeviceFeature.CoverPositionable),m=(r??[]).includes(W.DeviceFeature.CoverTilt),g=co(d?.state),p=d?.position??null,y=p!==null,S=d?.state==="open"||d?.state==="opening",E=(j,N)=>{f||!j||(N!==void 0&&u(N),j({}))},T=j=>{f||(u({position:j}),s?.setPosition({position:j}))};return(0,i.jsxs)("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsxs)("div",{className:"flex items-center gap-6",children:[y?(0,i.jsx)(xP,{position:p,interactive:h,onSetPosition:h?T:void 0}):(0,i.jsx)(SP,{isOpen:S}),(0,i.jsxs)("div",{className:"flex flex-col gap-3 flex-1",children:[y&&(0,i.jsxs)("div",{className:"flex items-baseline gap-1",children:[(0,i.jsx)("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:p}),(0,i.jsx)("span",{className:"text-base text-foreground-subtle",children:"%"}),(0,i.jsx)("span",{className:"text-xs text-foreground-subtle ml-1",children:"open"})]}),!y&&(0,i.jsx)("div",{className:"flex items-baseline gap-1",children:(0,i.jsx)("span",{className:"text-3xl font-semibold capitalize text-foreground",children:d?.state??"—"})}),(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsx)(kf,{label:"Open",busy:f,variant:g.up,onClick:()=>E(s?.open,{state:"opening"}),children:(0,i.jsx)(Ti,{className:"h-5 w-5"})}),(0,i.jsx)(kf,{label:"Stop",busy:f,variant:g.stop,onClick:()=>E(s?.stop,{state:"stopped"}),children:(0,i.jsx)(Un,{className:"h-4 w-4"})}),(0,i.jsx)(kf,{label:"Close",busy:f,variant:g.down,onClick:()=>E(s?.close,{state:"closing"}),children:(0,i.jsx)(fr,{className:"h-5 w-5"})})]})]})]}),h&&(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{className:"w-12 shrink-0",children:"Position"}),(0,i.jsx)("input",{"aria-label":"Position",type:"range",min:0,max:100,step:1,value:p??0,disabled:f,className:"flex-1",onChange:j=>{T(Number(j.target.value))}}),(0,i.jsxs)("span",{className:"w-8 text-right tabular-nums",children:[p??"—","%"]})]}),!h&&p!==null&&(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{className:"w-12 shrink-0",children:"Position"}),(0,i.jsx)("input",{"aria-label":"Position",type:"range",min:0,max:100,step:1,value:p,disabled:!0,readOnly:!0,className:"flex-1 opacity-60"}),(0,i.jsxs)("span",{className:"w-8 text-right tabular-nums",children:[p,"%"]})]}),m&&(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{className:"w-12 shrink-0",children:"Tilt"}),(0,i.jsx)("input",{"aria-label":"Tilt position",type:"range",min:0,max:100,step:1,value:d?.tiltPosition??0,disabled:f,className:"flex-1",onChange:j=>{const N=Number(j.target.value);u({tiltPosition:N}),f||s?.setTiltPosition({tiltPosition:N})}}),(0,i.jsxs)("span",{className:"w-8 text-right tabular-nums",children:[d?.tiltPosition??"—","%"]})]})]})}function l0(e){return(0,i.jsx)("span",{className:"text-foreground-subtle text-xs select-none","aria-hidden":"true",children:"—"})}function Tf(e){return(0,i.jsx)("div",{className:"rounded border border-border bg-surface-subtle px-3 py-2 text-xs text-foreground-subtle",children:"Controls coming soon"})}var _P=C.accessories.setChildHidden.useMutation,wP=C.accessories.getStatus.useQuery,EP=C.addonPages.listPages.useQuery,c0=C.addons.list.useQuery,kP=C.addons.getLogs.useQuery,TP=C.addons.listPackages.useQuery,CP=C.addons.installPackage.useMutation,IP=C.addons.installFromWorkspace.useMutation,PP=C.addons.isWorkspaceAvailable.useQuery,AP=C.addons.listWorkspacePackages.useQuery,jP=C.addons.uninstallPackage.useMutation,NP=C.addons.reloadPackages.useMutation,DP=C.addons.searchAvailable.useQuery,MP=C.addons.listUpdates.useQuery,$P=C.addons.updatePackage.useMutation,RP=C.addons.rollbackPackage.useMutation,LP=C.addons.forceRefresh.useMutation,OP=C.addons.restartServer.useMutation,FP=C.addons.getLastRestart.useQuery,UP=C.addons.listFrameworkPackages.useQuery,BP=C.addons.listCapabilityProviders.useQuery,zP=C.addons.setCapabilityProviderEnabled.useMutation,GP=C.addons.updateFrameworkPackage.useMutation,ZP=C.addons.startBulkUpdate.useMutation,VP=C.addons.getBulkUpdateState.useQuery,HP=C.addons.cancelBulkUpdate.useMutation,KP=C.addons.listActiveBulkUpdates.useQuery,WP=C.addons.getVersions.useQuery,qP=C.addons.restartAddon.useMutation,QP=C.addons.retryLoad.useMutation,YP=C.addons.getAutoUpdateSettings.useQuery,XP=C.addons.setAutoUpdateSettings.useMutation,JP=C.addons.getAddonAutoUpdate.useQuery,eA=C.addons.setAddonAutoUpdate.useMutation,tA=C.addons.applyAutoUpdateToAll.useMutation,rA=C.addons.custom.useMutation,nA=C.addons.onAddonLogs.useSubscription,iA=C.addonSettings.getGlobalSettings.useQuery,sA=C.addonSettings.updateGlobalSettings.useMutation,aA=C.addonSettings.getDeviceSettings.useQuery,oA=C.addonSettings.updateDeviceSettings.useMutation,u0=C.addonWidgets.listWidgets.useQuery,lA=C.airQualitySensor.getStatus.useQuery,cA=C.alarmPanel.arm.useMutation,uA=C.alarmPanel.disarm.useMutation,dA=C.alarmPanel.trigger.useMutation,fA=C.alarmPanel.getStatus.useQuery,hA=C.alerts.emit.useMutation,mA=C.alerts.update.useMutation,gA=C.alerts.list.useQuery,pA=C.alerts.getUnreadCount.useQuery,vA=C.alerts.markRead.useMutation,bA=C.alerts.markAllRead.useMutation,yA=C.alerts.dismiss.useMutation,xA=C.ambientLightSensor.getStatus.useQuery,SA=C.audioAnalysis.resolveDeviceSettings.useQuery,_A=C.audioAnalysis.getDeviceSettingsContribution.useQuery,wA=C.audioAnalysis.getDeviceLiveContribution.useQuery,EA=C.audioAnalysis.applyDeviceSettingsPatch.useMutation,kA=C.audioAnalyzer.analyseChunk.useMutation,TA=C.audioAnalyzer.classify.useQuery,CA=C.audioAnalyzer.isReady.useQuery,IA=C.audioAnalyzer.dispose.useMutation,PA=C.audioAnalyzer.reprobeAudioEngine.useMutation,AA=C.audioCodec.listSupportedCodecs.useQuery,jA=C.audioCodec.canHandle.useQuery,NA=C.audioCodec.createDecodeSession.useMutation,DA=C.audioCodec.createEncodeSession.useMutation,MA=C.audioCodec.closeSession.useMutation,$A=C.audioCodec.pushEncodedFrame.useMutation,RA=C.audioCodec.pullPcm.useQuery,LA=C.audioCodec.pushPcm.useMutation,OA=C.audioCodec.pullEncoded.useQuery,FA=C.audioCodec.flushEncode.useMutation,UA=C.audioCodec.listActiveSessions.useQuery,BA=C.audioMetrics.getCurrentSnapshot.useQuery,zA=C.audioMetrics.getHistory.useQuery,GA=C.automationControl.enable.useMutation,ZA=C.automationControl.disable.useMutation,VA=C.automationControl.trigger.useMutation,HA=C.automationControl.getStatus.useQuery,KA=C.backup.listDestinations.useQuery,WA=C.backup.trigger.useMutation,qA=C.backup.list.useQuery,QA=C.backup.listLocations.useQuery,YA=C.backup.getEntries.useQuery,XA=C.backup.restore.useMutation,JA=C.backup.delete.useMutation,ej=C.backup.listArchives.useQuery,tj=C.backup.upsertDestinationPolicy.useMutation,rj=C.backup.previewSchedule.useQuery,nj=C.battery.wakeForStream.useMutation,ij=C.battery.getStatus.useQuery,sj=C.binary.getStatus.useQuery,aj=C.brightness.setBrightness.useMutation,oj=C.brightness.getStatus.useQuery,lj=C.broker.list.useQuery,cj=C.broker.get.useQuery,uj=C.broker.listProviders.useQuery,dj=C.broker.add.useMutation,fj=C.broker.remove.useMutation,hj=C.broker.testConnection.useMutation,mj=C.broker.getSettings.useQuery,gj=C.broker.setSettings.useMutation,pj=C.broker.getBrokerConfig.useQuery,vj=C.broker.getSettingsSchema.useQuery,bj=C.broker.testSettings.useMutation,yj=C.broker.publish.useMutation,xj=C.broker.subscribe.useMutation,Sj=C.broker.unsubscribe.useMutation,_j=C.broker.getState.useQuery,wj=C.broker.getStatus.useQuery,Ej=C.button.press.useMutation,kj=C.cameraCredentials.getCredentials.useQuery,Tj=C.cameraCredentials.getStatus.useQuery,Cj=C.cameraPipelineConfig.getDeviceSettingsContribution.useQuery,Ij=C.cameraPipelineConfig.getDeviceLiveContribution.useQuery,Pj=C.cameraPipelineConfig.applyDeviceSettingsPatch.useMutation,Aj=C.cameraStreams.getCameraStreams.useQuery,jj=C.cameraStreams.getBrokerStreams.useQuery,d0=C.cameraStreams.getRtspEntries.useQuery,Nj=C.cameraStreams.getProfileRtspEntries.useQuery,Dj=C.cameraStreams.pickStream.useQuery,Mj=C.carbonMonoxide.getStatus.useQuery,$j=C.climateControl.setMode.useMutation,Rj=C.climateControl.setFanMode.useMutation,Lj=C.climateControl.setPreset.useMutation,Oj=C.climateControl.setTarget.useMutation,Fj=C.climateControl.setTargetRange.useMutation,Uj=C.climateControl.setTargetHumidity.useMutation,Bj=C.climateControl.getStatus.useQuery,zj=C.color.setColor.useMutation,Gj=C.color.getStatus.useQuery,Zj=C.connectivity.getStatus.useQuery,Vj=C.consumables.reset.useMutation,Hj=C.consumables.getStatus.useQuery,Kj=C.contact.getStatus.useQuery,Wj=C.control.setValue.useMutation,qj=C.control.getStatus.useQuery,Qj=C.cover.open.useMutation,Yj=C.cover.close.useMutation,Xj=C.cover.stop.useMutation,Jj=C.cover.setPosition.useMutation,eN=C.cover.setTiltPosition.useMutation,tN=C.cover.getStatus.useQuery,rN=C.decoder.supportsCodec.useQuery,nN=C.decoder.getInfo.useQuery,iN=C.decoder.createSession.useQuery,sN=C.decoder.destroySession.useQuery,aN=C.decoder.pushPacket.useQuery,oN=C.decoder.openStream.useQuery,lN=C.decoder.pullFrames.useQuery,cN=C.decoder.pullHandles.useQuery,uN=C.decoder.getFrame.useQuery,dN=C.decoder.getShmStats.useQuery,fN=C.decoder.updateConfig.useQuery,hN=C.decoder.getStats.useQuery,mN=C.decoder.listActiveSessions.useQuery,gN=C.decoder.reprobeHwaccel.useMutation,pN=C.detectionPipeline.getDeviceSettingsContribution.useQuery,vN=C.detectionPipeline.getDeviceLiveContribution.useQuery,bN=C.detectionPipeline.applyDeviceSettingsPatch.useMutation,yN=C.deviceAdoption.listCandidateFilters.useQuery,xN=C.deviceAdoption.listCandidates.useQuery,SN=C.deviceAdoption.getCandidate.useQuery,_N=C.deviceAdoption.refresh.useMutation,wN=C.deviceAdoption.adopt.useMutation,EN=C.deviceAdoption.release.useMutation,kN=C.deviceAdoption.resync.useMutation,TN=C.deviceAdoption.getStatus.useQuery,CN=C.deviceDiscovery.listDiscovered.useQuery,IN=C.deviceDiscovery.refreshDiscovery.useMutation,PN=C.deviceDiscovery.adoptDevice.useMutation,AN=C.deviceDiscovery.releaseDevice.useMutation,jN=C.deviceDiscovery.getStatus.useQuery,f0=C.deviceExport.getStatus.useQuery,h0=C.deviceExport.listSupportedDeviceKinds.useQuery,m0=C.deviceExport.listExposedDevices.useQuery,g0=C.deviceExport.exposeDevice.useMutation,p0=C.deviceExport.unexposeDevice.useMutation,NN=C.deviceExport.getDeviceSettingsContribution.useQuery,DN=C.deviceExport.getDeviceLiveContribution.useQuery,MN=C.deviceExport.applyDeviceSettingsPatch.useMutation,$N=C.deviceManager.allocateDeviceId.useMutation,RN=C.deviceManager.registerDevice.useMutation,LN=C.deviceManager.removeDevice.useMutation,ON=C.deviceManager.persistConfig.useMutation,FN=C.deviceManager.loadConfig.useQuery,UN=C.deviceManager.loadRuntimeState.useQuery,BN=C.deviceManager.loadMeta.useQuery,zN=C.deviceManager.setName.useMutation,GN=C.deviceManager.setLocation.useMutation,ZN=C.deviceManager.setType.useMutation,VN=C.deviceManager.setIntegrationId.useMutation,HN=C.deviceManager.setLinkDeviceId.useMutation,KN=C.deviceManager.setPrimaryChildEntityId.useMutation,WN=C.deviceManager.setChildLayout.useMutation,qN=C.deviceManager.setDeviceLinks.useMutation,QN=C.deviceManager.getWireableFields.useQuery,YN=C.deviceManager.setRole.useMutation,XN=C.deviceManager.applyInitialMeta.useMutation,JN=C.deviceManager.setMetadata.useMutation,eD=C.deviceManager.listLocations.useQuery,tD=C.deviceManager.addLocation.useMutation,rD=C.deviceManager.removeLocation.useMutation,nD=C.deviceManager.setDisabled.useMutation,iD=C.deviceManager.listPersistedByAddon.useQuery,Cf=C.deviceManager.listAll.useQuery,If=C.deviceManager.getDevice.useQuery,sD=C.deviceManager.getChildren.useQuery,aD=C.deviceManager.getStreamSources.useQuery,oD=C.deviceManager.getConfigSchema.useQuery,lD=C.deviceManager.getSettingsSchema.useQuery,cD=C.deviceManager.updateConfig.useMutation,uD=C.deviceManager.enable.useMutation,dD=C.deviceManager.disable.useMutation,fD=C.deviceManager.remove.useMutation,hD=C.deviceManager.removeByIntegration.useMutation,mD=C.deviceManager.getStreamProfileMap.useQuery,gD=C.deviceManager.setStreamProfileMap.useMutation,pD=C.deviceManager.probeStreams.useMutation,vD=C.deviceManager.getBindings.useQuery,bD=C.deviceManager.getAllBindings.useQuery,yD=C.deviceManager.setWrapperActive.useMutation,xD=C.deviceManager.listWrappersForCap.useQuery,SD=C.deviceManager.listBindableCapsForDeviceType.useQuery,_D=C.deviceManager.getDeviceSettingsAggregate.useQuery,wD=C.deviceManager.getDeviceLiveInfoAggregate.useQuery,ED=C.deviceManager.getDeviceAggregate.useQuery,kD=C.deviceManager.runDeviceAction.useMutation,TD=C.deviceManager.updateDeviceField.useMutation,CD=C.deviceManager.updateDeviceFieldsBatch.useMutation,ID=C.deviceManager.discoverDevices.useMutation,PD=C.deviceManager.adoptDevice.useMutation,AD=C.deviceManager.getCreationSchema.useQuery,jD=C.deviceManager.createDevice.useMutation,ND=C.deviceManager.testCreationField.useMutation,DD=C.deviceManager.adoptionListCandidates.useQuery,MD=C.deviceManager.adoptionRefresh.useMutation,$D=C.deviceManager.adoptionAdopt.useMutation,RD=C.deviceManager.adoptionRelease.useMutation,LD=C.deviceManager.testField.useMutation,OD=C.deviceManager.getDeviceStatusAggregate.useQuery,FD=C.deviceOps.getStreamSources.useQuery,UD=C.deviceOps.getConfigEntries.useQuery,BD=C.deviceOps.setConfig.useMutation,zD=C.deviceOps.runAction.useMutation,GD=C.deviceOps.removeDevice.useMutation,ZD=C.deviceOps.getSettingsSchema.useQuery,VD=C.deviceOps.getRawState.useQuery,HD=C.deviceProvider.start.useMutation,KD=C.deviceProvider.stop.useMutation,WD=C.deviceProvider.getStatus.useQuery,qD=C.deviceProvider.getDevices.useQuery,QD=C.deviceProvider.supportsDiscovery.useQuery,YD=C.deviceProvider.discoverDevices.useMutation,XD=C.deviceProvider.adoptDiscoveredDevice.useMutation,JD=C.deviceProvider.supportsManualCreation.useQuery,eM=C.deviceProvider.getChildCreationSchema.useQuery,tM=C.deviceProvider.createDevice.useMutation,rM=C.deviceProvider.testCreationField.useMutation,nM=C.deviceState.getSnapshot.useQuery,iM=C.deviceState.getCapSlice.useQuery,sM=C.deviceState.getAllSnapshots.useQuery,aM=C.deviceState.setCapSlice.useMutation,oM=C.deviceStatus.getStatus.useQuery,lM=C.doorbell.getStatus.useQuery,cM=C.enumSensor.getStatus.useQuery,uM=C.eventEmitter.getStatus.useQuery,dM=C.events.getEvents.useQuery,fM=C.events.getEventThumbnail.useQuery,hM=C.events.getEventClipUrl.useQuery,mM=C.fanControl.setPercentage.useMutation,gM=C.fanControl.setPreset.useMutation,pM=C.fanControl.setDirection.useMutation,vM=C.fanControl.setOscillating.useMutation,bM=C.fanControl.getStatus.useQuery,yM=C.featureProbe.getStatus.useQuery,xM=C.flood.getStatus.useQuery,SM=C.gas.getStatus.useQuery,_M=C.humidifier.setOn.useMutation,wM=C.humidifier.setTargetHumidity.useMutation,EM=C.humidifier.setMode.useMutation,kM=C.humidifier.getStatus.useQuery,TM=C.humiditySensor.getStatus.useQuery,CM=C.image.getStatus.useQuery,IM=C.integrations.list.useQuery,PM=C.integrations.get.useQuery,AM=C.integrations.getByAddonId.useQuery,jM=C.integrations.create.useMutation,NM=C.integrations.update.useMutation,DM=C.integrations.delete.useMutation,MM=C.integrations.getSettings.useQuery,$M=C.integrations.setSettings.useMutation,RM=C.integrations.getAvailableTypes.useQuery,LM=C.integrations.testConnection.useMutation,OM=C.intercom.startSession.useMutation,FM=C.intercom.handleAnswer.useMutation,UM=C.intercom.stopSession.useMutation,BM=C.intercom.startTalkSession.useMutation,zM=C.intercom.pushTalkAudio.useMutation,GM=C.intercom.endTalkSession.useMutation,ZM=C.intercom.getStatus.useQuery,VM=C.lawnMowerControl.startMowing.useMutation,HM=C.lawnMowerControl.pause.useMutation,KM=C.lawnMowerControl.dock.useMutation,WM=C.lawnMowerControl.getStatus.useQuery,qM=C.localNetwork.list.useQuery,QM=C.localNetwork.getPreferred.useQuery,YM=C.localNetwork.getConnectionEndpoints.useQuery,XM=C.localNetwork.getAllowedAddresses.useQuery,JM=C.localNetwork.setAllowedAddresses.useMutation,e$=C.localNetwork.resetAllowlistToBestMatch.useMutation,t$=C.lockControl.lock.useMutation,r$=C.lockControl.unlock.useMutation,n$=C.lockControl.open.useMutation,i$=C.lockControl.getStatus.useQuery,s$=C.mediaPlayer.play.useMutation,a$=C.mediaPlayer.pause.useMutation,o$=C.mediaPlayer.stop.useMutation,l$=C.mediaPlayer.next.useMutation,c$=C.mediaPlayer.previous.useMutation,u$=C.mediaPlayer.seek.useMutation,d$=C.mediaPlayer.setVolume.useMutation,f$=C.mediaPlayer.setMute.useMutation,h$=C.mediaPlayer.setShuffle.useMutation,m$=C.mediaPlayer.setRepeat.useMutation,g$=C.mediaPlayer.selectSource.useMutation,p$=C.mediaPlayer.playMedia.useMutation,v$=C.mediaPlayer.getStatus.useQuery,b$=C.meshNetwork.getStatus.useQuery,y$=C.meshNetwork.join.useMutation,x$=C.meshNetwork.startLogin.useMutation,S$=C.meshNetwork.leave.useMutation,_$=C.meshNetwork.logout.useMutation,w$=C.meshNetwork.listPeers.useQuery,E$=C.meshNetwork.testConnection.useMutation,k$=C.metricsProvider.collectSnapshot.useQuery,T$=C.metricsProvider.getCached.useQuery,C$=C.metricsProvider.getCurrent.useQuery,I$=C.metricsProvider.getDiskSpace.useQuery,P$=C.metricsProvider.getGpuInfo.useQuery,A$=C.metricsProvider.getCpuTemperature.useQuery,j$=C.metricsProvider.getProcessStats.useQuery,N$=C.metricsProvider.listAddonInstances.useQuery,D$=C.metricsProvider.getAddonStats.useQuery,M$=C.metricsProvider.listNodeProcesses.useQuery,$$=C.metricsProvider.killProcess.useMutation,R$=C.motion.isDetected.useQuery,L$=C.motion.getStatus.useQuery,O$=C.motionDetection.analyze.useMutation,F$=C.motionDetection.removeCamera.useMutation,U$=C.motionDetection.reset.useMutation,B$=C.motionDetection.getDeviceSettingsContribution.useQuery,z$=C.motionDetection.getDeviceLiveContribution.useQuery,G$=C.motionDetection.applyDeviceSettingsPatch.useMutation,Z$=C.motionTrigger.setMotionTrigger.useMutation,V$=C.motionTrigger.getStatus.useQuery,H$=C.motionZones.getOptions.useQuery,K$=C.motionZones.setZone.useMutation,W$=C.motionZones.getStatus.useQuery,q$=C.mqttBroker.listBrokers.useQuery,Q$=C.mqttBroker.getBrokerConfig.useQuery,Y$=C.mqttBroker.addBroker.useMutation,X$=C.mqttBroker.removeBroker.useMutation,J$=C.mqttBroker.testConnection.useMutation,eR=C.mqttBroker.startEmbeddedBroker.useMutation,tR=C.mqttBroker.stopEmbeddedBroker.useMutation,rR=C.mqttBroker.getStatus.useQuery,nR=C.nativeObjectDetection.setEnabled.useMutation,iR=C.nativeObjectDetection.getStatus.useQuery,sR=C.networkAccess.start.useMutation,aR=C.networkAccess.stop.useMutation,oR=C.networkAccess.getEndpoint.useQuery,lR=C.networkAccess.getStatus.useQuery,cR=C.networkAccess.listEndpoints.useQuery,uR=C.networkQuality.getDeviceStats.useQuery,dR=C.networkQuality.getAllStats.useQuery,fR=C.networkQuality.reportClientStats.useMutation,hR=C.nodes.topology.useQuery,mR=C.nodes.deployAddon.useMutation,gR=C.nodes.undeployAddon.useMutation,pR=C.nodes.restartAddon.useMutation,vR=C.nodes.restartProcess.useMutation,bR=C.nodes.restartNode.useMutation,yR=C.nodes.shutdownNode.useMutation,xR=C.nodes.renameNode.useMutation,SR=C.nodes.clusterAddonStatus.useQuery,_R=C.nodes.getCapUsageGraph.useQuery,wR=C.nodes.getNodeAddons.useQuery,ER=C.nodes.setProcessLogLevel.useMutation,kR=C.nodes.executeQuery.useMutation,TR=C.notificationOutput.send.useMutation,CR=C.notificationOutput.sendTest.useMutation,IR=C.notifier.send.useMutation,PR=C.notifier.cancel.useMutation,AR=C.notifier.getStatus.useQuery,jR=C.numericSensor.getStatus.useQuery,NR=C.osd.setOverlay.useMutation,DR=C.osd.getStatus.useQuery,MR=C.pipelineAnalytics.getActiveTracks.useQuery,$R=C.pipelineAnalytics.getTrack.useQuery,RR=C.pipelineAnalytics.listTracks.useQuery,LR=C.pipelineAnalytics.clearTracks.useMutation,v0=C.pipelineAnalytics.getMotionEvents.useQuery,b0=C.pipelineAnalytics.getObjectEvents.useQuery,y0=C.pipelineAnalytics.getAudioEvents.useQuery,x0=C.pipelineAnalytics.getEventDensity.useQuery,OR=C.pipelineAnalytics.pruneEventsBefore.useMutation,FR=C.pipelineAnalytics.getEventMedia.useQuery,UR=C.pipelineAnalytics.getTrackMedia.useQuery,BR=C.pipelineAnalytics.getDeviceSettingsContribution.useQuery,zR=C.pipelineAnalytics.getDeviceLiveContribution.useQuery,GR=C.pipelineAnalytics.applyDeviceSettingsPatch.useMutation,ZR=C.pipelineExecutor.getAvailableEngines.useQuery,VR=C.pipelineExecutor.getSelectedEngine.useQuery,HR=C.pipelineExecutor.getDefaultSteps.useQuery,KR=C.pipelineExecutor.reprobeEngine.useMutation,WR=C.pipelineExecutor.getVideoPipelineSteps.useQuery,qR=C.pipelineExecutor.setVideoPipelineSteps.useMutation,QR=C.pipelineExecutor.getSchema.useQuery,YR=C.pipelineExecutor.getGlobalSteps.useQuery,XR=C.pipelineExecutor.getGlobalPipelineConfig.useQuery,JR=C.pipelineExecutor.getOrchestratorConfigSchema.useQuery,eL=C.pipelineExecutor.listTemplates.useQuery,tL=C.pipelineExecutor.saveTemplate.useMutation,rL=C.pipelineExecutor.updateTemplate.useMutation,nL=C.pipelineExecutor.deleteTemplate.useMutation,iL=C.pipelineExecutor.getCapabilities.useQuery,sL=C.pipelineExecutor.getAddonModels.useQuery,aL=C.pipelineExecutor.downloadModel.useMutation,oL=C.pipelineExecutor.deleteModel.useMutation,lL=C.pipelineExecutor.detect.useQuery,cL=C.pipelineExecutor.runPipeline.useMutation,uL=C.pipelineExecutor.runPipelineBatch.useMutation,dL=C.pipelineExecutor.cacheFrameInPool.useMutation,fL=C.pipelineExecutor.inferCached.useMutation,hL=C.pipelineExecutor.uncacheFrame.useMutation,mL=C.pipelineExecutor.getEffectiveTuning.useQuery,gL=C.pipelineExecutor.listLoadedEngines.useQuery,pL=C.pipelineExecutor.spinEngine.useMutation,vL=C.pipelineExecutor.killEngine.useMutation,bL=C.pipelineExecutor.listReferenceImages.useQuery,yL=C.pipelineExecutor.getReferenceImage.useQuery,xL=C.pipelineExecutor.getReferenceAudioFiles.useQuery,SL=C.pipelineExecutor.getReferenceAudio.useQuery,_L=C.pipelineExecutor.getAudioCapabilities.useQuery,wL=C.pipelineExecutor.runAudioTest.useMutation,EL=C.pipelineExecutor.getDetectionConfigSchema.useQuery,kL=C.pipelineOrchestrator.assignPipeline.useMutation,TL=C.pipelineOrchestrator.unassignPipeline.useMutation,CL=C.pipelineOrchestrator.rebalance.useMutation,IL=C.pipelineOrchestrator.getPipelineAssignments.useQuery,PL=C.pipelineOrchestrator.getPipelineAssignment.useQuery,AL=C.pipelineOrchestrator.getAgentLoad.useQuery,jL=C.pipelineOrchestrator.getGlobalMetrics.useQuery,NL=C.pipelineOrchestrator.getCameraMetrics.useQuery,DL=C.pipelineOrchestrator.getCapabilityBindings.useQuery,ML=C.pipelineOrchestrator.setCapabilityBinding.useMutation,$L=C.pipelineOrchestrator.assignDecoder.useMutation,RL=C.pipelineOrchestrator.unassignDecoder.useMutation,LL=C.pipelineOrchestrator.getDecoderAssignments.useQuery,OL=C.pipelineOrchestrator.assignAudio.useMutation,FL=C.pipelineOrchestrator.unassignAudio.useMutation,UL=C.pipelineOrchestrator.getAudioAssignment.useQuery,BL=C.pipelineOrchestrator.getAudioNodeLoad.useQuery,zL=C.pipelineOrchestrator.getAudioAssignments.useQuery,GL=C.pipelineOrchestrator.getDecoderAssignment.useQuery,ZL=C.pipelineOrchestrator.getAgentSettings.useQuery,VL=C.pipelineOrchestrator.listAgentSettings.useQuery,HL=C.pipelineOrchestrator.setAgentAddonDefaults.useMutation,KL=C.pipelineOrchestrator.removeAgentSettings.useMutation,WL=C.pipelineOrchestrator.getCameraSettings.useQuery,qL=C.pipelineOrchestrator.setCameraStepToggle.useMutation,QL=C.pipelineOrchestrator.getCameraStepOverrides.useQuery,YL=C.pipelineOrchestrator.setCameraStepOverride.useMutation,XL=C.pipelineOrchestrator.setCameraPipelineForAgent.useMutation,JL=C.pipelineOrchestrator.resolvePipeline.useQuery,e2=C.pipelineOrchestrator.listTemplates.useQuery,t2=C.pipelineOrchestrator.saveTemplate.useMutation,r2=C.pipelineOrchestrator.updateTemplate.useMutation,n2=C.pipelineOrchestrator.deleteTemplate.useMutation,i2=C.pipelineOrchestrator.getDeviceSettingsContribution.useQuery,s2=C.pipelineOrchestrator.getDeviceLiveContribution.useQuery,a2=C.pipelineOrchestrator.applyDeviceSettingsPatch.useMutation,o2=C.pipelineRunner.attachCamera.useMutation,l2=C.pipelineRunner.detachCamera.useMutation,c2=C.pipelineRunner.reportMotion.useMutation,u2=C.pipelineRunner.getLocalLoad.useQuery,d2=C.pipelineRunner.getLocalMetrics.useQuery,f2=C.pipelineRunner.getCameraMetrics.useQuery,h2=C.pipelineRunner.getAllCameraMetrics.useQuery,m2=C.pipelineRunner.getLocalCameras.useQuery,g2=C.powerMeter.getStatus.useQuery,p2=C.presence.getStatus.useQuery,v2=C.pressureSensor.getStatus.useQuery,b2=C.privacyMask.getOptions.useQuery,y2=C.privacyMask.setMask.useMutation,x2=C.privacyMask.getStatus.useQuery,S2=C.ptz.move.useMutation,_2=C.ptz.continuousMove.useMutation,w2=C.ptz.stop.useMutation,E2=C.ptz.getPresets.useQuery,k2=C.ptz.goToPreset.useMutation,T2=C.ptz.savePreset.useMutation,C2=C.ptz.deletePreset.useMutation,I2=C.ptz.getOptions.useQuery,P2=C.ptz.goHome.useMutation,A2=C.ptz.getPosition.useQuery,j2=C.ptz.setAutofocus.useMutation,N2=C.ptz.getStatus.useQuery,S0=C.ptzAutotrack.getStatus.useQuery,_0=C.ptzAutotrack.setEnabled.useMutation,D2=C.ptzAutotrack.getSettings.useQuery,w0=C.ptzAutotrack.setSettings.useMutation,M2=C.reboot.reboot.useMutation,Pf=C.recording.getAvailability.useQuery,$2=C.recording.getPlaybackManifest.useQuery,R2=C.recording.getStorageUsage.useQuery,E0=C.recording.getDeviceConfig.useQuery,k0=C.recording.setDeviceConfig.useMutation,T0=C.recording.rescanStorage.useMutation,L2=C.recording.pruneFootage.useMutation,C0=C.recording.getStatus.useQuery,O2=C.recording.getDeviceSettingsContribution.useQuery,F2=C.recording.getDeviceLiveContribution.useQuery,U2=C.recording.applyDeviceSettingsPatch.useMutation,B2=C.scriptRunner.run.useMutation,z2=C.scriptRunner.stop.useMutation,G2=C.scriptRunner.getStatus.useQuery,Z2=C.settingsStore.get.useQuery,V2=C.settingsStore.set.useMutation,H2=C.settingsStore.query.useQuery,K2=C.settingsStore.insert.useMutation,W2=C.settingsStore.update.useMutation,q2=C.settingsStore.delete.useMutation,Q2=C.settingsStore.count.useQuery,Y2=C.settingsStore.histogram.useQuery,X2=C.settingsStore.isEmpty.useQuery,J2=C.settingsStore.declareCollection.useMutation,eO=C.smoke.getStatus.useQuery,tO=C.snapshot.getSnapshot.useQuery,rO=C.snapshot.invalidateCache.useMutation,nO=C.snapshot.getStatus.useQuery,iO=C.snapshot.getDeviceSettingsContribution.useQuery,sO=C.snapshot.getDeviceLiveContribution.useQuery,aO=C.snapshot.applyDeviceSettingsPatch.useMutation,oO=C.snapshotProvider.supportsDevice.useQuery,lO=C.snapshotProvider.getSnapshot.useQuery,cO=C.storage.resolve.useQuery,uO=C.storage.write.useMutation,dO=C.storage.read.useQuery,fO=C.storage.exists.useQuery,hO=C.storage.list.useQuery,mO=C.storage.delete.useMutation,gO=C.storage.getAvailableSpace.useQuery,pO=C.storage.beginUpload.useMutation,vO=C.storage.writeChunk.useMutation,bO=C.storage.finalizeUpload.useMutation,yO=C.storage.abortUpload.useMutation,xO=C.storage.beginDownload.useMutation,SO=C.storage.readChunk.useQuery,_O=C.storage.endDownload.useMutation,wO=C.storage.listLocations.useQuery,EO=C.storage.getDefaultLocation.useQuery,kO=C.storage.listLocationDeclarations.useQuery,TO=C.storage.upsertLocation.useMutation,CO=C.storage.deleteLocation.useMutation,IO=C.storage.testLocation.useQuery,PO=C.storage.listProviders.useQuery,AO=C.storage.testConfig.useQuery,jO=C.streamBroker.publishCameraStream.useMutation,NO=C.streamBroker.retractCameraStream.useMutation,DO=C.streamBroker.assignProfile.useMutation,MO=C.streamBroker.unassignProfile.useMutation,$O=C.streamBroker.listAllCameraStreams.useQuery,RO=C.streamBroker.listAllProfileSlots.useQuery,LO=C.streamBroker.getBrokerStats.useQuery,OO=C.streamBroker.listClients.useQuery,FO=C.streamBroker.killClient.useMutation,UO=C.streamBroker.restartProfile.useMutation,BO=C.streamBroker.getStreamUrl.useQuery,zO=C.streamBroker.getStreamWithCodec.useMutation,GO=C.streamBroker.releaseStreamWithCodec.useMutation,ZO=C.streamBroker.subscribeAudioChunks.useMutation,VO=C.streamBroker.pullAudioChunks.useQuery,HO=C.streamBroker.unsubscribeAudioChunks.useMutation,KO=C.streamBroker.subscribeFrames.useMutation,WO=C.streamBroker.pullFrameHandles.useQuery,qO=C.streamBroker.unsubscribeFrames.useMutation,QO=C.streamBroker.setPreBufferDuration.useMutation,YO=C.streamBroker.getPreBufferInfo.useQuery,XO=C.streamBroker.getRtspPort.useQuery,JO=C.streamBroker.getAllRtspEntries.useQuery,e4=C.streamBroker.getRtspEntry.useQuery,t4=C.streamBroker.regenerateRtspToken.useMutation,r4=C.streamBroker.setRtspEnabled.useMutation,n4=C.streamBroker.isRtspEnabled.useQuery,i4=C.streamBroker.getDeviceSettingsContribution.useQuery,s4=C.streamBroker.getDeviceLiveContribution.useQuery,a4=C.streamBroker.applyDeviceSettingsPatch.useMutation,o4=C.streamCatalog.getCatalog.useQuery,l4=C.streamParams.getOptions.useQuery,c4=C.streamParams.setProfile.useMutation,u4=C.streamParams.getConfigSchema.useQuery,d4=C.streamParams.getStatus.useQuery,f4=C.switch.setState.useMutation,h4=C.switch.getStatus.useQuery,m4=C.system.info.useQuery,g4=C.system.health.useQuery,p4=C.system.featureFlags.useQuery,v4=C.system.networkAddresses.useQuery,b4=C.system.getRetentionConfig.useQuery,y4=C.system.setRetentionConfig.useMutation,x4=C.system.forceRetentionCleanup.useMutation,S4=C.tamper.getStatus.useQuery,_4=C.temperatureSensor.getStatus.useQuery,w4=C.toast.onToast.useSubscription,E4=C.turnProvider.getTurnServers.useQuery,k4=C.update.installUpdate.useMutation,T4=C.update.getStatus.useQuery,C4=C.userManagement.listUsers.useQuery,I4=C.userManagement.createUser.useMutation,P4=C.userManagement.updateUser.useMutation,A4=C.userManagement.deleteUser.useMutation,j4=C.userManagement.resetPassword.useMutation,N4=C.userManagement.setUserScopes.useMutation,D4=C.userManagement.validateCredentials.useMutation,M4=C.userManagement.listApiKeys.useQuery,$4=C.userManagement.createApiKey.useMutation,R4=C.userManagement.revokeApiKey.useMutation,L4=C.userManagement.validateApiKey.useMutation,O4=C.userManagement.createScopedToken.useMutation,F4=C.userManagement.revokeScopedToken.useMutation,U4=C.userManagement.validateScopedToken.useQuery,B4=C.userManagement.listScopedTokens.useQuery,z4=C.userManagement.setupTotp.useMutation,G4=C.userManagement.confirmTotp.useMutation,Z4=C.userManagement.disableTotp.useMutation,V4=C.userManagement.getTotpStatus.useQuery,H4=C.userManagement.verifyTotp.useMutation,K4=C.userManagement.oauthIssueCode.useMutation,W4=C.userManagement.oauthExchangeCode.useMutation,q4=C.userManagement.oauthRefresh.useMutation,Q4=C.userManagement.oauthVerifyAccessToken.useQuery,Y4=C.userManagement.listOauthSessions.useQuery,X4=C.userManagement.revokeOauthSession.useMutation,J4=C.vacuumControl.start.useMutation,e5=C.vacuumControl.pause.useMutation,t5=C.vacuumControl.stop.useMutation,r5=C.vacuumControl.returnToBase.useMutation,n5=C.vacuumControl.locate.useMutation,i5=C.vacuumControl.setFanSpeed.useMutation,s5=C.vacuumControl.getStatus.useQuery,a5=C.valve.open.useMutation,o5=C.valve.close.useMutation,l5=C.valve.stop.useMutation,c5=C.valve.setPosition.useMutation,u5=C.valve.getStatus.useQuery,d5=C.vibration.getStatus.useQuery,f5=C.waterHeater.setTargetTemp.useMutation,h5=C.waterHeater.setOperationMode.useMutation,m5=C.waterHeater.setAway.useMutation,g5=C.waterHeater.getStatus.useQuery,p5=C.weather.getStatus.useQuery,v5=C.webrtcSession.listStreams.useQuery,b5=C.webrtcSession.createSession.useMutation,y5=C.webrtcSession.handleOffer.useMutation,x5=C.webrtcSession.handleAnswer.useMutation,S5=C.webrtcSession.addIceCandidate.useMutation,_5=C.webrtcSession.getIceCandidates.useQuery,w5=C.webrtcSession.closeSession.useMutation,E5=C.webrtcSession.hasAdaptiveBitrate.useQuery,k5=C.webrtcSession.getSessionState.useQuery,T5=C.zoneAnalytics.getCurrentSnapshot.useQuery,C5=C.zoneAnalytics.getZoneHistory.useQuery,I5=C.zoneAnalytics.getCameraHistory.useQuery,P5=C.zoneAnalytics.getUnzonedHistory.useQuery,A5=C.zoneRules.listRules.useQuery,j5=C.zoneRules.setRules.useMutation,N5=C.zones.listZones.useQuery,D5=C.zones.addZone.useMutation,M5=C.zones.removeZone.useMutation,$5=C.zones.updateZone.useMutation;function uo(e,t){return t!==void 0?e.toFixed(t):Number.isInteger(e)?String(e):e.toFixed(1)}var I0={kind:"binary",field:"on",onLabel:"Low",offLabel:"Normal"};function P0(e){return e==="battery-sensor"}function A0(e,t){if(!j0(e))return!1;const r=e[t];if(typeof r!="number")return!1;const n=e.lastFetchedAt;return!(r===0&&n===0)}var Af={"temperature-sensor":{kind:"numeric",field:"celsius",canonicalUnit:"°C",getSliceHandle:e=>e.temperatureSensor},"humidity-sensor":{kind:"numeric",field:"percent",canonicalUnit:"%",getSliceHandle:e=>e.humiditySensor},"ambient-light-sensor":{kind:"numeric",field:"lux",canonicalUnit:"lx",getSliceHandle:e=>e.ambientLightSensor},"pressure-sensor":{kind:"numeric",field:"hpa",canonicalUnit:"hPa",getSliceHandle:e=>e.pressureSensor},"numeric-sensor":{kind:"numeric",field:"value",getSliceHandle:e=>e.numericSensor},"power-sensor":{kind:"numeric",field:"watts",canonicalUnit:"W",getSliceHandle:e=>e.powerMeter},"energy-sensor":{kind:"numeric",field:"kwhTotal",canonicalUnit:"kWh",getSliceHandle:e=>e.powerMeter},"voltage-sensor":{kind:"numeric",field:"volts",canonicalUnit:"V",getSliceHandle:e=>e.powerMeter},"current-sensor":{kind:"numeric",field:"amps",canonicalUnit:"A",getSliceHandle:e=>e.powerMeter},"battery-sensor":{kind:"numeric",field:"value",canonicalUnit:"%",getSliceHandle:e=>e.numericSensor},"generic-sensor":{kind:"numeric",field:"value",getSliceHandle:e=>e.numericSensor},"motion-sensor":{kind:"binary",field:"detected",onLabel:"Detected",offLabel:"Clear",getSliceHandle:e=>e.motion},"pir-sensor":{kind:"binary",field:"detected",onLabel:"Detected",offLabel:"Clear",getSliceHandle:e=>e.motion},"contact-sensor":{kind:"binary",field:"entryOpen",onLabel:"Open",offLabel:"Closed",getSliceHandle:e=>e.contact},"smoke-sensor":{kind:"binary",field:"detected",onLabel:"Smoke!",offLabel:"Clear",getSliceHandle:e=>e.smoke},"leak-sensor":{kind:"binary",field:"flooded",onLabel:"Leak!",offLabel:"Dry",getSliceHandle:e=>e.flood},"co-sensor":{kind:"binary",field:"detected",onLabel:"CO!",offLabel:"Clear",getSliceHandle:e=>e.carbonMonoxide},"binary-sensor":{kind:"binary",field:"on",onLabel:"On",offLabel:"Off",getSliceHandle:e=>e.binary},presence:{kind:"presence",getSliceHandle:e=>e.presence},"enum-sensor":{kind:"string",getSliceHandle:e=>e.enumSensor},"datetime-sensor":{kind:"datetime",format:"datetime",getSliceHandle:e=>e.enumSensor}};function j0(e){return typeof e=="object"&&e!==null}function R5(e){return typeof e=="object"&&e!==null}function L5(e){return typeof e=="object"&&e!==null&&"state"in e&&typeof e.state=="string"}function fo(e){return typeof e=="object"&&e!==null&&"value"in e&&typeof e.value=="string"}function N0(e){if(typeof e!="object"||e===null)return;const t=e.format;if(t==="date"||t==="time"||t==="datetime")return t}function O5(e){return e==="home"?"Home":e==="not_home"?"Away":e.charAt(0).toUpperCase()+e.slice(1)}function Rl({trpc:e,device:t}){const r=t.role!=null?Af[t.role]:void 0,n=P0(t.role),s=Br(e,t.id),a=En(s!==null&&r!==void 0?r.getSliceHandle(s.state):void 0),c=En(s!==null&&r?.kind==="numeric"?s.state.enumSensor:void 0),d=En(s!==null&&n?s.state.binary:void 0),u=n&&r?.kind==="numeric"&&!A0(a,r.field)&&d!==void 0,f=u?I0:r,h=u?d:a;if(f===void 0||h===void 0)return null;if(f.kind==="numeric"){if(!j0(h))return null;const g=h[f.field];if(typeof g!="number")return null;const p=h.lastFetchedAt,y=g===0&&p===0;if(y&&fo(c)&&c.value!=="")return(0,i.jsx)("span",{className:A("inline-flex items-baseline text-xs text-foreground"),children:c.value});if(y)return null;const S=h,E=(typeof S.unit=="string"?S.unit:void 0)??f.canonicalUnit??"",T=uo(g,typeof S.precision=="number"?S.precision:void 0);return(0,i.jsxs)("span",{className:A("inline-flex items-baseline gap-0.5 tabular-nums text-xs text-foreground"),children:[(0,i.jsx)("span",{children:T}),E&&(0,i.jsx)("span",{className:"text-foreground-subtle",children:E})]})}if(f.kind==="binary"){if(!R5(h))return null;const p=!!h[f.field],y=p?f.onLabel:f.offLabel;return(0,i.jsx)("span",{className:A("inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium",p?"bg-warning/15 text-warning":"bg-surface-subtle text-foreground-subtle"),children:y})}if(f.kind==="string")return!fo(h)||h.value===""?null:(0,i.jsx)("span",{className:A("inline-flex items-baseline text-xs text-foreground"),children:h.value});if(f.kind==="datetime"){if(!fo(h)||h.value==="")return null;const g=N0(h)??f.format,p=il(h.value,g);return(0,i.jsx)("span",{className:A("inline-flex items-baseline text-xs text-foreground"),children:p})}if(!L5(h))return null;const m=O5(h.state);return(0,i.jsx)("span",{className:A("inline-flex items-center rounded px-1.5 py-0.5 text-xs font-medium",h.state==="home"?"bg-success/15 text-success":"bg-surface-subtle text-foreground-subtle"),children:m})}function F5(e){return{id:e.id,stableId:e.stableId,addonId:e.addonId,type:e.type,name:e.name,online:e.online,disabled:e.disabled,parentDeviceId:e.parentDeviceId,role:e.role??void 0,features:e.features}}function D0({trpc:e,deviceId:t}){const{data:r}=If({deviceId:t},{staleTime:6e4});return r===void 0?null:(0,i.jsx)(Rl,{trpc:e,device:F5(r)})}function U5(e){return typeof e=="object"&&e!==null}function B5(e){return typeof e=="object"&&e!==null}function z5(e){return typeof e=="object"&&e!==null&&"state"in e&&typeof e.state=="string"}function G5(e){return e==="home"?"Home":e==="not_home"?"Away":e.charAt(0).toUpperCase()+e.slice(1)}var Z5={low:"bg-danger",medium:"bg-warning",high:"bg-success"};function V5(e){return e<=20?"low":e<=50?"medium":"high"}function H5({percent:e}){const t=Math.min(100,Math.max(0,e)),r=V5(t);return(0,i.jsx)("div",{"data-testid":"battery-bar","data-band":r,className:"h-2 w-24 overflow-hidden rounded-full bg-border",children:(0,i.jsx)("div",{className:A("h-full rounded-full transition-all",Z5[r]),style:{width:`${t}%`}})})}function K5({trpc:e,device:t}){const r=t.role!=null?Af[t.role]:void 0,n=P0(t.role),s=Br(e,t.id),a=En(s!==null&&r!==void 0?r.getSliceHandle(s.state):void 0),c=En(s!==null&&n?s.state.binary:void 0),d=n&&r?.kind==="numeric"&&!A0(a,r.field)&&c!==void 0,u=d?I0:r,f=d?c:a;if(u===void 0||f===void 0)return(0,i.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4 min-h-[96px]",children:[(0,i.jsx)("span",{className:"text-sm text-foreground-subtle",children:t.name}),(0,i.jsx)("span",{className:"text-xs text-foreground-subtle italic",children:"Awaiting state…"})]});if(u.kind==="numeric"){if(!U5(f))return null;const m=f[u.field];if(typeof m!="number")return null;const g=f,p=(typeof g.unit=="string"?g.unit:void 0)??u.canonicalUnit??"";return(0,i.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsxs)("div",{className:"flex items-baseline gap-1",children:[(0,i.jsx)("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:uo(m,typeof g.precision=="number"?g.precision:void 0)}),p&&(0,i.jsx)("span",{className:"text-base text-foreground-subtle",children:p})]}),n&&(0,i.jsx)(H5,{percent:m}),(0,i.jsx)("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}if(u.kind==="binary"){if(!B5(f))return null;const g=!!f[u.field],p=g?u.onLabel:u.offLabel;return(0,i.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsx)("span",{className:A("inline-flex items-center rounded px-3 py-1.5 text-lg font-semibold",g?"bg-warning/15 text-warning":"bg-surface-subtle text-foreground-subtle"),children:p}),(0,i.jsx)("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}if(u.kind==="datetime"){if(!fo(f))return null;if(f.value==="")return(0,i.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4 min-h-[96px]",children:[(0,i.jsx)("span",{className:"text-sm text-foreground-subtle",children:t.name}),(0,i.jsx)("span",{className:"text-xs text-foreground-subtle italic",children:"Awaiting state…"})]});const m=N0(f)??u.format;return(0,i.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsx)("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:il(f.value,m)}),(0,i.jsx)("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}if(u.kind==="string")return!fo(f)||f.value===""?null:(0,i.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsx)("span",{className:"text-xl font-semibold text-foreground",children:f.value}),(0,i.jsx)("span",{className:"text-sm text-foreground-subtle",children:t.name})]});if(!z5(f))return null;const h=G5(f.state);return(0,i.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsx)("span",{className:A("inline-flex items-center rounded px-3 py-1.5 text-lg font-semibold",f.state==="home"?"bg-success/15 text-success":"bg-surface-subtle text-foreground-subtle"),children:h}),(0,i.jsx)("span",{className:"text-sm text-foreground-subtle",children:t.name})]})}function M0({trpc:e,deviceId:t}){const{data:r}=If({deviceId:t},{staleTime:6e4});return r===void 0?null:(0,i.jsx)(K5,{trpc:e,device:r})}function $0(e){return e===void 0||e.inProgress?!1:e.availableVersion!==null&&e.currentVersion!==null&&e.availableVersion!==e.currentVersion}function R0(e,t){return bt({trpc:e,deviceId:t,cap:r=>r.update,slice:r=>r.state.update})}function W5({trpc:e,deviceId:t}){const{cap:r,slice:n}=R0(e,t);return r===void 0?null:n?.inProgress?(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 text-xs text-foreground-subtle",children:[(0,i.jsx)(hr,{className:"h-3.5 w-3.5 animate-spin"}),"Updating…"]}):$0(n)?(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 rounded bg-warning/15 px-1.5 py-0.5 text-[10px] font-medium text-warning",children:[(0,i.jsx)(Xa,{className:"h-3 w-3"}),"Update"]}):(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 text-[10px] text-foreground-subtle",children:[(0,i.jsx)(On,{className:"h-3 w-3 text-success"}),n?.currentVersion??"Up to date"]})}function q5({trpc:e,deviceId:t}){const{cap:r,slice:n,available:s}=R0(e,t);if(r===void 0)return null;const a=n?.inProgress===!0,c=$0(n),d=n?.currentVersion??"—",u=()=>{!s||r===void 0||!c||r.installUpdate({})};return(0,i.jsxs)("div",{className:"flex flex-col items-center justify-center gap-2 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsxs)("div",{className:"flex items-baseline gap-1.5",children:[(0,i.jsx)("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:d}),c&&n?.availableVersion!=null&&(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("span",{className:"text-base text-foreground-subtle",children:"→"}),(0,i.jsx)("span",{className:"text-base font-medium text-warning tabular-nums",children:n.availableVersion})]})]}),a?(0,i.jsxs)("span",{className:"inline-flex items-center gap-1.5 rounded px-3 py-1.5 text-sm font-medium text-foreground-subtle",children:[(0,i.jsx)(hr,{className:"h-4 w-4 animate-spin"}),"Installing…"]}):c?(0,i.jsxs)("button",{type:"button",onClick:f=>{f.stopPropagation(),u()},disabled:!s,className:"inline-flex items-center gap-1.5 rounded-lg bg-primary px-4 py-1.5 text-sm font-medium text-primary-foreground shadow-sm transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[(0,i.jsx)(Xa,{className:"h-4 w-4"}),"Install update"]}):(0,i.jsxs)("span",{className:"inline-flex items-center gap-1.5 rounded bg-success/15 px-3 py-1 text-sm font-medium text-success",children:[(0,i.jsx)(On,{className:"h-4 w-4"}),"Up to date"]}),n?.state!=null&&n.state!==""&&(0,i.jsx)("span",{className:"text-[10px] text-foreground-subtle",children:n.state})]})}function L0(e){switch(e){case"cleaning":return{label:"Cleaning",tone:"text-primary"};case"paused":return{label:"Paused",tone:"text-warning"};case"returning":return{label:"Returning",tone:"text-primary"};case"docked":return{label:"Docked",tone:"text-success"};case"idle":return{label:"Idle",tone:"text-foreground-subtle"};case"error":return{label:"Error",tone:"text-destructive"};case void 0:return{label:"Unknown",tone:"text-foreground-subtle"}}}function O0(e,t){return bt({trpc:e,deviceId:t,cap:r=>r.vacuumControl,slice:r=>r.state.vacuumControl})}function jf({label:e,busy:t,active:r,onClick:n,children:s}){return(0,i.jsx)("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:a=>{a.stopPropagation(),n()},className:A("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",r&&"bg-primary text-primary-foreground",t&&"opacity-40 cursor-not-allowed"),children:s})}function Q5(e){switch(e){case"cleaning":return{glow:"bg-primary/15",accent:"text-primary",docked:!1,active:!0};case"returning":return{glow:"bg-primary/10",accent:"text-primary",docked:!1,active:!0};case"docked":return{glow:"bg-success/10",accent:"text-success",docked:!0,active:!1};case"paused":return{glow:"bg-warning/10",accent:"text-warning",docked:!1,active:!1};case"error":return{glow:"bg-destructive/10",accent:"text-destructive",docked:!1,active:!1};case"idle":return{glow:"bg-transparent",accent:"text-foreground-subtle",docked:!1,active:!1};case void 0:return{glow:"bg-transparent",accent:"text-foreground-subtle",docked:!1,active:!1}}}function Y5({state:e}){const t=Q5(e);return(0,i.jsxs)("div",{"aria-hidden":"true",className:"relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0",style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.06)"},children:[(0,i.jsx)("div",{className:A("absolute inset-0 transition-colors duration-300",t.glow)}),(0,i.jsx)("div",{className:A("absolute inset-0 flex items-center justify-center",t.accent),children:(0,i.jsxs)("svg",{viewBox:"0 0 100 100",className:"w-20 h-20",fill:"none",children:[t.docked&&(0,i.jsx)("rect",{x:"34",y:"80",width:"32",height:"8",rx:"2",fill:"currentColor",opacity:"0.35"}),t.active&&(0,i.jsx)("circle",{cx:"50",cy:"50",r:"44",stroke:"currentColor",strokeWidth:"2",opacity:"0.4",className:"animate-ping",style:{transformOrigin:"center"}}),(0,i.jsx)("circle",{cx:"50",cy:"50",r:"34",fill:"currentColor",fillOpacity:"0.12",stroke:"currentColor",strokeWidth:"2.5"}),(0,i.jsx)("path",{d:"M 24 42 A 34 34 0 0 1 76 42",stroke:"currentColor",strokeWidth:"3",opacity:"0.55",strokeLinecap:"round"}),(0,i.jsx)("circle",{cx:"50",cy:"50",r:"9",fill:"currentColor",fillOpacity:"0.25",stroke:"currentColor",strokeWidth:"2"}),(0,i.jsx)("circle",{cx:"50",cy:"50",r:"3",fill:"currentColor"})]})})]})}function F0({level:e}){return(0,i.jsxs)("span",{className:"inline-flex items-center gap-0.5 tabular-nums text-xs text-foreground-subtle",children:[(0,i.jsx)(Od,{className:"h-3.5 w-3.5"}),e,"%"]})}function X5(e){switch(e){case"cleanWater":return!0;case"detergent":return!0;case"dirtyWater":return!1;case"dustBin":return!1;default:return e}}function U0(e,t){const r=X5(e);return t.level!==null?r?t.level<=15?"warning":"ok":t.level>=85?"warning":"ok":t.status!==null?r?t.status==="low"?"warning":"ok":t.status==="full"?"warning":"ok":"ok"}function J5(e){switch(e){case"cleanWater":return{label:"Clean water",icon:(0,i.jsx)(Cp,{className:"h-3.5 w-3.5"})};case"dirtyWater":return{label:"Dirty water",icon:(0,i.jsx)(zd,{className:"h-3.5 w-3.5"})};case"detergent":return{label:"Detergent",icon:(0,i.jsx)(KT,{className:"h-3.5 w-3.5"})};case"dustBin":return{label:"Dust bin",icon:(0,i.jsx)(en,{className:"h-3.5 w-3.5"})};default:return e}}function e3({kind:e,tank:t}){if(t===null)return null;const r=J5(e),n=U0(e,t)==="warning";return t.level!==null?(0,i.jsxs)("div",{className:"flex items-center gap-2 text-xs",children:[(0,i.jsxs)("span",{className:A("inline-flex items-center gap-1 w-24 shrink-0",n?"text-warning":"text-foreground-subtle"),children:[r.icon,r.label]}),(0,i.jsx)("span",{className:"relative h-1.5 flex-1 overflow-hidden rounded-full bg-surface-hover",children:(0,i.jsx)("span",{className:A("absolute inset-y-0 left-0 rounded-full transition-all",n?"bg-warning":"bg-primary"),style:{width:`${t.level}%`}})}),(0,i.jsxs)("span",{className:A("tabular-nums w-9 text-right",n?"text-warning":"text-foreground-subtle"),children:[t.level,"%"]})]}):t.status!==null?(0,i.jsxs)("div",{className:"flex items-center gap-2 text-xs",children:[(0,i.jsxs)("span",{className:A("inline-flex items-center gap-1 w-24 shrink-0",n?"text-warning":"text-foreground-subtle"),children:[r.icon,r.label]}),(0,i.jsx)("span",{className:A("inline-flex items-center rounded-full px-2 py-0.5 text-[11px] font-medium",n?"bg-warning/15 text-warning":"bg-primary/15 text-foreground-subtle"),children:t.status})]}):null}function t3({cleanWater:e,dirtyWater:t,detergent:r,dustBin:n}){const s=[["cleanWater",e],["dirtyWater",t],["detergent",r],["dustBin",n]];return s.some(([,a])=>a!==null&&(a.level!==null||a.status!==null))?(0,i.jsx)("div",{className:"grid grid-cols-1 gap-x-6 gap-y-2 rounded-md border border-border bg-surface-hover/40 p-3 sm:grid-cols-2",children:s.map(([a,c])=>(0,i.jsx)(e3,{kind:a,tank:c},a))}):null}function B0({trpc:e,deviceId:t}){const{cap:r,slice:n,available:s}=O0(e,t);if(r===void 0)return null;const a=!s,c=n?.state,d=c==="cleaning",u=f=>{a||f===void 0||f({})};return(0,i.jsxs)("div",{className:"inline-flex items-center gap-1",children:[(0,i.jsx)(jf,{label:"Start",busy:a,active:d,onClick:()=>u(r.start),children:(0,i.jsx)(Fn,{className:"h-3 w-3"})}),(0,i.jsx)(jf,{label:"Pause",busy:a,active:c==="paused",onClick:()=>u(r.pause),children:(0,i.jsx)(to,{className:"h-3 w-3"})}),(0,i.jsx)(jf,{label:"Return to base",busy:a,active:c==="returning",onClick:()=>u(r.returnToBase),children:(0,i.jsx)(os,{className:"h-3.5 w-3.5"})}),n?.batteryLevel!=null&&(0,i.jsx)("span",{className:"ml-1",children:(0,i.jsx)(F0,{level:n.batteryLevel})})]})}function ho({label:e,busy:t,active:r,onClick:n,children:s}){return(0,i.jsx)("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:a=>{a.stopPropagation(),n()},className:A("inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",r&&"bg-primary text-primary-foreground hover:bg-primary/90",t&&"opacity-40 cursor-not-allowed"),children:s})}function z0({trpc:e,deviceId:t}){const{cap:r,slice:n,available:s}=O0(e,t);if(r===void 0)return null;const a=!s,c=n?.state,d=L0(c),u=n?.availableFanSpeeds??[],f=m=>{a||m===void 0||m({})},h=m=>{a||m===""||r.setFanSpeed({speed:m})};return(0,i.jsxs)("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsxs)("div",{className:"flex items-center gap-6",children:[(0,i.jsx)(Y5,{state:c}),(0,i.jsxs)("div",{className:"flex flex-col gap-3 flex-1",children:[(0,i.jsxs)("div",{className:"flex items-center justify-between",children:[(0,i.jsx)("span",{className:A("text-3xl font-semibold",d.tone),children:d.label}),n?.batteryLevel!=null&&(0,i.jsx)(F0,{level:n.batteryLevel})]}),(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsx)(ho,{label:"Start",busy:a,active:c==="cleaning",onClick:()=>f(r.start),children:(0,i.jsx)(Fn,{className:"h-5 w-5"})}),(0,i.jsx)(ho,{label:"Pause",busy:a,active:c==="paused",onClick:()=>f(r.pause),children:(0,i.jsx)(to,{className:"h-5 w-5"})}),(0,i.jsx)(ho,{label:"Stop",busy:a,active:!1,onClick:()=>f(r.stop),children:(0,i.jsx)(Un,{className:"h-4 w-4"})}),(0,i.jsx)(ho,{label:"Return to base",busy:a,active:c==="returning",onClick:()=>f(r.returnToBase),children:(0,i.jsx)(os,{className:"h-5 w-5"})}),(0,i.jsx)(ho,{label:"Locate",busy:a,active:!1,onClick:()=>f(r.locate),children:(0,i.jsx)(lC,{className:"h-5 w-5"})})]})]})]}),u.length>0&&(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{className:"w-16 shrink-0",children:"Fan speed"}),(0,i.jsxs)("select",{"aria-label":"Fan speed",value:n?.fanSpeed??"",disabled:a,onChange:m=>{h(m.target.value)},onClick:m=>{m.stopPropagation()},className:"flex-1 rounded border border-border bg-surface px-2 py-1 text-foreground disabled:opacity-50",children:[n?.fanSpeed==null&&(0,i.jsx)("option",{value:"",children:"—"}),u.map(m=>(0,i.jsx)("option",{value:m,children:m},m))]})]}),(0,i.jsx)(t3,{cleanWater:n?.cleanWater??null,dirtyWater:n?.dirtyWater??null,detergent:n?.detergent??null,dustBin:n?.dustBin??null})]})}function G0(e){switch(e){case"mowing":return{label:"Mowing",tone:"text-primary"};case"paused":return{label:"Paused",tone:"text-warning"};case"docked":return{label:"Docked",tone:"text-success"};case"idle":return{label:"Idle",tone:"text-foreground-subtle"};case"error":return{label:"Error",tone:"text-destructive"};case void 0:return{label:"Unknown",tone:"text-foreground-subtle"}}}function Z0(e,t){return bt({trpc:e,deviceId:t,cap:r=>r.lawnMowerControl,slice:r=>r.state.lawnMowerControl})}function r3(e){switch(e){case"mowing":return{glow:"bg-primary/15",accent:"text-primary",docked:!1,active:!0};case"docked":return{glow:"bg-success/10",accent:"text-success",docked:!0,active:!1};case"paused":return{glow:"bg-warning/10",accent:"text-warning",docked:!1,active:!1};case"error":return{glow:"bg-destructive/10",accent:"text-destructive",docked:!1,active:!1};case"idle":return{glow:"bg-transparent",accent:"text-foreground-subtle",docked:!1,active:!1};case void 0:return{glow:"bg-transparent",accent:"text-foreground-subtle",docked:!1,active:!1}}}function n3({activity:e}){const t=r3(e);return(0,i.jsxs)("div",{"aria-hidden":"true",className:"relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-emerald-700/40 to-emerald-900/30 overflow-hidden flex-shrink-0",style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.06)"},children:[(0,i.jsx)("div",{className:A("absolute inset-0 transition-colors duration-300",t.glow)}),(0,i.jsx)("div",{className:A("absolute inset-0 flex items-center justify-center",t.accent),children:(0,i.jsxs)("svg",{viewBox:"0 0 100 100",className:"w-20 h-20",fill:"none",children:[t.docked&&(0,i.jsx)("rect",{x:"30",y:"78",width:"40",height:"9",rx:"2",fill:"currentColor",opacity:"0.35"}),t.active&&(0,i.jsxs)("g",{stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",opacity:"0.5",children:[(0,i.jsx)("line",{x1:"18",y1:"36",x2:"10",y2:"36",className:"animate-pulse"}),(0,i.jsx)("line",{x1:"18",y1:"50",x2:"6",y2:"50",className:"animate-pulse"}),(0,i.jsx)("line",{x1:"18",y1:"64",x2:"10",y2:"64",className:"animate-pulse"})]}),(0,i.jsx)("rect",{x:"28",y:"34",width:"44",height:"34",rx:"8",fill:"currentColor",fillOpacity:"0.14",stroke:"currentColor",strokeWidth:"2.5"}),(0,i.jsx)("line",{x1:"34",y1:"60",x2:"66",y2:"60",stroke:"currentColor",strokeWidth:"2",opacity:"0.5"}),(0,i.jsx)("circle",{cx:"50",cy:"48",r:"5",stroke:"currentColor",strokeWidth:"2",opacity:"0.6"}),(0,i.jsx)("circle",{cx:"34",cy:"68",r:"6",fill:"currentColor",fillOpacity:"0.3",stroke:"currentColor",strokeWidth:"2"}),(0,i.jsx)("circle",{cx:"66",cy:"68",r:"6",fill:"currentColor",fillOpacity:"0.3",stroke:"currentColor",strokeWidth:"2"})]})})]})}function V0({level:e}){return(0,i.jsxs)("span",{className:"inline-flex items-center gap-0.5 tabular-nums text-xs text-foreground-subtle",children:[(0,i.jsx)(Od,{className:"h-3.5 w-3.5"}),e,"%"]})}function Nf({label:e,busy:t,active:r,onClick:n,children:s}){return(0,i.jsx)("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:a=>{a.stopPropagation(),n()},className:A("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",r&&"bg-primary text-primary-foreground",t&&"opacity-40 cursor-not-allowed"),children:s})}function H0({trpc:e,deviceId:t}){const{cap:r,slice:n,available:s}=Z0(e,t);if(r===void 0)return null;const a=!s,c=n?.activity,d=u=>{a||u===void 0||u({})};return(0,i.jsxs)("div",{className:"inline-flex items-center gap-1",children:[(0,i.jsx)(Nf,{label:"Mow",busy:a,active:c==="mowing",onClick:()=>d(r.startMowing),children:(0,i.jsx)(Fn,{className:"h-3 w-3"})}),(0,i.jsx)(Nf,{label:"Pause",busy:a,active:c==="paused",onClick:()=>d(r.pause),children:(0,i.jsx)(to,{className:"h-3 w-3"})}),(0,i.jsx)(Nf,{label:"Dock",busy:a,active:c==="docked",onClick:()=>d(r.dock),children:(0,i.jsx)(os,{className:"h-3.5 w-3.5"})}),n?.batteryLevel!=null&&(0,i.jsx)("span",{className:"ml-1",children:(0,i.jsx)(V0,{level:n.batteryLevel})})]})}function Df({label:e,busy:t,active:r,onClick:n,children:s}){return(0,i.jsx)("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:a=>{a.stopPropagation(),n()},className:A("inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",r&&"bg-primary text-primary-foreground hover:bg-primary/90",t&&"opacity-40 cursor-not-allowed"),children:s})}function K0({trpc:e,deviceId:t}){const{cap:r,slice:n,available:s}=Z0(e,t);if(r===void 0)return null;const a=!s,c=n?.activity,d=G0(c),u=f=>{a||f===void 0||f({})};return(0,i.jsx)("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:(0,i.jsxs)("div",{className:"flex items-center gap-6",children:[(0,i.jsx)(n3,{activity:c}),(0,i.jsxs)("div",{className:"flex flex-col gap-3 flex-1",children:[(0,i.jsxs)("div",{className:"flex items-center justify-between",children:[(0,i.jsx)("span",{className:A("text-3xl font-semibold",d.tone),children:d.label}),n?.batteryLevel!=null&&(0,i.jsx)(V0,{level:n.batteryLevel})]}),(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsx)(Df,{label:"Start mowing",busy:a,active:c==="mowing",onClick:()=>u(r.startMowing),children:(0,i.jsx)(Fn,{className:"h-5 w-5"})}),(0,i.jsx)(Df,{label:"Pause",busy:a,active:c==="paused",onClick:()=>u(r.pause),children:(0,i.jsx)(to,{className:"h-5 w-5"})}),(0,i.jsx)(Df,{label:"Dock",busy:a,active:c==="docked",onClick:()=>u(r.dock),children:(0,i.jsx)(os,{className:"h-5 w-5"})})]})]})]})})}function W0(e){switch(e){case"open":return{label:"Open",tone:"text-primary"};case"opening":return{label:"Opening",tone:"text-primary"};case"closing":return{label:"Closing",tone:"text-warning"};case"closed":return{label:"Closed",tone:"text-foreground-subtle"};case"stopped":return{label:"Stopped",tone:"text-warning"};case void 0:return{label:"Unknown",tone:"text-foreground-subtle"}}}function q0(e,t){return bt({trpc:e,deviceId:t,cap:r=>r.valve,slice:r=>r.state.valve})}function Q0(e){switch(e){case"accent":return"bg-primary text-primary-foreground";case"filled":return"bg-primary/15 text-primary";case"neutral":return""}}function Mf({label:e,busy:t,variant:r,onClick:n,children:s}){return(0,i.jsx)("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:a=>{a.stopPropagation(),n()},className:A("inline-flex h-5 w-5 items-center justify-center rounded text-xs text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",Q0(r),t&&"opacity-40 cursor-not-allowed"),children:s})}function Y0({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:a}=q0(e,t),{display:c,applyOptimistic:d}=Zt(s,{enabled:r??!0});if(n===void 0)return null;const u=!a,f=co(c?.state),h=(m,g)=>{u||!m||(g!==void 0&&d(g),m({}))};return(0,i.jsxs)("div",{className:"inline-flex items-center gap-1",children:[(0,i.jsx)(Mf,{label:"Open",busy:u,variant:f.up,onClick:()=>h(n.open,{state:"opening"}),children:(0,i.jsx)(Ti,{className:"h-3.5 w-3.5"})}),(0,i.jsx)(Mf,{label:"Stop",busy:u,variant:f.stop,onClick:()=>h(n.stop,{state:"stopped"}),children:(0,i.jsx)(Un,{className:"h-3 w-3"})}),(0,i.jsx)(Mf,{label:"Close",busy:u,variant:f.down,onClick:()=>h(n.close,{state:"closing"}),children:(0,i.jsx)(fr,{className:"h-3.5 w-3.5"})}),c!==void 0&&c.position!==null&&(0,i.jsxs)("span",{className:"tabular-nums text-xs text-foreground-subtle ml-1",children:[c.position,"%"]})]})}function i3(e){switch(e){case"open":return{glow:"bg-primary/15",accent:"text-primary",flowing:!0,active:!1};case"opening":return{glow:"bg-primary/10",accent:"text-primary",flowing:!0,active:!0};case"closing":return{glow:"bg-warning/10",accent:"text-warning",flowing:!1,active:!0};case"closed":return{glow:"bg-transparent",accent:"text-foreground-subtle",flowing:!1,active:!1};case"stopped":return{glow:"bg-warning/10",accent:"text-warning",flowing:!1,active:!1};case void 0:return{glow:"bg-transparent",accent:"text-foreground-subtle",flowing:!1,active:!1}}}function s3(e){switch(e){case"open":return 0;case"opening":return 0;case"closed":return 1;case"closing":return 1;case"stopped":return 1;case void 0:return 1}}function a3({state:e,position:t,interactive:r,onSetPosition:n}){const s=i3(e),a=t!==null?1-t/100:s3(e),c=41+a*8,d=-90*(1-a),u=(0,l.useRef)(null),f=(0,l.useRef)(!1),h=(0,l.useRef)(null),m=E=>{const T=t??0,j=u.current;if(j===null)return T;const N=j.getBoundingClientRect();if(N.height<=0)return T;const O=(E-N.top)/N.height,U=Math.round(100-O*100);return Math.min(100,Math.max(0,U))},g=E=>{if(n===void 0)return;const T=m(E);h.current!==T&&(h.current=T,n(T))},p=E=>{r&&(E.stopPropagation(),E.preventDefault(),f.current=!0,h.current=null,E.currentTarget.setPointerCapture(E.pointerId),g(E.clientY))},y=E=>{!r||!f.current||(E.stopPropagation(),g(E.clientY))},S=E=>{!r||!f.current||(E.stopPropagation(),f.current=!1,h.current=null,E.currentTarget.hasPointerCapture(E.pointerId)&&E.currentTarget.releasePointerCapture(E.pointerId))};return(0,i.jsxs)("div",{ref:u,"data-testid":"valve-graphic",...r?{"aria-label":"Drag to set position",role:"slider","aria-valuemin":0,"aria-valuemax":100,"aria-valuenow":t??0}:{"aria-hidden":"true"},onPointerDown:r?p:void 0,onPointerMove:r?y:void 0,onPointerUp:r?S:void 0,onPointerCancel:r?S:void 0,className:A("relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0",r&&"cursor-ns-resize touch-none select-none"),style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.06)"},children:[(0,i.jsx)("div",{className:A("absolute inset-0 transition-colors duration-300",s.glow)}),(0,i.jsx)("div",{className:A("absolute inset-0 flex items-center justify-center",s.accent),"aria-hidden":"true",children:(0,i.jsxs)("svg",{viewBox:"0 0 100 100",className:"w-24 h-28",fill:"none",children:[(0,i.jsx)("rect",{x:"40",y:"4",width:"20",height:"92",rx:"3",fill:"currentColor",fillOpacity:"0.06",stroke:"currentColor",strokeWidth:"2.5"}),s.flowing&&(0,i.jsx)("line",{x1:"50",y1:"8",x2:"50",y2:"92",stroke:"currentColor",strokeWidth:"4",strokeLinecap:"round",strokeDasharray:"4 8",opacity:"0.5",className:"animate-pulse"}),s.active&&(0,i.jsx)("circle",{cx:"50",cy:"50",r:"22",stroke:"currentColor",strokeWidth:"2",opacity:"0.4",className:"animate-ping",style:{transformOrigin:"center"}}),(0,i.jsx)("circle",{cx:"50",cy:"50",r:"17",fill:"currentColor",fillOpacity:"0.12",stroke:"currentColor",strokeWidth:"2.5"}),(0,i.jsx)("rect",{x:"43",y:c,width:"14",height:"6",rx:"1.5",fill:"currentColor",fillOpacity:"0.55",className:"transition-all duration-200"}),(0,i.jsx)("line",{x1:"50",y1:"33",x2:"50",y2:"22",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round"}),(0,i.jsx)("g",{style:{transform:`rotate(${d}deg)`,transformOrigin:"50px 20px",transition:"transform 200ms"},children:(0,i.jsx)("rect",{x:"34",y:"17",width:"32",height:"6",rx:"3",fill:"currentColor",fillOpacity:"0.7"})})]})})]})}function $f({label:e,busy:t,variant:r,onClick:n,children:s}){return(0,i.jsx)("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:a=>{a.stopPropagation(),n()},className:A("inline-flex h-10 w-10 items-center justify-center rounded-md text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",Q0(r),t&&"opacity-40 cursor-not-allowed"),children:s})}function X0({trpc:e,deviceId:t,features:r,optimistic:n}){const{cap:s,slice:a,available:c}=q0(e,t),{display:d,applyOptimistic:u}=Zt(a,{enabled:n??!0});if(s===void 0)return null;const f=!c,h=(r??[]).includes(W.DeviceFeature.ValvePositionable),m=co(d?.state),g=W0(d?.state),p=d?.position??null,y=p!==null,S=(T,j)=>{f||!T||(j!==void 0&&u(j),T({}))},E=T=>{f||(u({position:T}),s.setPosition({position:T}))};return(0,i.jsxs)("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsxs)("div",{className:"flex items-center gap-6",children:[(0,i.jsx)(a3,{state:d?.state,position:p,interactive:h&&y,onSetPosition:h&&y?E:void 0}),(0,i.jsxs)("div",{className:"flex flex-col gap-3 flex-1",children:[y&&(0,i.jsxs)("div",{className:"flex items-baseline gap-1",children:[(0,i.jsx)("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:p}),(0,i.jsx)("span",{className:"text-base text-foreground-subtle",children:"%"}),(0,i.jsx)("span",{className:"text-xs text-foreground-subtle ml-1",children:"open"})]}),!y&&(0,i.jsx)("div",{className:"flex items-baseline gap-1",children:(0,i.jsx)("span",{className:A("text-3xl font-semibold",g.tone),children:g.label})}),(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsx)($f,{label:"Open",busy:f,variant:m.up,onClick:()=>S(s.open,{state:"opening"}),children:(0,i.jsx)(Ti,{className:"h-5 w-5"})}),(0,i.jsx)($f,{label:"Stop",busy:f,variant:m.stop,onClick:()=>S(s.stop,{state:"stopped"}),children:(0,i.jsx)(Un,{className:"h-4 w-4"})}),(0,i.jsx)($f,{label:"Close",busy:f,variant:m.down,onClick:()=>S(s.close,{state:"closing"}),children:(0,i.jsx)(fr,{className:"h-5 w-5"})})]})]})]}),h&&(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{className:"w-12 shrink-0",children:"Position"}),(0,i.jsx)("input",{"aria-label":"Position",type:"range",min:0,max:100,step:1,value:p??0,disabled:f,className:"flex-1",onChange:T=>{E(Number(T.target.value))}}),(0,i.jsxs)("span",{className:"w-8 text-right tabular-nums",children:[p??"—","%"]})]}),!h&&y&&(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{className:"w-12 shrink-0",children:"Position"}),(0,i.jsx)("input",{"aria-label":"Position",type:"range",min:0,max:100,step:1,value:p,disabled:!0,readOnly:!0,className:"flex-1 opacity-60"}),(0,i.jsxs)("span",{className:"w-8 text-right tabular-nums",children:[p,"%"]})]})]})}function J0(e,t){switch(t){case"humidifying":return{glow:"bg-primary/15",accent:"text-primary",misting:!0};case"drying":return{glow:"bg-warning/10",accent:"text-warning",misting:!1};case"idle":return{glow:"bg-transparent",accent:"text-foreground-subtle",misting:!1};case"off":return{glow:"bg-transparent",accent:"text-foreground-subtle",misting:!1};default:return e?{glow:"bg-primary/10",accent:"text-primary",misting:!0}:{glow:"bg-transparent",accent:"text-foreground-subtle",misting:!1}}}function eb(e,t){return bt({trpc:e,deviceId:t,cap:r=>r.humidifier,slice:r=>r.state.humidifier})}function tb({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:a}=eb(e,t),{display:c,applyOptimistic:d}=Zt(s,{enabled:r??!0});if(n===void 0)return null;const u=!a,f=c?.on??!1,h=()=>{u||(d({on:!f}),n.setOn({on:!f}))};return(0,i.jsxs)("div",{className:"inline-flex items-center gap-2",children:[(0,i.jsx)("button",{type:"button","aria-label":f?"Turn off":"Turn on",title:f?"Turn off":"Turn on",disabled:u,onClick:m=>{m.stopPropagation(),h()},className:A("inline-flex h-5 w-5 items-center justify-center rounded text-xs transition-colors",f?"bg-primary text-primary-foreground":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",u&&"opacity-40 cursor-not-allowed"),children:(0,i.jsx)(yl,{className:"h-3.5 w-3.5"})}),c!==void 0&&c.targetHumidity!==null&&(0,i.jsxs)("span",{className:"tabular-nums text-xs text-foreground-subtle",children:[c.currentHumidity!==null&&(0,i.jsxs)(i.Fragment,{children:[c.currentHumidity,"%",(0,i.jsx)("span",{className:"mx-0.5",children:"→"})]}),c.targetHumidity,"%"]})]})}function o3({fillPct:e,tint:t}){const r=82-Math.min(100,Math.max(0,e))/100*56,n=`humidifier-droplet-clip-${(0,l.useId)()}`;return(0,i.jsxs)("div",{"data-testid":"humidifier-graphic","aria-hidden":"true",className:"relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0",style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.06)"},children:[(0,i.jsx)("div",{className:A("absolute inset-0 transition-colors duration-300",t.glow)}),(0,i.jsx)("div",{className:A("absolute inset-0 flex items-center justify-center",t.accent),children:(0,i.jsxs)("svg",{viewBox:"0 0 100 100",className:"w-24 h-28",fill:"none",children:[(0,i.jsx)("defs",{children:(0,i.jsx)("clipPath",{id:n,children:(0,i.jsx)("path",{d:"M50 26 C50 26 30 52 30 66 a20 20 0 0 0 40 0 C70 52 50 26 50 26 Z"})})}),t.misting&&(0,i.jsxs)("g",{className:"animate-pulse",opacity:"0.55",children:[(0,i.jsx)("line",{x1:"42",y1:"20",x2:"42",y2:"8",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"3 5"}),(0,i.jsx)("line",{x1:"50",y1:"18",x2:"50",y2:"4",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"3 5"}),(0,i.jsx)("line",{x1:"58",y1:"20",x2:"58",y2:"8",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"3 5"})]}),(0,i.jsx)("path",{d:"M50 26 C50 26 30 52 30 66 a20 20 0 0 0 40 0 C70 52 50 26 50 26 Z",fill:"currentColor",fillOpacity:"0.08",stroke:"currentColor",strokeWidth:"2.5"}),(0,i.jsx)("g",{clipPath:`url(#${n})`,children:(0,i.jsx)("rect",{x:"28",y:r,width:"44",height:"60",fill:"currentColor",fillOpacity:"0.4",className:"transition-all duration-300"})}),(0,i.jsx)("circle",{cx:"43",cy:"56",r:"3",fill:"currentColor",fillOpacity:"0.5"})]})})]})}function rb({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:a}=eb(e,t),{display:c,applyOptimistic:d}=Zt(s,{enabled:r??!0});if(n===void 0||c===void 0)return null;const u=!a,f=J0(c.on,c.action),h=c.minHumidity??0,m=c.maxHumidity??100,g=c.targetHumidity,p=c.currentHumidity,y=p??g??0,S=()=>{u||(d({on:!c.on}),n.setOn({on:!c.on}))},E=T=>{u||(d({targetHumidity:T}),n.setTargetHumidity({humidity:T}))};return(0,i.jsxs)("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsxs)("div",{className:"flex items-center gap-6",children:[(0,i.jsx)(o3,{fillPct:y,tint:f}),(0,i.jsxs)("div",{className:"flex flex-col gap-3 flex-1",children:[(0,i.jsxs)("div",{className:"flex items-baseline gap-1",children:[(0,i.jsx)("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:g!==null?g:"—"}),(0,i.jsx)("span",{className:"text-base text-foreground-subtle",children:"%"}),(0,i.jsx)("span",{className:"text-xs text-foreground-subtle ml-1",children:"target"})]}),(0,i.jsxs)("div",{className:"text-xs text-foreground-subtle tabular-nums",children:["Current: ",p!==null?`${p}%`:"—",c.action!==null&&(0,i.jsxs)("span",{className:"ml-2 capitalize",children:["· ",c.action]})]}),(0,i.jsxs)("button",{type:"button","aria-label":c.on?"Turn off":"Turn on",disabled:u,onClick:T=>{T.stopPropagation(),S()},className:A("inline-flex w-fit items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors",c.on?"bg-primary text-primary-foreground":"border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover",u&&"opacity-40 cursor-not-allowed"),children:[(0,i.jsx)(yl,{className:"h-4 w-4"}),c.on?"On":"Off"]})]})]}),(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{className:"w-12 shrink-0",children:"Target"}),(0,i.jsx)("input",{"aria-label":"Target humidity",type:"range",min:h,max:m,step:1,value:g??h,disabled:u,className:"flex-1",onChange:T=>{E(Number(T.target.value))}}),(0,i.jsxs)("span",{className:"w-8 text-right tabular-nums",children:[g??"—","%"]})]}),c.availableModes.length>0&&(0,i.jsx)("select",{"aria-label":"Mode",value:c.mode??"",disabled:u,onChange:T=>{T.stopPropagation();const j=c.availableModes.find(N=>N===T.target.value);!u&&j!==void 0&&(d({mode:j}),n.setMode({mode:j}))},className:A("w-full rounded border border-border bg-surface px-3 py-1.5 text-sm",u&&"opacity-40 cursor-not-allowed"),children:c.availableModes.map(T=>(0,i.jsx)("option",{value:T,children:T},T))})]})}function nb(e){switch(e){case"heating":return{glow:"bg-warning/10",accent:"text-warning",heating:!0};case"idle":return{glow:"bg-primary/10",accent:"text-primary",heating:!1};case"off":return{glow:"bg-transparent",accent:"text-foreground-subtle",heating:!1}}}function ib(e,t,r){return e===null||e==="off"?"off":t!==null&&r!==null&&t<r?"heating":"idle"}function sb(e,t){return bt({trpc:e,deviceId:t,cap:r=>r.waterHeater,slice:r=>r.state.waterHeater})}function ab({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s}=sb(e,t),{display:a}=Zt(s,{enabled:r??!0});return n===void 0||a===void 0?null:(0,i.jsxs)("div",{className:"inline-flex items-center gap-1.5 text-xs text-foreground-subtle",children:[(0,i.jsxs)("span",{className:"tabular-nums",children:[a.currentTemp!==null&&(0,i.jsxs)(i.Fragment,{children:[a.currentTemp,"°",(0,i.jsx)("span",{className:"mx-0.5",children:"→"})]}),a.targetTemp!==null?`${a.targetTemp}°`:"—"]}),a.operationMode!==null&&(0,i.jsxs)("span",{className:"capitalize text-foreground-subtle/80",children:["· ",a.operationMode.replace(/_/g," ")]})]})}function l3({fillPct:e,tint:t}){const r=86-Math.min(100,Math.max(0,e))/100*68,n=`water-heater-tank-clip-${(0,l.useId)()}`;return(0,i.jsxs)("div",{"data-testid":"water-heater-graphic","aria-hidden":"true",className:"relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0",style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.06)"},children:[(0,i.jsx)("div",{className:A("absolute inset-0 transition-colors duration-300",t.glow)}),(0,i.jsx)("div",{className:A("absolute inset-0 flex items-center justify-center",t.accent),children:(0,i.jsxs)("svg",{viewBox:"0 0 100 100",className:"w-24 h-28",fill:"none",children:[(0,i.jsx)("defs",{children:(0,i.jsx)("clipPath",{id:n,children:(0,i.jsx)("rect",{x:"30",y:"18",width:"40",height:"68",rx:"14"})})}),(0,i.jsx)("g",{clipPath:`url(#${n})`,children:(0,i.jsx)("rect",{x:"28",y:r,width:"44",height:"72",fill:"currentColor",fillOpacity:"0.32",className:"transition-all duration-300"})}),(0,i.jsx)("rect",{x:"30",y:"18",width:"40",height:"68",rx:"14",fill:"currentColor",fillOpacity:"0.06",stroke:"currentColor",strokeWidth:"2.5"}),(0,i.jsx)("line",{x1:"50",y1:"18",x2:"50",y2:"8",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round"}),(0,i.jsx)("rect",{x:"40",y:"6",width:"20",height:"5",rx:"2",fill:"currentColor",fillOpacity:"0.6"}),(0,i.jsx)("g",{className:t.heating?"animate-pulse":void 0,opacity:t.heating?.9:.35,children:(0,i.jsx)("path",{d:"M38 74 q4 -6 8 0 q4 6 8 0 q4 -6 8 0",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",fill:"none"})}),(0,i.jsx)("circle",{cx:"62",cy:"34",r:"3.5",stroke:"currentColor",strokeWidth:"2",fill:t.heating?"currentColor":"none",fillOpacity:"0.6"})]})})]})}function ob({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:a}=sb(e,t),{display:c,applyOptimistic:d}=Zt(s,{enabled:r??!0});if(n===void 0||c===void 0)return null;const u=!a,f=ib(c.operationMode,c.currentTemp,c.targetTemp),h=nb(f),m=c.currentTemp,g=c.targetTemp,p=c.minTemp,y=c.maxTemp,S=m!==null&&g!==null&&g>0?Math.min(100,m/g*100):m!==null&&y!==null&&y>0?Math.min(100,m/y*100):50,E=N=>{let O=N;return p!==null&&(O=Math.max(p,O)),y!==null&&(O=Math.min(y,O)),O},T=N=>{if(u||g===null)return;const O=E(g+N);d({targetTemp:O}),n.setTargetTemp({temp:O})},j=()=>{u||c.away===null||(d({away:!c.away}),n.setAway({on:!c.away}))};return(0,i.jsxs)("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsxs)("div",{className:"flex items-center gap-6",children:[(0,i.jsx)(l3,{fillPct:S,tint:h}),(0,i.jsxs)("div",{className:"flex flex-col gap-3 flex-1",children:[(0,i.jsxs)("div",{className:"flex items-baseline gap-1",children:[(0,i.jsx)("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:m!==null?m:"—"}),(0,i.jsx)("span",{className:"text-base text-foreground-subtle",children:"°"})]}),(0,i.jsxs)("div",{className:"text-xs text-foreground-subtle tabular-nums",children:["Target: ",g!==null?`${g}°`:"—",(0,i.jsxs)("span",{className:"ml-2 capitalize",children:["· ",f]})]}),g!==null&&(0,i.jsx)("div",{className:"w-[180px]",children:(0,i.jsx)(wf,{value:g,unit:"°",onDelta:T})})]})]}),c.availableModes.length>0&&(0,i.jsx)("select",{"aria-label":"Operation mode",value:c.operationMode??"",disabled:u,onChange:N=>{N.stopPropagation();const O=c.availableModes.find(U=>U===N.target.value);!u&&O!==void 0&&(d({operationMode:O}),n.setOperationMode({mode:O}))},className:A("w-full rounded border border-border bg-surface px-3 py-1.5 text-sm",u&&"opacity-40 cursor-not-allowed"),children:c.availableModes.map(N=>(0,i.jsx)("option",{value:N,children:N},N))}),c.away!==null&&(0,i.jsxs)("button",{type:"button","aria-label":c.away?"Disable away mode":"Enable away mode",disabled:u,onClick:N=>{N.stopPropagation(),j()},className:A("inline-flex w-fit items-center gap-2 rounded-md px-3 py-1.5 text-sm transition-colors",c.away?"bg-primary text-primary-foreground":"border border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover",u&&"opacity-40 cursor-not-allowed"),children:[(0,i.jsx)(yl,{className:"h-4 w-4"}),"Away ",c.away?"on":"off"]})]})}function Rf(e){switch(e){case"sunny":return{label:"Sunny",glyph:"sun"};case"clear-night":return{label:"Clear night",glyph:"clear-night"};case"partlycloudy":return{label:"Partly cloudy",glyph:"partly-cloudy"};case"cloudy":return{label:"Cloudy",glyph:"cloudy"};case"rainy":return{label:"Rainy",glyph:"rain"};case"pouring":return{label:"Pouring",glyph:"rain"};case"snowy":return{label:"Snowy",glyph:"snow"};case"snowy-rainy":return{label:"Sleet",glyph:"snow"};case"lightning":return{label:"Lightning",glyph:"lightning"};case"lightning-rainy":return{label:"Thunderstorm",glyph:"lightning"};case"fog":return{label:"Fog",glyph:"fog"};case"windy":return{label:"Windy",glyph:"wind"};case"windy-variant":return{label:"Windy",glyph:"wind"};case"hail":return{label:"Hail",glyph:"hail"};case"exceptional":return{label:"Exceptional",glyph:"cloudy"};case null:return{label:"Unknown",glyph:"cloudy"};default:return{label:e,glyph:"cloudy"}}}function Lf(e){switch(e){case"sunny":return{glow:"bg-warning/15",accent:"text-warning"};case"clear-night":return{glow:"bg-primary/10",accent:"text-primary"};case"partlycloudy":return{glow:"bg-warning/10",accent:"text-warning"};case"cloudy":return{glow:"bg-transparent",accent:"text-foreground-subtle"};case"rainy":case"pouring":return{glow:"bg-primary/15",accent:"text-primary"};case"snowy":case"snowy-rainy":return{glow:"bg-primary/10",accent:"text-primary"};case"lightning":case"lightning-rainy":return{glow:"bg-warning/20",accent:"text-warning"};case"fog":return{glow:"bg-transparent",accent:"text-foreground-subtle"};case"windy":case"windy-variant":return{glow:"bg-transparent",accent:"text-foreground-subtle"};case"hail":return{glow:"bg-primary/10",accent:"text-primary"};default:return{glow:"bg-transparent",accent:"text-foreground-subtle"}}}function c3(e){const t="h-4 w-4";switch(e){case"sun":return(0,i.jsx)(Xd,{className:t});case"clear-night":return(0,i.jsx)(bl,{className:t});case"partly-cloudy":return(0,i.jsx)(Tp,{className:t});case"cloudy":return(0,i.jsx)(FT,{className:t});case"rain":return(0,i.jsx)(OT,{className:t});case"snow":return(0,i.jsx)(kp,{className:t});case"lightning":return(0,i.jsx)(LT,{className:t});case"fog":return(0,i.jsx)(RT,{className:t});case"wind":return(0,i.jsx)(xl,{className:t});case"hail":return(0,i.jsx)(kp,{className:t});default:return null}}function lb(e,t){return bt({trpc:e,deviceId:t,cap:r=>r.weather,slice:r=>r.state.weather})}function u3(e,t){return e===null?"—":`${Math.round(e)}${t??"°"}`}function cb({trpc:e,deviceId:t}){const{slice:r}=lb(e,t);if(r===void 0)return null;const n=Rf(r.condition);return(0,i.jsxs)("div",{className:"inline-flex items-center gap-1.5 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{className:A("inline-flex",Lf(r.condition).accent),title:n.label,"aria-label":n.label,children:c3(n.glyph)}),(0,i.jsx)("span",{className:"tabular-nums",children:u3(r.temperature,r.temperatureUnit)})]})}function d3({glyph:e,tint:t}){const r=(0,l.useId)();return(0,i.jsxs)("div",{"data-testid":"weather-scene","aria-hidden":"true",className:"relative w-28 h-36 rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface overflow-hidden flex-shrink-0",style:{boxShadow:"inset 0 0 0 2px rgba(255,255,255,.06)"},children:[(0,i.jsx)("div",{className:A("absolute inset-0 transition-colors duration-300",t.glow)}),(0,i.jsx)("div",{className:A("absolute inset-0 flex items-center justify-center",t.accent),children:(0,i.jsx)("svg",{viewBox:"0 0 100 100",className:"w-24 h-28",fill:"none","data-glyph":e,children:f3(e,r)})})]})}function Ni({cx:e,cy:t,scale:r=1}){return(0,i.jsx)("g",{transform:`translate(${e} ${t}) scale(${r})`,children:(0,i.jsx)("path",{d:"M-22 8 a13 13 0 0 1 4 -25 a16 16 0 0 1 30 4 a11 11 0 0 1 -2 21 Z",fill:"currentColor",fillOpacity:"0.12",stroke:"currentColor",strokeWidth:"2.5",strokeLinejoin:"round"})})}function f3(e,t){switch(e){case"sun":return(0,i.jsxs)("g",{children:[(0,i.jsx)("circle",{cx:"50",cy:"48",r:"16",fill:"currentColor",fillOpacity:"0.18",stroke:"currentColor",strokeWidth:"2.5"}),(0,i.jsx)("g",{stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[0,45,90,135,180,225,270,315].map(r=>{const n=r*Math.PI/180;return(0,i.jsx)("line",{x1:50+Math.cos(n)*22,y1:48+Math.sin(n)*22,x2:50+Math.cos(n)*30,y2:48+Math.sin(n)*30},`${t}-ray-${r}`)})})]});case"clear-night":return(0,i.jsxs)("g",{children:[(0,i.jsx)("path",{d:"M62 30 a22 22 0 1 0 8 38 a18 18 0 0 1 -8 -38 Z",fill:"currentColor",fillOpacity:"0.18",stroke:"currentColor",strokeWidth:"2.5"}),(0,i.jsx)("circle",{cx:"34",cy:"32",r:"1.6",fill:"currentColor"}),(0,i.jsx)("circle",{cx:"28",cy:"48",r:"1.2",fill:"currentColor"}),(0,i.jsx)("circle",{cx:"40",cy:"62",r:"1.4",fill:"currentColor"})]});case"partly-cloudy":return(0,i.jsxs)("g",{children:[(0,i.jsx)("circle",{cx:"38",cy:"38",r:"12",fill:"currentColor",fillOpacity:"0.18",stroke:"currentColor",strokeWidth:"2.5"}),(0,i.jsx)("g",{stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",children:[200,240,300].map(r=>{const n=r*Math.PI/180;return(0,i.jsx)("line",{x1:38+Math.cos(n)*16,y1:38+Math.sin(n)*16,x2:38+Math.cos(n)*22,y2:38+Math.sin(n)*22},`${t}-pcray-${r}`)})}),(0,i.jsx)(Ni,{cx:58,cy:60})]});case"cloudy":return(0,i.jsxs)("g",{children:[(0,i.jsx)(Ni,{cx:40,cy:44,scale:.9}),(0,i.jsx)(Ni,{cx:62,cy:58})]});case"rain":return(0,i.jsxs)("g",{children:[(0,i.jsx)(Ni,{cx:50,cy:42}),(0,i.jsxs)("g",{className:"animate-pulse",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",opacity:"0.7",children:[(0,i.jsx)("line",{x1:"38",y1:"62",x2:"34",y2:"78"}),(0,i.jsx)("line",{x1:"50",y1:"62",x2:"46",y2:"80"}),(0,i.jsx)("line",{x1:"62",y1:"62",x2:"58",y2:"78"})]})]});case"snow":return(0,i.jsxs)("g",{children:[(0,i.jsx)(Ni,{cx:50,cy:42}),(0,i.jsxs)("g",{fill:"currentColor",opacity:"0.8",className:"animate-pulse",children:[(0,i.jsx)("circle",{cx:"38",cy:"70",r:"2.5"}),(0,i.jsx)("circle",{cx:"50",cy:"76",r:"2.5"}),(0,i.jsx)("circle",{cx:"62",cy:"70",r:"2.5"})]})]});case"lightning":return(0,i.jsxs)("g",{children:[(0,i.jsx)(Ni,{cx:50,cy:40}),(0,i.jsx)("path",{d:"M52 58 L42 74 L50 74 L46 88 L62 68 L53 68 L58 58 Z",fill:"currentColor",fillOpacity:"0.85",className:"animate-pulse"})]});case"fog":return(0,i.jsxs)("g",{stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",opacity:"0.6",children:[(0,i.jsx)("line",{x1:"26",y1:"40",x2:"74",y2:"40"}),(0,i.jsx)("line",{x1:"30",y1:"52",x2:"70",y2:"52"}),(0,i.jsx)("line",{x1:"24",y1:"64",x2:"68",y2:"64"}),(0,i.jsx)("line",{x1:"32",y1:"76",x2:"76",y2:"76"})]});case"wind":return(0,i.jsxs)("g",{stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",fill:"none",opacity:"0.75",children:[(0,i.jsx)("path",{d:"M22 42 H60 a7 7 0 1 0 -7 -7"}),(0,i.jsx)("path",{d:"M22 56 H72 a7 7 0 1 1 -7 7"}),(0,i.jsx)("path",{d:"M22 70 H52 a6 6 0 1 0 -6 -6"})]});case"hail":return(0,i.jsxs)("g",{children:[(0,i.jsx)(Ni,{cx:50,cy:42}),(0,i.jsxs)("g",{fill:"currentColor",opacity:"0.85",className:"animate-pulse",children:[(0,i.jsx)("circle",{cx:"40",cy:"70",r:"3"}),(0,i.jsx)("circle",{cx:"52",cy:"78",r:"3"}),(0,i.jsx)("circle",{cx:"62",cy:"68",r:"3"})]})]});default:return null}}function Of({icon:e,label:t,value:r}){return(0,i.jsxs)("div",{className:"flex items-center gap-1.5 text-xs text-foreground-subtle",title:t,children:[(0,i.jsx)("span",{className:"inline-flex text-foreground-subtle","aria-hidden":"true",children:e}),(0,i.jsx)("span",{className:"tabular-nums text-foreground",children:r})]})}function ub({trpc:e,deviceId:t}){const{slice:r}=lb(e,t);if(r===void 0)return null;const n=Rf(r.condition),s=Lf(r.condition),a=r.temperatureUnit??"°";return(0,i.jsx)("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:(0,i.jsxs)("div",{className:"flex items-center gap-6",children:[(0,i.jsx)(d3,{glyph:n.glyph,tint:s}),(0,i.jsxs)("div",{className:"flex flex-col gap-3 flex-1",children:[(0,i.jsxs)("div",{className:"flex items-baseline gap-1",children:[(0,i.jsx)("span",{className:"text-3xl font-semibold tabular-nums text-foreground",children:r.temperature!==null?Math.round(r.temperature):"—"}),(0,i.jsx)("span",{className:"text-base text-foreground-subtle",children:a}),(0,i.jsx)("span",{className:"text-xs text-foreground-subtle ml-2 capitalize",children:n.label})]}),(0,i.jsxs)("div",{className:"flex flex-col gap-1.5",children:[r.humidity!==null&&(0,i.jsx)(Of,{icon:(0,i.jsx)(zd,{className:"h-3.5 w-3.5"}),label:"Humidity",value:`${Math.round(r.humidity)}%`}),r.windSpeed!==null&&(0,i.jsx)(Of,{icon:r.windBearing!==null?(0,i.jsx)(mC,{className:"h-3.5 w-3.5",style:{transform:`rotate(${r.windBearing}deg)`}}):(0,i.jsx)(xl,{className:"h-3.5 w-3.5"}),label:"Wind",value:`${Math.round(r.windSpeed)} ${r.windSpeedUnit??""}`.trim()}),r.pressure!==null&&(0,i.jsx)(Of,{icon:(0,i.jsx)(eo,{className:"h-3.5 w-3.5"}),label:"Pressure",value:`${Math.round(r.pressure)} ${r.pressureUnit??""}`.trim()})]})]})]})})}var h3=288,m3=196,g3="h-7 w-7 rounded",Ff=8,db=8;function Uf({src:e,alt:t,caption:r,placeholder:n="No image",thumbClassName:s=g3,expandedWidth:a=h3,expandedHeight:c=m3}){const d=(0,l.useRef)(null),[u,f]=(0,l.useState)(null),[h,m]=(0,l.useState)(!1);(0,l.useEffect)(()=>{m(!1)},[e]);const g=e!==null&&!h,p=e??void 0,y=(0,l.useCallback)(()=>{const E=d.current;if(!E)return;const T=E.getBoundingClientRect(),j=T.top,N=window.innerHeight-T.bottom,O=j<c+Ff&&N>j?T.bottom+Ff:T.top-c-Ff,U=T.right-a;f({top:O,left:Math.max(db,Math.min(U,window.innerWidth-a-db))})},[a,c]),S=(0,l.useCallback)(()=>f(null),[]);return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("button",{ref:d,type:"button",onClick:E=>E.stopPropagation(),onMouseEnter:y,onMouseLeave:S,onFocus:y,onBlur:S,"aria-label":t,className:`flex flex-shrink-0 items-center justify-center overflow-hidden border border-border bg-background text-foreground-subtle transition-colors hover:bg-surface-hover ${s}`,children:g?(0,i.jsx)("img",{src:p,alt:"",onError:()=>m(!0),className:"h-full w-full object-cover"}):(0,i.jsx)(jp,{className:"h-3.5 w-3.5","aria-hidden":"true"})}),u&&(0,I.createPortal)((0,i.jsxs)("div",{"aria-hidden":"true",style:{position:"fixed",top:u.top,left:u.left,width:a,pointerEvents:"none"},className:"z-[9999] overflow-hidden rounded-lg border border-border bg-surface shadow-lg shadow-black/30",children:[(0,i.jsx)("div",{className:"flex h-40 items-center justify-center bg-background",children:g?(0,i.jsx)("img",{src:p,alt:t,className:"h-full w-full object-cover"}):(0,i.jsx)("span",{className:"text-xs text-foreground-subtle",children:n})}),(0,i.jsx)("div",{className:"px-3 py-2",children:(0,i.jsx)("p",{className:"truncate text-xs font-semibold text-foreground",children:r??t})})]}),document.body)]})}function fb(e,t){return bt({trpc:e,deviceId:t,cap:r=>r.image,slice:r=>r.state.image})}function hb({trpc:e,deviceId:t}){const{slice:r}=fb(e,t);return r===void 0?null:(0,i.jsx)(Uf,{src:r.url,alt:"Image",placeholder:"No image",thumbClassName:"h-7 w-7 rounded"})}function mb({trpc:e,deviceId:t,deviceName:r}){const{slice:n}=fb(e,t),[s,a]=(0,l.useState)(!1);return(0,l.useEffect)(()=>{a(!1)},[n?.url??null]),n===void 0?null:(0,i.jsx)("div",{className:"flex flex-col items-stretch gap-3 rounded-lg border border-border bg-surface p-4",children:(0,i.jsx)("div",{className:"flex w-full items-center justify-center overflow-hidden rounded border-2 border-border bg-gradient-to-b from-surface-hover to-surface",children:n.url!==null&&!s?(0,i.jsx)("img",{src:n.url,alt:r??"Image",onError:()=>a(!0),className:"max-h-72 w-full object-contain"}):(0,i.jsxs)("div",{"data-testid":"image-placeholder",className:"flex h-48 w-full flex-col items-center justify-center gap-2 text-foreground-subtle",children:[(0,i.jsx)(jp,{className:"h-8 w-8","aria-hidden":"true"}),(0,i.jsx)("span",{className:"text-xs",children:"No image"})]})})})}function Ll({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:a}=bt({trpc:e,deviceId:t,cap:y=>y.switch,slice:y=>y.state.switch}),{display:c,applyOptimistic:d}=Zt(s,{enabled:r??!0}),[u,f]=(0,l.useState)(!1);if(c===void 0)return null;const h=c.on===!0,m=u||!a,g={transform:h?"translateX(14px)":"translateX(2px)"},p=async()=>{if(m||!n)return;const y=!h;d({on:y}),f(!0);try{await n.setState({on:y})}finally{f(!1)}};return(0,i.jsx)("button",{type:"button","aria-pressed":h,title:h?"Turn off":"Turn on",disabled:m,onClick:y=>{y.stopPropagation(),p()},className:A("relative inline-flex h-4 w-7 items-center rounded-full border transition-colors flex-shrink-0",h?"bg-success/30 border-success/50":"bg-surface-hover border-border",m&&"opacity-60"),children:(0,i.jsx)("span",{className:A("absolute h-3 w-3 rounded-full transition-all",h?"bg-success":"bg-foreground-subtle"),style:g})})}function p3(e){return e instanceof Error?e.message:String(e)}function gb({trpc:e,deviceId:t,layout:r,optimistic:n,features:s}){const{cap:a,slice:c,available:d}=bt({trpc:e,deviceId:t,cap:se=>se.lockControl,slice:se=>se.state.lockControl}),{display:u,applyOptimistic:f}=Zt(c,{enabled:n??!0}),[h,m]=(0,l.useState)(null),[g,p]=(0,l.useState)(!1),[y,S]=(0,l.useState)(null);if(u===void 0)return null;const E=u.state==="locked"||u.state==="locking",T=!d||u.state==="jammed",j=s?.includes(W.DeviceFeature.LockOpen)===!0,N=r==="compact",O=()=>{f({state:"locking"}),a?.lock({})},U=()=>{f({state:"unlocking"}),a?.unlock({})},z=()=>{a?.open({})},K=()=>{if(!T){if(!E){O();return}if(N){S(null),m("unlock");return}U()}},G=()=>{if(!T){if(N){S(null),m("open");return}z()}},X=()=>{g||m(null)},te=async()=>{if(!(g||h===null)){S(null),p(!0);try{h==="unlock"?(f({state:"unlocking"}),await a?.unlock({})):await a?.open({}),m(null)}catch(se){S(p3(se))}finally{p(!1)}}},ne=E?"Unlock":"Lock",ae=h==="open"?"Open door?":"Unlock device?",oe=h==="open"?"This will release the latch and open the door.":"This will unlock the device.",pe=h==="open"?"Confirm open":"Confirm unlock",le=h==="open"?(0,i.jsx)(Ya,{className:"h-4 w-4 text-amber-400"}):(0,i.jsx)(Vd,{className:"h-4 w-4 text-amber-400"});return(0,i.jsxs)("div",{className:A("inline-flex items-center",r==="full"?"gap-2":"gap-1"),children:[(0,i.jsxs)("button",{type:"button","aria-label":ne,title:u.state==="jammed"?"Jammed":ne,disabled:T,onClick:se=>{se.stopPropagation(),K()},className:A("inline-flex items-center justify-center rounded transition-colors",r==="full"?"h-7 gap-1.5 px-2 text-xs":"h-5 w-5",E?"text-success":"text-warning",T&&"opacity-40 cursor-not-allowed","hover:bg-surface-hover"),children:[E?(0,i.jsx)(Hd,{className:"h-3.5 w-3.5"}):(0,i.jsx)(Vd,{className:"h-3.5 w-3.5"}),r==="full"&&(0,i.jsx)("span",{children:u.state})]}),j&&(0,i.jsxs)("button",{type:"button","aria-label":"Open door",title:"Open door",disabled:T,onClick:se=>{se.stopPropagation(),G()},className:A("inline-flex items-center justify-center rounded transition-colors",r==="full"?"h-7 gap-1.5 px-2 text-xs":"h-5 w-5","text-foreground-muted",T&&"opacity-40 cursor-not-allowed","hover:bg-surface-hover"),children:[(0,i.jsx)(Ya,{className:"h-3.5 w-3.5"}),r==="full"&&(0,i.jsx)("span",{children:"Open"})]}),N&&(0,i.jsx)(_l,{open:h!==null,onOpenChange:se=>{se||X()},children:(0,i.jsxs)(no,{width:"sm",onClick:se=>se.stopPropagation(),children:[(0,i.jsxs)(wl,{children:[(0,i.jsxs)(kl,{className:"flex items-center gap-2",children:[le,ae]}),(0,i.jsx)(Tl,{children:oe})]}),y!==null&&(0,i.jsx)("div",{className:"mt-2 px-3 py-2 rounded border border-danger/40 bg-danger/10 text-xs text-danger",children:y}),(0,i.jsxs)(El,{children:[(0,i.jsx)(tn,{type:"button",variant:"ghost",size:"sm",disabled:g,onClick:()=>X(),children:"Cancel"}),(0,i.jsxs)(tn,{type:"button",variant:"danger",size:"sm","aria-label":pe,disabled:g,onClick:()=>{te()},children:[g&&(0,i.jsx)(hr,{className:"h-3.5 w-3.5 animate-spin"}),pe]})]})]})})]})}function pb({trpc:e,deviceId:t,layout:r,optimistic:n}){const{cap:s,slice:a,available:c}=bt({trpc:e,deviceId:t,cap:h=>h.brightness,slice:h=>h.state.brightness}),{display:d,applyOptimistic:u}=Zt(a,{enabled:n??!0});if(d===void 0)return null;const f=!c;return(0,i.jsxs)("label",{className:A("flex items-center gap-2 text-xs text-foreground-subtle",r==="compact"&&"min-w-[140px]"),children:[(0,i.jsx)("input",{"aria-label":"Brightness",type:"range",min:0,max:100,step:1,value:d.percentage,disabled:f,onChange:h=>{const m=Number(h.target.value);u({percentage:m}),f||s?.setBrightness({percentage:m})}}),(0,i.jsxs)("span",{className:"tabular-nums w-8 text-right",children:[d.percentage,"%"]})]})}function vb({trpc:e,deviceId:t,features:r,layout:n,optimistic:s}){const{cap:a,slice:c,available:d}=bt({trpc:e,deviceId:t,cap:S=>S.fanControl,slice:S=>S.state.fanControl}),{display:u,applyOptimistic:f}=Zt(c,{enabled:s??!0});if(u===void 0)return null;const h=!d,m=r??[],g=m.includes("fan-speed"),p=m.includes("fan-preset"),y=c?.percentageStep!=null&&c.percentageStep>0?c.percentageStep:1;return(0,i.jsxs)("div",{className:A("inline-flex items-center gap-2",n==="full"&&"flex-col items-stretch"),children:[g&&(0,i.jsxs)("div",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("input",{"aria-label":"Fan speed",type:"range",min:0,max:100,step:y,value:u.percentage??0,disabled:h,onChange:S=>{const E=Number(S.target.value),T=Math.min(100,Math.max(0,Math.round(E/y)*y));f({percentage:T}),h||a?.setPercentage({percentage:T})}}),(0,i.jsxs)("span",{className:"tabular-nums w-8 text-right",children:[u.percentage??"—","%"]})]}),p&&u.availablePresets.length>0&&(0,i.jsx)("div",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:(0,i.jsxs)("select",{"aria-label":"Fan preset",value:u.preset,disabled:h,onChange:S=>{const E=S.target.value;!h&&E&&(f({preset:E}),a?.setPreset({preset:E}))},className:"bg-surface border border-border rounded px-1 py-0.5",children:[(0,i.jsx)("option",{value:"",disabled:!0,children:"—"}),u.availablePresets.map(S=>(0,i.jsx)("option",{value:S,children:S},S))]})})]})}var Bf={heat:"border-amber-400 bg-amber-50 dark:bg-amber-950",cool:"border-blue-400 bg-blue-50 dark:bg-blue-950",auto:"border-purple-400 bg-purple-50 dark:bg-purple-950",heat_cool:"border-fuchsia-400 bg-fuchsia-50 dark:bg-fuchsia-950",fan_only:"border-slate-400 bg-slate-50 dark:bg-slate-950",dry:"border-cyan-400 bg-cyan-50 dark:bg-cyan-950",off:"border-zinc-300 bg-zinc-50 dark:bg-zinc-900"},v3={heat:"text-amber-600 dark:text-amber-400",cool:"text-blue-600 dark:text-blue-400",auto:"text-purple-600 dark:text-purple-400",heat_cool:"text-fuchsia-600 dark:text-fuchsia-400",fan_only:"text-slate-600 dark:text-slate-400",dry:"text-cyan-600 dark:text-cyan-400",off:"text-foreground"},b3={heat:"bg-amber-400 text-amber-950",cool:"bg-blue-400 text-blue-950",auto:"bg-purple-400 text-purple-950",heat_cool:"bg-fuchsia-400 text-fuchsia-950",fan_only:"bg-slate-400 text-slate-950",dry:"bg-cyan-400 text-cyan-950",off:"bg-zinc-300 text-zinc-700"};function bb({trpc:e,deviceId:t,features:r,layout:n,optimistic:s}){const{cap:a,slice:c,available:d}=bt({trpc:e,deviceId:t,cap:p=>p.climateControl,slice:p=>p.state.climateControl}),{display:u,applyOptimistic:f}=Zt(c,{enabled:s??!0});if(a===void 0||u===void 0)return null;const h=!d;if(n==="compact")return(0,i.jsxs)("div",{"data-mode":u.mode,className:"inline-flex items-center gap-1",children:[(0,i.jsx)("span",{className:A("text-xs tabular-nums font-medium",v3[u.mode]),children:u.target!==null?(0,i.jsxs)(i.Fragment,{children:[u.target,"°",u.currentTemp!==null&&(0,i.jsxs)("span",{className:"text-foreground-subtle font-normal",children:[" (",u.currentTemp,"°)"]})]}):u.currentTemp!==null?(0,i.jsxs)("span",{className:"text-foreground-subtle",children:[u.currentTemp,"°"]}):null}),u.target!==null&&(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("button",{type:"button","aria-label":"Decrease target",disabled:h,onClick:p=>{if(p.stopPropagation(),!h&&u.target!==null){const y=u.target-1;f({target:y}),a.setTarget({target:y})}},className:A("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",h&&"opacity-40 cursor-not-allowed"),children:"−"}),(0,i.jsx)("button",{type:"button","aria-label":"Increase target",disabled:h,onClick:p=>{if(p.stopPropagation(),!h&&u.target!==null){const y=u.target+1;f({target:y}),a.setTarget({target:y})}},className:A("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",h&&"opacity-40 cursor-not-allowed"),children:"+"})]}),(0,i.jsx)("select",{"aria-label":"Mode",value:u.mode,disabled:h,onChange:p=>{p.stopPropagation();const y=p.target.value;h||(f({mode:y}),a.setMode({mode:y}))},className:A("bg-transparent px-0.5 text-xs text-foreground-subtle hover:text-foreground cursor-pointer",h&&"opacity-40 cursor-not-allowed"),children:u.availableModes.map(p=>(0,i.jsx)("option",{value:p,children:p},p))})]});const m=u.mode==="heat_cool"||u.targetLow!==null&&u.targetHigh!==null,g=!m&&u.target!==null;return(0,i.jsxs)("div",{"data-mode":u.mode,className:A("inline-flex items-center gap-2 rounded border px-2 py-1 transition-colors",Bf[u.mode],"flex-col items-stretch gap-3"),children:[(0,i.jsxs)("div",{className:"inline-flex items-center gap-1 text-xs tabular-nums",children:[u.currentTemp!==null&&(0,i.jsxs)("span",{className:"text-foreground-subtle",children:[u.currentTemp,"°"]}),g&&(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("span",{className:"text-foreground-subtle",children:"→"}),(0,i.jsxs)("span",{className:"font-medium",children:[u.target,"°"]}),(0,i.jsx)("button",{type:"button","aria-label":"Decrease target",disabled:h,onClick:p=>{if(p.stopPropagation(),!h&&u.target!==null){const y=u.target-1;f({target:y}),a.setTarget({target:y})}},className:A("inline-flex h-4 w-4 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",h&&"opacity-40 cursor-not-allowed"),children:"−"}),(0,i.jsx)("button",{type:"button","aria-label":"Increase target",disabled:h,onClick:p=>{if(p.stopPropagation(),!h&&u.target!==null){const y=u.target+1;f({target:y}),a.setTarget({target:y})}},className:A("inline-flex h-4 w-4 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",h&&"opacity-40 cursor-not-allowed"),children:"+"})]})]}),(0,i.jsx)("div",{className:"inline-flex items-center gap-0.5 rounded bg-surface-subtle p-0.5",children:u.availableModes.map(p=>(0,i.jsx)("button",{type:"button","aria-label":p,disabled:h,onClick:y=>{y.stopPropagation(),h||(f({mode:p}),a.setMode({mode:p}))},className:A("rounded px-1.5 py-0.5 text-xs transition-colors",p===u.mode?b3[p]:"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",h&&"opacity-40 cursor-not-allowed"),children:p},p))}),m&&(0,i.jsxs)("div",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsxs)("label",{className:"flex items-center gap-1",children:[(0,i.jsx)("span",{children:"Low"}),(0,i.jsx)("input",{"aria-label":"Target low",type:"number",step:.5,value:u.targetLow??"",disabled:h,onChange:p=>{if(!h){const y=Number(p.target.value),S=u.targetHigh??y;f({targetLow:y}),a.setTargetRange({targetLow:y,targetHigh:S})}},className:"w-14 rounded border border-border bg-surface px-1 py-0.5 tabular-nums"})]}),(0,i.jsxs)("label",{className:"flex items-center gap-1",children:[(0,i.jsx)("span",{children:"High"}),(0,i.jsx)("input",{"aria-label":"Target high",type:"number",step:.5,value:u.targetHigh??"",disabled:h,onChange:p=>{if(!h){const y=Number(p.target.value),S=u.targetLow??y;f({targetHigh:y}),a.setTargetRange({targetLow:S,targetHigh:y})}},className:"w-14 rounded border border-border bg-surface px-1 py-0.5 tabular-nums"})]})]}),u.availableFanModes.length>0&&(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{children:"Fan"}),(0,i.jsxs)("select",{"aria-label":"Fan mode",value:u.fanMode,disabled:h,onChange:p=>{const y=p.target.value;!h&&y&&(f({fanMode:y}),a.setFanMode({fanMode:y}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:[(0,i.jsx)("option",{value:"",disabled:!0,children:"—"}),u.availableFanModes.map(p=>(0,i.jsx)("option",{value:p,children:p},p))]})]}),u.availablePresets.length>0&&(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{children:"Preset"}),(0,i.jsxs)("select",{"aria-label":"Preset",value:u.preset,disabled:h,onChange:p=>{const y=p.target.value;!h&&y&&(f({preset:y}),a.setPreset({preset:y}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:[(0,i.jsx)("option",{value:"",disabled:!0,children:"—"}),u.availablePresets.map(p=>(0,i.jsx)("option",{value:p,children:p},p))]})]}),u.targetHumidity!==null&&(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{children:"Humidity"}),(0,i.jsx)("input",{"aria-label":"Target humidity",type:"range",min:0,max:100,step:1,value:u.targetHumidity,disabled:h,onChange:p=>{const y=Number(p.target.value);f({targetHumidity:y}),h||a.setTargetHumidity({targetHumidity:y})}}),(0,i.jsxs)("span",{className:"tabular-nums w-8 text-right",children:[u.targetHumidity,"%"]})]})]})}var yb={playing:"border-green-400 bg-green-50 dark:bg-green-950",paused:"border-amber-400 bg-amber-50 dark:bg-amber-950",buffering:"border-blue-400 bg-blue-50 dark:bg-blue-950",on:"border-slate-400 bg-slate-50 dark:bg-slate-950",idle:"border-slate-400 bg-slate-50 dark:bg-slate-950",off:"border-zinc-300 bg-zinc-50 dark:bg-zinc-900",standby:"border-zinc-300 bg-zinc-50 dark:bg-zinc-900"},y3={playing:"bg-green-500",paused:"bg-amber-400",buffering:"bg-blue-400",on:"bg-slate-400",idle:"bg-slate-400",off:"bg-zinc-300",standby:"bg-zinc-300"},xb=["off","all","one"];function x3(e){return xb.includes(e)}var S3={off:"Off",all:"All",one:"One"};function _3(e){return e==="playing"||e==="buffering"?"pause":"play"}function Sb({trpc:e,deviceId:t,features:r,layout:n,optimistic:s}){const{cap:a,slice:c,available:d}=bt({trpc:e,deviceId:t,cap:g=>g.mediaPlayer,slice:g=>g.state.mediaPlayer}),{display:u,applyOptimistic:f}=Zt(c,{enabled:s??!0});if(u===void 0)return null;const h=!d,m=_3(u.state);return(0,i.jsxs)("div",{"data-state":u.state,className:A("inline-flex items-center gap-2 rounded border px-2 py-1 transition-colors",yb[u.state],n==="full"&&"flex-col items-stretch gap-3"),children:[(0,i.jsxs)("div",{className:"inline-flex items-center gap-2",children:[(0,i.jsx)("span",{role:"status","aria-label":u.state,className:A("inline-block h-2 w-2 rounded-full flex-shrink-0",y3[u.state])}),(0,i.jsx)("button",{type:"button","aria-label":m==="play"?"Play":"Pause",disabled:h,onClick:g=>{g.stopPropagation(),!h&&(m==="play"?(f({state:"playing"}),a?.play({})):(f({state:"paused"}),a?.pause({})))},className:A("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",h&&"opacity-40 cursor-not-allowed"),children:m==="play"?"▶":"⏸"})]}),n==="full"&&(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("div",{className:"inline-flex items-center gap-1",children:[(0,i.jsx)("button",{type:"button","aria-label":"Previous",disabled:h,onClick:g=>{g.stopPropagation(),h||a?.previous({})},className:A("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",h&&"opacity-40 cursor-not-allowed"),children:"⏮"}),(0,i.jsx)("button",{type:"button","aria-label":"Next",disabled:h,onClick:g=>{g.stopPropagation(),h||a?.next({})},className:A("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors text-xs",h&&"opacity-40 cursor-not-allowed"),children:"⏭"})]}),u.volumeLevel!==null&&(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{children:"Vol"}),(0,i.jsx)("input",{"aria-label":"Volume",type:"range",min:0,max:100,step:1,value:u.volumeLevel,disabled:h,onChange:g=>{const p=Number(g.target.value);f({volumeLevel:p}),h||a?.setVolume({volumeLevel:p})}}),(0,i.jsxs)("span",{className:"tabular-nums w-8 text-right",children:[u.volumeLevel,"%"]})]}),u.isMuted!==null&&(0,i.jsx)("button",{type:"button","aria-label":u.isMuted?"Unmute":"Mute",disabled:h,onClick:g=>{if(g.stopPropagation(),!h&&u.isMuted!==null){const p=!u.isMuted;f({isMuted:p}),a?.setMute({muted:p})}},className:A("inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors",u.isMuted?"bg-amber-400 text-amber-950":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",h&&"opacity-40 cursor-not-allowed"),children:u.isMuted?"🔇":"🔊"}),u.availableSources.length>0&&(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{children:"Source"}),(0,i.jsxs)("select",{"aria-label":"Source",value:u.source,disabled:h,onChange:g=>{const p=g.target.value;!h&&p&&(f({source:p}),a?.selectSource({source:p}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:[(0,i.jsx)("option",{value:"",disabled:!0,children:"—"}),u.availableSources.map(g=>(0,i.jsx)("option",{value:g,children:g},g))]})]}),u.shuffle!==null&&(0,i.jsx)("button",{type:"button","aria-label":"Shuffle",disabled:h,onClick:g=>{if(g.stopPropagation(),!h&&u.shuffle!==null){const p=!u.shuffle;f({shuffle:p}),a?.setShuffle({shuffle:p})}},className:A("inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs transition-colors",u.shuffle?"bg-green-400 text-green-950":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",h&&"opacity-40 cursor-not-allowed"),children:"⇌ Shuffle"}),u.repeat!==null&&(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{children:"Repeat"}),(0,i.jsx)("select",{"aria-label":"Repeat",value:u.repeat,disabled:h,onChange:g=>{const p=g.target.value;!h&&x3(p)&&(f({repeat:p}),a?.setRepeat({repeat:p}))},className:"rounded border border-border bg-surface px-1 py-0.5",children:xb.map(g=>(0,i.jsx)("option",{value:g,children:S3[g]},g))})]})]})]})}function w3(e){return e.slice(0,10)}function E3(e){return e.slice(0,5)}function k3(e){return(e.includes("T")?e:e.replace(" ","T")).slice(0,16)}function T3({value:e,busy:t,onCommit:r,unit:n,min:s,max:a,step:c,precision:d}){const[u,f]=(0,l.useState)(uo(e,d)),h=Number(u),m=u!==""&&!Number.isNaN(h),g=c??1,p=S=>{let E=S;return s!==void 0&&(E=Math.max(s,E)),a!==void 0&&(E=Math.min(a,E)),E},y=()=>{!t&&m&&r(p(h))};return(0,i.jsxs)("div",{className:"inline-flex items-center gap-1",children:[(0,i.jsx)("button",{type:"button","aria-label":"Decrement",disabled:t,onClick:S=>{if(S.stopPropagation(),!t){const E=p(e-g);f(uo(E,d)),r(E)}},className:A("inline-flex h-5 w-5 items-center justify-center rounded border border-border bg-surface text-xs transition-colors hover:bg-surface-hover",t&&"opacity-40 cursor-not-allowed"),children:"−"}),(0,i.jsx)("input",{"aria-label":"Numeric value",type:"number",disabled:t,value:u,onChange:S=>{f(S.target.value);const E=Number(S.target.value);S.target.value!==""&&!Number.isNaN(E)&&(t||r(p(E)))},onBlur:y,onKeyDown:S=>{S.key==="Enter"&&y()},className:A("w-16 rounded border border-border bg-surface px-1 py-0.5 text-xs tabular-nums text-center",t&&"opacity-40 cursor-not-allowed")}),n!==void 0&&(0,i.jsx)("span",{className:"text-foreground-subtle text-xs",children:n}),(0,i.jsx)("button",{type:"button","aria-label":"Increment",disabled:t,onClick:S=>{if(S.stopPropagation(),!t){const E=p(e+g);f(uo(E,d)),r(E)}},className:A("inline-flex h-5 w-5 items-center justify-center rounded border border-border bg-surface text-xs transition-colors hover:bg-surface-hover",t&&"opacity-40 cursor-not-allowed"),children:"+"})]})}function C3({value:e,busy:t,onCommit:r}){const[n,s]=(0,l.useState)(e);return(0,i.jsx)("input",{type:"text",disabled:t,value:n,onChange:a=>s(a.target.value),onBlur:()=>{t||r(n)},onKeyDown:a=>{a.key==="Enter"&&!t&&r(n)},className:A("rounded border border-border bg-surface px-2 py-0.5 text-xs",t&&"opacity-40 cursor-not-allowed")})}function I3({slice:e,busy:t,setValueFn:r,layout:n}){switch(e.kind){case"numeric":return(0,i.jsx)(T3,{value:typeof e.value=="number"?e.value:Number(e.value),busy:t,onCommit:s=>{r({control:{kind:"numeric",value:s}})},unit:e.unit,min:e.min,max:e.max,step:e.step,precision:e.precision});case"select":return(0,i.jsx)("select",{"aria-label":"Control value",disabled:t,value:String(e.value),onChange:s=>{s.stopPropagation(),t||r({control:{kind:"select",value:s.target.value}})},className:A("w-full max-w-full min-w-0 truncate rounded border border-border bg-surface px-1 py-0.5 text-xs",t&&"opacity-40 cursor-not-allowed"),children:e.options.map(s=>(0,i.jsx)("option",{value:s,children:s},s))});case"text":return(0,i.jsx)(C3,{value:String(e.value),busy:t,onCommit:s=>{r({control:{kind:"text",value:s}})}});case"datetime":{const s=String(e.value),a=e.format??"datetime";return n==="compact"?s===""?(0,i.jsx)("span",{"aria-label":"Control value",className:"text-xs text-foreground-subtle",children:"—"}):(0,i.jsx)("span",{"aria-label":"Control value",className:"text-xs text-foreground",children:il(s,a)}):(0,i.jsx)("input",{type:a==="date"?"date":a==="time"?"time":"datetime-local","aria-label":"Control value",disabled:t,value:a==="date"?w3(s):a==="time"?E3(s):k3(s),onChange:c=>{c.stopPropagation(),t||r({control:{kind:"datetime",value:c.target.value}})},className:A("rounded border border-border bg-surface px-1 py-0.5 text-xs",t&&"opacity-40 cursor-not-allowed")})}default:return null}}function zf({trpc:e,deviceId:t,features:r,layout:n,optimistic:s}){const{cap:a,slice:c,available:d}=bt({trpc:e,deviceId:t,cap:g=>g.control,slice:g=>g.state.control}),{display:u,applyOptimistic:f}=Zt(c,{enabled:s??!0});if(u===void 0)return null;const h=!d,m=g=>{!h&&a&&(f({value:g.control.value}),a.setValue(g))};return(0,i.jsx)("div",{"data-kind":u.kind,className:"inline-flex min-w-0 max-w-full items-center gap-1 rounded border border-border px-2 py-1 transition-colors",children:(0,i.jsx)(I3,{slice:u,busy:h,setValueFn:m,layout:n})})}var P3=5,A3=35;function Gf(e,t,r){return Math.min(1,Math.max(0,(e-t)/(r-t)))}function Zf(e,t,r){return Math.round(t+e*(r-t))}var Bn=176,Ol=76,Fl=2*Math.PI*Ol,mo=Fl*(270/360),Vf=Bn/2-Ol-10;function _b(e){const t=Bn/2,r=Bn/2,n=Fl-mo,s=e.mode==="band"?(()=>{const a=e.band.from*mo,c=Math.max(0,(e.band.to-e.band.from)*mo);return{dasharray:`${c} ${Fl-c}`,dashoffset:-a}})():(()=>{const a=e.fraction*mo;return{dasharray:`${a} ${Fl-a}`,dashoffset:void 0}})();return(0,i.jsxs)("svg",{width:Bn,height:Bn,viewBox:`0 0 ${Bn} ${Bn}`,"aria-hidden":"true",className:"absolute inset-0",style:{transform:"rotate(135deg)"},children:[(0,i.jsx)("circle",{cx:t,cy:r,r:Ol,fill:"none",stroke:"var(--color-border)",strokeWidth:12,strokeDasharray:`${mo} ${n}`,strokeLinecap:"round"}),(0,i.jsx)("circle",{cx:t,cy:r,r:Ol,fill:"none",stroke:e.color,strokeWidth:12,strokeDasharray:s.dasharray,...s.dashoffset!==void 0?{strokeDashoffset:s.dashoffset}:{},strokeLinecap:"round"})]})}var j3={heat:"#f59e0b",cool:"#60a5fa",auto:"#c084fc",heat_cool:"#e879f9",fan_only:"#94a3b8",dry:"#22d3ee",off:"#d4d4d8"};function wb({trpc:e,deviceId:t,features:r,optimistic:n}){const{cap:s,slice:a,available:c}=bt({trpc:e,deviceId:t,cap:T=>T.climateControl,slice:T=>T.state.climateControl}),{display:d,applyOptimistic:u}=Zt(a,{enabled:n??!0});if(s===void 0||d===void 0)return null;const f=!c,h=j3[d.mode],m=d.mode==="heat_cool"||d.targetLow!==null&&d.targetHigh!==null,g=P3,p=A3,y=!m&&d.target!==null?Gf(d.target,g,p):0,S=m&&d.targetLow!==null?Gf(d.targetLow,g,p):0,E=m&&d.targetHigh!==null?Gf(d.targetHigh,g,p):0;return(0,i.jsxs)("div",{"data-mode":d.mode,className:A("flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4 transition-colors",Bf[d.mode]),children:[(0,i.jsxs)("div",{className:"flex flex-col items-center gap-3",children:[(0,i.jsxs)("div",{className:"relative",style:{width:Bn,height:Bn},children:[m?(0,i.jsx)(_b,{mode:"band",band:{from:S,to:E},color:h}):(0,i.jsx)(_b,{mode:"fill",fraction:y,color:h}),m?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("div",{"data-testid":"arc-knob",children:(0,i.jsx)(lo,{fraction:S,color:h,knobTopPx:Vf,onDragFraction:T=>{if(f||d.targetHigh===null)return;const j=Math.min(Zf(T,g,p),d.targetHigh);u({targetLow:j}),s.setTargetRange({targetLow:j,targetHigh:d.targetHigh})}})}),(0,i.jsx)("div",{"data-testid":"arc-knob",children:(0,i.jsx)(lo,{fraction:E,color:h,knobTopPx:Vf,onDragFraction:T=>{if(f||d.targetLow===null)return;const j=Math.max(Zf(T,g,p),d.targetLow);u({targetHigh:j}),s.setTargetRange({targetLow:d.targetLow,targetHigh:j})}})})]}):(0,i.jsx)("div",{"data-testid":"arc-knob",children:(0,i.jsx)(lo,{fraction:y,color:h,knobTopPx:Vf,onDragFraction:T=>{if(f)return;const j=Zf(T,g,p);u({target:j}),s.setTarget({target:j})}})}),(0,i.jsxs)("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none",children:[(0,i.jsxs)("div",{"data-testid":"current-temp",className:"text-4xl font-bold tabular-nums text-foreground leading-none",children:[d.currentTemp!==null?d.currentTemp:"—",(0,i.jsx)("span",{className:"text-lg text-foreground-subtle font-normal ml-0.5",children:"°"})]}),!m&&d.target!==null&&(0,i.jsxs)("div",{className:"text-xs font-semibold",style:{color:h},children:["set ",d.target,"°"]}),m&&d.targetLow!==null&&d.targetHigh!==null&&(0,i.jsxs)("div",{className:"text-xs font-semibold",style:{color:h},children:[d.targetLow,"° – ",d.targetHigh,"°"]})]})]}),!m&&d.target!==null&&(0,i.jsx)("div",{className:"w-[200px]",children:(0,i.jsx)(wf,{value:`${d.target}°`,onDelta:T=>{if(f||d.target===null)return;const j=d.target+T;u({target:j}),s.setTarget({target:j})}})})]}),(0,i.jsx)("select",{"aria-label":"Mode",value:d.mode,disabled:f,onChange:T=>{T.stopPropagation();const j=T.target.value;!f&&j&&(u({mode:d.availableModes.find(N=>N===j)??d.mode}),s.setMode({mode:d.availableModes.find(N=>N===j)??d.mode}))},className:A("w-full rounded border border-border bg-surface px-3 py-1.5 text-sm",f&&"opacity-40 cursor-not-allowed"),children:d.availableModes.map(T=>(0,i.jsx)("option",{value:T,children:T},T))})]})}function N3(e){return e==="locked"||e==="locking"}function Eb(e){return e==="jammed"}var D3={locked:{colorClass:"border-success/30 bg-success/10 text-success",icon:"locked"},locking:{colorClass:"border-success/30 bg-success/10 text-success",icon:"locked"},unlocked:{colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"open"},unlocking:{colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"open"},jammed:{colorClass:"border-danger/30 bg-danger/10 text-danger",icon:"locked"}};function M3({state:e}){const t=D3[e];return(0,i.jsx)("div",{"data-testid":"lock-glyph","data-state":e,className:A("flex h-16 w-16 items-center justify-center rounded-full border-2",t.colorClass),children:t.icon==="locked"?(0,i.jsx)(Hd,{className:"h-8 w-8","aria-hidden":"true"}):(0,i.jsx)(Vd,{className:"h-8 w-8","aria-hidden":"true"})})}function $3({state:e}){return(0,i.jsx)("span",{className:A("text-sm font-medium capitalize",Eb(e)?"text-danger":"text-foreground-muted"),children:e})}function R3({busy:e,onOpen:t}){return(0,i.jsxs)("button",{type:"button","aria-label":"Open (unlatch)",title:"Open (unlatch)",disabled:e,onClick:r=>{r.stopPropagation(),t()},className:A("inline-flex items-center gap-1.5 rounded-md border border-border px-3 py-1.5 text-xs font-medium","text-foreground-muted hover:bg-surface-hover transition-colors",e&&"opacity-40 cursor-not-allowed"),children:[(0,i.jsx)(Ya,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Open"]})}function kb({trpc:e,deviceId:t,features:r,optimistic:n}){const{cap:s,slice:a,available:c}=bt({trpc:e,deviceId:t,cap:S=>S.lockControl,slice:S=>S.state.lockControl}),{display:d,applyOptimistic:u}=Zt(a,{enabled:n??!0});if(s===void 0||d===void 0)return null;const f=N3(d.state),h=Eb(d.state)||!c,m=r?.includes(W.DeviceFeature.LockOpen)===!0,g=()=>{h||(f?(u({state:"unlocking"}),s.unlock({})):(u({state:"locking"}),s.lock({})))},p=()=>{h||s.open({})},y=f?"Unlock":"Lock";return(0,i.jsxs)("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsxs)("div",{className:"flex flex-col items-center gap-2",children:[(0,i.jsx)(M3,{state:d.state}),(0,i.jsx)($3,{state:d.state})]}),(0,i.jsx)("div",{className:A(h&&"pointer-events-none opacity-40"),children:(0,i.jsx)(e0,{on:f,targetLabel:y,onConfirm:g})}),m&&(0,i.jsx)("div",{className:"flex justify-center",children:(0,i.jsx)(R3,{busy:h,onOpen:p})})]})}var zn=150,Ul=64,L3=zn/2,Hf=2*Math.PI*Ul,Kf=Hf*(270/360);function Wf({fraction:e,color:t,children:r,onDragFraction:n}){const s=Math.min(1,Math.max(0,e)),a=zn/2,c=zn/2,d=Hf-Kf,u=s*Kf;return(0,i.jsxs)("div",{className:"relative",style:{width:zn,height:zn},children:[(0,i.jsxs)("svg",{width:zn,height:zn,viewBox:`0 0 ${zn} ${zn}`,"aria-hidden":"true",className:"absolute inset-0",style:{transform:"rotate(135deg)"},children:[(0,i.jsx)("circle",{cx:a,cy:c,r:Ul,fill:"none",stroke:"var(--color-border)",strokeWidth:11,strokeDasharray:`${Kf} ${d}`,strokeLinecap:"round"}),(0,i.jsx)("circle",{cx:a,cy:c,r:Ul,fill:"none",stroke:t,strokeWidth:11,strokeDasharray:`${u} ${Hf-u}`,strokeLinecap:"round"})]}),(0,i.jsx)("div",{"data-testid":"arc-knob",children:(0,i.jsx)(lo,{fraction:s,color:t,knobTopPx:L3-Ul-10,...n!==void 0?{onDragFraction:n}:{}})}),(0,i.jsx)("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-0.5 pointer-events-none",children:r})]})}function Bl({on:e,busy:t,onToggle:r}){const n={transform:e?"translateX(30px)":"translateX(3px)"};return(0,i.jsx)("button",{type:"button","aria-pressed":e,title:e?"Turn off":"Turn on",disabled:t,onClick:s=>{s.stopPropagation(),r()},className:A("relative inline-flex h-8 w-16 items-center rounded-full border transition-colors flex-shrink-0",e?"bg-success/30 border-success/50":"bg-surface-hover border-border",t&&"opacity-60 cursor-not-allowed"),children:(0,i.jsx)("span",{className:A("absolute h-6 w-6 rounded-full transition-all",e?"bg-success":"bg-foreground-subtle"),style:n})})}var qf=500,Tb=150,O3="linear-gradient(90deg, #9ec9ff, #ffffff, #ffb24d)";function F3(e,t,r){return Math.min(1,Math.max(0,(e-t)/(r-t)))}function U3(e){return F3(e,Tb,qf)}var B3="#f4b740",z3="#d4d4d8";function Cb({trpc:e,deviceId:t,features:r,optimistic:n}){const s=bt({trpc:e,deviceId:t,cap:O=>O.switch,slice:O=>O.state.switch}),a=bt({trpc:e,deviceId:t,cap:O=>O.brightness,slice:O=>O.state.brightness}),c=bt({trpc:e,deviceId:t,cap:O=>O.color,slice:O=>O.state.color}),d=Zt(s.slice,{enabled:n??!0}),u=Zt(a.slice,{enabled:n??!0}),f=Zt(c.slice,{enabled:n??!0});if(s.cap===void 0||d.display===void 0)return null;const h=d.display.on===!0,m=!s.available,g=u.display?.percentage??0,p=!a.available,y=h?g/100:0,S=h?B3:z3,E=(r?.includes(W.DeviceFeature.LightColorMired)??!1)&&c.cap!==void 0,T=f.display?.mireds,j=!c.available,N=()=>{if(m)return;const O=!h;d.applyOptimistic({on:O}),s.cap?.setState({on:O})};return(0,i.jsxs)("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsxs)("div",{className:"flex flex-col items-center gap-3",children:[(0,i.jsxs)(Wf,{fraction:y,color:S,children:[(0,i.jsxs)("div",{"data-testid":"brightness-readout",className:"text-3xl font-bold tabular-nums text-foreground leading-none",children:[g,(0,i.jsx)("span",{className:"text-base text-foreground-subtle font-normal ml-0.5",children:"%"})]}),(0,i.jsx)(Zd,{className:"h-5 w-5 text-foreground-subtle","aria-hidden":"true"})]}),a.cap!==void 0&&(0,i.jsxs)("label",{className:"flex w-full items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{className:"w-16",children:"Brightness"}),(0,i.jsx)("input",{"aria-label":"Brightness",type:"range",min:0,max:100,step:1,className:"flex-1",value:g,disabled:p||!h,onChange:O=>{const U=Number(O.target.value);u.applyOptimistic({percentage:U}),p||a.cap?.setBrightness({percentage:U})}}),(0,i.jsxs)("span",{className:"tabular-nums w-9 text-right",children:[g,"%"]})]})]}),(0,i.jsxs)("div",{className:"flex items-center justify-between",children:[(0,i.jsx)("span",{className:"text-sm font-medium text-foreground-muted",children:h?"On":"Off"}),(0,i.jsx)(Bl,{on:h,busy:m,onToggle:N})]}),E&&(0,i.jsxs)("div",{className:"flex items-center gap-2","data-testid":"color-temp-strip",children:[(0,i.jsx)(Jd,{className:"h-4 w-4 text-foreground-subtle","aria-hidden":"true"}),(0,i.jsxs)("label",{className:"flex-1",children:[(0,i.jsx)("span",{className:"sr-only",children:"Colour temperature"}),(0,i.jsx)("input",{"aria-label":"Colour temperature",type:"range",min:Tb,max:qf,step:1,className:"w-full",value:T??qf,disabled:j||!h,onChange:O=>{const U=Number(O.target.value);f.applyOptimistic({mode:"mired",mireds:U}),j||c.cap?.setColor({color:{mode:"mired",mireds:U}})}}),(0,i.jsx)("div",{className:"pointer-events-none mt-1",children:(0,i.jsx)($l,{fraction:T!==void 0?U3(T):.5,color:O3})})]})]})]})}var G3="#3aa6a0",Z3="#d4d4d8";function Ib({trpc:e,deviceId:t,features:r,optimistic:n}){const s=bt({trpc:e,deviceId:t,cap:G=>G.switch,slice:G=>G.state.switch}),a=bt({trpc:e,deviceId:t,cap:G=>G.fanControl,slice:G=>G.state.fanControl}),c=Zt(s.slice,{enabled:n??!0}),d=Zt(a.slice,{enabled:n??!0});if(s.cap===void 0||c.display===void 0)return null;const u=c.display.on===!0,f=!s.available,h=d.display?.percentage??0,m=!a.available,g=u?h/100:0,p=u?G3:Z3,y=r?.includes(W.DeviceFeature.FanSpeed)??!1,S=(r?.includes(W.DeviceFeature.FanOscillating)??!1)&&a.cap!==void 0,E=d.display?.availablePresets??[],T=(r?.includes(W.DeviceFeature.FanPreset)??!1)&&a.cap!==void 0&&E.length>0,j=d.display?.preset??"",N=d.display?.oscillating===!0,O=()=>{if(f)return;const G=!u;c.applyOptimistic({on:G}),s.cap?.setState({on:G})},U=()=>{if(m)return;const G=!N;d.applyOptimistic({oscillating:G}),a.cap?.setOscillating({oscillating:G})},z=G=>{if(m)return;const X=d.display;if(X===void 0)return;const te=X.percentageStep!==void 0&&X.percentageStep>0?X.percentageStep:1,ne=Math.min(100,Math.max(0,Math.round(G*100/te)*te));d.applyOptimistic({percentage:ne}),a.cap?.setPercentage({percentage:ne})},K=G=>{m||G===""||(d.applyOptimistic({preset:G}),a.cap?.setPreset({preset:G}))};return(0,i.jsxs)("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-4",children:[(0,i.jsx)("div",{className:"flex flex-col items-center gap-3",children:y?(0,i.jsxs)(Wf,{fraction:g,color:p,onDragFraction:z,children:[(0,i.jsxs)("div",{"data-testid":"speed-readout",className:"text-3xl font-bold tabular-nums text-foreground leading-none",children:[h,(0,i.jsx)("span",{className:"text-base text-foreground-subtle font-normal ml-0.5",children:"%"})]}),(0,i.jsx)(Gd,{className:"h-5 w-5 text-foreground-subtle","aria-hidden":"true"})]}):(0,i.jsx)("div",{"data-testid":"fan-onoff-icon",className:"flex h-[150px] w-[150px] items-center justify-center",children:(0,i.jsx)(Gd,{className:"h-16 w-16",style:{color:p},"aria-hidden":"true"})})}),T&&(0,i.jsx)("div",{className:"flex justify-center",children:(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{children:"Preset"}),(0,i.jsxs)("select",{"aria-label":"Fan preset",value:j,disabled:m,onChange:G=>{G.stopPropagation(),K(G.target.value)},className:A("bg-surface border border-border rounded px-1 py-0.5",m&&"opacity-40 cursor-not-allowed"),children:[(0,i.jsx)("option",{value:"",disabled:!0,children:"—"}),E.map(G=>(0,i.jsx)("option",{value:G,children:G},G))]})]})}),(0,i.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[S?(0,i.jsxs)("button",{type:"button","aria-label":"Oscillate","aria-pressed":N,disabled:m,onClick:G=>{G.stopPropagation(),U()},className:A("inline-flex items-center gap-1.5 rounded-md border px-3 py-1.5 text-xs font-medium transition-colors",N?"border-success/50 bg-success/10 text-success":"border-border text-foreground-muted hover:bg-surface-hover",m&&"opacity-40 cursor-not-allowed"),children:[(0,i.jsx)(Ii,{className:"h-3.5 w-3.5","aria-hidden":"true"}),"Oscillate"]}):(0,i.jsx)("span",{className:"text-sm font-medium text-foreground-muted",children:u?"On":"Off"}),(0,i.jsx)(Bl,{on:u,busy:f,onToggle:O})]})]})}function Pb({trpc:e,deviceId:t,optimistic:r}){const{cap:n,slice:s,available:a}=bt({trpc:e,deviceId:t,cap:m=>m.switch,slice:m=>m.state.switch}),{display:c,applyOptimistic:d}=Zt(s,{enabled:r??!0});if(n===void 0||c===void 0)return null;const u=c.on===!0,f=!a,h=()=>{if(f)return;const m=!u;d({on:m}),n.setState({on:m})};return(0,i.jsxs)("div",{className:"flex flex-col items-center gap-4 rounded-lg border border-border bg-surface p-6",children:[(0,i.jsx)("div",{"data-testid":"switch-glyph","data-state":u?"on":"off",className:A("flex h-16 w-16 items-center justify-center rounded-full border-2 transition-colors",u?"border-success/30 bg-success/10 text-success":"border-border bg-surface-subtle text-foreground-subtle"),children:(0,i.jsx)(yl,{className:"h-8 w-8","aria-hidden":"true"})}),(0,i.jsx)("span",{className:"text-sm font-medium text-foreground-muted",children:u?"On":"Off"}),(0,i.jsx)(Bl,{on:u,busy:f,onToggle:h})]})}function V3(e){return e==="playing"||e==="buffering"?"pause":"play"}function H3(e,t){return e===null||t===null||t<=0?0:Math.min(1,Math.max(0,e/t))}function Ab(e){if(e===null)return"--:--";const t=Math.floor(e/1e3);return`${Math.floor(t/60)}:${(t%60).toString().padStart(2,"0")}`}function K3({title:e,subtitle:t}){return(0,i.jsxs)("div",{className:"flex flex-col items-center gap-1 text-center",children:[(0,i.jsx)(hC,{className:"h-6 w-6 text-foreground-subtle","aria-hidden":"true"}),(0,i.jsx)("span",{className:"text-base font-semibold text-foreground line-clamp-1",children:e??"Nothing playing"}),t&&(0,i.jsx)("span",{className:"text-xs text-foreground-subtle line-clamp-1",children:t})]})}function Qf({label:e,busy:t,onPress:r,children:n,primary:s}){return(0,i.jsx)("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:a=>{a.stopPropagation(),t||r()},className:A("inline-flex items-center justify-center rounded-full transition-colors",s?"h-12 w-12 bg-primary text-primary-foreground hover:bg-primary/90 shadow-md":"h-10 w-10 text-foreground-muted hover:bg-surface-hover",t&&"opacity-40 cursor-not-allowed"),children:n})}function jb({trpc:e,deviceId:t,features:r,optimistic:n}){const{cap:s,slice:a,available:c}=bt({trpc:e,deviceId:t,cap:N=>N.mediaPlayer,slice:N=>N.state.mediaPlayer}),{display:d,applyOptimistic:u}=Zt(a,{enabled:n??!0});if(s===void 0||d===void 0)return null;const f=!c,h=V3(d.state),m=(r?.includes(W.DeviceFeature.MediaPlayerSeek)??!1)&&d.durationMs!==null&&d.durationMs>0,g=r?.includes(W.DeviceFeature.MediaPlayerNext)??!1,p=r?.includes(W.DeviceFeature.MediaPlayerPrevious)??!1,y=(r?.includes(W.DeviceFeature.MediaPlayerVolume)??!1)&&d.volumeLevel!==null,S=()=>{f||(h==="play"?(u({state:"playing"}),s.play({})):(u({state:"paused"}),s.pause({})))},E=d.currentMedia?.artist??d.currentMedia?.album??null,T=H3(d.positionMs,d.durationMs),j=d.volumeLevel??0;return(0,i.jsxs)("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6",children:[(0,i.jsx)(K3,{title:d.currentMedia?.title??null,subtitle:E}),m&&(0,i.jsxs)("div",{"data-testid":"media-seek",className:"flex flex-col gap-1",children:[(0,i.jsxs)("label",{className:"relative block",children:[(0,i.jsx)("span",{className:"sr-only",children:"Seek"}),(0,i.jsx)("input",{"aria-label":"Seek",type:"range",min:0,max:d.durationMs??0,step:1e3,className:"absolute inset-0 h-4 w-full cursor-pointer opacity-0",value:d.positionMs??0,disabled:f,onChange:N=>{if(f)return;const O=Number(N.target.value);u({positionMs:O}),s.seek({positionMs:O})}}),(0,i.jsx)("div",{className:"pointer-events-none",children:(0,i.jsx)($l,{fraction:T})})]}),(0,i.jsxs)("div",{className:"flex justify-between text-[11px] tabular-nums text-foreground-subtle",children:[(0,i.jsx)("span",{children:Ab(d.positionMs)}),(0,i.jsx)("span",{children:Ab(d.durationMs)})]})]}),(0,i.jsxs)("div",{className:"flex items-center justify-center gap-4",children:[p&&(0,i.jsx)(Qf,{label:"Previous",busy:f,onPress:()=>void s.previous({}),children:(0,i.jsx)(CC,{className:"h-5 w-5","aria-hidden":"true"})}),(0,i.jsx)(Qf,{label:h==="play"?"Play":"Pause",busy:f,onPress:S,primary:!0,children:h==="play"?(0,i.jsx)(Fn,{className:"h-6 w-6","aria-hidden":"true"}):(0,i.jsx)(to,{className:"h-6 w-6","aria-hidden":"true"})}),g&&(0,i.jsx)(Qf,{label:"Next",busy:f,onPress:()=>void s.next({}),children:(0,i.jsx)(IC,{className:"h-5 w-5","aria-hidden":"true"})})]}),y&&(0,i.jsxs)("div",{"data-testid":"media-volume",className:"flex items-center gap-2",children:[(0,i.jsx)("button",{type:"button","aria-label":d.isMuted===!0?"Unmute":"Mute",title:d.isMuted===!0?"Unmute":"Mute",disabled:f,onClick:N=>{if(N.stopPropagation(),f||d.isMuted===null)return;const O=!d.isMuted;u({isMuted:O}),s.setMute({muted:O})},className:A("inline-flex h-7 w-7 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",f&&"opacity-40 cursor-not-allowed"),children:d.isMuted===!0?(0,i.jsx)(OC,{className:"h-4 w-4","aria-hidden":"true"}):(0,i.jsx)(tf,{className:"h-4 w-4","aria-hidden":"true"})}),(0,i.jsxs)("label",{className:"relative block flex-1",children:[(0,i.jsx)("span",{className:"sr-only",children:"Volume"}),(0,i.jsx)("input",{"aria-label":"Volume",type:"range",min:0,max:100,step:1,className:"absolute inset-0 h-4 w-full cursor-pointer opacity-0",value:j,disabled:f,onChange:N=>{if(f)return;const O=Number(N.target.value);u({volumeLevel:O}),s.setVolume({volumeLevel:O})}}),(0,i.jsx)("div",{className:"pointer-events-none",children:(0,i.jsx)($l,{fraction:j/100})})]}),(0,i.jsxs)("span",{className:"w-9 text-right text-[11px] tabular-nums text-foreground-subtle",children:[j,"%"]})]})]})}var W3={disarmed:{label:"Disarmed",colorClass:"border-border bg-surface-subtle text-foreground-subtle",icon:"disarmed"},armed_home:{label:"Armed Home",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_away:{label:"Armed Away",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_night:{label:"Armed Night",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_vacation:{label:"Armed Vacation",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},armed_custom_bypass:{label:"Armed (Bypass)",colorClass:"border-success/30 bg-success/10 text-success",icon:"armed"},arming:{label:"Arming…",colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"pending"},disarming:{label:"Disarming…",colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"pending"},pending:{label:"Pending",colorClass:"border-warning/30 bg-warning/10 text-warning",icon:"pending"},triggered:{label:"Triggered",colorClass:"border-danger/30 bg-danger/10 text-danger",icon:"triggered"}},q3={home:"Home",away:"Away",night:"Night",vacation:"Vacation",custom_bypass:"Bypass"};function Q3(e){return e.startsWith("armed_")}function Y3(e){return e==="arming"||e==="disarming"}function X3({icon:e}){return e==="disarmed"?(0,i.jsx)(kC,{className:"h-8 w-8","aria-hidden":"true"}):e==="triggered"?(0,i.jsx)(Qd,{className:"h-8 w-8","aria-hidden":"true"}):e==="pending"?(0,i.jsx)(Gp,{className:"h-8 w-8","aria-hidden":"true"}):(0,i.jsx)(EC,{className:"h-8 w-8","aria-hidden":"true"})}function Nb({label:e,active:t,busy:r,onSelect:n}){return(0,i.jsx)("button",{type:"button","aria-label":e,"aria-pressed":t,disabled:r,onClick:s=>{s.stopPropagation(),r||n()},className:A("flex-1 rounded-md px-3 py-2 text-sm font-medium transition-colors",t?"bg-primary text-primary-foreground shadow-sm":"text-foreground-muted hover:bg-surface-hover",r&&"opacity-40 cursor-not-allowed"),children:e})}function Db({state:e,availableModes:t,busy:r,onDisarm:n,onArm:s}){const a=Q3(e),c=Y3(e);return(0,i.jsxs)("div",{className:"flex items-stretch gap-1 rounded-lg border border-border bg-surface-subtle p-1",children:[(0,i.jsx)(Nb,{label:"Disarm",active:!a&&!c,busy:r,onSelect:n}),t.map(d=>(0,i.jsx)(Nb,{label:q3[d],active:!c&&e===`armed_${d}`,busy:r,onSelect:()=>s(d)},d))]})}function Mb(e,t,r){const{cap:n,slice:s,available:a}=bt({trpc:e,deviceId:t,cap:m=>m.alarmPanel,slice:m=>m.state.alarmPanel}),{display:c,applyOptimistic:d}=Zt(s,{enabled:r??!0}),u=!a;return{display:c,capPresent:n!==void 0,busy:u,handleDisarm:()=>{n===void 0||u||(d({state:"disarming"}),n.disarm({}))},handleArm:m=>{n===void 0||u||(d({state:"arming"}),n.arm({mode:m}))}}}function $b({trpc:e,deviceId:t,optimistic:r}){const{display:n,capPresent:s,busy:a,handleDisarm:c,handleArm:d}=Mb(e,t,r);return!s||n===void 0?null:(0,i.jsx)(Db,{state:n.state,availableModes:n.availableModes,busy:a,onDisarm:c,onArm:d})}function Rb({trpc:e,deviceId:t,optimistic:r}){const{display:n,capPresent:s,busy:a,handleDisarm:c,handleArm:d}=Mb(e,t,r);if(!s||n===void 0)return null;const u=W3[n.state];return(0,i.jsxs)("div",{className:"flex flex-col items-stretch gap-4 rounded-lg border border-border bg-surface p-6",children:[(0,i.jsxs)("div",{className:"flex flex-col items-center gap-2",children:[(0,i.jsx)("div",{"data-testid":"alarm-state","data-state":n.state,className:A("flex h-16 w-16 items-center justify-center rounded-full border-2",u.colorClass),children:(0,i.jsx)(X3,{icon:u.icon})}),(0,i.jsx)("span",{className:"text-sm font-medium text-foreground-muted",children:u.label})]}),(0,i.jsx)(Db,{state:n.state,availableModes:n.availableModes,busy:a,onDisarm:c,onArm:d})]})}function J3({children:e}){return(0,i.jsx)("div",{className:"flex flex-col items-stretch gap-3 rounded-lg border border-border bg-surface p-4",children:e})}function Lb(e,t){const{cap:r}=bt({trpc:e,deviceId:t,cap:n=>n.switch,slice:n=>n.state.switch});return r!==void 0}function Ob({trpc:e,deviceId:t,features:r,optimistic:n}){return Lb(e,t)?(0,i.jsx)(Ll,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}):null}function eF(e,t){const{cap:r}=bt({trpc:e,deviceId:t,cap:n=>n.lockControl,slice:n=>n.state.lockControl});return r!==void 0}function Fb({trpc:e,deviceId:t,features:r,optimistic:n}){return eF(e,t)?(0,i.jsx)(gb,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}):null}function Ub({trpc:e,deviceId:t,features:r,optimistic:n}){return Lb(e,t)?(0,i.jsxs)("div",{className:"inline-flex items-center gap-2",children:[(0,i.jsx)(Ll,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}),(0,i.jsx)(pb,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n})]}):null}function tF(e,t){const{cap:r}=bt({trpc:e,deviceId:t,cap:n=>n.fanControl,slice:n=>n.state.fanControl});return r!==void 0}function Bb({trpc:e,deviceId:t,features:r,optimistic:n}){return tF(e,t)?(0,i.jsxs)("div",{className:"inline-flex items-center gap-2",children:[(0,i.jsx)(Ll,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}),(0,i.jsx)(vb,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n})]}):null}function rF(e,t){const{cap:r}=bt({trpc:e,deviceId:t,cap:n=>n.climateControl,slice:n=>n.state.climateControl});return r!==void 0}function zb({trpc:e,deviceId:t,features:r,optimistic:n}){return rF(e,t)?(0,i.jsx)(bb,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}):null}function nF(e,t){const{cap:r}=bt({trpc:e,deviceId:t,cap:n=>n.mediaPlayer,slice:n=>n.state.mediaPlayer});return r!==void 0}function Gb({trpc:e,deviceId:t,features:r,optimistic:n}){return nF(e,t)?(0,i.jsx)(Sb,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}):null}function Zb(e,t){const{cap:r}=bt({trpc:e,deviceId:t,cap:n=>n.control,slice:n=>n.state.control});return r!==void 0}function Vb({trpc:e,deviceId:t,features:r,optimistic:n}){return Zb(e,t)?(0,i.jsx)(zf,{trpc:e,deviceId:t,features:r,layout:"compact",optimistic:n}):null}function Hb({trpc:e,deviceId:t,features:r,optimistic:n}){return Zb(e,t)?(0,i.jsx)(J3,{children:(0,i.jsx)(zf,{trpc:e,deviceId:t,features:r,layout:"full",optimistic:n})}):null}var iF={InlineControl:s0,HeroCard:o0},ai={InlineControl:l0,HeroCard:Tf},Kb={InlineControl:D0,HeroCard:M0},sF={InlineControl:W5,HeroCard:q5},Wb={InlineControl:Ob,HeroCard:Pb},aF={InlineControl:Fb,HeroCard:kb},oF={InlineControl:Ub,HeroCard:Cb},lF={InlineControl:Bb,HeroCard:Ib},cF={InlineControl:zb,HeroCard:wb},uF={InlineControl:Gb,HeroCard:jb},dF={InlineControl:$b,HeroCard:Rb},fF={InlineControl:Vb,HeroCard:Hb},hF={InlineControl:B0,HeroCard:z0},mF={InlineControl:H0,HeroCard:K0},gF={InlineControl:Y0,HeroCard:X0},pF={InlineControl:tb,HeroCard:rb},vF={InlineControl:ab,HeroCard:ob},bF={InlineControl:cb,HeroCard:ub},yF={InlineControl:hb,HeroCard:mb},qb={[W.DeviceType.Cover]:iF,[W.DeviceType.Valve]:gF,[W.DeviceType.Humidifier]:pF,[W.DeviceType.WaterHeater]:vF,[W.DeviceType.Camera]:ai,[W.DeviceType.Hub]:ai,[W.DeviceType.Switch]:Wb,[W.DeviceType.Siren]:Wb,[W.DeviceType.Light]:oF,[W.DeviceType.Fan]:lF,[W.DeviceType.Sensor]:Kb,[W.DeviceType.Thermostat]:cF,[W.DeviceType.Button]:{InlineControl:r0,HeroCard:n0},[W.DeviceType.EventEmitter]:ai,[W.DeviceType.Update]:sF,[W.DeviceType.Generic]:ai,[W.DeviceType.Notifier]:ai,[W.DeviceType.Script]:ai,[W.DeviceType.Automation]:ai,[W.DeviceType.Lock]:aF,[W.DeviceType.MediaPlayer]:uF,[W.DeviceType.AlarmPanel]:dF,[W.DeviceType.Control]:fF,[W.DeviceType.Presence]:Kb,[W.DeviceType.Weather]:bF,[W.DeviceType.Vacuum]:hF,[W.DeviceType.LawnMower]:mF,[W.DeviceType.Container]:ai,[W.DeviceType.Image]:yF},Qb={[W.DeviceType.Cover]:!0,[W.DeviceType.Valve]:!0,[W.DeviceType.Thermostat]:!0,[W.DeviceType.Control]:!0,[W.DeviceType.Button]:!0,[W.DeviceType.MediaPlayer]:!0,[W.DeviceType.AlarmPanel]:!0,[W.DeviceType.Lock]:!1,[W.DeviceType.Vacuum]:!1,[W.DeviceType.LawnMower]:!1,[W.DeviceType.Humidifier]:!1,[W.DeviceType.Switch]:!1,[W.DeviceType.Siren]:!1,[W.DeviceType.Light]:!1,[W.DeviceType.Fan]:!1,[W.DeviceType.WaterHeater]:!1,[W.DeviceType.Sensor]:!1,[W.DeviceType.Presence]:!1,[W.DeviceType.EventEmitter]:!1,[W.DeviceType.Notifier]:!1,[W.DeviceType.Script]:!1,[W.DeviceType.Automation]:!1,[W.DeviceType.Camera]:!1,[W.DeviceType.Hub]:!1,[W.DeviceType.Update]:!1,[W.DeviceType.Generic]:!1,[W.DeviceType.Weather]:!1,[W.DeviceType.Container]:!1,[W.DeviceType.Image]:!1},Yb=new Set(Object.values(W.DeviceType));function zl(e){return Yb.has(e)?qb[e]:null}function go(e,t){return t==="table"?"fit":Yb.has(e)&&Qb[e]?Yv:t==="center"?Jv:Xv}function xF(e){return e instanceof Error?e.message:String(e)}function SF({trpc:e,deviceId:t,deviceName:r}){const{dev:n,cap:s}=bt({trpc:e,deviceId:t,cap:p=>p.reboot,slice:()=>{}}),[a,c]=(0,l.useState)(!1),[d,u]=(0,l.useState)(!1),[f,h]=(0,l.useState)(null);if(n===null||s===void 0||s===null)return null;const m=p=>{p.stopPropagation(),h(null),c(!0)},g=async()=>{if(!d){h(null),u(!0);try{await s.reboot({}),c(!1)}catch(p){h(xF(p))}finally{u(!1)}}};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("button",{type:"button",onClick:m,className:A("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors flex-shrink-0",a&&"bg-surface-hover text-foreground"),title:"Reboot device","aria-label":"Reboot device","aria-haspopup":"dialog","aria-expanded":a,children:(0,i.jsx)(Wd,{className:"h-3 w-3"})}),(0,i.jsx)(_l,{open:a,onOpenChange:p=>{d||c(p)},children:(0,i.jsxs)(no,{width:"sm",onClick:p=>p.stopPropagation(),children:[(0,i.jsxs)(wl,{children:[(0,i.jsxs)(kl,{className:"flex items-center gap-2",children:[(0,i.jsx)(Wd,{className:"h-4 w-4 text-amber-400"}),"Reboot device?"]}),(0,i.jsxs)(Tl,{children:["This will restart ",r,". It may be unavailable for a moment."]})]}),f!==null&&(0,i.jsx)("div",{className:"mt-2 px-3 py-2 rounded border border-danger/40 bg-danger/10 text-xs text-danger",children:f}),(0,i.jsxs)(El,{children:[(0,i.jsx)(tn,{type:"button",variant:"ghost",size:"sm",disabled:d,onClick:()=>{d||c(!1)},children:"Cancel"}),(0,i.jsxs)(tn,{type:"button",variant:"danger",size:"sm",disabled:d,onClick:()=>{g()},children:[d&&(0,i.jsx)(hr,{className:"h-3.5 w-3.5 animate-spin"}),"Reboot"]})]})]})})]})}var Xb=new Set([W.DeviceType.Sensor,W.DeviceType.Presence]);function Yf({trpc:e,device:t,controlPlacement:r}){const n=Dl(t.id),s=r??"right";if(t.disabled)return null;if(t.type===W.DeviceType.Container){const m=ds(n,t.linkDeviceId,t.primaryChildEntityId),g=m===null?void 0:n.find(p=>p.id===m.id);return g===void 0?null:(0,i.jsx)(_F,{trpc:e,child:g,placement:s})}const a=Xb.has(t.type),c=(a?null:zl(t.type))?.InlineControl??null,d=go(t.type,s),u=Vv(t),f=(t.features??[]).includes("rebootable"),h=(t.features??[]).includes("pan-tilt-zoom");return(0,i.jsxs)(i.Fragment,{children:[a&&(0,i.jsxs)(oo,{align:go(t.type,s),children:[u&&(0,i.jsx)(Xf,{trpc:e,deviceId:t.id,features:t.features}),(0,i.jsx)(Rl,{trpc:e,device:t})]}),c!==null&&(0,i.jsxs)(oo,{align:d,onClick:m=>m.stopPropagation(),children:[u&&(0,i.jsx)(Xf,{trpc:e,deviceId:t.id,features:t.features}),(0,i.jsx)(c,{trpc:e,deviceId:t.id,features:t.features})]}),!a&&c===null&&u&&(0,i.jsx)(Xf,{trpc:e,deviceId:t.id,features:t.features}),h&&(0,i.jsx)(kF,{trpc:e,deviceId:t.id}),f&&(0,i.jsx)(SF,{trpc:e,deviceId:t.id,deviceName:t.name})]})}function _F({trpc:e,child:t,placement:r}){if(Xb.has(t.type))return(0,i.jsx)(oo,{align:go(t.type,r),children:(0,i.jsx)(Rl,{trpc:e,device:t})});const n=zl(t.type)?.InlineControl??null;return n===null?null:(0,i.jsx)(oo,{align:go(t.type,r),onClick:s=>s.stopPropagation(),children:(0,i.jsx)(n,{trpc:e,deviceId:t.id,features:t.features})})}function Xf({trpc:e,deviceId:t,features:r}){const{dev:n,cap:s,slice:a,available:c}=bt({trpc:e,deviceId:t,cap:m=>m.motionTrigger,slice:m=>m.state.motionTrigger,requireFeature:"motion-trigger",deviceFeatures:r}),[d,u]=(0,l.useState)(!1);if(n!==null&&!s)return null;const f=a?.enabled===!0,h=async m=>{if(m.stopPropagation(),!(d||!c||!s)){u(!0);try{await s.setMotionTrigger({enabled:!f})}finally{u(!1)}}};return(0,i.jsx)("button",{type:"button",onClick:m=>{h(m)},disabled:d||!c,className:A("inline-flex h-4 w-4 items-center justify-center rounded transition-colors flex-shrink-0",f?"text-primary bg-primary/10":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover",(d||!c)&&"opacity-50"),title:c?f?"Motion-trigger: on (click to disable)":"Motion-trigger: off (click to enable)":"Awaiting state…","aria-pressed":f,children:(0,i.jsx)(wn,{className:"h-2.5 w-2.5"})})}var wF=4,EF=300;function kF({trpc:e,deviceId:t}){const r=(0,l.useRef)(null),n=(0,l.useRef)(null),[s,a]=(0,l.useState)(null),c=s!==null,d=Sf(e,t,{enabled:c}),u=()=>a(null),f=()=>{const m=r.current;if(!m)return;const g=m.getBoundingClientRect(),p=8,y=Math.min(EF,window.innerWidth-p*2),S=Math.max(p,Math.min(g.right-y,window.innerWidth-y-p)),E=g.bottom+wF;a({top:E,left:S,width:y,maxHeight:Math.max(160,window.innerHeight-E-p)})};(0,l.useEffect)(()=>{if(!c)return;const m=p=>{const y=r.current,S=n.current,E=p.target;E!==null&&(y&&y.contains(E)||S&&S.contains(E)||u())},g=p=>{p.key==="Escape"&&(p.stopPropagation(),u())};return document.addEventListener("mousedown",m),document.addEventListener("touchstart",m),document.addEventListener("keydown",g),()=>{document.removeEventListener("mousedown",m),document.removeEventListener("touchstart",m),document.removeEventListener("keydown",g)}},[c]);const h=m=>{m.stopPropagation(),c?u():f()};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("button",{ref:r,type:"button",onClick:h,className:A("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors flex-shrink-0",c&&"bg-surface-hover text-foreground"),title:"PTZ controls","aria-label":"PTZ controls","aria-haspopup":"dialog","aria-expanded":c,children:(0,i.jsx)(qT,{className:"h-3 w-3"})}),s&&(0,I.createPortal)((0,i.jsx)("div",{ref:n,style:{position:"fixed",top:s.top,left:s.left,width:s.width,maxHeight:s.maxHeight},className:"z-[9999] overflow-y-auto rounded-lg border border-border bg-surface shadow-lg shadow-black/30",onClick:m=>m.stopPropagation(),children:(0,i.jsx)(_f,{mode:"panel",controls:d})}),document.body)]})}function Jb({icon:e,label:t,onClick:r,danger:n=!1}){return(0,i.jsx)("button",{type:"button","aria-label":t,title:t,onClick:r,className:A("inline-flex h-6 w-6 items-center justify-center rounded transition-colors flex-shrink-0",n?"text-danger hover:bg-danger/10":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover"),children:(0,i.jsx)(e,{className:"h-3.5 w-3.5"})})}function TF({device:e,onDelete:t}){const r=ji(),n=async()=>{await r({title:"Delete device?",message:`This will remove "${e.name.trim()!==""?e.name:`#${String(e.id)}`}" and all its settings. This action cannot be undone.`,confirmLabel:"Delete",variant:"danger"})&&t(e)};return(0,i.jsx)("span",{onClick:s=>s.stopPropagation(),children:(0,i.jsx)(Jb,{icon:en,label:"Delete device",danger:!0,onClick:()=>{n()}})})}var CF=Object.freeze([]);function IF(e){return e==="native"?"native":"enhanced"}function PF(e){return e.map(t=>({kind:"marker",feature:t}))}function AF(e,t){const r=new Map,n=t.entries??[];for(const a of n)r.set(a.capName,a);const s=[];for(const a of e){const c=sP[a];if(c===void 0){s.push({kind:"marker",feature:a});continue}const d=r.get(c);d&&s.push({kind:IF(d.kind),feature:a,capName:c})}return s}function jF(e,t,r){const[n,s]=(0,l.useState)(null),[a,c]=(0,l.useState)(!1),[d,u]=(0,l.useState)(!0);return(0,l.useEffect)(()=>{if(t===null){s(null),c(!1),u(!1);return}let f=!1;u(!0),c(!1);const h=async()=>{try{const g=await e.deviceManager.getBindings.query({deviceId:t});if(f)return;s(g),u(!1)}catch{if(f)return;c(!0),u(!1)}};h();const m=e.live?.onEvent.subscribe({category:"capability.binding-changed"},{onData:g=>{const p=g.data?.source;if(!p){h();return}p.type==="device"&&p.id===t&&h()}});return()=>{f=!0,m?.unsubscribe()}},[e,t]),r.length===0?{loading:d,resolved:CF}:d||a||!n?{loading:d,resolved:PF(r)}:{loading:!1,resolved:AF(r,n)}}var NF=[];function Jf({trpc:e,device:t,flags:r,accessoryCount:n,adoptedCount:s,showFeatureRow:a=!1}){const c=n+s,d=r.showChildrenAccordion&&c>0,u=t.features??NF,f=a&&u.length>0,{resolved:h}=jF(e,f?t.id:null,u),m=f&&h.length>0;return!d&&!m?null:(0,i.jsxs)("div",{className:"flex items-center gap-1.5 flex-nowrap whitespace-nowrap min-w-0",children:[d&&(0,i.jsx)(DF,{accessoryCount:n,adoptedCount:s}),m&&(0,i.jsx)(MF,{resolved:h})]})}function DF({accessoryCount:e,adoptedCount:t}){const r=e+t;return r===0?null:(0,i.jsxs)("span",{className:"text-[9px] font-medium text-foreground-subtle bg-surface-elevated/60 rounded px-1.5 py-0.5 flex-shrink-0",title:t>0&&e>0?`${String(t)} adopted · ${String(e)} accessor${e===1?"y":"ies"}`:t>0?`${String(t)} adopted`:`${String(e)} accessor${e===1?"y":"ies"}`,children:["+",r]})}var ey=240,ty=200;function MF({resolved:e}){const t=(0,l.useRef)(null),[r,n]=(0,l.useState)(null),s=()=>{const c=t.current;if(!c)return;const d=c.getBoundingClientRect();n({top:window.innerHeight-d.bottom>=ty?d.bottom+4:d.top-ty-4,left:Math.max(8,Math.min(d.left,window.innerWidth-ey-8))})},a=()=>n(null);return(0,i.jsxs)("span",{ref:t,className:"relative inline-flex items-center gap-1 cursor-help",onMouseEnter:s,onMouseLeave:a,children:[e.map(c=>{const d=Bv[c.feature];return d?(0,i.jsx)("span",{className:"inline-flex items-center justify-center h-4 w-4 rounded bg-surface-elevated/60 text-foreground-subtle",title:zv[c.feature]??c.feature,children:(0,i.jsx)(d,{className:"h-2.5 w-2.5"})},c.feature):null}),r&&(0,I.createPortal)((0,i.jsx)($F,{resolved:e,position:r}),document.body)]})}function $F({resolved:e,position:t}){return(0,i.jsxs)("div",{style:{position:"fixed",top:t.top,left:t.left,width:ey,pointerEvents:"none"},className:"z-[9999] rounded-md border border-border bg-surface shadow-lg shadow-black/30 p-2",children:[(0,i.jsx)("h5",{className:"text-[9px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1.5",children:"Features"}),(0,i.jsx)("ul",{className:"space-y-0.5",children:e.map(r=>(0,i.jsx)(RF,{entry:r},r.feature))})]})}function RF({entry:e}){const t=Bv[e.feature],r=zv[e.feature]??e.feature;return(0,i.jsxs)("li",{className:"flex items-center justify-between gap-2 text-[10px]",children:[(0,i.jsxs)("span",{className:"flex items-center gap-1.5 text-foreground",children:[t&&(0,i.jsx)(t,{className:"h-3 w-3 text-foreground-subtle"}),(0,i.jsx)("span",{children:r})]}),(0,i.jsx)(LF,{kind:e.kind})]})}function LF({kind:e}){return e==="marker"?(0,i.jsx)("span",{className:"text-[8.5px] px-1 rounded text-foreground-subtle",title:"Informational marker (no cap registered)",children:"marker"}):(0,i.jsx)("span",{className:A("text-[8.5px] px-1 rounded",e==="native"?"bg-success/15 text-success":"bg-primary/15 text-primary"),children:e})}var ry={horizontal:"h-3.5 w-3.5",stacked:"h-4 w-4 mt-0.5"};function eh({device:e,variant:t,flags:r,parent:n,integrationIcon:s,hasChildren:a,expanded:c,onToggleExpand:d,onNavigateToParent:u,stacked:f=!1}){const h=Uv(lP(e,Dl(e.id))),m=f?ry.stacked:ry.horizontal;return(0,i.jsxs)("div",{className:A(f?"flex items-start gap-2 w-full min-w-0":"flex items-center gap-2 flex-1 min-w-0"),children:[r.showChildrenAccordion&&a?(0,i.jsx)("button",{type:"button","data-testid":"chevron-slot",onClick:g=>{g.stopPropagation(),d()},className:A("flex items-center justify-center text-foreground-subtle hover:text-foreground transition-colors flex-shrink-0",m),"aria-label":c?"Collapse children":"Expand children","aria-expanded":c,children:c?(0,i.jsx)(fr,{className:"h-3 w-3"}):(0,i.jsx)(mn,{className:"h-3 w-3"})}):r.showChildrenAccordion?(0,i.jsx)("span",{"data-testid":"chevron-slot",className:A("flex-shrink-0",m)}):null,(0,i.jsx)(h,{className:A("text-foreground-subtle flex-shrink-0",f?"h-4 w-4 mt-0.5":t==="minimal"?"h-3 w-3":"h-3.5 w-3.5")}),(0,i.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,i.jsxs)("div",{className:A("min-w-0",f?"flex flex-col gap-1":"flex items-center gap-1.5"),children:[r.showIntegrationIcon&&s&&(0,i.jsx)("span",{className:"flex-shrink-0",children:s}),(0,i.jsx)("span",{className:A("font-semibold text-foreground",f?"text-[13px] leading-snug line-clamp-2 break-words":A("truncate",t==="minimal"?"text-[10.5px]":"text-[11px]")),title:e.name,children:e.name})]}),(r.showId||r.showStableId)&&(0,i.jsxs)("div",{className:"mt-0.5 flex items-center gap-1 text-[9px] text-foreground-subtle font-mono truncate",title:r.showStableId?`stableId: ${e.stableId}`:void 0,children:[r.showId&&(0,i.jsxs)("span",{className:"flex-shrink-0 tabular-nums",children:["#",String(e.id)]}),r.showId&&r.showStableId&&(0,i.jsx)("span",{className:"flex-shrink-0 opacity-50",children:"·"}),r.showStableId&&(0,i.jsx)("span",{className:"truncate",children:cP(e.stableId)})]}),r.showParentBadge&&n&&(0,i.jsxs)("button",{type:"button",onClick:g=>{g.stopPropagation(),u(n.id)},className:"mt-0.5 inline-flex max-w-full items-center gap-1 text-[9px] text-foreground-subtle hover:text-primary transition-colors",title:`Open parent: ${n.name} (#${String(n.id)})`,children:[(0,i.jsx)(Fp,{className:"h-2.5 w-2.5 shrink-0"}),(0,i.jsxs)("span",{className:"truncate",children:["Under: ",n.name]})]})]})]})}function ny(e,t){return Dv(e,t,r=>r.battery)??null}function iy(e,t){const r=Br(e,t),n=(0,l.useRef)(!1),{data:s,isLoading:a,isFetching:c,refetch:d}=(0,ye.useQuery)({queryKey:["device",t,"snapshot"],queryFn:()=>{if(!r)throw new Error("useDeviceSnapshotImage: device proxy not ready");const h=n.current;return n.current=!1,r.snapshot?.getSnapshot({force:h})??null},enabled:r!==null&&t!==null,staleTime:1e4,gcTime:1440*60*1e3,refetchOnWindowFocus:!1,refetchOnReconnect:!1,retry:!1}),u=s?`data:${s.contentType};base64,${s.base64}`:null;function f(){n.current=!0,d()}return{src:u,loading:a||c,refresh:f}}var OF=50;function FF(e){return e<=10?Sp:e<=30?ST:e<=70?Od:xp}function UF(e,t){return t!=="none"?"text-emerald-400":e<=10?"text-rose-400":e<=30?"text-amber-400":"text-foreground-subtle"}function sy({status:e,variant:t="compact",className:r}){if(!e)return null;if(e.binary===!0){const d=e.percentage<OF,u=d?Sp:xp;return(0,i.jsxs)("span",{className:A("inline-flex items-center gap-1 text-[10px] font-medium",d?"text-rose-400":"text-foreground-subtle",r),title:`Battery: ${d?"low":"normal"}`,children:[(0,i.jsx)(u,{className:"h-3.5 w-3.5"}),(0,i.jsx)("span",{children:d?"Low":"Normal"})]})}const n=FF(e.percentage),s=UF(e.percentage,e.charging),a=e.charging==="solar"?Xd:e.charging==="dc"?vC:null,c=e.sleeping;return(0,i.jsxs)("span",{className:A("inline-flex items-center gap-1 text-[10px] font-medium",s,r),title:`Battery: ${Math.round(e.percentage)}%`+(e.charging!=="none"?` · charging (${e.charging})`:"")+(e.sleeping?" · sleeping":""),children:[(0,i.jsx)(n,{className:"h-3.5 w-3.5"}),(0,i.jsxs)("span",{children:[Math.round(e.percentage),"%"]}),a&&(0,i.jsx)(a,{className:"h-3 w-3"}),c&&(0,i.jsx)(bl,{className:"h-3 w-3 text-blue-300"}),t==="full"&&e.charging!=="none"&&(0,i.jsx)("span",{className:"text-foreground-subtle",children:e.charging})]})}function th({trpc:e,device:t,status:r,enabled:n,showStatusPills:s=!1}){const a=iy(e,n&&t.online?t.id:null),c=(t.features??[]).includes("battery-operated"),d=s&&c&&!t.disabled,u=ny(e,d?t.id:null);if(!n&&!d)return null;const f=r==="offline"||r==="disabled",h=r==="offline"?"Offline — no snapshot":r==="disabled"?"Disabled":"No snapshot yet";return(0,i.jsxs)("span",{className:"inline-flex items-center gap-1.5 flex-nowrap whitespace-nowrap",children:[d&&u&&(0,i.jsx)(sy,{status:u}),n&&(0,i.jsx)(Uf,{src:f?null:a.src,alt:t.name,placeholder:h,thumbClassName:"h-7 w-7 rounded"})]})}function BF(e,t){if(e==="disabled")return"Disabled";if(e==="online")return"Online";const r=ri(t);return r===null?"Offline":`Offline · last seen ${r}`}function rh({status:e,lastChangedAt:t}){return(0,i.jsx)("span",{className:A("h-1.5 w-1.5 rounded-full flex-shrink-0",e==="disabled"?"bg-warning":e==="online"?"bg-success":"bg-danger"),title:BF(e,t)})}var zF=["name","icon","type","manufacturer","features","previewActions"],GF={devices:["name","icon","type","manufacturer","features","previewActions"],"integration-detail":["name","manufacturer","features","previewActions"]};function ay(e){return GF[e]}var ZF={name:0,previewActions:1,icon:2,features:3,type:4,manufacturer:5},Di={name:"",previewActions:"",icon:"",features:"hidden md:table-cell",type:"hidden lg:table-cell",manufacturer:"hidden xl:table-cell"},nh="manufacturer",oy="model";function ly(e){if(typeof e=="string"){const t=e.trim();return t===""?null:t}return typeof e=="number"&&Number.isFinite(e)||typeof e=="boolean"?String(e):null}function fs(e,t){return e==null?null:ly(e[t])}function cy(e){const t=fs(e.metadata,nh),r=fs(e.metadata,oy);return t!==null&&r!==null?`${t} · ${r}`:t??r??null}function uy(e){if(e==null)return[];const t=[];for(const r of Object.keys(e)){const n=ly(e[r]);n!==null&&t.push({key:r,value:n})}return t}function dy(e){return fs(e.metadata,nh)!==null}function fy(e){return(fs(e.metadata,nh)??"").toLowerCase()}function hy(e){return(fs(e.metadata,oy)??"").toLowerCase()}function VF(e,t){const r=fy(e).localeCompare(fy(t));return r!==0?r:hy(e).localeCompare(hy(t))}function HF({device:e}){const t=cy(e),r=uy(e.metadata);if(t===null&&r.length===0)return(0,i.jsx)("span",{className:"text-xs text-foreground-subtle/60",children:"—"});const n=t??"—";return r.length===0?(0,i.jsx)("span",{className:"block truncate text-xs text-foreground-subtle",children:n}):(0,i.jsxs)(lv,{className:"block w-full min-w-0",children:[(0,i.jsx)(cv,{className:"block w-full min-w-0",children:(0,i.jsx)("span",{className:"block truncate text-xs text-foreground-subtle",children:n})}),(0,i.jsx)(uv,{className:"whitespace-normal text-left max-w-xs",children:(0,i.jsx)("dl",{className:"grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5",children:r.map(s=>(0,i.jsxs)("div",{className:"contents",children:[(0,i.jsx)("dt",{className:"font-medium opacity-70",children:s.key}),(0,i.jsx)("dd",{className:"break-words",children:s.value})]},s.key))})})]})}function KF({title:e,count:t,children:r,defaultOpen:n=!0}){const[s,a]=(0,l.useState)(n);return(0,i.jsxs)("div",{className:"rounded-md border border-border-subtle/50",children:[(0,i.jsxs)("button",{type:"button",onClick:()=>a(c=>!c),className:A("w-full flex items-center gap-1.5 px-2 py-1.5 text-left transition-colors","hover:bg-surface-hover"),"aria-expanded":s,children:[s?(0,i.jsx)(fr,{className:"h-3 w-3 text-foreground-subtle flex-shrink-0"}):(0,i.jsx)(mn,{className:"h-3 w-3 text-foreground-subtle flex-shrink-0"}),(0,i.jsx)("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle flex-1 truncate",children:e}),(0,i.jsx)("span",{className:"text-[10px] font-medium text-foreground-subtle/70 tabular-nums",children:t})]}),s&&(0,i.jsx)("div",{className:"space-y-1 px-1 pb-1.5",children:r})]})}var WF="Disabled";function my(e,t,r){const n=t.filter(f=>f.disabled!==!0),s=qF(t.filter(f=>f.disabled===!0));if(r===void 0||r.length===0)return{sections:[],ungrouped:n,disabledSection:s};const a=new Map;for(const f of n)a.set(f.stableId,f);const c=[],d=new Map,u=new Set;for(const f of r){const h=`${e}-${f.childKey}`,m=a.get(h);if(m===void 0)continue;let g=d.get(f.section);g===void 0&&(g={title:f.section,entries:[],collapsed:!1},d.set(f.section,g),c.push(f.section)),g.entries.push({child:m,order:f.order??Number.MAX_SAFE_INTEGER}),f.collapsed===!0&&(g.collapsed=!0),u.add(m.id)}return{sections:c.map(f=>{const h=d.get(f),m=[...h===void 0?[]:h.entries].sort((p,y)=>p.order!==y.order?p.order-y.order:p.child.name.localeCompare(y.child.name)),g=h===void 0?!0:!h.collapsed;return{title:f,children:m.map(p=>p.child),defaultOpen:g}}),ungrouped:n.filter(f=>!u.has(f.id)),disabledSection:s}}function qF(e){if(e.length!==0)return{title:WF,children:[...e].sort((t,r)=>t.name.localeCompare(r.name)),defaultOpen:!1,muted:!0}}function Gl(e){const{trpc:t,device:r,parent:n,integrationIcon:s,onNavigate:a,className:c,renderRowAction:d,onDelete:u,selection:f}=e,h=iP(e),m=e.variant??"compact",g=e.view??"card",p=!r.disabled,y=r.isCamera??r.type.toLowerCase()==="camera",S=e.children??[],E=S.filter(Zv),T=S.filter(oe=>!Zv(oe)),j=S.length>0,[N,O]=(0,l.useState)(!1),U=e.expanded??N,z=e.onToggleExpand??(()=>O(oe=>!oe)),K=oe=>{a?.(oe)},G=e.rowClickSelects===!0&&f!==void 0,X=()=>{if(G&&f!==void 0){f.onToggle();return}K(r.id)},te=e.indentLevel??(e.isAccessoryRow?2:0),ne=oP(r,S),ae=p?ne?"online":"offline":"disabled";return g==="table"?(0,i.jsx)(YF,{trpc:t,device:r,variant:m,flags:h,parent:n??null,integrationIcon:s??null,accessoryCount:E.length,adoptedCount:T.length,hasChildren:j,expanded:U,onToggleExpand:z,onRowClick:X,rowSelects:G,rowSelected:f?.selected??!1,onNavigate:K,displayStatus:ae,isCamera:y,showSnapshot:h.showSnapshot&&y,isAccessoryRow:e.isAccessoryRow??!1,indentLevel:te,className:c,renderRowAction:d??null,onDelete:u??null,selection:f,showTypeCell:e.showTypeCell??!0,showManufacturerCell:e.showManufacturerCell??!0,showFeaturesCell:e.showFeaturesCell??!0}):m==="minimal"?(0,i.jsxs)("div",{className:A("rounded-lg border border-border bg-surface transition-colors",!p&&"opacity-60",c),children:[(0,i.jsxs)("div",{"data-testid":"device-card-body",onClick:X,...G?{role:"button","aria-pressed":f?.selected??!1,tabIndex:0,onKeyDown:oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),X())}}:{},className:A("flex items-center gap-2 cursor-pointer hover:border-foreground-subtle/30 w-full px-2.5 py-1.5",f?.selected&&"bg-primary/10"),children:[f&&(0,i.jsx)("input",{type:"checkbox",checked:f.selected,onChange:f.onToggle,onClick:oe=>oe.stopPropagation(),"aria-label":`Select ${r.name}`,className:"flex-shrink-0"}),(0,i.jsx)(eh,{device:r,variant:m,flags:h,parent:n??null,integrationIcon:s??null,hasChildren:j,expanded:U,onToggleExpand:z,onNavigateToParent:K}),(0,i.jsx)(Jf,{trpc:t,device:r,flags:h,accessoryCount:E.length,adoptedCount:T.length,showFeatureRow:!1}),(0,i.jsx)(th,{trpc:t,device:r,status:ae,enabled:h.showSnapshot&&y,showStatusPills:!0}),(0,i.jsx)(Yf,{trpc:t,device:r,flags:h,controlPlacement:"right"}),d&&(0,i.jsx)("span",{onClick:oe=>oe.stopPropagation(),children:d(r)}),(0,i.jsx)(rh,{status:ae})]}),U&&j&&(0,i.jsx)(Kv,{trpc:t,accessoryChildren:E,adoptedChildren:T,onNavigate:K})]}):(0,i.jsxs)("div",{className:A("group rounded-xl border border-border bg-surface transition-colors","hover:border-foreground-subtle/30",!p&&"opacity-60",c),children:[(0,i.jsxs)("div",{"data-testid":"device-card-body",onClick:X,...G?{role:"button","aria-pressed":f?.selected??!1,tabIndex:0,onKeyDown:oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),X())}}:{},className:A("flex flex-col gap-2 cursor-pointer w-full p-3 rounded-xl",f?.selected&&"bg-primary/10"),children:[(0,i.jsxs)("div",{className:"flex items-start justify-between gap-2",children:[f&&(0,i.jsx)("input",{type:"checkbox",checked:f.selected,onChange:f.onToggle,onClick:oe=>oe.stopPropagation(),"aria-label":`Select ${r.name}`,className:"flex-shrink-0 mt-0.5"}),(0,i.jsx)(eh,{device:r,variant:m,flags:h,parent:n??null,integrationIcon:s??null,hasChildren:j,expanded:U,onToggleExpand:z,onNavigateToParent:K,stacked:!0}),(0,i.jsx)(rh,{status:ae})]}),(0,i.jsx)(Jf,{trpc:t,device:r,flags:h,accessoryCount:E.length,adoptedCount:T.length,showFeatureRow:!1}),(0,i.jsxs)("div",{className:"flex items-center justify-end gap-1.5",children:[(0,i.jsx)(th,{trpc:t,device:r,status:ae,enabled:h.showSnapshot&&y,showStatusPills:!0}),(0,i.jsx)(Yf,{trpc:t,device:r,flags:h,controlPlacement:"right"}),d&&(0,i.jsx)("span",{onClick:oe=>oe.stopPropagation(),children:d(r)})]})]}),U&&j&&(0,i.jsx)(Kv,{trpc:t,accessoryChildren:E,adoptedChildren:T,onNavigate:K})]})}var QF={0:"pl-2",1:"pl-6",2:"pl-8"};function YF(e){const{trpc:t,device:r,variant:n,flags:s,parent:a,integrationIcon:c,accessoryCount:d,adoptedCount:u,hasChildren:f,expanded:h,onToggleExpand:m,onNavigate:g,onRowClick:p,rowSelects:y,rowSelected:S,displayStatus:E,isCamera:T,showSnapshot:j,isAccessoryRow:N,indentLevel:O,className:U,renderRowAction:z,onDelete:K,selection:G,showTypeCell:X,showManufacturerCell:te,showFeaturesCell:ne}=e,ae=Dl(r.id);return(0,i.jsxs)("tr",{onClick:p,...y?{role:"button","aria-pressed":S,tabIndex:0,onKeyDown:oe=>{(oe.key==="Enter"||oe.key===" ")&&(oe.preventDefault(),p())}}:{},className:A("group cursor-pointer hover:bg-surface-hover transition-colors",!f&&"border-b border-border-subtle/40",N&&"bg-foreground-subtle/[0.03]",S&&"bg-primary/10",U),children:[(0,i.jsx)("td",{className:A("sticky left-0 z-[1] py-1.5 align-middle pr-2 transition-colors",S?"bg-primary/10 group-hover:bg-surface-hover":N?"bg-surface-subtle group-hover:bg-surface-hover":"bg-surface group-hover:bg-surface-hover","w-64 max-w-[16rem] min-w-0 overflow-hidden",QF[O]),children:(0,i.jsxs)("div",{className:"flex items-center gap-1.5",children:[G&&(0,i.jsx)("input",{type:"checkbox",checked:G.selected,onChange:G.onToggle,onClick:oe=>oe.stopPropagation(),"aria-label":`Select ${r.name}`,className:"flex-shrink-0"}),(0,i.jsx)(eh,{device:r,variant:n,flags:s,parent:a,integrationIcon:c,hasChildren:f,expanded:h,onToggleExpand:m,onNavigateToParent:g})]})}),X&&(0,i.jsx)("td",{className:A(Di.type,"px-2 py-1.5 align-middle text-[10px] text-foreground-subtle whitespace-nowrap"),children:Hv(r,ae)}),te&&(0,i.jsx)("td",{className:A(Di.manufacturer,"px-2 py-1.5 align-middle w-40 max-w-[10rem] min-w-0 overflow-hidden"),children:(0,i.jsx)(HF,{device:r})}),ne&&(0,i.jsx)("td",{className:A(Di.features,"px-2 py-1.5 align-middle"),children:(0,i.jsx)(Jf,{trpc:t,device:r,flags:s,accessoryCount:d,adoptedCount:u,showFeatureRow:!0})}),(0,i.jsx)("td",{className:"px-2 py-1.5 align-middle text-right whitespace-nowrap",children:(0,i.jsxs)("span",{className:"inline-flex items-center justify-end gap-1.5",children:[(0,i.jsx)(Yf,{trpc:t,device:r,flags:s,controlPlacement:"table"}),(0,i.jsx)(th,{trpc:t,device:r,status:E,enabled:j&&T,showStatusPills:!0}),z&&(0,i.jsx)("span",{onClick:oe=>oe.stopPropagation(),children:z(r)}),K&&(0,i.jsx)(TF,{device:r,onDelete:K}),(0,i.jsx)(rh,{status:E})]})})]})}function ih({selectedIds:e,onClear:t,remove:r,disable:n,enable:s}){const[a,c]=(0,l.useState)(!1);if(e.size===0)return null;const d=[...e],u=d.length,f=()=>{for(const S of d)n({deviceId:S});t()},h=()=>{for(const S of d)s({deviceId:S});t()},m=()=>{c(!0)},g=()=>{for(const S of d)r({deviceId:S});c(!1),t()},p=()=>{c(!1)},y=()=>{c(!1),t()};return(0,i.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2 rounded-lg border border-border bg-surface-hover",children:[(0,i.jsxs)("span",{className:"text-xs font-medium text-foreground-subtle shrink-0",children:[u," selected"]}),(0,i.jsx)("div",{className:"h-3.5 w-px bg-border shrink-0","aria-hidden":"true"}),(0,i.jsxs)("div",{className:"flex items-center gap-1.5 flex-wrap",children:[(0,i.jsx)("button",{type:"button",onClick:f,className:A("inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors","border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface"),children:"Disable"}),(0,i.jsx)("button",{type:"button",onClick:h,className:A("inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors","border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface"),children:"Enable"}),a?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("button",{type:"button",onClick:g,className:A("inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors","border-red-500/50 bg-red-500/10 text-red-400 hover:bg-red-500/20"),children:["Confirm delete ",u,"?"]}),(0,i.jsx)("button",{type:"button",onClick:p,className:A("inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors","border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface"),children:"Cancel"})]}):(0,i.jsx)("button",{type:"button",onClick:m,className:A("inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors","border-red-500/40 bg-red-500/10 text-red-400 hover:bg-red-500/20"),children:"Delete"}),(0,i.jsx)("button",{type:"button",onClick:y,className:A("inline-flex items-center h-6 px-2.5 rounded-md border text-[10.5px] font-medium transition-colors","border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface"),children:"Clear"})]})]})}function XF(e){const[t,r]=(0,l.useState)(!1),n=(0,l.useRef)(null),s=e.selectedIds.size;return(0,l.useEffect)(()=>{if(!t)return;const a=d=>{const u=d.target instanceof Node?d.target:null;u&&n.current&&!n.current.contains(u)&&r(!1)},c=d=>{d.key==="Escape"&&r(!1)};return document.addEventListener("mousedown",a),document.addEventListener("touchstart",a),document.addEventListener("keydown",c),()=>{document.removeEventListener("mousedown",a),document.removeEventListener("touchstart",a),document.removeEventListener("keydown",c)}},[t]),s===0?null:(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("div",{className:"hidden sm:block",children:(0,i.jsx)(ih,{...e})}),(0,i.jsxs)("div",{ref:n,"data-testid":"batch-actions-compact",className:"relative sm:hidden",children:[(0,i.jsxs)("button",{type:"button",onClick:()=>r(a=>!a),"aria-haspopup":"menu","aria-expanded":t,className:"inline-flex items-center gap-1.5 h-7 px-2.5 rounded-full border border-primary/40 bg-primary/15 text-[10.5px] font-medium text-primary",children:[(0,i.jsxs)("span",{children:["Actions · ",String(s)]}),(0,i.jsx)(fr,{className:`h-3 w-3 transition-transform ${t?"rotate-180":""}`})]}),t&&(0,i.jsx)("div",{role:"menu",className:"absolute left-0 top-full mt-1 z-30 rounded-lg border border-border bg-surface shadow-md",children:(0,i.jsx)(ih,{...e})})]})]})}function sh(e,t){const[r,n]=(0,l.useState)(e);return(0,l.useEffect)(()=>{const s=setTimeout(()=>n(e),t);return()=>clearTimeout(s)},[e,t]),r}var ah=[25,50,100,200],oh="camstack.device-list.pageSize";function lh(e){return ah.includes(e)}function JF(e){return lh(e)?e:50}function eU(e){if(typeof window>"u")return e;try{const t=window.localStorage.getItem(oh);if(t===null)return e;const r=Number.parseInt(t,10);return Number.isFinite(r)&&lh(r)?r:e}catch{return e}}function tU(e){if(!(typeof window>"u"))try{window.localStorage.setItem(oh,String(e))}catch{}}function gy(e){const t=JF(e),[r,n]=(0,l.useState)(()=>eU(t));return[r,(0,l.useCallback)(s=>{lh(s)&&(n(s),tU(s))},[])]}function py(e){const t=new Map;for(const r of e)t.set(r.id,r);return e.filter(r=>{if(r.parentDeviceId===null||r.parentDeviceId===void 0)return!0;const n=t.get(r.parentDeviceId);return n?vy.has(n.type.toLowerCase()):!0})}var vy=new Set(["hub","nvr"]);function rU(e){const t=new Map;for(const s of e)t.set(s.id,s);const r=[],n=new Map;for(const s of e){const a=s.parentDeviceId;if(a==null){r.push(s);continue}const c=t.get(a);if(!c){r.push(s);continue}const d=s.role!==null&&s.role!==void 0;if(vy.has(c.type)&&!d){r.push(s);continue}const u=n.get(a);u?u.push(s):n.set(a,[s])}return{topLevel:r,accessoriesByParent:n}}function ch(e){return e.toLowerCase().replace(/[-_\s]+/g,"")}function hs(e,t){const r=ch(e);return r===""?!0:ch(t).includes(r)}var by=2;function nU(e,t){if(t<=1)return[{kind:"page",n:1}];if(t<=7){const a=[];for(let c=1;c<=t;c++)a.push({kind:"page",n:c});return a}const r=[],n=Math.max(2,e-by),s=Math.min(t-1,e+by);r.push({kind:"page",n:1}),n>2&&r.push({kind:"ellipsis",side:"left"});for(let a=n;a<=s;a++)r.push({kind:"page",n:a});return s<t-1&&r.push({kind:"ellipsis",side:"right"}),r.push({kind:"page",n:t}),r}function uh({currentPage:e,totalItems:t,pageSize:r,onPageChange:n,itemNoun:s="devices"}){if(t<=r)return null;const a=Math.ceil(t/r),c=(e-1)*r+1,d=Math.min(e*r,t),u=nU(e,a);return(0,i.jsxs)("div",{className:"flex items-center justify-between gap-4 flex-wrap pt-2 text-[11px] text-foreground-subtle",children:[(0,i.jsxs)("span",{children:["Showing ",c,"–",d," of ",t," ",s]}),(0,i.jsxs)("span",{className:"inline-flex items-center gap-1",children:[(0,i.jsx)("button",{type:"button","aria-label":"Previous page",disabled:e===1,onClick:()=>n(e-1),className:A("inline-flex items-center justify-center h-7 w-7 rounded border border-border bg-surface text-foreground-subtle","hover:text-foreground hover:bg-surface-hover transition-colors","disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-surface"),children:(0,i.jsx)(IT,{className:"h-3 w-3"})}),u.map((f,h)=>f.kind==="ellipsis"?(0,i.jsx)("span",{className:"px-1 text-foreground-subtle/60 select-none",children:"…"},`e-${h}`):(0,i.jsx)("button",{type:"button",onClick:()=>n(f.n),className:A("inline-flex items-center justify-center h-7 min-w-7 px-1.5 rounded border text-[10.5px] font-medium transition-colors",f.n===e?"border-primary/40 bg-primary/10 text-primary":"border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover"),children:f.n},`p-${f.n}`)),(0,i.jsx)("button",{type:"button","aria-label":"Next page",disabled:e===a,onClick:()=>n(e+1),className:A("inline-flex items-center justify-center h-7 w-7 rounded border border-border bg-surface text-foreground-subtle","hover:text-foreground hover:bg-surface-hover transition-colors","disabled:opacity-40 disabled:cursor-not-allowed disabled:hover:bg-surface"),children:(0,i.jsx)(mn,{className:"h-3 w-3"})})]})]})}function iU({label:e,options:t,selected:r,onChange:n}){const[s,a]=(0,l.useState)(!1),c=(0,l.useRef)(null);(0,l.useEffect)(()=>{if(!s)return;const h=g=>{const p=g.target instanceof Node?g.target:null;p&&c.current&&!c.current.contains(p)&&a(!1)},m=g=>{g.key==="Escape"&&a(!1)};return document.addEventListener("mousedown",h),document.addEventListener("touchstart",h),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("touchstart",h),document.removeEventListener("keydown",m)}},[s]);const d=new Set(r),u=r.length,f=h=>{const m=new Set(d);m.has(h)?m.delete(h):m.add(h),n(t.filter(g=>m.has(g.id)).map(g=>g.id))};return(0,i.jsxs)("div",{ref:c,className:"relative",children:[(0,i.jsxs)("button",{type:"button",onClick:()=>a(h=>!h),"aria-haspopup":"listbox","aria-expanded":s,className:`inline-flex items-center gap-1.5 h-7 px-2.5 rounded-full border text-[10.5px] font-medium transition-colors ${u>0?"border-primary/40 bg-primary/15 text-primary":"border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,children:[(0,i.jsxs)("span",{children:[e,u>0?` · ${String(u)}`:""]}),(0,i.jsx)(fr,{className:`h-3 w-3 transition-transform ${s?"rotate-180":""}`})]}),s&&(0,i.jsxs)("div",{role:"listbox",className:"absolute left-0 top-full mt-1 z-30 min-w-[180px] max-h-72 overflow-y-auto rounded-lg border border-border bg-surface shadow-xl py-1",children:[u>0&&(0,i.jsx)("button",{type:"button",onClick:()=>n([]),className:"flex w-full items-center px-3 py-1.5 text-left text-[10.5px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground",children:"Clear selection"}),t.map(h=>{const m=d.has(h.id),g=h.icon;return(0,i.jsxs)("button",{type:"button",role:"option","aria-selected":m,onClick:()=>f(h.id),className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-[10.5px] text-foreground hover:bg-surface-hover",children:[(0,i.jsx)("span",{className:`flex h-3.5 w-3.5 items-center justify-center rounded border shrink-0 ${m?"border-primary bg-primary":"border-border"}`,children:m&&(0,i.jsx)(On,{className:"h-2.5 w-2.5 text-primary-foreground"})}),g&&(0,i.jsx)(g,{className:"h-3.5 w-3.5 shrink-0 text-foreground-subtle"}),(0,i.jsx)("span",{className:"truncate",children:h.label})]},h.id)})]})]})}function yy({label:e,options:t,selected:r,onChange:n}){const s=(0,l.useRef)(null),[a,c]=(0,l.useState)(null);(0,l.useEffect)(()=>{const h=s.current;if(!h||typeof ResizeObserver>"u")return;const m=new ResizeObserver(g=>{const p=g[0];p&&c(p.contentRect.width)});return m.observe(h),()=>m.disconnect()},[]);const d=new Set(r),u=h=>{const m=new Set(d);m.has(h)?m.delete(h):m.add(h),n(t.filter(g=>m.has(g.id)).map(g=>g.id))},f=56+t.length*88;return(0,i.jsx)("div",{ref:s,className:"min-w-0 flex-1",children:a!==null&&a>=f?(0,i.jsxs)("div",{className:"flex items-center gap-1.5 flex-wrap",children:[(0,i.jsx)("span",{className:"text-[10px] font-medium uppercase tracking-wider text-foreground-subtle",children:e}),t.map(h=>{const m=d.has(h.id),g=h.icon;return(0,i.jsxs)("button",{type:"button",onClick:()=>u(h.id),"aria-pressed":m,className:`inline-flex items-center gap-1 h-7 px-2.5 rounded-full border text-[10.5px] font-medium transition-colors ${m?"border-primary/40 bg-primary/15 text-primary":"border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,children:[g&&(0,i.jsx)(g,{className:"h-3 w-3 shrink-0"}),h.label]},h.id)})]}):(0,i.jsx)(iU,{label:e,options:t,selected:r,onChange:n})})}function sU({view:e,onViewChange:t,hideView:r=!1,typeOptions:n,selectedTypes:s,onTypesChange:a,addons:c,selectedAddons:d,onAddonsChange:u,hideAddons:f=!1}){return(0,i.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[!r&&e!==void 0&&t!==void 0&&(0,i.jsxs)("span",{className:"inline-flex border border-border rounded-md overflow-hidden",children:[(0,i.jsx)("button",{type:"button",onClick:()=>t("cards"),className:A("inline-flex items-center justify-center h-7 w-8 transition-colors",e==="cards"?"bg-primary/10 text-primary":"bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover"),"aria-label":"Cards view",children:(0,i.jsx)(nC,{className:"h-3.5 w-3.5"})}),(0,i.jsx)("button",{type:"button",onClick:()=>t("table"),className:A("inline-flex items-center justify-center h-7 w-8 border-l border-border transition-colors",e==="table"?"bg-primary/10 text-primary":"bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover"),"aria-label":"Table view",children:(0,i.jsx)(jC,{className:"h-3.5 w-3.5"})})]}),n&&n.length>0&&(0,i.jsx)(yy,{label:"Type",options:n,selected:s,onChange:a}),!f&&c&&c.length>0&&(0,i.jsx)(aU,{addons:c,selected:d,onChange:u})]})}function aU({addons:e,selected:t,onChange:r}){const[n,s]=(0,l.useState)(!1),a=(0,l.useRef)(null);(0,l.useEffect)(()=>{if(!n)return;const f=m=>{const g=m.target;g&&a.current&&!a.current.contains(g)&&s(!1)},h=m=>{m.key==="Escape"&&s(!1)};return document.addEventListener("mousedown",f),document.addEventListener("touchstart",f),document.addEventListener("keydown",h),()=>{document.removeEventListener("mousedown",f),document.removeEventListener("touchstart",f),document.removeEventListener("keydown",h)}},[n]);const c=new Set(t),d=t.length,u=f=>{const h=new Set(c);h.has(f)?h.delete(f):h.add(f),r(e.filter(m=>h.has(m.id)).map(m=>m.id))};return(0,i.jsxs)("div",{ref:a,className:"relative",children:[(0,i.jsxs)("button",{type:"button",onClick:()=>s(f=>!f),className:A("inline-flex items-center gap-1.5 h-7 px-2.5 rounded-full border text-[10.5px] font-medium transition-colors",d>0?"border-primary/40 bg-primary/15 text-primary":"border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover"),"aria-haspopup":"listbox","aria-expanded":n,children:[(0,i.jsxs)("span",{children:["Integration",d>0?` · ${String(d)}`:""]}),(0,i.jsx)(fr,{className:A("h-3 w-3 transition-transform",n&&"rotate-180")})]}),n&&(0,i.jsxs)("div",{role:"listbox",className:"absolute left-0 top-full mt-1 z-30 min-w-[180px] max-h-72 overflow-y-auto rounded-lg border border-border bg-surface shadow-xl py-1",children:[d>0&&(0,i.jsx)("button",{type:"button",onClick:()=>r([]),className:"flex w-full items-center px-3 py-1.5 text-left text-[10.5px] text-foreground-subtle hover:bg-surface-hover hover:text-foreground",children:"Clear selection"}),e.map(f=>{const h=c.has(f.id);return(0,i.jsxs)("button",{type:"button",role:"option","aria-selected":h,onClick:()=>u(f.id),className:A("flex w-full items-center gap-2 px-3 py-1.5 text-left text-[10.5px] transition-colors",h?"text-primary":"text-foreground hover:bg-surface-hover"),children:[(0,i.jsx)("span",{className:A("flex h-3.5 w-3.5 shrink-0 items-center justify-center rounded border",h?"border-primary bg-primary/20":"border-border"),children:h&&(0,i.jsx)(On,{className:"h-2.5 w-2.5"})}),f.icon&&(0,i.jsx)("span",{className:"inline-flex items-center",children:f.icon}),(0,i.jsx)("span",{className:"truncate",children:f.name})]},f.id)})]})]})}function oU({variant:e,onClearFilters:t}){return(0,i.jsxs)("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[(0,i.jsx)(tC,{className:"h-8 w-8 text-foreground-subtle/40 mb-3"}),(0,i.jsx)("p",{className:"text-sm font-medium text-foreground-subtle",children:e==="filtered"?"No devices match the current filters":"No devices yet"}),e==="filtered"&&t&&(0,i.jsx)("button",{type:"button",onClick:t,className:"mt-2 text-[11px] text-primary hover:underline",children:"Clear filters"})]})}function xy(e){return e?e.split(",").map(t=>t.trim()).filter(t=>t.length>0):[]}function kn(e,t){if(e==="root")return t==="addons"?"addon":t==="types"?"type":t;switch(t){case"view":return"deviceView";case"page":return"devicePage";case"types":return"deviceType";case"q":return"deviceQ";case"addons":return"deviceAddon"}}function Sy(e){try{const t=localStorage.getItem(`camstack:${e}:lastFilters`);if(!t)return{};const r=JSON.parse(t);return typeof r!="object"||r===null?{}:r}catch{return{}}}function lU(e,t){try{localStorage.setItem(`camstack:${e}:lastFilters`,JSON.stringify(t))}catch{}}function _y(e,t,r){const n=new URLSearchParams(window.location.search),s=n.get(kn(e,"view")),a=s==="cards"||s==="table"?s:r.view??t,c=n.get(kn(e,"page")),d=c?parseInt(c,10):1;return{view:a,page:Number.isFinite(d)&&d>=1?d:1,addons:xy(n.get(kn(e,"addons"))??r.addon??null),types:xy(n.get(kn(e,"types"))??r.type??null),q:n.get(kn(e,"q"))??r.q??""}}function cU(e,t,r){const n=new URLSearchParams(window.location.search),s=(d,u)=>{u===null||u===""?n.delete(d):n.set(d,u)};s(kn(e,"view"),t.view===r?null:t.view),s(kn(e,"page"),t.page===1?null:String(t.page)),s(kn(e,"addons"),t.addons.length>0?t.addons.join(","):null),s(kn(e,"types"),t.types.length>0?t.types.join(","):null),s(kn(e,"q"),t.q||null);const a=n.toString(),c=a?`${window.location.pathname}?${a}`:window.location.pathname;window.history.replaceState(null,"",c)}function uU(e){const{scope:t,defaultView:r,lsKey:n}=e,[s,a]=(0,l.useState)(()=>_y(t,r,Sy(n))),c=(0,l.useRef)(s);c.current=s,(0,l.useEffect)(()=>{const u=()=>{const f=_y(t,r,Sy(n));c.current=f,a(f)};return window.addEventListener("popstate",u),()=>window.removeEventListener("popstate",u)},[t,r,n]);const d=(0,l.useCallback)(u=>{const f=u(c.current);c.current=f,a(f),cU(t,f,r),lU(n,{view:f.view,addon:f.addons.length>0?f.addons.join(","):null,type:f.types.length>0?f.types.join(","):null,q:f.q})},[t,r,n]);return{state:s,setView:(0,l.useCallback)(u=>d(f=>({...f,view:u})),[d]),setPage:(0,l.useCallback)(u=>d(f=>({...f,page:u})),[d]),setAddons:(0,l.useCallback)(u=>d(f=>({...f,addons:u,page:1})),[d]),setTypes:(0,l.useCallback)(u=>d(f=>({...f,types:u,page:1})),[d]),setQ:(0,l.useCallback)(u=>d(f=>({...f,q:u,page:1})),[d]),clearFilters:(0,l.useCallback)(()=>d(u=>({...u,addons:[],types:[],q:"",page:1})),[d])}}function dU({rows:e,accessoriesByParent:t,trpc:r,resolveIntegrationIcon:n,resolveParent:s,onNavigate:a,renderRowAction:c,selectable:d,rowClickSelects:u,activeSelected:f,onToggleSelection:h}){return(0,i.jsx)("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3 items-stretch",children:e.map(m=>{const g=t.get(m.id)??[],p=d?{selected:f.has(m.id),onToggle:()=>h(m.id)}:void 0;return(0,i.jsx)(Gl,{trpc:r,device:m,view:"card",integrationIcon:n?.(m.addonId)??null,parent:m.parentDeviceId!==null?s?.(m.parentDeviceId)??null:null,children:g,onNavigate:a??void 0,renderRowAction:c??void 0,selection:p,rowClickSelects:u},m.id)})})}function dh({columnId:e,label:t,sort:r,onSort:n}){const s=r!==null&&r.columnId===e;return(0,i.jsxs)("button",{type:"button",onClick:()=>n(e),className:"group/sort inline-flex items-center gap-0.5 uppercase tracking-wider hover:text-foreground transition-colors",children:[(0,i.jsx)("span",{children:t}),s?r.dir==="asc"?(0,i.jsx)(Ti,{className:"h-3 w-3 flex-shrink-0"}):(0,i.jsx)(fr,{className:"h-3 w-3 flex-shrink-0"}):(0,i.jsx)(Ti,{className:A("h-3 w-3 flex-shrink-0 opacity-0 transition-opacity","group-hover/sort:opacity-30")})]})}function fh(e,t){return e===null||e.columnId!==t?"none":e.dir==="asc"?"ascending":"descending"}var fU=new Set(["hub","nvr"]);function hU(e,t){return e.parentDeviceId===null||t===null?0:fU.has(t.toLowerCase())?1:0}function mU({rows:e,accessoriesByParent:t,autoExpandedParents:r,devices:n,visibleColumns:s,trpc:a,resolveIntegrationIcon:c,resolveParent:d,onNavigate:u,renderRowAction:f,onDeleteDevice:h,selectable:m,rowClickSelects:g,activeSelected:p,onToggleSelection:y,sort:S,onSort:E}){const T=s.includes("type"),j=s.includes("features"),N=s.includes("manufacturer"),O=s.includes("icon"),U=(0,l.useMemo)(()=>{const z=new Map;for(const K of n)z.set(K.id,K.type);return z},[n]);return(0,i.jsx)("div",{className:"rounded-lg border border-border bg-surface overflow-x-auto",children:(0,i.jsxs)("table",{className:"w-full border-collapse",children:[(0,i.jsx)("thead",{children:(0,i.jsxs)("tr",{className:"border-b border-border",children:[(0,i.jsx)("th",{"aria-sort":fh(S,"name"),className:"sticky left-0 z-[1] bg-surface text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-64 max-w-[16rem]",children:(0,i.jsx)(dh,{columnId:"name",label:"Name",sort:S,onSort:E})}),T&&(0,i.jsx)("th",{"aria-sort":fh(S,"type"),className:A(Di.type,"text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-24"),children:(0,i.jsx)(dh,{columnId:"type",label:"Type",sort:S,onSort:E})}),N&&(0,i.jsx)("th",{"aria-sort":fh(S,"manufacturer"),className:A(Di.manufacturer,"text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-40"),children:(0,i.jsx)(dh,{columnId:"manufacturer",label:"Hardware",sort:S,onSort:E})}),j&&(0,i.jsx)("th",{className:A(Di.features,"text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-32"),children:"Features"}),(0,i.jsx)("th",{className:"text-right px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle w-32",children:"Preview"})]})}),(0,i.jsx)("tbody",{children:e.map(z=>{const K=t.get(z.id)??[],G=K.length>0,X=r.has(z.id),te=z.parentDeviceId!==null?d?.(z.parentDeviceId)??null:null,ne=z.parentDeviceId!==null?U.get(z.parentDeviceId)??null:null,ae=m?{selected:p.has(z.id),onToggle:()=>y(z.id)}:void 0;return(0,i.jsx)(gU,{parent:z,accessories:K,hasAccessories:G,forceExpanded:X,trpc:a,integrationIcon:O?c?.(z.addonId)??null:null,showType:T,showManufacturer:N,showFeatures:j,parentRowParent:te,indentLevel:hU(z,ne),onNavigate:u??null,renderRowAction:f??null,onDeleteDevice:h,selection:ae,rowClickSelects:g},z.id)})})]})})}function gU({parent:e,accessories:t,hasAccessories:r,forceExpanded:n,trpc:s,integrationIcon:a,showType:c,showManufacturer:d,showFeatures:u,parentRowParent:f,indentLevel:h,onNavigate:m,renderRowAction:g,onDeleteDevice:p,selection:y,rowClickSelects:S}){const[E,T]=(0,l.useState)(n),j=(0,l.useRef)(n);(0,l.useEffect)(()=>{j.current!==n&&(T(n),j.current=n)},[n]);const N=()=>T(ne=>!ne),O=r&&E,U=(0,l.useMemo)(()=>my(e.stableId,t,e.childLayout),[e.stableId,e.childLayout,t]),[z,K]=(0,l.useState)(()=>{const ne=U.sections.filter(ae=>!ae.defaultOpen).map(ae=>ae.title);return U.disabledSection!==void 0&&!U.disabledSection.defaultOpen&&ne.push(U.disabledSection.title),new Set(ne)}),G=ne=>K(ae=>{const oe=new Set(ae);return oe.has(ne)?oe.delete(ne):oe.add(ne),oe}),X=2+(c?1:0)+(d?1:0)+(u?1:0),te=U.disabledSection;return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(Gl,{trpc:s,device:e,view:"table",integrationIcon:a,parent:f,children:t,onNavigate:m??void 0,showChildrenAccordion:!0,expanded:E,onToggleExpand:N,indentLevel:h,renderRowAction:g??void 0,onDelete:p??void 0,selection:y,rowClickSelects:S,showTypeCell:c,showManufacturerCell:d,showFeaturesCell:u}),O&&U.ungrouped.map(ne=>(0,i.jsx)(wy,{trpc:s,accessory:ne,showType:c,showManufacturer:d,showFeatures:u,onNavigate:m},ne.id)),O&&U.sections.map(ne=>{const ae=!z.has(ne.title);return(0,i.jsx)(Ey,{title:ne.title,count:ne.children.length,open:ae,colSpan:X,onToggle:()=>G(ne.title),rows:ne.children,trpc:s,showType:c,showManufacturer:d,showFeatures:u,onNavigate:m},ne.title)}),O&&te!==void 0&&(0,i.jsx)(Ey,{title:te.title,count:te.children.length,open:!z.has(te.title),colSpan:X,onToggle:()=>G(te.title),rows:te.children,trpc:s,showType:c,showManufacturer:d,showFeatures:u,onNavigate:m,muted:!0},te.title)]})}function wy({trpc:e,accessory:t,showType:r,showManufacturer:n,showFeatures:s,onNavigate:a,muted:c}){return(0,i.jsx)(Gl,{trpc:e,device:t,view:"table",integrationIcon:null,parent:null,isAccessoryRow:!0,showChildrenAccordion:!1,onNavigate:a??void 0,showTypeCell:r,showManufacturerCell:n,showFeaturesCell:s,className:c===!0?"opacity-60":void 0})}function Ey({title:e,count:t,open:r,colSpan:n,onToggle:s,rows:a,trpc:c,showType:d,showManufacturer:u,showFeatures:f,onNavigate:h,muted:m}){return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("tr",{className:A("border-b border-border-subtle/40 bg-surface",m===!0&&"opacity-60"),children:(0,i.jsx)("td",{colSpan:n,className:"p-0",children:(0,i.jsxs)("button",{type:"button",onClick:s,className:"w-full flex items-center gap-1.5 pl-8 pr-2 py-1 text-left hover:bg-surface-hover transition-colors","aria-expanded":r,children:[r?(0,i.jsx)(fr,{className:"h-3 w-3 text-foreground-subtle flex-shrink-0"}):(0,i.jsx)(mn,{className:"h-3 w-3 text-foreground-subtle flex-shrink-0"}),(0,i.jsx)("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-foreground-subtle flex-1 truncate",children:e}),(0,i.jsx)("span",{className:"text-[10px] font-medium text-foreground-subtle/70 tabular-nums",children:t})]})})}),r&&a.map(g=>(0,i.jsx)(wy,{trpc:c,accessory:g,showType:d,showManufacturer:u,showFeatures:f,onNavigate:h,muted:m},g.id))]})}function ky(e){return jl(e.type).label.toLowerCase()}function Ty(e){return e.name.toLowerCase()}function pU(e){return e==="name"?(t,r)=>Ty(t).localeCompare(Ty(r)):e==="type"?(t,r)=>ky(t).localeCompare(ky(r)):VF}function Cy(e,t){return e===null||e.columnId!==t?{columnId:t,dir:"asc"}:e.dir==="asc"?{columnId:t,dir:"desc"}:null}function Iy(e,t){if(t===null)return[...e];const r=pU(t.columnId),n=t.dir==="asc"?1:-1;return[...e].sort((s,a)=>{if(t.columnId==="manufacturer"){const c=dy(s);if(c!==dy(a))return c?-1:1}return n*r(s,a)})}var vU={cards:24,table:50};function bU(e){const{devices:t,trpc:r,context:n="devices",defaultView:s="table",filters:a,forceAddon:c,resolveIntegrationIcon:d,resolveParent:u,onNavigate:f,pageSize:h=vU,urlScope:m="root",lsKey:g=m==="root"?"devices":"integrations:nested",renderRowAction:p,onDeleteDevice:y,selectable:S=!1,selectedIds:E,onSelectionChange:T,batchActions:j}=e,[N,O]=(0,l.useState)(!1),[U,z]=(0,l.useState)(new Set),K=E??U,G=At=>{const jt=new Set(K);jt.has(At)?jt.delete(At):jt.add(At),E===void 0&&z(jt),T?.(jt)},X=()=>{E===void 0?z(new Set):T?.(new Set)},te=()=>{X(),O(!1)},ne=S||j!==void 0&&N,ae=j!==void 0&&N,oe=(0,l.useMemo)(()=>ay(n),[n]),[pe,le]=(0,l.useState)(null),se=At=>le(jt=>Cy(jt,At)),Ce=a?.typeOptions,q=(0,l.useMemo)(()=>Ce??$v(),[Ce]),Q=uU({scope:m,defaultView:s,lsKey:g}),ie=Q.state.view,[be,we]=gy(h.table),Re=ie==="cards"?h.cards:be,[Ee,Fe]=(0,l.useState)(Q.state.q),Ge=sh(Ee,300);(0,l.useEffect)(()=>{Ge!==Q.state.q&&Q.setQ(Ge)},[Ge]);const Be=(0,l.useMemo)(()=>c!==void 0?[c]:Q.state.addons,[c,Q.state.addons]),st=(0,l.useMemo)(()=>{const At=new Map;for(const jt of t){if(jt.parentDeviceId===null||jt.parentDeviceId===void 0)continue;const rr=At.get(jt.parentDeviceId);rr?rr.push(jt):At.set(jt.parentDeviceId,[jt])}return At},[t]),at=(0,l.useMemo)(()=>{const At=Q.state.q,jt=Be.length>0?new Set(Be):null,rr=Q.state.types.length>0?new Set(Q.state.types):null;return t.filter(Gt=>!(jt&&!jt.has(Gt.addonId)||rr&&!rr.has(Hv(Gt,st.get(Gt.id)))||At.trim()!==""&&!hs(At,Gt.name)&&!hs(At,Gt.stableId)))},[t,st,Be,Q.state.types,Q.state.q]),We=(0,l.useMemo)(()=>rU(at),[at]),ct=(0,l.useMemo)(()=>Iy(We.topLevel,pe),[We.topLevel,pe]),He=(0,l.useMemo)(()=>{if(Q.state.q.trim()==="")return new Set;const At=Q.state.q,jt=new Set;for(const[rr,Gt]of We.accessoriesByParent.entries())Gt.some(sn=>hs(At,sn.name)||hs(At,sn.stableId))&&jt.add(rr);return jt},[We.accessoriesByParent,Q.state.q]),$e=We.topLevel.length,Ke=Math.max(1,Math.ceil($e/Re)),ft=Math.min(Q.state.page,Ke),St=(ft-1)*Re,Rt=ct.slice(St,St+Re);(0,l.useEffect)(()=>{ft!==Q.state.page&&Q.setPage(ft)},[ft]),yU();const dr=Be.length>0||Q.state.types.length>0||Q.state.q!=="",Er=$e===0;return(0,i.jsxs)("div",{className:"flex flex-col gap-3",children:[(0,i.jsxs)("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[(0,i.jsx)(sU,{view:ie,onViewChange:Q.setView,typeOptions:q,selectedTypes:Q.state.types,onTypesChange:Q.setTypes,addons:a?.addons,selectedAddons:Q.state.addons,onAddonsChange:Q.setAddons,hideAddons:c!==void 0}),(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[j!==void 0&&(N?(0,i.jsxs)("button",{type:"button",onClick:te,className:"inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md border border-border bg-surface text-[11px] font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:[(0,i.jsx)(mr,{className:"h-3 w-3"}),"Done"]}):(0,i.jsxs)("button",{type:"button",onClick:()=>O(!0),className:"inline-flex items-center gap-1.5 h-7 px-2.5 rounded-md border border-border bg-surface text-[11px] font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:[(0,i.jsx)(Dp,{className:"h-3 w-3"}),"Select"]})),(0,i.jsxs)("div",{className:"relative",children:[(0,i.jsx)(ls,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-foreground-subtle pointer-events-none"}),(0,i.jsx)("input",{type:"text",value:Ee,onChange:At=>Fe(At.target.value),placeholder:"Search by name or stableId","aria-label":"Search devices by name or stableId",className:"h-7 pl-7 pr-2.5 rounded-md border border-border bg-surface text-[11px] text-foreground placeholder:text-foreground-subtle/60 focus:outline-none focus:ring-1 focus:ring-primary/40 w-56"})]})]})]}),j!==void 0&&N&&(0,i.jsx)(XF,{selectedIds:K,onClear:X,remove:j.remove,disable:j.disable,enable:j.enable}),Er?(0,i.jsx)(oU,{variant:dr?"filtered":"nofilter",onClearFilters:dr?Q.clearFilters:void 0}):ie==="cards"?(0,i.jsx)(xf,{value:We.accessoriesByParent,children:(0,i.jsx)(dU,{rows:Rt,accessoriesByParent:We.accessoriesByParent,trpc:r,resolveIntegrationIcon:d??null,resolveParent:u??null,onNavigate:f??null,renderRowAction:p??null,selectable:ne,rowClickSelects:ae,activeSelected:K,onToggleSelection:G})}):(0,i.jsx)(xf,{value:We.accessoriesByParent,children:(0,i.jsx)(mU,{rows:Rt,accessoriesByParent:We.accessoriesByParent,autoExpandedParents:He,visibleColumns:oe,sort:pe,onSort:se,devices:at,trpc:r,resolveIntegrationIcon:d??null,resolveParent:u??null,onNavigate:f??null,renderRowAction:p??null,onDeleteDevice:y??null,selectable:ne,rowClickSelects:ae,activeSelected:K,onToggleSelection:G})}),!Er&&ie==="table"&&(0,i.jsxs)("div",{className:"flex items-center justify-between gap-4 flex-wrap pt-2 text-[11px] text-foreground-subtle",children:[(0,i.jsxs)("div",{className:"inline-flex items-center gap-2",children:[$e<=be&&(0,i.jsxs)("span",{children:[$e," ",$e===1?"device":"devices"]}),(0,i.jsxs)("div",{className:"inline-flex items-center gap-1.5",children:[(0,i.jsx)("span",{"aria-hidden":"true",children:"Per page"}),(0,i.jsx)("select",{"aria-label":"Devices per page",value:be,onChange:At=>{we(Number.parseInt(At.target.value,10))},className:"h-7 px-1.5 rounded-md border border-border bg-surface text-[11px] text-foreground focus:outline-none focus:ring-1 focus:ring-primary/40",children:ah.map(At=>(0,i.jsx)("option",{value:At,children:At},At))})]})]}),(0,i.jsx)(uh,{currentPage:ft,totalItems:$e,pageSize:Re,onPageChange:Q.setPage})]}),!Er&&ie==="cards"&&(0,i.jsx)(uh,{currentPage:ft,totalItems:$e,pageSize:Re,onPageChange:Q.setPage}),c===void 0&&dr&&$e>0&&(0,i.jsxs)("p",{className:"text-[11px] text-foreground-subtle",children:["Showing ",$e," of ",py(t).length," devices",Be.length>0&&(0,i.jsxs)(i.Fragment,{children:[" ","· filtered by"," ",(0,i.jsx)("strong",{className:"text-primary",children:Be.map(At=>a?.addons?.find(jt=>jt.id===At)?.name??At).join(", ")})]})]})]})}function yU(){(0,ye.useQueryClient)()}function xU(e){const{items:t,getKey:r,getSearchText:n,renderItem:s,getFilterType:a,mapFilterOption:c,filterOptions:d,filterLabel:u="Type",columns:f,renderExpanded:h,isExpanded:m,rowClassName:g,onRowClick:p,isLoading:y=!1,searchPlaceholder:S="Search",emptyLabel:E="No items found.",pageSize:T=100,toolbar:j}=e,[N,O]=(0,l.useState)(""),U=sh(N,300),[z,K]=(0,l.useState)([]),[G,X]=(0,l.useState)(1);(0,l.useEffect)(()=>{X(1)},[U,z]);const te=(0,l.useMemo)(()=>{if(!a)return[];if(d)return d;const q=new Set;for(const Q of t){const ie=a(Q);ie!==null&&ie!==""&&q.add(ie)}return[...q].sort().map(Q=>{const ie=c?.(Q);return{id:Q,label:ie?.label??Q,...ie?.icon?{icon:ie.icon}:{}}})},[t,a,c,d]),ne=(0,l.useMemo)(()=>new Set(z),[z]),ae=(0,l.useMemo)(()=>{const q=U;return t.filter(Q=>{if(ne.size>0&&a){const ie=a(Q);if(ie===null||!ne.has(ie))return!1}return!(q.trim()!==""&&!hs(q,n(Q)))})},[t,U,n,ne,a]),oe=ae.length,pe=Math.max(1,Math.ceil(oe/T)),le=Math.min(G,pe),se=(le-1)*T,Ce=ae.slice(se,se+T);return(0,l.useEffect)(()=>{le!==G&&X(le)},[le,G]),(0,i.jsxs)("div",{className:"flex flex-col gap-3 h-full min-h-0",children:[(0,i.jsxs)("div",{className:"flex items-center justify-between gap-3 flex-wrap shrink-0",children:[a&&te.length>0?(0,i.jsx)(yy,{label:u,options:te,selected:z,onChange:K}):(0,i.jsx)("span",{}),(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsxs)("div",{className:"relative",children:[(0,i.jsx)(ls,{className:"absolute left-2 top-1/2 -translate-y-1/2 h-3 w-3 text-foreground-subtle pointer-events-none"}),(0,i.jsx)("input",{type:"text",value:N,onChange:q=>O(q.target.value),placeholder:S,"aria-label":S,className:"h-7 pl-7 pr-2.5 rounded-md border border-border bg-surface text-[11px] text-foreground placeholder:text-foreground-subtle/60 focus:outline-none focus:ring-1 focus:ring-primary/40 w-56"})]}),j]})]}),(0,i.jsx)("div",{className:"flex-1 min-h-0 overflow-y-auto",children:y&&oe===0?(0,i.jsx)("div",{className:"flex items-center justify-center py-12 text-xs text-foreground-subtle",children:"Loading…"}):oe===0?(0,i.jsx)("div",{className:"flex items-center justify-center py-12 text-xs text-foreground-subtle",children:E}):f?(0,i.jsx)("div",{className:"rounded-lg border border-border bg-surface overflow-x-auto",children:(0,i.jsxs)("table",{className:"w-full border-collapse",children:[(0,i.jsx)("thead",{children:(0,i.jsx)("tr",{className:"border-b border-border",children:f.map(q=>(0,i.jsx)("th",{className:`text-left px-2 py-2 text-[9.5px] font-medium uppercase tracking-wider text-foreground-subtle ${q.headerClassName??""}`,children:q.header},q.key))})}),(0,i.jsx)("tbody",{children:Ce.map(q=>(0,i.jsxs)(l.Fragment,{children:[(0,i.jsx)("tr",{className:`border-b border-border/60 ${p?"cursor-pointer hover:bg-surface-hover transition-colors":""} ${g?.(q)??""}`,...p?{onClick:()=>p(q),role:"button",tabIndex:0,onKeyDown:Q=>{(Q.key==="Enter"||Q.key===" ")&&(Q.preventDefault(),p(q))}}:{},children:f.map(Q=>(0,i.jsx)("td",{className:`px-2 py-2 align-middle ${Q.cellClassName??""}`,children:Q.cell(q)},Q.key))}),h&&m?.(q)&&(0,i.jsx)("tr",{className:"border-b border-border/60 bg-surface/40",children:(0,i.jsx)("td",{colSpan:f.length,className:"px-2 pb-2 pt-0",children:h(q)})})]},r(q)))})]})}):(0,i.jsx)("div",{className:"space-y-1.5",children:Ce.map(q=>(0,i.jsx)(l.Fragment,{children:s?.(q)},r(q)))})}),(0,i.jsx)("div",{className:"shrink-0",children:(0,i.jsx)(uh,{currentPage:le,totalItems:oe,pageSize:T,onPageChange:X})})]})}function Py(e){return"mode"in e&&e.mode==="generic"?(0,i.jsx)(xU,{...e}):(0,i.jsx)(bU,{...e})}function SU({trpc:e,deviceId:t,features:r,layout:n}){const{cap:s,slice:a,available:c}=bt({trpc:e,deviceId:t,cap:m=>m.cover,slice:m=>m.state.cover});if(a===void 0)return null;const d=(r??[]).includes("cover-positionable"),u=!c,f=a.position,h=m=>{u||!m||m({})};return(0,i.jsxs)("div",{className:A("inline-flex items-center gap-1",n==="full"&&"flex-col items-stretch gap-2"),children:[(0,i.jsxs)("div",{className:"inline-flex items-center gap-1",children:[(0,i.jsx)(hh,{label:"Open",busy:u,onClick:()=>h(s?.open),children:(0,i.jsx)(Ti,{className:"h-3.5 w-3.5"})}),(0,i.jsx)(hh,{label:"Stop",busy:u,onClick:()=>h(s?.stop),children:(0,i.jsx)(Un,{className:"h-3 w-3"})}),(0,i.jsx)(hh,{label:"Close",busy:u,onClick:()=>h(s?.close),children:(0,i.jsx)(fr,{className:"h-3.5 w-3.5"})})]}),d&&n==="full"&&(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs text-foreground-subtle",children:[(0,i.jsx)("span",{children:"Position"}),(0,i.jsx)("input",{"aria-label":"Position",type:"range",min:0,max:100,step:1,value:f??0,disabled:u,onChange:m=>{u||s?.setPosition({position:Number(m.target.value)})}}),(0,i.jsxs)("span",{className:"tabular-nums w-8 text-right",children:[f??"—","%"]})]})]})}function hh({label:e,busy:t,onClick:r,children:n}){return(0,i.jsx)("button",{type:"button","aria-label":e,title:e,disabled:t,onClick:s=>{s.stopPropagation(),r()},className:A("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",t&&"opacity-40 cursor-not-allowed"),children:n})}var _U=["cover","lock-control","switch","brightness","fan-control","climate-control","media-player","control"],wU=240,EU=6;function kU({icon:e,title:t,children:r}){const n=(0,l.useRef)(null),s=(0,l.useRef)(null),[a,c]=(0,l.useState)(null),d=a!==null,u=()=>c(null),f=()=>{const h=n.current;if(!h)return;const m=h.getBoundingClientRect(),g=8,p=Math.min(wU,window.innerWidth-g*2),y=Math.max(g,Math.min(m.right-p,window.innerWidth-p-g));c({top:m.bottom+EU,left:y,width:p})};return(0,l.useEffect)(()=>{if(!d)return;const h=g=>{const p=g.target;s.current?.contains(p)||n.current?.contains(p)||u()},m=g=>{g.key==="Escape"&&u()};return document.addEventListener("mousedown",h),document.addEventListener("touchstart",h),document.addEventListener("keydown",m),()=>{document.removeEventListener("mousedown",h),document.removeEventListener("touchstart",h),document.removeEventListener("keydown",m)}},[d]),(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("button",{ref:n,type:"button",title:t,"aria-label":t,"aria-haspopup":"dialog","aria-expanded":d,onClick:h=>{h.stopPropagation(),d?u():f()},className:A("inline-flex h-5 w-5 items-center justify-center rounded text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors flex-shrink-0",d&&"bg-surface-hover text-foreground"),children:(0,i.jsx)(e,{className:"h-3 w-3"})}),a&&(0,I.createPortal)((0,i.jsx)("div",{ref:s,style:{position:"fixed",top:a.top,left:a.left,width:a.width},className:"z-[9999] rounded-lg border border-border bg-surface shadow-lg shadow-black/30 p-2",onClick:h=>h.stopPropagation(),children:r}),document.body)]})}function TU({lastChangedAt:e,className:t}){const r=ri(e);return(0,i.jsxs)("span",{title:r===null?"Unavailable":`Unavailable · last seen ${r}`,className:A("inline-flex items-center gap-1 rounded-full px-2 py-0.5","bg-surface-hover text-foreground-subtle text-[10px] font-medium","border border-border",t),children:[(0,i.jsx)(Kp,{className:"h-3 w-3 flex-shrink-0","aria-hidden":"true"}),(0,i.jsx)("span",{children:"Unavailable"}),r!==null?(0,i.jsx)("span",{className:"text-foreground-subtle/70",children:`· last seen ${r}`}):null]})}function CU({trpc:e,children:t,linkDeviceId:r,primaryChildEntityId:n,onSetPrimary:s}){const a=ds(t,r,n),c=a===null?void 0:t.find(u=>u.id===a.id);if(c===void 0)return(0,i.jsx)("div",{className:"flex h-full w-full items-center justify-center p-4 text-[11px] italic text-foreground-subtle",children:"No child entities to display."});const d=zl(c.type)?.HeroCard??Tf;return(0,i.jsxs)("div",{className:"flex h-full w-full flex-col items-stretch gap-3 p-3 sm:p-4",children:[t.length>1&&(0,i.jsx)(IU,{childrenList:t,selectedId:c.id,onSetPrimary:s}),(0,i.jsx)(d,{trpc:e,deviceId:c.id,features:c.features})]})}function IU({childrenList:e,selectedId:t,onSetPrimary:r}){return(0,i.jsxs)("label",{className:"flex items-center justify-end gap-1.5 self-end text-[11px] text-foreground-subtle",children:[(0,i.jsx)("span",{children:"primary child:"}),(0,i.jsx)("select",{value:t,onChange:n=>{const s=Number(n.target.value);if(!Number.isFinite(s)||s===t)return;const a=e.find(c=>c.id===s);a!==void 0&&r(Nl(a))},className:"rounded-md border border-border bg-surface px-1.5 py-0.5 text-[11px] text-foreground",children:e.map(n=>(0,i.jsxs)("option",{value:n.id,children:[n.name," (",n.type,")"]},n.id))})]})}function PU({options:e,value:t,onChange:r}){return(0,i.jsx)("div",{className:"flex flex-wrap gap-2",children:e.map(n=>{const s=n.id===t;return(0,i.jsxs)("button",{onClick:()=>n.available&&r(n.id),disabled:!n.available,className:`flex items-center gap-2 rounded-lg border px-3 py-2 text-xs font-medium transition-all ${s?"border-primary/40 bg-primary/10 text-primary":n.available?"border-border bg-surface text-foreground-subtle hover:bg-surface-hover hover:text-foreground":"border-border/40 bg-surface/40 text-foreground-subtle/40 cursor-not-allowed"}`,children:[(0,i.jsx)(BT,{className:"h-3.5 w-3.5 shrink-0"}),n.label,n.isBest&&(0,i.jsxs)("span",{className:"inline-flex items-center gap-0.5 rounded-full bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-semibold text-amber-400",children:[(0,i.jsx)(AC,{className:"h-2.5 w-2.5"}),"Best"]}),n.platformScore!=null&&(0,i.jsxs)("span",{className:"text-[10px] text-foreground-subtle/60",children:["(",n.platformScore,")"]}),(0,i.jsx)("span",{className:`h-1.5 w-1.5 rounded-full ${n.available?"bg-success":"bg-danger"}`})]},n.id)})})}function AU(e,t){const r=new Set(t.slots.flatMap(c=>c.addons.map(d=>d.id))),n=[];function s(c){if(!r.has(c.addonId))return n.push(`Addon "${c.addonId}" is no longer available — step removed`),null;const d=t.slots.flatMap(h=>h.addons).find(h=>h.id===c.addonId);let u=c.modelId;if(d&&!d.models.some(h=>h.id===u)){const h=d.defaultModelId;n.push(`Model "${u}" not available for ${c.addonId} — using "${h}"`),u=h}const f=c.children.map(h=>s(h)).filter(h=>h!==null);return{...c,modelId:u,children:f}}const a=e.map(c=>s(c)).filter(c=>c!==null);return{valid:n.length===0,steps:a,warnings:n}}function jU(e){const t=new Map;for(const r of e.slots)for(const n of r.addons)t.set(n.id,n);return t}function mh(e){return{addonId:e.id,addonName:e.name,slot:e.slot,inputClasses:[...e.inputClasses],outputClasses:[...e.outputClasses],enabled:!0,modelId:e.defaultModelId,children:[]}}function gh({addon:e,onClick:t}){return(0,i.jsx)("button",{type:"button",onClick:t,className:"w-full rounded-lg border border-dashed border-border/60 px-3 py-2.5 text-left transition-all hover:border-primary/30 hover:bg-surface/60 group",children:(0,i.jsxs)("div",{className:"flex items-center gap-3",children:[(0,i.jsx)(MT,{className:"h-[18px] w-[18px] text-foreground-subtle/30 group-hover:text-primary/60 shrink-0"}),(0,i.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,i.jsx)("span",{className:"text-[13px] font-medium text-foreground-subtle/50 group-hover:text-foreground-subtle block truncate",children:e.name}),(0,i.jsxs)("div",{className:"flex items-center gap-1 mt-0.5 flex-wrap",children:[e.inputClasses.map(r=>(0,i.jsx)("span",{className:"text-[9px] uppercase font-semibold tracking-wide px-1.5 py-0.5 rounded bg-blue-500/8 text-blue-400/50",children:r},r)),e.inputClasses.length>0&&e.outputClasses.length>0&&(0,i.jsx)("span",{className:"text-foreground-subtle/25 text-[10px]",children:"→"}),e.outputClasses.map(r=>(0,i.jsx)("span",{className:"text-[9px] uppercase font-semibold tracking-wide px-1.5 py-0.5 rounded bg-green-500/8 text-green-400/50",children:r},r))]})]})]})})}function NU({schema:e,steps:t,onChange:r,templates:n,selectedTemplateId:s,onSelectTemplate:a,onSaveTemplate:c,onUpdateTemplate:d,onDeleteTemplate:u,readOnly:f=!1,excludeAddons:h=[],hideTemplates:m=!1,showOnlyEnabled:g=!1,showSlotLabels:p=!1,toggleMode:y="simple",overrides:S={},onOverrideChange:E,inheritedEnabledByAddon:T={},hideModelAndSettings:j=!1}){const N=be=>({toggleMode:y,hideModelAndSettings:j,...y==="threeState"?{overrideState:S[be]!==void 0?S[be]:null,onOverrideChange:E?we=>E(be,we):void 0,inheritedEnabled:T[be]}:{}}),O=(0,l.useMemo)(()=>new Set(h),[h]),U=(0,l.useMemo)(()=>jU(e),[e]),[z,K]=(0,l.useState)([]),G=s?JSON.stringify(t)!==JSON.stringify(n.find(be=>be.id===s)?.steps):!1;function X(be){const we=be.target.value||null;if(we){const Re=n.find(Ee=>Ee.id===we);Re&&K([...AU(Re.steps,e).warnings])}else K([]);a(we)}function te(){s&&d(s,t)}function ne(){const be=window.prompt("Template name:");be?.trim()&&c(be.trim(),t)}function ae(){if(!s)return;const be=n.find(we=>we.id===s);be&&window.confirm(`Delete template "${be.name}"?`)&&u(s)}function oe(be){r(t.map(we=>we.addonId!==be.addonId?we:pe(be)))}function pe(be){const we=be.children.some(Re=>Re.enabled||Re.children.some(Ee=>Ee.enabled));return{...be,enabled:be.enabled||we,children:be.children.map(Re=>{const Ee=Re.children.some(Fe=>Fe.enabled);return{...Re,enabled:Re.enabled||Ee}})}}function le(be,we){const Re=mh(we);r(t.map(Ee=>Ee.addonId!==be?Ee:{...Ee,children:[...Ee.children,Re]}))}function se(be){const we=new Set;for(const Re of be){we.add(Re.addonId);for(const Fe of Re.children)we.add(Fe.addonId);const Ee=se(Re.children);for(const Fe of Ee)we.add(Fe)}return we}const Ce=se(t);function q(be){const we=U.get(be.addonId);if(!we)return[];const Re=e.slots.find(Be=>Be.id===we.slot)?.parentSlot==null,Ee=we.childSlots,Fe=new Set(be.children.map(Be=>Be.addonId)),Ge=[];for(const Be of e.slots)if(Ee.includes(Be.id))for(const st of Be.addons){if(Fe.has(st.id)||O.has(st.id))continue;const at=st.inputClasses.length===0;at&&!Re||(at||st.inputClasses.some(We=>be.outputClasses.includes(We)))&&Ge.push(st)}return Ge}function Q(be){const we=g?{...be,children:be.children.filter(Ee=>Ee.enabled).map(Ee=>({...Ee,children:Ee.children.filter(Fe=>Fe.enabled)}))}:be,Re=g?[]:q(we);return(0,i.jsxs)("div",{className:"space-y-1.5",children:[(0,i.jsx)(Cl,{step:we,schema:U.get(we.addonId)??null,allSchemas:U,onChange:oe,onDelete:f?void 0:Ee=>r(t.filter(Fe=>Fe.addonId!==Ee)),readOnly:f,...N(we.addonId)}),(we.children.length>0||Re.length>0)&&(0,i.jsxs)("div",{className:"ml-4 pl-3 border-l border-border/60 space-y-1.5",children:[p&&(0,i.jsx)("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/40",children:"Slot: Cropper / Classifier"}),we.children.map(Ee=>{const Fe=q(Ee);return(0,i.jsxs)("div",{className:"space-y-1.5",children:[(0,i.jsx)(Cl,{step:Ee,schema:U.get(Ee.addonId)??null,allSchemas:U,depth:1,onChange:Ge=>{oe({...we,children:we.children.map(Be=>Be.addonId===Ge.addonId?Ge:Be)})},onDelete:f?void 0:Ge=>{oe({...we,children:we.children.filter(Be=>Be.addonId!==Ge)})},readOnly:f,...N(Ee.addonId)}),(Ee.children.length>0||Fe.length>0)&&(0,i.jsxs)("div",{className:"ml-4 pl-3 border-l border-border/40 space-y-1.5",children:[p&&(0,i.jsx)("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/30",children:"Slot: Recognizer"}),Ee.children.map(Ge=>(0,i.jsx)(Cl,{step:Ge,schema:U.get(Ge.addonId)??null,allSchemas:U,depth:2,onChange:Be=>{oe({...we,children:we.children.map(st=>st.addonId===Ee.addonId?{...st,children:st.children.map(at=>at.addonId===Be.addonId?Be:at)}:st)})},onDelete:f?void 0:Be=>{oe({...we,children:we.children.map(st=>st.addonId===Ee.addonId?{...st,children:st.children.filter(at=>at.addonId!==Be)}:st)})},readOnly:f,...N(Ge.addonId)},Ge.addonId)),!f&&Fe.map(Ge=>(0,i.jsx)(gh,{addon:Ge,onClick:()=>{const Be=mh(Ge);oe({...we,children:we.children.map(st=>st.addonId===Ee.addonId?{...st,children:[...st.children,Be]}:st)})}},Ge.id))]})]},Ee.addonId)}),!f&&Re.map(Ee=>(0,i.jsx)(gh,{addon:Ee,onClick:()=>le(we.addonId,Ee)},Ee.id))]})]},we.addonId)}const ie=e.slots.filter(be=>be.parentSlot===null).sort((be,we)=>be.priority-we.priority);return(0,i.jsxs)("div",{className:"space-y-4",children:[!m&&(0,i.jsx)("div",{className:"rounded-lg border border-border bg-surface p-3",children:(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsx)("div",{className:"relative flex-1 min-w-0",children:(0,i.jsxs)("select",{value:s??"",onChange:X,className:"w-full rounded-lg border border-border bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:border-primary/50",children:[(0,i.jsx)("option",{value:"",children:"No template"}),n.map(be=>(0,i.jsx)("option",{value:be.id,children:be.name},be.id))]})}),G&&(0,i.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-amber-500 shrink-0"}),(0,i.jsx)("button",{onClick:te,disabled:!s||f,title:"Save",className:A("p-2 rounded-lg border border-border transition-colors",s&&!f?"text-foreground-subtle hover:bg-surface-hover":"text-foreground-subtle/30 cursor-not-allowed"),children:(0,i.jsx)(Bp,{className:"h-4 w-4"})}),(0,i.jsx)("button",{onClick:ne,disabled:f,title:"Save As",className:A("p-2 rounded-lg border border-border transition-colors",f?"text-foreground-subtle/30 cursor-not-allowed":"text-foreground-subtle hover:bg-surface-hover"),children:(0,i.jsx)(UT,{className:"h-4 w-4"})}),(0,i.jsx)("button",{onClick:ae,disabled:!s||f,title:"Delete",className:A("p-2 rounded-lg border border-border transition-colors",s&&!f?"text-foreground-subtle hover:text-danger":"text-foreground-subtle/30 cursor-not-allowed"),children:(0,i.jsx)(en,{className:"h-4 w-4"})})]})}),z.length>0&&(0,i.jsxs)("div",{className:"rounded-lg border border-amber-500/30 bg-amber-500/5 p-3 text-xs text-amber-400 space-y-1",children:[(0,i.jsxs)("div",{className:"flex items-center justify-between",children:[(0,i.jsx)("span",{className:"font-medium",children:"Template loaded with warnings:"}),(0,i.jsx)("button",{onClick:()=>K([]),className:"text-amber-400/60 hover:text-amber-400",children:(0,i.jsx)(mr,{className:"h-3.5 w-3.5"})})]}),z.map((be,we)=>(0,i.jsxs)("div",{children:["• ",be]},we))]}),ie.map(be=>{const we=t.filter(Be=>Be.slot===be.id&&!O.has(Be.addonId)),Re=g?we.filter(Be=>Be.enabled):we,Ee=g?[]:be.addons.filter(Be=>!Ce.has(Be.id)&&!O.has(Be.id)),Fe=new Map,Ge=[];for(const Be of Re)Be.group?(Fe.has(Be.group)||Fe.set(Be.group,[]),Fe.get(Be.group).push(Be)):Ge.push(Be);return(0,i.jsxs)("div",{className:"space-y-2",children:[p&&(0,i.jsxs)("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/50",children:["Slot: ",be.label]}),Ge.map(Be=>Q(Be)),[...Fe.entries()].map(([Be,st])=>(0,i.jsxs)("div",{className:"space-y-2 rounded-lg border border-border/40 p-2",children:[(0,i.jsx)("span",{className:"text-[10px] font-semibold uppercase tracking-widest text-foreground-subtle/50 px-1",children:Be}),st.map(at=>Q(at))]},Be)),!f&&Ee.map(Be=>(0,i.jsx)(gh,{addon:Be,onClick:()=>{r([...t,mh(Be)])}},Be.id))]},be.id)})]})}var po={person:"#3b82f6",vehicle:"#f59e0b",animal:"#22c55e",face:"#a855f7",plate:"#ec4899",bird:"#14b8a6",dog:"#84cc16",cat:"#f97316",car:"#f59e0b",truck:"#d97706",bus:"#b45309",motorcycle:"#eab308",bicycle:"#ca8a04",motion:"#facc15"},Ay=["#ef4444","#8b5cf6","#06b6d4","#f97316","#10b981","#6366f1","#e11d48","#0891b2","#7c3aed","#059669"],DU="#f59e42";function zr(e,t){if(t?.[e])return t[e];if(t?.[e.toLowerCase()])return t[e.toLowerCase()];if(po[e])return po[e];if(po[e.toLowerCase()])return po[e.toLowerCase()];let r=0;for(let n=0;n<e.length;n++)r=r*31+(e.codePointAt(n)??0)>>>0;return Ay[r%Ay.length]??"#f59e42"}function MU({src:e,imageWidth:t,imageHeight:r,detections:n=[],classColors:s,aspectRatio:a,className:c,placeholder:d,showConfidence:u=!0,minConfidence:f=0,borderWidth:h=2}){function m(T){return zr(T,s)}const g=a??(t&&r?`${t}/${r}`:"16/9"),p=n.filter(T=>T.score>=f),y=p.filter(T=>T.kind==="first-level"),S=p.filter(T=>T.kind==="detail"),E=LU(S,T=>T.parentId??"");return(0,i.jsx)("div",{className:A("rounded-lg border border-border bg-surface overflow-hidden relative",c),style:{aspectRatio:g},children:e?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)("img",{src:e,className:"absolute inset-0 w-full h-full object-fill",alt:""}),p.map((T,j)=>T.debug?.mask&&T.debug.maskWidth&&T.debug.maskHeight?(0,i.jsx)($U,{mask:T.debug.mask,maskWidth:T.debug.maskWidth,maskHeight:T.debug.maskHeight,bbox:T.bbox,imageWidth:t,imageHeight:r,color:m(T.macroClass)},`mask-${j}`):null),y.map(T=>{const j=E.get(T.id)??[];return(0,i.jsx)(jy,{detection:T,imageWidth:t,imageHeight:r,color:m(T.macroClass),showConfidence:u,borderWidth:T.debug?.mask?1:h,children:j.map(N=>(0,i.jsx)(RU,{child:N,parentBbox:T.bbox,color:m(N.macroClass),showConfidence:u},`child-${N.id}`))},`det-${T.id}`)}),S.filter(T=>!T.parentId||!y.some(j=>j.id===T.parentId)).map(T=>(0,i.jsx)(jy,{detection:T,imageWidth:t,imageHeight:r,color:m(T.macroClass),showConfidence:u,borderWidth:h},`orphan-${T.id}`))]}):(0,i.jsx)("div",{className:"w-full h-full flex items-center justify-center text-foreground-subtle text-sm",children:d??"No image loaded"})})}function jy({detection:e,imageWidth:t,imageHeight:r,color:n,showConfidence:s,borderWidth:a,children:c}){const{x:d,y:u,width:f,height:h}=e.bbox,m=(0,i.jsxs)("div",{className:"absolute left-0 flex flex-col items-start gap-px",style:{bottom:"100%",marginBottom:"2px"},children:[(0,i.jsxs)("span",{className:"text-[10px] px-1 rounded-sm whitespace-nowrap text-white",style:{backgroundColor:n},children:[e.macroClass,s&&` ${(e.score*100).toFixed(0)}%`]}),e.labels.map((g,p)=>(0,i.jsxs)("span",{className:"text-[9px] font-semibold px-1 rounded-sm whitespace-nowrap text-white",style:{backgroundColor:zr(g.label)},children:[g.label," ",(g.score*100).toFixed(0),"%"]},`${e.id}-lbl-${p}`))]});return(0,i.jsxs)("div",{className:"absolute rounded-sm",style:{left:`${d/t*100}%`,top:`${u/r*100}%`,width:`${f/t*100}%`,height:`${h/r*100}%`,borderWidth:`${a}px`,borderStyle:"solid",borderColor:n},children:[m,c]})}function $U({mask:e,maskWidth:t,maskHeight:r,bbox:n,imageWidth:s,imageHeight:a,color:c}){const d=(0,l.useRef)(null);return(0,l.useEffect)(()=>{const u=d.current;if(!u)return;const f=u.getContext("2d");if(!f)return;const h=atob(e),m=new Uint8Array(h.length);for(let T=0;T<h.length;T++)m[T]=h.charCodeAt(T);const g=parseInt(c.slice(1,3),16),p=parseInt(c.slice(3,5),16),y=parseInt(c.slice(5,7),16);u.width=t,u.height=r;const S=f.createImageData(t,r),E=t*r;for(let T=0;T<E;T++){const j=T<m.length?m[T]:0,N=T*4;j>0&&(S.data[N]=g,S.data[N+1]=p,S.data[N+2]=y,S.data[N+3]=120)}f.putImageData(S,0,0)},[e,t,r,c]),(0,i.jsx)("canvas",{ref:d,className:"absolute pointer-events-none",style:{left:`${n.x/s*100}%`,top:`${n.y/a*100}%`,width:`${n.width/s*100}%`,height:`${n.height/a*100}%`,imageRendering:"pixelated"}})}function RU({child:e,parentBbox:t,color:r,showConfidence:n}){if(t.width<=0||t.height<=0)return null;const s=(e.bbox.x-t.x)/t.width*100,a=(e.bbox.y-t.y)/t.height*100,c=e.bbox.width/t.width*100,d=e.bbox.height/t.height*100;return(0,i.jsx)("div",{className:"absolute rounded-sm",style:{left:`${Math.max(0,s)}%`,top:`${Math.max(0,a)}%`,width:`${Math.min(100,c)}%`,height:`${Math.min(100,d)}%`,borderWidth:"1px",borderStyle:"solid",borderColor:r},children:(0,i.jsxs)("div",{className:"absolute left-0 flex flex-col items-start gap-px",style:{bottom:"100%",marginBottom:"1px"},children:[(0,i.jsxs)("span",{className:"text-[9px] px-0.5 rounded-sm whitespace-nowrap text-white",style:{backgroundColor:r},children:[e.macroClass,n&&` ${(e.score*100).toFixed(0)}%`]}),e.labels.map((u,f)=>(0,i.jsxs)("span",{className:"text-[8px] font-semibold px-0.5 rounded-sm whitespace-nowrap text-white",style:{backgroundColor:zr(u.label)},children:[u.label," ",(u.score*100).toFixed(0),"%"]},`${e.id}-lbl-${f}`))]})})}function LU(e,t){const r=new Map;for(const n of e){const s=t(n),a=r.get(s)??[];a.push(n),r.set(s,a)}return r}function OU({detections:e,classColors:t,className:r,hiddenKeys:n,onToggleVisibility:s}){const a=t;if(e.length===0)return(0,i.jsx)("div",{className:"text-sm text-foreground-subtle italic text-center py-4",children:"No detections"});const c=e.filter(h=>h.kind==="first-level"),d=e.filter(h=>h.kind==="detail"),u=new Map;for(const h of d){if(!h.parentId)continue;const m=u.get(h.parentId)??[];m.push(h),u.set(h.parentId,m)}const f=d.filter(h=>!h.parentId||!c.some(m=>m.id===h.parentId));return(0,i.jsxs)("div",{className:r,children:[(0,i.jsxs)("div",{className:"text-xs font-medium text-foreground-subtle uppercase tracking-wide mb-2",children:["Detections (",e.length,")"]}),(0,i.jsxs)("div",{className:"space-y-2",children:[c.map(h=>(0,i.jsx)(Ny,{detection:h,children_:u.get(h.id)??[],colors:a,hiddenKeys:n,onToggleVisibility:s},h.id)),f.map(h=>(0,i.jsx)(Ny,{detection:h,children_:[],colors:a,hiddenKeys:n,onToggleVisibility:s},h.id))]})]})}function Ny({detection:e,children_:t,colors:r,hiddenKeys:n,onToggleVisibility:s}){const a=zr(e.macroClass,r),c=!n?.has(e.id),d=e.debug?.mask,u=e.debug?.maskWidth,f=e.debug?.maskHeight,h=e.debug?.alternateLabels;return(0,i.jsxs)("div",{className:`rounded-md border border-border bg-surface p-3 space-y-1 ${c?"":"opacity-40"}`,children:[(0,i.jsxs)("div",{className:"flex justify-between items-center",children:[(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[s&&(0,i.jsx)("input",{type:"checkbox",checked:c,onChange:()=>s(e.id,!c),className:"h-3.5 w-3.5 rounded border-border accent-primary cursor-pointer shrink-0"}),(0,i.jsx)("span",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:a}}),(0,i.jsx)("span",{className:"text-sm font-medium text-foreground",children:e.macroClass}),e.kind==="detail"&&(0,i.jsx)("span",{className:"text-[9px] font-mono px-1 py-0.5 rounded bg-primary/10 text-primary",children:"detail"}),d&&u&&f&&(0,i.jsxs)("span",{className:"text-[9px] font-mono px-1 py-0.5 rounded bg-primary/10 text-primary",children:["mask ",u,"x",f]})]}),(0,i.jsx)(BU,{confidence:e.score})]}),(0,i.jsxs)("div",{className:"text-[10px] text-foreground-subtle font-mono",children:["bbox: [",Math.round(e.bbox.x),", ",Math.round(e.bbox.y),","," ",Math.round(e.bbox.x+e.bbox.width),","," ",Math.round(e.bbox.y+e.bbox.height),"]"]}),e.labels.length>0&&(0,i.jsx)("div",{className:"flex flex-wrap gap-1 mt-1",children:e.labels.map((m,g)=>(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 text-[10px] font-medium px-1.5 py-0.5 rounded-full",style:{backgroundColor:zr(m.label,r)+"20",color:zr(m.label,r)},children:[m.label,(0,i.jsxs)("span",{className:"opacity-60",children:[(m.score*100).toFixed(0),"%"]}),m.detectionId&&(0,i.jsxs)("span",{className:"opacity-40 text-[8px]",children:["→ ",m.detectionId]})]},g))}),h&&Object.keys(h).length>0&&(0,i.jsx)(UU,{alternateLabels:h,colors:r}),t.length>0&&(0,i.jsx)(FU,{items:t,colors:r,hiddenKeys:n,onToggleVisibility:s})]})}function FU({items:e,colors:t,hiddenKeys:r,onToggleVisibility:n}){return(0,i.jsx)("div",{className:"ml-4 mt-1.5 space-y-1.5 border-l-2 border-border pl-3",children:e.map(s=>{const a=zr(s.macroClass,t),c=!r?.has(s.id),d=s.debug?.mask,u=s.debug?.maskWidth,f=s.debug?.maskHeight;return(0,i.jsxs)("div",{className:`text-xs space-y-0.5 ${c?"":"opacity-40"}`,children:[(0,i.jsxs)("div",{className:"flex items-center gap-1.5",children:[n&&(0,i.jsx)("input",{type:"checkbox",checked:c,onChange:()=>n(s.id,!c),className:"h-3 w-3 rounded border-border accent-primary cursor-pointer shrink-0"}),(0,i.jsx)("span",{className:"h-1.5 w-1.5 rounded-full shrink-0",style:{backgroundColor:a}}),(0,i.jsx)("span",{className:"font-medium",style:{color:a},children:s.macroClass}),(0,i.jsxs)("span",{className:"text-foreground-subtle",children:[(s.score*100).toFixed(0),"%"]}),d&&u&&f&&(0,i.jsxs)("span",{className:"text-[9px] font-mono px-1 py-0.5 rounded bg-primary/10 text-primary",children:["mask ",u,"x",f]})]}),s.labels.length>0&&(0,i.jsx)("div",{className:"flex flex-wrap gap-1 ml-5 mt-0.5",children:s.labels.map((h,m)=>(0,i.jsxs)("span",{className:"inline-flex items-center gap-0.5 text-[9px] font-medium px-1 py-0.5 rounded-full",style:{backgroundColor:zr(h.label,t)+"20",color:zr(h.label,t)},children:[h.label," ",(0,i.jsxs)("span",{className:"opacity-60",children:[(h.score*100).toFixed(0),"%"]})]},m))})]},s.id)})})}function UU({alternateLabels:e,colors:t}){const[r,n]=(0,l.useState)(!1),s=Object.keys(e);return(0,i.jsxs)("div",{className:"mt-1",children:[(0,i.jsxs)("button",{onClick:()=>n(a=>!a),className:"text-[9px] text-foreground-subtle hover:text-foreground transition-colors flex items-center gap-1",children:[(0,i.jsx)("span",{className:`transition-transform ${r?"rotate-90":""}`,children:"▶"}),"Alternates (",s.length," source",s.length!==1?"s":"",")"]}),r&&(0,i.jsx)("div",{className:"mt-1 ml-3 space-y-1.5",children:s.map(a=>{const c=e[a];return!c||c.length===0?null:(0,i.jsxs)("div",{children:[(0,i.jsx)("div",{className:"text-[9px] font-medium text-foreground-subtle mb-0.5",children:a}),(0,i.jsx)("div",{className:"flex flex-wrap gap-1",children:c.map((d,u)=>(0,i.jsxs)("span",{className:"inline-flex items-center gap-0.5 text-[9px] px-1 py-0.5 rounded-full",style:{backgroundColor:zr(a,t)+"10",color:zr(a,t),opacity:Math.max(.4,d.score)},children:[d.label,(0,i.jsxs)("span",{className:"opacity-60",children:[(d.score*100).toFixed(1),"%"]})]},u))})]},a)})})]})}function BU({confidence:e}){return(0,i.jsxs)("span",{className:`text-xs font-medium px-2 py-0.5 rounded-full ${e>=.8?"bg-success/10 text-success":e>=.5?"bg-warning/10 text-warning":"bg-danger/10 text-danger"}`,children:[(e*100).toFixed(1),"%"]})}function zU({timings:e,totalMs:t,className:r}){const n=Object.entries(e);return n.length===0&&t===void 0?null:(0,i.jsxs)("div",{className:`rounded-lg border border-border bg-surface p-3 space-y-2 ${r??""}`,children:[(0,i.jsx)("div",{className:"text-xs font-medium text-foreground-subtle uppercase tracking-wide",children:"Timings"}),(0,i.jsxs)("div",{className:"space-y-1 text-xs",children:[n.map(([s,a])=>(0,i.jsxs)("div",{className:"flex justify-between",children:[(0,i.jsx)("span",{className:"text-foreground-subtle",children:s}),(0,i.jsxs)("span",{className:"font-mono text-foreground",children:[a.toFixed(1),"ms"]})]},s)),t!==void 0&&(0,i.jsxs)("div",{className:"flex justify-between pt-1 border-t border-border font-medium text-foreground",children:[(0,i.jsx)("span",{children:"Total"}),(0,i.jsxs)("span",{className:"font-mono",children:[t.toFixed(1),"ms"]})]})]})]})}function GU({images:e,selectedFilename:t,uploadedName:r,onSelect:n,onUpload:s,className:a,accept:c="image/*",uploadLabel:d="Upload..."}){const u=()=>{const f=document.createElement("input");f.type="file",f.accept=c,f.onchange=()=>{const h=f.files?.[0];if(!h)return;const m=new FileReader;m.onload=()=>{const g=m.result,p=g.split(",")[1];p&&s(p,h.name,g)},m.readAsDataURL(h)},f.click()};return(0,i.jsxs)("div",{className:`flex flex-wrap items-center gap-2 ${a??""}`,children:[e.map(f=>(0,i.jsx)("button",{onClick:()=>n(f.filename),className:`px-3 py-1.5 text-xs rounded-md border transition-colors ${t===f.filename?"bg-primary text-primary-foreground border-primary":"bg-surface border-border text-foreground hover:border-primary/50"}`,children:f.id??f.filename.replace(/\.[^.]+$/,"")},f.filename)),(0,i.jsx)("button",{onClick:u,className:"px-3 py-1.5 text-xs rounded-md border border-border bg-surface text-foreground hover:bg-surface-hover transition-colors",children:d}),r&&(0,i.jsx)("span",{className:"text-xs text-foreground-subtle",children:r})]})}var Zl="w-full px-3 py-2 text-sm rounded-md border border-border bg-surface text-foreground focus:outline-none focus:ring-2 focus:ring-primary/50";function ZU({runtime:e,backend:t,modelId:r,agentId:n="hub",runtimes:s,backends:a,models:c,agents:d=[],onRuntimeChange:u,onBackendChange:f,onModelChange:h,onAgentChange:m,layout:g="grid",className:p,showAgent:y=!1}){return(0,i.jsxs)("div",{className:`${g==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4":g==="horizontal"?"flex flex-wrap items-end gap-4":"space-y-3"} ${p??""}`,children:[y&&d.length>0&&(0,i.jsxs)("label",{className:"space-y-1",children:[(0,i.jsx)("span",{className:"text-xs font-medium text-foreground-subtle",children:"Agent"}),(0,i.jsx)("select",{value:n,onChange:S=>m?.(S.target.value),className:Zl,children:d.map(S=>(0,i.jsxs)("option",{value:S.id,children:[S.name," (",S.status,")"]},S.id))})]}),(0,i.jsxs)("label",{className:"space-y-1",children:[(0,i.jsx)("span",{className:"text-xs font-medium text-foreground-subtle",children:"Runtime"}),(0,i.jsx)("select",{value:e,onChange:S=>u(S.target.value),className:Zl,children:s.map(S=>(0,i.jsxs)("option",{value:S.value,disabled:!S.available,children:[S.label,S.available?"":" (unavailable)"]},S.value))})]}),(0,i.jsxs)("label",{className:"space-y-1",children:[(0,i.jsx)("span",{className:"text-xs font-medium text-foreground-subtle",children:"Backend"}),(0,i.jsx)("select",{value:t,onChange:S=>f(S.target.value),className:Zl,children:a.map(S=>(0,i.jsxs)("option",{value:S.id,disabled:!S.available,children:[S.label,S.available?"":" (unavailable)"]},S.id))})]}),(0,i.jsxs)("label",{className:"space-y-1",children:[(0,i.jsx)("span",{className:"text-xs font-medium text-foreground-subtle",children:"Model"}),(0,i.jsx)("select",{value:r,onChange:S=>h(S.target.value),className:Zl,children:c.length===0?(0,i.jsx)("option",{value:"",children:"No compatible models"}):c.map(S=>(0,i.jsxs)("option",{value:S.id,children:[S.name,S.downloaded?" ✓":""]},S.id))})]})]})}var VU=class{constructor(){this.keyToValue=new Map,this.valueToKey=new Map}set(e,t){this.keyToValue.set(e,t),this.valueToKey.set(t,e)}getByKey(e){return this.keyToValue.get(e)}getByValue(e){return this.valueToKey.get(e)}clear(){this.keyToValue.clear(),this.valueToKey.clear()}},Dy=class{constructor(e){this.generateIdentifier=e,this.kv=new VU}register(e,t){this.kv.getByValue(e)||(t||(t=this.generateIdentifier(e)),this.kv.set(t,e))}clear(){this.kv.clear()}getIdentifier(e){return this.kv.getByValue(e)}getValue(e){return this.kv.getByKey(e)}},HU=class extends Dy{constructor(){super(e=>e.name),this.classToAllowedProps=new Map}register(e,t){typeof t=="object"?(t.allowProps&&this.classToAllowedProps.set(e,t.allowProps),super.register(e,t.identifier)):super.register(e,t)}getAllowedProps(e){return this.classToAllowedProps.get(e)}};function KU(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 WU(e,t){const r=KU(e);if("find"in r)return r.find(t);const n=r;for(let s=0;s<n.length;s++){const a=n[s];if(t(a))return a}}function ms(e,t){Object.entries(e).forEach(([r,n])=>t(n,r))}function Vl(e,t){return e.indexOf(t)!==-1}function My(e,t){for(let r=0;r<e.length;r++){const n=e[r];if(t(n))return n}}var qU=class{constructor(){this.transfomers={}}register(e){this.transfomers[e.name]=e}findApplicable(e){return WU(this.transfomers,t=>t.isApplicable(e))}findByName(e){return this.transfomers[e]}},QU=e=>Object.prototype.toString.call(e).slice(8,-1),$y=e=>typeof e>"u",YU=e=>e===null,vo=e=>typeof e!="object"||e===null||e===Object.prototype?!1:Object.getPrototypeOf(e)===null?!0:Object.getPrototypeOf(e)===Object.prototype,ph=e=>vo(e)&&Object.keys(e).length===0,oi=e=>Array.isArray(e),XU=e=>typeof e=="string",JU=e=>typeof e=="number"&&!isNaN(e),e6=e=>typeof e=="boolean",t6=e=>e instanceof RegExp,bo=e=>e instanceof Map,yo=e=>e instanceof Set,Ry=e=>QU(e)==="Symbol",r6=e=>e instanceof Date&&!isNaN(e.valueOf()),Ly=e=>e instanceof Error,Oy=e=>typeof e=="number"&&isNaN(e),n6=e=>e6(e)||YU(e)||$y(e)||JU(e)||XU(e)||Ry(e),i6=e=>typeof e=="bigint",s6=e=>e===1/0||e===-1/0,a6=e=>ArrayBuffer.isView(e)&&!(e instanceof DataView),o6=e=>e instanceof URL,vh=e=>e.replace(/\\/g,"\\\\").replace(/\./g,"\\."),bh=e=>e.map(String).map(vh).join("."),xo=(e,t)=>{const r=[];let n="";for(let a=0;a<e.length;a++){let c=e.charAt(a);if(!t&&c==="\\"){const d=e.charAt(a+1);if(d==="\\"){n+="\\",a++;continue}else if(d!==".")throw Error("invalid path")}if(c==="\\"&&e.charAt(a+1)==="."){n+=".",a++;continue}if(c==="."){r.push(n),n="";continue}n+=c}const s=n;return r.push(s),r};function Tn(e,t,r,n){return{isApplicable:e,annotation:t,transform:r,untransform:n}}var Fy=[Tn($y,"undefined",()=>null,()=>{}),Tn(i6,"bigint",e=>e.toString(),e=>typeof BigInt<"u"?BigInt(e):(console.error("Please add a BigInt polyfill."),e)),Tn(r6,"Date",e=>e.toISOString(),e=>new Date(e)),Tn(Ly,"Error",(e,t)=>{const r={name:e.name,message:e.message};return"cause"in e&&(r.cause=e.cause),t.allowedErrorProps.forEach(n=>{r[n]=e[n]}),r},(e,t)=>{const r=new Error(e.message,{cause:e.cause});return r.name=e.name,r.stack=e.stack,t.allowedErrorProps.forEach(n=>{r[n]=e[n]}),r}),Tn(t6,"regexp",e=>""+e,e=>{const t=e.slice(1,e.lastIndexOf("/")),r=e.slice(e.lastIndexOf("/")+1);return new RegExp(t,r)}),Tn(yo,"set",e=>[...e.values()],e=>new Set(e)),Tn(bo,"map",e=>[...e.entries()],e=>new Map(e)),Tn(e=>Oy(e)||s6(e),"number",e=>Oy(e)?"NaN":e>0?"Infinity":"-Infinity",Number),Tn(e=>e===0&&1/e===-1/0,"number",()=>"-0",Number),Tn(o6,"URL",e=>e.toString(),e=>new URL(e))];function Hl(e,t,r,n){return{isApplicable:e,annotation:t,transform:r,untransform:n}}var Uy=Hl((e,t)=>Ry(e)?!!t.symbolRegistry.getIdentifier(e):!1,(e,t)=>["symbol",t.symbolRegistry.getIdentifier(e)],e=>e.description,(e,t,r)=>{const n=r.symbolRegistry.getValue(t[1]);if(!n)throw new Error("Trying to deserialize unknown symbol");return n}),l6=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array,Uint8ClampedArray].reduce((e,t)=>(e[t.name]=t,e),{}),By=Hl(a6,e=>["typed-array",e.constructor.name],e=>[...e],(e,t)=>{const r=l6[t[1]];if(!r)throw new Error("Trying to deserialize unknown typed array");return new r(e)});function zy(e,t){return e?.constructor?!!t.classRegistry.getIdentifier(e.constructor):!1}var Gy=Hl(zy,(e,t)=>["class",t.classRegistry.getIdentifier(e.constructor)],(e,t)=>{const r=t.classRegistry.getAllowedProps(e.constructor);if(!r)return{...e};const n={};return r.forEach(s=>{n[s]=e[s]}),n},(e,t,r)=>{const n=r.classRegistry.getValue(t[1]);if(!n)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(n.prototype),e)}),Zy=Hl((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 n=r.customTransformerRegistry.findByName(t[1]);if(!n)throw new Error("Trying to deserialize unknown custom value");return n.deserialize(e)}),c6=[Gy,Uy,Zy,By],Vy=(e,t)=>{const r=My(c6,s=>s.isApplicable(e,t));if(r)return{value:r.transform(e,t),type:r.annotation(e,t)};const n=My(Fy,s=>s.isApplicable(e,t));if(n)return{value:n.transform(e,t),type:n.annotation}},Hy={};Fy.forEach(e=>{Hy[e.annotation]=e});var u6=(e,t,r)=>{if(oi(t))switch(t[0]){case"symbol":return Uy.untransform(e,t,r);case"class":return Gy.untransform(e,t,r);case"custom":return Zy.untransform(e,t,r);case"typed-array":return By.untransform(e,t,r);default:throw new Error("Unknown transformation: "+t)}else{const n=Hy[t];if(!n)throw new Error("Unknown transformation: "+t);return n.untransform(e,r)}},gs=(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 Ky(e){if(Vl(e,"__proto__"))throw new Error("__proto__ is not allowed as a property");if(Vl(e,"prototype"))throw new Error("prototype is not allowed as a property");if(Vl(e,"constructor"))throw new Error("constructor is not allowed as a property")}var d6=(e,t)=>{Ky(t);for(let r=0;r<t.length;r++){const n=t[r];if(yo(e))e=gs(e,+n);else if(bo(e)){const s=+n,a=+t[++r]==0?"key":"value",c=gs(e,s);switch(a){case"key":e=c;break;case"value":e=e.get(c);break}}else e=e[n]}return e},yh=(e,t,r)=>{if(Ky(t),t.length===0)return r(e);let n=e;for(let a=0;a<t.length-1;a++){const c=t[a];if(oi(n)){const d=+c;n=n[d]}else if(vo(n))n=n[c];else if(yo(n)){const d=+c;n=gs(n,d)}else if(bo(n)){if(a===t.length-2)break;const d=+c,u=+t[++a]==0?"key":"value",f=gs(n,d);switch(u){case"key":n=f;break;case"value":n=n.get(f);break}}}const s=t[t.length-1];if(oi(n)?n[+s]=r(n[+s]):vo(n)&&(n[s]=r(n[s])),yo(n)){const a=gs(n,+s),c=r(a);a!==c&&(n.delete(a),n.add(c))}if(bo(n)){const a=+t[t.length-2],c=gs(n,a);switch(+s==0?"key":"value"){case"key":{const d=r(c);n.set(d,n.get(c)),d!==c&&n.delete(c);break}case"value":n.set(c,r(n.get(c)));break}}return e},Wy=e=>e<1;function xh(e,t,r,n=[]){if(!e)return;const s=Wy(r);if(!oi(e)){ms(e,(d,u)=>xh(d,t,r,[...n,...xo(u,s)]));return}const[a,c]=e;c&&ms(c,(d,u)=>{xh(d,t,r,[...n,...xo(u,s)])}),t(a,n)}function f6(e,t,r,n){return xh(t,(s,a)=>{e=yh(e,a,c=>u6(c,s,n))},r),e}function h6(e,t,r){const n=Wy(r);function s(a,c){const d=d6(e,xo(c,n));a.map(u=>xo(u,n)).forEach(u=>{e=yh(e,u,()=>d)})}if(oi(t)){const[a,c]=t;a.forEach(d=>{e=yh(e,xo(d,n),()=>e)}),c&&ms(c,s)}else ms(t,s);return e}var m6=(e,t)=>vo(e)||oi(e)||bo(e)||yo(e)||Ly(e)||zy(e,t);function g6(e,t,r){const n=r.get(e);n?n.push(t):r.set(e,[t])}function p6(e,t){const r={};let n;return e.forEach(s=>{if(s.length<=1)return;t||(s=s.map(d=>d.map(String)).sort((d,u)=>d.length-u.length));const[a,...c]=s;a.length===0?n=c.map(bh):r[bh(a)]=c.map(bh)}),n?ph(r)?[n]:[n,r]:ph(r)?void 0:r}var qy=(e,t,r,n,s=[],a=[],c=new Map)=>{const d=n6(e);if(!d){g6(e,s,t);const p=c.get(e);if(p)return n?{transformedValue:null}:p}if(!m6(e,r)){const p=Vy(e,r),y=p?{transformedValue:p.value,annotations:[p.type]}:{transformedValue:e};return d||c.set(e,y),y}if(Vl(a,e))return{transformedValue:null};const u=Vy(e,r),f=u?.value??e,h=oi(f)?[]:{},m={};ms(f,(p,y)=>{if(y==="__proto__"||y==="constructor"||y==="prototype")throw new Error(`Detected property ${y}. This is a prototype pollution risk, please remove it from your object.`);const S=qy(p,t,r,n,[...s,y],[...a,e],c);h[y]=S.transformedValue,oi(S.annotations)?m[vh(y)]=S.annotations:vo(S.annotations)&&ms(S.annotations,(E,T)=>{m[vh(y)+"."+T]=E})});const g=ph(m)?{transformedValue:h,annotations:u?[u.type]:void 0}:{transformedValue:h,annotations:u?[u.type,m]:m};return d||c.set(e,g),g};function Qy(e){return Object.prototype.toString.call(e).slice(8,-1)}function Yy(e){return Qy(e)==="Array"}function v6(e){if(Qy(e)!=="Object")return!1;const t=Object.getPrototypeOf(e);return!!t&&t.constructor===Object&&t===Object.prototype}function b6(e,t,r,n,s){const a={}.propertyIsEnumerable.call(n,t)?"enumerable":"nonenumerable";a==="enumerable"&&(e[t]=r),s&&a==="nonenumerable"&&Object.defineProperty(e,t,{value:r,enumerable:!1,writable:!0,configurable:!0})}function Sh(e,t={}){if(Yy(e))return e.map(s=>Sh(s,t));if(!v6(e))return e;const r=Object.getOwnPropertyNames(e),n=Object.getOwnPropertySymbols(e);return[...r,...n].reduce((s,a)=>{if(a==="__proto__"||Yy(t.props)&&!t.props.includes(a))return s;const c=e[a];return b6(s,a,Sh(c,t),e,t.nonenumerable),s},{})}var Ct=class{constructor({dedupe:e=!1}={}){this.classRegistry=new HU,this.symbolRegistry=new Dy(t=>t.description??""),this.customTransformerRegistry=new qU,this.allowedErrorProps=[],this.dedupe=e}serialize(e){const t=new Map,r=qy(e,t,this,this.dedupe),n={json:r.transformedValue};r.annotations&&(n.meta={...n.meta,values:r.annotations});const s=p6(t,this.dedupe);return s&&(n.meta={...n.meta,referentialEqualities:s}),n.meta&&(n.meta.v=1),n}deserialize(e,t){const{json:r,meta:n}=e;let s=t?.inPlace?r:Sh(r);return n?.values&&(s=f6(s,n.values,n.v??0,this)),n?.referentialEqualities&&(s=h6(s,n.referentialEqualities,n.v??0)),s}stringify(e){return JSON.stringify(this.serialize(e))}parse(e){return this.deserialize(JSON.parse(e),{inPlace:!0})}registerClass(e,t){this.classRegistry.register(e,t)}registerSymbol(e,t){this.symbolRegistry.register(e,t)}registerCustom(e,t){this.customTransformerRegistry.register({name:t,...e})}allowErrorProps(...e){this.allowedErrorProps.push(...e)}};Ct.defaultInstance=new Ct,Ct.serialize=Ct.defaultInstance.serialize.bind(Ct.defaultInstance),Ct.deserialize=Ct.defaultInstance.deserialize.bind(Ct.defaultInstance),Ct.stringify=Ct.defaultInstance.stringify.bind(Ct.defaultInstance),Ct.parse=Ct.defaultInstance.parse.bind(Ct.defaultInstance),Ct.registerClass=Ct.defaultInstance.registerClass.bind(Ct.defaultInstance),Ct.registerSymbol=Ct.defaultInstance.registerSymbol.bind(Ct.defaultInstance),Ct.registerCustom=Ct.defaultInstance.registerCustom.bind(Ct.defaultInstance),Ct.allowErrorProps=Ct.defaultInstance.allowErrorProps.bind(Ct.defaultInstance),Ct.serialize,Ct.deserialize,Ct.stringify,Ct.parse,Ct.registerClass,Ct.registerCustom,Ct.registerSymbol,Ct.allowErrorProps;function y6({className:e}){return(0,i.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[(0,i.jsx)("path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}),(0,i.jsx)("circle",{cx:"12",cy:"12",r:"3"})]})}function x6({className:e}){return(0,i.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[(0,i.jsx)("path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}),(0,i.jsx)("path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}),(0,i.jsx)("path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}),(0,i.jsx)("path",{d:"m2 2 20 20"})]})}function S6({className:e}){return(0,i.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:(0,i.jsx)("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})})}function Xy({onLogin:e,serverUrl:t,logoSrc:r,error:n,className:s}){const[a,c]=(0,l.useState)(""),[d,u]=(0,l.useState)(""),[f,h]=(0,l.useState)(!1),[m,g]=(0,l.useState)(!1),[p,y]=(0,l.useState)(null),S=n??p,E=async T=>{if(T.preventDefault(),!m){y(null),g(!0);try{await e(a,d)}catch(j){y(j instanceof Error?j.message:"Login failed. Please try again.")}finally{g(!1)}}};return(0,i.jsx)("div",{className:A("flex min-h-screen items-center justify-center bg-background p-4",s),children:(0,i.jsxs)("div",{className:"w-full max-w-sm",children:[r&&(0,i.jsx)("div",{className:"flex justify-center mb-8",children:(0,i.jsx)("img",{src:r,alt:"Logo",className:"h-12"})}),t&&(0,i.jsx)("p",{className:"mb-4 text-center text-xs text-foreground-subtle truncate",children:t}),(0,i.jsxs)("form",{onSubmit:E,className:"space-y-4 rounded-xl border border-border bg-surface p-6 shadow-xl shadow-black/10",children:[S&&(0,i.jsx)("div",{className:"rounded-md bg-danger/10 border border-danger/20 px-3 py-2 text-xs text-danger",children:S}),(0,i.jsxs)("div",{className:"space-y-1.5",children:[(0,i.jsx)("label",{className:"text-xs font-medium text-foreground-subtle",children:"Username"}),(0,i.jsx)("input",{type:"text",value:a,onChange:T=>c(T.target.value),autoComplete:"username",required:!0,className:"w-full rounded-lg border border-border bg-background px-3 py-2.5 text-sm text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary"})]}),(0,i.jsxs)("div",{className:"space-y-1.5",children:[(0,i.jsx)("label",{className:"text-xs font-medium text-foreground-subtle",children:"Password"}),(0,i.jsxs)("div",{className:"relative",children:[(0,i.jsx)("input",{type:f?"text":"password",value:d,onChange:T=>u(T.target.value),autoComplete:"current-password",required:!0,className:"w-full rounded-lg border border-border bg-background px-3 py-2.5 pr-10 text-sm text-foreground placeholder:text-foreground-subtle focus:outline-none focus:ring-2 focus:ring-primary/50 focus:border-primary"}),(0,i.jsx)("button",{type:"button",onClick:()=>h(T=>!T),className:"absolute right-2.5 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground",tabIndex:-1,children:f?(0,i.jsx)(x6,{className:"h-4 w-4"}):(0,i.jsx)(y6,{className:"h-4 w-4"})})]})]}),(0,i.jsxs)("button",{type:"submit",disabled:m,className:"w-full rounded-lg bg-primary px-4 py-2.5 text-sm font-semibold text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed transition-colors flex items-center justify-center gap-2",children:[m&&(0,i.jsx)(S6,{className:"h-4 w-4 animate-spin"}),m?"Logging in...":"Log in"]})]})]})})}var _h="camstack_dev_token",Jy=(0,l.createContext)(null);function _6(){const e=(0,l.useContext)(Jy);if(!e)throw new Error("useDevShell must be used within a DevShell");return e}function w6(){return typeof window>"u"?null:localStorage.getItem(_h)}function E6({className:e}){return(0,i.jsxs)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:[(0,i.jsx)("circle",{cx:"12",cy:"12",r:"4"}),(0,i.jsx)("path",{d:"M12 2v2"}),(0,i.jsx)("path",{d:"M12 20v2"}),(0,i.jsx)("path",{d:"m4.93 4.93 1.41 1.41"}),(0,i.jsx)("path",{d:"m17.66 17.66 1.41 1.41"}),(0,i.jsx)("path",{d:"M2 12h2"}),(0,i.jsx)("path",{d:"M20 12h2"}),(0,i.jsx)("path",{d:"m6.34 17.66-1.41 1.41"}),(0,i.jsx)("path",{d:"m19.07 4.93-1.41 1.41"})]})}function k6({className:e}){return(0,i.jsx)("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:e,children:(0,i.jsx)("path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z"})})}function T6({children:e,serverUrl:t,title:r,token:n,onLogout:s}){const a=x.useThemeMode$1(),c=(0,l.useMemo)(()=>[(0,ve.splitLink)({condition:g=>g.type==="subscription",true:(0,ve.wsLink)({client:(0,ve.createWSClient)({url:t.replace(/^http/,"ws")+"/trpc",connectionParams:()=>({token:n})}),transformer:Ct}),false:(0,ve.httpLink)({url:`${t}/trpc`,transformer:Ct,headers:()=>({authorization:`Bearer ${n}`})})})],[t,n]),d=(0,l.useMemo)(()=>(0,ve.createTRPCClient)({links:c}),[c]),u=(0,l.useMemo)(()=>C.createClient({links:c}),[c]),f=(0,l.useMemo)(()=>(0,Ze.createSystem)({serverUrl:t,token:n}),[t,n]);(0,l.useEffect)(()=>(f.init().catch(()=>{}),()=>{f.close()}),[f]);const h=(0,l.useMemo)(()=>new ye.QueryClient,[]),m=(0,l.useMemo)(()=>({trpc:d,token:n,logout:s}),[d,n,s]);return(0,i.jsx)(Av,{system:f,children:(0,i.jsx)(C.Provider,{client:u,queryClient:h,children:(0,i.jsx)(ye.QueryClientProvider,{client:h,children:(0,i.jsx)(Jy.Provider,{value:m,children:(0,i.jsxs)("div",{className:"min-h-screen bg-background text-foreground",children:[(0,i.jsxs)("div",{className:"flex items-center justify-between border-b border-border bg-surface px-4 py-2",children:[(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsx)("span",{className:"rounded bg-warning/20 px-2 py-0.5 text-xs font-bold text-warning",children:"DEV MODE"}),r&&(0,i.jsx)("span",{className:"text-sm font-medium text-foreground",children:r}),(0,i.jsx)("span",{className:"text-xs text-foreground-subtle",children:t})]}),(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsxs)("button",{type:"button",onClick:a.toggleMode,className:"flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",title:`Theme: ${a.mode}`,children:[a.resolvedMode==="dark"?(0,i.jsx)(E6,{className:"h-3.5 w-3.5"}):(0,i.jsx)(k6,{className:"h-3.5 w-3.5"}),a.mode==="dark"?"Dark":a.mode==="light"?"Light":"System"]}),(0,i.jsx)("button",{type:"button",onClick:s,className:"rounded-md px-2.5 py-1 text-xs font-medium text-danger hover:bg-danger/10 transition-colors",children:"Logout"})]})]}),(0,i.jsx)("div",{className:"p-4",children:e({trpc:d,theme:a})})]})})})})})}function ex({children:e,serverUrl:t="https://localhost:4443",title:r}){const[n,s]=(0,l.useState)(w6),a=(0,l.useCallback)(async(d,u)=>{const f=await(0,ve.createTRPCClient)({links:[(0,ve.httpLink)({url:`${t}/trpc`,transformer:Ct})]}).auth.login.mutate({username:d,password:u});if(!f.token)throw new Error("No token returned");localStorage.setItem(_h,f.token),s(f.token)},[t]),c=(0,l.useCallback)(()=>{localStorage.removeItem(_h),s(null)},[]);return n?(0,i.jsx)(x.ThemeProvider$1,{children:(0,i.jsx)(T6,{serverUrl:t,title:r,token:n,onLogout:c,children:e})}):(0,i.jsx)(x.ThemeProvider$1,{children:(0,i.jsx)(Xy,{onLogin:a,serverUrl:t})})}function C6(e,t={}){const{serverUrl:r="https://localhost:4443",title:n,rootId:s="root"}=t,a=document.getElementById(s);if(!a){console.error(`[mountAddonPage] Element #${s} not found`);return}(0,Z.createRoot)(a).render((0,l.createElement)(ex,{serverUrl:r,title:n,children:({trpc:c,theme:d})=>(0,l.createElement)(e,{trpc:c,theme:{isDark:d.resolvedMode==="dark"},navigate:u=>{console.log("[dev] navigate:",u)}})}))}var tx=Sn("camstack:custom-field-renderers",{});function I6({renderers:e,children:t}){return(0,i.jsx)(tx.Provider,{value:e,children:t})}function rx(e){return(0,l.useContext)(tx)[e]??null}var wh=Sn("camstack:device-context",null);function P6({deviceId:e,device:t,children:r}){const n={deviceId:e,device:t??null};return(0,i.jsx)(wh.Provider,{value:n,children:r})}function nx(){return(0,l.useContext)(wh)?.deviceId??null}function A6(){return(0,l.useContext)(wh)?.device??null}var ix=Sn("camstack:widget-registry",null),Kl=new Map,Wl=new Map,sx=new Set;function Eh(e,t){return`${e}::${t}`}function j6(e){if(!e||typeof e!="object")return!1;const t=e.default;return t!==null&&typeof t=="object"}function N6(e){if(!e||typeof e!="object")return typeof e;const t=e,r=Object.getPrototypeOf(t),n=r&&typeof r=="object"?r.constructor?.name:void 0;return{ownKeys:Object.keys(t),allKeys:Object.getOwnPropertyNames(t),proto:typeof n=="string"?n:void 0}}async function kh(e,t,r){const n=Eh(e,t),s=Kl.get(n);if(s)return s;const a=Wl.get(n);if(a)return a;sx.has(e)||(pp(),iT([{name:e,entry:r,type:"module"}],{force:!1}),sx.add(e));const c=nT(`${e}/${t.startsWith("./")?t.slice(2):t}`).then(d=>{if(!j6(d)){const f=N6(d);throw new Error(`Remote ${e} (${r}) does not expose a default record on '${t}'. Got: ${JSON.stringify(f)}`)}const u=d.default;return Kl.set(n,u),Wl.delete(n),u}).catch(d=>{throw Wl.delete(n),d});return Wl.set(n,c),c}function Th(e,t){return Kl.get(Eh(e,t))}var D6=3e4,M6=2e3;function $6({children:e}){const t=(0,ye.useQueryClient)(),r=(0,l.useRef)(Date.now()),{data:n}=u0(void 0,{staleTime:0,refetchOnMount:"always",refetchInterval:u=>{const f=u.state.data;return f&&f.length>0||Date.now()-r.current>=D6?!1:M6}});so("addon.widget-ready",()=>{t.invalidateQueries({queryKey:[["addonWidgets","listWidgets"]]})});const[s,a]=(0,l.useState)(0),c=(0,l.useMemo)(()=>n??[],[n]);(0,l.useEffect)(()=>{if(c.length===0)return;let u=!1;const f=new Set;for(const h of c){const m=Eh(h.remote.remoteName,h.remote.exposedModule);if(f.has(m)||(f.add(m),Kl.has(m)))continue;const g=h.bundleUrl;kh(h.remote.remoteName,h.remote.exposedModule,g).then(()=>{u||a(p=>p+1)}).catch(p=>{const y=p instanceof Error?p.message:String(p);(typeof globalThis<"u"?globalThis.console:void 0)?.error?.("[WidgetRegistry] Failed to load widget remote",{remoteName:h.remote.remoteName,exposedModule:h.remote.exposedModule,entryUrl:g,reason:y})})}return()=>{u=!0}},[c]);const d=(0,l.useMemo)(()=>{const u=new Map,f=new Map;for(const m of c)u.set(`${m.addonId}/${m.stableId}`,m),f.set(m.remote.remoteName,m.bundleUrl);const h=(m,g)=>({widgetId:m,addonId:g.addonId,stableId:g.stableId,tab:g.tab,subTab:g.subTab,label:g.label,order:g.order,kind:g.kind,remote:g.remote,description:g.description,icon:g.icon,bundleUrl:g.bundleUrl,hosts:g.hosts,requires:g.requires,defaultSize:g.defaultSize,allowedSizes:g.allowedSizes,defaultColumns:g.defaultColumns,defaultRows:g.defaultRows});return{resolve:m=>{const g=u.get(m);if(!g)return;const p=Th(g.remote.remoteName,g.remote.exposedModule);if(!p)return null;const y=p[g.remote.componentKey??g.stableId];if(y)return y},metadata:m=>{const g=u.get(m);if(g)return h(m,g)},listAll:()=>{const m=[];for(const[g,p]of u)m.push(h(g,p));return m},entryUrlFor:m=>f.get(m)}},[c,s]);return(0,i.jsx)(ix.Provider,{value:d,children:e})}function R6(e){return ql().resolve(e)}function ax(e){return ql().metadata(e)}function L6(){return ql().listAll()}function ox(e,t){const r=Ch(),n=t??r?.entryUrlFor(e.remoteName),[s,a]=(0,l.useState)(0),[c,d]=(0,l.useState)(!1);return(0,l.useEffect)(()=>{if(!n||(d(!1),Th(e.remoteName,e.exposedModule)))return;let u=!1;return kh(e.remoteName,e.exposedModule,n).then(()=>{u||a(f=>f+1)}).catch(f=>{const h=f instanceof Error?f.message:String(f);(typeof globalThis<"u"?globalThis.console:void 0)?.error?.("[WidgetRegistry] Failed to load remote component",{remoteName:e.remoteName,exposedModule:e.exposedModule,entryUrl:n,reason:h}),u||d(!0)}),()=>{u=!0}},[e.remoteName,e.exposedModule,n]),(0,l.useMemo)(()=>{if(!n||c)return;const u=Th(e.remoteName,e.exposedModule);if(!u)return null;const f=e.componentKey;return f===void 0?Object.values(u)[0]??void 0:u[f]??void 0},[e.remoteName,e.exposedModule,e.componentKey,n,s,c])}function ql(){const e=Ch();if(!e)throw new Error("useWidgetRegistry(): no <WidgetRegistryProvider> in tree");return e}function Ch(){return O6(ix)}function O6(e){return(0,l.useContext)(e)}function Gn({title:e,icon:t,headerRight:r,collapsible:n=!1,defaultOpen:s=!0,bodyClassName:a="p-3",children:c}){const[d,u]=(0,l.useState)(s),f=!n||d,h=(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wider text-foreground",children:[t,e]}),n?d?(0,i.jsx)(fr,{className:"h-3.5 w-3.5 text-foreground-subtle"}):(0,i.jsx)(mn,{className:"h-3.5 w-3.5 text-foreground-subtle"}):r]}),m=`px-4 py-2 flex items-center justify-between ${f?"border-b border-border":""}`;return(0,i.jsxs)("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[n?(0,i.jsx)("button",{type:"button",onClick:()=>u(g=>!g),className:`w-full text-left ${m}`,children:h}):(0,i.jsx)("div",{className:m,children:h}),f?(0,i.jsx)("div",{className:a,children:c}):null]})}function Ql({label:e,icon:t,children:r,footer:n}){return(0,i.jsxs)("div",{className:"rounded-md border border-border/60 bg-background/40 px-3 py-2",children:[(0,i.jsxs)("div",{className:"mb-1 flex items-center gap-1.5 text-[11px] uppercase tracking-wider text-foreground-subtle",children:[t,e]}),(0,i.jsx)("div",{className:"text-sm font-medium text-foreground",children:r}),n?(0,i.jsx)("div",{className:"mt-0.5 text-[10px] text-foreground-subtle",children:n}):null]})}function F6({deviceId:e}){const t=Br(Mr().trpcClient,e),[r,n]=(0,l.useState)(null),[s,a]=(0,l.useState)(!1);(0,l.useEffect)(()=>{if(!t)return;let d=!1;return(async()=>{try{const u=await t.ptz?.getStatus({});if(d||!u)return;n(u.autofocus)}catch{}})(),()=>{d=!0}},[t]);const c=(0,l.useCallback)(async()=>{if(!(!t?.ptz||r===null)){a(!0);try{const d=!r;await t.ptz.setAutofocus({enabled:d}),n(d)}catch(d){console.error("ptz.setAutofocus failed",d)}finally{a(!1)}}},[t,r]);return r===null?null:(0,i.jsxs)("div",{className:"flex items-center justify-between border-t border-border/40 mt-2 pt-2",children:[(0,i.jsx)("span",{className:"text-[10.5px] font-semibold text-foreground",children:"Autofocus"}),(0,i.jsxs)("button",{type:"button",onClick:()=>void c(),disabled:s,"aria-pressed":r,className:`flex items-center gap-1.5 rounded-md px-2 py-1 text-[10px] font-medium transition-colors ${r?"bg-success/15 text-success hover:bg-success/25":"bg-surface-elevated/40 text-foreground-subtle hover:bg-surface-hover hover:text-foreground"} disabled:opacity-50`,children:[(0,i.jsx)("span",{className:`h-1.5 w-1.5 rounded-full ${r?"bg-success":"bg-foreground-subtle/40"}`}),r?"On":"Off"]})]})}function lx({deviceId:e}){const t=Mr(),r=Number.isFinite(e),n=Sf(t.trpcClient,r?e:0,{enabled:r});if(!r)return(0,i.jsxs)("div",{className:"flex items-center justify-center h-full text-[11px] text-foreground-subtle italic",children:["Device #",e," not loaded."]});const s=n.options?.hasAutofocus===!0;return(0,i.jsxs)(Gn,{title:"PTZ",icon:(0,i.jsx)(fC,{className:"h-3.5 w-3.5 text-foreground-subtle"}),bodyClassName:"p-3 flex flex-col overflow-y-auto",children:[(0,i.jsx)(_f,{controls:n,mode:"panel"}),s&&(0,i.jsx)(F6,{deviceId:e})]})}var U6=15;function B6(e){return e.status==="replace"||e.level!==null&&e.level<=U6}function z6(e){try{return new Date(e).toLocaleDateString(void 0,{year:"numeric",month:"short",day:"numeric"})}catch{return""}}function G6({item:e,busy:t,canReset:r,onReset:n}){const s=B6(e),a=s?"bg-warning":"bg-success";return(0,i.jsxs)("div",{className:`flex flex-col gap-1.5 rounded-md border p-3 ${s?"border-warning/40 bg-warning/5":"border-border/40 bg-surface-elevated/30"}`,children:[(0,i.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,i.jsx)("span",{className:`text-xs font-semibold ${s?"text-warning":"text-foreground"}`,children:e.label}),e.resettable&&(0,i.jsx)("button",{type:"button",onClick:()=>n(e.key),disabled:t||!r,className:"rounded-md border border-border bg-surface px-2 py-0.5 text-[10px] font-medium text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors",children:"Replaced"})]}),e.level!==null?(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsx)("div",{className:"h-1.5 flex-1 overflow-hidden rounded-full bg-surface-elevated/60",children:(0,i.jsx)("div",{className:`h-full rounded-full ${a} transition-all`,style:{width:`${Math.max(0,Math.min(100,e.level))}%`}})}),(0,i.jsxs)("span",{className:"text-[10px] font-medium tabular-nums text-foreground-subtle",children:[Math.round(e.level),"%"]})]}):e.status!==null?(0,i.jsx)("span",{className:`inline-flex w-fit items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium ${e.status==="replace"?"bg-warning/15 text-warning":"bg-success/15 text-success"}`,children:e.status==="replace"?"Replace":"OK"}):(0,i.jsx)("span",{className:"text-[10px] text-foreground-subtle",children:"—"}),e.lastResetAt!==null&&(0,i.jsxs)("span",{className:"text-[10px] text-foreground-subtle",children:["Replaced ",z6(e.lastResetAt)]})]})}function cx({deviceId:e}){const t=Mr(),r=Number.isFinite(e),{cap:n,slice:s,available:a}=bt({trpc:t.trpcClient,deviceId:r?e:null,cap:h=>h.consumables,slice:h=>h.state.consumables}),[c,d]=(0,l.useState)(null),u=(0,l.useCallback)(async h=>{if(n){d(h);try{await n.reset({key:h})}catch(m){console.error("consumables.reset failed",m)}finally{d(null)}}},[n]),f=s?.items??[];return(0,i.jsx)(Gn,{title:"Consumables",icon:(0,i.jsx)(eo,{className:"h-3.5 w-3.5 text-foreground-subtle"}),bodyClassName:"p-3 overflow-y-auto",children:f.length===0?(0,i.jsx)("p",{className:"text-[11px] text-foreground-subtle italic leading-relaxed",children:"No consumables reported."}):(0,i.jsx)("div",{className:"flex flex-col gap-2",children:f.map(h=>(0,i.jsx)(G6,{item:h,busy:c===h.key,canReset:a,onReset:m=>void u(m)},h.key))})})}function ux(e){const t=(0,ye.useQueryClient)(),r=S0({deviceId:e??0},{enabled:e!==null&&Number.isFinite(e),refetchInterval:5e3,retry:1}),n=_0({onSuccess:()=>{t.invalidateQueries({queryKey:[["ptzAutotrack"]]})}}),s=w0({onSuccess:()=>{t.invalidateQueries({queryKey:[["ptzAutotrack"]]})}}),a=(0,l.useCallback)(async u=>{e!==null&&await n.mutateAsync({deviceId:e,enabled:u})},[e,n]),c=(0,l.useCallback)(async u=>{e!==null&&await s.mutateAsync({deviceId:e,settings:u})},[e,s]),d=r.error?r.error.message:n.error?n.error.message:s.error?s.error.message:null;return{status:r.data??null,isLoading:r.isLoading,isPending:n.isPending||s.isPending,error:d,setEnabled:a,setSettings:c}}function dx({deviceId:e}){const{status:t,isLoading:r,isPending:n,error:s,setEnabled:a,setSettings:c}=ux(Number.isFinite(e)?e:null),[d,u]=(0,l.useState)({targetType:"",stopDelaySeconds:30,disappearDelaySeconds:15}),[f,h]=(0,l.useState)(!1);(0,l.useEffect)(()=>{if(f)return;const g=t?.currentSettings;g&&u({targetType:g.targetType,stopDelaySeconds:g.stopDelaySeconds,disappearDelaySeconds:g.disappearDelaySeconds})},[t,f]);const m=(0,i.jsx)(Bd,{className:"h-3.5 w-3.5 text-foreground-subtle"});return r&&!t?(0,i.jsx)(Gn,{title:"Autotrack",icon:m,children:(0,i.jsxs)("div",{className:"flex items-center gap-2 text-[10.5px] text-foreground-subtle",children:[(0,i.jsx)(hr,{className:"h-3 w-3 animate-spin"}),"Loading autotrack…"]})}):(0,i.jsxs)(Gn,{title:"Autotrack",icon:m,headerRight:(0,i.jsxs)("button",{type:"button",onClick:()=>{a(!(t?.enabled??!1))},disabled:n,className:`flex items-center gap-1.5 rounded-md px-2 py-1 text-[10px] font-medium transition-colors ${t?.enabled?"bg-success/15 text-success hover:bg-success/25":"bg-surface-elevated/40 text-foreground-subtle hover:bg-surface-hover hover:text-foreground"} disabled:opacity-50`,"aria-pressed":t?.enabled??!1,children:[(0,i.jsx)("span",{className:`h-1.5 w-1.5 rounded-full ${t?.enabled?"bg-success":"bg-foreground-subtle/40"}`}),t?.enabled?"Enabled":"Disabled"]}),bodyClassName:"p-3 space-y-2",children:[s&&(0,i.jsxs)("div",{className:"flex items-start gap-1.5 rounded-md border border-danger/30 bg-danger/5 px-2 py-1.5 text-[10px] text-danger",children:[(0,i.jsx)(as,{className:"h-3 w-3 flex-shrink-0 mt-0.5"}),(0,i.jsx)("span",{className:"leading-snug break-words",children:s})]}),(0,i.jsxs)("div",{className:"grid grid-cols-2 gap-2 px-2",children:[(t?.supportedTargetTypes?.length??0)>0&&(0,i.jsxs)("label",{className:"col-span-2 flex flex-col gap-1",children:[(0,i.jsx)("span",{className:"text-[10px] font-medium text-foreground-subtle",children:"Target type"}),(0,i.jsx)("select",{value:d.targetType,onFocus:()=>h(!0),onChange:g=>u(p=>({...p,targetType:g.target.value})),onBlur:()=>{h(!1);const g=t?.currentSettings?.targetType??"";d.targetType!==g&&c({targetType:d.targetType})},disabled:n,className:"rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground focus:border-primary focus:outline-none disabled:opacity-50",children:(t?.supportedTargetTypes??[]).map(g=>(0,i.jsx)("option",{value:g.value,children:g.label},g.value))})]}),(0,i.jsxs)("label",{className:"flex flex-col gap-1",children:[(0,i.jsx)("span",{className:"text-[10px] font-medium text-foreground-subtle",children:"Stop delay (s)"}),(0,i.jsx)("input",{type:"number",min:0,max:300,value:d.stopDelaySeconds,onFocus:()=>h(!0),onChange:g=>u(p=>({...p,stopDelaySeconds:Number(g.target.value)||0})),onBlur:()=>{h(!1);const g=t?.currentSettings?.stopDelaySeconds??30;d.stopDelaySeconds!==g&&c({stopDelaySeconds:d.stopDelaySeconds})},disabled:n,className:"rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground focus:border-primary focus:outline-none disabled:opacity-50"})]}),(0,i.jsxs)("label",{className:"flex flex-col gap-1",children:[(0,i.jsx)("span",{className:"text-[10px] font-medium text-foreground-subtle",children:"Disappear delay (s)"}),(0,i.jsx)("input",{type:"number",min:0,max:300,value:d.disappearDelaySeconds,onFocus:()=>h(!0),onChange:g=>u(p=>({...p,disappearDelaySeconds:Number(g.target.value)||0})),onBlur:()=>{h(!1);const g=t?.currentSettings?.disappearDelaySeconds??15;d.disappearDelaySeconds!==g&&c({disappearDelaySeconds:d.disappearDelaySeconds})},disabled:n,className:"rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground focus:border-primary focus:outline-none disabled:opacity-50"})]})]}),(0,i.jsx)("p",{className:"px-2 text-[9.5px] text-foreground-subtle leading-snug italic",children:"Settings save on blur. Vendor support varies — Reolink honours all three; Hikvision honours target type + stop delay only (disappear delay is accepted but ignored at firmware push)."})]})}var Ih=Sn("camstack:player-overlays-state",null),Ph=Sn("camstack:player-overlays-actions",null);function Z6({children:e}){const[t,r]=(0,l.useState)(()=>new Map),[n,s]=(0,l.useState)(()=>new Map),a=(0,l.useCallback)(m=>{r(g=>{const p=new Map(g);return p.set(m.id,m),p})},[]),c=(0,l.useCallback)(m=>{r(g=>{if(!g.has(m))return g;const p=new Map(g);return p.delete(m),p})},[]),d=(0,l.useCallback)(m=>{s(g=>{const p=new Map(g);return p.set(m.id,m),p})},[]),u=(0,l.useCallback)(m=>{s(g=>{if(!g.has(m))return g;const p=new Map(g);return p.delete(m),p})},[]),f=(0,l.useMemo)(()=>({layers:t,buttons:n}),[t,n]),h=(0,l.useMemo)(()=>({setLayer:a,removeLayer:c,setButton:d,removeButton:u}),[a,c,d,u]);return(0,i.jsx)(Ih.Provider,{value:f,children:(0,i.jsx)(Ph.Provider,{value:h,children:e})})}function V6(){const e=(0,l.useContext)(Ih);return(0,l.useMemo)(()=>e?[...e.layers.values()].sort((t,r)=>t.order-r.order):[],[e])}function fx(){const e=(0,l.useContext)(Ih);return(0,l.useMemo)(()=>e?[...e.buttons.values()].sort((t,r)=>t.order-r.order):[],[e])}function Ah(e){const t=(0,l.useContext)(Ph);(0,l.useEffect)(()=>{if(!(!t||!e))return t.setLayer(e),()=>t.removeLayer(e.id)},[t,e])}function H6(e){const t=(0,l.useContext)(Ph);(0,l.useEffect)(()=>{if(!(!t||!e))return t.setButton(e),()=>t.removeButton(e.id)},[t,e])}var hx={rect:"#ef4444",polygon:"#3b82f6",grid:"#6366f1",line:"#f59e0b"},mx="33",jh="66",Yl="#6366f1",ps=3,gx=2,K6=12,Nh=16,Dh=9;function So(e,t,r){return{x:e.x*t,y:e.y*r}}function Mh(e,t,r){return{x:e.x/t,y:e.y/r}}function px(e,t,r){return e.flatMap(n=>[n.x*t,n.y*r])}function vs(e){return!Number.isFinite(e)||e<0?0:e>1?1:e}function W6(e){return e.color??hx[e.shape.kind]}function q6(e,t){const r=e[t],n=e[(t+1)%e.length];if(!r||!n)return[...e];const s={x:(r.x+n.x)/2,y:(r.y+n.y)/2};return[...e.slice(0,t+1),s,...e.slice(t+1)]}function Q6(e,t){return e.length!==t.length?!1:e.every((r,n)=>{const s=t[n];return Math.abs(r.x-s.x)<1e-6&&Math.abs(r.y-s.y)<1e-6})}function Y6(e){return e.kind==="polygon"||e.kind==="line"}function X6({items:e,selectedId:t,onSelect:r,onShapeChange:n,onDrawComplete:s,drawingKind:a,supportedShapes:c,transparent:d=!1,backdrop:u,polygonVertices:f,grid:h}){const m=(0,l.useRef)(null),[g,p]=(0,l.useState)({w:800,h:450}),[y,S]=(0,l.useState)([]),[E,T]=(0,l.useState)(null),[j,N]=(0,l.useState)(null),[O,U]=(0,l.useState)(null),z=a!==null&&c.includes(a);(0,l.useEffect)(()=>{if(!O)return;const q=e.find(Q=>Q.id===O.itemId);if(!q||!Y6(q.shape)){U(null);return}Q6(q.shape.points,O.points)&&U(null)},[e,O]),(0,l.useEffect)(()=>{const q=m.current;if(!q)return;const Q=new ResizeObserver(ie=>{const be=ie[0];if(!be)return;const{width:we,height:Re}=be.contentRect;p(d?{w:we,h:Re}:{w:we,h:we*9/16})});return Q.observe(q),()=>Q.disconnect()},[d]),(0,l.useEffect)(()=>{!z&&E!==null&&T(null)},[z,E]);const K=(0,l.useCallback)(q=>{s(q),S([])},[s]),G=(0,l.useCallback)(q=>{if(!z||a===null){r(null);return}const Q=q.target.getStage();if(!Q)return;const ie=Q.getPointerPosition();if(!ie)return;const be=Mh(ie,g.w,g.h);if(a==="rect"){const we=vs(be.x),Re=vs(be.y);K({kind:"rect",x:we,y:Re,width:Math.min(.2,1-we),height:Math.min(.2,1-Re)});return}if(a==="grid"){const we=h?.width??Nh,Re=h?.height??Dh;K({kind:"grid",gridWidth:we,gridHeight:Re,cells:Array.from({length:we*Re},()=>!1)});return}if(a==="line"){if(y.length===0){S([be]);return}K({kind:"line",points:[...y,be]});return}if(a==="polygon"){if(y.length===0){S([be]);return}if(y.length>=ps){const we=So(y[0],g.w,g.h);if(Math.hypot(ie.x-we.x,ie.y-we.y)<K6){K({kind:"polygon",points:y});return}}S(we=>[...we,be])}},[z,a,y,g,h,K,r]),X=(0,l.useCallback)(q=>{!z||a!=="polygon"||y.length<ps||(q.cancelBubble=!0,K({kind:"polygon",points:y}))},[z,a,y,K]),te=(0,l.useRef)(null),ne=(0,l.useRef)(null);(0,l.useEffect)(()=>()=>{te.current!==null&&cancelAnimationFrame(te.current)},[]);const ae=(0,l.useCallback)(q=>{if(!z)return;const Q=q.target.getStage();Q&&(ne.current=Q.getPointerPosition()??null,te.current===null&&(te.current=requestAnimationFrame(()=>{te.current=null,T(ne.current)})))},[z]),oe=(0,l.useRef)(!1),pe=(0,l.useRef)(!0),le=(0,l.useRef)(new Set),se=(0,l.useCallback)((q,Q,ie,be)=>{const we=Q.gridWidth*Q.gridHeight;if(ie<0||ie>=we||Q.cells[ie]===be)return;const Re=[...Q.cells];for(;Re.length<we;)Re.push(!1);Re.length=we,Re[ie]=be,n(q,{...Q,cells:Re})},[n]),Ce=[];if(!d){for(let q=1;q<Nh;q++){const Q=g.w/Nh*q;Ce.push((0,i.jsx)(_e.Line,{points:[Q,0,Q,g.h],stroke:"#ffffff",strokeWidth:.5,opacity:.08},`gv-${q}`))}for(let q=1;q<Dh;q++){const Q=g.h/Dh*q;Ce.push((0,i.jsx)(_e.Line,{points:[0,Q,g.w,Q],stroke:"#ffffff",strokeWidth:.5,opacity:.08},`gh-${q}`))}}return(0,i.jsxs)("div",{ref:m,className:d?"absolute inset-0":"relative w-full bg-zinc-900 rounded-lg overflow-hidden",style:{cursor:z?"crosshair":"default"},children:[u&&!d?(0,i.jsx)("div",{className:"absolute inset-0 pointer-events-none [&>*]:w-full [&>*]:h-full [&>img]:object-cover [&>video]:object-cover",style:{width:g.w,height:g.h},children:u}):null,(0,i.jsxs)(_e.Stage,{width:g.w,height:g.h,onClick:G,onDblClick:X,onMouseMove:ae,children:[(0,i.jsxs)(_e.Layer,{listening:!1,children:[(0,i.jsx)(_e.Line,{points:[0,0,g.w,0,g.w,g.h,0,g.h,0,0],stroke:"transparent",strokeWidth:0}),Ce]}),(0,i.jsx)(_e.Layer,{children:e.map(q=>{const Q=q.id===t,ie=q.enabled===!1,be=W6(q),we=Q&&!z&&!ie;if(q.shape.kind==="rect")return(0,i.jsx)(eB,{item:q,shape:q.shape,color:be,selected:Q,dimmed:ie,editable:we,isDrawing:z,size:g,onSelect:r,onShapeChange:n},q.id);if(q.shape.kind==="grid")return(0,i.jsx)(tB,{item:q,shape:q.shape,color:be,dimmed:ie,editable:we,size:g,onSelect:r,paintingRef:oe,paintValueRef:pe,paintedRef:le,paintCell:se},q.id);const Re=q.shape.kind==="line",Ee=Re?gx:Math.max(ps,f?.min??ps),Fe=Re?gx:f?.max,Ge=O&&O.itemId===q.id?O.points:q.shape.points;return(0,i.jsx)(rB,{item:q,shape:q.shape,color:be,selected:Q,dimmed:ie,editable:we,isLine:Re,isDrawing:z,size:g,effectivePoints:Ge,minVertices:Ee,maxVertices:Fe,isDragging:j===q.id,onSelect:r,onShapeChange:n,setDragOverride:U,setDraggingItemId:N},q.id)})}),(0,i.jsx)(_e.Layer,{listening:!1,children:z&&y.length>0&&(0,i.jsxs)(_e.Group,{children:[a==="polygon"&&y.length>=2&&(0,i.jsx)(_e.Line,{points:px(y,g.w,g.h),stroke:Yl,strokeWidth:1.5,dash:[6,3],opacity:.8}),a==="line"&&y.length===1&&E&&(0,i.jsx)(_e.Line,{points:[y[0].x*g.w,y[0].y*g.h,E.x,E.y],stroke:hx.line,strokeWidth:1.5,dash:[6,3],opacity:.7}),a==="polygon"&&E&&y.length>=1&&(0,i.jsx)(_e.Line,{points:[y[y.length-1].x*g.w,y[y.length-1].y*g.h,E.x,E.y],stroke:Yl,strokeWidth:1,dash:[4,4],opacity:.5}),y.map((q,Q)=>{const ie=So(q,g.w,g.h),be=Q===0&&a==="polygon"&&y.length>=ps;return(0,i.jsx)(_e.Circle,{x:ie.x,y:ie.y,radius:be?7:4,fill:be?Yl:"#ffffff",stroke:Yl,strokeWidth:1.5,opacity:.9},Q)})]})})]}),z?(0,i.jsx)("div",{className:"px-3 py-1.5 bg-zinc-800/80 text-[11px] text-zinc-400 border-t border-zinc-700",children:a==="line"?"Click to set the start point, click again to complete the line":a==="rect"?"Click to drop a rectangle, then drag the corner to resize":a==="grid"?"Click to add the grid, then paint cells":y.length<ps?"Click to add points (min 3). Double-click or click the first point to close.":"Continue adding points. Double-click or click the first point to close."}):null]})}var Xl=.02;function J6(e,t){return Math.abs(e.x-t.x)<1e-6&&Math.abs(e.y-t.y)<1e-6&&Math.abs(e.width-t.width)<1e-6&&Math.abs(e.height-t.height)<1e-6}function eB({item:e,shape:t,color:r,selected:n,dimmed:s,editable:a,isDrawing:c,size:d,onSelect:u,onShapeChange:f}){const[h,m]=(0,l.useState)(null),g={x:t.x,y:t.y,width:t.width,height:t.height};(0,l.useEffect)(()=>{h&&J6(g,h)&&m(null)},[t.x,t.y,t.width,t.height,h]);const p=h??g,y=p.x*d.w,S=p.y*d.h,E=p.width*d.w,T=p.height*d.h,j=s?.35:n?1:.85,N=G=>{m(G),f(e.id,{kind:"rect",x:G.x,y:G.y,width:G.width,height:G.height})},O=G=>({x:Math.max(-y,Math.min(d.w-(y+E),G.x)),y:Math.max(-S,Math.min(d.h-(S+T),G.y))}),U=G=>{const X=G.target,te=X.x()/d.w,ne=X.y()/d.h;if(X.position({x:0,y:0}),te===0&&ne===0)return;const ae=Math.min(Math.max(0,p.x+te),Math.max(0,1-p.width)),oe=Math.min(Math.max(0,p.y+ne),Math.max(0,1-p.height));N({...p,x:ae,y:oe})},z=G=>{const X=G.target,te=vs(X.x()/d.w-p.x),ne=vs(X.y()/d.h-p.y);m({...p,width:Math.max(Xl,Math.min(te,1-p.x)),height:Math.max(Xl,Math.min(ne,1-p.y))})},K=G=>{const X=G.target,te=vs(X.x()/d.w-p.x),ne=vs(X.y()/d.h-p.y);N({...p,width:Math.max(Xl,Math.min(te,1-p.x)),height:Math.max(Xl,Math.min(ne,1-p.y))})};return(0,i.jsx)(_e.Group,{onClick:G=>{G.cancelBubble=!0,c||u(e.id)},children:(0,i.jsxs)(_e.Group,{draggable:a,dragBoundFunc:a?O:void 0,onDragEnd:a?U:void 0,onMouseEnter:G=>{if(!a)return;const X=G.target.getStage();X&&(X.container().style.cursor="move")},onMouseLeave:G=>{if(!a)return;const X=G.target.getStage();X&&(X.container().style.cursor=c?"crosshair":"default")},children:[(0,i.jsx)(_e.Rect,{x:y,y:S,width:E,height:T,fill:r+(n?jh:mx),stroke:r,strokeWidth:n?2.5:1.5,opacity:j}),e.label?(0,i.jsx)(_e.Text,{x:y,y:S-16,text:e.label,fontSize:12,fill:r,stroke:"#000000",strokeWidth:3,fillAfterStrokeEnabled:!0,fontStyle:"bold",listening:!1}):null,a?(0,i.jsx)(_e.Circle,{x:y+E,y:S+T,radius:6,fill:r,stroke:"#ffffff",strokeWidth:1.5,draggable:!0,dragBoundFunc:G=>({x:Math.min(d.w,Math.max(y,G.x)),y:Math.min(d.h,Math.max(S,G.y))}),onDragStart:G=>{G.cancelBubble=!0},onDragMove:z,onDragEnd:K,onMouseEnter:G=>{const X=G.target.getStage();X&&(X.container().style.cursor="nwse-resize")},onMouseLeave:G=>{const X=G.target.getStage();X&&(X.container().style.cursor="default")}}):null]})})}function tB({item:e,shape:t,color:r,dimmed:n,editable:s,size:a,onSelect:c,paintingRef:d,paintValueRef:u,paintedRef:f,paintCell:h}){const{gridWidth:m,gridHeight:g,cells:p}=t,y=a.w/m,S=a.h/g,E=m*g,T=n?.3:1,j=U=>{if(!s){c(e.id);return}const z=p[U]!==!0;d.current=!0,u.current=z,f.current=new Set([U]),h(e.id,t,U,z)},N=U=>{!d.current||!s||f.current.has(U)||(f.current.add(U),h(e.id,t,U,u.current))},O=()=>{d.current&&(d.current=!1,f.current=new Set)};return(0,i.jsx)(_e.Group,{opacity:T,onMouseUp:O,onMouseLeave:O,children:Array.from({length:E},(U,z)=>{const K=z%m,G=Math.floor(z/m),X=p[z]===!0;return(0,i.jsx)(_e.Rect,{x:K*y,y:G*S,width:y,height:S,fill:X?r+jh:"#ffffff10",stroke:X?r:"#ffffff40",strokeWidth:.5,onMouseDown:te=>{te.cancelBubble=!0,j(z)},onMouseEnter:()=>N(z)},z)})})}function rB({item:e,shape:t,color:r,selected:n,dimmed:s,editable:a,isLine:c,isDrawing:d,size:u,effectivePoints:f,minVertices:h,maxVertices:m,isDragging:g,onSelect:p,onShapeChange:y,setDragOverride:S,setDraggingItemId:E}){const T=px(f,u.w,u.h),j=s?.35:n?1:c?.8:.85,N=pe=>c?{kind:"line",points:[...pe]}:{kind:"polygon",points:[...pe]},O=f.map(pe=>pe.x*u.w),U=f.map(pe=>pe.y*u.h),z=O.length>0?Math.min(...O):0,K=O.length>0?Math.max(...O):0,G=U.length>0?Math.min(...U):0,X=U.length>0?Math.max(...U):0,te=pe=>({x:Math.max(-z,Math.min(u.w-K,pe.x)),y:Math.max(-G,Math.min(u.h-X,pe.y))}),ne=pe=>{const le=pe.target,se=le.x()/u.w,Ce=le.y()/u.h;if(le.position({x:0,y:0}),E(null),se===0&&Ce===0)return;const q=t.points.map(Q=>({x:Q.x+se,y:Q.y+Ce}));S({itemId:e.id,points:q}),y(e.id,N(q))},ae=!c&&f.length>h,oe=!c&&(m===void 0||f.length<m);return(0,i.jsxs)(_e.Group,{onClick:pe=>{pe.cancelBubble=!0,d||p(e.id)},children:[(0,i.jsxs)(_e.Group,{draggable:a,dragBoundFunc:a?te:void 0,onDragStart:a?()=>E(e.id):void 0,onDragEnd:a?ne:void 0,onMouseEnter:pe=>{if(!a)return;const le=pe.target.getStage();le&&(le.container().style.cursor="move")},onMouseLeave:pe=>{if(!a)return;const le=pe.target.getStage();le&&(le.container().style.cursor=d?"crosshair":"default")},children:[c?(0,i.jsx)(_e.Arrow,{points:T,stroke:r,strokeWidth:n?3:2,fill:r,pointerLength:10,pointerWidth:8,opacity:j}):(0,i.jsx)(_e.Line,{points:T,closed:!0,fill:r+(n?jh:mx),stroke:r,strokeWidth:n?2.5:1.5,opacity:j}),e.label&&f.length>0?(()=>{const pe=So({x:f.reduce((se,Ce)=>se+Ce.x,0)/f.length,y:f.reduce((se,Ce)=>se+Ce.y,0)/f.length},u.w,u.h),le=Math.max(40,e.label.length*11*.62);return(0,i.jsx)(_e.Text,{x:pe.x-le/2,y:pe.y-7,width:le,align:"center",text:e.label,fontSize:12,fill:r,stroke:"#000000",strokeWidth:3,fillAfterStrokeEnabled:!0,fontStyle:"bold",listening:!1})})():null]}),a&&!g&&f.map((pe,le)=>{const se=So(pe,u.w,u.h);return(0,i.jsx)(_e.Circle,{x:se.x,y:se.y,radius:5,fill:r,stroke:"#ffffff",strokeWidth:1.5,draggable:!0,onDragMove:Ce=>{const q=Mh({x:Ce.target.x(),y:Ce.target.y()},u.w,u.h);S(Q=>{const ie=Q&&Q.itemId===e.id?Q.points:t.points;return{itemId:e.id,points:ie.map((be,we)=>we===le?q:be)}})},onDragEnd:Ce=>{const q=Mh({x:Ce.target.x(),y:Ce.target.y()},u.w,u.h),Q=t.points.map((ie,be)=>be===le?q:ie);S({itemId:e.id,points:Q}),y(e.id,N(Q))},onContextMenu:Ce=>{Ce.evt.preventDefault(),Ce.cancelBubble=!0,ae&&y(e.id,N(t.points.filter((q,Q)=>Q!==le)))}},`pt-${le}`)}),a&&!g&&oe&&f.length>=2&&f.map((pe,le)=>{const se=f[(le+1)%f.length],Ce=So({x:(pe.x+se.x)/2,y:(pe.y+se.y)/2},u.w,u.h);return(0,i.jsx)(_e.Circle,{x:Ce.x,y:Ce.y,radius:4,fill:"#ffffff",stroke:r,strokeWidth:1.5,opacity:.6,onMouseEnter:q=>{const Q=q.target;Q.to({radius:6,opacity:1,duration:.1});const ie=Q.getStage();ie&&(ie.container().style.cursor="copy")},onMouseLeave:q=>{const Q=q.target;Q.to({radius:4,opacity:.6,duration:.1});const ie=Q.getStage();ie&&(ie.container().style.cursor=d?"crosshair":"default")},onClick:q=>{q.cancelBubble=!0,y(e.id,N(q6(t.points,le)))}},`mid-${le}`)})]})}var $h=(0,l.memo)(X6),nB=110,iB="motion-zones",Rh=0,sB=[1,2,3],Lh=1,_o="rounded-md border border-border bg-surface px-2 py-1 text-[11px] font-medium text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors",Oh="rounded-md border border-primary/50 bg-primary/15 px-2.5 py-1 text-[11px] font-medium text-primary hover:bg-primary/25 disabled:opacity-40 transition-colors";function vx(e,t,r){const n=t*r,s=new Array(n);for(let a=0;a<n;a+=1)s[a]=e[a]===!0;return s}function aB(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(e[r]!==t[r])return!1;return!0}function li(e,t){return Math.ceil(e/t)}function Jl(e,t,r){return Math.min(r-1,Math.floor((e+.5)/t*r))}function ec(e,t,r,n){const s=li(t,n),a=li(r,n),c=new Array(s*a).fill(!1);for(let d=0;d<r;d+=1){const u=Jl(d,r,a);for(let f=0;f<t;f+=1)e[d*t+f]===!0&&(c[u*s+Jl(f,t,s)]=!0)}return c}function Fh(e,t,r,n){const s=li(t,n),a=li(r,n),c=new Array(t*r).fill(!1);for(let d=0;d<r;d+=1){const u=Jl(d,r,a);for(let f=0;f<t;f+=1)c[d*t+f]=e[u*s+Jl(f,t,s)]===!0}return c}function bx({deviceId:e}){const t=Br(Mr().trpcClient,e),[r,n]=(0,l.useState)(null),[s,a]=(0,l.useState)(!1),[c,d]=(0,l.useState)(null),[u,f]=(0,l.useState)(null),[h,m]=(0,l.useState)(Lh),[g,p]=(0,l.useState)(!1),[y,S]=(0,l.useState)(!1),E=(0,l.useRef)(!1);(0,l.useEffect)(()=>{if(!t)return;let q=!1;return E.current=!1,n(null),a(!1),d(null),f(null),m(Lh),S(!1),(async()=>{try{const Q=await t.motionZones?.getOptions({});if(q)return;if(!Q)throw new Error("device proxy not ready");if(n(Q),E.current)return;const ie=await t.motionZones?.getStatus({});if(q)return;if(!ie)throw new Error("device proxy not ready");E.current=!0;const be=ie.regions.find(Re=>Re.shape.kind==="grid"),we=vx(be?be.shape.cells:[],Q.grid.width,Q.grid.height);f(we),d(ec(we,Q.grid.width,Q.grid.height,Lh))}catch(Q){if(q)return;za(Q)?a(!0):console.error("Motion Zones load failed",Q)}})(),()=>{q=!0}},[t]);const T=r?r.grid.width:0,j=r?r.grid.height:0,N=li(T,h),O=li(j,h),U=(0,l.useMemo)(()=>c&&r?Fh(c,T,j,h):null,[c,r,T,j,h]),z=(0,l.useMemo)(()=>U!==null&&u!==null&&!aB(U,u),[U,u]),K=(0,l.useMemo)(()=>U?U.reduce((q,Q)=>Q?q+1:q,0):0,[U]),G=T*j,X=N*O,te=(0,l.useCallback)(q=>{X>0&&d(new Array(X).fill(q))},[X]),ne=(0,l.useCallback)(()=>{d(q=>q&&q.map(Q=>!Q))},[]),ae=(0,l.useCallback)(()=>{u&&r&&d(ec(u,T,j,h))},[u,r,T,j,h]),oe=(0,l.useCallback)(q=>{q===h||!r||d(Q=>{if(!Q)return m(q),Q;const ie=ec(Fh(Q,T,j,h),T,j,q);return m(q),ie})},[h,r,T,j]),pe=(0,l.useMemo)(()=>r&&c?[{id:Rh,shape:{kind:"grid",gridWidth:N,gridHeight:O,cells:[...c]}}]:[],[r,c,N,O]),le=(0,l.useCallback)((q,Q)=>{Q.kind==="grid"&&d(Q.cells)},[]),se=(0,l.useCallback)(async()=>{if(!(!t||!c||!r)){p(!0);try{const q=Fh(c,r.grid.width,r.grid.height,h),Q={kind:"grid",gridWidth:r.grid.width,gridHeight:r.grid.height,cells:q};await t.motionZones?.setZone({patch:{regions:[{id:Rh,enabled:!0,shape:Q}]}});const ie=await t.motionZones?.getStatus({});if(ie){const be=ie.regions.find(Re=>Re.shape.kind==="grid"),we=vx(be?be.shape.cells:[],r.grid.width,r.grid.height);f(we),d(ec(we,r.grid.width,r.grid.height,h))}}catch(q){console.error("Motion Zones save failed",q)}finally{p(!1)}}},[t,c,r,h]);Ah((0,l.useMemo)(()=>y&&!s&&r&&c?{id:iB,order:nB,node:(0,i.jsx)($h,{transparent:!0,items:pe,supportedShapes:["grid"],grid:{width:N,height:O},selectedId:Rh,onSelect:()=>{},onShapeChange:le,onDrawComplete:()=>{},drawingKind:null})}:null,[y,s,r,c,pe,le,N,O]));const Ce=!s&&r!==null&&c!==null;return t?(0,i.jsx)(Gn,{title:"Motion Zones",icon:(0,i.jsx)(QT,{className:"h-3.5 w-3.5 text-foreground-subtle"}),children:(0,i.jsx)("div",{className:"flex flex-col gap-3",children:s?(0,i.jsx)("p",{className:`${xn} leading-relaxed`,children:"This camera doesn't expose an on-board motion zones grid."}):Ce?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("p",{className:`${xn} leading-relaxed`,children:["Toggle ",(0,i.jsx)("strong",{className:"text-foreground",children:"Edit grid"})," to paint the region directly on the live frame, then ",(0,i.jsx)("strong",{className:"text-foreground",children:"Save"})," to push the mask to the camera. Pick a bigger ",(0,i.jsx)("strong",{className:"text-foreground",children:"Cell size"})," ","for quicker, broad-stroke painting — it's resampled to the camera's native"," ",r.grid.width,"×",r.grid.height," grid on save (×1 is the finest)."]}),(0,i.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,i.jsx)("button",{type:"button",onClick:()=>S(q=>!q),disabled:g,"aria-pressed":y,className:y?Oh:_o,children:y?"Done editing":"Edit grid"}),(0,i.jsx)("button",{type:"button",onClick:()=>te(!0),disabled:g,className:_o,children:"All on"}),(0,i.jsx)("button",{type:"button",onClick:()=>te(!1),disabled:g,className:_o,children:"All off"}),(0,i.jsx)("button",{type:"button",onClick:ne,disabled:g,className:_o,children:"Invert"}),(0,i.jsxs)("div",{className:"flex items-center gap-1 ml-1",role:"group","aria-label":"Cell size",children:[(0,i.jsx)("span",{className:`${xn} mr-0.5`,children:"Cell size"}),sB.map(q=>(0,i.jsxs)("button",{type:"button",onClick:()=>oe(q),disabled:g,"aria-pressed":h===q,title:q===1?`Camera grid ${T}×${j} (finest)`:`${li(T,q)}×${li(j,q)} painting grid · cells ×${q} bigger`,className:h===q?Oh:_o,children:["×",q]},q))]}),(0,i.jsxs)("span",{className:`${xn} ml-1 tabular-nums`,children:[K," / ",G," cells · ",r.grid.width,"×",r.grid.height,h!==1?` · paint ${N}×${O}`:""]}),(0,i.jsx)("span",{className:"flex-1"}),(0,i.jsx)("button",{type:"button",onClick:ae,disabled:g||!z,className:"rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors",children:"Revert"}),(0,i.jsx)("button",{type:"button",onClick:()=>void se(),disabled:g||!z,className:Oh,children:g?"Saving…":"Save"})]})]}):(0,i.jsx)("p",{className:`${xn} leading-relaxed`,children:"Loading the camera's grid…"})})}):null}var oB=120,lB="privacy-mask",tc="rounded-md border border-border bg-surface px-2 py-1 text-[11px] font-medium text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors",wo="rounded-md border border-primary/50 bg-primary/15 px-2.5 py-1 text-[11px] font-medium text-primary hover:bg-primary/25 disabled:opacity-40 transition-colors";function yx(e){return e.kind==="rect"||e.kind==="polygon"?e:null}function cB(e){const t=new Set(e.map(n=>n.id));let r=0;for(;t.has(r);)r+=1;return r}function uB(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r+=1)if(JSON.stringify(e[r])!==JSON.stringify(t[r]))return!1;return!0}function dB({deviceId:e}){const t=Br(Mr().trpcClient,e),[r,n]=(0,l.useState)(null),[s,a]=(0,l.useState)(!1),[c,d]=(0,l.useState)(null),[u,f]=(0,l.useState)(null),[h,m]=(0,l.useState)(!1),[g,p]=(0,l.useState)(!1),[y,S]=(0,l.useState)(null),[E,T]=(0,l.useState)(null),j=(0,l.useRef)(!1);(0,l.useEffect)(()=>{if(!t)return;let Ee=!1;return j.current=!1,n(null),a(!1),d(null),f(null),p(!1),S(null),T(null),(async()=>{try{const Fe=await t.privacyMask?.getOptions({});if(Ee)return;if(!Fe)throw new Error("device proxy not ready");if(n(Fe),j.current)return;const Ge=await t.privacyMask?.getStatus({});if(Ee)return;if(!Ge)throw new Error("device proxy not ready");j.current=!0;const Be={enabled:Ge.enabled,regions:Ge.regions};f(Be),d(Be)}catch(Fe){if(Ee)return;za(Fe)?a(!0):console.error("Privacy Mask load failed",Fe)}})(),()=>{Ee=!0}},[t]);const N=(0,l.useMemo)(()=>c!==null&&u!==null&&(c.enabled!==u.enabled||!uB(c.regions,u.regions)),[c,u]),O=c?c.regions.length:0,U=r?r.maxRegions:0,z=(0,l.useRef)(0);(0,l.useEffect)(()=>{z.current=U},[U]);const K=U>0&&O>=U,G=(0,l.useCallback)(()=>{d(Ee=>Ee&&{...Ee,enabled:!Ee.enabled})},[]),X=(0,l.useCallback)(Ee=>{S(typeof Ee=="number"?Ee:null)},[]),te=(0,l.useMemo)(()=>c?c.regions.map(Ee=>({id:Ee.id,shape:Ee.shape,enabled:Ee.enabled,label:`Zone ${String(Ee.id)}`})):[],[c]),ne=(0,l.useCallback)((Ee,Fe)=>{const Ge=yx(Fe);Ge&&d(Be=>Be&&{...Be,regions:Be.regions.map(st=>st.id===Ee?{...st,shape:Ge}:st)})},[]),ae=(0,l.useCallback)(Ee=>{const Fe=yx(Ee);Fe&&(T(null),d(Ge=>{if(!Ge)return Ge;const Be=z.current;if(Be>0&&Ge.regions.length>=Be)return Ge;const st=cB(Ge.regions),at={id:st,enabled:!0,shape:Fe};return S(st),{...Ge,regions:[...Ge.regions,at]}}))},[]),oe=(0,l.useCallback)(Ee=>{p(!0),S(null),T(Ee)},[]),pe=(0,l.useCallback)(Ee=>{p(!0),T(null),S(Ee)},[]),le=(0,l.useCallback)(Ee=>{S(Fe=>Fe===Ee?null:Fe),d(Fe=>Fe&&{...Fe,regions:Fe.regions.filter(Ge=>Ge.id!==Ee)})},[]),se=(0,l.useCallback)(()=>{T(null),S(null),u&&d({enabled:u.enabled,regions:u.regions})},[u]),Ce=(0,l.useCallback)(async()=>{if(!(!t||!c)){m(!0);try{await t.privacyMask?.setMask({patch:{enabled:c.enabled,regions:[...c.regions]}});const Ee=await t.privacyMask?.getStatus({});if(Ee){const Fe={enabled:Ee.enabled,regions:Ee.regions};f(Fe),d(Fe)}}catch(Ee){console.error("Privacy Mask save failed",Ee)}finally{m(!1)}}},[t,c]),q=(0,l.useCallback)(()=>{p(Ee=>(Ee&&(T(null),S(null)),!Ee))},[]),Q=r?.supportedShapes??[];Ah((0,l.useMemo)(()=>g&&!s&&r&&c?{id:lB,order:oB,node:(0,i.jsx)($h,{transparent:!0,items:te,supportedShapes:Q,polygonVertices:r.polygonVertices,selectedId:y,onSelect:X,onShapeChange:ne,onDrawComplete:ae,drawingKind:E})}:null,[g,s,r,c,te,Q,y,X,ne,ae,E]));const ie=r?.supportedShapes.includes("rect")??!1,be=r?.supportedShapes.includes("polygon")??!1,we=r!==null&&(r.maxRegions<=0||r.supportedShapes.length===0),Re=!s&&!we&&r!==null&&c!==null;return t?(0,i.jsx)(Gn,{title:"Privacy Mask",icon:(0,i.jsx)(vl,{className:"h-3.5 w-3.5 text-foreground-subtle"}),children:(0,i.jsx)("div",{className:"flex flex-col gap-3",children:s||we?(0,i.jsx)("p",{className:`${xn} leading-relaxed`,children:"This camera doesn't support an on-board privacy mask."}):Re?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("p",{className:`${xn} leading-relaxed`,children:["Toggle ",(0,i.jsx)("strong",{className:"text-foreground",children:"Edit mask"})," to draw blanked-out zones on the live frame, then ",(0,i.jsx)("strong",{className:"text-foreground",children:"Save"})," to push them to the camera. Drag a rectangle to move, its corner to resize; drag polygon vertices, click an edge midpoint to add one, or right-click a vertex to remove it."]}),(0,i.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,i.jsx)("button",{type:"button",onClick:q,disabled:h,"aria-pressed":g,className:g?wo:tc,children:g?"Done editing":"Edit mask"}),(0,i.jsx)("button",{type:"button",onClick:G,disabled:h,"aria-pressed":c.enabled,className:c.enabled?wo:tc,children:c.enabled?"Mask on":"Mask off"}),ie&&(0,i.jsx)("button",{type:"button",onClick:()=>oe("rect"),disabled:h||K,"aria-pressed":E==="rect",className:E==="rect"?wo:tc,title:K?"Maximum zones reached":"Add a rectangle zone",children:"+ Rect"}),be&&(0,i.jsx)("button",{type:"button",onClick:()=>oe("polygon"),disabled:h||K,"aria-pressed":E==="polygon",className:E==="polygon"?wo:tc,title:K?"Maximum zones reached":"Add a polygon zone",children:"+ Polygon"}),(0,i.jsxs)("span",{className:`${xn} ml-1 tabular-nums`,children:[O," / ",U," zones"]}),(0,i.jsx)("span",{className:"flex-1"}),(0,i.jsx)("button",{type:"button",onClick:se,disabled:h||!N,className:"rounded-md border border-border bg-surface px-2 py-1 text-[11px] text-foreground-subtle hover:bg-surface-hover disabled:opacity-40 transition-colors",children:"Revert"}),(0,i.jsx)("button",{type:"button",onClick:()=>void Ce(),disabled:h||!N,className:wo,children:h?"Saving…":"Save"})]}),O>0?(0,i.jsx)("div",{className:"flex flex-col gap-1",children:c.regions.map(Ee=>{const Fe=y===Ee.id,Ge=Ee.shape.kind==="polygon"?eC:Un;return(0,i.jsxs)("div",{className:`flex items-center gap-2 rounded-md border px-2 py-1 transition-colors ${Fe?"border-primary/50 bg-primary/10":"border-border bg-surface"}`,children:[(0,i.jsxs)("button",{type:"button",onClick:()=>pe(Ee.id),disabled:h,className:"flex flex-1 items-center gap-2 text-left text-[11px] font-medium text-foreground-subtle hover:text-foreground disabled:opacity-40 transition-colors",children:[(0,i.jsx)(Ge,{className:"h-3.5 w-3.5 shrink-0"}),(0,i.jsxs)("span",{children:["Zone ",Ee.id]}),(0,i.jsx)("span",{className:"text-foreground-faint capitalize",children:Ee.shape.kind})]}),(0,i.jsx)("button",{type:"button",onClick:()=>le(Ee.id),disabled:h,"aria-label":`Delete zone ${String(Ee.id)}`,title:"Delete zone",className:"inline-flex h-6 w-6 items-center justify-center rounded border border-border bg-surface text-foreground-subtle hover:border-red-400/40 hover:bg-red-500/10 hover:text-red-400 disabled:opacity-40 transition-colors",children:(0,i.jsx)(en,{className:"h-3.5 w-3.5"})})]},Ee.id)})}):null]}):(0,i.jsx)("p",{className:`${xn} leading-relaxed`,children:"Loading the camera's privacy mask…"})})}):null}function fB(){return{schedule:{kind:"always"},mode:"continuous",preBufferSec:0,postBufferSec:0,resetTimeoutOnNewEvent:!0}}function hB(e){return e==="onMotion"||e==="onAudioThreshold"}function Mi(e,t,r){return e.map((n,s)=>s===t?{...n,...r}:n)}function mB(e,t){return e.filter((r,n)=>n!==t)}var gB=[{d:0,label:"S"},{d:1,label:"M"},{d:2,label:"T"},{d:3,label:"W"},{d:4,label:"T"},{d:5,label:"F"},{d:6,label:"S"}];function pB(e){return e==="onMotion"||e==="onAudioThreshold"?e:"continuous"}function vB(e,t){return t==="onAudioThreshold"?{mode:t,thresholdDbfs:e.thresholdDbfs??-30}:t==="onMotion"?{mode:t,thresholdDbfs:void 0}:{mode:t,preBufferSec:0,postBufferSec:0,thresholdDbfs:void 0}}function bB({schedule:e,onChange:t}){const r=n=>{const s=e.days??[0,1,2,3,4,5,6],a=s.includes(n)?s.filter(c=>c!==n):[...s,n].sort((c,d)=>c-d);t({...e,days:a})};return(0,i.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[(0,i.jsx)("input",{type:"time",value:e.start,onChange:n=>t({...e,start:n.target.value}),className:"rounded-md border border-border bg-background px-2 py-1 text-xs"}),(0,i.jsx)("span",{children:"–"}),(0,i.jsx)("input",{type:"time",value:e.end,onChange:n=>t({...e,end:n.target.value}),className:"rounded-md border border-border bg-background px-2 py-1 text-xs"}),(0,i.jsx)("div",{className:"flex gap-1",children:gB.map(({d:n,label:s})=>(0,i.jsx)("button",{type:"button",onClick:()=>r(n),className:`h-6 w-6 rounded text-[10px] ${!e.days||e.days.includes(n)?"bg-primary text-primary-foreground":"bg-surface-hover text-foreground-subtle"}`,children:s},n))})]})}function yB({rules:e,onChange:t}){return(0,i.jsxs)("div",{className:"space-y-2",children:[e.length===0?(0,i.jsx)("p",{className:"text-xs text-foreground-subtle",children:"No rules — recording is continuous (always) when enabled."}):null,e.map((r,n)=>(0,i.jsxs)("div",{className:"space-y-2 rounded-lg border border-border bg-surface p-3",children:[(0,i.jsxs)("div",{className:"flex items-center justify-between gap-2",children:[(0,i.jsxs)("select",{className:"rounded-md border border-border bg-background px-2 py-1 text-xs",value:r.schedule.kind,onChange:s=>{t(Mi(e,n,{schedule:s.target.value==="timeOfDay"?{kind:"timeOfDay",start:"00:00",end:"23:59"}:{kind:"always"}}))},children:[(0,i.jsx)("option",{value:"always",children:"Always"}),(0,i.jsx)("option",{value:"timeOfDay",children:"Time of day"})]}),(0,i.jsx)("button",{type:"button",onClick:()=>t(mB(e,n)),className:"text-foreground-subtle hover:text-red-500",children:(0,i.jsx)(mr,{className:"h-4 w-4"})})]}),r.schedule.kind==="timeOfDay"?(0,i.jsx)(bB,{schedule:r.schedule,onChange:s=>t(Mi(e,n,{schedule:s}))}):null,(0,i.jsxs)("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:[(0,i.jsxs)("select",{className:"rounded-md border border-border bg-background px-2 py-1 text-xs",value:r.mode,onChange:s=>t(Mi(e,n,vB(r,pB(s.target.value)))),children:[(0,i.jsx)("option",{value:"continuous",children:"Continuous"}),(0,i.jsx)("option",{value:"onMotion",children:"On motion"}),(0,i.jsx)("option",{value:"onAudioThreshold",children:"On audio"})]}),hB(r.mode)?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("label",{className:"flex items-center gap-1",children:["pre",(0,i.jsx)("input",{type:"number",min:0,value:r.preBufferSec,onChange:s=>t(Mi(e,n,{preBufferSec:Number(s.target.value)})),className:"w-14 rounded-md border border-border bg-background px-1 py-1 text-xs"}),"s"]}),(0,i.jsxs)("label",{className:"flex items-center gap-1",children:["post",(0,i.jsx)("input",{type:"number",min:0,value:r.postBufferSec,onChange:s=>t(Mi(e,n,{postBufferSec:Number(s.target.value)})),className:"w-14 rounded-md border border-border bg-background px-1 py-1 text-xs"}),"s"]}),(0,i.jsxs)("label",{className:"flex items-center gap-1",children:[(0,i.jsx)("input",{type:"checkbox",checked:r.resetTimeoutOnNewEvent,onChange:s=>t(Mi(e,n,{resetTimeoutOnNewEvent:s.target.checked}))}),"reset"]})]}):null,r.mode==="onAudioThreshold"?(0,i.jsxs)("label",{className:"flex items-center gap-1",children:["thr",(0,i.jsx)("input",{type:"number",value:r.thresholdDbfs??-30,onChange:s=>t(Mi(e,n,{thresholdDbfs:Number(s.target.value)})),className:"w-16 rounded-md border border-border bg-background px-1 py-1 text-xs"}),"dBFS"]}):null]})]},n)),(0,i.jsxs)("button",{type:"button",onClick:()=>t([...e,fB()]),className:"flex items-center gap-1 rounded-md border border-dashed border-border px-3 py-1.5 text-xs text-foreground-subtle hover:border-primary hover:text-foreground",children:[(0,i.jsx)(Ci,{className:"h-3.5 w-3.5"})," Add rule"]})]})}var xB=["high","mid","low"];function SB({initial:e,saving:t,onSave:r}){const[n,s]=(0,l.useState)(e),a=n.retention??{},c=u=>s({...n,retention:{...a,...u}}),d=u=>u===""?void 0:Number(u);return(0,i.jsxs)("div",{className:"space-y-4",children:[(0,i.jsxs)("label",{className:"flex items-center gap-2 text-xs",children:[(0,i.jsx)("input",{type:"checkbox",checked:n.enabled,onChange:u=>s({...n,enabled:u.target.checked})}),"Record this camera"]}),(0,i.jsxs)("div",{className:"flex flex-wrap items-center gap-4 text-xs",children:[(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsx)("span",{className:"text-foreground-subtle",children:"Profiles:"}),xB.map(u=>(0,i.jsx)("button",{type:"button",onClick:()=>{const f=n.profiles??[],h=f.includes(u)?f.filter(m=>m!==u):[...f,u];s({...n,profiles:h.length?h:void 0})},className:`rounded px-2 py-1 ${(n.profiles??[]).includes(u)?"bg-primary text-primary-foreground":"bg-surface-hover text-foreground-subtle"}`,children:u},u))]}),(0,i.jsxs)("label",{className:"flex items-center gap-1",children:["Segment",(0,i.jsx)("input",{type:"number",min:1,value:n.segmentSeconds??"",placeholder:"default",onChange:u=>s({...n,segmentSeconds:d(u.target.value)}),className:"w-16 rounded-md border border-border bg-background px-1 py-1 text-xs"}),"s"]})]}),(0,i.jsxs)("div",{children:[(0,i.jsx)("div",{className:"mb-1.5 text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle",children:"Rules"}),(0,i.jsx)(yB,{rules:n.rules??[],onChange:u=>s({...n,rules:u})})]}),(0,i.jsxs)("div",{children:[(0,i.jsx)("div",{className:"mb-1.5 text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle",children:"Retention (empty = node default)"}),(0,i.jsxs)("div",{className:"flex flex-wrap items-center gap-3 text-xs",children:[(0,i.jsxs)("label",{className:"flex items-center gap-1",children:["Max age",(0,i.jsx)("input",{type:"number",min:0,value:a.maxAgeDays??"",placeholder:"14",onChange:u=>c({maxAgeDays:d(u.target.value)}),className:"w-16 rounded-md border border-border bg-background px-1 py-1 text-xs"}),"days"]}),(0,i.jsxs)("label",{className:"flex items-center gap-1",children:["Max size",(0,i.jsx)("input",{type:"number",min:0,value:a.maxSizeGb??"",placeholder:"∞",onChange:u=>c({maxSizeGb:d(u.target.value)}),className:"w-16 rounded-md border border-border bg-background px-1 py-1 text-xs"}),"GB"]})]})]}),(0,i.jsx)("div",{className:"flex justify-end",children:(0,i.jsxs)("button",{type:"button",disabled:t,onClick:()=>r(n),className:"flex items-center gap-1.5 rounded-md bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground disabled:opacity-60",children:[t?(0,i.jsx)(hr,{className:"h-3.5 w-3.5 animate-spin"}):(0,i.jsx)(Bp,{className:"h-3.5 w-3.5"})," Save"]})})]})}var xx=Sn("camstack:vod-playback",{request:null,play:()=>{},clear:()=>{}});function _B({children:e}){const[t,r]=(0,l.useState)(null),n=(0,l.useMemo)(()=>({request:t,play:s=>r(s),clear:()=>r(null)}),[t]);return(0,i.jsx)(xx.Provider,{value:n,children:e})}function Sx(){return(0,l.useContext)(xx)}function wB(e){const t=e.filter(n=>n.endMs>n.startMs).map(n=>({startMs:n.startMs,endMs:n.endMs})).sort((n,s)=>n.startMs-s.startMs),r=[];for(const n of t){const s=r[r.length-1];s&&n.startMs<=s.endMs?n.endMs>s.endMs&&(r[r.length-1]={startMs:s.startMs,endMs:n.endMs}):r.push(n)}return r}function EB(e){if(!Number.isFinite(e)||e<0)return"—";if(e<1024)return`${Math.round(e)} B`;const t=["KB","MB","GB","TB","PB"];let r=e/1024,n="KB";for(const s of t){if(n=s,r<1024)break;r/=1024}return`${r>=100?Math.round(r).toString():r.toFixed(1)} ${n}`}var kB=["object","motion","audio"];function TB(e,t,r){const n=[];for(const s of e){const a={motion:s.motion,object:s.object,audio:s.audio},c=a.motion+a.object+a.audio;if(c===0)continue;const d=Math.floor((s.bucketStart-t)/r);let u=null,f=-1;for(const h of kB)a[h]>f&&(f=a[h],u=h);n.push({index:d,startMs:s.bucketStart,endMs:s.bucketStart+r,counts:a,total:c,dominant:u})}return n.sort((s,a)=>s.index-a.index)}function CB(e,t){return e<t.startMs?t.startMs-e:e>t.endMs?e-t.endMs:0}function IB(e,t){if(t.length===0)return null;const r=t.find(a=>e>=a.startMs&&e<=a.endMs);if(r)return{fromMs:e,toMs:r.endMs};let n=null,s=1/0;for(const a of t){const c=CB(e,a);c<s&&(s=c,n=a)}return n?{fromMs:n.startMs,toMs:n.endMs}:null}function $i(e,t,r){const n=r-t;if(n<=0)return 0;const s=(e-t)/n*100;return s<0?0:s>100?100:s}function Uh(e,t){const r=new Date(e.getFullYear(),e.getMonth(),e.getDate(),0,0,0,0).getTime(),n=new Date(e.getFullYear(),e.getMonth(),e.getDate()+1,0,0,0,0).getTime();return{fromMs:r,toMs:Math.max(r,Math.min(n,t))}}var bs=[24*36e5,12*36e5,6*36e5,36e5,15*6e4];function _x(e,t,r,n){if(r>=t.toMs-t.fromMs)return t;let s=n-r/2,a=n+r/2;return s<t.fromMs&&(s=t.fromMs,a=s+r),a>t.toMs&&(a=t.toMs,s=a-r),{fromMs:s,toMs:a}}function PB(e,t,r){const n=e.toMs-e.fromMs;let s=e.fromMs+r,a=e.toMs+r;return s<t.fromMs&&(s=t.fromMs,a=s+n),a>t.toMs&&(a=t.toMs,s=a-n),{fromMs:s,toMs:a}}var Bh=[15*6e4,5*6e4,6e4,3e4,15e3,5e3];function AB(e){const t=e/100;for(const r of Bh)if(r<=t)return r;return Bh[Bh.length-1]??5e3}function jB(e,t,r){const n=[];for(let s=0;s<r;s++){const a=e+s/(r-1)*(t-e),c=$i(a,e,t),d=new Date(a).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"});n.push({pct:c,label:d})}return n}function NB({windowFrom:e,windowTo:t,spans:r,playheadMs:n,onSeek:s}){const[a,c]=(0,l.useState)(null),d=g=>{const p=g.currentTarget.getBoundingClientRect();if(p.width<=0)return null;const y=(g.clientX-p.left)/p.width;return e+Math.min(1,Math.max(0,y))*(t-e)},u=g=>{const p=d(g);p!==null&&s(p)},f=g=>{const p=d(g);if(p===null)return;const y=g.currentTarget.getBoundingClientRect();c({xPct:y.width>0?(g.clientX-y.left)/y.width*100:0,ms:p})},h=()=>{c(null)},m=a!==null?new Date(a.ms).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit",second:"2-digit"}):null;return(0,i.jsxs)("div",{className:"relative",children:[(0,i.jsxs)("div",{"data-testid":"coverage-track",onClick:u,onMouseMove:f,onMouseLeave:h,className:"relative h-5 cursor-pointer overflow-hidden rounded bg-background/40",role:"group","aria-label":"Recorded coverage timeline",children:[r.map(g=>{const p=$i(g.startMs,e,t),y=$i(g.endMs,e,t);return(0,i.jsx)("div",{"data-testid":"coverage-fascia",className:"absolute inset-y-0 bg-gradient-to-b from-primary to-primary/80",style:{left:`${p}%`,width:`${Math.max(.5,y-p)}%`}},`${g.startMs}-${g.endMs}`)}),n!==null?(0,i.jsx)("div",{"data-testid":"coverage-playhead",className:"absolute inset-y-[-2px] w-0.5 bg-amber-500 shadow-[0_0_6px] shadow-amber-500",style:{left:`${$i(n,e,t)}%`}}):null]}),a!==null&&m!==null?(0,i.jsx)("div",{"data-testid":"coverage-hover-tooltip",className:"pointer-events-none absolute top-full z-10 mt-0.5 -translate-x-1/2 rounded bg-popover px-1.5 py-0.5 text-[9px] text-popover-foreground shadow",style:{left:`${a.xPct}%`},children:m}):null]})}var DB={motion:"bg-emerald-500",object:"bg-violet-500",audio:"bg-orange-500"};function MB({windowFrom:e,windowTo:t,buckets:r,selectedIndex:n,onSelectBucket:s}){const a=r.reduce((u,f)=>Math.max(u,f.total),0),c=r[0],d=c?$i(c.endMs,e,t)-$i(c.startMs,e,t):0;return(0,i.jsx)("div",{className:"relative h-6 rounded bg-background/40",children:r.map(u=>{if(u.total===0||u.dominant===null)return null;const f=a>0?Math.max(15,u.total/a*100):0,h=$i(u.startMs,e,t),m=u.index===n;return(0,i.jsx)("button",{type:"button","data-testid":"heatmap-bar",title:`${new Date(u.startMs).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})} · motion ${u.counts.motion} · object ${u.counts.object}`,onClick:()=>s(u.index),className:`absolute bottom-0 rounded-t-sm transition-opacity ${DB[u.dominant]} ${m?"opacity-100 ring-1 ring-amber-400":"opacity-80 hover:opacity-100"}`,style:{left:`${h}%`,width:`${Math.max(.6,d)}%`,height:`${f}%`}},u.index)})})}function $B({mediaUrl:e,kind:t}){const[r,n]=(0,l.useState)(!1);return e&&!r?(0,i.jsx)("img",{src:e,alt:"",className:"h-full w-full object-cover",loading:"lazy",onError:()=>n(!0)}):(0,i.jsx)("div",{className:"flex h-full w-full items-center justify-center text-white/30",children:(0,i.jsx)(wx,{kind:t,large:!0})})}function wx({kind:e,large:t=!1}){const r=t?"h-7 w-7":"h-3.5 w-3.5 text-foreground-subtle";return e==="object"?(0,i.jsx)(Fd,{className:r}):e==="audio"?(0,i.jsx)(tf,{className:r}):(0,i.jsx)(wn,{className:r})}var RB=["motion","object","audio"];function LB(e){return new Date(e).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}function OB({clips:e,loading:t,busyKey:r,onPlay:n,enabledKinds:s,onToggleKind:a,hasMore:c,onLoadMore:d}){const u=(0,i.jsx)("div",{className:"flex items-center gap-3 pb-1",children:RB.map(f=>(0,i.jsxs)("label",{className:"flex cursor-pointer items-center gap-1 text-xs text-foreground-subtle select-none",children:[(0,i.jsx)("input",{type:"checkbox",checked:s.has(f),onChange:()=>a(f),className:"h-3.5 w-3.5 accent-primary"}),f]},f))});return t&&e.length===0?(0,i.jsxs)("div",{className:"space-y-2",children:[u,(0,i.jsx)("div",{className:"px-1 py-2 text-xs text-foreground-subtle",children:"Loading events…"})]}):e.length===0?(0,i.jsxs)("div",{className:"space-y-2",children:[u,(0,i.jsx)("div",{className:"px-1 py-2 text-xs text-foreground-subtle",children:"No events in this window."})]}):(0,i.jsxs)("div",{className:"space-y-2",children:[u,t?(0,i.jsx)("div",{className:"px-1 text-[10px] text-foreground-subtle",children:"Loading events…"}):null,(0,i.jsx)("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-3",children:e.map(f=>{const h=`event:${f.id}`;return(0,i.jsxs)("button",{type:"button",disabled:r!==null,onClick:()=>n(f),className:"group overflow-hidden rounded-lg border border-border text-left transition-colors hover:border-primary disabled:opacity-60",children:[(0,i.jsxs)("div",{className:"relative aspect-video bg-black/90",children:[(0,i.jsx)($B,{mediaUrl:f.mediaUrl,kind:f.kind}),(0,i.jsx)("div",{className:"absolute inset-0 flex items-center justify-center bg-black/0 transition-colors group-hover:bg-black/30",children:r===h?(0,i.jsx)(hr,{className:"h-6 w-6 animate-spin text-white"}):(0,i.jsx)(Fn,{className:"h-6 w-6 text-white opacity-0 transition-opacity group-hover:opacity-100"})})]}),(0,i.jsxs)("div",{className:"flex items-center gap-1.5 bg-surface px-2 py-1.5",children:[(0,i.jsx)(wx,{kind:f.kind}),(0,i.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,i.jsx)("div",{className:"truncate text-xs font-medium text-foreground",children:f.label}),(0,i.jsx)("div",{className:"text-[10px] text-foreground-subtle",children:LB(f.timestamp)})]})]})]},h)})}),e.length>0?(0,i.jsxs)("div",{className:"flex items-center gap-2 pt-1 text-[11px] text-foreground-subtle",children:[(0,i.jsxs)("span",{children:["(",e.length," shown)"]}),c?(0,i.jsx)("button",{type:"button",onClick:d,className:"rounded px-2 py-0.5 text-[11px] font-medium text-primary hover:underline",children:"Load more"}):null]}):null]})}function Ex(e){return`${e.getFullYear()}-${String(e.getMonth()+1).padStart(2,"0")}-${String(e.getDate()).padStart(2,"0")}`}function FB(e){const t=e.split("-"),r=t[0]!==void 0?parseInt(t[0],10):NaN,n=t[1]!==void 0?parseInt(t[1],10):NaN,s=t[2]!==void 0?parseInt(t[2],10):NaN;return isNaN(r)||isNaN(n)||isNaN(s)?null:new Date(r,n-1,s)}function UB({day:e,onDayChange:t,view:r,dayBounds:n,onViewChange:s}){const a=p=>{const y=FB(p.target.value);y!==null&&t(y)},c=r.toMs-r.fromMs,d=(()=>{let p=0,y=1/0;for(let S=0;S<bs.length;S++){const E=bs[S];if(E===void 0)continue;const T=Math.abs(E-c);T<y&&(y=T,p=S)}return p})(),u=(r.fromMs+r.toMs)/2,f=()=>{const p=bs[Math.min(d+1,bs.length-1)];p!==void 0&&s(_x(r,n,p,u))},h=()=>{const p=bs[Math.max(d-1,0)];p!==void 0&&s(_x(r,n,p,u))},m=d<bs.length-1,g=d>0;return(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsx)("input",{type:"date",value:Ex(e),max:Ex(new Date),onChange:a,className:"rounded border border-border bg-background px-2 py-0.5 text-[11px] text-foreground focus:outline-none focus:ring-1 focus:ring-primary","aria-label":"Select recording day"}),(0,i.jsxs)("div",{className:"ml-auto flex items-center gap-1",children:[(0,i.jsx)("button",{type:"button",onClick:h,disabled:!g,title:"Zoom out","aria-label":"Zoom out",className:"rounded p-1 text-foreground-subtle transition-colors hover:bg-background/60 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40",children:(0,i.jsx)(qp,{size:13})}),(0,i.jsx)("button",{type:"button",onClick:f,disabled:!m,title:"Zoom in","aria-label":"Zoom in",className:"rounded p-1 text-foreground-subtle transition-colors hover:bg-background/60 hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40",children:(0,i.jsx)(Wp,{size:13})})]}),(0,i.jsx)("span",{className:"text-[9px] text-foreground-subtle",children:BB(c)})]})}function BB(e){const t=e/36e5;if(t>=24)return"24h";if(t>=1)return`${Math.round(t)}h`;const r=e/6e4;return`${Math.round(r)}m`}var zB=["motion","object","audio"],zh=60,GB=18e3/100,ZB=5e3,VB=1e4,HB=[];function KB({deviceId:e}){const t=Mr(),r=Sx(),[n,s]=(0,l.useState)(null),[a,c]=(0,l.useState)(null),[d,u]=(0,l.useState)(null),[f,h]=(0,l.useState)(null),[m,g]=(0,l.useState)(()=>new Set(zB)),p=(0,l.useCallback)($e=>{g(Ke=>{const ft=new Set(Ke);return ft.has($e)?ft.delete($e):ft.add($e),ft})},[]),[y,S]=(0,l.useState)(zh),E=(0,l.useCallback)(()=>{S($e=>$e+zh)},[]);(0,l.useEffect)(()=>{S(zh)},[n]);const[T,j]=(0,l.useState)(()=>new Date),[N,O]=(0,l.useState)(()=>Uh(new Date,Date.now())),U=(0,l.useMemo)(()=>Uh(T,Date.now()),[T]),z=(0,l.useCallback)($e=>{j($e),O(Uh($e,Date.now())),s(null)},[]),K=(0,l.useCallback)($e=>{O($e),s(null)},[]),G=(0,l.useRef)(null),X=(0,l.useCallback)($e=>{const Ke=Math.abs($e.deltaX)>Math.abs($e.deltaY)?$e.deltaX:$e.shiftKey?$e.deltaY:0;if(Ke===0)return;$e.preventDefault();const ft=Ke*GB;O(St=>PB(St,U,ft))},[U]),te=AB(N.toMs-N.fromMs),ne=Pf({deviceId:e,fromMs:N.fromMs,toMs:N.toMs}),ae=x0({deviceId:e,since:N.fromMs,until:N.toMs,bucketMs:te}),oe=ne.data?.ranges??HB,pe=(0,l.useMemo)(()=>wB(oe),[oe]),le=(0,l.useMemo)(()=>TB(ae.data??[],N.fromMs,te),[ae.data,N.fromMs,te]),se=n!==null?le.find($e=>$e.index===n):void 0,Ce=se!==void 0,q=se?.startMs??0,Q=se?Math.min(se.endMs,N.toMs):0,ie=b0({deviceId:e,since:q,until:Q,limit:y,projection:"slim"},{enabled:Ce&&m.has("object")}),be=v0({deviceId:e,since:q,until:Q,limit:y,projection:"slim"},{enabled:Ce&&m.has("motion")}),we=y0({deviceId:e,since:q,until:Q,limit:y,projection:"slim"},{enabled:Ce&&m.has("audio")}),Re=(0,l.useMemo)(()=>{if(!se)return[];const $e=[];if(m.has("object"))for(const Ke of ie.data??[])$e.push({id:Ke.id,timestamp:Ke.timestamp,kind:"object",label:Ke.label??Ke.className,mediaUrl:Ke.mediaUrl});if(m.has("motion"))for(const Ke of be.data??[])$e.push({id:Ke.id,timestamp:Ke.timestamp,kind:"motion",label:`Motion (${Ke.regionCount})`,mediaUrl:Ke.mediaUrl});if(m.has("audio"))for(const Ke of we.data??[])$e.push({id:Ke.id,timestamp:Ke.timestamp,kind:"audio",label:Ke.classification?.className??"Audio",mediaUrl:Ke.mediaUrl});return $e.sort((Ke,ft)=>ft.timestamp-Ke.timestamp)},[se,m,ie.data,be.data,we.data]),Ee=(0,l.useMemo)(()=>!!(m.has("object")&&(ie.data?.length??0)===y||m.has("motion")&&(be.data?.length??0)===y||m.has("audio")&&(we.data?.length??0)===y),[m,ie.data,be.data,we.data,y]),Fe=(0,l.useCallback)(async($e,Ke,ft,St,Rt)=>{u($e),h(null);try{const dr=await t.trpcClient.recording.getPlaybackManifest.query({deviceId:e,fromMs:Ke,toMs:ft});dr?.playbackUrl?(c(Rt),r.play({url:dr.playbackUrl,label:St})):h("No playable footage for this selection.")}catch{h("Could not load this recording.")}finally{u(null)}},[t,e,r]),Ge=(0,l.useCallback)($e=>{const Ke=IB($e,pe);if(!Ke)return;const ft=`Recording · ${new Date(Ke.fromMs).toLocaleString(void 0,{month:"short",day:"numeric",hour:"2-digit",minute:"2-digit"})}`;Fe(`seek:${Ke.fromMs}`,Ke.fromMs,Ke.toMs,ft,Ke.fromMs)},[pe,Fe]),Be=(0,l.useCallback)($e=>{const Ke=`${$e.label} · ${new Date($e.timestamp).toLocaleTimeString(void 0,{hour:"2-digit",minute:"2-digit"})}`;Fe(`event:${$e.id}`,$e.timestamp-ZB,$e.timestamp+VB,Ke,$e.timestamp)},[Fe]),st=(0,l.useCallback)($e=>{s(Ke=>Ke===$e?null:$e)},[]),at=ne.isLoading,We=ae.isLoading,ct=(ie.isLoading||be.isLoading||we.isLoading)&&Ce,He=(0,l.useMemo)(()=>jB(N.fromMs,N.toMs,5),[N.fromMs,N.toMs]);return(0,i.jsxs)("div",{className:"space-y-3",children:[ne.isError?(0,i.jsx)(ao,{variant:"warning",message:"Recorder unavailable — the recording service may not be running for this node."}):null,f?(0,i.jsx)(ao,{variant:"warning",message:f}):null,(0,i.jsx)(UB,{day:T,onDayChange:z,view:N,dayBounds:U,onViewChange:K}),(0,i.jsxs)("div",{ref:G,onWheel:X,className:"space-y-1",children:[(0,i.jsxs)("div",{className:"space-y-1",children:[(0,i.jsx)("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle",children:"Recorded"}),at?(0,i.jsx)("div",{className:"h-5 animate-pulse rounded bg-background/40"}):pe.length===0?(0,i.jsx)(pf,{icon:Pp,title:"No recordings for this window."}):(0,i.jsx)(NB,{windowFrom:N.fromMs,windowTo:N.toMs,spans:pe,playheadMs:a,onSeek:Ge})]}),(0,i.jsxs)("div",{className:"space-y-1",children:[(0,i.jsx)("div",{className:"text-[10px] font-semibold uppercase tracking-wider text-foreground-subtle",children:"Events · density"}),We?(0,i.jsx)("div",{className:"h-6 animate-pulse rounded bg-background/40"}):(0,i.jsx)(MB,{windowFrom:N.fromMs,windowTo:N.toMs,buckets:le,selectedIndex:n,onSelectBucket:st})]}),(0,i.jsx)("div",{className:"relative h-3",children:He.map($e=>(0,i.jsx)("span",{className:"absolute -translate-x-1/2 text-[9px] text-foreground-subtle",style:{left:`${$e.pct}%`},children:$e.label},$e.pct))})]}),se?(0,i.jsx)(OB,{clips:Re,loading:ct,busyKey:d,onPlay:Be,enabledKinds:m,onToggleKind:p,hasMore:Ee,onLoadMore:E}):(0,i.jsx)("p",{className:"text-[11px] text-foreground-subtle",children:"Click the coverage bar to play from any point, or a density bar to browse that window's events."})]})}var WB=1440*60*1e3;function qB(e){const t=Math.round(e/1e3),r=Math.floor(t/3600),n=Math.floor(t%3600/60),s=t%60;return r>0?`${r}h ${n}m`:n>0?`${n}m ${s}s`:`${s}s`}function kx({deviceId:e}){const t=(0,ye.useQueryClient)(),r=C0({deviceId:e}),n=E0({deviceId:e}),s=k0(),a=T0(),c=T=>{s.mutate({deviceId:e,config:T},{onSuccess:()=>{n.refetch(),r.refetch()}})},d=(0,l.useCallback)(()=>{a.mutate({deviceId:e},{onSuccess:()=>{t.invalidateQueries({queryKey:[["recording"]]})}})},[e,t,a]),u=(0,l.useMemo)(()=>Date.now(),[]),f=Pf({deviceId:e,fromMs:u-WB,toMs:u}),h=r.data?W.RecordingStatusSchema.safeParse(r.data):null,m=h?.success?h.data:null,g=n.data?W.RecordingConfigSchema.safeParse(n.data):null,p=g?.success?g.data:null,y=f.data?.ranges??[],S=y.reduce((T,j)=>T+Math.max(0,j.endMs-j.startMs),0),E=m?.enabled===!0&&m.activeMode==="continuous";return(0,i.jsxs)("div",{className:"space-y-3",children:[(0,i.jsx)(Gn,{title:"Settings",icon:(0,i.jsx)(wC,{className:"h-3.5 w-3.5 text-foreground-subtle"}),collapsible:!0,defaultOpen:!1,children:p?(0,i.jsx)(SB,{initial:p,saving:s.isPending,onSave:c},JSON.stringify(p)):(0,i.jsx)("div",{className:"px-1 py-2 text-xs text-foreground-subtle",children:"Loading settings…"})}),(0,i.jsx)(Gn,{title:"Recording",icon:(0,i.jsx)(Pp,{className:"h-3.5 w-3.5 text-foreground-subtle"}),headerRight:(0,i.jsxs)("span",{className:"flex items-center gap-2",children:[E?(0,i.jsxs)("span",{className:"flex items-center gap-1.5 text-[10px] text-emerald-500",children:[(0,i.jsx)(Up,{className:"h-3 w-3"})," Recording"]}):null,(0,i.jsx)("button",{type:"button",onClick:d,disabled:a.isPending,"aria-label":"Rescan storage",className:"flex items-center rounded p-0.5 text-foreground-subtle transition-colors hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",children:(0,i.jsx)(Ii,{className:`h-3.5 w-3.5 ${a.isPending?"animate-spin":""}`})})]}),children:(0,i.jsxs)("div",{className:"space-y-3",children:[(0,i.jsxs)("div",{className:"grid grid-cols-1 gap-2 sm:grid-cols-3",children:[(0,i.jsx)(Ql,{label:"Status",icon:(0,i.jsx)(wp,{className:`h-3.5 w-3.5 ${E?"text-emerald-500":""}`}),footer:m?.nodeId?`node: ${m.nodeId}`:void 0,children:r.isLoading?"…":E?"Recording (continuous)":"Idle"}),(0,i.jsx)(Ql,{label:"Storage",icon:(0,i.jsx)(XT,{className:"h-3.5 w-3.5"}),children:m?EB(m.storageBytes):"—"}),(0,i.jsx)(Ql,{label:"Recorded (24h)",icon:(0,i.jsx)(Ud,{className:"h-3.5 w-3.5"}),footer:`${y.length} segment range${y.length===1?"":"s"}`,children:f.isLoading?"…":qB(S)})]}),r.isError?(0,i.jsx)(ao,{variant:"warning",message:"Recorder unavailable — the recording service may not be running for this node."}):null,(0,i.jsx)(KB,{deviceId:e}),(0,i.jsx)("p",{className:"text-[11px] text-foreground-subtle",children:"Recordings play in the main player above — switch back to live from there."})]})})]})}var Tx={"host/motion-zones-grid":bx,"host/privacy-mask-grid":dB,"host/ptz-panel":lx,"host/consumables-panel":cx,"host/ptz-autotrack":dx,"host/recording-panel":kx};function Cx(e){const{widgetId:t,deviceId:r}=e,n=Tx[t];return n!==void 0?r===void 0?(0,i.jsx)(Eo,{widgetId:t,reason:"missing-device-context"}):(0,i.jsx)(n,{deviceId:r}):(0,i.jsx)(QB,{...e})}function QB(e){const{widgetId:t}=e,r=ax(t);return r===void 0?(0,i.jsx)(Eo,{widgetId:t,reason:"unknown"}):(0,i.jsx)(YB,{...e,metadata:r})}function YB(e){const{widgetId:t,host:r="device-tab",config:n,deviceId:s,integrationId:a,instanceId:c,size:d,columns:u,rows:f,metadata:h}=e,m=ox(h.remote,h.bundleUrl),g=(0,l.useMemo)(()=>c??t,[c,t]);return m===null?(0,i.jsx)(XB,{}):m===void 0?(0,i.jsx)(Eo,{widgetId:t,reason:"missing-export"}):h.requires.deviceContext&&s===void 0?(0,i.jsx)(Eo,{widgetId:t,reason:"missing-device-context"}):h.requires.integrationContext&&a===void 0?(0,i.jsx)(Eo,{widgetId:t,reason:"missing-integration-context"}):(0,i.jsx)(m,{instanceId:g,host:r,config:n,deviceId:s,integrationId:a,size:d,columns:u,rows:f})}function XB(){return(0,i.jsxs)("div",{className:"rounded-lg border border-border bg-surface/40 p-4 animate-pulse",children:[(0,i.jsx)("div",{className:"h-3 w-24 bg-foreground-subtle/20 rounded mb-2"}),(0,i.jsx)("div",{className:"h-2 w-full bg-foreground-subtle/10 rounded mb-1"}),(0,i.jsx)("div",{className:"h-2 w-3/4 bg-foreground-subtle/10 rounded"})]})}function Eo({widgetId:e,reason:t}){return(0,i.jsx)("div",{className:"rounded-lg border border-warning/30 bg-warning/10 px-3 py-2 text-xs text-warning",children:t==="unknown"?`Widget "${e}" not registered`:t==="missing-export"?`Widget "${e}" bundle does not export this stableId`:t==="missing-device-context"?`Widget "${e}" requires a deviceId`:`Widget "${e}" requires an integrationId`})}var JB=Object.defineProperty,rc=Object.getOwnPropertySymbols,Ix=Object.prototype.hasOwnProperty,Px=Object.prototype.propertyIsEnumerable,Ax=(e,t,r)=>t in e?JB(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,Gh=(e,t)=>{for(var r in t||(t={}))Ix.call(t,r)&&Ax(e,r,t[r]);if(rc)for(var r of rc(t))Px.call(t,r)&&Ax(e,r,t[r]);return e},Zh=(e,t)=>{var r={};for(var n in e)Ix.call(e,n)&&t.indexOf(n)<0&&(r[n]=e[n]);if(e!=null&&rc)for(var n of rc(e))t.indexOf(n)<0&&Px.call(e,n)&&(r[n]=e[n]);return r};/**
141
+ * @license QR Code generator library (TypeScript)
142
+ * Copyright (c) Project Nayuki.
143
+ * SPDX-License-Identifier: MIT
144
+ */var Ri;(e=>{const t=class It{constructor(u,f,h,m){if(this.version=u,this.errorCorrectionLevel=f,this.modules=[],this.isFunction=[],u<It.MIN_VERSION||u>It.MAX_VERSION)throw new RangeError("Version value out of range");if(m<-1||m>7)throw new RangeError("Mask value out of range");this.size=u*4+17;let g=[];for(let y=0;y<this.size;y++)g.push(!1);for(let y=0;y<this.size;y++)this.modules.push(g.slice()),this.isFunction.push(g.slice());this.drawFunctionPatterns();const p=this.addEccAndInterleave(h);if(this.drawCodewords(p),m==-1){let y=1e9;for(let S=0;S<8;S++){this.applyMask(S),this.drawFormatBits(S);const E=this.getPenaltyScore();E<y&&(m=S,y=E),this.applyMask(S)}}s(0<=m&&m<=7),this.mask=m,this.applyMask(m),this.drawFormatBits(m),this.isFunction=[]}static encodeText(u,f){const h=e.QrSegment.makeSegments(u);return It.encodeSegments(h,f)}static encodeBinary(u,f){const h=e.QrSegment.makeBytes(u);return It.encodeSegments([h],f)}static encodeSegments(u,f,h=1,m=40,g=-1,p=!0){if(!(It.MIN_VERSION<=h&&h<=m&&m<=It.MAX_VERSION)||g<-1||g>7)throw new RangeError("Invalid value");let y,S;for(y=h;;y++){const N=It.getNumDataCodewords(y,f)*8,O=c.getTotalBits(u,y);if(O<=N){S=O;break}if(y>=m)throw new RangeError("Data too long")}for(const N of[It.Ecc.MEDIUM,It.Ecc.QUARTILE,It.Ecc.HIGH])p&&S<=It.getNumDataCodewords(y,N)*8&&(f=N);let E=[];for(const N of u){r(N.mode.modeBits,4,E),r(N.numChars,N.mode.numCharCountBits(y),E);for(const O of N.getData())E.push(O)}s(E.length==S);const T=It.getNumDataCodewords(y,f)*8;s(E.length<=T),r(0,Math.min(4,T-E.length),E),r(0,(8-E.length%8)%8,E),s(E.length%8==0);for(let N=236;E.length<T;N^=253)r(N,8,E);let j=[];for(;j.length*8<E.length;)j.push(0);return E.forEach((N,O)=>j[O>>>3]|=N<<7-(O&7)),new It(y,f,j,g)}getModule(u,f){return 0<=u&&u<this.size&&0<=f&&f<this.size&&this.modules[f][u]}getModules(){return this.modules}drawFunctionPatterns(){for(let h=0;h<this.size;h++)this.setFunctionModule(6,h,h%2==0),this.setFunctionModule(h,6,h%2==0);this.drawFinderPattern(3,3),this.drawFinderPattern(this.size-4,3),this.drawFinderPattern(3,this.size-4);const u=this.getAlignmentPatternPositions(),f=u.length;for(let h=0;h<f;h++)for(let m=0;m<f;m++)h==0&&m==0||h==0&&m==f-1||h==f-1&&m==0||this.drawAlignmentPattern(u[h],u[m]);this.drawFormatBits(0),this.drawVersion()}drawFormatBits(u){const f=this.errorCorrectionLevel.formatBits<<3|u;let h=f;for(let g=0;g<10;g++)h=h<<1^(h>>>9)*1335;const m=(f<<10|h)^21522;s(m>>>15==0);for(let g=0;g<=5;g++)this.setFunctionModule(8,g,n(m,g));this.setFunctionModule(8,7,n(m,6)),this.setFunctionModule(8,8,n(m,7)),this.setFunctionModule(7,8,n(m,8));for(let g=9;g<15;g++)this.setFunctionModule(14-g,8,n(m,g));for(let g=0;g<8;g++)this.setFunctionModule(this.size-1-g,8,n(m,g));for(let g=8;g<15;g++)this.setFunctionModule(8,this.size-15+g,n(m,g));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let u=this.version;for(let h=0;h<12;h++)u=u<<1^(u>>>11)*7973;const f=this.version<<12|u;s(f>>>18==0);for(let h=0;h<18;h++){const m=n(f,h),g=this.size-11+h%3,p=Math.floor(h/3);this.setFunctionModule(g,p,m),this.setFunctionModule(p,g,m)}}drawFinderPattern(u,f){for(let h=-4;h<=4;h++)for(let m=-4;m<=4;m++){const g=Math.max(Math.abs(m),Math.abs(h)),p=u+m,y=f+h;0<=p&&p<this.size&&0<=y&&y<this.size&&this.setFunctionModule(p,y,g!=2&&g!=4)}}drawAlignmentPattern(u,f){for(let h=-2;h<=2;h++)for(let m=-2;m<=2;m++)this.setFunctionModule(u+m,f+h,Math.max(Math.abs(m),Math.abs(h))!=1)}setFunctionModule(u,f,h){this.modules[f][u]=h,this.isFunction[f][u]=!0}addEccAndInterleave(u){const f=this.version,h=this.errorCorrectionLevel;if(u.length!=It.getNumDataCodewords(f,h))throw new RangeError("Invalid argument");const m=It.NUM_ERROR_CORRECTION_BLOCKS[h.ordinal][f],g=It.ECC_CODEWORDS_PER_BLOCK[h.ordinal][f],p=Math.floor(It.getNumRawDataModules(f)/8),y=m-p%m,S=Math.floor(p/m);let E=[];const T=It.reedSolomonComputeDivisor(g);for(let N=0,O=0;N<m;N++){let U=u.slice(O,O+S-g+(N<y?0:1));O+=U.length;const z=It.reedSolomonComputeRemainder(U,T);N<y&&U.push(0),E.push(U.concat(z))}let j=[];for(let N=0;N<E[0].length;N++)E.forEach((O,U)=>{(N!=S-g||U>=y)&&j.push(O[N])});return s(j.length==p),j}drawCodewords(u){if(u.length!=Math.floor(It.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let f=0;for(let h=this.size-1;h>=1;h-=2){h==6&&(h=5);for(let m=0;m<this.size;m++)for(let g=0;g<2;g++){const p=h-g,y=(h+1&2)==0?this.size-1-m:m;!this.isFunction[y][p]&&f<u.length*8&&(this.modules[y][p]=n(u[f>>>3],7-(f&7)),f++)}}s(f==u.length*8)}applyMask(u){if(u<0||u>7)throw new RangeError("Mask value out of range");for(let f=0;f<this.size;f++)for(let h=0;h<this.size;h++){let m;switch(u){case 0:m=(h+f)%2==0;break;case 1:m=f%2==0;break;case 2:m=h%3==0;break;case 3:m=(h+f)%3==0;break;case 4:m=(Math.floor(h/3)+Math.floor(f/2))%2==0;break;case 5:m=h*f%2+h*f%3==0;break;case 6:m=(h*f%2+h*f%3)%2==0;break;case 7:m=((h+f)%2+h*f%3)%2==0;break;default:throw new Error("Unreachable")}!this.isFunction[f][h]&&m&&(this.modules[f][h]=!this.modules[f][h])}}getPenaltyScore(){let u=0;for(let g=0;g<this.size;g++){let p=!1,y=0,S=[0,0,0,0,0,0,0];for(let E=0;E<this.size;E++)this.modules[g][E]==p?(y++,y==5?u+=It.PENALTY_N1:y>5&&u++):(this.finderPenaltyAddHistory(y,S),p||(u+=this.finderPenaltyCountPatterns(S)*It.PENALTY_N3),p=this.modules[g][E],y=1);u+=this.finderPenaltyTerminateAndCount(p,y,S)*It.PENALTY_N3}for(let g=0;g<this.size;g++){let p=!1,y=0,S=[0,0,0,0,0,0,0];for(let E=0;E<this.size;E++)this.modules[E][g]==p?(y++,y==5?u+=It.PENALTY_N1:y>5&&u++):(this.finderPenaltyAddHistory(y,S),p||(u+=this.finderPenaltyCountPatterns(S)*It.PENALTY_N3),p=this.modules[E][g],y=1);u+=this.finderPenaltyTerminateAndCount(p,y,S)*It.PENALTY_N3}for(let g=0;g<this.size-1;g++)for(let p=0;p<this.size-1;p++){const y=this.modules[g][p];y==this.modules[g][p+1]&&y==this.modules[g+1][p]&&y==this.modules[g+1][p+1]&&(u+=It.PENALTY_N2)}let f=0;for(const g of this.modules)f=g.reduce((p,y)=>p+(y?1:0),f);const h=this.size*this.size,m=Math.ceil(Math.abs(f*20-h*10)/h)-1;return s(0<=m&&m<=9),u+=m*It.PENALTY_N4,s(0<=u&&u<=2568888),u}getAlignmentPatternPositions(){if(this.version==1)return[];{const u=Math.floor(this.version/7)+2,f=this.version==32?26:Math.ceil((this.version*4+4)/(u*2-2))*2;let h=[6];for(let m=this.size-7;h.length<u;m-=f)h.splice(1,0,m);return h}}static getNumRawDataModules(u){if(u<It.MIN_VERSION||u>It.MAX_VERSION)throw new RangeError("Version number out of range");let f=(16*u+128)*u+64;if(u>=2){const h=Math.floor(u/7)+2;f-=(25*h-10)*h-55,u>=7&&(f-=36)}return s(208<=f&&f<=29648),f}static getNumDataCodewords(u,f){return Math.floor(It.getNumRawDataModules(u)/8)-It.ECC_CODEWORDS_PER_BLOCK[f.ordinal][u]*It.NUM_ERROR_CORRECTION_BLOCKS[f.ordinal][u]}static reedSolomonComputeDivisor(u){if(u<1||u>255)throw new RangeError("Degree out of range");let f=[];for(let m=0;m<u-1;m++)f.push(0);f.push(1);let h=1;for(let m=0;m<u;m++){for(let g=0;g<f.length;g++)f[g]=It.reedSolomonMultiply(f[g],h),g+1<f.length&&(f[g]^=f[g+1]);h=It.reedSolomonMultiply(h,2)}return f}static reedSolomonComputeRemainder(u,f){let h=f.map(m=>0);for(const m of u){const g=m^h.shift();h.push(0),f.forEach((p,y)=>h[y]^=It.reedSolomonMultiply(p,g))}return h}static reedSolomonMultiply(u,f){if(u>>>8||f>>>8)throw new RangeError("Byte out of range");let h=0;for(let m=7;m>=0;m--)h=h<<1^(h>>>7)*285,h^=(f>>>m&1)*u;return s(h>>>8==0),h}finderPenaltyCountPatterns(u){const f=u[1];s(f<=this.size*3);const h=f>0&&u[2]==f&&u[3]==f*3&&u[4]==f&&u[5]==f;return(h&&u[0]>=f*4&&u[6]>=f?1:0)+(h&&u[6]>=f*4&&u[0]>=f?1:0)}finderPenaltyTerminateAndCount(u,f,h){return u&&(this.finderPenaltyAddHistory(f,h),f=0),f+=this.size,this.finderPenaltyAddHistory(f,h),this.finderPenaltyCountPatterns(h)}finderPenaltyAddHistory(u,f){f[0]==0&&(u+=this.size),f.pop(),f.unshift(u)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],e.QrCode=t;function r(d,u,f){if(u<0||u>31||d>>>u)throw new RangeError("Value out of range");for(let h=u-1;h>=0;h--)f.push(d>>>h&1)}function n(d,u){return(d>>>u&1)!=0}function s(d){if(!d)throw new Error("Assertion error")}const a=class ir{constructor(u,f,h){if(this.mode=u,this.numChars=f,this.bitData=h,f<0)throw new RangeError("Invalid argument");this.bitData=h.slice()}static makeBytes(u){let f=[];for(const h of u)r(h,8,f);return new ir(ir.Mode.BYTE,u.length,f)}static makeNumeric(u){if(!ir.isNumeric(u))throw new RangeError("String contains non-numeric characters");let f=[];for(let h=0;h<u.length;){const m=Math.min(u.length-h,3);r(parseInt(u.substring(h,h+m),10),m*3+1,f),h+=m}return new ir(ir.Mode.NUMERIC,u.length,f)}static makeAlphanumeric(u){if(!ir.isAlphanumeric(u))throw new RangeError("String contains unencodable characters in alphanumeric mode");let f=[],h;for(h=0;h+2<=u.length;h+=2){let m=ir.ALPHANUMERIC_CHARSET.indexOf(u.charAt(h))*45;m+=ir.ALPHANUMERIC_CHARSET.indexOf(u.charAt(h+1)),r(m,11,f)}return h<u.length&&r(ir.ALPHANUMERIC_CHARSET.indexOf(u.charAt(h)),6,f),new ir(ir.Mode.ALPHANUMERIC,u.length,f)}static makeSegments(u){return u==""?[]:ir.isNumeric(u)?[ir.makeNumeric(u)]:ir.isAlphanumeric(u)?[ir.makeAlphanumeric(u)]:[ir.makeBytes(ir.toUtf8ByteArray(u))]}static makeEci(u){let f=[];if(u<0)throw new RangeError("ECI assignment value out of range");if(u<128)r(u,8,f);else if(u<16384)r(2,2,f),r(u,14,f);else if(u<1e6)r(6,3,f),r(u,21,f);else throw new RangeError("ECI assignment value out of range");return new ir(ir.Mode.ECI,0,f)}static isNumeric(u){return ir.NUMERIC_REGEX.test(u)}static isAlphanumeric(u){return ir.ALPHANUMERIC_REGEX.test(u)}getData(){return this.bitData.slice()}static getTotalBits(u,f){let h=0;for(const m of u){const g=m.mode.numCharCountBits(f);if(m.numChars>=1<<g)return 1/0;h+=4+g+m.bitData.length}return h}static toUtf8ByteArray(u){u=encodeURI(u);let f=[];for(let h=0;h<u.length;h++)u.charAt(h)!="%"?f.push(u.charCodeAt(h)):(f.push(parseInt(u.substring(h+1,h+3),16)),h+=2);return f}};a.NUMERIC_REGEX=/^[0-9]*$/,a.ALPHANUMERIC_REGEX=/^[A-Z0-9 $%*+.\/:-]*$/,a.ALPHANUMERIC_CHARSET="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";let c=a;e.QrSegment=a})(Ri||(Ri={})),(e=>{(t=>{const r=class{constructor(s,a){this.ordinal=s,this.formatBits=a}};r.LOW=new r(0,1),r.MEDIUM=new r(1,0),r.QUARTILE=new r(2,3),r.HIGH=new r(3,2),t.Ecc=r})(e.QrCode||(e.QrCode={}))})(Ri||(Ri={})),(e=>{(t=>{const r=class{constructor(s,a){this.modeBits=s,this.numBitsCharCount=a}numCharCountBits(s){return this.numBitsCharCount[Math.floor((s+7)/17)]}};r.NUMERIC=new r(1,[10,12,14]),r.ALPHANUMERIC=new r(2,[9,11,13]),r.BYTE=new r(4,[8,16,16]),r.KANJI=new r(8,[8,10,12]),r.ECI=new r(7,[0,0,0]),t.Mode=r})(e.QrSegment||(e.QrSegment={}))})(Ri||(Ri={}));var ys=Ri;/**
145
+ * @license qrcode.react
146
+ * Copyright (c) Paul O'Shannessy
147
+ * SPDX-License-Identifier: ISC
148
+ */var ez={L:ys.QrCode.Ecc.LOW,M:ys.QrCode.Ecc.MEDIUM,Q:ys.QrCode.Ecc.QUARTILE,H:ys.QrCode.Ecc.HIGH},jx=128,Nx="L",Dx="#FFFFFF",Mx="#000000",$x=!1,Rx=1,tz=4,rz=0,nz=.1;function Lx(e,t=0){const r=[];return e.forEach(function(n,s){let a=null;n.forEach(function(c,d){if(!c&&a!==null){r.push(`M${a+t} ${s+t}h${d-a}v1H${a+t}z`),a=null;return}if(d===n.length-1){if(!c)return;a===null?r.push(`M${d+t},${s+t} h1v1H${d+t}z`):r.push(`M${a+t},${s+t} h${d+1-a}v1H${a+t}z`);return}c&&a===null&&(a=d)})}),r.join("")}function Ox(e,t){return e.slice().map((r,n)=>n<t.y||n>=t.y+t.h?r:r.map((s,a)=>a<t.x||a>=t.x+t.w?s:!1))}function iz(e,t,r,n){if(n==null)return null;const s=e.length+r*2,a=Math.floor(t*nz),c=s/t,d=(n.width||a)*c,u=(n.height||a)*c,f=n.x==null?e.length/2-d/2:n.x*c,h=n.y==null?e.length/2-u/2:n.y*c,m=n.opacity==null?1:n.opacity;let g=null;if(n.excavate){let y=Math.floor(f),S=Math.floor(h);g={x:y,y:S,w:Math.ceil(d+f-y),h:Math.ceil(u+h-S)}}const p=n.crossOrigin;return{x:f,y:h,h:u,w:d,excavation:g,opacity:m,crossOrigin:p}}function sz(e,t){return t!=null?Math.max(Math.floor(t),0):e?tz:rz}function Fx({value:e,level:t,minVersion:r,includeMargin:n,marginSize:s,imageSettings:a,size:c,boostLevel:d}){let u=w.default.useMemo(()=>{const p=(Array.isArray(e)?e:[e]).reduce((y,S)=>(y.push(...ys.QrSegment.makeSegments(S)),y),[]);return ys.QrCode.encodeSegments(p,ez[t],r,void 0,void 0,d)},[e,t,r,d]);const{cells:f,margin:h,numCells:m,calculatedImageSettings:g}=w.default.useMemo(()=>{let p=u.getModules();const y=sz(n,s);return{cells:p,margin:y,numCells:p.length+y*2,calculatedImageSettings:iz(p,c,y,a)}},[u,c,a,n,s]);return{qrcode:u,margin:h,cells:f,numCells:m,calculatedImageSettings:g}}var az=(function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0})(),oz=w.default.forwardRef(function(t,r){const n=t,{value:s,size:a=jx,level:c=Nx,bgColor:d=Dx,fgColor:u=Mx,includeMargin:f=$x,minVersion:h=Rx,boostLevel:m,marginSize:g,imageSettings:p}=n,y=Zh(n,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:S}=y,E=Zh(y,["style"]),T=p?.src,j=w.default.useRef(null),N=w.default.useRef(null),O=w.default.useCallback(oe=>{j.current=oe,typeof r=="function"?r(oe):r&&(r.current=oe)},[r]),[U,z]=w.default.useState(!1),{margin:K,cells:G,numCells:X,calculatedImageSettings:te}=Fx({value:s,level:c,minVersion:h,boostLevel:m,includeMargin:f,marginSize:g,imageSettings:p,size:a});w.default.useEffect(()=>{if(j.current!=null){const oe=j.current,pe=oe.getContext("2d");if(!pe)return;let le=G;const se=N.current,Ce=te!=null&&se!==null&&se.complete&&se.naturalHeight!==0&&se.naturalWidth!==0;Ce&&te.excavation!=null&&(le=Ox(G,te.excavation));const q=window.devicePixelRatio||1;oe.height=oe.width=a*q;const Q=a/X*q;pe.scale(Q,Q),pe.fillStyle=d,pe.fillRect(0,0,X,X),pe.fillStyle=u,az?pe.fill(new Path2D(Lx(le,K))):G.forEach(function(ie,be){ie.forEach(function(we,Re){we&&pe.fillRect(Re+K,be+K,1,1)})}),te&&(pe.globalAlpha=te.opacity),Ce&&pe.drawImage(se,te.x+K,te.y+K,te.w,te.h)}}),w.default.useEffect(()=>{z(!1)},[T]);const ne=Gh({height:a,width:a},S);let ae=null;return T!=null&&(ae=w.default.createElement("img",{src:T,key:T,style:{display:"none"},onLoad:()=>{z(!0)},ref:N,crossOrigin:te?.crossOrigin})),w.default.createElement(w.default.Fragment,null,w.default.createElement("canvas",Gh({style:ne,height:a,width:a,ref:O,role:"img"},E)),ae)});oz.displayName="QRCodeCanvas";var Ux=w.default.forwardRef(function(t,r){const n=t,{value:s,size:a=jx,level:c=Nx,bgColor:d=Dx,fgColor:u=Mx,includeMargin:f=$x,minVersion:h=Rx,boostLevel:m,title:g,marginSize:p,imageSettings:y}=n,S=Zh(n,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:E,cells:T,numCells:j,calculatedImageSettings:N}=Fx({value:s,level:c,minVersion:h,boostLevel:m,includeMargin:f,marginSize:p,imageSettings:y,size:a});let O=T,U=null;y!=null&&N!=null&&(N.excavation!=null&&(O=Ox(T,N.excavation)),U=w.default.createElement("image",{href:y.src,height:N.h,width:N.w,x:N.x+E,y:N.y+E,preserveAspectRatio:"none",opacity:N.opacity,crossOrigin:N.crossOrigin}));const z=Lx(O,E);return w.default.createElement("svg",Gh({height:a,width:a,viewBox:`0 0 ${j} ${j}`,ref:r,role:"img"},S),!!g&&w.default.createElement("title",null,g),w.default.createElement("path",{fill:d,d:`M0,0 h${j}v${j}H0z`,shapeRendering:"crispEdges"}),w.default.createElement("path",{fill:u,d:z,shapeRendering:"crispEdges"}),U)});Ux.displayName="QRCodeSVG";var lz=192;function Vh({value:e,size:t=lz,className:r,alt:n}){const s=e.trim();return s.length===0?null:(0,i.jsx)("div",{className:A("inline-flex rounded-md bg-white p-2",r),children:(0,i.jsx)(Ux,{value:s,size:t,marginSize:1,title:n??"QR code"})})}var cz="w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none disabled:opacity-50 disabled:cursor-not-allowed";function Bx({value:e,onChange:t,disabled:r}){const n=[];for(const s of W.TIMEZONES)n.includes(s.region)||n.push(s.region);return(0,i.jsxs)("select",{className:cz,value:e,disabled:r,onChange:s=>t(s.target.value),children:[!(0,W.findTimezone)(e)&&(0,i.jsx)("option",{value:"",children:"— Select timezone —"}),n.map(s=>(0,i.jsx)("optgroup",{label:s,children:W.TIMEZONES.filter(a=>a.region===s).map(a=>(0,i.jsx)("option",{value:a.id,children:a.label},a.id))},s))]})}var ci="w-full rounded-md border border-border bg-background px-2.5 py-1.5 text-xs text-foreground focus:border-primary focus:ring-1 focus:ring-primary/30 outline-none disabled:opacity-50 disabled:cursor-not-allowed",nc="block text-[11px] font-medium text-foreground mb-1 break-words",uz="text-[10px] text-foreground-subtle mt-0.5 break-words";function qt({label:e,description:t,required:r,span:n,children:s,translationFn:a}){const c=n===2?"col-span-1 @[480px]:col-span-2":n===3?"col-span-1 @[480px]:col-span-2 @[880px]:col-span-3":n===4?"col-span-1 @[480px]:col-span-2 @[1140px]:col-span-4":"col-span-1",d=gn(e,a),u=gn(t,a),f=d!==void 0&&d!=="";return(0,i.jsxs)("div",{className:`${c} min-w-0`,children:[f&&(0,i.jsxs)("label",{className:nc,children:[d,r&&(0,i.jsx)("span",{className:"text-danger ml-0.5",children:"*"})]}),s,u&&(0,i.jsx)("p",{className:uz,children:u})]})}function dz({field:e,value:t,onChange:r,disabled:n,translationFn:s}){return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsx)("input",{type:e.inputType??"text",className:ci,value:t==null?"":String(t),placeholder:e.placeholder,maxLength:e.maxLength,pattern:e.pattern,disabled:n||e.disabled,onChange:a=>r(a.target.value)})})}function fz({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const[a,c]=(0,l.useState)(t==null?"":String(t)),d=(0,l.useRef)(!1);(0,l.useEffect)(()=>{d.current||c(t==null?"":String(t))},[t]);const u=f=>{if(c(f),f===""||f==="-"){r(void 0);return}const h=Number(f);Number.isNaN(h)||r(h)};return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsxs)("div",{className:"flex items-center gap-1",children:[(0,i.jsx)("input",{type:"number",className:ci,value:a,placeholder:e.placeholder,min:e.min,max:e.max,step:e.step,disabled:n||e.disabled,onFocus:()=>{d.current=!0},onBlur:()=>{d.current=!1},onChange:f=>u(f.target.value)}),e.unit&&(0,i.jsx)("span",{className:"text-xs text-foreground-subtle whitespace-nowrap",children:e.unit})]})})}function hz({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const a=!!t,c=n||e.disabled;return e.style==="checkbox"?(0,i.jsx)(qt,{label:void 0,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsxs)("label",{className:"flex items-center gap-2 cursor-pointer select-none",children:[(0,i.jsx)("input",{type:"checkbox",className:"h-3.5 w-3.5 rounded border-border accent-primary",checked:a,disabled:c,onChange:d=>r(d.target.checked)}),(0,i.jsx)("span",{className:"text-xs font-medium text-foreground",children:gn(e.label,s)}),e.required&&(0,i.jsx)("span",{className:"text-danger",children:"*"})]})}):(0,i.jsx)(qt,{label:void 0,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsxs)("div",{className:"flex items-center justify-between",children:[(0,i.jsxs)("span",{className:nc+" mb-0",children:[gn(e.label,s),e.required&&(0,i.jsx)("span",{className:"text-danger ml-0.5",children:"*"})]}),(0,i.jsx)("button",{type:"button",role:"switch","aria-checked":a,disabled:c,onClick:()=>!c&&r(!a),className:["relative inline-flex h-4 w-8 shrink-0 items-center rounded-full transition-colors duration-150",a?"bg-primary":"bg-foreground-subtle/30",c?"opacity-50 cursor-not-allowed":"cursor-pointer"].join(" "),children:(0,i.jsx)("span",{className:["inline-block h-3 w-3 rounded-full bg-white shadow transition-transform duration-150",a?"translate-x-4":"translate-x-0.5"].join(" ")})})]})})}function mz({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const a=e.options.some(c=>c.value==="");return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsxs)("select",{className:ci,value:t==null?"":String(t),disabled:n||e.disabled,onChange:c=>r(c.target.value),children:[!e.required&&!a&&(0,i.jsx)("option",{value:"",children:"— Select —"}),e.options.map(c=>(0,i.jsx)("option",{value:c.value,children:c.label},c.value))]})})}function gz({field:e,value:t,onChange:r,disabled:n,translationFn:s}){return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsx)(Bx,{value:typeof t=="string"?t:"",onChange:r,disabled:n||e.disabled})})}function pz({field:e,value:t,onChange:r,disabled:n,translationFn:s}){return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsx)("input",{type:"datetime-local",className:ci,value:typeof t=="string"?t:"",placeholder:e.placeholder,disabled:n||e.disabled,onChange:a=>r(a.target.value)})})}function vz({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const a=Array.isArray(t)?t:[],c=d=>{if(a.includes(d))r(a.filter(u=>u!==d));else{if(e.maxItems!==void 0&&a.length>=e.maxItems)return;r([...a,d])}};return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsx)("div",{className:"flex flex-wrap gap-2",children:e.options.map(d=>{const u=a.includes(d.value);return(0,i.jsxs)("label",{className:["flex items-center gap-1.5 rounded-md border px-2 py-1 text-xs cursor-pointer select-none transition-colors",u?"border-primary bg-primary/10 text-primary":"border-border bg-background text-foreground hover:bg-surface",n||e.disabled?"opacity-50 cursor-not-allowed":""].join(" "),children:[(0,i.jsx)("input",{type:"checkbox",className:"sr-only",checked:u,disabled:n||e.disabled,onChange:()=>c(d.value)}),d.label]},d.value)})})})}function bz({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const[a,c]=(0,l.useState)(!1),d=e.showToggle!==!1;return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsxs)("div",{className:"relative",children:[(0,i.jsx)("input",{type:a?"text":"password",className:ci+(d?" pr-9":""),value:t==null?"":String(t),placeholder:e.placeholder,disabled:n||e.disabled,onChange:u=>r(u.target.value)}),d&&(0,i.jsx)("button",{type:"button",className:"absolute right-2 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground",tabIndex:-1,onClick:()=>c(u=>!u),children:a?(0,i.jsx)(vl,{className:"h-3.5 w-3.5"}):(0,i.jsx)(Ja,{className:"h-3.5 w-3.5"})})]})})}function yz({field:e,value:t,onChange:r,disabled:n,translationFn:s}){return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsx)("textarea",{className:ci+" resize-y min-h-[60px]",value:t==null?"":String(t),placeholder:e.placeholder,rows:e.rows??3,maxLength:e.maxLength,disabled:n||e.disabled,onChange:a=>r(a.target.value)})})}function xz({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const a=t==null,c=e.nullable===!0,d=a?e.default??e.min:Number(t),u=e.showValue!==!1,f=e.nullLabel??"Auto",h=n||e.disabled,m=e.displayScale??1,g=e.min/m,p=e.max/m,y=d/m,S=(e.step??1)/m;if(c&&a)return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsxs)("button",{className:"w-full rounded-lg border border-dashed border-border px-3 py-2 text-xs text-foreground-subtle hover:border-primary/40 hover:text-primary transition-colors text-left",disabled:h,onClick:()=>r(e.default??e.min),children:[f," — click to set manually"]})});const E=e.showStepper===!0&&u,T=N=>{const O=d+N*(e.step??1),U=Math.min(e.max,Math.max(e.min,O));U!==d&&r(U)},j="flex h-6 w-6 shrink-0 items-center justify-center rounded border border-border bg-surface text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:cursor-not-allowed disabled:opacity-40";return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsxs)("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-2",children:[(0,i.jsxs)("div",{className:"flex min-w-0 flex-1 basis-[160px] items-center gap-2",children:[(0,i.jsx)("span",{className:"text-[10px] text-foreground-subtle tabular-nums shrink-0",children:g}),(0,i.jsx)("input",{type:"range",className:"min-w-0 flex-1 h-1 accent-primary cursor-pointer disabled:opacity-50",min:g,max:p,step:S,value:y,disabled:h,onChange:N=>r(Number(N.target.value)*m)}),(0,i.jsx)("span",{className:"text-[10px] text-foreground-subtle tabular-nums shrink-0",children:p})]}),(u||c||e.unit)&&(0,i.jsxs)("div",{className:"flex shrink-0 items-center gap-2",children:[E&&(0,i.jsx)("button",{type:"button",className:j,disabled:h||d<=e.min,onClick:()=>T(-1),title:`Decrease by ${e.step??1}`,"aria-label":"Decrement",children:(0,i.jsx)(Lp,{className:"h-3 w-3"})}),u&&(0,i.jsx)("input",{type:"number",className:"w-16 rounded border border-border bg-surface px-1.5 py-0.5 text-xs text-center text-foreground tabular-nums focus:outline-none focus:ring-1 focus:ring-primary",min:g,max:p,step:S,value:y,disabled:h,onChange:N=>{if(N.target.value===""){r(c?null:e.min);return}const O=Number(N.target.value)*m,U=e.step??1,z=O-e.min,K=e.min+Math.round(z/U)*U;r(Math.min(e.max,Math.max(e.min,K)))}}),E&&(0,i.jsx)("button",{type:"button",className:j,disabled:h||d>=e.max,onClick:()=>T(1),title:`Increase by ${e.step??1}`,"aria-label":"Increment",children:(0,i.jsx)(Ci,{className:"h-3 w-3"})}),e.unit&&(0,i.jsx)("span",{className:"text-[10px] text-foreground-subtle",children:e.unit}),c&&(0,i.jsx)("button",{className:"text-[10px] text-foreground-subtle hover:text-primary transition-colors",title:`Reset to ${f}`,disabled:h,onClick:()=>r(null),children:f})]})]})})}function Sz({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const a=Array.isArray(t)?t:[],[c,d]=(0,l.useState)(""),u=(0,l.useRef)(null),f=(0,l.useCallback)(p=>{const y=p.trim();!y||a.includes(y)||e.maxTags!==void 0&&a.length>=e.maxTags||(r([...a,y]),d(""))},[a,e.maxTags,r]),h=p=>r(a.filter(y=>y!==p)),m=p=>{p.key==="Enter"||p.key===","?(p.preventDefault(),f(c)):p.key==="Backspace"&&c===""&&a.length>0&&h(a[a.length-1])},g=n||e.disabled;return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsxs)("div",{className:["flex flex-wrap gap-1.5 rounded-md border border-border bg-background px-2 py-1.5 min-h-[38px] cursor-text","focus-within:border-primary focus-within:ring-1 focus-within:ring-primary/30",g?"opacity-50 cursor-not-allowed":""].join(" "),onClick:()=>!g&&u.current?.focus(),children:[a.map(p=>(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 rounded-md bg-primary/10 px-1.5 py-0.5 text-xs text-primary",children:[p,!g&&(0,i.jsx)("button",{type:"button",onClick:()=>h(p),className:"hover:text-danger",children:(0,i.jsx)(mr,{className:"h-2.5 w-2.5"})})]},p)),(0,i.jsx)("input",{ref:u,type:"text",className:"flex-1 min-w-[80px] bg-transparent text-sm text-foreground outline-none placeholder:text-foreground-disabled",value:c,placeholder:a.length===0?e.placeholder??"Add tags…":"",disabled:g,list:`tags-suggestions-${e.key}`,onChange:p=>d(p.target.value),onKeyDown:m,onBlur:()=>{c.trim()&&f(c)}}),e.suggestions&&(0,i.jsx)("datalist",{id:`tags-suggestions-${e.key}`,children:e.suggestions.map(p=>(0,i.jsx)("option",{value:p},p))})]})})}function zx({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const{nodes:a}=Pl(),c=typeof t=="string"?t:"",d=e.showOffline?a:a.filter(u=>u.isOnline);return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsxs)("select",{className:"w-full px-3 py-2 text-sm bg-background border border-border rounded-lg text-foreground focus:outline-none focus:border-primary/50 disabled:opacity-50",value:c,onChange:u=>r(u.target.value),disabled:n,children:[(0,i.jsx)("option",{value:"",children:"Select node…"}),d.map(u=>(0,i.jsxs)("option",{value:u.id,disabled:!u.isOnline,children:[u.shortName,u.isOnline?"":" (offline)"]},u.id))]})})}function Gx({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const{nodes:a}=Pl(),c=new Set(Array.isArray(t)?t.map(String):[]),d=e.showOffline?a:a.filter(f=>f.isOnline),u=f=>{const h=new Set(c);h.has(f)?h.delete(f):h.add(f),r([...h])};return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:(0,i.jsx)("div",{className:"flex flex-wrap gap-1.5",children:d.map(f=>{const h=c.has(f.id);return(0,i.jsx)("button",{type:"button",onClick:()=>u(f.id),disabled:n||!f.isOnline,className:`px-2.5 py-1 text-xs font-medium rounded-md border transition-colors ${h?"border-primary bg-primary/10 text-primary":"border-border bg-surface text-foreground-subtle hover:bg-surface-hover"} ${f.isOnline?"":"opacity-50 cursor-not-allowed"}`,children:f.shortName},f.id)})})})}function _z({field:e,value:t,onChange:r,disabled:n,translationFn:s}){const a=t==null?"#000000":String(t);return(0,i.jsxs)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:[(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsx)("input",{type:"color",className:"h-9 w-9 rounded-md border border-border bg-background cursor-pointer p-0.5 disabled:opacity-50",value:a,disabled:n||e.disabled,onChange:c=>r(c.target.value)}),(0,i.jsx)("input",{type:"text",className:ci+" flex-1 font-mono",value:a,placeholder:"#000000",disabled:n||e.disabled,onChange:c=>r(c.target.value)})]}),e.presets&&e.presets.length>0&&(0,i.jsx)("div",{className:"flex gap-1.5 mt-1.5",children:e.presets.map(c=>(0,i.jsx)("button",{type:"button",className:"h-5 w-5 rounded-md border border-border hover:scale-110 transition-transform disabled:opacity-50",style:{backgroundColor:c},disabled:n||e.disabled,title:c,onClick:()=>r(c)},c))})]})}function wz({field:e,value:t,onChange:r,disabled:n,translationFn:s,onTestField:a,onAction:c,externalProbe:d}){const[u,f]=(0,l.useState)("idle"),[h,m]=(0,l.useState)(null),g=d?.status??u,p=d?.result??h,y=!!a||!!c,S=(0,l.useCallback)(async()=>{if(y){f("probing"),m(null);try{const j=a?await a(e.key,t):await c("test-probe",e.key,t),N=j&&typeof j=="object"?j:{status:"error",error:"Probe handler returned no result"};m(N),f(N.status==="ok"?"ok":"error")}catch(j){m({status:"error",error:j instanceof Error?j.message:String(j)}),f("error")}}},[a,c,e.key,t,y]),E=g==="probing"?"border-primary/40 bg-primary/10 text-primary":g==="ok"?"border-success/40 bg-success/10 text-success hover:bg-success/15":g==="error"?"border-danger/40 bg-danger/10 text-danger hover:bg-danger/15":"border-border text-foreground-subtle hover:text-foreground hover:bg-surface-hover",T=g==="probing"?(0,i.jsx)(hr,{className:"h-3 w-3 animate-spin"}):g==="ok"?(0,i.jsx)(jT,{className:"h-3 w-3"}):g==="error"?(0,i.jsx)(as,{className:"h-3 w-3"}):(0,i.jsx)(rf,{className:"h-3 w-3"});return(0,i.jsxs)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,translationFn:s,children:[(0,i.jsxs)("div",{className:"@container flex items-center gap-2",style:{containerType:"inline-size"},children:[(0,i.jsxs)("button",{type:"button",onClick:S,title:"Test",disabled:e.disabled||g==="probing"||!y||!t,className:`flex-shrink-0 inline-flex items-center gap-1.5 rounded-md border px-2 py-2 text-xs font-medium transition-colors disabled:opacity-50 disabled:cursor-not-allowed @[280px]:px-3 ${E}`,children:[T,(0,i.jsx)("span",{className:"hidden @[280px]:inline",children:"Test"})]}),(0,i.jsx)("input",{type:e.inputType??"url",className:ci+" flex-1 min-w-0",value:t==null?"":String(t),placeholder:e.placeholder,disabled:n||e.disabled,onChange:j=>{r(j.target.value),u!=="idle"&&(f("idle"),m(null))}})]}),g==="ok"&&p?.labels&&p.labels.length>0&&(0,i.jsx)("div",{className:"flex flex-wrap gap-1 mt-1.5",children:p.labels.map((j,N)=>(0,i.jsx)("span",{className:"text-xs bg-success/10 text-success rounded px-2 py-0.5 font-mono",children:j},N))}),g==="error"&&p?.error&&(0,i.jsx)("p",{className:"text-xs text-danger mt-1 truncate",title:p.error,children:p.error})]})}function Ez({field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:a}){const[c,d]=(0,l.useState)(e.defaultCollapsed??!1),u=e.style==="accordion";return(0,i.jsx)("div",{className:`${e.span===2?"col-span-2":e.span===3?"col-span-3":e.span===4?"col-span-4":"col-span-1"} min-w-0`,children:(0,i.jsxs)("div",{className:"@container rounded-lg border border-border bg-surface/50 overflow-hidden",style:{containerType:"inline-size"},children:[(0,i.jsxs)("div",{className:["px-3 py-2 flex items-center justify-between min-w-0",u?"cursor-pointer hover:bg-surface":""].join(" "),onClick:u?()=>d(f=>!f):void 0,children:[(0,i.jsx)("span",{className:"text-xs font-semibold text-foreground min-w-0 break-words",children:gn(e.label,s)}),u&&(0,i.jsx)("span",{className:"text-foreground-subtle text-xs shrink-0 ml-2",children:c?"▸":"▾"})]}),!c&&(0,i.jsx)("div",{className:"px-3 pb-3 grid grid-cols-1 @[480px]:grid-cols-2 gap-x-4 gap-y-3",children:e.fields.map(f=>(0,i.jsx)(xs,{field:f,values:t,onChange:r,disabled:n,translationFn:s,onTestField:a},f.key))})]})})}function kz({field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:a,onAction:c}){const[d,u]=(0,l.useState)(e.tabs[0]?.id??""),f=e.span===2?"col-span-2":e.span===3?"col-span-3":e.span===4?"col-span-4":"col-span-1";return e.tabs.length===0?null:(0,i.jsxs)("div",{className:`${f} min-w-0`,children:[e.label&&(0,i.jsx)("div",{className:nc,children:gn(e.label,s)}),(0,i.jsxs)("div",{className:"@container rounded-lg border border-border-subtle bg-surface-hover/40 overflow-hidden",style:{containerType:"inline-size"},children:[(0,i.jsx)("div",{className:"flex flex-wrap gap-1 p-1.5 border-b border-border-subtle bg-surface/40",role:"tablist",children:e.tabs.map(h=>{const m=h.id===d;return(0,i.jsxs)("button",{type:"button",role:"tab","aria-selected":m,onClick:()=>u(h.id),className:`inline-flex items-center gap-1.5 whitespace-nowrap rounded-md px-2.5 py-1 text-[11px] transition-colors ${m?"bg-primary text-primary-foreground font-medium shadow-sm":"bg-transparent text-foreground-subtle hover:bg-surface hover:text-foreground"}`,children:[(0,i.jsx)("span",{children:gn(h.label,s)}),h.badge&&(0,i.jsx)("span",{className:`text-[9px] px-1 py-0.5 rounded-full font-medium ${m?"bg-primary-foreground/20 text-primary-foreground":"bg-primary/10 text-primary"}`,children:h.badge})]},h.id)})}),e.tabs.map(h=>h.id!==d?null:(0,i.jsx)("div",{role:"tabpanel",className:"px-3 pb-3 pt-2 grid grid-cols-1 @[480px]:grid-cols-2 gap-x-4 gap-y-3",children:h.fields.map((m,g)=>{const p="key"in m&&typeof m.key=="string"?m.key:`__${h.id}__${g}`;return(0,i.jsx)(xs,{field:m,values:t,onChange:r,disabled:n,translationFn:s,onTestField:a,onAction:c},p)})},h.id))]})]})}function Tz({span:e}){return(0,i.jsx)("div",{className:e===2?"col-span-2":e===3?"col-span-3":e===4?"col-span-4":"col-span-full",children:(0,i.jsx)("hr",{className:"border-border"})})}var Zx={info:{border:"border-info",bg:"bg-info/5",text:"text-info"},warning:{border:"border-warning",bg:"bg-warning/5",text:"text-warning"},success:{border:"border-success",bg:"bg-success/5",text:"text-success"},danger:{border:"border-danger",bg:"bg-danger/5",text:"text-danger"}};function Cz(e){if(typeof window>"u"||typeof DOMParser>"u")return"";const t=new Set(["A","UL","OL","LI","STRONG","EM","CODE","BR","P","SPAN"]),r=new DOMParser().parseFromString(`<div>${e}</div>`,"text/html"),n=r.body.firstElementChild;if(!n)return"";const s=a=>{const c=Array.from(a.children);for(const d of c){if(!t.has(d.tagName)){const f=r.createTextNode(d.textContent??"");d.replaceWith(f);continue}const u=d.tagName==="A"?new Set(["href"]):new Set;for(const f of Array.from(d.attributes))u.has(f.name)||d.removeAttribute(f.name);if(d.tagName==="A"){const f=d.getAttribute("href")??"";!/^https?:\/\//i.test(f)&&!f.startsWith("mailto:")?d.removeAttribute("href"):(d.setAttribute("target","_blank"),d.setAttribute("rel","noopener noreferrer"))}s(d)}};return s(n),n.innerHTML}function Iz({field:e}){const t=Zx[e.variant??"info"]??Zx.info,r=e.format==="html";return(0,i.jsx)("div",{className:"col-span-full",children:(0,i.jsxs)("div",{className:`rounded-md border-l-4 px-3 py-2.5 ${t.border} ${t.bg}`,children:[e.label&&(0,i.jsx)("p",{className:`text-xs font-semibold mb-0.5 ${t.text}`,children:e.label}),r?(0,i.jsx)("div",{className:"text-xs text-foreground-subtle leading-relaxed info-html-content",dangerouslySetInnerHTML:{__html:Cz(e.content)}}):(0,i.jsx)("p",{className:"text-xs text-foreground-subtle leading-relaxed whitespace-pre-line",children:e.content})]})})}function Pz({field:e}){const t=e.value;if(!t||t.length===0)return null;const r=e.size??192,n=e.alt??e.label;return(0,i.jsx)("div",{className:"col-span-full",children:(0,i.jsxs)("div",{className:"rounded-md border border-foreground-subtle/20 px-3 py-3 bg-background-subtle/40 flex flex-col items-start gap-2",children:[e.label&&(0,i.jsx)("p",{className:"text-xs font-semibold text-foreground",children:e.label}),e.caption&&(0,i.jsx)("p",{className:"text-xs text-foreground-subtle leading-relaxed",children:e.caption}),(0,i.jsx)(Vh,{value:t,size:r,alt:n})]})})}var Vx={ok:"bg-success",warn:"bg-amber-500",danger:"bg-danger",idle:"bg-foreground-subtle/40",unknown:"bg-foreground-subtle/40"};function Az(e){if(!Number.isFinite(e)||e<0)return"—";if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const r=Math.floor(t/60),n=t%60;return n===0?`${r}m`:`${r}m ${n}s`}function jz(e){return!Number.isFinite(e)||e<=0?"—":new Date(e).toLocaleTimeString()}function Nz({kind:e,value:t}){return t==null||t===""?(0,i.jsx)("span",{className:"text-foreground-subtle/60",children:"—"}):e==="monospace"?(0,i.jsx)("span",{className:"font-mono text-[11px]",children:String(t)}):e==="status"?(0,i.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,i.jsx)("span",{className:`inline-block h-1.5 w-1.5 rounded-full ${Vx[String(t).toLowerCase()]??Vx.unknown}`}),(0,i.jsx)("span",{children:String(t)})]}):e==="duration"&&typeof t=="number"?(0,i.jsx)("span",{className:"font-mono text-[11px]",children:Az(t)}):e==="timestamp"&&typeof t=="number"?(0,i.jsx)("span",{className:"font-mono text-[11px]",children:jz(t)}):(0,i.jsx)("span",{children:String(t)})}function Dz({field:e}){const t=e.value??[],r=e.description;return(0,i.jsxs)("div",{className:"col-span-full",children:[e.label&&(0,i.jsx)("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle mb-1",children:e.label}),r&&(0,i.jsx)("p",{className:"text-xs text-foreground-subtle mb-2",children:r}),t.length===0?(0,i.jsx)("div",{className:"rounded-md border border-border bg-surface-subtle px-3 py-2 text-xs text-foreground-subtle",children:e.emptyMessage??"No entries"}):(0,i.jsx)("div",{className:"rounded-md border border-border overflow-hidden",children:(0,i.jsxs)("table",{className:"w-full text-xs",children:[(0,i.jsx)("thead",{className:"bg-surface-subtle border-b border-border",children:(0,i.jsx)("tr",{children:e.columns.map(n=>(0,i.jsx)("th",{className:"px-3 py-1.5 text-left font-medium text-foreground-subtle",style:n.width?{width:n.width}:void 0,children:n.label},n.key))})}),(0,i.jsx)("tbody",{className:"divide-y divide-border",children:t.map((n,s)=>(0,i.jsx)("tr",{className:"hover:bg-surface-hover/40",children:e.columns.map(a=>(0,i.jsx)("td",{className:"px-3 py-1.5 align-top text-foreground",children:(0,i.jsx)(Nz,{kind:a.kind,value:n[a.key]})},a.key))},s))})]})})]})}function Mz({field:e,value:t,onChange:r,disabled:n,translationFn:s,onTestField:a,onAction:c}){const d=Array.isArray(t)?t:[],u=e.minRows??0,f=e.maxRows??Number.POSITIVE_INFINITY,h=(E,T,j)=>{const N=d.slice();N[E]={...N[E]??{},[T]:j},r(N)},m=E=>{d.length<=u||r(d.filter((T,j)=>j!==E))},g=()=>{if(d.length>=f)return;const E=e.defaultItem??{};r([...d,{...E}])},p=(E,T)=>e.rowTitleTemplate?e.rowTitleTemplate.replace(/\{(\w+)\}/g,(j,N)=>{const O=E[N];return O==null||O===""?"—":String(O)}):`Row ${T+1}`,y=d.length>u,S=d.length<f;return(0,i.jsxs)("div",{className:"col-span-full space-y-2",children:[(0,i.jsxs)("div",{className:"space-y-0.5",children:[e.label&&(0,i.jsx)("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle",children:gn(e.label,s)}),e.description&&(0,i.jsx)("p",{className:"text-[11px] text-foreground-subtle",children:gn(e.description,s)})]}),d.length===0?(0,i.jsx)("div",{className:"rounded-md border border-dashed border-border bg-background px-3 py-3 text-center text-[11px] text-foreground-subtle",children:e.emptyMessage??"No entries"}):(0,i.jsx)("div",{className:"space-y-2",children:d.map((E,T)=>(0,i.jsxs)("div",{className:"rounded-md border border-border bg-background",children:[(0,i.jsxs)("div",{className:"flex items-center justify-between border-b border-border px-3 py-1.5",children:[(0,i.jsx)("span",{className:"text-xs font-medium text-foreground",children:p(E,T)}),(0,i.jsxs)("button",{type:"button",onClick:()=>m(T),disabled:n||!y,className:"inline-flex items-center gap-1 rounded px-2 py-0.5 text-[10px] text-danger hover:bg-danger/10 disabled:opacity-30 disabled:cursor-not-allowed",title:y?"Remove this row":`At least ${u} row(s) required`,children:[(0,i.jsx)(Lp,{className:"h-3 w-3"}),"Remove"]})]}),(0,i.jsx)("div",{className:"grid grid-cols-1 @[480px]:grid-cols-2 gap-x-3 gap-y-2 p-3",children:e.itemFields.map(j=>(0,i.jsx)(xs,{field:j,values:E,onChange:(N,O)=>h(T,N,O),disabled:n,translationFn:s,onTestField:a,allFields:e.itemFields,onAction:c},j.key))})]},T))}),(0,i.jsxs)("div",{children:[(0,i.jsxs)("button",{type:"button",onClick:g,disabled:n||!S,className:"inline-flex items-center gap-1 rounded border border-border bg-surface px-3 py-1 text-[11px] font-medium text-foreground hover:border-primary/40 hover:bg-primary/5 disabled:opacity-30 disabled:cursor-not-allowed",children:[(0,i.jsx)(Ci,{className:"h-3 w-3"}),e.addLabel??"Add"]}),!S&&Number.isFinite(f)&&(0,i.jsxs)("span",{className:"ml-2 text-[10px] text-foreground-subtle",children:["(limit: ",f,")"]})]})]})}function $z({field:e,disabled:t,onAction:r}){const[n,s]=(0,l.useState)(!1),a=ji(),c=async()=>{if(!(e.confirmMessage&&!await a({title:e.label,message:e.confirmMessage,confirmLabel:e.buttonLabel,variant:e.variant==="danger"?"danger":"default"}))&&r){s(!0);try{await r(e.action,e.key)}finally{s(!1)}}},d={default:"border border-border text-foreground hover:bg-surface-hover",primary:"bg-primary text-primary-foreground hover:bg-primary/90",danger:"bg-danger text-white hover:bg-danger/90"};return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,children:(0,i.jsx)("button",{onClick:c,disabled:t||n,className:`inline-flex items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50 ${d[e.variant??"default"]??d.default}`,children:n?"Processing...":e.buttonLabel})})}function Hh(e,t){const r={...e.paramsStatic??{}};if(e.paramsFromForm)for(const[n,s]of Object.entries(e.paramsFromForm)){const a=t[s];a!=null&&a!==""&&(r[n]=a)}return r}function Rz({field:e,value:t,values:r,onChange:n,disabled:s,onAction:a}){const[c,d]=(0,l.useState)(!1),[u,f]=(0,l.useState)(null),[h,m]=(0,l.useState)(null),g=Hh(e,r),p=Object.keys(e.paramsFromForm??{}).some(T=>g[T]===void 0);(0,l.useEffect)(()=>{if(!a||p){m(null),f(null);return}let T=!1;return d(!0),f(null),a(e.action,e.key,g).then(j=>{if(T)return;const N=j;let O=[];if(Array.isArray(N))O=N;else if(N&&typeof N=="object")for(const U of Object.keys(N)){const z=N[U];if(Array.isArray(z)){O=z;break}}m(O)}).catch(j=>{T||(f(j instanceof Error?j.message:String(j)),m([]))}).finally(()=>{T||d(!1)}),()=>{T=!0}},[(e.refreshOn??Object.values(e.paramsFromForm??{})).map(T=>`${T}=${JSON.stringify(r[T])}`).join("|"),a,e.action,e.key]);const y=e.mapOption.value,S=e.mapOption.label,E=e.mapOption.description;return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,children:p?(0,i.jsx)("div",{className:"text-[11px] text-foreground-subtle italic",children:e.emptyParamsMessage??"Fill the prerequisite fields above first."}):c?(0,i.jsxs)("div",{className:"flex items-center gap-2 text-[11px] text-foreground-subtle",children:[(0,i.jsx)(hr,{className:"h-3 w-3 animate-spin"})," Loading options…"]}):u?(0,i.jsx)("div",{className:"text-[11px] text-danger",children:u}):h&&h.length===0?(0,i.jsx)("div",{className:"text-[11px] text-foreground-subtle italic",children:e.emptyResultsMessage??"No options returned."}):(()=>{const T=(h??[]).some(j=>{const N=j[y];return N===""||N===void 0});return(0,i.jsxs)("select",{className:"w-full rounded-md border border-border bg-surface px-2 py-1.5 text-xs text-foreground",value:typeof t=="string"?t:"",disabled:s,onChange:j=>n(j.target.value),children:[!T&&(0,i.jsx)("option",{value:"",children:"— Select —"}),(h??[]).map((j,N)=>{const O=j[y],U=j[S],z=E?j[E]:void 0,K=typeof O=="string"&&O!==""?O:`row-${N}`;return(0,i.jsxs)("option",{value:typeof O=="string"?O:String(O??""),children:[typeof U=="string"?U:String(U??K),z!==void 0?` (${String(z)})`:""]},K)})]})})()})}function Lz({field:e,values:t,disabled:r,onAction:n}){const[s,a]=(0,l.useState)(!1),[c,d]=(0,l.useState)(null),u=ji(),f=async()=>{if(e.confirmMessage&&!await u({title:e.label,message:e.confirmMessage,confirmLabel:e.buttonLabel,variant:e.variant==="danger"?"danger":"default"})||!n)return;const m=Hh(e,t);a(!0),d(null);try{const g=await n(e.action,e.key,m),p=typeof g=="object"&&g!==null?g:null;d({kind:"ok",text:e.successMessage?e.successMessage.replace(/\{(\w+)\}/g,(y,S)=>{const E=p?.[S];return E===void 0?"":String(E)}):"Done."})}catch(g){d({kind:"error",text:g instanceof Error?g.message:String(g)})}finally{a(!1)}},h={default:"border border-border text-foreground hover:bg-surface-hover",primary:"bg-primary text-primary-foreground hover:bg-primary/90",danger:"bg-danger text-white hover:bg-danger/90"};return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,children:(0,i.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,i.jsx)("button",{onClick:f,disabled:r||s,className:`inline-flex w-fit items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50 ${h[e.variant??"default"]??h.default}`,children:s?"Working…":e.buttonLabel}),c&&(0,i.jsx)("div",{className:`text-[11px] ${c.kind==="ok"?"text-emerald-700 dark:text-emerald-300":"text-danger"}`,children:c.text})]})})}function Oz({field:e,values:t,disabled:r,onAction:n}){const[s,a]=(0,l.useState)(!1),[c,d]=(0,l.useState)(null),u=ji(),f=async()=>{if(e.confirmMessage&&!await u({title:e.label,message:e.confirmMessage,confirmLabel:e.buttonLabel,variant:e.variant==="danger"?"danger":"default"})||!n)return;const m=Hh(e,t);a(!0),d(null);try{const g=await n("device-custom-action",e.action,m),p=typeof g=="object"&&g!==null?g:null;d({kind:"ok",text:e.successMessage?e.successMessage.replace(/\{(\w+)\}/g,(y,S)=>{const E=p?.[S];return E===void 0?"":String(E)}):"Done."})}catch(g){d({kind:"error",text:g instanceof Error?g.message:String(g)})}finally{a(!1)}},h={default:"border border-border text-foreground hover:bg-surface-hover",primary:"bg-primary text-primary-foreground hover:bg-primary/90",danger:"bg-danger text-white hover:bg-danger/90"};return(0,i.jsx)(qt,{label:e.label,description:e.description,required:e.required,span:e.span,children:(0,i.jsxs)("div",{className:"flex flex-col gap-1.5",children:[(0,i.jsx)("button",{onClick:f,disabled:r||s,className:`inline-flex w-fit items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-medium transition-colors disabled:opacity-50 ${h[e.variant??"default"]??h.default}`,children:s?"Working…":e.buttonLabel}),c&&(0,i.jsx)("div",{className:`text-[11px] ${c.kind==="ok"?"text-emerald-700 dark:text-emerald-300":"text-danger"}`,children:c.text})]})})}function Fz({field:e}){const t=nx();return(0,i.jsx)(qt,{label:void 0,description:void 0,span:e.span,children:(0,i.jsx)(Cx,{widgetId:e.widgetId,host:"device-tab",config:e.widgetConfig,deviceId:t??void 0,instanceId:e.key})})}function Uz(e,t){if(e==null)return"—";if(typeof e=="boolean")return e?"yes":"no";if(typeof e=="number"){const r=Number.isInteger(e)?String(e):e.toFixed(2);return t?`${r} ${t}`:r}return typeof e=="string"?e:JSON.stringify(e)}function Bz({field:e,values:t,onAction:r,translationFn:n}){const s="key"in e?e.key:void 0;if(!s)return null;const a=t[s],c=a!==void 0?a:"default"in e?e.default:void 0,d=Uz(c,"unit"in e?e.unit:void 0),u="label"in e?e.label:void 0,f="description"in e?e.description:void 0,h="span"in e?e.span:void 0,m="actions"in e?e.actions??[]:[];return(0,i.jsx)(qt,{label:u,description:f,span:h,translationFn:n,children:(0,i.jsxs)("div",{className:"flex items-stretch gap-1",children:[(0,i.jsx)("div",{className:"flex-1 rounded-md border border-border bg-surface-alt px-2.5 py-1.5 text-xs text-foreground font-mono break-all",children:d}),m.length>0&&(0,i.jsx)("div",{className:"flex items-center gap-1",children:m.map(g=>(0,i.jsx)(Gz,{action:g,fieldKey:s,value:c,onAction:r},g.action))})]})})}function zz({name:e}){const t="h-3.5 w-3.5";switch(e){case"copy":return(0,i.jsx)(ii,{className:t});case"refresh-cw":return(0,i.jsx)(Ii,{className:t});case"external-link":return(0,i.jsx)(Ip,{className:t});case"trash-2":return(0,i.jsx)(en,{className:t});case"download":return(0,i.jsx)(Xa,{className:t});case"upload":return(0,i.jsx)(Hp,{className:t});default:return(0,i.jsx)(BC,{className:t})}}function Gz({action:e,fieldKey:t,value:r,onAction:n}){const s=ji(),[a,c]=(0,l.useState)(!1),d=e.variant==="danger"?"text-danger hover:bg-danger/10 border-danger/30":e.variant==="primary"?"text-primary hover:bg-primary/10 border-primary/30":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover border-border",u=async()=>{if(!(e.confirmMessage&&!await s({title:e.tooltip,message:e.confirmMessage,variant:e.variant==="danger"?"danger":"default"}))){if(e.action==="copy-value"){try{await navigator.clipboard.writeText(typeof r=="string"?r:String(r))}catch{}return}if(n){c(!0);try{await n(e.action,t)}finally{c(!1)}}}};return(0,i.jsx)("button",{type:"button",onClick:u,disabled:a,title:e.tooltip,className:`inline-flex items-center justify-center rounded-md border px-2 py-1.5 transition-colors disabled:opacity-50 ${d}`,children:(0,i.jsx)(zz,{name:e.icon})})}function Zz(e){return"multiple"in e&&e.multiple!=null}function Vz({field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:a,externalProbe:c,allFields:d,onAction:u}){const f=e.multiple,h=f.min,m=f.max,g=t[e.key],p=[...Array.isArray(g)?g:g!=null?[g]:[]],y=f.itemDefault!==void 0?f.itemDefault:"default"in e&&e.default!==void 0?e.default:"";for(;p.length<h;)p.push(y);const S=O=>r(e.key,[...O]),E=(O,U)=>{const z=[...p];z[O]=U,S(z)},T=()=>{p.length>=m||S([...p,y])},j=O=>{p.length<=h||S(p.filter((U,z)=>z!==O))},N=()=>{const{multiple:O,...U}=e;return{...U,...{label:void 0,description:void 0,required:!1}}};return(0,i.jsx)(qt,{label:e.label,description:e.description,required:h>0?e.required:!1,span:e.span,translationFn:s,children:(0,i.jsxs)("div",{className:"space-y-2",children:[p.map((O,U)=>{const z=f.itemLabel?.replace("${n}",String(U+1));return(0,i.jsxs)("div",{className:"space-y-1",children:[z&&(0,i.jsx)("div",{className:nc,children:z}),(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsx)("div",{className:"flex-1 min-w-0",children:(0,i.jsx)(xs,{field:N(),values:{...t,[e.key]:O},onChange:(K,G)=>E(U,G),disabled:n,translationFn:s,onTestField:a,onAction:u,allFields:d})}),p.length>h&&(0,i.jsx)("button",{type:"button",onClick:()=>j(U),disabled:n,title:"Remove",className:"flex-shrink-0 inline-flex items-center justify-center rounded-md border border-border p-1.5 text-foreground-subtle hover:text-danger hover:border-danger/50 transition-colors disabled:opacity-40",children:(0,i.jsx)(en,{className:"h-3.5 w-3.5"})})]})]},U)}),(0,i.jsxs)("div",{className:"flex items-center justify-between pt-1",children:[p.length<m?(0,i.jsxs)("button",{type:"button",onClick:T,disabled:n,className:"inline-flex items-center gap-1.5 rounded-md border border-border px-2.5 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-40",children:[(0,i.jsx)(Ci,{className:"h-3 w-3"}),f.addLabel??"Add"]}):(0,i.jsx)("span",{}),(0,i.jsxs)("span",{className:"text-[10px] text-foreground-subtle tabular-nums",children:[p.length,"/",m]})]})]})})}function Hx(e,t,r){if(!("showWhen"in e)||!e.showWhen)return!0;const n=e.showWhen,s=t[n.field],a=r?.find(u=>"key"in u&&u.key===n.field),c=a&&"default"in a?a.default:void 0,d=s!==void 0?s:c;return n.equals!==void 0?d===n.equals:n.notEquals!==void 0?d!==n.notEquals:n.in!==void 0?n.in.includes(d):n.notIn!==void 0?!n.notIn.includes(d):n.includes!==void 0?Array.isArray(d)&&d.includes(n.includes):n.notIncludes!==void 0?!Array.isArray(d)||!d.includes(n.notIncludes):!0}function xs({field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:a,externalProbe:c,allFields:d,onAction:u}){if(Zz(e))return(0,i.jsx)(Vz,{field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:a,externalProbe:c,allFields:d,onAction:u});if("readonlyField"in e&&e.readonlyField===!0)return(0,i.jsx)(Bz,{field:e,values:t,onAction:u,translationFn:s});if(!Hx(e,t,d))return null;const f=t[e.key],h=f!==void 0?f:"default"in e?e.default:void 0,m=p=>r(e.key,p),g=rx(e.type);switch(e.type){case"text":return(0,i.jsx)(dz,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"number":return(0,i.jsx)(fz,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"boolean":return(0,i.jsx)(hz,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"select":return(0,i.jsx)(mz,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"multiselect":return(0,i.jsx)(vz,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"timezone":return(0,i.jsx)(gz,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"datetime":return(0,i.jsx)(pz,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"password":return(0,i.jsx)(bz,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"textarea":return(0,i.jsx)(yz,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"slider":return(0,i.jsx)(xz,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"tags":return(0,i.jsx)(Sz,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"color":return(0,i.jsx)(_z,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"node-select":return(0,i.jsx)(zx,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"node-multiselect":return(0,i.jsx)(Gx,{field:e,value:h,onChange:m,disabled:n,translationFn:s});case"probe":return(0,i.jsx)(wz,{field:e,value:h,onChange:m,disabled:n,translationFn:s,onTestField:a,onAction:u,externalProbe:c});case"group":return(0,i.jsx)(Ez,{field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:a});case"sub-tabs":return(0,i.jsx)(kz,{field:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:a,onAction:u});case"separator":return(0,i.jsx)(Tz,{});case"info":return(0,i.jsx)(Iz,{field:e});case"qr-code":return(0,i.jsx)(Pz,{field:e});case"object-array":return(0,i.jsx)(Dz,{field:e});case"editable-array":return(0,i.jsx)(Mz,{field:e,value:h,onChange:m,disabled:n,translationFn:s,onTestField:a,onAction:u});case"button":return(0,i.jsx)($z,{field:e,disabled:n,onAction:u});case"addon-action-select":return(0,i.jsx)(Rz,{field:e,value:h,values:t,onChange:m,disabled:n,onAction:u});case"addon-action-button":return(0,i.jsx)(Lz,{field:e,values:t,disabled:n,onAction:u});case"device-action-button":return(0,i.jsx)(Oz,{field:e,values:t,disabled:n,onAction:u});case"widget":return(0,i.jsx)(Fz,{field:e});default:return g?(0,i.jsx)(g,{field:e,value:h,onChange:m,disabled:n}):null}}function Hz(e){return/^[a-zA-Z0-9_]+(\.[a-zA-Z0-9_]+)+$/.test(e)}function gn(e,t){if(e!==void 0)return t&&Hz(e)?t(e):e}function Kz({section:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:a,probeResults:c}){const[d,u]=(0,l.useState)(e.defaultCollapsed??!1),f=e.style==="accordion",h=e.columns??2,m=h===1?"grid-cols-1":h===3?"grid-cols-1 @[480px]:grid-cols-2 @[880px]:grid-cols-3":h===4?"grid-cols-1 @[480px]:grid-cols-2 @[1140px]:grid-cols-4":"grid-cols-1 @[480px]:grid-cols-2";return(0,i.jsxs)("div",{className:"@container rounded-lg border border-border bg-surface p-3",style:{containerType:"inline-size"},children:[(0,i.jsxs)("div",{className:["flex items-center justify-between mb-2",f?"cursor-pointer":""].join(" "),onClick:f?()=>u(g=>!g):void 0,children:[(0,i.jsxs)("div",{children:[(0,i.jsx)("h3",{className:"text-[11px] font-semibold text-foreground-subtle uppercase tracking-wider",children:gn(e.title,s)}),e.description&&(0,i.jsx)("p",{className:"text-[10px] text-foreground-subtle mt-0.5",children:gn(e.description,s)})]}),f&&(0,i.jsx)("span",{className:"text-foreground-subtle text-xs ml-2",children:d?"▸":"▾"})]}),!d&&(0,i.jsx)("div",{className:`grid ${m} gap-x-3 gap-y-2.5`,children:e.fields.map(g=>(0,i.jsx)(xs,{field:g,values:t,onChange:r,disabled:n,translationFn:s,onTestField:a,externalProbe:c?.[g.key]},g.key))})]})}function Kx({schema:e,values:t,onChange:r,disabled:n,translationFn:s,onTestField:a,probeResults:c,onClearProbe:d}){const u=(f,h)=>{r({...t,[f]:h}),d?.(f)};return(0,i.jsx)("div",{className:"space-y-4",children:e.sections.map(f=>(0,i.jsx)(Kz,{section:f,values:t,onChange:u,disabled:n,translationFn:s,onTestField:a,probeResults:c},f.id))})}var Wz=({open:e})=>(0,i.jsx)("svg",{className:`h-3 w-3 transition-transform ${e?"rotate-90":""}`,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round","aria-hidden":!0,children:(0,i.jsx)("polyline",{points:"9 18 15 12 9 6"})});function Wx(e){const t={};if(!e)return t;for(const r of e.sections)for(const n of r.fields){if(n.type==="separator"||n.type==="info"||n.type==="button"||n.type==="group")continue;const s=n.key;t[s]=n.value}return t}function qz(e){return{...e,sections:e.sections.map(t=>({...t,fields:t.fields.map(r=>{if(r.type==="separator"||r.type==="info"||r.type==="button"||r.type==="group")return r;const{value:n,...s}=r;return s})}))}}function Qz({trpc:e,addonId:t,nodeId:r,title:n,disabled:s,onAfterChange:a,refreshToken:c,collapsible:d,defaultOpen:u,mode:f,onOverrideChange:h}){const m=f??"persist",[g,p]=(0,l.useState)(null),[y,S]=(0,l.useState)(!0),[E,T]=(0,l.useState)(null),[j,N]=(0,l.useState)(!1),[O,U]=(0,l.useState)(u??!1),[z,K]=(0,l.useState)({}),[G,X]=(0,l.useState)(null);(0,l.useEffect)(()=>{X(null),K({})},[e,t,r,c,m]),(0,l.useEffect)(()=>{let le=!1;S(!0),T(null);const se=m==="override"&&Object.keys(z).length>0?z:void 0;return e.addonSettings.getGlobalSettings.query({addonId:t,nodeId:r,...se?{overlay:se}:{}}).then(Ce=>{le||(p(Ce),se||X(Wx(Ce)),S(!1))}).catch(Ce=>{le||(T(Ce instanceof Error?Ce.message:String(Ce)),S(!1))}),()=>{le=!0}},[e,t,r,c,m,JSON.stringify(z)]);const te=(0,l.useMemo)(()=>Wx(g),[g]),ne=(0,l.useMemo)(()=>g?qz(g):null,[g]),ae=async le=>{if(m==="override"){const Ce=G??te,q={};for(const ie of Object.keys(le))le[ie]!==Ce[ie]&&(q[ie]=le[ie]);const Q={...Ce,...q};K(q),h?.(q,Q);return}const se={};for(const Ce of Object.keys(le))le[Ce]!==te[Ce]&&(se[Ce]=le[Ce]);if(Object.keys(se).length!==0){N(!0);try{await e.addonSettings.updateGlobalSettings.mutate({addonId:t,nodeId:r,patch:se}),p(await e.addonSettings.getGlobalSettings.query({addonId:t,nodeId:r})),a?.()}catch(Ce){T(Ce instanceof Error?Ce.message:String(Ce))}finally{N(!1)}}};if(y)return(0,i.jsxs)("div",{className:"text-xs text-foreground-subtle animate-pulse",children:["Loading ",n??t,"…"]});if(E)return(0,i.jsxs)("div",{className:"text-xs text-red-400",children:[n??t,": ",E]});if(!g||!ne)return(0,i.jsxs)("div",{className:"text-xs text-foreground-subtle",children:[n??t," not available on ",r,"."]});const oe=m==="override"?{...te,...z}:te,pe=(0,i.jsxs)(i.Fragment,{children:[m==="override"?(0,i.jsx)("div",{className:"mb-2 text-[11px] text-foreground-subtle",children:"Benchmark override — applies to this run only. The addon's saved settings are not changed."}):null,(0,i.jsx)(Kx,{schema:ne,values:oe,onChange:ae,disabled:s===!0||j})]});return d===!0?(0,i.jsxs)("section",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[(0,i.jsxs)("button",{type:"button",onClick:()=>U(le=>!le),className:"w-full px-4 py-2 flex items-center gap-2 hover:bg-surface-hover text-left","aria-expanded":O,children:[(0,i.jsx)(Wz,{open:O}),(0,i.jsx)("h3",{className:"text-xs font-semibold text-foreground uppercase tracking-wide flex-1",children:n??t}),(0,i.jsx)("span",{className:"text-[10px] text-foreground-subtle",children:O?"hide":"edit"})]}),O?(0,i.jsx)("div",{className:"border-t border-border px-4 py-3",children:pe}):null]}):n?(0,i.jsxs)("section",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[(0,i.jsx)("div",{className:"border-b border-border px-4 py-2",children:(0,i.jsx)("h3",{className:"text-xs font-semibold text-foreground uppercase tracking-wide",children:n})}),(0,i.jsx)("div",{className:"px-4 py-3",children:pe})]}):(0,i.jsx)("div",{children:pe})}function qx({detections:{motion:e,motionRaw:t,detection:r,phase:n},showMotionZones:s=!0,showMotionRaw:a=!0,showDetections:c=!0,showPhaseIndicator:d=!0}){const u=s&&e&&e.zones.length>0,f=a&&t&&t.boxes.length>0,h=c&&r&&r.detections.length>0;return!u&&!f&&!h&&!d?null:(0,i.jsxs)("div",{className:"absolute inset-0 pointer-events-none z-10",children:[d&&(0,i.jsx)(Yz,{phase:n}),f&&(0,i.jsx)(Xz,{raw:t}),u&&(0,i.jsx)(Jz,{motion:e}),h&&(0,i.jsx)(eG,{detections:r.detections,frameWidth:r.frameWidth,frameHeight:r.frameHeight})]})}function Yz({phase:e}){const t=yd(e);return(0,i.jsxs)("div",{className:"absolute top-2 left-2 flex items-center gap-1.5 px-2 py-1 rounded-md bg-black/60 backdrop-blur-sm",children:[(0,i.jsx)("span",{className:`w-2 h-2 rounded-full ${t.dotClass}`}),(0,i.jsx)("span",{className:"text-[10px] font-semibold text-white uppercase tracking-wider",children:t.label})]})}function Xz({raw:e}){return e.frameWidth===0||e.frameHeight===0?null:(0,i.jsx)(i.Fragment,{children:e.boxes.map((t,r)=>{const[n,s,a,c]=t.bbox,d=n/e.frameWidth*100,u=s/e.frameHeight*100,f=(a-n)/e.frameWidth*100,h=(c-s)/e.frameHeight*100,m=Math.max(.05,Math.min(.25,t.changeScore*.3));return(0,i.jsx)("div",{className:"absolute rounded-sm",style:{left:`${d}%`,top:`${u}%`,width:`${f}%`,height:`${h}%`,backgroundColor:`rgba(239, 68, 68, ${m})`}},`mr-${r}`)})})}function Jz({motion:e}){return e.frameWidth===0||e.frameHeight===0?null:(0,i.jsx)(i.Fragment,{children:e.zones.filter(t=>t.w*t.h/(e.frameWidth*e.frameHeight)<.9).map((t,r)=>{const n=Math.max(.15,Math.min(.5,t.intensity/255));return(0,i.jsx)("div",{className:"absolute rounded-sm",style:{left:`${t.x/e.frameWidth*100}%`,top:`${t.y/e.frameHeight*100}%`,width:`${t.w/e.frameWidth*100}%`,height:`${t.h/e.frameHeight*100}%`,border:`1px solid rgba(250, 204, 21, ${n})`,backgroundColor:`rgba(250, 204, 21, ${n*.15})`}},`mz-${r}`)})})}function eG({detections:e,frameWidth:t,frameHeight:r}){return t===0||r===0?null:(0,i.jsx)(i.Fragment,{children:e.map(n=>{const{x:s,y:a,width:c,height:d}=n.bbox,u=s/t*100,f=a/r*100,h=c/t*100,m=d/r*100,g=zr(n.macroClass),p=[`${n.macroClass} ${(n.score*100).toFixed(0)}%`];for(const y of n.labels)p.push(y.label);return(0,i.jsx)("div",{className:"absolute border-2 rounded-sm",style:{left:`${u}%`,top:`${f}%`,width:`${h}%`,height:`${m}%`,borderColor:g},children:(0,i.jsx)("div",{className:"absolute -top-4 left-0 px-1 py-0.5 text-[9px] font-bold text-white rounded-sm whitespace-nowrap",style:{backgroundColor:g},children:p.join(" | ")})},`det-${n.id}`)})})}function tG(){return typeof window>"u"?!1:window.matchMedia("(hover: none) and (pointer: coarse)").matches||typeof navigator<"u"&&navigator.maxTouchPoints>0||"ontouchstart"in window}function rG(e){const t={};if(typeof window<"u"){if(e){const n=e.getBoundingClientRect();n.width>0&&n.height>0&&(t.viewportWidth=Math.round(n.width),t.viewportHeight=Math.round(n.height))}t.viewportWidth===void 0&&(t.viewportWidth=window.innerWidth,t.viewportHeight=window.innerHeight),t.devicePixelRatio=window.devicePixelRatio||1;const r=navigator.connection;r?.downlink&&r.downlink>0&&(t.downlinkMbps=r.downlink)}return t}var nG=1500,iG=15e3,sG=40;function Qx({serverUrl:e,streamKey:t,label:r,autoPlay:n=!0,muted:s=!0,showControls:a=!0,className:c="",onStateChange:d,onError:u,overlay:f,createSession:h,sendAnswer:m,handleOffer:g,getIceServers:p,addIceCandidate:y,getIceCandidates:S,closeSession:E,getSessionState:T,reoffer:j,posterUrl:N,hintsOverride:O}){const U=(0,l.useRef)(null),z=(0,l.useRef)(null),K=(0,l.useRef)(null),G=(0,l.useRef)(new Set),X=(0,l.useRef)(null),te=(0,l.useRef)(null),ne=(0,l.useRef)(0),ae=(0,l.useRef)(!0),oe=(0,l.useRef)(null),pe=(0,l.useRef)(null),le=(0,l.useRef)(0),se=(0,l.useRef)(!1),Ce=(0,l.useRef)(async()=>{}),[q,Q]=(0,l.useState)("idle"),[ie,be]=(0,l.useState)(""),[we,Re]=(0,l.useState)(s),[Ee,Fe]=(0,l.useState)(!1),[Ge,Be]=(0,l.useState)(!1),st=tG(),[at,We]=(0,l.useState)(!0),ct=(0,l.useRef)(null),He=(0,l.useRef)(!1);(m||h)&&(He.current=!0);const $e=He.current,Ke=(0,l.useRef)(!1);g&&(Ke.current=!0);const ft=Ke.current,St=(0,l.useCallback)(Ue=>{Q(Ue),d?.(Ue)},[d]),Rt=(0,l.useCallback)(()=>{if(X.current?.abort(),X.current=null,te.current&&(clearTimeout(te.current),te.current=null),pe.current&&(clearTimeout(pe.current),pe.current=null),oe.current=null,se.current=!1,le.current=0,K.current&&(K.current.close(),K.current=null),E&&G.current.size>0){for(const Ue of G.current)E(Ue).catch(()=>{});G.current.clear()}U.current&&(U.current.srcObject=null)},[E]),dr=1e3,Er=(0,l.useCallback)(Ue=>{if(!T||!j)return;pe.current&&(clearTimeout(pe.current),pe.current=null);const lt=async()=>{if(ae.current&&oe.current===Ue){if(!se.current)try{const{pendingRenegotiation:nt}=await T(Ue);if(ae.current&&oe.current===Ue&&nt&&nt.epoch>le.current&&!se.current){le.current=nt.epoch,await Ce.current(Ue,nt.target);return}}catch{}!ae.current||oe.current!==Ue||(pe.current=setTimeout(()=>{lt()},dr))}};pe.current=setTimeout(()=>{lt()},dr)},[T,j]),At=(0,l.useCallback)(async()=>{if(!ae.current||!h||!m)return;Rt(),St("connecting");const Ue=new AbortController;X.current=Ue;try{const{sessionId:lt,sdpOffer:nt,iceServers:nr}=await h({...rG(z.current),...O});if(G.current.add(lt),!ae.current||Ue.signal.aborted){E?.(lt).catch(()=>{}),G.current.delete(lt);return}const qe=new RTCPeerConnection({iceServers:[...nr??[],{urls:"stun:stun.l.google.com:19302"}]});K.current=qe;const kt=new MediaStream;qe.ontrack=Vt=>{console.debug("[WebRTC] ontrack",Vt.track.kind,Vt.track.readyState),kt.addTrack(Vt.track),U.current&&(U.current.srcObject=kt,U.current.play().catch(()=>{}))},qe.oniceconnectionstatechange=()=>{if(!ae.current)return;const Vt=qe.iceConnectionState;console.debug("[WebRTC] ICE state:",Vt),Vt==="connected"||Vt==="completed"?(ne.current=0,St("playing"),U.current?.paused&&(console.debug("[WebRTC] video was paused at ICE connected — calling play()"),U.current.play().catch(()=>{}))):(Vt==="failed"||Vt==="disconnected"||Vt==="closed")&&(St("disconnected"),jr())},qe.onicecandidateerror=Vt=>{console.debug("[WebRTC] ICE candidate error:",Vt)},console.debug("[WebRTC] Setting remote description (server offer)..."),await qe.setRemoteDescription({type:"offer",sdp:nt});const vr=await qe.createAnswer();if(await qe.setLocalDescription(vr),console.debug("[WebRTC] Local description set, waiting for ICE gathering..."),await Yx(qe),!ae.current)return;const Nr=(qe.localDescription?.sdp??"").split(`
149
+ `).filter(Vt=>Vt.startsWith("a=candidate:")).length;console.debug("[WebRTC] Sending answer to server",{localCandidates:Nr,sessionId:lt.slice(0,8)}),await m(lt,qe.localDescription?.sdp??""),console.debug("[WebRTC] Answer sent successfully");const Zi=qe,Ht=()=>{const Vt=Zi.connectionState;if(Vt==="closed"||Vt==="failed")return;const gi=U.current;gi&&gi.readyState===0&&console.log(`[WebRTC] no video data yet (ice=${Zi.iceConnectionState})`)};setTimeout(Ht,3e3),setTimeout(Ht,8e3)}catch(lt){if(!ae.current)return;const nt=lt instanceof Error?lt.message:String(lt);be(nt),St("error"),u?.(nt),jr()}},[e,t,h,m,Rt,St,u,O]),jt=(0,l.useCallback)(async()=>{if(ae.current){Rt(),St("connecting");try{const Ue=new RTCPeerConnection({iceServers:[{urls:"stun:stun.l.google.com:19302"}]});K.current=Ue,Ue.addTransceiver("video",{direction:"recvonly"}),Ue.addTransceiver("audio",{direction:"recvonly"});const lt=new MediaStream;Ue.ontrack=vr=>{lt.addTrack(vr.track),U.current&&(U.current.srcObject=lt,U.current.play().catch(()=>{}))},Ue.oniceconnectionstatechange=()=>{if(!ae.current)return;const vr=Ue.iceConnectionState;vr==="connected"||vr==="completed"?(ne.current=0,St("playing"),U.current?.paused&&U.current.play().catch(()=>{})):(vr==="failed"||vr==="disconnected"||vr==="closed")&&(St("disconnected"),jr())};const nt=await Ue.createOffer();if(await Ue.setLocalDescription(nt),await Yx(Ue),!ae.current)return;const nr=`${e}/api/webrtc?src=${encodeURIComponent(t)}`,qe=await fetch(nr,{method:"POST",headers:{"Content-Type":"application/sdp"},body:Ue.localDescription?.sdp??""});if(!qe.ok)throw new Error(`WHEP ${qe.status}: ${qe.statusText}`);const kt=await qe.text();await Ue.setRemoteDescription({type:"answer",sdp:kt})}catch(Ue){if(!ae.current)return;const lt=Ue instanceof Error?Ue.message:String(Ue);be(lt),St("error"),u?.(lt),jr()}}},[e,t,Rt,St,u]),rr=(0,l.useCallback)(async()=>{if(!ae.current||!g)return;Rt(),St("connecting");const Ue=new AbortController;X.current=Ue;try{const lt=await p?.();if(!ae.current||Ue.signal.aborted)return;const nt=new RTCPeerConnection({iceServers:[...lt??[],{urls:"stun:stun.l.google.com:19302"}]});K.current=nt;const nr=new MediaStream;nt.ontrack=Ht=>{console.debug("[WebRTC] ontrack (client-offer)",Ht.track.kind,Ht.track.readyState),nr.addTrack(Ht.track),U.current&&(U.current.srcObject=nr,U.current.play().catch(()=>{}))},nt.oniceconnectionstatechange=()=>{if(!ae.current)return;const Ht=nt.iceConnectionState;console.debug("[WebRTC] ICE state (client-offer):",Ht),Ht==="connected"||Ht==="completed"?(ne.current=0,St("playing"),U.current?.paused&&U.current.play().catch(()=>{})):(Ht==="failed"||Ht==="disconnected"||Ht==="closed")&&(St("disconnected"),jr())};let qe=null;const kt=[];nt.onicecandidate=Ht=>{if(!Ht.candidate)return;const Vt=Ht.candidate.toJSON();qe&&y?y(qe,Vt).catch(()=>{}):kt.push(Vt)},nt.addTransceiver("video",{direction:"recvonly"}),nt.addTransceiver("audio",{direction:"recvonly"});const vr=await nt.createOffer();if(await nt.setLocalDescription(vr),!ae.current||Ue.signal.aborted)return;const{sessionId:Nr,sdpAnswer:Zi}=await g(nt.localDescription?.sdp??vr.sdp??"");if(qe=Nr,G.current.add(Nr),oe.current=Nr,!ae.current||Ue.signal.aborted){E?.(Nr).catch(()=>{}),G.current.delete(Nr);return}if(y)for(const Ht of kt)y(Nr,Ht).catch(()=>{});if(kt.length=0,await nt.setRemoteDescription({type:"answer",sdp:Zi}),console.debug("[WebRTC] Client-offer answer set (trickle)",{sessionId:Nr.slice(0,8)}),S){const Ht=new Set,Vt=Date.now(),gi=async()=>{if(!(!ae.current||Ue.signal.aborted||K.current!==nt)){try{const{candidates:pi,done:gg}=await S(Nr);for(const Vi of pi){const Rs=Vi.candidate??"";Rs&&!Ht.has(Rs)&&(Ht.add(Rs),nt.addIceCandidate(new RTCIceCandidate(Vi)).catch(()=>{}))}const lr=nt.iceConnectionState;if(gg||Date.now()-Vt>1e4||lr==="connected"||lr==="completed")return}catch{}setTimeout(()=>{gi()},200)}};gi()}Er(Nr)}catch(lt){if(!ae.current)return;const nt=lt instanceof Error?lt.message:String(lt);be(nt),St("error"),u?.(nt),jr()}},[g,p,y,S,E,Rt,St,u,Er]);Ce.current=(0,l.useCallback)(async(Ue,lt)=>{const nt=j;if(!ae.current||!nt)return;const nr=K.current;se.current=!0;try{const qe=await p?.();if(!ae.current)return;const kt=new RTCPeerConnection({iceServers:[...qe??[],{urls:"stun:stun.l.google.com:19302"}]}),vr=new MediaStream;let Nr=!1;const Zi=()=>{Nr||!ae.current||(Nr=!0,K.current=kt,U.current&&(U.current.srcObject=vr,U.current.play().catch(()=>{})),nr&&nr!==kt&&nr.close())};kt.ontrack=lr=>{console.debug("[WebRTC] ontrack (reoffer)",lr.track.kind,lr.track.readyState),vr.addTrack(lr.track),Zi()},kt.oniceconnectionstatechange=()=>{if(!ae.current)return;const lr=kt.iceConnectionState;console.debug("[WebRTC] ICE state (reoffer):",lr),lr==="connected"||lr==="completed"?(ne.current=0,Zi(),St("playing"),U.current?.paused&&U.current.play().catch(()=>{})):(lr==="failed"||lr==="closed")&&(!Nr&&lr==="failed"&&kt.close(),St("disconnected"),jr())};let Ht=null;const Vt=[];kt.onicecandidate=lr=>{if(!lr.candidate)return;const Vi=lr.candidate.toJSON();Ht&&y?y(Ht,Vi).catch(()=>{}):Vt.push(Vi)},kt.addTransceiver("video",{direction:"recvonly"}),kt.addTransceiver("audio",{direction:"recvonly"});const gi=await kt.createOffer();if(await kt.setLocalDescription(gi),!ae.current){kt.close();return}const{sessionId:pi,sdpAnswer:gg}=await nt(Ue,kt.localDescription?.sdp??gi.sdp??"",lt);if(!ae.current){kt.close();return}if(Ht=pi,G.current.add(pi),oe.current=pi,y)for(const lr of Vt)y(pi,lr).catch(()=>{});if(Vt.length=0,await kt.setRemoteDescription({type:"answer",sdp:gg}),S){const lr=new Set,Vi=Date.now(),Rs=async()=>{if(ae.current&&!(kt.connectionState==="closed"||kt.signalingState==="closed")){try{const{candidates:VH,done:HH}=await S(pi);for(const dw of VH){const pg=dw.candidate??"";pg&&!lr.has(pg)&&(lr.add(pg),kt.addIceCandidate(new RTCIceCandidate(dw)).catch(()=>{}))}const uw=kt.iceConnectionState;if(HH||Date.now()-Vi>1e4||uw==="connected"||uw==="completed")return}catch{}setTimeout(()=>{Rs()},200)}};Rs()}Er(pi)}catch(qe){console.debug("[WebRTC] reoffer failed; keeping last frame, re-arming poll",qe instanceof Error?qe.message:String(qe)),Er(Ue)}finally{se.current=!1}},[j,p,y,S,St,Er]);const Gt=ft?rr:$e?At:jt,sn=(0,l.useRef)(()=>{});sn.current=Gt;const jr=(0,l.useCallback)(()=>{if(!ae.current||ne.current>=sG)return;const Ue=ne.current;ne.current+=1;const lt=Math.min(iG,nG*2**Ue),nt=Math.round(lt*(.8+Math.random()*.4));te.current=setTimeout(()=>{ae.current&&sn.current()},nt)},[]);(0,l.useEffect)(()=>(ae.current=!0,ne.current=0,n&&Gt(),()=>{ae.current=!1,Rt()}),[e,t]);const Wn=(0,l.useRef)(!1);(0,l.useEffect)(()=>{if(n){if(ft){if(!g)return}else if($e){if(!h||!m)return}else return;Wn.current||K.current||(Wn.current=!0,Gt())}},[n,ft,$e,g,h,m,Gt]);const Gi=()=>{ne.current=0,Gt()},he=()=>{U.current&&(U.current.muted=!U.current.muted,Re(U.current.muted))},rt=async()=>{if(z.current)try{if(document.fullscreenElement){await document.exitFullscreen();return}if(z.current.requestFullscreen){await z.current.requestFullscreen();return}const Ue=U.current;Ue?.webkitEnterFullscreen&&Ue.webkitEnterFullscreen()}catch(Ue){console.warn(`Fullscreen toggle failed: ${Ue instanceof Error?Ue.message:Ue}`)}},ut=async()=>{const Ue=U.current;if(Ue)try{if(typeof Ue.webkitSetPresentationMode=="function"){Ue.webkitSetPresentationMode(Ue.webkitPresentationMode==="picture-in-picture"?"inline":"picture-in-picture");return}document.pictureInPictureElement?await document.exitPictureInPicture():await Ue.requestPictureInPicture()}catch(lt){console.warn(`PiP toggle failed: ${lt instanceof Error?lt.message:String(lt)}`)}},gt=()=>{if(!U.current)return;const Ue=document.createElement("canvas");Ue.width=U.current.videoWidth||1280,Ue.height=U.current.videoHeight||720;const lt=Ue.getContext("2d");if(!lt)return;lt.drawImage(U.current,0,0);const nt=document.createElement("a");nt.download=`${t.replace(/[/:]/g,"-")}-${Date.now()}.jpg`,nt.href=Ue.toDataURL("image/jpeg",.92),nt.click()};(0,l.useEffect)(()=>{const Ue=()=>Fe(!!document.fullscreenElement);document.addEventListener("fullscreenchange",Ue);const lt=U.current;return lt?.addEventListener("webkitbeginfullscreen",Ue),lt?.addEventListener("webkitendfullscreen",Ue),()=>{document.removeEventListener("fullscreenchange",Ue),lt?.removeEventListener("webkitbeginfullscreen",Ue),lt?.removeEventListener("webkitendfullscreen",Ue)}},[]),(0,l.useEffect)(()=>{const Ue=U.current,lt=typeof document<"u"&&document.pictureInPictureEnabled===!0,nt=Ue!==null&&typeof Ue.webkitSetPresentationMode=="function";Be(lt||nt)},[]);const Lt=()=>{st||(We(!0),ct.current&&clearTimeout(ct.current),ct.current=setTimeout(()=>We(!1),3e3))},dt=()=>{We(Ue=>!Ue),ct.current&&clearTimeout(ct.current)};return(0,i.jsxs)("div",{ref:z,className:`relative isolate bg-black overflow-hidden group ${c}`,onMouseMove:Lt,onMouseEnter:Lt,onTouchStart:dt,children:[(0,i.jsx)("video",{ref:U,autoPlay:n,muted:we,playsInline:!0,...N?{poster:N}:{},className:"w-full h-full object-contain relative z-0"}),r&&q==="playing"&&(0,i.jsx)("div",{className:"absolute top-2 left-2 z-10 transform-gpu px-2 py-0.5 rounded bg-black/60 text-[10px] text-white font-medium",children:r}),f,q==="connecting"&&(0,i.jsxs)("div",{className:"absolute inset-0 z-10 transform-gpu flex flex-col items-center justify-center bg-black/70 gap-2",children:[(0,i.jsx)("svg",{className:"h-6 w-6 text-white/60 animate-spin",viewBox:"0 0 24 24",fill:"none",children:(0,i.jsx)("circle",{cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeDasharray:"32",strokeDashoffset:"32",className:"animate-[dash_1.5s_ease-in-out_infinite]"})}),(0,i.jsx)("span",{className:"text-xs text-white/60",children:"Connecting…"})]}),(q==="error"||q==="disconnected")&&(0,i.jsxs)("div",{className:"absolute inset-0 z-10 transform-gpu flex flex-col items-center justify-center bg-black/70 gap-2",children:[(0,i.jsx)("svg",{className:"h-6 w-6 text-red-400",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:(0,i.jsx)("path",{d:"M1 1l5.5 5.5M23 23l-5.5-5.5M8.11 15.89a8 8 0 0110.78-10.78M3.64 3.64A12 12 0 0020.36 20.36",strokeLinecap:"round"})}),(0,i.jsx)("span",{className:"text-xs text-red-400 text-center px-4",children:q==="error"?ie||"Connection failed":"Disconnected"}),(0,i.jsx)("button",{onClick:Gi,className:"mt-1 inline-flex items-center gap-1.5 rounded px-3 py-1 text-xs bg-white/10 text-white hover:bg-white/20 transition-colors",children:"Reconnect"})]}),a&&q!=="idle"&&q!=="error"&&(0,i.jsxs)("div",{className:`absolute bottom-0 inset-x-0 z-20 transform-gpu flex items-center justify-between px-3 py-1.5 bg-gradient-to-t from-black/80 to-transparent transition-opacity duration-200 ${st||at?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"}`,children:[(0,i.jsx)("div",{className:"flex items-center gap-1",children:(0,i.jsx)(ic,{onClick:he,title:we?"Unmute":"Mute",children:we?(0,i.jsxs)("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,i.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,i.jsx)("line",{x1:"23",y1:"9",x2:"17",y2:"15"}),(0,i.jsx)("line",{x1:"17",y1:"9",x2:"23",y2:"15"})]}):(0,i.jsxs)("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,i.jsx)("polygon",{points:"11 5 6 9 2 9 2 15 6 15 11 19 11 5"}),(0,i.jsx)("path",{d:"M19.07 4.93a10 10 0 010 14.14M15.54 8.46a5 5 0 010 7.07"})]})})}),(0,i.jsxs)("div",{className:"flex items-center gap-1",children:[(0,i.jsx)(ic,{onClick:gt,title:"Take snapshot",children:(0,i.jsxs)("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:[(0,i.jsx)("path",{d:"M23 19a2 2 0 01-2 2H3a2 2 0 01-2-2V8a2 2 0 012-2h4l2-3h6l2 3h4a2 2 0 012 2z"}),(0,i.jsx)("circle",{cx:"12",cy:"13",r:"4"})]})}),Ge&&(0,i.jsx)(ic,{onClick:ut,title:"Picture-in-Picture",children:(0,i.jsxs)("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,i.jsx)("path",{d:"M21 9V6a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2h4"}),(0,i.jsx)("rect",{width:"10",height:"7",x:"12",y:"13",rx:"2"})]})}),(0,i.jsx)(ic,{onClick:rt,title:Ee?"Exit fullscreen":"Fullscreen",children:Ee?(0,i.jsx)("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:(0,i.jsx)("path",{d:"M8 3v3a2 2 0 01-2 2H3m18 0h-3a2 2 0 01-2-2V3m0 18v-3a2 2 0 012-2h3M3 16h3a2 2 0 012 2v3"})}):(0,i.jsx)("svg",{className:"h-3.5 w-3.5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",children:(0,i.jsx)("path",{d:"M8 3H5a2 2 0 00-2 2v3m18 0V5a2 2 0 00-2-2h-3m0 18h3a2 2 0 002-2v-3M3 16v3a2 2 0 002 2h3"})})})]})]})]})}function ic({onClick:e,title:t,children:r}){return(0,i.jsx)("button",{onClick:e,title:t,className:"rounded-full p-1.5 min-w-[44px] min-h-[44px] flex items-center justify-center text-white/80 hover:text-white hover:bg-white/20 active:bg-white/30 transition-colors",children:r})}async function Yx(e){if(e.iceGatheringState!=="complete")return new Promise(t=>{let r=!1,n;const s=()=>{r||(r=!0,n&&clearInterval(n),e.removeEventListener("icegatheringstatechange",a),t())},a=()=>{e.iceGatheringState==="complete"&&s()};e.addEventListener("icegatheringstatechange",a);const c=Date.now();n=setInterval(()=>{const d=e.localDescription?.sdp??"";/ typ host/.test(d)&&Date.now()-c>=600&&s()},100),setTimeout(s,2500)})}var Ye=Number.isFinite||function(e){return typeof e=="number"&&isFinite(e)},aG=Number.isSafeInteger||function(e){return typeof e=="number"&&Math.abs(e)<=oG},oG=Number.MAX_SAFE_INTEGER||9007199254740991,it=(function(e){return e.NETWORK_ERROR="networkError",e.MEDIA_ERROR="mediaError",e.KEY_SYSTEM_ERROR="keySystemError",e.MUX_ERROR="muxError",e.OTHER_ERROR="otherError",e})({}),fe=(function(e){return e.KEY_SYSTEM_NO_KEYS="keySystemNoKeys",e.KEY_SYSTEM_NO_ACCESS="keySystemNoAccess",e.KEY_SYSTEM_NO_SESSION="keySystemNoSession",e.KEY_SYSTEM_NO_CONFIGURED_LICENSE="keySystemNoConfiguredLicense",e.KEY_SYSTEM_LICENSE_REQUEST_FAILED="keySystemLicenseRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED="keySystemServerCertificateRequestFailed",e.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED="keySystemServerCertificateUpdateFailed",e.KEY_SYSTEM_SESSION_UPDATE_FAILED="keySystemSessionUpdateFailed",e.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED="keySystemStatusOutputRestricted",e.KEY_SYSTEM_STATUS_INTERNAL_ERROR="keySystemStatusInternalError",e.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR="keySystemDestroyMediaKeysError",e.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR="keySystemDestroyCloseSessionError",e.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR="keySystemDestroyRemoveSessionError",e.MANIFEST_LOAD_ERROR="manifestLoadError",e.MANIFEST_LOAD_TIMEOUT="manifestLoadTimeOut",e.MANIFEST_PARSING_ERROR="manifestParsingError",e.MANIFEST_INCOMPATIBLE_CODECS_ERROR="manifestIncompatibleCodecsError",e.LEVEL_EMPTY_ERROR="levelEmptyError",e.LEVEL_LOAD_ERROR="levelLoadError",e.LEVEL_LOAD_TIMEOUT="levelLoadTimeOut",e.LEVEL_PARSING_ERROR="levelParsingError",e.LEVEL_SWITCH_ERROR="levelSwitchError",e.AUDIO_TRACK_LOAD_ERROR="audioTrackLoadError",e.AUDIO_TRACK_LOAD_TIMEOUT="audioTrackLoadTimeOut",e.SUBTITLE_LOAD_ERROR="subtitleTrackLoadError",e.SUBTITLE_TRACK_LOAD_TIMEOUT="subtitleTrackLoadTimeOut",e.FRAG_LOAD_ERROR="fragLoadError",e.FRAG_LOAD_TIMEOUT="fragLoadTimeOut",e.FRAG_DECRYPT_ERROR="fragDecryptError",e.FRAG_PARSING_ERROR="fragParsingError",e.FRAG_GAP="fragGap",e.REMUX_ALLOC_ERROR="remuxAllocError",e.KEY_LOAD_ERROR="keyLoadError",e.KEY_LOAD_TIMEOUT="keyLoadTimeOut",e.BUFFER_ADD_CODEC_ERROR="bufferAddCodecError",e.BUFFER_INCOMPATIBLE_CODECS_ERROR="bufferIncompatibleCodecsError",e.BUFFER_APPEND_ERROR="bufferAppendError",e.BUFFER_APPENDING_ERROR="bufferAppendingError",e.BUFFER_STALLED_ERROR="bufferStalledError",e.BUFFER_FULL_ERROR="bufferFullError",e.BUFFER_SEEK_OVER_HOLE="bufferSeekOverHole",e.BUFFER_NUDGE_ON_STALL="bufferNudgeOnStall",e.ASSET_LIST_LOAD_ERROR="assetListLoadError",e.ASSET_LIST_LOAD_TIMEOUT="assetListLoadTimeout",e.ASSET_LIST_PARSING_ERROR="assetListParsingError",e.INTERSTITIAL_ASSET_ITEM_ERROR="interstitialAssetItemError",e.INTERNAL_EXCEPTION="internalException",e.INTERNAL_ABORTED="aborted",e.ATTACH_MEDIA_ERROR="attachMediaError",e.UNKNOWN="unknown",e})({}),$=(function(e){return e.MEDIA_ATTACHING="hlsMediaAttaching",e.MEDIA_ATTACHED="hlsMediaAttached",e.MEDIA_DETACHING="hlsMediaDetaching",e.MEDIA_DETACHED="hlsMediaDetached",e.MEDIA_ENDED="hlsMediaEnded",e.STALL_RESOLVED="hlsStallResolved",e.BUFFER_RESET="hlsBufferReset",e.BUFFER_CODECS="hlsBufferCodecs",e.BUFFER_CREATED="hlsBufferCreated",e.BUFFER_APPENDING="hlsBufferAppending",e.BUFFER_APPENDED="hlsBufferAppended",e.BUFFER_EOS="hlsBufferEos",e.BUFFERED_TO_END="hlsBufferedToEnd",e.BUFFER_FLUSHING="hlsBufferFlushing",e.BUFFER_FLUSHED="hlsBufferFlushed",e.MANIFEST_LOADING="hlsManifestLoading",e.MANIFEST_LOADED="hlsManifestLoaded",e.MANIFEST_PARSED="hlsManifestParsed",e.LEVEL_SWITCHING="hlsLevelSwitching",e.LEVEL_SWITCHED="hlsLevelSwitched",e.LEVEL_LOADING="hlsLevelLoading",e.LEVEL_LOADED="hlsLevelLoaded",e.LEVEL_UPDATED="hlsLevelUpdated",e.LEVEL_PTS_UPDATED="hlsLevelPtsUpdated",e.LEVELS_UPDATED="hlsLevelsUpdated",e.AUDIO_TRACKS_UPDATED="hlsAudioTracksUpdated",e.AUDIO_TRACK_SWITCHING="hlsAudioTrackSwitching",e.AUDIO_TRACK_SWITCHED="hlsAudioTrackSwitched",e.AUDIO_TRACK_LOADING="hlsAudioTrackLoading",e.AUDIO_TRACK_LOADED="hlsAudioTrackLoaded",e.AUDIO_TRACK_UPDATED="hlsAudioTrackUpdated",e.SUBTITLE_TRACKS_UPDATED="hlsSubtitleTracksUpdated",e.SUBTITLE_TRACKS_CLEARED="hlsSubtitleTracksCleared",e.SUBTITLE_TRACK_SWITCH="hlsSubtitleTrackSwitch",e.SUBTITLE_TRACK_LOADING="hlsSubtitleTrackLoading",e.SUBTITLE_TRACK_LOADED="hlsSubtitleTrackLoaded",e.SUBTITLE_TRACK_UPDATED="hlsSubtitleTrackUpdated",e.SUBTITLE_FRAG_PROCESSED="hlsSubtitleFragProcessed",e.CUES_PARSED="hlsCuesParsed",e.NON_NATIVE_TEXT_TRACKS_FOUND="hlsNonNativeTextTracksFound",e.INIT_PTS_FOUND="hlsInitPtsFound",e.FRAG_LOADING="hlsFragLoading",e.FRAG_LOAD_EMERGENCY_ABORTED="hlsFragLoadEmergencyAborted",e.FRAG_LOADED="hlsFragLoaded",e.FRAG_DECRYPTED="hlsFragDecrypted",e.FRAG_PARSING_INIT_SEGMENT="hlsFragParsingInitSegment",e.FRAG_PARSING_USERDATA="hlsFragParsingUserdata",e.FRAG_PARSING_METADATA="hlsFragParsingMetadata",e.FRAG_PARSED="hlsFragParsed",e.FRAG_BUFFERED="hlsFragBuffered",e.FRAG_CHANGED="hlsFragChanged",e.FPS_DROP="hlsFpsDrop",e.FPS_DROP_LEVEL_CAPPING="hlsFpsDropLevelCapping",e.MAX_AUTO_LEVEL_UPDATED="hlsMaxAutoLevelUpdated",e.ERROR="hlsError",e.DESTROYING="hlsDestroying",e.KEY_LOADING="hlsKeyLoading",e.KEY_LOADED="hlsKeyLoaded",e.LIVE_BACK_BUFFER_REACHED="hlsLiveBackBufferReached",e.BACK_BUFFER_REACHED="hlsBackBufferReached",e.STEERING_MANIFEST_LOADED="hlsSteeringManifestLoaded",e.ASSET_LIST_LOADING="hlsAssetListLoading",e.ASSET_LIST_LOADED="hlsAssetListLoaded",e.INTERSTITIALS_UPDATED="hlsInterstitialsUpdated",e.INTERSTITIALS_BUFFERED_TO_BOUNDARY="hlsInterstitialsBufferedToBoundary",e.INTERSTITIAL_ASSET_PLAYER_CREATED="hlsInterstitialAssetPlayerCreated",e.INTERSTITIAL_STARTED="hlsInterstitialStarted",e.INTERSTITIAL_ASSET_STARTED="hlsInterstitialAssetStarted",e.INTERSTITIAL_ASSET_ENDED="hlsInterstitialAssetEnded",e.INTERSTITIAL_ASSET_ERROR="hlsInterstitialAssetError",e.INTERSTITIAL_ENDED="hlsInterstitialEnded",e.INTERSTITIALS_PRIMARY_RESUMED="hlsInterstitialsPrimaryResumed",e.PLAYOUT_LIMIT_REACHED="hlsPlayoutLimitReached",e.EVENT_CUE_ENTER="hlsEventCueEnter",e})({}),Et={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Je={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},Ss=class{constructor(e,t=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=t,this.totalWeight_=r}sample(e,t){const r=Math.pow(this.alpha_,e);this.estimate_=t*(1-r)+r*this.estimate_,this.totalWeight_+=e}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const e=1-Math.pow(this.alpha_,this.totalWeight_);if(e)return this.estimate_/e}return this.estimate_}},lG=class{constructor(e,t,r,n=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Ss(e),this.fast_=new Ss(t),this.defaultTTFB_=n,this.ttfb_=new Ss(e)}update(e,t){const{slow_:r,fast_:n,ttfb_:s}=this;r.halfLife!==e&&(this.slow_=new Ss(e,r.getEstimate(),r.getTotalWeight())),n.halfLife!==t&&(this.fast_=new Ss(t,n.getEstimate(),n.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new Ss(e,s.getEstimate(),s.getTotalWeight()))}sample(e,t){e=Math.max(e,this.minDelayMs_);const r=8*t,n=e/1e3,s=r/n;this.fast_.sample(n,s),this.slow_.sample(n,s)}sampleTTFB(e){const t=e/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(t,2)/2);this.ttfb_.sample(r,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}};function cG(e,t,r){return(t=dG(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function Ft(){return Ft=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)({}).hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},Ft.apply(null,arguments)}function Xx(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),r.push.apply(r,n)}return r}function Mt(e){for(var t=1;t<arguments.length;t++){var r=arguments[t]!=null?arguments[t]:{};t%2?Xx(Object(r),!0).forEach(function(n){cG(e,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):Xx(Object(r)).forEach(function(n){Object.defineProperty(e,n,Object.getOwnPropertyDescriptor(r,n))})}return e}function uG(e,t){if(typeof e!="object"||!e)return e;var r=e[Symbol.toPrimitive];if(r!==void 0){var n=r.call(e,t);if(typeof n!="object")return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function dG(e){var t=uG(e,"string");return typeof t=="symbol"?t:t+""}var rn=class{constructor(e,t){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const r=`[${e}]:`;this.trace=ui,this.debug=t.debug.bind(null,r),this.log=t.log.bind(null,r),this.warn=t.warn.bind(null,r),this.info=t.info.bind(null,r),this.error=t.error.bind(null,r)}},ui=function(){},fG={trace:ui,debug:ui,log:ui,warn:ui,info:ui,error:ui};function Kh(){return Ft({},fG)}function hG(e,t){const r=self.console[e];return r?r.bind(self.console,`${t?"["+t+"] ":""}[${e}] >`):ui}function Jx(e,t,r){return t[e]?t[e].bind(t):hG(e,r)}var Wh=Kh();function mG(e,t,r){const n=Kh();if(typeof console=="object"&&e===!0||typeof e=="object"){const s=["debug","log","info","warn","error"];s.forEach(a=>{n[a]=Jx(a,e,r)});try{n.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return Kh()}s.forEach(a=>{Wh[a]=Jx(a,e)})}else Ft(Wh,n);return n}var $t=Wh;function di(e=!0){if(!(typeof self>"u"))return(e||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function gG(e){return typeof self<"u"&&e===self.ManagedMediaSource}function eS(e,t){const r=Object.keys(e),n=Object.keys(t),s=r.length,a=n.length;return!s||!a||s===a&&!r.some(c=>n.indexOf(c)===-1)}function Gr(e,t=!1){if(typeof TextDecoder<"u"){const u=new TextDecoder("utf-8").decode(e);if(t){const f=u.indexOf("\0");return f!==-1?u.substring(0,f):u}return u.replace(/\0/g,"")}const r=e.length;let n,s,a,c="",d=0;for(;d<r;){if(n=e[d++],n===0&&t)return c;if(n===0||n===3)continue;switch(n>>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:c+=String.fromCharCode(n);break;case 12:case 13:s=e[d++],c+=String.fromCharCode((n&31)<<6|s&63);break;case 14:s=e[d++],a=e[d++],c+=String.fromCharCode((n&15)<<12|(s&63)<<6|(a&63)<<0);break}}return c}function xr(e){let t="";for(let r=0;r<e.length;r++){let n=e[r].toString(16);n.length<2&&(n="0"+n),t+=n}return t}function tS(e){return Uint8Array.from(e.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}function pG(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var qh={exports:{}},rS;function vG(){return rS||(rS=1,(function(e,t){(function(r){var n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,s=/^(?=([^\/?#]*))\1([^]*)$/,a=/(?:\/|^)\.(?=\/)/g,c=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,d={buildAbsoluteURL:function(u,f,h){if(h=h||{},u=u.trim(),f=f.trim(),!f){if(!h.alwaysNormalize)return u;var m=d.parseURL(u);if(!m)throw new Error("Error trying to parse base URL.");return m.path=d.normalizePath(m.path),d.buildURLFromParts(m)}var g=d.parseURL(f);if(!g)throw new Error("Error trying to parse relative URL.");if(g.scheme)return h.alwaysNormalize?(g.path=d.normalizePath(g.path),d.buildURLFromParts(g)):f;var p=d.parseURL(u);if(!p)throw new Error("Error trying to parse base URL.");if(!p.netLoc&&p.path&&p.path[0]!=="/"){var y=s.exec(p.path);p.netLoc=y[1],p.path=y[2]}p.netLoc&&!p.path&&(p.path="/");var S={scheme:p.scheme,netLoc:g.netLoc,path:null,params:g.params,query:g.query,fragment:g.fragment};if(!g.netLoc&&(S.netLoc=p.netLoc,g.path[0]!=="/"))if(!g.path)S.path=p.path,g.params||(S.params=p.params,g.query||(S.query=p.query));else{var E=p.path,T=E.substring(0,E.lastIndexOf("/")+1)+g.path;S.path=d.normalizePath(T)}return S.path===null&&(S.path=h.alwaysNormalize?d.normalizePath(g.path):g.path),d.buildURLFromParts(S)},parseURL:function(u){var f=n.exec(u);return f?{scheme:f[1]||"",netLoc:f[2]||"",path:f[3]||"",params:f[4]||"",query:f[5]||"",fragment:f[6]||""}:null},normalizePath:function(u){for(u=u.split("").reverse().join("").replace(a,"");u.length!==(u=u.replace(c,"")).length;);return u.split("").reverse().join("")},buildURLFromParts:function(u){return u.scheme+u.netLoc+u.path+u.params+u.query+u.fragment}};e.exports=d})()})(qh)),qh.exports}var Qh=vG(),Yh=class{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}},Bt={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"},nS=class{constructor(e){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof e=="string"&&(e={url:e}),this.base=e,yG(this,"stats")}setByteRange(e,t){const r=e.split("@",2);let n;r.length===1?n=t?.byteRangeEndOffset||0:n=parseInt(r[1]),this._byteRange=[n,parseInt(r[0])+n]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[Bt.AUDIO]:null,[Bt.VIDEO]:null,[Bt.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(e){this._streams=e}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new Yh),this._stats}set stats(e){this._stats=e}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Qh.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Bt.AUDIO]=null,e[Bt.VIDEO]=null,e[Bt.AUDIOVIDEO]=null}};function ar(e){return e.sn!=="initSegment"}var Xh=class extends nS{constructor(e,t){super(t),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=e}get byteLength(){if(this.hasStats){const e=this.stats.total;if(e)return e}if(this.byteRange.length){const e=this.byteRange[0],t=this.byteRange[1];if(Ye(e)&&Ye(t))return t-e}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(e){this._bitrate=e}get decryptdata(){var e;const{levelkeys:t}=this;if(!t||t.NONE)return null;if(t.identity)this._decryptdata||(this._decryptdata=t.identity.getDecryptData(this.sn));else if(!((e=this._decryptdata)!=null&&e.keyId)){const r=Object.keys(t);if(r.length===1){const n=this._decryptdata=t[r[0]]||null;n&&(this._decryptdata=n.getDecryptData(this.sn,t))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const e=Ye(this.duration)?this.duration:0;return this.programDateTime+e*1e3}get encrypted(){var e;if((e=this._decryptdata)!=null&&e.encrypted)return!0;if(this.levelkeys){var t;const r=Object.keys(this.levelkeys),n=r.length;if(n>1||n===1&&(t=this.levelkeys[r[0]])!=null&&t.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(e){if(!Ye(e)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=e}get ref(){return ar(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(e){this.setStart(this.start+e)}setStart(e){this.start=e,this._ref&&(this._ref.start=e)}setDuration(e){this.duration=e,this._ref&&(this._ref.duration=e)}setKeyFormat(e){const t=this.levelkeys;if(t){var r;const n=t[e];n&&!((r=this._decryptdata)!=null&&r.keyId)&&(this._decryptdata=n.getDecryptData(this.sn,t))}}abortRequests(){var e,t;(e=this.loader)==null||e.abort(),(t=this.keyLoader)==null||t.abort()}setElementaryStreamInfo(e,t,r,n,s,a=!1){const{elementaryStreams:c}=this,d=c[e];if(!d){c[e]={startPTS:t,endPTS:r,startDTS:n,endDTS:s,partial:a};return}d.startPTS=Math.min(d.startPTS,t),d.endPTS=Math.max(d.endPTS,r),d.startDTS=Math.min(d.startDTS,n),d.endDTS=Math.max(d.endDTS,s)}},bG=class extends nS{constructor(e,t,r,n,s){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=t,this.index=n;const a=e.enumeratedString("BYTERANGE");a&&this.setByteRange(a,s),s&&(this.fragOffset=s.fragOffset+s.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:e}=this;return!!(e.audio||e.video||e.audiovideo)}};function iS(e,t){const r=Object.getPrototypeOf(e);if(r){const n=Object.getOwnPropertyDescriptor(r,t);return n||iS(r,t)}}function yG(e,t){const r=iS(e,t);r&&(r.enumerable=!0,Object.defineProperty(e,t,r))}var sS=Math.pow(2,32)-1,xG=[].push,aS={video:1,audio:2,id3:3,text:4};function gr(e){return String.fromCharCode.apply(null,e)}function oS(e,t){const r=e[t]<<8|e[t+1];return r<0?65536+r:r}function mt(e,t){const r=cS(e,t);return r<0?4294967296+r:r}function lS(e,t){let r=mt(e,t);return r*=Math.pow(2,32),r+=mt(e,t+4),r}function cS(e,t){return e[t]<<24|e[t+1]<<16|e[t+2]<<8|e[t+3]}function SG(e){const t=e.byteLength;for(let r=0;r<t;){const n=mt(e,r);if(n>8&&e[r+4]===109&&e[r+5]===111&&e[r+6]===111&&e[r+7]===102)return!0;r=n>1?r+n:t}return!1}function yt(e,t){const r=[];if(!t.length)return r;const n=e.byteLength;for(let s=0;s<n;){const a=mt(e,s),c=gr(e.subarray(s+4,s+8)),d=a>1?s+a:n;if(c===t[0])if(t.length===1)r.push(e.subarray(s+8,d));else{const u=yt(e.subarray(s+8,d),t.slice(1));u.length&&xG.apply(r,u)}s=d}return r}function _G(e){const t=[],r=e[0];let n=8;const s=mt(e,n);n+=4;let a=0,c=0;r===0?(a=mt(e,n),c=mt(e,n+4),n+=8):(a=lS(e,n),c=lS(e,n+8),n+=16),n+=2;let d=e.length+c;const u=oS(e,n);n+=2;for(let f=0;f<u;f++){let h=n;const m=mt(e,h);h+=4;const g=m&2147483647;if((m&2147483648)>>>31===1)return $t.warn("SIDX has hierarchical references (not supported)"),null;const p=mt(e,h);h+=4,t.push({referenceSize:g,subsegmentDuration:p,info:{duration:p/s,start:d,end:d+g-1}}),d+=g,h+=4,n=h}return{earliestPresentationTime:a,timescale:s,version:r,referencesCount:u,references:t}}function uS(e){const t=[],r=yt(e,["moov","trak"]);for(let n=0;n<r.length;n++){const s=r[n],a=yt(s,["tkhd"])[0];if(a){let c=a[0];const d=mt(a,c===0?12:20),u=yt(s,["mdia","mdhd"])[0];if(u){c=u[0];const f=mt(u,c===0?12:20),h=yt(s,["mdia","hdlr"])[0];if(h){const m=gr(h.subarray(8,12)),g={soun:Bt.AUDIO,vide:Bt.VIDEO}[m],p=yt(s,["mdia","minf","stbl","stsd"])[0],y=wG(p);g?(t[d]={timescale:f,type:g,stsd:y},t[g]=Mt({timescale:f,id:d},y)):t[d]={timescale:f,type:m,stsd:y}}}}}return yt(e,["moov","mvex","trex"]).forEach(n=>{const s=t[mt(n,4)];s&&(s.default={duration:mt(n,12),flags:mt(n,20)})}),t}function wG(e){const t=e.subarray(8),r=t.subarray(86),n=gr(t.subarray(4,8));let s=n,a;const c=n==="enca"||n==="encv";c&&yt(yt(t,[n])[0].subarray(n==="enca"?28:78),["sinf"]).forEach(u=>{const f=yt(u,["schm"])[0];if(f){const h=gr(f.subarray(4,8));if(h==="cbcs"||h==="cenc"){const m=yt(u,["frma"])[0];m&&(s=gr(m))}}});const d=s;switch(s){case"avc1":case"avc2":case"avc3":case"avc4":{const u=yt(r,["avcC"])[0];u&&u.length>3&&(s+="."+ac(u[1])+ac(u[2])+ac(u[3]),a=sc(d==="avc1"?"dva1":"dvav",r));break}case"mp4a":{const u=yt(t,[n])[0],f=yt(u.subarray(28),["esds"])[0];if(f&&f.length>7){let h=4;if(f[h++]!==3)break;h=Jh(f,h),h+=2;const m=f[h++];if(m&128&&(h+=2),m&64&&(h+=f[h++]),f[h++]!==4)break;h=Jh(f,h);const g=f[h++];if(g===64)s+="."+ac(g);else break;if(h+=12,f[h++]!==5)break;h=Jh(f,h);const p=f[h++];let y=(p&248)>>3;y===31&&(y+=1+((p&7)<<3)+((f[h]&224)>>5)),s+="."+y}break}case"hvc1":case"hev1":{const u=yt(r,["hvcC"])[0];if(u&&u.length>12){const f=u[1],h=["","A","B","C"][f>>6],m=f&31,g=mt(u,2),p=(f&32)>>5?"H":"L",y=u[12],S=u.subarray(6,12);s+="."+h+m,s+="."+EG(g).toString(16).toUpperCase(),s+="."+p+y;let E="";for(let T=S.length;T--;){const j=S[T];(j||E)&&(E="."+j.toString(16).toUpperCase()+E)}s+=E}a=sc(d=="hev1"?"dvhe":"dvh1",r);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":s=sc(s,r)||s;break;case"vp09":{const u=yt(r,["vpcC"])[0];if(u&&u.length>6){const f=u[4],h=u[5],m=u[6]>>4&15;s+="."+Cn(f)+"."+Cn(h)+"."+Cn(m)}break}case"av01":{const u=yt(r,["av1C"])[0];if(u&&u.length>2){const f=u[1]>>>5,h=u[1]&31,m=u[2]>>>7?"H":"M",g=(u[2]&64)>>6,p=(u[2]&32)>>5,y=f===2&&g?p?12:10:g?10:8,S=(u[2]&16)>>4,E=(u[2]&8)>>3,T=(u[2]&4)>>2,j=u[2]&3;s+="."+f+"."+Cn(h)+m+"."+Cn(y)+"."+S+"."+E+T+j+"."+Cn(1)+"."+Cn(1)+"."+Cn(1)+".0",a=sc("dav1",r)}break}}return{codec:s,encrypted:c,supplemental:a}}function sc(e,t){const r=yt(t,["dvvC"]),n=r.length?r[0]:yt(t,["dvcC"])[0];if(n){const s=n[2]>>1&127,a=n[2]<<5&32|n[3]>>3&31;return e+"."+Cn(s)+"."+Cn(a)}}function EG(e){let t=0;for(let r=0;r<32;r++)t|=(e>>r&1)<<31-r;return t>>>0}function Jh(e,t){const r=t+5;for(;e[t++]&128&&t<r;);return t}function ac(e){return("0"+e.toString(16).toUpperCase()).slice(-2)}function Cn(e){return(e<10?"0":"")+e}function kG(e,t){if(!e||!t)return;const r=t.keyId;r&&t.isCommonEncryption&&dS(e,(n,s)=>{const a=n.subarray(8,24);a.some(c=>c!==0)||($t.log(`[eme] Patching keyId in 'enc${s?"a":"v"}>sinf>>tenc' box: ${xr(a)} -> ${xr(r)}`),n.set(r,8))})}function TG(e){const t=[];return dS(e,r=>t.push(r.subarray(8,24))),t}function dS(e,t){yt(e,["moov","trak"]).forEach(r=>{const n=yt(r,["mdia","minf","stbl","stsd"])[0];if(!n)return;const s=n.subarray(8);let a=yt(s,["enca"]);const c=a.length>0;c||(a=yt(s,["encv"])),a.forEach(d=>{yt(c?d.subarray(28):d.subarray(78),["sinf"]).forEach(u=>{const f=fS(u);f&&t(f,c)})})})}function fS(e){const t=yt(e,["schm"])[0];if(t){const r=gr(t.subarray(4,8));if(r==="cbcs"||r==="cenc"){const n=yt(e,["schi","tenc"])[0];if(n)return n}}}function CG(e,t,r){const n={},s=yt(e,["moof","traf"]);for(let a=0;a<s.length;a++){const c=s[a],d=yt(c,["tfhd"])[0],u=mt(d,4),f=t[u];if(!f)continue;n[u]||(n[u]={start:NaN,duration:0,sampleCount:0,timescale:f.timescale,type:f.type});const h=n[u],m=yt(c,["tfdt"])[0];if(m){const N=m[0];let O=mt(m,4);N===1&&(O===sS?r.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"):(O*=sS+1,O+=mt(m,8))),Ye(O)&&(!Ye(h.start)||O<h.start)&&(h.start=O)}const g=f.default,p=mt(d,0)|g?.flags;let y=g?.duration||0;p&8&&(p&2?y=mt(d,12):y=mt(d,8));const S=yt(c,["trun"]);let E=h.start||0,T=0,j=y;for(let N=0;N<S.length;N++){const O=S[N],U=mt(O,4),z=h.sampleCount;h.sampleCount+=U;const K=O[3]&1,G=O[3]&4,X=O[2]&1,te=O[2]&2,ne=O[2]&4,ae=O[2]&8;let oe=8,pe=U;for(K&&(oe+=4),G&&U&&(!(O[oe+1]&1)&&h.keyFrameIndex===void 0&&(h.keyFrameIndex=z),oe+=4,X?(j=mt(O,oe),oe+=4):j=y,te&&(oe+=4),ae&&(oe+=4),E+=j,T+=j,pe--);pe--;)X?(j=mt(O,oe),oe+=4):j=y,te&&(oe+=4),ne&&(O[oe+1]&1||h.keyFrameIndex===void 0&&(h.keyFrameIndex=h.sampleCount-(pe+1),h.keyFrameStart=E),oe+=4),ae&&(oe+=4),E+=j,T+=j;!T&&y&&(T+=y*U)}h.duration+=T}if(!Object.keys(n).some(a=>n[a].duration)){let a=1/0,c=0;const d=yt(e,["sidx"]);for(let u=0;u<d.length;u++){const f=_G(d[u]);if(f!=null&&f.references){a=Math.min(a,f.earliestPresentationTime/f.timescale);const h=f.references.reduce((m,g)=>m+g.info.duration||0,0);c=Math.max(c,h+f.earliestPresentationTime/f.timescale)}}c&&Ye(c)&&Object.keys(n).forEach(u=>{n[u].duration||(n[u].duration=c*n[u].timescale-n[u].start)})}return n}function IG(e){const t={valid:null,remainder:null},r=yt(e,["moof"]);if(r.length<2)return t.remainder=e,t;const n=r[r.length-1];return t.valid=e.slice(0,n.byteOffset-8),t.remainder=e.slice(n.byteOffset-8),t}function nn(e,t){const r=new Uint8Array(e.length+t.length);return r.set(e),r.set(t,e.length),r}function hS(e,t){const r=[],n=t.samples,s=t.timescale,a=t.id;let c=!1;return yt(n,["moof"]).map(d=>{const u=d.byteOffset-8;yt(d,["traf"]).map(f=>{const h=yt(f,["tfdt"]).map(m=>{const g=m[0];let p=mt(m,4);return g===1&&(p*=Math.pow(2,32),p+=mt(m,8)),p/s})[0];return h!==void 0&&(e=h),yt(f,["tfhd"]).map(m=>{const g=mt(m,4),p=mt(m,0)&16777215,y=(p&1)!==0,S=(p&2)!==0,E=(p&8)!==0;let T=0;const j=(p&16)!==0;let N=0;const O=(p&32)!==0;let U=8;g===a&&(y&&(U+=8),S&&(U+=4),E&&(T=mt(m,U),U+=4),j&&(N=mt(m,U),U+=4),O&&(U+=4),t.type==="video"&&(c=oc(t.codec)),yt(f,["trun"]).map(z=>{const K=z[0],G=mt(z,0)&16777215,X=(G&1)!==0;let te=0;const ne=(G&4)!==0,ae=(G&256)!==0;let oe=0;const pe=(G&512)!==0;let le=0;const se=(G&1024)!==0,Ce=(G&2048)!==0;let q=0;const Q=mt(z,4);let ie=8;X&&(te=mt(z,ie),ie+=4),ne&&(ie+=4);let be=te+u;for(let we=0;we<Q;we++){if(ae?(oe=mt(z,ie),ie+=4):oe=T,pe?(le=mt(z,ie),ie+=4):le=N,se&&(ie+=4),Ce&&(K===0?q=mt(z,ie):q=cS(z,ie),ie+=4),t.type===Bt.VIDEO){let Re=0;for(;Re<le;){const Ee=mt(n,be);be+=4,PG(c,n[be])&&em(n.subarray(be,be+Ee),c?2:1,e+q/s,r),be+=Ee,Re+=Ee+4}}e+=oe/s}}))})})}),r}function oc(e){if(!e)return!1;const t=e.substring(0,4);return t==="hvc1"||t==="hev1"||t==="dvh1"||t==="dvhe"}function PG(e,t){if(e){const r=t>>1&63;return r===39||r===40}else return(t&31)===6}function em(e,t,r,n){const s=mS(e);let a=0;a+=t;let c=0,d=0,u=0;for(;a<s.length;){c=0;do{if(a>=s.length)break;u=s[a++],c+=u}while(u===255);d=0;do{if(a>=s.length)break;u=s[a++],d+=u}while(u===255);const f=s.length-a;let h=a;if(d<f)a+=d;else if(d>f){$t.error(`Malformed SEI payload. ${d} is too small, only ${f} bytes left to parse.`);break}if(c===4){if(s[h++]===181){const m=oS(s,h);if(h+=2,m===49){const g=mt(s,h);if(h+=4,g===1195456820){const p=s[h++];if(p===3){const y=s[h++],S=31&y,E=64&y,T=E?2+S*3:0,j=new Uint8Array(T);if(E){j[0]=y;for(let N=1;N<T;N++)j[N]=s[h++]}n.push({type:p,payloadType:c,pts:r,bytes:j})}}}}}else if(c===5&&d>16){const m=[];for(let y=0;y<16;y++){const S=s[h++].toString(16);m.push(S.length==1?"0"+S:S),(y===3||y===5||y===7||y===9)&&m.push("-")}const g=d-16,p=new Uint8Array(g);for(let y=0;y<g;y++)p[y]=s[h++];n.push({payloadType:c,pts:r,uuid:m.join(""),userData:Gr(p),userDataBytes:p})}}}function mS(e){const t=e.byteLength,r=[];let n=1;for(;n<t-2;)e[n]===0&&e[n+1]===0&&e[n+2]===3?(r.push(n+2),n+=2):n++;if(r.length===0)return e;const s=t-r.length,a=new Uint8Array(s);let c=0;for(n=0;n<s;c++,n++)c===r[0]&&(c++,r.shift()),a[n]=e[c];return a}function AG(e){const t=e[0];let r="",n="",s=0,a=0,c=0,d=0,u=0,f=0;if(t===0){for(;gr(e.subarray(f,f+1))!=="\0";)r+=gr(e.subarray(f,f+1)),f+=1;for(r+=gr(e.subarray(f,f+1)),f+=1;gr(e.subarray(f,f+1))!=="\0";)n+=gr(e.subarray(f,f+1)),f+=1;n+=gr(e.subarray(f,f+1)),f+=1,s=mt(e,12),a=mt(e,16),d=mt(e,20),u=mt(e,24),f=28}else if(t===1){f+=4,s=mt(e,f),f+=4;const m=mt(e,f);f+=4;const g=mt(e,f);for(f+=4,c=2**32*m+g,aG(c)||(c=Number.MAX_SAFE_INTEGER,$t.warn("Presentation time exceeds safe integer limit and wrapped to max safe integer in parsing emsg box")),d=mt(e,f),f+=4,u=mt(e,f),f+=4;gr(e.subarray(f,f+1))!=="\0";)r+=gr(e.subarray(f,f+1)),f+=1;for(r+=gr(e.subarray(f,f+1)),f+=1;gr(e.subarray(f,f+1))!=="\0";)n+=gr(e.subarray(f,f+1)),f+=1;n+=gr(e.subarray(f,f+1)),f+=1}const h=e.subarray(f,e.byteLength);return{schemeIdUri:r,value:n,timeScale:s,presentationTime:c,presentationTimeDelta:a,eventDuration:d,id:u,payload:h}}function jG(e,...t){const r=t.length;let n=8,s=r;for(;s--;)n+=t[s].byteLength;const a=new Uint8Array(n);for(a[0]=n>>24&255,a[1]=n>>16&255,a[2]=n>>8&255,a[3]=n&255,a.set(e,4),s=0,n=8;s<r;s++)a.set(t[s],n),n+=t[s].byteLength;return a}function NG(e,t,r){if(e.byteLength!==16)throw new RangeError("Invalid system id");let n,s;n=0,s=new Uint8Array;let a;n>0?(a=new Uint8Array(4),t.length>0&&new DataView(a.buffer).setUint32(0,t.length,!1)):a=new Uint8Array;const c=new Uint8Array(4);return r.byteLength>0&&new DataView(c.buffer).setUint32(0,r.byteLength,!1),jG([112,115,115,104],new Uint8Array([n,0,0,0]),e,a,s,c,r)}function DG(e){const t=[];if(e instanceof ArrayBuffer){const r=e.byteLength;let n=0;for(;n+32<r;){const s=MG(new DataView(e,n));t.push(s),n+=s.size}}return t}function MG(e){const t=e.getUint32(0),r=e.byteOffset,n=e.byteLength;if(n<t)return{offset:r,size:n};if(e.getUint32(4)!==1886614376)return{offset:r,size:t};const s=e.getUint32(8)>>>24;if(s!==0&&s!==1)return{offset:r,size:t};const a=e.buffer,c=xr(new Uint8Array(a,r+12,16));let d=null,u=null,f=0;if(s===0)f=28;else{const m=e.getUint32(28);if(!m||n<32+m*16)return{offset:r,size:t};d=[];for(let g=0;g<m;g++)d.push(new Uint8Array(a,r+32+g*16,16));f=32+m*16}if(!f)return{offset:r,size:t};const h=e.getUint32(f);return t-32<h?{offset:r,size:t}:(u=new Uint8Array(a,r+f+4,h),{version:s,systemId:c,kids:d,data:u,offset:r,size:t})}var gS=()=>/\(Windows.+Firefox\//i.test(navigator.userAgent),_s={audio:{a3ds:1,"ac-3":.95,"ac-4":1,alac:.9,alaw:1,dra1:1,"dts+":1,"dts-":1,dtsc:1,dtse:1,dtsh:1,"ec-3":.9,enca:1,fLaC:.9,flac:.9,FLAC:.9,g719:1,g726:1,m4ae:1,mha1:1,mha2:1,mhm1:1,mhm2:1,mlpa:1,mp4a:1,"raw ":1,Opus:1,opus:1,samr:1,sawb:1,sawp:1,sevc:1,sqcp:1,ssmv:1,twos:1,ulaw:1},video:{avc1:1,avc2:1,avc3:1,avc4:1,avcp:1,av01:.8,dav1:.8,drac:1,dva1:1,dvav:1,dvh1:.7,dvhe:.7,encv:1,hev1:.75,hvc1:.75,mjp2:1,mp4v:1,mvc1:1,mvc2:1,mvc3:1,mvc4:1,resv:1,rv60:1,s263:1,svc1:1,svc2:1,"vc-1":1,vp08:1,vp09:.9},text:{stpp:1,wvtt:1}};function tm(e,t){const r=_s[t];return!!r&&!!r[e.slice(0,4)]}function ko(e,t,r=!0){return!e.split(",").some(n=>!rm(n,t,r))}function rm(e,t,r=!0){var n;const s=di(r);return(n=s?.isTypeSupported(To(e,t)))!=null?n:!1}function To(e,t){return`${t}/mp4;codecs=${e}`}function pS(e){if(e){const t=e.substring(0,4);return _s.video[t]}return 2}function lc(e){const t=gS();return e.split(",").reduce((r,n)=>{const s=t&&oc(n)?9:_s.video[n];return s?(s*2+r)/(r?3:2):(_s.audio[n]+r)/(r?2:1)},0)}var nm={};function $G(e,t=!0){if(nm[e])return nm[e];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[e];for(let s=0;s<r.length;s++){var n;if(rm(r[s],"audio",t))return nm[e]=r[s],r[s];if(r[s]==="mp3"&&(n=di(t))!=null&&n.isTypeSupported("audio/mpeg"))return""}return e}var RG=/flac|opus|mp4a\.40\.34/i;function cc(e,t=!0){return e.replace(RG,r=>$G(r.toLowerCase(),t))}function LG(e,t){const r=[];if(e){const n=e.split(",");for(let s=0;s<n.length;s++)tm(n[s],"video")||r.push(n[s])}return t&&r.push(t),r.join(",")}function uc(e,t){if(e&&(e.length>4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(e)!==-1)&&(vS(e,"audio")||vS(e,"video")))return e;if(t){const r=t.split(",");if(r.length>1){if(e){for(let n=r.length;n--;)if(r[n].substring(0,4)===e.substring(0,4))return r[n]}return r[0]}}return t||e}function vS(e,t){return tm(e,t)&&rm(e,t)}function OG(e){const t=e.split(",");for(let r=0;r<t.length;r++){const n=t[r].split(".");n.length>2&&n[0]==="avc1"&&(t[r]=`avc1.${parseInt(n[1]).toString(16)}${("000"+parseInt(n[2]).toString(16)).slice(-4)}`)}return t.join(",")}function FG(e){if(e.startsWith("av01.")){const t=e.split("."),r=["0","111","01","01","01","0"];for(let n=t.length;n>4&&n<10;n++)t[n]=r[n-4];return t.join(".")}return e}function bS(e){const t=di(e)||{isTypeSupported:()=>!1};return{mpeg:t.isTypeSupported("audio/mpeg"),mp3:t.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:t.isTypeSupported('audio/mp4; codecs="ac-3"')}}function im(e){return e.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}var UG={supported:!0,powerEfficient:!0,smooth:!0},BG={supported:!1,smooth:!1,powerEfficient:!1},yS={supported:!0,configurations:[],decodingInfoResults:[UG]};function xS(e,t){return{supported:!1,configurations:t,decodingInfoResults:[BG],error:e}}function zG(e,t,r,n,s,a){const c=e.videoCodec,d=e.audioCodec?e.audioGroups:null,u=a?.audioCodec,f=a?.channels,h=f?parseInt(f):u?1/0:2;let m=null;if(d!=null&&d.length)try{d.length===1&&d[0]?m=t.groups[d[0]].channels:m=d.reduce((g,p)=>{if(p){const y=t.groups[p];if(!y)throw new Error(`Audio track group ${p} not found`);Object.keys(y.channels).forEach(S=>{g[S]=(g[S]||0)+y.channels[S]})}return g},{2:0})}catch{return!0}return c!==void 0&&(c.split(",").some(g=>oc(g))||e.width>1920&&e.height>1088||e.height>1920&&e.width>1088||e.frameRate>Math.max(n,30)||e.videoRange!=="SDR"&&e.videoRange!==r||e.bitrate>Math.max(s,8e6))||!!m&&Ye(h)&&Object.keys(m).some(g=>parseInt(g)>h)}function SS(e,t,r,n={}){const s=e.videoCodec;if(!s&&!e.audioCodec||!r)return Promise.resolve(yS);const a=[],c=GG(e),d=c.length,u=ZG(e,t,d>0),f=u.length;for(let h=d||1*f||1;h--;){const m={type:"media-source"};if(d&&(m.video=c[h%d]),f){m.audio=u[h%f];const g=m.audio.bitrate;m.video&&g&&(m.video.bitrate-=g)}a.push(m)}if(s){const h=navigator.userAgent;if(s.split(",").some(m=>oc(m))&&gS())return Promise.resolve(xS(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${h})`),a))}return Promise.all(a.map(h=>{const m=HG(h);return n[m]||(n[m]=r.decodingInfo(h))})).then(h=>({supported:!h.some(m=>!m.supported),configurations:a,decodingInfoResults:h})).catch(h=>({supported:!1,configurations:a,decodingInfoResults:[],error:h}))}function GG(e){var t;const r=(t=e.videoCodec)==null?void 0:t.split(","),n=_S(e),s=e.width||640,a=e.height||480,c=e.frameRate||30,d=e.videoRange.toLowerCase();return r?r.map(u=>{const f={contentType:To(FG(u),"video"),width:s,height:a,bitrate:n,framerate:c};return d!=="sdr"&&(f.transferFunction=d),f}):[]}function ZG(e,t,r){var n;const s=(n=e.audioCodec)==null?void 0:n.split(","),a=_S(e);return s&&e.audioGroups?e.audioGroups.reduce((c,d)=>{var u;const f=d?(u=t.groups[d])==null?void 0:u.tracks:null;return f?f.reduce((h,m)=>{if(m.groupId===d){const g=parseFloat(m.channels||"");s.forEach(p=>{const y={contentType:To(p,"audio"),bitrate:r?VG(p,a):a};g&&(y.channels=""+g),h.push(y)})}return h},c):c},[]):[]}function VG(e,t){if(t<=1)return 1;let r=128e3;return e==="ec-3"?r=768e3:e==="ac-3"&&(r=64e4),Math.min(t/2,r)}function _S(e){return Math.ceil(Math.max(e.bitrate*.9,e.averageBitrate)/1e3)*1e3||1}function HG(e){let t="";const{audio:r,video:n}=e;if(n){const s=im(n.contentType);t+=`${s}_r${n.height}x${n.width}f${Math.ceil(n.framerate)}${n.transferFunction||"sd"}_${Math.ceil(n.bitrate/1e5)}`}if(r){const s=im(r.contentType);t+=`${n?"_":""}${s}_c${r.channels}`}return t}var sm=["NONE","TYPE-0","TYPE-1",null];function KG(e){return sm.indexOf(e)>-1}var dc=["SDR","PQ","HLG"];function WG(e){return!!e&&dc.indexOf(e)>-1}var fc={No:"",Yes:"YES",v2:"v2"};function wS(e){const{canSkipUntil:t,canSkipDateRanges:r,age:n}=e,s=n<t/2;return t&&s?r?fc.v2:fc.Yes:fc.No}var ES=class{constructor(e,t,r){this.msn=void 0,this.part=void 0,this.skip=void 0,this.msn=e,this.part=t,this.skip=r}addDirectives(e){const t=new self.URL(e);return this.msn!==void 0&&t.searchParams.set("_HLS_msn",this.msn.toString()),this.part!==void 0&&t.searchParams.set("_HLS_part",this.part.toString()),this.skip&&t.searchParams.set("_HLS_skip",this.skip),t.href}},Co=class{constructor(e){if(this._attrs=void 0,this.audioCodec=void 0,this.bitrate=void 0,this.codecSet=void 0,this.url=void 0,this.frameRate=void 0,this.height=void 0,this.id=void 0,this.name=void 0,this.supplemental=void 0,this.videoCodec=void 0,this.width=void 0,this.details=void 0,this.fragmentError=0,this.loadError=0,this.loaded=void 0,this.realBitrate=0,this.supportedPromise=void 0,this.supportedResult=void 0,this._avgBitrate=0,this._audioGroups=void 0,this._subtitleGroups=void 0,this._urlId=0,this.url=[e.url],this._attrs=[e.attrs],this.bitrate=e.bitrate,e.details&&(this.details=e.details),this.id=e.id||0,this.name=e.name,this.width=e.width||0,this.height=e.height||0,this.frameRate=e.attrs.optionalFloat("FRAME-RATE",0),this._avgBitrate=e.attrs.decimalInteger("AVERAGE-BANDWIDTH"),this.audioCodec=e.audioCodec,this.videoCodec=e.videoCodec,this.codecSet=[e.videoCodec,e.audioCodec].filter(r=>!!r).map(r=>r.substring(0,4)).join(","),"supplemental"in e){var t;this.supplemental=e.supplemental;const r=(t=e.supplemental)==null?void 0:t.videoCodec;r&&r!==e.videoCodec&&(this.codecSet+=`,${r.substring(0,4)}`)}this.addGroupId("audio",e.attrs.AUDIO),this.addGroupId("text",e.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(e){return kS(this._audioGroups,e)}hasSubtitleGroup(e){return kS(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,t){if(t){if(e==="audio"){let r=this._audioGroups;r||(r=this._audioGroups=[]),r.indexOf(t)===-1&&r.push(t)}else if(e==="text"){let r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),r.indexOf(t)===-1&&r.push(t)}}}get urlId(){return 0}set urlId(e){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var e;return(e=this.audioGroups)==null?void 0:e[0]}get textGroupId(){var e;return(e=this.subtitleGroups)==null?void 0:e[0]}addFallback(){}};function kS(e,t){return!t||!e?!1:e.indexOf(t)!==-1}function qG(){if(typeof matchMedia=="function"){const e=matchMedia("(dynamic-range: high)"),t=matchMedia("bad query");if(e.media!==t.media)return e.matches===!0}return!1}function QG(e,t){let r=!1,n=[];if(e&&(r=e!=="SDR",n=[e]),t){n=t.allowedVideoRanges||dc.slice(0);const s=n.join("")!=="SDR"&&!t.videoCodec;r=t.preferHDR!==void 0?t.preferHDR:s&&qG(),r||(n=["SDR"])}return{preferHDR:r,allowedVideoRanges:n}}var YG=e=>{const t=new WeakSet;return(r,n)=>{if(e&&(n=e(r,n)),typeof n=="object"&&n!==null){if(t.has(n))return;t.add(n)}return n}},zt=(e,t)=>JSON.stringify(e,YG(t));function XG(e,t,r,n,s){const a=Object.keys(e),c=n?.channels,d=n?.audioCodec,u=s?.videoCodec,f=c&&parseInt(c)===2;let h=!1,m=!1,g=1/0,p=1/0,y=1/0,S=1/0,E=0,T=[];const{preferHDR:j,allowedVideoRanges:N}=QG(t,s);for(let K=a.length;K--;){const G=e[a[K]];h||(h=G.channels[2]>0),g=Math.min(g,G.minHeight),p=Math.min(p,G.minFramerate),y=Math.min(y,G.minBitrate),N.filter(X=>G.videoRanges[X]>0).length>0&&(m=!0)}g=Ye(g)?g:0,p=Ye(p)?p:0;const O=Math.max(1080,g),U=Math.max(30,p);y=Ye(y)?y:r,r=Math.max(y,r),m||(t=void 0);const z=a.length>1;return{codecSet:a.reduce((K,G)=>{const X=e[G];if(G===K)return K;if(T=m?N.filter(te=>X.videoRanges[te]>0):[],z){if(X.minBitrate>r)return In(G,`min bitrate of ${X.minBitrate} > current estimate of ${r}`),K;if(!X.hasDefaultAudio)return In(G,"no renditions with default or auto-select sound found"),K;if(d&&G.indexOf(d.substring(0,4))%5!==0)return In(G,`audio codec preference "${d}" not found`),K;if(c&&!f){if(!X.channels[c])return In(G,`no renditions with ${c} channel sound found (channels options: ${Object.keys(X.channels)})`),K}else if((!d||f)&&h&&X.channels[2]===0)return In(G,"no renditions with stereo sound found"),K;if(X.minHeight>O)return In(G,`min resolution of ${X.minHeight} > maximum of ${O}`),K;if(X.minFramerate>U)return In(G,`min framerate of ${X.minFramerate} > maximum of ${U}`),K;if(!T.some(te=>X.videoRanges[te]>0))return In(G,`no variants with VIDEO-RANGE of ${zt(T)} found`),K;if(u&&G.indexOf(u.substring(0,4))%5!==0)return In(G,`video codec preference "${u}" not found`),K;if(X.maxScore<E)return In(G,`max score of ${X.maxScore} < selected max of ${E}`),K}return K&&(lc(G)>=lc(K)||X.fragmentError>e[K].fragmentError)?K:(S=X.minIndex,E=X.maxScore,G)},void 0),videoRanges:T,preferHDR:j,minFramerate:p,minBitrate:y,minIndex:S}}function In(e,t){$t.log(`[abr] start candidates with "${e}" ignored because ${t}`)}function TS(e){return e.reduce((t,r)=>{let n=t.groups[r.groupId];n||(n=t.groups[r.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),n.tracks.push(r);const s=r.channels||"2";return n.channels[s]=(n.channels[s]||0)+1,n.hasDefault=n.hasDefault||r.default,n.hasAutoSelect=n.hasAutoSelect||r.autoselect,n.hasDefault&&(t.hasDefaultAudio=!0),n.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function JG(e,t,r,n){return e.slice(r,n+1).reduce((s,a,c)=>{if(!a.codecSet)return s;const d=a.audioGroups;let u=s[a.codecSet];u||(s[a.codecSet]=u={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:c,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!d,fragmentError:0}),u.minBitrate=Math.min(u.minBitrate,a.bitrate);const f=Math.min(a.height,a.width);return u.minHeight=Math.min(u.minHeight,f),u.minFramerate=Math.min(u.minFramerate,a.frameRate),u.minIndex=Math.min(u.minIndex,c),u.maxScore=Math.max(u.maxScore,a.score),u.fragmentError+=a.fragmentError,u.videoRanges[a.videoRange]=(u.videoRanges[a.videoRange]||0)+1,d&&d.forEach(h=>{if(!h)return;const m=t.groups[h];m&&(u.hasDefaultAudio=u.hasDefaultAudio||t.hasDefaultAudio?m.hasDefault:m.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(m.channels).forEach(g=>{u.channels[g]=(u.channels[g]||0)+m.channels[g]}))}),s},{})}function CS(e){if(!e)return e;const{lang:t,assocLang:r,characteristics:n,channels:s,audioCodec:a}=e;return{lang:t,assocLang:r,characteristics:n,channels:s,audioCodec:a}}function Pn(e,t,r){if("attrs"in e){const n=t.indexOf(e);if(n!==-1)return n}for(let n=0;n<t.length;n++){const s=t[n];if(Li(e,s,r))return n}return-1}function Li(e,t,r){const{groupId:n,name:s,lang:a,assocLang:c,default:d}=e,u=e.forced;return(n===void 0||t.groupId===n)&&(s===void 0||t.name===s)&&(a===void 0||e8(a,t.lang))&&(a===void 0||t.assocLang===c)&&(d===void 0||t.default===d)&&(u===void 0||t.forced===u)&&(!("characteristics"in e)||t8(e.characteristics||"",t.characteristics))&&(r===void 0||r(e,t))}function e8(e,t="--"){return e.length===t.length?e===t:e.startsWith(t)||t.startsWith(e)}function t8(e,t=""){const r=e.split(","),n=t.split(",");return r.length===n.length&&!r.some(s=>n.indexOf(s)===-1)}function Oi(e,t){const{audioCodec:r,channels:n}=e;return(r===void 0||(t.audioCodec||"").substring(0,4)===r.substring(0,4))&&(n===void 0||n===(t.channels||"2"))}function r8(e,t,r,n,s){const a=t[n],c=t.reduce((m,g,p)=>{const y=g.uri;return(m[y]||(m[y]=[])).push(p),m},{})[a.uri];c.length>1&&(n=Math.max.apply(Math,c));const d=a.videoRange,u=a.frameRate,f=a.codecSet.substring(0,4),h=IS(t,n,m=>{if(m.videoRange!==d||m.frameRate!==u||m.codecSet.substring(0,4)!==f)return!1;const g=m.audioGroups;return Pn(e,r.filter(p=>!g||g.indexOf(p.groupId)!==-1),s)>-1});return h>-1?h:IS(t,n,m=>{const g=m.audioGroups;return Pn(e,r.filter(p=>!g||g.indexOf(p.groupId)!==-1),s)>-1})}function IS(e,t,r){for(let n=t;n>-1;n--)if(r(e[n]))return n;for(let n=t+1;n<e.length;n++)if(r(e[n]))return n;return-1}function hc(e,t){var r;return!!e&&e!==((r=t.loadLevelObj)==null?void 0:r.uri)}var n8=class extends rn{constructor(e){super("abr",e.logger),this.hls=void 0,this.lastLevelLoadSec=0,this.lastLoadedFragLevel=-1,this.firstSelection=-1,this._nextAutoLevel=-1,this.nextAutoLevelKey="",this.audioTracksByGroup=null,this.codecTiers=null,this.timer=-1,this.fragCurrent=null,this.partCurrent=null,this.bitrateTestDelay=0,this.rebufferNotice=-1,this.supportedCache={},this.bwEstimator=void 0,this._abandonRulesCheck=t=>{var r;const{fragCurrent:n,partCurrent:s,hls:a}=this,{autoLevelEnabled:c,media:d}=a;if(!n||!d)return;const u=performance.now(),f=s?s.stats:n.stats,h=s?s.duration:n.duration,m=u-f.loading.start,g=a.minAutoLevel,p=n.level,y=this._nextAutoLevel;if(f.aborted||f.loaded&&f.loaded===f.total||p<=g){this.clearTimer(),this._nextAutoLevel=-1;return}if(!c)return;const S=y>-1&&y!==p,E=!!t||S;if(!E&&(d.paused||!d.playbackRate||!d.readyState))return;const T=a.mainForwardBufferInfo;if(!E&&T===null)return;const j=this.bwEstimator.getEstimateTTFB(),N=Math.abs(d.playbackRate);if(m<=Math.max(j,1e3*(h/(N*2))))return;const O=T?T.len/N:0,U=f.loading.first?f.loading.first-f.loading.start:-1,z=f.loaded&&U>-1,K=this.getBwEstimate(),G=a.levels,X=G[p],te=Math.max(f.loaded,Math.round(h*(n.bitrate||X.averageBitrate)/8));let ne=z?m-U:m;ne<1&&z&&(ne=Math.min(m,f.loaded*8/K));const ae=z?f.loaded*1e3/ne:0,oe=j/1e3,pe=ae?(te-f.loaded)/ae:te*8/K+oe;if(pe<=O)return;const le=ae?ae*8:K,se=((r=t?.details||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,Ce=this.hls.config.abrBandWidthUpFactor;let q=Number.POSITIVE_INFINITY,Q;for(Q=p-1;Q>g;Q--){const Re=G[Q].maxBitrate,Ee=!G[Q].details||se;if(q=this.getTimeToLoadFrag(oe,le,h*Re,Ee),q<Math.min(O,h+oe))break}if(q>=pe||q>h*10)return;z?this.bwEstimator.sample(m-Math.min(j,U),f.loaded):this.bwEstimator.sampleTTFB(m);const ie=G[Q].maxBitrate;this.getBwEstimate()*Ce>ie&&this.resetEstimator(ie);const be=this.findBestLevel(ie,g,Q,0,O,1,1);be>-1&&(Q=be),this.warn(`Fragment ${n.sn}${s?" part "+s.index:""} of level ${p} is loading too slowly;
150
+ Fragment duration: ${n.duration.toFixed(3)}
151
+ Time to underbuffer: ${O.toFixed(3)} s
152
+ Estimated load time for current fragment: ${pe.toFixed(3)} s
153
+ Estimated load time for down switch fragment: ${q.toFixed(3)} s
154
+ TTFB estimate: ${U|0} ms
155
+ Current BW estimate: ${Ye(K)?K|0:"Unknown"} bps
156
+ New BW estimate: ${this.getBwEstimate()|0} bps
157
+ Switching to level ${Q} @ ${ie|0} bps`),a.nextLoadLevel=a.nextAutoLevel=Q,this.clearTimer();const we=()=>{if(this.clearTimer(),this.fragCurrent===n&&this.hls.loadLevel===Q&&Q>0){const Re=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${Q>0?"and switching down":""}
158
+ Fragment duration: ${n.duration.toFixed(3)} s
159
+ Time to underbuffer: ${Re.toFixed(3)} s`),n.abortRequests(),this.fragCurrent=this.partCurrent=null,Q>g){let Ee=this.findBestLevel(this.hls.levels[g].bitrate,g,Q,0,Re,1,1);Ee===-1&&(Ee=g),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Ee,this.resetEstimator(this.hls.levels[Ee].bitrate)}}};S||pe>q*2?we():this.timer=self.setInterval(we,q*1e3),a.trigger($.FRAG_LOAD_EMERGENCY_ABORTED,{frag:n,part:s,stats:f})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(this.log(`setting initial bwe to ${e}`),this.hls.config.abrEwmaDefaultEstimate=e),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const e=this.hls.config;return new lG(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.FRAG_LOADING,this.onFragLoading,this),e.on($.FRAG_LOADED,this.onFragLoaded,this),e.on($.FRAG_BUFFERED,this.onFragBuffered,this),e.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on($.LEVEL_LOADED,this.onLevelLoaded,this),e.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on($.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.FRAG_LOADING,this.onFragLoading,this),e.off($.FRAG_LOADED,this.onFragLoaded,this),e.off($.FRAG_BUFFERED,this.onFragBuffered,this),e.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off($.LEVEL_LOADED,this.onLevelLoaded,this),e.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off($.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off($.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,t){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(e,t){const r=t.frag;if(!this.ignoreFragment(r)){if(!r.bitrateTest){var n;this.fragCurrent=r,this.partCurrent=(n=t.part)!=null?n:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,t){this.clearTimer()}onError(e,t){if(!t.fatal)switch(t.details){case fe.BUFFER_ADD_CODEC_ERROR:case fe.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case fe.FRAG_LOAD_TIMEOUT:{const r=t.frag,{fragCurrent:n,partCurrent:s}=this;if(r&&n&&r.sn===n.sn&&r.level===n.level){const a=performance.now(),c=s?s.stats:r.stats,d=a-c.loading.start,u=c.loading.first?c.loading.first-c.loading.start:-1;if(c.loaded&&u>-1){const f=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(d-Math.min(f,u),c.loaded)}else this.bwEstimator.sampleTTFB(d)}break}}}getTimeToLoadFrag(e,t,r,n){return e+r/t+(n?e+this.lastLevelLoadSec:0)}onLevelLoaded(e,t){const r=this.hls.config,{loading:n}=t.stats,s=n.end-n.first;Ye(s)&&(this.lastLevelLoadSec=s/1e3),t.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(t.levelInfo)}onFragLoaded(e,{frag:t,part:r}){const n=r?r.stats:t.stats;if(t.type===Je.MAIN&&this.bwEstimator.sampleTTFB(n.loading.first-n.loading.start),!this.ignoreFragment(t)){if(this.clearTimer(),t.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const s=r?r.duration:t.duration,a=this.hls.levels[t.level],c=(a.loaded?a.loaded.bytes:0)+n.loaded,d=(a.loaded?a.loaded.duration:0)+s;a.loaded={bytes:c,duration:d},a.realBitrate=Math.round(8*c/d)}if(t.bitrateTest){const s={stats:n,frag:t,part:r,id:t.type};this.onFragBuffered($.FRAG_BUFFERED,s),t.bitrateTest=!1}else this.lastLoadedFragLevel=t.level}}onFragBuffered(e,t){const{frag:r,part:n}=t,s=n!=null&&n.stats.loaded?n.stats:r.stats;if(s.aborted||this.ignoreFragment(r))return;const a=s.parsing.end-s.loading.start-Math.min(s.loading.first-s.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(a,s.loaded),s.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==Je.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:t}=this.hls,r=this.getBwEstimate(),n=this.hls.config.maxStarvationDelay,s=this.findBestLevel(r,t,e,0,n,1,1);if(s>-1)return s;const a=this.hls.firstLevel,c=Math.min(Math.max(a,t),e);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${c}`),c}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,t=this.bwEstimator.canEstimate(),r=this.lastLoadedFragLevel>-1;if(e!==-1&&(!t||!r||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const n=t&&r?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const s=this.hls.levels;if(s.length>Math.max(e,n)&&s[e].loadError<=s[n].loadError)return e}return this._nextAutoLevel=n,this.nextAutoLevelKey=this.getAutoLevelKey(),n}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:t,hls:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:n,config:s,minAutoLevel:a}=r,c=t?t.duration:e?e.duration:0,d=this.getBwEstimate(),u=this.getStarvationDelay();let f=s.abrBandWidthFactor,h=s.abrBandWidthUpFactor;if(u){const S=this.findBestLevel(d,a,n,u,0,f,h);if(S>=0)return this.rebufferNotice=-1,S}let m=c?Math.min(c,s.maxStarvationDelay):s.maxStarvationDelay;if(!u){const S=this.bitrateTestDelay;S&&(m=(c?Math.min(c,s.maxLoadingDelay):s.maxLoadingDelay)-S,this.info(`bitrate test took ${Math.round(1e3*S)}ms, set first fragment max fetchDuration to ${Math.round(1e3*m)} ms`),f=h=1)}const g=this.findBestLevel(d,a,n,u,m,f,h);if(this.rebufferNotice!==g&&(this.rebufferNotice=g,this.info(`${u?"rebuffering expected":"buffer is empty"}, optimal quality level ${g}`)),g>-1)return g;const p=r.levels[a],y=r.loadLevelObj;return y&&p?.bitrate<y.bitrate?a:r.loadLevel}getStarvationDelay(){const e=this.hls,t=e.media;if(!t)return 1/0;const r=t&&t.playbackRate!==0?Math.abs(t.playbackRate):1,n=e.mainForwardBufferInfo;return(n?n.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,t,r,n,s,a,c){var d;const u=n+s,f=this.lastLoadedFragLevel,h=f===-1?this.hls.firstLevel:f,{fragCurrent:m,partCurrent:g}=this,{levels:p,allAudioTracks:y,loadLevel:S,config:E}=this.hls;if(p.length===1)return 0;const T=p[h],j=!!((d=this.hls.latestLevelDetails)!=null&&d.live),N=S===-1||f===-1;let O,U="SDR",z=T?.frameRate||0;const{audioPreference:K,videoPreference:G}=E,X=this.audioTracksByGroup||(this.audioTracksByGroup=TS(y));let te=-1;if(N){if(this.firstSelection!==-1)return this.firstSelection;const le=XG(this.codecTiers||(this.codecTiers=JG(p,X,t,r)),U,e,K,G),{codecSet:se,videoRanges:Ce,minFramerate:q,minBitrate:Q,minIndex:ie,preferHDR:be}=le;te=ie,O=se,U=be?Ce[Ce.length-1]:Ce[0],z=q,e=Math.max(e,Q),this.log(`picked start tier ${zt(le)}`)}else O=T?.codecSet,U=T?.videoRange;const ne=g?g.duration:m?m.duration:0,ae=this.bwEstimator.getEstimateTTFB()/1e3,oe=[];for(let le=r;le>=t;le--){var pe;const se=p[le],Ce=le>h;if(!se)continue;if(E.useMediaCapabilities&&!se.supportedResult&&!se.supportedPromise){const Re=navigator.mediaCapabilities;typeof Re?.decodingInfo=="function"&&zG(se,X,U,z,e,K)?(se.supportedPromise=SS(se,X,Re,this.supportedCache),se.supportedPromise.then(Ee=>{if(!this.hls)return;se.supportedResult=Ee;const Fe=this.hls.levels,Ge=Fe.indexOf(se);Ee.error?this.warn(`MediaCapabilities decodingInfo error: "${Ee.error}" for level ${Ge} ${zt(Ee)}`):Ee.supported?Ee.decodingInfoResults.some(Be=>Be.smooth===!1||Be.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ge} not smooth or powerEfficient: ${zt(Ee)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ge} ${zt(Ee)}`),Ge>-1&&Fe.length>1&&(this.log(`Removing unsupported level ${Ge}`),this.hls.removeLevel(Ge),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Ee=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Ee}`)})):se.supportedResult=yS}if((O&&se.codecSet!==O||U&&se.videoRange!==U||Ce&&z>se.frameRate||!Ce&&z>0&&z<se.frameRate||(pe=se.supportedResult)!=null&&(pe=pe.decodingInfoResults)!=null&&pe.some(Re=>Re.smooth===!1))&&(!N||le!==te)){oe.push(le);continue}const q=se.details,Q=(g?q?.partTarget:q?.averagetargetduration)||ne;let ie;Ce?ie=c*e:ie=a*e;const be=ne&&n>=ne*2&&s===0?se.averageBitrate:se.maxBitrate,we=this.getTimeToLoadFrag(ae,ie,be*Q,q===void 0);if(ie>=be&&(le===f||se.loadError===0&&se.fragmentError===0)&&(we<=ae||!Ye(we)||j&&!this.bitrateTestDelay||we<u)){const Re=this.forcedAutoLevel;return le!==S&&(Re===-1||Re!==S)&&(oe.length&&this.trace(`Skipped level(s) ${oe.join(",")} of ${r} max with CODECS and VIDEO-RANGE:"${p[oe[0]].codecs}" ${p[oe[0]].videoRange}; not compatible with "${O}" ${U}`),this.info(`switch candidate:${h}->${le} adjustedbw(${Math.round(ie)})-bitrate=${Math.round(ie-be)} ttfb:${ae.toFixed(1)} avgDuration:${Q.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${we.toFixed(1)} firstSelection:${N} codecSet:${se.codecSet} videoRange:${se.videoRange} hls.loadLevel:${S}`)),N&&(this.firstSelection=le),le}}return-1}set nextAutoLevel(e){const t=this.deriveNextAutoLevel(e);this._nextAutoLevel!==t&&(this.nextAutoLevelKey="",this._nextAutoLevel=t)}deriveNextAutoLevel(e){const{maxAutoLevel:t,minAutoLevel:r}=this.hls;return Math.min(Math.max(e,r),t)}},PS={search:function(e,t){let r=0,n=e.length-1,s=null,a=null;for(;r<=n;){s=(r+n)/2|0,a=e[s];const c=t(a);if(c>0)r=s+1;else if(c<0)n=s-1;else return a}return null}};function i8(e,t,r){if(t===null||!Array.isArray(e)||!e.length||!Ye(t)||t<(e[0].programDateTime||0)||t>=(e[e.length-1].endProgramDateTime||0))return null;for(let n=0;n<e.length;++n){const s=e[n];if(a8(t,r,s))return s}return null}function Fi(e,t,r=0,n=0,s=.005){let a=null;if(e){a=t[1+e.sn-t[0].sn]||null;const d=e.endDTS-r;d>0&&d<15e-7&&(r+=15e-7),a&&e.level!==a.level&&a.end<=e.end&&(a=t[2+e.sn-t[0].sn]||null)}else r===0&&t[0].start===0&&(a=t[0]);if(a&&((!e||e.level===a.level)&&AS(r,n,a)===0||s8(a,e,Math.min(s,n))))return a;const c=PS.search(t,AS.bind(null,r,n));return c&&(c!==e||!a)?c:a}function s8(e,t,r){if(t&&t.start===0&&t.level<e.level&&(t.endPTS||0)>0){const n=t.tagList.reduce((s,a)=>(a[0]==="INF"&&(s+=parseFloat(a[1])),s),r);return e.start<=n}return!1}function AS(e=0,t=0,r){if(r.start<=e&&r.start+r.duration>e)return 0;const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=e?1:r.start-n>e&&r.start?-1:0}function a8(e,t,r){const n=Math.min(t,r.duration+(r.deltaPTS?r.deltaPTS:0))*1e3;return(r.endProgramDateTime||0)-n>e}function jS(e,t,r){if(e&&e.startCC<=t&&e.endCC>=t){let n=e.fragments;const{fragmentHint:s}=e;s&&(n=n.concat(s));let a;return PS.search(n,c=>c.cc<t?1:c.cc>t?-1:(a=c,c.end<=r?1:c.start>r?-1:0)),a||null}return null}function mc(e){switch(e.details){case fe.FRAG_LOAD_TIMEOUT:case fe.KEY_LOAD_TIMEOUT:case fe.LEVEL_LOAD_TIMEOUT:case fe.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function NS(e){return e.details.startsWith("key")}function DS(e){return NS(e)&&!!e.frag&&!e.frag.decryptdata}function MS(e,t){const r=mc(t);return e.default[`${r?"timeout":"error"}Retry`]}function am(e,t){const r=e.backoff==="linear"?1:Math.pow(2,t);return Math.min(r*e.retryDelayMs,e.maxRetryDelayMs)}function $S(e){return Mt(Mt({},e),{errorRetry:null,timeoutRetry:null})}function gc(e,t,r,n){if(!e)return!1;const s=n?.code,a=t<e.maxNumRetry&&(o8(s)||!!r);return e.shouldRetry?e.shouldRetry(e,t,r,n,a):a}function o8(e){return om(e)||!!e&&(e<400||e>499)}function om(e){return e===0&&navigator.onLine===!1}var Sr={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Zr={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4},l8=class extends rn{constructor(e){super("error-controller",e.logger),this.hls=void 0,this.playlistError=0,this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on($.ERROR,this.onError,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off($.ERROR,this.onError,this),e.off($.ERROR,this.onErrorOut,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return e?.type===Je.MAIN?e.level:this.getVariantIndex()}getVariantIndex(){var e;const t=this.hls,r=t.currentLevel;return(e=t.loadLevelObj)!=null&&e.details||r===-1?t.loadLevel:r}variantHasKey(e,t){if(e){var r;if((r=e.details)!=null&&r.hasKey(t))return!0;const n=e.audioGroups;if(n)return this.hls.allAudioTracks.filter(s=>n.indexOf(s.groupId)>=0).some(s=>{var a;return(a=s.details)==null?void 0:a.hasKey(t)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(e,t){var r;if(t.fatal)return;const n=this.hls,s=t.context;switch(t.details){case fe.FRAG_LOAD_ERROR:case fe.FRAG_LOAD_TIMEOUT:case fe.KEY_LOAD_ERROR:case fe.KEY_LOAD_TIMEOUT:t.errorAction=this.getFragRetryOrSwitchAction(t);return;case fe.FRAG_PARSING_ERROR:if((r=t.frag)!=null&&r.gap){t.errorAction=ws();return}case fe.FRAG_GAP:case fe.FRAG_DECRYPT_ERROR:t.errorAction=this.getFragRetryOrSwitchAction(t),t.errorAction.action=Sr.SendAlternateToPenaltyBox;return;case fe.LEVEL_EMPTY_ERROR:case fe.LEVEL_PARSING_ERROR:{var a;const d=t.parent===Je.MAIN?t.level:n.loadLevel;t.details===fe.LEVEL_EMPTY_ERROR&&((a=t.context)!=null&&(a=a.levelDetails)!=null&&a.live)?t.errorAction=this.getPlaylistRetryOrSwitchAction(t,d):(t.levelRetry=!1,t.errorAction=this.getLevelSwitchAction(t,d))}return;case fe.LEVEL_LOAD_ERROR:case fe.LEVEL_LOAD_TIMEOUT:typeof s?.level=="number"&&(t.errorAction=this.getPlaylistRetryOrSwitchAction(t,s.level));return;case fe.AUDIO_TRACK_LOAD_ERROR:case fe.AUDIO_TRACK_LOAD_TIMEOUT:case fe.SUBTITLE_LOAD_ERROR:case fe.SUBTITLE_TRACK_LOAD_TIMEOUT:if(s){const d=n.loadLevelObj;if(d&&(s.type===Et.AUDIO_TRACK&&d.hasAudioGroup(s.groupId)||s.type===Et.SUBTITLE_TRACK&&d.hasSubtitleGroup(s.groupId))){t.errorAction=this.getPlaylistRetryOrSwitchAction(t,n.loadLevel),t.errorAction.action=Sr.SendAlternateToPenaltyBox,t.errorAction.flags=Zr.MoveAllAlternatesMatchingHost;return}}return;case fe.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:t.errorAction={action:Sr.SendAlternateToPenaltyBox,flags:Zr.MoveAllAlternatesMatchingHDCP};return;case fe.KEY_SYSTEM_SESSION_UPDATE_FAILED:case fe.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case fe.KEY_SYSTEM_NO_SESSION:t.errorAction={action:Sr.SendAlternateToPenaltyBox,flags:Zr.MoveAllAlternatesMatchingKey};return;case fe.BUFFER_ADD_CODEC_ERROR:case fe.REMUX_ALLOC_ERROR:case fe.BUFFER_APPEND_ERROR:if(!t.errorAction){var c;t.errorAction=this.getLevelSwitchAction(t,(c=t.level)!=null?c:n.loadLevel)}return;case fe.INTERNAL_EXCEPTION:case fe.BUFFER_APPENDING_ERROR:case fe.BUFFER_FULL_ERROR:case fe.LEVEL_SWITCH_ERROR:case fe.BUFFER_STALLED_ERROR:case fe.BUFFER_SEEK_OVER_HOLE:case fe.BUFFER_NUDGE_ON_STALL:t.errorAction=ws();return}t.type===it.KEY_SYSTEM_ERROR&&(t.levelRetry=!1,t.errorAction=ws())}getPlaylistRetryOrSwitchAction(e,t){const r=this.hls,n=MS(r.config.playlistLoadPolicy,e),s=this.playlistError++;if(gc(n,s,mc(e),e.response))return{action:Sr.RetryRequest,flags:Zr.None,retryConfig:n,retryCount:s};const a=this.getLevelSwitchAction(e,t);return n&&(a.retryConfig=n,a.retryCount=s),a}getFragRetryOrSwitchAction(e){const t=this.hls,r=this.getVariantLevelIndex(e.frag),n=t.levels[r],{fragLoadPolicy:s,keyLoadPolicy:a}=t.config,c=MS(NS(e)?a:s,e),d=t.levels.reduce((f,h)=>f+h.fragmentError,0);if(n&&(e.details!==fe.FRAG_GAP&&n.fragmentError++,!DS(e)&&gc(c,d,mc(e),e.response)))return{action:Sr.RetryRequest,flags:Zr.None,retryConfig:c,retryCount:d};const u=this.getLevelSwitchAction(e,r);return c&&(u.retryConfig=c,u.retryCount=d),u}getLevelSwitchAction(e,t){const r=this.hls;t==null&&(t=r.loadLevel);const n=this.hls.levels[t];if(n){var s,a;const u=e.details;n.loadError++,u===fe.BUFFER_APPEND_ERROR&&n.fragmentError++;let f=-1;const{levels:h,loadLevel:m,minAutoLevel:g,maxAutoLevel:p}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const y=(s=e.frag)==null?void 0:s.type,S=(y===Je.AUDIO&&u===fe.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(u===fe.BUFFER_ADD_CODEC_ERROR||u===fe.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:N})=>n.audioCodec!==N),E=e.sourceBufferName==="video"&&(u===fe.BUFFER_ADD_CODEC_ERROR||u===fe.BUFFER_APPEND_ERROR)&&h.some(({codecSet:N,audioCodec:O})=>n.codecSet!==N&&n.audioCodec===O),{type:T,groupId:j}=(a=e.context)!=null?a:{};for(let N=h.length;N--;){const O=(N+m)%h.length;if(O!==m&&O>=g&&O<=p&&h[O].loadError===0){var c,d;const U=h[O];if(u===fe.FRAG_GAP&&y===Je.MAIN&&e.frag){const z=h[O].details;if(z){const K=Fi(e.frag,z.fragments,e.frag.start);if(K!=null&&K.gap)continue}}else{if(T===Et.AUDIO_TRACK&&U.hasAudioGroup(j)||T===Et.SUBTITLE_TRACK&&U.hasSubtitleGroup(j))continue;if(y===Je.AUDIO&&(c=n.audioGroups)!=null&&c.some(z=>U.hasAudioGroup(z))||y===Je.SUBTITLE&&(d=n.subtitleGroups)!=null&&d.some(z=>U.hasSubtitleGroup(z))||S&&n.audioCodec===U.audioCodec||E&&n.codecSet===U.codecSet||!S&&n.codecSet!==U.codecSet)continue}f=O;break}}if(f>-1&&r.loadLevel!==f)return e.levelRetry=!0,this.playlistError=0,{action:Sr.SendAlternateToPenaltyBox,flags:Zr.None,nextAutoLevel:f}}return{action:Sr.SendAlternateToPenaltyBox,flags:Zr.MoveAllAlternatesMatchingHost}}onErrorOut(e,t){var r;switch((r=t.errorAction)==null?void 0:r.action){case Sr.DoNothing:break;case Sr.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(t),!t.errorAction.resolved&&t.details!==fe.FRAG_GAP?t.fatal=!0:/MediaSource readyState: ended/.test(t.error.message)&&(this.warn(`MediaSource ended after "${t.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(t.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const t=this.hls,r=e.errorAction;if(!r)return;const{flags:n}=r,s=r.nextAutoLevel;switch(n){case Zr.None:this.switchLevel(e,s);break;case Zr.MoveAllAlternatesMatchingHDCP:{const d=this.getVariantLevelIndex(e.frag),u=t.levels[d],f=u?.attrs["HDCP-LEVEL"];if(r.hdcpLevel=f,f==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(f){t.maxHdcpLevel=sm[sm.indexOf(f)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${t.maxHdcpLevel}" or lower`);break}}case Zr.MoveAllAlternatesMatchingKey:{const d=e.decryptdata;if(d){const u=this.hls.levels,f=u.length;for(let m=f;m--;)if(this.variantHasKey(u[m],d)){var a,c;this.log(`Banned key found in level ${m} (${u[m].bitrate}bps) or audio group "${(a=u[m].audioGroups)==null?void 0:a.join(",")}" (${(c=e.frag)==null?void 0:c.type} fragment) ${xr(d.keyId||[])}`),u[m].fragmentError++,u[m].loadError++,this.log(`Removing level ${m} with key error (${e.error})`),this.hls.removeLevel(m)}const h=e.frag;if(this.hls.levels.length<f)r.resolved=!0;else if(h&&h.type!==Je.MAIN){const m=h.decryptdata;m&&!d.matches(m)&&(r.resolved=!0)}}break}}r.resolved||this.switchLevel(e,s)}switchLevel(e,t){if(t!==void 0&&e.errorAction&&(this.warn(`switching to level ${t} after ${e.details}`),this.hls.nextAutoLevel=t,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel,e.details===fe.BUFFER_ADD_CODEC_ERROR&&e.mimeType&&e.sourceBufferName!=="audiovideo")){const r=im(e.mimeType),n=this.hls.levels;for(let s=n.length;s--;)n[s][`${e.sourceBufferName}Codec`]===r&&(this.log(`Removing level ${s} for ${e.details} ("${r}" not supported)`),this.hls.removeLevel(s))}}};function ws(e){const t={action:Sr.DoNothing,flags:Zr.None};return e&&(t.resolved=!0),t}var pr={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"},c8=class{constructor(e){this.activePartLists=Object.create(null),this.endListFragments=Object.create(null),this.fragments=Object.create(null),this.timeRanges=Object.create(null),this.bufferPadding=.2,this.hls=void 0,this.hasGaps=!1,this.hls=e,this._registerListeners()}_registerListeners(){const{hls:e}=this;e&&(e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.BUFFER_APPENDED,this.onBufferAppended,this),e.on($.FRAG_BUFFERED,this.onFragBuffered,this),e.on($.FRAG_LOADED,this.onFragLoaded,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.BUFFER_APPENDED,this.onBufferAppended,this),e.off($.FRAG_BUFFERED,this.onFragBuffered,this),e.off($.FRAG_LOADED,this.onFragLoaded,this))}destroy(){this._unregisterListeners(),this.hls=this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,t){const r=this.activePartLists[t];if(r)for(let n=r.length;n--;){const s=r[n];if(!s)break;if(s.start<=e&&e<=s.end&&s.loaded)return s}return this.getBufferedFrag(e,t)}getBufferedFrag(e,t){return this.getFragAtPos(e,t,!0)}getFragAtPos(e,t,r){const{fragments:n}=this,s=Object.keys(n);for(let a=s.length;a--;){const c=n[s[a]];if(c?.body.type===t&&(!r||c.buffered)){const d=c.body;if(d.start<=e&&e<=d.end)return d}}return null}detectEvictedFragments(e,t,r,n,s){this.timeRanges&&(this.timeRanges[e]=t);const a=n?.fragment.sn||-1;Object.keys(this.fragments).forEach(c=>{const d=this.fragments[c];if(!d||a>=d.body.sn)return;if(!d.buffered&&(!d.loaded||s)){d.body.type===r&&this.removeFragment(d.body);return}const u=d.range[e];if(u){if(u.time.length===0){this.removeFragment(d.body);return}u.time.some(f=>{const h=!this.isTimeBuffered(f.startPTS,f.endPTS,t);return h&&this.removeFragment(d.body),h})}})}detectPartialFragments(e){const t=this.timeRanges;if(!t||e.frag.sn==="initSegment")return;const r=e.frag,n=Es(r),s=this.fragments[n];if(!s||s.buffered&&r.gap)return;const a=!r.relurl;Object.keys(t).forEach(c=>{const d=r.elementaryStreams[c];if(!d)return;const u=t[c],f=a||d.partial===!0;s.range[c]=this.getBufferedTimes(r,e.part,f,u)}),s.loaded=null,Object.keys(s.range).length?(this.bufferedEnd(s,r),pc(s)||this.removeParts(r.sn-1,r.type)):this.removeFragment(s.body)}bufferedEnd(e,t){e.buffered=!0,(e.body.endList=t.endList||e.body.endList)&&(this.endListFragments[e.body.type]=e)}removeParts(e,t){const r=this.activePartLists[t];r&&(this.activePartLists[t]=RS(r,n=>n.fragment.sn>=e))}fragBuffered(e,t){const r=Es(e);let n=this.fragments[r];!n&&t&&(n=this.fragments[r]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),n&&(n.loaded=null,this.bufferedEnd(n,e))}getBufferedTimes(e,t,r,n){const s={time:[],partial:r},a=e.start,c=e.end,d=e.minEndPTS||c,u=e.maxStartPTS||a;for(let f=0;f<n.length;f++){const h=n.start(f)-this.bufferPadding,m=n.end(f)+this.bufferPadding;if(u>=h&&d<=m){s.time.push({startPTS:Math.max(a,n.start(f)),endPTS:Math.min(c,n.end(f))});break}else if(a<m&&c>h){const g=Math.max(a,n.start(f)),p=Math.min(c,n.end(f));p>g&&(s.partial=!0,s.time.push({startPTS:g,endPTS:p}))}else if(c<=h)break}return s}getPartialFragment(e){let t=null,r,n,s,a=0;const{bufferPadding:c,fragments:d}=this;return Object.keys(d).forEach(u=>{const f=d[u];f&&pc(f)&&(n=f.body.start-c,s=f.body.end+c,e>=n&&e<=s&&(r=Math.min(e-n,s-e),a<=r&&(t=f.body,a=r)))}),t}isEndListAppended(e){const t=this.endListFragments[e];return t!==void 0&&(t.buffered||pc(t))}getState(e){const t=Es(e),r=this.fragments[t];return r?r.buffered?pc(r)?pr.PARTIAL:pr.OK:pr.APPENDING:pr.NOT_LOADED}isTimeBuffered(e,t,r){let n,s;for(let a=0;a<r.length;a++){if(n=r.start(a)-this.bufferPadding,s=r.end(a)+this.bufferPadding,e>=n&&t<=s)return!0;if(t<=n)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(e,t){if(t.frag.sn==="initSegment"||t.frag.bitrateTest)return;const r=t.frag,n=t.part?null:t,s=Es(r);this.fragments[s]={body:r,appendedPTS:null,loaded:n,buffered:!1,range:Object.create(null)}}onBufferAppended(e,t){const{frag:r,part:n,timeRanges:s,type:a}=t;if(r.sn==="initSegment")return;const c=r.type;if(n){let u=this.activePartLists[c];u||(this.activePartLists[c]=u=[]),u.push(n)}this.timeRanges=s;const d=s[a];this.detectEvictedFragments(a,d,c,n)}onFragBuffered(e,t){this.detectPartialFragments(t)}hasFragment(e){const t=Es(e);return!!this.fragments[t]}hasFragments(e){const{fragments:t}=this,r=Object.keys(t);if(!e)return r.length>0;for(let n=r.length;n--;){const s=t[r[n]];if(s?.body.type===e)return!0}return!1}hasParts(e){var t;return!!((t=this.activePartLists[e])!=null&&t.length)}removeFragmentsInRange(e,t,r,n,s){n&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const c=this.fragments[a];if(!c)return;const d=c.body;d.type!==r||n&&!d.gap||d.start<t&&d.end>e&&(c.buffered||s)&&this.removeFragment(d)})}removeFragment(e){const t=Es(e);e.clearElementaryStreamInfo();const r=this.activePartLists[e.type];if(r){const n=e.sn;this.activePartLists[e.type]=RS(r,s=>s.fragment.sn!==n)}delete this.fragments[t],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){var e;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const t=(e=this.hls)==null||(e=e.latestLevelDetails)==null?void 0:e.partList;t&&t.forEach(r=>r.clearElementaryStreamInfo())}};function pc(e){var t,r,n;return e.buffered&&!!(e.body.gap||(t=e.range.video)!=null&&t.partial||(r=e.range.audio)!=null&&r.partial||(n=e.range.audiovideo)!=null&&n.partial)}function Es(e){return`${e.type}_${e.level}_${e.sn}`}function RS(e,t){return e.filter(r=>{const n=t(r);return n||r.clearElementaryStreamInfo(),n})}var fi={cbc:0,ctr:1},u8=class{constructor(e,t,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=e,this.aesIV=t,this.aesMode=r}decrypt(e,t){switch(this.aesMode){case fi.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},t,e);case fi.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},t,e);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}};function d8(e){const t=e.byteLength,r=t&&new DataView(e.buffer).getUint8(t-1);return r?e.slice(0,t-r):e}var f8=class{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(e){const t=new DataView(e),r=new Uint32Array(4);for(let n=0;n<4;n++)r[n]=t.getUint32(n*4);return r}initTable(){const e=this.sBox,t=this.invSBox,r=this.subMix,n=r[0],s=r[1],a=r[2],c=r[3],d=this.invSubMix,u=d[0],f=d[1],h=d[2],m=d[3],g=new Uint32Array(256);let p=0,y=0,S=0;for(S=0;S<256;S++)S<128?g[S]=S<<1:g[S]=S<<1^283;for(S=0;S<256;S++){let E=y^y<<1^y<<2^y<<3^y<<4;E=E>>>8^E&255^99,e[p]=E,t[E]=p;const T=g[p],j=g[T],N=g[j];let O=g[E]*257^E*16843008;n[p]=O<<24|O>>>8,s[p]=O<<16|O>>>16,a[p]=O<<8|O>>>24,c[p]=O,O=N*16843009^j*65537^T*257^p*16843008,u[E]=O<<24|O>>>8,f[E]=O<<16|O>>>16,h[E]=O<<8|O>>>24,m[E]=O,p?(p=T^g[g[g[N^T]]],y^=g[g[y]]):p=y=1}}expandKey(e){const t=this.uint8ArrayToUint32Array_(e);let r=!0,n=0;for(;n<t.length&&r;)r=t[n]===this.key[n],n++;if(r)return;this.key=t;const s=this.keySize=t.length;if(s!==4&&s!==6&&s!==8)throw new Error("Invalid aes key size="+s);const a=this.ksRows=(s+6+1)*4;let c,d;const u=this.keySchedule=new Uint32Array(a),f=this.invKeySchedule=new Uint32Array(a),h=this.sBox,m=this.rcon,g=this.invSubMix,p=g[0],y=g[1],S=g[2],E=g[3];let T,j;for(c=0;c<a;c++){if(c<s){T=u[c]=t[c];continue}j=T,c%s===0?(j=j<<8|j>>>24,j=h[j>>>24]<<24|h[j>>>16&255]<<16|h[j>>>8&255]<<8|h[j&255],j^=m[c/s|0]<<24):s>6&&c%s===4&&(j=h[j>>>24]<<24|h[j>>>16&255]<<16|h[j>>>8&255]<<8|h[j&255]),u[c]=T=(u[c-s]^j)>>>0}for(d=0;d<a;d++)c=a-d,d&3?j=u[c]:j=u[c-4],d<4||c<=4?f[d]=j:f[d]=p[h[j>>>24]]^y[h[j>>>16&255]]^S[h[j>>>8&255]]^E[h[j&255]],f[d]=f[d]>>>0}networkToHostOrderSwap(e){return e<<24|(e&65280)<<8|(e&16711680)>>8|e>>>24}decrypt(e,t,r){const n=this.keySize+6,s=this.invKeySchedule,a=this.invSBox,c=this.invSubMix,d=c[0],u=c[1],f=c[2],h=c[3],m=this.uint8ArrayToUint32Array_(r);let g=m[0],p=m[1],y=m[2],S=m[3];const E=new Int32Array(e),T=new Int32Array(E.length);let j,N,O,U,z,K,G,X,te,ne,ae,oe,pe,le;const se=this.networkToHostOrderSwap;for(;t<E.length;){for(te=se(E[t]),ne=se(E[t+1]),ae=se(E[t+2]),oe=se(E[t+3]),z=te^s[0],K=oe^s[1],G=ae^s[2],X=ne^s[3],pe=4,le=1;le<n;le++)j=d[z>>>24]^u[K>>16&255]^f[G>>8&255]^h[X&255]^s[pe],N=d[K>>>24]^u[G>>16&255]^f[X>>8&255]^h[z&255]^s[pe+1],O=d[G>>>24]^u[X>>16&255]^f[z>>8&255]^h[K&255]^s[pe+2],U=d[X>>>24]^u[z>>16&255]^f[K>>8&255]^h[G&255]^s[pe+3],z=j,K=N,G=O,X=U,pe=pe+4;j=a[z>>>24]<<24^a[K>>16&255]<<16^a[G>>8&255]<<8^a[X&255]^s[pe],N=a[K>>>24]<<24^a[G>>16&255]<<16^a[X>>8&255]<<8^a[z&255]^s[pe+1],O=a[G>>>24]<<24^a[X>>16&255]<<16^a[z>>8&255]<<8^a[K&255]^s[pe+2],U=a[X>>>24]<<24^a[z>>16&255]<<16^a[K>>8&255]<<8^a[G&255]^s[pe+3],T[t]=se(j^g),T[t+1]=se(U^p),T[t+2]=se(O^y),T[t+3]=se(N^S),g=te,p=ne,y=ae,S=oe,t=t+4}return T.buffer}},h8=class{constructor(e,t,r){this.subtle=void 0,this.key=void 0,this.aesMode=void 0,this.subtle=e,this.key=t,this.aesMode=r}expandKey(){const e=m8(this.aesMode);return this.subtle.importKey("raw",this.key,{name:e},!1,["encrypt","decrypt"])}};function m8(e){switch(e){case fi.cbc:return"AES-CBC";case fi.ctr:return"AES-CTR";default:throw new Error(`[FastAESKey] invalid aes mode ${e}`)}}var g8=16,lm=class{constructor(e,{removePKCS7Padding:t=!0}={}){if(this.logEnabled=!0,this.removePKCS7Padding=void 0,this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null,this.useSoftware=void 0,this.enableSoftwareAES=void 0,this.enableSoftwareAES=e.enableSoftwareAES,this.removePKCS7Padding=t,t)try{const r=self.crypto;r&&(this.subtle=r.subtle||r.webkitSubtle)}catch{}this.useSoftware=!this.subtle}destroy(){this.subtle=null,this.softwareDecrypter=null,this.key=null,this.fastAesKey=null,this.remainderData=null,this.currentIV=null,this.currentResult=null}isSync(){return this.useSoftware}flush(){const{currentResult:e,remainderData:t}=this;if(!e||t)return this.reset(),null;const r=new Uint8Array(e);return this.reset(),this.removePKCS7Padding?d8(r):r}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(e,t,r,n){return this.useSoftware?new Promise((s,a)=>{const c=ArrayBuffer.isView(e)?e:new Uint8Array(e);this.softwareDecrypt(c,t,r,n);const d=this.flush();d?s(d.buffer):a(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(e),t,r,n)}softwareDecrypt(e,t,r,n){const{currentIV:s,currentResult:a,remainderData:c}=this;if(n!==fi.cbc||t.byteLength!==16)return $t.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),c&&(e=nn(c,e),this.remainderData=null);const d=this.getValidChunk(e);if(!d.length)return null;s&&(r=s);let u=this.softwareDecrypter;u||(u=this.softwareDecrypter=new f8),u.expandKey(t);const f=a;return this.currentResult=u.decrypt(d.buffer,0,r),this.currentIV=d.slice(-16).buffer,f||null}webCryptoDecrypt(e,t,r,n){if(this.key!==t||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(e,t,r,n));this.key=t,this.fastAesKey=new h8(this.subtle,t,n)}return this.fastAesKey.expandKey().then(s=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new u8(this.subtle,new Uint8Array(r),n).decrypt(e.buffer,s)):Promise.reject(new Error("web crypto not initialized"))).catch(s=>($t.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${s.name}: ${s.message}`),this.onWebCryptoError(e,t,r,n)))}onWebCryptoError(e,t,r,n){const s=this.enableSoftwareAES;if(s){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,t,r,n);const a=this.flush();if(a)return a.buffer}throw new Error("WebCrypto"+(s?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(e){let t=e;const r=e.length-e.length%g8;return r!==e.length&&(t=e.slice(0,r),this.remainderData=e.slice(r)),t}logOnce(e){this.logEnabled&&($t.log(`[decrypter]: ${e}`),this.logEnabled=!1)}},LS=Math.pow(2,17),p8=class{constructor(e){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=e}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(e,t){const r=e.url;if(!r)return Promise.reject(new Zn({type:it.NETWORK_ERROR,details:fe.FRAG_LOAD_ERROR,fatal:!1,frag:e,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const n=this.config,s=n.fLoader,a=n.loader;return new Promise((c,d)=>{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(p=>p[0]==="GAP")){d(FS(e));return}else e.gap=!1;const u=this.loader=s?new s(n):new a(n),f=OS(e);e.loader=u;const h=$S(n.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:LS};e.stats=u.stats;const g={onSuccess:(p,y,S,E)=>{this.resetLoader(e,u);let T=p.data;S.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(T.slice(0,16)),T=T.slice(16)),c({frag:e,part:null,payload:T,networkDetails:E})},onError:(p,y,S,E)=>{this.resetLoader(e,u),d(new Zn({type:it.NETWORK_ERROR,details:fe.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:Mt({url:r,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:S,stats:E}))},onAbort:(p,y,S)=>{this.resetLoader(e,u),d(new Zn({type:it.NETWORK_ERROR,details:fe.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:S,stats:p}))},onTimeout:(p,y,S)=>{this.resetLoader(e,u),d(new Zn({type:it.NETWORK_ERROR,details:fe.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:S,stats:p}))}};t&&(g.onProgress=(p,y,S,E)=>t({frag:e,part:null,payload:S,networkDetails:E})),u.load(f,m,g)})}loadPart(e,t,r){this.abort();const n=this.config,s=n.fLoader,a=n.loader;return new Promise((c,d)=>{if(this.loader&&this.loader.destroy(),e.gap||t.gap){d(FS(e,t));return}const u=this.loader=s?new s(n):new a(n),f=OS(e,t);e.loader=u;const h=$S(n.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:LS};t.stats=u.stats,u.load(f,m,{onSuccess:(g,p,y,S)=>{this.resetLoader(e,u),this.updateStatsFromPart(e,t);const E={frag:e,part:t,payload:g.data,networkDetails:S};r(E),c(E)},onError:(g,p,y,S)=>{this.resetLoader(e,u),d(new Zn({type:it.NETWORK_ERROR,details:fe.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:t,response:Mt({url:f.url,data:void 0},g),error:new Error(`HTTP Error ${g.code} ${g.text}`),networkDetails:y,stats:S}))},onAbort:(g,p,y)=>{e.stats.aborted=t.stats.aborted,this.resetLoader(e,u),d(new Zn({type:it.NETWORK_ERROR,details:fe.INTERNAL_ABORTED,fatal:!1,frag:e,part:t,error:new Error("Aborted"),networkDetails:y,stats:g}))},onTimeout:(g,p,y)=>{this.resetLoader(e,u),d(new Zn({type:it.NETWORK_ERROR,details:fe.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:t,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:y,stats:g}))}})})}updateStatsFromPart(e,t){const r=e.stats,n=t.stats,s=n.total;if(r.loaded+=n.loaded,s){const d=Math.round(e.duration/t.duration),u=Math.min(Math.round(r.loaded/s),d),f=(d-u)*Math.round(r.loaded/u);r.total=r.loaded+f}else r.total=Math.max(r.loaded,r.total);const a=r.loading,c=n.loading;a.start?a.first+=c.first-c.start:(a.start=c.start,a.first=c.first),a.end=c.end}resetLoader(e,t){e.loader=null,this.loader===t&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),t.destroy()}};function OS(e,t=null){const r=t||e,n={frag:e,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},s=r.byteRangeStartOffset,a=r.byteRangeEndOffset;if(Ye(s)&&Ye(a)){var c;let d=s,u=a;if(e.sn==="initSegment"&&v8((c=e.decryptdata)==null?void 0:c.method)){const f=a-s;f%16&&(u=a+(16-f%16)),s!==0&&(n.resetIV=!0,d=s-16)}n.rangeStart=d,n.rangeEnd=u}return n}function FS(e,t){const r=new Error(`GAP ${e.gap?"tag":"attribute"} found`),n={type:it.MEDIA_ERROR,details:fe.FRAG_GAP,fatal:!1,frag:e,error:r,networkDetails:null};return t&&(n.part=t),(t||e).stats.aborted=!0,new Zn(n)}function v8(e){return e==="AES-128"||e==="AES-256"}var Zn=class extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}},US=class extends rn{constructor(e,t){super(e,t),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(e){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,e),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}},cm=class{constructor(e,t,r,n=0,s=-1,a=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=vc(),this.buffering={audio:vc(),video:vc(),audiovideo:vc()},this.level=e,this.sn=t,this.id=r,this.size=n,this.part=s,this.partial=a}};function vc(){return{start:0,executeStart:0,executeEnd:0,end:0}}var BS={length:0,start:()=>0,end:()=>0},xt=class Da{static isBuffered(t,r){if(t){const n=Da.getBuffered(t);for(let s=n.length;s--;)if(r>=n.start(s)&&r<=n.end(s))return!0}return!1}static bufferedRanges(t){if(t){const r=Da.getBuffered(t);return Da.timeRangesToArray(r)}return[]}static timeRangesToArray(t){const r=[];for(let n=0;n<t.length;n++)r.push({start:t.start(n),end:t.end(n)});return r}static bufferInfo(t,r,n){if(t){const s=Da.bufferedRanges(t);if(s.length)return Da.bufferedInfo(s,r,n)}return{len:0,start:r,end:r,bufferedIndex:-1}}static bufferedInfo(t,r,n){r=Math.max(0,r),t.length>1&&t.sort((h,m)=>h.start-m.start||m.end-h.end);let s=-1,a=[];if(n)for(let h=0;h<t.length;h++){r>=t[h].start&&r<=t[h].end&&(s=h);const m=a.length;if(m){const g=a[m-1].end;t[h].start-g<n?t[h].end>g&&(a[m-1].end=t[h].end):a.push(t[h])}else a.push(t[h])}else a=t;let c=0,d,u=r,f=r;for(let h=0;h<a.length;h++){const m=a[h].start,g=a[h].end;if(s===-1&&r>=m&&r<=g&&(s=h),r+n>=m&&r<g)u=m,f=g,c=f-r;else if(r+n<m){d=m;break}}return{len:c,start:u||0,end:f||0,nextStart:d,buffered:t,bufferedIndex:s}}static getBuffered(t){try{return t.buffered||BS}catch(r){return $t.log("failed to get media.buffered",r),BS}}},zS=/\{\$([a-zA-Z0-9-_]+)\}/g;function GS(e){return zS.test(e)}function um(e,t){if(e.variableList!==null||e.hasVariableRefs){const r=e.variableList;return t.replace(zS,n=>{const s=n.substring(2,n.length-1),a=r?.[s];return a===void 0?(e.playlistParsingError||(e.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${s}"`)),n):a})}return t}function ZS(e,t,r){let n=e.variableList;n||(e.variableList=n={});let s,a;if("QUERYPARAM"in t){s=t.QUERYPARAM;try{const c=new self.URL(r).searchParams;if(c.has(s))a=c.get(s);else throw new Error(`"${s}" does not match any query parameter in URI: "${r}"`)}catch(c){e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${c.message}`))}}else s=t.NAME,a=t.VALUE;s in n?e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${s}"`)):n[s]=a||""}function b8(e,t,r){const n=t.IMPORT;if(r&&n in r){let s=e.variableList;s||(e.variableList=s={}),s[n]=r[n]}else e.playlistParsingError||(e.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}var y8=/^(\d+)x(\d+)$/,VS=/(.+?)=(".*?"|.*?)(?:,|$)/g,or=class Gw{constructor(t,r){typeof t=="string"&&(t=Gw.parseAttrList(t,r)),Ft(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const r=parseInt(this[t],10);return r>Number.MAX_SAFE_INTEGER?1/0:r}hexadecimalInteger(t){if(this[t]){let r=(this[t]||"0x").slice(2);r=(r.length&1?"0":"")+r;const n=new Uint8Array(r.length/2);for(let s=0;s<r.length/2;s++)n[s]=parseInt(r.slice(s*2,s*2+2),16);return n}return null}hexadecimalIntegerAsNumber(t){const r=parseInt(this[t],16);return r>Number.MAX_SAFE_INTEGER?1/0:r}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,r){const n=this[t];return n?parseFloat(n):r}enumeratedString(t){return this[t]}enumeratedStringList(t,r){const n=this[t];return(n?n.split(/[ ,]+/):[]).reduce((s,a)=>(s[a.toLowerCase()]=!0,s),r)}bool(t){return this[t]==="YES"}decimalResolution(t){const r=y8.exec(this[t]);if(r!==null)return{width:parseInt(r[1],10),height:parseInt(r[2],10)}}static parseAttrList(t,r){let n;const s={};for(VS.lastIndex=0;(n=VS.exec(t))!==null;){const c=n[1].trim();let d=n[2];const u=d.indexOf('"')===0&&d.lastIndexOf('"')===d.length-1;let f=!1;if(u)d=d.slice(1,-1);else switch(c){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":f=!0}if(r&&(u||f))d=um(r,d);else if(!f&&!u)switch(c){case"CLOSED-CAPTIONS":if(d==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":$t.warn(`${t}: attribute ${c} is missing quotes`)}s[c]=d}return s}},x8="com.apple.hls.interstitial";function S8(e){return e!=="ID"&&e!=="CLASS"&&e!=="CUE"&&e!=="START-DATE"&&e!=="DURATION"&&e!=="END-DATE"&&e!=="END-ON-NEXT"}function _8(e){return e==="SCTE35-OUT"||e==="SCTE35-IN"||e==="SCTE35-CMD"}var HS=class{constructor(e,t,r=0){var n;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=t?.tagAnchor||null,this.tagOrder=(n=t?.tagOrder)!=null?n:r,t){const s=t.attr;for(const a in s)if(Object.prototype.hasOwnProperty.call(e,a)&&e[a]!==s[a]){$t.warn(`DATERANGE tag attribute: "${a}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=a;break}e=Ft(new or({}),s,e)}if(this.attr=e,t?(this._startDate=t._startDate,this._cue=t._cue,this._endDate=t._endDate,this._dateAtEnd=t._dateAtEnd):this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const s=t?.endDate||new Date(this.attr["END-DATE"]);Ye(s.getTime())&&(this._endDate=s)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get cue(){const e=this._cue;return e===void 0?this._cue=this.attr.enumeratedStringList(this.attr.CUE?"CUE":"X-CUE",{pre:!1,post:!1,once:!1}):e}get startTime(){const{tagAnchor:e}=this;return e===null||e.programDateTime===null?($t.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${e}`),NaN):e.start+(this.startDate.getTime()-e.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const e=this._endDate||this._dateAtEnd;if(e)return e;const t=this.duration;return t!==null?this._dateAtEnd=new Date(this._startDate.getTime()+t*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(Ye(e))return e}else if(this._endDate)return(this._endDate.getTime()-this._startDate.getTime())/1e3;return null}get plannedDuration(){return"PLANNED-DURATION"in this.attr?this.attr.decimalFloatingPoint("PLANNED-DURATION"):null}get endOnNext(){return this.attr.bool("END-ON-NEXT")}get isInterstitial(){return this.class===x8}get isValid(){return!!this.id&&!this._badValueForSameId&&Ye(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)&&(!this.attr.CUE||!this.cue.pre&&!this.cue.post||this.cue.pre!==this.cue.post)&&(!this.isInterstitial||"X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)}},w8=10,E8=class{constructor(e){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const t=this.lastPartSn-e.lastPartSn,r=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!r||!!t||!this.live,this.advanced=this.endSN>e.endSN||t>0||t===0&&r>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1}hasKey(e){return this.encryptedFragments.some(t=>{let r=t.decryptdata;return r||(t.setKeyFormat(e.keyFormat),r=t.decryptdata),!!r&&e.matches(r)})}get hasProgramDateTime(){return this.fragments.length?Ye(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||w8}get drift(){const e=this.driftEndTime-this.driftStartTime;return e>0?(this.driftEnd-this.driftStart)*1e3/e:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const e=this.partList;if(e){const t=this.lastPartIndex;if(t!==-1){for(let r=e.length;r--;)if(e[r].index>t)return e[r].index;return t}}return 0}get lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const e=this.partEnd-this.fragmentStart;return this.age>Math.max(e,this.totalduration)+this.levelTargetDuration}return!1}};function bc(e,t){return e.length===t.length?!e.some((r,n)=>r!==t[n]):!1}function KS(e,t){return!e&&!t?!0:!e||!t?!1:bc(e,t)}function ks(e){return e==="AES-128"||e==="AES-256"||e==="AES-256-CTR"}function dm(e){switch(e){case"AES-128":case"AES-256":return fi.cbc;case"AES-256-CTR":return fi.ctr;default:throw new Error(`invalid full segment method ${e}`)}}function fm(e){return Uint8Array.from(atob(e),t=>t.charCodeAt(0))}function hm(e){return Uint8Array.from(unescape(encodeURIComponent(e)),t=>t.charCodeAt(0))}function k8(e){const t=hm(e).subarray(0,16),r=new Uint8Array(16);return r.set(t,16-t.length),r}function WS(e){const t=function(n,s,a){const c=n[s];n[s]=n[a],n[a]=c};t(e,0,3),t(e,1,2),t(e,4,5),t(e,6,7)}function qS(e){const t=e.split(":");let r=null;if(t[0]==="data"&&t.length===2){const n=t[1].split(";"),s=n[n.length-1].split(",");if(s.length===2){const a=s[0]==="base64",c=s[1];a?(n.splice(-1,1),r=fm(c)):r=k8(c)}}return r}var yc=typeof self<"u"?self:void 0,Yt={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},_r={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function xc(e){switch(e){case _r.FAIRPLAY:return Yt.FAIRPLAY;case _r.PLAYREADY:return Yt.PLAYREADY;case _r.WIDEVINE:return Yt.WIDEVINE;case _r.CLEARKEY:return Yt.CLEARKEY}}function mm(e){switch(e){case Yt.FAIRPLAY:return _r.FAIRPLAY;case Yt.PLAYREADY:return _r.PLAYREADY;case Yt.WIDEVINE:return _r.WIDEVINE;case Yt.CLEARKEY:return _r.CLEARKEY}}function Io(e){const{drmSystems:t,widevineLicenseUrl:r}=e,n=t?[Yt.FAIRPLAY,Yt.WIDEVINE,Yt.PLAYREADY,Yt.CLEARKEY].filter(s=>!!t[s]):[];return!n[Yt.WIDEVINE]&&r&&n.push(Yt.WIDEVINE),n}var QS=(function(e){return yc!=null&&(e=yc.navigator)!=null&&e.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null})();function T8(e,t,r,n){let s;switch(e){case Yt.FAIRPLAY:s=["cenc","sinf"];break;case Yt.WIDEVINE:case Yt.PLAYREADY:s=["cenc"];break;case Yt.CLEARKEY:s=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${e}`)}return C8(s,t,r,n)}function C8(e,t,r,n){return[{initDataTypes:e,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:t.map(s=>({contentType:`audio/mp4; codecs=${s}`,robustness:n.audioRobustness||"",encryptionScheme:n.audioEncryptionScheme||null})),videoCapabilities:r.map(s=>({contentType:`video/mp4; codecs=${s}`,robustness:n.videoRobustness||"",encryptionScheme:n.videoEncryptionScheme||null}))}]}function I8(e){var t;return!!e&&(e.sessionType==="persistent-license"||!!((t=e.sessionTypes)!=null&&t.some(r=>r==="persistent-license")))}function YS(e){const t=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2),r=String.fromCharCode.apply(null,Array.from(t)),n=r.substring(r.indexOf("<"),r.length),s=new DOMParser().parseFromString(n,"text/xml").getElementsByTagName("KID")[0];if(s){const a=s.childNodes[0]?s.childNodes[0].nodeValue:s.getAttribute("VALUE");if(a){const c=fm(a).subarray(0,16);return WS(c),c}}return null}var Ts={},Sc=class qc{static clearKeyUriToKeyIdMap(){Ts={}}static setKeyIdForUri(t,r){Ts[t]=r}static addKeyIdForUri(t){const r=Object.keys(Ts).length%Number.MAX_SAFE_INTEGER,n=new Uint8Array(16);return new DataView(n.buffer,12,4).setUint32(0,r),Ts[t]=n,n}constructor(t,r,n,s=[1],a=null,c){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=r,this.keyFormat=n,this.keyFormatVersions=s,this.iv=a,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!ks(t),c!=null&&c.startsWith("0x")&&(this.keyId=new Uint8Array(tS(c)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&bc(t.keyFormatVersions,this.keyFormatVersions)&&KS(t.iv,this.iv)&&KS(t.keyId,this.keyId)}isSupported(){if(this.method){if(ks(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case _r.FAIRPLAY:case _r.WIDEVINE:case _r.PLAYREADY:case _r.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t,r){if(!this.encrypted||!this.uri)return null;if(ks(this.method)){let a=this.iv;return a||(typeof t!="number"&&($t.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),a=A8(t)),new qc(this.method,this.uri,"identity",this.keyFormatVersions,a)}if(this.keyId){const a=Ts[this.uri];if(a&&!bc(this.keyId,a)&&qc.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const n=qS(this.uri);if(n)switch(this.keyFormat){case _r.WIDEVINE:if(this.pssh=n,!this.keyId){const a=DG(n.buffer);if(a.length){var s;const c=a[0];this.keyId=(s=c.kids)!=null&&s.length?c.kids[0]:null}}this.keyId||(this.keyId=XS(r));break;case _r.PLAYREADY:{const a=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=NG(a,null,n),this.keyId=YS(n);break}default:{let a=n.subarray(0,16);if(a.length!==16){const c=new Uint8Array(16);c.set(a,16-a.length),a=c}this.keyId=a;break}}if(!this.keyId||this.keyId.byteLength!==16){let a;a=P8(r),a||(a=XS(r),a||(a=Ts[this.uri])),a&&(this.keyId=a,qc.setKeyIdForUri(this.uri,a))}return this}};function P8(e){const t=e?.[_r.WIDEVINE];return t?t.keyId:null}function XS(e){const t=e?.[_r.PLAYREADY];if(t){const r=qS(t.uri);if(r)return YS(r)}return null}function A8(e){const t=new Uint8Array(16);for(let r=12;r<16;r++)t[r]=e>>8*(15-r)&255;return t}var JS=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,e1=/#EXT-X-MEDIA:(.*)/g,j8=/^#EXT(?:INF|-X-TARGETDURATION):/m,gm=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),N8=new RegExp([/#EXT-X-(PROGRAM-DATE-TIME|BYTERANGE|DATERANGE|DEFINE|KEY|MAP|PART|PART-INF|PLAYLIST-TYPE|PRELOAD-HINT|RENDITION-REPORT|SERVER-CONTROL|SKIP|START):(.+)/.source,/#EXT-X-(BITRATE|DISCONTINUITY-SEQUENCE|MEDIA-SEQUENCE|TARGETDURATION|VERSION): *(\d+)/.source,/#EXT-X-(DISCONTINUITY|ENDLIST|GAP|INDEPENDENT-SEGMENTS)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|")),Po=class Uo{static findGroup(t,r){for(let n=0;n<t.length;n++){const s=t[n];if(s.id===r)return s}}static resolve(t,r){return Qh.buildAbsoluteURL(r,t,{alwaysNormalize:!0})}static isMediaPlaylist(t){return j8.test(t)}static parseMasterPlaylist(t,r){const n={contentSteering:null,levels:[],playlistParsingError:null,sessionData:null,sessionKeys:null,startTimeOffset:null,variableList:null,hasVariableRefs:GS(t)},s=[];if(JS.lastIndex=0,!t.startsWith("#EXTM3U"))return n.playlistParsingError=new Error("no EXTM3U delimiter"),n;let a;for(;(a=JS.exec(t))!=null;)if(a[1]){var c;const d=new or(a[1],n),u=um(n,a[2]),f={attrs:d,bitrate:d.decimalInteger("BANDWIDTH")||d.decimalInteger("AVERAGE-BANDWIDTH"),name:d.NAME,url:Uo.resolve(u,r)},h=d.decimalResolution("RESOLUTION");h&&(f.width=h.width,f.height=h.height),i1(d.CODECS,f);const m=d["SUPPLEMENTAL-CODECS"];m&&(f.supplemental={},i1(m,f.supplemental)),(c=f.unknownCodecs)!=null&&c.length||s.push(f),n.levels.push(f)}else if(a[3]){const d=a[3],u=a[4];switch(d){case"SESSION-DATA":{const f=new or(u,n),h=f["DATA-ID"];h&&(n.sessionData===null&&(n.sessionData={}),n.sessionData[h]=f);break}case"SESSION-KEY":{const f=r1(u,r,n);f.encrypted&&f.isSupported()?(n.sessionKeys===null&&(n.sessionKeys=[]),n.sessionKeys.push(f)):$t.warn(`[Keys] Ignoring invalid EXT-X-SESSION-KEY tag: "${u}"`);break}case"DEFINE":ZS(n,new or(u,n),r);break;case"CONTENT-STEERING":{const f=new or(u,n);n.contentSteering={uri:Uo.resolve(f["SERVER-URI"],r),pathwayId:f["PATHWAY-ID"]||"."};break}case"START":n.startTimeOffset=n1(u);break}}return n.levels=s.length>0&&s.length<n.levels.length?s:n.levels,n.levels.length===0&&(n.playlistParsingError=new Error("no levels found in manifest")),n}static parseMasterPlaylistMedia(t,r,n){let s;const a={},c=n.levels,d={AUDIO:c.map(f=>({id:f.attrs.AUDIO,audioCodec:f.audioCodec})),SUBTITLES:c.map(f=>({id:f.attrs.SUBTITLES,textCodec:f.textCodec})),"CLOSED-CAPTIONS":[]};let u=0;for(e1.lastIndex=0;(s=e1.exec(t))!==null;){const f=new or(s[1],n),h=f.TYPE;if(h){const m=d[h],g=a[h]||[];a[h]=g;const p=f.LANGUAGE,y=f["ASSOC-LANGUAGE"],S=f.CHANNELS,E=f.CHARACTERISTICS,T=f["INSTREAM-ID"],j={attrs:f,bitrate:0,id:u++,groupId:f["GROUP-ID"]||"",name:f.NAME||p||"",type:h,default:f.bool("DEFAULT"),autoselect:f.bool("AUTOSELECT"),forced:f.bool("FORCED"),lang:p,url:f.URI?Uo.resolve(f.URI,r):""};if(y&&(j.assocLang=y),S&&(j.channels=S),E&&(j.characteristics=E),T&&(j.instreamId=T),m!=null&&m.length){const N=Uo.findGroup(m,j.groupId)||m[0];s1(j,N,"audioCodec"),s1(j,N,"textCodec")}g.push(j)}}return a}static parseLevelPlaylist(t,r,n,s,a,c){var d;const u={url:r},f=new E8(r),h=f.fragments,m=[];let g=null,p=0,y=0,S=0,E=0,T=0,j=null,N=new Xh(s,u),O,U,z,K=-1,G=!1,X=null,te;if(gm.lastIndex=0,f.m3u8=t,f.hasVariableRefs=GS(t),((d=gm.exec(t))==null?void 0:d[0])!=="#EXTM3U")return f.playlistParsingError=new Error("Missing format identifier #EXTM3U"),f;for(;(O=gm.exec(t))!==null;){G&&(G=!1,N=new Xh(s,u),N.playlistOffset=S,N.setStart(S),N.sn=p,N.cc=E,T&&(N.bitrate=T),N.level=n,g&&(N.initSegment=g,g.rawProgramDateTime&&(N.rawProgramDateTime=g.rawProgramDateTime,g.rawProgramDateTime=null),X&&(N.setByteRange(X),X=null)));const pe=O[1];if(pe){N.duration=parseFloat(pe);const le=(" "+O[2]).slice(1);N.title=le||null,N.tagList.push(le?["INF",pe,le]:["INF",pe])}else if(O[3]){if(Ye(N.duration)){N.playlistOffset=S,N.setStart(S),z&&o1(N,z,f),N.sn=p,N.level=n,N.cc=E,h.push(N);const le=(" "+O[3]).slice(1);N.relurl=um(f,le),pm(N,j,m),j=N,S+=N.duration,p++,y=0,G=!0}}else{if(O=O[0].match(N8),!O){$t.warn("No matches on slow regex match for level playlist!");continue}for(U=1;U<O.length&&O[U]===void 0;U++);const le=(" "+O[U]).slice(1),se=(" "+O[U+1]).slice(1),Ce=O[U+2]?(" "+O[U+2]).slice(1):null;switch(le){case"BYTERANGE":j?N.setByteRange(se,j):N.setByteRange(se);break;case"PROGRAM-DATE-TIME":N.rawProgramDateTime=se,N.tagList.push(["PROGRAM-DATE-TIME",se]),K===-1&&(K=h.length);break;case"PLAYLIST-TYPE":f.type&&Vn(f,le,O),f.type=se.toUpperCase();break;case"MEDIA-SEQUENCE":f.startSN!==0?Vn(f,le,O):h.length>0&&l1(f,le,O),p=f.startSN=parseInt(se);break;case"SKIP":{f.skippedSegments&&Vn(f,le,O);const q=new or(se,f),Q=q.decimalInteger("SKIPPED-SEGMENTS");if(Ye(Q)){f.skippedSegments+=Q;for(let be=Q;be--;)h.push(null);p+=Q}const ie=q.enumeratedString("RECENTLY-REMOVED-DATERANGES");ie&&(f.recentlyRemovedDateranges=(f.recentlyRemovedDateranges||[]).concat(ie.split(" ")));break}case"TARGETDURATION":f.targetduration!==0&&Vn(f,le,O),f.targetduration=Math.max(parseInt(se),1);break;case"VERSION":f.version!==null&&Vn(f,le,O),f.version=parseInt(se);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":f.live||Vn(f,le,O),f.live=!1;break;case"#":(se||Ce)&&N.tagList.push(Ce?[se,Ce]:[se]);break;case"DISCONTINUITY":E++,N.tagList.push(["DIS"]);break;case"GAP":N.gap=!0,N.tagList.push([le]);break;case"BITRATE":N.tagList.push([le,se]),T=parseInt(se)*1e3,Ye(T)?N.bitrate=T:T=0;break;case"DATERANGE":{const q=new or(se,f),Q=new HS(q,f.dateRanges[q.ID],f.dateRangeTagCount);f.dateRangeTagCount++,Q.isValid||f.skippedSegments?f.dateRanges[Q.id]=Q:$t.warn(`Ignoring invalid DATERANGE tag: "${se}"`),N.tagList.push(["EXT-X-DATERANGE",se]);break}case"DEFINE":{const q=new or(se,f);"IMPORT"in q?b8(f,q,c):ZS(f,q,r)}break;case"DISCONTINUITY-SEQUENCE":f.startCC!==0?Vn(f,le,O):h.length>0&&l1(f,le,O),f.startCC=E=parseInt(se);break;case"KEY":{const q=r1(se,r,f);if(q.isSupported()){if(q.method==="NONE"){z=void 0;break}z||(z={});const Q=z[q.keyFormat];Q!=null&&Q.matches(q)||(Q&&(z=Ft({},z)),z[q.keyFormat]=q)}else $t.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${se}"`);break}case"START":f.startTimeOffset=n1(se);break;case"MAP":{const q=new or(se,f);if(N.duration){const Q=new Xh(s,u);a1(Q,q,n,z),g=Q,N.initSegment=g,g.rawProgramDateTime&&!N.rawProgramDateTime&&(N.rawProgramDateTime=g.rawProgramDateTime)}else{const Q=N.byteRangeEndOffset;if(Q){const ie=N.byteRangeStartOffset;X=`${Q-ie}@${ie}`}else X=null;a1(N,q,n,z),g=N,G=!0}g.cc=E;break}case"SERVER-CONTROL":te&&Vn(f,le,O),te=new or(se),f.canBlockReload=te.bool("CAN-BLOCK-RELOAD"),f.canSkipUntil=te.optionalFloat("CAN-SKIP-UNTIL",0),f.canSkipDateRanges=f.canSkipUntil>0&&te.bool("CAN-SKIP-DATERANGES"),f.partHoldBack=te.optionalFloat("PART-HOLD-BACK",0),f.holdBack=te.optionalFloat("HOLD-BACK",0);break;case"PART-INF":f.partTarget&&Vn(f,le,O),f.partTarget=new or(se).decimalFloatingPoint("PART-TARGET");break;case"PART":{let q=f.partList;q||(q=f.partList=[]);const Q=y>0?q[q.length-1]:void 0,ie=y++,be=new bG(new or(se,f),N,u,ie,Q);q.push(be),N.duration+=be.duration;break}case"PRELOAD-HINT":f.preloadHint=new or(se,f);break;case"RENDITION-REPORT":{const q=new or(se,f);f.renditionReports=f.renditionReports||[],f.renditionReports.push(q);break}default:$t.warn(`line parsed but not handled: ${O}`);break}}}j&&!j.relurl?(h.pop(),S-=j.duration,f.partList&&(f.fragmentHint=j)):f.partList&&(pm(N,j,m),N.cc=E,f.fragmentHint=N,z&&o1(N,z,f)),f.targetduration||(f.playlistParsingError=new Error("Missing Target Duration"));const ne=h.length,ae=h[0],oe=h[ne-1];if(S+=f.skippedSegments*f.targetduration,S>0&&ne&&oe){f.averagetargetduration=S/ne;const pe=oe.sn;f.endSN=pe!=="initSegment"?pe:0,f.live||(oe.endList=!0),K>0&&(M8(h,K),ae&&m.unshift(ae))}return f.fragmentHint&&(S+=f.fragmentHint.duration),f.totalduration=S,m.length&&f.dateRangeTagCount&&ae&&t1(m,f),f.endCC=E,f}};function t1(e,t){let r=e.length;if(!r)if(t.hasProgramDateTime){const d=t.fragments[t.fragments.length-1];e.push(d),r++}else return;const n=e[r-1],s=t.live?1/0:t.totalduration,a=Object.keys(t.dateRanges);for(let d=a.length;d--;){const u=t.dateRanges[a[d]],f=u.startDate.getTime();u.tagAnchor=n.ref;for(let h=r;h--;){var c;if(((c=e[h])==null?void 0:c.sn)<t.startSN)break;const m=D8(t,f,e,h,s);if(m!==-1){u.tagAnchor=t.fragments[m].ref;break}}}}function D8(e,t,r,n,s){const a=r[n];if(a){const d=a.programDateTime;if(t>=d||n===0){var c;if(t<=d+((((c=r[n+1])==null?void 0:c.start)||s)-a.start)*1e3){const u=r[n].sn-e.startSN;if(u<0)return-1;const f=e.fragments;if(f.length>r.length){const h=(r[n+1]||f[f.length-1]).sn-e.startSN;for(let m=h;m>u;m--){const g=f[m].programDateTime;if(t>=g&&t<g+f[m].duration*1e3)return m}}return u}}}return-1}function r1(e,t,r){var n,s;const a=new or(e,r),c=(n=a.METHOD)!=null?n:"",d=a.URI,u=a.hexadecimalInteger("IV"),f=a.KEYFORMATVERSIONS,h=(s=a.KEYFORMAT)!=null?s:"identity";return d&&a.IV&&!u&&$t.error(`Invalid IV: ${a.IV}`),new Sc(c,d?Po.resolve(d,t):"",h,(f||"1").split("/").map(Number).filter(Number.isFinite),u,a.KEYID)}function n1(e){const t=new or(e).decimalFloatingPoint("TIME-OFFSET");return Ye(t)?t:null}function i1(e,t){let r=(e||"").split(/[ ,]+/).filter(n=>n);["video","audio","text"].forEach(n=>{const s=r.filter(a=>tm(a,n));s.length&&(t[`${n}Codec`]=s.map(a=>a.split("/")[0]).join(","),r=r.filter(a=>s.indexOf(a)===-1))}),t.unknownCodecs=r}function s1(e,t,r){const n=t[r];n&&(e[r]=n)}function M8(e,t){let r=e[t];for(let n=t;n--;){const s=e[n];if(!s)return;s.programDateTime=r.programDateTime-s.duration*1e3,r=s}}function pm(e,t,r){e.rawProgramDateTime?r.push(e):t!=null&&t.programDateTime&&(e.programDateTime=t.endProgramDateTime)}function a1(e,t,r,n){e.relurl=t.URI,t.BYTERANGE&&e.setByteRange(t.BYTERANGE),e.level=r,e.sn="initSegment",n&&(e.levelkeys=n),e.initSegment=null}function o1(e,t,r){e.levelkeys=t;const{encryptedFragments:n}=r;(!n.length||n[n.length-1].levelkeys!==t)&&Object.keys(t).some(s=>t[s].isCommonEncryption)&&n.push(e)}function Vn(e,t,r){e.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${r[0]})`)}function l1(e,t,r){e.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${r[0]})`)}function vm(e,t){const r=t.startPTS;if(Ye(r)){let n=0,s;t.sn>e.sn?(n=r-e.start,s=e):(n=e.start-r,s=t),s.duration!==n&&s.setDuration(n)}else t.sn>e.sn?e.cc===t.cc&&e.minEndPTS?t.setStart(e.start+(e.minEndPTS-e.start)):t.setStart(e.start+e.duration):t.setStart(Math.max(e.start-t.duration,0))}function c1(e,t,r,n,s,a,c){n-r<=0&&(c.warn("Fragment should have a positive duration",t),n=r+t.duration,a=s+t.duration);let d=r,u=n;const f=t.startPTS,h=t.endPTS;if(Ye(f)){const E=Math.abs(f-r);e&&E>e.totalduration?c.warn(`media timestamps and playlist times differ by ${E}s for level ${t.level} ${e.url}`):Ye(t.deltaPTS)?t.deltaPTS=Math.max(E,t.deltaPTS):t.deltaPTS=E,d=Math.max(r,f),r=Math.min(r,f),s=t.startDTS!==void 0?Math.min(s,t.startDTS):s,u=Math.min(n,h),n=Math.max(n,h),a=t.endDTS!==void 0?Math.max(a,t.endDTS):a}const m=r-t.start;t.start!==0&&t.setStart(r),t.setDuration(n-t.start),t.startPTS=r,t.maxStartPTS=d,t.startDTS=s,t.endPTS=n,t.minEndPTS=u,t.endDTS=a;const g=t.sn;if(!e||g<e.startSN||g>e.endSN)return 0;let p;const y=g-e.startSN,S=e.fragments;for(S[y]=t,p=y;p>0;p--)vm(S[p],S[p-1]);for(p=y;p<S.length-1;p++)vm(S[p],S[p+1]);return e.fragmentHint&&vm(S[S.length-1],e.fragmentHint),e.PTSKnown=e.alignedSliding=!0,m}function $8(e,t,r){if(e===t)return;let n=null;const s=e.fragments;for(let h=s.length-1;h>=0;h--){const m=s[h].initSegment;if(m){n=m;break}}e.fragmentHint&&delete e.fragmentHint.endPTS;let a;O8(e,t,(h,m,g,p)=>{if((!t.startCC||t.skippedSegments)&&m.cc!==h.cc){const y=h.cc-m.cc;for(let S=g;S<p.length;S++)p[S].cc+=y;t.endCC=p[p.length-1].cc}Ye(h.startPTS)&&Ye(h.endPTS)&&(m.setStart(m.startPTS=h.startPTS),m.startDTS=h.startDTS,m.maxStartPTS=h.maxStartPTS,m.endPTS=h.endPTS,m.endDTS=h.endDTS,m.minEndPTS=h.minEndPTS,m.setDuration(h.endPTS-h.startPTS),m.duration&&(a=m),t.PTSKnown=t.alignedSliding=!0),h.hasStreams&&(m.elementaryStreams=h.elementaryStreams),m.loader=h.loader,h.hasStats&&(m.stats=h.stats),h.initSegment&&(m.initSegment=h.initSegment,n=h.initSegment)});const c=t.fragments,d=t.fragmentHint?c.concat(t.fragmentHint):c;if(n&&d.forEach(h=>{var m;h&&(!h.initSegment||h.initSegment.relurl===((m=n)==null?void 0:m.relurl))&&(h.initSegment=n)}),t.skippedSegments){if(t.deltaUpdateFailed=c.some(h=>!h),t.deltaUpdateFailed){r.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let h=t.skippedSegments;h--;)c.shift();t.startSN=c[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=R8(e.dateRanges,t,r));const h=e.fragments.filter(m=>m.rawProgramDateTime);if(e.hasProgramDateTime&&!t.hasProgramDateTime)for(let m=1;m<d.length;m++)d[m].programDateTime===null&&pm(d[m],d[m-1],h);t1(h,t)}t.endCC=c[c.length-1].cc}if(!t.startCC){var u;const h=h1(e,t.startSN-1);t.startCC=(u=h?.cc)!=null?u:c[0].cc}L8(e.partList,t.partList,(h,m)=>{m.elementaryStreams=h.elementaryStreams,m.stats=h.stats}),a?c1(t,a,a.startPTS,a.endPTS,a.startDTS,a.endDTS,r):d1(e,t),c.length&&(t.totalduration=t.edge-c[0].start),t.driftStartTime=e.driftStartTime,t.driftStart=e.driftStart;const f=t.advancedDateTime;if(t.advanced&&f){const h=t.edge;t.driftStart||(t.driftStartTime=f,t.driftStart=h),t.driftEndTime=f,t.driftEnd=h}else t.driftEndTime=e.driftEndTime,t.driftEnd=e.driftEnd,t.advancedDateTime=e.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=e.requestScheduled)}function R8(e,t,r){const{dateRanges:n,recentlyRemovedDateranges:s}=t,a=Ft({},e);s&&s.forEach(d=>{delete a[d]});const c=Object.keys(a).length;return c?(Object.keys(n).forEach(d=>{const u=a[d],f=new HS(n[d].attr,u);f.isValid?(a[d]=f,u||(f.tagOrder+=c)):r.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${zt(n[d].attr)}"`)}),a):n}function L8(e,t,r){if(e&&t){let n=0;for(let s=0,a=e.length;s<=a;s++){const c=e[s],d=t[s+n];c&&d&&c.index===d.index&&c.fragment.sn===d.fragment.sn?r(c,d):n--}}}function O8(e,t,r){const n=t.skippedSegments,s=Math.max(e.startSN,t.startSN)-t.startSN,a=(e.fragmentHint?1:0)+(n?t.endSN:Math.min(e.endSN,t.endSN))-t.startSN,c=t.startSN-e.startSN,d=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,u=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments;for(let f=s;f<=a;f++){const h=u[c+f];let m=d[f];if(n&&!m&&h&&(m=t.fragments[f]=h),h&&m){r(h,m,f,d);const g=h.relurl,p=m.relurl;if(g&&F8(g,p)){t.playlistParsingError=u1(`media sequence mismatch ${m.sn}:`,e,t,h,m);return}else if(h.cc!==m.cc){t.playlistParsingError=u1(`discontinuity sequence mismatch (${h.cc}!=${m.cc})`,e,t,h,m);return}}}}function u1(e,t,r,n,s){return new Error(`${e} ${s.url}
160
+ Playlist starting @${t.startSN}
161
+ ${t.m3u8}
162
+
163
+ Playlist starting @${r.startSN}
164
+ ${r.m3u8}`)}function d1(e,t,r=!0){const n=t.startSN+t.skippedSegments-e.startSN,s=e.fragments,a=n>=0;let c=0;if(a&&n<s.length)c=s[n].start;else if(a&&t.startSN===e.endSN+1)c=e.fragmentEnd;else if(a&&r)c=e.fragmentStart+n*t.levelTargetDuration;else if(!t.skippedSegments&&t.fragmentStart===0)c=e.fragmentStart;else return;bm(t,c)}function bm(e,t){if(t){const r=e.fragments;for(let n=e.skippedSegments;n<r.length;n++)r[n].addStart(t);e.fragmentHint&&e.fragmentHint.addStart(t)}}function f1(e,t=1/0){let r=1e3*e.targetduration;if(e.updated){const n=e.fragments;if(n.length&&r*4>t){const s=n[n.length-1].duration*1e3;s<r&&(r=s)}}else r/=2;return Math.round(r)}function h1(e,t,r){if(!e)return null;let n=e.fragments[t-e.startSN];return n||(n=e.fragmentHint,n&&n.sn===t)?n:t<e.startSN&&r&&r.sn===t?r:null}function m1(e,t,r){return e?g1(e.partList,t,r):null}function g1(e,t,r){if(e)for(let n=e.length;n--;){const s=e[n];if(s.index===r&&s.fragment.sn===t)return s}return null}function p1(e){e.forEach((t,r)=>{var n;(n=t.details)==null||n.fragments.forEach(s=>{s.level=r,s.initSegment&&(s.initSegment.level=r)})})}function F8(e,t){return e!==t&&t?v1(e)!==v1(t):!1}function v1(e){return e.replace(/\?[^?]*$/,"")}function Ao(e,t){for(let n=0,s=e.length;n<s;n++){var r;if(((r=e[n])==null?void 0:r.cc)===t)return e[n]}return null}function U8(e,t){return!!(e&&t.startCC<e.endCC&&t.endCC>e.startCC)}function b1(e,t){const r=e.start+t;e.startPTS=r,e.setStart(r),e.endPTS=r+e.duration}function y1(e,t){const r=t.fragments;for(let n=0,s=r.length;n<s;n++)b1(r[n],e);t.fragmentHint&&b1(t.fragmentHint,e),t.alignedSliding=!0}function B8(e,t){e&&(x1(t,e),t.alignedSliding||_c(t,e),!t.alignedSliding&&!t.skippedSegments&&d1(e,t,!1))}function x1(e,t){if(!U8(t,e))return;const r=Math.min(t.endCC,e.endCC),n=Ao(t.fragments,r),s=Ao(e.fragments,r);!n||!s||($t.log(`Aligning playlist at start of dicontinuity sequence ${r}`),y1(n.start-s.start,e))}function _c(e,t){if(!e.hasProgramDateTime||!t.hasProgramDateTime)return;const r=e.fragments,n=t.fragments;if(!r.length||!n.length)return;let s,a;const c=Math.min(t.endCC,e.endCC);t.startCC<c&&e.startCC<c&&(s=Ao(n,c),a=Ao(r,c)),(!s||!a)&&(s=n[Math.floor(n.length/2)],a=Ao(r,s.cc)||r[Math.floor(r.length/2)]);const d=s.programDateTime,u=a.programDateTime;!d||!u||y1((u-d)/1e3-(a.start-s.start),e)}function Ar(e,t,r){$r(e,t,r),e.addEventListener(t,r)}function $r(e,t,r){e.removeEventListener(t,r)}var z8={toString:function(e){let t="";const r=e.length;for(let n=0;n<r;n++)t+=`[${e.start(n).toFixed(3)}-${e.end(n).toFixed(3)}]`;return t}},Ne={STOPPED:"STOPPED",IDLE:"IDLE",KEY_LOADING:"KEY_LOADING",FRAG_LOADING:"FRAG_LOADING",FRAG_LOADING_WAITING_RETRY:"FRAG_LOADING_WAITING_RETRY",WAITING_TRACK:"WAITING_TRACK",PARSING:"PARSING",PARSED:"PARSED",ENDED:"ENDED",ERROR:"ERROR",WAITING_INIT_PTS:"WAITING_INIT_PTS",WAITING_LEVEL:"WAITING_LEVEL"},ym=class extends US{constructor(e,t,r,n,s){super(n,e.logger),this.hls=void 0,this.fragPrevious=null,this.fragCurrent=null,this.fragmentTracker=void 0,this.transmuxer=null,this._state=Ne.STOPPED,this.playlistType=void 0,this.media=null,this.mediaBuffer=null,this.config=void 0,this.bitrateTest=!1,this.lastCurrentTime=0,this.nextLoadPosition=0,this.startPosition=0,this.startTimeOffset=null,this.retryDate=0,this.levels=null,this.fragmentLoader=void 0,this.keyLoader=void 0,this.levelLastLoaded=null,this.startFragRequested=!1,this.decrypter=void 0,this.initPTS=[],this.buffering=!0,this.loadingParts=!1,this.loopSn=void 0,this.onMediaSeeking=()=>{const{config:a,fragCurrent:c,media:d,mediaBuffer:u,state:f}=this,h=d?d.currentTime:0,m=xt.bufferInfo(u||d,h,a.maxBufferHole),g=!m.len;if(this.log(`Media seeking to ${Ye(h)?h.toFixed(3):h}, state: ${f}, ${g?"out of":"in"} buffer`),this.state===Ne.ENDED)this.resetLoadingState();else if(c){const p=a.maxFragLookUpTolerance,y=c.start-p,S=c.start+c.duration+p;if(g||S<m.start||y>m.end){const E=h>S;(h<y||E)&&(E&&c.loader&&(this.log(`Cancelling fragment load for seek (sn: ${c.sn})`),c.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(d&&(this.fragmentTracker.removeFragmentsInRange(h,1/0,this.playlistType,!0),h>this.lastCurrentTime&&(this.lastCurrentTime=h),!this.loadingParts)){const p=Math.max(m.end,h),y=this.shouldLoadParts(this.getLevelDetails(),p);y&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${p.toFixed(2)}`),this.loadingParts=y)}this.hls.hasEnoughToStart||(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,g&&(this.startPosition=h)),g&&this.state===Ne.IDLE&&this.tickImmediate()},this.onMediaEnded=()=>{this.log("setting startPosition to 0 because media ended"),this.startPosition=this.lastCurrentTime=0},this.playlistType=s,this.hls=e,this.fragmentLoader=new p8(e.config),this.keyLoader=r,this.fragmentTracker=t,this.config=e.config,this.decrypter=new lm(e.config)}registerListeners(){const{hls:e}=this;e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_LOADED,this.onManifestLoaded,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_LOADED,this.onManifestLoaded,this),e.off($.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(e){}stopLoad(){if(this.state===Ne.STOPPED)return;this.fragmentLoader.abort(),this.keyLoader.abort(this.playlistType);const e=this.fragCurrent;e!=null&&e.loader&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.resetTransmuxer(),this.fragCurrent=null,this.fragPrevious=null,this.clearInterval(),this.clearNextTick(),this.state=Ne.STOPPED}get startPositionValue(){const{nextLoadPosition:e,startPosition:t}=this;return t===-1&&e?e:t}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(e,t){if(t.live||!this.media)return!1;const r=e.end||0,n=this.config.timelineOffset||0;if(r<=n)return!1;const s=e.buffered;this.config.maxBufferHole&&s&&s.length>1&&(e=xt.bufferedInfo(s,e.start,0));const a=e.nextStart;if(a&&a>n&&a<t.edge||this.media.currentTime<e.start)return!1;const c=t.partList;if(c!=null&&c.length){const u=c[c.length-1];return xt.isBuffered(this.media,u.start+u.duration/2)}const d=t.fragments[t.fragments.length-1].type;return this.fragmentTracker.isEndListAppended(d)}getLevelDetails(){if(this.levels&&this.levelLastLoaded!==null)return this.levelLastLoaded.details}get timelineOffset(){const e=this.config.timelineOffset;if(e){var t;return((t=this.getLevelDetails())==null?void 0:t.appliedTimelineOffset)||e}return 0}onMediaAttached(e,t){const r=this.media=this.mediaBuffer=t.media;Ar(r,"seeking",this.onMediaSeeking),Ar(r,"ended",this.onMediaEnded);const n=this.config;this.levels&&n.autoStartLoad&&this.state===Ne.STOPPED&&this.startLoad(n.startPosition)}onMediaDetaching(e,t){const r=!!t.transferMedia,n=this.media;if(n!==null){if(n.ended&&(this.log("MSE detaching and video ended, reset startPosition"),this.startPosition=this.lastCurrentTime=0),$r(n,"seeking",this.onMediaSeeking),$r(n,"ended",this.onMediaEnded),this.keyLoader&&!r&&this.keyLoader.detach(),this.media=this.mediaBuffer=null,this.loopSn=void 0,r){this.resetLoadingState(),this.resetTransmuxer();return}this.loadingParts=!1,this.fragmentTracker.removeAllFragments(),this.stopLoad()}}onManifestLoading(){this.initPTS=[],this.levels=this.levelLastLoaded=this.fragCurrent=null,this.lastCurrentTime=this.startPosition=0,this.startFragRequested=!1}onError(e,t){}onManifestLoaded(e,t){this.startTimeOffset=t.startTimeOffset}onHandlerDestroying(){this.stopLoad(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),super.onHandlerDestroying(),this.hls=this.onMediaSeeking=this.onMediaEnded=null}onHandlerDestroyed(){this.state=Ne.STOPPED,this.fragmentLoader&&this.fragmentLoader.destroy(),this.keyLoader&&this.keyLoader.destroy(),this.decrypter&&this.decrypter.destroy(),this.hls=this.log=this.warn=this.decrypter=this.keyLoader=this.fragmentLoader=this.fragmentTracker=null,super.onHandlerDestroyed()}loadFragment(e,t,r){this.startFragRequested=!0,this._loadFragForPlayback(e,t,r)}_loadFragForPlayback(e,t,r){const n=s=>{const a=s.frag;if(this.fragContextChanged(a)){this.warn(`${a.type} sn: ${a.sn}${s.part?" part: "+s.part.index:""} of ${this.fragInfo(a,!1,s.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(a);return}a.stats.chunkCount++,this._handleFragmentLoadProgress(s)};this._doFragLoad(e,t,r,n).then(s=>{if(!s)return;const a=this.state,c=s.frag;if(this.fragContextChanged(c)){(a===Ne.FRAG_LOADING||!this.fragCurrent&&a===Ne.PARSING)&&(this.fragmentTracker.removeFragment(c),this.state=Ne.IDLE);return}"payload"in s&&(this.log(`Loaded ${c.type} sn: ${c.sn} of ${this.playlistLabel()} ${c.level}`),this.hls.trigger($.FRAG_LOADED,s)),this._handleFragmentLoadComplete(s)}).catch(s=>{this.state===Ne.STOPPED||this.state===Ne.ERROR||(this.warn(`Frag error: ${s?.message||s}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var t;const{fragmentTracker:r}=this;if(r.getState(e)===pr.APPENDING){const n=e.type,s=this.getFwdBufferInfo(this.mediaBuffer,n),a=Math.max(e.duration,s?s.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?e.sn-c.sn:0)===1||this.reduceMaxBufferLength(a,e.duration))&&r.removeFragment(e)}else((t=this.mediaBuffer)==null?void 0:t.buffered.length)===0?r.removeAllFragments():r.hasParts(e.type)&&(r.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),r.getState(e)===pr.PARTIAL&&r.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const t=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}waitForLive(e){const t=e.details;return t?.live&&t.type!=="EVENT"&&(this.levelLastLoaded!==e||t.expired)}flushMainBuffer(e,t,r=null){if(!(e-t))return;const n={startOffset:e,endOffset:t,type:r};this.hls.trigger($.BUFFER_FLUSHING,n)}_loadInitSegment(e,t){this._doFragLoad(e,t).then(r=>{const n=r?.frag;if(!n||this.fragContextChanged(n)||!this.levels)throw new Error("init load aborted");return r}).then(r=>{const{hls:n}=this,{frag:s,payload:a}=r,c=s.decryptdata;if(a&&a.byteLength>0&&c!=null&&c.key&&c.iv&&ks(c.method)){const d=self.performance.now();return this.decrypter.decrypt(new Uint8Array(a),c.key.buffer,c.iv.buffer,dm(c.method)).catch(u=>{throw n.trigger($.ERROR,{type:it.MEDIA_ERROR,details:fe.FRAG_DECRYPT_ERROR,fatal:!1,error:u,reason:u.message,frag:s}),u}).then(u=>{const f=self.performance.now();return n.trigger($.FRAG_DECRYPTED,{frag:s,payload:u,stats:{tstart:d,tdecrypt:f}}),r.payload=u,this.completeInitSegmentLoad(r)})}return this.completeInitSegmentLoad(r)}).catch(r=>{this.state===Ne.STOPPED||this.state===Ne.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:t}=this;if(!t)throw new Error("init load aborted, missing levels");const r=e.frag.stats;this.state!==Ne.STOPPED&&(this.state=Ne.IDLE),e.frag.data=new Uint8Array(e.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(e,t){var r,n;const s=e.tracks;if(s&&!t.encrypted&&((r=s.audio)!=null&&r.encrypted||(n=s.video)!=null&&n.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const a=this.media,c=new Error(`Encrypted track with no key in ${this.fragInfo(t)} (media ${a?"attached mediaKeys: "+a.mediaKeys:"detached"})`);return this.warn(c.message),!a||a.mediaKeys?!1:(this.hls.trigger($.ERROR,{type:it.KEY_SYSTEM_ERROR,details:fe.KEY_SYSTEM_NO_KEYS,fatal:!1,error:c,frag:t}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(e){const{fragCurrent:t}=this;return!e||!t||e.sn!==t.sn||e.level!==t.level}fragBufferedComplete(e,t){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)} > buffer:${r?z8.toString(xt.getBuffered(r)):"(detached)"})`),ar(e)){var n;if(e.type!==Je.SUBTITLE){const a=e.elementaryStreams;if(!Object.keys(a).some(c=>!!a[c])){this.state=Ne.IDLE;return}}const s=(n=this.levels)==null?void 0:n[e.level];s!=null&&s.fragmentError&&(this.log(`Resetting level fragment error count of ${s.fragmentError} on frag buffered`),s.fragmentError=0)}this.state=Ne.IDLE}_handleFragmentLoadComplete(e){const{transmuxer:t}=this;if(!t)return;const{frag:r,part:n,partsLoaded:s}=e,a=!s||s.length===0||s.some(d=>!d),c=new cm(r.level,r.sn,r.stats.chunkCount+1,0,n?n.index:-1,!a);t.flush(c)}_handleFragmentLoadProgress(e){}_doFragLoad(e,t,r=null,n){var s;this.fragCurrent=e;const a=t.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let c=null;if(e.encrypted&&!((s=e.decryptdata)!=null&&s.key)){if(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.playlistLabel()} ${e.level}`),this.state=Ne.KEY_LOADING,this.fragCurrent=e,c=this.keyLoader.load(e).then(m=>{if(!this.fragContextChanged(m.frag))return this.hls.trigger($.KEY_LOADED,m),this.state===Ne.KEY_LOADING&&(this.state=Ne.IDLE),m}),this.hls.trigger($.KEY_LOADING,{frag:e}),this.fragCurrent===null)return this.log("context changed in KEY_LOADING"),Promise.resolve(null)}else e.encrypted||(c=this.keyLoader.loadClear(e,a.encryptedFragments,this.startFragRequested),c&&this.log("[eme] blocking frag load until media-keys acquired"));const d=this.fragPrevious;if(ar(e)&&(!d||e.sn!==d.sn)){const m=this.shouldLoadParts(t.details,e.end);m!==this.loadingParts&&(this.log(`LL-Part loading ${m?"ON":"OFF"} loading sn ${d?.sn}->${e.sn}`),this.loadingParts=m)}if(r=Math.max(e.start,r||0),this.loadingParts&&ar(e)){const m=a.partList;if(m&&n){r>a.fragmentEnd&&a.fragmentHint&&(e=a.fragmentHint);const g=this.getNextPart(m,e,r);if(g>-1){const p=m[g];e=this.fragCurrent=p.fragment,this.log(`Loading ${e.type} sn: ${e.sn} part: ${p.index} (${g}/${m.length-1}) of ${this.fragInfo(e,!1,p)}) cc: ${e.cc} [${a.startSN}-${a.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=p.start+p.duration,this.state=Ne.FRAG_LOADING;let y;return c?y=c.then(S=>!S||this.fragContextChanged(S.frag)?null:this.doFragPartsLoad(e,p,t,n)).catch(S=>this.handleFragLoadError(S)):y=this.doFragPartsLoad(e,p,t,n).catch(S=>this.handleFragLoadError(S)),this.hls.trigger($.FRAG_LOADING,{frag:e,part:p,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):y}else if(!e.url||this.loadedEndOfParts(m,r))return Promise.resolve(null)}}if(ar(e)&&this.loadingParts){var u;this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${e.sn} loaded parts: ${(u=a.partList)==null?void 0:u.filter(m=>m.loaded).map(m=>`[${m.start}-${m.end}]`)}`),this.loadingParts=!1}else if(!e.url)return Promise.resolve(null);this.log(`Loading ${e.type} sn: ${e.sn} of ${this.fragInfo(e,!1)}) cc: ${e.cc} ${"["+a.startSN+"-"+a.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),Ye(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Ne.FRAG_LOADING;const f=this.config.progressive&&e.type!==Je.SUBTITLE;let h;return f&&c?h=c.then(m=>!m||this.fragContextChanged(m.frag)?null:this.fragmentLoader.load(e,n)).catch(m=>this.handleFragLoadError(m)):h=Promise.all([this.fragmentLoader.load(e,f?n:void 0),c]).then(([m])=>(!f&&n&&n(m),m)).catch(m=>this.handleFragLoadError(m)),this.hls.trigger($.FRAG_LOADING,{frag:e,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(e,t,r,n){return new Promise((s,a)=>{var c;const d=[],u=(c=r.details)==null?void 0:c.partList,f=h=>{this.fragmentLoader.loadPart(e,h,n).then(m=>{d[h.index]=m;const g=m.part;this.hls.trigger($.FRAG_LOADED,m);const p=m1(r.details,e.sn,h.index+1)||g1(u,e.sn,h.index+1);if(p)f(p);else return s({frag:e,part:g,partsLoaded:d})}).catch(a)};f(t)})}handleFragLoadError(e){if("data"in e){const t=e.data;t.frag&&t.details===fe.INTERNAL_ABORTED?this.handleFragLoadAborted(t.frag,t.part):t.frag&&t.type===it.KEY_SYSTEM_ERROR?(t.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(t.frag)):this.hls.trigger($.ERROR,t)}else this.hls.trigger($.ERROR,{type:it.OTHER_ERROR,details:fe.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const t=this.getCurrentContext(e);if(!t||this.state!==Ne.PARSING){!this.fragCurrent&&this.state!==Ne.STOPPED&&this.state!==Ne.ERROR&&(this.state=Ne.IDLE);return}const{frag:r,part:n,level:s}=t,a=self.performance.now();r.stats.parsing.end=a,n&&(n.stats.parsing.end=a);const c=this.getLevelDetails(),d=c&&r.sn>c.endSN||this.shouldLoadParts(c,r.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(r,n,s,e.partial)}shouldLoadParts(e,t){if(this.config.lowLatencyMode){if(!e)return this.loadingParts;if(e.partList){var r;const s=e.partList[0];if(s.fragment.type===Je.SUBTITLE)return!1;if(t>=s.end+(((r=e.fragmentHint)==null?void 0:r.duration)||0)){var n;if((this.hls.hasEnoughToStart?((n=this.media)==null?void 0:n.currentTime)||this.lastCurrentTime:this.getLoadPosition())>s.start-s.fragment.duration)return!0}}}return!1}getCurrentContext(e){const{levels:t,fragCurrent:r}=this,{level:n,sn:s,part:a}=e;if(!(t!=null&&t[n]))return this.warn(`Levels object was unset while buffering fragment ${s} of ${this.playlistLabel()} ${n}. The current chunk will not be buffered.`),null;const c=t[n],d=c.details,u=a>-1?m1(d,s,a):null,f=u?u.fragment:h1(d,s,r);return f?(r&&r!==f&&(f.stats=r.stats),{frag:f,part:u,level:c}):null}bufferFragmentData(e,t,r,n,s){if(this.state!==Ne.PARSING)return;const{data1:a,data2:c}=e;let d=a;if(c&&(d=nn(a,c)),!d.length)return;const u=this.initPTS[t.cc],f=u?-u.baseTime/u.timescale:void 0,h={type:e.type,frag:t,part:r,chunkMeta:n,offset:f,parent:t.type,data:d};if(this.hls.trigger($.BUFFER_APPENDING,h),e.dropped&&e.independent&&!r){if(s)return;this.flushBufferGap(t)}}flushBufferGap(e){const t=this.media;if(!t)return;if(!xt.isBuffered(t,t.currentTime)){this.flushMainBuffer(0,e.start);return}const r=t.currentTime,n=xt.bufferInfo(t,r,0),s=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,s*.25),c=Math.max(Math.min(e.start-a,n.end-a),r+a);e.start-c>a&&this.flushMainBuffer(c,e.start)}getFwdBufferInfo(e,t){var r;const n=this.getLoadPosition();if(!Ye(n))return null;const s=this.lastCurrentTime>n||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(e,n,t,s)}getFwdBufferInfoAtPos(e,t,r,n){const s=xt.bufferInfo(e,t,n);if(s.len===0&&s.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(t,r);if(a&&(s.nextStart<=a.end||a.gap)){const c=Math.max(Math.min(s.nextStart,a.end)-t,n);return xt.bufferInfo(e,t,c)}}return s}getMaxBufferLength(e){const{config:t}=this;let r;return e?r=Math.max(8*t.maxBufferSize/e,t.maxBufferLength):r=t.maxBufferLength,Math.min(r,t.maxMaxBufferLength)}exceedsMaxBuffer(e,t,r){const n=e.nextStart;if(n&&r.start>n){const s=e.buffered;if(s){let a=e.len;const c=e.bufferedIndex;for(let d=s.length-1;d>c;d--)s[d].start<r.start&&(a+=s[d].end-s[d].start);return a>=t}}return!1}reduceMaxBufferLength(e,t){const r=this.config,n=Math.max(Math.min(e-t,r.maxBufferLength),t),s=Math.max(e-t*3,r.maxMaxBufferLength/2,n);return s>=n?(r.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0):!1}getAppendedFrag(e,t=Je.MAIN){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(e,t):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(e,t){const r=t.fragments,n=r.length;if(!n)return null;const{config:s}=this,a=t.fragmentStart,c=s.lowLatencyMode&&!!t.partList;let d=null;if(t.live){const h=s.initialLiveManifestSize;if(n<h)return this.warn(`Not enough fragments to start playback (have: ${n}, need: ${h})`),null;if(!t.PTSKnown&&!this.startFragRequested&&this.startPosition===-1||e<a){var u;c&&!this.loadingParts&&(this.log("LL-Part loading ON for initial live fragment"),this.loadingParts=!0),d=this.getInitialLiveFragment(t);const m=this.config.startPosition,g=this.hls.startPosition,p=this.hls.liveSyncPosition,y=((u=d)==null?void 0:u.start)||0;let S,E;g!==-1&&g>=a?(S=g,E=g===m?"config":"next load start"):p!==null?(S=p,E="live edge"):(S=e,E="buffer pos"),S<y&&(S=y,E="live frag start"),S<a&&(S=a,E="playlist start"),(this.startPosition!=S||this.nextLoadPosition!=S)&&(this.log(`Setting startPosition to ${S.toFixed(3)} ${g===-1?"":`(from ${m}) `}based on ${E}. live edge: ${p} live frag start: ${y.toFixed(3)} playlist start: ${a.toFixed(3)} buffer pos: ${e}`),this.startPosition=this.nextLoadPosition=S)}}else e<=a&&(d=r[0]);if(!d){const h=this.loadingParts?t.partEnd:t.fragmentEnd;d=this.getFragmentAtPosition(e,h,t)}let f=this.filterReplacedPrimary(d,t);if(!f&&d){const h=d.sn-t.startSN;f=this.filterReplacedPrimary(r[h+1]||null,t)}return this.mapToInitFragWhenRequired(f)}isLoopLoading(e,t){if(this.nextLoadPosition<=t)return!1;const r=this.fragmentTracker.getState(e);return r===pr.OK||r===pr.PARTIAL&&!!e.gap}getNextFragmentLoopLoading(e,t,r,n,s){let a=null;if(e.gap&&(a=this.getNextFragment(this.nextLoadPosition,t),a&&!a.gap&&r.nextStart)){const c=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,n,0);if(c!==null&&r.len+c.len>=s){const d=a.sn;return this.loopSn!==d&&(this.log(`buffer full after gaps in "${n}" playlist starting at sn: ${d}`),this.loopSn=d),null}}return this.loopSn=void 0,a}get primaryPrefetch(){if(S1(this.config)){var e;if(!((e=this.hls.interstitialsManager)==null||(e=e.playingItem)==null)&&e.event)return!0}return!1}filterReplacedPrimary(e,t){if(!e)return e;if(S1(this.config)&&e.type!==Je.SUBTITLE){const r=this.hls.interstitialsManager,n=r?.bufferingItem;if(n){const a=n.event;if(a){if(a.appendInPlace||Math.abs(e.start-n.start)>1||n.start===0)return null}else if(e.end<=n.start&&t?.live===!1||e.start>n.end&&n.nextEvent&&(n.nextEvent.appendInPlace||e.start-n.end>1))return null}const s=r?.playerQueue;if(s)for(let a=s.length;a--;){const c=s[a].interstitial;if(c.appendInPlace&&e.start>=c.startTime&&e.end<=c.resumeTime)return null}}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!e.initSegment.data&&!this.bitrateTest?e.initSegment:e}getNextPart(e,t,r){let n=-1,s=!1,a=!0;for(let c=0,d=e.length;c<d;c++){const u=e[c];if(a=a&&!u.independent,n>-1&&r<u.start)break;const f=u.loaded;f?n=-1:(s||(u.independent||a)&&u.fragment===t)&&(u.fragment!==t&&this.warn(`Need buffer at ${r} but next unloaded part starts at ${u.start}`),n=c),s=f}return n}loadedEndOfParts(e,t){let r;for(let n=e.length;n--;){if(r=e[n],!r.loaded)return!1;if(t>r.start)return!0}return!1}getInitialLiveFragment(e){const t=e.fragments,r=this.fragPrevious;let n=null;if(r){if(e.hasProgramDateTime&&(n=i8(t,r.endProgramDateTime,this.config.maxFragLookUpTolerance),n&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`)),!n){const s=r.sn+1;if(s>=e.startSN&&s<=e.endSN){const a=t[s-e.startSN];r.cc===a.cc&&(n=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${n.sn}`))}n||(n=jS(e,r.cc,r.end),n&&this.log(`Live playlist, switching playlist, load frag with same CC: ${n.sn}`))}}else{const s=this.hls.liveSyncPosition;s!==null&&(n=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return n}getFragmentAtPosition(e,t,r){const{config:n}=this;let{fragPrevious:s}=this,{fragments:a,endSN:c}=r;const{fragmentHint:d}=r,{maxFragLookUpTolerance:u}=n,f=r.partList,h=!!(this.loadingParts&&f!=null&&f.length&&d);h&&!this.bitrateTest&&f[f.length-1].fragment.sn===d.sn&&(a=a.concat(d),c=d.sn);let m;if(e<t){var g;const p=e<this.lastCurrentTime||e>t-u||(g=this.media)!=null&&g.paused||!this.startFragRequested?0:u;m=Fi(s,a,e,p)}else m=a[a.length-1];if(m){const p=m.sn-r.startSN,y=this.fragmentTracker.getState(m);if((y===pr.OK||y===pr.PARTIAL&&m.gap)&&(s=m),s&&m.sn===s.sn&&(!h||f[0].fragment.sn>m.sn||!r.live)&&m.level===s.level){const S=a[p+1];m.sn<c&&this.fragmentTracker.getState(S)!==pr.OK?m=S:m=null}}return m}alignPlaylists(e,t,r){const n=e.fragments.length;if(!n)return this.warn("No fragments in live playlist"),0;const s=e.fragmentStart,a=!t,c=e.alignedSliding&&Ye(s);if(a||!c&&!s){B8(r,e);const d=e.fragmentStart;return this.log(`Live playlist sliding: ${d.toFixed(2)} start-sn: ${t?t.startSN:"na"}->${e.startSN} fragments: ${n}`),d}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,t){let r=this.startPosition;r<t&&(r=-1);const n=this.timelineOffset;if(r===-1){const s=this.startTimeOffset!==null,a=s?this.startTimeOffset:e.startTimeOffset;a!==null&&Ye(a)?(r=t+a,a<0&&(r+=e.edge),r=Math.min(Math.max(t,r),t+e.totalduration),this.log(`Setting startPosition to ${r} for start time offset ${a} found in ${s?"multivariant":"media"} playlist`),this.startPosition=r):e.live?(r=this.hls.liveSyncPosition||t,this.log(`Setting startPosition to -1 to start at live edge ${r}`),this.startPosition=-1):(this.log("setting startPosition to 0 by default"),this.startPosition=r=0),this.lastCurrentTime=r+n}this.nextLoadPosition=r+n}getLoadPosition(){var e;const{media:t}=this;let r=0;return(e=this.hls)!=null&&e.hasEnoughToStart&&t?r=t.currentTime:this.nextLoadPosition>=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(e,t){this.transmuxer&&e.type===this.playlistType&&ar(e)&&e.stats.aborted&&(this.log(`Fragment ${e.sn}${t?" part "+t.index:""} of ${this.playlistLabel()} ${e.level} was aborted`),this.resetFragmentLoading(e))}resetFragmentLoading(e){(!this.fragCurrent||!this.fragContextChanged(e)&&this.state!==Ne.FRAG_LOADING_WAITING_RETRY)&&(this.state=Ne.IDLE)}onFragmentOrKeyLoadError(e,t){var r;if(t.chunkMeta&&!t.frag){const E=this.getCurrentContext(t.chunkMeta);E&&(t.frag=E.frag)}const n=t.frag;if(!n||n.type!==e||!this.levels)return;if(this.fragContextChanged(n)){var s;this.warn(`Frag load error must match current frag to retry ${n.url} > ${(s=this.fragCurrent)==null?void 0:s.url}`);return}const a=t.details===fe.FRAG_GAP;a&&this.fragmentTracker.fragBuffered(n,!0);const c=t.errorAction;if(!c){this.state=Ne.ERROR;return}const{action:d,flags:u,retryCount:f=0,retryConfig:h}=c,m=!!h,g=m&&d===Sr.RetryRequest,p=m&&!c.resolved&&u===Zr.MoveAllAlternatesMatchingHost,y=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!g&&p&&ar(n)&&!n.endList&&y&&!DS(t))this.resetFragmentErrors(e),this.treatAsGap(n),c.resolved=!0;else if((g||p)&&f<h.maxNumRetry){var S;const E=om((S=t.response)==null?void 0:S.code),T=am(h,f);if(this.resetStartWhenNotLoaded(),this.retryDate=self.performance.now()+T,this.state=Ne.FRAG_LOADING_WAITING_RETRY,c.resolved=!0,E){this.log("Waiting for connection (offline)"),this.retryDate=1/0,t.reason="offline";return}this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${t.details}, retrying loading ${f+1}/${h.maxNumRetry} in ${T}ms`)}else if(h)if(this.resetFragmentErrors(e),f<h.maxNumRetry)!a&&d!==Sr.RemoveAlternatePermanently&&(c.resolved=!0);else{this.warn(`${t.details} reached or exceeded max retry (${f})`);return}else d===Sr.SendAlternateToPenaltyBox?this.state=Ne.WAITING_LEVEL:this.state=Ne.ERROR;this.tickImmediate()}checkRetryDate(){const e=self.performance.now(),t=this.retryDate,r=t===1/0;(!t||e>=t||r&&!om(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Ne.IDLE)}reduceLengthAndFlushBuffer(e){if(this.state===Ne.PARSING||this.state===Ne.PARSED){const t=e.frag,r=e.parent,n=this.getFwdBufferInfo(this.mediaBuffer,r),s=n&&n.len>.5;s&&this.reduceMaxBufferLength(n.len,t?.duration||10);const a=!s;return a&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${r} buffer`),t&&(this.fragmentTracker.removeFragment(t),this.nextLoadPosition=t.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===Je.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Ne.STOPPED&&(this.state=Ne.IDLE)}afterBufferFlushed(e,t,r){if(!e)return;const n=xt.getBuffered(e);this.fragmentTracker.detectEvictedFragments(t,n,r),this.state===Ne.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Ne.STOPPED&&(this.state=Ne.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const e=this.levelLastLoaded,t=e?e.details:null;t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.log(`Loading context changed while buffering sn ${e.sn} of ${this.playlistLabel()} ${e.level===-1?"<removed>":e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,t,r,n){const s=r.details;if(!s){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((c,d)=>{const u=e.elementaryStreams[d];if(u){const f=u.endPTS-u.startPTS;if(f<=0)return this.warn(`Could not parse fragment ${e.sn} ${d} duration reliably (${f})`),c||!1;const h=n?0:c1(s,e,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger($.LEVEL_PTS_UPDATED,{details:s,level:r,drift:h,type:d,frag:e,start:u.startPTS,end:u.endPTS}),!0}return c},!1)){var a;const c=((a=this.transmuxer)==null?void 0:a.error)===null;if((r.fragmentError===0||c&&(r.fragmentError<2||e.endList))&&this.treatAsGap(e,r),c){const d=new Error(`Found no media in fragment ${e.sn} of ${this.playlistLabel()} ${e.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger($.ERROR,{type:it.MEDIA_ERROR,details:fe.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:e,reason:`Found no media in msn ${e.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Ne.PARSED,this.log(`Parsed ${e.type} sn: ${e.sn}${t?" part: "+t.index:""} of ${this.fragInfo(e,!1,t)})`),this.hls.trigger($.FRAG_PARSED,{frag:e,part:t})}playlistLabel(){return this.playlistType===Je.MAIN?"level":"track"}fragInfo(e,t=!0,r){var n,s;return`${this.playlistLabel()} ${e.level} (${r?"part":"frag"}:[${((n=t&&!r?e.startPTS:(r||e).start)!=null?n:NaN).toFixed(3)}-${((s=t&&!r?e.endPTS:(r||e).end)!=null?s:NaN).toFixed(3)}]${r&&e.type==="main"?"INDEPENDENT="+(r.independent?"YES":"NO"):""}`}treatAsGap(e,t){t&&t.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)}resetTransmuxer(){var e;(e=this.transmuxer)==null||e.reset()}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(e){const t=this._state;t!==e&&(this._state=e,this.log(`${t}->${e}`))}get state(){return this._state}};function S1(e){return!!e.interstitialsController&&e.enableInterstitialPlayback!==!1}var _1=class{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:t}=this;let r;if(e.length)e.length===1?r=e[0]:r=G8(e,t);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}};function G8(e,t){const r=new Uint8Array(t);let n=0;for(let s=0;s<e.length;s++){const a=e[s];r.set(a,n),n+=a.length}return r}var xm={exports:{}},w1;function Z8(){return w1||(w1=1,(function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function s(u,f,h){this.fn=u,this.context=f,this.once=h||!1}function a(u,f,h,m,g){if(typeof h!="function")throw new TypeError("The listener must be a function");var p=new s(h,m||u,g),y=r?r+f:f;return u._events[y]?u._events[y].fn?u._events[y]=[u._events[y],p]:u._events[y].push(p):(u._events[y]=p,u._eventsCount++),u}function c(u,f){--u._eventsCount===0?u._events=new n:delete u._events[f]}function d(){this._events=new n,this._eventsCount=0}d.prototype.eventNames=function(){var f=[],h,m;if(this._eventsCount===0)return f;for(m in h=this._events)t.call(h,m)&&f.push(r?m.slice(1):m);return Object.getOwnPropertySymbols?f.concat(Object.getOwnPropertySymbols(h)):f},d.prototype.listeners=function(f){var h=r?r+f:f,m=this._events[h];if(!m)return[];if(m.fn)return[m.fn];for(var g=0,p=m.length,y=new Array(p);g<p;g++)y[g]=m[g].fn;return y},d.prototype.listenerCount=function(f){var h=r?r+f:f,m=this._events[h];return m?m.fn?1:m.length:0},d.prototype.emit=function(f,h,m,g,p,y){var S=r?r+f:f;if(!this._events[S])return!1;var E=this._events[S],T=arguments.length,j,N;if(E.fn){switch(E.once&&this.removeListener(f,E.fn,void 0,!0),T){case 1:return E.fn.call(E.context),!0;case 2:return E.fn.call(E.context,h),!0;case 3:return E.fn.call(E.context,h,m),!0;case 4:return E.fn.call(E.context,h,m,g),!0;case 5:return E.fn.call(E.context,h,m,g,p),!0;case 6:return E.fn.call(E.context,h,m,g,p,y),!0}for(N=1,j=new Array(T-1);N<T;N++)j[N-1]=arguments[N];E.fn.apply(E.context,j)}else{var O=E.length,U;for(N=0;N<O;N++)switch(E[N].once&&this.removeListener(f,E[N].fn,void 0,!0),T){case 1:E[N].fn.call(E[N].context);break;case 2:E[N].fn.call(E[N].context,h);break;case 3:E[N].fn.call(E[N].context,h,m);break;case 4:E[N].fn.call(E[N].context,h,m,g);break;default:if(!j)for(U=1,j=new Array(T-1);U<T;U++)j[U-1]=arguments[U];E[N].fn.apply(E[N].context,j)}}return!0},d.prototype.on=function(f,h,m){return a(this,f,h,m,!1)},d.prototype.once=function(f,h,m){return a(this,f,h,m,!0)},d.prototype.removeListener=function(f,h,m,g){var p=r?r+f:f;if(!this._events[p])return this;if(!h)return c(this,p),this;var y=this._events[p];if(y.fn)y.fn===h&&(!g||y.once)&&(!m||y.context===m)&&c(this,p);else{for(var S=0,E=[],T=y.length;S<T;S++)(y[S].fn!==h||g&&!y[S].once||m&&y[S].context!==m)&&E.push(y[S]);E.length?this._events[p]=E.length===1?E[0]:E:c(this,p)}return this},d.prototype.removeAllListeners=function(f){var h;return f?(h=r?r+f:f,this._events[h]&&c(this,h)):(this._events=new n,this._eventsCount=0),this},d.prototype.off=d.prototype.removeListener,d.prototype.addListener=d.prototype.on,d.prefixed=r,d.EventEmitter=d,e.exports=d})(xm)),xm.exports}var Sm=pG(Z8()),jo="1.6.16",Cs={};function V8(){return typeof __HLS_WORKER_BUNDLE__=="function"}function H8(){const e=Cs[jo];if(e)return e.clientCount++,e;const t=new self.Blob([`var exports={};var module={exports:exports};function define(f){f()};define.amd=true;(${__HLS_WORKER_BUNDLE__.toString()})(true);`],{type:"text/javascript"}),r=self.URL.createObjectURL(t),n={worker:new self.Worker(r),objectURL:r,clientCount:1};return Cs[jo]=n,n}function K8(e){const t=Cs[e];if(t)return t.clientCount++,t;const r=new self.URL(e,self.location.href).href,n={worker:new self.Worker(r),scriptURL:r,clientCount:1};return Cs[e]=n,n}function W8(e){const t=Cs[e||jo];if(t&&t.clientCount--===1){const{worker:r,objectURL:n}=t;delete Cs[e||jo],n&&self.URL.revokeObjectURL(n),r.terminate()}}function E1(e,t){return t+10<=e.length&&e[t]===51&&e[t+1]===68&&e[t+2]===73&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function _m(e,t){return t+10<=e.length&&e[t]===73&&e[t+1]===68&&e[t+2]===51&&e[t+3]<255&&e[t+4]<255&&e[t+6]<128&&e[t+7]<128&&e[t+8]<128&&e[t+9]<128}function wc(e,t){let r=0;return r=(e[t]&127)<<21,r|=(e[t+1]&127)<<14,r|=(e[t+2]&127)<<7,r|=e[t+3]&127,r}function No(e,t){const r=t;let n=0;for(;_m(e,t);){n+=10;const s=wc(e,t+6);n+=s,E1(e,t+10)&&(n+=10),t+=n}if(n>0)return e.subarray(r,r+n)}function q8(e,t,r,n){const s=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],a=t[r+2],c=a>>2&15;if(c>12){const p=new Error(`invalid ADTS sampling index:${c}`);e.emit($.ERROR,$.ERROR,{type:it.MEDIA_ERROR,details:fe.FRAG_PARSING_ERROR,fatal:!0,error:p,reason:p.message});return}const d=(a>>6&3)+1,u=t[r+3]>>6&3|(a&1)<<2,f="mp4a.40."+d,h=s[c];let m=c;(d===5||d===29)&&(m-=3);const g=[d<<3|(m&14)>>1,(m&1)<<7|u<<3];return $t.log(`manifest codec:${n}, parsed codec:${f}, channels:${u}, rate:${h} (ADTS object type:${d} sampling index:${c})`),{config:g,samplerate:h,channelCount:u,codec:f,parsedCodec:f,manifestCodec:n}}function k1(e,t){return e[t]===255&&(e[t+1]&246)===240}function T1(e,t){return e[t+1]&1?7:9}function wm(e,t){return(e[t+3]&3)<<11|e[t+4]<<3|(e[t+5]&224)>>>5}function Q8(e,t){return t+5<e.length}function Ec(e,t){return t+1<e.length&&k1(e,t)}function Y8(e,t){return Q8(e,t)&&k1(e,t)&&wm(e,t)<=e.length-t}function X8(e,t){if(Ec(e,t)){const r=T1(e,t);if(t+r>=e.length)return!1;const n=wm(e,t);if(n<=r)return!1;const s=t+n;return s===e.length||Ec(e,s)}return!1}function C1(e,t,r,n,s){if(!e.samplerate){const a=q8(t,r,n,s);if(!a)return;Ft(e,a)}}function I1(e){return 1024*9e4/e}function J8(e,t){const r=T1(e,t);if(t+r<=e.length){const n=wm(e,t)-r;if(n>0)return{headerLength:r,frameLength:n}}}function P1(e,t,r,n,s){const a=n+s*I1(e.samplerate),c=J8(t,r);let d;if(c){const{frameLength:f,headerLength:h}=c,m=h+f,g=Math.max(0,r+m-t.length);g?(d=new Uint8Array(m-h),d.set(t.subarray(r+h,t.length),0)):d=t.subarray(r+h,r+m);const p={unit:d,pts:a};return g||e.samples.push(p),{sample:p,length:m,missing:g}}const u=t.length-r;return d=new Uint8Array(u),d.set(t.subarray(r,t.length),0),{sample:{unit:d,pts:a},length:u,missing:-1}}function e9(e,t){return _m(e,t)&&wc(e,t+6)+10<=e.length-t}function t9(e){return e instanceof ArrayBuffer?e:e.byteOffset==0&&e.byteLength==e.buffer.byteLength?e.buffer:new Uint8Array(e).buffer}function Em(e,t=0,r=1/0){return r9(e,t,r,Uint8Array)}function r9(e,t,r,n){const s=n9(e);let a=1;"BYTES_PER_ELEMENT"in n&&(a=n.BYTES_PER_ELEMENT);const c=i9(e)?e.byteOffset:0,d=(c+e.byteLength)/a,u=(c+t)/a,f=Math.floor(Math.max(0,Math.min(u,d)));return new n(s,f,Math.floor(Math.min(f+Math.max(r,0),d))-f)}function n9(e){return e instanceof ArrayBuffer?e:e.buffer}function i9(e){return e&&e.buffer instanceof ArrayBuffer&&e.byteLength!==void 0&&e.byteOffset!==void 0}function s9(e){const t={key:e.type,description:"",data:"",mimeType:null,pictureType:null},r=3;if(e.size<2)return;if(e.data[0]!==r){console.log("Ignore frame with unrecognized character encoding");return}const n=e.data.subarray(1).indexOf(0);if(n===-1)return;const s=Gr(Em(e.data,1,n)),a=e.data[2+n],c=e.data.subarray(3+n).indexOf(0);if(c===-1)return;const d=Gr(Em(e.data,3+n,c));let u;return s==="-->"?u=Gr(Em(e.data,4+n+c)):u=t9(e.data.subarray(4+n+c)),t.mimeType=s,t.pictureType=a,t.description=d,t.data=u,t}function a9(e){if(e.size<2)return;const t=Gr(e.data,!0),r=new Uint8Array(e.data.subarray(t.length+1));return{key:e.type,info:t,data:r.buffer}}function o9(e){if(e.size<2)return;if(e.type==="TXXX"){let r=1;const n=Gr(e.data.subarray(r),!0);r+=n.length+1;const s=Gr(e.data.subarray(r));return{key:e.type,info:n,data:s}}const t=Gr(e.data.subarray(1));return{key:e.type,info:"",data:t}}function l9(e){if(e.type==="WXXX"){if(e.size<2)return;let r=1;const n=Gr(e.data.subarray(r),!0);r+=n.length+1;const s=Gr(e.data.subarray(r));return{key:e.type,info:n,data:s}}const t=Gr(e.data);return{key:e.type,info:"",data:t}}function c9(e){return e.type==="PRIV"?a9(e):e.type[0]==="W"?l9(e):e.type==="APIC"?s9(e):o9(e)}function u9(e){const t=String.fromCharCode(e[0],e[1],e[2],e[3]),r=wc(e,4),n=10;return{type:t,size:r,data:e.subarray(n,n+r)}}var kc=10,d9=10;function A1(e){let t=0;const r=[];for(;_m(e,t);){const n=wc(e,t+6);e[t+5]>>6&1&&(t+=kc),t+=kc;const s=t+n;for(;t+d9<s;){const a=u9(e.subarray(t)),c=c9(a);c&&r.push(c),t+=a.size+kc}E1(e,t)&&(t+=kc)}return r}function j1(e){return e&&e.key==="PRIV"&&e.info==="com.apple.streaming.transportStreamTimestamp"}function f9(e){if(e.data.byteLength===8){const t=new Uint8Array(e.data),r=t[3]&1;let n=(t[4]<<23)+(t[5]<<15)+(t[6]<<7)+t[7];return n/=45,r&&(n+=4772185884e-2),Math.round(n)}}function km(e){const t=A1(e);for(let r=0;r<t.length;r++){const n=t[r];if(j1(n))return f9(n)}}var Vr=(function(e){return e.audioId3="org.id3",e.dateRange="com.apple.quicktime.HLS",e.emsg="https://aomedia.org/emsg/ID3",e.misbklv="urn:misb:KLV:bin:1910.1",e})({});function An(e="",t=9e4){return{type:e,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}var Tm=class{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(e,t,r,n){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(e){this.initPTS=e,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(e,t){return!1}appendFrame(e,t,r){}demux(e,t){this.cachedData&&(e=nn(this.cachedData,e),this.cachedData=null);let r=No(e,0),n=r?r.length:0,s;const a=this._audioTrack,c=this._id3Track,d=r?km(r):void 0,u=e.length;for((this.basePTS===null||this.frameIndex===0&&Ye(d))&&(this.basePTS=h9(d,t,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),r&&r.length>0&&c.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Vr.audioId3,duration:Number.POSITIVE_INFINITY});n<u;){if(this.canParse(e,n)){const f=this.appendFrame(a,e,n);f?(this.frameIndex++,this.lastPTS=f.sample.pts,n+=f.length,s=n):n=u}else e9(e,n)?(r=No(e,n),c.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:Vr.audioId3,duration:Number.POSITIVE_INFINITY}),n+=r.length,s=n):n++;if(n===u&&s!==u){const f=e.slice(s);this.cachedData?this.cachedData=nn(this.cachedData,f):this.cachedData=f}}return{audioTrack:a,videoTrack:An(),id3Track:c,textTrack:An()}}demuxSampleAes(e,t,r){return Promise.reject(new Error(`[${this}] This demuxer does not support Sample-AES decryption`))}flush(e){const t=this.cachedData;return t&&(this.cachedData=null,this.demux(t,0)),{audioTrack:this._audioTrack,videoTrack:An(),id3Track:this._id3Track,textTrack:An()}}destroy(){this.cachedData=null,this._audioTrack=this._id3Track=void 0}},h9=(e,t,r)=>{if(Ye(e))return e*90;const n=r?r.baseTime*9e4/r.timescale:0;return t*9e4+n},Tc=null,m9=[32,64,96,128,160,192,224,256,288,320,352,384,416,448,32,48,56,64,80,96,112,128,160,192,224,256,320,384,32,40,48,56,64,80,96,112,128,160,192,224,256,320,32,48,56,64,80,96,112,128,144,160,176,192,224,256,8,16,24,32,40,48,56,64,80,96,112,128,144,160],g9=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],p9=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],v9=[0,1,1,4];function N1(e,t,r,n,s){if(r+24>t.length)return;const a=D1(t,r);if(a&&r+a.frameLength<=t.length){const c=n+s*(a.samplesPerFrame*9e4/a.sampleRate),d={unit:t.subarray(r,r+a.frameLength),pts:c,dts:c};return e.config=[],e.channelCount=a.channelCount,e.samplerate=a.sampleRate,e.samples.push(d),{sample:d,length:a.frameLength,missing:0}}}function D1(e,t){const r=e[t+1]>>3&3,n=e[t+1]>>1&3,s=e[t+2]>>4&15,a=e[t+2]>>2&3;if(r!==1&&s!==0&&s!==15&&a!==3){const c=e[t+2]>>1&1,d=e[t+3]>>6,u=m9[(r===3?3-n:n===3?3:4)*14+s-1]*1e3,f=g9[(r===3?0:r===2?1:2)*3+a],h=d===3?1:2,m=p9[r][n],g=v9[n],p=m*8*g,y=Math.floor(m*u/f+c)*g;if(Tc===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Tc=S?parseInt(S[1]):0}return Tc&&Tc<=87&&n===2&&u>=224e3&&d===0&&(e[t+3]=e[t+3]|128),{sampleRate:f,channelCount:h,frameLength:y,samplesPerFrame:p}}}function Cm(e,t){return e[t]===255&&(e[t+1]&224)===224&&(e[t+1]&6)!==0}function M1(e,t){return t+1<e.length&&Cm(e,t)}function b9(e,t){return Cm(e,t)&&4<=e.length-t}function $1(e,t){if(t+1<e.length&&Cm(e,t)){const n=D1(e,t);let s=4;n!=null&&n.frameLength&&(s=n.frameLength);const a=t+s;return a===e.length||M1(e,a)}return!1}var y9=class extends Tm{constructor(e,t){super(),this.observer=void 0,this.config=void 0,this.observer=e,this.config=t}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e,t){if(!e)return!1;const r=No(e,0);let n=r?.length||0;if($1(e,n))return!1;for(let s=e.length;n<s;n++)if(X8(e,n))return t.log("ADTS sync word found !"),!0;return!1}canParse(e,t){return Y8(e,t)}appendFrame(e,t,r){C1(e,this.observer,t,r,e.manifestCodec);const n=P1(e,t,r,this.basePTS,this.frameIndex);if(n&&n.missing===0)return n}},R1=(e,t)=>{let r=0,n=5;t+=n;const s=new Uint32Array(1),a=new Uint32Array(1),c=new Uint8Array(1);for(;n>0;){c[0]=e[t];const d=Math.min(n,8),u=8-d;a[0]=4278190080>>>24+u<<u,s[0]=(c[0]&a[0])>>u,r=r?r<<d|s[0]:s[0],t+=1,n-=d}return r},x9=class extends Tm{constructor(e){super(),this.observer=void 0,this.observer=e}resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/ac-3",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"ac3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}canParse(e,t){return t+64<e.length}appendFrame(e,t,r){const n=L1(e,t,r,this.basePTS,this.frameIndex);if(n!==-1)return{sample:e.samples[e.samples.length-1],length:n,missing:0}}static probe(e){if(!e)return!1;const t=No(e,0);if(!t)return!1;const r=t.length;return e[r]===11&&e[r+1]===119&&km(t)!==void 0&&R1(e,r)<16}};function L1(e,t,r,n,s){if(r+8>t.length||t[r]!==11||t[r+1]!==119)return-1;const a=t[r+4]>>6;if(a>=3)return-1;const c=[48e3,44100,32e3][a],d=t[r+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][d*3+a]*2;if(r+u>t.length)return-1;const f=t[r+6]>>5;let h=0;f===2?h+=2:(f&1&&f!==1&&(h+=2),f&4&&(h+=2));const m=(t[r+6]<<8|t[r+7])>>12-h&1,g=[2,1,2,3,3,4,4,5][f]+m,p=t[r+5]>>3,y=t[r+5]&7,S=new Uint8Array([a<<6|p<<1|y>>2,(y&3)<<6|f<<3|m<<2|d>>4,d<<4&224]),E=n+s*(1536/c*9e4),T=t.subarray(r,r+u);return e.config=S,e.channelCount=g,e.samplerate=c,e.samples.push({unit:T,pts:E}),u}var S9=class extends Tm{resetInitSegment(e,t,r,n){super.resetInitSegment(e,t,r,n),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:t,duration:n,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const t=No(e,0);let r=t?.length||0;if(t&&e[r]===11&&e[r+1]===119&&km(t)!==void 0&&R1(e,r)<=16)return!1;for(let n=e.length;r<n;r++)if($1(e,r))return $t.log("MPEG Audio sync word found !"),!0;return!1}canParse(e,t){return b9(e,t)}appendFrame(e,t,r){if(this.basePTS!==null)return N1(e,t,r,this.basePTS,this.frameIndex)}},_9=/\/emsg[-/]ID3/i,w9=class{constructor(e,t){this.remainderData=null,this.timeOffset=0,this.config=void 0,this.videoTrack=void 0,this.audioTrack=void 0,this.id3Track=void 0,this.txtTrack=void 0,this.config=t}resetTimeStamp(){}resetInitSegment(e,t,r,n){const s=this.videoTrack=An("video",1),a=this.audioTrack=An("audio",1),c=this.txtTrack=An("text",1);if(this.id3Track=An("id3",1),this.timeOffset=0,!(e!=null&&e.byteLength))return;const d=uS(e);if(d.video){const{id:u,timescale:f,codec:h,supplemental:m}=d.video;s.id=u,s.timescale=c.timescale=f,s.codec=h,s.supplemental=m}if(d.audio){const{id:u,timescale:f,codec:h}=d.audio;a.id=u,a.timescale=f,a.codec=h}c.id=aS.text,s.sampleDuration=0,s.duration=a.duration=n}resetContiguity(){this.remainderData=null}static probe(e){return SG(e)}demux(e,t){this.timeOffset=t;let r=e;const n=this.videoTrack,s=this.txtTrack;if(this.config.progressive){this.remainderData&&(r=nn(this.remainderData,e));const c=IG(r);this.remainderData=c.remainder,n.samples=c.valid||new Uint8Array}else n.samples=r;const a=this.extractID3Track(n,t);return s.samples=hS(t,n),{videoTrack:n,audioTrack:this.audioTrack,id3Track:a,textTrack:this.txtTrack}}flush(){const e=this.timeOffset,t=this.videoTrack,r=this.txtTrack;t.samples=this.remainderData||new Uint8Array,this.remainderData=null;const n=this.extractID3Track(t,this.timeOffset);return r.samples=hS(e,t),{videoTrack:t,audioTrack:An(),id3Track:n,textTrack:An()}}extractID3Track(e,t){const r=this.id3Track;if(e.samples.length){const n=yt(e.samples,["emsg"]);n&&n.forEach(s=>{const a=AG(s);if(_9.test(a.schemeIdUri)){const c=O1(a,t);let d=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;d<=.001&&(d=Number.POSITIVE_INFINITY);const u=a.payload;r.samples.push({data:u,len:u.byteLength,dts:c,pts:c,type:Vr.emsg,duration:d})}else if(this.config.enableEmsgKLVMetadata&&a.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const c=O1(a,t);r.samples.push({data:a.payload,len:a.payload.byteLength,dts:c,pts:c,type:Vr.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(e,t,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}};function O1(e,t){return Ye(e.presentationTime)?e.presentationTime/e.timeScale:t+e.presentationTimeDelta/e.timeScale}var E9=class{constructor(e,t,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new lm(t,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer,fi.cbc)}decryptAacSample(e,t,r){const n=e[t].unit;if(n.length<=16)return;const s=n.subarray(16,n.length-n.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(a).then(c=>{const d=new Uint8Array(c);n.set(d,16),this.decrypter.isSync()||this.decryptAacSamples(e,t+1,r)}).catch(r)}decryptAacSamples(e,t,r){for(;;t++){if(t>=e.length){r();return}if(!(e[t].unit.length<32)&&(this.decryptAacSample(e,t,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const t=Math.floor((e.length-48)/160)*16+16,r=new Int8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)r.set(e.subarray(s,s+16),n);return r}getAvcDecryptedUnit(e,t){const r=new Uint8Array(t);let n=0;for(let s=32;s<e.length-16;s+=160,n+=16)e.set(r.subarray(n,n+16),s);return e}decryptAvcSample(e,t,r,n,s){const a=mS(s.data),c=this.getAvcEncryptedData(a);this.decryptBuffer(c.buffer).then(d=>{s.data=this.getAvcDecryptedUnit(a,d),this.decrypter.isSync()||this.decryptAvcSamples(e,t,r+1,n)}).catch(n)}decryptAvcSamples(e,t,r,n){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;t++,r=0){if(t>=e.length){n();return}const s=e[t].units;for(;!(r>=s.length);r++){const a=s[r];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,t,r,n,a),!this.decrypter.isSync()))return}}}},F1=class{constructor(){this.VideoSample=null}createVideoSample(e,t,r){return{key:e,frame:!1,pts:t,dts:r,units:[],length:0}}getLastNalUnit(e){var t;let r=this.VideoSample,n;if((!r||r.units.length===0)&&(r=e[e.length-1]),(t=r)!=null&&t.units){const s=r.units;n=s[s.length-1]}return n}pushAccessUnit(e,t){if(e.units.length&&e.frame){if(e.pts===void 0){const r=t.samples,n=r.length;if(n){const s=r[n-1];e.pts=s.pts,e.dts=s.dts}else{t.dropped++;return}}t.samples.push(e)}}parseNALu(e,t,r){const n=t.byteLength;let s=e.naluState||0;const a=s,c=[];let d=0,u,f,h,m=-1,g=0;for(s===-1&&(m=0,g=this.getNALuType(t,0),s=0,d=1);d<n;){if(u=t[d++],!s){s=u?0:1;continue}if(s===1){s=u?0:2;continue}if(!u)s=3;else if(u===1){if(f=d-s-1,m>=0){const p={data:t.subarray(m,f),type:g};c.push(p)}else{const p=this.getLastNalUnit(e.samples);p&&(a&&d<=4-a&&p.state&&(p.data=p.data.subarray(0,p.data.byteLength-a)),f>0&&(p.data=nn(p.data,t.subarray(0,f)),p.state=0))}d<n?(h=this.getNALuType(t,d),m=d,g=h,s=0):s=-1}else s=0}if(m>=0&&s>=0){const p={data:t.subarray(m,n),type:g,state:s};c.push(p)}if(c.length===0){const p=this.getLastNalUnit(e.samples);p&&(p.data=nn(p.data,t))}return e.naluState=s,c}},Do=class{constructor(e){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=e,this.bytesAvailable=e.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const e=this.data,t=this.bytesAvailable,r=e.byteLength-t,n=new Uint8Array(4),s=Math.min(4,t);if(s===0)throw new Error("no bytes available");n.set(e.subarray(r,r+s)),this.word=new DataView(n.buffer).getUint32(0),this.bitsAvailable=s*8,this.bytesAvailable-=s}skipBits(e){let t;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,t=e>>3,e-=t<<3,this.bytesAvailable-=t,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let t=Math.min(this.bitsAvailable,e);const r=this.word>>>32-t;if(e>32&&$t.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=t,this.bitsAvailable>0)this.word<<=t;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return t=e-t,t>0&&this.bitsAvailable?r<<t|this.readBits(t):r}skipLZ(){let e;for(e=0;e<this.bitsAvailable;++e)if((this.word&2147483648>>>e)!==0)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const e=this.skipLZ();return this.readBits(e+1)-1}readEG(){const e=this.readUEG();return 1&e?1+e>>>1:-1*(e>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}},k9=class extends F1{parsePES(e,t,r,n){const s=this.parseNALu(e,r.data,n);let a=this.VideoSample,c,d=!1;r.data=null,a&&s.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(u=>{var f,h;switch(u.type){case 1:{let y=!1;c=!0;const S=u.data;if(d&&S.length>4){const E=this.readSliceType(S);(E===2||E===4||E===7||E===9)&&(y=!0)}if(y){var m;(m=a)!=null&&m.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.frame=!0,a.key=y;break}case 5:c=!0,(f=a)!=null&&f.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0,a.frame=!0;break;case 6:c=!0,em(u.data,1,r.pts,t.samples);break;case 7:{var g,p;c=!0,d=!0;const y=u.data,S=this.readSPS(y);if(!e.sps||e.width!==S.width||e.height!==S.height||((g=e.pixelRatio)==null?void 0:g[0])!==S.pixelRatio[0]||((p=e.pixelRatio)==null?void 0:p[1])!==S.pixelRatio[1]){e.width=S.width,e.height=S.height,e.pixelRatio=S.pixelRatio,e.sps=[y];const E=y.subarray(1,4);let T="avc1.";for(let j=0;j<3;j++){let N=E[j].toString(16);N.length<2&&(N="0"+N),T+=N}e.codec=T}break}case 8:c=!0,e.pps=[u.data];break;case 9:c=!0,e.audFound=!0,(h=a)!=null&&h.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:c=!0;break;default:c=!1;break}a&&c&&a.units.push(u)}),n&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}getNALuType(e,t){return e[t]&31}readSliceType(e){const t=new Do(e);return t.readUByte(),t.readUEG(),t.readUEG()}skipScalingList(e,t){let r=8,n=8,s;for(let a=0;a<e;a++)n!==0&&(s=t.readEG(),n=(r+s+256)%256),r=n===0?r:n}readSPS(e){const t=new Do(e);let r=0,n=0,s=0,a=0,c,d,u;const f=t.readUByte.bind(t),h=t.readBits.bind(t),m=t.readUEG.bind(t),g=t.readBoolean.bind(t),p=t.skipBits.bind(t),y=t.skipEG.bind(t),S=t.skipUEG.bind(t),E=this.skipScalingList.bind(this);f();const T=f();if(h(5),p(3),f(),S(),T===100||T===110||T===122||T===244||T===44||T===83||T===86||T===118||T===128){const K=m();if(K===3&&p(1),S(),S(),p(1),g())for(d=K!==3?8:12,u=0;u<d;u++)g()&&(u<6?E(16,t):E(64,t))}S();const j=m();if(j===0)m();else if(j===1)for(p(1),y(),y(),c=m(),u=0;u<c;u++)y();S(),p(1);const N=m(),O=m(),U=h(1);U===0&&p(1),p(1),g()&&(r=m(),n=m(),s=m(),a=m());let z=[1,1];if(g()&&g())switch(f()){case 1:z=[1,1];break;case 2:z=[12,11];break;case 3:z=[10,11];break;case 4:z=[16,11];break;case 5:z=[40,33];break;case 6:z=[24,11];break;case 7:z=[20,11];break;case 8:z=[32,11];break;case 9:z=[80,33];break;case 10:z=[18,11];break;case 11:z=[15,11];break;case 12:z=[64,33];break;case 13:z=[160,99];break;case 14:z=[4,3];break;case 15:z=[3,2];break;case 16:z=[2,1];break;case 255:z=[f()<<8|f(),f()<<8|f()];break}return{width:Math.ceil((N+1)*16-r*2-n*2),height:(2-U)*(O+1)*16-(U?2:4)*(s+a),pixelRatio:z}}},T9=class extends F1{constructor(...e){super(...e),this.initVPS=null}parsePES(e,t,r,n){const s=this.parseNALu(e,r.data,n);let a=this.VideoSample,c,d=!1;r.data=null,a&&s.length&&!e.audFound&&(this.pushAccessUnit(a,e),a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),s.forEach(u=>{var f,h;switch(u.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),a.frame=!0,c=!0;break;case 16:case 17:case 18:case 21:if(c=!0,d){var m;(m=a)!=null&&m.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null)}a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0,a.frame=!0;break;case 19:case 20:c=!0,(f=a)!=null&&f.frame&&!a.key&&(this.pushAccessUnit(a,e),a=this.VideoSample=null),a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0,a.frame=!0;break;case 39:c=!0,em(u.data,2,r.pts,t.samples);break;case 32:c=!0,e.vps||(typeof e.params!="object"&&(e.params={}),e.params=Ft(e.params,this.readVPS(u.data)),this.initVPS=u.data),e.vps=[u.data];break;case 33:if(c=!0,d=!0,e.vps!==void 0&&e.vps[0]!==this.initVPS&&e.sps!==void 0&&!this.matchSPS(e.sps[0],u.data)&&(this.initVPS=e.vps[0],e.sps=e.pps=void 0),!e.sps){const g=this.readSPS(u.data);e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.codec=g.codecString,e.sps=[],typeof e.params!="object"&&(e.params={});for(const p in g.params)e.params[p]=g.params[p]}this.pushParameterSet(e.sps,u.data,e.vps),a||(a=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),a.key=!0;break;case 34:if(c=!0,typeof e.params=="object"){if(!e.pps){e.pps=[];const g=this.readPPS(u.data);for(const p in g)e.params[p]=g[p]}this.pushParameterSet(e.pps,u.data,e.vps)}break;case 35:c=!0,e.audFound=!0,(h=a)!=null&&h.frame&&(this.pushAccessUnit(a,e),a=null),a||(a=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:c=!1;break}a&&c&&a.units.push(u)}),n&&a&&(this.pushAccessUnit(a,e),this.VideoSample=null)}pushParameterSet(e,t,r){(r&&r[0]===this.initVPS||!r&&!e.length)&&e.push(t)}getNALuType(e,t){return(e[t]&126)>>>1}ebsp2rbsp(e){const t=new Uint8Array(e.byteLength);let r=0;for(let n=0;n<e.byteLength;n++)n>=2&&e[n]===3&&e[n-1]===0&&e[n-2]===0||(t[r]=e[n],r++);return new Uint8Array(t.buffer,0,r)}pushAccessUnit(e,t){super.pushAccessUnit(e,t),this.initVPS&&(this.initVPS=null)}readVPS(e){const t=new Do(e);t.readUByte(),t.readUByte(),t.readBits(4),t.skipBits(2),t.readBits(6);const r=t.readBits(3),n=t.readBoolean();return{numTemporalLayers:r+1,temporalIdNested:n}}readSPS(e){const t=new Do(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.readBits(4);const r=t.readBits(3);t.readBoolean();const n=t.readBits(2),s=t.readBoolean(),a=t.readBits(5),c=t.readUByte(),d=t.readUByte(),u=t.readUByte(),f=t.readUByte(),h=t.readUByte(),m=t.readUByte(),g=t.readUByte(),p=t.readUByte(),y=t.readUByte(),S=t.readUByte(),E=t.readUByte(),T=[],j=[];for(let We=0;We<r;We++)T.push(t.readBoolean()),j.push(t.readBoolean());if(r>0)for(let We=r;We<8;We++)t.readBits(2);for(let We=0;We<r;We++)T[We]&&(t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte(),t.readUByte()),j[We]&&t.readUByte();t.readUEG();const N=t.readUEG();N==3&&t.skipBits(1);const O=t.readUEG(),U=t.readUEG(),z=t.readBoolean();let K=0,G=0,X=0,te=0;z&&(K+=t.readUEG(),G+=t.readUEG(),X+=t.readUEG(),te+=t.readUEG());const ne=t.readUEG(),ae=t.readUEG(),oe=t.readUEG(),pe=t.readBoolean();for(let We=pe?0:r;We<=r;We++)t.skipUEG(),t.skipUEG(),t.skipUEG();if(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG(),t.readBoolean()&&t.readBoolean())for(let We=0;We<4;We++)for(let ct=0;ct<(We===3?2:6);ct++)if(!t.readBoolean())t.readUEG();else{const He=Math.min(64,1<<4+(We<<1));We>1&&t.readEG();for(let $e=0;$e<He;$e++)t.readEG()}t.readBoolean(),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.skipUEG(),t.skipUEG(),t.readBoolean());const le=t.readUEG();let se=0;for(let We=0;We<le;We++){let ct=!1;if(We!==0&&(ct=t.readBoolean()),ct){We===le&&t.readUEG(),t.readBoolean(),t.readUEG();let He=0;for(let $e=0;$e<=se;$e++){const Ke=t.readBoolean();let ft=!1;Ke||(ft=t.readBoolean()),(Ke||ft)&&He++}se=He}else{const He=t.readUEG(),$e=t.readUEG();se=He+$e;for(let Ke=0;Ke<He;Ke++)t.readUEG(),t.readBoolean();for(let Ke=0;Ke<$e;Ke++)t.readUEG(),t.readBoolean()}}if(t.readBoolean()){const We=t.readUEG();for(let ct=0;ct<We;ct++){for(let He=0;He<oe+4;He++)t.readBits(1);t.readBits(1)}}let Ce=0,q=1,Q=1,ie=!0,be=1,we=0;t.readBoolean(),t.readBoolean();let Re=!1;if(t.readBoolean()){if(t.readBoolean()){const We=t.readUByte(),ct=[1,12,10,16,40,24,20,32,80,18,15,64,160,4,3,2],He=[1,11,11,11,33,11,11,11,33,11,11,33,99,3,2,1];We>0&&We<16?(q=ct[We-1],Q=He[We-1]):We===255&&(q=t.readBits(16),Q=t.readBits(16))}if(t.readBoolean()&&t.readBoolean(),t.readBoolean()&&(t.readBits(3),t.readBoolean(),t.readBoolean()&&(t.readUByte(),t.readUByte(),t.readUByte())),t.readBoolean()&&(t.readUEG(),t.readUEG()),t.readBoolean(),t.readBoolean(),t.readBoolean(),Re=t.readBoolean(),Re&&(t.skipUEG(),t.skipUEG(),t.skipUEG(),t.skipUEG()),t.readBoolean()&&(be=t.readBits(32),we=t.readBits(32),t.readBoolean()&&t.readUEG(),t.readBoolean())){const We=t.readBoolean(),ct=t.readBoolean();let He=!1;(We||ct)&&(He=t.readBoolean(),He&&(t.readUByte(),t.readBits(5),t.readBoolean(),t.readBits(5)),t.readBits(4),t.readBits(4),He&&t.readBits(4),t.readBits(5),t.readBits(5),t.readBits(5));for(let $e=0;$e<=r;$e++){ie=t.readBoolean();const Ke=ie||t.readBoolean();let ft=!1;Ke?t.readEG():ft=t.readBoolean();const St=ft?1:t.readUEG()+1;if(We)for(let Rt=0;Rt<St;Rt++)t.readUEG(),t.readUEG(),He&&(t.readUEG(),t.readUEG()),t.skipBits(1);if(ct)for(let Rt=0;Rt<St;Rt++)t.readUEG(),t.readUEG(),He&&(t.readUEG(),t.readUEG()),t.skipBits(1)}}t.readBoolean()&&(t.readBoolean(),t.readBoolean(),t.readBoolean(),Ce=t.readUEG())}let Ee=O,Fe=U;if(z){let We=1,ct=1;N===1?We=ct=2:N==2&&(We=2),Ee=O-We*G-We*K,Fe=U-ct*te-ct*X}const Ge=n?["A","B","C"][n]:"",Be=c<<24|d<<16|u<<8|f;let st=0;for(let We=0;We<32;We++)st=(st|(Be>>We&1)<<31-We)>>>0;let at=st.toString(16);return a===1&&at==="2"&&(at="6"),{codecString:`hvc1.${Ge}${a}.${at}.${s?"H":"L"}${E}.B0`,params:{general_tier_flag:s,general_profile_idc:a,general_profile_space:n,general_profile_compatibility_flags:[c,d,u,f],general_constraint_indicator_flags:[h,m,g,p,y,S],general_level_idc:E,bit_depth:ne+8,bit_depth_luma_minus8:ne,bit_depth_chroma_minus8:ae,min_spatial_segmentation_idc:Ce,chroma_format_idc:N,frame_rate:{fixed:ie,fps:we/be}},width:Ee,height:Fe,pixelRatio:[q,Q]}}readPPS(e){const t=new Do(this.ebsp2rbsp(e));t.readUByte(),t.readUByte(),t.skipUEG(),t.skipUEG(),t.skipBits(2),t.skipBits(3),t.skipBits(2),t.skipUEG(),t.skipUEG(),t.skipEG(),t.skipBits(2),t.readBoolean()&&t.skipUEG(),t.skipEG(),t.skipEG(),t.skipBits(4);const r=t.readBoolean(),n=t.readBoolean();let s=1;return n&&r?s=0:n?s=3:r&&(s=2),{parallelismType:s}}matchSPS(e,t){return String.fromCharCode.apply(null,e).substr(3)===String.fromCharCode.apply(null,t).substr(3)}},br=188,C9=class Hi{constructor(t,r,n,s){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=r,this.typeSupported=n,this.logger=s,this.videoParser=null}static probe(t,r){const n=Hi.syncOffset(t);return n>0&&r.warn(`MPEG2-TS detected but first sync word found @ offset ${n}`),n!==-1}static syncOffset(t){const r=t.length;let n=Math.min(br*5,r-br)+1,s=0;for(;s<n;){let a=!1,c=-1,d=0;for(let u=s;u<r;u+=br)if(t[u]===71&&(r-u===br||t[u+br]===71)){if(d++,c===-1&&(c=u,c!==0&&(n=Math.min(c+br*99,t.length-br)+1)),a||(a=Im(t,u)===0),a&&d>1&&(c===0&&d>2||u+br>n))return c}else{if(d)return-1;break}s++}return-1}static createTrack(t,r){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:aS[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?r:void 0}}resetInitSegment(t,r,n,s){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Hi.createTrack("video"),this._videoTrack.duration=s,this._audioTrack=Hi.createTrack("audio",s),this._id3Track=Hi.createTrack("id3"),this._txtTrack=Hi.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=n}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:r,_id3Track:n}=this;t&&(t.pesData=null),r&&(r.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,r,n=!1,s=!1){n||(this.sampleAes=null);let a;const c=this._videoTrack,d=this._audioTrack,u=this._id3Track,f=this._txtTrack;let h=c.pid,m=c.pesData,g=d.pid,p=u.pid,y=d.pesData,S=u.pesData,E=null,T=this.pmtParsed,j=this._pmtId,N=t.length;if(this.remainderData&&(t=nn(this.remainderData,t),N=t.length,this.remainderData=null),N<br&&!s)return this.remainderData=t,{audioTrack:d,videoTrack:c,id3Track:u,textTrack:f};const O=Math.max(0,Hi.syncOffset(t));N-=(N-O)%br,N<t.byteLength&&!s&&(this.remainderData=new Uint8Array(t.buffer,N,t.buffer.byteLength-N));let U=0;for(let K=O;K<N;K+=br)if(t[K]===71){const G=!!(t[K+1]&64),X=Im(t,K),te=(t[K+3]&48)>>4;let ne;if(te>1){if(ne=K+5+t[K+4],ne===K+br)continue}else ne=K+4;switch(X){case h:G&&(m&&(a=Is(m,this.logger))&&(this.readyVideoParser(c.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(c,f,a,!1)),m={data:[],size:0}),m&&(m.data.push(t.subarray(ne,K+br)),m.size+=K+br-ne);break;case g:if(G){if(y&&(a=Is(y,this.logger)))switch(d.segmentCodec){case"aac":this.parseAACPES(d,a);break;case"mp3":this.parseMPEGPES(d,a);break;case"ac3":this.parseAC3PES(d,a);break}y={data:[],size:0}}y&&(y.data.push(t.subarray(ne,K+br)),y.size+=K+br-ne);break;case p:G&&(S&&(a=Is(S,this.logger))&&this.parseID3PES(u,a),S={data:[],size:0}),S&&(S.data.push(t.subarray(ne,K+br)),S.size+=K+br-ne);break;case 0:G&&(ne+=t[ne]+1),j=this._pmtId=I9(t,ne);break;case j:{G&&(ne+=t[ne]+1);const ae=P9(t,ne,this.typeSupported,n,this.observer,this.logger);h=ae.videoPid,h>0&&(c.pid=h,c.segmentCodec=ae.segmentVideoCodec),g=ae.audioPid,g>0&&(d.pid=g,d.segmentCodec=ae.segmentAudioCodec),p=ae.id3Pid,p>0&&(u.pid=p),E!==null&&!T&&(this.logger.warn(`MPEG-TS PMT found at ${K} after unknown PID '${E}'. Backtracking to sync byte @${O} to parse all TS packets.`),E=null,K=O-188),T=this.pmtParsed=!0;break}case 17:case 8191:break;default:E=X;break}}else U++;U>0&&Pm(this.observer,new Error(`Found ${U} TS packet/s that do not start with 0x47`),void 0,this.logger),c.pesData=m,d.pesData=y,u.pesData=S;const z={audioTrack:d,videoTrack:c,id3Track:u,textTrack:f};return s&&this.extractRemainingSamples(z),z}flush(){const{remainderData:t}=this;this.remainderData=null;let r;return t?r=this.demux(t,-1,!1,!0):r={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(r),this.sampleAes?this.decrypt(r,this.sampleAes):r}extractRemainingSamples(t){const{audioTrack:r,videoTrack:n,id3Track:s,textTrack:a}=t,c=n.pesData,d=r.pesData,u=s.pesData;let f;if(c&&(f=Is(c,this.logger))?(this.readyVideoParser(n.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(n,a,f,!0),n.pesData=null)):n.pesData=c,d&&(f=Is(d,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,f);break;case"mp3":this.parseMPEGPES(r,f);break;case"ac3":this.parseAC3PES(r,f);break}r.pesData=null}else d!=null&&d.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=d;u&&(f=Is(u,this.logger))?(this.parseID3PES(s,f),s.pesData=null):s.pesData=u}demuxSampleAes(t,r,n){const s=this.demux(t,n,!0,!this.config.progressive),a=this.sampleAes=new E9(this.observer,this.config,r);return this.decrypt(s,a)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new k9:t==="hevc"&&(this.videoParser=new T9))}decrypt(t,r){return new Promise(n=>{const{audioTrack:s,videoTrack:a}=t;s.samples&&s.segmentCodec==="aac"?r.decryptAacSamples(s.samples,0,()=>{a.samples?r.decryptAvcSamples(a.samples,0,0,()=>{n(t)}):n(t)}):a.samples&&r.decryptAvcSamples(a.samples,0,0,()=>{n(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,r){let n=0;const s=this.aacOverFlow;let a=r.data;if(s){this.aacOverFlow=null;const m=s.missing,g=s.sample.unit.byteLength;if(m===-1)a=nn(s.sample.unit,a);else{const p=g-m;s.sample.unit.set(a.subarray(0,m),p),t.samples.push(s.sample),n=s.missing}}let c,d;for(c=n,d=a.length;c<d-1&&!Ec(a,c);c++);if(c!==n){let m;const g=c<d-1;if(g?m=`AAC PES did not start with ADTS header,offset:${c}`:m="No ADTS header found in AAC PES",Pm(this.observer,new Error(m),g,this.logger),!g)return}C1(t,this.observer,a,c,this.audioCodec);let u;if(r.pts!==void 0)u=r.pts;else if(s){const m=I1(t.samplerate);u=s.sample.pts+m}else{this.logger.warn("[tsdemuxer]: AAC PES unknown PTS");return}let f=0,h;for(;c<d;)if(h=P1(t,a,c,u,f),c+=h.length,h.missing){this.aacOverFlow=h;break}else for(f++;c<d-1&&!Ec(a,c);c++);}parseMPEGPES(t,r){const n=r.data,s=n.length;let a=0,c=0;const d=r.pts;if(d===void 0){this.logger.warn("[tsdemuxer]: MPEG PES unknown PTS");return}for(;c<s;)if(M1(n,c)){const u=N1(t,n,c,d,a);if(u)c+=u.length,a++;else break}else c++}parseAC3PES(t,r){{const n=r.data,s=r.pts;if(s===void 0){this.logger.warn("[tsdemuxer]: AC3 PES unknown PTS");return}const a=n.length;let c=0,d=0,u;for(;d<a&&(u=L1(t,n,d,s,c++))>0;)d+=u}}parseID3PES(t,r){if(r.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const n=Ft({},r,{type:this._videoTrack?Vr.emsg:Vr.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(n)}};function Im(e,t){return((e[t+1]&31)<<8)+e[t+2]}function I9(e,t){return(e[t+10]&31)<<8|e[t+11]}function P9(e,t,r,n,s,a){const c={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},d=(e[t+1]&15)<<8|e[t+2],u=t+3+d-4,f=(e[t+10]&15)<<8|e[t+11];for(t+=12+f;t<u;){const h=Im(e,t),m=(e[t+3]&15)<<8|e[t+4];switch(e[t]){case 207:if(!n){Am("ADTS AAC",a);break}case 15:c.audioPid===-1&&(c.audioPid=h);break;case 21:c.id3Pid===-1&&(c.id3Pid=h);break;case 219:if(!n){Am("H.264",a);break}case 27:c.videoPid===-1&&(c.videoPid=h);break;case 3:case 4:!r.mpeg&&!r.mp3?a.log("MPEG audio found, not supported in this browser"):c.audioPid===-1&&(c.audioPid=h,c.segmentAudioCodec="mp3");break;case 193:if(!n){Am("AC-3",a);break}case 129:r.ac3?c.audioPid===-1&&(c.audioPid=h,c.segmentAudioCodec="ac3"):a.log("AC-3 audio found, not supported in this browser");break;case 6:if(c.audioPid===-1&&m>0){let g=t+5,p=m;for(;p>2;){switch(e[g]){case 106:r.ac3!==!0?a.log("AC-3 audio found, not supported in this browser for now"):(c.audioPid=h,c.segmentAudioCodec="ac3");break}const y=e[g+1]+2;g+=y,p-=y}}break;case 194:case 135:return Pm(s,new Error("Unsupported EC-3 in M2TS found"),void 0,a),c;case 36:c.videoPid===-1&&(c.videoPid=h,c.segmentVideoCodec="hevc",a.log("HEVC in M2TS found"));break}t+=m+5}return c}function Pm(e,t,r,n){n.warn(`parsing error: ${t.message}`),e.emit($.ERROR,$.ERROR,{type:it.MEDIA_ERROR,details:fe.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:t,reason:t.message})}function Am(e,t){t.log(`${e} with AES-128-CBC encryption found in unencrypted stream`)}function Is(e,t){let r=0,n,s,a,c,d;const u=e.data;if(!e||e.size===0)return null;for(;u[0].length<19&&u.length>1;)u[0]=nn(u[0],u[1]),u.splice(1,1);if(n=u[0],(n[0]<<16)+(n[1]<<8)+n[2]===1){if(s=(n[4]<<8)+n[5],s&&s>e.size-6)return null;const f=n[7];f&192&&(c=(n[9]&14)*536870912+(n[10]&255)*4194304+(n[11]&254)*16384+(n[12]&255)*128+(n[13]&254)/2,f&64?(d=(n[14]&14)*536870912+(n[15]&255)*4194304+(n[16]&254)*16384+(n[17]&255)*128+(n[18]&254)/2,c-d>60*9e4&&(t.warn(`${Math.round((c-d)/9e4)}s delta between PTS and DTS, align them`),c=d)):d=c),a=n[8];let h=a+9;if(e.size<=h)return null;e.size-=h;const m=new Uint8Array(e.size);for(let g=0,p=u.length;g<p;g++){n=u[g];let y=n.byteLength;if(h)if(h>y){h-=y;continue}else n=n.subarray(h),y-=h,h=0;m.set(n,r),r+=y}return s&&(s-=a+3),{data:m,pts:c,dts:d,len:s}}return null}var A9=class{static getSilentFrame(e,t){switch(e){case"mp4a.40.2":if(t===1)return new Uint8Array([0,200,0,128,35,128]);if(t===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(t===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(t===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(t===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(t===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(t===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(t===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}},hi=Math.pow(2,32)-1,wr=class Se{static init(){Se.types={avc1:[],avcC:[],hvc1:[],hvcC:[],btrt:[],dinf:[],dref:[],esds:[],ftyp:[],hdlr:[],mdat:[],mdhd:[],mdia:[],mfhd:[],minf:[],moof:[],moov:[],mp4a:[],".mp3":[],dac3:[],"ac-3":[],mvex:[],mvhd:[],pasp:[],sdtp:[],stbl:[],stco:[],stsc:[],stsd:[],stsz:[],stts:[],tfdt:[],tfhd:[],traf:[],trak:[],trun:[],trex:[],tkhd:[],vmhd:[],smhd:[]};let t;for(t in Se.types)Se.types.hasOwnProperty(t)&&(Se.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);Se.HDLR_TYPES={video:new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),audio:new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0])};const r=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]);Se.STTS=Se.STSC=Se.STCO=new Uint8Array([0,0,0,0,0,0,0,0]),Se.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),Se.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),Se.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),Se.STSD=new Uint8Array([0,0,0,0,0,0,0,1]);const n=new Uint8Array([105,115,111,109]),s=new Uint8Array([97,118,99,49]),a=new Uint8Array([0,0,0,1]);Se.FTYP=Se.box(Se.types.ftyp,n,a,n,s),Se.DINF=Se.box(Se.types.dinf,Se.box(Se.types.dref,r))}static box(t,...r){let n=8,s=r.length;const a=s;for(;s--;)n+=r[s].byteLength;const c=new Uint8Array(n);for(c[0]=n>>24&255,c[1]=n>>16&255,c[2]=n>>8&255,c[3]=n&255,c.set(t,4),s=0,n=8;s<a;s++)c.set(r[s],n),n+=r[s].byteLength;return c}static hdlr(t){return Se.box(Se.types.hdlr,Se.HDLR_TYPES[t])}static mdat(t){return Se.box(Se.types.mdat,t)}static mdhd(t,r){r*=t;const n=Math.floor(r/(hi+1)),s=Math.floor(r%(hi+1));return Se.box(Se.types.mdhd,new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,n>>24,n>>16&255,n>>8&255,n&255,s>>24,s>>16&255,s>>8&255,s&255,85,196,0,0]))}static mdia(t){return Se.box(Se.types.mdia,Se.mdhd(t.timescale||0,t.duration||0),Se.hdlr(t.type),Se.minf(t))}static mfhd(t){return Se.box(Se.types.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?Se.box(Se.types.minf,Se.box(Se.types.smhd,Se.SMHD),Se.DINF,Se.stbl(t)):Se.box(Se.types.minf,Se.box(Se.types.vmhd,Se.VMHD),Se.DINF,Se.stbl(t))}static moof(t,r,n){return Se.box(Se.types.moof,Se.mfhd(t),Se.traf(n,r))}static moov(t){let r=t.length;const n=[];for(;r--;)n[r]=Se.trak(t[r]);return Se.box.apply(null,[Se.types.moov,Se.mvhd(t[0].timescale||0,t[0].duration||0)].concat(n).concat(Se.mvex(t)))}static mvex(t){let r=t.length;const n=[];for(;r--;)n[r]=Se.trex(t[r]);return Se.box.apply(null,[Se.types.mvex,...n])}static mvhd(t,r){r*=t;const n=Math.floor(r/(hi+1)),s=Math.floor(r%(hi+1)),a=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,n>>24,n>>16&255,n>>8&255,n&255,s>>24,s>>16&255,s>>8&255,s&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return Se.box(Se.types.mvhd,a)}static sdtp(t){const r=t.samples||[],n=new Uint8Array(4+r.length);let s,a;for(s=0;s<r.length;s++)a=r[s].flags,n[s+4]=a.dependsOn<<4|a.isDependedOn<<2|a.hasRedundancy;return Se.box(Se.types.sdtp,n)}static stbl(t){return Se.box(Se.types.stbl,Se.stsd(t),Se.box(Se.types.stts,Se.STTS),Se.box(Se.types.stsc,Se.STSC),Se.box(Se.types.stsz,Se.STSZ),Se.box(Se.types.stco,Se.STCO))}static avc1(t){let r=[],n=[],s,a,c;for(s=0;s<t.sps.length;s++)a=t.sps[s],c=a.byteLength,r.push(c>>>8&255),r.push(c&255),r=r.concat(Array.prototype.slice.call(a));for(s=0;s<t.pps.length;s++)a=t.pps[s],c=a.byteLength,n.push(c>>>8&255),n.push(c&255),n=n.concat(Array.prototype.slice.call(a));const d=Se.box(Se.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|t.sps.length].concat(r).concat([t.pps.length]).concat(n))),u=t.width,f=t.height,h=t.pixelRatio[0],m=t.pixelRatio[1];return Se.box(Se.types.avc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&255,f>>8&255,f&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,Se.box(Se.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Se.box(Se.types.pasp,new Uint8Array([h>>24,h>>16&255,h>>8&255,h&255,m>>24,m>>16&255,m>>8&255,m&255])))}static esds(t){const r=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...r,6,1,2])}static audioStsd(t){const r=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,r>>8&255,r&255,0,0])}static mp4a(t){return Se.box(Se.types.mp4a,Se.audioStsd(t),Se.box(Se.types.esds,Se.esds(t)))}static mp3(t){return Se.box(Se.types[".mp3"],Se.audioStsd(t))}static ac3(t){return Se.box(Se.types["ac-3"],Se.audioStsd(t),Se.box(Se.types.dac3,t.config))}static stsd(t){const{segmentCodec:r}=t;if(t.type==="audio"){if(r==="aac")return Se.box(Se.types.stsd,Se.STSD,Se.mp4a(t));if(r==="ac3"&&t.config)return Se.box(Se.types.stsd,Se.STSD,Se.ac3(t));if(r==="mp3"&&t.codec==="mp3")return Se.box(Se.types.stsd,Se.STSD,Se.mp3(t))}else if(t.pps&&t.sps){if(r==="avc")return Se.box(Se.types.stsd,Se.STSD,Se.avc1(t));if(r==="hevc"&&t.vps)return Se.box(Se.types.stsd,Se.STSD,Se.hvc1(t))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${t.type} segment codec (${r}/${t.codec})`)}static tkhd(t){const r=t.id,n=(t.duration||0)*(t.timescale||0),s=t.width||0,a=t.height||0,c=Math.floor(n/(hi+1)),d=Math.floor(n%(hi+1));return Se.box(Se.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,r>>24&255,r>>16&255,r>>8&255,r&255,0,0,0,0,c>>24,c>>16&255,c>>8&255,c&255,d>>24,d>>16&255,d>>8&255,d&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,s>>8&255,s&255,0,0,a>>8&255,a&255,0,0]))}static traf(t,r){const n=Se.sdtp(t),s=t.id,a=Math.floor(r/(hi+1)),c=Math.floor(r%(hi+1));return Se.box(Se.types.traf,Se.box(Se.types.tfhd,new Uint8Array([0,0,0,0,s>>24,s>>16&255,s>>8&255,s&255])),Se.box(Se.types.tfdt,new Uint8Array([1,0,0,0,a>>24,a>>16&255,a>>8&255,a&255,c>>24,c>>16&255,c>>8&255,c&255])),Se.trun(t,n.length+16+20+8+16+8+8),n)}static trak(t){return t.duration=t.duration||4294967295,Se.box(Se.types.trak,Se.tkhd(t),Se.mdia(t))}static trex(t){const r=t.id;return Se.box(Se.types.trex,new Uint8Array([0,0,0,0,r>>24,r>>16&255,r>>8&255,r&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,r){const n=t.samples||[],s=n.length,a=12+16*s,c=new Uint8Array(a);let d,u,f,h,m,g;for(r+=8+a,c.set([t.type==="video"?1:0,0,15,1,s>>>24&255,s>>>16&255,s>>>8&255,s&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255],0),d=0;d<s;d++)u=n[d],f=u.duration,h=u.size,m=u.flags,g=u.cts,c.set([f>>>24&255,f>>>16&255,f>>>8&255,f&255,h>>>24&255,h>>>16&255,h>>>8&255,h&255,m.isLeading<<2|m.dependsOn,m.isDependedOn<<6|m.hasRedundancy<<4|m.paddingValue<<1|m.isNonSync,m.degradPrio&61440,m.degradPrio&15,g>>>24&255,g>>>16&255,g>>>8&255,g&255],12+16*d);return Se.box(Se.types.trun,c)}static initSegment(t){Se.types||Se.init();const r=Se.moov(t);return nn(Se.FTYP,r)}static hvc1(t){const r=t.params,n=[t.vps,t.sps,t.pps],s=new Uint8Array([1,r.general_profile_space<<6|(r.general_tier_flag?32:0)|r.general_profile_idc,r.general_profile_compatibility_flags[0],r.general_profile_compatibility_flags[1],r.general_profile_compatibility_flags[2],r.general_profile_compatibility_flags[3],r.general_constraint_indicator_flags[0],r.general_constraint_indicator_flags[1],r.general_constraint_indicator_flags[2],r.general_constraint_indicator_flags[3],r.general_constraint_indicator_flags[4],r.general_constraint_indicator_flags[5],r.general_level_idc,240|r.min_spatial_segmentation_idc>>8,255&r.min_spatial_segmentation_idc,252|r.parallelismType,252|r.chroma_format_idc,248|r.bit_depth_luma_minus8,248|r.bit_depth_chroma_minus8,0,parseInt(r.frame_rate.fps),3|r.temporal_id_nested<<2|r.num_temporal_layers<<3|(r.frame_rate.fixed?64:0),n.length]);let a=s.length;for(let p=0;p<n.length;p+=1){a+=3;for(let y=0;y<n[p].length;y+=1)a+=2+n[p][y].length}const c=new Uint8Array(a);c.set(s,0),a=s.length;const d=n.length-1;for(let p=0;p<n.length;p+=1){c.set(new Uint8Array([32+p|(p===d?128:0),0,n[p].length]),a),a+=3;for(let y=0;y<n[p].length;y+=1)c.set(new Uint8Array([n[p][y].length>>8,n[p][y].length&255]),a),a+=2,c.set(n[p][y],a),a+=n[p][y].length}const u=Se.box(Se.types.hvcC,c),f=t.width,h=t.height,m=t.pixelRatio[0],g=t.pixelRatio[1];return Se.box(Se.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,f>>8&255,f&255,h>>8&255,h&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),u,Se.box(Se.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),Se.box(Se.types.pasp,new Uint8Array([m>>24,m>>16&255,m>>8&255,m&255,g>>24,g>>16&255,g>>8&255,g&255])))}};wr.types=void 0,wr.HDLR_TYPES=void 0,wr.STTS=void 0,wr.STSC=void 0,wr.STCO=void 0,wr.STSZ=void 0,wr.VMHD=void 0,wr.SMHD=void 0,wr.STSD=void 0,wr.FTYP=void 0,wr.DINF=void 0;var U1=9e4;function jm(e,t,r=1,n=!1){const s=e*t*r;return n?Math.round(s):s}function j9(e,t,r=1,n=!1){return jm(e,t,1/r,n)}function Mo(e,t=!1){return jm(e,1e3,1/U1,t)}function N9(e,t=1){return jm(e,U1,1/t)}function B1(e){const{baseTime:t,timescale:r,trackId:n}=e;return`${t/r} (${t}/${r}) trackId: ${n}`}var D9=10*1e3,M9=1024,$9=1152,R9=1536,Ps=null,Nm=null;function z1(e,t,r,n){return{duration:t,size:r,cts:n,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}var Cc=class extends rn{constructor(e,t,r,n){if(super("mp4-remuxer",n),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=t,this.typeSupported=r,this.ISGenerated=!1,Ps===null){const s=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Ps=s?parseInt(s[1]):0}if(Nm===null){const s=navigator.userAgent.match(/Safari\/(\d+)/i);Nm=s?parseInt(s[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){const t=this._initPTS;(!t||!e||e.trackId!==t.trackId||e.baseTime!==t.baseTime||e.timescale!==t.timescale)&&this.log(`Reset initPTS: ${t&&B1(t)} > ${e&&B1(e)}`),this._initPTS=this._initDTS=e}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let t=!1;const r=e[0].pts,n=e.reduce((s,a)=>{let c=a.pts,d=c-s;return d<-4294967296&&(t=!0,c=Hr(c,r),d=c-s),d>0?s:c},r);return t&&this.debug("PTS rollover detected"),n}remux(e,t,r,n,s,a,c,d){let u,f,h,m,g,p,y=s,S=s;const E=e.pid>-1,T=t.pid>-1,j=t.samples.length,N=e.samples.length>0,O=c&&j>0||j>1;if((!E||N)&&(!T||O)||this.ISGenerated||c){if(this.ISGenerated){var U,z,K,G;const ae=this.videoTrackConfig;(ae&&(t.width!==ae.width||t.height!==ae.height||((U=t.pixelRatio)==null?void 0:U[0])!==((z=ae.pixelRatio)==null?void 0:z[0])||((K=t.pixelRatio)==null?void 0:K[1])!==((G=ae.pixelRatio)==null?void 0:G[1]))||!ae&&O||this.nextAudioTs===null&&N)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(e,t,s,a));const X=this.isVideoContiguous;let te=-1,ne;if(O&&(te=L9(t.samples),!X&&this.config.forceKeyFrameOnDiscontinuity))if(p=!0,te>0){this.warn(`Dropped ${te} out of ${j} video samples due to a missing keyframe`);const ae=this.getVideoStartPts(t.samples);t.samples=t.samples.slice(te),t.dropped+=te,S+=(t.samples[0].pts-ae)/t.inputTimeScale,ne=S}else te===-1&&(this.warn(`No keyframe found out of ${j} video samples`),p=!1);if(this.ISGenerated){if(N&&O){const ae=this.getVideoStartPts(t.samples),oe=(Hr(e.samples[0].pts,ae)-ae)/t.inputTimeScale;y+=Math.max(0,oe),S+=Math.max(0,-oe)}if(N){if(e.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(e,t,s,a)),f=this.remuxAudio(e,y,this.isAudioContiguous,a,T||O||d===Je.AUDIO?S:void 0),O){const ae=f?f.endPTS-f.startPTS:0;t.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(e,t,s,a)),u=this.remuxVideo(t,S,X,ae)}}else O&&(u=this.remuxVideo(t,S,X,0));u&&(u.firstKeyFrame=te,u.independent=te!==-1,u.firstKeyFramePTS=ne)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(g=G1(r,s,this._initPTS,this._initDTS)),n.samples.length&&(m=Z1(n,s,this._initPTS))),{audio:f,video:u,initSegment:h,independent:p,text:m,id3:g}}computeInitPts(e,t,r,n){const s=Math.round(r*t);let a=Hr(e,s);if(a<s+t)for(this.log(`Adjusting PTS for rollover in timeline near ${(s-a)/t} ${n}`);a<s+t;)a+=8589934592;return a-s}generateIS(e,t,r,n){const s=e.samples,a=t.samples,c=this.typeSupported,d={},u=this._initPTS;let f=!u||n,h="audio/mp4",m,g,p,y=-1;if(f&&(m=g=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":c.mpeg?(h="audio/mpeg",e.codec=""):c.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}d.audio={id:"audio",container:h,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&c.mpeg?new Uint8Array(0):wr.initSegment([e]),metadata:{channelCount:e.channelCount}},f&&(y=e.id,p=e.inputTimeScale,!u||p!==u.timescale?m=g=this.computeInitPts(s[0].pts,p,r,"audio"):f=!1)}if(t.sps&&t.pps&&a.length){if(t.timescale=t.inputTimeScale,d.video={id:"main",container:"video/mp4",codec:t.codec,initSegment:wr.initSegment([t]),metadata:{width:t.width,height:t.height}},f)if(y=t.id,p=t.inputTimeScale,!u||p!==u.timescale){const S=this.getVideoStartPts(a),E=Hr(a[0].dts,S),T=this.computeInitPts(E,p,r,"video"),j=this.computeInitPts(S,p,r,"video");g=Math.min(g,T),m=Math.min(m,j)}else f=!1;this.videoTrackConfig={width:t.width,height:t.height,pixelRatio:t.pixelRatio}}if(Object.keys(d).length)return this.ISGenerated=!0,f?(u&&this.warn(`Timestamps at playlist time: ${n?"":"~"}${r} ${m/p} != initPTS: ${u.baseTime/u.timescale} (${u.baseTime}/${u.timescale}) trackId: ${u.trackId}`),this.log(`Found initPTS at playlist time: ${r} offset: ${m/p} (${m}/${p}) trackId: ${y}`),this._initPTS={baseTime:m,timescale:p,trackId:y},this._initDTS={baseTime:g,timescale:p,trackId:y}):m=p=void 0,{tracks:d,initPTS:m,timescale:p,trackId:y}}remuxVideo(e,t,r,n){const s=e.inputTimeScale,a=e.samples,c=[],d=a.length,u=this._initPTS,f=u.baseTime*s/u.timescale;let h=this.nextVideoTs,m=8,g=this.videoSampleDuration,p,y,S=Number.POSITIVE_INFINITY,E=Number.NEGATIVE_INFINITY,T=!1;if(!r||h===null){const q=f+t*s,Q=a[0].pts-Hr(a[0].dts,a[0].pts);Ps&&h!==null&&Math.abs(q-Q-(h+f))<15e3?r=!0:h=q-Q-f}const j=h+f;for(let q=0;q<d;q++){const Q=a[q];Q.pts=Hr(Q.pts,j),Q.dts=Hr(Q.dts,j),Q.dts<a[q>0?q-1:q].dts&&(T=!0)}T&&a.sort(function(q,Q){const ie=q.dts-Q.dts,be=q.pts-Q.pts;return ie||be}),p=a[0].dts,y=a[a.length-1].dts;const N=y-p,O=N?Math.round(N/(d-1)):g||e.inputTimeScale/30;if(r){const q=p-j,Q=q>O,ie=q<-1;if((Q||ie)&&(Q?this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Mo(q,!0)} ms (${q}dts) hole between fragments detected at ${t.toFixed(3)}`):this.warn(`${(e.segmentCodec||"").toUpperCase()}: ${Mo(-q,!0)} ms (${q}dts) overlapping between fragments detected at ${t.toFixed(3)}`),!ie||j>=a[0].pts||Ps)){p=j;const be=a[0].pts-q;if(Q)a[0].dts=p,a[0].pts=be;else{let we=!0;for(let Re=0;Re<a.length&&!(a[Re].dts>be&&we);Re++){const Ee=a[Re].pts;if(a[Re].dts-=q,a[Re].pts-=q,Re<a.length-1){const Fe=a[Re+1].pts;we=Fe<=a[Re].pts==Fe<=Ee}}}this.log(`Video: Initial PTS/DTS adjusted: ${Mo(be,!0)}/${Mo(p,!0)}, delta: ${Mo(q,!0)} ms`)}}p=Math.max(0,p);let U=0,z=0,K=p;for(let q=0;q<d;q++){const Q=a[q],ie=Q.units,be=ie.length;let we=0;for(let Re=0;Re<be;Re++)we+=ie[Re].data.length;z+=we,U+=be,Q.length=we,Q.dts<K?(Q.dts=K,K+=O/4|0||1):K=Q.dts,S=Math.min(Q.pts,S),E=Math.max(Q.pts,E)}y=a[d-1].dts;const G=z+4*U+8;let X;try{X=new Uint8Array(G)}catch(q){this.observer.emit($.ERROR,$.ERROR,{type:it.MUX_ERROR,details:fe.REMUX_ALLOC_ERROR,fatal:!1,error:q,bytes:G,reason:`fail allocating video mdat ${G}`});return}const te=new DataView(X.buffer);te.setUint32(0,G),X.set(wr.types.mdat,4);let ne=!1,ae=Number.POSITIVE_INFINITY,oe=Number.POSITIVE_INFINITY,pe=Number.NEGATIVE_INFINITY,le=Number.NEGATIVE_INFINITY;for(let q=0;q<d;q++){const Q=a[q],ie=Q.units;let be=0;for(let Ee=0,Fe=ie.length;Ee<Fe;Ee++){const Ge=ie[Ee],Be=Ge.data,st=Ge.data.byteLength;te.setUint32(m,st),m+=4,X.set(Be,m),m+=st,be+=4+st}let we;if(q<d-1)g=a[q+1].dts-Q.dts,we=a[q+1].pts-Q.pts;else{const Ee=this.config,Fe=q>0?Q.dts-a[q-1].dts:O;if(we=q>0?Q.pts-a[q-1].pts:O,Ee.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ge=Math.floor(Ee.maxBufferHole*s),Be=(n?S+n*s:this.nextAudioTs+f)-Q.pts;Be>Ge?(g=Be-Fe,g<0?g=Fe:ne=!0,this.log(`It is approximately ${Be/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=Fe}else g=Fe}const Re=Math.round(Q.pts-Q.dts);ae=Math.min(ae,g),pe=Math.max(pe,g),oe=Math.min(oe,we),le=Math.max(le,we),c.push(z1(Q.key,g,be,Re))}if(c.length){if(Ps){if(Ps<70){const q=c[0].flags;q.dependsOn=2,q.isNonSync=0}}else if(Nm&&le-oe<pe-ae&&O/pe<.025&&c[0].cts===0){this.warn("Found irregular gaps in sample duration. Using PTS instead of DTS to determine MP4 sample duration.");let q=p;for(let Q=0,ie=c.length;Q<ie;Q++){const be=q+c[Q].duration,we=q+c[Q].cts;if(Q<ie-1){const Re=be+c[Q+1].cts;c[Q].duration=Re-we}else c[Q].duration=Q?c[Q-1].duration:O;c[Q].cts=0,q=be}}}g=ne||!g?O:g;const se=y+g;this.nextVideoTs=h=se-f,this.videoSampleDuration=g,this.isVideoContiguous=!0;const Ce={data1:wr.moof(e.sequenceNumber++,p,Ft(e,{samples:c})),data2:X,startPTS:(S-f)/s,endPTS:(E+g-f)/s,startDTS:(p-f)/s,endDTS:h/s,type:"video",hasAudio:!1,hasVideo:!0,nb:c.length,dropped:e.dropped};return e.samples=[],e.dropped=0,Ce}getSamplesPerFrame(e){switch(e.segmentCodec){case"mp3":return $9;case"ac3":return R9;default:return M9}}remuxAudio(e,t,r,n,s){const a=e.inputTimeScale,c=a/(e.samplerate?e.samplerate:a),d=this.getSamplesPerFrame(e),u=d*c,f=this._initPTS,h=e.segmentCodec==="mp3"&&this.typeSupported.mpeg,m=[],g=s!==void 0;let p=e.samples,y=h?0:8,S=this.nextAudioTs||-1;const E=f.baseTime*a/f.timescale,T=E+t*a;if(this.isAudioContiguous=r=r||p.length&&S>0&&(n&&Math.abs(T-(S+E))<9e3||Math.abs(Hr(p[0].pts,T)-(S+E))<20*u),p.forEach(function(oe){oe.pts=Hr(oe.pts,T)}),!r||S<0){const oe=p.length;if(p=p.filter(pe=>pe.pts>=0),oe!==p.length&&this.warn(`Removed ${p.length-oe} of ${oe} samples (initPTS ${E} / ${a})`),!p.length)return;s===0?S=0:n&&!g?S=Math.max(0,T-E):S=p[0].pts-E}if(e.segmentCodec==="aac"){const oe=this.config.maxAudioFramesDrift;for(let pe=0,le=S+E;pe<p.length;pe++){const se=p[pe],Ce=se.pts,q=Ce-le,Q=Math.abs(1e3*q/a);if(q<=-oe*u&&g)pe===0&&(this.warn(`Audio frame @ ${(Ce/a).toFixed(3)}s overlaps marker by ${Math.round(1e3*q/a)} ms.`),this.nextAudioTs=S=Ce-E,le=Ce);else if(q>=oe*u&&Q<D9&&g){let ie=Math.round(q/u);for(le=Ce-ie*u;le<0&&ie&&u;)ie--,le+=u;pe===0&&(this.nextAudioTs=S=le-E),this.warn(`Injecting ${ie} audio frames @ ${((le-E)/a).toFixed(3)}s due to ${Math.round(1e3*q/a)} ms gap.`);for(let be=0;be<ie;be++){let we=A9.getSilentFrame(e.parsedCodec||e.manifestCodec||e.codec,e.channelCount);we||(this.log("Unable to get silent frame for given audio codec; duplicating last frame instead."),we=se.unit.subarray()),p.splice(pe,0,{unit:we,pts:le}),le+=u,pe++}}se.pts=le,le+=u}}let j=null,N=null,O,U=0,z=p.length;for(;z--;)U+=p[z].unit.byteLength;for(let oe=0,pe=p.length;oe<pe;oe++){const le=p[oe],se=le.unit;let Ce=le.pts;if(N!==null){const Q=m[oe-1];Q.duration=Math.round((Ce-N)/c)}else if(r&&e.segmentCodec==="aac"&&(Ce=S+E),j=Ce,U>0){U+=y;try{O=new Uint8Array(U)}catch(Q){this.observer.emit($.ERROR,$.ERROR,{type:it.MUX_ERROR,details:fe.REMUX_ALLOC_ERROR,fatal:!1,error:Q,bytes:U,reason:`fail allocating audio mdat ${U}`});return}h||(new DataView(O.buffer).setUint32(0,U),O.set(wr.types.mdat,4))}else return;O.set(se,y);const q=se.byteLength;y+=q,m.push(z1(!0,d,q,0)),N=Ce}const K=m.length;if(!K)return;const G=m[m.length-1];S=N-E,this.nextAudioTs=S+c*G.duration;const X=h?new Uint8Array(0):wr.moof(e.sequenceNumber++,j/c,Ft({},e,{samples:m}));e.samples=[];const te=(j-E)/a,ne=this.nextAudioTs/a,ae={data1:X,data2:O,startPTS:te,endPTS:ne,startDTS:te,endDTS:ne,type:"audio",hasAudio:!0,hasVideo:!1,nb:K};return this.isAudioContiguous=!0,ae}};function Hr(e,t){let r;if(t===null)return e;for(t<e?r=-8589934592:r=8589934592;Math.abs(e-t)>4294967296;)e+=r;return e}function L9(e){for(let t=0;t<e.length;t++)if(e[t].key)return t;return-1}function G1(e,t,r,n){const s=e.samples.length;if(!s)return;const a=e.inputTimeScale;for(let d=0;d<s;d++){const u=e.samples[d];u.pts=Hr(u.pts-r.baseTime*a/r.timescale,t*a)/a,u.dts=Hr(u.dts-n.baseTime*a/n.timescale,t*a)/a}const c=e.samples;return e.samples=[],{samples:c}}function Z1(e,t,r){const n=e.samples.length;if(!n)return;const s=e.inputTimeScale;for(let c=0;c<n;c++){const d=e.samples[c];d.pts=Hr(d.pts-r.baseTime*s/r.timescale,t*s)/s}e.samples.sort((c,d)=>c.pts-d.pts);const a=e.samples;return e.samples=[],{samples:a}}var O9=class extends rn{constructor(e,t,r,n){super("passthrough-remuxer",n),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(e){this.lastEndTime=null;const t=this.initPTS;t&&e&&t.baseTime===e.baseTime&&t.timescale===e.timescale||(this.initPTS=e)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(e,t,r,n){this.audioCodec=t,this.videoCodec=r,this.generateInitSegment(e,n),this.emitInitSegment=!0}generateInitSegment(e,t){let{audioCodec:r,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:s,video:a}=this.initData=uS(e);if(t)kG(e,t);else{const d=s||a;d!=null&&d.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${d.codec}")!`)}s&&(r=V1(s,Bt.AUDIO,this)),a&&(n=V1(a,Bt.VIDEO,this));const c={};s&&a?c.audiovideo={container:"video/mp4",codec:r+","+n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:s?c.audio={container:"audio/mp4",codec:r,encrypted:s.encrypted,initSegment:e,id:"audio"}:a?c.video={container:"video/mp4",codec:n,supplemental:a.supplemental,encrypted:a.encrypted,initSegment:e,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=c}remux(e,t,r,n,s,a){var c,d;let{initPTS:u,lastEndTime:f}=this;const h={audio:void 0,video:void 0,text:n,id3:r,initSegment:void 0};Ye(f)||(f=this.lastEndTime=s||0);const m=t.samples;if(!m.length)return h;const g={initPTS:void 0,timescale:void 0,trackId:void 0};let p=this.initData;if((c=p)!=null&&c.length||(this.generateInitSegment(m),p=this.initData),!((d=p)!=null&&d.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(g.tracks=this.initTracks,this.emitInitSegment=!1);const y=CG(m,p,this),S=p.audio?y[p.audio.id]:null,E=p.video?y[p.video.id]:null,T=Ic(E,1/0),j=Ic(S,1/0),N=Ic(E,0,!0),O=Ic(S,0,!0);let U=s,z=0;const K=S&&(!E||!u&&j<T||u&&u.trackId===p.audio.id),G=K?S:E;if(G){const Ce=G.timescale,q=G.start-s*Ce,Q=K?p.audio.id:p.video.id;U=G.start/Ce,z=K?O-j:N-T,(a||!u)&&(F9(u,U,s,z)||Ce!==u.timescale)&&(u&&this.warn(`Timestamps at playlist time: ${a?"":"~"}${s} ${q/Ce} != initPTS: ${u.baseTime/u.timescale} (${u.baseTime}/${u.timescale}) trackId: ${u.trackId}`),this.log(`Found initPTS at playlist time: ${s} offset: ${U-s} (${q}/${Ce}) trackId: ${Q}`),u=null,g.initPTS=q,g.timescale=Ce,g.trackId=Q)}else this.warn(`No audio or video samples found for initPTS at playlist time: ${s}`);u?(g.initPTS=u.baseTime,g.timescale=u.timescale,g.trackId=u.trackId):((!g.timescale||g.trackId===void 0||g.initPTS===void 0)&&(this.warn("Could not set initPTS"),g.initPTS=U,g.timescale=1,g.trackId=-1),this.initPTS=u={baseTime:g.initPTS,timescale:g.timescale,trackId:g.trackId});const X=U-u.baseTime/u.timescale,te=X+z;z>0?this.lastEndTime=te:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const ne=!!p.audio,ae=!!p.video;let oe="";ne&&(oe+="audio"),ae&&(oe+="video");const pe=(p.audio?p.audio.encrypted:!1)||(p.video?p.video.encrypted:!1),le={data1:m,startPTS:X,startDTS:X,endPTS:te,endDTS:te,type:oe,hasAudio:ne,hasVideo:ae,nb:1,dropped:0,encrypted:pe};h.audio=ne&&!ae?le:void 0,h.video=ae?le:void 0;const se=E?.sampleCount;if(se){const Ce=E.keyFrameIndex,q=Ce!==-1;le.nb=se,le.dropped=Ce===0||this.isVideoContiguous?0:q?Ce:se,le.independent=q,le.firstKeyFrame=Ce,q&&E.keyFrameStart&&(le.firstKeyFramePTS=(E.keyFrameStart-u.baseTime)/u.timescale),this.isVideoContiguous||(h.independent=q),this.isVideoContiguous||(this.isVideoContiguous=q),le.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${Ce}/${se} dropped: ${le.dropped} start: ${le.firstKeyFramePTS||"NA"}`)}return h.initSegment=g,h.id3=G1(r,s,u,u),n.samples.length&&(h.text=Z1(n,s,u)),h}};function Ic(e,t,r=!1){return e?.start!==void 0?(e.start+(r?e.duration:0))/e.timescale:t}function F9(e,t,r,n){if(e===null)return!0;const s=Math.max(n,1),a=t-e.baseTime/e.timescale;return Math.abs(a-r)>s}function V1(e,t,r){const n=e.codec;return n&&n.length>4?n:t===Bt.AUDIO?n==="ec-3"||n==="ac-3"||n==="alac"?n:n==="fLaC"||n==="Opus"?cc(n,!1):(r.warn(`Unhandled audio codec "${n}" in mp4 MAP`),n||"mp4a"):(r.warn(`Unhandled video codec "${n}" in mp4 MAP`),n||"avc1")}var Hn;try{Hn=self.performance.now.bind(self.performance)}catch{Hn=Date.now}var Pc=[{demux:w9,remux:O9},{demux:C9,remux:Cc},{demux:y9,remux:Cc},{demux:S9,remux:Cc}];Pc.splice(2,0,{demux:x9,remux:Cc});var H1=class{constructor(e,t,r,n,s,a){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=e,this.typeSupported=t,this.config=r,this.id=s,this.logger=a}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,t,r,n){const s=r.transmuxing;s.executeStart=Hn();let a=new Uint8Array(e);const{currentTransmuxState:c,transmuxConfig:d}=this;n&&(this.currentTransmuxState=n);const{contiguous:u,discontinuity:f,trackSwitch:h,accurateTimeOffset:m,timeOffset:g,initSegmentChange:p}=n||c,{audioCodec:y,videoCodec:S,defaultInitPts:E,duration:T,initSegmentData:j}=d,N=U9(a,t);if(N&&ks(N.method)){const K=this.getDecrypter(),G=dm(N.method);if(K.isSync()){let X=K.softwareDecrypt(a,N.key.buffer,N.iv.buffer,G);if(r.part>-1){const te=K.flush();X=te&&te.buffer}if(!X)return s.executeEnd=Hn(),Dm(r);a=new Uint8Array(X)}else return this.asyncResult=!0,this.decryptionPromise=K.webCryptoDecrypt(a,N.key.buffer,N.iv.buffer,G).then(X=>{const te=this.push(X,null,r);return this.decryptionPromise=null,te}),this.decryptionPromise}const O=this.needsProbing(f,h);if(O){const K=this.configureTransmuxer(a);if(K)return this.logger.warn(`[transmuxer] ${K.message}`),this.observer.emit($.ERROR,$.ERROR,{type:it.MEDIA_ERROR,details:fe.FRAG_PARSING_ERROR,fatal:!1,error:K,reason:K.message}),s.executeEnd=Hn(),Dm(r)}(f||h||p||O)&&this.resetInitSegment(j,y,S,T,t),(f||p||O)&&this.resetInitialTimestamp(E),u||this.resetContiguity();const U=this.transmux(a,N,g,m,r);this.asyncResult=$o(U);const z=this.currentTransmuxState;return z.contiguous=!0,z.discontinuity=!1,z.trackSwitch=!1,s.executeEnd=Hn(),U}flush(e){const t=e.transmuxing;t.executeStart=Hn();const{decrypter:r,currentTransmuxState:n,decryptionPromise:s}=this;if(s)return this.asyncResult=!0,s.then(()=>this.flush(e));const a=[],{timeOffset:c}=n;if(r){const h=r.flush();h&&a.push(this.push(h.buffer,null,e))}const{demuxer:d,remuxer:u}=this;if(!d||!u){t.executeEnd=Hn();const h=[Dm(e)];return this.asyncResult?Promise.resolve(h):h}const f=d.flush(c);return $o(f)?(this.asyncResult=!0,f.then(h=>(this.flushRemux(a,h,e),a))):(this.flushRemux(a,f,e),this.asyncResult?Promise.resolve(a):a)}flushRemux(e,t,r){const{audioTrack:n,videoTrack:s,id3Track:a,textTrack:c}=t,{accurateTimeOffset:d,timeOffset:u}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===Je.MAIN?"level":"track"} ${r.level}`);const f=this.remuxer.remux(n,s,a,c,u,d,!0,this.id);e.push({remuxResult:f,chunkMeta:r}),r.transmuxing.executeEnd=Hn()}resetInitialTimestamp(e){const{demuxer:t,remuxer:r}=this;!t||!r||(t.resetTimeStamp(e),r.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:t}=this;!e||!t||(e.resetContiguity(),t.resetNextTimestamp())}resetInitSegment(e,t,r,n,s){const{demuxer:a,remuxer:c}=this;!a||!c||(a.resetInitSegment(e,t,r,n),c.resetInitSegment(e,t,r,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,t,r,n,s){let a;return t&&t.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,t,r,n,s):a=this.transmuxUnencrypted(e,r,n,s),a}transmuxUnencrypted(e,t,r,n){const{audioTrack:s,videoTrack:a,id3Track:c,textTrack:d}=this.demuxer.demux(e,t,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,a,c,d,t,r,!1,this.id),chunkMeta:n}}transmuxSampleAes(e,t,r,n,s){return this.demuxer.demuxSampleAes(e,t,r).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,r,n,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){const{config:t,observer:r,typeSupported:n}=this;let s;for(let h=0,m=Pc.length;h<m;h++){var a;if((a=Pc[h].demux)!=null&&a.probe(e,this.logger)){s=Pc[h];break}}if(!s)return new Error("Failed to find demuxer by probing fragment data");const c=this.demuxer,d=this.remuxer,u=s.remux,f=s.demux;(!d||!(d instanceof u))&&(this.remuxer=new u(r,t,n,this.logger)),(!c||!(c instanceof f))&&(this.demuxer=new f(r,t,n,this.logger),this.probe=f.probe)}needsProbing(e,t){return!this.demuxer||!this.remuxer||e||t}getDecrypter(){let e=this.decrypter;return e||(e=this.decrypter=new lm(this.config)),e}};function U9(e,t){let r=null;return e.byteLength>0&&t?.key!=null&&t.iv!==null&&t.method!=null&&(r=t),r}var Dm=e=>({remuxResult:{},chunkMeta:e});function $o(e){return"then"in e&&e.then instanceof Function}var B9=class{constructor(e,t,r,n,s){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=e,this.videoCodec=t,this.initSegmentData=r,this.duration=n,this.defaultInitPts=s||null}},z9=class{constructor(e,t,r,n,s,a){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=e,this.contiguous=t,this.accurateTimeOffset=r,this.trackSwitch=n,this.timeOffset=s,this.initSegmentChange=a}},K1=0,W1=class{constructor(e,t,r,n){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=K1++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=d=>{const u=d.data,f=this.hls;if(!(!f||!(u!=null&&u.event)||u.instanceNo!==this.instanceNo))switch(u.event){case"init":{var h;const m=(h=this.workerContext)==null?void 0:h.objectURL;m&&self.URL.revokeObjectURL(m);break}case"transmuxComplete":this.handleTransmuxComplete(u.data);break;case"flush":this.onFlush(u.data);break;case"workerLog":f.logger[u.data.logType]&&f.logger[u.data.logType](u.data.message);break;default:u.data=u.data||{},u.data.frag=this.frag,u.data.part=this.part,u.data.id=this.id,f.trigger(u.event,u.data);break}},this.onWorkerError=d=>{if(!this.hls)return;const u=new Error(`${d.message} (${d.filename}:${d.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger($.ERROR,{type:it.OTHER_ERROR,details:fe.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:u})};const s=e.config;this.hls=e,this.id=t,this.useWorker=!!s.enableWorker,this.onTransmuxComplete=r,this.onFlush=n;const a=(d,u)=>{u=u||{},u.frag=this.frag||void 0,d===$.ERROR&&(u=u,u.parent=this.id,u.part=this.part,this.error=u.error),this.hls.trigger(d,u)};this.observer=new Sm,this.observer.on($.FRAG_DECRYPTED,a),this.observer.on($.ERROR,a);const c=bS(s.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const d=this.hls.logger;if(s.workerPath||V8()){try{s.workerPath?(d.log(`loading Web Worker ${s.workerPath} for "${t}"`),this.workerContext=K8(s.workerPath)):(d.log(`injecting Web Worker for "${t}"`),this.workerContext=H8());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:c,id:t,config:zt(s)})}catch(u){d.warn(`Error setting up "${t}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new H1(this.observer,c,s,"",t,e.logger)}return}}this.transmuxer=new H1(this.observer,c,s,"",t,e.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const e=this.instanceNo;this.instanceNo=K1++;const t=this.hls.config,r=bS(t.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:e,typeSupported:r,id:this.id,config:zt(t)})}}terminateWorker(){if(this.workerContext){const{worker:e}=this.workerContext;this.workerContext=null,e.removeEventListener("message",this.onWorkerMessage),e.removeEventListener("error",this.onWorkerError),W8(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const t=this.transmuxer;t&&(t.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(e,t,r,n,s,a,c,d,u,f){var h,m;u.transmuxing.start=self.performance.now();const{instanceNo:g,transmuxer:p}=this,y=a?a.start:s.start,S=s.decryptdata,E=this.frag,T=!(E&&s.cc===E.cc),j=!(E&&u.level===E.level),N=E?u.sn-E.sn:-1,O=this.part?u.part-this.part.index:-1,U=N===0&&u.id>1&&u.id===E?.stats.chunkCount,z=!j&&(N===1||N===0&&(O===1||U&&O<=0)),K=self.performance.now();(j||N||s.stats.parsing.start===0)&&(s.stats.parsing.start=K),a&&(O||!z)&&(a.stats.parsing.start=K);const G=!(E&&((h=s.initSegment)==null?void 0:h.url)===((m=E.initSegment)==null?void 0:m.url)),X=new z9(T,z,d,j,y,G);if(!z||T||G){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${s.type} sn: ${u.sn}${u.part>-1?" part: "+u.part:""} ${this.id===Je.MAIN?"level":"track"}: ${u.level} id: ${u.id}
165
+ discontinuity: ${T}
166
+ trackSwitch: ${j}
167
+ contiguous: ${z}
168
+ accurateTimeOffset: ${d}
169
+ timeOffset: ${y}
170
+ initSegmentChange: ${G}`);const te=new B9(r,n,t,c,f);this.configureTransmuxer(te)}if(this.frag=s,this.part=a,this.workerContext)this.workerContext.worker.postMessage({instanceNo:g,cmd:"demux",data:e,decryptdata:S,chunkMeta:u,state:X},e instanceof ArrayBuffer?[e]:[]);else if(p){const te=p.push(e,S,u,X);$o(te)?te.then(ne=>{this.handleTransmuxComplete(ne)}).catch(ne=>{this.transmuxerError(ne,u,"transmuxer-interface push error")}):this.handleTransmuxComplete(te)}}flush(e){e.transmuxing.start=self.performance.now();const{instanceNo:t,transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:t,cmd:"flush",chunkMeta:e});else if(r){const n=r.flush(e);$o(n)?n.then(s=>{this.handleFlushResult(s,e)}).catch(s=>{this.transmuxerError(s,e,"transmuxer-interface flush error")}):this.handleFlushResult(n,e)}}transmuxerError(e,t,r){this.hls&&(this.error=e,this.hls.trigger($.ERROR,{type:it.MEDIA_ERROR,details:fe.FRAG_PARSING_ERROR,chunkMeta:t,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:e,err:e,reason:r}))}handleFlushResult(e,t){e.forEach(r=>{this.handleTransmuxComplete(r)}),this.onFlush(t)}configureTransmuxer(e){const{instanceNo:t,transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:t,cmd:"configure",config:e}):r&&r.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}},q1=100,G9=class extends ym{constructor(e,t,r){super(e,t,r,"audio-stream-controller",Je.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.waitingData=null,this.mainDetails=null,this.flushing=!1,this.bufferFlushed=!1,this.cachedTrackLoadedData=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.resetItem()}resetItem(){this.mainDetails=this.mainAnchor=this.mainFragLoading=this.bufferedTrack=this.switchingTrack=this.waitingData=this.cachedTrackLoadedData=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on($.LEVEL_LOADED,this.onLevelLoaded,this),e.on($.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on($.BUFFER_RESET,this.onBufferReset,this),e.on($.BUFFER_CREATED,this.onBufferCreated,this),e.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on($.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on($.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on($.FRAG_LOADING,this.onFragLoading,this),e.on($.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:e}=this;e&&(super.unregisterListeners(),e.off($.LEVEL_LOADED,this.onLevelLoaded,this),e.off($.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off($.BUFFER_RESET,this.onBufferReset,this),e.off($.BUFFER_CREATED,this.onBufferCreated,this),e.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off($.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off($.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off($.FRAG_LOADING,this.onFragLoading,this),e.off($.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:s,trackId:a}){if(r===Je.MAIN){const c=t.cc,d=this.fragCurrent;if(this.initPTS[c]={baseTime:n,timescale:s,trackId:a},this.log(`InitPTS for cc: ${c} found from main: ${n/s} (${n}/${s}) trackId: ${a}`),this.mainAnchor=t,this.state===Ne.WAITING_INIT_PTS){const u=this.waitingData;(!u&&!this.loadingParts||u&&u.frag.cc!==c)&&this.syncWithAnchor(t,u?.frag)}else!this.hls.hasEnoughToStart&&d&&d.cc!==c?(d.abortRequests(),this.syncWithAnchor(t,d)):this.state===Ne.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(e,t){var r;const n=((r=this.mainFragLoading)==null?void 0:r.frag)||null;if(t&&n?.cc===t.cc)return;const s=(n||e).cc,a=jS(this.getLevelDetails(),s,this.getLoadPosition());a&&(this.log(`Syncing with main frag at ${a.start} cc ${a.cc}`),this.startFragRequested=!1,this.nextLoadPosition=a.start,this.resetLoadingState(),this.state===Ne.IDLE&&this.doTickIdle())}startLoad(e,t){if(!this.levels){this.startPosition=e,this.state=Ne.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(q1),r>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r,this.state=Ne.IDLE):this.state=Ne.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}doTick(){switch(this.state){case Ne.IDLE:this.doTickIdle();break;case Ne.WAITING_TRACK:{const{levels:e,trackId:t}=this,r=e?.[t],n=r?.details;if(n&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(n))break;this.state=Ne.WAITING_INIT_PTS}break}case Ne.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break;case Ne.WAITING_INIT_PTS:{const e=this.waitingData;if(e){const{frag:t,part:r,cache:n,complete:s}=e,a=this.mainAnchor;if(this.initPTS[t.cc]!==void 0){this.waitingData=null,this.state=Ne.FRAG_LOADING;const c={frag:t,part:r,payload:n.flush().buffer,networkDetails:null};this._handleFragmentLoadProgress(c),s&&super._handleFragmentLoadComplete(c)}else a&&a.cc!==e.frag.cc&&this.syncWithAnchor(a,e.frag)}else this.state=Ne.IDLE}}this.onTickEnd()}resetLoadingState(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){var e;const{hls:t,levels:r,media:n,trackId:s}=this,a=t.config;if(!this.buffering||!n&&!this.primaryPrefetch&&(this.startFragRequested||!a.startFragPrefetch)||!(r!=null&&r[s]))return;const c=r[s],d=c.details;if(!d||this.waitForLive(c)||this.waitForCdnTuneIn(d)){this.state=Ne.WAITING_TRACK,this.startFragRequested=!1;return}const u=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&u&&(this.bufferFlushed=!1,this.afterBufferFlushed(u,Bt.AUDIO,Je.AUDIO));const f=this.getFwdBufferInfo(u,Je.AUDIO);if(f===null)return;if(!this.switchingTrack&&this._streamEnded(f,d)){t.trigger($.BUFFER_EOS,{type:"audio"}),this.state=Ne.ENDED;return}const h=f.len,m=t.maxBufferLength,g=d.fragments,p=g[0].start,y=this.getLoadPosition(),S=this.flushing?y:f.end;if(this.switchingTrack&&n){const j=y;d.PTSKnown&&j<p&&(f.end>p||f.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=p+.05)}if(h>=m&&!this.switchingTrack&&S<g[g.length-1].start)return;let E=this.getNextFragment(S,d);if(E&&this.isLoopLoading(E,S)&&(E=this.getNextFragmentLoopLoading(E,d,f,Je.MAIN,m)),!E){this.bufferFlushed=!0;return}if(this.exceedsMaxBuffer(f,m,E))return;let T=((e=this.mainFragLoading)==null?void 0:e.frag)||null;if(!this.audioOnly&&this.startFragRequested&&T&&ar(E)&&!E.endList&&(!d.live||!this.loadingParts&&S<this.hls.liveSyncPosition)&&(this.fragmentTracker.getState(T)===pr.OK&&(this.mainFragLoading=T=null),T&&ar(T))){if(E.start>T.end){const j=this.fragmentTracker.getFragAtPos(S,Je.MAIN);j&&j.end>T.end&&(T=j,this.mainFragLoading={frag:j,targetBufferTime:null})}if(E.start>T.end)return}this.loadFragment(E,c,S)}onMediaDetaching(e,t){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(e,t)}onAudioTracksUpdated(e,{audioTracks:t}){this.resetTransmuxer(),this.levels=t.map(r=>new Co(r))}onAudioTrackSwitching(e,t){const r=!!t.url;this.trackId=t.id;const{fragCurrent:n}=this;n&&(n.abortRequests(),this.removeUnbufferedFrags(n.start)),this.resetLoadingState(),r?(this.switchingTrack=t,this.flushAudioIfNeeded(t),this.state!==Ne.STOPPED&&(this.setInterval(q1),this.state=Ne.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=t,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(e,t){this.mainDetails=t.details;const r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded($.AUDIO_TRACK_LOADED,r))}onAudioTrackLoaded(e,t){var r;const{levels:n}=this,{details:s,id:a,groupId:c,track:d}=t;if(!n){this.warn(`Audio tracks reset while loading track ${a} "${d.name}" of "${c}"`);return}const u=this.mainDetails;if(!u||s.endCC>u.endCC||u.expired){this.cachedTrackLoadedData=t,this.state!==Ne.STOPPED&&(this.state=Ne.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${a} "${d.name}" of "${c}" loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const f=n[a];let h=0;if(s.live||(r=f.details)!=null&&r.live){if(this.checkLiveUpdate(s),s.deltaUpdateFailed)return;if(f.details){var m;h=this.alignPlaylists(s,f.details,(m=this.levelLastLoaded)==null?void 0:m.details)}s.alignedSliding||(x1(s,u),s.alignedSliding||_c(s,u),h=s.fragmentStart)}f.details=s,this.levelLastLoaded=f,this.startFragRequested||this.setStartPosition(u,h),this.hls.trigger($.AUDIO_TRACK_UPDATED,{details:s,id:a,groupId:t.groupId}),this.state===Ne.WAITING_TRACK&&!this.waitForCdnTuneIn(s)&&(this.state=Ne.IDLE),this.tick()}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:n,payload:s}=e,{config:a,trackId:c,levels:d}=this;if(!d){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const u=d[c];if(!u){this.warn("Audio track is undefined on fragment load progress");return}const f=u.details;if(!f){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(r.start);return}const h=a.defaultAudioCodec||u.audioCodec||"mp4a.40.2";let m=this.transmuxer;m||(m=this.transmuxer=new W1(this.hls,Je.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const g=this.initPTS[r.cc],p=(t=r.initSegment)==null?void 0:t.data;if(g!==void 0){const S=n?n.index:-1,E=S!==-1,T=new cm(r.level,r.sn,r.stats.chunkCount,s.byteLength,S,E);m.push(s,p,h,"",r,n,f.totalduration,!1,T,g)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${f.startSN} ,${f.endSN}],track ${c}`);const{cache:y}=this.waitingData=this.waitingData||{frag:r,part:n,cache:new _1,complete:!1};y.push(new Uint8Array(s)),this.state!==Ne.STOPPED&&(this.state=Ne.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(e,t){this.bufferFlushed=this.flushing=!1;const r=t.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}onFragLoading(e,t){!this.audioOnly&&t.frag.type===Je.MAIN&&ar(t.frag)&&(this.mainFragLoading=t,this.state===Ne.IDLE&&this.tick())}onFragBuffered(e,t){const{frag:r,part:n}=t;if(r.type!==Je.AUDIO){!this.audioOnly&&r.type===Je.MAIN&&!r.elementaryStreams.video&&!r.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(ar(r)){this.fragPrevious=r;const s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger($.AUDIO_TRACK_SWITCHED,Mt({},s)))}this.fragBufferedComplete(r,n),this.media&&this.tick()}onError(e,t){var r;if(t.fatal){this.state=Ne.ERROR;return}switch(t.details){case fe.FRAG_GAP:case fe.FRAG_PARSING_ERROR:case fe.FRAG_DECRYPT_ERROR:case fe.FRAG_LOAD_ERROR:case fe.FRAG_LOAD_TIMEOUT:case fe.KEY_LOAD_ERROR:case fe.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Je.AUDIO,t);break;case fe.AUDIO_TRACK_LOAD_ERROR:case fe.AUDIO_TRACK_LOAD_TIMEOUT:case fe.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Ne.WAITING_TRACK&&((r=t.context)==null?void 0:r.type)===Et.AUDIO_TRACK&&(this.state=Ne.IDLE);break;case fe.BUFFER_ADD_CODEC_ERROR:case fe.BUFFER_APPEND_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)||this.resetLoadingState();break;case fe.BUFFER_FULL_ERROR:if(t.parent!=="audio")return;this.reduceLengthAndFlushBuffer(t)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case fe.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onBufferFlushing(e,{type:t}){t!==Bt.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:t}){if(t!==Bt.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Ne.ENDED&&(this.state=Ne.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,t,Je.AUDIO),this.tick())}}_handleTransmuxComplete(e){var t;const r="audio",{hls:n}=this,{remuxResult:s,chunkMeta:a}=e,c=this.getCurrentContext(a);if(!c){this.resetWhenMissingContext(a);return}const{frag:d,part:u,level:f}=c,{details:h}=f,{audio:m,text:g,id3:p,initSegment:y}=s;if(this.fragContextChanged(d)||!h){this.fragmentTracker.removeFragment(d);return}if(this.state=Ne.PARSING,this.switchingTrack&&m&&this.completeAudioSwitch(this.switchingTrack),y!=null&&y.tracks){const S=d.initSegment||d;if(this.unhandledEncryptionError(y,d))return;this._bufferInitSegment(f,y.tracks,S,a),n.trigger($.FRAG_PARSING_INIT_SEGMENT,{frag:S,id:r,tracks:y.tracks})}if(m){const{startPTS:S,endPTS:E,startDTS:T,endDTS:j}=m;u&&(u.elementaryStreams[Bt.AUDIO]={startPTS:S,endPTS:E,startDTS:T,endDTS:j}),d.setElementaryStreamInfo(Bt.AUDIO,S,E,T,j),this.bufferFragmentData(m,d,u,a)}if(p!=null&&(t=p.samples)!=null&&t.length){const S=Ft({id:r,frag:d,details:h},p);n.trigger($.FRAG_PARSING_METADATA,S)}if(g){const S=Ft({id:r,frag:d,details:h},g);n.trigger($.FRAG_PARSING_USERDATA,S)}}_bufferInitSegment(e,t,r,n){if(this.state!==Ne.PARSING||(t.video&&delete t.video,t.audiovideo&&delete t.audiovideo,!t.audio))return;const s=t.audio;s.id=Je.AUDIO;const a=e.audioCodec;this.log(`Init audio buffer, container:${s.container}, codecs[level/parsed]=[${a}/${s.codec}]`),a&&a.split(",").length===1&&(s.levelCodec=a),this.hls.trigger($.BUFFER_CODECS,t);const c=s.initSegment;if(c!=null&&c.byteLength){const d={type:"audio",frag:r,part:null,chunkMeta:n,parent:r.type,data:c};this.hls.trigger($.BUFFER_APPENDING,d)}this.tickImmediate()}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);if(this.switchingTrack||n===pr.NOT_LOADED||n===pr.PARTIAL){var s;if(!ar(e))this._loadInitSegment(e,t);else if((s=t.details)!=null&&s.live&&!this.initPTS[e.cc]){this.log(`Waiting for video PTS in continuity counter ${e.cc} of live stream before loading audio fragment ${e.sn} of level ${this.trackId}`),this.state=Ne.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragmentStart!==t.details.fragmentStart&&_c(t.details,a)}else super.loadFragment(e,t,r)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){if(this.media&&this.bufferedTrack){const{name:t,lang:r,assocLang:n,characteristics:s,audioCodec:a,channels:c}=this.bufferedTrack;Li({name:t,lang:r,assocLang:n,characteristics:s,audioCodec:a,channels:c},e,Oi)||(hc(e.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=e)}}completeAudioSwitch(e){const{hls:t}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,t.trigger($.AUDIO_TRACK_SWITCHED,Mt({},e))}},Mm=class extends rn{constructor(e,t){super(t,e.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=e}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,t,r){const n=t?.renditionReports;if(n){let s=-1;for(let a=0;a<n.length;a++){const c=n[a];let d;try{d=new self.URL(c.URI,t.url).href}catch(u){this.warn(`Could not construct new URL for Rendition Report: ${u}`),d=c.URI||""}if(d===e){s=a;break}else d===e.substring(0,d.length)&&(s=a)}if(s!==-1){const a=n[s],c=parseInt(a["LAST-MSN"])||t.lastPartSn;let d=parseInt(a["LAST-PART"])||t.lastPartIndex;if(this.hls.config.lowLatencyMode){const f=Math.min(t.age-t.partTarget,t.targetduration);d>=0&&f>t.partTarget&&(d+=1)}const u=r&&wS(r);return new ES(c,d>=0?d:void 0,u)}}}loadPlaylist(e){this.clearTimer()}loadingPlaylist(e,t){this.clearTimer()}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}getUrlWithDirectives(e,t){if(t)try{return t.addDirectives(e)}catch(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}return e}playlistLoaded(e,t,r){const{details:n,stats:s}=t,a=self.performance.now(),c=s.loading.first?Math.max(0,a-s.loading.first):0;n.advancedDateTime=Date.now()-c;const d=this.hls.config.timelineOffset;if(d!==n.appliedTimelineOffset){const f=Math.max(d||0,0);n.appliedTimelineOffset=f,n.fragments.forEach(h=>{h.setStart(h.playlistOffset+f)})}if(n.live||r!=null&&r.live){const f="levelInfo"in t?t.levelInfo:t.track;if(n.reloaded(r),r&&n.fragments.length>0){$8(r,n,this);const E=n.playlistParsingError;if(E){this.warn(E);const T=this.hls;if(!T.config.ignorePlaylistParsingErrors){var u;const{networkDetails:j}=t;T.trigger($.ERROR,{type:it.NETWORK_ERROR,details:fe.LEVEL_PARSING_ERROR,fatal:!1,url:n.url,error:E,reason:E.message,level:t.level||void 0,parent:(u=n.fragments[0])==null?void 0:u.type,networkDetails:j,stats:s});return}n.playlistParsingError=null}}n.requestScheduled===-1&&(n.requestScheduled=s.loading.start);const h=this.hls.mainForwardBufferInfo,m=h?h.end-h.len:0,g=f1(n,(n.edge-m)*1e3);if(n.requestScheduled+g<a?n.requestScheduled=a:n.requestScheduled+=g,this.log(`live playlist ${e} ${n.advanced?"REFRESHED "+n.lastPartSn+"-"+n.lastPartIndex:n.updated?"UPDATED":"MISSED"}`),!this.canLoad||!n.live)return;let p,y,S;if(n.canBlockReload&&n.endSN&&n.advanced){const E=this.hls.config.lowLatencyMode,T=n.lastPartSn,j=n.endSN,N=n.lastPartIndex,O=N!==-1,U=T===j;O?U?(y=j+1,S=E?0:N):(y=T,S=E?N+1:n.maxPartIndex):y=j+1;const z=n.age,K=z+n.ageHeader;let G=Math.min(K-n.partTarget,n.targetduration*1.5);if(G>0){if(K>n.targetduration*3)this.log(`Playlist last advanced ${z.toFixed(2)}s ago. Omitting segment and part directives.`),y=void 0,S=void 0;else if(r!=null&&r.tuneInGoal&&K-n.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${G} with playlist age: ${n.age}`),G=0;else{const X=Math.floor(G/n.targetduration);if(y+=X,S!==void 0){const te=Math.round(G%n.targetduration/n.partTarget);S+=te}this.log(`CDN Tune-in age: ${n.ageHeader}s last advanced ${z.toFixed(2)}s goal: ${G} skip sn ${X} to part ${S}`)}n.tuneInGoal=G}if(p=this.getDeliveryDirectives(n,t.deliveryDirectives,y,S),E||!U){n.requestScheduled=a,this.loadingPlaylist(f,p);return}}else(n.canBlockReload||n.canSkipUntil)&&(p=this.getDeliveryDirectives(n,t.deliveryDirectives,y,S));p&&y!==void 0&&n.canBlockReload&&(n.requestScheduled=s.loading.first+Math.max(g-c*2,g/2)),this.scheduleLoading(f,p,n)}else this.clearTimer()}scheduleLoading(e,t,r){const n=r||e.details;if(!n){this.loadingPlaylist(e,t);return}const s=self.performance.now(),a=n.requestScheduled;if(s>=a){this.loadingPlaylist(e,t);return}const c=a-s;this.log(`reload live playlist ${e.name||e.bitrate+"bps"} in ${Math.round(c)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(e,t),c)}getDeliveryDirectives(e,t,r,n){let s=wS(e);return t!=null&&t.skip&&e.deltaUpdateFailed&&(r=t.msn,n=t.part,s=fc.No),new ES(r,n,s)}checkRetry(e){const t=e.details,r=mc(e),n=e.errorAction,{action:s,retryCount:a=0,retryConfig:c}=n||{},d=!!n&&!!c&&(s===Sr.RetryRequest||!n.resolved&&s===Sr.SendAlternateToPenaltyBox);if(d){var u;if(a>=c.maxNumRetry)return!1;if(r&&(u=e.context)!=null&&u.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${c.maxNumRetry} after "${t}" without delivery-directives`),this.loadPlaylist();else{const f=am(c,a);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),f),this.warn(`Retrying playlist loading ${a+1}/${c.maxNumRetry} after "${t}" in ${f}ms`)}e.levelRetry=!0,n.resolved=!0}return d}};function Q1(e,t){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(!Ro(e[r].attrs,t[r].attrs))return!1;return!0}function Ro(e,t,r){const n=e["STABLE-RENDITION-ID"];return n&&!r?n===t["STABLE-RENDITION-ID"]:!(r||["LANGUAGE","NAME","CHARACTERISTICS","AUTOSELECT","DEFAULT","FORCED","ASSOC-LANGUAGE"]).some(s=>e[s]!==t[s])}function $m(e,t){return t.label.toLowerCase()===e.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(e.lang||"").toLowerCase())}var Z9=class extends Mm{constructor(e){super(e,"audio-track-controller"),this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.registerListeners()}registerListeners(){const{hls:e}=this;e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.LEVEL_LOADING,this.onLevelLoading,this),e.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.LEVEL_LOADING,this.onLevelLoading,this),e.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off($.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off($.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.audioTracks||[]}onAudioTrackLoaded(e,t){const{id:r,groupId:n,details:s}=t,a=this.tracksInGroup[r];if(!a||a.groupId!==n){this.warn(`Audio track with id:${r} and group:${n} not found in active group ${a?.groupId}`);return}const c=a.details;a.details=t.details,this.log(`Audio track ${r} "${a.name}" lang:${a.lang} group:${n} loaded [${s.startSN}-${s.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,c)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const r=t.audioGroups||null,n=this.groupIds;let s=this.currentTrack;if(!r||n?.length!==r?.length||r!=null&&r.some(c=>n?.indexOf(c)===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const c=this.tracks.filter(m=>!r||r.indexOf(m.groupId)!==-1);if(c.length)this.selectDefaultTrack&&!c.some(m=>m.default)&&(this.selectDefaultTrack=!1),c.forEach((m,g)=>{m.id=g});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=c;const d=this.hls.config.audioPreference;if(!s&&d){const m=Pn(d,c,Oi);if(m>-1)s=c[m];else{const g=Pn(d,this.tracks);s=this.tracks[g]}}let u=this.findTrackId(s);u===-1&&s&&(u=this.findTrackId(null));const f={audioTracks:c};this.log(`Updating audio tracks, ${c.length} track(s) found in group(s): ${r?.join(",")}`),this.hls.trigger($.AUDIO_TRACKS_UPDATED,f);const h=this.trackId;if(u!==-1&&h===-1)this.setAudioTrack(u);else if(c.length&&h===-1){var a;const m=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${c.length}`);this.warn(m.message),this.hls.trigger($.ERROR,{type:it.MEDIA_ERROR,details:fe.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:m})}}}onError(e,t){t.fatal||!t.context||t.context.type===Et.AUDIO_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(e){this.selectDefaultTrack=!1,this.setAudioTrack(e)}setAudioOption(e){const t=this.hls;if(t.config.audioPreference=e,e){const r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){const n=this.currentTrack;if(n&&Li(e,n,Oi))return n;const s=Pn(e,this.tracksInGroup,Oi);if(s>-1){const a=this.tracksInGroup[s];return this.setAudioTrack(s),a}else if(n){let a=t.loadLevel;a===-1&&(a=t.firstAutoLevel);const c=r8(e,t.levels,r,a,Oi);if(c===-1)return null;t.nextLoadLevel=c}if(e.channels||e.audioCodec){const a=Pn(e,r);if(a>-1)return r[a]}}}return null}setAudioTrack(e){const t=this.tracksInGroup;if(e<0||e>=t.length){this.warn(`Invalid audio track id: ${e}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,n=t[e],s=n.details&&!n.details.live;if(e===this.trackId&&n===r&&s||(this.log(`Switching to audio-track ${e} "${n.name}" lang:${n.lang} group:${n.groupId} channels:${n.channels}`),this.trackId=e,this.currentTrack=n,this.hls.trigger($.AUDIO_TRACK_SWITCHING,Mt({},n)),s))return;const a=this.switchParams(n.url,r?.details,n.details);this.loadPlaylist(a)}findTrackId(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const n=t[r];if(!(this.selectDefaultTrack&&!n.default)&&(!e||Li(e,n,Oi)))return r}if(e){const{name:r,lang:n,assocLang:s,characteristics:a,audioCodec:c,channels:d}=e;for(let u=0;u<t.length;u++){const f=t[u];if(Li({name:r,lang:n,assocLang:s,characteristics:a,audioCodec:c,channels:d},f,Oi))return u}for(let u=0;u<t.length;u++){const f=t[u];if(Ro(e.attrs,f.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return u}for(let u=0;u<t.length;u++){const f=t[u];if(Ro(e.attrs,f.attrs,["LANGUAGE"]))return u}}return-1}loadPlaylist(e){super.loadPlaylist();const t=this.currentTrack;this.shouldLoadPlaylist(t)&&hc(t.url,this.hls)&&this.scheduleLoading(t,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=e.id,n=e.groupId,s=this.getUrlWithDirectives(e.url,t),a=e.details,c=a?.age;this.log(`Loading audio-track ${r} "${e.name}" lang:${e.lang} group:${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${c&&a.live?" age "+c.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger($.AUDIO_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:t||null,track:e})}},V9=class{constructor(e){this.tracks=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.tracks=e}destroy(){this.tracks=this.queues=null}append(e,t,r){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];n.push(e),n.length===1&&!r&&this.executeNext(t)}appendBlocker(e){return new Promise(t=>{const r={label:"async-blocker",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,e)})}prependBlocker(e){return new Promise(t=>{if(this.queues){const r={label:"async-blocker-prepend",execute:t,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[e].unshift(r)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(e=>{var t;const r=(t=e[0])==null?void 0:t.label;(r==="async-blocker"||r==="async-blocker-prepend")&&(e[0].execute(),e.splice(0,1))})}unblockAudio(e){this.queues!==null&&this.queues.audio[0]===e&&this.shiftAndExecuteNext("audio")}executeNext(e){if(this.queues===null||this.tracks===null)return;const t=this.queues[e];if(t.length){const n=t[0];try{n.execute()}catch(s){var r;if(n.onError(s),this.queues===null||this.tracks===null)return;const a=(r=this.tracks[e])==null?void 0:r.buffer;a!=null&&a.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues!==null&&(this.queues[e].shift(),this.executeNext(e))}current(e){var t;return((t=this.queues)==null?void 0:t[e][0])||null}toString(){const{queues:e,tracks:t}=this;return e===null||t===null?"<destroyed>":`
171
+ ${this.list("video")}
172
+ ${this.list("audio")}
173
+ ${this.list("audiovideo")}}`}list(e){var t,r;return(t=this.queues)!=null&&t[e]||(r=this.tracks)!=null&&r[e]?`${e}: (${this.listSbInfo(e)}) ${this.listOps(e)}`:""}listSbInfo(e){var t;const r=(t=this.tracks)==null?void 0:t[e],n=r?.buffer;return n?`SourceBuffer${n.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(e){var t;return((t=this.queues)==null?void 0:t[e].map(r=>r.label).join(", "))||""}},Y1=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,X1="HlsJsTrackRemovedError",H9=class extends Error{constructor(e){super(e),this.name=X1}},K9=class extends rn{constructor(e,t){super("buffer-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=r=>{var n;this.hls&&((n=this.mediaSource)==null?void 0:n.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=r=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=r=>{const{media:n,mediaSource:s}=this;r&&this.log("Media source opened"),!(!n||!s)&&(s.removeEventListener("sourceopen",this._onMediaSourceOpen),n.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger($.MEDIA_ATTACHED,{media:n,mediaSource:s}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:r,_objectUrl:n}=this;r!==n&&this.error(`Media element src was set while attaching MediaSource (${n} > ${r})`)},this.hls=e,this.fragmentTracker=t,this.appendSource=gG(di(e.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.transferData=this.overrides=void 0,this.operationQueue&&(this.operationQueue.destroy(),this.operationQueue=null),this.hls=this.fragmentTracker=null,this._onMediaSourceOpen=this._onMediaSourceClose=null,this._onMediaSourceEnded=null,this._onStartStreaming=this._onEndStreaming=null}registerListeners(){const{hls:e}=this;e.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.BUFFER_RESET,this.onBufferReset,this),e.on($.BUFFER_APPENDING,this.onBufferAppending,this),e.on($.BUFFER_CODECS,this.onBufferCodecs,this),e.on($.BUFFER_EOS,this.onBufferEos,this),e.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on($.LEVEL_UPDATED,this.onLevelUpdated,this),e.on($.FRAG_PARSED,this.onFragParsed,this),e.on($.FRAG_CHANGED,this.onFragChanged,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.BUFFER_RESET,this.onBufferReset,this),e.off($.BUFFER_APPENDING,this.onBufferAppending,this),e.off($.BUFFER_CODECS,this.onBufferCodecs,this),e.off($.BUFFER_EOS,this.onBufferEos,this),e.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off($.LEVEL_UPDATED,this.onLevelUpdated,this),e.off($.FRAG_PARSED,this.onFragParsed,this),e.off($.FRAG_CHANGED,this.onFragChanged,this),e.off($.ERROR,this.onError,this)}transferMedia(){const{media:e,mediaSource:t}=this;if(!e)return null;const r={};if(this.operationQueue){const s=this.isUpdating();s||this.operationQueue.removeBlockers();const a=this.isQueued();(s||a)&&this.warn(`Transfering MediaSource with${a?" operations in queue":""}${s?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const n=this.transferData;return!this.sourceBufferCount&&n&&n.mediaSource===t?Ft(r,n.tracks):this.sourceBuffers.forEach(s=>{const[a]=s;a&&(r[a]=Ft({},this.tracks[a]),this.removeBuffer(a)),s[0]=s[1]=null}),{media:e,mediaSource:t,tracks:r}}initTracks(){const e={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=e,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,t){var r;let n=2;(t.audio&&!t.video||!t.altAudio)&&(n=1),this.bufferCodecEventsTotal=n,this.log(`${n} bufferCodec event(s) expected.`),(r=this.transferData)!=null&&r.mediaSource&&this.sourceBufferCount&&n&&this.bufferCreated()}onMediaAttaching(e,t){const r=this.media=t.media;this.transferData=this.overrides=void 0;const n=di(this.appendSource);if(n){const s=!!t.mediaSource;(s||t.overrides)&&(this.transferData=t,this.overrides=t.overrides);const a=this.mediaSource=t.mediaSource||new n;if(this.assignMediaSource(a),s)this._objectUrl=r.src,this.attachTransferred();else{const c=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{r.removeAttribute("src");const d=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||d&&a instanceof d,J1(r),W9(r,c),r.load()}catch{r.src=c}else r.src=c}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(e){var t,r;this.log(`${((t=this.transferData)==null?void 0:t.mediaSource)===e?"transferred":"created"} media source: ${(r=e.constructor)==null?void 0:r.name}`),e.addEventListener("sourceopen",this._onMediaSourceOpen),e.addEventListener("sourceended",this._onMediaSourceEnded),e.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(e.addEventListener("startstreaming",this._onStartStreaming),e.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const e=this.media,t=this.transferData;if(!t||!e)return;const r=this.tracks,n=t.tracks,s=n?Object.keys(n):null,a=s?s.length:0,c=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(n&&s&&a){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal})
174
+ required tracks: ${zt(r,(d,u)=>d==="initSegment"?void 0:u)};
175
+ transfer tracks: ${zt(n,(d,u)=>d==="initSegment"?void 0:u)}}`),!eS(n,r)){t.mediaSource=null,t.tracks=void 0;const d=e.currentTime,u=this.details,f=Math.max(d,u?.fragments[0].start||0);if(f-d>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${d} -> ${f}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(n)}"->"${Object.keys(r)}") start time: ${f} currentTime: ${d}`),this.onMediaDetaching($.MEDIA_DETACHING,{}),this.onMediaAttaching($.MEDIA_ATTACHING,t),e.currentTime=f;return}this.transferData=void 0,s.forEach(d=>{const u=d,f=n[u];if(f){const h=f.buffer;if(h){const m=this.fragmentTracker,g=f.id;if(m.hasFragments(g)||m.hasParts(g)){const S=xt.getBuffered(h);m.detectEvictedFragments(u,S,g,null,!0)}const p=Rm(u),y=[u,h];this.sourceBuffers[p]=y,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(u),this.trackSourceBuffer(u,f)}}}),c(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),c()}get mediaSourceOpenOrEnded(){var e;const t=(e=this.mediaSource)==null?void 0:e.readyState;return t==="open"||t==="ended"}onMediaDetaching(e,t){const r=!!t.transferMedia;this.transferData=this.overrides=void 0;const{media:n,mediaSource:s,_objectUrl:a}=this;if(s){if(this.log(`media source ${r?"transferring":"detaching"}`),r)this.sourceBuffers.forEach(([c])=>{c&&this.removeBuffer(c)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const c=s.readyState==="open";try{const d=s.sourceBuffers;for(let u=d.length;u--;)c&&d[u].abort(),s.removeSourceBuffer(d[u]);c&&s.endOfStream()}catch(d){this.warn(`onMediaDetaching: ${d.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}s.removeEventListener("sourceopen",this._onMediaSourceOpen),s.removeEventListener("sourceended",this._onMediaSourceEnded),s.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(s.removeEventListener("startstreaming",this._onStartStreaming),s.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}n&&(n.removeEventListener("emptied",this._onMediaEmptied),r||(a&&self.URL.revokeObjectURL(a),this.mediaSrc===a?(n.removeAttribute("src"),this.appendSource&&J1(n),n.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger($.MEDIA_DETACHED,t)}onBufferReset(){this.sourceBuffers.forEach(([e])=>{e&&this.resetBuffer(e)}),this.initTracks()}resetBuffer(e){var t;const r=(t=this.tracks[e])==null?void 0:t.buffer;if(this.removeBuffer(e),r)try{var n;(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(s){this.warn(`onBufferReset ${e}`,s)}delete this.tracks[e]}removeBuffer(e){this.removeBufferListeners(e),this.sourceBuffers[Rm(e)]=[null,null];const t=this.tracks[e];t&&(t.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new V9(this.tracks)}onBufferCodecs(e,t){var r;const n=this.tracks,s=Object.keys(t);this.log(`BUFFER_CODECS: "${s}" (current SB count ${this.sourceBufferCount})`);const a="audiovideo"in t&&(n.audio||n.video)||n.audiovideo&&("audio"in t||"video"in t),c=!a&&this.sourceBufferCount&&this.media&&s.some(d=>!n[d]);if(a||c){this.warn(`Unsupported transition between "${Object.keys(n)}" and "${s}" SourceBuffers`);return}s.forEach(d=>{var u,f;const{id:h,codec:m,levelCodec:g,container:p,metadata:y,supplemental:S}=t[d];let E=n[d];const T=(u=this.transferData)==null||(u=u.tracks)==null?void 0:u[d],j=T!=null&&T.buffer?T:E,N=j?.pendingCodec||j?.codec,O=j?.levelCodec;E||(E=n[d]={buffer:void 0,listeners:[],codec:m,supplemental:S,container:p,levelCodec:g,metadata:y,id:h});const U=uc(N,O),z=U?.replace(Y1,"$1");let K=uc(m,g);const G=(f=K)==null?void 0:f.replace(Y1,"$1");K&&U&&z!==G&&(d.slice(0,5)==="audio"&&(K=cc(K,this.appendSource)),this.log(`switching codec ${N} to ${K}`),K!==(E.pendingCodec||E.codec)&&(E.pendingCodec=K),E.container=p,this.appendChangeType(d,p,K))}),(this.tracksReady||this.sourceBufferCount)&&(t.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!t.video&&((r=t.audio)==null?void 0:r.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((e,t)=>{const r=this.tracks[t];return e[t]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},e},{})}appendChangeType(e,t,r){const n=`${t};codecs=${r}`,s={label:`change-type=${n}`,execute:()=>{const a=this.tracks[e];if(a){const c=a.buffer;c!=null&&c.changeType&&(this.log(`changing ${e} sourceBuffer type to ${n}`),c.changeType(n),a.codec=r,a.container=t)}this.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn(`Failed to change ${e} SourceBuffer type`,a)}};this.append(s,e,this.isPending(this.tracks[e]))}blockAudio(e){var t;const r=e.start,n=r+e.duration*.05;if(((t=this.fragmentTracker.getAppendedFrag(r,Je.MAIN))==null?void 0:t.gap)===!0)return;const s={label:"block-audio",execute:()=>{var a;const c=this.tracks.video;(this.lastVideoAppendEnd>n||c!=null&&c.buffer&&xt.isBuffered(c.buffer,n)||((a=this.fragmentTracker.getAppendedFrag(n,Je.MAIN))==null?void 0:a.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:a=>{this.warn("Error executing block-audio operation",a)}};this.blockedAudioAppend={op:s,frag:e},this.append(s,"audio",!0)}unblockAudio(){const{blockedAudioAppend:e,operationQueue:t}=this;e&&t&&(this.blockedAudioAppend=null,t.unblockAudio(e.op))}onBufferAppending(e,t){const{tracks:r}=this,{data:n,type:s,parent:a,frag:c,part:d,chunkMeta:u,offset:f}=t,h=u.buffering[s],{sn:m,cc:g}=c,p=self.performance.now();h.start=p;const y=c.stats.buffering,S=d?d.stats.buffering:null;y.start===0&&(y.start=p),S&&S.start===0&&(S.start=p);const E=r.audio;let T=!1;s==="audio"&&E?.container==="audio/mpeg"&&(T=!this.lastMpegAudioChunk||u.id===1||this.lastMpegAudioChunk.sn!==u.sn,this.lastMpegAudioChunk=u);const j=r.video,N=j?.buffer;if(N&&m!=="initSegment"){const z=d||c,K=this.blockedAudioAppend;if(s==="audio"&&a!=="main"&&!this.blockedAudioAppend&&!(j.ending||j.ended)){const G=z.start+z.duration*.05,X=N.buffered,te=this.currentOp("video");!X.length&&!te?this.blockAudio(z):!te&&!xt.isBuffered(N,G)&&this.lastVideoAppendEnd<G&&this.blockAudio(z)}else if(s==="video"){const G=z.end;if(K){const X=K.frag.start;(G>X||G<this.lastVideoAppendEnd||xt.isBuffered(N,X))&&this.unblockAudio()}this.lastVideoAppendEnd=G}}const O=(d||c).start,U={label:`append-${s}`,execute:()=>{var z;h.executeStart=self.performance.now();const K=(z=this.tracks[s])==null?void 0:z.buffer;K&&(T?this.updateTimestampOffset(K,O,.1,s,m,g):f!==void 0&&Ye(f)&&this.updateTimestampOffset(K,f,1e-6,s,m,g)),this.appendExecutor(n,s)},onStart:()=>{},onComplete:()=>{const z=self.performance.now();h.executeEnd=h.end=z,y.first===0&&(y.first=z),S&&S.first===0&&(S.first=z);const K={};this.sourceBuffers.forEach(([G,X])=>{G&&(K[G]=xt.getBuffered(X))}),this.appendErrors[s]=0,s==="audio"||s==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger($.BUFFER_APPENDED,{type:s,frag:c,part:d,chunkMeta:u,parent:c.type,timeRanges:K})},onError:z=>{var K;const G={type:it.MEDIA_ERROR,parent:c.type,details:fe.BUFFER_APPEND_ERROR,sourceBufferName:s,frag:c,part:d,chunkMeta:u,error:z,err:z,fatal:!1},X=(K=this.media)==null?void 0:K.error;if(z.code===DOMException.QUOTA_EXCEEDED_ERR||z.name=="QuotaExceededError"||"quota"in z)G.details=fe.BUFFER_FULL_ERROR;else if(z.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!X)G.errorAction=ws(!0);else if(z.name===X1&&this.sourceBufferCount===0)G.errorAction=ws(!0);else{const te=++this.appendErrors[s];this.warn(`Failed ${te}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${s}" sourceBuffer (${X||"no media error"})`),(te>=this.hls.config.appendErrorMaxRetry||X)&&(G.fatal=!0)}this.hls.trigger($.ERROR,G)}};this.log(`queuing "${s}" append sn: ${m}${d?" p: "+d.index:""} of ${c.type===Je.MAIN?"level":"track"} ${c.level} cc: ${g}`),this.append(U,s,this.isPending(this.tracks[s]))}getFlushOp(e,t,r){return this.log(`queuing "${e}" remove ${t}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(e,t,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger($.BUFFER_FLUSHED,{type:e})},onError:n=>{this.warn(`Failed to remove ${t}-${r} from "${e}" SourceBuffer`,n)}}}onBufferFlushing(e,t){const{type:r,startOffset:n,endOffset:s}=t;r?this.append(this.getFlushOp(r,n,s),r):this.sourceBuffers.forEach(([a])=>{a&&this.append(this.getFlushOp(a,n,s),a)})}onFragParsed(e,t){const{frag:r,part:n}=t,s=[],a=n?n.elementaryStreams:r.elementaryStreams;a[Bt.AUDIOVIDEO]?s.push("audiovideo"):(a[Bt.AUDIO]&&s.push("audio"),a[Bt.VIDEO]&&s.push("video"));const c=()=>{const d=self.performance.now();r.stats.buffering.end=d,n&&(n.stats.buffering.end=d);const u=n?n.stats:r.stats;this.hls.trigger($.FRAG_BUFFERED,{frag:r,part:n,stats:u,id:r.type})};s.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(c,s).catch(d=>{this.warn(`Fragment buffered callback ${d}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(e,t){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([e])=>{if(e){const t=this.tracks[e];if(t)return!t.ended||t.ending}return!1})}onBufferEos(e,t){var r;this.sourceBuffers.forEach(([s])=>{if(s){const a=this.tracks[s];(!t.type||t.type===s)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${s} buffer reached EOS`)))}});const n=((r=this.overrides)==null?void 0:r.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([s])=>{var a;return s&&!((a=this.tracks[s])!=null&&a.ended)})?n?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:s}=this;if(!s||s.readyState!=="open"){s&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${s.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),s.endOfStream(),this.hls.trigger($.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger($.BUFFERED_TO_END,void 0)):t.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([e])=>{if(e!==null){const t=this.tracks[e];t&&(t.ending=!1)}})}onLevelUpdated(e,{details:t}){t.fragments.length&&(this.details=t,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const e=this.getDurationAndRange();e&&this.updateMediaSource(e)})}onError(e,t){if(t.details===fe.BUFFER_APPEND_ERROR&&t.frag){var r;const n=(r=t.errorAction)==null?void 0:r.nextAutoLevel;Ye(n)&&n!==t.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:e,details:t,media:r}=this;if(!r||t===null||!this.sourceBufferCount)return;const n=e.config,s=r.currentTime,a=t.levelTargetDuration,c=t.live&&n.liveBackBufferLength!==null?n.liveBackBufferLength:n.backBufferLength;if(Ye(c)&&c>=0){const u=Math.max(c,a),f=Math.floor(s/a)*a-u;this.flushBackBuffer(s,a,f)}const d=n.frontBufferFlushThreshold;if(Ye(d)&&d>0){const u=Math.max(n.maxBufferLength,d),f=Math.max(u,a),h=Math.floor(s/a)*a+f;this.flushFrontBuffer(s,a,h)}}flushBackBuffer(e,t,r){this.sourceBuffers.forEach(([n,s])=>{if(s){const c=xt.getBuffered(s);if(c.length>0&&r>c.start(0)){var a;this.hls.trigger($.BACK_BUFFER_REACHED,{bufferEnd:r});const d=this.tracks[n];if((a=this.details)!=null&&a.live)this.hls.trigger($.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(d!=null&&d.ended){this.log(`Cannot flush ${n} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger($.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:n})}}})}flushFrontBuffer(e,t,r){this.sourceBuffers.forEach(([n,s])=>{if(s){const a=xt.getBuffered(s),c=a.length;if(c<2)return;const d=a.start(c-1),u=a.end(c-1);if(r>d||e>=d&&e<=u)return;this.hls.trigger($.BUFFER_FLUSHING,{startOffset:d,endOffset:1/0,type:n})}})}getDurationAndRange(){var e;const{details:t,mediaSource:r}=this;if(!t||!this.media||r?.readyState!=="open")return null;const n=t.edge;if(t.live&&this.hls.config.liveDurationInfinity){if(t.fragments.length&&r.setLiveSeekableRange){const c=Math.max(0,t.fragmentStart);return{duration:1/0,start:c,end:Math.max(c,n)}}return{duration:1/0}}const s=(e=this.overrides)==null?void 0:e.duration;if(s)return Ye(s)?{duration:s}:null;const a=this.media.duration;return n>(Ye(r.duration)?r.duration:0)&&n>a||!Ye(a)?{duration:n}:null}updateMediaSource({duration:e,start:t,end:r}){const n=this.mediaSource;!this.media||!n||n.readyState!=="open"||(n.duration!==e&&(Ye(e)&&this.log(`Updating MediaSource duration to ${e.toFixed(3)}`),n.duration=e),t!==void 0&&r!==void 0&&(this.log(`MediaSource duration is set to ${n.duration}. Setting seekable range to ${t}-${r}.`),n.setLiveSeekableRange(t,r)))}get tracksReady(){const e=this.pendingTrackCount;return e>0&&(e>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:e,pendingTrackCount:t,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${t} codec events expected: ${e}) ${zt(r)}`),this.tracksReady){var n;const s=(n=this.transferData)==null?void 0:n.tracks;s&&Object.keys(s).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const e={};this.sourceBuffers.forEach(([t,r])=>{if(t){const n=this.tracks[t];e[t]={buffer:r,container:n.container,codec:n.codec,supplemental:n.supplemental,levelCodec:n.levelCodec,id:n.id,metadata:n.metadata}}}),this.hls.trigger($.BUFFER_CREATED,{tracks:e}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([t])=>{this.executeNext(t)})}else{const e=new Error("could not create source buffer for media codec(s)");this.hls.trigger($.ERROR,{type:it.MEDIA_ERROR,details:fe.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:e,reason:e.message})}}createSourceBuffers(){const{tracks:e,sourceBuffers:t,mediaSource:r}=this;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(const s in e){const a=s,c=e[a];if(this.isPending(c)){const d=this.getTrackCodec(c,a),u=`${c.container};codecs=${d}`;c.codec=d,this.log(`creating sourceBuffer(${u})${this.currentOp(a)?" Queued":""} ${zt(c)}`);try{const f=r.addSourceBuffer(u),h=Rm(a);t[h]=[a,f],c.buffer=f}catch(f){var n;this.error(`error while trying to add sourceBuffer: ${f.message}`),this.shiftAndExecuteNext(a),(n=this.operationQueue)==null||n.removeBlockers(),delete this.tracks[a],this.hls.trigger($.ERROR,{type:it.MEDIA_ERROR,details:fe.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:f,sourceBufferName:a,mimeType:u,parent:c.id});return}this.trackSourceBuffer(a,c)}}this.bufferCreated()}getTrackCodec(e,t){const r=e.supplemental;let n=e.codec;r&&(t==="video"||t==="audiovideo")&&ko(r,"video")&&(n=LG(n,r));const s=uc(n,e.levelCodec);return s?t.slice(0,5)==="audio"?cc(s,this.appendSource):s:""}trackSourceBuffer(e,t){const r=t.buffer;if(!r)return;const n=this.getTrackCodec(t,e);this.tracks[e]={buffer:r,codec:n,container:t.container,levelCodec:t.levelCodec,supplemental:t.supplemental,metadata:t.metadata,id:t.id,listeners:[]},this.removeBufferListeners(e),this.addBufferListener(e,"updatestart",this.onSBUpdateStart),this.addBufferListener(e,"updateend",this.onSBUpdateEnd),this.addBufferListener(e,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(e,"bufferedchange",(s,a)=>{const c=a.removedRanges;c!=null&&c.length&&this.hls.trigger($.BUFFER_FLUSHED,{type:s})})}get mediaSrc(){var e,t;const r=((e=this.media)==null||(t=e.querySelector)==null?void 0:t.call(e,"source"))||this.media;return r?.src}onSBUpdateStart(e){const t=this.currentOp(e);t&&t.onStart()}onSBUpdateEnd(e){var t;if(((t=this.mediaSource)==null?void 0:t.readyState)==="closed"){this.resetBuffer(e);return}const r=this.currentOp(e);r&&(r.onComplete(),this.shiftAndExecuteNext(e))}onSBUpdateError(e,t){var r;const n=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(r=this.mediaSource)==null?void 0:r.readyState}`);this.error(`${n}`,t),this.hls.trigger($.ERROR,{type:it.MEDIA_ERROR,details:fe.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:n,fatal:!1});const s=this.currentOp(e);s&&s.onError(n)}updateTimestampOffset(e,t,r,n,s,a){const c=t-e.timestampOffset;Math.abs(c)>=r&&(this.log(`Updating ${n} SourceBuffer timestampOffset to ${t} (sn: ${s} cc: ${a})`),e.timestampOffset=t)}removeExecutor(e,t,r){const{media:n,mediaSource:s}=this,a=this.tracks[e],c=a?.buffer;if(!n||!s||!c){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(e);return}const d=Ye(n.duration)?n.duration:1/0,u=Ye(s.duration)?s.duration:1/0,f=Math.max(0,t),h=Math.min(r,d,u);h>f&&(!a.ending||a.ended)?(a.ended=!1,this.log(`Removing [${f},${h}] from the ${e} SourceBuffer`),c.remove(f,h)):this.shiftAndExecuteNext(e)}appendExecutor(e,t){const r=this.tracks[t],n=r?.buffer;if(!n)throw new H9(`Attempting to append to the ${t} SourceBuffer, but it does not exist`);r.ending=!1,r.ended=!1,n.appendBuffer(e)}blockUntilOpen(e){if(this.isUpdating()||this.isQueued())this.blockBuffers(e).catch(t=>{this.warn(`SourceBuffer blocked callback ${t}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{e()}catch(t){this.warn(`Callback run without blocking ${this.operationQueue} ${t}`)}}isUpdating(){return this.sourceBuffers.some(([e,t])=>e&&t.updating)}isQueued(){return this.sourceBuffers.some(([e])=>e&&!!this.currentOp(e))}isPending(e){return!!e&&!e.buffer}blockBuffers(e,t=this.sourceBufferTypes){if(!t.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);const{operationQueue:r}=this,n=t.map(s=>this.appendBlocker(s));return t.length>1&&this.blockedAudioAppend&&this.unblockAudio(),Promise.all(n).then(s=>{r===this.operationQueue&&(e(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(e){e.forEach(t=>{var r;const n=(r=this.tracks[t])==null?void 0:r.buffer;!n||n.updating||this.shiftAndExecuteNext(t)})}append(e,t,r){this.operationQueue&&this.operationQueue.append(e,t,r)}appendBlocker(e){if(this.operationQueue)return this.operationQueue.appendBlocker(e)}currentOp(e){return this.operationQueue?this.operationQueue.current(e):null}executeNext(e){e&&this.operationQueue&&this.operationQueue.executeNext(e)}shiftAndExecuteNext(e){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(e)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((e,t)=>e+(this.isPending(this.tracks[t])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((e,[t])=>e+(t?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([e])=>e).filter(e=>!!e)}addBufferListener(e,t,r){const n=this.tracks[e];if(!n)return;const s=n.buffer;if(!s)return;const a=r.bind(this,e);n.listeners.push({event:t,listener:a}),s.addEventListener(t,a)}removeBufferListeners(e){const t=this.tracks[e];if(!t)return;const r=t.buffer;r&&(t.listeners.forEach(n=>{r.removeEventListener(n.event,n.listener)}),t.listeners.length=0)}};function J1(e){const t=e.querySelectorAll("source");[].slice.call(t).forEach(r=>{e.removeChild(r)})}function W9(e,t){const r=self.document.createElement("source");r.type="video/mp4",r.src=t,e.appendChild(r)}function Rm(e){return e==="audio"?1:0}var q9=class Zw{constructor(t){this.hls=void 0,this.autoLevelCapping=void 0,this.firstLevel=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.firstLevel=-1,this.media=null,this.restrictedLevels=[],this.timer=void 0,this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),this.timer&&this.stopCapping(),this.media=null,this.clientRect=null,this.hls=this.streamController=null}registerListeners(){const{hls:t}=this;t.on($.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on($.MANIFEST_PARSED,this.onManifestParsed,this),t.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on($.BUFFER_CODECS,this.onBufferCodecs,this),t.on($.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off($.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off($.MANIFEST_PARSED,this.onManifestParsed,this),t.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off($.BUFFER_CODECS,this.onBufferCodecs,this),t.off($.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,r){const n=this.hls.levels[r.droppedLevel];this.isLevelAllowed(n)&&this.restrictedLevels.push({bitrate:n.bitrate,height:n.height,width:n.width})}onMediaAttaching(t,r){this.media=r.media instanceof HTMLVideoElement?r.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,r){const n=this.hls;this.restrictedLevels=[],this.firstLevel=r.firstLevel,n.config.capLevelToPlayerSize&&r.video&&this.startCapping()}onLevelsUpdated(t,r){this.timer&&Ye(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,r){this.hls.config.capLevelToPlayerSize&&r.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const t=this.hls.levels;if(t.length){const r=this.hls,n=this.getMaxLevel(t.length-1);n!==this.autoLevelCapping&&r.logger.log(`Setting autoLevelCapping to ${n}: ${t[n].height}p@${t[n].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),r.autoLevelCapping=n,r.autoLevelEnabled&&r.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=r.autoLevelCapping}}}getMaxLevel(t){const r=this.hls.levels;if(!r.length)return-1;const n=r.filter((s,a)=>this.isLevelAllowed(s)&&a<=t);return this.clientRect=null,Zw.getMaxLevelByMediaSize(n,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,r={width:0,height:0};if(t){const n=t.getBoundingClientRect();r.width=n.width,r.height=n.height,!r.width&&!r.height&&(r.width=n.right-n.left||t.width||0,r.height=n.bottom-n.top||t.height||0)}return this.clientRect=r,r}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch{}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(r=>t.bitrate===r.bitrate&&t.width===r.width&&t.height===r.height)}static getMaxLevelByMediaSize(t,r,n){if(!(t!=null&&t.length))return-1;const s=(d,u)=>u?d.width!==u.width||d.height!==u.height:!0;let a=t.length-1;const c=Math.max(r,n);for(let d=0;d<t.length;d+=1){const u=t[d];if((u.width>=c||u.height>=c)&&s(u,t[d+1])){a=d;break}}return a}},Rr={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},Q9={HLS:"h"},Ui=class xg{constructor(t,r){Array.isArray(t)&&(t=t.map(n=>n instanceof xg?n:new xg(n))),this.value=t,this.params=r}},Y9="Dict";function X9(e){return Array.isArray(e)?JSON.stringify(e):e instanceof Map?"Map{}":e instanceof Set?"Set{}":typeof e=="object"?JSON.stringify(e):String(e)}function J9(e,t,r,n){return new Error(`failed to ${e} "${X9(t)}" as ${r}`,{cause:n})}function jn(e,t,r){return J9("serialize",e,t,r)}var e_=class{constructor(e){this.description=e}},t_="Bare Item",eZ="Boolean";function tZ(e){if(typeof e!="boolean")throw jn(e,eZ);return e?"?1":"?0"}function rZ(e){return btoa(String.fromCharCode(...e))}var nZ="Byte Sequence";function iZ(e){if(ArrayBuffer.isView(e)===!1)throw jn(e,nZ);return`:${rZ(e)}:`}var sZ="Integer";function aZ(e){return e<-999999999999999||999999999999999<e}function r_(e){if(aZ(e))throw jn(e,sZ);return e.toString()}function oZ(e){return`@${r_(e.getTime()/1e3)}`}function n_(e,t){if(e<0)return-n_(-e,t);const r=Math.pow(10,t);if(Math.abs(e*r%1-.5)<Number.EPSILON){const n=Math.floor(e*r);return(n%2===0?n:n+1)/r}else return Math.round(e*r)/r}var lZ="Decimal";function cZ(e){const t=n_(e,3);if(Math.floor(Math.abs(t)).toString().length>12)throw jn(e,lZ);const r=t.toString();return r.includes(".")?r:`${r}.0`}var uZ="String",dZ=/[\x00-\x1f\x7f]+/;function fZ(e){if(dZ.test(e))throw jn(e,uZ);return`"${e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function hZ(e){return e.description||e.toString().slice(7,-1)}var mZ="Token";function i_(e){const t=hZ(e);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw jn(t,mZ);return t}function Lm(e){switch(typeof e){case"number":if(!Ye(e))throw jn(e,t_);return Number.isInteger(e)?r_(e):cZ(e);case"string":return fZ(e);case"symbol":return i_(e);case"boolean":return tZ(e);case"object":if(e instanceof Date)return oZ(e);if(e instanceof Uint8Array)return iZ(e);if(e instanceof e_)return i_(e);default:throw jn(e,t_)}}var gZ="Key";function Om(e){if(/^[a-z*][a-z0-9\-_.*]*$/.test(e)===!1)throw jn(e,gZ);return e}function Fm(e){return e==null?"":Object.entries(e).map(([t,r])=>r===!0?`;${Om(t)}`:`;${Om(t)}=${Lm(r)}`).join("")}function s_(e){return e instanceof Ui?`${Lm(e.value)}${Fm(e.params)}`:Lm(e)}function pZ(e){return`(${e.value.map(s_).join(" ")})${Fm(e.params)}`}function vZ(e,t={whitespace:!0}){if(typeof e!="object"||e==null)throw jn(e,Y9);const r=e instanceof Map?e.entries():Object.entries(e),n=t?.whitespace?" ":"";return Array.from(r).map(([s,a])=>{a instanceof Ui||(a=new Ui(a));let c=Om(s);return a.value===!0?c+=Fm(a.params):(c+="=",Array.isArray(a.value)?c+=pZ(a):c+=s_(a)),c}).join(`,${n}`)}function a_(e,t){return vZ(e,t)}var Nn="CMCD-Object",tr="CMCD-Request",Bi="CMCD-Session",mi="CMCD-Status",bZ={br:Nn,ab:Nn,d:Nn,ot:Nn,tb:Nn,tpb:Nn,lb:Nn,tab:Nn,lab:Nn,url:Nn,pb:tr,bl:tr,tbl:tr,dl:tr,ltc:tr,mtp:tr,nor:tr,nrr:tr,rc:tr,sn:tr,sta:tr,su:tr,ttfb:tr,ttfbb:tr,ttlb:tr,cmsdd:tr,cmsds:tr,smrt:tr,df:tr,cs:tr,ts:tr,cid:Bi,pr:Bi,sf:Bi,sid:Bi,st:Bi,v:Bi,msd:Bi,bs:mi,bsd:mi,cdn:mi,rtp:mi,bg:mi,pt:mi,ec:mi,e:mi},yZ={REQUEST:tr};function xZ(e){return Object.keys(e).reduce((t,r)=>{var n;return(n=e[r])===null||n===void 0||n.forEach(s=>t[s]=r),t},{})}function SZ(e,t){const r={};if(!e)return r;const n=Object.keys(e),s=t?xZ(t):{};return n.reduce((a,c)=>{var d;const u=bZ[c]||s[c]||yZ.REQUEST,f=(d=a[u])!==null&&d!==void 0?d:a[u]={};return f[c]=e[c],a},r)}function _Z(e){return["ot","sf","st","e","sta"].includes(e)}function wZ(e){return typeof e=="number"?Ye(e):e!=null&&e!==""&&e!==!1}var o_="event";function EZ(e,t){const r=new URL(e),n=new URL(t);if(r.origin!==n.origin)return e;const s=r.pathname.split("/").slice(1),a=n.pathname.split("/").slice(1,-1);for(;s[0]===a[0];)s.shift(),a.shift();for(;a.length;)a.shift(),s.unshift("..");return s.join("/")+r.search+r.hash}var Ac=e=>Math.round(e),Um=(e,t)=>Array.isArray(e)?e.map(r=>Um(r,t)):e instanceof Ui&&typeof e.value=="string"?new Ui(Um(e.value,t),e.params):(t.baseUrl&&(e=EZ(e,t.baseUrl)),t.version===1?encodeURIComponent(e):e),jc=e=>Ac(e/100)*100,kZ=(e,t)=>{let r=e;return t.version>=2&&(e instanceof Ui&&typeof e.value=="string"?r=new Ui([e]):typeof e=="string"&&(r=[e])),Um(r,t)},TZ={br:Ac,d:Ac,bl:jc,dl:jc,mtp:jc,nor:kZ,rtp:jc,tb:Ac},l_="request",c_="response",Bm=["ab","bg","bl","br","bs","bsd","cdn","cid","cs","df","ec","lab","lb","ltc","msd","mtp","pb","pr","pt","sf","sid","sn","st","sta","tab","tb","tbl","tpb","ts","v"],CZ=["e"],IZ=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function Nc(e){return IZ.test(e)}function PZ(e){return Bm.includes(e)||CZ.includes(e)||Nc(e)}var u_=["d","dl","nor","ot","rtp","su"];function AZ(e){return Bm.includes(e)||u_.includes(e)||Nc(e)}var jZ=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function NZ(e){return Bm.includes(e)||u_.includes(e)||jZ.includes(e)||Nc(e)}var DZ=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function MZ(e){return DZ.includes(e)||Nc(e)}var $Z={[c_]:NZ,[o_]:PZ,[l_]:AZ};function d_(e,t={}){const r={};if(e==null||typeof e!="object")return r;const n=t.version||e.v||1,s=t.reportingMode||l_,a=n===1?MZ:$Z[s];let c=Object.keys(e).filter(a);const d=t.filter;typeof d=="function"&&(c=c.filter(d));const u=s===c_||s===o_;u&&!c.includes("ts")&&c.push("ts"),n>1&&!c.includes("v")&&c.push("v");const f=Ft({},TZ,t.formatters),h={version:n,reportingMode:s,baseUrl:t.baseUrl};return c.sort().forEach(m=>{let g=e[m];const p=f[m];if(typeof p=="function"&&(g=p(g,h)),m==="v"){if(n===1)return;g=n}m=="pr"&&g===1||(u&&m==="ts"&&!Ye(g)&&(g=Date.now()),wZ(g)&&(_Z(m)&&typeof g=="string"&&(g=new e_(g)),r[m]=g))}),r}function RZ(e,t={}){const r={};if(!e)return r;const n=SZ(d_(e,t),t?.customHeaderMap);return Object.entries(n).reduce((s,[a,c])=>{const d=a_(c,{whitespace:!1});return d&&(s[a]=d),s},r)}function LZ(e,t,r){return Ft(e,RZ(t,r))}var OZ="CMCD";function FZ(e,t={}){return e?a_(d_(e,t),{whitespace:!1}):""}function UZ(e,t={}){if(!e)return"";const r=FZ(e,t);return encodeURIComponent(r)}function BZ(e,t={}){return e?`${OZ}=${UZ(e,t)}`:""}var f_=/CMCD=[^&#]+/;function zZ(e,t,r){const n=BZ(t,r);return n?f_.test(e)?e.replace(f_,n):`${e}${e.includes("?")?"&":"?"}${n}`:e}var GZ=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=void 0,this.sid=void 0,this.cid=void 0,this.useHeaders=!1,this.includeKeys=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.audioBuffer=void 0,this.videoBuffer=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0),this.buffering=!0},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1},this.applyPlaylistData=n=>{try{this.apply(n,{ot:Rr.MANIFEST,su:!this.initialized})}catch(s){this.hls.logger.warn("Could not generate manifest CMCD data.",s)}},this.applyFragmentData=n=>{try{const{frag:s,part:a}=n,c=this.hls.levels[s.level],d=this.getObjectType(s),u={d:(a||s).duration*1e3,ot:d};(d===Rr.VIDEO||d===Rr.AUDIO||d==Rr.MUXED)&&(u.br=c.bitrate/1e3,u.tb=this.getTopBandwidth(d)/1e3,u.bl=this.getBufferLength(d));const f=a?this.getNextPart(a):this.getNextFrag(s);f!=null&&f.url&&f.url!==s.url&&(u.nor=f.url),this.apply(n,u)}catch(s){this.hls.logger.warn("Could not generate segment CMCD data.",s)}},this.hls=e;const t=this.config=e.config,{cmcd:r}=t;r!=null&&(t.pLoader=this.createPlaylistLoader(),t.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||e.sessionId,this.cid=r.contentId,this.useHeaders=r.useHeaders===!0,this.includeKeys=r.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHED,this.onMediaDetached,this),e.on($.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHED,this.onMediaDetached,this),e.off($.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(e,t){var r,n;this.audioBuffer=(r=t.tracks.audio)==null?void 0:r.buffer,this.videoBuffer=(n=t.tracks.video)==null?void 0:n.buffer}createData(){var e;return{v:1,sf:Q9.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,t={}){Ft(t,this.createData());const r=t.ot===Rr.INIT||t.ot===Rr.VIDEO||t.ot===Rr.MUXED;this.starved&&r&&(t.bs=!0,t.su=!0,this.starved=!1),t.su==null&&(t.su=this.buffering);const{includeKeys:n}=this;n&&(t=Object.keys(t).reduce((a,c)=>(n.includes(c)&&(a[c]=t[c]),a),{}));const s={baseUrl:e.url};this.useHeaders?(e.headers||(e.headers={}),LZ(e.headers,t,s)):e.url=zZ(e.url,t,s)}getNextFrag(e){var t;const r=(t=this.hls.levels[e.level])==null?void 0:t.details;if(r){const n=e.sn-r.startSN;return r.fragments[n+1]}}getNextPart(e){var t;const{index:r,fragment:n}=e,s=(t=this.hls.levels[n.level])==null||(t=t.details)==null?void 0:t.partList;if(s){const{sn:a}=n;for(let c=s.length-1;c>=0;c--){const d=s[c];if(d.index===r&&d.fragment.sn===a)return s[c+1]}}}getObjectType(e){const{type:t}=e;if(t==="subtitle")return Rr.TIMED_TEXT;if(e.sn==="initSegment")return Rr.INIT;if(t==="audio")return Rr.AUDIO;if(t==="main")return this.hls.audioTracks.length?Rr.VIDEO:Rr.MUXED}getTopBandwidth(e){let t=0,r;const n=this.hls;if(e===Rr.AUDIO)r=n.audioTracks;else{const s=n.maxAutoLevel,a=s>-1?s+1:n.levels.length;r=n.levels.slice(0,a)}return r.forEach(s=>{s.bitrate>t&&(t=s.bitrate)}),t>0?t:NaN}getBufferLength(e){const t=this.media,r=e===Rr.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!t?NaN:xt.bufferInfo(r,t.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,t=this.applyPlaylistData,r=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new r(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,a,c){t(s),this.loader.load(s,a,c)}}}createFragmentLoader(){const{fLoader:e}=this.config,t=this.applyFragmentData,r=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new r(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,a,c){t(s),this.loader.load(s,a,c)}}}},ZZ=3e5,VZ=class extends rn{constructor(e){super("content-steering",e.logger),this.hls=void 0,this.loader=null,this.uri=null,this.pathwayId=".",this._pathwayPriority=null,this.timeToLoad=300,this.reloadTimer=-1,this.updated=0,this.started=!1,this.enabled=!0,this.levels=null,this.audioTracks=null,this.subtitleTracks=null,this.penalizedPathways={},this.hls=e,this.registerListeners()}registerListeners(){const e=this.hls;e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_LOADED,this.onManifestLoaded,this),e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_LOADED,this.onManifestLoaded,this),e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((e,t)=>(e.indexOf(t.pathwayId)===-1&&e.push(t.pathwayId),e),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(e){this.updatePathwayPriority(e)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const e=this.timeToLoad*1e3-(performance.now()-this.updated);if(e>0){this.scheduleRefresh(this.uri,e);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(e){const t=this.levels;t&&(this.levels=t.filter(r=>r!==e))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(e,t){const{contentSteering:r}=t;r!==null&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(e,t){this.audioTracks=t.audioTracks,this.subtitleTracks=t.subtitleTracks}onError(e,t){const{errorAction:r}=t;if(r?.action===Sr.SendAlternateToPenaltyBox&&r.flags===Zr.MoveAllAlternatesMatchingHost){const n=this.levels;let s=this._pathwayPriority,a=this.pathwayId;if(t.context){const{groupId:c,pathwayId:d,type:u}=t.context;c&&n?a=this.getPathwayForGroupId(c,u,a):d&&(a=d)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!s&&n&&(s=this.pathways()),s&&s.length>1&&(this.updatePathwayPriority(s),r.resolved=this.pathwayId!==a),t.details===fe.BUFFER_APPEND_ERROR&&!t.fatal?r.resolved=!0:r.resolved||this.warn(`Could not resolve ${t.details} ("${t.error.message}") with content-steering for Pathway: ${a} levels: ${n&&n.length} priorities: ${zt(s)} penalized: ${zt(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let t=this.getLevelsForPathway(this.pathwayId);if(t.length===0){const r=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),t=this.getLevelsForPathway(r),this.pathwayId=r}return t.length!==e.length&&this.log(`Found ${t.length}/${e.length} levels in Pathway "${this.pathwayId}"`),t}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(t=>e===t.pathwayId)}updatePathwayPriority(e){this._pathwayPriority=e;let t;const r=this.penalizedPathways,n=performance.now();Object.keys(r).forEach(s=>{n-r[s]>ZZ&&delete r[s]});for(let s=0;s<e.length;s++){const a=e[s];if(a in r)continue;if(a===this.pathwayId)return;const c=this.hls.nextLoadLevel,d=this.hls.levels[c];if(t=this.getLevelsForPathway(a),t.length>0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,p1(t),this.hls.trigger($.LEVELS_UPDATED,{levels:t});const u=this.hls.levels[c];d&&u&&this.levels&&(u.attrs["STABLE-VARIANT-ID"]!==d.attrs["STABLE-VARIANT-ID"]&&u.bitrate!==d.bitrate&&this.log(`Unstable Pathways change from bitrate ${d.bitrate} to ${u.bitrate}`),this.hls.nextLoadLevel=c);break}}}getPathwayForGroupId(e,t,r){const n=this.getLevelsForPathway(r).concat(this.levels||[]);for(let s=0;s<n.length;s++)if(t===Et.AUDIO_TRACK&&n[s].hasAudioGroup(e)||t===Et.SUBTITLE_TRACK&&n[s].hasSubtitleGroup(e))return n[s].pathwayId;return r}clonePathways(e){const t=this.levels;if(!t)return;const r={},n={};e.forEach(s=>{const{ID:a,"BASE-ID":c,"URI-REPLACEMENT":d}=s;if(t.some(f=>f.pathwayId===a))return;const u=this.getLevelsForPathway(c).map(f=>{const h=new or(f.attrs);h["PATHWAY-ID"]=a;const m=h.AUDIO&&`${h.AUDIO}_clone_${a}`,g=h.SUBTITLES&&`${h.SUBTITLES}_clone_${a}`;m&&(r[h.AUDIO]=m,h.AUDIO=m),g&&(n[h.SUBTITLES]=g,h.SUBTITLES=g);const p=m_(f.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",d),y=new Co({attrs:h,audioCodec:f.audioCodec,bitrate:f.bitrate,height:f.height,name:f.name,url:p,videoCodec:f.videoCodec,width:f.width});if(f.audioGroups)for(let S=1;S<f.audioGroups.length;S++)y.addGroupId("audio",`${f.audioGroups[S]}_clone_${a}`);if(f.subtitleGroups)for(let S=1;S<f.subtitleGroups.length;S++)y.addGroupId("text",`${f.subtitleGroups[S]}_clone_${a}`);return y});t.push(...u),h_(this.audioTracks,r,d,a),h_(this.subtitleTracks,n,d,a)})}loadSteeringManifest(e){const t=this.hls.config,r=t.loader;this.loader&&this.loader.destroy(),this.loader=new r(t);let n;try{n=new self.URL(e)}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest URI: ${e}`);return}if(n.protocol!=="data:"){const f=(this.hls.bandwidthEstimate||t.abrEwmaDefaultEstimate)|0;n.searchParams.set("_HLS_pathway",this.pathwayId),n.searchParams.set("_HLS_throughput",""+f)}const s={responseType:"json",url:n.href},a=t.steeringManifestLoadPolicy.default,c=a.errorRetry||a.timeoutRetry||{},d={loadPolicy:a,timeout:a.maxLoadTimeMs,maxRetry:c.maxNumRetry||0,retryDelay:c.retryDelayMs||0,maxRetryDelay:c.maxRetryDelayMs||0},u={onSuccess:(f,h,m,g)=>{this.log(`Loaded steering manifest: "${n}"`);const p=f.data;if(p?.VERSION!==1){this.log(`Steering VERSION ${p.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=p.TTL;const{"RELOAD-URI":y,"PATHWAY-CLONES":S,"PATHWAY-PRIORITY":E}=p;if(y)try{this.uri=new self.URL(y,n).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${y}`);return}this.scheduleRefresh(this.uri||m.url),S&&this.clonePathways(S);const T={steeringManifest:p,url:n.toString()};this.hls.trigger($.STEERING_MANIFEST_LOADED,T),E&&this.updatePathwayPriority(E)},onError:(f,h,m,g)=>{if(this.log(`Error loading steering manifest: ${f.code} ${f.text} (${h.url})`),this.stopLoad(),f.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let p=this.timeToLoad*1e3;if(f.code===429){const y=this.loader;if(typeof y?.getResponseHeader=="function"){const S=y.getResponseHeader("Retry-After");S&&(p=parseFloat(S)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,p)},onTimeout:(f,h,m)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${n}`),this.loader.load(s,d,u)}scheduleRefresh(e,t=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const n=(r=this.hls)==null?void 0:r.media;if(n&&!n.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},t)}};function h_(e,t,r,n){e&&Object.keys(t).forEach(s=>{const a=e.filter(c=>c.groupId===s).map(c=>{const d=Ft({},c);return d.details=void 0,d.attrs=new or(d.attrs),d.url=d.attrs.URI=m_(c.url,c.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),d.groupId=d.attrs["GROUP-ID"]=t[s],d.attrs["PATHWAY-ID"]=n,d});e.push(...a)})}function m_(e,t,r,n){const{HOST:s,PARAMS:a,[r]:c}=n;let d;t&&(d=c?.[t],d&&(e=d));const u=new self.URL(e);return s&&!d&&(u.host=s),a&&Object.keys(a).sort().forEach(f=>{f&&u.searchParams.set(f,a[f])}),u.href}var g_=class Qc extends rn{constructor(t){super("eme",t.logger),this.hls=void 0,this.config=void 0,this.media=null,this.mediaResolved=void 0,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.mediaKeys=null,this.setMediaKeysQueue=Qc.CDMCleanupPromise?[Qc.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=r=>{const{initDataType:n,initData:s}=r,a=`"${r.type}" event: init data type: "${n}"`;if(this.debug(a),s!==null){if(!this.keyFormatPromise){let c=Object.keys(this.keySystemAccessPromises);c.length||(c=Io(this.config));const d=c.map(mm).filter(u=>!!u);this.keyFormatPromise=this.getKeyFormatPromise(d)}this.keyFormatPromise.then(c=>{const d=xc(c);if(n!=="sinf"||d!==Yt.FAIRPLAY){this.log(`Ignoring "${r.type}" event with init data type: "${n}" for selected key-system ${d}`);return}let u;try{const p=gr(new Uint8Array(s)),y=fS(fm(JSON.parse(p).sinf));if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");u=new Uint8Array(y.subarray(8,24))}catch(p){this.warn(`${a} Failed to parse sinf: ${p}`);return}const f=xr(u),{keyIdToKeySessionPromise:h,mediaKeySessions:m}=this;let g=h[f];for(let p=0;p<m.length;p++){const y=m[p],S=y.decryptdata;if(!S.keyId)continue;const E=xr(S.keyId);if(bc(u,S.keyId)||S.uri.replace(/-/g,"").indexOf(f)!==-1){if(g=h[E],!g)continue;if(S.pssh)break;delete h[E],S.pssh=new Uint8Array(s),S.keyId=u,g=h[f]=g.then(()=>this.generateRequestWithPreferredKeySession(y,n,s,"encrypted-event-key-match")),g.catch(T=>this.handleError(T));break}}g||this.handleError(new Error(`Key ID ${f} not encountered in playlist. Key-system sessions ${m.length}.`))}).catch(c=>this.handleError(c))}},this.onWaitingForKey=r=>{this.log(`"${r.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on($.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on($.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on($.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on($.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on($.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off($.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off($.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off($.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off($.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off($.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:r,widevineLicenseUrl:n}=this.config,s=r?.[t];if(s)return s.licenseUrl;if(t===Yt.WIDEVINE&&n)return n}getLicenseServerUrlOrThrow(t){const r=this.getLicenseServerUrl(t);if(r===void 0)throw new Error(`no license server URL configured for key-system "${t}"`);return r}getServerCertificateUrl(t){const{drmSystems:r}=this.config,n=r?.[t];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const r=this.hls.levels,n=(c,d,u)=>!!c&&u.indexOf(c)===d,s=r.map(c=>c.audioCodec).filter(n),a=r.map(c=>c.videoCodec).filter(n);return s.length+a.length===0&&a.push("avc1.42e01e"),new Promise((c,d)=>{const u=f=>{const h=f.shift();this.getMediaKeysPromise(h,s,a).then(m=>c({keySystem:h,mediaKeys:m})).catch(m=>{f.length?u(f):m instanceof Kr?d(m):d(new Kr({type:it.KEY_SYSTEM_ERROR,details:fe.KEY_SYSTEM_NO_ACCESS,error:m,fatal:!0},m.message))})};u(t)})}requestMediaKeySystemAccess(t,r){const{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!="function"){let s=`Configured requestMediaKeySystemAccess is not a function ${n}`;return QS===null&&self.location.protocol==="http:"&&(s=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(s))}return n(t,r)}getMediaKeysPromise(t,r,n){var s;const a=T8(t,r,n,this.config.drmSystemOptions||{});let c=this.keySystemAccessPromises[t],d=(s=c)==null?void 0:s.keySystemAccess;if(!d){this.log(`Requesting encrypted media "${t}" key-system access with config: ${zt(a)}`),d=this.requestMediaKeySystemAccess(t,a);const u=c=this.keySystemAccessPromises[t]={keySystemAccess:d};return d.catch(f=>{this.log(`Failed to obtain access to key-system "${t}": ${f}`)}),d.then(f=>{this.log(`Access for key-system "${f.keySystem}" obtained`);const h=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const m=u.mediaKeys=f.createMediaKeys().then(g=>(this.log(`Media-keys created for "${t}"`),u.hasMediaKeys=!0,h.then(p=>p?this.setMediaKeysServerCertificate(g,t,p):g)));return m.catch(g=>{this.error(`Failed to create media-keys for "${t}"}: ${g}`)}),m})}return d.then(()=>c.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:r,mediaKeys:n}){this.log(`Creating key-system session "${r}" keyId: ${xr(t.keyId||[])} keyUri: ${t.uri}`);const s={decryptdata:t,keySystem:r,mediaKeys:n,mediaKeysSession:n.createSession(),keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(t){const r=t.decryptdata;if(r.pssh){const n=this.createMediaKeySessionContext(t),s=Dc(r),a="cenc";this.keyIdToKeySessionPromise[s]=this.generateRequestWithPreferredKeySession(n,a,r.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,r){const n=t.mediaKeysSession;return this.log(`Updating key-session "${n.sessionId}" for keyId ${xr(t.decryptdata.keyId||[])}
176
+ } (data length: ${r.byteLength})`),n.update(r)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>mm(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:r,mediaKeys:n})=>this.attemptSetMediaKeys(r,n))}selectKeySystem(t){return new Promise((r,n)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:s})=>{const a=mm(s);a?r(a):n(new Error(`Unable to find format for key-system "${s}"`))}).catch(n)})}selectKeySystemFormat(t){const r=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)),this.keyFormatPromise}getKeyFormatPromise(t){const r=Io(this.config),n=t.map(xc).filter(s=>!!s&&r.indexOf(s)!==-1);return this.selectKeySystem(n)}getKeyStatus(t){const{mediaKeySessions:r}=this;for(let n=0;n<r.length;n++){const s=HZ(t,r[n]);if(s)return s}}loadKey(t){const r=t.keyInfo.decryptdata,n=Dc(r),s=this.bannedKeyIds[n];if(s||this.getKeyStatus(r)==="internal-error"){const d=p_(s||"internal-error",r);return this.handleError(d,t.frag),Promise.reject(d)}const a=`(keyId: ${n} format: "${r.keyFormat}" method: ${r.method} uri: ${r.uri})`;this.log(`Starting session for key ${a}`);const c=this.keyIdToKeySessionPromise[n];if(!c){const d=this.getKeySystemForKeyPromise(r).then(({keySystem:u,mediaKeys:f})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${a}`),this.attemptSetMediaKeys(u,f).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:u,mediaKeys:f,decryptdata:r}))))).then(u=>{const f="cenc",h=r.pssh?r.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(u,f,h,"playlist-key")});return d.catch(u=>this.handleError(u,t.frag)),this.keyIdToKeySessionPromise[n]=d,d}return c.catch(d=>{if(d instanceof Kr){const u=Mt({},d.data);this.getKeyStatus(r)==="internal-error"&&(u.decryptdata=r);const f=new Kr(u,d.message);this.handleError(f,t.frag)}}),c}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,r){if(this.hls)if(t instanceof Kr){r&&(t.data.frag=r);const n=t.data.decryptdata;this.error(`${t.message}${n?` (${xr(n.keyId||[])})`:""}`),this.hls.trigger($.ERROR,t.data)}else this.error(t.message),this.hls.trigger($.ERROR,{type:it.KEY_SYSTEM_ERROR,details:fe.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const r=Dc(t),n=this.keyIdToKeySessionPromise[r];if(!n){const s=xc(t.keyFormat),a=s?[s]:Io(this.config);return this.attemptKeySystemAccess(a)}return n}getKeySystemSelectionPromise(t){if(t.length||(t=Io(this.config)),t.length===0)throw new Kr({type:it.KEY_SYSTEM_ERROR,details:fe.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${zt({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,r){if(this.mediaResolved=void 0,this.mediaKeys===r)return Promise.resolve();const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const s=Promise.all(n).then(()=>this.media?this.media.setMediaKeys(r):new Promise((a,c)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return c(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=r,this.media.setMediaKeys(r).then(a).catch(c)}}));return this.mediaKeys=r,this.setMediaKeysQueue.push(s),s.then(()=>{this.log(`Media-keys set for "${t}"`),n.push(s),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(a=>n.indexOf(a)===-1)})}generateRequestWithPreferredKeySession(t,r,n,s){var a;const c=(a=this.config.drmSystems)==null||(a=a[t.keySystem])==null?void 0:a.generateRequest;if(c)try{const y=c.call(this.hls,r,n,t);if(!y)throw new Error("Invalid response from configured generateRequest filter");r=y.initDataType,n=y.initData?y.initData:null,t.decryptdata.pssh=n?new Uint8Array(n):null}catch(y){if(this.warn(y.message),this.hls&&this.hls.config.debug)throw y}if(n===null)return this.log(`Skipping key-session request for "${s}" (no initData)`),Promise.resolve(t);const d=Dc(t.decryptdata),u=t.decryptdata.uri;this.log(`Generating key-session request for "${s}" keyId: ${d} URI: ${u} (init data type: ${r} length: ${n.byteLength})`);const f=new Sm,h=t._onmessage=y=>{const S=t.mediaKeysSession;if(!S){f.emit("error",new Error("invalid state"));return}const{messageType:E,message:T}=y;this.log(`"${E}" message event for session "${S.sessionId}" message size: ${T.byteLength}`),E==="license-request"||E==="license-renewal"?this.renewLicense(t,T).catch(j=>{f.eventNames().length?f.emit("error",j):this.handleError(j)}):E==="license-release"?t.keySystem===Yt.FAIRPLAY&&this.updateKeySession(t,hm("acknowledged")).then(()=>this.removeSession(t)).catch(j=>this.handleError(j)):this.warn(`unhandled media key message type "${E}"`)},m=(y,S)=>{S.keyStatus=y;let E;y.startsWith("usable")?f.emit("resolved"):y==="internal-error"||y==="output-restricted"||y==="output-downscaled"?E=p_(y,S.decryptdata):y==="expired"?E=new Error(`key expired (keyId: ${d})`):y==="released"?E=new Error("key released"):y==="status-pending"||this.warn(`unhandled key status change "${y}" (keyId: ${d})`),E&&(f.eventNames().length?f.emit("error",E):this.handleError(E))},g=t._onkeystatuseschange=y=>{if(!t.mediaKeysSession){f.emit("error",new Error("invalid state"));return}const S=this.getKeyStatuses(t);if(!Object.keys(S).some(j=>S[j]!=="status-pending"))return;if(S[d]==="expired"){this.log(`Expired key ${zt(S)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let E=S[d];if(E)m(E,t);else{var T;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(T=t.keyStatusTimeouts)[d]||(T[d]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const N=this.getKeyStatus(t.decryptdata);if(N&&N!=="status-pending")return this.log(`No status for keyId ${d} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${N} from other session.`),m(N,t);this.log(`key status for ${d} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),E="internal-error",m(E,t)},1e3)),this.log(`No status for keyId ${d} (${zt(S)}).`)}};Ar(t.mediaKeysSession,"message",h),Ar(t.mediaKeysSession,"keystatuseschange",g);const p=new Promise((y,S)=>{f.on("error",S),f.on("resolved",y)});return t.mediaKeysSession.generateRequest(r,n).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${d} URI: ${u}`)}).catch(y=>{throw new Kr({type:it.KEY_SYSTEM_ERROR,details:fe.KEY_SYSTEM_NO_SESSION,error:y,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${y}`)}).then(()=>p).catch(y=>(f.removeAllListeners(),this.removeSession(t).then(()=>{throw y}))).then(()=>(f.removeAllListeners(),t))}getKeyStatuses(t){const r={};return t.mediaKeysSession.keyStatuses.forEach((n,s)=>{if(typeof s=="string"&&typeof n=="object"){const d=s;s=n,n=d}const a="buffer"in s?new Uint8Array(s.buffer,s.byteOffset,s.byteLength):new Uint8Array(s);if(t.keySystem===Yt.PLAYREADY&&a.length===16){const d=xr(a);r[d]=n,WS(a)}const c=xr(a);n==="internal-error"&&(this.bannedKeyIds[c]=n),this.log(`key status change "${n}" for keyStatuses keyId: ${c} key-session "${t.mediaKeysSession.sessionId}"`),r[c]=n}),r}fetchServerCertificate(t){const r=this.config,n=r.loader,s=new n(r),a=this.getServerCertificateUrl(t);return a?(this.log(`Fetching server certificate for "${t}"`),new Promise((c,d)=>{const u={responseType:"arraybuffer",url:a},f=r.certLoadPolicy.default,h={loadPolicy:f,timeout:f.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};s.load(u,h,{onSuccess:(m,g,p,y)=>{c(m.data)},onError:(m,g,p,y)=>{d(new Kr({type:it.KEY_SYSTEM_ERROR,details:fe.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:Mt({url:u.url,data:void 0},m)},`"${t}" certificate request failed (${a}). Status: ${m.code} (${m.text})`))},onTimeout:(m,g,p)=>{d(new Kr({type:it.KEY_SYSTEM_ERROR,details:fe.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:p,response:{url:u.url,data:void 0}},`"${t}" certificate request timed out (${a})`))},onAbort:(m,g,p)=>{d(new Error("aborted"))}})})):Promise.resolve()}setMediaKeysServerCertificate(t,r,n){return new Promise((s,a)=>{t.setServerCertificate(n).then(c=>{this.log(`setServerCertificate ${c?"success":"not supported by CDM"} (${n.byteLength}) on "${r}"`),s(t)}).catch(c=>{a(new Kr({type:it.KEY_SYSTEM_ERROR,details:fe.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:c,fatal:!0},c.message))})})}renewLicense(t,r){return this.requestLicense(t,new Uint8Array(r)).then(n=>this.updateKeySession(t,new Uint8Array(n)).catch(s=>{throw new Kr({type:it.KEY_SYSTEM_ERROR,details:fe.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:s,fatal:!1},s.message)}))}unpackPlayReadyKeyMessage(t,r){const n=String.fromCharCode.apply(null,new Uint16Array(r.buffer));if(!n.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),r;const s=new DOMParser().parseFromString(n,"application/xml"),a=s.querySelectorAll("HttpHeader");if(a.length>0){let h;for(let m=0,g=a.length;m<g;m++){var c,d;h=a[m];const p=(c=h.querySelector("name"))==null?void 0:c.textContent,y=(d=h.querySelector("value"))==null?void 0:d.textContent;p&&y&&t.setRequestHeader(p,y)}}const u=s.querySelector("Challenge"),f=u?.textContent;if(!f)throw new Error("Cannot find <Challenge> in key message");return hm(atob(f))}setupLicenseXHR(t,r,n,s){const a=this.config.licenseXhrSetup;return a?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return a.call(this.hls,t,r,n,s)}).catch(c=>{if(!n.decryptdata)throw c;return t.open("POST",r,!0),a.call(this.hls,t,r,n,s)}).then(c=>(t.readyState||t.open("POST",r,!0),{xhr:t,licenseChallenge:c||s})):(t.open("POST",r,!0),Promise.resolve({xhr:t,licenseChallenge:s}))}requestLicense(t,r){const n=this.config.keyLoadPolicy.default;return new Promise((s,a)=>{const c=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${c}`);const d=new XMLHttpRequest;d.responseType="arraybuffer",d.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return a(new Error("invalid state"));if(d.readyState===4)if(d.status===200){this._requestLicenseFailureCount=0;let u=d.response;this.log(`License received ${u instanceof ArrayBuffer?u.byteLength:u}`);const f=this.config.licenseResponseCallback;if(f)try{u=f.call(this.hls,d,c,t)}catch(h){this.error(h)}s(u)}else{const u=n.errorRetry,f=u?u.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>f||d.status>=400&&d.status<500)a(new Kr({type:it.KEY_SYSTEM_ERROR,details:fe.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:d,response:{url:c,data:void 0,code:d.status,text:d.statusText}},`License Request XHR failed (${c}). Status: ${d.status} (${d.statusText})`));else{const h=f-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${h} attempts left`),this.requestLicense(t,r).then(s,a)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=d,this.setupLicenseXHR(d,c,t,r).then(({xhr:u,licenseChallenge:f})=>{t.keySystem==Yt.PLAYREADY&&(f=this.unpackPlayReadyKeyMessage(u,f)),u.send(f)}).catch(a)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,r){if(!this.config.emeEnabled)return;const n=r.media;this.media=n,Ar(n,"encrypted",this.onMediaEncrypted),Ar(n,"waitingforkey",this.onWaitingForKey);const s=this.mediaResolved;s?s():this.mediaKeys=n.mediaKeys}onMediaDetached(){const t=this.media;t&&($r(t,"encrypted",this.onMediaEncrypted),$r(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const r=this.mediaResolved;if(r&&r(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const n=this.media,s=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,Sc.clearKeyUriToKeyIdMap();const a=s.length;Qc.CDMCleanupPromise=Promise.all(s.map(c=>this.removeSession(c)).concat((n==null||(t=n.setMediaKeys(null))==null?void 0:t.catch(c=>{this.log(`Could not clear media keys: ${c}`),this.hls&&this.hls.trigger($.ERROR,{type:it.OTHER_ERROR,details:fe.KEY_SYSTEM_DESTROY_MEDIA_KEYS_ERROR,fatal:!1,error:new Error(`Could not clear media keys: ${c}`)})}))||Promise.resolve())).catch(c=>{this.log(`Could not close sessions and clear media keys: ${c}`),this.hls&&this.hls.trigger($.ERROR,{type:it.OTHER_ERROR,details:fe.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${c}`)})}).then(()=>{a&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:r}){if(!(!r||!this.config.emeEnabled)&&!this.keyFormatPromise){const n=r.reduce((s,a)=>(s.indexOf(a.keyFormat)===-1&&s.push(a.keyFormat),s),[]);this.log(`Selecting key-system from session-keys ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)}}removeSession(t){const{mediaKeysSession:r,licenseXhr:n,decryptdata:s}=t;if(r){this.log(`Remove licenses and keys and close session "${r.sessionId}" keyId: ${xr(s?.keyId||[])}`),t._onmessage&&(r.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const a=this.mediaKeySessions.indexOf(t);a>-1&&this.mediaKeySessions.splice(a,1);const{keyStatusTimeouts:c}=t;c&&Object.keys(c).forEach(u=>self.clearTimeout(c[u]));const{drmSystemOptions:d}=this.config;return(I8(d)?new Promise((u,f)=>{self.setTimeout(()=>f(new Error("MediaKeySession.remove() timeout")),8e3),r.remove().then(u).catch(f)}):Promise.resolve()).catch(u=>{this.log(`Could not remove session: ${u}`),this.hls&&this.hls.trigger($.ERROR,{type:it.OTHER_ERROR,details:fe.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${u}`)})}).then(()=>r.close()).catch(u=>{this.log(`Could not close session: ${u}`),this.hls&&this.hls.trigger($.ERROR,{type:it.OTHER_ERROR,details:fe.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${u}`)})})}return Promise.resolve()}};g_.CDMCleanupPromise=void 0;function Dc(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return xr(e.keyId)}function HZ(e,t){if(e.keyId&&t.mediaKeysSession.keyStatuses.has(e.keyId))return t.mediaKeysSession.keyStatuses.get(e.keyId);if(e.matches(t.decryptdata))return t.keyStatus}var Kr=class extends Error{constructor(e,t){super(t),this.data=void 0,e.error||(e.error=new Error(t)),this.data=e,e.err=e.error}};function p_(e,t){const r=e==="output-restricted",n=r?fe.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:fe.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new Kr({type:it.KEY_SYSTEM_ERROR,details:n,fatal:!1,decryptdata:t},r?"HDCP level output restricted":`key status changed to "${e}"`)}var KZ=class{constructor(e){this.hls=void 0,this.isVideoPlaybackQualityAvailable=!1,this.timer=void 0,this.media=null,this.lastTime=void 0,this.lastDroppedFrames=0,this.lastDecodedFrames=0,this.streamController=void 0,this.hls=e,this.registerListeners()}setStreamController(e){this.streamController=e}registerListeners(){this.hls.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on($.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off($.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,t){const r=this.hls.config;if(r.capLevelOnFPSDrop){const n=t.media instanceof self.HTMLVideoElement?t.media:null;this.media=n,n&&typeof n.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(e,t,r){const n=performance.now();if(t){if(this.lastTime){const s=n-this.lastTime,a=r-this.lastDroppedFrames,c=t-this.lastDecodedFrames,d=1e3*a/s,u=this.hls;if(u.trigger($.FPS_DROP,{currentDropped:a,currentDecoded:c,totalDroppedFrames:r}),d>0&&a>u.config.fpsDroppedMonitoringThreshold*c){let f=u.currentLevel;u.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+f),f>0&&(u.autoLevelCapping===-1||u.autoLevelCapping>=f)&&(f=f-1,u.trigger($.FPS_DROP_LEVEL_CAPPING,{level:f,droppedLevel:u.currentLevel}),u.autoLevelCapping=f,this.streamController.nextLevelSwitch())}}this.lastTime=n,this.lastDroppedFrames=r,this.lastDecodedFrames=t}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const t=e.getVideoPlaybackQuality();this.checkFPS(e,t.totalVideoFrames,t.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}};function v_(e,t){let r;try{r=new Event("addtrack")}catch{r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=e,t.dispatchEvent(r)}function b_(e,t){const r=e.mode;if(r==="disabled"&&(e.mode="hidden"),e.cues&&!e.cues.getCueById(t.id))try{if(e.addCue(t),!e.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(n){$t.debug(`[texttrack-utils]: ${n}`);try{const s=new self.TextTrackCue(t.startTime,t.endTime,t.text);s.id=t.id,e.addCue(s)}catch(s){$t.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${s}`)}}r==="disabled"&&(e.mode=r)}function As(e,t){const r=e.mode;if(r==="disabled"&&(e.mode="hidden"),e.cues)for(let n=e.cues.length;n--;)t&&e.cues[n].removeEventListener("enter",t),e.removeCue(e.cues[n]);r==="disabled"&&(e.mode=r)}function zm(e,t,r,n){const s=e.mode;if(s==="disabled"&&(e.mode="hidden"),e.cues&&e.cues.length>0){const a=qZ(e.cues,t,r);for(let c=0;c<a.length;c++)(!n||n(a[c]))&&e.removeCue(a[c])}s==="disabled"&&(e.mode=s)}function WZ(e,t){if(t<=e[0].startTime)return 0;const r=e.length-1;if(t>e[r].endTime)return-1;let n=0,s=r,a;for(;n<=s;)if(a=Math.floor((s+n)/2),t<e[a].startTime)s=a-1;else if(t>e[a].startTime&&n<r)n=a+1;else return a;return e[n].startTime-t<t-e[s].startTime?n:s}function qZ(e,t,r){const n=[],s=WZ(e,t);if(s>-1)for(let a=s,c=e.length;a<c;a++){const d=e[a];if(d.startTime>=t&&d.endTime<=r)n.push(d);else if(d.startTime>r)return n}return n}function Mc(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r];(n.kind==="subtitles"||n.kind==="captions")&&n.label&&t.push(e[r])}return t}var QZ=class extends Mm{constructor(e){super(e,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let t=null;const r=Mc(this.media.textTracks);for(let s=0;s<r.length;s++)if(r[s].mode==="hidden")t=r[s];else if(r[s].mode==="showing"){t=r[s];break}const n=this.findTrackForTextTrack(t);this.subtitleTrack!==n&&this.setSubtitleTrack(n)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(e){this._subtitleDisplay=e,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.LEVEL_LOADING,this.onLevelLoading,this),e.on($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on($.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.LEVEL_LOADING,this.onLevelLoading,this),e.off($.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off($.ERROR,this.onError,this)}onMediaAttached(e,t){this.media=t.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(e){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,e)}onMediaDetaching(e,t){const r=this.media;if(!r)return;const n=!!t.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,!n&&Mc(r.textTracks).forEach(s=>{As(s)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,t){this.tracks=t.subtitleTracks}onSubtitleTrackLoaded(e,t){const{id:r,groupId:n,details:s}=t,a=this.tracksInGroup[r];if(!a||a.groupId!==n){this.warn(`Subtitle track with id:${r} and group:${n} not found in active group ${a?.groupId}`);return}const c=a.details;a.details=t.details,this.log(`Subtitle track ${r} "${a.name}" lang:${a.lang} group:${n} loaded [${s.startSN}-${s.endSN}]`),r===this.trackId&&this.playlistLoaded(r,t,c)}onLevelLoading(e,t){this.switchLevel(t.level)}onLevelSwitching(e,t){this.switchLevel(t.level)}switchLevel(e){const t=this.hls.levels[e];if(!t)return;const r=t.subtitleGroups||null,n=this.groupIds;let s=this.currentTrack;if(!r||n?.length!==r?.length||r!=null&&r.some(a=>n?.indexOf(a)===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(f=>!r||r.indexOf(f.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(f=>f.default)&&(this.selectDefaultTrack=!1),a.forEach((f,h)=>{f.id=h});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const c=this.hls.config.subtitlePreference;if(!s&&c){this.selectDefaultTrack=!1;const f=Pn(c,a);if(f>-1)s=a[f];else{const h=Pn(c,this.tracks);s=this.tracks[h]}}let d=this.findTrackId(s);d===-1&&s&&(d=this.findTrackId(null));const u={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${r?.join(",")}" group-id`),this.hls.trigger($.SUBTITLE_TRACKS_UPDATED,u),d!==-1&&this.trackId===-1&&this.setSubtitleTrack(d)}}findTrackId(e){const t=this.tracksInGroup,r=this.selectDefaultTrack;for(let n=0;n<t.length;n++){const s=t[n];if(!(r&&!s.default||!r&&!e)&&(!e||Li(s,e)))return n}if(e){for(let n=0;n<t.length;n++){const s=t[n];if(Ro(e.attrs,s.attrs,["LANGUAGE","ASSOC-LANGUAGE","CHARACTERISTICS"]))return n}for(let n=0;n<t.length;n++){const s=t[n];if(Ro(e.attrs,s.attrs,["LANGUAGE"]))return n}}return-1}findTrackForTextTrack(e){if(e){const t=this.tracksInGroup;for(let r=0;r<t.length;r++){const n=t[r];if($m(n,e))return r}}return-1}onError(e,t){t.fatal||!t.context||t.context.type===Et.SUBTITLE_TRACK&&t.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(t.context.groupId)!==-1)&&this.checkRetry(t)}get allSubtitleTracks(){return this.tracks}get subtitleTracks(){return this.tracksInGroup}get subtitleTrack(){return this.trackId}set subtitleTrack(e){this.selectDefaultTrack=!1,this.setSubtitleTrack(e)}setSubtitleOption(e){if(this.hls.config.subtitlePreference=e,e){if(e.id===-1)return this.setSubtitleTrack(-1),null;const t=this.allSubtitleTracks;if(this.selectDefaultTrack=!1,t.length){const r=this.currentTrack;if(r&&Li(e,r))return r;const n=Pn(e,this.tracksInGroup);if(n>-1){const s=this.tracksInGroup[n];return this.setSubtitleTrack(n),s}else{if(r)return null;{const s=Pn(e,t);if(s>-1)return t[s]}}}}return null}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=e.id,n=e.groupId,s=this.getUrlWithDirectives(e.url,t),a=e.details,c=a?.age;this.log(`Loading subtitle ${r} "${e.name}" lang:${e.lang} group:${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${c&&a.live?" age "+c.toFixed(1)+(a.type&&" "+a.type||""):""} ${s}`),this.hls.trigger($.SUBTITLE_TRACK_LOADING,{url:s,id:r,groupId:n,deliveryDirectives:t||null,track:e})}toggleTrackModes(){const{media:e}=this;if(!e)return;const t=Mc(e.textTracks),r=this.currentTrack;let n;if(r&&(n=t.filter(s=>$m(r,s))[0],n||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(t).forEach(s=>{s.mode!=="disabled"&&s!==n&&(s.mode="disabled")}),n){const s=this.subtitleDisplay?"showing":"hidden";n.mode!==s&&(n.mode=s)}}setSubtitleTrack(e){const t=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=t.length||!Ye(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,n=t[e]||null;if(this.trackId=e,this.currentTrack=n,this.toggleTrackModes(),!n){this.hls.trigger($.SUBTITLE_TRACK_SWITCH,{id:e});return}const s=!!n.details&&!n.details.live;if(e===this.trackId&&n===r&&s)return;this.log(`Switching to subtitle-track ${e}`+(n?` "${n.name}" lang:${n.lang} group:${n.groupId}`:""));const{id:a,groupId:c="",name:d,type:u,url:f}=n;this.hls.trigger($.SUBTITLE_TRACK_SWITCH,{id:a,groupId:c,name:d,type:u,url:f});const h=this.switchParams(n.url,r?.details,n.details);this.loadPlaylist(h)}};function YZ(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),r=t.toString();return URL.revokeObjectURL(t),r.slice(r.lastIndexOf("/")+1)}catch{let r=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const s=(r+Math.random()*16)%16|0;return r=Math.floor(r/16),(n=="x"?s:s&3|8).toString(16)})}}}function Lo(e){let t=5381,r=e.length;for(;r;)t=t*33^e.charCodeAt(--r);return(t>>>0).toString()}var js=.025,$c=(function(e){return e[e.Point=0]="Point",e[e.Range=1]="Range",e})({});function XZ(e,t,r){return`${e.identifier}-${r+1}-${Lo(t)}`}var JZ=class{constructor(e,t){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=t,this.dateRange=e,this.setDateRange(e)}setDateRange(e){this.dateRange=e,this.resumeOffset=e.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=e.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=e.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=e.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var e;this.appendInPlaceStarted=!1,(e=this.assetListLoader)==null||e.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(e){var t;if(e>0&&e>=this.assetList.length)return!0;const r=this.playoutLimit;return e<=0||isNaN(r)?!1:r===0?!0:(((t=this.assetList[e])==null?void 0:t.startOffset)||0)>r}findAssetIndex(e){return this.assetList.indexOf(e)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const e=this.dateRange.startTime;if(this.snapOptions.out){const t=this.dateRange.tagAnchor;if(t)return Gm(e,t)}return e}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const e=this.dateRange.tagAnchor;if(e){const t=this.dateRange.startTime;return t-Gm(t,e)<.1}return!1}get resumptionOffset(){const e=this.resumeOffset,t=Ye(e)?e:this.duration;return this.cumulativeDuration+t}get resumeTime(){const e=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const t=this.resumeAnchor;if(t)return Gm(e,t)}return e}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)<js))}set appendInPlace(e){if(this.appendInPlaceStarted){this.resetOnResume=!e;return}this.appendInPlaceDisabled=!e}get timelineStart(){return this._timelineStart!==null?this._timelineStart:this.startTime}set timelineStart(e){this._timelineStart=e}get duration(){const e=this.playoutLimit;let t;return this._duration!==null?t=this._duration:this.dateRange.duration?t=this.dateRange.duration:t=this.dateRange.plannedDuration||0,!isNaN(e)&&e<t&&(t=e),t}set duration(e){this._duration=e}get cue(){return this.dateRange.cue}get timelineOccupancy(){return this.dateRange.attr["X-TIMELINE-OCCUPIES"]==="RANGE"?$c.Range:$c.Point}get supplementsPrimary(){return this.dateRange.attr["X-TIMELINE-STYLE"]==="PRIMARY"}get contentMayVary(){return this.dateRange.attr["X-CONTENT-MAY-VARY"]!=="NO"}get assetUrl(){return this.dateRange.attr["X-ASSET-URI"]}get assetListUrl(){return this.dateRange.attr["X-ASSET-LIST"]}get baseUrl(){return this.base.url}get assetListLoaded(){return this.assetList.length>0||this.assetListResponse!==null}toString(){return eV(this)}};function Gm(e,t){return e-t.start<t.duration/2&&!(Math.abs(e-(t.start+t.duration))<js)?t.start:t.start+t.duration}function y_(e,t,r){const n=new self.URL(e,r);return n.protocol!=="data:"&&n.searchParams.set("_HLS_primary_id",t),n}function Zm(e,t){for(;(r=e.assetList[++t])!=null&&r.error;)var r;return t}function eV(e){return`["${e.identifier}" ${e.cue.pre?"<pre>":e.cue.post?"<post>":""}${e.timelineStart.toFixed(2)}-${e.resumeTime.toFixed(2)}]`}function Ns(e){const t=e.timelineStart,r=e.duration||0;return`["${e.identifier}" ${t.toFixed(2)}-${(t+r).toFixed(2)}]`}var tV=class{constructor(e,t,r,n){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger($.PLAYOUT_LIMIT_REACHED,{})};const s=this.hls=new e(t);this.interstitial=r,this.assetItem=n;const a=()=>{this.hasDetails=!0};s.once($.LEVEL_LOADED,a),s.once($.AUDIO_TRACK_LOADED,a),s.once($.SUBTITLE_TRACK_LOADED,a),s.on($.MEDIA_ATTACHING,(c,{media:d})=>{this.removeMediaListeners(),this.mediaAttached=d,this.interstitial.playoutLimit&&(d.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&s.on($.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,s.trigger($.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const e=this.hls;if(e)if(e.url)e.levels.length&&!e.started&&e.startLoad(-1,!0);else{let t=this.assetItem.uri;try{t=y_(t,e.config.primarySessionId||"").href}catch{}e.loadSource(t)}}bufferedInPlaceToEnd(e){var t;if(!this.appendInPlace)return!1;if((t=this.hls)!=null&&t.bufferedToEnd)return!0;if(!e)return!1;const r=Math.min(this._bufferedEosTime||1/0,this.duration),n=this.timelineOffset,s=xt.bufferInfo(e,n,0);return this.getAssetTime(s.end)>=r-.02}reachedPlayout(e){const t=this.interstitial.playoutLimit;return this.startOffset+e>=t}get destroyed(){var e;return!((e=this.hls)!=null&&e.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var e;return((e=this.hls)==null?void 0:e.media)||null}get bufferedEnd(){const e=this.media||this.mediaAttached;if(!e)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const t=xt.bufferInfo(e,e.currentTime,.001);return this.getAssetTime(t.end)}get currentTime(){const e=this.media||this.mediaAttached;return e?this.getAssetTime(e.currentTime):this._currentTime||0}get duration(){const e=this.assetItem.duration;if(!e)return 0;const t=this.interstitial.playoutLimit;if(t){const r=t-this.startOffset;if(r>0&&r<e)return r}return e}get remaining(){const e=this.duration;return e?Math.max(0,e-this.currentTime):0}get startOffset(){return this.assetItem.startOffset}get timelineOffset(){var e;return((e=this.hls)==null?void 0:e.config.timelineOffset)||0}set timelineOffset(e){const t=this.timelineOffset;if(e!==t){const r=e-t;if(Math.abs(r)>1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=e}}}getAssetTime(e){const t=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,e-t),r)}removeMediaListeners(){const e=this.mediaAttached;e&&(this._currentTime=e.currentTime,this.bufferSnapShot(),e.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var e;(e=this.hls)!=null&&e.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(e){var t;this.loadSource(),(t=this.hls)==null||t.attachMedia(e)}detachMedia(){var e;this.removeMediaListeners(),this.mediaAttached=null,(e=this.hls)==null||e.detachMedia()}resumeBuffering(){var e;(e=this.hls)==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.hls)==null||e.pauseBuffering()}transferMedia(){var e;return this.bufferSnapShot(),((e=this.hls)==null?void 0:e.transferMedia())||null}resetDetails(){const e=this.hls;if(e&&this.hasDetails){e.stopLoad();const t=r=>delete r.details;e.levels.forEach(t),e.allAudioTracks.forEach(t),e.allSubtitleTracks.forEach(t),this.hasDetails=!1}}on(e,t,r){var n;(n=this.hls)==null||n.on(e,t)}once(e,t,r){var n;(n=this.hls)==null||n.once(e,t)}off(e,t,r){var n;(n=this.hls)==null||n.off(e,t)}toString(){var e;return`HlsAssetPlayer: ${Ns(this.assetItem)} ${(e=this.hls)==null?void 0:e.sessionId} ${this.appendInPlace?"append-in-place":""}`}},x_=.033,rV=class extends rn{constructor(e,t){super("interstitials-sched",t),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=e}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(e=>e.reset()),this.events=this.items=null}resetErrorsInRange(e,t){return this.events?this.events.reduce((r,n)=>e<=n.startOffset&&t>n.startOffset?(delete n.error,r+1):r,0):0}get duration(){const e=this.items;return e?e[e.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(e){return e&&this.eventMap[e]||null}hasEvent(e){return e in this.eventMap}findItemIndex(e,t){if(e.event)return this.findEventIndex(e.event.identifier);let r=-1;e.nextEvent?r=this.findEventIndex(e.nextEvent.identifier)-1:e.previousEvent&&(r=this.findEventIndex(e.previousEvent.identifier)+1);const n=this.items;if(n)for(n[r]||(t===void 0&&(t=e.start),r=this.findItemIndexAtTime(t));r>=0&&(s=n[r])!=null&&s.event;){var s;r--}return r}findItemIndexAtTime(e,t){const r=this.items;if(r)for(let n=0;n<r.length;n++){let s=r[n];if(t&&t!=="primary"&&(s=s[t]),e===s.start||e>s.start&&e<s.end)return n}return-1}findJumpRestrictedIndex(e,t){const r=this.items;if(r)for(let n=e;n<=t&&r[n];n++){const s=r[n].event;if(s!=null&&s.restrictions.jump&&!s.appendInPlace)return n}return-1}findEventIndex(e){const t=this.items;if(t)for(let n=t.length;n--;){var r;if(((r=t[n].event)==null?void 0:r.identifier)===e)return n}return-1}findAssetIndex(e,t){const r=e.assetList,n=r.length;if(n>1)for(let s=0;s<n;s++){const a=r[s];if(!a.error){const c=a.timelineStart;if(t===c||t>c&&(t<c+(a.duration||0)||s===n-1))return s}}return 0}get assetIdAtEnd(){var e;const t=(e=this.items)==null||(e=e[this.length-1])==null?void 0:e.event;if(t){const r=t.assetList,n=r[r.length-1];if(n)return n.identifier}return null}parseInterstitialDateRanges(e,t){const r=e.main.details,{dateRanges:n}=r,s=this.events,a=this.parseDateRanges(n,{url:r.url},t),c=Object.keys(n),d=s?s.filter(u=>!c.includes(u.identifier)):[];a.length&&a.sort((u,f)=>{const h=u.cue.pre,m=u.cue.post,g=f.cue.pre,p=f.cue.post;if(h&&!g)return-1;if(g&&!h||m&&!p)return 1;if(p&&!m)return-1;if(!h&&!g&&!m&&!p){const y=u.startTime,S=f.startTime;if(y!==S)return y-S}return u.dateRange.tagOrder-f.dateRange.tagOrder}),this.events=a,d.forEach(u=>{this.removeEvent(u)}),this.updateSchedule(e,d)}updateSchedule(e,t=[],r=!1){const n=this.events||[];if(n.length||t.length||this.length<2){const s=this.items,a=this.parseSchedule(n,e);(r||t.length||s?.length!==a.length||a.some((c,d)=>Math.abs(c.playout.start-s[d].playout.start)>.005||Math.abs(c.playout.end-s[d].playout.end)>.005))&&(this.items=a,this.onScheduleUpdate(t,s))}}parseDateRanges(e,t,r){const n=[],s=Object.keys(e);for(let a=0;a<s.length;a++){const c=s[a],d=e[c];if(d.isInterstitial){let u=this.eventMap[c];u?u.setDateRange(d):(u=new JZ(d,t),this.eventMap[c]=u,r===!1&&(u.appendInPlace=r)),n.push(u)}}return n}parseSchedule(e,t){const r=[],n=t.main.details,s=n.live?1/0:n.edge;let a=0;if(e=e.filter(d=>!d.error&&!(d.cue.once&&d.hasPlayed)),e.length){this.resolveOffsets(e,t);let d=0,u=0;if(e.forEach((f,h)=>{const m=f.cue.pre,g=f.cue.post,p=e[h-1]||null,y=f.appendInPlace,S=g?s:f.startOffset,E=f.duration,T=f.timelineOccupancy===$c.Range?E:0,j=f.resumptionOffset,N=p?.startTime===S,O=S+f.cumulativeDuration;let U=y?O+E:S+j;if(m||!g&&S<=0){const K=u;u+=T,f.timelineStart=O;const G=a;a+=E,r.push({event:f,start:O,end:U,playout:{start:G,end:a},integrated:{start:K,end:u}})}else if(S<=s){if(!N){const X=S-d;if(X>x_){const te=d,ne=u;u+=X;const ae=a;a+=X;const oe={previousEvent:e[h-1]||null,nextEvent:f,start:te,end:te+X,playout:{start:ae,end:a},integrated:{start:ne,end:u}};r.push(oe)}else X>0&&p&&(p.cumulativeDuration+=X,r[r.length-1].end=S)}g&&(U=O),f.timelineStart=O;const K=u;u+=T;const G=a;a+=E,r.push({event:f,start:O,end:U,playout:{start:G,end:a},integrated:{start:K,end:u}})}else return;const z=f.resumeTime;g||z>s?d=s:d=z}),d<s){var c;const f=d,h=u,m=s-d;u+=m;const g=a;a+=m,r.push({previousEvent:((c=r[r.length-1])==null?void 0:c.event)||null,nextEvent:null,start:d,end:f+m,playout:{start:g,end:a},integrated:{start:h,end:u}})}this.setDurations(s,a,u)}else r.push({previousEvent:null,nextEvent:null,start:0,end:s,playout:{start:0,end:s},integrated:{start:0,end:s}}),this.setDurations(s,s,s);return r}setDurations(e,t,r){this.durations={primary:e,playout:t,integrated:r}}resolveOffsets(e,t){const r=t.main.details,n=r.live?1/0:r.edge;let s=0,a=-1;e.forEach((c,d)=>{const u=c.cue.pre,f=c.cue.post,h=u?0:f?n:c.startTime;this.updateAssetDurations(c),a===h?c.cumulativeDuration=s:(s=0,a=h),!f&&c.snapOptions.in&&(c.resumeAnchor=Fi(null,r.fragments,c.startOffset+c.resumptionOffset,0,0)||void 0),c.appendInPlace&&!c.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(c,t)||(c.appendInPlace=!1)),!c.appendInPlace&&d+1<e.length&&e[d+1].startTime-e[d].resumeTime<x_&&(e[d+1].appendInPlace=!1,e[d+1].appendInPlace&&this.warn(`Could not change append strategy for abutting event ${c}`));const m=Ye(c.resumeOffset)?c.resumeOffset:c.duration;s+=m})}primaryCanResumeInPlaceAt(e,t){const r=e.resumeTime,n=e.startTime+e.resumptionOffset;return Math.abs(r-n)>js?(this.log(`"${e.identifier}" resumption ${r} not aligned with estimated timeline end ${n}`),!1):!Object.keys(t).some(s=>{const a=t[s].details,c=a.edge;if(r>=c)return this.log(`"${e.identifier}" resumption ${r} past ${s} playlist end ${c}`),!1;const d=Fi(null,a.fragments,r);if(!d)return this.log(`"${e.identifier}" resumption ${r} does not align with any fragments in ${s} playlist (${a.fragStart}-${a.fragmentEnd})`),!0;const u=s==="audio"?.175:0;return Math.abs(d.start-r)<js+u||Math.abs(d.end-r)<js+u?!1:(this.log(`"${e.identifier}" resumption ${r} not aligned with ${s} fragment bounds (${d.start}-${d.end} sn: ${d.sn} cc: ${d.cc})`),!0)})}updateAssetDurations(e){if(!e.assetListLoaded)return;const t=e.timelineStart;let r=0,n=!1,s=!1;for(let a=0;a<e.assetList.length;a++){const c=e.assetList[a],d=t+r;c.startOffset=r,c.timelineStart=d,n||(n=c.duration===null),s||(s=!!c.error);const u=c.error?0:c.duration||0;r+=u}n&&!s?e.duration=Math.max(r,e.duration):e.duration=r}removeEvent(e){e.reset(),delete this.eventMap[e.identifier]}};function pn(e){return`[${e.event?'"'+e.event.identifier+'"':"primary"}: ${e.start.toFixed(2)}-${e.end.toFixed(2)}]`}var nV=class{constructor(e){this.hls=void 0,this.hls=e}destroy(){this.hls=null}loadAssetList(e,t){const r=e.assetListUrl;let n;try{n=y_(r,this.hls.sessionId,e.baseUrl)}catch(h){const m=this.assignAssetListError(e,fe.ASSET_LIST_LOAD_ERROR,h,r);this.hls.trigger($.ERROR,m);return}t&&n.protocol!=="data:"&&n.searchParams.set("_HLS_start_offset",""+t);const s=this.hls.config,a=s.loader,c=new a(s),d={responseType:"json",url:n.href},u=s.interstitialAssetListLoadPolicy.default,f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};return c.load(d,f,{onSuccess:(h,m,g,p)=>{const y=h.data,S=y?.ASSETS;if(!Array.isArray(S)){const E=this.assignAssetListError(e,fe.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,m,p);this.hls.trigger($.ERROR,E);return}e.assetListResponse=y,this.hls.trigger($.ASSET_LIST_LOADED,{event:e,assetListResponse:y,networkDetails:p})},onError:(h,m,g,p)=>{const y=this.assignAssetListError(e,fe.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${h.code} ${h.text} (${m.url})`),m.url,p,g);this.hls.trigger($.ERROR,y)},onTimeout:(h,m,g)=>{const p=this.assignAssetListError(e,fe.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${m.url})`),m.url,h,g);this.hls.trigger($.ERROR,p)}}),this.hls.trigger($.ASSET_LIST_LOADING,{event:e}),c}assignAssetListError(e,t,r,n,s,a){return e.error=r,{type:it.NETWORK_ERROR,details:t,fatal:!1,interstitial:e,url:n,error:r,networkDetails:a,stats:s}}};function S_(e){var t;e==null||(t=e.play())==null||t.catch(()=>{})}function Ds(e,t){return`[${e}] Advancing timeline position to ${t}`}var iV=class extends rn{constructor(e,t){super("interstitials",e.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled||!this.schedule)return;const n=r-this.timelinePos;if(Math.abs(n)<1/7056e5)return;const s=n<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=r,this.bufferedPos=r;const a=this.playingItem;if(!a){this.checkBuffer();return}if(s&&this.schedule.resetErrorsInRange(r,r-n)&&this.updateSchedule(!0),this.checkBuffer(),s&&r<a.start||r>=a.end){var c;const m=this.findItemIndex(a);let g=this.schedule.findItemIndexAtTime(r);if(g===-1&&(g=m+(s?-1:1),this.log(`seeked ${s?"back ":""}to position not covered by schedule ${r} (resolving from ${m} to ${g})`)),!this.isInterstitial(a)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!s&&g>m){const p=this.schedule.findJumpRestrictedIndex(m+1,g);if(p>m){this.setSchedulePosition(p);return}}this.setSchedulePosition(g);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(a)){const m=a.event.assetList[0];m&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,m))}return}const u=d.timelineStart,f=d.duration||0;if(s&&r<u||r>=u+f){var h;(h=a.event)!=null&&h.appendInPlace&&(this.clearAssetPlayers(a.event,a),this.flushFrontBuffer(r)),this.setScheduleToAssetAtTime(r,d)}},this.onTimeupdate=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),r>this.timelinePos)this.timelinePos=r,r>this.bufferedPos&&this.checkBuffer();else return;const n=this.playingItem;if(!n||this.playingLastItem)return;if(r>=n.end){this.timelinePos=n.end;const a=this.findItemIndex(n);this.setSchedulePosition(a+1)}const s=this.playingAsset;s&&r>=s.timelineStart+(s.duration||0)&&this.setScheduleToAssetAtTime(r,s)},this.onScheduleUpdate=(r,n)=>{const s=this.schedule;if(!s)return;const a=this.playingItem,c=s.events||[],d=s.items||[],u=s.durations,f=r.map(y=>y.identifier),h=!!(c.length||f.length);(h||n)&&this.log(`INTERSTITIALS_UPDATED (${c.length}): ${c}
177
+ Schedule: ${d.map(y=>pn(y))} pos: ${this.timelinePos}`),f.length&&this.log(`Removed events ${f}`);let m=null,g=null;a&&(m=this.updateItem(a,this.timelinePos),this.itemsMatch(a,m)?this.playingItem=m:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const p=this.bufferingItem;if(p&&(g=this.updateItem(p,this.bufferedPos),this.itemsMatch(p,g)?this.bufferingItem=g:p.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(p.event,null))),r.forEach(y=>{y.assetList.forEach(S=>{this.clearAssetPlayer(S.identifier,null)})}),this.playerQueue.forEach(y=>{if(y.interstitial.appendInPlace){const S=y.assetItem.timelineStart,E=y.timelineOffset-S;if(E)try{y.timelineOffset=S}catch(T){Math.abs(E)>js&&this.warn(`${T} ("${y.assetId}" ${y.timelineOffset}->${S})`)}}}),h||n){if(this.hls.trigger($.INTERSTITIALS_UPDATED,{events:c.slice(0),schedule:d.slice(0),durations:u,removedIds:f}),this.isInterstitial(a)&&f.includes(a.event.identifier)){this.warn(`Interstitial "${a.event.identifier}" removed while playing`),this.primaryFallback(a.event);return}a&&this.trimInPlace(m,a),p&&g!==m&&this.trimInPlace(g,p),this.checkBuffer()}},this.hls=e,this.HlsPlayerClass=t,this.assetListLoader=new nV(e),this.schedule=new rV(this.onScheduleUpdate,e.logger),this.registerListeners()}registerListeners(){const e=this.hls;e&&(e.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.LEVEL_UPDATED,this.onLevelUpdated,this),e.on($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on($.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.on($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on($.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.on($.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.on($.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.on($.BUFFER_APPENDED,this.onBufferAppended,this),e.on($.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on($.BUFFERED_TO_END,this.onBufferedToEnd,this),e.on($.MEDIA_ENDED,this.onMediaEnded,this),e.on($.ERROR,this.onError,this),e.on($.DESTROYING,this.onDestroying,this))}unregisterListeners(){const e=this.hls;e&&(e.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.LEVEL_UPDATED,this.onLevelUpdated,this),e.off($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off($.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),e.off($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off($.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),e.off($.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),e.off($.ASSET_LIST_LOADED,this.onAssetListLoaded,this),e.off($.BUFFER_CODECS,this.onBufferCodecs,this),e.off($.BUFFER_APPENDED,this.onBufferAppended,this),e.off($.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off($.BUFFERED_TO_END,this.onBufferedToEnd,this),e.off($.MEDIA_ENDED,this.onMediaEnded,this),e.off($.ERROR,this.onError,this),e.off($.DESTROYING,this.onDestroying,this))}startLoad(){this.resumeBuffering()}stopLoad(){this.pauseBuffering()}resumeBuffering(){var e;(e=this.getBufferingPlayer())==null||e.resumeBuffering()}pauseBuffering(){var e;(e=this.getBufferingPlayer())==null||e.pauseBuffering()}destroy(){this.unregisterListeners(),this.stopLoad(),this.assetListLoader&&this.assetListLoader.destroy(),this.emptyPlayerQueue(),this.clearScheduleState(),this.schedule&&this.schedule.destroy(),this.media=this.detachedData=this.mediaSelection=this.requiredTracks=this.altSelection=this.schedule=this.manager=null,this.hls=this.HlsPlayerClass=this.log=null,this.assetListLoader=null,this.onPlay=this.onPause=this.onSeeking=this.onTimeupdate=null,this.onScheduleUpdate=null}onDestroying(){const e=this.primaryMedia||this.media;e&&this.removeMediaListeners(e)}removeMediaListeners(e){$r(e,"play",this.onPlay),$r(e,"pause",this.onPause),$r(e,"seeking",this.onSeeking),$r(e,"timeupdate",this.onTimeupdate)}onMediaAttaching(e,t){const r=this.media=t.media;Ar(r,"seeking",this.onSeeking),Ar(r,"timeupdate",this.onTimeupdate),Ar(r,"play",this.onPlay),Ar(r,"pause",this.onPause)}onMediaAttached(e,t){const r=this.effectivePlayingItem,n=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!n){this.clearScheduleState();const s=this.findItemIndex(r);this.setSchedulePosition(s)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(e,t){const r=!!t.transferMedia,n=this.media;if(this.media=null,!r&&(n&&this.removeMediaListeners(n),this.detachedData)){const s=this.getBufferingPlayer();s&&(this.log(`Removing schedule state for detachedData and ${s}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,s.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const e=this,t=()=>e.bufferingItem||e.waitingItem,r=h=>h&&e.getAssetPlayer(h.identifier),n=(h,m,g,p,y)=>{if(h){let S=h[m].start;const E=h.event;if(E){if(m==="playout"||E.timelineOccupancy!==$c.Point){const T=r(g);T?.interstitial===E&&(S+=T.assetItem.startOffset+T[y])}}else{const T=p==="bufferedPos"?a():e[p];S+=T-h.start}return S}return 0},s=(h,m)=>{var g;if(h!==0&&m!=="primary"&&(g=e.schedule)!=null&&g.length){var p;const y=e.schedule.findItemIndexAtTime(h),S=(p=e.schedule.items)==null?void 0:p[y];if(S)return h+(S[m].start-S.start)}return h},a=()=>{const h=e.bufferedPos;return h===Number.MAX_VALUE?c("primary"):Math.max(h,0)},c=h=>{var m,g;return(m=e.primaryDetails)!=null&&m.live?e.primaryDetails.edge:((g=e.schedule)==null?void 0:g.durations[h])||0},d=(h,m)=>{var g,p;const y=e.effectivePlayingItem;if(y!=null&&(g=y.event)!=null&&g.restrictions.skip||!e.schedule)return;e.log(`seek to ${h} "${m}"`);const S=e.effectivePlayingItem,E=e.schedule.findItemIndexAtTime(h,m),T=(p=e.schedule.items)==null?void 0:p[E],j=e.getBufferingPlayer(),N=j?.interstitial,O=N?.appendInPlace,U=S&&e.itemsMatch(S,T);if(S&&(O||U)){const z=r(e.playingAsset),K=z?.media||e.primaryMedia;if(K){const G=m==="primary"?K.currentTime:n(S,m,e.playingAsset,"timelinePos","currentTime"),X=h-G,te=(O?G:K.currentTime)+X;if(te>=0&&(!z||O||te<=z.duration)){K.currentTime=te;return}}}if(T){let z=h;if(m!=="primary"){const G=h-T[m].start;z=T.start+G}const K=!e.isInterstitial(T);if((!e.isInterstitial(S)||S.event.appendInPlace)&&(K||T.event.appendInPlace)){const G=e.media||(O?j?.media:null);G&&(G.currentTime=z)}else if(S){const G=e.findItemIndex(S);if(E>G){const te=e.schedule.findJumpRestrictedIndex(G+1,E);if(te>G){e.setSchedulePosition(te);return}}let X=0;if(K)e.timelinePos=z,e.checkBuffer();else{const te=T.event.assetList,ne=h-(T[m]||T).start;for(let ae=te.length;ae--;){const oe=te[ae];if(oe.duration&&ne>=oe.startOffset&&ne<oe.startOffset+oe.duration){X=ae;break}}}e.setSchedulePosition(E,X)}}},u=()=>{const h=e.effectivePlayingItem;if(e.isInterstitial(h))return h;const m=t();return e.isInterstitial(m)?m:null},f={get bufferedEnd(){const h=t(),m=e.bufferingItem;if(m&&m===h){var g;return n(m,"playout",e.bufferingAsset,"bufferedPos","bufferedEnd")-m.playout.start||((g=e.bufferingAsset)==null?void 0:g.startOffset)||0}return 0},get currentTime(){const h=u(),m=e.effectivePlayingItem;return m&&m===h?n(m,"playout",e.effectivePlayingAsset,"timelinePos","currentTime")-m.playout.start:0},set currentTime(h){const m=u(),g=e.effectivePlayingItem;g&&g===m&&d(h+g.playout.start,"playout")},get duration(){const h=u();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;const m=(h=u())==null?void 0:h.event.assetList;return m?m.map(g=>e.getAssetPlayer(g.identifier)):[]},get playingIndex(){var h;const m=(h=u())==null?void 0:h.event;return m&&e.effectivePlayingAsset?m.findAssetIndex(e.effectivePlayingAsset):-1},get scheduleItem(){return u()}};return this.manager={get events(){var h;return((h=e.schedule)==null||(h=h.events)==null?void 0:h.slice(0))||[]},get schedule(){var h;return((h=e.schedule)==null||(h=h.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return u()?f:null},get playerQueue(){return e.playerQueue.slice(0)},get bufferingAsset(){return e.bufferingAsset},get bufferingItem(){return t()},get bufferingIndex(){const h=t();return e.findItemIndex(h)},get playingAsset(){return e.effectivePlayingAsset},get playingItem(){return e.effectivePlayingItem},get playingIndex(){const h=e.effectivePlayingItem;return e.findItemIndex(h)},primary:{get bufferedEnd(){return a()},get currentTime(){const h=e.timelinePos;return h>0?h:0},set currentTime(h){d(h,"primary")},get duration(){return c("primary")},get seekableStart(){var h;return((h=e.primaryDetails)==null?void 0:h.fragmentStart)||0}},integrated:{get bufferedEnd(){return n(t(),"integrated",e.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return n(e.effectivePlayingItem,"integrated",e.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){d(h,"integrated")},get duration(){return c("integrated")},get seekableStart(){var h;return s(((h=e.primaryDetails)==null?void 0:h.fragmentStart)||0,"integrated")}},skip:()=>{const h=e.effectivePlayingItem,m=h?.event;if(m&&!m.restrictions.skip){const g=e.findItemIndex(h);m.appendInPlace?d(h.playout.start+h.event.duration+.001,"playout"):e.advanceAfterAssetEnded(m,g,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var e;const t=this.playingItem,r=(e=this.schedule)==null?void 0:e.items;return!this.playbackStarted||!t||!r?!1:this.findItemIndex(t)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var e,t;if(this.mediaSelection===null)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let n=this.media;!n&&(e=this.bufferingItem)!=null&&(e=e.event)!=null&&e.appendInPlace&&(n=this.primaryMedia);const s=(t=n)==null?void 0:t.currentTime;if(!(s===void 0||!Ye(s)))return s}get primaryMedia(){var e;return this.media||((e=this.detachedData)==null?void 0:e.media)||null}isInterstitial(e){return!!(e!=null&&e.event)}retreiveMediaSource(e,t){const r=this.getAssetPlayer(e);r&&this.transferMediaFromPlayer(r,t)}transferMediaFromPlayer(e,t){const r=e.interstitial.appendInPlace,n=e.media;if(r&&n===this.primaryMedia){if(this.bufferingAsset=null,(!t||this.isInterstitial(t)&&!t.event.appendInPlace)&&t&&n){this.detachedData={media:n};return}const s=e.transferMedia();this.log(`transfer MediaSource from ${e} ${zt(s)}`),this.detachedData=s}else t&&n&&(this.shouldPlay||(this.shouldPlay=!n.paused))}transferMediaTo(e,t){var r,n;if(e.media===t)return;let s=null;const a=this.hls,c=e!==a,d=c&&e.interstitial.appendInPlace,u=(r=this.detachedData)==null?void 0:r.mediaSource;let f;if(a.media)d&&(s=a.transferMedia(),this.detachedData=s),f="Primary";else if(u){const p=this.getBufferingPlayer();p?(s=p.transferMedia(),f=`${p}`):f="detached MediaSource"}else f="detached media";if(!s){if(u)s=this.detachedData,this.log(`using detachedData: MediaSource ${zt(s)}`);else if(!this.detachedData||a.media===t){const p=this.playerQueue;p.length>1&&p.forEach(y=>{if(c&&y.interstitial.appendInPlace!==d){const S=y.interstitial;this.clearInterstitial(y.interstitial,null),S.appendInPlace=!1,S.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${S}`)}}),this.hls.detachMedia(),this.detachedData={media:t}}}const h=s&&"mediaSource"in s&&((n=s.mediaSource)==null?void 0:n.readyState)!=="closed",m=h&&s?s:t;this.log(`${h?"transfering MediaSource":"attaching media"} to ${c?e:"Primary"} from ${f} (media.currentTime: ${t.currentTime})`);const g=this.schedule;if(m===s&&g){const p=c&&e.assetId===g.assetIdAtEnd;m.overrides={duration:g.duration,endOfStream:!c||p,cueRemoval:!c}}e.attachMedia(m)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const e=this.schedule,t=e?.events;if(!t||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const r=this.timelinePos,n=this.effectivePlayingItem;if(r===-1){const s=this.hls.startPosition;if(this.timelinePos=s,t.length===0)this.setSchedulePosition(0);else if(t[0].cue.pre){this.log(Ds("checkStart (preroll)",s));const a=e.findEventIndex(t[0].identifier);this.setSchedulePosition(a)}else if(s>=0||!this.primaryLive){this.log(Ds("checkStart",s));const a=this.timelinePos=s>0?s:0,c=e.findItemIndexAtTime(a);this.setSchedulePosition(c)}else this.hls.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(n&&!this.playingItem){this.log(Ds("checkStart (playing item)",n.start));const s=e.findItemIndex(n);this.setSchedulePosition(s)}}advanceAssetBuffering(e,t){const r=e.event,n=Zm(r,r.findAssetIndex(t));if(!r.isAssetPastPlayoutLimit(n))this.bufferedToEvent(e,n);else if(this.schedule){var s;const a=(s=this.schedule.items)==null?void 0:s[this.findItemIndex(e)+1];a&&this.bufferedToItem(a)}}advanceAfterAssetEnded(e,t,r){const n=Zm(e,r);if(e.isAssetPastPlayoutLimit(n)){if(this.schedule){const s=this.schedule.items;if(s){const a=t+1;if(a>=s.length){this.setSchedulePosition(-1);return}const c=e.resumeTime;this.timelinePos<c&&(this.log(Ds("advanceAfterAssetEnded",c)),this.timelinePos=c,e.appendInPlace&&this.advanceInPlace(c),this.checkBuffer(this.bufferedPos<c)),this.setSchedulePosition(a)}}}else{if(e.appendInPlace){const s=e.assetList[n];s&&this.advanceInPlace(s.timelineStart)}this.setSchedulePosition(t,n)}}setScheduleToAssetAtTime(e,t){const r=this.schedule;if(!r)return;const n=t.parentIdentifier,s=r.getEvent(n);if(s){const a=r.findEventIndex(n),c=r.findAssetIndex(s,e);this.advanceAfterAssetEnded(s,a,c-1)}}setSchedulePosition(e,t){var r;const n=(r=this.schedule)==null?void 0:r.items;if(!n||this.playbackDisabled)return;const s=e>=0?n[e]:null;this.log(`setSchedulePosition ${e}, ${t} (${s&&pn(s)}) pos: ${this.timelinePos}`);const a=this.waitingItem||this.playingItem,c=this.playingLastItem;if(this.isInterstitial(a)){const f=a.event,h=this.playingAsset,m=h?.identifier,g=m?this.getAssetPlayer(m):null;if(g&&m&&(!this.eventItemsMatch(a,s)||t!==void 0&&m!==f.assetList[t].identifier)){var d;const p=f.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${p+1}/${f.assetList.length} ${Ns(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger($.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:p,event:f,schedule:n.slice(0),scheduleIndex:e,player:g}),a!==this.playingItem){this.itemsMatch(a,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(f,this.findItemIndex(this.playingItem),p);return}this.retreiveMediaSource(m,s),g.media&&!((d=this.detachedData)!=null&&d.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(a,s)&&(this.endedItem=a,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${f} ${pn(a)}`),f.hasPlayed=!0,this.hls.trigger($.INTERSTITIAL_ENDED,{event:f,schedule:n.slice(0),scheduleIndex:e}),f.cue.once)){var u;this.updateSchedule();const p=(u=this.schedule)==null?void 0:u.items;if(s&&p){const y=this.findItemIndex(s);this.advanceSchedule(y,p,t,a,c)}return}}this.advanceSchedule(e,n,t,a,c)}advanceSchedule(e,t,r,n,s){const a=this.schedule;if(!a)return;const c=t[e]||null,d=this.primaryMedia,u=this.playerQueue;if(u.length&&u.forEach(f=>{const h=f.interstitial,m=a.findEventIndex(h.identifier);(m<e||m>e+1)&&this.clearInterstitial(h,c)}),this.isInterstitial(c)){this.timelinePos=Math.min(Math.max(this.timelinePos,c.start),c.end);const f=c.event;if(r===void 0){r=a.findAssetIndex(f,this.timelinePos);const p=Zm(f,r-1);if(f.isAssetPastPlayoutLimit(p)||f.appendInPlace&&this.timelinePos===c.end){this.advanceAfterAssetEnded(f,e,r);return}r=p}const h=this.waitingItem;this.assetsBuffered(c,d)||this.setBufferingItem(c);let m=this.preloadAssets(f,r);if(this.eventItemsMatch(c,h||n)||(this.waitingItem=c,this.log(`INTERSTITIAL_STARTED ${pn(c)} ${f.appendInPlace?"append in place":""}`),this.hls.trigger($.INTERSTITIAL_STARTED,{event:f,schedule:t.slice(0),scheduleIndex:e})),!f.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${f}`);return}if(f.assetListLoader&&(f.assetListLoader.destroy(),f.assetListLoader=void 0),!d){this.log(`Waiting for attachMedia to start Interstitial ${f}`);return}this.waitingItem=this.endedItem=null,this.playingItem=c;const g=f.assetList[r];if(!g){this.advanceAfterAssetEnded(f,e,r||0);return}if(m||(m=this.getAssetPlayer(g.identifier)),m===null||m.destroyed){const p=f.assetList.length;this.warn(`asset ${r+1}/${p} player destroyed ${f}`),m=this.createAssetPlayer(f,g,r),m.loadSource()}if(!this.eventItemsMatch(c,this.bufferingItem)&&f.appendInPlace&&this.isAssetBuffered(g))return;this.startAssetPlayer(m,r,t,e,d),this.shouldPlay&&S_(m.media)}else c?(this.resumePrimary(c,e,n),this.shouldPlay&&S_(this.hls.media)):s&&this.isInterstitial(n)&&(this.endedItem=null,this.playingItem=n,n.event.appendInPlace||this.attachPrimary(a.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var e;return(e=this.mediaSelection)==null?void 0:e.main.details}get primaryLive(){var e;return!!((e=this.primaryDetails)!=null&&e.live)}resumePrimary(e,t,r){var n,s;if(this.playingItem=e,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(e),this.log(`resuming ${pn(e)}`),!((n=this.detachedData)!=null&&n.mediaSource)){let c=this.timelinePos;(c<e.start||c>=e.end)&&(c=this.getPrimaryResumption(e,t),this.log(Ds("resumePrimary",c)),this.timelinePos=c),this.attachPrimary(c,e)}if(!r)return;const a=(s=this.schedule)==null?void 0:s.items;a&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${pn(e)}`),this.hls.trigger($.INTERSTITIALS_PRIMARY_RESUMED,{schedule:a.slice(0),scheduleIndex:t}),this.checkBuffer())}getPrimaryResumption(e,t){const r=e.start;if(this.primaryLive){const n=this.primaryDetails;if(t===0)return this.hls.startPosition;if(n&&(r<n.fragmentStart||r>n.edge))return this.hls.liveSyncPosition||-1}return r}isAssetBuffered(e){const t=this.getAssetPlayer(e.identifier);return t!=null&&t.hls?t.hls.bufferedToEnd:xt.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=e.timelineStart+(e.duration||0)}attachPrimary(e,t,r){t?this.setBufferingItem(t):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const n=this.primaryMedia;if(!n)return;const s=this.hls;s.media?this.checkBuffer():(this.transferMediaTo(s,n),r&&this.startLoadingPrimaryAt(e,r)),r||(this.log(Ds("attachPrimary",e)),this.timelinePos=e,this.startLoadingPrimaryAt(e,r))}startLoadingPrimaryAt(e,t){var r;const n=this.hls;!n.loadingEnabled||!n.media||Math.abs((((r=n.mainForwardBufferInfo)==null?void 0:r.start)||n.media.currentTime)-e)>.5?n.startLoad(e,t):n.bufferingEnabled||n.resumeBuffering()}onManifestLoading(){var e;this.stopLoad(),(e=this.schedule)==null||e.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off($.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on($.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(e,t){if(t.level===-1||!this.schedule)return;const r=this.hls.levels[t.level];if(!r.details)return;const n=Mt(Mt({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=n,this.schedule.parseInterstitialDateRanges(n,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(e,t){const r=this.hls.audioTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Mt(Mt({},this.altSelection),{},{audio:r});return}const s=Mt(Mt({},n),{},{audio:r});this.mediaSelection=s}onSubtitleTrackUpdated(e,t){const r=this.hls.subtitleTracks[t.id],n=this.mediaSelection;if(!n){this.altSelection=Mt(Mt({},this.altSelection),{},{subtitles:r});return}const s=Mt(Mt({},n),{},{subtitles:r});this.mediaSelection=s}onAudioTrackSwitching(e,t){const r=CS(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setAudioOption(t)||n.setAudioOption(r)))}onSubtitleTrackSwitch(e,t){const r=CS(t);this.playerQueue.forEach(({hls:n})=>n&&(n.setSubtitleOption(t)||t.id!==-1&&n.setSubtitleOption(r)))}onBufferCodecs(e,t){const r=t.tracks;r&&(this.requiredTracks=r)}onBufferAppended(e,t){this.checkBuffer()}onBufferFlushed(e,t){const r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){const n=this.timelinePos;this.bufferedPos=n,this.checkBuffer()}}onBufferedToEnd(e){if(!this.schedule)return;const t=this.schedule.events;if(this.bufferedPos<Number.MAX_VALUE&&t){for(let n=0;n<t.length;n++){const s=t[n];if(s.cue.post){var r;const a=this.schedule.findEventIndex(s.identifier),c=(r=this.schedule.items)==null?void 0:r[a];this.isInterstitial(c)&&this.eventItemsMatch(c,this.bufferingItem)&&this.bufferedToItem(c,0);break}}this.bufferedPos=Number.MAX_VALUE}}onMediaEnded(e){const t=this.playingItem;if(!this.playingLastItem&&t){const r=this.findItemIndex(t);this.setSchedulePosition(r+1)}else this.shouldPlay=!1}updateItem(e,t){var r;const n=(r=this.schedule)==null?void 0:r.items;return e&&n&&n[this.findItemIndex(e,t)]||null}trimInPlace(e,t){if(this.isInterstitial(e)&&e.event.appendInPlace&&t.end-e.end>.25){e.event.assetList.forEach((s,a)=>{e.event.isAssetPastPlayoutLimit(a)&&this.clearAssetPlayer(s.identifier,null)});const r=e.end+.25,n=xt.bufferInfo(this.primaryMedia,r,0);(n.end>r||(n.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${pn(e)} (was ${pn(t)})`),this.attachPrimary(r,null,!0),this.flushFrontBuffer(r))}}itemsMatch(e,t){return!!t&&(e===t||e.event&&t.event&&this.eventItemsMatch(e,t)||!e.event&&!t.event&&this.findItemIndex(e)===this.findItemIndex(t))}eventItemsMatch(e,t){var r;return!!t&&(e===t||e.event.identifier===((r=t.event)==null?void 0:r.identifier))}findItemIndex(e,t){return e&&this.schedule?this.schedule.findItemIndex(e,t):-1}updateSchedule(e=!1){var t;const r=this.mediaSelection;r&&((t=this.schedule)==null||t.updateSchedule(r,[],e))}checkBuffer(e){var t;const r=(t=this.schedule)==null?void 0:t.items;if(!r)return;const n=xt.bufferInfo(this.primaryMedia,this.timelinePos,0);e&&(this.bufferedPos=this.timelinePos),e||(e=n.len<1),this.updateBufferedPos(n.end,r,e)}updateBufferedPos(e,t,r){const n=this.schedule,s=this.bufferingItem;if(this.bufferedPos>e||!n)return;if(t.length===1&&this.itemsMatch(t[0],s)){this.bufferedPos=e;return}const a=this.playingItem,c=this.findItemIndex(a);let d=n.findItemIndexAtTime(e);if(this.bufferedPos<e){var u;const f=this.findItemIndex(s),h=Math.min(f+1,t.length-1),m=t[h];if((d===-1&&s&&e>=s.end||(u=m.event)!=null&&u.appendInPlace&&e+.01>=m.start)&&(d=h),this.isInterstitial(s)){const g=s.event;if(h-c>1&&g.appendInPlace===!1||g.assetList.length===0&&g.assetListLoader)return}if(this.bufferedPos=e,d>f&&d>c)this.bufferedToItem(m);else{const g=this.primaryDetails;this.primaryLive&&g&&e>g.edge-g.targetduration&&m.start<g.edge+this.hls.config.interstitialLiveLookAhead&&this.isInterstitial(m)&&this.preloadAssets(m.event,0)}}else r&&a&&!this.itemsMatch(a,s)&&(d===c?this.bufferedToItem(a):d===c+1&&this.bufferedToItem(t[d]))}assetsBuffered(e,t){return e.event.assetList.length===0?!1:!e.event.assetList.some(r=>{const n=this.getAssetPlayer(r.identifier);return!(n!=null&&n.bufferedInPlaceToEnd(t))})}setBufferingItem(e){const t=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(e,t)&&r){const{items:n,events:s}=r;if(!n||!s)return t;const a=this.isInterstitial(e),c=this.getBufferingPlayer();this.bufferingItem=e,this.bufferedPos=Math.max(e.start,Math.min(e.end,this.timelinePos));const d=c?c.remaining:t?t.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${pn(e)}`+(t?` (${d.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(a){const u=r.findAssetIndex(e.event,this.bufferedPos);e.event.assetList.forEach((f,h)=>{const m=this.getAssetPlayer(f.identifier);m&&(h===u&&m.loadSource(),m.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(u=>u.pauseBuffering());this.hls.trigger($.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:s.slice(0),schedule:n.slice(0),bufferingIndex:this.findItemIndex(e),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==e&&(this.bufferingItem=e);return t}bufferedToItem(e,t=0){const r=this.setBufferingItem(e);if(!this.playbackDisabled){if(this.isInterstitial(e))this.bufferedToEvent(e,t);else if(r!==null){this.bufferingAsset=null;const n=this.detachedData;n?n.mediaSource?this.attachPrimary(e.start,e,!0):this.preloadPrimary(e):this.preloadPrimary(e)}}}preloadPrimary(e){const t=this.findItemIndex(e),r=this.getPrimaryResumption(e,t);this.startLoadingPrimaryAt(r)}bufferedToEvent(e,t){const r=e.event,n=r.assetList.length===0&&!r.assetListLoader,s=r.cue.once;if(n||!s){const a=this.preloadAssets(r,t);if(a!=null&&a.interstitial.appendInPlace){const c=this.primaryMedia;c&&this.bufferAssetPlayer(a,c)}}}preloadAssets(e,t){const r=e.assetUrl,n=e.assetList.length,s=n===0&&!e.assetListLoader,a=e.cue.once;if(s){const d=e.timelineStart;if(e.appendInPlace){var c;const m=this.playingItem;!this.isInterstitial(m)&&(m==null||(c=m.nextEvent)==null?void 0:c.identifier)===e.identifier&&this.flushFrontBuffer(d+.25)}let u,f=0;if(!this.playingItem&&this.primaryLive&&(f=this.hls.startPosition,f===-1&&(f=this.hls.liveSyncPosition||0)),f&&!(e.cue.pre||e.cue.post)){const m=f-d;m>0&&(u=Math.round(m*1e3)/1e3)}if(this.log(`Load interstitial asset ${t+1}/${r?1:n} ${e}${u?` live-start: ${f} start-offset: ${u}`:""}`),r)return this.createAsset(e,0,0,d,e.duration,r);const h=this.assetListLoader.loadAssetList(e,u);h&&(e.assetListLoader=h)}else if(!a&&n){for(let u=t;u<n;u++){const f=e.assetList[u],h=this.getAssetPlayerQueueIndex(f.identifier);(h===-1||this.playerQueue[h].destroyed)&&!f.error&&this.createAssetPlayer(e,f,u)}const d=e.assetList[t];if(d){const u=this.getAssetPlayer(d.identifier);return u&&u.loadSource(),u}}return null}flushFrontBuffer(e){const t=this.requiredTracks;t&&(this.log(`Removing front buffer starting at ${e}`),Object.keys(t).forEach(r=>{this.hls.trigger($.BUFFER_FLUSHING,{startOffset:e,endOffset:1/0,type:r})}))}getAssetPlayerQueueIndex(e){const t=this.playerQueue;for(let r=0;r<t.length;r++)if(e===t[r].assetId)return r;return-1}getAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);return this.playerQueue[t]||null}getBufferingPlayer(){const{playerQueue:e,primaryMedia:t}=this;if(t){for(let r=0;r<e.length;r++)if(e[r].media===t)return e[r]}return null}createAsset(e,t,r,n,s,a){const c={parentIdentifier:e.identifier,identifier:XZ(e,a,t),duration:s,startOffset:r,timelineStart:n,uri:a};return this.createAssetPlayer(e,c,t)}createAssetPlayer(e,t,r){const n=this.hls,s=n.userConfig;let a=s.videoPreference;const c=n.loadLevelObj||n.levels[n.currentLevel];(a||c)&&(a=Ft({},a),c.videoCodec&&(a.videoCodec=c.videoCodec),c.videoRange&&(a.allowedVideoRanges=[c.videoRange]));const d=n.audioTracks[n.audioTrack],u=n.subtitleTracks[n.subtitleTrack];let f=0;if(this.primaryLive||e.appendInPlace){const N=this.timelinePos-t.timelineStart;if(N>1){const O=t.duration;O&&N<O&&(f=N)}}const h=t.identifier,m=Mt(Mt({},s),{},{maxMaxBufferLength:Math.min(180,n.config.maxMaxBufferLength),autoStartLoad:!0,startFragPrefetch:!0,primarySessionId:n.sessionId,assetPlayerId:h,abrEwmaDefaultEstimate:n.bandwidthEstimate,interstitialsController:void 0,startPosition:f,liveDurationInfinity:!1,testBandwidth:!1,videoPreference:a,audioPreference:d||s.audioPreference,subtitlePreference:u||s.subtitlePreference});e.appendInPlace&&(e.appendInPlaceStarted=!0,t.timelineStart&&(m.timelineOffset=t.timelineStart));const g=m.cmcd;g!=null&&g.sessionId&&g.contentId&&(m.cmcd=Ft({},g,{contentId:Lo(t.uri)})),this.getAssetPlayer(h)&&this.warn(`Duplicate date range identifier ${e} and asset ${h}`);const p=new tV(this.HlsPlayerClass,m,e,t);this.playerQueue.push(p),e.assetList[r]=t;let y=!0;const S=N=>{if(N.live){var O;const K=new Error(`Interstitials MUST be VOD assets ${e}`),G={fatal:!0,type:it.OTHER_ERROR,details:fe.INTERSTITIAL_ASSET_ITEM_ERROR,error:K},X=((O=this.schedule)==null?void 0:O.findEventIndex(e.identifier))||-1;this.handleAssetItemError(G,e,X,r,K.message);return}const U=N.edge-N.fragmentStart,z=t.duration;(y||z===null||U>z)&&(y=!1,this.log(`Interstitial asset "${h}" duration change ${z} > ${U}`),t.duration=U,this.updateSchedule())};p.on($.LEVEL_UPDATED,(N,{details:O})=>S(O)),p.on($.LEVEL_PTS_UPDATED,(N,{details:O})=>S(O)),p.on($.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const E=(N,O)=>{const U=this.getAssetPlayer(h);if(U&&O.tracks){U.off($.BUFFER_CODECS,E),U.tracks=O.tracks;const z=this.primaryMedia;this.bufferingAsset===U.assetItem&&z&&!U.media&&this.bufferAssetPlayer(U,z)}};p.on($.BUFFER_CODECS,E);const T=()=>{var N;const O=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${O}`),!O||!this.schedule)return;const U=this.schedule.findEventIndex(e.identifier),z=(N=this.schedule.items)==null?void 0:N[U];this.isInterstitial(z)&&this.advanceAssetBuffering(z,t)};p.on($.BUFFERED_TO_END,T);const j=N=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const O=this.schedule.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,O,N)};return p.once($.MEDIA_ENDED,j(r)),p.once($.PLAYOUT_LIMIT_REACHED,j(1/0)),p.on($.ERROR,(N,O)=>{if(!this.schedule)return;const U=this.getAssetPlayer(h);if(O.details===fe.BUFFER_STALLED_ERROR){if(U!=null&&U.appendInPlace){this.handleInPlaceStall(e);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(O,e,this.schedule.findEventIndex(e.identifier),r,`Asset player error ${O.error} ${e}`)}),p.on($.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const N=new Error(`Asset player destroyed unexpectedly ${h}`),O={fatal:!0,type:it.OTHER_ERROR,details:fe.INTERSTITIAL_ASSET_ITEM_ERROR,error:N};this.handleAssetItemError(O,e,this.schedule.findEventIndex(e.identifier),r,N.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Ns(t)}`),this.hls.trigger($.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:t,assetListIndex:r,event:e,player:p}),p}clearInterstitial(e,t){this.clearAssetPlayers(e,t),e.reset()}clearAssetPlayers(e,t){e.assetList.forEach(r=>{this.clearAssetPlayer(r.identifier,t)})}resetAssetPlayer(e){const t=this.getAssetPlayerQueueIndex(e);if(t!==-1){this.log(`reset asset player "${e}" after error`);const r=this.playerQueue[t];this.transferMediaFromPlayer(r,null),r.resetDetails()}}clearAssetPlayer(e,t){const r=this.getAssetPlayerQueueIndex(e);if(r!==-1){const n=this.playerQueue[r];this.log(`clear ${n} toSegment: ${t&&pn(t)}`),this.transferMediaFromPlayer(n,t),this.playerQueue.splice(r,1),n.destroy()}}emptyPlayerQueue(){let e;for(;e=this.playerQueue.pop();)e.destroy();this.playerQueue=[]}startAssetPlayer(e,t,r,n,s){const{interstitial:a,assetItem:c,assetId:d}=e,u=a.assetList.length,f=this.playingAsset;this.endedAsset=null,this.playingAsset=c,(!f||f.identifier!==d)&&(f&&(this.clearAssetPlayer(f.identifier,r[n]),delete f.error),this.log(`INTERSTITIAL_ASSET_STARTED ${t+1}/${u} ${Ns(c)}`),this.hls.trigger($.INTERSTITIAL_ASSET_STARTED,{asset:c,assetListIndex:t,event:a,schedule:r.slice(0),scheduleIndex:n,player:e})),this.bufferAssetPlayer(e,s)}bufferAssetPlayer(e,t){var r,n;if(!this.schedule)return;const{interstitial:s,assetItem:a}=e,c=this.schedule.findEventIndex(s.identifier),d=(r=this.schedule.items)==null?void 0:r[c];if(!d)return;e.loadSource(),this.setBufferingItem(d),this.bufferingAsset=a;const u=this.getBufferingPlayer();if(u===e)return;const f=s.appendInPlace;if(f&&u?.interstitial.appendInPlace===!1)return;const h=u?.tracks||((n=this.detachedData)==null?void 0:n.tracks)||this.requiredTracks;if(f&&a!==this.playingAsset){if(!e.tracks){this.log(`Waiting for track info before buffering ${e}`);return}if(h&&!eS(h,e.tracks)){const m=new Error(`Asset ${Ns(a)} SourceBuffer tracks ('${Object.keys(e.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),g={fatal:!0,type:it.OTHER_ERROR,details:fe.INTERSTITIAL_ASSET_ITEM_ERROR,error:m},p=s.findAssetIndex(a);this.handleAssetItemError(g,s,c,p,m.message);return}}this.transferMediaTo(e,t)}handleInPlaceStall(e){const t=this.schedule,r=this.primaryMedia;if(!t||!r)return;const n=r.currentTime,s=t.findAssetIndex(e,n),a=e.assetList[s];if(a){const c=this.getAssetPlayer(a.identifier);if(c){const d=c.currentTime||n-a.timelineStart,u=c.duration-d;if(this.warn(`Stalled at ${d} of ${d+u} in ${c} ${e} (media.currentTime: ${n})`),d&&(u/r.playbackRate<.5||c.bufferedInPlaceToEnd(r))&&c.hls){const f=t.findEventIndex(e.identifier);this.advanceAfterAssetEnded(e,f,s)}}}}advanceInPlace(e){const t=this.primaryMedia;t&&t.currentTime<e&&(t.currentTime=e)}handleAssetItemError(e,t,r,n,s){if(e.details===fe.BUFFER_STALLED_ERROR)return;const a=t.assetList[n]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${a&&Ns(a)} ${e.error}`),!this.schedule)return;const c=a?.identifier||"",d=this.getAssetPlayerQueueIndex(c),u=this.playerQueue[d]||null,f=this.schedule.items,h=Ft({},e,{fatal:!1,errorAction:ws(!0),asset:a,assetListIndex:n,event:t,schedule:f,scheduleIndex:r,player:u});if(this.hls.trigger($.INTERSTITIAL_ASSET_ERROR,h),!e.fatal)return;const m=this.playingAsset,g=this.bufferingAsset,p=new Error(s);if(a&&(this.clearAssetPlayer(c,null),a.error=p),!t.assetList.some(y=>!y.error))t.error=p;else for(let y=n;y<t.assetList.length;y++)this.resetAssetPlayer(t.assetList[y].identifier);this.updateSchedule(!0),t.error?this.primaryFallback(t):m&&m.identifier===c?this.advanceAfterAssetEnded(t,r,n):g&&g.identifier===c&&this.isInterstitial(this.bufferingItem)&&this.advanceAssetBuffering(this.bufferingItem,g)}primaryFallback(e){const t=e.timelineStart,r=this.effectivePlayingItem;let n=this.timelinePos;if(r){this.log(`Fallback to primary from event "${e.identifier}" start: ${t} pos: ${n} playing: ${pn(r)} error: ${e.error}`),n===-1&&(n=this.hls.startPosition);const a=this.updateItem(r,n);this.itemsMatch(r,a)&&this.clearInterstitial(e,null),e.appendInPlace&&(this.attachPrimary(t,null),this.flushFrontBuffer(t))}else if(n===-1){this.checkStart();return}if(!this.schedule)return;const s=this.schedule.findItemIndexAtTime(n);this.setSchedulePosition(s)}onAssetListLoaded(e,t){var r,n;const s=t.event,a=s.identifier,c=t.assetListResponse.ASSETS;if(!((r=this.schedule)!=null&&r.hasEvent(a)))return;const d=s.timelineStart,u=s.duration;let f=0;c.forEach((y,S)=>{const E=parseFloat(y.DURATION);this.createAsset(s,S,f,d+f,E,y.URI),f+=E}),s.duration=f,this.log(`Loaded asset-list with duration: ${f} (was: ${u}) ${s}`);const h=this.waitingItem,m=h?.event.identifier===a;this.updateSchedule();const g=(n=this.bufferingItem)==null?void 0:n.event;if(m){var p;const y=this.schedule.findEventIndex(a),S=(p=this.schedule.items)==null?void 0:p[y];if(S){if(!this.playingItem&&this.timelinePos>S.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==y){s.error=new Error(`Interstitial ${c.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${s}`),this.log(s.error.message),this.updateSchedule(!0),this.primaryFallback(s);return}this.setBufferingItem(S)}this.setSchedulePosition(y)}else if(g?.identifier===a){const y=s.assetList[0];if(y){const S=this.getAssetPlayer(y.identifier);if(g.appendInPlace){const E=this.primaryMedia;S&&E&&this.bufferAssetPlayer(S,E)}else S&&S.loadSource()}}}onError(e,t){if(this.schedule)switch(t.details){case fe.ASSET_LIST_PARSING_ERROR:case fe.ASSET_LIST_LOAD_ERROR:case fe.ASSET_LIST_LOAD_TIMEOUT:{const r=t.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case fe.BUFFER_STALLED_ERROR:{const r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace){this.handleInPlaceStall(r.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}},__=500,sV=class extends ym{constructor(e,t,r){super(e,t,r,"subtitle-stream-controller",Je.SUBTITLE),this.currentTrackId=-1,this.tracksBuffered=[],this.mainDetails=null,this.registerListeners()}onHandlerDestroying(){this.unregisterListeners(),super.onHandlerDestroying(),this.mainDetails=null}registerListeners(){super.registerListeners();const{hls:e}=this;e.on($.LEVEL_LOADED,this.onLevelLoaded,this),e.on($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.on($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on($.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.on($.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off($.LEVEL_LOADED,this.onLevelLoaded,this),e.off($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off($.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),e.off($.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off($.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),e.off($.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(e,t){this.stopLoad(),this.state=Ne.IDLE,this.setInterval(__),this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(e,t){this.tracksBuffered=[],super.onMediaDetaching(e,t)}onLevelLoaded(e,t){this.mainDetails=t.details}onSubtitleFragProcessed(e,t){const{frag:r,success:n}=t;if(this.fragContextChanged(r)||(ar(r)&&(this.fragPrevious=r),this.state=Ne.IDLE),!n)return;const s=this.tracksBuffered[this.currentTrackId];if(!s)return;let a;const c=r.start;for(let u=0;u<s.length;u++)if(c>=s[u].start&&c<=s[u].end){a=s[u];break}const d=r.start+r.duration;a?a.end=d:(a={start:c,end:d},s.push(a)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(e,t){const{startOffset:r,endOffset:n}=t;if(r===0&&n!==Number.POSITIVE_INFINITY){const s=n-1;if(s<=0)return;t.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach(a=>{for(let c=0;c<a.length;){if(a[c].end<=s){a.shift();continue}else if(a[c].start<s)a[c].start=s;else break;c++}}),this.fragmentTracker.removeFragmentsInRange(r,s,Je.SUBTITLE)}}onError(e,t){const r=t.frag;r?.type===Je.SUBTITLE&&(t.details===fe.FRAG_GAP&&this.fragmentTracker.fragBuffered(r,!0),this.fragCurrent&&this.fragCurrent.abortRequests(),this.state!==Ne.STOPPED&&(this.state=Ne.IDLE))}onSubtitleTracksUpdated(e,{subtitleTracks:t}){if(this.levels&&Q1(this.levels,t)){this.levels=t.map(r=>new Co(r));return}this.tracksBuffered=[],this.levels=t.map(r=>{const n=new Co(r);return this.tracksBuffered[n.id]=[],n}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Je.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,t){var r;if(this.currentTrackId=t.id,!((r=this.levels)!=null&&r.length)||this.currentTrackId===-1){this.clearInterval();return}const n=this.levels[this.currentTrackId];n!=null&&n.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,n&&this.state!==Ne.STOPPED&&this.setInterval(__)}onSubtitleTrackLoaded(e,t){var r;const{currentTrackId:n,levels:s}=this,{details:a,id:c}=t;if(!s){this.warn(`Subtitle tracks were reset while loading level ${c}`);return}const d=s[c];if(c>=s.length||!d)return;this.log(`Subtitle track ${c} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let u=0;if(a.live||(r=d.details)!=null&&r.live){if(a.deltaUpdateFailed)return;const h=this.mainDetails;if(!h){this.startFragRequested=!1;return}const m=h.fragments[0];if(!d.details)a.hasProgramDateTime&&h.hasProgramDateTime?(_c(a,h),u=a.fragmentStart):m&&(u=m.start,bm(a,u));else{var f;u=this.alignPlaylists(a,d.details,(f=this.levelLastLoaded)==null?void 0:f.details),u===0&&m&&(u=m.start,bm(a,u))}h&&!this.startFragRequested&&this.setStartPosition(h,u)}d.details=a,this.levelLastLoaded=d,c===n&&(this.hls.trigger($.SUBTITLE_TRACK_UPDATED,{details:a,id:c,groupId:t.groupId}),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===Ne.IDLE&&(Fi(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),d.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:t,payload:r}=e,n=t.decryptdata,s=this.hls;if(!this.fragContextChanged(t)&&r&&r.byteLength>0&&n!=null&&n.key&&n.iv&&ks(n.method)){const a=performance.now();this.decrypter.decrypt(new Uint8Array(r),n.key.buffer,n.iv.buffer,dm(n.method)).catch(c=>{throw s.trigger($.ERROR,{type:it.MEDIA_ERROR,details:fe.FRAG_DECRYPT_ERROR,fatal:!1,error:c,reason:c.message,frag:t}),c}).then(c=>{const d=performance.now();s.trigger($.FRAG_DECRYPTED,{frag:t,payload:c,stats:{tstart:a,tdecrypt:d}})}).catch(c=>{this.warn(`${c.name}: ${c.message}`),this.state=Ne.IDLE})}}doTick(){if(!this.media){this.state=Ne.IDLE;return}if(this.state===Ne.IDLE){const{currentTrackId:e,levels:t}=this,r=t?.[e];if(!r||!t.length||!r.details||this.waitForLive(r))return;const{config:n}=this,s=this.getLoadPosition(),{end:a,len:c}=xt.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,n.maxBufferHole),d=r.details;if(c>this.hls.maxBufferLength+d.levelTargetDuration)return;const u=d.fragments,f=u.length,h=d.edge;let m=null;const g=this.fragPrevious;if(a<h){const y=n.maxFragLookUpTolerance,S=a>h-y?0:y;m=Fi(g,u,Math.max(u[0].start,a),S),!m&&g&&g.start<u[0].start&&(m=u[0])}else m=u[f-1];if(m=this.filterReplacedPrimary(m,r.details),!m)return;const p=u[m.sn-d.startSN-1];if(p&&p.cc===m.cc&&this.fragmentTracker.getState(p)===pr.NOT_LOADED&&(m=p),this.fragmentTracker.getState(m)===pr.NOT_LOADED){const y=this.mapToInitFragWhenRequired(m);y&&this.loadFragment(y,r,a)}}}loadFragment(e,t,r){ar(e)?super.loadFragment(e,t,r):this._loadInitSegment(e,t)}get mediaBufferTimeRanges(){return new aV(this.tracksBuffered[this.currentTrackId]||[])}},aV=class{constructor(e){this.buffered=void 0;const t=(r,n,s)=>{if(n=n>>>0,n>s-1)throw new DOMException(`Failed to execute '${r}' on 'TimeRanges': The index provided (${n}) is greater than the maximum bound (${s})`);return e[n][r]};this.buffered={get length(){return e.length},end(r){return t("end",r,e.length)},start(r){return t("start",r,e.length)}}}},oV={42:225,92:233,94:237,95:243,96:250,123:231,124:247,125:209,126:241,127:9608,128:174,129:176,130:189,131:191,132:8482,133:162,134:163,135:9834,136:224,137:32,138:232,139:226,140:234,141:238,142:244,143:251,144:193,145:201,146:211,147:218,148:220,149:252,150:8216,151:161,152:42,153:8217,154:9473,155:169,156:8480,157:8226,158:8220,159:8221,160:192,161:194,162:199,163:200,164:202,165:203,166:235,167:206,168:207,169:239,170:212,171:217,172:249,173:219,174:171,175:187,176:195,177:227,178:205,179:204,180:236,181:210,182:242,183:213,184:245,185:123,186:125,187:92,188:94,189:95,190:124,191:8764,192:196,193:228,194:214,195:246,196:223,197:165,198:164,199:9475,200:197,201:229,202:216,203:248,204:9487,205:9491,206:9495,207:9499},w_=e=>String.fromCharCode(oV[e]||e),vn=15,Kn=100,lV={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},cV={17:2,18:4,21:6,22:8,23:10,19:13,20:15},uV={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},dV={25:2,26:4,29:6,30:8,31:10,27:13,28:15},fV=["white","green","blue","cyan","red","yellow","magenta","black","transparent"],hV=class{constructor(){this.time=null,this.verboseLevel=0}log(e,t){if(this.verboseLevel>=e){const r=typeof t=="function"?t():t;$t.log(`${this.time} [${e}] ${r}`)}}},zi=function(t){const r=[];for(let n=0;n<t.length;n++)r.push(t[n].toString(16));return r},E_=class{constructor(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}reset(){this.foreground="white",this.underline=!1,this.italics=!1,this.background="black",this.flash=!1}setStyles(e){const t=["foreground","underline","italics","background","flash"];for(let r=0;r<t.length;r++){const n=t[r];e.hasOwnProperty(n)&&(this[n]=e[n])}}isDefault(){return this.foreground==="white"&&!this.underline&&!this.italics&&this.background==="black"&&!this.flash}equals(e){return this.foreground===e.foreground&&this.underline===e.underline&&this.italics===e.italics&&this.background===e.background&&this.flash===e.flash}copy(e){this.foreground=e.foreground,this.underline=e.underline,this.italics=e.italics,this.background=e.background,this.flash=e.flash}toString(){return"color="+this.foreground+", underline="+this.underline+", italics="+this.italics+", background="+this.background+", flash="+this.flash}},mV=class{constructor(){this.uchar=" ",this.penState=new E_}reset(){this.uchar=" ",this.penState.reset()}setChar(e,t){this.uchar=e,this.penState.copy(t)}setPenState(e){this.penState.copy(e)}equals(e){return this.uchar===e.uchar&&this.penState.equals(e.penState)}copy(e){this.uchar=e.uchar,this.penState.copy(e.penState)}isEmpty(){return this.uchar===" "&&this.penState.isDefault()}},gV=class{constructor(e){this.chars=[],this.pos=0,this.currPenState=new E_,this.cueStartTime=null,this.logger=void 0;for(let t=0;t<Kn;t++)this.chars.push(new mV);this.logger=e}equals(e){for(let t=0;t<Kn;t++)if(!this.chars[t].equals(e.chars[t]))return!1;return!0}copy(e){for(let t=0;t<Kn;t++)this.chars[t].copy(e.chars[t])}isEmpty(){let e=!0;for(let t=0;t<Kn;t++)if(!this.chars[t].isEmpty()){e=!1;break}return e}setCursor(e){this.pos!==e&&(this.pos=e),this.pos<0?(this.logger.log(3,"Negative cursor position "+this.pos),this.pos=0):this.pos>Kn&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Kn)}moveCursor(e){const t=this.pos+e;if(e>1)for(let r=this.pos+1;r<t+1;r++)this.chars[r].setPenState(this.currPenState);this.setCursor(t)}backSpace(){this.moveCursor(-1),this.chars[this.pos].setChar(" ",this.currPenState)}insertChar(e){e>=144&&this.backSpace();const t=w_(e);if(this.pos>=Kn){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+t+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(t,this.currPenState),this.moveCursor(1)}clearFromPos(e){let t;for(t=e;t<Kn;t++)this.chars[t].reset()}clear(){this.clearFromPos(0),this.pos=0,this.currPenState.reset()}clearToEndOfRow(){this.clearFromPos(this.pos)}getTextString(){const e=[];let t=!0;for(let r=0;r<Kn;r++){const n=this.chars[r].uchar;n!==" "&&(t=!1),e.push(n)}return t?"":e.join("")}setPenStyles(e){this.currPenState.setStyles(e),this.chars[this.pos].setPenState(this.currPenState)}},Vm=class{constructor(e){this.rows=[],this.currRow=vn-1,this.nrRollUpRows=null,this.lastOutputScreen=null,this.logger=void 0;for(let t=0;t<vn;t++)this.rows.push(new gV(e));this.logger=e}reset(){for(let e=0;e<vn;e++)this.rows[e].clear();this.currRow=vn-1}equals(e){let t=!0;for(let r=0;r<vn;r++)if(!this.rows[r].equals(e.rows[r])){t=!1;break}return t}copy(e){for(let t=0;t<vn;t++)this.rows[t].copy(e.rows[t])}isEmpty(){let e=!0;for(let t=0;t<vn;t++)if(!this.rows[t].isEmpty()){e=!1;break}return e}backSpace(){this.rows[this.currRow].backSpace()}clearToEndOfRow(){this.rows[this.currRow].clearToEndOfRow()}insertChar(e){this.rows[this.currRow].insertChar(e)}setPen(e){this.rows[this.currRow].setPenStyles(e)}moveCursor(e){this.rows[this.currRow].moveCursor(e)}setCursor(e){this.logger.log(2,"setCursor: "+e),this.rows[this.currRow].setCursor(e)}setPAC(e){this.logger.log(2,()=>"pacData = "+zt(e));let t=e.row-1;if(this.nrRollUpRows&&t<this.nrRollUpRows-1&&(t=this.nrRollUpRows-1),this.nrRollUpRows&&this.currRow!==t){for(let c=0;c<vn;c++)this.rows[c].clear();const s=this.currRow+1-this.nrRollUpRows,a=this.lastOutputScreen;if(a){const c=a.rows[s].cueStartTime,d=this.logger.time;if(c!==null&&d!==null&&c<d)for(let u=0;u<this.nrRollUpRows;u++)this.rows[t-this.nrRollUpRows+u+1].copy(a.rows[s+u])}}this.currRow=t;const r=this.rows[this.currRow];if(e.indent!==null){const s=e.indent,a=Math.max(s-1,0);r.setCursor(e.indent),e.color=r.chars[a].penState.foreground}const n={foreground:e.color,underline:e.underline,italics:e.italics,background:"black",flash:!1};this.setPen(n)}setBkgData(e){this.logger.log(2,()=>"bkgData = "+zt(e)),this.backSpace(),this.setPen(e),this.insertChar(32)}setRollUpRows(e){this.nrRollUpRows=e}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const e=this.currRow+1-this.nrRollUpRows,t=this.rows.splice(e,1)[0];t.clear(),this.rows.splice(this.currRow,0,t),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const t=[];let r="",n=-1;for(let s=0;s<vn;s++){const a=this.rows[s].getTextString();a&&(n=s+1,e?t.push("Row "+n+": '"+a+"'"):t.push(a.trim()))}return t.length>0&&(e?r="["+t.join(" | ")+"]":r=t.join(`
178
+ `)),r}getTextAndFormat(){return this.rows}},k_=class{constructor(e,t,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=t,this.mode=null,this.verbose=0,this.displayedMemory=new Vm(r),this.nonDisplayedMemory=new Vm(r),this.lastOutputScreen=new Vm(r),this.currRollUpRow=this.displayedMemory.rows[vn-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[vn-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(e){this.outputFilter=e}setPAC(e){this.writeScreen.setPAC(e)}setBkgData(e){this.writeScreen.setBkgData(e)}setMode(e){e!==this.mode&&(this.mode=e,this.logger.log(2,()=>"MODE="+e),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=e)}insertChars(e){for(let r=0;r<e.length;r++)this.writeScreen.insertChar(e[r]);const t=this.writeScreen===this.displayedMemory?"DISP":"NON_DISP";this.logger.log(2,()=>t+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(e){this.logger.log(2,"RU("+e+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(e)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const e=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=e,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(e){this.logger.log(2,"TO("+e+") - Tab Offset"),this.writeScreen.moveCursor(e)}ccMIDROW(e){const t={flash:!1};t.underline=e%2===1,t.italics=e>=46,t.italics?t.foreground="white":t.foreground=["white","green","blue","cyan","red","yellow","magenta"][Math.floor(e/2)-16],this.logger.log(2,"MIDROW: "+zt(t)),this.writeScreen.setPen(t)}outputDataUpdate(e=!1){const t=this.logger.time;t!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=t:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,t,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:t),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(e){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,e,this.displayedMemory),this.cueStartTime=e))}},T_=class{constructor(e,t,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=vV(),this.logger=void 0;const n=this.logger=new hV;this.channels=[null,new k_(e,t,n),new k_(e+1,r,n)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,t){this.channels[e].setHandler(t)}addData(e,t){this.logger.time=e;for(let r=0;r<t.length;r+=2){const n=t[r]&127,s=t[r+1]&127;let a=!1,c=null;if(n===0&&s===0)continue;this.logger.log(3,()=>"["+zi([t[r],t[r+1]])+"] -> ("+zi([n,s])+")");const d=this.cmdHistory;if(n>=16&&n<=31){if(pV(n,s,d)){Rc(null,null,d),this.logger.log(3,()=>"Repeated command ("+zi([n,s])+") is dropped");continue}Rc(n,s,this.cmdHistory),a=this.parseCmd(n,s),a||(a=this.parseMidrow(n,s)),a||(a=this.parsePAC(n,s)),a||(a=this.parseBackgroundAttributes(n,s))}else Rc(null,null,d);if(!a&&(c=this.parseChars(n,s),c)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(c):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!c&&this.logger.log(2,()=>"Couldn't parse cleaned data "+zi([n,s])+" orig: "+zi([t[r],t[r+1]]))}}parseCmd(e,t){if(!((e===20||e===28||e===21||e===29)&&t>=32&&t<=47||(e===23||e===31)&&t>=33&&t<=35))return!1;const r=e===20||e===21||e===23?1:2,n=this.channels[r];return e===20||e===21||e===28||e===29?t===32?n.ccRCL():t===33?n.ccBS():t===34?n.ccAOF():t===35?n.ccAON():t===36?n.ccDER():t===37?n.ccRU(2):t===38?n.ccRU(3):t===39?n.ccRU(4):t===40?n.ccFON():t===41?n.ccRDC():t===42?n.ccTR():t===43?n.ccRTD():t===44?n.ccEDM():t===45?n.ccCR():t===46?n.ccENM():t===47&&n.ccEOC():n.ccTO(t-32),this.currentChannel=r,!0}parseMidrow(e,t){let r=0;if((e===17||e===25)&&t>=32&&t<=47){if(e===17?r=1:r=2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const n=this.channels[r];return n?(n.ccMIDROW(t),this.logger.log(3,()=>"MIDROW ("+zi([e,t])+")"),!0):!1}return!1}parsePAC(e,t){let r;if(!((e>=17&&e<=23||e>=25&&e<=31)&&t>=64&&t<=127||(e===16||e===24)&&t>=64&&t<=95))return!1;const n=e<=23?1:2;t>=64&&t<=95?r=n===1?lV[e]:uV[e]:r=n===1?cV[e]:dV[e];const s=this.channels[n];return s?(s.setPAC(this.interpretPAC(r,t)),this.currentChannel=n,!0):!1}interpretPAC(e,t){let r;const n={color:null,italics:!1,indent:null,underline:!1,row:e};return t>95?r=t-96:r=t-64,n.underline=(r&1)===1,r<=13?n.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(n.italics=!0,n.color="white"):n.indent=Math.floor((r-16)/2)*4,n}parseChars(e,t){let r,n=null,s=null;if(e>=25?(r=2,s=e-8):(r=1,s=e),s>=17&&s<=19){let a;s===17?a=t+80:s===18?a=t+112:a=t+144,this.logger.log(2,()=>"Special char '"+w_(a)+"' in channel "+r),n=[a]}else e>=32&&e<=127&&(n=t===0?[e]:[e,t]);return n&&this.logger.log(3,()=>"Char codes = "+zi(n).join(",")),n}parseBackgroundAttributes(e,t){if(!((e===16||e===24)&&t>=32&&t<=47||(e===23||e===31)&&t>=45&&t<=47))return!1;let r;const n={};e===16||e===24?(r=Math.floor((t-32)/2),n.background=fV[r],t%2===1&&(n.background=n.background+"_semi")):t===45?n.background="transparent":(n.foreground="black",t===47&&(n.underline=!0));const s=e<=23?1:2;return this.channels[s].setBkgData(n),!0}reset(){for(let e=0;e<Object.keys(this.channels).length;e++){const t=this.channels[e];t&&t.reset()}Rc(null,null,this.cmdHistory)}cueSplitAtTime(e){for(let t=0;t<this.channels.length;t++){const r=this.channels[t];r&&r.cueSplitAtTime(e)}}};function Rc(e,t,r){r.a=e,r.b=t}function pV(e,t,r){return r.a===e&&r.b===t}function vV(){return{a:null,b:null}}var Hm=(function(){if(yc!=null&&yc.VTTCue)return self.VTTCue;const e=["","lr","rl"],t=["start","middle","end","left","right"];function r(d,u){if(typeof u!="string"||!Array.isArray(d))return!1;const f=u.toLowerCase();return~d.indexOf(f)?f:!1}function n(d){return r(e,d)}function s(d){return r(t,d)}function a(d,...u){let f=1;for(;f<arguments.length;f++){const h=arguments[f];for(const m in h)d[m]=h[m]}return d}function c(d,u,f){const h=this,m={enumerable:!0};h.hasBeenReset=!1;let g="",p=!1,y=d,S=u,E=f,T=null,j="",N=!0,O="auto",U="start",z=50,K="middle",G=50,X="middle";Object.defineProperty(h,"id",a({},m,{get:function(){return g},set:function(te){g=""+te}})),Object.defineProperty(h,"pauseOnExit",a({},m,{get:function(){return p},set:function(te){p=!!te}})),Object.defineProperty(h,"startTime",a({},m,{get:function(){return y},set:function(te){if(typeof te!="number")throw new TypeError("Start time must be set to a number.");y=te,this.hasBeenReset=!0}})),Object.defineProperty(h,"endTime",a({},m,{get:function(){return S},set:function(te){if(typeof te!="number")throw new TypeError("End time must be set to a number.");S=te,this.hasBeenReset=!0}})),Object.defineProperty(h,"text",a({},m,{get:function(){return E},set:function(te){E=""+te,this.hasBeenReset=!0}})),Object.defineProperty(h,"region",a({},m,{get:function(){return T},set:function(te){T=te,this.hasBeenReset=!0}})),Object.defineProperty(h,"vertical",a({},m,{get:function(){return j},set:function(te){const ne=n(te);if(ne===!1)throw new SyntaxError("An invalid or illegal string was specified.");j=ne,this.hasBeenReset=!0}})),Object.defineProperty(h,"snapToLines",a({},m,{get:function(){return N},set:function(te){N=!!te,this.hasBeenReset=!0}})),Object.defineProperty(h,"line",a({},m,{get:function(){return O},set:function(te){if(typeof te!="number"&&te!=="auto")throw new SyntaxError("An invalid number or illegal string was specified.");O=te,this.hasBeenReset=!0}})),Object.defineProperty(h,"lineAlign",a({},m,{get:function(){return U},set:function(te){const ne=s(te);if(!ne)throw new SyntaxError("An invalid or illegal string was specified.");U=ne,this.hasBeenReset=!0}})),Object.defineProperty(h,"position",a({},m,{get:function(){return z},set:function(te){if(te<0||te>100)throw new Error("Position must be between 0 and 100.");z=te,this.hasBeenReset=!0}})),Object.defineProperty(h,"positionAlign",a({},m,{get:function(){return K},set:function(te){const ne=s(te);if(!ne)throw new SyntaxError("An invalid or illegal string was specified.");K=ne,this.hasBeenReset=!0}})),Object.defineProperty(h,"size",a({},m,{get:function(){return G},set:function(te){if(te<0||te>100)throw new Error("Size must be between 0 and 100.");G=te,this.hasBeenReset=!0}})),Object.defineProperty(h,"align",a({},m,{get:function(){return X},set:function(te){const ne=s(te);if(!ne)throw new SyntaxError("An invalid or illegal string was specified.");X=ne,this.hasBeenReset=!0}})),h.displayState=void 0}return c.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},c})(),bV=class{decode(e,t){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}};function C_(e){function t(n,s,a,c){return(n|0)*3600+(s|0)*60+(a|0)+parseFloat(c||0)}const r=e.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?t(r[2],r[3],0,r[4]):t(r[1],r[2],r[3],r[4]):null}var yV=class{constructor(){this.values=Object.create(null)}set(e,t){!this.get(e)&&t!==""&&(this.values[e]=t)}get(e,t,r){return r?this.has(e)?this.values[e]:t[r]:this.has(e)?this.values[e]:t}has(e){return e in this.values}alt(e,t,r){for(let n=0;n<r.length;++n)if(t===r[n]){this.set(e,t);break}}integer(e,t){/^-?\d+$/.test(t)&&this.set(e,parseInt(t,10))}percent(e,t){if(/^([\d]{1,3})(\.[\d]*)?%$/.test(t)){const r=parseFloat(t);if(r>=0&&r<=100)return this.set(e,r),!0}return!1}};function I_(e,t,r,n){const s=n?e.split(n):[e];for(const a in s){if(typeof s[a]!="string")continue;const c=s[a].split(r);if(c.length!==2)continue;const d=c[0],u=c[1];t(d,u)}}var Km=new Hm(0,0,""),Lc=Km.align==="middle"?"middle":"center";function xV(e,t,r){const n=e;function s(){const d=C_(e);if(d===null)throw new Error("Malformed timestamp: "+n);return e=e.replace(/^[^\sa-zA-Z-]+/,""),d}function a(d,u){const f=new yV;I_(d,function(g,p){let y;switch(g){case"region":for(let S=r.length-1;S>=0;S--)if(r[S].id===p){f.set(g,r[S].region);break}break;case"vertical":f.alt(g,p,["rl","lr"]);break;case"line":y=p.split(","),f.integer(g,y[0]),f.percent(g,y[0])&&f.set("snapToLines",!1),f.alt(g,y[0],["auto"]),y.length===2&&f.alt("lineAlign",y[1],["start",Lc,"end"]);break;case"position":y=p.split(","),f.percent(g,y[0]),y.length===2&&f.alt("positionAlign",y[1],["start",Lc,"end","line-left","line-right","auto"]);break;case"size":f.percent(g,p);break;case"align":f.alt(g,p,["start",Lc,"end","left","right"]);break}},/:/,/\s/),u.region=f.get("region",null),u.vertical=f.get("vertical","");let h=f.get("line","auto");h==="auto"&&Km.line===-1&&(h=-1),u.line=h,u.lineAlign=f.get("lineAlign","start"),u.snapToLines=f.get("snapToLines",!0),u.size=f.get("size",100),u.align=f.get("align",Lc);let m=f.get("position","auto");m==="auto"&&Km.position===50&&(m=u.align==="start"||u.align==="left"?0:u.align==="end"||u.align==="right"?100:50),u.position=m}function c(){e=e.replace(/^\s+/,"")}if(c(),t.startTime=s(),c(),e.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+n);e=e.slice(3),c(),t.endTime=s(),c(),a(e,t)}function P_(e){return e.replace(/<br(?: \/)?>/gi,`
179
+ `)}var SV=class{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new bV,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const t=this;e&&(t.buffer+=t.decoder.decode(e,{stream:!0}));function r(){let s=t.buffer,a=0;for(s=P_(s);a<s.length&&s[a]!=="\r"&&s[a]!==`
180
+ `;)++a;const c=s.slice(0,a);return s[a]==="\r"&&++a,s[a]===`
181
+ `&&++a,t.buffer=s.slice(a),c}function n(s){I_(s,function(a,c){},/:/)}try{let s="";if(t.state==="INITIAL"){if(!/\r\n|\n/.test(t.buffer))return this;s=r();const c=s.match(/^()?WEBVTT([ \t].*)?$/);if(!(c!=null&&c[0]))throw new Error("Malformed WebVTT signature.");t.state="HEADER"}let a=!1;for(;t.buffer;){if(!/\r\n|\n/.test(t.buffer))return this;switch(a?a=!1:s=r(),t.state){case"HEADER":/:/.test(s)?n(s):s||(t.state="ID");continue;case"NOTE":s||(t.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(s)){t.state="NOTE";break}if(!s)continue;if(t.cue=new Hm(0,0,""),t.state="CUE",s.indexOf("-->")===-1){t.cue.id=s;continue}case"CUE":if(!t.cue){t.state="BADCUE";continue}try{xV(s,t.cue,t.regionList)}catch{t.cue=null,t.state="BADCUE";continue}t.state="CUETEXT";continue;case"CUETEXT":{const c=s.indexOf("-->")!==-1;if(!s||c&&(a=!0)){t.oncue&&t.cue&&t.oncue(t.cue),t.cue=null,t.state="ID";continue}if(t.cue===null)continue;t.cue.text&&(t.cue.text+=`
182
+ `),t.cue.text+=s}continue;case"BADCUE":s||(t.state="ID")}}}catch{t.state==="CUETEXT"&&t.cue&&t.oncue&&t.oncue(t.cue),t.cue=null,t.state=t.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=`
183
+
184
+ `,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(t){e.onparsingerror&&e.onparsingerror(t)}return e.onflush&&e.onflush(),this}},_V=/\r\n|\n\r|\n|\r/g,Wm=function(t,r,n=0){return t.slice(n,n+r.length)===r},wV=function(t){let r=parseInt(t.slice(-3));const n=parseInt(t.slice(-6,-4)),s=parseInt(t.slice(-9,-7)),a=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!Ye(r)||!Ye(n)||!Ye(s)||!Ye(a))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return r+=1e3*n,r+=60*1e3*s,r+=3600*1e3*a,r};function qm(e,t,r){return Lo(e.toString())+Lo(t.toString())+Lo(r)}var EV=function(t,r,n){let s=t[r],a=t[s.prevCC];if(!a||!a.new&&s.new){t.ccOffset=t.presentationOffset=s.start,s.new=!1;return}for(;(c=a)!=null&&c.new;){var c;t.ccOffset+=s.start-a.start,s.new=!1,s=a,a=t[s.prevCC]}t.presentationOffset=n};function kV(e,t,r,n,s,a,c){const d=new SV,u=Gr(new Uint8Array(e)).trim().replace(_V,`
185
+ `).split(`
186
+ `),f=[],h=t?N9(t.baseTime,t.timescale):0;let m="00:00.000",g=0,p=0,y,S=!0;d.oncue=function(E){const T=r[n];let j=r.ccOffset;const N=(g-h)/9e4;if(T!=null&&T.new&&(p!==void 0?j=r.ccOffset=T.start:EV(r,n,N)),N){if(!t){y=new Error("Missing initPTS for VTT MPEGTS");return}j=N-r.presentationOffset}const O=E.endTime-E.startTime,U=Hr((E.startTime+j-p)*9e4,s*9e4)/9e4;E.startTime=Math.max(U,0),E.endTime=Math.max(U+O,0);const z=E.text.trim();E.text=decodeURIComponent(encodeURIComponent(z)),E.id||(E.id=qm(E.startTime,E.endTime,z)),E.endTime>0&&f.push(E)},d.onparsingerror=function(E){y=E},d.onflush=function(){if(y){c(y);return}a(f)},u.forEach(E=>{if(S)if(Wm(E,"X-TIMESTAMP-MAP=")){S=!1,E.slice(16).split(",").forEach(T=>{Wm(T,"LOCAL:")?m=T.slice(6):Wm(T,"MPEGTS:")&&(g=parseInt(T.slice(7)))});try{p=wV(m)/1e3}catch(T){y=T}return}else E===""&&(S=!1);d.parse(E+`
187
+ `)}),d.flush()}var Qm="stpp.ttml.im1t",A_=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,j_=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,TV={left:"start",center:"center",right:"end",start:"start",end:"end"};function N_(e,t,r,n){const s=yt(new Uint8Array(e),["mdat"]);if(s.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const a=s.map(d=>Gr(d)),c=j9(t.baseTime,1,t.timescale);try{a.forEach(d=>r(CV(d,c)))}catch(d){n(d)}}function CV(e,t){const r=new DOMParser().parseFromString(e,"text/xml").getElementsByTagName("tt")[0];if(!r)throw new Error("Invalid ttml");const n={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},s=Object.keys(n).reduce((f,h)=>(f[h]=r.getAttribute(`ttp:${h}`)||n[h],f),{}),a=r.getAttribute("xml:space")!=="preserve",c=D_(Ym(r,"styling","style")),d=D_(Ym(r,"layout","region")),u=Ym(r,"body","[begin]");return[].map.call(u,f=>{const h=M_(f,a);if(!h||!f.hasAttribute("begin"))return null;const m=Jm(f.getAttribute("begin"),s),g=Jm(f.getAttribute("dur"),s);let p=Jm(f.getAttribute("end"),s);if(m===null)throw $_(f);if(p===null){if(g===null)throw $_(f);p=m+g}const y=new Hm(m-t,p-t,h);y.id=qm(y.startTime,y.endTime,y.text);const S=d[f.getAttribute("region")],E=c[f.getAttribute("style")],T=IV(S,E,c),{textAlign:j}=T;if(j){const N=TV[j];N&&(y.lineAlign=N),y.align=j}return Ft(y,T),y}).filter(f=>f!==null)}function Ym(e,t,r){const n=e.getElementsByTagName(t)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function D_(e){return e.reduce((t,r)=>{const n=r.getAttribute("xml:id");return n&&(t[n]=r),t},{})}function M_(e,t){return[].slice.call(e.childNodes).reduce((r,n,s)=>{var a;return n.nodeName==="br"&&s?r+`
188
+ `:(a=n.childNodes)!=null&&a.length?M_(n,t):t?r+n.textContent.trim().replace(/\s+/g," "):r+n.textContent},"")}function IV(e,t,r){const n="http://www.w3.org/ns/ttml#styling";let s=null;const a=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],c=e!=null&&e.hasAttribute("style")?e.getAttribute("style"):null;return c&&r.hasOwnProperty(c)&&(s=r[c]),a.reduce((d,u)=>{const f=Xm(t,n,u)||Xm(e,n,u)||Xm(s,n,u);return f&&(d[u]=f),d},{})}function Xm(e,t,r){return e&&e.hasAttributeNS(t,r)?e.getAttributeNS(t,r):null}function $_(e){return new Error(`Could not parse ttml timestamp ${e}`)}function Jm(e,t){if(!e)return null;let r=C_(e);return r===null&&(A_.test(e)?r=PV(e,t):j_.test(e)&&(r=AV(e,t))),r}function PV(e,t){const r=A_.exec(e),n=(r[4]|0)+(r[5]|0)/t.subFrameRate;return(r[1]|0)*3600+(r[2]|0)*60+(r[3]|0)+n/t.frameRate}function AV(e,t){const r=j_.exec(e),n=Number(r[1]);switch(r[2]){case"h":return n*3600;case"m":return n*60;case"ms":return n*1e3;case"f":return n/t.frameRate;case"t":return n/t.tickRate}return n}var Oc=class{constructor(e,t){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=e,this.trackName=t}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(e,t,r){(this.startTime===null||this.startTime>e)&&(this.startTime=e),this.endTime=t,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}},jV=class{constructor(e){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.textTracks=[],this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=O_(),this.captionsProperties=void 0,this.hls=e,this.config=e.config,this.Cues=e.config.cueHandler,this.captionsProperties={textTrack1:{label:this.config.captionsTextTrack1Label,languageCode:this.config.captionsTextTrack1LanguageCode},textTrack2:{label:this.config.captionsTextTrack2Label,languageCode:this.config.captionsTextTrack2LanguageCode},textTrack3:{label:this.config.captionsTextTrack3Label,languageCode:this.config.captionsTextTrack3LanguageCode},textTrack4:{label:this.config.captionsTextTrack4Label,languageCode:this.config.captionsTextTrack4LanguageCode}},e.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_LOADED,this.onManifestLoaded,this),e.on($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on($.FRAG_LOADING,this.onFragLoading,this),e.on($.FRAG_LOADED,this.onFragLoaded,this),e.on($.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on($.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on($.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on($.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on($.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_LOADED,this.onManifestLoaded,this),e.off($.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off($.FRAG_LOADING,this.onFragLoading,this),e.off($.FRAG_LOADED,this.onFragLoaded,this),e.off($.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off($.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off($.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off($.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const e=new Oc(this,"textTrack1"),t=new Oc(this,"textTrack2"),r=new Oc(this,"textTrack3"),n=new Oc(this,"textTrack4");this.cea608Parser1=new T_(1,e,t),this.cea608Parser2=new T_(3,r,n)}addCues(e,t,r,n,s){let a=!1;for(let c=s.length;c--;){const d=s[c],u=NV(d[0],d[1],t,r);if(u>=0&&(d[0]=Math.min(d[0],t),d[1]=Math.max(d[1],r),a=!0,u/(r-t)>.5))return}if(a||s.push([t,r]),this.config.renderTextTracksNatively){const c=this.captionsTracks[e];this.Cues.newCue(c,t,r,n)}else{const c=this.Cues.newCue(null,t,r,n);this.hls.trigger($.CUES_PARSED,{type:"captions",cues:c,track:e})}}onInitPtsFound(e,{frag:t,id:r,initPTS:n,timescale:s,trackId:a}){const{unparsedVttFrags:c}=this;r===Je.MAIN&&(this.initPTS[t.cc]={baseTime:n,timescale:s,trackId:a}),c.length&&(this.unparsedVttFrags=[],c.forEach(d=>{this.initPTS[d.frag.cc]?this.onFragLoaded($.FRAG_LOADED,d):this.hls.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:d.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(e,t){const{media:r}=this;if(r)for(let n=0;n<r.textTracks.length;n++){const s=r.textTracks[n];if(L_(s,{name:e,lang:t,characteristics:"transcribes-spoken-dialog,describes-music-and-sound"}))return s}return null}createCaptionsTrack(e){this.config.renderTextTracksNatively?this.createNativeTrack(e):this.createNonNativeTrack(e)}createNativeTrack(e){if(this.captionsTracks[e])return;const{captionsProperties:t,captionsTracks:r,media:n}=this,{label:s,languageCode:a}=t[e],c=this.getExistingTrack(s,a);if(c)r[e]=c,As(r[e]),v_(r[e],n);else{const d=this.createTextTrack("captions",s,a);d&&(d[e]=!0,r[e]=d)}}createNonNativeTrack(e){if(this.nonNativeCaptionsTracks[e])return;const t=this.captionsProperties[e];if(!t)return;const r={_id:e,label:t.label,kind:"captions",default:t.media?!!t.media.default:!1,closedCaptions:t.media};this.nonNativeCaptionsTracks[e]=r,this.hls.trigger($.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[r]})}createTextTrack(e,t,r){const n=this.media;if(n)return n.addTextTrack(e,t,r)}onMediaAttaching(e,t){this.media=t.media,t.mediaSource||this._cleanTracks()}onMediaDetaching(e,t){const r=!!t.transferMedia;if(this.media=null,r)return;const{captionsTracks:n}=this;Object.keys(n).forEach(s=>{As(n[s]),delete n[s]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=O_(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:e}=this;if(!e)return;const t=e.textTracks;if(t)for(let r=0;r<t.length;r++)As(t[r])}onSubtitleTracksUpdated(e,t){const r=t.subtitleTracks||[],n=r.some(s=>s.textCodec===Qm);if(this.config.enableWebVTT||n&&this.config.enableIMSC1){if(Q1(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const s=this.media,a=s?Mc(s.textTracks):null;if(this.tracks.forEach((c,d)=>{let u;if(a){let f=null;for(let h=0;h<a.length;h++)if(a[h]&&L_(a[h],c)){f=a[h],a[h]=null;break}f&&(u=f)}if(u)As(u);else{const f=R_(c);u=this.createTextTrack(f,c.name,c.lang),u&&(u.mode="disabled")}u&&this.textTracks.push(u)}),a!=null&&a.length){const c=a.filter(d=>d!==null).map(d=>d.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const s=this.tracks.map(a=>({label:a.name,kind:a.type.toLowerCase(),default:a.default,subtitleTrack:a}));this.hls.trigger($.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:s})}}}onManifestLoaded(e,t){this.config.enableCEA708Captions&&t.captions&&t.captions.forEach(r=>{const n=/(?:CC|SERVICE)([1-4])/.exec(r.instreamId);if(!n)return;const s=`textTrack${n[1]}`,a=this.captionsProperties[s];a&&(a.label=r.name,r.lang&&(a.languageCode=r.lang),a.media=r)})}closedCaptionsForLevel(e){const t=this.hls.levels[e.level];return t?.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,t){if(this.enabled&&t.frag.type===Je.MAIN){var r,n;const{cea608Parser1:s,cea608Parser2:a,lastSn:c}=this,{cc:d,sn:u}=t.frag,f=(r=(n=t.part)==null?void 0:n.index)!=null?r:-1;s&&a&&(u!==c+1||u===c&&f!==this.lastPartIndex+1||d!==this.lastCc)&&(s.reset(),a.reset()),this.lastCc=d,this.lastSn=u,this.lastPartIndex=f}}onFragLoaded(e,t){const{frag:r,payload:n}=t;if(r.type===Je.SUBTITLE)if(n.byteLength){const s=r.decryptdata,a="stats"in t;if(s==null||!s.encrypted||a){const c=this.tracks[r.level],d=this.vttCCs;d[r.cc]||(d[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),c&&c.textCodec===Qm?this._parseIMSC1(r,n):this._parseVTTs(t)}}else this.hls.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,t){const r=this.hls;N_(t,this.initPTS[e.cc],n=>{this._appendCues(n,e.level),r.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},n=>{r.logger.log(`Failed to parse IMSC1: ${n}`),r.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:n})})}_parseVTTs(e){var t;const{frag:r,payload:n}=e,{initPTS:s,unparsedVttFrags:a}=this,c=s.length-1;if(!s[r.cc]&&c===-1){a.push(e);return}const d=this.hls;kV((t=r.initSegment)!=null&&t.data?nn(r.initSegment.data,new Uint8Array(n)).buffer:n,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),d.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},u=>{const f=u.message==="Missing initPTS for VTT MPEGTS";f?a.push(e):this._fallbackToIMSC1(r,n),d.logger.log(`Failed to parse VTT cue: ${u}`),!(f&&c>r.cc)&&d.trigger($.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(e,t){const r=this.tracks[e.level];r.textCodec||N_(t,this.initPTS[e.cc],()=>{r.textCodec=Qm,this._parseIMSC1(e,t)},()=>{r.textCodec="wvtt"})}_appendCues(e,t){const r=this.hls;if(this.config.renderTextTracksNatively){const n=this.textTracks[t];if(!n||n.mode==="disabled")return;e.forEach(s=>b_(n,s))}else{const n=this.tracks[t];if(!n)return;const s=n.default?"default":"subtitles"+t;r.trigger($.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,t){const{frag:r}=t;r.type===Je.SUBTITLE&&this.onFragLoaded($.FRAG_LOADED,t)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,t){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:r,samples:n}=t;if(!(r.type===Je.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let s=0;s<n.length;s++){const a=n[s].bytes;if(a){this.cea608Parser1||this.initCea608Parsers();const c=this.extractCea608Data(a);this.cea608Parser1.addData(n[s].pts,c[0]),this.cea608Parser2.addData(n[s].pts,c[1])}}}onBufferFlushing(e,{startOffset:t,endOffset:r,endOffsetSubtitles:n,type:s}){const{media:a}=this;if(!(!a||a.currentTime<r)){if(!s||s==="video"){const{captionsTracks:c}=this;Object.keys(c).forEach(d=>zm(c[d],t,r))}if(this.config.renderTextTracksNatively&&t===0&&n!==void 0){const{textTracks:c}=this;Object.keys(c).forEach(d=>zm(c[d],t,n))}}}extractCea608Data(e){const t=[[],[]],r=e[0]&31;let n=2;for(let s=0;s<r;s++){const a=e[n++],c=127&e[n++],d=127&e[n++];if(!(c===0&&d===0)&&(4&a)!==0){const u=3&a;(u===0||u===1)&&(t[u].push(c),t[u].push(d))}}return t}};function R_(e){return e.characteristics&&/transcribes-spoken-dialog/gi.test(e.characteristics)&&/describes-music-and-sound/gi.test(e.characteristics)?"captions":"subtitles"}function L_(e,t){return!!e&&e.kind===R_(t)&&$m(t,e)}function NV(e,t,r,n){return Math.min(t,n)-Math.max(e,r)}function O_(){return{ccOffset:0,presentationOffset:0,0:{start:0,prevCC:-1,new:!0}}}var DV=/\s/,MV={newCue(e,t,r,n){const s=[];let a,c,d,u,f;const h=self.VTTCue||self.TextTrackCue;for(let g=0;g<n.rows.length;g++)if(a=n.rows[g],d=!0,u=0,f="",!a.isEmpty()){var m;for(let S=0;S<a.chars.length;S++)DV.test(a.chars[S].uchar)&&d?u++:(f+=a.chars[S].uchar,d=!1);a.cueStartTime=t,t===r&&(r+=1e-4),u>=16?u--:u++;const p=P_(f.trim()),y=qm(t,r,p);e!=null&&(m=e.cues)!=null&&m.getCueById(y)||(c=new h(t,r,p),c.id=y,c.line=g+1,c.align="left",c.position=10+Math.min(80,Math.floor(u*8/32)*10),s.push(c))}return e&&s.length&&(s.sort((g,p)=>g.line==="auto"||p.line==="auto"?0:g.line>8&&p.line>8?p.line-g.line:g.line-p.line),s.forEach(g=>b_(e,g))),s}};function $V(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}var RV=/(\d+)-(\d+)\/(\d+)/,F_=class{constructor(e){this.fetchSetup=void 0,this.requestTimeout=void 0,this.request=null,this.response=null,this.controller=void 0,this.context=null,this.config=null,this.callbacks=null,this.stats=void 0,this.loader=null,this.fetchSetup=e.fetchSetup||UV,this.controller=new self.AbortController,this.stats=new Yh}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(e,t,r){const n=this.stats;if(n.loading.start)throw new Error("Loader can only be used once.");n.loading.start=self.performance.now();const s=LV(e,this.controller.signal),a=e.responseType==="arraybuffer",c=a?"byteLength":"length",{maxTimeToFirstByteMs:d,maxLoadTimeMs:u}=t.loadPolicy;this.context=e,this.config=t,this.callbacks=r,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),t.timeout=d&&Ye(d)?d:u,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},t.timeout),($o(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(f=>{var h;this.response=this.loader=f;const m=Math.max(self.performance.now(),n.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=u,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(n,e,this.response))},u-(m-n.loading.start)),!f.ok){const{status:p,statusText:y}=f;throw new BV(y||"fetch, bad network response",p,f)}n.loading.first=m,n.total=FV(f.headers)||n.total;const g=(h=this.callbacks)==null?void 0:h.onProgress;return g&&Ye(t.highWaterMark)?this.loadProgressively(f,n,e,t.highWaterMark,g):a?f.arrayBuffer():e.responseType==="json"?f.json():f.text()}).then(f=>{var h,m;const g=this.response;if(!g)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),n.loading.end=Math.max(self.performance.now(),n.loading.first);const p=f[c];p&&(n.loaded=n.total=p);const y={url:g.url,data:f,code:g.status},S=(h=this.callbacks)==null?void 0:h.onProgress;S&&!Ye(t.highWaterMark)&&S(n,e,f,g),(m=this.callbacks)==null||m.onSuccess(y,n,e,g)}).catch(f=>{var h;if(self.clearTimeout(this.requestTimeout),n.aborted)return;const m=f&&f.code||0,g=f?f.message:null;(h=this.callbacks)==null||h.onError({code:m,text:g},e,f?f.details:null,n)})}getCacheAge(){let e=null;if(this.response){const t=this.response.headers.get("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,t,r,n=0,s){const a=new _1,c=e.body.getReader(),d=()=>c.read().then(u=>{if(u.done)return a.dataLength&&s(t,r,a.flush().buffer,e),Promise.resolve(new ArrayBuffer(0));const f=u.value,h=f.length;return t.loaded+=h,h<n||a.dataLength?(a.push(f),a.dataLength>=n&&s(t,r,a.flush().buffer,e)):s(t,r,f.buffer,e),d()}).catch(()=>Promise.reject());return d()}};function LV(e,t){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Ft({},e.headers))};return e.rangeEnd&&r.headers.set("Range","bytes="+e.rangeStart+"-"+String(e.rangeEnd-1)),r}function OV(e){const t=RV.exec(e);if(t)return parseInt(t[2])-parseInt(t[1])+1}function FV(e){const t=e.get("Content-Range");if(t){const n=OV(t);if(Ye(n))return n}const r=e.get("Content-Length");if(r)return parseInt(r)}function UV(e,t){return new self.Request(e.url,t)}var BV=class extends Error{constructor(e,t,r){super(e),this.code=void 0,this.details=void 0,this.code=t,this.details=r}},zV=/^age:\s*[\d.]+\s*$/im,U_=class{constructor(e){this.xhrSetup=void 0,this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=void 0,this.config=null,this.callbacks=null,this.context=null,this.loader=null,this.stats=void 0,this.xhrSetup=e&&e.xhrSetup||null,this.stats=new Yh,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const e=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),e&&(e.onreadystatechange=null,e.onprogress=null,e.readyState!==4&&(this.stats.aborted=!0,e.abort()))}abort(){var e;this.abortInternal(),(e=this.callbacks)!=null&&e.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(e,t,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=e,this.config=t,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:e,context:t}=this;if(!e||!t)return;const r=this.loader=new self.XMLHttpRequest,n=this.stats;n.loading.first=0,n.loaded=0,n.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return s(r,t.url)}).catch(a=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",t.url,!0),s(r,t.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,t,e)}).catch(a=>{var c;(c=this.callbacks)==null||c.onError({code:r.status,text:a.message},t,r,n)}):this.openAndSendXhr(r,t,e)}openAndSendXhr(e,t,r){e.readyState||e.open("GET",t.url,!0);const n=t.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:a}=r.loadPolicy;if(n)for(const c in n)e.setRequestHeader(c,n[c]);t.rangeEnd&&e.setRequestHeader("Range","bytes="+t.rangeStart+"-"+(t.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=t.responseType,self.clearTimeout(this.requestTimeout),r.timeout=s&&Ye(s)?s:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),e.send()}readystatechange(){const{context:e,loader:t,stats:r}=this;if(!e||!t)return;const n=t.readyState,s=this.config;if(!r.aborted&&n>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),s.timeout!==s.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),s.timeout=s.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),s.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),n===4)){self.clearTimeout(this.requestTimeout),t.onreadystatechange=null,t.onprogress=null;const u=t.status,f=t.responseType==="text"?t.responseText:null;if(u>=200&&u<300){const g=f??t.response;if(g!=null){var a,c;r.loading.end=Math.max(self.performance.now(),r.loading.first),r.loaded=r.total=t.responseType==="arraybuffer"?g.byteLength:g.length,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const p=(a=this.callbacks)==null?void 0:a.onProgress;p&&p(r,e,g,t);const y={url:t.responseURL,data:g,code:u};(c=this.callbacks)==null||c.onSuccess(y,r,e,t);return}}const h=s.loadPolicy.errorRetry,m=r.retry;if(gc(h,m,!1,{url:e.url,data:void 0,code:u}))this.retry(h);else{var d;$t.error(`${u} while loading ${e.url}`),(d=this.callbacks)==null||d.onError({code:u,text:t.statusText},e,t,r)}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,t=this.stats.retry;if(gc(e,t,!0))this.retry(e);else{var r;$t.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const n=this.callbacks;n&&(this.abortInternal(),n.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:t,stats:r}=this;this.retryDelay=am(e,r.retry),r.retry++,$t.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${t?.url}, retrying ${r.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const t=this.stats;t.loaded=e.loaded,e.lengthComputable&&(t.total=e.total)}getCacheAge(){let e=null;if(this.loader&&zV.test(this.loader.getAllResponseHeaders())){const t=this.loader.getResponseHeader("age");e=t?parseFloat(t):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}},GV=Mt(Mt({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,startOnSegmentBoundary:!1,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveSyncDuration:void 0,liveMaxLatencyDuration:void 0,maxLiveSyncPlaybackRate:1,liveDurationInfinity:!1,liveBackBufferLength:null,maxMaxBufferLength:600,enableWorker:!0,workerPath:null,enableSoftwareAES:!0,startLevel:void 0,startFragPrefetch:!1,fpsDroppedMonitoringPeriod:5e3,fpsDroppedMonitoringThreshold:.2,appendErrorMaxRetry:3,ignorePlaylistParsingErrors:!1,loader:U_,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:n8,bufferController:K9,capLevelController:q9,errorController:l8,fpsController:KZ,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:QS,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,useMediaCapabilities:!0,preserveManualLevelOnError:!1,certLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null}},keyLoadPolicy:{default:{maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"},errorRetry:{maxNumRetry:8,retryDelayMs:1e3,maxRetryDelayMs:2e4,backoff:"linear"}}},manifestLoadPolicy:{default:{maxTimeToFirstByteMs:1/0,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},playlistLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:2,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},fragLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:12e4,timeoutRetry:{maxNumRetry:4,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:6,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},steeringManifestLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:2e4,timeoutRetry:{maxNumRetry:2,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:1,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},interstitialAssetListLoadPolicy:{default:{maxTimeToFirstByteMs:1e4,maxLoadTimeMs:3e4,timeoutRetry:{maxNumRetry:0,retryDelayMs:0,maxRetryDelayMs:0},errorRetry:{maxNumRetry:0,retryDelayMs:1e3,maxRetryDelayMs:8e3}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},ZV()),{},{subtitleStreamController:sV,subtitleTrackController:QZ,timelineController:jV,audioStreamController:G9,audioTrackController:Z9,emeController:g_,cmcdController:GZ,contentSteeringController:VZ,interstitialsController:iV});function ZV(){return{cueHandler:MV,enableWebVTT:!0,enableIMSC1:!0,enableCEA708Captions:!0,captionsTextTrack1Label:"English",captionsTextTrack1LanguageCode:"en",captionsTextTrack2Label:"Spanish",captionsTextTrack2LanguageCode:"es",captionsTextTrack3Label:"Unknown CC",captionsTextTrack3LanguageCode:"",captionsTextTrack4Label:"Unknown CC",captionsTextTrack4LanguageCode:"",renderTextTracksNatively:!0}}function VV(e,t,r){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const n=eg(e),s=["manifest","level","frag"],a=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return s.forEach(c=>{const d=`${c==="level"?"playlist":c}LoadPolicy`,u=t[d]===void 0,f=[];a.forEach(h=>{const m=`${c}Loading${h}`,g=t[m];if(g!==void 0&&u){f.push(m);const p=n[d].default;switch(t[d]={default:p},h){case"TimeOut":p.maxLoadTimeMs=g,p.maxTimeToFirstByteMs=g;break;case"MaxRetry":p.errorRetry.maxNumRetry=g,p.timeoutRetry.maxNumRetry=g;break;case"RetryDelay":p.errorRetry.retryDelayMs=g,p.timeoutRetry.retryDelayMs=g;break;case"MaxRetryTimeout":p.errorRetry.maxRetryDelayMs=g,p.timeoutRetry.maxRetryDelayMs=g;break}}}),f.length&&r.warn(`hls.js config: "${f.join('", "')}" setting(s) are deprecated, use "${d}": ${zt(t[d])}`)}),Mt(Mt({},n),t)}function eg(e){return e&&typeof e=="object"?Array.isArray(e)?e.map(eg):Object.keys(e).reduce((t,r)=>(t[r]=eg(e[r]),t),{}):e}function HV(e,t){const r=e.loader;r!==F_&&r!==U_?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),e.progressive=!1):$V()&&(e.loader=F_,e.progressive=!0,e.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}var Fc=2,KV=.1,WV=.05,qV=100,QV=class extends US{constructor(e,t){super("gap-controller",e.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var r;(r=this.media)!=null&&r.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var r;this.ended=((r=this.media)==null?void 0:r.currentTime)||1,this.hls.trigger($.MEDIA_ENDED,{stalled:!1})}},this.hls=e,this.fragmentTracker=t,this.registerListeners()}registerListeners(){const{hls:e}=this;e&&(e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(e,t){this.setInterval(qV),this.mediaSource=t.mediaSource;const r=this.media=t.media;Ar(r,"playing",this.onMediaPlaying),Ar(r,"waiting",this.onMediaWaiting),Ar(r,"ended",this.onMediaEnded)}onMediaDetaching(e,t){this.clearInterval();const{media:r}=this;r&&($r(r,"playing",this.onMediaPlaying),$r(r,"waiting",this.onMediaWaiting),$r(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(e,t){this.buffered=t.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var e;if(!((e=this.media)!=null&&e.readyState)||!this.hasBuffered)return;const t=this.media.currentTime;this.poll(t,this.lastCurrentTime),this.lastCurrentTime=t}poll(e,t){var r,n;const s=(r=this.hls)==null?void 0:r.config;if(!s)return;const a=this.media;if(!a)return;const{seeking:c}=a,d=this.seeking&&!c,u=!this.seeking&&c,f=a.paused&&!c||a.ended||a.playbackRate===0;if(this.seeking=c,e!==t){t&&(this.ended=0),this.moved=!0,c||(this.nudgeRetry=0,s.nudgeOnVideoHole&&!f&&e>t&&this.nudgeOnVideoHole(e,t)),this.waiting===0&&this.stallResolved(e);return}if(u||d){d&&this.stallResolved(e);return}if(f){this.nudgeRetry=0,this.stallResolved(e),!this.ended&&a.ended&&this.hls&&(this.ended=e||1,this.hls.trigger($.MEDIA_ENDED,{stalled:!1}));return}if(!xt.getBuffered(a).length){this.nudgeRetry=0;return}const h=xt.bufferInfo(a,e,0),m=h.nextStart||0,g=this.fragmentTracker;if(c&&g&&this.hls){const U=B_(this.hls.inFlightFragments,e),z=h.len>Fc,K=!m||U||m-e>Fc&&!g.getPartialFragment(e);if(z||K)return;this.moved=!1}const p=(n=this.hls)==null?void 0:n.latestLevelDetails;if(!this.moved&&this.stalled!==null&&g){if(!(h.len>0)&&!m)return;const U=Math.max(m,h.start||0)-e,z=p!=null&&p.live?p.targetduration*2:Fc,K=Uc(e,g);if(U>0&&(U<=z||K)){a.paused||this._trySkipBufferHole(K);return}}const y=s.detectStallWithCurrentTimeMs,S=self.performance.now(),E=this.waiting;let T=this.stalled;if(T===null)if(E>0&&S-E<y)T=this.stalled=E;else{this.stalled=S;return}const j=S-T;if(!c&&(j>=y||E)&&this.hls){var N;if(((N=this.mediaSource)==null?void 0:N.readyState)==="ended"&&!(p!=null&&p.live)&&Math.abs(e-(p?.edge||0))<1){if(this.ended)return;this.ended=e||1,this.hls.trigger($.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const O=xt.bufferInfo(a,e,s.maxBufferHole);this._tryFixBufferStall(O,j,e)}stallResolved(e){const t=this.stalled;if(t&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-t;this.log(`playback not stuck anymore @${e}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger($.STALL_RESOLVED,{})}}nudgeOnVideoHole(e,t){var r;const n=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(r=this.buffered.audio)!=null&&r.length&&n&&n.length>1&&e>n.end(0)){const s=xt.bufferedInfo(xt.timeRangesToArray(this.buffered.audio),e,0);if(s.len>1&&t>=s.start){const a=xt.timeRangesToArray(n),c=xt.bufferedInfo(a,t,0).bufferedIndex;if(c>-1&&c<a.length-1){const d=xt.bufferedInfo(a,e,0).bufferedIndex,u=a[c].end,f=a[c+1].start;if((d===-1||d>c)&&f-u<1&&e-u<2){const h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${e} hole: ${u} -> ${f} buffered index: ${d}`);this.warn(h.message),this.media.currentTime+=1e-6;let m=Uc(e,this.fragmentTracker);m&&"fragment"in m?m=m.fragment:m||(m=void 0);const g=xt.bufferInfo(this.media,e,0);this.hls.trigger($.ERROR,{type:it.MEDIA_ERROR,details:fe.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:m,buffer:g.len,bufferInfo:g})}}}}}_tryFixBufferStall(e,t,r){var n,s;const{fragmentTracker:a,media:c}=this,d=(n=this.hls)==null?void 0:n.config;if(!c||!a||!d)return;const u=(s=this.hls)==null?void 0:s.latestLevelDetails,f=Uc(r,a);if((f||u!=null&&u.live&&r<u.fragmentStart)&&(this._trySkipBufferHole(f)||!this.media))return;const h=e.buffered,m=this.adjacentTraversal(e,r);(h&&h.length>1&&e.len>d.maxBufferHole||e.nextStart&&(e.nextStart-r<d.maxBufferHole||m))&&(t>d.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(e))}adjacentTraversal(e,t){const r=this.fragmentTracker,n=e.nextStart;if(r&&n){const s=r.getFragAtPos(t,Je.MAIN),a=r.getFragAtPos(n,Je.MAIN);if(s&&a)return a.sn-s.sn<2}return!1}_reportStall(e){const{hls:t,media:r,stallReported:n,stalled:s}=this;if(!n&&s!==null&&r&&t){this.stallReported=!0;const a=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${zt(e)})`);this.warn(a.message),t.trigger($.ERROR,{type:it.MEDIA_ERROR,details:fe.BUFFER_STALLED_ERROR,fatal:!1,error:a,buffer:e.len,bufferInfo:e,stalled:{start:s}})}}_trySkipBufferHole(e){var t;const{fragmentTracker:r,media:n}=this,s=(t=this.hls)==null?void 0:t.config;if(!n||!r||!s)return 0;const a=n.currentTime,c=xt.bufferInfo(n,a,0),d=a<c.start?c.start:c.nextStart;if(d&&this.hls){const f=c.len<=s.maxBufferHole,h=c.len>0&&c.len<1&&n.readyState<3,m=d-a;if(m>0&&(f||h)){if(m>s.maxBufferHole){let p=!1;if(a===0){const y=r.getAppendedFrag(0,Je.MAIN);y&&d<y.end&&(p=!0)}if(!p&&e){var u;if(!((u=this.hls.loadLevelObj)!=null&&u.details)||B_(this.hls.inFlightFragments,d))return 0;let y=!1,S=e.end;for(;S<d;){const E=Uc(S,r);if(E)S+=E.duration;else{y=!0;break}}if(y)return 0}}const g=Math.max(d+WV,a+KV);if(this.warn(`skipping hole, adjusting currentTime from ${a} to ${g}`),this.moved=!0,n.currentTime=g,!(e!=null&&e.gap)){const p=new Error(`fragment loaded with buffer holes, seeking from ${a} to ${g}`),y={type:it.MEDIA_ERROR,details:fe.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:p,reason:p.message,buffer:c.len,bufferInfo:c};e&&("fragment"in e?y.part=e:y.frag=e),this.hls.trigger($.ERROR,y)}return g}}return 0}_tryNudgeBuffer(e){const{hls:t,media:r,nudgeRetry:n}=this,s=t?.config;if(!r||!s)return 0;const a=r.currentTime;if(this.nudgeRetry++,n<s.nudgeMaxRetry){const c=a+(n+1)*s.nudgeOffset,d=new Error(`Nudging 'currentTime' from ${a} to ${c}`);this.warn(d.message),r.currentTime=c,t.trigger($.ERROR,{type:it.MEDIA_ERROR,details:fe.BUFFER_NUDGE_ON_STALL,error:d,fatal:!1,buffer:e.len,bufferInfo:e})}else{const c=new Error(`Playhead still not moving while enough data buffered @${a} after ${s.nudgeMaxRetry} nudges`);this.error(c.message),t.trigger($.ERROR,{type:it.MEDIA_ERROR,details:fe.BUFFER_STALLED_ERROR,error:c,fatal:!0,buffer:e.len,bufferInfo:e})}}};function B_(e,t){const r=z_(e.main);if(r&&r.start<=t)return r;const n=z_(e.audio);return n&&n.start<=t?n:null}function z_(e){if(!e)return null;switch(e.state){case Ne.IDLE:case Ne.STOPPED:case Ne.ENDED:case Ne.ERROR:return null}return e.frag}function Uc(e,t){return t.getAppendedFrag(e,Je.MAIN)||t.getPartialFragment(e)}var YV=.25;function tg(){if(!(typeof self>"u"))return self.VTTCue||self.TextTrackCue}function rg(e,t,r,n,s){let a=new e(t,r,"");try{a.value=n,s&&(a.type=s)}catch{a=new e(t,r,zt(s?Mt({type:s},n):n))}return a}var Bc=(()=>{const e=tg();try{e&&new e(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})(),XV=class{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.removeCues=!0,this.assetCue=void 0,this.onEventCueEnter=()=>{this.hls&&this.hls.trigger($.EVENT_CUE_ENTER,{})},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=this.onEventCueEnter=null}_registerListeners(){const{hls:e}=this;e&&(e.on($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on($.LEVEL_UPDATED,this.onLevelUpdated,this),e.on($.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:e}=this;e&&(e.off($.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off($.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off($.LEVEL_UPDATED,this.onLevelUpdated,this),e.off($.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(e,t){var r;this.media=t.media,((r=t.overrides)==null?void 0:r.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var e;const t=(e=this.hls)==null?void 0:e.latestLevelDetails;t&&this.updateDateRangeCues(t)}onMediaDetaching(e,t){this.media=null,!t.transferMedia&&(this.id3Track&&(this.removeCues&&As(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const t=this.getID3Track(e.textTracks);return t.mode="hidden",t}getID3Track(e){if(this.media){for(let t=0;t<e.length;t++){const r=e[t];if(r.kind==="metadata"&&r.label==="id3")return v_(r,this.media),r}return this.media.addTextTrack("metadata","id3")}}onFragParsingMetadata(e,t){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:r,enableID3MetadataCues:n}=this.hls.config;if(!r&&!n)return;const{samples:s}=t;this.id3Track||(this.id3Track=this.createTrack(this.media));const a=tg();if(a)for(let c=0;c<s.length;c++){const d=s[c].type;if(d===Vr.emsg&&!r||!n)continue;const u=A1(s[c].data),f=s[c].pts;let h=f+s[c].duration;h>Bc&&(h=Bc),h-f<=0&&(h=f+YV);for(let m=0;m<u.length;m++){const g=u[m];if(!j1(g)){this.updateId3CueEnds(f,d);const p=rg(a,f,h,g,d);p&&this.id3Track.addCue(p)}}}}updateId3CueEnds(e,t){var r;const n=(r=this.id3Track)==null?void 0:r.cues;if(n)for(let s=n.length;s--;){const a=n[s];a.type===t&&a.startTime<e&&a.endTime===Bc&&(a.endTime=e)}}onBufferFlushing(e,{startOffset:t,endOffset:r,type:n}){const{id3Track:s,hls:a}=this;if(!a)return;const{config:{enableEmsgMetadataCues:c,enableID3MetadataCues:d}}=a;if(s&&(c||d)){let u;n==="audio"?u=f=>f.type===Vr.audioId3&&d:n==="video"?u=f=>f.type===Vr.emsg&&c:u=f=>f.type===Vr.audioId3&&d||f.type===Vr.emsg&&c,zm(s,t,r,u)}}onLevelUpdated(e,{details:t}){this.updateDateRangeCues(t,!0)}onLevelPtsUpdated(e,t){Math.abs(t.drift)>.01&&this.updateDateRangeCues(t.details)}updateDateRangeCues(e,t){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:n,enableDateRangeMetadataCues:s,interstitialsController:a}=this.hls.config;if(!s)return;const c=tg();if(r&&n&&!a){const{fragmentStart:y,fragmentEnd:S}=e;let E=this.assetCue;E?(E.startTime=y,E.endTime=S):c&&(E=this.assetCue=rg(c,y,S,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),E&&(E.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(E),E.addEventListener("enter",this.onEventCueEnter)))}if(!e.hasProgramDateTime)return;const{id3Track:d}=this,{dateRanges:u}=e,f=Object.keys(u);let h=this.dateRangeCuesAppended;if(d&&t){var m;if((m=d.cues)!=null&&m.length){const y=Object.keys(h).filter(S=>!f.includes(S));for(let S=y.length;S--;){var g;const E=y[S],T=(g=h[E])==null?void 0:g.cues;delete h[E],T&&Object.keys(T).forEach(j=>{const N=T[j];if(N){N.removeEventListener("enter",this.onEventCueEnter);try{d.removeCue(N)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const p=e.fragments[e.fragments.length-1];if(!(f.length===0||!Ye(p?.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let y=0;y<f.length;y++){const S=f[y],E=u[S],T=E.startTime,j=h[S],N=j?.cues||{};let O=j?.durationKnown||!1,U=Bc;const{duration:z,endDate:K}=E;if(K&&z!==null)U=T+z,O=!0;else if(E.endOnNext&&!O){const X=f.reduce((te,ne)=>{if(ne!==E.id){const ae=u[ne];if(ae.class===E.class&&ae.startDate>E.startDate&&(!te||E.startDate<te.startDate))return ae}return te},null);X&&(U=X.startTime,O=!0)}const G=Object.keys(E.attr);for(let X=0;X<G.length;X++){const te=G[X];if(!S8(te))continue;const ne=N[te];if(ne)O&&!(j!=null&&j.durationKnown)?ne.endTime=U:Math.abs(ne.startTime-T)>.01&&(ne.startTime=T,ne.endTime=U);else if(c){let ae=E.attr[te];_8(te)&&(ae=tS(ae));const oe=rg(c,T,U,{key:te,data:ae},Vr.dateRange);oe&&(oe.id=S,this.id3Track.addCue(oe),N[te]=oe,a&&(te==="X-ASSET-LIST"||te==="X-ASSET-URL")&&oe.addEventListener("enter",this.onEventCueEnter))}}h[S]={cues:N,dateRange:E,durationKnown:O}}}}},JV=class{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:t}=this,r=this.levelDetails;if(!t||!r)return;this.currentTime=t.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:s,maxLiveSyncPlaybackRate:a}=this.config;if(!s||a===1||!r.live)return;const c=this.targetLatency;if(c===null)return;const d=n-c;if(d<Math.min(this.maxLatency,c+r.targetduration)&&d>.05&&this.forwardBufferLength>1){const u=Math.min(2,Math.max(1,a)),f=Math.round(2/(1+Math.exp(-.75*d-this.edgeStalled))*20)/20,h=Math.min(u,Math.max(1,f));this.changeMediaPlaybackRate(t,h)}else t.playbackRate!==1&&t.playbackRate!==0&&this.changeMediaPlaybackRate(t,1)},this.hls=e,this.config=e.config,this.registerListeners()}get levelDetails(){var e;return((e=this.hls)==null?void 0:e.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:e}=this;if(e.liveMaxLatencyDuration!==void 0)return e.liveMaxLatencyDuration;const t=this.levelDetails;return t?e.liveMaxLatencyDurationCount*t.targetduration:0}get targetLatency(){const e=this.levelDetails;if(e===null||this.hls===null)return null;const{holdBack:t,partHoldBack:r,targetduration:n}=e,{liveSyncDuration:s,liveSyncDurationCount:a,lowLatencyMode:c}=this.config,d=this.hls.userConfig;let u=c&&r||t;(this._targetLatencyUpdated||d.liveSyncDuration||d.liveSyncDurationCount||u===0)&&(u=s!==void 0?s:a*n);const f=n;return u+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,f)}set targetLatency(e){this.stallCount=0,this.config.liveSyncDuration=e,this._targetLatencyUpdated=!0}get liveSyncPosition(){const e=this.estimateLiveEdge(),t=this.targetLatency;if(e===null||t===null)return null;const r=this.levelDetails;if(r===null)return null;const n=r.edge,s=e-t-this.edgeStalled,a=n-r.totalduration,c=n-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(a,s),c)}get drift(){const e=this.levelDetails;return e===null?1:e.drift}get edgeStalled(){const e=this.levelDetails;if(e===null)return 0;const t=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-t,0)}get forwardBufferLength(){const{media:e}=this,t=this.levelDetails;if(!e||!t)return 0;const r=e.buffered.length;return(r?e.buffered.end(r-1):t.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:e}=this;e&&(e.on($.MEDIA_ATTACHED,this.onMediaAttached,this),e.on($.MEDIA_DETACHING,this.onMediaDetaching,this),e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.LEVEL_UPDATED,this.onLevelUpdated,this),e.on($.ERROR,this.onError,this))}unregisterListeners(){const{hls:e}=this;e&&(e.off($.MEDIA_ATTACHED,this.onMediaAttached,this),e.off($.MEDIA_DETACHING,this.onMediaDetaching,this),e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.LEVEL_UPDATED,this.onLevelUpdated,this),e.off($.ERROR,this.onError,this))}onMediaAttached(e,t){this.media=t.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:t}){t.advanced&&this.onTimeupdate(),!t.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(e,t){var r;t.details===fe.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(r=this.levelDetails)!=null&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(e,t){var r,n;e.playbackRate!==t&&((r=this.hls)==null||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(n=this.targetLatency)==null?void 0:n.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${e.playbackRate} to ${t}`),e.playbackRate=t)}estimateLiveEdge(){const e=this.levelDetails;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}},e7=class extends Mm{constructor(e,t){super(e,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=t,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.MANIFEST_LOADED,this.onManifestLoaded,this),e.on($.LEVEL_LOADED,this.onLevelLoaded,this),e.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on($.FRAG_BUFFERED,this.onFragBuffered,this),e.on($.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.MANIFEST_LOADED,this.onManifestLoaded,this),e.off($.LEVEL_LOADED,this.onLevelLoaded,this),e.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off($.FRAG_BUFFERED,this.onFragBuffered,this),e.off($.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(e=>{e.loadError=0,e.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(e,t){this.resetLevels()}onManifestLoaded(e,t){const r=this.hls.config.preferManagedMediaSource,n=[],s={},a={};let c=!1,d=!1,u=!1;t.levels.forEach(f=>{const h=f.attrs;let{audioCodec:m,videoCodec:g}=f;m&&(f.audioCodec=m=cc(m,r)||void 0),g&&(g=f.videoCodec=OG(g));const{width:p,height:y,unknownCodecs:S}=f,E=S?.length||0;if(c||(c=!!(p&&y)),d||(d=!!g),u||(u=!!m),E||m&&!this.isAudioSupported(m)||g&&!this.isVideoSupported(g)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:T,"FRAME-RATE":j,"HDCP-LEVEL":N,"PATHWAY-ID":O,RESOLUTION:U,"VIDEO-RANGE":z}=h,K=`${`${O||"."}-`}${f.bitrate}-${U}-${j}-${T}-${z}-${N}`;if(s[K])if(s[K].uri!==f.url&&!f.attrs["PATHWAY-ID"]){const G=a[K]+=1;f.attrs["PATHWAY-ID"]=new Array(G+1).join(".");const X=this.createLevel(f);s[K]=X,n.push(X)}else s[K].addGroupId("audio",h.AUDIO),s[K].addGroupId("text",h.SUBTITLES);else{const G=this.createLevel(f);s[K]=G,a[K]=1,n.push(G)}}),this.filterAndSortMediaOptions(n,t,c,d,u)}createLevel(e){const t=new Co(e),r=e.supplemental;if(r!=null&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const n=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(n.message),t.supportedResult=xS(n,[])}return t}isAudioSupported(e){return ko(e,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(e){return ko(e,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(e,t,r,n,s){var a;let c=[],d=[],u=e;const f=((a=t.stats)==null?void 0:a.parsing)||{};if((r||n)&&s&&(u=u.filter(({videoCodec:T,videoRange:j,width:N,height:O})=>(!!T||!!(N&&O))&&WG(j))),u.length===0){Promise.resolve().then(()=>{if(this.hls){let T="no level with compatible codecs found in manifest",j=T;t.levels.length&&(j=`one or more CODECS in variant not supported: ${zt(t.levels.map(O=>O.attrs.CODECS).filter((O,U,z)=>z.indexOf(O)===U))}`,this.warn(j),T+=` (${j})`);const N=new Error(T);this.hls.trigger($.ERROR,{type:it.MEDIA_ERROR,details:fe.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:t.url,error:N,reason:j})}}),f.end=performance.now();return}t.audioTracks&&(c=t.audioTracks.filter(T=>!T.audioCodec||this.isAudioSupported(T.audioCodec)),G_(c)),t.subtitles&&(d=t.subtitles,G_(d));const h=u.slice(0);u.sort((T,j)=>{if(T.attrs["HDCP-LEVEL"]!==j.attrs["HDCP-LEVEL"])return(T.attrs["HDCP-LEVEL"]||"")>(j.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&T.height!==j.height)return T.height-j.height;if(T.frameRate!==j.frameRate)return T.frameRate-j.frameRate;if(T.videoRange!==j.videoRange)return dc.indexOf(T.videoRange)-dc.indexOf(j.videoRange);if(T.videoCodec!==j.videoCodec){const N=pS(T.videoCodec),O=pS(j.videoCodec);if(N!==O)return O-N}if(T.uri===j.uri&&T.codecSet!==j.codecSet){const N=lc(T.codecSet),O=lc(j.codecSet);if(N!==O)return O-N}return T.averageBitrate!==j.averageBitrate?T.averageBitrate-j.averageBitrate:0});let m=h[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==h.length)){for(let T=0;T<h.length;T++)if(h[T].pathwayId===u[0].pathwayId){m=h[T];break}}this._levels=u;for(let T=0;T<u.length;T++)if(u[T]===m){var g;this._firstLevel=T;const j=m.bitrate,N=this.hls.bandwidthEstimate;if(this.log(`manifest loaded, ${u.length} level(s) found, first bitrate: ${j}`),((g=this.hls.userConfig)==null?void 0:g.abrEwmaDefaultEstimate)===void 0){const O=Math.min(j,this.hls.config.abrEwmaDefaultEstimateMax);O>N&&N===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=O)}break}const p=s&&!n,y=this.hls.config,S=!!(y.audioStreamController&&y.audioTrackController),E={levels:u,audioTracks:c,subtitleTracks:d,sessionData:t.sessionData,sessionKeys:t.sessionKeys,firstLevel:this._firstLevel,stats:t.stats,audio:s,video:n,altAudio:S&&!p&&c.some(T=>!!T.url)};f.end=performance.now(),this.hls.trigger($.MANIFEST_PARSED,E)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(e){const t=this._levels;if(t.length===0)return;if(e<0||e>=t.length){const f=new Error("invalid level idx"),h=e<0;if(this.hls.trigger($.ERROR,{type:it.OTHER_ERROR,details:fe.LEVEL_SWITCH_ERROR,level:e,fatal:h,error:f,reason:f.message}),h)return;e=Math.min(e,t.length-1)}const r=this.currentLevelIndex,n=this.currentLevel,s=n?n.attrs["PATHWAY-ID"]:void 0,a=t[e],c=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,r===e&&n&&s===c)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${c?" with Pathway "+c:""} from level ${r}${s?" with Pathway "+s:""}`);const d={level:e,attrs:a.attrs,details:a.details,bitrate:a.bitrate,averageBitrate:a.averageBitrate,maxBitrate:a.maxBitrate,realBitrate:a.realBitrate,width:a.width,height:a.height,codecSet:a.codecSet,audioCodec:a.audioCodec,videoCodec:a.videoCodec,audioGroups:a.audioGroups,subtitleGroups:a.subtitleGroups,loaded:a.loaded,loadError:a.loadError,fragmentError:a.fragmentError,name:a.name,id:a.id,uri:a.uri,url:a.url,urlId:0,audioGroupIds:a.audioGroupIds,textGroupIds:a.textGroupIds};this.hls.trigger($.LEVEL_SWITCHING,d);const u=a.details;if(!u||u.live){const f=this.switchParams(a.uri,n?.details,u);this.loadPlaylist(f)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(e){this.manualLevelIndex=e,this._startLevel===void 0&&(this._startLevel=e),e!==-1&&(this.level=e)}get firstLevel(){return this._firstLevel}set firstLevel(e){this._firstLevel=e}get startLevel(){if(this._startLevel===void 0){const e=this.hls.config.startLevel;return e!==void 0?e:this.hls.firstAutoLevel}return this._startLevel}set startLevel(e){this._startLevel=e}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(e){if(this.steering){const t=this.steering.pathways(),r=e.filter(n=>t.indexOf(n)!==-1);if(e.length<1){this.warn(`pathwayPriority ${e} should contain at least one pathway from list: ${t}`);return}this.steering.pathwayPriority=r}}onError(e,t){t.fatal||!t.context||t.context.type===Et.LEVEL&&t.context.level===this.level&&this.checkRetry(t)}onFragBuffered(e,{frag:t}){if(t!==void 0&&t.type===Je.MAIN){const r=t.elementaryStreams;if(!Object.keys(r).some(s=>!!r[s]))return;const n=this._levels[t.level];n!=null&&n.loadError&&(this.log(`Resetting level error count of ${n.loadError} on frag buffered`),n.loadError=0)}}onLevelLoaded(e,t){var r;const{level:n,details:s}=t,a=t.levelInfo;if(!a){var c;this.warn(`Invalid level index ${n}`),(c=t.deliveryDirectives)!=null&&c.skip&&(s.deltaUpdateFailed=!0);return}if(a===this.currentLevel||t.withoutMultiVariant){a.fragmentError===0&&(a.loadError=0);let d=a.details;d===t.details&&d.advanced&&(d=void 0),this.playlistLoaded(n,t,d)}else(r=t.deliveryDirectives)!=null&&r.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,e)}loadingPlaylist(e,t){super.loadingPlaylist(e,t);const r=this.getUrlWithDirectives(e.uri,t),n=this.currentLevelIndex,s=e.attrs["PATHWAY-ID"],a=e.details,c=a?.age;this.log(`Loading level index ${n}${t?.msn!==void 0?" at sn "+t.msn+" part "+t.part:""}${s?" Pathway "+s:""}${c&&a.live?" age "+c.toFixed(1)+(a.type&&" "+a.type||""):""} ${r}`),this.hls.trigger($.LEVEL_LOADING,{url:r,level:n,levelInfo:e,pathwayId:e.attrs["PATHWAY-ID"],id:0,deliveryDirectives:t||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(e){this.level=e,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=e)}removeLevel(e){var t;if(this._levels.length===1)return;const r=this._levels.filter((s,a)=>a!==e?!0:(this.steering&&this.steering.removeLevel(s),s===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,s.details&&s.details.fragments.forEach(c=>c.level=-1)),!1));p1(r),this._levels=r,this.currentLevelIndex>-1&&(t=this.currentLevel)!=null&&t.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const n=r.length-1;this._firstLevel=Math.min(this._firstLevel,n),this._startLevel&&(this._startLevel=Math.min(this._startLevel,n)),this.hls.trigger($.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(e,{levels:t}){this._levels=t}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:t,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==t&&(this._maxAutoLevel=t,this.hls.trigger($.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:t,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}};function G_(e){const t={};e.forEach(r=>{const n=r.groupId||"";r.id=t[n]=t[n]||0,t[n]++})}function Z_(){return self.SourceBuffer||self.WebKitSourceBuffer}function V_(){if(!di())return!1;const e=Z_();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function t7(){if(!V_())return!1;const e=di();return typeof e?.isTypeSupported=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(t=>e.isTypeSupported(To(t,"video")))||["mp4a.40.2","fLaC"].some(t=>e.isTypeSupported(To(t,"audio"))))}function r7(){var e;const t=Z_();return typeof(t==null||(e=t.prototype)==null?void 0:e.changeType)=="function"}var n7=100,i7=class extends ym{constructor(e,t,r){super(e,t,r,"stream-controller",Je.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=0,this.audioOnly=!1,this.fragPlaying=null,this.fragLastKbps=0,this.couldBacktrack=!1,this.backtrackFragment=null,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const n=this.media,s=n?n.currentTime:null;if(s===null||!Ye(s)||(this.log(`Media seeked to ${s.toFixed(3)}`),!this.getBufferedFrag(s)))return;const a=this.getFwdBufferInfoAtPos(n,s,Je.MAIN,0);if(a===null||a.len===0){this.warn(`Main forward buffer length at ${s} on "seeked" event ${a?a.len:"empty"})`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:e}=this;e.on($.MANIFEST_PARSED,this.onManifestParsed,this),e.on($.LEVEL_LOADING,this.onLevelLoading,this),e.on($.LEVEL_LOADED,this.onLevelLoaded,this),e.on($.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.on($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on($.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.on($.BUFFER_CREATED,this.onBufferCreated,this),e.on($.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on($.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:e}=this;e.off($.MANIFEST_PARSED,this.onManifestParsed,this),e.off($.LEVEL_LOADED,this.onLevelLoaded,this),e.off($.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),e.off($.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off($.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),e.off($.BUFFER_CREATED,this.onBufferCreated,this),e.off($.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off($.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off($.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(e,t){if(this.levels){const{lastCurrentTime:r,hls:n}=this;if(this.stopLoad(),this.setInterval(n7),this.level=-1,!this.startFragRequested){let s=n.startLevel;s===-1&&(n.config.testBandwidth&&this.levels.length>1?(s=0,this.bitrateTest=!0):s=n.firstAutoLevel),n.nextLoadLevel=s,this.level=n.loadLevel,this._hasEnoughToStart=!!t}r>0&&e===-1&&!t&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=Ne.IDLE,this.nextLoadPosition=this.lastCurrentTime=e+this.timelineOffset,this.startPosition=t?-1:e,this.tick()}else this._forceStartLoad=!0,this.state=Ne.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Ne.WAITING_LEVEL:{const{levels:e,level:t}=this,r=e?.[t],n=r?.details;if(n&&(!n.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(n))break;this.state=Ne.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Ne.IDLE;break}break}case Ne.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Ne.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var e;super.onTickEnd(),(e=this.media)!=null&&e.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:t,levels:r,media:n}=this;if(t===null||!n&&!this.primaryPrefetch&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const s=this.buffering?e.nextLoadLevel:e.loadLevel;if(!(r!=null&&r[s]))return;const a=r[s],c=this.getMainFwdBufferInfo();if(c===null)return;const d=this.getLevelDetails();if(d&&this._streamEnded(c,d)){const y={};this.altAudio===2&&(y.type="video"),this.hls.trigger($.BUFFER_EOS,y),this.state=Ne.ENDED;return}if(!this.buffering)return;e.loadLevel!==s&&e.manualLevel===-1&&this.log(`Adapting to level ${s} from level ${this.level}`),this.level=e.nextLoadLevel=s;const u=a.details;if(!u||this.state===Ne.WAITING_LEVEL||this.waitForLive(a)){this.level=s,this.state=Ne.WAITING_LEVEL,this.startFragRequested=!1;return}const f=c.len,h=this.getMaxBufferLength(a.maxBitrate);if(f>=h)return;this.backtrackFragment&&this.backtrackFragment.start>c.end&&(this.backtrackFragment=null);const m=this.backtrackFragment?this.backtrackFragment.start:c.end;let g=this.getNextFragment(m,u);if(this.couldBacktrack&&!this.fragPrevious&&g&&ar(g)&&this.fragmentTracker.getState(g)!==pr.OK){var p;const y=((p=this.backtrackFragment)!=null?p:g).sn-u.startSN,S=u.fragments[y-1];S&&g.cc===S.cc&&(g=S,this.fragmentTracker.removeFragment(S))}else this.backtrackFragment&&c.len&&(this.backtrackFragment=null);if(g&&this.isLoopLoading(g,m)){if(!g.gap){const y=this.audioOnly&&!this.altAudio?Bt.AUDIO:Bt.VIDEO,S=(y===Bt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;S&&this.afterBufferFlushed(S,y,Je.MAIN)}g=this.getNextFragmentLoopLoading(g,u,c,Je.MAIN,h)}g&&(this.exceedsMaxBuffer(c,h,g)||(g.initSegment&&!g.initSegment.data&&!this.bitrateTest&&(g=g.initSegment),this.loadFragment(g,a,m)))}loadFragment(e,t,r){const n=this.fragmentTracker.getState(e);n===pr.NOT_LOADED||n===pr.PARTIAL?ar(e)?this.bitrateTest?(this.log(`Fragment ${e.sn} of level ${e.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(e,t)):super.loadFragment(e,t,r):this._loadInitSegment(e,t):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,Je.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var e;(((e=this.getLevelDetails())==null?void 0:e.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:e,media:t}=this;if(t!=null&&t.readyState){let r;const n=this.getAppendedFrag(t.currentTime);n&&n.start>1&&this.flushMainBuffer(0,n.start-1);const s=this.getLevelDetails();if(s!=null&&s.live){const c=this.getMainFwdBufferInfo();if(!c||c.len<s.targetduration*2)return}if(!t.paused&&e){const c=e[this.hls.nextLoadLevel],d=this.fragLastKbps;d&&this.fragCurrent?r=this.fragCurrent.duration*c.maxBitrate/(1e3*d)+1:r=0}else r=0;const a=this.getBufferedFrag(t.currentTime+r);if(a){const c=this.followingBufferedFrag(a);if(c){this.abortCurrentFrag();const d=c.maxStartPTS?c.maxStartPTS:c.start,u=c.duration,f=Math.max(a.end,d+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));this.flushMainBuffer(f,Number.POSITIVE_INFINITY)}}}}abortCurrentFrag(){const e=this.fragCurrent;switch(this.fragCurrent=null,this.backtrackFragment=null,e&&(e.abortRequests(),this.fragmentTracker.removeFragment(e)),this.state){case Ne.KEY_LOADING:case Ne.FRAG_LOADING:case Ne.FRAG_LOADING_WAITING_RETRY:case Ne.PARSING:case Ne.PARSED:this.state=Ne.IDLE;break}this.nextLoadPosition=this.getLoadPosition()}flushMainBuffer(e,t){super.flushMainBuffer(e,t,this.altAudio===2?"video":null)}onMediaAttached(e,t){super.onMediaAttached(e,t);const r=t.media;Ar(r,"playing",this.onMediaPlaying),Ar(r,"seeked",this.onMediaSeeked)}onMediaDetaching(e,t){const{media:r}=this;r&&($r(r,"playing",this.onMediaPlaying),$r(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,this.fragPlaying=null,super.onMediaDetaching(e,t),!t.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger($.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.fragLastKbps=0,this.fragPlaying=this.backtrackFragment=null,this.altAudio=0,this.audioOnly=!1}onManifestParsed(e,t){let r=!1,n=!1;for(let s=0;s<t.levels.length;s++){const a=t.levels[s].audioCodec;a&&(r=r||a.indexOf("mp4a.40.2")!==-1,n=n||a.indexOf("mp4a.40.5")!==-1)}this.audioCodecSwitch=r&&n&&!r7(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=t.levels,this.startFragRequested=!1}onLevelLoading(e,t){const{levels:r}=this;if(!r||this.state!==Ne.IDLE)return;const n=t.levelInfo;(!n.details||n.details.live&&(this.levelLastLoaded!==n||n.details.expired)||this.waitForCdnTuneIn(n.details))&&(this.state=Ne.WAITING_LEVEL)}onLevelLoaded(e,t){var r;const{levels:n,startFragRequested:s}=this,a=t.level,c=t.details,d=c.totalduration;if(!n){this.warn(`Levels were reset while loading level ${a}`);return}this.log(`Level ${a} loaded [${c.startSN},${c.endSN}]${c.lastPartSn?`[part-${c.lastPartSn}-${c.lastPartIndex}]`:""}, cc [${c.startCC}, ${c.endCC}] duration:${d}`);const u=t.levelInfo,f=this.fragCurrent;f&&(this.state===Ne.FRAG_LOADING||this.state===Ne.FRAG_LOADING_WAITING_RETRY)&&f.level!==t.level&&f.loader&&this.abortCurrentFrag();let h=0;if(c.live||(r=u.details)!=null&&r.live){var m;if(this.checkLiveUpdate(c),c.deltaUpdateFailed)return;h=this.alignPlaylists(c,u.details,(m=this.levelLastLoaded)==null?void 0:m.details)}if(u.details=c,this.levelLastLoaded=u,s||this.setStartPosition(c,h),this.hls.trigger($.LEVEL_UPDATED,{details:c,level:a}),this.state===Ne.WAITING_LEVEL){if(this.waitForCdnTuneIn(c))return;this.state=Ne.IDLE}s&&c.live&&this.synchronizeToLiveEdge(c),this.tick()}synchronizeToLiveEdge(e){const{config:t,media:r}=this;if(!r)return;const n=this.hls.liveSyncPosition,s=this.getLoadPosition(),a=e.fragmentStart,c=e.edge,d=s>=a-t.maxFragLookUpTolerance&&s<=c;if(n!==null&&r.duration>n&&(s<n||!d)){const f=t.liveMaxLatencyDuration!==void 0?t.liveMaxLatencyDuration:t.liveMaxLatencyDurationCount*e.targetduration;if((!d&&r.readyState<4||s<c-f)&&(this._hasEnoughToStart||(this.nextLoadPosition=n),r.readyState))if(this.warn(`Playback: ${s.toFixed(3)} is located too far from the end of live sliding playlist: ${c}, reset currentTime to : ${n.toFixed(3)}`),this.config.liveSyncMode==="buffered"){var u;const h=xt.bufferInfo(r,n,0);if(!((u=h.buffered)!=null&&u.length)){r.currentTime=n;return}if(h.start<=s){r.currentTime=n;return}const{nextStart:m}=xt.bufferedInfo(h.buffered,s,0);m&&(r.currentTime=m)}else r.currentTime=n}}_handleFragmentLoadProgress(e){var t;const r=e.frag,{part:n,payload:s}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const c=a[r.level];if(!c){this.warn(`Level ${r.level} not found on progress`);return}const d=c.details;if(!d){this.warn(`Dropping fragment ${r.sn} of level ${r.level} after level details were reset`),this.fragmentTracker.removeFragment(r);return}const u=c.videoCodec,f=d.PTSKnown||!d.live,h=(t=r.initSegment)==null?void 0:t.data,m=this._getAudioCodec(c),g=this.transmuxer=this.transmuxer||new W1(this.hls,Je.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),p=n?n.index:-1,y=p!==-1,S=new cm(r.level,r.sn,r.stats.chunkCount,s.byteLength,p,y),E=this.initPTS[r.cc];g.push(s,h,m,u,r,n,d.totalduration,f,S,E)}onAudioTrackSwitching(e,t){const r=this.hls,n=this.altAudio!==0;if(hc(t.url,r))this.altAudio=1;else{if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const s=this.fragCurrent;s&&(this.log("Switching to main audio track, cancel main fragment load"),s.abortRequests(),this.fragmentTracker.removeFragment(s)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();if(n){this.altAudio=0,this.fragmentTracker.removeAllFragments(),r.once($.BUFFER_FLUSHED,()=>{this.hls&&this.hls.trigger($.AUDIO_TRACK_SWITCHED,t)}),r.trigger($.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger($.AUDIO_TRACK_SWITCHED,t)}}onAudioTrackSwitched(e,t){const r=hc(t.url,this.hls);if(r){const n=this.videoBuffer;n&&this.mediaBuffer!==n&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=n)}this.altAudio=r?2:0,this.tick()}onBufferCreated(e,t){const r=t.tracks;let n,s,a=!1;for(const c in r){const d=r[c];if(d.id==="main"){if(s=c,n=d,c==="video"){const u=r[c];u&&(this.videoBuffer=u.buffer)}}else a=!0}a&&n?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=n.buffer):this.mediaBuffer=this.media}onFragBuffered(e,t){const{frag:r,part:n}=t,s=r.type===Je.MAIN;if(s){if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${n?" p: "+n.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Ne.PARSED&&(this.state=Ne.IDLE);return}const c=n?n.stats:r.stats;this.fragLastKbps=Math.round(8*c.total/(c.buffering.end-c.loading.first)),ar(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,n)}const a=this.media;a&&(!this._hasEnoughToStart&&xt.getBuffered(a).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),s&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(e,t){var r;if(t.fatal){this.state=Ne.ERROR;return}switch(t.details){case fe.FRAG_GAP:case fe.FRAG_PARSING_ERROR:case fe.FRAG_DECRYPT_ERROR:case fe.FRAG_LOAD_ERROR:case fe.FRAG_LOAD_TIMEOUT:case fe.KEY_LOAD_ERROR:case fe.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Je.MAIN,t);break;case fe.LEVEL_LOAD_ERROR:case fe.LEVEL_LOAD_TIMEOUT:case fe.LEVEL_PARSING_ERROR:!t.levelRetry&&this.state===Ne.WAITING_LEVEL&&((r=t.context)==null?void 0:r.type)===Et.LEVEL&&(this.state=Ne.IDLE);break;case fe.BUFFER_ADD_CODEC_ERROR:case fe.BUFFER_APPEND_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&this.resetLoadingState();break;case fe.BUFFER_FULL_ERROR:if(t.parent!=="main")return;this.reduceLengthAndFlushBuffer(t)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case fe.INTERNAL_EXCEPTION:this.recoverWorkerError(t);break}}onFragLoadEmergencyAborted(){this.state=Ne.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(e,{type:t}){if(t!==Bt.AUDIO||!this.altAudio){const r=(t===Bt.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,t,Je.MAIN),this.tick())}}onLevelsUpdated(e,t){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=t.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const t=e.currentTime;let r=this.startPosition;if(r>=0&&t<r){if(e.seeking){this.log(`could not seek to ${r}, already seeking at ${t}`);return}const n=this.timelineOffset;n&&r&&(r+=n);const s=this.getLevelDetails(),a=xt.getBuffered(e),c=a.length?a.start(0):0,d=c-r,u=Math.max(this.config.maxBufferHole,this.config.maxFragLookUpTolerance);(this.config.startOnSegmentBoundary||d>0&&(d<u||this.loadingParts&&d<2*(s?.partTarget||0)))&&(this.log(`adjusting start position by ${d} to match buffer start`),r+=d,this.startPosition=r),t<r&&(this.log(`seek to target start position ${r} from current time ${t} buffer start ${c}`),e.currentTime=r)}}_getAudioCodec(e){let t=this.config.defaultAudioCodec||e.audioCodec;return this.audioCodecSwap&&t&&(this.log("Swapping audio codec"),t.indexOf("mp4a.40.5")!==-1?t="mp4a.40.2":t="mp4a.40.5"),t}_loadBitrateTestFrag(e,t){e.bitrateTest=!0,this._doFragLoad(e,t).then(r=>{const{hls:n}=this,s=r?.frag;if(!s||this.fragContextChanged(s))return;t.fragmentError=0,this.state=Ne.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const a=s.stats;a.parsing.start=a.parsing.end=a.buffering.start=a.buffering.end=self.performance.now(),n.trigger($.FRAG_LOADED,r),s.bitrateTest=!1}).catch(r=>{this.state===Ne.STOPPED||this.state===Ne.ERROR||(this.warn(r),this.resetFragmentLoading(e))})}_handleTransmuxComplete(e){const t=this.playlistType,{hls:r}=this,{remuxResult:n,chunkMeta:s}=e,a=this.getCurrentContext(s);if(!a){this.resetWhenMissingContext(s);return}const{frag:c,part:d,level:u}=a,{video:f,text:h,id3:m,initSegment:g}=n,{details:p}=u,y=this.altAudio?void 0:n.audio;if(this.fragContextChanged(c)){this.fragmentTracker.removeFragment(c);return}if(this.state=Ne.PARSING,g){const S=g.tracks;if(S){const N=c.initSegment||c;if(this.unhandledEncryptionError(g,c))return;this._bufferInitSegment(u,S,N,s),r.trigger($.FRAG_PARSING_INIT_SEGMENT,{frag:N,id:t,tracks:S})}const E=g.initPTS,T=g.timescale,j=this.initPTS[c.cc];if(Ye(E)&&(!j||j.baseTime!==E||j.timescale!==T)){const N=g.trackId;this.initPTS[c.cc]={baseTime:E,timescale:T,trackId:N},r.trigger($.INIT_PTS_FOUND,{frag:c,id:t,initPTS:E,timescale:T,trackId:N})}}if(f&&p){y&&f.type==="audiovideo"&&this.logMuxedErr(c);const S=p.fragments[c.sn-1-p.startSN],E=c.sn===p.startSN,T=!S||c.cc>S.cc;if(n.independent!==!1){const{startPTS:j,endPTS:N,startDTS:O,endDTS:U}=f;if(d)d.elementaryStreams[f.type]={startPTS:j,endPTS:N,startDTS:O,endDTS:U};else if(f.firstKeyFrame&&f.independent&&s.id===1&&!T&&(this.couldBacktrack=!0),f.dropped&&f.independent){const z=this.getMainFwdBufferInfo(),K=(z?z.end:this.getLoadPosition())+this.config.maxBufferHole,G=f.firstKeyFramePTS?f.firstKeyFramePTS:j;if(!E&&K<G-this.config.maxBufferHole&&!T){this.backtrack(c);return}else T&&(c.gap=!0);c.setElementaryStreamInfo(f.type,c.start,N,c.start,U,!0)}else E&&j-(p.appliedTimelineOffset||0)>Fc&&(c.gap=!0);c.setElementaryStreamInfo(f.type,j,N,O,U),this.backtrackFragment&&(this.backtrackFragment=c),this.bufferFragmentData(f,c,d,s,E||T)}else if(E||T)c.gap=!0;else{this.backtrack(c);return}}if(y){const{startPTS:S,endPTS:E,startDTS:T,endDTS:j}=y;d&&(d.elementaryStreams[Bt.AUDIO]={startPTS:S,endPTS:E,startDTS:T,endDTS:j}),c.setElementaryStreamInfo(Bt.AUDIO,S,E,T,j),this.bufferFragmentData(y,c,d,s)}if(p&&m!=null&&m.samples.length){const S={id:t,frag:c,details:p,samples:m.samples};r.trigger($.FRAG_PARSING_METADATA,S)}if(p&&h){const S={id:t,frag:c,details:p,samples:h.samples};r.trigger($.FRAG_PARSING_USERDATA,S)}}logMuxedErr(e){this.warn(`${ar(e)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${e.url}`)}_bufferInitSegment(e,t,r,n){if(this.state!==Ne.PARSING)return;this.audioOnly=!!t.audio&&!t.video,this.altAudio&&!this.audioOnly&&(delete t.audio,t.audiovideo&&this.logMuxedErr(r));const{audio:s,video:a,audiovideo:c}=t;if(s){const u=e.audioCodec;let f=uc(s.codec,u);f==="mp4a"&&(f="mp4a.40.5");const h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){f&&(f.indexOf("mp4a.40.5")!==-1?f="mp4a.40.2":f="mp4a.40.5");const m=s.metadata;m&&"channelCount"in m&&(m.channelCount||1)!==1&&h.indexOf("firefox")===-1&&(f="mp4a.40.5")}f&&f.indexOf("mp4a.40.5")!==-1&&h.indexOf("android")!==-1&&s.container!=="audio/mpeg"&&(f="mp4a.40.2",this.log(`Android: force audio codec to ${f}`)),u&&u!==f&&this.log(`Swapping manifest audio codec "${u}" for "${f}"`),s.levelCodec=f,s.id=Je.MAIN,this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${f||""}/${u||""}/${s.codec}]`),delete t.audiovideo}if(a){a.levelCodec=e.videoCodec,a.id=Je.MAIN;const u=a.codec;if(u?.length===4)switch(u){case"hvc1":case"hev1":a.codec="hvc1.1.6.L120.90";break;case"av01":a.codec="av01.0.04M.08";break;case"avc1":a.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${u}]${a.codec!==u?" parsed-corrected="+a.codec:""}${a.supplemental?" supplemental="+a.supplemental:""}`),delete t.audiovideo}c&&(this.log(`Init audiovideo buffer, container:${c.container}, codecs[level/parsed]=[${e.codecs}/${c.codec}]`),delete t.video,delete t.audio);const d=Object.keys(t);if(d.length){if(this.hls.trigger($.BUFFER_CODECS,t),!this.hls)return;d.forEach(u=>{const f=t[u].initSegment;f!=null&&f.byteLength&&this.hls.trigger($.BUFFER_APPENDING,{type:u,data:f,frag:r,part:null,chunkMeta:n,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const e=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(e,Je.MAIN)}get maxBufferLength(){const{levels:e,level:t}=this,r=e?.[t];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(e){this.couldBacktrack=!0,this.backtrackFragment=e,this.resetTransmuxer(),this.flushBufferGap(e),this.fragmentTracker.removeFragment(e),this.fragPrevious=null,this.nextLoadPosition=e.start,this.state=Ne.IDLE}checkFragmentChanged(){const e=this.media;let t=null;if(e&&e.readyState>1&&e.seeking===!1){const r=e.currentTime;if(xt.isBuffered(e,r)?t=this.getAppendedFrag(r):xt.isBuffered(e,r+.1)&&(t=this.getAppendedFrag(r+.1)),t){this.backtrackFragment=null;const n=this.fragPlaying,s=t.level;(!n||t.sn!==n.sn||n.level!==s)&&(this.fragPlaying=t,this.hls.trigger($.FRAG_CHANGED,{frag:t}),(!n||n.level!==s)&&this.hls.trigger($.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){var e;if(this.fragPlaying)return this.fragPlaying;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;return Ye(t)?this.getAppendedFrag(t):null}get currentProgramDateTime(){var e;const t=((e=this.media)==null?void 0:e.currentTime)||this.lastCurrentTime;if(Ye(t)){const r=this.getLevelDetails(),n=this.currentFrag||(r?Fi(null,r.fragments,t):null);if(n){const s=n.programDateTime;if(s!==null){const a=s+(t-n.start)*1e3;return new Date(a)}}}return null}get currentLevel(){const e=this.currentFrag;return e?e.level:-1}get nextBufferedFrag(){const e=this.currentFrag;return e?this.followingBufferedFrag(e):null}get forceStartLoad(){return this._forceStartLoad}},s7=class extends rn{constructor(e,t){super("key-loader",t),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const r in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[r].loader;if(n){var t;if(e&&e!==((t=n.context)==null?void 0:t.frag.type))return;n.abort()}}}detach(){for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e];(t.mediaKeySessionContext||t.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyIdToKeyInfo){const t=this.keyIdToKeyInfo[e].loader;t&&t.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(e,t=fe.KEY_LOAD_ERROR,r,n,s){return new Zn({type:it.NETWORK_ERROR,details:t,fatal:!1,frag:e,response:s,error:r,networkDetails:n})}loadClear(e,t,r){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(t.length)for(let n=0,s=t.length;n<s;n++){const a=t[n];if(e.cc<=a.cc&&(!ar(e)||!ar(a)||e.sn<a.sn)||!r&&n==s-1)return this.emeController.selectKeySystemFormat(a).then(c=>{if(!this.emeController)return;a.setKeyFormat(c);const d=xc(c);if(d)return this.emeController.getKeySystemAccess([d])})}if(this.config.requireKeySystemAccessOnStart){const n=Io(this.config);if(n.length)return this.emeController.getKeySystemAccess(n)}}return null}load(e){return!e.decryptdata&&e.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(e).then(t=>this.loadInternal(e,t)):this.loadInternal(e)}loadInternal(e,t){var r,n;t&&e.setKeyFormat(t);const s=e.decryptdata;if(!s){const u=new Error(t?`Expected frag.decryptdata to be defined after setting format ${t}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(e,fe.KEY_LOAD_ERROR,u))}const a=s.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,fe.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));const c=ng(s);let d=this.keyIdToKeyInfo[c];if((r=d)!=null&&r.decryptdata.key)return s.key=d.decryptdata.key,Promise.resolve({frag:e,keyInfo:d});if(this.emeController&&(n=d)!=null&&n.keyLoadPromise)switch(this.emeController.getKeyStatus(d.decryptdata)){case"usable":case"usable-in-future":return d.keyLoadPromise.then(u=>{const{keyInfo:f}=u;return s.key=f.decryptdata.key,{frag:e,keyInfo:f}})}switch(this.log(`${this.keyIdToKeyInfo[c]?"Rel":"L"}oading${s.keyId?" keyId: "+xr(s.keyId):""} URI: ${s.uri} from ${e.type} ${e.level}`),d=this.keyIdToKeyInfo[c]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return s.keyFormat==="identity"?this.loadKeyHTTP(d,e):this.loadKeyEME(d,e);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(d,e);default:return Promise.reject(this.createKeyLoadError(e,fe.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,t){const r={frag:t,keyInfo:e};if(this.emeController&&this.config.emeEnabled){var n;if(!e.decryptdata.keyId&&(n=t.initSegment)!=null&&n.data){const s=TG(t.initSegment.data);if(s.length){let a=s[0];a.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${xr(a)}`),Sc.setKeyIdForUri(e.decryptdata.uri,a)):(a=Sc.addKeyIdForUri(e.decryptdata.uri),this.log(`Generating keyId to patch media ${xr(a)}`)),e.decryptdata.keyId=a}}return!e.decryptdata.keyId&&!ar(t)?Promise.resolve(r):(e.keyLoadPromise=this.emeController.loadKey(r).then(s=>(e.mediaKeySessionContext=s,r))).catch(s=>{throw e.keyLoadPromise=null,"data"in s&&(s.data.frag=t),s})}return Promise.resolve(r)}loadKeyHTTP(e,t){const r=this.config,n=r.loader,s=new n(r);return t.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((a,c)=>{const d={keyInfo:e,frag:t,responseType:"arraybuffer",url:e.decryptdata.uri},u=r.keyLoadPolicy.default,f={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0};s.load(d,f,{onSuccess:(h,m,g,p)=>{const{frag:y,keyInfo:S}=g,E=ng(S.decryptdata);if(!y.decryptdata||S!==this.keyIdToKeyInfo[E])return c(this.createKeyLoadError(y,fe.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));S.decryptdata.key=y.decryptdata.key=new Uint8Array(h.data),y.keyLoader=null,S.loader=null,a({frag:y,keyInfo:S})},onError:(h,m,g,p)=>{this.resetLoader(m),c(this.createKeyLoadError(t,fe.KEY_LOAD_ERROR,new Error(`HTTP Error ${h.code} loading key ${h.text}`),g,Mt({url:d.url,data:void 0},h)))},onTimeout:(h,m,g)=>{this.resetLoader(m),c(this.createKeyLoadError(t,fe.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),g))},onAbort:(h,m,g)=>{this.resetLoader(m),c(this.createKeyLoadError(t,fe.INTERNAL_ABORTED,new Error("key loading aborted"),g))}})})}resetLoader(e){const{frag:t,keyInfo:r,url:n}=e,s=r.loader;t.keyLoader===s&&(t.keyLoader=null,r.loader=null);const a=ng(r.decryptdata)||n;delete this.keyIdToKeyInfo[a],s&&s.destroy()}};function ng(e){if(e.keyFormat!==_r.FAIRPLAY){const t=e.keyId;if(t)return xr(t)}return e.uri}function H_(e){const{type:t}=e;switch(t){case Et.AUDIO_TRACK:return Je.AUDIO;case Et.SUBTITLE_TRACK:return Je.SUBTITLE;default:return Je.MAIN}}function ig(e,t){let r=e.url;return(r===void 0||r.indexOf("data:")===0)&&(r=t.url),r}var a7=class{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.onManifestLoaded=this.checkAutostartLoad,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on($.MANIFEST_LOADING,this.onManifestLoading,this),e.on($.LEVEL_LOADING,this.onLevelLoading,this),e.on($.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on($.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.on($.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:e}=this;e.off($.MANIFEST_LOADING,this.onManifestLoading,this),e.off($.LEVEL_LOADING,this.onLevelLoading,this),e.off($.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off($.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),e.off($.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(e){const t=this.hls.config,r=t.pLoader,n=t.loader,s=new(r||n)(t);return this.loaders[e.type]=s,s}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const t=this.loaders[e];t&&t.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,t){const{url:r}=t;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Et.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(e,t){const{id:r,level:n,pathwayId:s,url:a,deliveryDirectives:c,levelInfo:d}=t;this.load({id:r,level:n,pathwayId:s,responseType:"text",type:Et.LEVEL,url:a,deliveryDirectives:c,levelOrTrack:d})}onAudioTrackLoading(e,t){const{id:r,groupId:n,url:s,deliveryDirectives:a,track:c}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Et.AUDIO_TRACK,url:s,deliveryDirectives:a,levelOrTrack:c})}onSubtitleTrackLoading(e,t){const{id:r,groupId:n,url:s,deliveryDirectives:a,track:c}=t;this.load({id:r,groupId:n,level:null,responseType:"text",type:Et.SUBTITLE_TRACK,url:s,deliveryDirectives:a,levelOrTrack:c})}onLevelsUpdated(e,t){const r=this.loaders[Et.LEVEL];if(r){const n=r.context;n&&!t.levels.some(s=>s===n.levelOrTrack)&&(r.abort(),delete this.loaders[Et.LEVEL])}}load(e){var t;const r=this.hls.config;let n=this.getInternalLoader(e);if(n){const d=this.hls.logger,u=n.context;if(u&&u.levelOrTrack===e.levelOrTrack&&(u.url===e.url||u.deliveryDirectives&&!e.deliveryDirectives)){u.url===e.url?d.log(`[playlist-loader]: ignore ${e.url} ongoing request`):d.log(`[playlist-loader]: ignore ${e.url} in favor of ${u.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),n.abort()}let s;if(e.type===Et.MANIFEST?s=r.manifestLoadPolicy.default:s=Ft({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),n=this.createInternalLoader(e),Ye((t=e.deliveryDirectives)==null?void 0:t.part)){let d;if(e.type===Et.LEVEL&&e.level!==null?d=this.hls.levels[e.level].details:e.type===Et.AUDIO_TRACK&&e.id!==null?d=this.hls.audioTracks[e.id].details:e.type===Et.SUBTITLE_TRACK&&e.id!==null&&(d=this.hls.subtitleTracks[e.id].details),d){const u=d.partTarget,f=d.targetduration;if(u&&f){const h=Math.max(u*3,f*.8)*1e3;s=Ft({},s,{maxTimeToFirstByteMs:Math.min(h,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(h,s.maxTimeToFirstByteMs)})}}}const a=s.errorRetry||s.timeoutRetry||{},c={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0};n.load(e,c,{onSuccess:(d,u,f,h)=>{const m=this.getInternalLoader(f);this.resetInternalLoader(f.type);const g=d.data;u.parsing.start=performance.now(),Po.isMediaPlaylist(g)||f.type!==Et.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,f,h||null,m):this.handleMasterPlaylist(d,u,f,h)},onError:(d,u,f,h)=>{this.handleNetworkError(u,f,!1,d,h)},onTimeout:(d,u,f)=>{this.handleNetworkError(u,f,!0,void 0,d)}})}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:e,startPosition:t},forceStartLoad:r}=this.hls;(e||r)&&(this.hls.logger.log(`${e?"auto":"force"} startLoad with configured startPosition ${t}`),this.hls.startLoad(t))}handleMasterPlaylist(e,t,r,n){const s=this.hls,a=e.data,c=ig(e,r),d=Po.parseMasterPlaylist(a,c);if(d.playlistParsingError){t.parsing.end=performance.now(),this.handleManifestParsingError(e,r,d.playlistParsingError,n,t);return}const{contentSteering:u,levels:f,sessionData:h,sessionKeys:m,startTimeOffset:g,variableList:p}=d;this.variableList=p,f.forEach(T=>{const{unknownCodecs:j}=T;if(j){const{preferManagedMediaSource:N}=this.hls.config;let{audioCodec:O,videoCodec:U}=T;for(let z=j.length;z--;){const K=j[z];ko(K,"audio",N)?(T.audioCodec=O=O?`${O},${K}`:K,_s.audio[O.substring(0,4)]=2,j.splice(z,1)):ko(K,"video",N)&&(T.videoCodec=U=U?`${U},${K}`:K,_s.video[U.substring(0,4)]=2,j.splice(z,1))}}});const{AUDIO:y=[],SUBTITLES:S,"CLOSED-CAPTIONS":E}=Po.parseMasterPlaylistMedia(a,c,d);y.length&&!y.some(T=>!T.url)&&f[0].audioCodec&&!f[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),y.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new or({}),bitrate:0,url:""})),s.trigger($.MANIFEST_LOADED,{levels:f,audioTracks:y,subtitles:S,captions:E,contentSteering:u,url:c,stats:t,networkDetails:n,sessionData:h,sessionKeys:m,startTimeOffset:g,variableList:p})}handleTrackOrLevelPlaylist(e,t,r,n,s){const a=this.hls,{id:c,level:d,type:u}=r,f=ig(e,r),h=Ye(d)?d:Ye(c)?c:0,m=H_(r),g=Po.parseLevelPlaylist(e.data,f,h,m,0,this.variableList);if(u===Et.MANIFEST){const p={attrs:new or({}),bitrate:0,details:g,name:"",url:f};g.requestScheduled=t.loading.start+f1(g,0),a.trigger($.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:f,stats:t,networkDetails:n,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}t.parsing.end=performance.now(),r.levelDetails=g,this.handlePlaylistLoaded(g,e,t,r,n,s)}handleManifestParsingError(e,t,r,n,s){this.hls.trigger($.ERROR,{type:it.NETWORK_ERROR,details:fe.MANIFEST_PARSING_ERROR,fatal:t.type===Et.MANIFEST,url:e.url,err:r,error:r,reason:r.message,response:e,context:t,networkDetails:n,stats:s})}handleNetworkError(e,t,r=!1,n,s){let a=`A network ${r?"timeout":"error"+(n?" (status "+n.code+")":"")} occurred while loading ${e.type}`;e.type===Et.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===Et.AUDIO_TRACK||e.type===Et.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const c=new Error(a);this.hls.logger.warn(`[playlist-loader]: ${a}`);let d=fe.UNKNOWN,u=!1;const f=this.getInternalLoader(e);switch(e.type){case Et.MANIFEST:d=r?fe.MANIFEST_LOAD_TIMEOUT:fe.MANIFEST_LOAD_ERROR,u=!0;break;case Et.LEVEL:d=r?fe.LEVEL_LOAD_TIMEOUT:fe.LEVEL_LOAD_ERROR,u=!1;break;case Et.AUDIO_TRACK:d=r?fe.AUDIO_TRACK_LOAD_TIMEOUT:fe.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case Et.SUBTITLE_TRACK:d=r?fe.SUBTITLE_TRACK_LOAD_TIMEOUT:fe.SUBTITLE_LOAD_ERROR,u=!1;break}f&&this.resetInternalLoader(e.type);const h={type:it.NETWORK_ERROR,details:d,fatal:u,url:e.url,loader:f,context:e,error:c,networkDetails:t,stats:s};n&&(h.response=Mt({url:t?.url||e.url,data:void 0},n)),this.hls.trigger($.ERROR,h)}handlePlaylistLoaded(e,t,r,n,s,a){const c=this.hls,{type:d,level:u,levelOrTrack:f,id:h,groupId:m,deliveryDirectives:g}=n,p=ig(t,n),y=H_(n);let S=typeof n.level=="number"&&y===Je.MAIN?u:void 0;const E=e.playlistParsingError;if(E){if(this.hls.logger.warn(`${E} ${e.url}`),!c.config.ignorePlaylistParsingErrors){c.trigger($.ERROR,{type:it.NETWORK_ERROR,details:fe.LEVEL_PARSING_ERROR,fatal:!1,url:p,error:E,reason:E.message,response:t,context:n,level:S,parent:y,networkDetails:s,stats:r});return}e.playlistParsingError=null}if(!e.fragments.length){const T=e.playlistParsingError=new Error("No Segments found in Playlist");c.trigger($.ERROR,{type:it.NETWORK_ERROR,details:fe.LEVEL_EMPTY_ERROR,fatal:!1,url:p,error:T,reason:T.message,response:t,context:n,level:S,parent:y,networkDetails:s,stats:r});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),d){case Et.MANIFEST:case Et.LEVEL:if(S){if(!f)S=0;else if(f!==c.levels[S]){const T=c.levels.indexOf(f);T>-1&&(S=T)}}c.trigger($.LEVEL_LOADED,{details:e,levelInfo:f||c.levels[0],level:S||0,id:h||0,stats:r,networkDetails:s,deliveryDirectives:g,withoutMultiVariant:d===Et.MANIFEST});break;case Et.AUDIO_TRACK:c.trigger($.AUDIO_TRACK_LOADED,{details:e,track:f,id:h||0,groupId:m||"",stats:r,networkDetails:s,deliveryDirectives:g});break;case Et.SUBTITLE_TRACK:c.trigger($.SUBTITLE_TRACK_LOADED,{details:e,track:f,id:h||0,groupId:m||"",stats:r,networkDetails:s,deliveryDirectives:g});break}}},Oo=class Ma{static get version(){return jo}static isMSESupported(){return V_()}static isSupported(){return t7()}static getMediaSource(){return di()}static get Events(){return $}static get MetadataSchema(){return Vr}static get ErrorTypes(){return it}static get ErrorDetails(){return fe}static get DefaultConfig(){return Ma.defaultConfig?Ma.defaultConfig:GV}static set DefaultConfig(t){Ma.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new Sm,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const r=this.logger=mG(t.debug||!1,"Hls instance",t.assetPlayerId),n=this.config=VV(Ma.DefaultConfig,t,r);this.userConfig=t,n.progressive&&HV(n,r);const{abrController:s,bufferController:a,capLevelController:c,errorController:d,fpsController:u}=n,f=new d(this),h=this.abrController=new s(this),m=new c8(this),g=n.interstitialsController,p=g?this.interstitialsController=new g(this,Ma):null,y=this.bufferController=new a(this,m),S=this.capLevelController=new c(this),E=new u(this),T=new a7(this),j=n.contentSteeringController,N=j?new j(this):null,O=this.levelController=new e7(this,N),U=new XV(this),z=new s7(this.config,this.logger),K=this.streamController=new i7(this,m,z),G=this.gapController=new QV(this,m);S.setStreamController(K),E.setStreamController(K);const X=[T,O,K];p&&X.splice(1,0,p),N&&X.splice(1,0,N),this.networkControllers=X;const te=[h,y,G,S,E,U,m];this.audioTrackController=this.createController(n.audioTrackController,X);const ne=n.audioStreamController;ne&&X.push(this.audioStreamController=new ne(this,m,z)),this.subtitleTrackController=this.createController(n.subtitleTrackController,X);const ae=n.subtitleStreamController;ae&&X.push(this.subtititleStreamController=new ae(this,m,z)),this.createController(n.timelineController,te),z.emeController=this.emeController=this.createController(n.emeController,te),this.cmcdController=this.createController(n.cmcdController,te),this.latencyController=this.createController(JV,te),this.coreComponents=te,X.push(f);const oe=f.onErrorOut;typeof oe=="function"&&this.on($.ERROR,oe,f),this.on($.MANIFEST_LOADED,T.onManifestLoaded,T)}createController(t,r){if(t){const n=new t(this);return r&&r.push(n),n}return null}on(t,r,n=this){this._emitter.on(t,r,n)}once(t,r,n=this){this._emitter.once(t,r,n)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,r,n=this,s){this._emitter.off(t,r,n,s)}listeners(t){return this._emitter.listeners(t)}emit(t,r,n){return this._emitter.emit(t,r,n)}trigger(t,r){if(this.config.debug)return this.emit(t,t,r);try{return this.emit(t,t,r)}catch(n){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;const s=t===$.ERROR;this.trigger($.ERROR,{type:it.OTHER_ERROR,details:fe.INTERNAL_EXCEPTION,fatal:s,event:t,error:n}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger($.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(r=>r.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(r=>r.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const a=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger($.ERROR,{type:it.OTHER_ERROR,details:fe.ATTACH_MEDIA_ERROR,fatal:!0,error:a});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const r="media"in t,n=r?t.media:t,s=r?t:{media:n};this._media=n,this.trigger($.MEDIA_ATTACHING,s)}detachMedia(){this.logger.log("detachMedia"),this.trigger($.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger($.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const r=this.media,n=this._url,s=this._url=Qh.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${s}`),r&&n&&(n!==s||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger($.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,r){this.logger.log(`startLoad(${t+(r?", <skip seek to start>":"")})`),this.started=!0,this.resumeBuffering();for(let n=0;n<this.networkControllers.length&&(this.networkControllers[n].startLoad(t,r),!(!this.started||!this.networkControllers));n++);}stopLoad(){this.logger.log("stopLoad"),this.started=!1;for(let t=0;t<this.networkControllers.length&&(this.networkControllers[t].stopLoad(),!(this.started||!this.networkControllers));t++);}get loadingEnabled(){return this.started}get bufferingEnabled(){return this.streamController.bufferingEnabled}resumeBuffering(){this.bufferingEnabled||(this.logger.log("resume buffering"),this.networkControllers.forEach(t=>{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[Je.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[Je.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[Je.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,r=t?.currentTime;this.detachMedia(),t&&(this.attachMedia(t),r&&this.startLoad(r))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=YZ()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const r=!!t;r!==this.config.capLevelToPlayerSize&&(r?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=r)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){KG(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:r}}=this;if(!t)return 0;const n=t.length;for(let s=0;s<n;s++)if(t[s].maxBitrate>=r)return s;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:r,maxHdcpLevel:n}=this;let s;if(r===-1&&t!=null&&t.length?s=t.length-1:s=r,n)for(let a=s;a--;){const c=t[a].attrs["HDCP-LEVEL"];if(c&&c<=n)return a}return s}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var r;return((r=this.audioTrackController)==null?void 0:r.setAudioOption(t))||null}setSubtitleOption(t){var r;return((r=this.subtitleTrackController)==null?void 0:r.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const r=this.audioTrackController;r&&(r.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const r=this.subtitleTrackController;r&&(r.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const r=this.subtitleTrackController;r&&(r.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){var t;return((t=this.interstitialsController)==null?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,r=this.allAudioTracks){return SS(t,TS(r),navigator.mediaCapabilities)}};Oo.defaultConfig=void 0;function o7(e,t){return e.name!==void 0&&e.name.length>0?e.name:e.height!==void 0&&e.height>0?`${e.height}p`:e.bitrate!==void 0&&e.bitrate>0?`${Math.round(e.bitrate/1e3)} kbps`:`Level ${t+1}`}function l7(e){return[{value:-1,label:"Auto"},...e.map((t,r)=>({value:r,label:o7(t,r)}))]}function c7(e){return{height:e.height>0?e.height:void 0,bitrate:e.bitrate>0?e.bitrate:void 0,name:e.name.length>0?e.name:void 0}}function K_({url:e,authToken:t,posterUrl:r,autoPlay:n=!0,className:s,onQualityOptions:a,selectedLevel:c=-1}){const d=(0,l.useRef)(null),u=(0,l.useRef)(null),[f,h]=(0,l.useState)(null),[m,g]=(0,l.useState)(!0);return(0,l.useEffect)(()=>{const p=d.current;if(!p||!e)return;h(null),g(!0),a?.([]);const y=()=>g(!1);if(p.addEventListener("playing",y),Oo.isSupported()){const S=new Oo({enableWorker:!0,lowLatencyMode:!1,xhrSetup:E=>{E.withCredentials=!0,t&&E.setRequestHeader("Authorization",`Bearer ${t}`)}});return u.current=S,S.loadSource(e),S.attachMedia(p),S.on(Oo.Events.MANIFEST_PARSED,(E,T)=>{const j=T.levels.map(c7);a?.(j.length>1?l7(j):[]),n&&p.play().catch(()=>{})}),S.on(Oo.Events.ERROR,(E,T)=>{T.fatal&&(g(!1),h(`Playback error (${T.type}).`))}),()=>{p.removeEventListener("playing",y),u.current=null,S.destroy()}}if(p.canPlayType("application/vnd.apple.mpegurl")){p.src=e;const S=()=>{n&&p.play().catch(()=>{})};return p.addEventListener("loadedmetadata",S),p.addEventListener("error",()=>h("Could not load this recording.")),()=>{p.removeEventListener("loadedmetadata",S),p.removeEventListener("playing",y),p.removeAttribute("src"),p.load()}}return g(!1),h("HLS playback is not supported in this browser."),()=>p.removeEventListener("playing",y)},[e,t,n,a]),(0,l.useEffect)(()=>{const p=u.current;p!==null&&(p.currentLevel=c)},[c]),(0,i.jsxs)("div",{className:`relative h-full w-full bg-black ${s??""}`,children:[(0,i.jsx)("video",{ref:d,controls:!0,playsInline:!0,className:"h-full w-full",...r?{poster:r}:{}}),m&&!f?(0,i.jsx)("div",{className:"pointer-events-none absolute inset-0 flex items-center justify-center",children:(0,i.jsx)("div",{className:"h-8 w-8 animate-spin rounded-full border-2 border-white/20 border-t-white/60"})}):null,f?(0,i.jsx)("div",{className:"absolute inset-0 flex items-center justify-center px-4 text-center text-sm text-amber-400",children:f}):null]})}function u7(e){return e==="streaming"?"bg-emerald-500":e==="connecting"?"bg-amber-500":e==="error"?"bg-rose-500":"bg-zinc-500"}function d7(e){const t=Math.floor(e/1e3);return t<60?`${t}s`:t<3600?`${Math.floor(t/60)}m`:`${Math.floor(t/3600)}h${Math.floor(t%3600/60)}m`}function sg({className:e}){return(0,i.jsx)("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("polygon",{points:"5 3 19 12 5 21 5 3"})})}function f7({className:e}){return(0,i.jsx)("svg",{className:e,viewBox:"0 0 24 24",fill:"currentColor",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("rect",{x:"6",y:"6",width:"12",height:"12",rx:"1"})})}function h7({className:e}){return(0,i.jsxs)("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,i.jsx)("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3z"}),(0,i.jsx)("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),(0,i.jsx)("line",{x1:"12",y1:"19",x2:"12",y2:"23"}),(0,i.jsx)("line",{x1:"8",y1:"23",x2:"16",y2:"23"})]})}function m7({className:e}){return(0,i.jsxs)("svg",{className:e,viewBox:"0 0 24 24",fill:"currentColor",children:[(0,i.jsx)("circle",{cx:"5",cy:"12",r:"2"}),(0,i.jsx)("circle",{cx:"12",cy:"12",r:"2"}),(0,i.jsx)("circle",{cx:"19",cy:"12",r:"2"})]})}function ag({label:e,active:t,onClick:r}){return(0,i.jsxs)("button",{type:"button",onClick:r,className:"w-full flex items-center justify-between gap-3 px-3 py-1.5 text-[11px] text-foreground hover:bg-surface-hover transition-colors",children:[(0,i.jsx)("span",{children:e}),(0,i.jsx)("span",{className:`inline-block h-3 w-5 rounded-full transition-colors ${t?"bg-primary":"bg-foreground-subtle/30"} relative`,children:(0,i.jsx)("span",{className:`absolute top-0.5 h-2 w-2 rounded-full bg-white transition-all ${t?"left-2.5":"left-0.5"}`})})]})}function g7({className:e}){return(0,i.jsxs)("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,i.jsx)("circle",{cx:"12",cy:"12",r:"2",fill:"currentColor"}),(0,i.jsx)("path",{d:"M16.24 7.76a6 6 0 0 1 0 8.49M7.76 16.24a6 6 0 0 1 0-8.49M19.07 4.93a10 10 0 0 1 0 14.14M4.93 19.07a10 10 0 0 1 0-14.14"})]})}function W_({className:e}){return(0,i.jsxs)("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,i.jsx)("polyline",{points:"23 4 23 10 17 10"}),(0,i.jsx)("polyline",{points:"1 20 1 14 7 14"}),(0,i.jsx)("path",{d:"M3.51 9a9 9 0 0114.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0020.49 15"})]})}function p7({className:e}){return(0,i.jsxs)("svg",{className:e,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[(0,i.jsx)("line",{x1:"2",y1:"2",x2:"22",y2:"22"}),(0,i.jsx)("path",{d:"M10.41 10.41a2 2 0 11-2.83-2.83"}),(0,i.jsx)("line",{x1:"13.5",y1:"13.5",x2:"6",y2:"21"}),(0,i.jsx)("path",{d:"M18 12l-1.5-1.5"}),(0,i.jsx)("path",{d:"M21 15V5a2 2 0 00-2-2H5"}),(0,i.jsx)("path",{d:"M21 21H5a2 2 0 01-2-2V11"})]})}function v7({serverUrl:e,createSession:t,sendAnswer:r,handleOffer:n,getIceServers:s,addIceCandidate:a,getIceCandidates:c,closeSession:d,getSessionState:u,playbackUrl:f,playbackAuthToken:h,onExitPlayback:m,posterUrl:g,streams:p,activeStreamId:y,onStreamChange:S,deviceName:E,phase:T,pipelineMetrics:j,detections:N,defaultShowDetections:O=!0,defaultShowMotion:U=!1,streamStats:z,autoPlay:K=!1,showPlayStop:G=!1,snapshotSrc:X,snapshotLoading:te=!1,onRefreshSnapshot:ne,showStreamStats:ae=!1,children:oe,extraOverlay:pe,ptzAvailable:le=!1,ptzShown:se=!1,ptzOverlay:Ce,onPtzToggle:q,intercomAvailable:Q=!1,intercomShown:ie=!1,onIntercomToggle:be,chromeless:we=!1,className:Re}){const Ee=fx(),[Fe,Ge]=(0,l.useState)(K),[Be,st]=(0,l.useState)(O),[at,We]=(0,l.useState)(U),[ct,He]=(0,l.useState)(null),[$e,Ke]=(0,l.useState)([]),[ft,St]=(0,l.useState)(-1),[Rt,dr]=(0,l.useState)(!1),Er=(0,l.useRef)(null);(0,l.useEffect)(()=>{if(!Rt)return;function qe(kt){Er.current&&!Er.current.contains(kt.target)&&dr(!1)}return document.addEventListener("mousedown",qe),()=>document.removeEventListener("mousedown",qe)},[Rt]),(0,l.useEffect)(()=>{St(-1)},[f]);const At=(0,l.useCallback)(qe=>{Ke(qe)},[]),jt=y??ct??p?.[0]?.id??"",rr=p?.find(qe=>qe.id===jt)??p?.[0],Gt=rr?.inputFps!=null?{status:rr.status??"unknown",inputFps:rr.inputFps,bitrateKbps:rr.bitrateKbps??0}:null,sn=qe=>{He(qe),S?.(qe),Fe&&G&&(Ge(!1),setTimeout(()=>Ge(!0),50))},jr=(0,l.useMemo)(()=>{const qe=rr?.target;if(!(!qe||!t))return kt=>t(qe,kt)},[t,rr]),Wn=(0,l.useMemo)(()=>{const qe=rr?.target;if(!(!qe||!n))return(kt,vr)=>n(qe,kt,vr)},[n,rr]),Gi=(0,l.useMemo)(()=>{if(n)return(qe,kt,vr)=>n(vr,kt,qe)},[n]),he=p,rt=()=>Ge(!0),ut=()=>Ge(!1),gt=j?.phase??T,Lt=gt==="active",dt=!!N,Ue=dt&&(Be||at),lt=le&&se&&!!Ce,nt=!!f,nr=nt||(G?Fe:!0);return(0,i.jsxs)("div",{className:`overflow-hidden ${we?"":"rounded-xl border border-border bg-surface"} ${Re??""}`,children:[(0,i.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 px-3 py-2 border-b border-border",children:[(0,i.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(z??Gt)&&(0,i.jsx)("span",{className:`shrink-0 w-2 h-2 rounded-full ${u7((z??Gt).status)}`}),E&&(0,i.jsx)("span",{className:"text-xs font-medium text-foreground truncate",children:E}),!nt&&he&&he.length>1&&(0,i.jsxs)("div",{className:"relative",children:[(0,i.jsx)("select",{"data-testid":"stream-profile-select",value:jt,onChange:qe=>sn(qe.target.value),className:"appearance-none cursor-pointer rounded-md border border-border bg-surface-hover hover:bg-surface text-foreground text-[11px] font-medium pl-2 pr-6 py-1 focus:outline-none focus:ring-1 focus:ring-primary transition-colors",children:he.map(qe=>(0,i.jsx)("option",{value:qe.id,children:qe.label},qe.id))}),(0,i.jsx)("span",{className:"pointer-events-none absolute right-1.5 top-1/2 -translate-y-1/2 text-foreground-subtle",children:(0,i.jsx)("svg",{className:"h-2.5 w-2.5",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("polyline",{points:"3 4.5 6 7.5 9 4.5"})})})]}),nt&&$e.length>1&&(0,i.jsxs)("div",{className:"relative",children:[(0,i.jsx)("select",{"data-testid":"vod-quality-select",value:ft,onChange:qe=>St(Number(qe.target.value)),className:"appearance-none cursor-pointer rounded-md border border-border bg-surface-hover hover:bg-surface text-foreground text-[11px] font-medium pl-2 pr-6 py-1 focus:outline-none focus:ring-1 focus:ring-primary transition-colors",children:$e.map(qe=>(0,i.jsx)("option",{value:qe.value,children:qe.label},qe.value))}),(0,i.jsx)("span",{className:"pointer-events-none absolute right-1.5 top-1/2 -translate-y-1/2 text-foreground-subtle",children:(0,i.jsx)("svg",{className:"h-2.5 w-2.5",viewBox:"0 0 12 12",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:(0,i.jsx)("polyline",{points:"3 4.5 6 7.5 9 4.5"})})})]})]}),(0,i.jsxs)("div",{className:"flex items-center gap-1.5 shrink-0 ml-auto",children:[Q&&!nt&&(0,i.jsxs)("button",{"data-testid":"stream-intercom-toggle","data-intercom-shown":ie?"true":"false",onClick:be,className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors ${ie?"bg-primary/15 text-primary":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,title:ie?"Close intercom":"Open intercom",children:[(0,i.jsx)(h7,{className:"h-3 w-3"}),(0,i.jsx)("span",{className:"hidden xl:inline",children:"Intercom"})]}),Ee.map(qe=>{const kt=qe.tone==="primary"?"bg-primary text-primary-foreground":"bg-primary/15 text-primary";return(0,i.jsxs)("button",{type:"button","data-toolbar-button-id":qe.id,"data-toolbar-button-active":qe.active?"true":"false",onClick:qe.onClick,disabled:qe.disabled,className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors disabled:opacity-50 ${qe.active?kt:"text-foreground-subtle hover:text-foreground hover:bg-surface-hover"}`,title:qe.title??qe.label,children:[qe.icon,(0,i.jsx)("span",{className:"hidden xl:inline",children:qe.label})]},qe.id)}),G&&(0,i.jsxs)("button",{"data-testid":"stream-play-toggle","data-stream-playing":nr?"true":"false","data-vod":nt?"true":"false",onClick:nt?m:nr?ut:rt,className:`inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium transition-colors ${nt?"bg-primary/10 text-primary hover:bg-primary/20":nr?"bg-danger/10 text-danger hover:bg-danger/20":"bg-primary/10 text-primary hover:bg-primary/20"}`,title:nt?"Return to live":nr?"Stop stream":"Start stream",children:[nt?(0,i.jsx)(g7,{className:"h-3 w-3"}):nr?(0,i.jsx)(f7,{className:"h-3 w-3"}):(0,i.jsx)(sg,{className:"h-3 w-3"}),(0,i.jsx)("span",{className:"hidden xl:inline",children:nt?"Live":nr?"Stop":"Play"})]}),ne&&!nt&&(0,i.jsxs)("button",{"data-testid":"stream-snapshot-refresh",onClick:ne,disabled:te,className:"inline-flex items-center gap-1 rounded-md px-2 py-1 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50",title:"Force snapshot refresh",children:[(0,i.jsx)(W_,{className:`h-3 w-3 ${te?"animate-spin":""}`}),(0,i.jsx)("span",{className:"hidden xl:inline",children:"Snapshot"})]}),(dt||le||j||gt||z||Gt&&Gt.inputFps>0)&&(0,i.jsxs)("div",{ref:Er,className:"relative",children:[(0,i.jsx)("button",{onClick:()=>dr(qe=>!qe),title:"More controls",className:"inline-flex items-center justify-center rounded-md p-1 text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",children:(0,i.jsx)(m7,{className:"h-3.5 w-3.5"})}),Rt&&(0,i.jsxs)("div",{className:"absolute right-0 top-full mt-1 z-30 min-w-[200px] rounded-lg border border-border bg-surface shadow-xl py-1.5",children:[ae&&z&&(0,i.jsxs)("div",{className:"px-3 py-1.5 text-[10px] text-foreground-subtle border-b border-border-subtle",children:[(0,i.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,i.jsx)("span",{children:"Input"}),(0,i.jsxs)("span",{className:"tabular-nums text-foreground",children:[z.inputFps.toFixed(1)," fps"]})]}),(0,i.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,i.jsx)("span",{children:"Decode"}),(0,i.jsxs)("span",{className:"tabular-nums text-foreground",children:[z.decodeFps.toFixed(1)," fps"]})]}),(0,i.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,i.jsx)("span",{children:"Uptime"}),(0,i.jsx)("span",{className:"tabular-nums text-foreground",children:d7(z.uptimeMs)})]})]}),!ae&&Gt&&Gt.inputFps>0&&(0,i.jsxs)("div",{className:"px-3 py-1.5 text-[10px] text-foreground-subtle border-b border-border-subtle",children:[(0,i.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,i.jsx)("span",{children:"Input"}),(0,i.jsxs)("span",{className:"tabular-nums text-foreground",children:[Gt.inputFps.toFixed(1)," fps"]})]}),Gt.bitrateKbps>0&&(0,i.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,i.jsx)("span",{children:"Bitrate"}),(0,i.jsxs)("span",{className:"tabular-nums text-foreground",children:[Gt.bitrateKbps," kbps"]})]})]}),(j||dt&&gt)&&(0,i.jsxs)("div",{className:"px-3 py-1.5 text-[10px] text-foreground-subtle border-b border-border-subtle",children:[(0,i.jsxs)("div",{className:"flex justify-between gap-3 items-center",children:[(0,i.jsx)("span",{children:"Phase"}),(0,i.jsxs)("span",{className:`flex items-center gap-1 font-semibold uppercase tracking-wider ${Lt?"text-red-400":"text-emerald-400"}`,children:[(0,i.jsx)("span",{className:`w-1.5 h-1.5 rounded-full ${Lt?"bg-red-500 animate-pulse":"bg-emerald-500"}`}),Lt?"Active":"Watching"]})]}),j&&j.detectionFps>0&&(0,i.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,i.jsx)("span",{children:"Detection"}),(0,i.jsxs)("span",{className:"tabular-nums text-foreground",children:[j.detectionFps.toFixed(1)," det/s"]})]}),j&&j.avgInferenceMs>0&&(0,i.jsxs)("div",{className:"flex justify-between gap-3",children:[(0,i.jsx)("span",{children:"Inference"}),(0,i.jsxs)("span",{className:"tabular-nums text-foreground",children:[j.avgInferenceMs.toFixed(0)," ms"]})]})]}),dt&&(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(ag,{label:"Show detections",active:Be,onClick:()=>st(qe=>!qe)}),(0,i.jsx)(ag,{label:"Show motion",active:at,onClick:()=>We(qe=>!qe)})]}),le&&(0,i.jsx)(ag,{label:"PTZ controls",active:se,onClick:()=>{q?.(),dr(!1)}})]})]})]})]}),f?(0,i.jsxs)("div",{className:"aspect-video relative",children:[(0,i.jsx)(K_,{url:f,authToken:h??null,onQualityOptions:At,selectedLevel:ft,...g?{posterUrl:g}:{}}),pe||lt?(0,i.jsxs)(i.Fragment,{children:[pe,lt&&Ce]}):null]}):nr&&e?(0,i.jsx)("div",{className:"aspect-video relative",children:(0,i.jsx)(Qx,{serverUrl:e,streamKey:jt,autoPlay:!0,className:"w-full h-full",createSession:jr,sendAnswer:r,handleOffer:Wn,reoffer:Gi,getSessionState:u,getIceServers:s,addIceCandidate:a,getIceCandidates:c,closeSession:d,...g?{posterUrl:g}:{},overlay:Ue||pe||lt?(0,i.jsxs)(i.Fragment,{children:[Ue&&(0,i.jsx)(qx,{detections:N,showPhaseIndicator:!1,showMotionZones:at,showMotionRaw:at,showDetections:Be}),pe,lt&&Ce]}):void 0},jt)}):(0,i.jsx)(b7,{src:X??null,isLoading:te,onPlay:rt,onRetry:ne,extraOverlay:pe||lt?(0,i.jsxs)(i.Fragment,{children:[pe,lt&&Ce]}):null,suppressPlayHover:!!pe||lt}),oe]})}function b7({src:e,isLoading:t,onPlay:r,onRetry:n,extraOverlay:s,suppressPlayHover:a=!1}){return e?(0,i.jsxs)("div",{className:"relative w-full aspect-video bg-black/90 flex items-center justify-center",children:[(0,i.jsx)("img",{src:e,alt:"Camera snapshot",className:"w-full h-full object-contain"}),!a&&(0,i.jsx)("button",{onClick:r,className:"absolute inset-0 flex items-center justify-center bg-black/30 opacity-0 hover:opacity-100 transition-opacity cursor-pointer",children:(0,i.jsx)("div",{className:"h-14 w-14 rounded-full bg-white/20 backdrop-blur-sm flex items-center justify-center",children:(0,i.jsx)(sg,{className:"h-7 w-7 text-white ml-0.5"})})}),s]}):t?(0,i.jsx)("div",{className:"relative w-full aspect-video bg-black/90 flex items-center justify-center",children:(0,i.jsx)("div",{className:"h-8 w-8 border-2 border-white/20 border-t-white/60 rounded-full animate-spin"})}):(0,i.jsx)("div",{className:"relative w-full aspect-video bg-black/90 flex items-center justify-center",children:(0,i.jsxs)("div",{className:"flex flex-col items-center gap-2 text-white/40",children:[(0,i.jsx)(p7,{className:"h-8 w-8"}),(0,i.jsx)("span",{className:"text-xs",children:"No snapshot available"}),(0,i.jsxs)("div",{className:"flex items-center gap-2 mt-1",children:[n&&(0,i.jsxs)("button",{onClick:n,className:"inline-flex items-center gap-1.5 rounded-md border border-white/20 px-3 py-1.5 text-xs font-medium text-white/60 hover:text-white hover:border-white/40 transition-colors",children:[(0,i.jsx)(W_,{className:"h-3 w-3"}),"Retry"]}),(0,i.jsxs)("button",{onClick:r,className:"inline-flex items-center gap-1.5 rounded-md bg-primary/80 px-3 py-1.5 text-xs font-medium text-white hover:bg-primary transition-colors",children:[(0,i.jsx)(sg,{className:"h-3 w-3"}),"Play Live"]})]})]})})}var q_={value:"auto",label:"Auto (best available)"};function y7(e){return e.charAt(0).toUpperCase()+e.slice(1)}function x7({deviceId:e,value:t,onChange:r,disabled:n,label:s,className:a}){const c=(0,l.useId)(),d=d0({deviceId:e},{refetchOnWindowFocus:!1}),[u,f]=(0,l.useState)([q_]);(0,l.useEffect)(()=>{if(!d.data)return;const g=`${e}/`,p=[q_];for(const y of d.data){if(!y.enabled)continue;const S=y.brokerId.startsWith(g)?y.brokerId.slice(g.length):y.brokerId;p.push({value:S,label:y7(S)})}f(p)},[d.data,e]);const h=s??"Preferred stream",m=d.isLoading?"Loading available streams…":d.isError?"Could not load streams — only Auto available.":u.length===1?"No enabled streams found — only Auto available.":null;return(0,i.jsxs)("div",{className:a,children:[(0,i.jsx)("label",{id:c,className:"text-xs font-medium text-foreground-muted block mb-1",children:h}),(0,i.jsx)(ro,{"aria-labelledby":c,options:u,value:t,disabled:n,onChange:g=>r(g.target.value)}),m!==null&&(0,i.jsx)("p",{className:"text-foreground-subtle text-[10px] mt-1",children:m})]})}var S7=2e3;function Q_({value:e,label:t,className:r,disabled:n}){const[s,a]=(0,l.useState)(!1),c=(0,l.useCallback)(()=>{e&&navigator.clipboard.writeText(e).then(()=>{a(!0),setTimeout(()=>a(!1),S7)})},[e]);return(0,i.jsxs)(tn,{size:"sm",variant:"ghost",type:"button",disabled:n||e.length===0,onClick:c,className:A(r),"aria-label":s?"Copied":`Copy ${t??"value"}`,children:[s?(0,i.jsx)(On,{className:"h-3.5 w-3.5 text-success"}):(0,i.jsx)(ii,{className:"h-3.5 w-3.5"}),t?(0,i.jsx)("span",{className:"ml-1",children:s?"Copied":t}):null]})}var _7=Le.z.array(W.ExposedDeviceSchema),w7=Le.z.object({id:Le.z.number(),stableId:Le.z.string(),addonId:Le.z.string(),type:Le.z.string(),name:Le.z.string(),online:Le.z.boolean(),disabled:Le.z.boolean(),parentDeviceId:Le.z.number().nullable(),role:Le.z.string().nullable().optional(),features:Le.z.array(Le.z.string()).optional(),isCamera:Le.z.boolean().optional(),sourceInfo:W.SourceInfoSchema.optional()}),E7=Le.z.array(Le.z.string()),Y_=1e4;function k7(e){return e==="linked"?"success":e==="error"?"danger":"warning"}function T7(e){return e==="linked"?"Linked":e==="unlinked"?"Unlinked":e==="error"?"Error":e}function C7({field:e}){const[t,r]=(0,l.useState)(!1),n=e.secret===!0,s=n&&!t?"•".repeat(Math.min(e.value.length,24)):e.value;return(0,i.jsxs)("div",{className:"flex items-center gap-2 py-1.5",children:[(0,i.jsx)("span",{className:"text-[11px] text-foreground-subtle w-32 shrink-0",children:e.label}),(0,i.jsx)("span",{className:"flex-1 min-w-0 truncate font-mono text-xs text-foreground",children:s||"—"}),n&&(0,i.jsx)(tn,{size:"sm",variant:"ghost",type:"button","aria-label":t?"Hide value":"Reveal value",onClick:()=>r(a=>!a),children:t?(0,i.jsx)(vl,{className:"h-3.5 w-3.5"}):(0,i.jsx)(Ja,{className:"h-3.5 w-3.5"})}),(0,i.jsx)(Q_,{value:e.value,label:e.label})]})}function I7({setup:e}){const t=e.fields??[];return(0,i.jsxs)("div",{className:"border-b border-border bg-surface-hover/10",children:[(0,i.jsxs)("div",{className:"flex items-center gap-2 px-4 py-2 border-b border-border",children:[(0,i.jsx)(yC,{className:"h-3.5 w-3.5 text-foreground-subtle shrink-0"}),(0,i.jsx)("span",{className:"text-[11px] font-semibold text-foreground-subtle uppercase tracking-wide",children:"Setup"})]}),(0,i.jsxs)("div",{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-start",children:[e.qr&&(0,i.jsx)("div",{className:"shrink-0",children:(0,i.jsx)(Vh,{value:e.qr,alt:"Pairing QR code"})}),(0,i.jsxs)("div",{className:"flex-1 min-w-0",children:[e.note&&(0,i.jsx)("p",{className:"text-xs text-foreground-muted whitespace-pre-line mb-2",children:e.note}),t.length>0&&(0,i.jsx)("div",{className:"divide-y divide-border-subtle",children:t.map(r=>(0,i.jsx)(C7,{field:r},r.label))})]})]})]})}function P7({addonId:e,deviceId:t,exposed:r,busy:n,onExpose:s,onUnexpose:a}){const c=d=>{d.stopPropagation(),!n&&(r?a(t):s(t))};return(0,i.jsx)(tn,{size:"sm",variant:r?"ghost":"primary",disabled:n,onClick:c,title:r?`Stop exposing to "${e}"`:`Expose to "${e}"`,children:r?(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(RC,{className:"mr-1 h-3.5 w-3.5"}),"Exposed"]}):(0,i.jsxs)(i.Fragment,{children:[(0,i.jsx)(qd,{className:"mr-1 h-3.5 w-3.5"}),"Expose"]})})}function A7({addonId:e,trpc:t,onOpenDevice:r}){const n=(0,ye.useQueryClient)(),s=f0({nodeId:"hub",addonId:e},{refetchInterval:Y_,retry:!1}),a=m0({nodeId:"hub",addonId:e},{refetchInterval:Y_,retry:!1}),c=h0({nodeId:"hub",addonId:e},{retry:!1}),d=Cf({},{refetchInterval:5e3}),u=(0,l.useCallback)(()=>{n.invalidateQueries({queryKey:[["deviceExport"]]})},[n]),f=g0({onSuccess:u}),h=p0({onSuccess:u}),m=(0,l.useMemo)(()=>{const ne=W.DeviceExportStatusSchema.safeParse(s.data);return ne.success?ne.data:null},[s.data]),g=(0,l.useMemo)(()=>{const ne=_7.safeParse(a.data);return ne.success?ne.data:[]},[a.data]),p=(0,l.useMemo)(()=>new Set(g.map(ne=>ne.deviceId)),[g]),y=(0,l.useMemo)(()=>{const ne=E7.safeParse(c.data);return new Set(ne.success?ne.data:[])},[c.data]),S=(0,l.useMemo)(()=>[...y].sort(),[y]),E=(0,l.useMemo)(()=>S.map(ne=>{const ae=jl(ne);return{id:ne,label:ae.label,icon:ae.icon}}),[S]),T=(0,l.useMemo)(()=>{const ne=d.data;if(!Array.isArray(ne))return[];const ae=[];for(const oe of ne){const pe=w7.safeParse(oe);pe.success&&y.has(pe.data.type)&&ae.push(pe.data)}return ae},[d.data,y]),j=m?.linkState??"unlinked",N=s.isLoading||a.isLoading||c.isLoading||d.isLoading,O=m?.exposedDeviceCount??p.size,U=f.isPending||h.isPending,z=(0,l.useCallback)(ne=>{f.mutate({deviceId:ne,nodeId:"hub",addonId:e})},[f,e]),K=(0,l.useCallback)(ne=>{h.mutate({deviceId:ne,nodeId:"hub",addonId:e})},[h,e]),G=(0,l.useCallback)(ne=>{const ae=String(ne.id);return(0,i.jsx)(P7,{addonId:e,deviceId:ae,exposed:p.has(ae),busy:U,onExpose:z,onUnexpose:K})},[e,p,U,z,K]),X=(0,l.useCallback)(ne=>r?.(String(ne)),[r]),te=S.length>0;return(0,i.jsxs)("div",{className:"rounded-lg border border-border bg-surface overflow-hidden",children:[(0,i.jsxs)("div",{className:"flex items-center justify-between gap-3 px-4 py-2.5 border-b border-border bg-surface-hover/20",children:[(0,i.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[(0,i.jsx)(qd,{className:"h-3.5 w-3.5 text-foreground-subtle shrink-0"}),(0,i.jsx)("span",{className:"text-[11px] font-semibold text-foreground-subtle uppercase tracking-wide",children:"Exported devices"}),(0,i.jsx)(Ai,{variant:k7(j),children:T7(j)}),(0,i.jsxs)("span",{className:"text-[11px] text-foreground-subtle",children:[O," exposed"]})]}),N&&(0,i.jsx)(hr,{className:"h-3.5 w-3.5 animate-spin text-foreground-subtle"})]}),m?.error&&(0,i.jsx)("div",{className:"px-4 py-3 border-b border-border",children:(0,i.jsx)(ao,{message:m.error})}),m?.setup&&(0,i.jsx)(I7,{setup:m.setup}),(0,i.jsx)("div",{className:"p-3",children:te&&T.length>0?(0,i.jsx)(Py,{devices:T,trpc:t,defaultView:"table",filters:{typeOptions:E},urlScope:"nested",lsKey:`device-export:${e}`,onNavigate:r?X:void 0,renderRowAction:G}):(0,i.jsx)(pf,{icon:qd,title:"No exportable devices",description:te?`No devices of the supported kinds (${S.join(", ")}) are available to expose to "${e}".`:`"${e}" reports no exportable device kinds yet.`})})]})}function j7({samples:e,sampleRate:t=16e3,height:r=96,className:n="",color:s="#3b82f6",bgColor:a="transparent"}){const c=(0,l.useRef)(null),d=(0,l.useRef)(null),u=(0,l.useCallback)(()=>{const h=c.current,m=d.current;if(!h||!m||!e||e.length===0)return;const g=m.clientWidth;if(g===0)return;const p=window.devicePixelRatio||1;h.width=g*p,h.height=r*p,h.style.width=`${g}px`,h.style.height=`${r}px`;const y=h.getContext("2d");if(!y)return;y.scale(p,p),a!=="transparent"?(y.fillStyle=a,y.fillRect(0,0,g,r)):y.clearRect(0,0,g,r);const S=e.length/g,E=r/2;y.fillStyle=s,y.globalAlpha=.7;for(let T=0;T<g;T++){const j=Math.floor(T*S),N=Math.min(Math.floor((T+1)*S),e.length);let O=0,U=0;for(let X=j;X<N;X++){const te=e[X];te<O&&(O=te),te>U&&(U=te)}const z=E-U*E,K=E-O*E,G=Math.max(1,K-z);y.fillRect(T,z,1,G)}y.globalAlpha=1,y.strokeStyle=s,y.globalAlpha=.2,y.lineWidth=1,y.beginPath(),y.moveTo(0,E),y.lineTo(g,E),y.stroke(),y.globalAlpha=1},[e,r,s,a]);(0,l.useEffect)(()=>{u()},[u]),(0,l.useEffect)(()=>{const h=new ResizeObserver(()=>u()),m=d.current;return m&&h.observe(m),()=>h.disconnect()},[u]);const f=((e&&t?Math.round(e.length/t*1e3):0)/1e3).toFixed(1);return(0,i.jsxs)("div",{ref:d,className:`relative ${n}`,children:[(0,i.jsx)("canvas",{ref:c,className:"w-full rounded-md"}),e&&e.length>0&&(0,i.jsxs)("div",{className:"absolute bottom-1 right-2 text-[10px] text-foreground-subtle/60 font-mono",children:[f,"s · ",t/1e3,"kHz · ",e.length.toLocaleString()," samples"]})]})}function N7({currentDbfs:e,durationSec:t=30,maxSamples:r=120,height:n=64,className:s="",color:a="#10b981",clipColor:c="#ef4444",clipThreshold:d=-6,minDbfs:u=-96}){const f=(0,l.useRef)(null),h=(0,l.useRef)(null),[m,g]=(0,l.useState)([]);(0,l.useEffect)(()=>{e!==null&&g(S=>{const E=[...S,{dbfs:e,timestamp:Date.now()}];return E.length>r?E.slice(-r):E})},[e,r]);const p=(0,l.useCallback)(()=>{const S=f.current,E=h.current;if(!S||!E)return;const T=E.clientWidth;if(T===0)return;const j=window.devicePixelRatio||1;S.width=T*j,S.height=n*j,S.style.width=`${T}px`,S.style.height=`${n}px`;const N=S.getContext("2d");if(!N||(N.scale(j,j),N.clearRect(0,0,T,n),m.length===0))return;const O=m[m.length-1].timestamp,U=t*1e3,z=O-U,K=m.filter(ne=>ne.timestamp>=z);if(K.length===0)return;const G=Math.max(1,Math.floor(T/(t*2))),X=Math.abs(u);for(const ne of K){const ae=ne.timestamp-z,oe=Math.floor(ae/U*T),pe=(Math.max(u,Math.min(0,ne.dbfs))-u)/X,le=Math.max(1,pe*n);N.fillStyle=ne.dbfs>=d?c:a,N.globalAlpha=.8,N.fillRect(oe,n-le,G,le)}N.globalAlpha=1;const te=n-(d-u)/X*n;N.strokeStyle=c,N.globalAlpha=.25,N.lineWidth=1,N.setLineDash([4,4]),N.beginPath(),N.moveTo(0,te),N.lineTo(T,te),N.stroke(),N.setLineDash([]),N.globalAlpha=1},[m,t,n,a,c,d,u]);(0,l.useEffect)(()=>{p()},[p]),(0,l.useEffect)(()=>{const S=new ResizeObserver(()=>p()),E=h.current;return E&&S.observe(E),()=>S.disconnect()},[p]);const y=m.length>0?m[m.length-1].dbfs:null;return(0,i.jsxs)("div",{ref:h,className:`relative ${s}`,children:[(0,i.jsx)("canvas",{ref:f,className:"w-full rounded-md"}),(0,i.jsxs)("div",{className:"absolute top-1 left-2 text-[9px] text-foreground-subtle/50 font-mono",children:[t,"s"]}),y!==null&&(0,i.jsxs)("div",{className:"absolute bottom-1 right-2 text-[9px] text-foreground-subtle/50 font-mono",children:[y.toFixed(1)," dBFS · ",m.length," samples"]})]})}function D7(e){return e>=.8?"bg-emerald-500":e>=.5?"bg-amber-500":e>=.3?"bg-orange-500":"bg-zinc-500"}function M7(e){return e>=.8?"text-emerald-400":e>=.5?"text-amber-400":e>=.3?"text-orange-400":"text-zinc-400"}function $7({classifications:e,processing:t=!1,inferenceMs:r,maxItems:n=10,className:s=""}){const a=e.slice(0,n),c=a.length>0?a[0].score:1;return t?(0,i.jsx)("div",{className:`rounded-xl border border-border bg-surface p-4 text-center ${s}`,children:(0,i.jsx)("div",{className:"text-sm text-foreground-subtle animate-pulse",children:"Classifying audio..."})}):a.length===0?(0,i.jsx)("div",{className:`rounded-xl border border-border bg-surface p-4 text-center ${s}`,children:(0,i.jsx)("div",{className:"text-xs text-foreground-subtle",children:"No classifications yet"})}):(0,i.jsxs)("div",{className:`rounded-xl border border-border bg-surface overflow-hidden ${s}`,children:[(0,i.jsxs)("div",{className:"px-3 py-2 border-b border-border flex items-center justify-between",children:[(0,i.jsx)("h3",{className:"text-xs font-medium text-foreground",children:"Audio Classifications"}),(0,i.jsxs)("div",{className:"flex items-center gap-3 text-[10px] text-foreground-subtle",children:[a.length<e.length&&(0,i.jsxs)("span",{children:["showing ",a.length," of ",e.length]}),r!==void 0&&(0,i.jsxs)("span",{className:"font-mono",children:[r.toFixed(1),"ms"]})]})]}),(0,i.jsx)("div",{className:"divide-y divide-border/50",children:a.map((d,u)=>{const f=c>0?d.score/c*100:0;return(0,i.jsxs)("div",{className:"px-3 py-1.5 flex items-center gap-3 hover:bg-surface-hover/30",children:[(0,i.jsx)("span",{className:"text-[10px] text-foreground-subtle w-5 text-right font-mono",children:u+1}),(0,i.jsx)("span",{className:"text-xs font-medium text-foreground min-w-[120px]",children:d.className}),(0,i.jsx)("div",{className:"flex-1 h-2 rounded-full bg-zinc-800 overflow-hidden",children:(0,i.jsx)("div",{className:`h-full rounded-full transition-all duration-300 ${D7(d.score)}`,style:{width:`${f}%`}})}),(0,i.jsxs)("span",{className:`text-xs font-mono font-semibold w-14 text-right ${M7(d.score)}`,children:[(d.score*100).toFixed(1),"%"]})]},`${d.className}-${u}`)})})]})}function R7({data:e,label:t="Response",className:r=""}){const[n,s]=(0,l.useState)(!1);if(!e)return null;const a=JSON.stringify(e,null,2);return(0,i.jsxs)("div",{className:`rounded-xl border border-border bg-surface overflow-hidden ${r}`,children:[(0,i.jsxs)("div",{className:"px-3 py-2 border-b border-border flex items-center justify-between cursor-pointer select-none hover:bg-surface-hover/30",onClick:()=>s(c=>!c),children:[(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[(0,i.jsx)("span",{className:"text-[10px] text-foreground-subtle",children:n?"▼":"▶"}),(0,i.jsx)("h3",{className:"text-xs font-medium text-foreground",children:t})]}),(0,i.jsx)("span",{className:"text-[10px] text-foreground-subtle font-mono",children:a.length>1e3?`${(a.length/1024).toFixed(1)} KB`:`${a.length} bytes`})]}),n&&(0,i.jsx)("div",{className:"max-h-80 overflow-y-auto overflow-x-auto",children:(0,i.jsx)("pre",{className:"p-3 text-[10px] leading-4 font-mono text-foreground-subtle whitespace-pre",children:a})})]})}var L7={Activity:wn,Eye:Ja,AlertTriangle:cs,PauseCircle:DT,PowerOff:bC};function O7({phase:e,...t}){const r=L7[yd(e).icon];return(0,i.jsx)(r,{...t})}function Ms(e){const[t,r]=(0,l.useState)([]),n=(0,l.useCallback)(a=>{r(c=>{const d=[...c,a];return d.length>e?d.slice(-e):d})},[e]),s=(0,l.useCallback)(()=>{r([])},[]);return(0,l.useMemo)(()=>({entries:t,append:n,reset:s}),[t,n,s])}function F7(e,t=40){return e.scrollHeight-e.scrollTop-e.clientHeight<=t}function X_(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}var J_={error:{icon:as,color:"text-red-400"},warn:{icon:cs,color:"text-amber-400"},info:{icon:rC,color:"text-blue-400"},debug:{icon:TT,color:"text-gray-500"}},ew={debug:0,info:1,warn:2,error:3},U7=["all","debug","info","warn","error"],B7=500;function z7(e,t){return t?(ew[e]??0)>=(ew[t]??0):!0}function og({agentId:e,addonId:t,deviceId:r,containerDeviceId:n,integrationId:s,requestId:a,level:c,maxHeight:d="max-h-96",showScope:u=!1,showFilters:f=!0,limit:h=100,liveBuffer:m,onClose:g,className:p}){const[y,S]=(0,l.useState)(""),[E,T]=(0,l.useState)(""),[j,N]=(0,l.useState)(c),O=e,U=t??(y||void 0),z=r??(E?Number(E):void 0),K=s,G=a,X=(0,l.useMemo)(()=>{const he={};return O&&(he.agentId=O),U&&(he.addonId=U),n!==void 0&&Number.isFinite(n)?he.containerDeviceId=n:z!==void 0&&Number.isFinite(z)&&(he.deviceId=z),K&&(he.integrationId=K),G&&(he.requestId=G),Object.keys(he).length>0?he:void 0},[O,U,z,n,K,G]),te=Ms(B7),ne=m??te,ae=ne.entries,[oe,pe]=(0,l.useState)(0),[le,se]=(0,l.useState)(!0),Ce=(0,l.useRef)(!1),[q,Q]=(0,l.useState)(!1),[ie,be]=(0,l.useState)(!1),[we,Re]=(0,l.useState)(new Set),[Ee,Fe]=(0,l.useState)(""),Ge=(0,l.useRef)(null),Be=`${O??""}:${U??""}:${String(z??"")}:${String(n??"")}:${K??""}:${G??""}`,st=(0,l.useRef)(Be);(0,l.useEffect)(()=>{st.current!==Be&&(st.current=Be,ne.reset(),pe(0),Re(new Set),Q(!1))},[Be,ne]);const{data:at,isLoading:We}=C.logs.query.useQuery({...X?{tags:X}:{},limit:h},{staleTime:3e4});C.logs.subscribe.useSubscription({...X?{tags:X}:{}},{onData:he=>{ne.append(he)}});const ct=(0,l.useMemo)(()=>{const he=(at??[]).map(dt=>({timestamp:dt.timestamp,level:dt.level,message:dt.message,scope:dt.scope,tags:dt.tags,meta:dt.meta})),rt=new Map;for(const dt of he)rt.set(`${dt.timestamp}|${dt.level}|${dt.scope??""}|${dt.message}`,dt);for(const dt of ae)rt.set(`${dt.timestamp}|${dt.level}|${dt.scope??""}|${dt.message}`,dt);const ut=[...rt.values()].sort((dt,Ue)=>new Date(dt.timestamp).getTime()-new Date(Ue.timestamp).getTime()),gt=(oe>0?ut.filter(dt=>new Date(dt.timestamp).getTime()>oe):ut).filter(dt=>z7(dt.level,j)),Lt=Ee.trim().toLowerCase();return Lt?gt.filter(dt=>{if(dt.message.toLowerCase().includes(Lt)||dt.scope&&dt.scope.toLowerCase().includes(Lt))return!0;if(dt.tags){for(const Ue of Object.values(dt.tags))if(Ue!==void 0&&String(Ue).toLowerCase().includes(Lt))return!0}if(dt.meta){for(const Ue of Object.values(dt.meta))if(Ue!=null&&X_(Ue).toLowerCase().includes(Lt))return!0}return!1}):gt},[at,ae,j,oe,Ee]),He=(0,l.useCallback)(he=>{const rt=Ge.current;rt&&(Ce.current=!0,rt.scrollTo({top:rt.scrollHeight,...he?{behavior:he}:{}}))},[]),[$e,Ke]=(0,l.useState)(!1),ft=(0,l.useRef)(ct.length);(0,l.useLayoutEffect)(()=>{const he=ct.length>ft.current;ft.current=ct.length,he&&(le?He():Ke(!0))},[ct.length,le,He]),(0,l.useEffect)(()=>{le&&$e&&Ke(!1)},[le,$e]);const St=(0,l.useCallback)(()=>{se(!0),He("smooth")},[He]),Rt=(0,l.useCallback)(()=>{if(Ce.current){Ce.current=!1;return}const he=Ge.current;if(!he)return;const rt=F7(he,40);se(ut=>ut===rt?ut:rt)},[]),dr=(0,l.useMemo)(()=>ct.filter(he=>he.tags&&Object.keys(he.tags).length>0||he.meta&&Object.keys(he.meta).length>0).map(he=>`${he.timestamp}|${he.level}|${he.scope??""}|${he.message}`),[ct]),Er=(0,l.useCallback)(()=>{Q(he=>(he&&Re(new Set),!he))},[]),At=(0,l.useCallback)(()=>{const he=ct.map(rt=>{const ut=new Date(rt.timestamp).toLocaleTimeString(),gt=rt.tags?" "+Object.entries(rt.tags).filter(([,Lt])=>Lt).map(([Lt,dt])=>`${Lt}=${dt}`).join(" "):"";return`${ut} [${rt.level.toUpperCase()}]${rt.scope?` [${rt.scope}]`:""}${gt} ${rt.message}`});navigator.clipboard.writeText(he.join(`
189
+ `)).then(()=>{be(!0),setTimeout(()=>be(!1),1500)})},[ct]),jt=C.logs.clear.useMutation(),rr=(0,l.useCallback)(()=>{pe(Date.now()),ne.reset(),jt.mutate({...X?{tags:X}:{}})},[ne,jt,X]),Gt=(0,l.useCallback)(he=>{Re(rt=>{const ut=new Set(rt);return ut.has(he)?ut.delete(he):ut.add(he),ut})},[]),[sn,jr]=(0,l.useState)(null),Wn=(0,l.useCallback)((he,rt)=>{const ut=new Date(he.timestamp).toISOString(),gt=he.tags?" "+Object.entries(he.tags).filter(([,Ue])=>Ue).map(([Ue,lt])=>`${Ue}=${lt}`).join(" "):"",Lt=he.meta&&Object.keys(he.meta).length>0?` meta=${JSON.stringify(he.meta)}`:"",dt=`${ut} [${he.level.toUpperCase()}]${he.scope?` [${he.scope}]`:""}${gt} ${he.message}${Lt}`;navigator.clipboard.writeText(dt).then(()=>{jr(rt),setTimeout(()=>jr(Ue=>Ue===rt?null:Ue),1200)})},[]),Gi=(0,l.useCallback)(he=>`${he.timestamp}|${he.level}|${he.scope??""}|${he.message}`,[]);return(0,i.jsxs)("div",{className:A("h-full min-h-0 flex flex-col",p),onClick:he=>he.stopPropagation(),children:[(0,i.jsxs)("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-hover/30 gap-2 shrink-0",children:[(0,i.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,i.jsx)("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle font-medium",children:"Logs"}),O&&(0,i.jsx)(lg,{label:"agent",value:O}),U&&(0,i.jsx)(lg,{label:"addon",value:U}),z!==void 0&&(0,i.jsx)(lg,{label:"device",value:`#${z}`}),(0,i.jsx)("div",{className:"flex rounded border border-border overflow-hidden text-[9px]",children:U7.map(he=>(0,i.jsxs)("button",{type:"button",onClick:()=>N(he==="all"?void 0:he),className:A("px-1.5 py-0.5 capitalize transition-colors",he==="all"&&!j||j===he?"bg-primary/10 text-primary":"text-foreground-subtle hover:bg-surface-hover",he!=="all"&&"border-l border-border"),children:[he,he!=="all"?"+":""]},he))}),(0,i.jsx)(zc,{icon:yp,label:le?"Following":"Paused",active:le,onClick:()=>{le?se(!1):St()}}),(0,i.jsx)(zc,{icon:q?PT:AT,label:q?"Collapse":"Expand",active:q,onClick:Er,disabled:dr.length===0}),(0,i.jsx)(zc,{icon:ii,label:ie?"Copied!":"Copy",onClick:At,disabled:ct.length===0}),(0,i.jsx)(zc,{icon:en,label:"Clear",onClick:rr}),(0,i.jsxs)("div",{className:"relative",children:[(0,i.jsx)("input",{type:"text",value:Ee,onChange:he=>Fe(he.target.value),placeholder:"Search…",className:"w-32 pl-1.5 pr-5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50"}),Ee&&(0,i.jsx)("button",{type:"button",onClick:()=>Fe(""),className:"absolute right-1 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground",title:"Clear search",children:(0,i.jsx)(mr,{className:"h-2.5 w-2.5"})})]}),ae.length>0&&(0,i.jsxs)("span",{className:"text-[9px] text-emerald-400 font-medium",children:["+",ae.length," live"]})]}),g&&(0,i.jsx)("button",{type:"button",onClick:g,className:"text-foreground-subtle hover:text-foreground",children:(0,i.jsx)(mr,{className:"h-3.5 w-3.5"})})]}),f&&(!t||!r)&&(0,i.jsxs)("div",{className:"flex items-center gap-2 px-3 py-1 border-b border-border/50 bg-surface/50 text-[10px]",children:[!t&&(0,i.jsxs)("label",{className:"flex items-center gap-1",children:[(0,i.jsx)("span",{className:"text-foreground-subtle",children:"Addon:"}),(0,i.jsx)("input",{type:"text",value:y,onChange:he=>S(he.target.value),placeholder:"all",className:"w-28 px-1.5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50"})]}),!r&&(0,i.jsxs)("label",{className:"flex items-center gap-1",children:[(0,i.jsx)("span",{className:"text-foreground-subtle",children:"Device:"}),(0,i.jsx)("input",{type:"text",inputMode:"numeric",value:E,onChange:he=>T(he.target.value),placeholder:"all",className:"w-16 px-1.5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50"})]})]}),(0,i.jsxs)("div",{className:"relative flex-1 min-h-0 flex flex-col",children:[!le&&$e&&(0,i.jsxs)("button",{type:"button",onClick:St,className:"absolute bottom-2 left-1/2 -translate-x-1/2 z-10 inline-flex items-center gap-1 px-2 py-1 rounded-full border border-primary/40 bg-primary/15 text-primary text-[10px] font-medium shadow-md backdrop-blur-sm hover:bg-primary/25 transition-colors",title:"Jump to the newest log line and resume following",children:[(0,i.jsx)(yp,{className:"h-3 w-3"}),"Jump to latest"]}),(0,i.jsxs)("div",{ref:Ge,onScroll:Rt,className:A("flex-1 min-h-0 overflow-auto font-mono text-[10px]",d),children:[We&&(0,i.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-foreground-subtle",children:[(0,i.jsx)(hr,{className:"h-3.5 w-3.5 animate-spin"}),"Loading logs..."]}),!We&&ct.length===0&&(0,i.jsx)("div",{className:"py-4 text-center text-foreground-subtle",children:"No logs found"}),ct.length>0&&(0,i.jsx)("table",{className:"w-full",children:(0,i.jsx)("tbody",{children:ct.map(he=>{const rt=J_[he.level]??J_.info,ut=rt.icon,gt=Gi(he),Lt=q||we.has(gt),dt=he.tags&&Object.keys(he.tags).length>0,Ue=he.meta&&Object.keys(he.meta).length>0,lt=dt||Ue;return(0,i.jsxs)("tr",{className:A("hover:bg-surface-hover/30 border-b border-border/30",lt&&"cursor-pointer"),onClick:lt?()=>Gt(gt):void 0,children:[(0,i.jsx)("td",{className:"px-2 py-1 text-foreground-subtle whitespace-nowrap align-top w-[70px]",children:new Date(he.timestamp).toLocaleTimeString()}),(0,i.jsx)("td",{className:A("px-1 py-1 align-top w-5",rt.color),children:(0,i.jsx)(ut,{className:"h-3 w-3"})}),u&&(0,i.jsx)("td",{className:"px-2 py-1 text-foreground-subtle align-top truncate max-w-[120px]",title:he.scope,children:he.scope?.replace(/^addon:/,"")??""}),(0,i.jsx)("td",{className:"px-2 py-1 text-foreground break-all",children:(0,i.jsxs)("div",{className:"flex items-start gap-1",children:[lt&&(Lt?(0,i.jsx)(fr,{className:"h-3 w-3 text-foreground-subtle shrink-0 mt-0.5"}):(0,i.jsx)(mn,{className:"h-3 w-3 text-foreground-subtle shrink-0 mt-0.5"})),(0,i.jsxs)("div",{className:"flex-1 min-w-0",children:[he.message,Lt&&lt&&(0,i.jsxs)("div",{className:"mt-0.5 pl-3 text-[9px] leading-snug",children:[Ue&&Object.entries(he.meta).filter(([,nt])=>nt!==void 0&&nt!=="").map(([nt,nr])=>(0,i.jsxs)("div",{className:"break-all",children:[(0,i.jsx)("span",{className:"text-amber-400/80",children:nt}),(0,i.jsx)("span",{className:"text-foreground-subtle",children:"="}),(0,i.jsx)("span",{className:"text-foreground",children:X_(nr)})]},`m-${nt}`)),dt&&Object.entries(he.tags).filter(([,nt])=>nt!==void 0).map(([nt,nr])=>(0,i.jsxs)("div",{className:"break-all",children:[(0,i.jsx)("span",{className:"text-primary/70",children:nt}),(0,i.jsx)("span",{className:"text-foreground-subtle",children:"="}),(0,i.jsx)("span",{className:"text-foreground",children:nr})]},`t-${nt}`))]})]})]})}),(0,i.jsx)("td",{className:"px-1 py-1 align-top w-5",children:(0,i.jsx)(Z7,{copied:sn===gt,onCopy:()=>Wn(he,gt)})})]},gt)})})})]})]})]})}function G7({position:e="bottom",className:t,...r}){return(0,i.jsx)("div",{className:A(e==="bottom"?"absolute bottom-0 left-0 right-0 z-10 border-t border-border bg-surface/95 backdrop-blur-sm":"absolute inset-x-2 bottom-2 z-10 rounded-lg border border-border bg-surface/95 backdrop-blur-sm shadow-xl",t),children:(0,i.jsx)(og,{maxHeight:"max-h-48",...r})})}function lg({label:e,value:t}){return(0,i.jsxs)("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium",children:[e,": ",t]})}function Z7({copied:e,onCopy:t}){return(0,i.jsx)("button",{type:"button",title:"Copy this row",onClick:r=>{r.stopPropagation(),t()},className:A("rounded p-0.5 transition-colors",e?"text-emerald-400":"text-foreground-subtle/60 hover:text-foreground hover:bg-surface-hover"),children:e?(0,i.jsx)(On,{className:"h-3 w-3"}):(0,i.jsx)(ii,{className:"h-3 w-3"})})}function zc({icon:e,label:t,onClick:r,disabled:n,active:s}){return(0,i.jsxs)("button",{type:"button",onClick:r,disabled:n,className:A("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors",s?"border-amber-500/30 bg-amber-500/10 text-amber-400":"border-border text-foreground-subtle hover:text-foreground",n&&"opacity-40 cursor-not-allowed"),children:[(0,i.jsx)(e,{className:"h-2.5 w-2.5"}),t]})}function V7(e,t,r,n){if(n!==void 0&&(e.source.deviceId??(e.source.type==="device"&&typeof e.source.id=="number"?e.source.id:void 0))!==n||r!==void 0&&(e.source.addonId??(e.source.type==="addon"&&typeof e.source.id=="string"?e.source.id:void 0))!==r)return!1;if(t!==void 0){const s=e.source.nodeId;if(!s||s!==t&&!s.startsWith(`${t}/`))return!1}return!0}var H7={[W.EventCategory.AddonStarted]:{icon:Fn,color:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30",label:"Started"},[W.EventCategory.AddonInstalled]:{icon:Xa,color:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30",label:"Installed"},[W.EventCategory.AddonRestarted]:{icon:Ii,color:"bg-blue-500/15 text-blue-400 border-blue-500/30",label:"Restarted"},[W.EventCategory.AddonUpdated]:{icon:Hp,color:"bg-blue-500/15 text-blue-400 border-blue-500/30",label:"Updated"},[W.EventCategory.AddonStopped]:{icon:Un,color:"bg-foreground-subtle/10 text-foreground-subtle border-border",label:"Stopped"},[W.EventCategory.AddonUninstalled]:{icon:en,color:"bg-foreground-subtle/10 text-foreground-subtle border-border",label:"Uninstalled"},[W.EventCategory.AddonCrashed]:{icon:as,color:"bg-red-500/15 text-red-400 border-red-500/30",label:"Crashed"},[W.EventCategory.AddonError]:{icon:cs,color:"bg-red-500/15 text-red-400 border-red-500/30",label:"Error"},[W.EventCategory.DetectionPhaseTransition]:{icon:wn,color:"bg-violet-500/15 text-violet-400 border-violet-500/30",label:"Phase"},[W.EventCategory.DetectionResult]:{icon:SC,color:"bg-purple-500/15 text-purple-400 border-purple-500/30",label:"Detection"},[W.EventCategory.DetectionEvent]:{icon:Ja,color:"bg-blue-500/15 text-blue-400 border-blue-500/30",label:"Event"},[W.EventCategory.DetectionCameraNative]:{icon:Vp,color:"bg-cyan-500/15 text-cyan-400 border-cyan-500/30",label:"Camera AI"},[W.EventCategory.ProviderMotion]:{icon:si,color:"bg-orange-500/15 text-orange-400 border-orange-500/30",label:"Motion"},[W.EventCategory.MotionOnMotionChanged]:{icon:si,color:"bg-orange-500/15 text-orange-400 border-orange-500/30",label:"Motion"},[W.EventCategory.MotionAnalysis]:{icon:wn,color:"bg-orange-500/10 text-orange-300 border-orange-500/20",label:"Motion analysis"},[W.EventCategory.MotionZonesRaw]:{icon:wn,color:"bg-orange-500/10 text-orange-300 border-orange-500/20",label:"Motion zones"},[W.EventCategory.ProviderDetection]:{icon:Vp,color:"bg-cyan-500/15 text-cyan-400 border-cyan-500/30",label:"Provider Det"},[W.EventCategory.PipelineAudioInferenceResult]:{icon:$p,color:"bg-pink-500/15 text-pink-400 border-pink-500/30",label:"Audio"},[W.EventCategory.AgentOnline]:{icon:Fn,color:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30",label:"Agent Online"},[W.EventCategory.AgentOffline]:{icon:Un,color:"bg-red-500/15 text-red-400 border-red-500/30",label:"Agent Offline"},[W.EventCategory.DeviceRegistered]:{icon:Xa,color:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30",label:"Registered"},[W.EventCategory.DeviceUnregistered]:{icon:en,color:"bg-red-500/15 text-red-400 border-red-500/30",label:"Unregistered"},[W.EventCategory.DeviceStateChanged]:{icon:wn,color:"bg-foreground-subtle/10 text-foreground-subtle border-border",label:"State"},[W.EventCategory.EventEmitted]:{icon:si,color:"bg-amber-500/15 text-amber-400 border-amber-500/30",label:"Event"}};function cg(e,t){const r=H7[e]??{icon:Fn,color:"bg-foreground-subtle/10 text-foreground-subtle border-border",label:e.split(".").pop()??e};if(e===W.EventCategory.DeviceStateChanged&&t&&typeof t.capName=="string"){const n=t.capName;return{...r,label:n}}return r}var $s=Object.freeze([...new Set(Object.values(W.EventCategory))].sort()),K7=Object.freeze([W.EventCategory.PipelineCameraMetricsSnapshot,W.EventCategory.PipelineRunnerLoadSnapshot,W.EventCategory.PipelineEngineMetricsSnapshot,W.EventCategory.PipelineInferenceResult,W.EventCategory.PipelineTrace,W.EventCategory.PipelineProgress,W.EventCategory.StreamBrokerMetricsSnapshot,W.EventCategory.MetricsNodeResourcesSnapshot,W.EventCategory.MetricsNodeProcessesSnapshot,W.EventCategory.ClusterTopologySnapshot,W.EventCategory.MotionAnalysis,W.EventCategory.MotionZonesRaw,W.EventCategory.DetectionResult,W.EventCategory.PipelineAudioInferenceResult,W.EventCategory.PlatformProbePhase,W.EventCategory.BenchmarkProgress,W.EventCategory.ModelDownloadProgress]),W7=new Set(K7),q7=Object.freeze($s.filter(e=>!W7.has(e)));function Gc(e,t){if(e===W.EventCategory.DetectionPhaseTransition){const s=t.to,a=t.from,c=typeof t.source=="string"?t.source:null,d=typeof t.cooldownMs=="number"?t.cooldownMs:null,u=c?` (${c}${d?`, ${Math.round(d/1e3)}s cooldown`:""})`:"";return s==="active"?`Motion detected — phase active${u}`:s==="watching"?`Cooldown expired — phase watching${u}`:`Phase: ${String(a)} → ${String(s)}${u}`}if(e===W.EventCategory.DetectionResult){const s=t.frame?.detections??[];if(s.length===0)return null;const a=new Map;for(const c of s){const d=c,u=d.class??d.macroClass,f=typeof u=="string"?u:"";f&&a.set(f,(a.get(f)??0)+1)}return[...a.entries()].map(([c,d])=>d>1?`${c} ×${d}`:c).join(", ")}if(e===W.EventCategory.PipelineAudioInferenceResult){const s=t.frame?.detections??[];return s.length===0?null:s.map(a=>{const c=a,d=c.macroClass??c.class??c.label,u=typeof d=="string"?d:"",f=c.score;return f?`${u} (${Math.round(f*100)}%)`:u}).filter(Boolean).join(", ")}if(e===W.EventCategory.DetectionEvent){const s=t.label??t.class,a=t.score??t.confidence,c=[];return typeof s=="string"&&c.push(s),typeof a=="number"&&c.push(`${Math.round(a*100)}%`),c.length>0?c.join(" — "):null}if(e===W.EventCategory.ProviderMotion)return t.active===!0?"motion start":"motion stop";if(e===W.EventCategory.DeviceStateChanged){const s=t.slice;if(s&&typeof s=="object"){const a=Object.keys(s).filter(c=>c!=="lastFetchedAt"&&c!=="ts");if(a.length>0)return a.slice(0,4).join(", ")+(a.length>4?"…":"")}return null}if(e===W.EventCategory.EventEmitted)return(typeof t.eventType=="string"?t.eventType:null)??null;if(e===W.EventCategory.MotionOnMotionChanged){const s=t.detected,a=typeof t.source=="string"?t.source:null,c=s===!0?"motion start":s===!1?"motion stop":"motion";return a?`${c} (${a})`:c}if(e===W.EventCategory.ProviderDetection||e===W.EventCategory.DetectionCameraNative){const s=t.detections??[];if(!Array.isArray(s)||s.length===0)return(typeof t.class=="string"?t.class:null)??null;const a=new Map;for(const c of s){const d=c,u=d.class??d.macroClass,f=typeof u=="string"?u:"";f&&a.set(f,(a.get(f)??0)+1)}return[...a.entries()].map(([c,d])=>d>1?`${c} ×${d}`:c).join(", ")}const r=t.addonId,n=t.error;return n||(r?`addon: ${r}`:null)}function Q7(e){const t=e.category;return t===W.EventCategory.DetectionResult||t===W.EventCategory.PipelineAudioInferenceResult?Gc(t,e.data)!==null:!0}var Y7=300;function ug({agentId:e,addonId:t,deviceId:r,defaultCategories:n,categories:s,category:a,maxHeight:c="max-h-96",limit:d=50,showCategoryFilter:u=!0,showFilters:f=!1,liveBuffer:h,onClose:m,className:g}){const p=(0,l.useMemo)(()=>n??s??q7,[n,s]),y=(0,l.useMemo)(()=>[...p].sort().join(","),[p]),[S,E]=(0,l.useState)(()=>new Set(p)),T=(0,l.useRef)(y);(0,l.useEffect)(()=>{T.current!==y&&(T.current=y,E(new Set(p)))},[y,p]);const j=Ms(Y7),N=h??j,O=N.entries,[U,z]=(0,l.useState)(!0),[K,G]=(0,l.useState)(new Set),[X,te]=(0,l.useState)(""),[ne,ae]=(0,l.useState)(!1),[oe,pe]=(0,l.useState)(""),[le,se]=(0,l.useState)(0),Ce=(0,l.useRef)(null),q=(0,l.useRef)(null),Q=`${e??""}:${t??""}:${String(r??"")}:${a??""}`,ie=(0,l.useRef)(Q);(0,l.useEffect)(()=>{ie.current!==Q&&(ie.current=Q,N.reset(),G(new Set),se(0))},[Q,N]),(0,l.useEffect)(()=>{if(!ne)return;const he=rt=>{const ut=q.current;ut&&rt.target instanceof Node&&!ut.contains(rt.target)&&ae(!1)};return document.addEventListener("mousedown",he),()=>{document.removeEventListener("mousedown",he)}},[ne]);const be=(0,l.useMemo)(()=>{const he={};return e&&(he.agentId=e),t&&(he.addonId=t),r!==void 0&&(he.deviceId=r),a&&(he.category=a),he},[e,t,r,a]),we=(0,l.useMemo)(()=>[...S].sort(),[S]),Re=(0,l.useMemo)(()=>{const he={...be,limit:d};return we.length>0&&we.length<$s.length&&(he.category=we),he},[be,d,(0,l.useMemo)(()=>we.join(","),[we]),we]),{data:Ee,isLoading:Fe}=C.systemEvents.getRecent.useQuery(Re,{staleTime:3e4}),Ge=(0,l.useRef)(S);(0,l.useEffect)(()=>{Ge.current=S},[S]);const Be=be;C.systemEvents.subscribe.useSubscription(Be,{onData:he=>{const rt=he;rt?.id&&V7(rt,e,t,r)&&Ge.current.has(rt.category)&&N.append(rt)}});const st=(0,l.useRef)(O.length);(0,l.useEffect)(()=>{const he=Ce.current;if(!he){st.current=O.length;return}const rt=st.current;if(st.current=O.length,!(O.length<=rt)){if(U&&he.scrollTop<=8)he.scrollTo({top:0});else if(!U&&he.scrollTop>0){const ut=he.firstElementChild?.firstElementChild,gt=ut instanceof HTMLElement?ut.offsetHeight:28;he.scrollTop+=gt*(O.length-rt)}}},[O.length,U]);const at=(0,l.useMemo)(()=>{const he=new Map;for(const gt of Ee??[])he.set(gt.id,gt);for(const gt of O)he.set(gt.id,gt);let rt=[...he.values()].filter(gt=>S.has(gt.category)).filter(Q7);le>0&&(rt=rt.filter(gt=>new Date(gt.timestamp).getTime()>le));const ut=X.trim().toLowerCase();return ut&&(rt=rt.filter(gt=>{if(gt.category.toLowerCase().includes(ut)||cg(gt.category,gt.data).label.toLowerCase().includes(ut))return!0;const Lt=Gc(gt.category,gt.data);if(Lt&&Lt.toLowerCase().includes(ut))return!0;try{if(new Date(gt.timestamp).toLocaleTimeString().toLowerCase().includes(ut))return!0}catch{}try{if(JSON.stringify(gt.data).toLowerCase().includes(ut)||JSON.stringify(gt.source).toLowerCase().includes(ut))return!0}catch{}return!1})),rt.sort((gt,Lt)=>new Date(Lt.timestamp).getTime()-new Date(gt.timestamp).getTime())},[Ee,O,S,X,le]),We=(0,l.useCallback)(he=>{G(rt=>{const ut=new Set(rt);return ut.has(he)?ut.delete(he):ut.add(he),ut})},[]),ct=(0,l.useCallback)(he=>{E(rt=>{const ut=new Set(rt);return ut.has(he)?ut.delete(he):ut.add(he),ut})},[]),He=(0,l.useCallback)(()=>{E(new Set(p)),te(""),se(0)},[p]),$e=(0,l.useCallback)(()=>{se(Date.now()),N.reset()},[N]),[Ke,ft]=(0,l.useState)(!1),[St,Rt]=(0,l.useState)(null),dr=(0,l.useCallback)(he=>{const rt=new Date(he.timestamp).toISOString(),ut=Gc(he.category,he.data)??"",gt=ut?` ${ut}`:"";return`${rt} [${he.category}]${gt} data=${JSON.stringify(he.data)}`},[]),Er=(0,l.useCallback)(()=>{const he=at.map(dr);navigator.clipboard.writeText(he.join(`
190
+ `)).then(()=>{ft(!0),setTimeout(()=>ft(!1),1500)})},[at,dr]),At=(0,l.useCallback)(he=>{navigator.clipboard.writeText(dr(he)).then(()=>{Rt(he.id),setTimeout(()=>Rt(rt=>rt===he.id?null:rt),1200)})},[dr]),jt=(0,l.useCallback)(()=>{E(new Set($s))},[]),rr=(0,l.useCallback)(()=>{E(new Set)},[]),Gt=(0,l.useMemo)(()=>{const he=oe.trim().toLowerCase();return he?$s.filter(rt=>rt.toLowerCase().includes(he)):$s},[oe]),sn=$s.length,jr=S.size,Wn=jr===sn,Gi=Wn?"All":`${jr}/${sn}`;return(0,i.jsxs)("div",{className:A("h-full min-h-0 flex flex-col",g),onClick:he=>he.stopPropagation(),children:[(0,i.jsxs)("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-hover/30 gap-2 shrink-0",children:[(0,i.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,i.jsx)("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle font-medium",children:"Events"}),e&&(0,i.jsx)(Zc,{label:"agent",value:e}),t&&(0,i.jsx)(Zc,{label:"addon",value:t}),r!==void 0&&(0,i.jsx)(Zc,{label:"device",value:`#${r}`}),a&&(0,i.jsx)(Zc,{label:"category",value:a}),(0,i.jsxs)("button",{type:"button",onClick:()=>{z(he=>!he),!U&&Ce.current&&Ce.current.scrollTo({top:0,behavior:"smooth"})},className:A("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors",U?"border-border text-foreground-subtle hover:text-foreground":"border-amber-500/30 bg-amber-500/10 text-amber-400"),children:[(0,i.jsx)(bT,{className:"h-2.5 w-2.5"}),U?"Auto":"Paused"]}),u&&(0,i.jsxs)("div",{className:"relative",ref:q,children:[(0,i.jsxs)("button",{type:"button",onClick:()=>ae(he=>!he),className:A("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors",Wn?"border-border text-foreground-subtle hover:text-foreground":"border-violet-500/30 bg-violet-500/10 text-violet-400"),title:"Pick events to track",children:[(0,i.jsx)(Ap,{className:"h-2.5 w-2.5"}),"Filter (",Gi,")"]}),ne&&(0,i.jsx)(X7,{search:oe,onSearchChange:pe,categories:Gt,active:S,onToggle:ct,onSelectAll:jt,onSelectNone:rr,onResetDefaults:He})]}),(0,i.jsxs)("button",{type:"button",onClick:He,className:"inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground transition-colors",title:"Reset filters to defaults",children:[(0,i.jsx)(Kd,{className:"h-2.5 w-2.5"}),"Reset"]}),(0,i.jsxs)("button",{type:"button",onClick:$e,className:"inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground transition-colors",title:"Clear visible entries",children:[(0,i.jsx)(en,{className:"h-2.5 w-2.5"}),"Clear"]}),(0,i.jsxs)("button",{type:"button",onClick:Er,disabled:at.length===0,className:A("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors",Ke?"border-emerald-500/30 bg-emerald-500/10 text-emerald-400":"border-border text-foreground-subtle hover:text-foreground",at.length===0&&"opacity-40 cursor-not-allowed"),title:"Copy all visible events",children:[(0,i.jsx)(ii,{className:"h-2.5 w-2.5"}),Ke?"Copied!":"Copy"]}),(0,i.jsxs)("div",{className:"relative",children:[(0,i.jsx)("input",{type:"text",value:X,onChange:he=>te(he.target.value),placeholder:"Search…",className:"w-32 pl-1.5 pr-5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50"}),X&&(0,i.jsx)("button",{type:"button",onClick:()=>te(""),className:"absolute right-1 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground",title:"Clear search",children:(0,i.jsx)(mr,{className:"h-2.5 w-2.5"})})]}),O.length>0&&(0,i.jsxs)("span",{className:"text-[9px] text-emerald-400 font-medium",children:["+",O.length," live"]})]}),m&&(0,i.jsx)("button",{type:"button",onClick:m,className:"text-foreground-subtle hover:text-foreground",children:(0,i.jsx)(mr,{className:"h-3.5 w-3.5"})})]}),(0,i.jsxs)("div",{ref:Ce,className:A("flex-1 min-h-0 overflow-auto text-[10px]",c),children:[Fe&&(0,i.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-foreground-subtle",children:[(0,i.jsx)(hr,{className:"h-3.5 w-3.5 animate-spin"}),"Loading events..."]}),!Fe&&at.length===0&&(0,i.jsx)("div",{className:"py-4 text-center text-foreground-subtle",children:"No events found"}),at.length>0&&(0,i.jsx)("div",{className:"divide-y divide-border/30",children:at.map(he=>{const rt=cg(he.category,he.data),ut=rt.icon,gt=Gc(he.category,he.data),Lt=K.has(he.id);return(0,i.jsxs)("div",{className:"flex items-start gap-2 px-3 py-1.5 hover:bg-surface-hover/30 cursor-pointer",onClick:()=>We(he.id),children:[(0,i.jsx)("span",{className:"text-foreground-subtle whitespace-nowrap w-[70px] shrink-0 pt-0.5",children:new Date(he.timestamp).toLocaleTimeString()}),(0,i.jsx)(eH,{copied:St===he.id,onCopy:()=>At(he)}),(0,i.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,i.jsxs)("div",{className:"flex items-center gap-1.5",children:[Lt?(0,i.jsx)(fr,{className:"h-3 w-3 text-foreground-subtle shrink-0"}):(0,i.jsx)(mn,{className:"h-3 w-3 text-foreground-subtle shrink-0"}),(0,i.jsxs)("span",{className:A("inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[9px] font-medium",rt.color),children:[(0,i.jsx)(ut,{className:"h-2.5 w-2.5"}),rt.label]}),he.source.nodeId&&he.source.nodeId!=="hub"&&(0,i.jsx)("span",{className:"text-[9px] px-1 py-0.5 rounded bg-foreground-subtle/10 text-foreground-subtle font-mono",children:he.source.nodeId})]}),gt&&(0,i.jsx)("p",{className:"text-foreground-subtle text-[10px] mt-0.5 ml-5",children:gt}),Lt&&(0,i.jsxs)("div",{className:"mt-1 ml-5 text-[9px] bg-surface rounded px-2 py-1.5 space-y-0.5 font-mono overflow-x-auto",children:[(0,i.jsxs)("div",{children:[(0,i.jsx)("span",{className:"text-primary/70",children:"source"}),(0,i.jsx)("span",{className:"text-foreground-subtle",children:": "}),(0,i.jsx)("span",{className:"text-foreground",children:JSON.stringify(he.source)})]}),(0,i.jsxs)("div",{children:[(0,i.jsx)("span",{className:"text-primary/70",children:"category"}),(0,i.jsx)("span",{className:"text-foreground-subtle",children:": "}),(0,i.jsx)("span",{className:"text-foreground",children:he.category})]}),Object.entries(he.data).map(([dt,Ue])=>(0,i.jsxs)("div",{children:[(0,i.jsx)("span",{className:"text-primary/70",children:dt}),(0,i.jsx)("span",{className:"text-foreground-subtle",children:": "}),(0,i.jsx)("span",{className:"text-foreground break-all",children:typeof Ue=="object"?JSON.stringify(Ue):String(Ue)})]},dt))]})]})]},he.id)})})]})]})}function X7({search:e,onSearchChange:t,categories:r,active:n,onToggle:s,onSelectAll:a,onSelectNone:c,onResetDefaults:d}){return(0,i.jsxs)("div",{className:"absolute z-20 top-full mt-1 left-0 w-72 max-h-80 rounded-md border border-border bg-surface shadow-lg flex flex-col",onClick:u=>u.stopPropagation(),children:[(0,i.jsxs)("div",{className:"flex items-center gap-1 px-2 py-1.5 border-b border-border/50",children:[(0,i.jsx)(ls,{className:"h-3 w-3 text-foreground-subtle"}),(0,i.jsx)("input",{type:"text",value:e,onChange:u=>t(u.target.value),placeholder:"Filter categories…",className:"flex-1 bg-transparent text-[10px] focus:outline-none text-foreground placeholder:text-foreground-subtle",autoFocus:!0}),e&&(0,i.jsx)("button",{type:"button",onClick:()=>t(""),className:"text-foreground-subtle hover:text-foreground",children:(0,i.jsx)(mr,{className:"h-2.5 w-2.5"})})]}),(0,i.jsxs)("div",{className:"flex items-center gap-1 px-2 py-1 border-b border-border/50 text-[9px]",children:[(0,i.jsx)("button",{type:"button",onClick:a,className:"px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground",children:"All"}),(0,i.jsx)("button",{type:"button",onClick:c,className:"px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground",children:"None"}),(0,i.jsx)("button",{type:"button",onClick:d,className:"px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground",children:"Defaults"})]}),(0,i.jsxs)("div",{className:"overflow-y-auto flex-1",children:[r.length===0&&(0,i.jsx)("div",{className:"text-[10px] text-foreground-subtle italic px-2 py-3 text-center",children:"No matches"}),r.map(u=>{const f=n.has(u),h=cg(u),m=h.icon;return(0,i.jsxs)("button",{type:"button",onClick:()=>s(u),className:"w-full flex items-center gap-2 px-2 py-1 text-left hover:bg-surface-hover/40 text-[10px]",children:[(0,i.jsx)("input",{type:"checkbox",readOnly:!0,checked:f,className:"accent-violet-500"}),(0,i.jsxs)("span",{className:A("inline-flex items-center gap-1 rounded-full border px-1.5 py-0.5 text-[9px] font-medium shrink-0",h.color),children:[(0,i.jsx)(m,{className:"h-2.5 w-2.5"}),h.label]}),(0,i.jsx)("span",{className:"text-foreground-subtle font-mono truncate",children:u})]},u)})]})]})}function J7({position:e="bottom",className:t,...r}){return(0,i.jsx)("div",{className:A(e==="bottom"?"absolute bottom-0 left-0 right-0 z-10 border-t border-border bg-surface/95 backdrop-blur-sm":"absolute inset-x-2 bottom-2 z-10 rounded-lg border border-border bg-surface/95 backdrop-blur-sm shadow-xl",t),children:(0,i.jsx)(ug,{maxHeight:"max-h-48",...r})})}function Zc({label:e,value:t}){return(0,i.jsxs)("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium",children:[e,": ",t]})}function eH({copied:e,onCopy:t}){return(0,i.jsx)("button",{type:"button",title:"Copy this event",onClick:r=>{r.stopPropagation(),t()},className:A("rounded p-0.5 transition-colors mt-0.5",e?"text-emerald-400":"text-foreground-subtle/60 hover:text-foreground hover:bg-surface-hover"),children:e?(0,i.jsx)(On,{className:"h-3 w-3"}):(0,i.jsx)(ii,{className:"h-3 w-3"})})}function tH({deviceId:e,className:t="",onOpenChild:r}){const n=C.useUtils(),s=C.deviceDiscovery.listDiscovered.useQuery({deviceId:e},{refetchInterval:1e4,retry:!1}),a=C.deviceDiscovery.getStatus.useQuery({deviceId:e},{refetchInterval:1e4,retry:!1}),c=C.deviceDiscovery.refreshDiscovery.useMutation({onSuccess:()=>{n.deviceDiscovery.listDiscovered.invalidate({deviceId:e}),n.deviceDiscovery.getStatus.invalidate({deviceId:e})}}),d=C.deviceDiscovery.adoptDevice.useMutation({onSuccess:()=>{n.deviceDiscovery.listDiscovered.invalidate({deviceId:e})}}),u=C.deviceDiscovery.releaseDevice.useMutation({onSuccess:()=>{n.deviceDiscovery.listDiscovered.invalidate({deviceId:e})}}),[f,h]=(0,l.useState)(null),{available:m,adopted:g}=(0,l.useMemo)(()=>{const N=s.data??[],O=z=>typeof z.metadata.rtspChannel=="number"?z.metadata.rtspChannel:Number.POSITIVE_INFINITY,U=(z,K)=>{const G=O(z),X=O(K);return G!==X?G-X:z.name.localeCompare(K.name)};return{available:N.filter(z=>!z.alreadyAdopted).sort(U),adopted:N.filter(z=>z.alreadyAdopted).sort(U)}},[s.data]),p=a.data,y=p?.lastError??null,S=p?.lastDiscoveryAt??null;async function E(){await c.mutateAsync({deviceId:e}).catch(()=>{})}async function T(N){h(N.childNativeId);try{await d.mutateAsync({deviceId:e,childNativeId:N.childNativeId})}finally{h(null)}}async function j(N){if(N.adoptedDeviceId!=null){h(N.childNativeId);try{await u.mutateAsync({deviceId:e,childDeviceId:N.adoptedDeviceId})}finally{h(null)}}}return(0,i.jsxs)("div",{className:`rounded-xl border border-border bg-surface ${t}`,children:[(0,i.jsxs)("div",{className:"flex items-start justify-between gap-2 border-b border-border px-3 py-2 sm:px-5 sm:py-3",children:[(0,i.jsxs)("div",{className:"min-w-0",children:[(0,i.jsx)("h3",{className:"text-sm font-semibold text-foreground",children:"Discovered devices"}),(0,i.jsxs)("p",{className:"text-[11px] text-foreground-subtle",children:["Channels behind this hub. Click ",(0,i.jsx)("span",{className:"font-medium",children:"Add"})," to promote a channel to a managed device, or ",(0,i.jsx)("span",{className:"font-medium",children:"Remove"})," to detach."]})]}),(0,i.jsxs)("button",{type:"button",onClick:E,disabled:c.isPending,className:"inline-flex items-center gap-1.5 rounded-lg border border-border px-2 py-1.5 sm:px-3 text-xs font-medium text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors disabled:opacity-50 shrink-0",children:[c.isPending?(0,i.jsx)(hr,{className:"h-3.5 w-3.5 animate-spin"}):(0,i.jsx)(Ii,{className:"h-3.5 w-3.5"}),(0,i.jsx)("span",{className:"hidden sm:inline",children:"Refresh"})]})]}),y?(0,i.jsxs)("div",{className:"flex items-start gap-2 border-b border-border bg-destructive/10 px-5 py-2 text-[11px] text-destructive",children:[(0,i.jsx)(cs,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),(0,i.jsxs)("span",{children:["Last refresh failed: ",y]})]}):null,s.isLoading?(0,i.jsx)("div",{className:"flex items-center justify-center py-8 text-foreground-subtle",children:(0,i.jsx)(hr,{className:"h-5 w-5 animate-spin"})}):m.length===0&&g.length===0?(0,i.jsx)("div",{className:"px-5 py-8 text-center text-xs text-foreground-subtle",children:"No channels reported by the hub yet. Click Refresh to enumerate."}):(0,i.jsxs)(i.Fragment,{children:[m.length>0?(0,i.jsx)(tw,{title:"Available to add",count:m.length,tone:"primary",children:m.map(N=>(0,i.jsx)(rw,{child:N,busy:f===N.childNativeId,onAdopt:T,onRelease:j,onOpenChild:r},N.childNativeId))}):null,g.length>0?(0,i.jsx)(tw,{title:"Already adopted",count:g.length,tone:"muted",children:g.map(N=>(0,i.jsx)(rw,{child:N,busy:f===N.childNativeId,onAdopt:T,onRelease:j,onOpenChild:r},N.childNativeId))}):null]}),S!=null?(0,i.jsxs)("div",{className:"border-t border-border px-5 py-2 text-[10px] text-foreground-subtle",children:["Last refreshed ",new Date(S).toLocaleString()]}):null]})}function tw({title:e,count:t,tone:r,children:n}){return(0,i.jsxs)("div",{className:"border-t border-border",children:[(0,i.jsxs)("div",{className:`flex items-center justify-between border-b px-3 sm:px-5 py-1.5 text-[10px] uppercase tracking-wider ${r==="primary"?"bg-primary/5 text-primary border-primary/30":"bg-surface text-foreground-subtle border-border"}`,children:[(0,i.jsx)("span",{className:"font-semibold",children:e}),(0,i.jsx)("span",{className:"font-mono",children:t})]}),(0,i.jsx)("div",{className:"divide-y divide-border",children:n})]})}function rw({child:e,busy:t,onAdopt:r,onRelease:n,onOpenChild:s}){return(0,i.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-2 px-3 py-2 sm:px-5 sm:py-3 sm:flex-nowrap sm:gap-3",children:[(0,i.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,i.jsxs)("div",{className:"flex flex-wrap items-center gap-x-2 gap-y-1",children:[(0,i.jsx)(rH,{status:e.status}),(0,i.jsx)("span",{className:"truncate text-sm font-medium text-foreground",children:e.name}),e.metadata.isDoorbell?(0,i.jsx)("span",{className:"rounded bg-surface-hover px-1.5 py-0.5 text-[9px] uppercase tracking-wide text-foreground-subtle",children:"Doorbell"}):null,e.metadata.isBattery?(0,i.jsx)("span",{className:"rounded bg-surface-hover px-1.5 py-0.5 text-[9px] uppercase tracking-wide text-foreground-subtle",children:"Battery"}):null,e.metadata.isMultifocal?(0,i.jsx)("span",{className:"rounded bg-surface-hover px-1.5 py-0.5 text-[9px] uppercase tracking-wide text-foreground-subtle",children:"Multifocal"}):null]}),(0,i.jsxs)("div",{className:"mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[11px] text-foreground-subtle",children:[typeof e.metadata.rtspChannel=="number"?(0,i.jsxs)("span",{children:["ch ",(0,i.jsx)("span",{className:"font-mono",children:e.metadata.rtspChannel})]}):null,e.metadata.model?(0,i.jsx)("span",{className:"truncate max-w-[160px]",children:e.metadata.model}):null,e.metadata.uid?(0,i.jsxs)("span",{className:"font-mono truncate max-w-[140px]",children:[e.metadata.uid.slice(0,12),"…"]}):null]})]}),e.alreadyAdopted?(0,i.jsxs)("div",{className:"flex items-center gap-2",children:[s&&e.adoptedDeviceId!==null?(0,i.jsxs)("button",{type:"button",onClick:()=>s(e.adoptedDeviceId),className:"inline-flex items-center gap-1.5 rounded-lg border border-border px-3 py-1.5 text-xs text-foreground-subtle hover:text-foreground hover:bg-surface-hover transition-colors",title:"Open device detail",children:[(0,i.jsx)(Ip,{className:"h-3.5 w-3.5"}),"Open"]}):null,(0,i.jsxs)("button",{type:"button",onClick:()=>{n(e)},disabled:t,className:"inline-flex items-center gap-1.5 rounded-lg border border-destructive/30 px-3 py-1.5 text-xs text-destructive hover:bg-destructive/10 transition-colors disabled:opacity-50",children:[t?(0,i.jsx)(hr,{className:"h-3.5 w-3.5 animate-spin"}):(0,i.jsx)(en,{className:"h-3.5 w-3.5"}),"Remove"]})]}):(0,i.jsxs)("button",{type:"button",onClick:()=>{r(e)},disabled:t,className:"inline-flex items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-xs font-medium text-primary-foreground shadow-sm disabled:opacity-50",children:[t?(0,i.jsx)(hr,{className:"h-3.5 w-3.5 animate-spin"}):(0,i.jsx)(Ci,{className:"h-3.5 w-3.5"}),"Add"]})]})}function rH({status:e}){switch(e){case"online":return(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 rounded-full border border-emerald-500/40 bg-emerald-500/10 px-2 py-0.5 text-[10px] font-medium text-emerald-500",children:[(0,i.jsx)(rf,{className:"h-2.5 w-2.5"})," online"]});case"sleeping":return(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 rounded-full border border-amber-500/40 bg-amber-500/10 px-2 py-0.5 text-[10px] font-medium text-amber-500",children:[(0,i.jsx)(bl,{className:"h-2.5 w-2.5"})," sleeping"]});case"offline":return(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 rounded-full border border-destructive/40 bg-destructive/10 px-2 py-0.5 text-[10px] font-medium text-destructive",children:[(0,i.jsx)(Kp,{className:"h-2.5 w-2.5"})," offline"]});default:return(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 rounded-full border border-border bg-surface px-2 py-0.5 text-[10px] font-medium text-foreground-subtle",children:[(0,i.jsx)(Ep,{className:"h-2.5 w-2.5"})," unknown"]})}}function nH(e,t){if(!e||typeof e!="object")return null;const r=e;if(r.category!==W.EventCategory.DeviceStateChanged)return null;const n=r.data;return!n||typeof n!="object"||n.deviceId!==t||typeof n.capName!="string"||!n.slice||typeof n.slice!="object"?null:{capName:n.capName,slice:n.slice}}function iH(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function sH(e){if(!e||typeof e!="object")return!1;const t=e;return typeof t.source!="string"?!1:!!t.data&&typeof t.data=="object"&&!Array.isArray(t.data)}function aH(e,t){const r=new Map;for(const[n,s]of Object.entries(e)){const a=s&&typeof s=="object"&&!Array.isArray(s)?s:{value:s};r.set(n,{slice:a,updatedAt:t})}return r}var oH=Object.freeze([...new Set(W.ALL_CAPABILITY_DEFINITIONS.filter(e=>e.scope==="device").map(e=>e.name))].sort()),lH=1;function nw({deviceId:e,defaultCaps:t,maxHeight:r="max-h-96",onClose:n,className:s}){const[a,c]=(0,l.useState)((0,l.useMemo)(()=>new Set(t??[]),[t])),[d,u]=(0,l.useState)(""),[f,h]=(0,l.useState)(!1),[m,g]=(0,l.useState)(""),[p,y]=(0,l.useState)("normalized"),S=(0,l.useRef)(null),[E,T]=(0,l.useState)(new Map),[j,N]=(0,l.useState)(new Map),[,O]=(0,l.useState)(0),U=(0,l.useRef)(e);(0,l.useEffect)(()=>{U.current!==e&&(U.current=e,T(new Map),N(new Map))},[e]);const{data:z,isLoading:K}=C.deviceState.getAllSnapshots.useQuery({},{staleTime:3e4}),G=(0,l.useRef)(!1);(0,l.useEffect)(()=>{if(G.current||!iH(z))return;const He=z[String(e)];if(G.current=!0,!He)return;const $e=Date.now();T(Ke=>{const ft=new Map(Ke);for(const[St,Rt]of Object.entries(He))ft.has(St)||ft.set(St,{slice:Rt,updatedAt:$e});return ft})},[z,e]),(0,l.useEffect)(()=>{G.current=!1},[e]);const X=(0,l.useCallback)((He,$e)=>{T(Ke=>{const ft=new Map(Ke);return ft.set(He,{slice:$e,updatedAt:Date.now()}),ft})},[]),te=Br(Mr().trpcClient,e)?.deviceOps?.getRawState,ne=(0,ye.useQuery)({queryKey:["device-raw-state",e],queryFn:()=>te({deviceId:e}),enabled:te!=null,staleTime:6e4}),ae=sH(ne.data)?ne.data:null,oe=ne.isFetched&&!ne.isError&&ae!=null;(0,l.useEffect)(()=>{p==="raw"&&!oe&&y("normalized")},[p,oe]);const pe=(0,l.useMemo)(()=>ae?aH(ae.data,ne.dataUpdatedAt||Date.now()):new Map,[ae,ne.dataUpdatedAt]);(0,l.useEffect)(()=>{const He=setInterval(()=>O($e=>$e+1),5e3);return()=>clearInterval(He)},[]);const le=(0,l.useMemo)(()=>{const He=new Set(oH);for(const $e of E.keys())He.add($e);return[...He].sort()},[E]),se=(0,l.useMemo)(()=>{const He=d.trim().toLowerCase();return[...E.keys()].sort().filter($e=>a.size>0&&!a.has($e)?!1:!He||$e.toLowerCase().includes(He)?!0:hg(E.get($e)?.slice??{},He))},[E,a,d]),Ce=(0,l.useCallback)(He=>{c($e=>{const Ke=new Set($e);return Ke.has(He)?Ke.delete(He):Ke.add(He),Ke})},[]),q=(0,l.useCallback)(()=>{c(new Set(t??[])),u("")},[t]),Q=(0,l.useCallback)(()=>{c(new Set(le))},[le]),ie=(0,l.useCallback)(()=>{c(new Set)},[]),be=(0,l.useCallback)((He,$e)=>{N(Ke=>{const ft=new Map(Ke);return ft.set(He,!$e),ft})},[]),we=(0,l.useCallback)((He,$e)=>{const Ke=j.get(He);return Ke!==void 0?Ke:$e<lH},[j]),[Re,Ee]=(0,l.useState)(!1),Fe=(0,l.useCallback)(()=>{const He={};for(const $e of se){const Ke=E.get($e);Ke&&(He[$e]=Ke.slice)}navigator.clipboard.writeText(JSON.stringify(He,null,2)).then(()=>{Ee(!0),setTimeout(()=>Ee(!1),1500)})},[se,E]),Ge=(0,l.useMemo)(()=>{const He=m.trim().toLowerCase();return He?le.filter($e=>$e.toLowerCase().includes(He)):le},[m,le]),Be=le.length,st=a.size,at=st===0||st===Be,We=at?"All":`${st}/${Be}`;(0,l.useEffect)(()=>{if(!f)return;const He=$e=>{const Ke=S.current;Ke&&!Ke.contains($e.target)&&h(!1)};return document.addEventListener("mousedown",He),()=>document.removeEventListener("mousedown",He)},[f]);const ct=d.trim().toLowerCase();return(0,i.jsxs)("div",{className:A("h-full min-h-0 flex flex-col",s),onClick:He=>He.stopPropagation(),children:[(0,i.jsxs)("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-hover/30 gap-2 shrink-0",children:[(0,i.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,i.jsx)("span",{className:"text-[10px] uppercase tracking-wide text-foreground-subtle font-medium",children:"State"}),(0,i.jsx)(mH,{label:"device",value:`#${e}`}),oe&&(0,i.jsx)(cH,{mode:p,onChange:y}),p==="normalized"&&(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("div",{className:"relative",ref:S,children:[(0,i.jsxs)("button",{type:"button",onClick:()=>h(He=>!He),className:A("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors",at?"border-border text-foreground-subtle hover:text-foreground":"border-violet-500/30 bg-violet-500/10 text-violet-400"),title:"Pick caps to show",children:[(0,i.jsx)(Ap,{className:"h-2.5 w-2.5"}),"Filter (",We,")"]}),f&&(0,i.jsx)(gH,{search:m,onSearchChange:g,caps:Ge,active:a,onToggle:Ce,onSelectAll:Q,onSelectNone:ie,onResetDefaults:q})]}),(0,i.jsxs)("button",{type:"button",onClick:q,className:"inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground transition-colors",title:"Reset filters",children:[(0,i.jsx)(Kd,{className:"h-2.5 w-2.5"}),"Reset"]}),(0,i.jsxs)("button",{type:"button",onClick:Fe,disabled:se.length===0,className:A("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border transition-colors",Re?"border-emerald-500/30 bg-emerald-500/10 text-emerald-400":"border-border text-foreground-subtle hover:text-foreground",se.length===0&&"opacity-40 cursor-not-allowed"),title:"Copy visible state as JSON",children:[(0,i.jsx)(ii,{className:"h-2.5 w-2.5"}),Re?"Copied!":"Copy"]}),(0,i.jsxs)("div",{className:"relative",children:[(0,i.jsx)("input",{type:"text",value:d,onChange:He=>u(He.target.value),placeholder:"Search…",className:"w-32 pl-1.5 pr-5 py-0.5 rounded border border-border bg-background text-foreground text-[10px] focus:outline-none focus:border-primary/50"}),d&&(0,i.jsx)("button",{type:"button",onClick:()=>u(""),className:"absolute right-1 top-1/2 -translate-y-1/2 text-foreground-subtle hover:text-foreground",title:"Clear search",children:(0,i.jsx)(mr,{className:"h-2.5 w-2.5"})})]}),(0,i.jsxs)("span",{className:"text-[9px] text-emerald-400 font-medium inline-flex items-center gap-1",children:[(0,i.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-400 animate-pulse"}),"live"]})]}),p==="raw"&&ae&&(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 rounded-full border border-sky-500/30 bg-sky-500/15 text-sky-400 px-2 py-0.5 text-[9px] font-medium font-sans",children:["source: ",ae.source]}),(0,i.jsxs)("button",{type:"button",onClick:()=>ne.refetch(),disabled:ne.isFetching,className:A("inline-flex items-center gap-1 text-[9px] px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground transition-colors",ne.isFetching&&"opacity-60 cursor-wait"),title:"Re-read raw upstream state",children:[(0,i.jsx)(Kd,{className:A("h-2.5 w-2.5",ne.isFetching&&"animate-spin")}),"Refresh"]})]})]}),p==="normalized"&&(0,i.jsx)(uH,{deviceId:e,onPatch:X}),n&&(0,i.jsx)("button",{type:"button",onClick:n,className:"text-foreground-subtle hover:text-foreground",children:(0,i.jsx)(mr,{className:"h-3.5 w-3.5"})})]}),(0,i.jsx)("div",{className:A("flex-1 min-h-0 overflow-auto text-[10px] font-mono",r),children:p==="raw"?pe.size===0?(0,i.jsx)("div",{className:"py-4 text-center text-foreground-subtle font-sans",children:"No raw state"}):(0,i.jsx)("div",{className:"py-1",children:[...pe.entries()].map(([He,$e])=>(0,i.jsx)(iw,{capName:He,slice:$e.slice,updatedAt:$e.updatedAt,searchNeedle:"",isPathOpen:we,onToggle:be},He))}):(0,i.jsxs)(i.Fragment,{children:[K&&E.size===0&&(0,i.jsxs)("div",{className:"flex items-center justify-center gap-2 py-6 text-foreground-subtle font-sans",children:[(0,i.jsx)(hr,{className:"h-3.5 w-3.5 animate-spin"}),"Loading device state..."]}),!K&&E.size===0&&(0,i.jsx)("div",{className:"py-4 text-center text-foreground-subtle font-sans",children:"No runtime state"}),!K&&E.size>0&&se.length===0&&(0,i.jsx)("div",{className:"py-4 text-center text-foreground-subtle font-sans",children:"No caps match the filter"}),se.length>0&&(0,i.jsx)("div",{className:"py-1",children:se.map(He=>{const $e=E.get(He);return $e?(0,i.jsx)(iw,{capName:He,slice:$e.slice,updatedAt:$e.updatedAt,searchNeedle:ct,isPathOpen:we,onToggle:be},He):null})})]})})]})}function cH({mode:e,onChange:t}){return(0,i.jsx)("div",{className:"inline-flex items-center rounded border border-border overflow-hidden",children:[{value:"normalized",label:"Normalized"},{value:"raw",label:"Raw"}].map(r=>(0,i.jsx)("button",{type:"button",onClick:()=>t(r.value),className:A("text-[9px] px-1.5 py-0.5 transition-colors",e===r.value?"bg-violet-500/15 text-violet-400":"text-foreground-subtle hover:text-foreground"),children:r.label},r.value))})}function uH({deviceId:e,onPatch:t}){return C.systemEvents.subscribe.useSubscription({deviceId:e,category:W.EventCategory.DeviceStateChanged},{onData:r=>{const n=nH(r,e);n&&t(n.capName,n.slice)}}),null}function iw({capName:e,slice:t,updatedAt:r,searchNeedle:n,isPathOpen:s,onToggle:a}){const c=e,d=s(c,0),u=Object.entries(t);return(0,i.jsxs)("div",{children:[(0,i.jsxs)("div",{className:"flex items-center gap-1.5 px-3 py-1 hover:bg-surface-hover/30 cursor-pointer select-none",onClick:()=>a(c,d),children:[(0,i.jsx)(ow,{open:d,hasChildren:u.length>0}),(0,i.jsx)("span",{className:"inline-flex items-center gap-1 rounded-full border border-violet-500/30 bg-violet-500/15 text-violet-400 px-2 py-0.5 text-[9px] font-medium font-sans",children:e}),(0,i.jsxs)("span",{className:"text-[9px] text-foreground-subtle font-sans",children:[u.length," ",u.length===1?"key":"keys"]}),(0,i.jsxs)("span",{className:"ml-auto text-[9px] text-foreground-subtle/70 font-sans tabular-nums",children:["updated ",hH(r)]})]}),d&&(0,i.jsx)("div",{children:u.length===0?(0,i.jsx)(aw,{depth:1,label:"empty slice"}):u.map(([f,h])=>(0,i.jsx)(sw,{path:`${c}.${f}`,nodeKey:f,value:h,depth:1,searchNeedle:n,isPathOpen:s,onToggle:a},f))})]})}function sw({path:e,nodeKey:t,value:r,depth:n,searchNeedle:s,isPathOpen:a,onToggle:c}){const d=dH(r),u={paddingLeft:`${12+n*14}px`};if(!d)return(0,i.jsxs)("div",{className:"flex items-start gap-1 px-3 py-0.5",style:u,children:[(0,i.jsx)("span",{className:A("shrink-0",fg(t,s,"text-primary/70")),children:t}),(0,i.jsx)("span",{className:"text-foreground-subtle",children:":"}),(0,i.jsx)("span",{className:A("break-all",fg(dg(r),s,fH(r))),children:dg(r)})]});const f=a(e,n);return(0,i.jsxs)("div",{children:[(0,i.jsxs)("div",{className:"flex items-center gap-1 px-3 py-0.5 hover:bg-surface-hover/30 cursor-pointer select-none",style:u,onClick:()=>c(e,f),children:[(0,i.jsx)(ow,{open:f,hasChildren:d.entries.length>0}),(0,i.jsx)("span",{className:fg(t,s,"text-primary/70"),children:t}),(0,i.jsx)("span",{className:"text-foreground-subtle/70 text-[9px]",children:d.summary})]}),f&&(d.entries.length===0?(0,i.jsx)(aw,{depth:n+1,label:d.kind==="array"?"empty array":"empty object"}):d.entries.map(([h,m])=>(0,i.jsx)(sw,{path:`${e}.${h}`,nodeKey:h,value:m,depth:n+1,searchNeedle:s,isPathOpen:a,onToggle:c},h)))]})}function aw({depth:e,label:t}){return(0,i.jsx)("div",{className:"px-3 py-0.5 text-foreground-subtle/60 italic",style:{paddingLeft:`${12+e*14}px`},children:t})}function ow({open:e,hasChildren:t}){return t?e?(0,i.jsx)(fr,{className:"h-3 w-3 text-foreground-subtle shrink-0"}):(0,i.jsx)(mn,{className:"h-3 w-3 text-foreground-subtle shrink-0"}):(0,i.jsx)("span",{className:"inline-block w-3 shrink-0"})}function dH(e){if(Array.isArray(e))return{kind:"array",entries:e.map((t,r)=>[String(r),t]),summary:`[${e.length}]`};if(e&&typeof e=="object"){const t=Object.entries(e);return{kind:"object",entries:t,summary:`{${t.length}}`}}return null}function dg(e){if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e)}catch{return String(e)}}function fH(e){return e==null?"text-foreground-subtle/60":typeof e=="number"?"text-amber-400":typeof e=="boolean"?e?"text-emerald-400":"text-rose-400":"text-foreground"}function fg(e,t,r){return t&&e.toLowerCase().includes(t)?A(r,"bg-violet-500/20 rounded px-0.5"):r}function hg(e,t){if(Array.isArray(e))return e.some(r=>hg(r,t));if(e&&typeof e=="object"){for(const[r,n]of Object.entries(e))if(r.toLowerCase().includes(t)||hg(n,t))return!0;return!1}return dg(e).toLowerCase().includes(t)}function hH(e){const t=Date.now()-e;if(t<5e3)return"just now";const r=Math.floor(t/1e3);if(r<60)return`${r}s ago`;const n=Math.floor(r/60);return n<60?`${n}m ago`:`${Math.floor(n/60)}h ago`}function mH({label:e,value:t}){return(0,i.jsxs)("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary font-medium font-sans",children:[e,": ",t]})}function gH({search:e,onSearchChange:t,caps:r,active:n,onToggle:s,onSelectAll:a,onSelectNone:c,onResetDefaults:d}){return(0,i.jsxs)("div",{className:"absolute z-20 top-full mt-1 left-0 w-72 max-h-80 rounded-md border border-border bg-surface shadow-lg flex flex-col font-sans",onClick:u=>u.stopPropagation(),children:[(0,i.jsxs)("div",{className:"flex items-center gap-1 px-2 py-1.5 border-b border-border/50",children:[(0,i.jsx)(ls,{className:"h-3 w-3 text-foreground-subtle"}),(0,i.jsx)("input",{type:"text",value:e,onChange:u=>t(u.target.value),placeholder:"Filter caps…",className:"flex-1 bg-transparent text-[10px] focus:outline-none text-foreground placeholder:text-foreground-subtle",autoFocus:!0}),e&&(0,i.jsx)("button",{type:"button",onClick:()=>t(""),className:"text-foreground-subtle hover:text-foreground",children:(0,i.jsx)(mr,{className:"h-2.5 w-2.5"})})]}),(0,i.jsxs)("div",{className:"flex items-center gap-1 px-2 py-1 border-b border-border/50 text-[9px]",children:[(0,i.jsx)("button",{type:"button",onClick:a,className:"px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground",children:"All"}),(0,i.jsx)("button",{type:"button",onClick:c,className:"px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground",children:"None"}),(0,i.jsx)("button",{type:"button",onClick:d,className:"px-1.5 py-0.5 rounded border border-border text-foreground-subtle hover:text-foreground",children:"Defaults"})]}),(0,i.jsxs)("div",{className:"overflow-y-auto flex-1",children:[r.length===0&&(0,i.jsx)("div",{className:"text-[10px] text-foreground-subtle italic px-2 py-3 text-center",children:"No matches"}),r.map(u=>(0,i.jsxs)("button",{type:"button",onClick:()=>s(u),className:"w-full flex items-center gap-2 px-2 py-1 text-left hover:bg-surface-hover/40 text-[10px]",children:[(0,i.jsx)("input",{type:"checkbox",readOnly:!0,checked:n.has(u),className:"accent-violet-500"}),(0,i.jsx)("span",{className:"inline-flex items-center gap-1 rounded-full border border-violet-500/30 bg-violet-500/15 text-violet-400 px-1.5 py-0.5 text-[9px] font-medium shrink-0",children:u})]},u))]})]})}var mg=500,pH=[{id:"logs",label:"Logs",icon:zp},{id:"events",label:"Events",icon:Qa},{id:"state",label:"State",icon:zT}];function vH({deviceId:e,containerDeviceId:t,defaultEventCategories:r,defaultStateCaps:n,initialTab:s="events",className:a,maxHeight:c="max-h-96"}){const[d,u]=(0,l.useState)(s),f=Ms(mg),h=Ms(mg),m=Ms(mg),g=f.reset,p=h.reset,y=m.reset;return(0,l.useEffect)(()=>{g(),p(),y()},[e,g,p,y]),(0,i.jsxs)("div",{className:A("flex flex-col h-full min-h-0",a),children:[(0,i.jsx)("div",{className:"flex items-center gap-1 mb-2 shrink-0",children:pH.map(({id:S,label:E,icon:T})=>(0,i.jsxs)("button",{type:"button",onClick:()=>u(S),className:A("inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[11px] font-medium transition-colors",d===S?"bg-primary/15 text-primary border border-primary/30":"text-foreground-subtle hover:text-foreground hover:bg-surface-hover border border-transparent"),children:[(0,i.jsx)(T,{className:"h-3.5 w-3.5"}),E]},S))}),(0,i.jsxs)("div",{className:"flex-1 min-h-0 overflow-hidden",children:[d==="logs"&&(0,i.jsx)(og,{...t!==void 0?{containerDeviceId:t}:{deviceId:e},maxHeight:c,showFilters:!1,liveBuffer:f}),d==="events"&&(0,i.jsx)(ug,{deviceId:e,defaultCategories:r,maxHeight:c,showCategoryFilter:!0,liveBuffer:h}),d==="state"&&(0,i.jsx)(nw,{deviceId:e,defaultCaps:n,maxHeight:c,liveBuffer:m})]})]})}function bH({label:e,icon:t,title:r="Confirm action",description:n,confirmLabel:s,triggerVariant:a="outline",confirmVariant:c="danger",size:d="sm",disabled:u,className:f,action:h,onSuccess:m}){const[g,p]=(0,l.useState)(!1),[y,S]=(0,l.useState)(!1),[E,T]=(0,l.useState)(null),j=async()=>{T(null),S(!0);try{const N=await h();m?.(N),p(!1)}catch(N){T(N instanceof Error?N.message:String(N))}finally{S(!1)}};return(0,i.jsxs)(i.Fragment,{children:[(0,i.jsxs)(tn,{type:"button",variant:a,size:d,disabled:u,onClick:()=>{T(null),p(!0)},className:f,children:[t&&(0,i.jsx)(t,{className:"h-3.5 w-3.5"}),e]}),(0,i.jsx)(_l,{open:g,onOpenChange:N=>!y&&p(N),children:(0,i.jsxs)(no,{children:[(0,i.jsxs)(wl,{children:[(0,i.jsxs)(kl,{className:"flex items-center gap-2",children:[(0,i.jsx)(cs,{className:"h-4 w-4 text-amber-400"}),r]}),typeof n=="string"?(0,i.jsx)(Tl,{children:n}):n]}),E&&(0,i.jsx)("div",{className:A("mt-2 px-3 py-2 rounded border border-danger/40 bg-danger/10","text-xs text-danger"),children:E}),(0,i.jsxs)(El,{children:[(0,i.jsx)(tn,{type:"button",variant:"ghost",size:d,disabled:y,onClick:()=>p(!1),children:"Cancel"}),(0,i.jsxs)(tn,{type:"button",variant:c,size:d,disabled:y,onClick:()=>{j()},children:[y&&(0,i.jsx)(hr,{className:"h-3.5 w-3.5 animate-spin"}),s??e]})]})]})})]})}function yH(e,t){const r=document.createElement("a");r.href=t,r.download=e,document.body.appendChild(r),r.click(),document.body.removeChild(r)}function xH({trpc:e,deviceId:t,deviceName:r,size:n="sm",className:s}){const[a,c]=(0,l.useState)(!1),[d,u]=(0,l.useState)(!1),[f,h]=(0,l.useState)(null),m=r.replace(/[^a-zA-Z0-9_.-]+/g,"_"),g=(0,l.useCallback)(async U=>{c(!0),h(null),u(!1);try{const z=await e.snapshot.getSnapshot.query({deviceId:t,force:!0});if(!z)throw new Error("No snapshot available");const K=`data:${z.contentType};base64,${z.base64}`;if(U==="copy")try{await navigator.clipboard.writeText(K)}catch{throw new Error("Clipboard unavailable")}else{const G=z.contentType.includes("png")?"png":"jpg";yH(`${m}-${new Date().toISOString().replace(/[:.]/g,"-")}.${G}`,K)}u(!0),setTimeout(()=>u(!1),1500)}catch(z){h(z instanceof Error?z.message:String(z))}finally{c(!1)}},[e,t,m]),p=n==="md"?"h-9 px-3 text-sm gap-2":"h-7 px-2.5 text-[11px] gap-1.5",[y,S]=(0,l.useState)(null),[E,T]=(0,l.useState)(!1),j=()=>{T(!1),S(setTimeout(()=>{T(!0),g("copy")},600))},N=()=>{y&&(clearTimeout(y),S(null)),E||g("download")},O=()=>{y&&(clearTimeout(y),S(null))};return(0,i.jsxs)("button",{type:"button",title:"Click to download · long-press to copy",disabled:a,onPointerDown:j,onPointerUp:N,onPointerLeave:O,onPointerCancel:O,className:A("inline-flex items-center justify-center rounded-lg font-medium border border-border","text-foreground-subtle hover:text-foreground hover:bg-surface-hover","disabled:opacity-50 transition-colors",p,f&&"border-danger/40 text-danger",s),children:[a?(0,i.jsx)(hr,{className:"h-3.5 w-3.5 animate-spin"}):d?(0,i.jsx)(On,{className:"h-3.5 w-3.5 text-success"}):(0,i.jsx)(_p,{className:"h-3.5 w-3.5"}),"Snapshot"]})}function SH(e){const t=Date.now()-e;return t<6e4?"just now":t<36e5?`${Math.floor(t/6e4)}m ago`:t<864e5?`${Math.floor(t/36e5)}h ago`:`${Math.floor(t/864e5)}d ago`}function _H({history:e,limit:t=5,latestIsFresh:r,className:n}){if(e.length===0)return null;const s=r?wT:Qa,a=e.slice(0,t);return(0,i.jsxs)("div",{className:A("rounded-lg border border-border bg-surface px-3 py-2",n),children:[(0,i.jsxs)("div",{className:"flex items-center gap-2 mb-2",children:[(0,i.jsx)(s,{className:A("h-4 w-4 text-amber-400",r&&"animate-pulse")}),(0,i.jsx)("span",{className:"text-[11px] font-semibold uppercase tracking-wider text-foreground-subtle",children:"Recent presses"}),(0,i.jsx)("span",{className:"ml-auto rounded-full bg-foreground-subtle/10 px-1.5 py-0.5 text-[10px] font-medium text-foreground-subtle border border-border",children:e.length})]}),(0,i.jsx)("ul",{className:"space-y-1",children:a.map(c=>(0,i.jsxs)("li",{className:"flex items-center justify-between text-[11px]",title:new Date(c.timestamp).toLocaleString(),children:[(0,i.jsx)("span",{className:"text-foreground",children:SH(c.timestamp)}),(0,i.jsx)("span",{className:"text-foreground-subtle font-mono text-[10px]",children:new Date(c.timestamp).toLocaleTimeString()})]},`${c.deviceId}-${c.timestamp}`))})]})}function wH({items:e,header:t,triggerClassName:r,title:n="More actions"}){const[s,a]=(0,l.useState)(!1),c=e.filter(d=>!d.hidden);return c.length===0?null:(0,i.jsxs)(bv,{open:s,onOpenChange:a,children:[(0,i.jsx)(yv,{title:n,className:A("inline-flex items-center justify-center rounded-lg p-2","text-foreground-subtle hover:text-foreground hover:bg-surface-hover","border border-transparent transition-colors",r),children:(0,i.jsx)(ZT,{className:"h-4 w-4"})}),(0,i.jsxs)(xv,{className:"left-auto right-0 mt-1 min-w-[200px] p-1",children:[t&&(0,i.jsx)("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wider text-foreground-subtle",children:t}),(0,i.jsx)("ul",{className:"space-y-0.5",children:c.map((d,u)=>(0,i.jsxs)("li",{children:[d.separatorBefore&&u>0&&(0,i.jsx)("div",{className:"my-1 h-px bg-border"}),(0,i.jsxs)("button",{type:"button",disabled:d.disabled,onClick:()=>{d.disabled||(d.onClick(),a(!1))},className:A("flex w-full items-start gap-2 rounded-md px-2 py-1.5 text-left text-[12px]","transition-colors disabled:opacity-40 disabled:cursor-not-allowed",d.danger?"text-foreground hover:bg-danger/10 hover:text-danger":"text-foreground hover:bg-surface-hover"),children:[d.icon&&(0,i.jsx)(d.icon,{className:A("h-3.5 w-3.5 shrink-0 mt-0.5",d.danger&&"text-danger/80")}),(0,i.jsxs)("span",{className:"flex-1 min-w-0",children:[(0,i.jsx)("span",{className:"block leading-tight",children:d.label}),d.description&&(0,i.jsx)("span",{className:"block mt-0.5 text-[10px] text-foreground-subtle leading-tight",children:d.description})]})]})]},d.id))})]})]})}var EH=[{value:"view",label:"View",icon:Ja,hint:"Read-only — queries + subscriptions"},{value:"create",label:"Create",icon:gC,hint:"Mutations that create or update"},{value:"delete",label:"Delete",icon:en,hint:"Destructive ops (delete/revoke/reset/…)"}],kH=["device","system"];function TH(){return{type:"capability",target:"",access:["view"]}}function CH(e){if(e==null)return[];const t=new Set;for(const r of e)if(r.type==="device")for(const n of r.targets)t.add(n);return[...t]}function IH(e,t,r,n){let s;switch(e){case"addon":s=r;break;case"capability":s=n;break;case"category":s=kH.map(c=>({value:c,label:c}));break}if(t==null)return s;const a=new Set(t.filter(c=>c.type!=="device"&&c.type===e).map(c=>c.target));return s.filter(c=>a.has(c.value))}function PH(e,t){if(t==null)return["view","create","delete"];const r=t.filter(s=>s.type!==e.type?!1:s.type==="device"&&e.type==="device"?s.targets.some(a=>e.targets.includes(a)):s.type!=="device"&&e.type!=="device"?s.target===e.target:!1);if(r.length===0)return[];const n=new Set;for(const s of r)for(const a of s.access)n.add(a);return[...n]}function AH({value:e,onChange:t,clampToParent:r,emptyHint:n}){const{data:s}=c0(),{data:a}=Cf({}),c=(0,l.useMemo)(()=>(s??[]).map(y=>({value:y.manifest.id,label:y.manifest.id})).sort((y,S)=>y.label.localeCompare(S.label)),[s]),d=(0,l.useMemo)(()=>[...W.KNOWN_CAP_NAMES].sort().map(y=>({value:y,label:y})),[]),u=(0,l.useMemo)(()=>(a??[]).map(y=>({value:String(y.id),label:`${y.name} (#${y.id} · ${y.addonId})`})).sort((y,S)=>y.label.localeCompare(S.label)),[a]),f=(0,l.useMemo)(()=>r==null?null:CH(r),[r]),h=(y,S)=>{const E=[...S];switch(y){case"category":return{type:"category",target:"device",access:E};case"capability":return{type:"capability",target:"",access:E};case"addon":return{type:"addon",target:"",access:E};case"device":return{type:"device",targets:[],access:E}}},m=(y,S)=>{t(e.map((E,T)=>{if(T!==y)return E;if(S.type!==void 0&&S.type!==E.type)return h(S.type,S.access??E.access);const j=[...S.access??E.access];return E.type==="device"?{type:"device",targets:[...S.targets??E.targets],access:j}:E.type==="category"?{type:"category",target:S.target??E.target,access:j}:E.type==="capability"?{type:"capability",target:S.target??E.target,access:j}:{type:"addon",target:S.target??E.target,access:j}}))},g=y=>{t(e.filter((S,E)=>E!==y))},p=()=>{t([...e,TH()])};return(0,i.jsxs)("div",{className:"space-y-2",children:[e.length===0&&n&&(0,i.jsx)("div",{className:"text-[10px] text-foreground-subtle italic px-2 py-2",children:n}),e.map((y,S)=>{const E=PH(y,r);return(0,i.jsxs)("div",{className:"flex flex-wrap items-start gap-1.5 rounded border border-border bg-surface px-2 py-1.5",children:[(0,i.jsxs)("select",{value:y.type,onChange:T=>m(S,{type:T.target.value}),className:"rounded border border-border bg-background px-2 py-1 text-[11px] focus:outline-none focus:ring-1 focus:ring-primary",children:[(0,i.jsx)("option",{value:"category",children:"category"}),(0,i.jsx)("option",{value:"capability",children:"capability"}),(0,i.jsx)("option",{value:"addon",children:"addon"}),(0,i.jsx)("option",{value:"device",children:"device"})]}),y.type==="device"?(0,i.jsx)(jH,{value:y.targets,choices:u,clampToParent:f,onChange:T=>m(S,{targets:T})}):(0,i.jsxs)("select",{value:y.target,onChange:T=>m(S,{target:T.target.value}),className:"flex-1 min-w-[160px] rounded border border-border bg-background px-2 py-1 text-[11px] font-mono focus:outline-none focus:ring-1 focus:ring-primary",children:[(0,i.jsxs)("option",{value:"",children:["— pick ",y.type," —"]}),IH(y.type,r,c,d).map(T=>(0,i.jsx)("option",{value:T.value,children:T.label},T.value))]}),(0,i.jsx)("div",{className:"flex items-center gap-1",children:EH.map(({value:T,label:j,icon:N,hint:O})=>{const U=y.access.includes(T),z=r!=null&&!E.includes(T)&&!U;return(0,i.jsxs)("label",{title:z?`${O} — not granted by your scope`:O,className:`inline-flex items-center gap-1 rounded px-1.5 py-1 text-[10px] cursor-pointer transition-colors ${U?"bg-primary/15 text-primary font-medium":"text-foreground-subtle hover:bg-foreground-subtle/10"} ${z?"opacity-40 cursor-not-allowed":""}`,children:[(0,i.jsx)("input",{type:"checkbox",checked:U,disabled:z,onChange:K=>{const G=new Set(y.access);K.target.checked?G.add(T):G.delete(T),m(S,{access:[...G]})},className:"sr-only"}),(0,i.jsx)(N,{className:"h-3 w-3"}),j]},T)})}),(0,i.jsx)("button",{type:"button",onClick:()=>g(S),className:"rounded p-1 text-foreground-subtle hover:bg-danger/10 hover:text-danger transition-colors",title:"Remove scope",children:(0,i.jsx)(mr,{className:"h-3 w-3"})})]},S)}),(0,i.jsxs)("button",{type:"button",onClick:p,className:"inline-flex items-center gap-1 rounded px-2 py-1 text-[10px] text-foreground-subtle hover:text-foreground hover:bg-foreground-subtle/10 transition-colors",children:[(0,i.jsx)(Ci,{className:"h-3 w-3"}),"Add scope"]})]})}function jH({value:e,choices:t,clampToParent:r,onChange:n}){const[s,a]=(0,l.useState)(""),c=(0,l.useMemo)(()=>{const h=r==null?t:t.filter(g=>r.includes(g.value)),m=new Set(e);return h.filter(g=>!m.has(g.value))},[t,r,e]),d=h=>t.find(m=>m.value===h)?.label??`#${h}`,u=h=>{h&&(n([...e,h]),a(""))},f=h=>{n(e.filter(m=>m!==h))};return(0,i.jsxs)("div",{className:"flex-1 min-w-[160px] flex flex-wrap items-center gap-1",children:[e.length===0&&(0,i.jsx)("span",{className:"text-[10px] text-foreground-subtle italic px-1",children:"no devices selected"}),e.map(h=>(0,i.jsxs)("span",{className:"inline-flex items-center gap-1 rounded bg-primary/10 px-1.5 py-0.5 text-[10px] font-mono text-primary",children:[d(h),(0,i.jsx)("button",{type:"button",onClick:()=>f(h),className:"hover:text-danger transition-colors",title:"Remove device",children:(0,i.jsx)(mr,{className:"h-2.5 w-2.5"})})]},h)),c.length>0&&(0,i.jsxs)("select",{value:s,onChange:h=>u(h.target.value),className:"rounded border border-border bg-background px-1.5 py-0.5 text-[10px] focus:outline-none focus:ring-1 focus:ring-primary",children:[(0,i.jsx)("option",{value:"",children:"+ add device…"}),c.map(h=>(0,i.jsx)("option",{value:h.value,children:h.label},h.value))]})]})}function NH(e){for(const t of e){if(t.type==="device"){if(t.targets.length===0)return"Scope device: pick at least one device"}else if(t.target.trim().length===0)return`Scope ${t.type}: pick a target`;if(t.access.length===0){const r=t.type==="device"?`[${t.targets.join(",")}]`:t.target;return`Scope ${t.type}:${r}: pick at least one access`}}return null}var lw=Sn("camstack:zone-editing",null);function DH({children:e}){const[t,r]=(0,l.useState)(!1),[n,s]=(0,l.useState)(null),[a,c]=(0,l.useState)(null),[d,u]=(0,l.useState)(null),f=(0,l.useCallback)(j=>{r(j),j||(s(null),c(null),u(null))},[]),h=(0,l.useCallback)(j=>{s(j)},[]),m=(0,l.useCallback)(j=>{c(j)},[]),g=(0,l.useCallback)(j=>{r(!0),c(null),s(j),u(null)},[]),p=(0,l.useCallback)(()=>{r(!1),s(null),c(null),u(null)},[]),y=(0,l.useCallback)(j=>{c(j.id),u(j)},[]),S=(0,l.useCallback)(j=>{u(N=>N===null?N:{...N,...j})},[]),E=(0,l.useCallback)(()=>{u(null)},[]),T=(0,l.useMemo)(()=>({editing:t,drawingKind:n,selectedZoneId:a,editingDraft:d,setEditing:f,setDrawingKind:h,setSelectedZoneId:m,startDrawing:g,exitEditing:p,enterDraft:y,updateDraft:S,discardDraft:E}),[t,n,a,d,f,h,m,g,p,y,S,E]);return(0,i.jsx)(lw.Provider,{value:T,children:e})}function MH(){return(0,l.useContext)(lw)}var cw=500,$H=800;function Vc(e,t,r){try{const n=e.live;if(!n)return null;const s=n.onEvent;return!s||typeof s.subscribe!="function"?null:s.subscribe({category:t},{onData:r})}catch{return null}}function Hc(e,t){return e?.id===t}function RH(e,t){const[r,n]=(0,l.useState)(null),[s,a]=(0,l.useState)(null),[c,d]=(0,l.useState)(null),[u,f]=(0,l.useState)("watching"),h=(0,l.useRef)(void 0),m=(0,l.useRef)(void 0),g=(0,l.useRef)(void 0);return(0,l.useEffect)(()=>{if(t===null)return;const p=Vc(e,"detection.motion-analysis",y=>{const S=y;if(!Hc(S?.source,t))return;const E=S.data;!E?.regions||E.regions.length===0||(n({zones:E.regions.map(T=>({...T.bbox,intensity:T.intensity})),frameWidth:E.frameWidth,frameHeight:E.frameHeight}),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>n(null),cw))});return()=>{p?.unsubscribe(),h.current&&clearTimeout(h.current)}},[e,t]),(0,l.useEffect)(()=>{if(t===null)return;const p=Vc(e,"detection.motion-zones-raw",y=>{const S=y;if(!Hc(S?.source,t))return;const E=S.data;E?.zones&&(a({boxes:E.zones.map(T=>({bbox:T.bbox,changeScore:T.changeScore})),frameWidth:E.frameSize?.width??0,frameHeight:E.frameSize?.height??0,motionScore:E.zones.length>0?E.zones.reduce((T,j)=>T+j.changeScore,0)/E.zones.length:0}),m.current&&clearTimeout(m.current),m.current=setTimeout(()=>a(null),cw))});return()=>{p?.unsubscribe(),m.current&&clearTimeout(m.current)}},[e,t]),(0,l.useEffect)(()=>{if(t===null)return;const p=Vc(e,"detection.result",y=>{const S=y;if(!Hc(S?.source,t))return;const E=S.data?.frame;E?.detections?.length&&(d({detections:E.detections,frameWidth:E.width,frameHeight:E.height}),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>d(null),$H))});return()=>{p?.unsubscribe(),g.current&&clearTimeout(g.current)}},[e,t]),(0,l.useEffect)(()=>{if(t===null)return;const p=Vc(e,"detection.phase-transition",y=>{const S=y;Hc(S?.source,t)&&S.data?.to&&f(S.data.to)});return()=>{p?.unsubscribe()}},[e,t]),{motion:r,motionRaw:s,detection:c,phase:u}}function LH(e,t,r=5e3){const[n,s]=(0,l.useState)([]);(0,l.useEffect)(()=>{if(t===null)return;let p=!1;const y=()=>{e.webrtcSession.listStreams.query({deviceId:t}).then(E=>{p||s(E)}).catch(()=>{})};y();const S=setInterval(y,r);return()=>{p=!0,clearInterval(S)}},[e,t,r]);const[a,c]=(0,l.useState)(null);(0,l.useEffect)(()=>{if(t===null)return;let p=!1;return e.pipelineOrchestrator&&e.pipelineOrchestrator.getCameraMetrics.query({deviceId:t}).then(y=>{p||!y||c({phase:y.phase,detectionFps:y.actualFps,avgInferenceMs:y.avgInferenceTimeMs,droppedFrames:y.droppedFrames})}).catch(()=>{}),()=>{p=!0}},[e,t]),so("pipeline.camera-metrics-snapshot",p=>{if(t===null)return;const y=p.data;y.deviceId!==t||!y.metrics||c({phase:y.metrics.phase,detectionFps:y.metrics.actualFps,avgInferenceMs:y.metrics.avgInferenceTimeMs,droppedFrames:y.metrics.droppedFrames})});const{streams:d,hasWebrtc:u}=(0,l.useMemo)(()=>t===null||n.length===0?{streams:[],hasWebrtc:!1}:{streams:n.map(p=>({id:p.id,label:p.label,target:p.target,status:p.status,inputFps:p.inputFps,decodeFps:p.decodeFps,bitrateKbps:p.bitrateKbps})),hasWebrtc:!0},[t,n]),f=(0,l.useCallback)(async()=>{if(e.turnProvider)try{return(await e.turnProvider.getTurnServers.query()).map(p=>({urls:typeof p.urls=="string"?p.urls:[...p.urls],...p.username!==void 0?{username:p.username}:{},...p.credential!==void 0?{credential:p.credential}:{}}))}catch{return}},[e]),h=(0,l.useCallback)(async(p,y)=>{if(t===null)throw new Error("No device selected");const S=await e.webrtcSession.createSession.mutate({deviceId:t,target:p,hints:y}),E=await f();return{sessionId:S.sessionId,sdpOffer:S.sdpOffer,...E?{iceServers:E}:{}}},[e,t,f]),m=(0,l.useCallback)(async(p,y,S)=>{if(t===null)throw new Error("No device selected");return e.webrtcSession.handleOffer.mutate({deviceId:t,target:p,sdpOffer:y,...S!==void 0?{sessionId:S}:{}})},[e,t]),g=(0,l.useCallback)(async(p,y)=>{if(t===null)throw new Error("No device selected");await e.webrtcSession.handleAnswer.mutate({deviceId:t,sessionId:p,sdpAnswer:y})},[e,t]);return{streams:d,hasWebrtc:u,pipelineMetrics:a,createSession:h,handleOffer:m,getIceServers:f,addIceCandidate:(0,l.useCallback)(async(p,y)=>{t!==null&&await e.webrtcSession.addIceCandidate.mutate({deviceId:t,sessionId:p,candidate:y.candidate??"",sdpMid:y.sdpMid??null,sdpMLineIndex:y.sdpMLineIndex??null}).catch(()=>{})},[e,t]),getIceCandidates:(0,l.useCallback)(async p=>t===null?{candidates:[],done:!0}:e.webrtcSession.getIceCandidates.query({deviceId:t,sessionId:p}),[e,t]),sendAnswer:g,closeSession:(0,l.useCallback)(async p=>{t!==null&&await e.webrtcSession.closeSession.mutate({deviceId:t,sessionId:p}).catch(()=>{})},[e,t]),getSessionState:(0,l.useCallback)(async p=>{if(t===null)return{pendingRenegotiation:null};try{return await e.webrtcSession.getSessionState.query({deviceId:t,sessionId:p})}catch{return{pendingRenegotiation:null}}},[e,t])}}function OH(e){const t=e?.deviceId??null,r=e?.historyLimit??20,n=gf("doorbell.onPressed",t!==null?c=>c.deviceId===t:void 0),[s,a]=(0,l.useState)([]);return(0,l.useEffect)(()=>{n&&a(c=>{if(c.length>0&&c[0].deviceId===n.deviceId&&c[0].timestamp===n.timestamp)return c;const d=[n,...c];return d.length>r?d.slice(0,r):d})},[n,r]),{latest:n??null,history:s}}function FH(e){const t=Mr(),r=(0,l.useMemo)(()=>e?JSON.stringify(e):"",[e]),[n,s]=(0,l.useState)(()=>t.listDevices(e));return(0,l.useEffect)(()=>{const a=()=>{s(t.listDevices(e))};a();let c=null,d=null;try{c=t.onDeviceAdded(a),d=t.onDeviceRemoved(a)}catch{}const u=t.subscribeConnectionEvents(f=>{f==="connected"&&a()});return()=>{c?.(),d?.(),u()}},[t,e,r]),n}function UH(e){const t=Mr(),[r,n]=(0,l.useState)(()=>e===null?null:t.getDevice(e));return(0,l.useEffect)(()=>{if(e===null){n(null);return}const s=()=>{n(t.getDevice(e))};s();let a=null,c=null;try{a=t.onDeviceAdded(s),c=t.onDeviceRemoved(s)}catch{}const d=t.subscribeConnectionEvents(u=>{u==="connected"&&s()});return()=>{a?.(),c?.(),d()}},[t,e]),r}function BH(e,t,r){const n=Mr();return(0,ye.useQuery)({queryKey:e,queryFn:()=>t(n)(),...r})}function zH(e,t){const r=Mr();return(0,ye.useMutation)({mutationFn:n=>e(r)(n),...t})}function GH(e,t){const r=Mr(),n=(0,ye.useQueryClient)(),[s,a]=(0,l.useState)(r.connectionVersion);(0,l.useEffect)(()=>r.subscribeConnectionEvents((u,f)=>{u==="connected"&&a(f)}),[r]);const c=t.join("|"),d=JSON.stringify(e);(0,l.useEffect)(()=>{const u=[],f=()=>{const h=JSON.parse(d),m=h.length===1&&Array.isArray(h[0])?h:[h];n.invalidateQueries({queryKey:m})};f();for(const h of c.split("|"))if(h)try{u.push(r.subscribeEvent(h,f))}catch{}return()=>{for(const h of u)h()}},[r,n,c,d,s])}function ZH(e,t,r){const n=(0,l.useRef)(null),s=(0,l.useRef)(null);(n.current===null||s.current!==e)&&(n.current=(0,W.createLazyTrpcSource)(e),s.current=e);const a=(0,l.useRef)(void 0),c=(0,l.useRef)(null),d=c.current;return t===null?(a.current=void 0,c.current=null):(a.current===void 0||d===null||d.source!==n.current||d.deviceId!==t||d.capName!==r)&&(a.current=(0,W.createSliceHandle)(n.current,t,r),c.current={source:n.current,deviceId:t,capName:r}),En(a.current)}o.AddonGlobalSettingsForm=Qz,o.AgentStepEditor=yI,o.AlarmHeroCard=Rb,o.AlarmPanelInlineControl=$b,o.AppShell=ZI,o.ArcKnob=lo,o.AudioClassificationList=$7,o.AudioLevelWaveform=N7,o.AudioWaveform=j7,o.AutotrackSection=dx,o.BTN_COMPACT=hE,o.BTN_COMPACT_DANGER=gE,o.BTN_COMPACT_PRIMARY=mE,o.BTN_COMPACT_WARNING=pE,o.Badge=Ai,o.BatteryBadge=sy,o.BottomSheet=cf,o.Breadcrumb=oI,o.BrightnessPanel=pb,o.Button=tn,o.ButtonControl=r0,o.ButtonHeroCard=n0,o.CENTER=Jv,o.CHIP_ACTIVE=yE,o.CHIP_BASE=bE,o.CHIP_INACTIVE=xE,o.CLASS_COLORS=po,o.COLUMN_BREAKPOINT_CLASS=Di,o.COLUMN_PRIORITY=ZF,o.CONTROL_CAP_NAMES=_U,o.CONTROL_FILLS=Qb,o.CameraStreamPlayer=Qx,o.Card=sf,o.Checkbox=tv,o.ChildSectionAccordion=KF,o.ClimatePanel=bb,o.CodeBlock=zI,o.CollapsibleCard=Xp,o.ConfigFormBuilder=Kx,o.ConfigFormField=xs,o.ConfigSchemaField=Il,o.ConfirmActionButton=bH,o.ConfirmDialogProvider=FI,o.ConsumablesPanel=cx,o.ContainerChildrenProvider=xf,o.ContainerPrimaryHero=CU,o.ControlColumn=oo,o.ControlHeroCard=Hb,o.ControlInlineControl=Vb,o.ControlPanel=zf,o.CopyButton=Q_,o.CoverHeroCard=o0,o.CoverInlineControl=s0,o.CoverPanel=SU,o.CustomFieldRenderersProvider=I6,o.DEFAULT_COLOR=DU,o.DEVICE_COLUMNS=zF,o.DEVICE_LIST_PAGE_SIZE_KEY=oh,o.DEVICE_LIST_PAGE_SIZE_OPTIONS=ah,o.DEVICE_ROLE_META=Al,o.DEVICE_TYPE_CONTROL=qb,o.DEVICE_TYPE_META=us,o.DataTable=lI,o.DetectionCanvas=MU,o.DetectionOverlay=qx,o.DetectionResultTree=OU,o.DevShell=ex,o.DeviceActivityPanel=vH,o.DeviceBatchToolbar=ih,o.DeviceCard=HI,o.DeviceContextProvider=P6,o.DeviceExportPanel=A7,o.DeviceGrid=KI,o.DeviceItem=Gl,o.DeviceList=Py,o.Dialog=_l,o.DialogContent=no,o.DialogDescription=Tl,o.DialogFooter=El,o.DialogHeader=wl,o.DialogTitle=kl,o.DialogTrigger=qC,o.DiscoveryPanel=tH,o.DoorbellRecentPanel=_H,o.Dropdown=YC,o.DropdownContent=JC,o.DropdownItem=eI,o.DropdownTrigger=XC,o.DummyHeroCard=Tf,o.DummyInline=l0,o.EmptyState=pf,o.ErrorBox=ao,o.EventStream=ug,o.FILL=Yv,o.FanHeroCard=Ib,o.FanInlineControl=Bb,o.FanPanel=vb,o.FilterBar=GI,o.FloatingEventStream=J7,o.FloatingLogStream=G7,o.FloatingPanel=aI,o.FormField=RI,o.GRID_GAP=nE,o.GRID_PAIRED=aE,o.GRID_QUICK_STATS=sE,o.GripTrack=$l,o.HOST_WIDGETS=Tx,o.HlsVideo=K_,o.HoverZoomImage=Uf,o.HumidifierHeroCard=rb,o.HumidifierInlineControl=tb,o.INPUT_COMPACT=vE,o.IconAction=Jb,o.IconButton=nf,o.ImageHeroCard=mb,o.ImageInlineControl=hb,o.ImageSelector=GU,o.InferenceConfigSelector=ZU,o.Input=Sl,o.KebabMenu=wH,o.KeyValueList=BI,o.LIST_ROW=iE,o.Label=af,o.LawnMowerHeroCard=K0,o.LawnMowerInlineControl=H0,o.LightHeroCard=Cb,o.LightInlineControl=Ub,o.LockHeroCard=kb,o.LockInlineControl=Fb,o.LockPanel=gb,o.LogStream=og,o.LoginForm=Xy,o.MODE_COLOR=Bf,o.MaskShapeCanvas=$h,o.MediaPlayerHeroCard=jb,o.MediaPlayerInlineControl=Gb,o.MediaPlayerPanel=Sb,o.MobileDrawer=wv,o.MotionZonesSettings=bx,o.NodeMultiSelectField=Gx,o.NodePicker=PI,o.NodeSelectField=zx,o.OfflineBadge=TU,o.PHASE_CONFIG=bd,o.PRIORITY=yf,o.PTZOverlay=_f,o.PageHeader=LI,o.PhaseIcon=O7,o.PipelineBuilder=NU,o.PipelineRuntimeSelector=PU,o.PipelineStep=Cl,o.PipelineTreeMatrix=TI,o.PlayerOverlaysProvider=Z6,o.Popover=bv,o.PopoverContent=xv,o.PopoverRowAction=kU,o.PopoverTrigger=yv,o.ProviderBadge=DI,o.PtzPanel=lx,o.QrCode=Vh,o.RIGHT=Xv,o.ROLE_DESCRIPTOR=Af,o.RadialGauge=Wf,o.RecordingPanel=kx,o.ResponseLog=R7,o.SECTION_BODY=tE,o.SECTION_CARD=Jw,o.SECTION_HEADER=eE,o.SPLIT_PANEL_OUTER=oE,o.SPLIT_PANEL_SIDE=lE,o.STACK_GAP=rE,o.STATE_COLOR=yb,o.ScopePicker=AH,o.ScrollArea=uf,o.Select=ro,o.SemanticBadge=jv,o.SensorHeroCard=M0,o.SensorInlineControl=D0,o.SensorValueAtom=Rl,o.Separator=of,o.Sidebar=bf,o.SidebarItem=vf,o.Skeleton=Jp,o.SlideOverPanel=cI,o.SlideToggle=e0,o.SnapshotButton=xH,o.StatCard=UI,o.StateValuesStream=nw,o.StatusBadge=jI,o.StepTimings=zU,o.StepTreeMaster=dI,o.Stepper=wf,o.StreamBrokerSelector=x7,o.StreamPanel=v7,o.Switch=rv,o.SwitchHeroCard=Pb,o.SwitchInlineControl=Ob,o.SwitchPanel=Ll,o.SystemProvider=Av,o.TEXT_FIELD_LABEL=uE,o.TEXT_HINT=xn,o.TEXT_METRIC=fE,o.TEXT_SECTION_LABEL=cE,o.TEXT_VALUE=dE,o.TIMEZONES=W.TIMEZONES,o.Tabs=rI,o.TabsContent=sI,o.TabsList=nI,o.TabsTrigger=iI,o.TapToggle=Bl,o.ThemeProvider=x.ThemeProvider$1,o.ThermostatHeroCard=wb,o.ThermostatInlineControl=zb,o.TimezoneSelector=Bx,o.Tooltip=lv,o.TooltipContent=uv,o.TooltipTrigger=cv,o.VacuumHeroCard=z0,o.VacuumInlineControl=B0,o.ValueReadout=mP,o.ValveHeroCard=X0,o.ValveInlineControl=Y0,o.VersionBadge=$I,o.VodPlaybackProvider=_B,o.WaterHeaterHeroCard=ob,o.WaterHeaterInlineControl=ab,o.WeatherHeroCard=ub,o.WeatherInlineControl=cb,o.WidgetMetricCard=Ql,o.WidgetPanel=Gn,o.WidgetRegistryProvider=$6,o.WidgetSlot=Cx,o.ZoneEditingProvider=DH,o.__toESM=v,o.allDeviceTypeFilterOptions=$v,o.buildStepTreeFromSchema=fI,o.childEntityId=Nl,o.cn=A,o.columnsForContext=ay,o.containerChildToRef=Ov,o.countableDevices=py,o.coverHighlight=co,o.createSharedContext=Sn,o.createTheme=x.createTheme$1,o.darkColors=x.darkColors$1,o.defaultTheme=x.defaultTheme$1,o.deriveDeviceKind=rP,o.deviceRoleMeta=eP,o.deviceRoleMetaOf=Mv,o.deviceTypeMeta=JI,o.deviceTypeMetaOf=jl,o.ensureMfHostInit=pp,o.findTimezone=W.findTimezone,o.formatControlDateTime=il,o.formatLastSeen=ri,o.fuzzyMatch=hs,o.getClassColor=zr,o.getPhaseVisual=yd,o.groupChildrenByLayout=my,o.hardwareLabel=cy,o.humidifierTint=J0,o.isAbsentProvider=za,o.isFieldVisible=Hx,o.lawnMowerActivityMeta=G0,o.lightColors=x.lightColors$1,o.loadRemoteBundle=kh,o.metadataEntries=uy,o.metadataString=fs,o.mirror=kE,o.mountAddonPage=C6,o.nextSort=Cy,o.normalizeForSearch=ch,o.overrideEntityIdFromLink=Fv,o.providerIcons=zC,o.resolveContainerPrimary=ds,o.resolveControlAlign=go,o.resolveDeviceControl=zl,o.resolvePrimaryChild=Rv,o.sortRows=Iy,o.statusIcons=GC,o.tankAlert=U0,o.themeToCss=x.themeToCss$1,o.trpc=C,o.useAccessoriesGetStatus=wP,o.useAccessoriesSetChildHidden=_P,o.useAddonPagesListPages=EP,o.useAddonSettingsGetDeviceSettings=aA,o.useAddonSettingsGetGlobalSettings=iA,o.useAddonSettingsUpdateDeviceSettings=oA,o.useAddonSettingsUpdateGlobalSettings=sA,o.useAddonWidgetsListWidgets=u0,o.useAddonsApplyAutoUpdateToAll=tA,o.useAddonsCancelBulkUpdate=HP,o.useAddonsCustom=rA,o.useAddonsForceRefresh=LP,o.useAddonsGetAddonAutoUpdate=JP,o.useAddonsGetAutoUpdateSettings=YP,o.useAddonsGetBulkUpdateState=VP,o.useAddonsGetLastRestart=FP,o.useAddonsGetLogs=kP,o.useAddonsGetVersions=WP,o.useAddonsInstallFromWorkspace=IP,o.useAddonsInstallPackage=CP,o.useAddonsIsWorkspaceAvailable=PP,o.useAddonsList=c0,o.useAddonsListActiveBulkUpdates=KP,o.useAddonsListCapabilityProviders=BP,o.useAddonsListFrameworkPackages=UP,o.useAddonsListPackages=TP,o.useAddonsListUpdates=MP,o.useAddonsListWorkspacePackages=AP,o.useAddonsOnAddonLogs=nA,o.useAddonsReloadPackages=NP,o.useAddonsRestartAddon=qP,o.useAddonsRestartServer=OP,o.useAddonsRetryLoad=QP,o.useAddonsRollbackPackage=RP,o.useAddonsSearchAvailable=DP,o.useAddonsSetAddonAutoUpdate=eA,o.useAddonsSetAutoUpdateSettings=XP,o.useAddonsSetCapabilityProviderEnabled=zP,o.useAddonsStartBulkUpdate=ZP,o.useAddonsUninstallPackage=jP,o.useAddonsUpdateFrameworkPackage=GP,o.useAddonsUpdatePackage=$P,o.useAirQualitySensorGetStatus=lA,o.useAlarmPanelArm=cA,o.useAlarmPanelDisarm=uA,o.useAlarmPanelGetStatus=fA,o.useAlarmPanelTrigger=dA,o.useAlertsDismiss=yA,o.useAlertsEmit=hA,o.useAlertsGetUnreadCount=pA,o.useAlertsList=gA,o.useAlertsMarkAllRead=bA,o.useAlertsMarkRead=vA,o.useAlertsUpdate=mA,o.useAllWidgets=L6,o.useAmbientLightSensorGetStatus=xA,o.useAudioAnalysisApplyDeviceSettingsPatch=EA,o.useAudioAnalysisGetDeviceLiveContribution=wA,o.useAudioAnalysisGetDeviceSettingsContribution=_A,o.useAudioAnalysisResolveDeviceSettings=SA,o.useAudioAnalyzerAnalyseChunk=kA,o.useAudioAnalyzerClassify=TA,o.useAudioAnalyzerDispose=IA,o.useAudioAnalyzerIsReady=CA,o.useAudioAnalyzerReprobeAudioEngine=PA,o.useAudioCodecCanHandle=jA,o.useAudioCodecCloseSession=MA,o.useAudioCodecCreateDecodeSession=NA,o.useAudioCodecCreateEncodeSession=DA,o.useAudioCodecFlushEncode=FA,o.useAudioCodecListActiveSessions=UA,o.useAudioCodecListSupportedCodecs=AA,o.useAudioCodecPullEncoded=OA,o.useAudioCodecPullPcm=RA,o.useAudioCodecPushEncodedFrame=$A,o.useAudioCodecPushPcm=LA,o.useAudioMetricsGetCurrentSnapshot=BA,o.useAudioMetricsGetHistory=zA,o.useAutomationControlDisable=ZA,o.useAutomationControlEnable=GA,o.useAutomationControlGetStatus=HA,o.useAutomationControlTrigger=VA,o.useBackupDelete=JA,o.useBackupGetEntries=YA,o.useBackupList=qA,o.useBackupListArchives=ej,o.useBackupListDestinations=KA,o.useBackupListLocations=QA,o.useBackupPreviewSchedule=rj,o.useBackupRestore=XA,o.useBackupTrigger=WA,o.useBackupUpsertDestinationPolicy=tj,o.useBatteryGetStatus=ij,o.useBatteryWakeForStream=nj,o.useBinaryGetStatus=sj,o.useBrightnessGetStatus=oj,o.useBrightnessSetBrightness=aj,o.useBrokerAdd=dj,o.useBrokerGet=cj,o.useBrokerGetBrokerConfig=pj,o.useBrokerGetSettings=mj,o.useBrokerGetSettingsSchema=vj,o.useBrokerGetState=_j,o.useBrokerGetStatus=wj,o.useBrokerList=lj,o.useBrokerListProviders=uj,o.useBrokerPublish=yj,o.useBrokerRemove=fj,o.useBrokerSetSettings=gj,o.useBrokerSubscribe=xj,o.useBrokerTestConnection=hj,o.useBrokerTestSettings=bj,o.useBrokerUnsubscribe=Sj,o.useButtonPress=Ej,o.useCameraCredentialsGetCredentials=kj,o.useCameraCredentialsGetStatus=Tj,o.useCameraPipelineConfigApplyDeviceSettingsPatch=Pj,o.useCameraPipelineConfigGetDeviceLiveContribution=Ij,o.useCameraPipelineConfigGetDeviceSettingsContribution=Cj,o.useCameraStreamsGetBrokerStreams=jj,o.useCameraStreamsGetCameraStreams=Aj,o.useCameraStreamsGetProfileRtspEntries=Nj,o.useCameraStreamsGetRtspEntries=d0,o.useCameraStreamsPickStream=Dj,o.useCarbonMonoxideGetStatus=Mj,o.useClimateControlGetStatus=Bj,o.useClimateControlSetFanMode=Rj,o.useClimateControlSetMode=$j,o.useClimateControlSetPreset=Lj,o.useClimateControlSetTarget=Oj,o.useClimateControlSetTargetHumidity=Uj,o.useClimateControlSetTargetRange=Fj,o.useClusterNodes=Pl,o.useColorGetStatus=Gj,o.useColorSetColor=zj,o.useConfirm=ji,o.useConnectivityGetStatus=Zj,o.useConsumablesGetStatus=Hj,o.useConsumablesReset=Vj,o.useContactGetStatus=Kj,o.useContainerChildren=Dl,o.useControlGetStatus=qj,o.useControlSetValue=Wj,o.useCoverClose=Yj,o.useCoverGetStatus=tN,o.useCoverOpen=Qj,o.useCoverSetPosition=Jj,o.useCoverSetTiltPosition=eN,o.useCoverStop=Xj,o.useCustomFieldRenderer=rx,o.useDebouncedString=sh,o.useDecoderCreateSession=iN,o.useDecoderDestroySession=sN,o.useDecoderGetFrame=uN,o.useDecoderGetInfo=nN,o.useDecoderGetShmStats=dN,o.useDecoderGetStats=hN,o.useDecoderListActiveSessions=mN,o.useDecoderOpenStream=oN,o.useDecoderPullFrames=lN,o.useDecoderPullHandles=cN,o.useDecoderPushPacket=aN,o.useDecoderReprobeHwaccel=gN,o.useDecoderSupportsCodec=rN,o.useDecoderUpdateConfig=fN,o.useDetectionPipelineApplyDeviceSettingsPatch=bN,o.useDetectionPipelineGetDeviceLiveContribution=vN,o.useDetectionPipelineGetDeviceSettingsContribution=pN,o.useDevShell=_6,o.useDevice=UH,o.useDeviceAdoptionAdopt=wN,o.useDeviceAdoptionGetCandidate=SN,o.useDeviceAdoptionGetStatus=TN,o.useDeviceAdoptionListCandidateFilters=yN,o.useDeviceAdoptionListCandidates=xN,o.useDeviceAdoptionRefresh=_N,o.useDeviceAdoptionRelease=EN,o.useDeviceAdoptionResync=kN,o.useDeviceAutotrack=ux,o.useDeviceBattery=ny,o.useDeviceCapSlice=ZH,o.useDeviceCapability=bt,o.useDeviceDetections=RH,o.useDeviceDiscoveryAdoptDevice=PN,o.useDeviceDiscoveryGetStatus=jN,o.useDeviceDiscoveryListDiscovered=CN,o.useDeviceDiscoveryRefreshDiscovery=IN,o.useDeviceDiscoveryReleaseDevice=AN,o.useDeviceExportApplyDeviceSettingsPatch=MN,o.useDeviceExportExposeDevice=g0,o.useDeviceExportGetDeviceLiveContribution=DN,o.useDeviceExportGetDeviceSettingsContribution=NN,o.useDeviceExportGetStatus=f0,o.useDeviceExportListExposedDevices=m0,o.useDeviceExportListSupportedDeviceKinds=h0,o.useDeviceExportUnexposeDevice=p0,o.useDeviceId=nx,o.useDeviceListPageSize=gy,o.useDeviceManagerAddLocation=tD,o.useDeviceManagerAdoptDevice=PD,o.useDeviceManagerAdoptionAdopt=$D,o.useDeviceManagerAdoptionListCandidates=DD,o.useDeviceManagerAdoptionRefresh=MD,o.useDeviceManagerAdoptionRelease=RD,o.useDeviceManagerAllocateDeviceId=$N,o.useDeviceManagerApplyInitialMeta=XN,o.useDeviceManagerCreateDevice=jD,o.useDeviceManagerDisable=dD,o.useDeviceManagerDiscoverDevices=ID,o.useDeviceManagerEnable=uD,o.useDeviceManagerGetAllBindings=bD,o.useDeviceManagerGetBindings=vD,o.useDeviceManagerGetChildren=sD,o.useDeviceManagerGetConfigSchema=oD,o.useDeviceManagerGetCreationSchema=AD,o.useDeviceManagerGetDevice=If,o.useDeviceManagerGetDeviceAggregate=ED,o.useDeviceManagerGetDeviceLiveInfoAggregate=wD,o.useDeviceManagerGetDeviceSettingsAggregate=_D,o.useDeviceManagerGetDeviceStatusAggregate=OD,o.useDeviceManagerGetSettingsSchema=lD,o.useDeviceManagerGetStreamProfileMap=mD,o.useDeviceManagerGetStreamSources=aD,o.useDeviceManagerGetWireableFields=QN,o.useDeviceManagerListAll=Cf,o.useDeviceManagerListBindableCapsForDeviceType=SD,o.useDeviceManagerListLocations=eD,o.useDeviceManagerListPersistedByAddon=iD,o.useDeviceManagerListWrappersForCap=xD,o.useDeviceManagerLoadConfig=FN,o.useDeviceManagerLoadMeta=BN,o.useDeviceManagerLoadRuntimeState=UN,o.useDeviceManagerPersistConfig=ON,o.useDeviceManagerProbeStreams=pD,o.useDeviceManagerRegisterDevice=RN,o.useDeviceManagerRemove=fD,o.useDeviceManagerRemoveByIntegration=hD,o.useDeviceManagerRemoveDevice=LN,o.useDeviceManagerRemoveLocation=rD,o.useDeviceManagerRunDeviceAction=kD,o.useDeviceManagerSetChildLayout=WN,o.useDeviceManagerSetDeviceLinks=qN,o.useDeviceManagerSetDisabled=nD,o.useDeviceManagerSetIntegrationId=VN,o.useDeviceManagerSetLinkDeviceId=HN,o.useDeviceManagerSetLocation=GN,o.useDeviceManagerSetMetadata=JN,o.useDeviceManagerSetName=zN,o.useDeviceManagerSetPrimaryChildEntityId=KN,o.useDeviceManagerSetRole=YN,o.useDeviceManagerSetStreamProfileMap=gD,o.useDeviceManagerSetType=ZN,o.useDeviceManagerSetWrapperActive=yD,o.useDeviceManagerTestCreationField=ND,o.useDeviceManagerTestField=LD,o.useDeviceManagerUpdateConfig=cD,o.useDeviceManagerUpdateDeviceField=TD,o.useDeviceManagerUpdateDeviceFieldsBatch=CD,o.useDeviceOpsGetConfigEntries=UD,o.useDeviceOpsGetRawState=VD,o.useDeviceOpsGetSettingsSchema=ZD,o.useDeviceOpsGetStreamSources=FD,o.useDeviceOpsRemoveDevice=GD,o.useDeviceOpsRunAction=zD,o.useDeviceOpsSetConfig=BD,o.useDeviceProviderAdoptDiscoveredDevice=XD,o.useDeviceProviderCreateDevice=tM,o.useDeviceProviderDiscoverDevices=YD,o.useDeviceProviderGetChildCreationSchema=eM,o.useDeviceProviderGetDevices=qD,o.useDeviceProviderGetStatus=WD,o.useDeviceProviderStart=HD,o.useDeviceProviderStop=KD,o.useDeviceProviderSupportsDiscovery=QD,o.useDeviceProviderSupportsManualCreation=JD,o.useDeviceProviderTestCreationField=rM,o.useDeviceProxy=Br,o.useDeviceSnapshot=A6,o.useDeviceSnapshotImage=iy,o.useDeviceState=Dv,o.useDeviceStateGetAllSnapshots=sM,o.useDeviceStateGetCapSlice=iM,o.useDeviceStateGetSnapshot=nM,o.useDeviceStateSetCapSlice=aM,o.useDeviceStateSlice=En,o.useDeviceStatusGetStatus=oM,o.useDeviceWebrtc=LH,o.useDevices=FH,o.useDoorbellEvents=OH,o.useDoorbellGetStatus=lM,o.useEnumSensorGetStatus=cM,o.useEventEmitterGetStatus=uM,o.useEventInvalidation=GH,o.useEventStreamLatest=gf,o.useEventStreamMap=II,o.useEventsGetEventClipUrl=hM,o.useEventsGetEventThumbnail=fM,o.useEventsGetEvents=dM,o.useFanControlGetStatus=bM,o.useFanControlSetDirection=pM,o.useFanControlSetOscillating=vM,o.useFanControlSetPercentage=mM,o.useFanControlSetPreset=gM,o.useFeatureProbeGetStatus=yM,o.useFloodGetStatus=xM,o.useGasGetStatus=SM,o.useHumidifierGetStatus=kM,o.useHumidifierSetMode=EM,o.useHumidifierSetOn=_M,o.useHumidifierSetTargetHumidity=wM,o.useHumiditySensorGetStatus=TM,o.useImageGetStatus=CM,o.useIntegrationsCreate=jM,o.useIntegrationsDelete=DM,o.useIntegrationsGet=PM,o.useIntegrationsGetAvailableTypes=RM,o.useIntegrationsGetByAddonId=AM,o.useIntegrationsGetSettings=MM,o.useIntegrationsList=IM,o.useIntegrationsSetSettings=$M,o.useIntegrationsTestConnection=LM,o.useIntegrationsUpdate=NM,o.useIntercomEndTalkSession=GM,o.useIntercomGetStatus=ZM,o.useIntercomHandleAnswer=FM,o.useIntercomPushTalkAudio=zM,o.useIntercomStartSession=OM,o.useIntercomStartTalkSession=BM,o.useIntercomStopSession=UM,o.useIsMidWidth=tI,o.useIsMobile=io,o.useLawnMowerControlDock=KM,o.useLawnMowerControlGetStatus=WM,o.useLawnMowerControlPause=HM,o.useLawnMowerControlStartMowing=VM,o.useLiveBuffer=Ms,o.useLiveEvent=so,o.useLocalNetworkGetAllowedAddresses=XM,o.useLocalNetworkGetConnectionEndpoints=YM,o.useLocalNetworkGetPreferred=QM,o.useLocalNetworkList=qM,o.useLocalNetworkResetAllowlistToBestMatch=e$,o.useLocalNetworkSetAllowedAddresses=JM,o.useLockControlGetStatus=i$,o.useLockControlLock=t$,o.useLockControlOpen=n$,o.useLockControlUnlock=r$,o.useMediaPlayerGetStatus=v$,o.useMediaPlayerNext=l$,o.useMediaPlayerPause=a$,o.useMediaPlayerPlay=s$,o.useMediaPlayerPlayMedia=p$,o.useMediaPlayerPrevious=c$,o.useMediaPlayerSeek=u$,o.useMediaPlayerSelectSource=g$,o.useMediaPlayerSetMute=f$,o.useMediaPlayerSetRepeat=m$,o.useMediaPlayerSetShuffle=h$,o.useMediaPlayerSetVolume=d$,o.useMediaPlayerStop=o$,o.useMeshNetworkGetStatus=b$,o.useMeshNetworkJoin=y$,o.useMeshNetworkLeave=S$,o.useMeshNetworkListPeers=w$,o.useMeshNetworkLogout=_$,o.useMeshNetworkStartLogin=x$,o.useMeshNetworkTestConnection=E$,o.useMetricsProviderCollectSnapshot=k$,o.useMetricsProviderGetAddonStats=D$,o.useMetricsProviderGetCached=T$,o.useMetricsProviderGetCpuTemperature=A$,o.useMetricsProviderGetCurrent=C$,o.useMetricsProviderGetDiskSpace=I$,o.useMetricsProviderGetGpuInfo=P$,o.useMetricsProviderGetProcessStats=j$,o.useMetricsProviderKillProcess=$$,o.useMetricsProviderListAddonInstances=N$,o.useMetricsProviderListNodeProcesses=M$,o.useMotionDetectionAnalyze=O$,o.useMotionDetectionApplyDeviceSettingsPatch=G$,o.useMotionDetectionGetDeviceLiveContribution=z$,o.useMotionDetectionGetDeviceSettingsContribution=B$,o.useMotionDetectionRemoveCamera=F$,o.useMotionDetectionReset=U$,o.useMotionGetStatus=L$,o.useMotionIsDetected=R$,o.useMotionTriggerGetStatus=V$,o.useMotionTriggerSetMotionTrigger=Z$,o.useMotionZonesGetOptions=H$,o.useMotionZonesGetStatus=W$,o.useMotionZonesSetZone=K$,o.useMqttBrokerAddBroker=Y$,o.useMqttBrokerGetBrokerConfig=Q$,o.useMqttBrokerGetStatus=rR,o.useMqttBrokerListBrokers=q$,o.useMqttBrokerRemoveBroker=X$,o.useMqttBrokerStartEmbeddedBroker=eR,o.useMqttBrokerStopEmbeddedBroker=tR,o.useMqttBrokerTestConnection=J$,o.useNativeObjectDetectionGetStatus=iR,o.useNativeObjectDetectionSetEnabled=nR,o.useNetworkAccessGetEndpoint=oR,o.useNetworkAccessGetStatus=lR,o.useNetworkAccessListEndpoints=cR,o.useNetworkAccessStart=sR,o.useNetworkAccessStop=aR,o.useNetworkQualityGetAllStats=dR,o.useNetworkQualityGetDeviceStats=uR,o.useNetworkQualityReportClientStats=fR,o.useNodesClusterAddonStatus=SR,o.useNodesDeployAddon=mR,o.useNodesExecuteQuery=kR,o.useNodesGetCapUsageGraph=_R,o.useNodesGetNodeAddons=wR,o.useNodesRenameNode=xR,o.useNodesRestartAddon=pR,o.useNodesRestartNode=bR,o.useNodesRestartProcess=vR,o.useNodesSetProcessLogLevel=ER,o.useNodesShutdownNode=yR,o.useNodesTopology=hR,o.useNodesUndeployAddon=gR,o.useNotificationOutputSend=TR,o.useNotificationOutputSendTest=CR,o.useNotifierCancel=PR,o.useNotifierGetStatus=AR,o.useNotifierSend=IR,o.useNumericSensorGetStatus=jR,o.useOptimisticSlice=Zt,o.useOptionalSystem=CI,o.useOptionalWidgetRegistry=Ch,o.useOsdGetStatus=DR,o.useOsdSetOverlay=NR,o.usePTZ=Sf,o.usePipelineAnalyticsApplyDeviceSettingsPatch=GR,o.usePipelineAnalyticsClearTracks=LR,o.usePipelineAnalyticsGetActiveTracks=MR,o.usePipelineAnalyticsGetAudioEvents=y0,o.usePipelineAnalyticsGetDeviceLiveContribution=zR,o.usePipelineAnalyticsGetDeviceSettingsContribution=BR,o.usePipelineAnalyticsGetEventDensity=x0,o.usePipelineAnalyticsGetEventMedia=FR,o.usePipelineAnalyticsGetMotionEvents=v0,o.usePipelineAnalyticsGetObjectEvents=b0,o.usePipelineAnalyticsGetTrack=$R,o.usePipelineAnalyticsGetTrackMedia=UR,o.usePipelineAnalyticsListTracks=RR,o.usePipelineAnalyticsPruneEventsBefore=OR,o.usePipelineExecutorCacheFrameInPool=dL,o.usePipelineExecutorDeleteModel=oL,o.usePipelineExecutorDeleteTemplate=nL,o.usePipelineExecutorDetect=lL,o.usePipelineExecutorDownloadModel=aL,o.usePipelineExecutorGetAddonModels=sL,o.usePipelineExecutorGetAudioCapabilities=_L,o.usePipelineExecutorGetAvailableEngines=ZR,o.usePipelineExecutorGetCapabilities=iL,o.usePipelineExecutorGetDefaultSteps=HR,o.usePipelineExecutorGetDetectionConfigSchema=EL,o.usePipelineExecutorGetEffectiveTuning=mL,o.usePipelineExecutorGetGlobalPipelineConfig=XR,o.usePipelineExecutorGetGlobalSteps=YR,o.usePipelineExecutorGetOrchestratorConfigSchema=JR,o.usePipelineExecutorGetReferenceAudio=SL,o.usePipelineExecutorGetReferenceAudioFiles=xL,o.usePipelineExecutorGetReferenceImage=yL,o.usePipelineExecutorGetSchema=QR,o.usePipelineExecutorGetSelectedEngine=VR,o.usePipelineExecutorGetVideoPipelineSteps=WR,o.usePipelineExecutorInferCached=fL,o.usePipelineExecutorKillEngine=vL,o.usePipelineExecutorListLoadedEngines=gL,o.usePipelineExecutorListReferenceImages=bL,o.usePipelineExecutorListTemplates=eL,o.usePipelineExecutorReprobeEngine=KR,o.usePipelineExecutorRunAudioTest=wL,o.usePipelineExecutorRunPipeline=cL,o.usePipelineExecutorRunPipelineBatch=uL,o.usePipelineExecutorSaveTemplate=tL,o.usePipelineExecutorSetVideoPipelineSteps=qR,o.usePipelineExecutorSpinEngine=pL,o.usePipelineExecutorUncacheFrame=hL,o.usePipelineExecutorUpdateTemplate=rL,o.usePipelineOrchestratorApplyDeviceSettingsPatch=a2,o.usePipelineOrchestratorAssignAudio=OL,o.usePipelineOrchestratorAssignDecoder=$L,o.usePipelineOrchestratorAssignPipeline=kL,o.usePipelineOrchestratorDeleteTemplate=n2,o.usePipelineOrchestratorGetAgentLoad=AL,o.usePipelineOrchestratorGetAgentSettings=ZL,o.usePipelineOrchestratorGetAudioAssignment=UL,o.usePipelineOrchestratorGetAudioAssignments=zL,o.usePipelineOrchestratorGetAudioNodeLoad=BL,o.usePipelineOrchestratorGetCameraMetrics=NL,o.usePipelineOrchestratorGetCameraSettings=WL,o.usePipelineOrchestratorGetCameraStepOverrides=QL,o.usePipelineOrchestratorGetCapabilityBindings=DL,o.usePipelineOrchestratorGetDecoderAssignment=GL,o.usePipelineOrchestratorGetDecoderAssignments=LL,o.usePipelineOrchestratorGetDeviceLiveContribution=s2,o.usePipelineOrchestratorGetDeviceSettingsContribution=i2,o.usePipelineOrchestratorGetGlobalMetrics=jL,o.usePipelineOrchestratorGetPipelineAssignment=PL,o.usePipelineOrchestratorGetPipelineAssignments=IL,o.usePipelineOrchestratorListAgentSettings=VL,o.usePipelineOrchestratorListTemplates=e2,o.usePipelineOrchestratorRebalance=CL,o.usePipelineOrchestratorRemoveAgentSettings=KL,o.usePipelineOrchestratorResolvePipeline=JL,o.usePipelineOrchestratorSaveTemplate=t2,o.usePipelineOrchestratorSetAgentAddonDefaults=HL,o.usePipelineOrchestratorSetCameraPipelineForAgent=XL,o.usePipelineOrchestratorSetCameraStepOverride=YL,o.usePipelineOrchestratorSetCameraStepToggle=qL,o.usePipelineOrchestratorSetCapabilityBinding=ML,o.usePipelineOrchestratorUnassignAudio=FL,o.usePipelineOrchestratorUnassignDecoder=RL,o.usePipelineOrchestratorUnassignPipeline=TL,o.usePipelineOrchestratorUpdateTemplate=r2,o.usePipelineRunnerAttachCamera=o2,o.usePipelineRunnerDetachCamera=l2,o.usePipelineRunnerGetAllCameraMetrics=h2,o.usePipelineRunnerGetCameraMetrics=f2,o.usePipelineRunnerGetLocalCameras=m2,o.usePipelineRunnerGetLocalLoad=u2,o.usePipelineRunnerGetLocalMetrics=d2,o.usePipelineRunnerReportMotion=c2,o.usePlayerOverlayLayer=Ah,o.usePlayerOverlayLayers=V6,o.usePlayerToolbarButton=H6,o.usePlayerToolbarButtons=fx,o.usePowerMeterGetStatus=g2,o.usePresenceGetStatus=p2,o.usePressureSensorGetStatus=v2,o.usePrivacyMaskGetOptions=b2,o.usePrivacyMaskGetStatus=x2,o.usePrivacyMaskSetMask=y2,o.usePtzAutotrackGetSettings=D2,o.usePtzAutotrackGetStatus=S0,o.usePtzAutotrackSetEnabled=_0,o.usePtzAutotrackSetSettings=w0,o.usePtzContinuousMove=_2,o.usePtzDeletePreset=C2,o.usePtzGetOptions=I2,o.usePtzGetPosition=A2,o.usePtzGetPresets=E2,o.usePtzGetStatus=N2,o.usePtzGoHome=P2,o.usePtzGoToPreset=k2,o.usePtzMove=S2,o.usePtzSavePreset=T2,o.usePtzSetAutofocus=j2,o.usePtzStop=w2,o.useRebootReboot=M2,o.useRecordingApplyDeviceSettingsPatch=U2,o.useRecordingGetAvailability=Pf,o.useRecordingGetDeviceConfig=E0,o.useRecordingGetDeviceLiveContribution=F2,o.useRecordingGetDeviceSettingsContribution=O2,o.useRecordingGetPlaybackManifest=$2,o.useRecordingGetStatus=C0,o.useRecordingGetStorageUsage=R2,o.useRecordingPruneFootage=L2,o.useRecordingRescanStorage=T0,o.useRecordingSetDeviceConfig=k0,o.useRemoteComponent=ox,o.useScriptRunnerGetStatus=G2,o.useScriptRunnerRun=B2,o.useScriptRunnerStop=z2,o.useSettingsStoreCount=Q2,o.useSettingsStoreDeclareCollection=J2,o.useSettingsStoreDelete=q2,o.useSettingsStoreGet=Z2,o.useSettingsStoreHistogram=Y2,o.useSettingsStoreInsert=K2,o.useSettingsStoreIsEmpty=X2,o.useSettingsStoreQuery=H2,o.useSettingsStoreSet=V2,o.useSettingsStoreUpdate=W2,o.useSmokeGetStatus=eO,o.useSnapshotApplyDeviceSettingsPatch=aO,o.useSnapshotGetDeviceLiveContribution=sO,o.useSnapshotGetDeviceSettingsContribution=iO,o.useSnapshotGetSnapshot=tO,o.useSnapshotGetStatus=nO,o.useSnapshotInvalidateCache=rO,o.useSnapshotProviderGetSnapshot=lO,o.useSnapshotProviderSupportsDevice=oO,o.useStorageAbortUpload=yO,o.useStorageBeginDownload=xO,o.useStorageBeginUpload=pO,o.useStorageDelete=mO,o.useStorageDeleteLocation=CO,o.useStorageEndDownload=_O,o.useStorageExists=fO,o.useStorageFinalizeUpload=bO,o.useStorageGetAvailableSpace=gO,o.useStorageGetDefaultLocation=EO,o.useStorageList=hO,o.useStorageListLocationDeclarations=kO,o.useStorageListLocations=wO,o.useStorageListProviders=PO,o.useStorageRead=dO,o.useStorageReadChunk=SO,o.useStorageResolve=cO,o.useStorageTestConfig=AO,o.useStorageTestLocation=IO,o.useStorageUpsertLocation=TO,o.useStorageWrite=uO,o.useStorageWriteChunk=vO,o.useStreamBrokerApplyDeviceSettingsPatch=a4,o.useStreamBrokerAssignProfile=DO,o.useStreamBrokerGetAllRtspEntries=JO,o.useStreamBrokerGetBrokerStats=LO,o.useStreamBrokerGetDeviceLiveContribution=s4,o.useStreamBrokerGetDeviceSettingsContribution=i4,o.useStreamBrokerGetPreBufferInfo=YO,o.useStreamBrokerGetRtspEntry=e4,o.useStreamBrokerGetRtspPort=XO,o.useStreamBrokerGetStreamUrl=BO,o.useStreamBrokerGetStreamWithCodec=zO,o.useStreamBrokerIsRtspEnabled=n4,o.useStreamBrokerKillClient=FO,o.useStreamBrokerListAllCameraStreams=$O,o.useStreamBrokerListAllProfileSlots=RO,o.useStreamBrokerListClients=OO,o.useStreamBrokerPublishCameraStream=jO,o.useStreamBrokerPullAudioChunks=VO,o.useStreamBrokerPullFrameHandles=WO,o.useStreamBrokerRegenerateRtspToken=t4,o.useStreamBrokerReleaseStreamWithCodec=GO,o.useStreamBrokerRestartProfile=UO,o.useStreamBrokerRetractCameraStream=NO,o.useStreamBrokerSetPreBufferDuration=QO,o.useStreamBrokerSetRtspEnabled=r4,o.useStreamBrokerSubscribeAudioChunks=ZO,o.useStreamBrokerSubscribeFrames=KO,o.useStreamBrokerUnassignProfile=MO,o.useStreamBrokerUnsubscribeAudioChunks=HO,o.useStreamBrokerUnsubscribeFrames=qO,o.useStreamCatalogGetCatalog=o4,o.useStreamParamsGetConfigSchema=u4,o.useStreamParamsGetOptions=l4,o.useStreamParamsGetStatus=d4,o.useStreamParamsSetProfile=c4,o.useSwitchGetStatus=h4,o.useSwitchSetState=f4,o.useSystem=Mr,o.useSystemFeatureFlags=p4,o.useSystemForceRetentionCleanup=x4,o.useSystemGetRetentionConfig=b4,o.useSystemHealth=g4,o.useSystemInfo=m4,o.useSystemMutation=zH,o.useSystemNetworkAddresses=v4,o.useSystemQuery=BH,o.useSystemSetRetentionConfig=y4,o.useTamperGetStatus=S4,o.useTemperatureSensorGetStatus=_4,o.useThemeMode=x.useThemeMode$1,o.useToastOnToast=w4,o.useTurnProviderGetTurnServers=E4,o.useUpdateGetStatus=T4,o.useUpdateInstallUpdate=k4,o.useUserManagementConfirmTotp=G4,o.useUserManagementCreateApiKey=$4,o.useUserManagementCreateScopedToken=O4,o.useUserManagementCreateUser=I4,o.useUserManagementDeleteUser=A4,o.useUserManagementDisableTotp=Z4,o.useUserManagementGetTotpStatus=V4,o.useUserManagementListApiKeys=M4,o.useUserManagementListOauthSessions=Y4,o.useUserManagementListScopedTokens=B4,o.useUserManagementListUsers=C4,o.useUserManagementOauthExchangeCode=W4,o.useUserManagementOauthIssueCode=K4,o.useUserManagementOauthRefresh=q4,o.useUserManagementOauthVerifyAccessToken=Q4,o.useUserManagementResetPassword=j4,o.useUserManagementRevokeApiKey=R4,o.useUserManagementRevokeOauthSession=X4,o.useUserManagementRevokeScopedToken=F4,o.useUserManagementSetUserScopes=N4,o.useUserManagementSetupTotp=z4,o.useUserManagementUpdateUser=P4,o.useUserManagementValidateApiKey=L4,o.useUserManagementValidateCredentials=D4,o.useUserManagementValidateScopedToken=U4,o.useUserManagementVerifyTotp=H4,o.useVacuumControlGetStatus=s5,o.useVacuumControlLocate=n5,o.useVacuumControlPause=e5,o.useVacuumControlReturnToBase=r5,o.useVacuumControlSetFanSpeed=i5,o.useVacuumControlStart=J4,o.useVacuumControlStop=t5,o.useValveClose=o5,o.useValveGetStatus=u5,o.useValveOpen=a5,o.useValveSetPosition=c5,o.useValveStop=l5,o.useVibrationGetStatus=d5,o.useVodPlayback=Sx,o.useWaterHeaterGetStatus=g5,o.useWaterHeaterSetAway=m5,o.useWaterHeaterSetOperationMode=h5,o.useWaterHeaterSetTargetTemp=f5,o.useWeatherGetStatus=p5,o.useWebrtcSessionAddIceCandidate=S5,o.useWebrtcSessionCloseSession=w5,o.useWebrtcSessionCreateSession=b5,o.useWebrtcSessionGetIceCandidates=_5,o.useWebrtcSessionGetSessionState=k5,o.useWebrtcSessionHandleAnswer=x5,o.useWebrtcSessionHandleOffer=y5,o.useWebrtcSessionHasAdaptiveBitrate=E5,o.useWebrtcSessionListStreams=v5,o.useWidget=R6,o.useWidgetMetadata=ax,o.useWidgetRegistry=ql,o.useZoneAnalyticsGetCameraHistory=I5,o.useZoneAnalyticsGetCurrentSnapshot=T5,o.useZoneAnalyticsGetUnzonedHistory=P5,o.useZoneAnalyticsGetZoneHistory=C5,o.useZoneEditing=MH,o.useZoneRulesListRules=A5,o.useZoneRulesSetRules=j5,o.useZonesAddZone=D5,o.useZonesListZones=N5,o.useZonesRemoveZone=M5,o.useZonesUpdateZone=$5,o.vacuumStateMeta=L0,o.validateScopes=NH,o.valveStateMeta=W0,o.waterHeaterPhase=ib,o.waterHeaterTint=nb,o.weatherConditionMeta=Rf,o.weatherTint=Lf})(vg)),vg}var Hw=Vw();const NY=WH(Hw),qY=iK({__proto__:null,default:NY},[Hw]);export{qY as i};