From 8fcf36f2c944117ce53d0b8946dbb2eb70f0324b Mon Sep 17 00:00:00 2001 From: Impre-visible Date: Sun, 17 Nov 2024 18:51:10 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20chore:=20Bump=20version=20to=201?= =?UTF-8?q?0.0.7-alpha=20in=20pyproject.toml=20and=20update=20asset=20refe?= =?UTF-8?q?rences=20in=20index.html?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pyproject.toml | 2 +- .../{index-C5JChcNU.js => index-CMWFoLd4.js} | 24 +++++++++---------- src/chocolate_app/templates/index.html | 2 +- 3 files changed, 14 insertions(+), 14 deletions(-) rename src/chocolate_app/static/assets/{index-C5JChcNU.js => index-CMWFoLd4.js} (77%) diff --git a/pyproject.toml b/pyproject.toml index 9181920..7e6dd04 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "chocolate_app" -version = "10.0.5-alpha" +version = "10.0.7-alpha" description = "" authors = [ { name = "Imprevisible", email = "impr.visible@gmail.com" }, diff --git a/src/chocolate_app/static/assets/index-C5JChcNU.js b/src/chocolate_app/static/assets/index-CMWFoLd4.js similarity index 77% rename from src/chocolate_app/static/assets/index-C5JChcNU.js rename to src/chocolate_app/static/assets/index-CMWFoLd4.js index 850e72e..dd71868 100644 --- a/src/chocolate_app/static/assets/index-C5JChcNU.js +++ b/src/chocolate_app/static/assets/index-CMWFoLd4.js @@ -82,30 +82,30 @@ Error generating stack: `+s.message+` * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. - */var gd=L,rC=tC;function nC(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var iC=typeof Object.is=="function"?Object.is:nC,sC=rC.useSyncExternalStore,aC=gd.useRef,oC=gd.useEffect,lC=gd.useMemo,uC=gd.useDebugValue;eE.useSyncExternalStoreWithSelector=function(t,e,r,n,i){var s=aC(null);if(s.current===null){var a={hasValue:!1,value:null};s.current=a}else a=s.current;s=lC(function(){function l(m){if(!u){if(u=!0,c=m,m=n(m),i!==void 0&&a.hasValue){var h=a.value;if(i(h,m))return d=h}return d=m}if(h=d,iC(c,m))return h;var p=n(m);return i!==void 0&&i(h,p)?h:(c=m,d=p)}var u=!1,c,d,f=r===void 0?null:r;return[function(){return l(e())},f===null?void 0:function(){return l(f())}]},[e,r,n,i]);var o=sC(t,s[0],s[1]);return oC(function(){a.hasValue=!0,a.value=o},[o]),uC(o),o};JS.exports=eE;var cC=JS.exports;const dC=dp(cC),nE={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_API_URL:""},{useDebugValue:fC}=ne,{useSyncExternalStoreWithSelector:hC}=dC;let O0=!1;const pC=t=>t;function mC(t,e=pC,r){(nE?"production":void 0)!=="production"&&r&&!O0&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),O0=!0);const n=hC(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,r);return fC(n),n}const gC=t=>{(nE?"production":void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof t=="function"?H_(t):t,r=(n,i)=>mC(e,n,i);return Object.assign(r,e),r},vC=t=>gC,yC={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_API_URL:""};function xC(t,e){let r;try{r=t()}catch{return}return{getItem:i=>{var s;const a=l=>l===null?null:JSON.parse(l,void 0),o=(s=r.getItem(i))!=null?s:null;return o instanceof Promise?o.then(a):a(o)},setItem:(i,s)=>r.setItem(i,JSON.stringify(s,void 0)),removeItem:i=>r.removeItem(i)}}const Zo=t=>e=>{try{const r=t(e);return r instanceof Promise?r:{then(n){return Zo(n)(r)},catch(n){return this}}}catch(r){return{then(n){return this},catch(n){return Zo(n)(r)}}}},SC=(t,e)=>(r,n,i)=>{let s={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:v=>v,version:0,merge:(v,g)=>({...g,...v}),...e},a=!1;const o=new Set,l=new Set;let u;try{u=s.getStorage()}catch{}if(!u)return t((...v)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),r(...v)},n,i);const c=Zo(s.serialize),d=()=>{const v=s.partialize({...n()});let g;const y=c({state:v,version:s.version}).then(x=>u.setItem(s.name,x)).catch(x=>{g=x});if(g)throw g;return y},f=i.setState;i.setState=(v,g)=>{f(v,g),d()};const m=t((...v)=>{r(...v),d()},n,i);let h;const p=()=>{var v;if(!u)return;a=!1,o.forEach(y=>y(n()));const g=((v=s.onRehydrateStorage)==null?void 0:v.call(s,n()))||void 0;return Zo(u.getItem.bind(u))(s.name).then(y=>{if(y)return s.deserialize(y)}).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==s.version){if(s.migrate)return s.migrate(y.state,y.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return y.state}).then(y=>{var x;return h=s.merge(y,(x=n())!=null?x:m),r(h,!0),d()}).then(()=>{g==null||g(h,void 0),a=!0,l.forEach(y=>y(h))}).catch(y=>{g==null||g(void 0,y)})};return i.persist={setOptions:v=>{s={...s,...v},v.getStorage&&(u=v.getStorage())},clearStorage:()=>{u==null||u.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>p(),hasHydrated:()=>a,onHydrate:v=>(o.add(v),()=>{o.delete(v)}),onFinishHydration:v=>(l.add(v),()=>{l.delete(v)})},p(),h||m},EC=(t,e)=>(r,n,i)=>{let s={storage:xC(()=>localStorage),partialize:p=>p,version:0,merge:(p,v)=>({...v,...p}),...e},a=!1;const o=new Set,l=new Set;let u=s.storage;if(!u)return t((...p)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),r(...p)},n,i);const c=()=>{const p=s.partialize({...n()});return u.setItem(s.name,{state:p,version:s.version})},d=i.setState;i.setState=(p,v)=>{d(p,v),c()};const f=t((...p)=>{r(...p),c()},n,i);i.getInitialState=()=>f;let m;const h=()=>{var p,v;if(!u)return;a=!1,o.forEach(y=>{var x;return y((x=n())!=null?x:f)});const g=((v=s.onRehydrateStorage)==null?void 0:v.call(s,(p=n())!=null?p:f))||void 0;return Zo(u.getItem.bind(u))(s.name).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==s.version){if(s.migrate)return[!0,s.migrate(y.state,y.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,y.state];return[!1,void 0]}).then(y=>{var x;const[S,T]=y;if(m=s.merge(T,(x=n())!=null?x:f),r(m,!0),S)return c()}).then(()=>{g==null||g(m,void 0),m=n(),a=!0,l.forEach(y=>y(m))}).catch(y=>{g==null||g(void 0,y)})};return i.persist={setOptions:p=>{s={...s,...p},p.storage&&(u=p.storage)},clearStorage:()=>{u==null||u.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>h(),hasHydrated:()=>a,onHydrate:p=>(o.add(p),()=>{o.delete(p)}),onFinishHydration:p=>(l.add(p),()=>{l.delete(p)})},s.skipHydration||h(),m||f},TC=(t,e)=>"getStorage"in e||"serialize"in e||"deserialize"in e?((yC?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),SC(t,e)):EC(t,e),wC=TC,Ua=vC()(wC(t=>({access_token:localStorage.getItem("access_token")||"",refresh_token:localStorage.getItem("refresh_token")||"",profileData:null,isLoggedIn:!1,updateAccessToken:e=>{t({access_token:e})},updateProfileData:e=>{t({profileData:e})},login:(e,r,n)=>{localStorage.setItem("access_token",e),localStorage.setItem("refresh_token",r),t({access_token:e,refresh_token:r,profileData:n,isLoggedIn:!0})},logout:()=>{localStorage.removeItem("access_token"),localStorage.removeItem("refresh_token"),t({access_token:"",refresh_token:"",profileData:null,isLoggedIn:!1})}}),{name:"login-storage",getStorage:()=>localStorage})),ur=(t,e="")=>{const[r,n]=L.useState(null),[i,s]=L.useState(!0),[a,o]=L.useState(null),l=L.useRef(null),{updateProfileData:u,updateAccessToken:c,logout:d}=Ua(),f=Br(),m=L.useCallback(async()=>{var g;if(t===""){s(!1);return}t.startsWith("/")||(t=`/${t}`),t.startsWith("http")&&(e=""),e||(e="");let p;const v=new AbortController;l.current=v;try{p=await fetch(`${e}${t}`,{headers:{Authorization:`Bearer ${localStorage.getItem("access_token")}`},signal:v.signal});let y;try{y=await p.json()}catch{y=await p.text(),y=JSON.parse(y)}if(y.error&&y.message==="INVALID_TOKEN")throw new Error(JSON.stringify(y));n(y),s(!1),o(null)}catch(y){if((g=l.current)!=null&&g.signal.aborted)return;if(p=JSON.parse(y.message),p.message==="INVALID_TOKEN"){const S=await(await fetch(`${e}/api/auth/refresh`,{method:"POST",body:JSON.stringify({refresh_token:localStorage.getItem("refresh_token")}),headers:{"Content-Type":"application/json"}})).json();if(S.error){d(),f("/login"),s(!1);return}else{localStorage.setItem("access_token",S.data.access_token),c(S.data.access_token),u(S.data.user),m();return}}o(p),s(!1),n(null)}},[t]);return L.useEffect(()=>{s(!0),m()},[m]),{data:r,loading:i,error:a,fetchData:m,interupt:()=>{var p;(p=l.current)==null||p.abort()}}};function Ss(){const[t,e]=L.useState(null),[r,n]=L.useState(!1),[i,s]=L.useState(null),[a,o]=L.useState(null),{access_token:l,refresh_token:u}=Ua(),c={Authorization:`Bearer ${l}`,"x-refresh-token":u};return{data:t,handleSubmit:async({e:m="",url:h,body:p=t,headers:v={...c},dispatcher:g=null,dispatch:y=x=>x})=>{m&&m.preventDefault(),n(!0),s(null);try{const x={method:"POST",headers:{...v,...c,"Content-Type":p instanceof FormData?"multipart/form-data":"application/json"},body:p instanceof FormData?p:JSON.stringify(p)};h.startsWith("http")||(h=`${h}`);const S=await fetch(h,x);if(!S.ok)throw new Error(`Request failed with status ${S.status}`);const T=await S.json();g!==null&&y!==null?g(y(T)):(e(T),o(T)),n(!1),s(null)}catch(x){s(x.message),n(!1)}},handleChange:m=>{m.persist(),e(h=>({...h,[m.target.name]:m.target.value}))},pending:r,error:i,resMsg:a}}function iE(){const[t,e]=L.useState(null),[r,n]=L.useState(!1),[i,s]=L.useState(null),[a,o]=L.useState(null),{access_token:l,refresh_token:u}=Ua(),c={Authorization:`Bearer ${l}`,"x-refresh-token":u};return{data:t,handleSubmit:async({e:m="",url:h,body:p=t,headers:v={...c},dispatcher:g=null,dispatch:y=x=>x})=>{m&&m.preventDefault(),n(!0),s(null);try{const x={method:"DELETE",headers:{...v,...c,"Content-Type":p instanceof FormData?"multipart/form-data":"application/json"},body:p instanceof FormData?p:JSON.stringify(p)};h.startsWith("http")||(h=`${h}`);const S=await fetch(h,x);if(!S.ok)throw new Error(`Request failed with status ${S.status}`);const T=await S.json();g!==null&&y!==null?g(y(T)):(e(T),o(T)),n(!1),s(null)}catch(x){s(x.message),n(!1)}},handleChange:m=>{m.persist(),e(h=>({...h,[m.target.name]:m.target.value}))},pending:r,error:i,resMsg:a}}function sE(){const[t,e]=L.useState(null),[r,n]=L.useState(!1),[i,s]=L.useState(null),[a,o]=L.useState(null),{access_token:l,refresh_token:u}=Ua(),c={Authorization:`Bearer ${l}`,"x-refresh-token":u};return{data:t,handleSubmit:async({e:m="",url:h,body:p=t,headers:v={...c},dispatcher:g=null,dispatch:y=x=>x})=>{m&&m.preventDefault(),n(!0),s(null);try{const x={method:"PUT",headers:{...v,...c,"Content-Type":p instanceof FormData?"multipart/form-data":"application/json"},body:p instanceof FormData?p:JSON.stringify(p)};h.startsWith("http")||(h=`${h}`);const S=await fetch(h,x);if(!S.ok)throw new Error(`Request failed with status ${S.status}`);const T=await S.json();g!==null&&y!==null?g(y(T)):(e(T),o(T)),n(!1),s(null)}catch(x){s(x.message),n(!1)}},handleChange:m=>{m.persist(),e(h=>({...h,[m.target.name]:m.target.value}))},pending:r,error:i,resMsg:a}}const dm=()=>{const{login:t,logout:e,isLoggedIn:r,profileData:n,updateProfileData:i}=Ua(),{handleSubmit:s}=Ss(),a=c=>{if(c){if(c.error)throw new Error(c.error);if(c.data){const{access_token:d,refresh_token:f,user:m}=c.data;t(d,f,m)}}};return{login:async({username:c,password:d})=>{await s({url:"/api/auth/login",body:{username:c,password:d},dispatcher:a})},logout:()=>{e()},isLoggedIn:r,profileData:n,updateProfileData:c=>{i(c)}}},bC=({user:t,onClick:e})=>E.jsxs("article",{className:"flex flex-col items-center justify-center gap-2 cursor-pointer",onClick:e,children:[E.jsx("img",{className:"w-32 h-32 rounded-lg",src:`${t.profile_picture}`,alt:t.name}),E.jsx("h2",{className:"text-2xl max-w-32 text-neutral-200 overflow-hidden text-ellipsis",children:t.name})]}),LC=({selectedUser:t,isOpen:e,onClose:r,onSubmit:n})=>{const[i,s]=L.useState("");return E.jsxs(E.Fragment,{children:[E.jsx("section",{className:`fixed top-0 left-0 w-full h-full bg-black bg-opacity-0 z-50 ${e?"pointer-events-auto":"bg-opacity-0 pointer-events-none"} transition-opacity duration-300`,onClick:r})," ",E.jsxs("section",{className:`fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-neutral-900 rounded-lg p-8 z-50 ${e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"} transition-opacity duration-300`,children:[E.jsx("input",{type:"password",placeholder:"Password",value:i,onChange:a=>s(a.target.value),className:"w-full px-4 py-2 mb-4 rounded-lg border border-neutral-300 focus:outline-none focus:ring-2 focus:ring-primary-500"}),E.jsx("button",{onClick:()=>n((t==null?void 0:t.name)||"",i),className:"w-full px-4 py-2 text-white bg-primary-500 rounded-lg hover:bg-primary-600 focus:outline-none focus:ring-2 focus:ring-primary-500",children:"Login"})]})]})},AC=()=>{const[t,e]=L.useState(!1),[r,n]=L.useState(null),{data:i,error:s}=ur("/api/auth/accounts"),{login:a}=dm(),o=Br();L.useEffect(()=>{i&&i.data.length===0&&o("/invite")},[i]),L.useEffect(()=>{s&&Ke.error(s.message)});const l=c=>{c.password_empty?u(c.name,""):(n(c),e(!0))},u=async(c,d)=>{try{await a({username:c,password:d}),o("/home")}catch(f){Ke.error(f.message)}};return E.jsxs(E.Fragment,{children:[E.jsx("section",{className:"flex flex-wrap items-center justify-center content-center gap-x-16 gap-y-8 px-80 py-32 max-h-screen h-screen max-w-screen",children:i&&i.data.map(c=>E.jsx(bC,{user:c,onClick:()=>l(c)},c.id))}),E.jsx(LC,{selectedUser:r,isOpen:t,onClose:()=>{e(!1),n(null)},onSubmit:u})]})},_C=()=>{const t=Br(),{logout:e}=dm();return L.useEffect(()=>{e(),t("/login")},[]),E.jsx("div",{children:"Logging out..."})};var El=t=>t.type==="checkbox",Js=t=>t instanceof Date,ar=t=>t==null;const aE=t=>typeof t=="object";var Rt=t=>!ar(t)&&!Array.isArray(t)&&aE(t)&&!Js(t),oE=t=>Rt(t)&&t.target?El(t.target)?t.target.checked:t.target.value:t,CC=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,lE=(t,e)=>t.has(CC(e)),RC=t=>{const e=t.constructor&&t.constructor.prototype;return Rt(e)&&e.hasOwnProperty("isPrototypeOf")},fm=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function mr(t){let e;const r=Array.isArray(t);if(t instanceof Date)e=new Date(t);else if(t instanceof Set)e=new Set(t);else if(!(fm&&(t instanceof Blob||t instanceof FileList))&&(r||Rt(t)))if(e=r?[]:{},!r&&!RC(t))e=t;else for(const n in t)t.hasOwnProperty(n)&&(e[n]=mr(t[n]));else return t;return e}var vd=t=>Array.isArray(t)?t.filter(Boolean):[],bt=t=>t===void 0,ie=(t,e,r)=>{if(!e||!Rt(t))return r;const n=vd(e.split(/[,[\].]+?/)).reduce((i,s)=>ar(i)?i:i[s],t);return bt(n)||n===t?bt(t[e])?r:t[e]:n},Wr=t=>typeof t=="boolean",hm=t=>/^\w*$/.test(t),uE=t=>vd(t.replace(/["|']|\]/g,"").split(/\.|\[/)),Ze=(t,e,r)=>{let n=-1;const i=hm(e)?[e]:uE(e),s=i.length,a=s-1;for(;++nne.useContext(cE),IC=t=>{const{children:e,...r}=t;return ne.createElement(cE.Provider,{value:r},e)};var dE=(t,e,r,n=!0)=>{const i={defaultValues:e._defaultValues};for(const s in t)Object.defineProperty(i,s,{get:()=>{const a=s;return e._proxyFormState[a]!==fn.all&&(e._proxyFormState[a]=!n||fn.all),r&&(r[a]=!0),t[a]}});return i},gr=t=>Rt(t)&&!Object.keys(t).length,fE=(t,e,r,n)=>{r(t);const{name:i,...s}=t;return gr(s)||Object.keys(s).length>=Object.keys(e).length||Object.keys(s).find(a=>e[a]===(!n||fn.all))},bo=t=>Array.isArray(t)?t:[t],hE=(t,e,r)=>!t||!e||t===e||bo(t).some(n=>n&&(r?n===e:n.startsWith(e)||e.startsWith(n)));function pm(t){const e=ne.useRef(t);e.current=t,ne.useEffect(()=>{const r=!t.disabled&&e.current.subject&&e.current.subject.subscribe({next:e.current.next});return()=>{r&&r.unsubscribe()}},[t.disabled])}function kC(t){const e=yd(),{control:r=e.control,disabled:n,name:i,exact:s}=t||{},[a,o]=ne.useState(r._formState),l=ne.useRef(!0),u=ne.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),c=ne.useRef(i);return c.current=i,pm({disabled:n,next:d=>l.current&&hE(c.current,d.name,s)&&fE(d,u.current,r._updateFormState)&&o({...r._formState,...d}),subject:r._subjects.state}),ne.useEffect(()=>(l.current=!0,u.current.isValid&&r._updateValid(!0),()=>{l.current=!1}),[r]),dE(a,r,u.current,!1)}var Cn=t=>typeof t=="string",pE=(t,e,r,n,i)=>Cn(t)?(n&&e.watch.add(t),ie(r,t,i)):Array.isArray(t)?t.map(s=>(n&&e.watch.add(s),ie(r,s))):(n&&(e.watchAll=!0),r);function DC(t){const e=yd(),{control:r=e.control,name:n,defaultValue:i,disabled:s,exact:a}=t||{},o=ne.useRef(n);o.current=n,pm({disabled:s,subject:r._subjects.values,next:c=>{hE(o.current,c.name,a)&&u(mr(pE(o.current,r._names,c.values||r._formValues,!1,i)))}});const[l,u]=ne.useState(r._getWatch(n,i));return ne.useEffect(()=>r._removeUnmounted()),l}function PC(t){const e=yd(),{name:r,disabled:n,control:i=e.control,shouldUnregister:s}=t,a=lE(i._names.array,r),o=DC({control:i,name:r,defaultValue:ie(i._formValues,r,ie(i._defaultValues,r,t.defaultValue)),exact:!0}),l=kC({control:i,name:r,exact:!0}),u=ne.useRef(i.register(r,{...t.rules,value:o,...Wr(t.disabled)?{disabled:t.disabled}:{}}));return ne.useEffect(()=>{const c=i._options.shouldUnregister||s,d=(f,m)=>{const h=ie(i._fields,f);h&&h._f&&(h._f.mount=m)};if(d(r,!0),c){const f=mr(ie(i._options.defaultValues,r));Ze(i._defaultValues,r,f),bt(ie(i._formValues,r))&&Ze(i._formValues,r,f)}return()=>{(a?c&&!i._state.action:c)?i.unregister(r):d(r,!1)}},[r,i,a,s]),ne.useEffect(()=>{ie(i._fields,r)&&i._updateDisabledField({disabled:n,fields:i._fields,name:r,value:ie(i._fields,r)._f.value})},[n,r,i]),{field:{name:r,value:o,...Wr(n)||l.disabled?{disabled:l.disabled||n}:{},onChange:ne.useCallback(c=>u.current.onChange({target:{value:oE(c),name:r},type:vc.CHANGE}),[r]),onBlur:ne.useCallback(()=>u.current.onBlur({target:{value:ie(i._formValues,r),name:r},type:vc.BLUR}),[r,i]),ref:ne.useCallback(c=>{const d=ie(i._fields,r);d&&c&&(d._f.ref={focus:()=>c.focus(),select:()=>c.select(),setCustomValidity:f=>c.setCustomValidity(f),reportValidity:()=>c.reportValidity()})},[i._fields,r])},formState:l,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ie(l.errors,r)},isDirty:{enumerable:!0,get:()=>!!ie(l.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!ie(l.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!ie(l.validatingFields,r)},error:{enumerable:!0,get:()=>ie(l.errors,r)}})}}const OC=t=>t.render(PC(t));var mE=(t,e,r,n,i)=>e?{...r[t],types:{...r[t]&&r[t].types?r[t].types:{},[n]:i||!0}}:{},M0=t=>({isOnSubmit:!t||t===fn.onSubmit,isOnBlur:t===fn.onBlur,isOnChange:t===fn.onChange,isOnAll:t===fn.all,isOnTouch:t===fn.onTouched}),N0=(t,e,r)=>!r&&(e.watchAll||e.watch.has(t)||[...e.watch].some(n=>t.startsWith(n)&&/^\.\w+/.test(t.slice(n.length))));const Lo=(t,e,r,n)=>{for(const i of r||Object.keys(t)){const s=ie(t,i);if(s){const{_f:a,...o}=s;if(a){if(a.refs&&a.refs[0]&&e(a.refs[0],i)&&!n)return!0;if(a.ref&&e(a.ref,a.name)&&!n)return!0;if(Lo(o,e))break}else if(Rt(o)&&Lo(o,e))break}}};var MC=(t,e,r)=>{const n=bo(ie(t,r));return Ze(n,"root",e[r]),Ze(t,r,n),t},mm=t=>t.type==="file",ni=t=>typeof t=="function",yc=t=>{if(!fm)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},_u=t=>Cn(t),gm=t=>t.type==="radio",xc=t=>t instanceof RegExp;const F0={value:!1,isValid:!1},U0={value:!0,isValid:!0};var gE=t=>{if(Array.isArray(t)){if(t.length>1){const e=t.filter(r=>r&&r.checked&&!r.disabled).map(r=>r.value);return{value:e,isValid:!!e.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!bt(t[0].attributes.value)?bt(t[0].value)||t[0].value===""?U0:{value:t[0].value,isValid:!0}:U0:F0}return F0};const B0={isValid:!1,value:null};var vE=t=>Array.isArray(t)?t.reduce((e,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:e,B0):B0;function $0(t,e,r="validate"){if(_u(t)||Array.isArray(t)&&t.every(_u)||Wr(t)&&!t)return{type:r,message:_u(t)?t:"",ref:e}}var Ps=t=>Rt(t)&&!xc(t)?t:{value:t,message:""},j0=async(t,e,r,n,i)=>{const{ref:s,refs:a,required:o,maxLength:l,minLength:u,min:c,max:d,pattern:f,validate:m,name:h,valueAsNumber:p,mount:v,disabled:g}=t._f,y=ie(e,h);if(!v||g)return{};const x=a?a[0]:s,S=O=>{n&&x.reportValidity&&(x.setCustomValidity(Wr(O)?"":O||""),x.reportValidity())},T={},C=gm(s),_=El(s),b=C||_,I=(p||mm(s))&&bt(s.value)&&bt(y)||yc(s)&&s.value===""||y===""||Array.isArray(y)&&!y.length,A=mE.bind(null,h,r,T),k=(O,P,G,K=Gn.maxLength,H=Gn.minLength)=>{const se=O?P:G;T[h]={type:O?K:H,message:se,ref:s,...A(O?K:H,se)}};if(i?!Array.isArray(y)||!y.length:o&&(!b&&(I||ar(y))||Wr(y)&&!y||_&&!gE(a).isValid||C&&!vE(a).isValid)){const{value:O,message:P}=_u(o)?{value:!!o,message:o}:Ps(o);if(O&&(T[h]={type:Gn.required,message:P,ref:x,...A(Gn.required,P)},!r))return S(P),T}if(!I&&(!ar(c)||!ar(d))){let O,P;const G=Ps(d),K=Ps(c);if(!ar(y)&&!isNaN(y)){const H=s.valueAsNumber||y&&+y;ar(G.value)||(O=H>G.value),ar(K.value)||(P=Hnew Date(new Date().toDateString()+" "+j),W=s.type=="time",F=s.type=="week";Cn(G.value)&&y&&(O=W?se(y)>se(G.value):F?y>G.value:H>new Date(G.value)),Cn(K.value)&&y&&(P=W?se(y)+O.value,K=!ar(P.value)&&y.length<+P.value;if((G||K)&&(k(G,O.message,P.message),!r))return S(T[h].message),T}if(f&&!I&&Cn(y)){const{value:O,message:P}=Ps(f);if(xc(O)&&!y.match(O)&&(T[h]={type:Gn.pattern,message:P,ref:s,...A(Gn.pattern,P)},!r))return S(P),T}if(m){if(ni(m)){const O=await m(y,e),P=$0(O,x);if(P&&(T[h]={...P,...A(Gn.validate,P.message)},!r))return S(P.message),T}else if(Rt(m)){let O={};for(const P in m){if(!gr(O)&&!r)break;const G=$0(await m[P](y,e),x,P);G&&(O={...G,...A(P,G.message)},S(G.message),r&&(T[h]=O))}if(!gr(O)&&(T[h]={ref:x,...O},!r))return T}}return S(!0),T};function NC(t,e){const r=e.slice(0,-1).length;let n=0;for(;n{let t=[];return{get observers(){return t},next:i=>{for(const s of t)s.next&&s.next(i)},subscribe:i=>(t.push(i),{unsubscribe:()=>{t=t.filter(s=>s!==i)}}),unsubscribe:()=>{t=[]}}},Sc=t=>ar(t)||!aE(t);function Li(t,e){if(Sc(t)||Sc(e))return t===e;if(Js(t)&&Js(e))return t.getTime()===e.getTime();const r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(const i of r){const s=t[i];if(!n.includes(i))return!1;if(i!=="ref"){const a=e[i];if(Js(s)&&Js(a)||Rt(s)&&Rt(a)||Array.isArray(s)&&Array.isArray(a)?!Li(s,a):s!==a)return!1}}return!0}var yE=t=>t.type==="select-multiple",UC=t=>gm(t)||El(t),af=t=>yc(t)&&t.isConnected,xE=t=>{for(const e in t)if(ni(t[e]))return!0;return!1};function Ec(t,e={}){const r=Array.isArray(t);if(Rt(t)||r)for(const n in t)Array.isArray(t[n])||Rt(t[n])&&!xE(t[n])?(e[n]=Array.isArray(t[n])?[]:{},Ec(t[n],e[n])):ar(t[n])||(e[n]=!0);return e}function SE(t,e,r){const n=Array.isArray(t);if(Rt(t)||n)for(const i in t)Array.isArray(t[i])||Rt(t[i])&&!xE(t[i])?bt(e)||Sc(r[i])?r[i]=Array.isArray(t[i])?Ec(t[i],[]):{...Ec(t[i])}:SE(t[i],ar(e)?{}:e[i],r[i]):r[i]=!Li(t[i],e[i]);return r}var Ql=(t,e)=>SE(t,e,Ec(e)),EE=(t,{valueAsNumber:e,valueAsDate:r,setValueAs:n})=>bt(t)?t:e?t===""?NaN:t&&+t:r&&Cn(t)?new Date(t):n?n(t):t;function of(t){const e=t.ref;if(!(t.refs?t.refs.every(r=>r.disabled):e.disabled))return mm(e)?e.files:gm(e)?vE(t.refs).value:yE(e)?[...e.selectedOptions].map(({value:r})=>r):El(e)?gE(t.refs).value:EE(bt(e.value)?t.ref.value:e.value,t)}var BC=(t,e,r,n)=>{const i={};for(const s of t){const a=ie(e,s);a&&Ze(i,s,a._f)}return{criteriaMode:r,names:[...t],fields:i,shouldUseNativeValidation:n}},eo=t=>bt(t)?t:xc(t)?t.source:Rt(t)?xc(t.value)?t.value.source:t.value:t;const V0="AsyncFunction";var $C=t=>(!t||!t.validate)&&!!(ni(t.validate)&&t.validate.constructor.name===V0||Rt(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===V0)),jC=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate);function G0(t,e,r){const n=ie(t,r);if(n||hm(r))return{error:n,name:r};const i=r.split(".");for(;i.length;){const s=i.join("."),a=ie(e,s),o=ie(t,s);if(a&&!Array.isArray(a)&&r!==s)return{name:r};if(o&&o.type)return{name:s,error:o};i.pop()}return{name:r}}var VC=(t,e,r,n,i)=>i.isOnAll?!1:!r&&i.isOnTouch?!(e||t):(r?n.isOnBlur:i.isOnBlur)?!t:(r?n.isOnChange:i.isOnChange)?t:!0,GC=(t,e)=>!vd(ie(t,e)).length&&kt(t,e);const zC={mode:fn.onSubmit,reValidateMode:fn.onChange,shouldFocusError:!0};function HC(t={}){let e={...zC,...t},r={submitCount:0,isDirty:!1,isLoading:ni(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1},n={},i=Rt(e.defaultValues)||Rt(e.values)?mr(e.defaultValues||e.values)||{}:{},s=e.shouldUnregister?{}:mr(i),a={action:!1,mount:!1,watch:!1},o={mount:new Set,unMount:new Set,array:new Set,watch:new Set},l,u=0;const c={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},d={values:sf(),array:sf(),state:sf()},f=M0(e.mode),m=M0(e.reValidateMode),h=e.criteriaMode===fn.all,p=R=>N=>{clearTimeout(u),u=setTimeout(R,N)},v=async R=>{if(c.isValid||R){const N=e.resolver?gr((await b()).errors):await A(n,!0);N!==r.isValid&&d.state.next({isValid:N})}},g=(R,N)=>{(c.isValidating||c.validatingFields)&&((R||Array.from(o.mount)).forEach($=>{$&&(N?Ze(r.validatingFields,$,N):kt(r.validatingFields,$))}),d.state.next({validatingFields:r.validatingFields,isValidating:!gr(r.validatingFields)}))},y=(R,N=[],$,re,Z=!0,X=!0)=>{if(re&&$){if(a.action=!0,X&&Array.isArray(ie(n,R))){const ge=$(ie(n,R),re.argA,re.argB);Z&&Ze(n,R,ge)}if(X&&Array.isArray(ie(r.errors,R))){const ge=$(ie(r.errors,R),re.argA,re.argB);Z&&Ze(r.errors,R,ge),GC(r.errors,R)}if(c.touchedFields&&X&&Array.isArray(ie(r.touchedFields,R))){const ge=$(ie(r.touchedFields,R),re.argA,re.argB);Z&&Ze(r.touchedFields,R,ge)}c.dirtyFields&&(r.dirtyFields=Ql(i,s)),d.state.next({name:R,isDirty:O(R,N),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else Ze(s,R,N)},x=(R,N)=>{Ze(r.errors,R,N),d.state.next({errors:r.errors})},S=R=>{r.errors=R,d.state.next({errors:r.errors,isValid:!1})},T=(R,N,$,re)=>{const Z=ie(n,R);if(Z){const X=ie(s,R,bt($)?ie(i,R):$);bt(X)||re&&re.defaultChecked||N?Ze(s,R,N?X:of(Z._f)):K(R,X),a.mount&&v()}},C=(R,N,$,re,Z)=>{let X=!1,ge=!1;const oe={name:R},xe=!!(ie(n,R)&&ie(n,R)._f&&ie(n,R)._f.disabled);if(!$||re){c.isDirty&&(ge=r.isDirty,r.isDirty=oe.isDirty=O(),X=ge!==oe.isDirty);const ce=xe||Li(ie(i,R),N);ge=!!(!xe&&ie(r.dirtyFields,R)),ce||xe?kt(r.dirtyFields,R):Ze(r.dirtyFields,R,!0),oe.dirtyFields=r.dirtyFields,X=X||c.dirtyFields&&ge!==!ce}if($){const ce=ie(r.touchedFields,R);ce||(Ze(r.touchedFields,R,$),oe.touchedFields=r.touchedFields,X=X||c.touchedFields&&ce!==$)}return X&&Z&&d.state.next(oe),X?oe:{}},_=(R,N,$,re)=>{const Z=ie(r.errors,R),X=c.isValid&&Wr(N)&&r.isValid!==N;if(t.delayError&&$?(l=p(()=>x(R,$)),l(t.delayError)):(clearTimeout(u),l=null,$?Ze(r.errors,R,$):kt(r.errors,R)),($?!Li(Z,$):Z)||!gr(re)||X){const ge={...re,...X&&Wr(N)?{isValid:N}:{},errors:r.errors,name:R};r={...r,...ge},d.state.next(ge)}},b=async R=>{g(R,!0);const N=await e.resolver(s,e.context,BC(R||o.mount,n,e.criteriaMode,e.shouldUseNativeValidation));return g(R),N},I=async R=>{const{errors:N}=await b(R);if(R)for(const $ of R){const re=ie(N,$);re?Ze(r.errors,$,re):kt(r.errors,$)}else r.errors=N;return N},A=async(R,N,$={valid:!0})=>{for(const re in R){const Z=R[re];if(Z){const{_f:X,...ge}=Z;if(X){const oe=o.array.has(X.name),xe=Z._f&&$C(Z._f);xe&&c.validatingFields&&g([re],!0);const ce=await j0(Z,s,h,e.shouldUseNativeValidation&&!N,oe);if(xe&&c.validatingFields&&g([re]),ce[X.name]&&($.valid=!1,N))break;!N&&(ie(ce,X.name)?oe?MC(r.errors,ce,X.name):Ze(r.errors,X.name,ce[X.name]):kt(r.errors,X.name))}!gr(ge)&&await A(ge,N,$)}}return $.valid},k=()=>{for(const R of o.unMount){const N=ie(n,R);N&&(N._f.refs?N._f.refs.every($=>!af($)):!af(N._f.ref))&&Ee(R)}o.unMount=new Set},O=(R,N)=>(R&&N&&Ze(s,R,N),!Li(te(),i)),P=(R,N,$)=>pE(R,o,{...a.mount?s:bt(N)?i:Cn(R)?{[R]:N}:N},$,N),G=R=>vd(ie(a.mount?s:i,R,t.shouldUnregister?ie(i,R,[]):[])),K=(R,N,$={})=>{const re=ie(n,R);let Z=N;if(re){const X=re._f;X&&(!X.disabled&&Ze(s,R,EE(N,X)),Z=yc(X.ref)&&ar(N)?"":N,yE(X.ref)?[...X.ref.options].forEach(ge=>ge.selected=Z.includes(ge.value)):X.refs?El(X.ref)?X.refs.length>1?X.refs.forEach(ge=>(!ge.defaultChecked||!ge.disabled)&&(ge.checked=Array.isArray(Z)?!!Z.find(oe=>oe===ge.value):Z===ge.value)):X.refs[0]&&(X.refs[0].checked=!!Z):X.refs.forEach(ge=>ge.checked=ge.value===Z):mm(X.ref)?X.ref.value="":(X.ref.value=Z,X.ref.type||d.values.next({name:R,values:{...s}})))}($.shouldDirty||$.shouldTouch)&&C(R,Z,$.shouldTouch,$.shouldDirty,!0),$.shouldValidate&&j(R)},H=(R,N,$)=>{for(const re in N){const Z=N[re],X=`${R}.${re}`,ge=ie(n,X);(o.array.has(R)||!Sc(Z)||ge&&!ge._f)&&!Js(Z)?H(X,Z,$):K(X,Z,$)}},se=(R,N,$={})=>{const re=ie(n,R),Z=o.array.has(R),X=mr(N);Ze(s,R,X),Z?(d.array.next({name:R,values:{...s}}),(c.isDirty||c.dirtyFields)&&$.shouldDirty&&d.state.next({name:R,dirtyFields:Ql(i,s),isDirty:O(R,X)})):re&&!re._f&&!ar(X)?H(R,X,$):K(R,X,$),N0(R,o)&&d.state.next({...r}),d.values.next({name:a.mount?R:void 0,values:{...s}})},W=async R=>{a.mount=!0;const N=R.target;let $=N.name,re=!0;const Z=ie(n,$),X=()=>N.type?of(Z._f):oE(R),ge=oe=>{re=Number.isNaN(oe)||Li(oe,ie(s,$,oe))};if(Z){let oe,xe;const ce=X(),Ge=R.type===vc.BLUR||R.type===vc.FOCUS_OUT,nr=!jC(Z._f)&&!e.resolver&&!ie(r.errors,$)&&!Z._f.deps||VC(Ge,ie(r.touchedFields,$),r.isSubmitted,m,f),mt=N0($,o,Ge);Ze(s,$,ce),Ge?(Z._f.onBlur&&Z._f.onBlur(R),l&&l(0)):Z._f.onChange&&Z._f.onChange(R);const Pe=C($,ce,Ge,!1),Le=!gr(Pe)||mt;if(!Ge&&d.values.next({name:$,type:R.type,values:{...s}}),nr)return c.isValid&&(t.mode==="onBlur"?Ge&&v():v()),Le&&d.state.next({name:$,...mt?{}:Pe});if(!Ge&&mt&&d.state.next({...r}),e.resolver){const{errors:Nt}=await b([$]);if(ge(ce),re){const Xi=G0(r.errors,n,$),hr=G0(Nt,n,Xi.name||$);oe=hr.error,$=hr.name,xe=gr(Nt)}}else g([$],!0),oe=(await j0(Z,s,h,e.shouldUseNativeValidation))[$],g([$]),ge(ce),re&&(oe?xe=!1:c.isValid&&(xe=await A(n,!0)));re&&(Z._f.deps&&j(Z._f.deps),_($,xe,oe,Pe))}},F=(R,N)=>{if(ie(r.errors,N)&&R.focus)return R.focus(),1},j=async(R,N={})=>{let $,re;const Z=bo(R);if(e.resolver){const X=await I(bt(R)?R:Z);$=gr(X),re=R?!Z.some(ge=>ie(X,ge)):$}else R?(re=(await Promise.all(Z.map(async X=>{const ge=ie(n,X);return await A(ge&&ge._f?{[X]:ge}:ge)}))).every(Boolean),!(!re&&!r.isValid)&&v()):re=$=await A(n);return d.state.next({...!Cn(R)||c.isValid&&$!==r.isValid?{}:{name:R},...e.resolver||!R?{isValid:$}:{},errors:r.errors}),N.shouldFocus&&!re&&Lo(n,F,R?Z:o.mount),re},te=R=>{const N={...a.mount?s:i};return bt(R)?N:Cn(R)?ie(N,R):R.map($=>ie(N,$))},ee=(R,N)=>({invalid:!!ie((N||r).errors,R),isDirty:!!ie((N||r).dirtyFields,R),error:ie((N||r).errors,R),isValidating:!!ie(r.validatingFields,R),isTouched:!!ie((N||r).touchedFields,R)}),fe=R=>{R&&bo(R).forEach(N=>kt(r.errors,N)),d.state.next({errors:R?r.errors:{}})},ye=(R,N,$)=>{const re=(ie(n,R,{_f:{}})._f||{}).ref,Z=ie(r.errors,R)||{},{ref:X,message:ge,type:oe,...xe}=Z;Ze(r.errors,R,{...xe,...N,ref:re}),d.state.next({name:R,errors:r.errors,isValid:!1}),$&&$.shouldFocus&&re&&re.focus&&re.focus()},Re=(R,N)=>ni(R)?d.values.subscribe({next:$=>R(P(void 0,N),$)}):P(R,N,!0),Ee=(R,N={})=>{for(const $ of R?bo(R):o.mount)o.mount.delete($),o.array.delete($),N.keepValue||(kt(n,$),kt(s,$)),!N.keepError&&kt(r.errors,$),!N.keepDirty&&kt(r.dirtyFields,$),!N.keepTouched&&kt(r.touchedFields,$),!N.keepIsValidating&&kt(r.validatingFields,$),!e.shouldUnregister&&!N.keepDefaultValue&&kt(i,$);d.values.next({values:{...s}}),d.state.next({...r,...N.keepDirty?{isDirty:O()}:{}}),!N.keepIsValid&&v()},Fe=({disabled:R,name:N,field:$,fields:re,value:Z})=>{if(Wr(R)&&a.mount||R){const X=R?void 0:bt(Z)?of($?$._f:ie(re,N)._f):Z;Ze(s,N,X),C(N,X,!1,!1,!0)}},st=(R,N={})=>{let $=ie(n,R);const re=Wr(N.disabled)||Wr(t.disabled);return Ze(n,R,{...$||{},_f:{...$&&$._f?$._f:{ref:{name:R}},name:R,mount:!0,...N}}),o.mount.add(R),$?Fe({field:$,disabled:Wr(N.disabled)?N.disabled:t.disabled,name:R,value:N.value}):T(R,!0,N.value),{...re?{disabled:N.disabled||t.disabled}:{},...e.progressive?{required:!!N.required,min:eo(N.min),max:eo(N.max),minLength:eo(N.minLength),maxLength:eo(N.maxLength),pattern:eo(N.pattern)}:{},name:R,onChange:W,onBlur:W,ref:Z=>{if(Z){st(R,N),$=ie(n,R);const X=bt(Z.value)&&Z.querySelectorAll&&Z.querySelectorAll("input,select,textarea")[0]||Z,ge=UC(X),oe=$._f.refs||[];if(ge?oe.find(xe=>xe===X):X===$._f.ref)return;Ze(n,R,{_f:{...$._f,...ge?{refs:[...oe.filter(af),X,...Array.isArray(ie(i,R))?[{}]:[]],ref:{type:X.type,name:R}}:{ref:X}}}),T(R,!1,void 0,X)}else $=ie(n,R,{}),$._f&&($._f.mount=!1),(e.shouldUnregister||N.shouldUnregister)&&!(lE(o.array,R)&&a.action)&&o.unMount.add(R)}}},br=()=>e.shouldFocusError&&Lo(n,F,o.mount),tn=R=>{Wr(R)&&(d.state.next({disabled:R}),Lo(n,(N,$)=>{const re=ie(n,$);re&&(N.disabled=re._f.disabled||R,Array.isArray(re._f.refs)&&re._f.refs.forEach(Z=>{Z.disabled=re._f.disabled||R}))},0,!1))},jn=(R,N)=>async $=>{let re;$&&($.preventDefault&&$.preventDefault(),$.persist&&$.persist());let Z=mr(s);if(d.state.next({isSubmitting:!0}),e.resolver){const{errors:X,values:ge}=await b();r.errors=X,Z=ge}else await A(n);if(kt(r.errors,"root"),gr(r.errors)){d.state.next({errors:{}});try{await R(Z,$)}catch(X){re=X}}else N&&await N({...r.errors},$),br(),setTimeout(br);if(d.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:gr(r.errors)&&!re,submitCount:r.submitCount+1,errors:r.errors}),re)throw re},rn=(R,N={})=>{ie(n,R)&&(bt(N.defaultValue)?se(R,mr(ie(i,R))):(se(R,N.defaultValue),Ze(i,R,mr(N.defaultValue))),N.keepTouched||kt(r.touchedFields,R),N.keepDirty||(kt(r.dirtyFields,R),r.isDirty=N.defaultValue?O(R,mr(ie(i,R))):O()),N.keepError||(kt(r.errors,R),c.isValid&&v()),d.state.next({...r}))},xn=(R,N={})=>{const $=R?mr(R):i,re=mr($),Z=gr(R),X=Z?i:re;if(N.keepDefaultValues||(i=$),!N.keepValues){if(N.keepDirtyValues)for(const ge of o.mount)ie(r.dirtyFields,ge)?Ze(X,ge,ie(s,ge)):se(ge,ie(X,ge));else{if(fm&&bt(R))for(const ge of o.mount){const oe=ie(n,ge);if(oe&&oe._f){const xe=Array.isArray(oe._f.refs)?oe._f.refs[0]:oe._f.ref;if(yc(xe)){const ce=xe.closest("form");if(ce){ce.reset();break}}}}n={}}s=t.shouldUnregister?N.keepDefaultValues?mr(i):{}:mr(X),d.array.next({values:{...X}}),d.values.next({values:{...X}})}o={mount:N.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},a.mount=!c.isValid||!!N.keepIsValid||!!N.keepDirtyValues,a.watch=!!t.shouldUnregister,d.state.next({submitCount:N.keepSubmitCount?r.submitCount:0,isDirty:Z?!1:N.keepDirty?r.isDirty:!!(N.keepDefaultValues&&!Li(R,i)),isSubmitted:N.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Z?{}:N.keepDirtyValues?N.keepDefaultValues&&s?Ql(i,s):r.dirtyFields:N.keepDefaultValues&&R?Ql(i,R):N.keepDirty?r.dirtyFields:{},touchedFields:N.keepTouched?r.touchedFields:{},errors:N.keepErrors?r.errors:{},isSubmitSuccessful:N.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},nt=(R,N)=>xn(ni(R)?R(s):R,N);return{control:{register:st,unregister:Ee,getFieldState:ee,handleSubmit:jn,setError:ye,_executeSchema:b,_getWatch:P,_getDirty:O,_updateValid:v,_removeUnmounted:k,_updateFieldArray:y,_updateDisabledField:Fe,_getFieldArray:G,_reset:xn,_resetDefaultValues:()=>ni(e.defaultValues)&&e.defaultValues().then(R=>{nt(R,e.resetOptions),d.state.next({isLoading:!1})}),_updateFormState:R=>{r={...r,...R}},_disableForm:tn,_subjects:d,_proxyFormState:c,_setErrors:S,get _fields(){return n},get _formValues(){return s},get _state(){return a},set _state(R){a=R},get _defaultValues(){return i},get _names(){return o},set _names(R){o=R},get _formState(){return r},set _formState(R){r=R},get _options(){return e},set _options(R){e={...e,...R}}},trigger:j,register:st,handleSubmit:jn,watch:Re,setValue:se,getValues:te,reset:nt,resetField:rn,clearErrors:fe,unregister:Ee,setError:ye,setFocus:(R,N={})=>{const $=ie(n,R),re=$&&$._f;if(re){const Z=re.refs?re.refs[0]:re.ref;Z.focus&&(Z.focus(),N.shouldSelect&&Z.select())}},getFieldState:ee}}function WC(t={}){const e=ne.useRef(),r=ne.useRef(),[n,i]=ne.useState({isDirty:!1,isValidating:!1,isLoading:ni(t.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1,defaultValues:ni(t.defaultValues)?void 0:t.defaultValues});e.current||(e.current={...HC(t),formState:n});const s=e.current.control;return s._options=t,pm({subject:s._subjects.state,next:a=>{fE(a,s._proxyFormState,s._updateFormState,!0)&&i({...s._formState})}}),ne.useEffect(()=>s._disableForm(t.disabled),[s,t.disabled]),ne.useEffect(()=>{if(s._proxyFormState.isDirty){const a=s._getDirty();a!==n.isDirty&&s._subjects.state.next({isDirty:a})}},[s,n.isDirty]),ne.useEffect(()=>{t.values&&!Li(t.values,r.current)?(s._reset(t.values,s._options.resetOptions),r.current=t.values,i(a=>({...a}))):s._resetDefaultValues()},[t.values,s]),ne.useEffect(()=>{t.errors&&s._setErrors(t.errors)},[t.errors,s]),ne.useEffect(()=>{s._state.mount||(s._updateValid(),s._state.mount=!0),s._state.watch&&(s._state.watch=!1,s._subjects.state.next({...s._formState})),s._removeUnmounted()}),ne.useEffect(()=>{t.shouldUnregister&&s._subjects.values.next({values:s._getWatch()})},[t.shouldUnregister,s]),e.current.formState=dE(n,s),e.current}const z0=(t,e,r)=>{if(t&&"reportValidity"in t){const n=ie(r,e);t.setCustomValidity(n&&n.message||""),t.reportValidity()}},TE=(t,e)=>{for(const r in e.fields){const n=e.fields[r];n&&n.ref&&"reportValidity"in n.ref?z0(n.ref,r,t):n.refs&&n.refs.forEach(i=>z0(i,r,t))}},KC=(t,e)=>{e.shouldUseNativeValidation&&TE(t,e);const r={};for(const n in t){const i=ie(e.fields,n),s=Object.assign(t[n]||{},{ref:i&&i.ref});if(YC(e.names||Object.keys(t),n)){const a=Object.assign({},ie(r,n));Ze(a,"root",s),Ze(r,n,a)}else Ze(r,n,s)}return r},YC=(t,e)=>t.some(r=>r.startsWith(e+"."));var qC=function(t,e){for(var r={};t.length;){var n=t[0],i=n.code,s=n.message,a=n.path.join(".");if(!r[a])if("unionErrors"in n){var o=n.unionErrors[0].errors[0];r[a]={message:o.message,type:o.code}}else r[a]={message:s,type:i};if("unionErrors"in n&&n.unionErrors.forEach(function(c){return c.errors.forEach(function(d){return t.push(d)})}),e){var l=r[a].types,u=l&&l[n.code];r[a]=mE(a,e,r,i,u?[].concat(u,n.message):n.message)}t.shift()}return r},XC=function(t,e,r){return r===void 0&&(r={}),function(n,i,s){try{return Promise.resolve(function(a,o){try{var l=Promise.resolve(t[r.mode==="sync"?"parse":"parseAsync"](n,e)).then(function(u){return s.shouldUseNativeValidation&&TE({},s),{errors:{},values:r.raw?n:u}})}catch(u){return o(u)}return l&&l.then?l.then(void 0,o):l}(0,function(a){if(function(o){return Array.isArray(o==null?void 0:o.errors)}(a))return{values:{},errors:KC(qC(a.errors,!s.shouldUseNativeValidation&&s.criteriaMode==="all"),s)};throw a}))}catch(a){return Promise.reject(a)}}},We;(function(t){t.assertEqual=i=>i;function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{const s={};for(const a of i)s[a]=a;return s},t.getValidEnumValues=i=>{const s=t.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),a={};for(const o of s)a[o]=i[o];return t.objectValues(a)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const s=[];for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},t.find=(i,s)=>{for(const a of i)if(s(a))return a},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(We||(We={}));var Fh;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Fh||(Fh={}));const ue=We.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ai=t=>{switch(typeof t){case"undefined":return ue.undefined;case"string":return ue.string;case"number":return isNaN(t)?ue.nan:ue.number;case"boolean":return ue.boolean;case"function":return ue.function;case"bigint":return ue.bigint;case"symbol":return ue.symbol;case"object":return Array.isArray(t)?ue.array:t===null?ue.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ue.promise:typeof Map<"u"&&t instanceof Map?ue.map:typeof Set<"u"&&t instanceof Set?ue.set:typeof Date<"u"&&t instanceof Date?ue.date:ue.object;default:return ue.unknown}},J=We.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ZC=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class Mr extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let o=n,l=0;for(;lr.message){const r={},n=[];for(const i of this.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Mr.create=t=>new Mr(t);const ba=(t,e)=>{let r;switch(t.code){case J.invalid_type:t.received===ue.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case J.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,We.jsonStringifyReplacer)}`;break;case J.unrecognized_keys:r=`Unrecognized key(s) in object: ${We.joinValues(t.keys,", ")}`;break;case J.invalid_union:r="Invalid input";break;case J.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${We.joinValues(t.options)}`;break;case J.invalid_enum_value:r=`Invalid enum value. Expected ${We.joinValues(t.options)}, received '${t.received}'`;break;case J.invalid_arguments:r="Invalid function arguments";break;case J.invalid_return_type:r="Invalid function return type";break;case J.invalid_date:r="Invalid date";break;case J.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:We.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case J.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case J.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case J.custom:r="Invalid input";break;case J.invalid_intersection_types:r="Intersection results could not be merged";break;case J.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case J.not_finite:r="Number must be finite";break;default:r=e.defaultError,We.assertNever(t)}return{message:r}};let wE=ba;function QC(t){wE=t}function Tc(){return wE}const wc=t=>{const{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let o="";const l=n.filter(u=>!!u).slice().reverse();for(const u of l)o=u(a,{data:e,defaultError:o}).message;return{...i,path:s,message:o}},JC=[];function le(t,e){const r=Tc(),n=wc({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===ba?void 0:ba].filter(i=>!!i)});t.common.issues.push(n)}class tr{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const i of r){if(i.status==="aborted")return Ie;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const i of r){const s=await i.key,a=await i.value;n.push({key:s,value:a})}return tr.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const i of r){const{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return Ie;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(n[s.value]=a.value)}return{status:e.value,value:n}}}const Ie=Object.freeze({status:"aborted"}),ea=t=>({status:"dirty",value:t}),cr=t=>({status:"valid",value:t}),Uh=t=>t.status==="aborted",Bh=t=>t.status==="dirty",Qo=t=>t.status==="valid",Jo=t=>typeof Promise<"u"&&t instanceof Promise;function bc(t,e,r,n){if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function bE(t,e,r,n,i){if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,r),r}var Se;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(Se||(Se={}));var co,fo;class Fn{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const H0=(t,e)=>{if(Qo(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new Mr(t.common.issues);return this._error=r,this._error}}};function Ne(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,o)=>{var l,u;const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:(l=c??n)!==null&&l!==void 0?l:o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:(u=c??r)!==null&&u!==void 0?u:o.defaultError}},description:i}}class Ve{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return Ai(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ai(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new tr,ctx:{common:e.parent.common,data:e.data,parsedType:Ai(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(Jo(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){var n;const i={common:{issues:[],async:(n=r==null?void 0:r.async)!==null&&n!==void 0?n:!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ai(e)},s=this._parseSync({data:e,path:i.path,parent:i});return H0(i,s)}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ai(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(Jo(i)?i:Promise.resolve(i));return H0(n,s)}refine(e,r){const n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{const a=e(i),o=()=>s.addIssue({code:J.custom,...n(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new yn({schema:this,typeName:Ce.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return Mn.create(this,this._def)}nullable(){return Gi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return gn.create(this,this._def)}promise(){return Aa.create(this,this._def)}or(e){return nl.create([this,e],this._def)}and(e){return il.create(this,e,this._def)}transform(e){return new yn({...Ne(this._def),schema:this,typeName:Ce.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new ul({...Ne(this._def),innerType:this,defaultValue:r,typeName:Ce.ZodDefault})}brand(){return new vm({typeName:Ce.ZodBranded,type:this,...Ne(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new cl({...Ne(this._def),innerType:this,catchValue:r,typeName:Ce.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Tl.create(this,e)}readonly(){return dl.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const eR=/^c[^\s-]{8,}$/i,tR=/^[0-9a-z]+$/,rR=/^[0-9A-HJKMNP-TV-Z]{26}$/,nR=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,iR=/^[a-z0-9_-]{21}$/i,sR=/^[-+]?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)?)??$/,aR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,oR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let lf;const lR=/^(?:(?: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])$/,uR=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,cR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,LE="((\\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])))",dR=new RegExp(`^${LE}$`);function AE(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function fR(t){return new RegExp(`^${AE(t)}$`)}function _E(t){let e=`${LE}T${AE(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function hR(t,e){return!!((e==="v4"||!e)&&lR.test(t)||(e==="v6"||!e)&&uR.test(t))}class hn extends Ve{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ue.string){const s=this._getOrReturnCtx(e);return le(s,{code:J.invalid_type,expected:ue.string,received:s.parsedType}),Ie}const n=new tr;let i;for(const s of this._def.checks)if(s.kind==="min")e.data.lengths.value&&(i=this._getOrReturnCtx(e,i),le(i,{code:J.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const a=e.data.length>s.value,o=e.data.lengthe.test(i),{validation:r,code:J.invalid_string,...Se.errToObj(n)})}_addCheck(e){return new hn({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Se.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Se.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Se.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Se.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Se.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Se.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Se.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Se.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Se.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Se.errToObj(e)})}datetime(e){var r,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(r=e==null?void 0:e.offset)!==null&&r!==void 0?r:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...Se.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...Se.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...Se.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...Se.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...Se.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...Se.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...Se.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...Se.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...Se.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...Se.errToObj(r)})}nonempty(e){return this.min(1,Se.errToObj(e))}trim(){return new hn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new hn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new hn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value{var e;return new hn({checks:[],typeName:Ce.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...Ne(t)})};function pR(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=parseInt(t.toFixed(i).replace(".","")),a=parseInt(e.toFixed(i).replace(".",""));return s%a/Math.pow(10,i)}class $i extends Ve{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ue.number){const s=this._getOrReturnCtx(e);return le(s,{code:J.invalid_type,expected:ue.number,received:s.parsedType}),Ie}let n;const i=new tr;for(const s of this._def.checks)s.kind==="int"?We.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),le(n,{code:J.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),le(n,{code:J.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?pR(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),le(n,{code:J.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),le(n,{code:J.not_finite,message:s.message}),i.dirty()):We.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,Se.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Se.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Se.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Se.toString(r))}setLimit(e,r,n,i){return new $i({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Se.toString(i)}]})}_addCheck(e){return new $i({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Se.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Se.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Se.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:Se.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Se.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Se.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.valuee.kind==="int"||e.kind==="multipleOf"&&We.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.valuenew $i({checks:[],typeName:Ce.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Ne(t)});class ji extends Ve{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==ue.bigint){const s=this._getOrReturnCtx(e);return le(s,{code:J.invalid_type,expected:ue.bigint,received:s.parsedType}),Ie}let n;const i=new tr;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),le(n,{code:J.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),le(n,{code:J.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):We.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,Se.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Se.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Se.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Se.toString(r))}setLimit(e,r,n,i){return new ji({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Se.toString(i)}]})}_addCheck(e){return new ji({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Se.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Se.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value{var e;return new ji({checks:[],typeName:Ce.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...Ne(t)})};class el extends Ve{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ue.boolean){const n=this._getOrReturnCtx(e);return le(n,{code:J.invalid_type,expected:ue.boolean,received:n.parsedType}),Ie}return cr(e.data)}}el.create=t=>new el({typeName:Ce.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Ne(t)});class Es extends Ve{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ue.date){const s=this._getOrReturnCtx(e);return le(s,{code:J.invalid_type,expected:ue.date,received:s.parsedType}),Ie}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return le(s,{code:J.invalid_date}),Ie}const n=new tr;let i;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()s.value&&(i=this._getOrReturnCtx(e,i),le(i,{code:J.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):We.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Es({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:Se.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:Se.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew Es({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:Ce.ZodDate,...Ne(t)});class Lc extends Ve{_parse(e){if(this._getType(e)!==ue.symbol){const n=this._getOrReturnCtx(e);return le(n,{code:J.invalid_type,expected:ue.symbol,received:n.parsedType}),Ie}return cr(e.data)}}Lc.create=t=>new Lc({typeName:Ce.ZodSymbol,...Ne(t)});class tl extends Ve{_parse(e){if(this._getType(e)!==ue.undefined){const n=this._getOrReturnCtx(e);return le(n,{code:J.invalid_type,expected:ue.undefined,received:n.parsedType}),Ie}return cr(e.data)}}tl.create=t=>new tl({typeName:Ce.ZodUndefined,...Ne(t)});class rl extends Ve{_parse(e){if(this._getType(e)!==ue.null){const n=this._getOrReturnCtx(e);return le(n,{code:J.invalid_type,expected:ue.null,received:n.parsedType}),Ie}return cr(e.data)}}rl.create=t=>new rl({typeName:Ce.ZodNull,...Ne(t)});class La extends Ve{constructor(){super(...arguments),this._any=!0}_parse(e){return cr(e.data)}}La.create=t=>new La({typeName:Ce.ZodAny,...Ne(t)});class ds extends Ve{constructor(){super(...arguments),this._unknown=!0}_parse(e){return cr(e.data)}}ds.create=t=>new ds({typeName:Ce.ZodUnknown,...Ne(t)});class di extends Ve{_parse(e){const r=this._getOrReturnCtx(e);return le(r,{code:J.invalid_type,expected:ue.never,received:r.parsedType}),Ie}}di.create=t=>new di({typeName:Ce.ZodNever,...Ne(t)});class Ac extends Ve{_parse(e){if(this._getType(e)!==ue.undefined){const n=this._getOrReturnCtx(e);return le(n,{code:J.invalid_type,expected:ue.void,received:n.parsedType}),Ie}return cr(e.data)}}Ac.create=t=>new Ac({typeName:Ce.ZodVoid,...Ne(t)});class gn extends Ve{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==ue.array)return le(r,{code:J.invalid_type,expected:ue.array,received:r.parsedType}),Ie;if(i.exactLength!==null){const a=r.data.length>i.exactLength.value,o=r.data.lengthi.maxLength.value&&(le(r,{code:J.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,o)=>i.type._parseAsync(new Fn(r,a,r.path,o)))).then(a=>tr.mergeArray(n,a));const s=[...r.data].map((a,o)=>i.type._parseSync(new Fn(r,a,r.path,o)));return tr.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new gn({...this._def,minLength:{value:e,message:Se.toString(r)}})}max(e,r){return new gn({...this._def,maxLength:{value:e,message:Se.toString(r)}})}length(e,r){return new gn({...this._def,exactLength:{value:e,message:Se.toString(r)}})}nonempty(e){return this.min(1,e)}}gn.create=(t,e)=>new gn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Ce.ZodArray,...Ne(e)});function Bs(t){if(t instanceof vt){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=Mn.create(Bs(n))}return new vt({...t._def,shape:()=>e})}else return t instanceof gn?new gn({...t._def,type:Bs(t.element)}):t instanceof Mn?Mn.create(Bs(t.unwrap())):t instanceof Gi?Gi.create(Bs(t.unwrap())):t instanceof Un?Un.create(t.items.map(e=>Bs(e))):t}class vt extends Ve{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=We.objectKeys(e);return this._cached={shape:e,keys:r}}_parse(e){if(this._getType(e)!==ue.object){const u=this._getOrReturnCtx(e);return le(u,{code:J.invalid_type,expected:ue.object,received:u.parsedType}),Ie}const{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof di&&this._def.unknownKeys==="strip"))for(const u in i.data)a.includes(u)||o.push(u);const l=[];for(const u of a){const c=s[u],d=i.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Fn(i,d,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof di){const u=this._def.unknownKeys;if(u==="passthrough")for(const c of o)l.push({key:{status:"valid",value:c},value:{status:"valid",value:i.data[c]}});else if(u==="strict")o.length>0&&(le(i,{code:J.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const c of o){const d=i.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Fn(i,d,i.path,c)),alwaysSet:c in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const u=[];for(const c of l){const d=await c.key,f=await c.value;u.push({key:d,value:f,alwaysSet:c.alwaysSet})}return u}).then(u=>tr.mergeObjectSync(n,u)):tr.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return Se.errToObj,new vt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{var i,s,a,o;const l=(a=(s=(i=this._def).errorMap)===null||s===void 0?void 0:s.call(i,r,n).message)!==null&&a!==void 0?a:n.defaultError;return r.code==="unrecognized_keys"?{message:(o=Se.errToObj(e).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new vt({...this._def,unknownKeys:"strip"})}passthrough(){return new vt({...this._def,unknownKeys:"passthrough"})}extend(e){return new vt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new vt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ce.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new vt({...this._def,catchall:e})}pick(e){const r={};return We.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new vt({...this._def,shape:()=>r})}omit(e){const r={};return We.objectKeys(this.shape).forEach(n=>{e[n]||(r[n]=this.shape[n])}),new vt({...this._def,shape:()=>r})}deepPartial(){return Bs(this)}partial(e){const r={};return We.objectKeys(this.shape).forEach(n=>{const i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}),new vt({...this._def,shape:()=>r})}required(e){const r={};return We.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Mn;)s=s._def.innerType;r[n]=s}}),new vt({...this._def,shape:()=>r})}keyof(){return CE(We.objectKeys(this.shape))}}vt.create=(t,e)=>new vt({shape:()=>t,unknownKeys:"strip",catchall:di.create(),typeName:Ce.ZodObject,...Ne(e)});vt.strictCreate=(t,e)=>new vt({shape:()=>t,unknownKeys:"strict",catchall:di.create(),typeName:Ce.ZodObject,...Ne(e)});vt.lazycreate=(t,e)=>new vt({shape:t,unknownKeys:"strip",catchall:di.create(),typeName:Ce.ZodObject,...Ne(e)});class nl extends Ve{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(const o of s)if(o.result.status==="valid")return o.result;for(const o of s)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const a=s.map(o=>new Mr(o.ctx.common.issues));return le(r,{code:J.invalid_union,unionErrors:a}),Ie}if(r.common.async)return Promise.all(n.map(async s=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(i);{let s;const a=[];for(const l of n){const u={...r,common:{...r.common,issues:[]},parent:null},c=l._parseSync({data:r.data,path:r.path,parent:u});if(c.status==="valid")return c;c.status==="dirty"&&!s&&(s={result:c,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const o=a.map(l=>new Mr(l));return le(r,{code:J.invalid_union,unionErrors:o}),Ie}}get options(){return this._def.options}}nl.create=(t,e)=>new nl({options:t,typeName:Ce.ZodUnion,...Ne(e)});const Yn=t=>t instanceof al?Yn(t.schema):t instanceof yn?Yn(t.innerType()):t instanceof ol?[t.value]:t instanceof Vi?t.options:t instanceof ll?We.objectValues(t.enum):t instanceof ul?Yn(t._def.innerType):t instanceof tl?[void 0]:t instanceof rl?[null]:t instanceof Mn?[void 0,...Yn(t.unwrap())]:t instanceof Gi?[null,...Yn(t.unwrap())]:t instanceof vm||t instanceof dl?Yn(t.unwrap()):t instanceof cl?Yn(t._def.innerType):[];class xd extends Ve{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.object)return le(r,{code:J.invalid_type,expected:ue.object,received:r.parsedType}),Ie;const n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(le(r,{code:J.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Ie)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const i=new Map;for(const s of r){const a=Yn(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(i.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);i.set(o,s)}}return new xd({typeName:Ce.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Ne(n)})}}function $h(t,e){const r=Ai(t),n=Ai(e);if(t===e)return{valid:!0,data:t};if(r===ue.object&&n===ue.object){const i=We.objectKeys(e),s=We.objectKeys(t).filter(o=>i.indexOf(o)!==-1),a={...t,...e};for(const o of s){const l=$h(t[o],e[o]);if(!l.valid)return{valid:!1};a[o]=l.data}return{valid:!0,data:a}}else if(r===ue.array&&n===ue.array){if(t.length!==e.length)return{valid:!1};const i=[];for(let s=0;s{if(Uh(s)||Uh(a))return Ie;const o=$h(s.value,a.value);return o.valid?((Bh(s)||Bh(a))&&r.dirty(),{status:r.value,value:o.data}):(le(n,{code:J.invalid_intersection_types}),Ie)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>i(s,a)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}il.create=(t,e,r)=>new il({left:t,right:e,typeName:Ce.ZodIntersection,...Ne(r)});class Un extends Ve{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.array)return le(n,{code:J.invalid_type,expected:ue.array,received:n.parsedType}),Ie;if(n.data.lengththis._def.items.length&&(le(n,{code:J.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((a,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new Fn(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>tr.mergeArray(r,a)):tr.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new Un({...this._def,rest:e})}}Un.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Un({items:t,typeName:Ce.ZodTuple,rest:null,...Ne(e)})};class sl extends Ve{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.object)return le(n,{code:J.invalid_type,expected:ue.object,received:n.parsedType}),Ie;const i=[],s=this._def.keyType,a=this._def.valueType;for(const o in n.data)i.push({key:s._parse(new Fn(n,o,n.path,o)),value:a._parse(new Fn(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?tr.mergeObjectAsync(r,i):tr.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Ve?new sl({keyType:e,valueType:r,typeName:Ce.ZodRecord,...Ne(n)}):new sl({keyType:hn.create(),valueType:e,typeName:Ce.ZodRecord,...Ne(r)})}}class _c extends Ve{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.map)return le(n,{code:J.invalid_type,expected:ue.map,received:n.parsedType}),Ie;const i=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([o,l],u)=>({key:i._parse(new Fn(n,o,n.path,[u,"key"])),value:s._parse(new Fn(n,l,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of a){const u=await l.key,c=await l.value;if(u.status==="aborted"||c.status==="aborted")return Ie;(u.status==="dirty"||c.status==="dirty")&&r.dirty(),o.set(u.value,c.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const l of a){const u=l.key,c=l.value;if(u.status==="aborted"||c.status==="aborted")return Ie;(u.status==="dirty"||c.status==="dirty")&&r.dirty(),o.set(u.value,c.value)}return{status:r.value,value:o}}}}_c.create=(t,e,r)=>new _c({valueType:e,keyType:t,typeName:Ce.ZodMap,...Ne(r)});class Ts extends Ve{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.set)return le(n,{code:J.invalid_type,expected:ue.set,received:n.parsedType}),Ie;const i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(le(n,{code:J.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());const s=this._def.valueType;function a(l){const u=new Set;for(const c of l){if(c.status==="aborted")return Ie;c.status==="dirty"&&r.dirty(),u.add(c.value)}return{status:r.value,value:u}}const o=[...n.data.values()].map((l,u)=>s._parse(new Fn(n,l,n.path,u)));return n.common.async?Promise.all(o).then(l=>a(l)):a(o)}min(e,r){return new Ts({...this._def,minSize:{value:e,message:Se.toString(r)}})}max(e,r){return new Ts({...this._def,maxSize:{value:e,message:Se.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}Ts.create=(t,e)=>new Ts({valueType:t,minSize:null,maxSize:null,typeName:Ce.ZodSet,...Ne(e)});class la extends Ve{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.function)return le(r,{code:J.invalid_type,expected:ue.function,received:r.parsedType}),Ie;function n(o,l){return wc({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Tc(),ba].filter(u=>!!u),issueData:{code:J.invalid_arguments,argumentsError:l}})}function i(o,l){return wc({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Tc(),ba].filter(u=>!!u),issueData:{code:J.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Aa){const o=this;return cr(async function(...l){const u=new Mr([]),c=await o._def.args.parseAsync(l,s).catch(m=>{throw u.addIssue(n(l,m)),u}),d=await Reflect.apply(a,this,c);return await o._def.returns._def.type.parseAsync(d,s).catch(m=>{throw u.addIssue(i(d,m)),u})})}else{const o=this;return cr(function(...l){const u=o._def.args.safeParse(l,s);if(!u.success)throw new Mr([n(l,u.error)]);const c=Reflect.apply(a,this,u.data),d=o._def.returns.safeParse(c,s);if(!d.success)throw new Mr([i(c,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new la({...this._def,args:Un.create(e).rest(ds.create())})}returns(e){return new la({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new la({args:e||Un.create([]).rest(ds.create()),returns:r||ds.create(),typeName:Ce.ZodFunction,...Ne(n)})}}class al extends Ve{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}al.create=(t,e)=>new al({getter:t,typeName:Ce.ZodLazy,...Ne(e)});class ol extends Ve{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return le(r,{received:r.data,code:J.invalid_literal,expected:this._def.value}),Ie}return{status:"valid",value:e.data}}get value(){return this._def.value}}ol.create=(t,e)=>new ol({value:t,typeName:Ce.ZodLiteral,...Ne(e)});function CE(t,e){return new Vi({values:t,typeName:Ce.ZodEnum,...Ne(e)})}class Vi extends Ve{constructor(){super(...arguments),co.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return le(r,{expected:We.joinValues(n),received:r.parsedType,code:J.invalid_type}),Ie}if(bc(this,co)||bE(this,co,new Set(this._def.values)),!bc(this,co).has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return le(r,{received:r.data,code:J.invalid_enum_value,options:n}),Ie}return cr(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Vi.create(e,{...this._def,...r})}exclude(e,r=this._def){return Vi.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}co=new WeakMap;Vi.create=CE;class ll extends Ve{constructor(){super(...arguments),fo.set(this,void 0)}_parse(e){const r=We.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ue.string&&n.parsedType!==ue.number){const i=We.objectValues(r);return le(n,{expected:We.joinValues(i),received:n.parsedType,code:J.invalid_type}),Ie}if(bc(this,fo)||bE(this,fo,new Set(We.getValidEnumValues(this._def.values))),!bc(this,fo).has(e.data)){const i=We.objectValues(r);return le(n,{received:n.data,code:J.invalid_enum_value,options:i}),Ie}return cr(e.data)}get enum(){return this._def.values}}fo=new WeakMap;ll.create=(t,e)=>new ll({values:t,typeName:Ce.ZodNativeEnum,...Ne(e)});class Aa extends Ve{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.promise&&r.common.async===!1)return le(r,{code:J.invalid_type,expected:ue.promise,received:r.parsedType}),Ie;const n=r.parsedType===ue.promise?r.data:Promise.resolve(r.data);return cr(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Aa.create=(t,e)=>new Aa({type:t,typeName:Ce.ZodPromise,...Ne(e)});class yn extends Ve{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ce.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:a=>{le(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){const a=i.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async o=>{if(r.value==="aborted")return Ie;const l=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return l.status==="aborted"?Ie:l.status==="dirty"||r.value==="dirty"?ea(l.value):l});{if(r.value==="aborted")return Ie;const o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?Ie:o.status==="dirty"||r.value==="dirty"?ea(o.value):o}}if(i.type==="refinement"){const a=o=>{const l=i.refinement(o,s);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Ie:(o.status==="dirty"&&r.dirty(),a(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?Ie:(o.status==="dirty"&&r.dirty(),a(o.value).then(()=>({status:r.value,value:o.value}))))}if(i.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Qo(a))return a;const o=i.transform(a.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Qo(a)?Promise.resolve(i.transform(a.value,s)).then(o=>({status:r.value,value:o})):a);We.assertNever(i)}}yn.create=(t,e,r)=>new yn({schema:t,typeName:Ce.ZodEffects,effect:e,...Ne(r)});yn.createWithPreprocess=(t,e,r)=>new yn({schema:e,effect:{type:"preprocess",transform:t},typeName:Ce.ZodEffects,...Ne(r)});class Mn extends Ve{_parse(e){return this._getType(e)===ue.undefined?cr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Mn.create=(t,e)=>new Mn({innerType:t,typeName:Ce.ZodOptional,...Ne(e)});class Gi extends Ve{_parse(e){return this._getType(e)===ue.null?cr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Gi.create=(t,e)=>new Gi({innerType:t,typeName:Ce.ZodNullable,...Ne(e)});class ul extends Ve{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===ue.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}ul.create=(t,e)=>new ul({innerType:t,typeName:Ce.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ne(e)});class cl extends Ve{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Jo(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Mr(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Mr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}cl.create=(t,e)=>new cl({innerType:t,typeName:Ce.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ne(e)});class Cc extends Ve{_parse(e){if(this._getType(e)!==ue.nan){const n=this._getOrReturnCtx(e);return le(n,{code:J.invalid_type,expected:ue.nan,received:n.parsedType}),Ie}return{status:"valid",value:e.data}}}Cc.create=t=>new Cc({typeName:Ce.ZodNaN,...Ne(t)});const mR=Symbol("zod_brand");class vm extends Ve{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Tl extends Ve{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Ie:s.status==="dirty"?(r.dirty(),ea(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Ie:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new Tl({in:e,out:r,typeName:Ce.ZodPipeline})}}class dl extends Ve{_parse(e){const r=this._def.innerType._parse(e),n=i=>(Qo(i)&&(i.value=Object.freeze(i.value)),i);return Jo(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}}dl.create=(t,e)=>new dl({innerType:t,typeName:Ce.ZodReadonly,...Ne(e)});function RE(t,e={},r){return t?La.create().superRefine((n,i)=>{var s,a;if(!t(n)){const o=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,l=(a=(s=o.fatal)!==null&&s!==void 0?s:r)!==null&&a!==void 0?a:!0,u=typeof o=="string"?{message:o}:o;i.addIssue({code:"custom",...u,fatal:l})}}):La.create()}const gR={object:vt.lazycreate};var Ce;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Ce||(Ce={}));const vR=(t,e={message:`Input not instance of ${t.name}`})=>RE(r=>r instanceof t,e),IE=hn.create,kE=$i.create,yR=Cc.create,xR=ji.create,DE=el.create,SR=Es.create,ER=Lc.create,TR=tl.create,wR=rl.create,bR=La.create,LR=ds.create,AR=di.create,_R=Ac.create,CR=gn.create,RR=vt.create,IR=vt.strictCreate,kR=nl.create,DR=xd.create,PR=il.create,OR=Un.create,MR=sl.create,NR=_c.create,FR=Ts.create,UR=la.create,BR=al.create,$R=ol.create,jR=Vi.create,VR=ll.create,GR=Aa.create,W0=yn.create,zR=Mn.create,HR=Gi.create,WR=yn.createWithPreprocess,KR=Tl.create,YR=()=>IE().optional(),qR=()=>kE().optional(),XR=()=>DE().optional(),ZR={string:t=>hn.create({...t,coerce:!0}),number:t=>$i.create({...t,coerce:!0}),boolean:t=>el.create({...t,coerce:!0}),bigint:t=>ji.create({...t,coerce:!0}),date:t=>Es.create({...t,coerce:!0})},QR=Ie;var to=Object.freeze({__proto__:null,defaultErrorMap:ba,setErrorMap:QC,getErrorMap:Tc,makeIssue:wc,EMPTY_PATH:JC,addIssueToContext:le,ParseStatus:tr,INVALID:Ie,DIRTY:ea,OK:cr,isAborted:Uh,isDirty:Bh,isValid:Qo,isAsync:Jo,get util(){return We},get objectUtil(){return Fh},ZodParsedType:ue,getParsedType:Ai,ZodType:Ve,datetimeRegex:_E,ZodString:hn,ZodNumber:$i,ZodBigInt:ji,ZodBoolean:el,ZodDate:Es,ZodSymbol:Lc,ZodUndefined:tl,ZodNull:rl,ZodAny:La,ZodUnknown:ds,ZodNever:di,ZodVoid:Ac,ZodArray:gn,ZodObject:vt,ZodUnion:nl,ZodDiscriminatedUnion:xd,ZodIntersection:il,ZodTuple:Un,ZodRecord:sl,ZodMap:_c,ZodSet:Ts,ZodFunction:la,ZodLazy:al,ZodLiteral:ol,ZodEnum:Vi,ZodNativeEnum:ll,ZodPromise:Aa,ZodEffects:yn,ZodTransformer:yn,ZodOptional:Mn,ZodNullable:Gi,ZodDefault:ul,ZodCatch:cl,ZodNaN:Cc,BRAND:mR,ZodBranded:vm,ZodPipeline:Tl,ZodReadonly:dl,custom:RE,Schema:Ve,ZodSchema:Ve,late:gR,get ZodFirstPartyTypeKind(){return Ce},coerce:ZR,any:bR,array:CR,bigint:xR,boolean:DE,date:SR,discriminatedUnion:DR,effect:W0,enum:jR,function:UR,instanceof:vR,intersection:PR,lazy:BR,literal:$R,map:NR,nan:yR,nativeEnum:VR,never:AR,null:wR,nullable:HR,number:kE,object:RR,oboolean:XR,onumber:qR,optional:zR,ostring:YR,pipeline:KR,preprocess:WR,promise:GR,record:MR,set:FR,strictObject:IR,string:IE,symbol:ER,transformer:W0,tuple:OR,undefined:TR,union:kR,unknown:LR,void:_R,NEVER:QR,ZodIssueCode:J,quotelessJson:ZC,ZodError:Mr});function JR(t,e){typeof t=="function"?t(e):t!=null&&(t.current=e)}function eI(...t){return e=>t.forEach(r=>JR(r,e))}var Sd=L.forwardRef((t,e)=>{const{children:r,...n}=t,i=L.Children.toArray(r),s=i.find(rI);if(s){const a=s.props.children,o=i.map(l=>l===s?L.Children.count(a)>1?L.Children.only(null):L.isValidElement(a)?a.props.children:null:l);return E.jsx(jh,{...n,ref:e,children:L.isValidElement(a)?L.cloneElement(a,void 0,o):null})}return E.jsx(jh,{...n,ref:e,children:r})});Sd.displayName="Slot";var jh=L.forwardRef((t,e)=>{const{children:r,...n}=t;if(L.isValidElement(r)){const i=iI(r);return L.cloneElement(r,{...nI(n,r.props),ref:e?eI(e,i):i})}return L.Children.count(r)>1?L.Children.only(null):null});jh.displayName="SlotClone";var tI=({children:t})=>E.jsx(E.Fragment,{children:t});function rI(t){return L.isValidElement(t)&&t.type===tI}function nI(t,e){const r={...e};for(const n in e){const i=t[n],s=e[n];/^on[A-Z]/.test(n)?i&&s?r[n]=(...o)=>{s(...o),i(...o)}:i&&(r[n]=i):n==="style"?r[n]={...i,...s}:n==="className"&&(r[n]=[i,s].filter(Boolean).join(" "))}return{...t,...r}}function iI(t){var n,i;let e=(n=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:n.get,r=e&&"isReactWarning"in e&&e.isReactWarning;return r?t.ref:(e=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=e&&"isReactWarning"in e&&e.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}function PE(t){var e,r,n="";if(typeof t=="string"||typeof t=="number")n+=t;else if(typeof t=="object")if(Array.isArray(t))for(e=0;etypeof t=="boolean"?"".concat(t):t===0?"0":t,Y0=sI,OE=(t,e)=>r=>{var n;if((e==null?void 0:e.variants)==null)return Y0(t,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:i,defaultVariants:s}=e,a=Object.keys(i).map(u=>{const c=r==null?void 0:r[u],d=s==null?void 0:s[u];if(c===null)return null;const f=K0(c)||K0(d);return i[u][f]}),o=r&&Object.entries(r).reduce((u,c)=>{let[d,f]=c;return f===void 0||(u[d]=f),u},{}),l=e==null||(n=e.compoundVariants)===null||n===void 0?void 0:n.reduce((u,c)=>{let{class:d,className:f,...m}=c;return Object.entries(m).every(h=>{let[p,v]=h;return Array.isArray(v)?v.includes({...s,...o}[p]):{...s,...o}[p]===v})?[...u,d,f]:u},[]);return Y0(t,a,l,r==null?void 0:r.class,r==null?void 0:r.className)},ym="-",aI=t=>{const e=lI(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=t;return{getClassGroupId:a=>{const o=a.split(ym);return o[0]===""&&o.length!==1&&o.shift(),ME(o,e)||oI(a)},getConflictingClassGroupIds:(a,o)=>{const l=r[a]||[];return o&&n[a]?[...l,...n[a]]:l}}},ME=(t,e)=>{var a;if(t.length===0)return e.classGroupId;const r=t[0],n=e.nextPart.get(r),i=n?ME(t.slice(1),n):void 0;if(i)return i;if(e.validators.length===0)return;const s=t.join(ym);return(a=e.validators.find(({validator:o})=>o(s)))==null?void 0:a.classGroupId},q0=/^\[(.+)\]$/,oI=t=>{if(q0.test(t)){const e=q0.exec(t)[1],r=e==null?void 0:e.substring(0,e.indexOf(":"));if(r)return"arbitrary.."+r}},lI=t=>{const{theme:e,prefix:r}=t,n={nextPart:new Map,validators:[]};return cI(Object.entries(t.classGroups),r).forEach(([s,a])=>{Vh(a,n,s,e)}),n},Vh=(t,e,r,n)=>{t.forEach(i=>{if(typeof i=="string"){const s=i===""?e:X0(e,i);s.classGroupId=r;return}if(typeof i=="function"){if(uI(i)){Vh(i(n),e,r,n);return}e.validators.push({validator:i,classGroupId:r});return}Object.entries(i).forEach(([s,a])=>{Vh(a,X0(e,s),r,n)})})},X0=(t,e)=>{let r=t;return e.split(ym).forEach(n=>{r.nextPart.has(n)||r.nextPart.set(n,{nextPart:new Map,validators:[]}),r=r.nextPart.get(n)}),r},uI=t=>t.isThemeGetter,cI=(t,e)=>e?t.map(([r,n])=>{const i=n.map(s=>typeof s=="string"?e+s:typeof s=="object"?Object.fromEntries(Object.entries(s).map(([a,o])=>[e+a,o])):s);return[r,i]}):t,dI=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,r=new Map,n=new Map;const i=(s,a)=>{r.set(s,a),e++,e>t&&(e=0,n=r,r=new Map)};return{get(s){let a=r.get(s);if(a!==void 0)return a;if((a=n.get(s))!==void 0)return i(s,a),a},set(s,a){r.has(s)?r.set(s,a):i(s,a)}}},NE="!",fI=t=>{const{separator:e,experimentalParseClassName:r}=t,n=e.length===1,i=e[0],s=e.length,a=o=>{const l=[];let u=0,c=0,d;for(let v=0;vc?d-c:void 0;return{modifiers:l,hasImportantModifier:m,baseClassName:h,maybePostfixModifierPosition:p}};return r?o=>r({className:o,parseClassName:a}):a},hI=t=>{if(t.length<=1)return t;const e=[];let r=[];return t.forEach(n=>{n[0]==="["?(e.push(...r.sort(),n),r=[]):r.push(n)}),e.push(...r.sort()),e},pI=t=>({cache:dI(t.cacheSize),parseClassName:fI(t),...aI(t)}),mI=/\s+/,gI=(t,e)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:i}=e,s=[],a=t.trim().split(mI);let o="";for(let l=a.length-1;l>=0;l-=1){const u=a[l],{modifiers:c,hasImportantModifier:d,baseClassName:f,maybePostfixModifierPosition:m}=r(u);let h=!!m,p=n(h?f.substring(0,m):f);if(!p){if(!h){o=u+(o.length>0?" "+o:o);continue}if(p=n(f),!p){o=u+(o.length>0?" "+o:o);continue}h=!1}const v=hI(c).join(":"),g=d?v+NE:v,y=g+p;if(s.includes(y))continue;s.push(y);const x=i(p,h);for(let S=0;S0?" "+o:o)}return o};function vI(){let t=0,e,r,n="";for(;t{if(typeof t=="string")return t;let e,r="";for(let n=0;nd(c),t());return r=pI(u),n=r.cache.get,i=r.cache.set,s=o,o(l)}function o(l){const u=n(l);if(u)return u;const c=gI(l,r);return i(l,c),c}return function(){return s(vI.apply(null,arguments))}}const ct=t=>{const e=r=>r[t]||[];return e.isThemeGetter=!0,e},UE=/^\[(?:([a-z-]+):)?(.+)\]$/i,xI=/^\d+\/\d+$/,SI=new Set(["px","full","screen"]),EI=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,TI=/\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$/,wI=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,bI=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,LI=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,zn=t=>ua(t)||SI.has(t)||xI.test(t),gi=t=>Ba(t,"length",PI),ua=t=>!!t&&!Number.isNaN(Number(t)),uf=t=>Ba(t,"number",ua),ro=t=>!!t&&Number.isInteger(Number(t)),AI=t=>t.endsWith("%")&&ua(t.slice(0,-1)),Be=t=>UE.test(t),vi=t=>EI.test(t),_I=new Set(["length","size","percentage"]),CI=t=>Ba(t,_I,BE),RI=t=>Ba(t,"position",BE),II=new Set(["image","url"]),kI=t=>Ba(t,II,MI),DI=t=>Ba(t,"",OI),no=()=>!0,Ba=(t,e,r)=>{const n=UE.exec(t);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):r(n[2]):!1},PI=t=>TI.test(t)&&!wI.test(t),BE=()=>!1,OI=t=>bI.test(t),MI=t=>LI.test(t),NI=()=>{const t=ct("colors"),e=ct("spacing"),r=ct("blur"),n=ct("brightness"),i=ct("borderColor"),s=ct("borderRadius"),a=ct("borderSpacing"),o=ct("borderWidth"),l=ct("contrast"),u=ct("grayscale"),c=ct("hueRotate"),d=ct("invert"),f=ct("gap"),m=ct("gradientColorStops"),h=ct("gradientColorStopPositions"),p=ct("inset"),v=ct("margin"),g=ct("opacity"),y=ct("padding"),x=ct("saturate"),S=ct("scale"),T=ct("sepia"),C=ct("skew"),_=ct("space"),b=ct("translate"),I=()=>["auto","contain","none"],A=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto",Be,e],O=()=>[Be,e],P=()=>["",zn,gi],G=()=>["auto",ua,Be],K=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],H=()=>["solid","dashed","dotted","double","none"],se=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],W=()=>["start","end","center","between","around","evenly","stretch"],F=()=>["","0",Be],j=()=>["auto","avoid","all","avoid-page","page","left","right","column"],te=()=>[ua,Be];return{cacheSize:500,separator:":",theme:{colors:[no],spacing:[zn,gi],blur:["none","",vi,Be],brightness:te(),borderColor:[t],borderRadius:["none","","full",vi,Be],borderSpacing:O(),borderWidth:P(),contrast:te(),grayscale:F(),hueRotate:te(),invert:F(),gap:O(),gradientColorStops:[t],gradientColorStopPositions:[AI,gi],inset:k(),margin:k(),opacity:te(),padding:O(),saturate:te(),scale:te(),sepia:F(),skew:te(),space:O(),translate:O()},classGroups:{aspect:[{aspect:["auto","square","video",Be]}],container:["container"],columns:[{columns:[vi]}],"break-after":[{"break-after":j()}],"break-before":[{"break-before":j()}],"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"],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:[...K(),Be]}],overflow:[{overflow:A()}],"overflow-x":[{"overflow-x":A()}],"overflow-y":[{"overflow-y":A()}],overscroll:[{overscroll:I()}],"overscroll-x":[{"overscroll-x":I()}],"overscroll-y":[{"overscroll-y":I()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[p]}],"inset-x":[{"inset-x":[p]}],"inset-y":[{"inset-y":[p]}],start:[{start:[p]}],end:[{end:[p]}],top:[{top:[p]}],right:[{right:[p]}],bottom:[{bottom:[p]}],left:[{left:[p]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",ro,Be]}],basis:[{basis:k()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Be]}],grow:[{grow:F()}],shrink:[{shrink:F()}],order:[{order:["first","last","none",ro,Be]}],"grid-cols":[{"grid-cols":[no]}],"col-start-end":[{col:["auto",{span:["full",ro,Be]},Be]}],"col-start":[{"col-start":G()}],"col-end":[{"col-end":G()}],"grid-rows":[{"grid-rows":[no]}],"row-start-end":[{row:["auto",{span:[ro,Be]},Be]}],"row-start":[{"row-start":G()}],"row-end":[{"row-end":G()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Be]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Be]}],gap:[{gap:[f]}],"gap-x":[{"gap-x":[f]}],"gap-y":[{"gap-y":[f]}],"justify-content":[{justify:["normal",...W()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...W(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...W(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[v]}],mx:[{mx:[v]}],my:[{my:[v]}],ms:[{ms:[v]}],me:[{me:[v]}],mt:[{mt:[v]}],mr:[{mr:[v]}],mb:[{mb:[v]}],ml:[{ml:[v]}],"space-x":[{"space-x":[_]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[_]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Be,e]}],"min-w":[{"min-w":[Be,e,"min","max","fit"]}],"max-w":[{"max-w":[Be,e,"none","full","min","max","fit","prose",{screen:[vi]},vi]}],h:[{h:[Be,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Be,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Be,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Be,e,"auto","min","max","fit"]}],"font-size":[{text:["base",vi,gi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",uf]}],"font-family":[{font:[no]}],"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-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Be]}],"line-clamp":[{"line-clamp":["none",ua,uf]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",zn,Be]}],"list-image":[{"list-image":["none",Be]}],"list-style-type":[{list:["none","disc","decimal",Be]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[g]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[g]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...H(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",zn,gi]}],"underline-offset":[{"underline-offset":["auto",zn,Be]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:O()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Be]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Be]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[g]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...K(),RI]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",CI]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},kI]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[h]}],"gradient-via-pos":[{via:[h]}],"gradient-to-pos":[{to:[h]}],"gradient-from":[{from:[m]}],"gradient-via":[{via:[m]}],"gradient-to":[{to:[m]}],rounded:[{rounded:[s]}],"rounded-s":[{"rounded-s":[s]}],"rounded-e":[{"rounded-e":[s]}],"rounded-t":[{"rounded-t":[s]}],"rounded-r":[{"rounded-r":[s]}],"rounded-b":[{"rounded-b":[s]}],"rounded-l":[{"rounded-l":[s]}],"rounded-ss":[{"rounded-ss":[s]}],"rounded-se":[{"rounded-se":[s]}],"rounded-ee":[{"rounded-ee":[s]}],"rounded-es":[{"rounded-es":[s]}],"rounded-tl":[{"rounded-tl":[s]}],"rounded-tr":[{"rounded-tr":[s]}],"rounded-br":[{"rounded-br":[s]}],"rounded-bl":[{"rounded-bl":[s]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[g]}],"border-style":[{border:[...H(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[g]}],"divide-style":[{divide:H()}],"border-color":[{border:[i]}],"border-color-x":[{"border-x":[i]}],"border-color-y":[{"border-y":[i]}],"border-color-s":[{"border-s":[i]}],"border-color-e":[{"border-e":[i]}],"border-color-t":[{"border-t":[i]}],"border-color-r":[{"border-r":[i]}],"border-color-b":[{"border-b":[i]}],"border-color-l":[{"border-l":[i]}],"divide-color":[{divide:[i]}],"outline-style":[{outline:["",...H()]}],"outline-offset":[{"outline-offset":[zn,Be]}],"outline-w":[{outline:[zn,gi]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:P()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[g]}],"ring-offset-w":[{"ring-offset":[zn,gi]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",vi,DI]}],"shadow-color":[{shadow:[no]}],opacity:[{opacity:[g]}],"mix-blend":[{"mix-blend":[...se(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":se()}],filter:[{filter:["","none"]}],blur:[{blur:[r]}],brightness:[{brightness:[n]}],contrast:[{contrast:[l]}],"drop-shadow":[{"drop-shadow":["","none",vi,Be]}],grayscale:[{grayscale:[u]}],"hue-rotate":[{"hue-rotate":[c]}],invert:[{invert:[d]}],saturate:[{saturate:[x]}],sepia:[{sepia:[T]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[r]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[l]}],"backdrop-grayscale":[{"backdrop-grayscale":[u]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[c]}],"backdrop-invert":[{"backdrop-invert":[d]}],"backdrop-opacity":[{"backdrop-opacity":[g]}],"backdrop-saturate":[{"backdrop-saturate":[x]}],"backdrop-sepia":[{"backdrop-sepia":[T]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[a]}],"border-spacing-x":[{"border-spacing-x":[a]}],"border-spacing-y":[{"border-spacing-y":[a]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Be]}],duration:[{duration:te()}],ease:[{ease:["linear","in","out","in-out",Be]}],delay:[{delay:te()}],animate:[{animate:["none","spin","ping","pulse","bounce",Be]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[ro,Be]}],"translate-x":[{"translate-x":[b]}],"translate-y":[{"translate-y":[b]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Be]}],accent:[{accent:["auto",t]}],appearance:[{appearance:["none","auto"]}],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",Be]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":O()}],"scroll-mx":[{"scroll-mx":O()}],"scroll-my":[{"scroll-my":O()}],"scroll-ms":[{"scroll-ms":O()}],"scroll-me":[{"scroll-me":O()}],"scroll-mt":[{"scroll-mt":O()}],"scroll-mr":[{"scroll-mr":O()}],"scroll-mb":[{"scroll-mb":O()}],"scroll-ml":[{"scroll-ml":O()}],"scroll-p":[{"scroll-p":O()}],"scroll-px":[{"scroll-px":O()}],"scroll-py":[{"scroll-py":O()}],"scroll-ps":[{"scroll-ps":O()}],"scroll-pe":[{"scroll-pe":O()}],"scroll-pt":[{"scroll-pt":O()}],"scroll-pr":[{"scroll-pr":O()}],"scroll-pb":[{"scroll-pb":O()}],"scroll-pl":[{"scroll-pl":O()}],"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",Be]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[zn,gi,uf]}],stroke:[{stroke:[t,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","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","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","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-s","border-w-e","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-s","border-color-e","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"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","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-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"]}}},FI=yI(NI);function $r(...t){return FI(ri(t))}const UI=OE("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),xm=L.forwardRef(({className:t,variant:e,size:r,asChild:n=!1,...i},s)=>{const a=n?Sd:"button";return E.jsx(a,{className:$r(UI({variant:e,size:r,className:t})),ref:s,...i})});xm.displayName="Button";const Sm=L.forwardRef(({className:t,...e},r)=>E.jsx("div",{ref:r,className:$r("rounded-lg border bg-card text-card-foreground shadow-sm",t),...e}));Sm.displayName="Card";const Em=L.forwardRef(({className:t,...e},r)=>E.jsx("div",{ref:r,className:$r("flex flex-col space-y-1.5 p-6",t),...e}));Em.displayName="CardHeader";const Tm=L.forwardRef(({className:t,...e},r)=>E.jsx("h3",{ref:r,className:$r("text-2xl font-semibold leading-none tracking-tight",t),...e}));Tm.displayName="CardTitle";const BI=L.forwardRef(({className:t,...e},r)=>E.jsx("p",{ref:r,className:$r("text-sm text-muted-foreground",t),...e}));BI.displayName="CardDescription";const $E=L.forwardRef(({className:t,...e},r)=>E.jsx("div",{ref:r,className:$r("p-6 pt-0",t),...e}));$E.displayName="CardContent";const jE=L.forwardRef(({className:t,...e},r)=>E.jsx("div",{ref:r,className:$r("flex items-center p-6 pt-0",t),...e}));jE.displayName="CardFooter";var $I=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],jI=$I.reduce((t,e)=>{const r=L.forwardRef((n,i)=>{const{asChild:s,...a}=n,o=s?Sd:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),E.jsx(o,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{}),VI="Label",VE=L.forwardRef((t,e)=>E.jsx(jI.label,{...t,ref:e,onMouseDown:r=>{var i;r.target.closest("button, input, select, textarea")||((i=t.onMouseDown)==null||i.call(t,r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));VE.displayName=VI;var GE=VE;const GI=OE("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Ao=L.forwardRef(({className:t,...e},r)=>E.jsx(GE,{ref:r,className:$r(GI(),t),...e}));Ao.displayName=GE.displayName;const zI=IC,zE=L.createContext({}),cf=({...t})=>E.jsx(zE.Provider,{value:{name:t.name},children:E.jsx(OC,{...t})}),Ed=()=>{const t=L.useContext(zE),e=L.useContext(HE),{getFieldState:r,formState:n}=yd(),i=r(t.name,n);if(!t)throw new Error("useFormField should be used within ");const{id:s}=e;return{id:s,name:t.name,formItemId:`${s}-form-item`,formDescriptionId:`${s}-form-item-description`,formMessageId:`${s}-form-item-message`,...i}},HE=L.createContext({}),Cu=L.forwardRef(({className:t,...e},r)=>{const n=L.useId();return E.jsx(HE.Provider,{value:{id:n},children:E.jsx("div",{ref:r,className:$r("space-y-2",t),...e})})});Cu.displayName="FormItem";const Ru=L.forwardRef(({className:t,...e},r)=>{const{error:n,formItemId:i}=Ed();return E.jsx(Ao,{ref:r,className:$r(n&&"text-destructive",t),htmlFor:i,...e})});Ru.displayName="FormLabel";const Iu=L.forwardRef(({...t},e)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:s}=Ed();return E.jsx(Sd,{ref:e,id:n,"aria-describedby":r?`${i} ${s}`:`${i}`,"aria-invalid":!!r,...t})});Iu.displayName="FormControl";const HI=L.forwardRef(({className:t,...e},r)=>{const{formDescriptionId:n}=Ed();return E.jsx("p",{ref:r,id:n,className:$r("text-sm text-muted-foreground",t),...e})});HI.displayName="FormDescription";const ku=L.forwardRef(({className:t,children:e,...r},n)=>{const{error:i,formMessageId:s}=Ed(),a=i?String(i==null?void 0:i.message):e;return a?E.jsx("p",{ref:n,id:s,className:$r("text-sm font-medium text-destructive",t),...r,children:a}):null});ku.displayName="FormMessage";const fs=L.forwardRef(({className:t,type:e,...r},n)=>E.jsx("input",{type:e,className:$r("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),ref:n,...r}));fs.displayName="Input";const WI=to.object({username:to.string().min(4,"Username must be at least 4 characters long").max(20,"Username must be at most 20 characters long"),password:to.string().min(8,"Password must be at least 8 characters long").max(64,"Password must be at most 64 characters long").refine(t=>/[A-Z]/.test(t),{message:"Password must contain at least one uppercase letter"}).refine(t=>/[a-z]/.test(t),{message:"Password must contain at least one lowercase letter"}).refine(t=>/[0-9]/.test(t),{message:"Password must contain at least one number"}).refine(t=>/[!@#$%^&*()_+[\]{};':"\\|,.<>/?`~\\-]/.test(t),{message:"Password must contain at least one special character"}),confirmPassword:to.string(),type:to.enum(["admin","user"])}).refine(t=>t.password===t.confirmPassword,{message:"Passwords do not match",path:["confirmPassword"]}),KI=()=>{const t=WC({resolver:XC(WI),defaultValues:{username:"",password:"",confirmPassword:"",type:"user"}}),e=Br(),{handleSubmit:r,data:n,pending:i}=Ss(),s=async a=>{console.log(a);try{await r({url:"/api/auth/signup",body:{...a,code:window.location.search.includes("code")}}),Ke.success("Registration successful"),e("/sign-in")}catch(o){Ke.error(o.message)}};return L.useEffect(()=>{n&&(n.code===200?Ke.success("Sign up successful"):Ke.error("Sign up failed"))},[n]),E.jsx("section",{className:"h-screen w-screen flex items-center justify-center",children:E.jsxs(Sm,{className:"w-1/4 py-2 px-4 pb-8",children:[E.jsx(Em,{children:E.jsx(Tm,{children:"Sign Up"})}),E.jsx(zI,{...t,children:E.jsxs("form",{onSubmit:t.handleSubmit(s),className:"flex flex-col gap-6",children:[E.jsx(cf,{control:t.control,name:"username",render:({field:a})=>E.jsxs(Cu,{children:[E.jsx(Ru,{htmlFor:"username",children:"Username"}),E.jsx(Iu,{children:E.jsx(fs,{...a,placeholder:"Username",autoComplete:"given-name"})}),E.jsx(ku,{})]})}),E.jsx(cf,{control:t.control,name:"password",render:({field:a})=>E.jsxs(Cu,{children:[E.jsx(Ru,{htmlFor:"password",children:"Password"}),E.jsx(Iu,{children:E.jsx(fs,{...a,type:"password",placeholder:"Password",autoComplete:"new-password"})}),E.jsx(ku,{})]})}),E.jsx(cf,{control:t.control,name:"confirmPassword",render:({field:a})=>E.jsxs(Cu,{children:[E.jsx(Ru,{htmlFor:"confirmPassword",children:"Confirm Password"}),E.jsx(Iu,{children:E.jsx(fs,{...a,type:"password",placeholder:"Confirm Password",autoComplete:"new-password"})}),E.jsx(ku,{})]})}),E.jsx(xm,{variant:"default",children:i?"Signing up...":"Sign Up"})]})})]})})},_s=t=>E.jsx("section",{...t,children:E.jsx("div",{className:"flex justify-center items-center h-full",children:E.jsx("img",{src:"loader.gif",alt:"Loading...",className:"w-1/4"})})}),Rn=({state:t,iconBefore:e,iconAfter:r,to:n,onClick:i,className:s="",children:a,...o})=>{const l="flex items-center justify-center gap-2 py-2 px-4 rounded-md font-medium",f=t==="primary"?"bg-neutral-200 text-neutral-900 hover:bg-neutral-300":t==="secondary"?"bg-neutral-900 text-neutral-200 hover:bg-neutral-800":"bg-red-500 text-white hover:bg-red-600",m=Br(),h=()=>{n?m(n):i&&i()};return E.jsxs("button",{onClick:h,className:`${l} ${f} ${s} transition-colors duration-300`,...o,children:[e&&E.jsx("span",{children:e}),a,r&&E.jsx("span",{children:r})]})};var WE={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Z0=ne.createContext&&ne.createContext(WE),YI=["attr","size","title"];function qI(t,e){if(t==null)return{};var r=XI(t,e),n,i;if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function XI(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function Rc(){return Rc=Object.assign?Object.assign.bind():function(t){for(var e=1;ene.createElement(e.tag,Ic({key:r},e.attr),KE(e.child)))}function Mt(t){return e=>ne.createElement(ek,Rc({attr:Ic({},t.attr)},e),KE(t.child))}function ek(t){var e=r=>{var{attr:n,size:i,title:s}=t,a=qI(t,YI),o=i||r.size||"1em",l;return r.className&&(l=r.className),t.className&&(l=(l?l+" ":"")+t.className),ne.createElement("svg",Rc({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},r.attr,n,a,{className:l,style:Ic(Ic({color:t.color||r.color},r.style),t.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),s&&ne.createElement("title",null,s),t.children)};return Z0!==void 0?ne.createElement(Z0.Consumer,null,r=>e(r)):e(WE)}function tk(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M9.5 15.584V8.416a.5.5 0 0 1 .77-.42l5.576 3.583a.5.5 0 0 1 0 .842l-5.576 3.584a.5.5 0 0 1-.77-.42Z"},child:[]},{tag:"path",attr:{d:"M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12Zm11-9.5A9.5 9.5 0 0 0 2.5 12a9.5 9.5 0 0 0 9.5 9.5 9.5 9.5 0 0 0 9.5-9.5A9.5 9.5 0 0 0 12 2.5Z"},child:[]}]})(t)}const _a=({media:t})=>E.jsx("section",{className:"h-[85dvh] bg-cover bg-center flex items-end",style:{backgroundImage:`linear-gradient(hsl(var(--background)), transparent, hsl(var(--background))), linear-gradient(90deg, hsl(var(--background)) 5%, transparent), url(/api/medias/images/banner/${t.type}/${t.banner_id})`},children:E.jsxs("section",{className:"px-4 flex flex-col gap-4 w-3/4",children:[t.have_logo?E.jsx("img",{src:t.images.logo,alt:t.title,className:"h-48 object-contain rounded-md w-fit"}):E.jsx("h1",{className:"text-5xl font-bold",children:t.serie_title??t.title}),E.jsx("p",{children:t.description}),E.jsx("section",{className:"flex gap-4",children:E.jsx(Rn,{to:`/watch/${t.type}/${t.id}`,iconBefore:E.jsx(tk,{}),state:"primary",children:"Watch Now"})})]})});function J0(t){return t!==null&&typeof t=="object"&&"constructor"in t&&t.constructor===Object}function wm(t,e){t===void 0&&(t={}),e===void 0&&(e={}),Object.keys(e).forEach(r=>{typeof t[r]>"u"?t[r]=e[r]:J0(e[r])&&J0(t[r])&&Object.keys(e[r]).length>0&&wm(t[r],e[r])})}const YE={body:{},addEventListener(){},removeEventListener(){},activeElement:{blur(){},nodeName:""},querySelector(){return null},querySelectorAll(){return[]},getElementById(){return null},createEvent(){return{initEvent(){}}},createElement(){return{children:[],childNodes:[],style:{},setAttribute(){},getElementsByTagName(){return[]}}},createElementNS(){return{}},importNode(){return null},location:{hash:"",host:"",hostname:"",href:"",origin:"",pathname:"",protocol:"",search:""}};function $a(){const t=typeof document<"u"?document:{};return wm(t,YE),t}const rk={document:YE,navigator:{userAgent:""},location:{hash:"",host:"",hostname:"",href:"",origin:"",pathname:"",protocol:"",search:""},history:{replaceState(){},pushState(){},go(){},back(){}},CustomEvent:function(){return this},addEventListener(){},removeEventListener(){},getComputedStyle(){return{getPropertyValue(){return""}}},Image(){},Date(){},screen:{},setTimeout(){},clearTimeout(){},matchMedia(){return{}},requestAnimationFrame(t){return typeof setTimeout>"u"?(t(),null):setTimeout(t,0)},cancelAnimationFrame(t){typeof setTimeout>"u"||clearTimeout(t)}};function jr(){const t=typeof window<"u"?window:{};return wm(t,rk),t}function nk(t){return t===void 0&&(t=""),t.trim().split(" ").filter(e=>!!e.trim())}function ik(t){const e=t;Object.keys(e).forEach(r=>{try{e[r]=null}catch{}try{delete e[r]}catch{}})}function Gh(t,e){return e===void 0&&(e=0),setTimeout(t,e)}function kc(){return Date.now()}function sk(t){const e=jr();let r;return e.getComputedStyle&&(r=e.getComputedStyle(t,null)),!r&&t.currentStyle&&(r=t.currentStyle),r||(r=t.style),r}function ak(t,e){e===void 0&&(e="x");const r=jr();let n,i,s;const a=sk(t);return r.WebKitCSSMatrix?(i=a.transform||a.webkitTransform,i.split(",").length>6&&(i=i.split(", ").map(o=>o.replace(",",".")).join(", ")),s=new r.WebKitCSSMatrix(i==="none"?"":i)):(s=a.MozTransform||a.OTransform||a.MsTransform||a.msTransform||a.transform||a.getPropertyValue("transform").replace("translate(","matrix(1, 0, 0, 1,"),n=s.toString().split(",")),e==="x"&&(r.WebKitCSSMatrix?i=s.m41:n.length===16?i=parseFloat(n[12]):i=parseFloat(n[4])),e==="y"&&(r.WebKitCSSMatrix?i=s.m42:n.length===16?i=parseFloat(n[13]):i=parseFloat(n[5])),i||0}function Jl(t){return typeof t=="object"&&t!==null&&t.constructor&&Object.prototype.toString.call(t).slice(8,-1)==="Object"}function ok(t){return typeof window<"u"&&typeof window.HTMLElement<"u"?t instanceof HTMLElement:t&&(t.nodeType===1||t.nodeType===11)}function Ir(){const t=Object(arguments.length<=0?void 0:arguments[0]),e=["__proto__","constructor","prototype"];for(let r=1;re.indexOf(s)<0);for(let s=0,a=i.length;ss?"next":"prev",c=(f,m)=>u==="next"&&f>=m||u==="prev"&&f<=m,d=()=>{o=new Date().getTime(),a===null&&(a=o);const f=Math.max(Math.min((o-a)/l,1),0),m=.5-Math.cos(f*Math.PI)/2;let h=s+m*(r-s);if(c(h,r)&&(h=r),e.wrapperEl.scrollTo({[n]:h}),c(h,r)){e.wrapperEl.style.overflow="hidden",e.wrapperEl.style.scrollSnapType="",setTimeout(()=>{e.wrapperEl.style.overflow="",e.wrapperEl.scrollTo({[n]:h})}),i.cancelAnimationFrame(e.cssModeFrameID);return}e.cssModeFrameID=i.requestAnimationFrame(d)};d()}function In(t,e){e===void 0&&(e="");const r=[...t.children];return t instanceof HTMLSlotElement&&r.push(...t.assignedElements()),e?r.filter(n=>n.matches(e)):r}function lk(t,e){const r=e.contains(t);return!r&&e instanceof HTMLSlotElement?[...e.assignedElements()].includes(t):r}function Dc(t){try{console.warn(t);return}catch{}}function Pc(t,e){e===void 0&&(e=[]);const r=document.createElement(t);return r.classList.add(...Array.isArray(e)?e:nk(e)),r}function uk(t,e){const r=[];for(;t.previousElementSibling;){const n=t.previousElementSibling;e?n.matches(e)&&r.push(n):r.push(n),t=n}return r}function ck(t,e){const r=[];for(;t.nextElementSibling;){const n=t.nextElementSibling;e?n.matches(e)&&r.push(n):r.push(n),t=n}return r}function Ri(t,e){return jr().getComputedStyle(t,null).getPropertyValue(e)}function ev(t){let e=t,r;if(e){for(r=0;(e=e.previousSibling)!==null;)e.nodeType===1&&(r+=1);return r}}function dk(t,e){const r=[];let n=t.parentElement;for(;n;)r.push(n),n=n.parentElement;return r}function tv(t,e,r){const n=jr();return t[e==="width"?"offsetWidth":"offsetHeight"]+parseFloat(n.getComputedStyle(t,null).getPropertyValue(e==="width"?"margin-right":"margin-top"))+parseFloat(n.getComputedStyle(t,null).getPropertyValue(e==="width"?"margin-left":"margin-bottom"))}function Hn(t){return(Array.isArray(t)?t:[t]).filter(e=>!!e)}let df;function fk(){const t=jr(),e=$a();return{smoothScroll:e.documentElement&&e.documentElement.style&&"scrollBehavior"in e.documentElement.style,touch:!!("ontouchstart"in t||t.DocumentTouch&&e instanceof t.DocumentTouch)}}function XE(){return df||(df=fk()),df}let ff;function hk(t){let{userAgent:e}=t===void 0?{}:t;const r=XE(),n=jr(),i=n.navigator.platform,s=e||n.navigator.userAgent,a={ios:!1,android:!1},o=n.screen.width,l=n.screen.height,u=s.match(/(Android);?[\s\/]+([\d.]+)?/);let c=s.match(/(iPad).*OS\s([\d_]+)/);const d=s.match(/(iPod)(.*OS\s([\d_]+))?/),f=!c&&s.match(/(iPhone\sOS|iOS)\s([\d_]+)/),m=i==="Win32";let h=i==="MacIntel";const p=["1024x1366","1366x1024","834x1194","1194x834","834x1112","1112x834","768x1024","1024x768","820x1180","1180x820","810x1080","1080x810"];return!c&&h&&r.touch&&p.indexOf(`${o}x${l}`)>=0&&(c=s.match(/(Version)\/([\d.]+)/),c||(c=[0,1,"13_0_0"]),h=!1),u&&!m&&(a.os="android",a.android=!0),(c||f||d)&&(a.os="ios",a.ios=!0),a}function ZE(t){return t===void 0&&(t={}),ff||(ff=hk(t)),ff}let hf;function pk(){const t=jr(),e=ZE();let r=!1;function n(){const o=t.navigator.userAgent.toLowerCase();return o.indexOf("safari")>=0&&o.indexOf("chrome")<0&&o.indexOf("android")<0}if(n()){const o=String(t.navigator.userAgent);if(o.includes("Version/")){const[l,u]=o.split("Version/")[1].split(" ")[0].split(".").map(c=>Number(c));r=l<16||l===16&&u<2}}const i=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(t.navigator.userAgent),s=n(),a=s||i&&e.ios;return{isSafari:r||s,needPerspectiveFix:r,need3dFix:a,isWebView:i}}function mk(){return hf||(hf=pk()),hf}function gk(t){let{swiper:e,on:r,emit:n}=t;const i=jr();let s=null,a=null;const o=()=>{!e||e.destroyed||!e.initialized||(n("beforeResize"),n("resize"))},l=()=>{!e||e.destroyed||!e.initialized||(s=new ResizeObserver(d=>{a=i.requestAnimationFrame(()=>{const{width:f,height:m}=e;let h=f,p=m;d.forEach(v=>{let{contentBoxSize:g,contentRect:y,target:x}=v;x&&x!==e.el||(h=y?y.width:(g[0]||g).inlineSize,p=y?y.height:(g[0]||g).blockSize)}),(h!==f||p!==m)&&o()})}),s.observe(e.el))},u=()=>{a&&i.cancelAnimationFrame(a),s&&s.unobserve&&e.el&&(s.unobserve(e.el),s=null)},c=()=>{!e||e.destroyed||!e.initialized||n("orientationchange")};r("init",()=>{if(e.params.resizeObserver&&typeof i.ResizeObserver<"u"){l();return}i.addEventListener("resize",o),i.addEventListener("orientationchange",c)}),r("destroy",()=>{u(),i.removeEventListener("resize",o),i.removeEventListener("orientationchange",c)})}function vk(t){let{swiper:e,extendParams:r,on:n,emit:i}=t;const s=[],a=jr(),o=function(c,d){d===void 0&&(d={});const f=a.MutationObserver||a.WebkitMutationObserver,m=new f(h=>{if(e.__preventObserver__)return;if(h.length===1){i("observerUpdate",h[0]);return}const p=function(){i("observerUpdate",h[0])};a.requestAnimationFrame?a.requestAnimationFrame(p):a.setTimeout(p,0)});m.observe(c,{attributes:typeof d.attributes>"u"?!0:d.attributes,childList:e.isElement||(typeof d.childList>"u"?!0:d).childList,characterData:typeof d.characterData>"u"?!0:d.characterData}),s.push(m)},l=()=>{if(e.params.observer){if(e.params.observeParents){const c=dk(e.hostEl);for(let d=0;d{s.forEach(c=>{c.disconnect()}),s.splice(0,s.length)};r({observer:!1,observeParents:!1,observeSlideChildren:!1}),n("init",l),n("destroy",u)}var yk={on(t,e,r){const n=this;if(!n.eventsListeners||n.destroyed||typeof e!="function")return n;const i=r?"unshift":"push";return t.split(" ").forEach(s=>{n.eventsListeners[s]||(n.eventsListeners[s]=[]),n.eventsListeners[s][i](e)}),n},once(t,e,r){const n=this;if(!n.eventsListeners||n.destroyed||typeof e!="function")return n;function i(){n.off(t,i),i.__emitterProxy&&delete i.__emitterProxy;for(var s=arguments.length,a=new Array(s),o=0;o=0&&e.eventsAnyListeners.splice(r,1),e},off(t,e){const r=this;return!r.eventsListeners||r.destroyed||!r.eventsListeners||t.split(" ").forEach(n=>{typeof e>"u"?r.eventsListeners[n]=[]:r.eventsListeners[n]&&r.eventsListeners[n].forEach((i,s)=>{(i===e||i.__emitterProxy&&i.__emitterProxy===e)&&r.eventsListeners[n].splice(s,1)})}),r},emit(){const t=this;if(!t.eventsListeners||t.destroyed||!t.eventsListeners)return t;let e,r,n;for(var i=arguments.length,s=new Array(i),a=0;a{t.eventsAnyListeners&&t.eventsAnyListeners.length&&t.eventsAnyListeners.forEach(u=>{u.apply(n,[l,...r])}),t.eventsListeners&&t.eventsListeners[l]&&t.eventsListeners[l].forEach(u=>{u.apply(n,r)})}),t}};function xk(){const t=this;let e,r;const n=t.el;typeof t.params.width<"u"&&t.params.width!==null?e=t.params.width:e=n.clientWidth,typeof t.params.height<"u"&&t.params.height!==null?r=t.params.height:r=n.clientHeight,!(e===0&&t.isHorizontal()||r===0&&t.isVertical())&&(e=e-parseInt(Ri(n,"padding-left")||0,10)-parseInt(Ri(n,"padding-right")||0,10),r=r-parseInt(Ri(n,"padding-top")||0,10)-parseInt(Ri(n,"padding-bottom")||0,10),Number.isNaN(e)&&(e=0),Number.isNaN(r)&&(r=0),Object.assign(t,{width:e,height:r,size:t.isHorizontal()?e:r}))}function Sk(){const t=this;function e(A,k){return parseFloat(A.getPropertyValue(t.getDirectionLabel(k))||0)}const r=t.params,{wrapperEl:n,slidesEl:i,size:s,rtlTranslate:a,wrongRTL:o}=t,l=t.virtual&&r.virtual.enabled,u=l?t.virtual.slides.length:t.slides.length,c=In(i,`.${t.params.slideClass}, swiper-slide`),d=l?t.virtual.slides.length:c.length;let f=[];const m=[],h=[];let p=r.slidesOffsetBefore;typeof p=="function"&&(p=r.slidesOffsetBefore.call(t));let v=r.slidesOffsetAfter;typeof v=="function"&&(v=r.slidesOffsetAfter.call(t));const g=t.snapGrid.length,y=t.slidesGrid.length;let x=r.spaceBetween,S=-p,T=0,C=0;if(typeof s>"u")return;typeof x=="string"&&x.indexOf("%")>=0?x=parseFloat(x.replace("%",""))/100*s:typeof x=="string"&&(x=parseFloat(x)),t.virtualSize=-x,c.forEach(A=>{a?A.style.marginLeft="":A.style.marginRight="",A.style.marginBottom="",A.style.marginTop=""}),r.centeredSlides&&r.cssMode&&(eu(n,"--swiper-centered-offset-before",""),eu(n,"--swiper-centered-offset-after",""));const _=r.grid&&r.grid.rows>1&&t.grid;_?t.grid.initSlides(c):t.grid&&t.grid.unsetSlides();let b;const I=r.slidesPerView==="auto"&&r.breakpoints&&Object.keys(r.breakpoints).filter(A=>typeof r.breakpoints[A].slidesPerView<"u").length>0;for(let A=0;A1&&f.push(t.virtualSize-s)}if(l&&r.loop){const A=h[0]+x;if(r.slidesPerGroup>1){const k=Math.ceil((t.virtual.slidesBefore+t.virtual.slidesAfter)/r.slidesPerGroup),O=A*r.slidesPerGroup;for(let P=0;P!r.cssMode||r.loop?!0:O!==c.length-1).forEach(k=>{k.style[A]=`${x}px`})}if(r.centeredSlides&&r.centeredSlidesBounds){let A=0;h.forEach(O=>{A+=O+(x||0)}),A-=x;const k=A-s;f=f.map(O=>O<=0?-p:O>k?k+v:O)}if(r.centerInsufficientSlides){let A=0;h.forEach(O=>{A+=O+(x||0)}),A-=x;const k=(r.slidesOffsetBefore||0)+(r.slidesOffsetAfter||0);if(A+k{f[G]=P-O}),m.forEach((P,G)=>{m[G]=P+O})}}if(Object.assign(t,{slides:c,snapGrid:f,slidesGrid:m,slidesSizesGrid:h}),r.centeredSlides&&r.cssMode&&!r.centeredSlidesBounds){eu(n,"--swiper-centered-offset-before",`${-f[0]}px`),eu(n,"--swiper-centered-offset-after",`${t.size/2-h[h.length-1]/2}px`);const A=-t.snapGrid[0],k=-t.slidesGrid[0];t.snapGrid=t.snapGrid.map(O=>O+A),t.slidesGrid=t.slidesGrid.map(O=>O+k)}if(d!==u&&t.emit("slidesLengthChange"),f.length!==g&&(t.params.watchOverflow&&t.checkOverflow(),t.emit("snapGridLengthChange")),m.length!==y&&t.emit("slidesGridLengthChange"),r.watchSlidesProgress&&t.updateSlidesOffset(),t.emit("slidesUpdated"),!l&&!r.cssMode&&(r.effect==="slide"||r.effect==="fade")){const A=`${r.containerModifierClass}backface-hidden`,k=t.el.classList.contains(A);d<=r.maxBackfaceHiddenSlides?k||t.el.classList.add(A):k&&t.el.classList.remove(A)}}function Ek(t){const e=this,r=[],n=e.virtual&&e.params.virtual.enabled;let i=0,s;typeof t=="number"?e.setTransition(t):t===!0&&e.setTransition(e.params.speed);const a=o=>n?e.slides[e.getSlideIndexByData(o)]:e.slides[o];if(e.params.slidesPerView!=="auto"&&e.params.slidesPerView>1)if(e.params.centeredSlides)(e.visibleSlides||[]).forEach(o=>{r.push(o)});else for(s=0;se.slides.length&&!n)break;r.push(a(o))}else r.push(a(e.activeIndex));for(s=0;si?o:i}(i||i===0)&&(e.wrapperEl.style.height=`${i}px`)}function Tk(){const t=this,e=t.slides,r=t.isElement?t.isHorizontal()?t.wrapperEl.offsetLeft:t.wrapperEl.offsetTop:0;for(let n=0;n{e&&!t.classList.contains(r)?t.classList.add(r):!e&&t.classList.contains(r)&&t.classList.remove(r)};function wk(t){t===void 0&&(t=this&&this.translate||0);const e=this,r=e.params,{slides:n,rtlTranslate:i,snapGrid:s}=e;if(n.length===0)return;typeof n[0].swiperSlideOffset>"u"&&e.updateSlidesOffset();let a=-t;i&&(a=t),e.visibleSlidesIndexes=[],e.visibleSlides=[];let o=r.spaceBetween;typeof o=="string"&&o.indexOf("%")>=0?o=parseFloat(o.replace("%",""))/100*e.size:typeof o=="string"&&(o=parseFloat(o));for(let l=0;l=0&&m<=e.size-e.slidesSizesGrid[l],v=m>=0&&m1&&h<=e.size||m<=0&&h>=e.size;v&&(e.visibleSlides.push(u),e.visibleSlidesIndexes.push(l)),rv(u,v,r.slideVisibleClass),rv(u,p,r.slideFullyVisibleClass),u.progress=i?-d:d,u.originalProgress=i?-f:f}}function bk(t){const e=this;if(typeof t>"u"){const c=e.rtlTranslate?-1:1;t=e&&e.translate&&e.translate*c||0}const r=e.params,n=e.maxTranslate()-e.minTranslate();let{progress:i,isBeginning:s,isEnd:a,progressLoop:o}=e;const l=s,u=a;if(n===0)i=0,s=!0,a=!0;else{i=(t-e.minTranslate())/n;const c=Math.abs(t-e.minTranslate())<1,d=Math.abs(t-e.maxTranslate())<1;s=c||i<=0,a=d||i>=1,c&&(i=0),d&&(i=1)}if(r.loop){const c=e.getSlideIndexByData(0),d=e.getSlideIndexByData(e.slides.length-1),f=e.slidesGrid[c],m=e.slidesGrid[d],h=e.slidesGrid[e.slidesGrid.length-1],p=Math.abs(t);p>=f?o=(p-f)/h:o=(p+h-m)/h,o>1&&(o-=1)}Object.assign(e,{progress:i,progressLoop:o,isBeginning:s,isEnd:a}),(r.watchSlidesProgress||r.centeredSlides&&r.autoHeight)&&e.updateSlidesProgress(t),s&&!l&&e.emit("reachBeginning toEdge"),a&&!u&&e.emit("reachEnd toEdge"),(l&&!s||u&&!a)&&e.emit("fromEdge"),e.emit("progress",i)}const pf=(t,e,r)=>{e&&!t.classList.contains(r)?t.classList.add(r):!e&&t.classList.contains(r)&&t.classList.remove(r)};function Lk(){const t=this,{slides:e,params:r,slidesEl:n,activeIndex:i}=t,s=t.virtual&&r.virtual.enabled,a=t.grid&&r.grid&&r.grid.rows>1,o=d=>In(n,`.${r.slideClass}${d}, swiper-slide${d}`)[0];let l,u,c;if(s)if(r.loop){let d=i-t.virtual.slidesBefore;d<0&&(d=t.virtual.slides.length+d),d>=t.virtual.slides.length&&(d-=t.virtual.slides.length),l=o(`[data-swiper-slide-index="${d}"]`)}else l=o(`[data-swiper-slide-index="${i}"]`);else a?(l=e.filter(d=>d.column===i)[0],c=e.filter(d=>d.column===i+1)[0],u=e.filter(d=>d.column===i-1)[0]):l=e[i];l&&(a||(c=ck(l,`.${r.slideClass}, swiper-slide`)[0],r.loop&&!c&&(c=e[0]),u=uk(l,`.${r.slideClass}, swiper-slide`)[0],r.loop&&!u===0&&(u=e[e.length-1]))),e.forEach(d=>{pf(d,d===l,r.slideActiveClass),pf(d,d===c,r.slideNextClass),pf(d,d===u,r.slidePrevClass)}),t.emitSlidesClasses()}const Du=(t,e)=>{if(!t||t.destroyed||!t.params)return;const r=()=>t.isElement?"swiper-slide":`.${t.params.slideClass}`,n=e.closest(r());if(n){let i=n.querySelector(`.${t.params.lazyPreloaderClass}`);!i&&t.isElement&&(n.shadowRoot?i=n.shadowRoot.querySelector(`.${t.params.lazyPreloaderClass}`):requestAnimationFrame(()=>{n.shadowRoot&&(i=n.shadowRoot.querySelector(`.${t.params.lazyPreloaderClass}`),i&&i.remove())})),i&&i.remove()}},mf=(t,e)=>{if(!t.slides[e])return;const r=t.slides[e].querySelector('[loading="lazy"]');r&&r.removeAttribute("loading")},zh=t=>{if(!t||t.destroyed||!t.params)return;let e=t.params.lazyPreloadPrevNext;const r=t.slides.length;if(!r||!e||e<0)return;e=Math.min(e,r);const n=t.params.slidesPerView==="auto"?t.slidesPerViewDynamic():Math.ceil(t.params.slidesPerView),i=t.activeIndex;if(t.params.grid&&t.params.grid.rows>1){const a=i,o=[a-e];o.push(...Array.from({length:e}).map((l,u)=>a+n+u)),t.slides.forEach((l,u)=>{o.includes(l.column)&&mf(t,u)});return}const s=i+n-1;if(t.params.rewind||t.params.loop)for(let a=i-e;a<=s+e;a+=1){const o=(a%r+r)%r;(os)&&mf(t,o)}else for(let a=Math.max(i-e,0);a<=Math.min(s+e,r-1);a+=1)a!==i&&(a>s||a=e[s]&&n=e[s]&&n=e[s]&&(i=s);return r.normalizeSlideIndex&&(i<0||typeof i>"u")&&(i=0),i}function _k(t){const e=this,r=e.rtlTranslate?e.translate:-e.translate,{snapGrid:n,params:i,activeIndex:s,realIndex:a,snapIndex:o}=e;let l=t,u;const c=m=>{let h=m-e.virtual.slidesBefore;return h<0&&(h=e.virtual.slides.length+h),h>=e.virtual.slides.length&&(h-=e.virtual.slides.length),h};if(typeof l>"u"&&(l=Ak(e)),n.indexOf(r)>=0)u=n.indexOf(r);else{const m=Math.min(i.slidesPerGroupSkip,l);u=m+Math.floor((l-m)/i.slidesPerGroup)}if(u>=n.length&&(u=n.length-1),l===s&&!e.params.loop){u!==o&&(e.snapIndex=u,e.emit("snapIndexChange"));return}if(l===s&&e.params.loop&&e.virtual&&e.params.virtual.enabled){e.realIndex=c(l);return}const d=e.grid&&i.grid&&i.grid.rows>1;let f;if(e.virtual&&i.virtual.enabled&&i.loop)f=c(l);else if(d){const m=e.slides.filter(p=>p.column===l)[0];let h=parseInt(m.getAttribute("data-swiper-slide-index"),10);Number.isNaN(h)&&(h=Math.max(e.slides.indexOf(m),0)),f=Math.floor(h/i.grid.rows)}else if(e.slides[l]){const m=e.slides[l].getAttribute("data-swiper-slide-index");m?f=parseInt(m,10):f=l}else f=l;Object.assign(e,{previousSnapIndex:o,snapIndex:u,previousRealIndex:a,realIndex:f,previousIndex:s,activeIndex:l}),e.initialized&&zh(e),e.emit("activeIndexChange"),e.emit("snapIndexChange"),(e.initialized||e.params.runCallbacksOnInit)&&(a!==f&&e.emit("realIndexChange"),e.emit("slideChange"))}function Ck(t,e){const r=this,n=r.params;let i=t.closest(`.${n.slideClass}, swiper-slide`);!i&&r.isElement&&e&&e.length>1&&e.includes(t)&&[...e.slice(e.indexOf(t)+1,e.length)].forEach(o=>{!i&&o.matches&&o.matches(`.${n.slideClass}, swiper-slide`)&&(i=o)});let s=!1,a;if(i){for(let o=0;ol?c=l:n&&ta?o="next":s"u"&&(e=s.params.speed);const p=Math.min(s.params.slidesPerGroupSkip,a);let v=p+Math.floor((a-p)/s.params.slidesPerGroup);v>=l.length&&(v=l.length-1);const g=-l[v];if(o.normalizeSlideIndex)for(let x=0;x=T&&S=T&&S=T&&(a=x)}if(s.initialized&&a!==d&&(!s.allowSlideNext&&(f?g>s.translate&&g>s.minTranslate():gs.translate&&g>s.maxTranslate()&&(d||0)!==a))return!1;a!==(c||0)&&r&&s.emit("beforeSlideChangeStart"),s.updateProgress(g);let y;if(a>d?y="next":a0?(s._cssModeVirtualInitialSet=!0,requestAnimationFrame(()=>{m[x?"scrollLeft":"scrollTop"]=S})):m[x?"scrollLeft":"scrollTop"]=S,T&&requestAnimationFrame(()=>{s.wrapperEl.style.scrollSnapType="",s._immediateVirtual=!1})}else{if(!s.support.smoothScroll)return qE({swiper:s,targetPosition:S,side:x?"left":"top"}),!0;m.scrollTo({[x?"left":"top"]:S,behavior:"smooth"})}return!0}return s.setTransition(e),s.setTranslate(g),s.updateActiveIndex(a),s.updateSlidesClasses(),s.emit("beforeTransitionStart",e,n),s.transitionStart(r,y),e===0?s.transitionEnd(r,y):s.animating||(s.animating=!0,s.onSlideToWrapperTransitionEnd||(s.onSlideToWrapperTransitionEnd=function(S){!s||s.destroyed||S.target===this&&(s.wrapperEl.removeEventListener("transitionend",s.onSlideToWrapperTransitionEnd),s.onSlideToWrapperTransitionEnd=null,delete s.onSlideToWrapperTransitionEnd,s.transitionEnd(r,y))}),s.wrapperEl.addEventListener("transitionend",s.onSlideToWrapperTransitionEnd)),!0}function jk(t,e,r,n){t===void 0&&(t=0),r===void 0&&(r=!0),typeof t=="string"&&(t=parseInt(t,10));const i=this;if(i.destroyed)return;typeof e>"u"&&(e=i.params.speed);const s=i.grid&&i.params.grid&&i.params.grid.rows>1;let a=t;if(i.params.loop)if(i.virtual&&i.params.virtual.enabled)a=a+i.virtual.slidesBefore;else{let o;if(s){const f=a*i.params.grid.rows;o=i.slides.filter(m=>m.getAttribute("data-swiper-slide-index")*1===f)[0].column}else o=i.getSlideIndexByData(a);const l=s?Math.ceil(i.slides.length/i.params.grid.rows):i.slides.length,{centeredSlides:u}=i.params;let c=i.params.slidesPerView;c==="auto"?c=i.slidesPerViewDynamic():(c=Math.ceil(parseFloat(i.params.slidesPerView,10)),u&&c%2===0&&(c=c+1));let d=l-om.getAttribute("data-swiper-slide-index")*1===f)[0].column}else a=i.getSlideIndexByData(a)}return requestAnimationFrame(()=>{i.slideTo(a,e,r,n)}),i}function Vk(t,e,r){e===void 0&&(e=!0);const n=this,{enabled:i,params:s,animating:a}=n;if(!i||n.destroyed)return n;typeof t>"u"&&(t=n.params.speed);let o=s.slidesPerGroup;s.slidesPerView==="auto"&&s.slidesPerGroup===1&&s.slidesPerGroupAuto&&(o=Math.max(n.slidesPerViewDynamic("current",!0),1));const l=n.activeIndex{n.slideTo(n.activeIndex+l,t,e,r)}),!0}return s.rewind&&n.isEnd?n.slideTo(0,t,e,r):n.slideTo(n.activeIndex+l,t,e,r)}function Gk(t,e,r){e===void 0&&(e=!0);const n=this,{params:i,snapGrid:s,slidesGrid:a,rtlTranslate:o,enabled:l,animating:u}=n;if(!l||n.destroyed)return n;typeof t>"u"&&(t=n.params.speed);const c=n.virtual&&i.virtual.enabled;if(i.loop){if(u&&!c&&i.loopPreventsSliding)return!1;n.loopFix({direction:"prev"}),n._clientLeft=n.wrapperEl.clientLeft}const d=o?n.translate:-n.translate;function f(g){return g<0?-Math.floor(Math.abs(g)):Math.floor(g)}const m=f(d),h=s.map(g=>f(g));let p=s[h.indexOf(m)-1];if(typeof p>"u"&&i.cssMode){let g;s.forEach((y,x)=>{m>=y&&(g=x)}),typeof g<"u"&&(p=s[g>0?g-1:g])}let v=0;if(typeof p<"u"&&(v=a.indexOf(p),v<0&&(v=n.activeIndex-1),i.slidesPerView==="auto"&&i.slidesPerGroup===1&&i.slidesPerGroupAuto&&(v=v-n.slidesPerViewDynamic("previous",!0)+1,v=Math.max(v,0))),i.rewind&&n.isBeginning){const g=n.params.virtual&&n.params.virtual.enabled&&n.virtual?n.virtual.slides.length-1:n.slides.length-1;return n.slideTo(g,t,e,r)}else if(i.loop&&n.activeIndex===0&&i.cssMode)return requestAnimationFrame(()=>{n.slideTo(v,t,e,r)}),!0;return n.slideTo(v,t,e,r)}function zk(t,e,r){e===void 0&&(e=!0);const n=this;if(!n.destroyed)return typeof t>"u"&&(t=n.params.speed),n.slideTo(n.activeIndex,t,e,r)}function Hk(t,e,r,n){e===void 0&&(e=!0),n===void 0&&(n=.5);const i=this;if(i.destroyed)return;typeof t>"u"&&(t=i.params.speed);let s=i.activeIndex;const a=Math.min(i.params.slidesPerGroupSkip,s),o=a+Math.floor((s-a)/i.params.slidesPerGroup),l=i.rtlTranslate?i.translate:-i.translate;if(l>=i.snapGrid[o]){const u=i.snapGrid[o],c=i.snapGrid[o+1];l-u>(c-u)*n&&(s+=i.params.slidesPerGroup)}else{const u=i.snapGrid[o-1],c=i.snapGrid[o];l-u<=(c-u)*n&&(s-=i.params.slidesPerGroup)}return s=Math.max(s,0),s=Math.min(s,i.slidesGrid.length-1),i.slideTo(s,t,e,r)}function Wk(){const t=this;if(t.destroyed)return;const{params:e,slidesEl:r}=t,n=e.slidesPerView==="auto"?t.slidesPerViewDynamic():e.slidesPerView;let i=t.clickedIndex,s;const a=t.isElement?"swiper-slide":`.${e.slideClass}`;if(e.loop){if(t.animating)return;s=parseInt(t.clickedSlide.getAttribute("data-swiper-slide-index"),10),e.centeredSlides?it.slides.length-t.loopedSlides+n/2?(t.loopFix(),i=t.getSlideIndex(In(r,`${a}[data-swiper-slide-index="${s}"]`)[0]),Gh(()=>{t.slideTo(i)})):t.slideTo(i):i>t.slides.length-n?(t.loopFix(),i=t.getSlideIndex(In(r,`${a}[data-swiper-slide-index="${s}"]`)[0]),Gh(()=>{t.slideTo(i)})):t.slideTo(i)}else t.slideTo(i)}var Kk={slideTo:$k,slideToLoop:jk,slideNext:Vk,slidePrev:Gk,slideReset:zk,slideToClosest:Hk,slideToClickedSlide:Wk};function Yk(t){const e=this,{params:r,slidesEl:n}=e;if(!r.loop||e.virtual&&e.params.virtual.enabled)return;const i=()=>{In(n,`.${r.slideClass}, swiper-slide`).forEach((d,f)=>{d.setAttribute("data-swiper-slide-index",f)})},s=e.grid&&r.grid&&r.grid.rows>1,a=r.slidesPerGroup*(s?r.grid.rows:1),o=e.slides.length%a!==0,l=s&&e.slides.length%r.grid.rows!==0,u=c=>{for(let d=0;d1;u.length"u"?s=l.getSlideIndex(u.filter(P=>P.classList.contains(m.slideActiveClass))[0]):T=s;const C=n==="next"||!n,_=n==="prev"||!n;let b=0,I=0;const A=y?Math.ceil(u.length/m.grid.rows):u.length,O=(y?u[s].column:s)+(h&&typeof i>"u"?-p/2+.5:0);if(O=0;H-=1)u[H].column===K&&x.push(H)}else x.push(A-G-1)}}else if(O+p>A-g){I=Math.max(O-(A-g*2),v);for(let P=0;P{K.column===G&&S.push(H)}):S.push(G)}}if(l.__preventObserver__=!0,requestAnimationFrame(()=>{l.__preventObserver__=!1}),_&&x.forEach(P=>{u[P].swiperLoopMoveDOM=!0,f.prepend(u[P]),u[P].swiperLoopMoveDOM=!1}),C&&S.forEach(P=>{u[P].swiperLoopMoveDOM=!0,f.append(u[P]),u[P].swiperLoopMoveDOM=!1}),l.recalcSlides(),m.slidesPerView==="auto"?l.updateSlides():y&&(x.length>0&&_||S.length>0&&C)&&l.slides.forEach((P,G)=>{l.grid.updateSlide(G,P,l.slides)}),m.watchSlidesProgress&&l.updateSlidesOffset(),r){if(x.length>0&&_){if(typeof e>"u"){const P=l.slidesGrid[T],K=l.slidesGrid[T+b]-P;o?l.setTranslate(l.translate-K):(l.slideTo(T+Math.ceil(b),0,!1,!0),i&&(l.touchEventsData.startTranslate=l.touchEventsData.startTranslate-K,l.touchEventsData.currentTranslate=l.touchEventsData.currentTranslate-K))}else if(i){const P=y?x.length/m.grid.rows:x.length;l.slideTo(l.activeIndex+P,0,!1,!0),l.touchEventsData.currentTranslate=l.translate}}else if(S.length>0&&C)if(typeof e>"u"){const P=l.slidesGrid[T],K=l.slidesGrid[T-I]-P;o?l.setTranslate(l.translate-K):(l.slideTo(T-I,0,!1,!0),i&&(l.touchEventsData.startTranslate=l.touchEventsData.startTranslate-K,l.touchEventsData.currentTranslate=l.touchEventsData.currentTranslate-K))}else{const P=y?S.length/m.grid.rows:S.length;l.slideTo(l.activeIndex-P,0,!1,!0)}}if(l.allowSlidePrev=c,l.allowSlideNext=d,l.controller&&l.controller.control&&!a){const P={slideRealIndex:e,direction:n,setTranslate:i,activeSlideIndex:s,byController:!0};Array.isArray(l.controller.control)?l.controller.control.forEach(G=>{!G.destroyed&&G.params.loop&&G.loopFix({...P,slideTo:G.params.slidesPerView===m.slidesPerView?r:!1})}):l.controller.control instanceof l.constructor&&l.controller.control.params.loop&&l.controller.control.loopFix({...P,slideTo:l.controller.control.params.slidesPerView===m.slidesPerView?r:!1})}l.emit("loopFix")}function Xk(){const t=this,{params:e,slidesEl:r}=t;if(!e.loop||t.virtual&&t.params.virtual.enabled)return;t.recalcSlides();const n=[];t.slides.forEach(i=>{const s=typeof i.swiperSlideIndex>"u"?i.getAttribute("data-swiper-slide-index")*1:i.swiperSlideIndex;n[s]=i}),t.slides.forEach(i=>{i.removeAttribute("data-swiper-slide-index")}),n.forEach(i=>{r.append(i)}),t.recalcSlides(),t.slideTo(t.realIndex,0)}var Zk={loopCreate:Yk,loopFix:qk,loopDestroy:Xk};function Qk(t){const e=this;if(!e.params.simulateTouch||e.params.watchOverflow&&e.isLocked||e.params.cssMode)return;const r=e.params.touchEventsTarget==="container"?e.el:e.wrapperEl;e.isElement&&(e.__preventObserver__=!0),r.style.cursor="move",r.style.cursor=t?"grabbing":"grab",e.isElement&&requestAnimationFrame(()=>{e.__preventObserver__=!1})}function Jk(){const t=this;t.params.watchOverflow&&t.isLocked||t.params.cssMode||(t.isElement&&(t.__preventObserver__=!0),t[t.params.touchEventsTarget==="container"?"el":"wrapperEl"].style.cursor="",t.isElement&&requestAnimationFrame(()=>{t.__preventObserver__=!1}))}var eD={setGrabCursor:Qk,unsetGrabCursor:Jk};function tD(t,e){e===void 0&&(e=this);function r(n){if(!n||n===$a()||n===jr())return null;n.assignedSlot&&(n=n.assignedSlot);const i=n.closest(t);return!i&&!n.getRootNode?null:i||r(n.getRootNode().host)}return r(e)}function nv(t,e,r){const n=jr(),{params:i}=t,s=i.edgeSwipeDetection,a=i.edgeSwipeThreshold;return s&&(r<=a||r>=n.innerWidth-a)?s==="prevent"?(e.preventDefault(),!0):!1:!0}function rD(t){const e=this,r=$a();let n=t;n.originalEvent&&(n=n.originalEvent);const i=e.touchEventsData;if(n.type==="pointerdown"){if(i.pointerId!==null&&i.pointerId!==n.pointerId)return;i.pointerId=n.pointerId}else n.type==="touchstart"&&n.targetTouches.length===1&&(i.touchId=n.targetTouches[0].identifier);if(n.type==="touchstart"){nv(e,n,n.targetTouches[0].pageX);return}const{params:s,touches:a,enabled:o}=e;if(!o||!s.simulateTouch&&n.pointerType==="mouse"||e.animating&&s.preventInteractionOnTransition)return;!e.animating&&s.cssMode&&s.loop&&e.loopFix();let l=n.target;if(s.touchEventsTarget==="wrapper"&&!lk(l,e.wrapperEl)||"which"in n&&n.which===3||"button"in n&&n.button>0||i.isTouched&&i.isMoved)return;const u=!!s.noSwipingClass&&s.noSwipingClass!=="",c=n.composedPath?n.composedPath():n.path;u&&n.target&&n.target.shadowRoot&&c&&(l=c[0]);const d=s.noSwipingSelector?s.noSwipingSelector:`.${s.noSwipingClass}`,f=!!(n.target&&n.target.shadowRoot);if(s.noSwiping&&(f?tD(d,l):l.closest(d))){e.allowClick=!0;return}if(s.swipeHandler&&!l.closest(s.swipeHandler))return;a.currentX=n.pageX,a.currentY=n.pageY;const m=a.currentX,h=a.currentY;if(!nv(e,n,m))return;Object.assign(i,{isTouched:!0,isMoved:!1,allowTouchCallbacks:!0,isScrolling:void 0,startMoving:void 0}),a.startX=m,a.startY=h,i.touchStartTime=kc(),e.allowClick=!0,e.updateSize(),e.swipeDirection=void 0,s.threshold>0&&(i.allowThresholdMove=!1);let p=!0;l.matches(i.focusableElements)&&(p=!1,l.nodeName==="SELECT"&&(i.isTouched=!1)),r.activeElement&&r.activeElement.matches(i.focusableElements)&&r.activeElement!==l&&r.activeElement.blur();const v=p&&e.allowTouchMove&&s.touchStartPreventDefault;(s.touchStartForcePreventDefault||v)&&!l.isContentEditable&&n.preventDefault(),s.freeMode&&s.freeMode.enabled&&e.freeMode&&e.animating&&!s.cssMode&&e.freeMode.onTouchStart(),e.emit("touchStart",n)}function nD(t){const e=$a(),r=this,n=r.touchEventsData,{params:i,touches:s,rtlTranslate:a,enabled:o}=r;if(!o||!i.simulateTouch&&t.pointerType==="mouse")return;let l=t;if(l.originalEvent&&(l=l.originalEvent),l.type==="pointermove"&&(n.touchId!==null||l.pointerId!==n.pointerId))return;let u;if(l.type==="touchmove"){if(u=[...l.changedTouches].filter(C=>C.identifier===n.touchId)[0],!u||u.identifier!==n.touchId)return}else u=l;if(!n.isTouched){n.startMoving&&n.isScrolling&&r.emit("touchMoveOpposite",l);return}const c=u.pageX,d=u.pageY;if(l.preventedByNestedSwiper){s.startX=c,s.startY=d;return}if(!r.allowTouchMove){l.target.matches(n.focusableElements)||(r.allowClick=!1),n.isTouched&&(Object.assign(s,{startX:c,startY:d,currentX:c,currentY:d}),n.touchStartTime=kc());return}if(i.touchReleaseOnEdges&&!i.loop){if(r.isVertical()){if(ds.startY&&r.translate>=r.minTranslate()){n.isTouched=!1,n.isMoved=!1;return}}else if(cs.startX&&r.translate>=r.minTranslate())return}if(e.activeElement&&l.target===e.activeElement&&l.target.matches(n.focusableElements)){n.isMoved=!0,r.allowClick=!1;return}n.allowTouchCallbacks&&r.emit("touchMove",l),s.previousX=s.currentX,s.previousY=s.currentY,s.currentX=c,s.currentY=d;const f=s.currentX-s.startX,m=s.currentY-s.startY;if(r.params.threshold&&Math.sqrt(f**2+m**2)"u"){let C;r.isHorizontal()&&s.currentY===s.startY||r.isVertical()&&s.currentX===s.startX?n.isScrolling=!1:f*f+m*m>=25&&(C=Math.atan2(Math.abs(m),Math.abs(f))*180/Math.PI,n.isScrolling=r.isHorizontal()?C>i.touchAngle:90-C>i.touchAngle)}if(n.isScrolling&&r.emit("touchMoveOpposite",l),typeof n.startMoving>"u"&&(s.currentX!==s.startX||s.currentY!==s.startY)&&(n.startMoving=!0),n.isScrolling||l.type==="touchmove"&&n.preventTouchMoveFromPointerMove){n.isTouched=!1;return}if(!n.startMoving)return;r.allowClick=!1,!i.cssMode&&l.cancelable&&l.preventDefault(),i.touchMoveStopPropagation&&!i.nested&&l.stopPropagation();let h=r.isHorizontal()?f:m,p=r.isHorizontal()?s.currentX-s.previousX:s.currentY-s.previousY;i.oneWayMovement&&(h=Math.abs(h)*(a?1:-1),p=Math.abs(p)*(a?1:-1)),s.diff=h,h*=i.touchRatio,a&&(h=-h,p=-p);const v=r.touchesDirection;r.swipeDirection=h>0?"prev":"next",r.touchesDirection=p>0?"prev":"next";const g=r.params.loop&&!i.cssMode,y=r.touchesDirection==="next"&&r.allowSlideNext||r.touchesDirection==="prev"&&r.allowSlidePrev;if(!n.isMoved){if(g&&y&&r.loopFix({direction:r.swipeDirection}),n.startTranslate=r.getTranslate(),r.setTransition(0),r.animating){const C=new window.CustomEvent("transitionend",{bubbles:!0,cancelable:!0,detail:{bySwiperTouchMove:!0}});r.wrapperEl.dispatchEvent(C)}n.allowMomentumBounce=!1,i.grabCursor&&(r.allowSlideNext===!0||r.allowSlidePrev===!0)&&r.setGrabCursor(!0),r.emit("sliderFirstMove",l)}let x;if(new Date().getTime(),n.isMoved&&n.allowThresholdMove&&v!==r.touchesDirection&&g&&y&&Math.abs(h)>=1){Object.assign(s,{startX:c,startY:d,currentX:c,currentY:d,startTranslate:n.currentTranslate}),n.loopSwapReset=!0,n.startTranslate=n.currentTranslate;return}r.emit("sliderMove",l),n.isMoved=!0,n.currentTranslate=h+n.startTranslate;let S=!0,T=i.resistanceRatio;if(i.touchReleaseOnEdges&&(T=0),h>0?(g&&y&&!x&&n.allowThresholdMove&&n.currentTranslate>(i.centeredSlides?r.minTranslate()-r.slidesSizesGrid[r.activeIndex+1]-(i.slidesPerView!=="auto"&&r.slides.length-i.slidesPerView>=2?r.slidesSizesGrid[r.activeIndex+1]+r.params.spaceBetween:0)-r.params.spaceBetween:r.minTranslate())&&r.loopFix({direction:"prev",setTranslate:!0,activeSlideIndex:0}),n.currentTranslate>r.minTranslate()&&(S=!1,i.resistance&&(n.currentTranslate=r.minTranslate()-1+(-r.minTranslate()+n.startTranslate+h)**T))):h<0&&(g&&y&&!x&&n.allowThresholdMove&&n.currentTranslate<(i.centeredSlides?r.maxTranslate()+r.slidesSizesGrid[r.slidesSizesGrid.length-1]+r.params.spaceBetween+(i.slidesPerView!=="auto"&&r.slides.length-i.slidesPerView>=2?r.slidesSizesGrid[r.slidesSizesGrid.length-1]+r.params.spaceBetween:0):r.maxTranslate())&&r.loopFix({direction:"next",setTranslate:!0,activeSlideIndex:r.slides.length-(i.slidesPerView==="auto"?r.slidesPerViewDynamic():Math.ceil(parseFloat(i.slidesPerView,10)))}),n.currentTranslaten.startTranslate&&(n.currentTranslate=n.startTranslate),!r.allowSlidePrev&&!r.allowSlideNext&&(n.currentTranslate=n.startTranslate),i.threshold>0)if(Math.abs(h)>i.threshold||n.allowThresholdMove){if(!n.allowThresholdMove){n.allowThresholdMove=!0,s.startX=s.currentX,s.startY=s.currentY,n.currentTranslate=n.startTranslate,s.diff=r.isHorizontal()?s.currentX-s.startX:s.currentY-s.startY;return}}else{n.currentTranslate=n.startTranslate;return}!i.followFinger||i.cssMode||((i.freeMode&&i.freeMode.enabled&&r.freeMode||i.watchSlidesProgress)&&(r.updateActiveIndex(),r.updateSlidesClasses()),i.freeMode&&i.freeMode.enabled&&r.freeMode&&r.freeMode.onTouchMove(),r.updateProgress(n.currentTranslate),r.setTranslate(n.currentTranslate))}function iD(t){const e=this,r=e.touchEventsData;let n=t;n.originalEvent&&(n=n.originalEvent);let i;if(n.type==="touchend"||n.type==="touchcancel"){if(i=[...n.changedTouches].filter(T=>T.identifier===r.touchId)[0],!i||i.identifier!==r.touchId)return}else{if(r.touchId!==null||n.pointerId!==r.pointerId)return;i=n}if(["pointercancel","pointerout","pointerleave","contextmenu"].includes(n.type)&&!(["pointercancel","contextmenu"].includes(n.type)&&(e.browser.isSafari||e.browser.isWebView)))return;r.pointerId=null,r.touchId=null;const{params:a,touches:o,rtlTranslate:l,slidesGrid:u,enabled:c}=e;if(!c||!a.simulateTouch&&n.pointerType==="mouse")return;if(r.allowTouchCallbacks&&e.emit("touchEnd",n),r.allowTouchCallbacks=!1,!r.isTouched){r.isMoved&&a.grabCursor&&e.setGrabCursor(!1),r.isMoved=!1,r.startMoving=!1;return}a.grabCursor&&r.isMoved&&r.isTouched&&(e.allowSlideNext===!0||e.allowSlidePrev===!0)&&e.setGrabCursor(!1);const d=kc(),f=d-r.touchStartTime;if(e.allowClick){const T=n.path||n.composedPath&&n.composedPath();e.updateClickedSlide(T&&T[0]||n.target,T),e.emit("tap click",n),f<300&&d-r.lastClickTime<300&&e.emit("doubleTap doubleClick",n)}if(r.lastClickTime=kc(),Gh(()=>{e.destroyed||(e.allowClick=!0)}),!r.isTouched||!r.isMoved||!e.swipeDirection||o.diff===0&&!r.loopSwapReset||r.currentTranslate===r.startTranslate&&!r.loopSwapReset){r.isTouched=!1,r.isMoved=!1,r.startMoving=!1;return}r.isTouched=!1,r.isMoved=!1,r.startMoving=!1;let m;if(a.followFinger?m=l?e.translate:-e.translate:m=-r.currentTranslate,a.cssMode)return;if(a.freeMode&&a.freeMode.enabled){e.freeMode.onTouchEnd({currentPos:m});return}const h=m>=-e.maxTranslate()&&!e.params.loop;let p=0,v=e.slidesSizesGrid[0];for(let T=0;T=u[T]&&m=u[T])&&(p=T,v=u[u.length-1]-u[u.length-2])}let g=null,y=null;a.rewind&&(e.isBeginning?y=a.virtual&&a.virtual.enabled&&e.virtual?e.virtual.slides.length-1:e.slides.length-1:e.isEnd&&(g=0));const x=(m-u[p])/v,S=pa.longSwipesMs){if(!a.longSwipes){e.slideTo(e.activeIndex);return}e.swipeDirection==="next"&&(x>=a.longSwipesRatio?e.slideTo(a.rewind&&e.isEnd?g:p+S):e.slideTo(p)),e.swipeDirection==="prev"&&(x>1-a.longSwipesRatio?e.slideTo(p+S):y!==null&&x<0&&Math.abs(x)>a.longSwipesRatio?e.slideTo(y):e.slideTo(p))}else{if(!a.shortSwipes){e.slideTo(e.activeIndex);return}e.navigation&&(n.target===e.navigation.nextEl||n.target===e.navigation.prevEl)?n.target===e.navigation.nextEl?e.slideTo(p+S):e.slideTo(p):(e.swipeDirection==="next"&&e.slideTo(g!==null?g:p+S),e.swipeDirection==="prev"&&e.slideTo(y!==null?y:p))}}function iv(){const t=this,{params:e,el:r}=t;if(r&&r.offsetWidth===0)return;e.breakpoints&&t.setBreakpoint();const{allowSlideNext:n,allowSlidePrev:i,snapGrid:s}=t,a=t.virtual&&t.params.virtual.enabled;t.allowSlideNext=!0,t.allowSlidePrev=!0,t.updateSize(),t.updateSlides(),t.updateSlidesClasses();const o=a&&e.loop;(e.slidesPerView==="auto"||e.slidesPerView>1)&&t.isEnd&&!t.isBeginning&&!t.params.centeredSlides&&!o?t.slideTo(t.slides.length-1,0,!1,!0):t.params.loop&&!a?t.slideToLoop(t.realIndex,0,!1,!0):t.slideTo(t.activeIndex,0,!1,!0),t.autoplay&&t.autoplay.running&&t.autoplay.paused&&(clearTimeout(t.autoplay.resizeTimeout),t.autoplay.resizeTimeout=setTimeout(()=>{t.autoplay&&t.autoplay.running&&t.autoplay.paused&&t.autoplay.resume()},500)),t.allowSlidePrev=i,t.allowSlideNext=n,t.params.watchOverflow&&s!==t.snapGrid&&t.checkOverflow()}function sD(t){const e=this;e.enabled&&(e.allowClick||(e.params.preventClicks&&t.preventDefault(),e.params.preventClicksPropagation&&e.animating&&(t.stopPropagation(),t.stopImmediatePropagation())))}function aD(){const t=this,{wrapperEl:e,rtlTranslate:r,enabled:n}=t;if(!n)return;t.previousTranslate=t.translate,t.isHorizontal()?t.translate=-e.scrollLeft:t.translate=-e.scrollTop,t.translate===0&&(t.translate=0),t.updateActiveIndex(),t.updateSlidesClasses();let i;const s=t.maxTranslate()-t.minTranslate();s===0?i=0:i=(t.translate-t.minTranslate())/s,i!==t.progress&&t.updateProgress(r?-t.translate:t.translate),t.emit("setTranslate",t.translate,!1)}function oD(t){const e=this;Du(e,t.target),!(e.params.cssMode||e.params.slidesPerView!=="auto"&&!e.params.autoHeight)&&e.update()}function lD(){const t=this;t.documentTouchHandlerProceeded||(t.documentTouchHandlerProceeded=!0,t.params.touchReleaseOnEdges&&(t.el.style.touchAction="auto"))}const JE=(t,e)=>{const r=$a(),{params:n,el:i,wrapperEl:s,device:a}=t,o=!!n.nested,l=e==="on"?"addEventListener":"removeEventListener",u=e;!i||typeof i=="string"||(r[l]("touchstart",t.onDocumentTouchStart,{passive:!1,capture:o}),i[l]("touchstart",t.onTouchStart,{passive:!1}),i[l]("pointerdown",t.onTouchStart,{passive:!1}),r[l]("touchmove",t.onTouchMove,{passive:!1,capture:o}),r[l]("pointermove",t.onTouchMove,{passive:!1,capture:o}),r[l]("touchend",t.onTouchEnd,{passive:!0}),r[l]("pointerup",t.onTouchEnd,{passive:!0}),r[l]("pointercancel",t.onTouchEnd,{passive:!0}),r[l]("touchcancel",t.onTouchEnd,{passive:!0}),r[l]("pointerout",t.onTouchEnd,{passive:!0}),r[l]("pointerleave",t.onTouchEnd,{passive:!0}),r[l]("contextmenu",t.onTouchEnd,{passive:!0}),(n.preventClicks||n.preventClicksPropagation)&&i[l]("click",t.onClick,!0),n.cssMode&&s[l]("scroll",t.onScroll),n.updateOnWindowResize?t[u](a.ios||a.android?"resize orientationchange observerUpdate":"resize observerUpdate",iv,!0):t[u]("observerUpdate",iv,!0),i[l]("load",t.onLoad,{capture:!0}))};function uD(){const t=this,{params:e}=t;t.onTouchStart=rD.bind(t),t.onTouchMove=nD.bind(t),t.onTouchEnd=iD.bind(t),t.onDocumentTouchStart=lD.bind(t),e.cssMode&&(t.onScroll=aD.bind(t)),t.onClick=sD.bind(t),t.onLoad=oD.bind(t),JE(t,"on")}function cD(){JE(this,"off")}var dD={attachEvents:uD,detachEvents:cD};const sv=(t,e)=>t.grid&&e.grid&&e.grid.rows>1;function fD(){const t=this,{realIndex:e,initialized:r,params:n,el:i}=t,s=n.breakpoints;if(!s||s&&Object.keys(s).length===0)return;const a=t.getBreakpoint(s,t.params.breakpointsBase,t.el);if(!a||t.currentBreakpoint===a)return;const l=(a in s?s[a]:void 0)||t.originalParams,u=sv(t,n),c=sv(t,l),d=t.params.grabCursor,f=l.grabCursor,m=n.enabled;u&&!c?(i.classList.remove(`${n.containerModifierClass}grid`,`${n.containerModifierClass}grid-column`),t.emitContainerClasses()):!u&&c&&(i.classList.add(`${n.containerModifierClass}grid`),(l.grid.fill&&l.grid.fill==="column"||!l.grid.fill&&n.grid.fill==="column")&&i.classList.add(`${n.containerModifierClass}grid-column`),t.emitContainerClasses()),d&&!f?t.unsetGrabCursor():!d&&f&&t.setGrabCursor(),["navigation","pagination","scrollbar"].forEach(x=>{if(typeof l[x]>"u")return;const S=n[x]&&n[x].enabled,T=l[x]&&l[x].enabled;S&&!T&&t[x].disable(),!S&&T&&t[x].enable()});const h=l.direction&&l.direction!==n.direction,p=n.loop&&(l.slidesPerView!==n.slidesPerView||h),v=n.loop;h&&r&&t.changeDirection(),Ir(t.params,l);const g=t.params.enabled,y=t.params.loop;Object.assign(t,{allowTouchMove:t.params.allowTouchMove,allowSlideNext:t.params.allowSlideNext,allowSlidePrev:t.params.allowSlidePrev}),m&&!g?t.disable():!m&&g&&t.enable(),t.currentBreakpoint=a,t.emit("_beforeBreakpoint",l),r&&(p?(t.loopDestroy(),t.loopCreate(e),t.updateSlides()):!v&&y?(t.loopCreate(e),t.updateSlides()):v&&!y&&t.loopDestroy()),t.emit("breakpoint",l)}function hD(t,e,r){if(e===void 0&&(e="window"),!t||e==="container"&&!r)return;let n=!1;const i=jr(),s=e==="window"?i.innerHeight:r.clientHeight,a=Object.keys(t).map(o=>{if(typeof o=="string"&&o.indexOf("@")===0){const l=parseFloat(o.substr(1));return{value:s*l,point:o}}return{value:o,point:o}});a.sort((o,l)=>parseInt(o.value,10)-parseInt(l.value,10));for(let o=0;o{typeof n=="object"?Object.keys(n).forEach(i=>{n[i]&&r.push(e+i)}):typeof n=="string"&&r.push(e+n)}),r}function gD(){const t=this,{classNames:e,params:r,rtl:n,el:i,device:s}=t,a=mD(["initialized",r.direction,{"free-mode":t.params.freeMode&&r.freeMode.enabled},{autoheight:r.autoHeight},{rtl:n},{grid:r.grid&&r.grid.rows>1},{"grid-column":r.grid&&r.grid.rows>1&&r.grid.fill==="column"},{android:s.android},{ios:s.ios},{"css-mode":r.cssMode},{centered:r.cssMode&&r.centeredSlides},{"watch-progress":r.watchSlidesProgress}],r.containerModifierClass);e.push(...a),i.classList.add(...e),t.emitContainerClasses()}function vD(){const t=this,{el:e,classNames:r}=t;!e||typeof e=="string"||(e.classList.remove(...r),t.emitContainerClasses())}var yD={addClasses:gD,removeClasses:vD};function xD(){const t=this,{isLocked:e,params:r}=t,{slidesOffsetBefore:n}=r;if(n){const i=t.slides.length-1,s=t.slidesGrid[i]+t.slidesSizesGrid[i]+n*2;t.isLocked=t.size>s}else t.isLocked=t.snapGrid.length===1;r.allowSlideNext===!0&&(t.allowSlideNext=!t.isLocked),r.allowSlidePrev===!0&&(t.allowSlidePrev=!t.isLocked),e&&e!==t.isLocked&&(t.isEnd=!1),e!==t.isLocked&&t.emit(t.isLocked?"lock":"unlock")}var SD={checkOverflow:xD},Hh={init:!0,direction:"horizontal",oneWayMovement:!1,swiperElementNodeName:"SWIPER-CONTAINER",touchEventsTarget:"wrapper",initialSlide:0,speed:300,cssMode:!1,updateOnWindowResize:!0,resizeObserver:!0,nested:!1,createElements:!1,eventsPrefix:"swiper",enabled:!0,focusableElements:"input, select, option, textarea, button, video, label",width:null,height:null,preventInteractionOnTransition:!1,userAgent:null,url:null,edgeSwipeDetection:!1,edgeSwipeThreshold:20,autoHeight:!1,setWrapperSize:!1,virtualTranslate:!1,effect:"slide",breakpoints:void 0,breakpointsBase:"window",spaceBetween:0,slidesPerView:1,slidesPerGroup:1,slidesPerGroupSkip:0,slidesPerGroupAuto:!1,centeredSlides:!1,centeredSlidesBounds:!1,slidesOffsetBefore:0,slidesOffsetAfter:0,normalizeSlideIndex:!0,centerInsufficientSlides:!1,watchOverflow:!0,roundLengths:!1,touchRatio:1,touchAngle:45,simulateTouch:!0,shortSwipes:!0,longSwipes:!0,longSwipesRatio:.5,longSwipesMs:300,followFinger:!0,allowTouchMove:!0,threshold:5,touchMoveStopPropagation:!1,touchStartPreventDefault:!0,touchStartForcePreventDefault:!1,touchReleaseOnEdges:!1,uniqueNavElements:!0,resistance:!0,resistanceRatio:.85,watchSlidesProgress:!1,grabCursor:!1,preventClicks:!0,preventClicksPropagation:!0,slideToClickedSlide:!1,loop:!1,loopAddBlankSlides:!0,loopAdditionalSlides:0,loopPreventsSliding:!0,rewind:!1,allowSlidePrev:!0,allowSlideNext:!0,swipeHandler:null,noSwiping:!0,noSwipingClass:"swiper-no-swiping",noSwipingSelector:null,passiveListeners:!0,maxBackfaceHiddenSlides:10,containerModifierClass:"swiper-",slideClass:"swiper-slide",slideBlankClass:"swiper-slide-blank",slideActiveClass:"swiper-slide-active",slideVisibleClass:"swiper-slide-visible",slideFullyVisibleClass:"swiper-slide-fully-visible",slideNextClass:"swiper-slide-next",slidePrevClass:"swiper-slide-prev",wrapperClass:"swiper-wrapper",lazyPreloaderClass:"swiper-lazy-preloader",lazyPreloadPrevNext:0,runCallbacksOnInit:!0,_emitClasses:!1};function ED(t,e){return function(n){n===void 0&&(n={});const i=Object.keys(n)[0],s=n[i];if(typeof s!="object"||s===null){Ir(e,n);return}if(t[i]===!0&&(t[i]={enabled:!0}),i==="navigation"&&t[i]&&t[i].enabled&&!t[i].prevEl&&!t[i].nextEl&&(t[i].auto=!0),["pagination","scrollbar"].indexOf(i)>=0&&t[i]&&t[i].enabled&&!t[i].el&&(t[i].auto=!0),!(i in t&&"enabled"in s)){Ir(e,n);return}typeof t[i]=="object"&&!("enabled"in t[i])&&(t[i].enabled=!0),t[i]||(t[i]={enabled:!1}),Ir(e,n)}}const gf={eventsEmitter:yk,update:Rk,translate:Mk,transition:Bk,slide:Kk,loop:Zk,grabCursor:eD,events:dD,breakpoints:pD,checkOverflow:SD,classes:yD},vf={};let bm=class qn{constructor(){let e,r;for(var n=arguments.length,i=new Array(n),s=0;s1){const c=[];return a.querySelectorAll(r.el).forEach(d=>{const f=Ir({},r,{el:d});c.push(new qn(f))}),c}const o=this;o.__swiper__=!0,o.support=XE(),o.device=ZE({userAgent:r.userAgent}),o.browser=mk(),o.eventsListeners={},o.eventsAnyListeners=[],o.modules=[...o.__modules__],r.modules&&Array.isArray(r.modules)&&o.modules.push(...r.modules);const l={};o.modules.forEach(c=>{c({params:r,swiper:o,extendParams:ED(r,l),on:o.on.bind(o),once:o.once.bind(o),off:o.off.bind(o),emit:o.emit.bind(o)})});const u=Ir({},Hh,l);return o.params=Ir({},u,vf,r),o.originalParams=Ir({},o.params),o.passedParams=Ir({},r),o.params&&o.params.on&&Object.keys(o.params.on).forEach(c=>{o.on(c,o.params.on[c])}),o.params&&o.params.onAny&&o.onAny(o.params.onAny),Object.assign(o,{enabled:o.params.enabled,el:e,classNames:[],slides:[],slidesGrid:[],snapGrid:[],slidesSizesGrid:[],isHorizontal(){return o.params.direction==="horizontal"},isVertical(){return o.params.direction==="vertical"},activeIndex:0,realIndex:0,isBeginning:!0,isEnd:!1,translate:0,previousTranslate:0,progress:0,velocity:0,animating:!1,cssOverflowAdjustment(){return Math.trunc(this.translate/2**23)*2**23},allowSlideNext:o.params.allowSlideNext,allowSlidePrev:o.params.allowSlidePrev,touchEventsData:{isTouched:void 0,isMoved:void 0,allowTouchCallbacks:void 0,touchStartTime:void 0,isScrolling:void 0,currentTranslate:void 0,startTranslate:void 0,allowThresholdMove:void 0,focusableElements:o.params.focusableElements,lastClickTime:0,clickTimeout:void 0,velocities:[],allowMomentumBounce:void 0,startMoving:void 0,pointerId:null,touchId:null},allowClick:!0,allowTouchMove:o.params.allowTouchMove,touches:{startX:0,startY:0,currentX:0,currentY:0,diff:0},imagesToLoad:[],imagesLoaded:0}),o.emit("_swiper"),o.params.init&&o.init(),o}getDirectionLabel(e){return this.isHorizontal()?e:{width:"height","margin-top":"margin-left","margin-bottom ":"margin-right","margin-left":"margin-top","margin-right":"margin-bottom","padding-left":"padding-top","padding-right":"padding-bottom",marginRight:"marginBottom"}[e]}getSlideIndex(e){const{slidesEl:r,params:n}=this,i=In(r,`.${n.slideClass}, swiper-slide`),s=ev(i[0]);return ev(e)-s}getSlideIndexByData(e){return this.getSlideIndex(this.slides.filter(r=>r.getAttribute("data-swiper-slide-index")*1===e)[0])}recalcSlides(){const e=this,{slidesEl:r,params:n}=e;e.slides=In(r,`.${n.slideClass}, swiper-slide`)}enable(){const e=this;e.enabled||(e.enabled=!0,e.params.grabCursor&&e.setGrabCursor(),e.emit("enable"))}disable(){const e=this;e.enabled&&(e.enabled=!1,e.params.grabCursor&&e.unsetGrabCursor(),e.emit("disable"))}setProgress(e,r){const n=this;e=Math.min(Math.max(e,0),1);const i=n.minTranslate(),a=(n.maxTranslate()-i)*e+i;n.translateTo(a,typeof r>"u"?0:r),n.updateActiveIndex(),n.updateSlidesClasses()}emitContainerClasses(){const e=this;if(!e.params._emitClasses||!e.el)return;const r=e.el.className.split(" ").filter(n=>n.indexOf("swiper")===0||n.indexOf(e.params.containerModifierClass)===0);e.emit("_containerClasses",r.join(" "))}getSlideClasses(e){const r=this;return r.destroyed?"":e.className.split(" ").filter(n=>n.indexOf("swiper-slide")===0||n.indexOf(r.params.slideClass)===0).join(" ")}emitSlidesClasses(){const e=this;if(!e.params._emitClasses||!e.el)return;const r=[];e.slides.forEach(n=>{const i=e.getSlideClasses(n);r.push({slideEl:n,classNames:i}),e.emit("_slideClass",n,i)}),e.emit("_slideClasses",r)}slidesPerViewDynamic(e,r){e===void 0&&(e="current"),r===void 0&&(r=!1);const n=this,{params:i,slides:s,slidesGrid:a,slidesSizesGrid:o,size:l,activeIndex:u}=n;let c=1;if(typeof i.slidesPerView=="number")return i.slidesPerView;if(i.centeredSlides){let d=s[u]?Math.ceil(s[u].swiperSlideSize):0,f;for(let m=u+1;ml&&(f=!0));for(let m=u-1;m>=0;m-=1)s[m]&&!f&&(d+=s[m].swiperSlideSize,c+=1,d>l&&(f=!0))}else if(e==="current")for(let d=u+1;d=0;d-=1)a[u]-a[d]{a.complete&&Du(e,a)}),e.updateSize(),e.updateSlides(),e.updateProgress(),e.updateSlidesClasses();function i(){const a=e.rtlTranslate?e.translate*-1:e.translate,o=Math.min(Math.max(a,e.maxTranslate()),e.minTranslate());e.setTranslate(o),e.updateActiveIndex(),e.updateSlidesClasses()}let s;if(n.freeMode&&n.freeMode.enabled&&!n.cssMode)i(),n.autoHeight&&e.updateAutoHeight();else{if((n.slidesPerView==="auto"||n.slidesPerView>1)&&e.isEnd&&!n.centeredSlides){const a=e.virtual&&n.virtual.enabled?e.virtual.slides:e.slides;s=e.slideTo(a.length-1,0,!1,!0)}else s=e.slideTo(e.activeIndex,0,!1,!0);s||i()}n.watchOverflow&&r!==e.snapGrid&&e.checkOverflow(),e.emit("update")}changeDirection(e,r){r===void 0&&(r=!0);const n=this,i=n.params.direction;return e||(e=i==="horizontal"?"vertical":"horizontal"),e===i||e!=="horizontal"&&e!=="vertical"||(n.el.classList.remove(`${n.params.containerModifierClass}${i}`),n.el.classList.add(`${n.params.containerModifierClass}${e}`),n.emitContainerClasses(),n.params.direction=e,n.slides.forEach(s=>{e==="vertical"?s.style.width="":s.style.height=""}),n.emit("changeDirection"),r&&n.update()),n}changeLanguageDirection(e){const r=this;r.rtl&&e==="rtl"||!r.rtl&&e==="ltr"||(r.rtl=e==="rtl",r.rtlTranslate=r.params.direction==="horizontal"&&r.rtl,r.rtl?(r.el.classList.add(`${r.params.containerModifierClass}rtl`),r.el.dir="rtl"):(r.el.classList.remove(`${r.params.containerModifierClass}rtl`),r.el.dir="ltr"),r.update())}mount(e){const r=this;if(r.mounted)return!0;let n=e||r.params.el;if(typeof n=="string"&&(n=document.querySelector(n)),!n)return!1;n.swiper=r,n.parentNode&&n.parentNode.host&&n.parentNode.host.nodeName===r.params.swiperElementNodeName.toUpperCase()&&(r.isElement=!0);const i=()=>`.${(r.params.wrapperClass||"").trim().split(" ").join(".")}`;let a=n&&n.shadowRoot&&n.shadowRoot.querySelector?n.shadowRoot.querySelector(i()):In(n,i())[0];return!a&&r.params.createElements&&(a=Pc("div",r.params.wrapperClass),n.append(a),In(n,`.${r.params.slideClass}`).forEach(o=>{a.append(o)})),Object.assign(r,{el:n,wrapperEl:a,slidesEl:r.isElement&&!n.parentNode.host.slideSlots?n.parentNode.host:a,hostEl:r.isElement?n.parentNode.host:n,mounted:!0,rtl:n.dir.toLowerCase()==="rtl"||Ri(n,"direction")==="rtl",rtlTranslate:r.params.direction==="horizontal"&&(n.dir.toLowerCase()==="rtl"||Ri(n,"direction")==="rtl"),wrongRTL:Ri(a,"display")==="-webkit-box"}),!0}init(e){const r=this;if(r.initialized||r.mount(e)===!1)return r;r.emit("beforeInit"),r.params.breakpoints&&r.setBreakpoint(),r.addClasses(),r.updateSize(),r.updateSlides(),r.params.watchOverflow&&r.checkOverflow(),r.params.grabCursor&&r.enabled&&r.setGrabCursor(),r.params.loop&&r.virtual&&r.params.virtual.enabled?r.slideTo(r.params.initialSlide+r.virtual.slidesBefore,0,r.params.runCallbacksOnInit,!1,!0):r.slideTo(r.params.initialSlide,0,r.params.runCallbacksOnInit,!1,!0),r.params.loop&&r.loopCreate(),r.attachEvents();const i=[...r.el.querySelectorAll('[loading="lazy"]')];return r.isElement&&i.push(...r.hostEl.querySelectorAll('[loading="lazy"]')),i.forEach(s=>{s.complete?Du(r,s):s.addEventListener("load",a=>{Du(r,a.target)})}),zh(r),r.initialized=!0,zh(r),r.emit("init"),r.emit("afterInit"),r}destroy(e,r){e===void 0&&(e=!0),r===void 0&&(r=!0);const n=this,{params:i,el:s,wrapperEl:a,slides:o}=n;return typeof n.params>"u"||n.destroyed||(n.emit("beforeDestroy"),n.initialized=!1,n.detachEvents(),i.loop&&n.loopDestroy(),r&&(n.removeClasses(),s&&typeof s!="string"&&s.removeAttribute("style"),a&&a.removeAttribute("style"),o&&o.length&&o.forEach(l=>{l.classList.remove(i.slideVisibleClass,i.slideFullyVisibleClass,i.slideActiveClass,i.slideNextClass,i.slidePrevClass),l.removeAttribute("style"),l.removeAttribute("data-swiper-slide-index")})),n.emit("destroy"),Object.keys(n.eventsListeners).forEach(l=>{n.off(l)}),e!==!1&&(n.el&&typeof n.el!="string"&&(n.el.swiper=null),ik(n)),n.destroyed=!0),null}static extendDefaults(e){Ir(vf,e)}static get extendedDefaults(){return vf}static get defaults(){return Hh}static installModule(e){qn.prototype.__modules__||(qn.prototype.__modules__=[]);const r=qn.prototype.__modules__;typeof e=="function"&&r.indexOf(e)<0&&r.push(e)}static use(e){return Array.isArray(e)?(e.forEach(r=>qn.installModule(r)),qn):(qn.installModule(e),qn)}};Object.keys(gf).forEach(t=>{Object.keys(gf[t]).forEach(e=>{bm.prototype[e]=gf[t][e]})});bm.use([gk,vk]);const eT=["eventsPrefix","injectStyles","injectStylesUrls","modules","init","_direction","oneWayMovement","swiperElementNodeName","touchEventsTarget","initialSlide","_speed","cssMode","updateOnWindowResize","resizeObserver","nested","focusableElements","_enabled","_width","_height","preventInteractionOnTransition","userAgent","url","_edgeSwipeDetection","_edgeSwipeThreshold","_freeMode","_autoHeight","setWrapperSize","virtualTranslate","_effect","breakpoints","breakpointsBase","_spaceBetween","_slidesPerView","maxBackfaceHiddenSlides","_grid","_slidesPerGroup","_slidesPerGroupSkip","_slidesPerGroupAuto","_centeredSlides","_centeredSlidesBounds","_slidesOffsetBefore","_slidesOffsetAfter","normalizeSlideIndex","_centerInsufficientSlides","_watchOverflow","roundLengths","touchRatio","touchAngle","simulateTouch","_shortSwipes","_longSwipes","longSwipesRatio","longSwipesMs","_followFinger","allowTouchMove","_threshold","touchMoveStopPropagation","touchStartPreventDefault","touchStartForcePreventDefault","touchReleaseOnEdges","uniqueNavElements","_resistance","_resistanceRatio","_watchSlidesProgress","_grabCursor","preventClicks","preventClicksPropagation","_slideToClickedSlide","_loop","loopAdditionalSlides","loopAddBlankSlides","loopPreventsSliding","_rewind","_allowSlidePrev","_allowSlideNext","_swipeHandler","_noSwiping","noSwipingClass","noSwipingSelector","passiveListeners","containerModifierClass","slideClass","slideActiveClass","slideVisibleClass","slideFullyVisibleClass","slideNextClass","slidePrevClass","slideBlankClass","wrapperClass","lazyPreloaderClass","lazyPreloadPrevNext","runCallbacksOnInit","observer","observeParents","observeSlideChildren","a11y","_autoplay","_controller","coverflowEffect","cubeEffect","fadeEffect","flipEffect","creativeEffect","cardsEffect","hashNavigation","history","keyboard","mousewheel","_navigation","_pagination","parallax","_scrollbar","_thumbs","virtual","zoom","control"];function ws(t){return typeof t=="object"&&t!==null&&t.constructor&&Object.prototype.toString.call(t).slice(8,-1)==="Object"&&!t.__swiper__}function ca(t,e){const r=["__proto__","constructor","prototype"];Object.keys(e).filter(n=>r.indexOf(n)<0).forEach(n=>{typeof t[n]>"u"?t[n]=e[n]:ws(e[n])&&ws(t[n])&&Object.keys(e[n]).length>0?e[n].__swiper__?t[n]=e[n]:ca(t[n],e[n]):t[n]=e[n]})}function tT(t){return t===void 0&&(t={}),t.navigation&&typeof t.navigation.nextEl>"u"&&typeof t.navigation.prevEl>"u"}function rT(t){return t===void 0&&(t={}),t.pagination&&typeof t.pagination.el>"u"}function nT(t){return t===void 0&&(t={}),t.scrollbar&&typeof t.scrollbar.el>"u"}function iT(t){t===void 0&&(t="");const e=t.split(" ").map(n=>n.trim()).filter(n=>!!n),r=[];return e.forEach(n=>{r.indexOf(n)<0&&r.push(n)}),r.join(" ")}function TD(t){return t===void 0&&(t=""),t?t.includes("swiper-wrapper")?t:`swiper-wrapper ${t}`:"swiper-wrapper"}function wD(t){let{swiper:e,slides:r,passedParams:n,changedParams:i,nextEl:s,prevEl:a,scrollbarEl:o,paginationEl:l}=t;const u=i.filter(I=>I!=="children"&&I!=="direction"&&I!=="wrapperClass"),{params:c,pagination:d,navigation:f,scrollbar:m,virtual:h,thumbs:p}=e;let v,g,y,x,S,T,C,_;i.includes("thumbs")&&n.thumbs&&n.thumbs.swiper&&c.thumbs&&!c.thumbs.swiper&&(v=!0),i.includes("controller")&&n.controller&&n.controller.control&&c.controller&&!c.controller.control&&(g=!0),i.includes("pagination")&&n.pagination&&(n.pagination.el||l)&&(c.pagination||c.pagination===!1)&&d&&!d.el&&(y=!0),i.includes("scrollbar")&&n.scrollbar&&(n.scrollbar.el||o)&&(c.scrollbar||c.scrollbar===!1)&&m&&!m.el&&(x=!0),i.includes("navigation")&&n.navigation&&(n.navigation.prevEl||a)&&(n.navigation.nextEl||s)&&(c.navigation||c.navigation===!1)&&f&&!f.prevEl&&!f.nextEl&&(S=!0);const b=I=>{e[I]&&(e[I].destroy(),I==="navigation"?(e.isElement&&(e[I].prevEl.remove(),e[I].nextEl.remove()),c[I].prevEl=void 0,c[I].nextEl=void 0,e[I].prevEl=void 0,e[I].nextEl=void 0):(e.isElement&&e[I].el.remove(),c[I].el=void 0,e[I].el=void 0))};i.includes("loop")&&e.isElement&&(c.loop&&!n.loop?T=!0:!c.loop&&n.loop?C=!0:_=!0),u.forEach(I=>{if(ws(c[I])&&ws(n[I]))Object.assign(c[I],n[I]),(I==="navigation"||I==="pagination"||I==="scrollbar")&&"enabled"in n[I]&&!n[I].enabled&&b(I);else{const A=n[I];(A===!0||A===!1)&&(I==="navigation"||I==="pagination"||I==="scrollbar")?A===!1&&b(I):c[I]=n[I]}}),u.includes("controller")&&!g&&e.controller&&e.controller.control&&c.controller&&c.controller.control&&(e.controller.control=c.controller.control),i.includes("children")&&r&&h&&c.virtual.enabled?(h.slides=r,h.update(!0)):i.includes("virtual")&&h&&c.virtual.enabled&&(r&&(h.slides=r),h.update(!0)),i.includes("children")&&r&&c.loop&&(_=!0),v&&p.init()&&p.update(!0),g&&(e.controller.control=c.controller.control),y&&(e.isElement&&(!l||typeof l=="string")&&(l=document.createElement("div"),l.classList.add("swiper-pagination"),l.part.add("pagination"),e.el.appendChild(l)),l&&(c.pagination.el=l),d.init(),d.render(),d.update()),x&&(e.isElement&&(!o||typeof o=="string")&&(o=document.createElement("div"),o.classList.add("swiper-scrollbar"),o.part.add("scrollbar"),e.el.appendChild(o)),o&&(c.scrollbar.el=o),m.init(),m.updateSize(),m.setTranslate()),S&&(e.isElement&&((!s||typeof s=="string")&&(s=document.createElement("div"),s.classList.add("swiper-button-next"),s.innerHTML=e.hostEl.constructor.nextButtonSvg,s.part.add("button-next"),e.el.appendChild(s)),(!a||typeof a=="string")&&(a=document.createElement("div"),a.classList.add("swiper-button-prev"),a.innerHTML=e.hostEl.constructor.prevButtonSvg,a.part.add("button-prev"),e.el.appendChild(a))),s&&(c.navigation.nextEl=s),a&&(c.navigation.prevEl=a),f.init(),f.update()),i.includes("allowSlideNext")&&(e.allowSlideNext=n.allowSlideNext),i.includes("allowSlidePrev")&&(e.allowSlidePrev=n.allowSlidePrev),i.includes("direction")&&e.changeDirection(n.direction,!1),(T||_)&&e.loopDestroy(),(C||_)&&e.loopCreate(),e.update()}function bD(t,e){t===void 0&&(t={}),e===void 0&&(e=!0);const r={on:{}},n={},i={};ca(r,Hh),r._emitClasses=!0,r.init=!1;const s={},a=eT.map(l=>l.replace(/_/,"")),o=Object.assign({},t);return Object.keys(o).forEach(l=>{typeof t[l]>"u"||(a.indexOf(l)>=0?ws(t[l])?(r[l]={},i[l]={},ca(r[l],t[l]),ca(i[l],t[l])):(r[l]=t[l],i[l]=t[l]):l.search(/on[A-Z]/)===0&&typeof t[l]=="function"?e?n[`${l[2].toLowerCase()}${l.substr(3)}`]=t[l]:r.on[`${l[2].toLowerCase()}${l.substr(3)}`]=t[l]:s[l]=t[l])}),["navigation","pagination","scrollbar"].forEach(l=>{r[l]===!0&&(r[l]={}),r[l]===!1&&delete r[l]}),{params:r,passedParams:i,rest:s,events:n}}function LD(t,e){let{el:r,nextEl:n,prevEl:i,paginationEl:s,scrollbarEl:a,swiper:o}=t;tT(e)&&n&&i&&(o.params.navigation.nextEl=n,o.originalParams.navigation.nextEl=n,o.params.navigation.prevEl=i,o.originalParams.navigation.prevEl=i),rT(e)&&s&&(o.params.pagination.el=s,o.originalParams.pagination.el=s),nT(e)&&a&&(o.params.scrollbar.el=a,o.originalParams.scrollbar.el=a),o.init(r)}function AD(t,e,r,n,i){const s=[];if(!e)return s;const a=l=>{s.indexOf(l)<0&&s.push(l)};if(r&&n){const l=n.map(i),u=r.map(i);l.join("")!==u.join("")&&a("children"),n.length!==r.length&&a("children")}return eT.filter(l=>l[0]==="_").map(l=>l.replace(/_/,"")).forEach(l=>{if(l in t&&l in e)if(ws(t[l])&&ws(e[l])){const u=Object.keys(t[l]),c=Object.keys(e[l]);u.length!==c.length?a(l):(u.forEach(d=>{t[l][d]!==e[l][d]&&a(l)}),c.forEach(d=>{t[l][d]!==e[l][d]&&a(l)}))}else t[l]!==e[l]&&a(l)}),s}const _D=t=>{!t||t.destroyed||!t.params.virtual||t.params.virtual&&!t.params.virtual.enabled||(t.updateSlides(),t.updateProgress(),t.updateSlidesClasses(),t.parallax&&t.params.parallax&&t.params.parallax.enabled&&t.parallax.setTranslate())};function Oc(){return Oc=Object.assign?Object.assign.bind():function(t){for(var e=1;e{sT(r)?e.push(r):r.props&&r.props.children&&aT(r.props.children).forEach(n=>e.push(n))}),e}function CD(t){const e=[],r={"container-start":[],"container-end":[],"wrapper-start":[],"wrapper-end":[]};return ne.Children.toArray(t).forEach(n=>{if(sT(n))e.push(n);else if(n.props&&n.props.slot&&r[n.props.slot])r[n.props.slot].push(n);else if(n.props&&n.props.children){const i=aT(n.props.children);i.length>0?i.forEach(s=>e.push(s)):r["container-end"].push(n)}else r["container-end"].push(n)}),{slides:e,slots:r}}function RD(t,e,r){if(!r)return null;const n=c=>{let d=c;return c<0?d=e.length+c:d>=e.length&&(d=d-e.length),d},i=t.isHorizontal()?{[t.rtlTranslate?"right":"left"]:`${r.offset}px`}:{top:`${r.offset}px`},{from:s,to:a}=r,o=t.params.loop?-e.length:0,l=t.params.loop?e.length*2:e.length,u=[];for(let c=o;c=s&&c<=a&&u.push(e[n(c)]);return u.map((c,d)=>ne.cloneElement(c,{swiper:t,style:i,key:c.props.virtualIndex||c.key||`slide-${d}`}))}function _o(t,e){return typeof window>"u"?L.useEffect(t,e):L.useLayoutEffect(t,e)}const av=L.createContext(null),ID=L.createContext(null),oT=L.forwardRef(function(t,e){let{className:r,tag:n="div",wrapperTag:i="div",children:s,onSwiper:a,...o}=t===void 0?{}:t,l=!1;const[u,c]=L.useState("swiper"),[d,f]=L.useState(null),[m,h]=L.useState(!1),p=L.useRef(!1),v=L.useRef(null),g=L.useRef(null),y=L.useRef(null),x=L.useRef(null),S=L.useRef(null),T=L.useRef(null),C=L.useRef(null),_=L.useRef(null),{params:b,passedParams:I,rest:A,events:k}=bD(o),{slides:O,slots:P}=CD(s),G=()=>{h(!m)};Object.assign(b.on,{_containerClasses(F,j){c(j)}});const K=()=>{Object.assign(b.on,k),l=!0;const F={...b};if(delete F.wrapperClass,g.current=new bm(F),g.current.virtual&&g.current.params.virtual.enabled){g.current.virtual.slides=O;const j={cache:!1,slides:O,renderExternal:f,renderExternalUpdate:!1};ca(g.current.params.virtual,j),ca(g.current.originalParams.virtual,j)}};v.current||K(),g.current&&g.current.on("_beforeBreakpoint",G);const H=()=>{l||!k||!g.current||Object.keys(k).forEach(F=>{g.current.on(F,k[F])})},se=()=>{!k||!g.current||Object.keys(k).forEach(F=>{g.current.off(F,k[F])})};L.useEffect(()=>()=>{g.current&&g.current.off("_beforeBreakpoint",G)}),L.useEffect(()=>{!p.current&&g.current&&(g.current.emitSlidesClasses(),p.current=!0)}),_o(()=>{if(e&&(e.current=v.current),!!v.current)return g.current.destroyed&&K(),LD({el:v.current,nextEl:S.current,prevEl:T.current,paginationEl:C.current,scrollbarEl:_.current,swiper:g.current},b),a&&!g.current.destroyed&&a(g.current),()=>{g.current&&!g.current.destroyed&&g.current.destroy(!0,!1)}},[]),_o(()=>{H();const F=AD(I,y.current,O,x.current,j=>j.key);return y.current=I,x.current=O,F.length&&g.current&&!g.current.destroyed&&wD({swiper:g.current,slides:O,passedParams:I,changedParams:F,nextEl:S.current,prevEl:T.current,scrollbarEl:_.current,paginationEl:C.current}),()=>{se()}}),_o(()=>{_D(g.current)},[d]);function W(){return b.virtual?RD(g.current,O,d):O.map((F,j)=>ne.cloneElement(F,{swiper:g.current,swiperSlideIndex:j}))}return ne.createElement(n,Oc({ref:v,className:iT(`${u}${r?` ${r}`:""}`)},A),ne.createElement(ID.Provider,{value:g.current},P["container-start"],ne.createElement(i,{className:TD(b.wrapperClass)},P["wrapper-start"],W(),P["wrapper-end"]),tT(b)&&ne.createElement(ne.Fragment,null,ne.createElement("div",{ref:T,className:"swiper-button-prev"}),ne.createElement("div",{ref:S,className:"swiper-button-next"})),nT(b)&&ne.createElement("div",{ref:_,className:"swiper-scrollbar"}),rT(b)&&ne.createElement("div",{ref:C,className:"swiper-pagination"}),P["container-end"]))});oT.displayName="Swiper";const lT=L.forwardRef(function(t,e){let{tag:r="div",children:n,className:i="",swiper:s,zoom:a,lazy:o,virtualIndex:l,swiperSlideIndex:u,...c}=t===void 0?{}:t;const d=L.useRef(null),[f,m]=L.useState("swiper-slide"),[h,p]=L.useState(!1);function v(S,T,C){T===d.current&&m(C)}_o(()=>{if(typeof u<"u"&&(d.current.swiperSlideIndex=u),e&&(e.current=d.current),!(!d.current||!s)){if(s.destroyed){f!=="swiper-slide"&&m("swiper-slide");return}return s.on("_slideClass",v),()=>{s&&s.off("_slideClass",v)}}}),_o(()=>{s&&d.current&&!s.destroyed&&m(s.getSlideClasses(d.current))},[s]);const g={isActive:f.indexOf("swiper-slide-active")>=0,isVisible:f.indexOf("swiper-slide-visible")>=0,isPrev:f.indexOf("swiper-slide-prev")>=0,isNext:f.indexOf("swiper-slide-next")>=0},y=()=>typeof n=="function"?n(g):n,x=()=>{p(!0)};return ne.createElement(r,Oc({ref:d,className:iT(`${f}${i?` ${i}`:""}`),"data-swiper-slide-index":l,onLoad:x},c),a&&ne.createElement(av.Provider,{value:g},ne.createElement("div",{className:"swiper-zoom-container","data-swiper-zoom":typeof a=="number"?a:void 0},y(),o&&!h&&ne.createElement("div",{className:"swiper-lazy-preloader"}))),!a&&ne.createElement(av.Provider,{value:g},y(),o&&!h&&ne.createElement("div",{className:"swiper-lazy-preloader"})))});lT.displayName="SwiperSlide";const kD=({media:t})=>{const[e,r]=L.useState(null),[n,i]=L.useState(!1),s=L.useRef(!1),a=Br(),o=()=>{s.current=!0;const c=setTimeout(()=>{s.current&&i(!0)},500);r(c)},l=()=>{s.current=!1,e&&clearTimeout(e),i(!1)},u=()=>{a(`/watch/${t.type}/${t.id}`)};return E.jsxs("article",{onMouseEnter:o,onMouseLeave:l,onClick:u,children:[E.jsx("img",{src:`${t.images.banner}`,alt:t.serie_title||t.title,className:"w-auto max-w-none h-48 object-cover rounded-md select-none"}),t.images.logo?E.jsx("img",{src:`${t.images.logo}`,alt:t.serie_title||t.title,className:"absolute bottom-1 left-1 w-1/2 h-12 object-contain rounded-md select-none"}):E.jsx("h3",{className:"absolute bottom-1 left-1 bg-black bg-opacity-50 text-white text-xs p-1 rounded-md select-none",children:t.serie_title||t.title}),E.jsx("section",{className:`absolute bg-neutral-800 bg-opacity-50 w-full z-10 bottom-0 pointer-events-none ${n?"opacity-100":"opacity-0"} transition-opacity duration-300`,children:E.jsxs("section",{className:"w-full h-full bg-black bg-opacity-75 p-4 flex flex-col gap-2",children:[E.jsx("h3",{children:t.serie_title||t.title}),E.jsxs("section",{className:"flex flex-col gap-1",children:[E.jsxs("h2",{children:["Genres: ",t.genres.map((c,d)=>E.jsxs(E.Fragment,{children:[E.jsx("span",{children:c},d),d!==t.genres.length-1&&E.jsx("span",{children:" • "})]}))]}),E.jsxs("h2",{children:["Note: ",(+t.note).toFixed(2),"/10"]}),E.jsxs("h2",{children:["Durée: ",t.duration,t.type==="serie"?" episodes":""]})]})]})})]})};function DD(t,e,r,n){return t.params.createElements&&Object.keys(n).forEach(i=>{if(!r[i]&&r.auto===!0){let s=In(t.el,`.${n[i]}`)[0];s||(s=Pc("div",n[i]),s.className=n[i],t.el.append(s)),r[i]=s,e[i]=s}}),r}function PD(t){let{swiper:e,extendParams:r,on:n,emit:i}=t;r({navigation:{nextEl:null,prevEl:null,hideOnClick:!1,disabledClass:"swiper-button-disabled",hiddenClass:"swiper-button-hidden",lockClass:"swiper-button-lock",navigationDisabledClass:"swiper-navigation-disabled"}}),e.navigation={nextEl:null,prevEl:null};function s(h){let p;return h&&typeof h=="string"&&e.isElement&&(p=e.el.querySelector(h),p)?p:(h&&(typeof h=="string"&&(p=[...document.querySelectorAll(h)]),e.params.uniqueNavElements&&typeof h=="string"&&p&&p.length>1&&e.el.querySelectorAll(h).length===1?p=e.el.querySelector(h):p&&p.length===1&&(p=p[0])),h&&!p?h:p)}function a(h,p){const v=e.params.navigation;h=Hn(h),h.forEach(g=>{g&&(g.classList[p?"add":"remove"](...v.disabledClass.split(" ")),g.tagName==="BUTTON"&&(g.disabled=p),e.params.watchOverflow&&e.enabled&&g.classList[e.isLocked?"add":"remove"](v.lockClass))})}function o(){const{nextEl:h,prevEl:p}=e.navigation;if(e.params.loop){a(p,!1),a(h,!1);return}a(p,e.isBeginning&&!e.params.rewind),a(h,e.isEnd&&!e.params.rewind)}function l(h){h.preventDefault(),!(e.isBeginning&&!e.params.loop&&!e.params.rewind)&&(e.slidePrev(),i("navigationPrev"))}function u(h){h.preventDefault(),!(e.isEnd&&!e.params.loop&&!e.params.rewind)&&(e.slideNext(),i("navigationNext"))}function c(){const h=e.params.navigation;if(e.params.navigation=DD(e,e.originalParams.navigation,e.params.navigation,{nextEl:"swiper-button-next",prevEl:"swiper-button-prev"}),!(h.nextEl||h.prevEl))return;let p=s(h.nextEl),v=s(h.prevEl);Object.assign(e.navigation,{nextEl:p,prevEl:v}),p=Hn(p),v=Hn(v);const g=(y,x)=>{y&&y.addEventListener("click",x==="next"?u:l),!e.enabled&&y&&y.classList.add(...h.lockClass.split(" "))};p.forEach(y=>g(y,"next")),v.forEach(y=>g(y,"prev"))}function d(){let{nextEl:h,prevEl:p}=e.navigation;h=Hn(h),p=Hn(p);const v=(g,y)=>{g.removeEventListener("click",y==="next"?u:l),g.classList.remove(...e.params.navigation.disabledClass.split(" "))};h.forEach(g=>v(g,"next")),p.forEach(g=>v(g,"prev"))}n("init",()=>{e.params.navigation.enabled===!1?m():(c(),o())}),n("toEdge fromEdge lock unlock",()=>{o()}),n("destroy",()=>{d()}),n("enable disable",()=>{let{nextEl:h,prevEl:p}=e.navigation;if(h=Hn(h),p=Hn(p),e.enabled){o();return}[...h,...p].filter(v=>!!v).forEach(v=>v.classList.add(e.params.navigation.lockClass))}),n("click",(h,p)=>{let{nextEl:v,prevEl:g}=e.navigation;v=Hn(v),g=Hn(g);const y=p.target;let x=g.includes(y)||v.includes(y);if(e.isElement&&!x){const S=p.path||p.composedPath&&p.composedPath();S&&(x=S.find(T=>v.includes(T)||g.includes(T)))}if(e.params.navigation.hideOnClick&&!x){if(e.pagination&&e.params.pagination&&e.params.pagination.clickable&&(e.pagination.el===y||e.pagination.el.contains(y)))return;let S;v.length?S=v[0].classList.contains(e.params.navigation.hiddenClass):g.length&&(S=g[0].classList.contains(e.params.navigation.hiddenClass)),i(S===!0?"navigationShow":"navigationHide"),[...v,...g].filter(T=>!!T).forEach(T=>T.classList.toggle(e.params.navigation.hiddenClass))}});const f=()=>{e.el.classList.remove(...e.params.navigation.navigationDisabledClass.split(" ")),c(),o()},m=()=>{e.el.classList.add(...e.params.navigation.navigationDisabledClass.split(" ")),d()};Object.assign(e.navigation,{enable:f,disable:m,update:o,init:c,destroy:d})}const Ca=({medias:t,index:e})=>{const[r,n]=L.useState(!1),[i,s]=L.useState(!1),a=L.useRef(null),o=()=>{s(!0)},l=()=>{n(!0)},u=()=>{n(!1)};return E.jsxs("div",{className:"relative w-full",onMouseEnter:l,onMouseLeave:u,children:[E.jsx(oT,{modules:[PD],spaceBetween:10,slidesPerView:"auto",direction:"horizontal",freeMode:!0,onSlideChange:o,className:"!overflow-visible !w-full",ref:a,children:t.map((c,d)=>E.jsx(E.Fragment,{children:c?E.jsx(lT,{className:"!w-fit",children:E.jsx(kD,{media:c})},d):null}))}),i&&E.jsxs(E.Fragment,{children:[E.jsx("button",{style:{zIndex:e+1},className:`absolute left-0 top-1/2 transform -translate-y-1/2 ${r?"opacity-100":"opacity-0"} transition-opacity duration-300`,onClick:()=>{var c,d;return(d=(c=a.current)==null?void 0:c.swiper)==null?void 0:d.slidePrev()},children:"❮ "}),E.jsx("button",{style:{zIndex:e+1},className:`absolute right-0 top-1/2 transform -translate-y-1/2 ${r?"opacity-100":"opacity-0"} transition-opacity duration-300`,onClick:()=>{var c,d;return(d=(c=a.current)==null?void 0:c.swiper)==null?void 0:d.slideNext()},children:"❯ "})]})]})},OD=()=>E.jsx("div",{children:E.jsx("h1",{children:"404 - Not Found!"})}),wl=L.createContext({searchTerm:"",setSearchTerm:t=>{}}),MD=({children:t})=>{const[e,r]=L.useState("");return E.jsx(wl.Provider,{value:{searchTerm:e,setSearchTerm:r},children:t})};function ND(){const[t,e]=L.useState(""),[r,n]=L.useState(!0),[i,s]=L.useState(!0),{searchTerm:a}=L.useContext(wl),{data:o,loading:l}=ur(t),{data:u,loading:c,interupt:d}=ur("/api/medias/home");L.useEffect(()=>{c||setTimeout(()=>{n(!1)},500)},[c]),L.useEffect(()=>{l?s(!0):setTimeout(()=>{s(!1)},500)},[l]),L.useEffect(()=>{if(a===""||a.length<3){e("");return}e(`/api/medias/search/home?search=${a}`)},[a]),L.useEffect(()=>{const p=new URLSearchParams(window.location.search).get("query");p&&(d(),e(`/api/medias/search/home?search=${p}`))},[]);const f=["continue_watching","latest","recently_added","top_rated","best_of_year","family","comedy","animated","action","thriller","horror","drama","western"],m={continue_watching:"Continue Watching",latest:"Latest",recently_added:"Recently Added",top_rated:"Top Rated",best_of_year:"Best of the Year",family:"Family",comedy:"Comedy",animated:"Animated",action:"Action",thriller:"Thriller",horror:"Horror",drama:"Drama",western:"Western"};return E.jsxs(E.Fragment,{children:[E.jsx(_s,{className:"h-screen top-0 fixed bg-[--black] w-screen transition-all duration-300 pointer-events-none z-50 "+(r||i?"opacity-100":"opacity-0")}),!o&&u&&u.code===201&&E.jsxs("section",{className:`flex flex-col gap-8 pb-8 ${r||i?"overflow-hidden":""}`,children:[E.jsx(_a,{media:u.data.main_media}),E.jsx("section",{className:"flex flex-col gap-8 pl-4 overflow-hidden",children:f.map((h,p)=>{var v;return((v=u.data[h])==null?void 0:v.length)>0&&E.jsxs("section",{className:"flex flex-col gap-4 ",style:{zIndex:f.length-p},children:[E.jsx("h3",{className:"text-3xl font-bold",children:m[h]}),E.jsx(Ca,{medias:u.data[h],index:f.length-p})]},h)})})]}),o&&o.data.main_media&&o.code===201&&E.jsxs("section",{className:`flex flex-col gap-8 pb-8 ${r||i?"overflow-hidden":""}`,children:[E.jsx(_a,{media:o.data.main_media}),E.jsx("section",{className:"flex flex-col gap-8 pl-4 overflow-hidden",children:E.jsxs("section",{className:"flex flex-col gap-4",children:[E.jsx("h3",{className:"text-3xl font-bold",children:"Results"}),E.jsx(Ca,{medias:o.data.medias,index:0})]})})]}),(o&&o.code!==201||u&&u.code!==201)&&E.jsx("section",{className:"h-screen flex justify-center items-center",children:E.jsx(OD,{})})]})}function FD(){const[t,e]=L.useState(""),[r,n]=L.useState(!0),{searchTerm:i}=L.useContext(wl),{data:s}=ur(t),{data:a,interupt:o}=ur("/api/medias/movies");L.useEffect(()=>{(a||s)&&setTimeout(()=>{n(!1)},500)},[a]),L.useEffect(()=>{if(i===""||i.length<3){e("");return}e(`/api/medias/search/movies?search=${i}`)},[i]),L.useEffect(()=>{const d=new URLSearchParams(window.location.search).get("query");d&&(o(),e(`/api/medias/search/movies?search=${d}`))},[]);const l=["continue_watching","latest","recently_added","top_rated","best_of_year","family","comedy","animated","action","thriller","horror","drama","western"],u={continue_watching:"Continue Watching",latest:"Latest",recently_added:"Recently Added",top_rated:"Top Rated",best_of_year:"Best of the Year",family:"Family",comedy:"Comedy",animated:"Animated",action:"Action",thriller:"Thriller",horror:"Horror",drama:"Drama",western:"Western"};return E.jsxs(E.Fragment,{children:[E.jsx(_s,{className:"h-screen top-0 fixed bg-[--black] w-screen transition-all duration-300 pointer-events-none z-50 "+(r?"opacity-100":"opacity-0")}),!s&&a&&E.jsxs("section",{className:`flex flex-col gap-8 pb-8 ${r?"overflow-hidden":""}`,children:[E.jsx(_a,{media:a.data.main_media}),E.jsx("section",{className:"flex flex-col gap-8 pl-4 overflow-hidden",children:l.map((c,d)=>{var f;return((f=a.data[c])==null?void 0:f.length)>0&&E.jsxs("section",{className:"flex flex-col gap-4 ",style:{zIndex:l.length-d},children:[E.jsx("h3",{className:"text-3xl font-bold",children:u[c]}),E.jsx(Ca,{medias:a.data[c],index:l.length-d})]},c)})})]}),s&&E.jsxs("section",{className:`flex flex-col gap-8 pb-8 ${r?"overflow-hidden":""}`,children:[E.jsx(_a,{media:s.data.main_media}),E.jsx("section",{className:"flex flex-col gap-8 pl-4 overflow-hidden",children:E.jsxs("section",{className:"flex flex-col gap-4",children:[E.jsx("h3",{className:"text-3xl font-bold",children:"Results"}),E.jsx(Ca,{medias:s.data.medias,index:0})]})})]})]})}function UD(){const[t,e]=L.useState(""),[r,n]=L.useState(!0),{searchTerm:i}=L.useContext(wl),{data:s}=ur(t),{data:a,loading:o,interupt:l}=ur("/api/medias/shows");L.useEffect(()=>{o||setTimeout(()=>{n(!1)},500)},[o]),L.useEffect(()=>{if(i===""||i.length<3){e("");return}e(`/api/medias/search/shows?search=${i}`)},[i]),L.useEffect(()=>{const f=new URLSearchParams(window.location.search).get("query");f&&(l(),e(`/api/medias/search/shows?search=${f}`))},[]);const u=["continue_watching","latest","recently_added","top_rated","best_of_year","family","comedy","animated","action","thriller","horror","drama","western"],c={continue_watching:"Continue Watching",latest:"Latest",recently_added:"Recently Added",top_rated:"Top Rated",best_of_year:"Best of the Year",family:"Family",comedy:"Comedy",animated:"Animated",action:"Action",thriller:"Thriller",horror:"Horror",drama:"Drama",western:"Western"};return E.jsxs(E.Fragment,{children:[E.jsx(_s,{className:"h-screen top-0 fixed bg-[--black] w-screen transition-all duration-300 pointer-events-none z-50 "+(r?"opacity-100":"opacity-0")}),!s&&a&&E.jsxs("section",{className:`flex flex-col gap-8 pb-8 ${r?"overflow-hidden":""}`,children:[E.jsx(_a,{media:a.data.main_media}),E.jsx("section",{className:"flex flex-col gap-8 pl-4 overflow-hidden",children:u.map((d,f)=>{var m;return((m=a.data[d])==null?void 0:m.length)>0&&E.jsxs("section",{className:"flex flex-col gap-4 ",style:{zIndex:u.length-f},children:[E.jsx("h3",{className:"text-3xl font-bold",children:c[d]}),E.jsx(Ca,{medias:a.data[d],index:u.length-f})]},d)})})]}),s&&E.jsxs("section",{className:`flex flex-col gap-8 pb-8 ${r?"overflow-hidden":""}`,children:[E.jsx(_a,{media:s.data.main_media}),E.jsx("section",{className:"flex flex-col gap-8 pl-4 overflow-hidden",children:E.jsxs("section",{className:"flex flex-col gap-4",children:[E.jsx("h3",{className:"text-3xl font-bold",children:"Results"}),E.jsx(Ca,{medias:s.data.medias,index:0})]})})]})]})}function BD(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var uT={exports:{}};(function(t,e){(function(r){var n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,u,c){if(c=c||{},l=l.trim(),u=u.trim(),!u){if(!c.alwaysNormalize)return l;var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse base URL.");return d.path=o.normalizePath(d.path),o.buildURLFromParts(d)}var f=o.parseURL(u);if(!f)throw new Error("Error trying to parse relative URL.");if(f.scheme)return c.alwaysNormalize?(f.path=o.normalizePath(f.path),o.buildURLFromParts(f)):u;var m=o.parseURL(l);if(!m)throw new Error("Error trying to parse base URL.");if(!m.netLoc&&m.path&&m.path[0]!=="/"){var h=i.exec(m.path);m.netLoc=h[1],m.path=h[2]}m.netLoc&&!m.path&&(m.path="/");var p={scheme:m.scheme,netLoc:f.netLoc,path:null,params:f.params,query:f.query,fragment:f.fragment};if(!f.netLoc&&(p.netLoc=m.netLoc,f.path[0]!=="/"))if(!f.path)p.path=m.path,f.params||(p.params=m.params,f.query||(p.query=m.query));else{var v=m.path,g=v.substring(0,v.lastIndexOf("/")+1)+f.path;p.path=o.normalizePath(g)}return p.path===null&&(p.path=c.alwaysNormalize?o.normalizePath(f.path):f.path),o.buildURLFromParts(p)},parseURL:function(l){var u=n.exec(l);return u?{scheme:u[1]||"",netLoc:u[2]||"",path:u[3]||"",params:u[4]||"",query:u[5]||"",fragment:u[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(s,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};t.exports=o})()})(uT);var Lm=uT.exports;function ov(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function jt(t){for(var e=1;e`):es}function WD(t,...e){e.forEach(function(r){Co[r]=t[r]?t[r].bind(t):HD(r)})}function KD(t,e){if(typeof console=="object"&&t===!0||typeof t=="object"){WD(t,"debug","log","info","warn","error");try{Co.log(`Debug logs enabled for "${e}" in hls.js version 1.5.15`)}catch{Co=Wh}}else Co=Wh}const U=Co,YD=/^(\d+)x(\d+)$/,lv=/(.+?)=(".*?"|.*?)(?:,|$)/g;class gt{constructor(e){typeof e=="string"&&(e=gt.parseAttrList(e)),It(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const r=parseInt(this[e],10);return r>Number.MAX_SAFE_INTEGER?1/0:r}hexadecimalInteger(e){if(this[e]){let r=(this[e]||"0x").slice(2);r=(r.length&1?"0":"")+r;const n=new Uint8Array(r.length/2);for(let i=0;iNumber.MAX_SAFE_INTEGER?1/0:r}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,r){const n=this[e];return n?parseFloat(n):r}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const r=YD.exec(this[e]);if(r!==null)return{width:parseInt(r[1],10),height:parseInt(r[2],10)}}static parseAttrList(e){let r;const n={},i='"';for(lv.lastIndex=0;(r=lv.exec(e))!==null;){let s=r[2];s.indexOf(i)===0&&s.lastIndexOf(i)===s.length-1&&(s=s.slice(1,-1));const a=r[1].trim();n[a]=s}return n}}function qD(t){return t!=="ID"&&t!=="CLASS"&&t!=="START-DATE"&&t!=="DURATION"&&t!=="END-DATE"&&t!=="END-ON-NEXT"}function XD(t){return t==="SCTE35-OUT"||t==="SCTE35-IN"}class cT{constructor(e,r){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,r){const n=r.attr;for(const i in n)if(Object.prototype.hasOwnProperty.call(e,i)&&e[i]!==n[i]){U.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=i;break}e=It(new gt({}),n,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const n=new Date(this.attr["END-DATE"]);pe(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(pe(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 isValid(){return!!this.id&&!this._badValueForSameId&&pe(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class Td{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}}}var Je={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class dT{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[Je.AUDIO]:null,[Je.VIDEO]:null,[Je.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,r){const n=e.split("@",2);let i;n.length===1?i=(r==null?void 0:r.byteRangeEndOffset)||0:i=parseInt(n[1]),this._byteRange=[i,parseInt(n[0])+i]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Lm.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class yf extends dT{constructor(e,r){super(r),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=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.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new Td,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 decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const r=this.levelkeys.identity;if(r)this._decryptdata=r.getDecryptData(this.sn);else{const n=Object.keys(this.levelkeys);if(n.length===1)return this._decryptdata=this.levelkeys[n[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!pe(this.programDateTime))return null;const e=pe(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){const r=Object.keys(this.levelkeys),n=r.length;if(n>1||n===1&&this.levelkeys[r[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const r=this.levelkeys[e];r&&!this._decryptdata&&(this._decryptdata=r.getDecryptData(this.sn))}}abortRequests(){var e,r;(e=this.loader)==null||e.abort(),(r=this.keyLoader)==null||r.abort()}setElementaryStreamInfo(e,r,n,i,s,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:r,endPTS:n,startDTS:i,endDTS:s,partial:a};return}l.startPTS=Math.min(l.startPTS,r),l.endPTS=Math.max(l.endPTS,n),l.startDTS=Math.min(l.startDTS,i),l.endDTS=Math.max(l.endDTS,s)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Je.AUDIO]=null,e[Je.VIDEO]=null,e[Je.AUDIOVIDEO]=null}}class ZD extends dT{constructor(e,r,n,i,s){super(n),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new Td,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=r,this.index=i;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)}}const QD=10;class JD{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.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 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.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const r=this.lastPartSn-e.lastPartSn,n=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!n||!!r||!this.live,this.advanced=this.endSN>e.endSN||r>0||r===0&&n>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?pe(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||QD}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(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end: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 lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function Am(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}function eP(t){const e=Kh(t).subarray(0,16),r=new Uint8Array(16);return r.set(e,16-e.length),r}function tP(t){const e=function(n,i,s){const a=n[i];n[i]=n[s],n[s]=a};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function rP(t){const e=t.split(":");let r=null;if(e[0]==="data"&&e.length===2){const n=e[1].split(";"),i=n[n.length-1].split(",");if(i.length===2){const s=i[0]==="base64",a=i[1];s?(n.splice(-1,1),r=Am(a)):r=eP(a)}}return r}function Kh(t){return Uint8Array.from(unescape(encodeURIComponent(t)),e=>e.charCodeAt(0))}const Ra=typeof self<"u"?self:void 0;var ot={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},yr={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function uv(t){switch(t){case yr.FAIRPLAY:return ot.FAIRPLAY;case yr.PLAYREADY:return ot.PLAYREADY;case yr.WIDEVINE:return ot.WIDEVINE;case yr.CLEARKEY:return ot.CLEARKEY}}var ho={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",FAIRPLAY:"94ce86fb07ff4f43adb893d2fa968ca2",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function cv(t){if(t===ho.WIDEVINE)return ot.WIDEVINE;if(t===ho.PLAYREADY)return ot.PLAYREADY;if(t===ho.CENC||t===ho.CLEARKEY)return ot.CLEARKEY}function dv(t){switch(t){case ot.FAIRPLAY:return yr.FAIRPLAY;case ot.PLAYREADY:return yr.PLAYREADY;case ot.WIDEVINE:return yr.WIDEVINE;case ot.CLEARKEY:return yr.CLEARKEY}}function xf(t){const{drmSystems:e,widevineLicenseUrl:r}=t,n=e?[ot.FAIRPLAY,ot.WIDEVINE,ot.PLAYREADY,ot.CLEARKEY].filter(i=>!!e[i]):[];return!n[ot.WIDEVINE]&&r&&n.push(ot.WIDEVINE),n}const fT=function(t){return Ra!=null&&(t=Ra.navigator)!=null&&t.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function nP(t,e,r,n){let i;switch(t){case ot.FAIRPLAY:i=["cenc","sinf"];break;case ot.WIDEVINE:case ot.PLAYREADY:i=["cenc"];break;case ot.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return iP(i,e,r,n)}function iP(t,e,r,n){return[{initDataTypes:t,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:e.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 hs(t,e,r){return Uint8Array.prototype.slice?t.slice(e,r):new Uint8Array(Array.prototype.slice.call(t,e,r))}const _m=(t,e)=>e+10<=t.length&&t[e]===73&&t[e+1]===68&&t[e+2]===51&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,hT=(t,e)=>e+10<=t.length&&t[e]===51&&t[e+1]===68&&t[e+2]===73&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,fl=(t,e)=>{const r=e;let n=0;for(;_m(t,e);){n+=10;const i=wd(t,e+6);n+=i,hT(t,e+10)&&(n+=10),e+=n}if(n>0)return t.subarray(r,r+n)},wd=(t,e)=>{let r=0;return r=(t[e]&127)<<21,r|=(t[e+1]&127)<<14,r|=(t[e+2]&127)<<7,r|=t[e+3]&127,r},sP=(t,e)=>_m(t,e)&&wd(t,e+6)+10<=t.length-e,Cm=t=>{const e=mT(t);for(let r=0;rt&&t.key==="PRIV"&&t.info==="com.apple.streaming.transportStreamTimestamp",aP=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),r=wd(t,4),n=10;return{type:e,size:r,data:t.subarray(n,n+r)}},mT=t=>{let e=0;const r=[];for(;_m(t,e);){const n=wd(t,e+6);e+=10;const i=e+n;for(;e+8t.type==="PRIV"?lP(t):t.type[0]==="W"?cP(t):uP(t),lP=t=>{if(t.size<2)return;const e=Nn(t.data,!0),r=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:r.buffer}},uP=t=>{if(t.size<2)return;if(t.type==="TXXX"){let r=1;const n=Nn(t.data.subarray(r),!0);r+=n.length+1;const i=Nn(t.data.subarray(r));return{key:t.type,info:n,data:i}}const e=Nn(t.data.subarray(1));return{key:t.type,data:e}},cP=t=>{if(t.type==="WXXX"){if(t.size<2)return;let r=1;const n=Nn(t.data.subarray(r),!0);r+=n.length+1;const i=Nn(t.data.subarray(r));return{key:t.type,info:n,data:i}}const e=Nn(t.data);return{key:t.type,data:e}},dP=t=>{if(t.data.byteLength===8){const e=new Uint8Array(t.data),r=e[3]&1;let n=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return n/=45,r&&(n+=4772185884e-2),Math.round(n)}},Nn=(t,e=!1)=>{const r=fP();if(r){const u=r.decode(t);if(e){const c=u.indexOf("\0");return c!==-1?u.substring(0,c):u}return u.replace(/\0/g,"")}const n=t.length;let i,s,a,o="",l=0;for(;l>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:s=t[l++],o+=String.fromCharCode((i&31)<<6|s&63);break;case 14:s=t[l++],a=t[l++],o+=String.fromCharCode((i&15)<<12|(s&63)<<6|(a&63)<<0);break}}return o};let Sf;function fP(){if(!navigator.userAgent.includes("PlayStation 4"))return!Sf&&typeof self.TextDecoder<"u"&&(Sf=new self.TextDecoder("utf-8")),Sf}const bn={hexDump:function(t){let e="";for(let r=0;r>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=r&255}function pP(t){const e=t.byteLength;for(let r=0;r8&&t[r+4]===109&&t[r+5]===111&&t[r+6]===111&&t[r+7]===102)return!0;r=n>1?r+n:e}return!1}function Oe(t,e){const r=[];if(!e.length)return r;const n=t.byteLength;for(let i=0;i1?i+s:n;if(a===e[0])if(e.length===1)r.push(t.subarray(i+8,o));else{const l=Oe(t.subarray(i+8,o),e.slice(1));l.length&&hP.apply(r,l)}i=o}return r}function mP(t){const e=[],r=t[0];let n=8;const i=Te(t,n);n+=4;let s=0,a=0;r===0?(s=Te(t,n),a=Te(t,n+4),n+=8):(s=fv(t,n),a=fv(t,n+8),n+=16),n+=2;let o=t.length+a;const l=vT(t,n);n+=2;for(let u=0;u>>31===1)return U.warn("SIDX has hierarchical references (not supported)"),null;const h=Te(t,c);c+=4,e.push({referenceSize:f,subsegmentDuration:h,info:{duration:h/i,start:o,end:o+f-1}}),o+=f,c+=4,n=c}return{earliestPresentationTime:s,timescale:i,version:r,referencesCount:l,references:e}}function xT(t){const e=[],r=Oe(t,["moov","trak"]);for(let i=0;i{const s=Te(i,4),a=e[s];a&&(a.default={duration:Te(i,12),flags:Te(i,20)})}),e}function gP(t){const e=t.subarray(8),r=e.subarray(86),n=Dt(e.subarray(4,8));let i=n;const s=n==="enca"||n==="encv";if(s){const o=Oe(e,[n])[0].subarray(n==="enca"?28:78);Oe(o,["sinf"]).forEach(u=>{const c=Oe(u,["schm"])[0];if(c){const d=Dt(c.subarray(4,8));if(d==="cbcs"||d==="cenc"){const f=Oe(u,["frma"])[0];f&&(i=Dt(f))}}})}switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const a=Oe(r,["avcC"])[0];i+="."+tu(a[1])+tu(a[2])+tu(a[3]);break}case"mp4a":{const a=Oe(e,[n])[0],o=Oe(a.subarray(28),["esds"])[0];if(o&&o.length>12){let l=4;if(o[l++]!==3)break;l=Tf(o,l),l+=2;const u=o[l++];if(u&128&&(l+=2),u&64&&(l+=o[l++]),o[l++]!==4)break;l=Tf(o,l);const c=o[l++];if(c===64)i+="."+tu(c);else break;if(l+=12,o[l++]!==5)break;l=Tf(o,l);const d=o[l++];let f=(d&248)>>3;f===31&&(f+=1+((d&7)<<3)+((o[l]&224)>>5)),i+="."+f}break}case"hvc1":case"hev1":{const a=Oe(r,["hvcC"])[0],o=a[1],l=["","A","B","C"][o>>6],u=o&31,c=Te(a,2),d=(o&32)>>5?"H":"L",f=a[12],m=a.subarray(6,12);i+="."+l+u,i+="."+c.toString(16).toUpperCase(),i+="."+d+f;let h="";for(let p=m.length;p--;){const v=m[p];(v||h)&&(h="."+v.toString(16).toUpperCase()+h)}i+=h;break}case"dvh1":case"dvhe":{const a=Oe(r,["dvcC"])[0],o=a[2]>>1&127,l=a[2]<<5&32|a[3]>>3&31;i+="."+Tn(o)+"."+Tn(l);break}case"vp09":{const a=Oe(r,["vpcC"])[0],o=a[4],l=a[5],u=a[6]>>4&15;i+="."+Tn(o)+"."+Tn(l)+"."+Tn(u);break}case"av01":{const a=Oe(r,["av1C"])[0],o=a[1]>>>5,l=a[1]&31,u=a[2]>>>7?"H":"M",c=(a[2]&64)>>6,d=(a[2]&32)>>5,f=o===2&&c?d?12:10:c?10:8,m=(a[2]&16)>>4,h=(a[2]&8)>>3,p=(a[2]&4)>>2,v=a[2]&3;i+="."+o+"."+Tn(l)+u+"."+Tn(f)+"."+m+"."+h+p+v+"."+Tn(1)+"."+Tn(1)+"."+Tn(1)+"."+0;break}}return{codec:i,encrypted:s}}function Tf(t,e){const r=e+5;for(;t[e++]&128&&e{const a=Oe(i,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=Oe(a,["enca"]);const l=o.length>0;l||(o=Oe(a,["encv"])),o.forEach(u=>{const c=l?u.subarray(28):u.subarray(78);Oe(c,["sinf"]).forEach(f=>{const m=ST(f);if(m){const h=m.subarray(8,24);h.some(p=>p!==0)||(U.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${bn.hexDump(h)} -> ${bn.hexDump(r)}`),m.set(r,8))}})})}),t}function ST(t){const e=Oe(t,["schm"])[0];if(e){const r=Dt(e.subarray(4,8));if(r==="cbcs"||r==="cenc")return Oe(t,["schi","tenc"])[0]}return null}function yP(t,e){return Oe(e,["moof","traf"]).reduce((r,n)=>{const i=Oe(n,["tfdt"])[0],s=i[0],a=Oe(n,["tfhd"]).reduce((o,l)=>{const u=Te(l,4),c=t[u];if(c){let d=Te(i,4);if(s===1){if(d===Mc)return U.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;d*=Mc+1,d+=Te(i,8)}const f=c.timescale||9e4,m=d/f;if(pe(m)&&(o===null||mm+h.info.duration||0,0);o=Math.max(o,f+d.earliestPresentationTime/d.timescale),l=o-a}}if(l&&pe(l))return l}return n||i}function SP(t){const e=Te(t,0);let r=8;e&1&&(r+=4),e&4&&(r+=4);let n=0;const i=Te(t,4);for(let s=0;s{Oe(n,["tfhd"]).forEach(i=>{const s=Te(i,4),a=t[s];if(!a)return;const o=a.timescale||9e4;Oe(n,["tfdt"]).forEach(l=>{const u=l[0],c=r*o;if(c){let d=Te(l,4);if(u===0)d-=c,d=Math.max(d,0),Ef(l,4,d);else{d*=Math.pow(2,32),d+=Te(l,8),d-=c,d=Math.max(d,0);const f=Math.floor(d/(Mc+1)),m=Math.floor(d%(Mc+1));Ef(l,4,f),Ef(l,8,m)}}})})})}function TP(t){const e={valid:null,remainder:null},r=Oe(t,["moof"]);if(r.length<2)return e.remainder=t,e;const n=r[r.length-1];return e.valid=hs(t,0,n.byteOffset-8),e.remainder=hs(t,n.byteOffset-8),e}function Jr(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function hv(t,e){const r=[],n=e.samples,i=e.timescale,s=e.id;let a=!1;return Oe(n,["moof"]).map(l=>{const u=l.byteOffset-8;Oe(l,["traf"]).map(d=>{const f=Oe(d,["tfdt"]).map(m=>{const h=m[0];let p=Te(m,4);return h===1&&(p*=Math.pow(2,32),p+=Te(m,8)),p/i})[0];return f!==void 0&&(t=f),Oe(d,["tfhd"]).map(m=>{const h=Te(m,4),p=Te(m,0)&16777215,v=(p&1)!==0,g=(p&2)!==0,y=(p&8)!==0;let x=0;const S=(p&16)!==0;let T=0;const C=(p&32)!==0;let _=8;h===s&&(v&&(_+=8),g&&(_+=4),y&&(x=Te(m,_),_+=4),S&&(T=Te(m,_),_+=4),C&&(_+=4),e.type==="video"&&(a=wP(e.codec)),Oe(d,["trun"]).map(b=>{const I=b[0],A=Te(b,0)&16777215,k=(A&1)!==0;let O=0;const P=(A&4)!==0,G=(A&256)!==0;let K=0;const H=(A&512)!==0;let se=0;const W=(A&1024)!==0,F=(A&2048)!==0;let j=0;const te=Te(b,4);let ee=8;k&&(O=Te(b,ee),ee+=4),P&&(ee+=4);let fe=O+u;for(let ye=0;ye>1&63;return r===39||r===40}else return(e&31)===6}function ET(t,e,r,n){const i=TT(t);let s=0;s+=e;let a=0,o=0,l=0;for(;s=i.length)break;l=i[s++],a+=l}while(l===255);o=0;do{if(s>=i.length)break;l=i[s++],o+=l}while(l===255);const u=i.length-s;let c=s;if(ou){U.error(`Malformed SEI payload. ${o} is too small, only ${u} bytes left to parse.`);break}if(a===4){if(i[c++]===181){const f=vT(i,c);if(c+=2,f===49){const m=Te(i,c);if(c+=4,m===1195456820){const h=i[c++];if(h===3){const p=i[c++],v=31&p,g=64&p,y=g?2+v*3:0,x=new Uint8Array(y);if(g){x[0]=p;for(let S=1;S16){const d=[];for(let h=0;h<16;h++){const p=i[c++].toString(16);d.push(p.length==1?"0"+p:p),(h===3||h===5||h===7||h===9)&&d.push("-")}const f=o-16,m=new Uint8Array(f);for(let h=0;h>24&255,s[1]=n>>16&255,s[2]=n>>8&255,s[3]=n&255,s.set(t,4),i=0,n=8;i0?(s=new Uint8Array(4),e.length>0&&new DataView(s.buffer).setUint32(0,e.length,!1)):s=new Uint8Array;const a=new Uint8Array(4);return r&&r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),AP([112,115,115,104],new Uint8Array([n,0,0,0]),t,s,i,a,r||new Uint8Array)}function CP(t){const e=[];if(t instanceof ArrayBuffer){const r=t.byteLength;let n=0;for(;n+32>>24;if(s!==0&&s!==1)return{offset:r,size:e};const a=t.buffer,o=bn.hexDump(new Uint8Array(a,r+12,16)),l=t.getUint32(28);let u=null,c=null;if(s===0){if(e-32=22&&(this.keyId=r.subarray(r.length-22,r.length-6));break;case yr.PLAYREADY:{const n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=_P(n,null,r);const i=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),s=String.fromCharCode.apply(null,Array.from(i)),a=s.substring(s.indexOf("<"),s.length),u=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("KID")[0];if(u){const c=u.childNodes[0]?u.childNodes[0].nodeValue:u.getAttribute("VALUE");if(c){const d=Am(c).subarray(0,16);tP(d),this.keyId=d}}break}default:{let n=r.subarray(0,16);if(n.length!==16){const i=new Uint8Array(16);i.set(n,16-n.length),n=i}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n=ru[this.uri];if(!n){const i=Object.keys(ru).length%Number.MAX_SAFE_INTEGER;n=new Uint8Array(16),new DataView(n.buffer,12,4).setUint32(0,i),ru[this.uri]=n}this.keyId=n}return this}}function IP(t){const e=new Uint8Array(16);for(let r=12;r<16;r++)e[r]=t>>8*(15-r)&255;return e}const wT=/\{\$([a-zA-Z0-9-_]+)\}/g;function pv(t){return wT.test(t)}function pr(t,e,r){if(t.variableList!==null||t.hasVariableRefs)for(let n=r.length;n--;){const i=r[n],s=e[i];s&&(e[i]=Yh(t,s))}}function Yh(t,e){if(t.variableList!==null||t.hasVariableRefs){const r=t.variableList;return e.replace(wT,n=>{const i=n.substring(2,n.length-1),s=r==null?void 0:r[i];return s===void 0?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),n):s})}return e}function mv(t,e,r){let n=t.variableList;n||(t.variableList=n={});let i,s;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const a=new self.URL(r).searchParams;if(a.has(i))s=a.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${r}"`)}catch(a){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,s=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=s||""}function kP(t,e,r){const n=e.IMPORT;if(r&&n in r){let i=t.variableList;i||(t.variableList=i={}),i[n]=r[n]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}function bs(t=!0){return typeof self>"u"?void 0:(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function DP(t){return typeof self<"u"&&t===self.ManagedMediaSource}const Nc={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,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 PP(t,e){const r=Nc[e];return!!r&&!!r[t.slice(0,4)]}function wf(t,e,r=!0){return!t.split(",").some(n=>!bT(n,e,r))}function bT(t,e,r=!0){var n;const i=bs(r);return(n=i==null?void 0:i.isTypeSupported(pl(t,e)))!=null?n:!1}function pl(t,e){return`${e}/mp4;codecs="${t}"`}function gv(t){if(t){const e=t.substring(0,4);return Nc.video[e]}return 2}function Fc(t){return t.split(",").reduce((e,r)=>{const n=Nc.video[r];return n?(n*2+e)/(e?3:2):(Nc.audio[r]+e)/(e?2:1)},0)}const bf={};function OP(t,e=!0){if(bf[t])return bf[t];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t];for(let n=0;nOP(r.toLowerCase(),e))}function vv(t,e){return t&&t!=="mp4a"?t:e&&e.split(",")[0]}function NP(t){const e=t.split(",");for(let r=0;r2){let i=n.shift()+".";i+=parseInt(n.shift()).toString(16),i+=("000"+parseInt(n.shift()).toString(16)).slice(-4),e[r]=i}}return e.join(",")}const yv=/#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,xv=/#EXT-X-MEDIA:(.*)/g,FP=/^#EXT(?:INF|-X-TARGETDURATION):/m,Sv=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),UP=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(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("|"));class kn{static findGroup(e,r){for(let n=0;n0&&s.length({id:u.attrs.AUDIO,audioCodec:u.audioCodec})),SUBTITLES:a.map(u=>({id:u.attrs.SUBTITLES,textCodec:u.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(xv.lastIndex=0;(i=xv.exec(e))!==null;){const u=new gt(i[1]),c=u.TYPE;if(c){const d=o[c],f=s[c]||[];s[c]=f,pr(n,u,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const m=u.LANGUAGE,h=u["ASSOC-LANGUAGE"],p=u.CHANNELS,v=u.CHARACTERISTICS,g=u["INSTREAM-ID"],y={attrs:u,bitrate:0,id:l++,groupId:u["GROUP-ID"]||"",name:u.NAME||m||"",type:c,default:u.bool("DEFAULT"),autoselect:u.bool("AUTOSELECT"),forced:u.bool("FORCED"),lang:m,url:u.URI?kn.resolve(u.URI,r):""};if(h&&(y.assocLang=h),p&&(y.channels=p),v&&(y.characteristics=v),g&&(y.instreamId=g),d!=null&&d.length){const x=kn.findGroup(d,y.groupId)||d[0];wv(y,x,"audioCodec"),wv(y,x,"textCodec")}f.push(y)}}return s}static parseLevelPlaylist(e,r,n,i,s,a){const o=new JD(r),l=o.fragments;let u=null,c=0,d=0,f=0,m=0,h=null,p=new yf(i,r),v,g,y,x=-1,S=!1,T=null;for(Sv.lastIndex=0,o.m3u8=e,o.hasVariableRefs=pv(e);(v=Sv.exec(e))!==null;){S&&(S=!1,p=new yf(i,r),p.start=f,p.sn=c,p.cc=m,p.level=n,u&&(p.initSegment=u,p.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null,T&&(p.setByteRange(T),T=null)));const I=v[1];if(I){p.duration=parseFloat(I);const A=(" "+v[2]).slice(1);p.title=A||null,p.tagList.push(A?["INF",I,A]:["INF",I])}else if(v[3]){if(pe(p.duration)){p.start=f,y&&Av(p,y,o),p.sn=c,p.level=n,p.cc=m,l.push(p);const A=(" "+v[3]).slice(1);p.relurl=Yh(o,A),bv(p,h),h=p,f+=p.duration,c++,d=0,S=!0}}else if(v[4]){const A=(" "+v[4]).slice(1);h?p.setByteRange(A,h):p.setByteRange(A)}else if(v[5])p.rawProgramDateTime=(" "+v[5]).slice(1),p.tagList.push(["PROGRAM-DATE-TIME",p.rawProgramDateTime]),x===-1&&(x=l.length);else{if(v=v[0].match(UP),!v){U.warn("No matches on slow regex match for level playlist!");continue}for(g=1;g0&&P.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=P.optionalFloat("PART-HOLD-BACK",0),o.holdBack=P.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const P=new gt(k);o.partTarget=P.decimalFloatingPoint("PART-TARGET");break}case"PART":{let P=o.partList;P||(P=o.partList=[]);const G=d>0?P[P.length-1]:void 0,K=d++,H=new gt(k);pr(o,H,["BYTERANGE","URI"]);const se=new ZD(H,p,r,K,G);P.push(se),p.duration+=se.duration;break}case"PRELOAD-HINT":{const P=new gt(k);pr(o,P,["URI"]),o.preloadHint=P;break}case"RENDITION-REPORT":{const P=new gt(k);pr(o,P,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(P);break}default:U.warn(`line parsed but not handled: ${v}`);break}}}h&&!h.relurl?(l.pop(),f-=h.duration,o.partList&&(o.fragmentHint=h)):o.partList&&(bv(p,h),p.cc=m,o.fragmentHint=p,y&&Av(p,y,o));const C=l.length,_=l[0],b=l[C-1];if(f+=o.skippedSegments*o.targetduration,f>0&&C&&b){o.averagetargetduration=f/C;const I=b.sn;o.endSN=I!=="initSegment"?I:0,o.live||(b.endList=!0),_&&(o.startCC=_.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(f+=o.fragmentHint.duration),o.totalduration=f,o.endCC=m,x>0&&$P(l,x),o}}function Ev(t,e,r){var n,i;const s=new gt(t);pr(r,s,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=(n=s.METHOD)!=null?n:"",o=s.URI,l=s.hexadecimalInteger("IV"),u=s.KEYFORMATVERSIONS,c=(i=s.KEYFORMAT)!=null?i:"identity";o&&s.IV&&!l&&U.error(`Invalid IV: ${s.IV}`);const d=o?kn.resolve(o,e):"",f=(u||"1").split("/").map(Number).filter(Number.isFinite);return new hl(a,d,c,f,l)}function Tv(t){const r=new gt(t).decimalFloatingPoint("TIME-OFFSET");return pe(r)?r:null}function BP(t,e){let r=(t||"").split(/[ ,]+/).filter(n=>n);["video","audio","text"].forEach(n=>{const i=r.filter(s=>PP(s,n));i.length&&(e[`${n}Codec`]=i.join(","),r=r.filter(s=>i.indexOf(s)===-1))}),e.unknownCodecs=r}function wv(t,e,r){const n=e[r];n&&(t[r]=n)}function $P(t,e){let r=t[e];for(let n=e;n--;){const i=t[n];if(!i)return;i.programDateTime=r.programDateTime-i.duration*1e3,r=i}}function bv(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):e!=null&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),pe(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function Lv(t,e,r,n){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=r,t.sn="initSegment",n&&(t.levelkeys=n),t.initSegment=null}function Av(t,e,r){t.levelkeys=e;const{encryptedFragments:n}=r;(!n.length||n[n.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&n.push(t)}var He={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},we={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function _v(t){const{type:e}=t;switch(e){case He.AUDIO_TRACK:return we.AUDIO;case He.SUBTITLE_TRACK:return we.SUBTITLE;default:return we.MAIN}}function Lf(t,e){let r=t.url;return(r===void 0||r.indexOf("data:")===0)&&(r=e.url),r}class jP{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.LEVEL_LOADING,this.onLevelLoading,this),e.on(w.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(w.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.LEVEL_LOADING,this.onLevelLoading,this),e.off(w.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(w.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const r=this.hls.config,n=r.pLoader,i=r.loader,s=n||i,a=new s(r);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const r=this.loaders[e];r&&r.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,r){const{url:n}=r;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:He.MANIFEST,url:n,deliveryDirectives:null})}onLevelLoading(e,r){const{id:n,level:i,pathwayId:s,url:a,deliveryDirectives:o}=r;this.load({id:n,level:i,pathwayId:s,responseType:"text",type:He.LEVEL,url:a,deliveryDirectives:o})}onAudioTrackLoading(e,r){const{id:n,groupId:i,url:s,deliveryDirectives:a}=r;this.load({id:n,groupId:i,level:null,responseType:"text",type:He.AUDIO_TRACK,url:s,deliveryDirectives:a})}onSubtitleTrackLoading(e,r){const{id:n,groupId:i,url:s,deliveryDirectives:a}=r;this.load({id:n,groupId:i,level:null,responseType:"text",type:He.SUBTITLE_TRACK,url:s,deliveryDirectives:a})}load(e){var r;const n=this.hls.config;let i=this.getInternalLoader(e);if(i){const u=i.context;if(u&&u.url===e.url&&u.level===e.level){U.trace("[playlist-loader]: playlist request ongoing");return}U.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let s;if(e.type===He.MANIFEST?s=n.manifestLoadPolicy.default:s=It({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),pe((r=e.deliveryDirectives)==null?void 0:r.part)){let u;if(e.type===He.LEVEL&&e.level!==null?u=this.hls.levels[e.level].details:e.type===He.AUDIO_TRACK&&e.id!==null?u=this.hls.audioTracks[e.id].details:e.type===He.SUBTITLE_TRACK&&e.id!==null&&(u=this.hls.subtitleTracks[e.id].details),u){const c=u.partTarget,d=u.targetduration;if(c&&d){const f=Math.max(c*3,d*.8)*1e3;s=It({},s,{maxTimeToFirstByteMs:Math.min(f,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(f,s.maxTimeToFirstByteMs)})}}}const a=s.errorRetry||s.timeoutRetry||{},o={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(u,c,d,f)=>{const m=this.getInternalLoader(d);this.resetInternalLoader(d.type);const h=u.data;if(h.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(u,d,new Error("no EXTM3U delimiter"),f||null,c);return}c.parsing.start=performance.now(),kn.isMediaPlaylist(h)?this.handleTrackOrLevelPlaylist(u,c,d,f||null,m):this.handleMasterPlaylist(u,c,d,f)},onError:(u,c,d,f)=>{this.handleNetworkError(c,d,!1,u,f)},onTimeout:(u,c,d)=>{this.handleNetworkError(c,d,!0,void 0,u)}};i.load(e,o,l)}handleMasterPlaylist(e,r,n,i){const s=this.hls,a=e.data,o=Lf(e,n),l=kn.parseMasterPlaylist(a,o);if(l.playlistParsingError){this.handleManifestParsingError(e,n,l.playlistParsingError,i,r);return}const{contentSteering:u,levels:c,sessionData:d,sessionKeys:f,startTimeOffset:m,variableList:h}=l;this.variableList=h;const{AUDIO:p=[],SUBTITLES:v,"CLOSED-CAPTIONS":g}=kn.parseMasterPlaylistMedia(a,o,l);p.length&&!p.some(x=>!x.url)&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(U.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new gt({}),bitrate:0,url:""})),s.trigger(w.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:v,captions:g,contentSteering:u,url:o,stats:r,networkDetails:i,sessionData:d,sessionKeys:f,startTimeOffset:m,variableList:h})}handleTrackOrLevelPlaylist(e,r,n,i,s){const a=this.hls,{id:o,level:l,type:u}=n,c=Lf(e,n),d=0,f=pe(l)?l:pe(o)?o:0,m=_v(n),h=kn.parseLevelPlaylist(e.data,c,f,m,d,this.variableList);if(u===He.MANIFEST){const p={attrs:new gt({}),bitrate:0,details:h,name:"",url:c};a.trigger(w.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:c,stats:r,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}r.parsing.end=performance.now(),n.levelDetails=h,this.handlePlaylistLoaded(h,e,r,n,i,s)}handleManifestParsingError(e,r,n,i,s){this.hls.trigger(w.ERROR,{type:_e.NETWORK_ERROR,details:z.MANIFEST_PARSING_ERROR,fatal:r.type===He.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:r,networkDetails:i,stats:s})}handleNetworkError(e,r,n=!1,i,s){let a=`A network ${n?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===He.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===He.AUDIO_TRACK||e.type===He.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);U.warn(`[playlist-loader]: ${a}`);let l=z.UNKNOWN,u=!1;const c=this.getInternalLoader(e);switch(e.type){case He.MANIFEST:l=n?z.MANIFEST_LOAD_TIMEOUT:z.MANIFEST_LOAD_ERROR,u=!0;break;case He.LEVEL:l=n?z.LEVEL_LOAD_TIMEOUT:z.LEVEL_LOAD_ERROR,u=!1;break;case He.AUDIO_TRACK:l=n?z.AUDIO_TRACK_LOAD_TIMEOUT:z.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case He.SUBTITLE_TRACK:l=n?z.SUBTITLE_TRACK_LOAD_TIMEOUT:z.SUBTITLE_LOAD_ERROR,u=!1;break}c&&this.resetInternalLoader(e.type);const d={type:_e.NETWORK_ERROR,details:l,fatal:u,url:e.url,loader:c,context:e,error:o,networkDetails:r,stats:s};if(i){const f=(r==null?void 0:r.url)||e.url;d.response=jt({url:f,data:void 0},i)}this.hls.trigger(w.ERROR,d)}handlePlaylistLoaded(e,r,n,i,s,a){const o=this.hls,{type:l,level:u,id:c,groupId:d,deliveryDirectives:f}=i,m=Lf(r,i),h=_v(i),p=typeof i.level=="number"&&h===we.MAIN?u:void 0;if(!e.fragments.length){const g=new Error("No Segments found in Playlist");o.trigger(w.ERROR,{type:_e.NETWORK_ERROR,details:z.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:g,reason:g.message,response:r,context:i,level:p,parent:h,networkDetails:s,stats:n});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const v=e.playlistParsingError;if(v){o.trigger(w.ERROR,{type:_e.NETWORK_ERROR,details:z.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:r,context:i,level:p,parent:h,networkDetails:s,stats:n});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case He.MANIFEST:case He.LEVEL:o.trigger(w.LEVEL_LOADED,{details:e,level:p||0,id:c||0,stats:n,networkDetails:s,deliveryDirectives:f});break;case He.AUDIO_TRACK:o.trigger(w.AUDIO_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:n,networkDetails:s,deliveryDirectives:f});break;case He.SUBTITLE_TRACK:o.trigger(w.SUBTITLE_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:n,networkDetails:s,deliveryDirectives:f});break}}}function LT(t,e){let r;try{r=new Event("addtrack")}catch{r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function AT(t,e){const r=t.mode;if(r==="disabled"&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(n){U.debug(`[texttrack-utils]: ${n}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(i){U.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}r==="disabled"&&(t.mode=r)}function ta(t){const e=t.mode;if(e==="disabled"&&(t.mode="hidden"),t.cues)for(let r=t.cues.length;r--;)t.removeCue(t.cues[r]);e==="disabled"&&(t.mode=e)}function qh(t,e,r,n){const i=t.mode;if(i==="disabled"&&(t.mode="hidden"),t.cues&&t.cues.length>0){const s=GP(t.cues,e,r);for(let a=0;at[r].endTime)return-1;let n=0,i=r;for(;n<=i;){const s=Math.floor((i+n)/2);if(et[s].startTime&&n-1)for(let s=i,a=t.length;s=e&&o.endTime<=r)n.push(o);else if(o.startTime>r)return n}return n}function Pu(t){const e=[];for(let r=0;r"u"))return self.VTTCue||self.TextTrackCue}function Cv(t,e,r,n,i){let s=new t(e,r,"");try{s.value=n,i&&(s.type=i)}catch{s=new t(e,r,JSON.stringify(i?jt({type:i},n):n))}return s}const nu=(()=>{const t=Xh();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Af(t,e){return t.getTime()/1e3-e}function HP(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class WP{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(w.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(w.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,r){this.media=r.media}onMediaDetaching(){this.id3Track&&(ta(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const r=this.getID3Track(e.textTracks);return r.mode="hidden",r}getID3Track(e){if(this.media){for(let r=0;rnu&&(d=nu),d-c<=0&&(d=c+zP);for(let m=0;mc.type===dn.audioId3&&l:i==="video"?u=c=>c.type===dn.emsg&&o:u=c=>c.type===dn.audioId3&&l||c.type===dn.emsg&&o,qh(s,r,n,u)}}onLevelUpdated(e,{details:r}){if(!this.media||!r.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:n,id3Track:i}=this,{dateRanges:s}=r,a=Object.keys(s);if(i){const c=Object.keys(n).filter(d=>!a.includes(d));for(let d=c.length;d--;){const f=c[d];Object.keys(n[f].cues).forEach(m=>{i.removeCue(n[f].cues[m])}),delete n[f]}}const o=r.fragments[r.fragments.length-1];if(a.length===0||!pe(o==null?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,u=Xh();for(let c=0;c{if(C!==f.id){const _=s[C];if(_.class===f.class&&_.startDate>f.startDate&&(!T||f.startDatethis.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:r}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:r?e.liveMaxLatencyDurationCount*r.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:r,partHoldBack:n,targetduration:i}=e,{liveSyncDuration:s,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let u=o&&n||r;(l.liveSyncDuration||l.liveSyncDurationCount||u===0)&&(u=s!==void 0?s:a*i);const c=i;return u+Math.min(this.stallCount*1,c)}get liveSyncPosition(){const e=this.estimateLiveEdge(),r=this.targetLatency,n=this.levelDetails;if(e===null||r===null||n===null)return null;const i=n.edge,s=e-r-this.edgeStalled,a=i-n.totalduration,o=i-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(a,s),o)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(e===null)return 0;const r=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-r,0)}get forwardBufferLength(){const{media:e,levelDetails:r}=this;if(!e||!r)return 0;const n=e.buffered.length;return(n?e.buffered.end(n-1):r.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(w.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(w.ERROR,this.onError,this)}onMediaAttached(e,r){this.media=r.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:r}){this.levelDetails=r,r.advanced&&this.timeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,r){var n;r.details===z.BUFFER_STALLED_ERROR&&(this.stallCount++,(n=this.levelDetails)!=null&&n.live&&U.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:r}=this;if(!e||!r)return;this.currentTime=e.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:s}=this.config;if(!i||s===1||!r.live)return;const a=this.targetLatency;if(a===null)return;const o=n-a,l=Math.min(this.maxLatency,a+r.targetduration);if(o.05&&this.forwardBufferLength>1){const c=Math.min(2,Math.max(1,s)),d=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(c,Math.max(1,d))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const Zh=["NONE","TYPE-0","TYPE-1",null];function YP(t){return Zh.indexOf(t)>-1}const Bc=["SDR","PQ","HLG"];function qP(t){return!!t&&Bc.indexOf(t)>-1}var Ou={No:"",Yes:"YES",v2:"v2"};function Rv(t){const{canSkipUntil:e,canSkipDateRanges:r,age:n}=t,i=n!!r).map(r=>r.substring(0,4)).join(","),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 kv(this._audioGroups,e)}hasSubtitleGroup(e){return kv(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,r){if(r){if(e==="audio"){let n=this._audioGroups;n||(n=this._audioGroups=[]),n.indexOf(r)===-1&&n.push(r)}else if(e==="text"){let n=this._subtitleGroups;n||(n=this._subtitleGroups=[]),n.indexOf(r)===-1&&n.push(r)}}}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 kv(t,e){return!e||!t?!1:t.indexOf(e)!==-1}function _f(t,e){const r=e.startPTS;if(pe(r)){let n=0,i;e.sn>t.sn?(n=r-t.start,i=t):(n=t.start-r,i=e),i.duration!==n&&(i.duration=n)}else e.sn>t.sn?t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration:e.start=Math.max(t.start-e.duration,0)}function _T(t,e,r,n,i,s){n-r<=0&&(U.warn("Fragment should have a positive duration",e),n=r+e.duration,s=i+e.duration);let o=r,l=n;const u=e.startPTS,c=e.endPTS;if(pe(u)){const v=Math.abs(u-r);pe(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,o=Math.max(r,u),r=Math.min(r,u),i=Math.min(i,e.startDTS),l=Math.min(n,c),n=Math.max(n,c),s=Math.max(s,e.endDTS)}const d=r-e.start;e.start!==0&&(e.start=r),e.duration=n-e.start,e.startPTS=r,e.maxStartPTS=o,e.startDTS=i,e.endPTS=n,e.minEndPTS=l,e.endDTS=s;const f=e.sn;if(!t||ft.endSN)return 0;let m;const h=f-t.startSN,p=t.fragments;for(p[h]=e,m=h;m>0;m--)_f(p[m],p[m-1]);for(m=h;m=0;l--){const u=n[l].initSegment;if(u){r=u;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let i=0,s;if(JP(t,e,(l,u)=>{l.relurl&&(i=l.cc-u.cc),pe(l.startPTS)&&pe(l.endPTS)&&(u.start=u.startPTS=l.startPTS,u.startDTS=l.startDTS,u.maxStartPTS=l.maxStartPTS,u.endPTS=l.endPTS,u.endDTS=l.endDTS,u.minEndPTS=l.minEndPTS,u.duration=l.endPTS-l.startPTS,u.duration&&(s=u),e.PTSKnown=e.alignedSliding=!0),u.elementaryStreams=l.elementaryStreams,u.loader=l.loader,u.stats=l.stats,l.initSegment&&(u.initSegment=l.initSegment,r=l.initSegment)}),r&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(u=>{var c;u&&(!u.initSegment||u.initSegment.relurl===((c=r)==null?void 0:c.relurl))&&(u.initSegment=r)}),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(l=>!l),e.deltaUpdateFailed){U.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=ZP(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(i){U.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l{u.elementaryStreams=l.elementaryStreams,u.stats=l.stats}),s?_T(e,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):CT(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const l=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=l),e.driftEndTime=o,e.driftEnd=l}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function ZP(t,e,r){const n=It({},t);return r&&r.forEach(i=>{delete n[i]}),Object.keys(e).forEach(i=>{const s=new cT(e[i].attr,n[i]);s.isValid?n[i]=s:U.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[i].attr)}"`)}),n}function QP(t,e,r){if(t&&e){let n=0;for(let i=0,s=t.length;i<=s;i++){const a=t[i],o=e[i+n];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?r(a,o):n--}}}function JP(t,e,r){const n=e.skippedSegments,i=Math.max(t.startSN,e.startSN)-e.startSN,s=(t.fragmentHint?1:0)+(n?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let u=i;u<=s;u++){const c=l[a+u];let d=o[u];n&&!d&&u=n.length||Qh(e,n[r].start)}function Qh(t,e){if(e){const r=t.fragments;for(let n=t.skippedSegments;ne){const s=n[n.length-1].duration*1e3;s{const{details:n}=e;n!=null&&n.fragments&&n.fragments.forEach(i=>{i.level=r})})}function $c(t){switch(t.details){case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_TIMEOUT:case z.LEVEL_LOAD_TIMEOUT:case z.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Pv(t,e){const r=$c(e);return t.default[`${r?"timeout":"error"}Retry`]}function Rm(t,e){const r=t.backoff==="linear"?1:Math.pow(2,e);return Math.min(r*t.retryDelayMs,t.maxRetryDelayMs)}function Ov(t){return jt(jt({},t),{errorRetry:null,timeoutRetry:null})}function jc(t,e,r,n){if(!t)return!1;const i=n==null?void 0:n.code,s=e499)}const kT={search:function(t,e){let r=0,n=t.length-1,i=null,s=null;for(;r<=n;){i=(r+n)/2|0,s=t[i];const a=e(s);if(a>0)r=i+1;else if(a<0)n=i-1;else return s}return null}};function nO(t,e,r){if(e===null||!Array.isArray(t)||!t.length||!pe(e))return null;const n=t[0].programDateTime;if(e<(n||0))return null;const i=t[t.length-1].endProgramDateTime;if(e>=(i||0))return null;r=r||0;for(let s=0;s0&&o<15e-7&&(r+=15e-7)}else r===0&&e[0].start===0&&(s=e[0]);if(s&&((!t||t.level===s.level)&&Jh(r,n,s)===0||iO(s,t,Math.min(i,n))))return s;const a=kT.search(e,Jh.bind(null,r,n));return a&&(a!==t||!s)?a:s}function iO(t,e,r){if(e&&e.start===0&&e.level0){const n=e.tagList.reduce((i,s)=>(s[0]==="INF"&&(i+=parseFloat(s[1])),i),r);return t.start<=n}return!1}function Jh(t=0,e=0,r){if(r.start<=t&&r.start+r.duration>t)return 0;const n=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=t?1:r.start-n>t&&r.start?-1:0}function sO(t,e,r){const n=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0))*1e3;return(r.endProgramDateTime||0)-n>t}function aO(t,e){return kT.search(t,r=>r.cce?-1:0)}var zt={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},sn={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class oO{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=U.log.bind(U,"[info]:"),this.warn=U.warn.bind(U,"[warning]:"),this.error=U.error.bind(U,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(w.ERROR,this.onError,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(w.ERROR,this.onError,this),e.off(w.ERROR,this.onErrorOut,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===we.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,r){var n,i;if(r.fatal)return;const s=this.hls,a=r.context;switch(r.details){case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:r.errorAction=this.getFragRetryOrSwitchAction(r);return;case z.FRAG_PARSING_ERROR:if((n=r.frag)!=null&&n.gap){r.errorAction={action:zt.DoNothing,flags:sn.None};return}case z.FRAG_GAP:case z.FRAG_DECRYPT_ERROR:{r.errorAction=this.getFragRetryOrSwitchAction(r),r.errorAction.action=zt.SendAlternateToPenaltyBox;return}case z.LEVEL_EMPTY_ERROR:case z.LEVEL_PARSING_ERROR:{var o,l;const u=r.parent===we.MAIN?r.level:s.loadLevel;r.details===z.LEVEL_EMPTY_ERROR&&((o=r.context)!=null&&(l=o.levelDetails)!=null&&l.live)?r.errorAction=this.getPlaylistRetryOrSwitchAction(r,u):(r.levelRetry=!1,r.errorAction=this.getLevelSwitchAction(r,u))}return;case z.LEVEL_LOAD_ERROR:case z.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(r.errorAction=this.getPlaylistRetryOrSwitchAction(r,a.level));return;case z.AUDIO_TRACK_LOAD_ERROR:case z.AUDIO_TRACK_LOAD_TIMEOUT:case z.SUBTITLE_LOAD_ERROR:case z.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const u=s.levels[s.loadLevel];if(u&&(a.type===He.AUDIO_TRACK&&u.hasAudioGroup(a.groupId)||a.type===He.SUBTITLE_TRACK&&u.hasSubtitleGroup(a.groupId))){r.errorAction=this.getPlaylistRetryOrSwitchAction(r,s.loadLevel),r.errorAction.action=zt.SendAlternateToPenaltyBox,r.errorAction.flags=sn.MoveAllAlternatesMatchingHost;return}}return;case z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const u=s.levels[s.loadLevel],c=u==null?void 0:u.attrs["HDCP-LEVEL"];c?r.errorAction={action:zt.SendAlternateToPenaltyBox,flags:sn.MoveAllAlternatesMatchingHDCP,hdcpLevel:c}:this.keySystemError(r)}return;case z.BUFFER_ADD_CODEC_ERROR:case z.REMUX_ALLOC_ERROR:case z.BUFFER_APPEND_ERROR:r.errorAction=this.getLevelSwitchAction(r,(i=r.level)!=null?i:s.loadLevel);return;case z.INTERNAL_EXCEPTION:case z.BUFFER_APPENDING_ERROR:case z.BUFFER_FULL_ERROR:case z.LEVEL_SWITCH_ERROR:case z.BUFFER_STALLED_ERROR:case z.BUFFER_SEEK_OVER_HOLE:case z.BUFFER_NUDGE_ON_STALL:r.errorAction={action:zt.DoNothing,flags:sn.None};return}r.type===_e.KEY_SYSTEM_ERROR&&this.keySystemError(r)}keySystemError(e){const r=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,r)}getPlaylistRetryOrSwitchAction(e,r){const n=this.hls,i=Pv(n.config.playlistLoadPolicy,e),s=this.playlistError++;if(jc(i,s,$c(e),e.response))return{action:zt.RetryRequest,flags:sn.None,retryConfig:i,retryCount:s};const o=this.getLevelSwitchAction(e,r);return i&&(o.retryConfig=i,o.retryCount=s),o}getFragRetryOrSwitchAction(e){const r=this.hls,n=this.getVariantLevelIndex(e.frag),i=r.levels[n],{fragLoadPolicy:s,keyLoadPolicy:a}=r.config,o=Pv(e.details.startsWith("key")?a:s,e),l=r.levels.reduce((c,d)=>c+d.fragmentError,0);if(i&&(e.details!==z.FRAG_GAP&&i.fragmentError++,jc(o,l,$c(e),e.response)))return{action:zt.RetryRequest,flags:sn.None,retryConfig:o,retryCount:l};const u=this.getLevelSwitchAction(e,n);return o&&(u.retryConfig=o,u.retryCount=l),u}getLevelSwitchAction(e,r){const n=this.hls;r==null&&(r=n.loadLevel);const i=this.hls.levels[r];if(i){var s,a;const u=e.details;i.loadError++,u===z.BUFFER_APPEND_ERROR&&i.fragmentError++;let c=-1;const{levels:d,loadLevel:f,minAutoLevel:m,maxAutoLevel:h}=n;n.autoLevelEnabled||(n.loadLevel=-1);const p=(s=e.frag)==null?void 0:s.type,g=(p===we.AUDIO&&u===z.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(u===z.BUFFER_ADD_CODEC_ERROR||u===z.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:C})=>i.audioCodec!==C),x=e.sourceBufferName==="video"&&(u===z.BUFFER_ADD_CODEC_ERROR||u===z.BUFFER_APPEND_ERROR)&&d.some(({codecSet:C,audioCodec:_})=>i.codecSet!==C&&i.audioCodec===_),{type:S,groupId:T}=(a=e.context)!=null?a:{};for(let C=d.length;C--;){const _=(C+f)%d.length;if(_!==f&&_>=m&&_<=h&&d[_].loadError===0){var o,l;const b=d[_];if(u===z.FRAG_GAP&&p===we.MAIN&&e.frag){const I=d[_].details;if(I){const A=Vc(e.frag,I.fragments,e.frag.start);if(A!=null&&A.gap)continue}}else{if(S===He.AUDIO_TRACK&&b.hasAudioGroup(T)||S===He.SUBTITLE_TRACK&&b.hasSubtitleGroup(T))continue;if(p===we.AUDIO&&(o=i.audioGroups)!=null&&o.some(I=>b.hasAudioGroup(I))||p===we.SUBTITLE&&(l=i.subtitleGroups)!=null&&l.some(I=>b.hasSubtitleGroup(I))||g&&i.audioCodec===b.audioCodec||!g&&i.audioCodec!==b.audioCodec||x&&i.codecSet===b.codecSet)continue}c=_;break}}if(c>-1&&n.loadLevel!==c)return e.levelRetry=!0,this.playlistError=0,{action:zt.SendAlternateToPenaltyBox,flags:sn.None,nextAutoLevel:c}}return{action:zt.SendAlternateToPenaltyBox,flags:sn.MoveAllAlternatesMatchingHost}}onErrorOut(e,r){var n;switch((n=r.errorAction)==null?void 0:n.action){case zt.DoNothing:break;case zt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(r),!r.errorAction.resolved&&r.details!==z.FRAG_GAP?r.fatal=!0:/MediaSource readyState: ended/.test(r.error.message)&&(this.warn(`MediaSource ended after "${r.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(r.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const r=this.hls,n=e.errorAction;if(!n)return;const{flags:i,hdcpLevel:s,nextAutoLevel:a}=n;switch(i){case sn.None:this.switchLevel(e,a);break;case sn.MoveAllAlternatesMatchingHDCP:s&&(r.maxHdcpLevel=Zh[Zh.indexOf(s)-1],n.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${r.maxHdcpLevel}" or lower`);break}n.resolved||this.switchLevel(e,a)}switchLevel(e,r){r!==void 0&&e.errorAction&&(this.warn(`switching to level ${r} after ${e.details}`),this.hls.nextAutoLevel=r,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}}class Im{constructor(e,r){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=U.log.bind(U,`${r}:`),this.warn=U.warn.bind(U,`${r}:`),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.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,r,n){const i=r==null?void 0:r.renditionReports;if(i){let s=-1;for(let a=0;a=0&&c>r.partTarget&&(l+=1)}const u=n&&Rv(n);return new Iv(o,l>=0?l:void 0,u)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,r,n){const{details:i,stats:s}=r,a=self.performance.now(),o=s.loading.first?Math.max(0,a-s.loading.first):0;if(i.advancedDateTime=Date.now()-o,i.live||n!=null&&n.live){if(i.reloaded(n),n&&this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),n&&i.fragments.length>0&&XP(n,i),!this.canLoad||!i.live)return;let l,u,c;if(i.canBlockReload&&i.endSN&&i.advanced){const v=this.hls.config.lowLatencyMode,g=i.lastPartSn,y=i.endSN,x=i.lastPartIndex,S=x!==-1,T=g===y,C=v?0:x;S?(u=T?y+1:g,c=T?C:x+1):u=y+1;const _=i.age,b=_+i.ageHeader;let I=Math.min(b-i.partTarget,i.targetduration*1.5);if(I>0){if(n&&I>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${I} with playlist age: ${i.age}`),I=0;else{const A=Math.floor(I/i.targetduration);if(u+=A,c!==void 0){const k=Math.round(I%i.targetduration/i.partTarget);c+=k}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${_.toFixed(2)}s goal: ${I} skip sn ${A} to part ${c}`)}i.tuneInGoal=I}if(l=this.getDeliveryDirectives(i,r.deliveryDirectives,u,c),v||!T){this.loadPlaylist(l);return}}else(i.canBlockReload||i.canSkipUntil)&&(l=this.getDeliveryDirectives(i,r.deliveryDirectives,u,c));const d=this.hls.mainForwardBufferInfo,f=d?d.end-d.len:0,m=(i.edge-f)*1e3,h=eO(i,m);i.updated&&a>this.requestScheduled+h&&(this.requestScheduled=s.loading.start),u!==void 0&&i.canBlockReload?this.requestScheduled=s.loading.first+h-(i.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+hthis.loadPlaylist(l),p)}else this.clearTimer()}getDeliveryDirectives(e,r,n,i){let s=Rv(e);return r!=null&&r.skip&&e.deltaUpdateFailed&&(n=r.msn,i=r.part,s=Ou.No),new Iv(n,i,s)}checkRetry(e){const r=e.details,n=$c(e),i=e.errorAction,{action:s,retryCount:a=0,retryConfig:o}=i||{},l=!!i&&!!o&&(s===zt.RetryRequest||!i.resolved&&s===zt.SendAlternateToPenaltyBox);if(l){var u;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(n&&(u=e.context)!=null&&u.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${r}" without delivery-directives`),this.loadPlaylist();else{const c=Rm(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),c),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${r}" in ${c}ms`)}e.levelRetry=!0,i.resolved=!0}return l}}class Os{constructor(e,r=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=r,this.totalWeight_=n}sample(e,r){const n=Math.pow(this.alpha_,e);this.estimate_=r*(1-n)+n*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_}}class lO{constructor(e,r,n,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Os(e),this.fast_=new Os(r),this.defaultTTFB_=i,this.ttfb_=new Os(e)}update(e,r){const{slow_:n,fast_:i,ttfb_:s}=this;n.halfLife!==e&&(this.slow_=new Os(e,n.getEstimate(),n.getTotalWeight())),i.halfLife!==r&&(this.fast_=new Os(r,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new Os(e,s.getEstimate(),s.getTotalWeight()))}sample(e,r){e=Math.max(e,this.minDelayMs_);const n=8*r,i=e/1e3,s=n/i;this.fast_.sample(i,s),this.slow_.sample(i,s)}sampleTTFB(e){const r=e/1e3,n=Math.sqrt(2)*Math.exp(-Math.pow(r,2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const DT={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Mv={};function uO(t,e,r,n,i,s){const a=t.audioCodec?t.audioGroups:null,o=s==null?void 0:s.audioCodec,l=s==null?void 0:s.channels,u=l?parseInt(l):o?1/0:2;let c=null;if(a!=null&&a.length)try{a.length===1&&a[0]?c=e.groups[a[0]].channels:c=a.reduce((d,f)=>{if(f){const m=e.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(h=>{d[h]=(d[h]||0)+m.channels[h]})}return d},{2:0})}catch{return!0}return t.videoCodec!==void 0&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(n,30)||t.videoRange!=="SDR"&&t.videoRange!==r||t.bitrate>Math.max(i,8e6))||!!c&&pe(u)&&Object.keys(c).some(d=>parseInt(d)>u)}function cO(t,e,r){const n=t.videoCodec,i=t.audioCodec;if(!n||!i||!r)return Promise.resolve(DT);const s={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(t.bitrate*.9,t.averageBitrate)),framerate:t.frameRate||30},a=t.videoRange;a!=="SDR"&&(s.transferFunction=a.toLowerCase());const o=n.split(",").map(l=>({type:"media-source",video:jt(jt({},s),{},{contentType:pl(l,"video")})}));return i&&t.audioGroups&&t.audioGroups.forEach(l=>{var u;l&&((u=e.groups[l])==null||u.tracks.forEach(c=>{if(c.groupId===l){const d=c.channels||"",f=parseFloat(d);pe(f)&&f>2&&o.push.apply(o,i.split(",").map(m=>({type:"media-source",audio:{contentType:pl(m,"audio"),channels:""+f}})))}}))}),Promise.all(o.map(l=>{const u=dO(l);return Mv[u]||(Mv[u]=r.decodingInfo(l))})).then(l=>({supported:!l.some(u=>!u.supported),configurations:o,decodingInfoResults:l})).catch(l=>({supported:!1,configurations:o,decodingInfoResults:[],error:l}))}function dO(t){const{audio:e,video:r}=t,n=r||e;if(n){const i=n.contentType.split('"')[1];if(r)return`r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${i}_${Math.ceil(r.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${i}`}return""}function fO(){if(typeof matchMedia=="function"){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return t.matches===!0}return!1}function hO(t,e){let r=!1,n=[];return t&&(r=t!=="SDR",n=[t]),e&&(n=e.allowedVideoRanges||Bc.slice(0),r=e.preferHDR!==void 0?e.preferHDR:fO(),r?n=n.filter(i=>i!=="SDR"):n=["SDR"]),{preferHDR:r,allowedVideoRanges:n}}function pO(t,e,r,n,i){const s=Object.keys(t),a=n==null?void 0:n.channels,o=n==null?void 0:n.audioCodec,l=a&&parseInt(a)===2;let u=!0,c=!1,d=1/0,f=1/0,m=1/0,h=0,p=[];const{preferHDR:v,allowedVideoRanges:g}=hO(e,i);for(let T=s.length;T--;){const C=t[s[T]];u=C.channels[2]>0,d=Math.min(d,C.minHeight),f=Math.min(f,C.minFramerate),m=Math.min(m,C.minBitrate);const _=g.filter(b=>C.videoRanges[b]>0);_.length>0&&(c=!0,p=_)}d=pe(d)?d:0,f=pe(f)?f:0;const y=Math.max(1080,d),x=Math.max(30,f);return m=pe(m)?m:r,r=Math.max(m,r),c||(e=void 0,p=[]),{codecSet:s.reduce((T,C)=>{const _=t[C];if(C===T)return T;if(_.minBitrate>r)return Wn(C,`min bitrate of ${_.minBitrate} > current estimate of ${r}`),T;if(!_.hasDefaultAudio)return Wn(C,"no renditions with default or auto-select sound found"),T;if(o&&C.indexOf(o.substring(0,4))%5!==0)return Wn(C,`audio codec preference "${o}" not found`),T;if(a&&!l){if(!_.channels[a])return Wn(C,`no renditions with ${a} channel sound found (channels options: ${Object.keys(_.channels)})`),T}else if((!o||l)&&u&&_.channels[2]===0)return Wn(C,"no renditions with stereo sound found"),T;return _.minHeight>y?(Wn(C,`min resolution of ${_.minHeight} > maximum of ${y}`),T):_.minFramerate>x?(Wn(C,`min framerate of ${_.minFramerate} > maximum of ${x}`),T):p.some(b=>_.videoRanges[b]>0)?_.maxScore=Fc(T)||_.fragmentError>t[T].fragmentError)?T:(h=_.maxScore,C):(Wn(C,`no variants with VIDEO-RANGE of ${JSON.stringify(p)} found`),T)},void 0),videoRanges:p,preferHDR:v,minFramerate:f,minBitrate:m}}function Wn(t,e){U.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function mO(t){return t.reduce((e,r)=>{let n=e.groups[r.groupId];n||(n=e.groups[r.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),n.tracks.push(r);const i=r.channels||"2";return n.channels[i]=(n.channels[i]||0)+1,n.hasDefault=n.hasDefault||r.default,n.hasAutoSelect=n.hasAutoSelect||r.autoselect,n.hasDefault&&(e.hasDefaultAudio=!0),n.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function gO(t,e,r,n){return t.slice(r,n+1).reduce((i,s)=>{if(!s.codecSet)return i;const a=s.audioGroups;let o=i[s.codecSet];o||(i[s.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),o.minBitrate=Math.min(o.minBitrate,s.bitrate);const l=Math.min(s.height,s.width);return o.minHeight=Math.min(o.minHeight,l),o.minFramerate=Math.min(o.minFramerate,s.frameRate),o.maxScore=Math.max(o.maxScore,s.score),o.fragmentError+=s.fragmentError,o.videoRanges[s.videoRange]=(o.videoRanges[s.videoRange]||0)+1,a&&a.forEach(u=>{if(!u)return;const c=e.groups[u];c&&(o.hasDefaultAudio=o.hasDefaultAudio||e.hasDefaultAudio?c.hasDefault:c.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(c.channels).forEach(d=>{o.channels[d]=(o.channels[d]||0)+c.channels[d]}))}),i},{})}function Dn(t,e,r){if("attrs"in t){const n=e.indexOf(t);if(n!==-1)return n}for(let n=0;nn.indexOf(i)===-1)}function Ms(t,e){const{audioCodec:r,channels:n}=t;return(r===void 0||(e.audioCodec||"").substring(0,4)===r.substring(0,4))&&(n===void 0||n===(e.channels||"2"))}function yO(t,e,r,n,i){const s=e[n],o=e.reduce((f,m,h)=>{const p=m.uri;return(f[p]||(f[p]=[])).push(h),f},{})[s.uri];o.length>1&&(n=Math.max.apply(Math,o));const l=s.videoRange,u=s.frameRate,c=s.codecSet.substring(0,4),d=Nv(e,n,f=>{if(f.videoRange!==l||f.frameRate!==u||f.codecSet.substring(0,4)!==c)return!1;const m=f.audioGroups,h=r.filter(p=>!m||m.indexOf(p.groupId)!==-1);return Dn(t,h,i)>-1});return d>-1?d:Nv(e,n,f=>{const m=f.audioGroups,h=r.filter(p=>!m||m.indexOf(p.groupId)!==-1);return Dn(t,h,i)>-1})}function Nv(t,e,r){for(let n=e;n;n--)if(r(t[n]))return n;for(let n=e+1;n{const{fragCurrent:r,partCurrent:n,hls:i}=this,{autoLevelEnabled:s,media:a}=i;if(!r||!a)return;const o=performance.now(),l=n?n.stats:r.stats,u=n?n.duration:r.duration,c=o-l.loading.start,d=i.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||r.level<=d){this.clearTimer(),this._nextAutoLevel=-1;return}if(!s||a.paused||!a.playbackRate||!a.readyState)return;const f=i.mainForwardBufferInfo;if(f===null)return;const m=this.bwEstimator.getEstimateTTFB(),h=Math.abs(a.playbackRate);if(c<=Math.max(m,1e3*(u/(h*2))))return;const p=f.len/h,v=l.loading.first?l.loading.first-l.loading.start:-1,g=l.loaded&&v>-1,y=this.getBwEstimate(),x=i.levels,S=x[r.level],T=l.total||Math.max(l.loaded,Math.round(u*S.averageBitrate/8));let C=g?c-v:c;C<1&&g&&(C=Math.min(c,l.loaded*8/y));const _=g?l.loaded*1e3/C:0,b=_?(T-l.loaded)/_:T*8/y+m/1e3;if(b<=p)return;const I=_?_*8:y;let A=Number.POSITIVE_INFINITY,k;for(k=r.level-1;k>d;k--){const P=x[k].maxBitrate;if(A=this.getTimeToLoadFrag(m/1e3,I,u*P,!x[k].details),A=b||A>u*10)return;i.nextLoadLevel=i.nextAutoLevel=k,g?this.bwEstimator.sample(c-Math.min(m,v),l.loaded):this.bwEstimator.sampleTTFB(c);const O=x[k].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>O&&this.resetEstimator(O),this.clearTimer(),U.warn(`[abr] Fragment ${r.sn}${n?" part "+n.index:""} of level ${r.level} is loading too slowly; + */var gd=L,rC=tC;function nC(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var iC=typeof Object.is=="function"?Object.is:nC,sC=rC.useSyncExternalStore,aC=gd.useRef,oC=gd.useEffect,lC=gd.useMemo,uC=gd.useDebugValue;eE.useSyncExternalStoreWithSelector=function(t,e,r,n,i){var s=aC(null);if(s.current===null){var a={hasValue:!1,value:null};s.current=a}else a=s.current;s=lC(function(){function l(m){if(!u){if(u=!0,c=m,m=n(m),i!==void 0&&a.hasValue){var h=a.value;if(i(h,m))return d=h}return d=m}if(h=d,iC(c,m))return h;var p=n(m);return i!==void 0&&i(h,p)?h:(c=m,d=p)}var u=!1,c,d,f=r===void 0?null:r;return[function(){return l(e())},f===null?void 0:function(){return l(f())}]},[e,r,n,i]);var o=sC(t,s[0],s[1]);return oC(function(){a.hasValue=!0,a.value=o},[o]),uC(o),o};JS.exports=eE;var cC=JS.exports;const dC=dp(cC),nE={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_API_URL:""},{useDebugValue:fC}=ne,{useSyncExternalStoreWithSelector:hC}=dC;let O0=!1;const pC=t=>t;function mC(t,e=pC,r){(nE?"production":void 0)!=="production"&&r&&!O0&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),O0=!0);const n=hC(t.subscribe,t.getState,t.getServerState||t.getInitialState,e,r);return fC(n),n}const gC=t=>{(nE?"production":void 0)!=="production"&&typeof t!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof t=="function"?H_(t):t,r=(n,i)=>mC(e,n,i);return Object.assign(r,e),r},vC=t=>gC,yC={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1,VITE_API_URL:""};function xC(t,e){let r;try{r=t()}catch{return}return{getItem:i=>{var s;const a=l=>l===null?null:JSON.parse(l,void 0),o=(s=r.getItem(i))!=null?s:null;return o instanceof Promise?o.then(a):a(o)},setItem:(i,s)=>r.setItem(i,JSON.stringify(s,void 0)),removeItem:i=>r.removeItem(i)}}const Zo=t=>e=>{try{const r=t(e);return r instanceof Promise?r:{then(n){return Zo(n)(r)},catch(n){return this}}}catch(r){return{then(n){return this},catch(n){return Zo(n)(r)}}}},SC=(t,e)=>(r,n,i)=>{let s={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:v=>v,version:0,merge:(v,g)=>({...g,...v}),...e},a=!1;const o=new Set,l=new Set;let u;try{u=s.getStorage()}catch{}if(!u)return t((...v)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),r(...v)},n,i);const c=Zo(s.serialize),d=()=>{const v=s.partialize({...n()});let g;const y=c({state:v,version:s.version}).then(x=>u.setItem(s.name,x)).catch(x=>{g=x});if(g)throw g;return y},f=i.setState;i.setState=(v,g)=>{f(v,g),d()};const m=t((...v)=>{r(...v),d()},n,i);let h;const p=()=>{var v;if(!u)return;a=!1,o.forEach(y=>y(n()));const g=((v=s.onRehydrateStorage)==null?void 0:v.call(s,n()))||void 0;return Zo(u.getItem.bind(u))(s.name).then(y=>{if(y)return s.deserialize(y)}).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==s.version){if(s.migrate)return s.migrate(y.state,y.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return y.state}).then(y=>{var x;return h=s.merge(y,(x=n())!=null?x:m),r(h,!0),d()}).then(()=>{g==null||g(h,void 0),a=!0,l.forEach(y=>y(h))}).catch(y=>{g==null||g(void 0,y)})};return i.persist={setOptions:v=>{s={...s,...v},v.getStorage&&(u=v.getStorage())},clearStorage:()=>{u==null||u.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>p(),hasHydrated:()=>a,onHydrate:v=>(o.add(v),()=>{o.delete(v)}),onFinishHydration:v=>(l.add(v),()=>{l.delete(v)})},p(),h||m},EC=(t,e)=>(r,n,i)=>{let s={storage:xC(()=>localStorage),partialize:p=>p,version:0,merge:(p,v)=>({...v,...p}),...e},a=!1;const o=new Set,l=new Set;let u=s.storage;if(!u)return t((...p)=>{console.warn(`[zustand persist middleware] Unable to update item '${s.name}', the given storage is currently unavailable.`),r(...p)},n,i);const c=()=>{const p=s.partialize({...n()});return u.setItem(s.name,{state:p,version:s.version})},d=i.setState;i.setState=(p,v)=>{d(p,v),c()};const f=t((...p)=>{r(...p),c()},n,i);i.getInitialState=()=>f;let m;const h=()=>{var p,v;if(!u)return;a=!1,o.forEach(y=>{var x;return y((x=n())!=null?x:f)});const g=((v=s.onRehydrateStorage)==null?void 0:v.call(s,(p=n())!=null?p:f))||void 0;return Zo(u.getItem.bind(u))(s.name).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==s.version){if(s.migrate)return[!0,s.migrate(y.state,y.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,y.state];return[!1,void 0]}).then(y=>{var x;const[S,T]=y;if(m=s.merge(T,(x=n())!=null?x:f),r(m,!0),S)return c()}).then(()=>{g==null||g(m,void 0),m=n(),a=!0,l.forEach(y=>y(m))}).catch(y=>{g==null||g(void 0,y)})};return i.persist={setOptions:p=>{s={...s,...p},p.storage&&(u=p.storage)},clearStorage:()=>{u==null||u.removeItem(s.name)},getOptions:()=>s,rehydrate:()=>h(),hasHydrated:()=>a,onHydrate:p=>(o.add(p),()=>{o.delete(p)}),onFinishHydration:p=>(l.add(p),()=>{l.delete(p)})},s.skipHydration||h(),m||f},TC=(t,e)=>"getStorage"in e||"serialize"in e||"deserialize"in e?((yC?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),SC(t,e)):EC(t,e),wC=TC,Ua=vC()(wC(t=>({access_token:localStorage.getItem("access_token")||"",refresh_token:localStorage.getItem("refresh_token")||"",profileData:null,isLoggedIn:!1,updateAccessToken:e=>{t({access_token:e})},updateProfileData:e=>{t({profileData:e})},login:(e,r,n)=>{localStorage.setItem("access_token",e),localStorage.setItem("refresh_token",r),t({access_token:e,refresh_token:r,profileData:n,isLoggedIn:!0})},logout:()=>{localStorage.removeItem("access_token"),localStorage.removeItem("refresh_token"),t({access_token:"",refresh_token:"",profileData:null,isLoggedIn:!1})}}),{name:"login-storage",getStorage:()=>localStorage})),ur=(t,e="")=>{const[r,n]=L.useState(null),[i,s]=L.useState(!0),[a,o]=L.useState(null),l=L.useRef(null),{updateProfileData:u,updateAccessToken:c,logout:d}=Ua(),f=Br(),m=L.useCallback(async()=>{var g;if(t===""){s(!1);return}t.startsWith("/")||(t=`/${t}`),t.startsWith("http")&&(e=""),e||(e="");let p;const v=new AbortController;l.current=v;try{p=await fetch(`${e}${t}`,{headers:{Authorization:`Bearer ${localStorage.getItem("access_token")}`},signal:v.signal});let y;try{y=await p.json()}catch{y=await p.text(),y=JSON.parse(y)}if(y.error&&y.message==="INVALID_TOKEN")throw new Error(JSON.stringify(y));n(y),s(!1),o(null)}catch(y){if((g=l.current)!=null&&g.signal.aborted)return;if(p=JSON.parse(y.message),p.message==="INVALID_TOKEN"){const S=await(await fetch(`${e}/api/auth/refresh`,{method:"POST",body:JSON.stringify({refresh_token:localStorage.getItem("refresh_token")}),headers:{"Content-Type":"application/json"}})).json();if(S.error){d(),f("/login"),s(!1);return}else{localStorage.setItem("access_token",S.data.access_token),c(S.data.access_token),u(S.data.user),m();return}}o(p),s(!1),n(null)}},[t]);return L.useEffect(()=>{s(!0),m()},[m]),{data:r,loading:i,error:a,fetchData:m,interupt:()=>{var p;(p=l.current)==null||p.abort()}}};function Ss(){const[t,e]=L.useState(null),[r,n]=L.useState(!1),[i,s]=L.useState(null),[a,o]=L.useState(null),{access_token:l,refresh_token:u}=Ua(),c={Authorization:`Bearer ${l}`,"x-refresh-token":u};return{data:t,handleSubmit:async({e:m="",url:h,body:p=t,headers:v={...c},dispatcher:g=null,dispatch:y=x=>x})=>{m&&m.preventDefault(),n(!0),s(null);try{const x={method:"POST",headers:{...v,...c,"Content-Type":p instanceof FormData?"multipart/form-data":"application/json"},body:p instanceof FormData?p:JSON.stringify(p)};h.startsWith("http")||(h=`${h}`);const S=await fetch(h,x);if(!S.ok)throw new Error(`Request failed with status ${S.status}`);const T=await S.json();g!==null&&y!==null?g(y(T)):(e(T),o(T)),n(!1),s(null)}catch(x){s(x.message),n(!1)}},handleChange:m=>{m.persist(),e(h=>({...h,[m.target.name]:m.target.value}))},pending:r,error:i,resMsg:a}}function iE(){const[t,e]=L.useState(null),[r,n]=L.useState(!1),[i,s]=L.useState(null),[a,o]=L.useState(null),{access_token:l,refresh_token:u}=Ua(),c={Authorization:`Bearer ${l}`,"x-refresh-token":u};return{data:t,handleSubmit:async({e:m="",url:h,body:p=t,headers:v={...c},dispatcher:g=null,dispatch:y=x=>x})=>{m&&m.preventDefault(),n(!0),s(null);try{const x={method:"DELETE",headers:{...v,...c,"Content-Type":p instanceof FormData?"multipart/form-data":"application/json"},body:p instanceof FormData?p:JSON.stringify(p)};h.startsWith("http")||(h=`${h}`);const S=await fetch(h,x);if(!S.ok)throw new Error(`Request failed with status ${S.status}`);const T=await S.json();g!==null&&y!==null?g(y(T)):(e(T),o(T)),n(!1),s(null)}catch(x){s(x.message),n(!1)}},handleChange:m=>{m.persist(),e(h=>({...h,[m.target.name]:m.target.value}))},pending:r,error:i,resMsg:a}}function sE(){const[t,e]=L.useState(null),[r,n]=L.useState(!1),[i,s]=L.useState(null),[a,o]=L.useState(null),{access_token:l,refresh_token:u}=Ua(),c={Authorization:`Bearer ${l}`,"x-refresh-token":u};return{data:t,handleSubmit:async({e:m="",url:h,body:p=t,headers:v={...c},dispatcher:g=null,dispatch:y=x=>x})=>{m&&m.preventDefault(),n(!0),s(null);try{const x={method:"PUT",headers:{...v,...c,"Content-Type":p instanceof FormData?"multipart/form-data":"application/json"},body:p instanceof FormData?p:JSON.stringify(p)};h.startsWith("http")||(h=`${h}`);const S=await fetch(h,x);if(!S.ok)throw new Error(`Request failed with status ${S.status}`);const T=await S.json();g!==null&&y!==null?g(y(T)):(e(T),o(T)),n(!1),s(null)}catch(x){s(x.message),n(!1)}},handleChange:m=>{m.persist(),e(h=>({...h,[m.target.name]:m.target.value}))},pending:r,error:i,resMsg:a}}const dm=()=>{const{login:t,logout:e,isLoggedIn:r,profileData:n,updateProfileData:i}=Ua(),{handleSubmit:s}=Ss(),a=c=>{if(c){if(c.error)throw new Error(c.error);if(c.data){const{access_token:d,refresh_token:f,user:m}=c.data;t(d,f,m)}}};return{login:async({username:c,password:d})=>{await s({url:"/api/auth/login",body:{username:c,password:d},dispatcher:a})},logout:()=>{e()},isLoggedIn:r,profileData:n,updateProfileData:c=>{i(c)}}},bC=({user:t,onClick:e})=>E.jsxs("article",{className:"flex flex-col items-center justify-center gap-2 cursor-pointer",onClick:e,children:[E.jsx("img",{className:"w-32 h-32 rounded-lg",src:`${t.profile_picture}`,alt:t.name}),E.jsx("h2",{className:"text-2xl max-w-32 text-neutral-200 overflow-hidden text-ellipsis",children:t.name})]}),LC=({selectedUser:t,isOpen:e,onClose:r,onSubmit:n})=>{const[i,s]=L.useState("");return E.jsxs(E.Fragment,{children:[E.jsx("section",{className:`fixed top-0 left-0 w-full h-full bg-black bg-opacity-0 z-50 ${e?"pointer-events-auto":"bg-opacity-0 pointer-events-none"} transition-opacity duration-300`,onClick:r})," ",E.jsxs("section",{className:`fixed top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-neutral-900 rounded-lg p-8 z-50 ${e?"opacity-100 pointer-events-auto":"opacity-0 pointer-events-none"} transition-opacity duration-300`,children:[E.jsx("input",{type:"password",placeholder:"Password",value:i,onChange:a=>s(a.target.value),className:"w-full px-4 py-2 mb-4 rounded-lg border border-neutral-300 focus:outline-none focus:ring-2 focus:ring-primary-500"}),E.jsx("button",{onClick:()=>n((t==null?void 0:t.name)||"",i),className:"w-full px-4 py-2 text-white bg-primary-500 rounded-lg hover:bg-primary-600 focus:outline-none focus:ring-2 focus:ring-primary-500",children:"Login"})]})]})},AC=()=>{const[t,e]=L.useState(!1),[r,n]=L.useState(null),{data:i,error:s}=ur("/api/auth/accounts"),{login:a}=dm(),o=Br();L.useEffect(()=>{i&&i.data.length===0&&o("/invite")},[i]),L.useEffect(()=>{s&&Ke.error(s.message)});const l=c=>{c.password_empty?u(c.name,""):(n(c),e(!0))},u=async(c,d)=>{try{await a({username:c,password:d}),o("/home")}catch(f){Ke.error(f.message)}};return E.jsxs(E.Fragment,{children:[E.jsx("section",{className:"flex flex-wrap items-center justify-center content-center gap-x-16 gap-y-8 px-80 py-32 max-h-screen h-screen max-w-screen",children:i&&i.data.map(c=>E.jsx(bC,{user:c,onClick:()=>l(c)},c.id))}),E.jsx(LC,{selectedUser:r,isOpen:t,onClose:()=>{e(!1),n(null)},onSubmit:u})]})},_C=()=>{const t=Br(),{logout:e}=dm();return L.useEffect(()=>{e(),t("/login")},[]),E.jsx("div",{children:"Logging out..."})};var El=t=>t.type==="checkbox",Js=t=>t instanceof Date,ar=t=>t==null;const aE=t=>typeof t=="object";var Rt=t=>!ar(t)&&!Array.isArray(t)&&aE(t)&&!Js(t),oE=t=>Rt(t)&&t.target?El(t.target)?t.target.checked:t.target.value:t,CC=t=>t.substring(0,t.search(/\.\d+(\.|$)/))||t,lE=(t,e)=>t.has(CC(e)),RC=t=>{const e=t.constructor&&t.constructor.prototype;return Rt(e)&&e.hasOwnProperty("isPrototypeOf")},fm=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function mr(t){let e;const r=Array.isArray(t);if(t instanceof Date)e=new Date(t);else if(t instanceof Set)e=new Set(t);else if(!(fm&&(t instanceof Blob||t instanceof FileList))&&(r||Rt(t)))if(e=r?[]:{},!r&&!RC(t))e=t;else for(const n in t)t.hasOwnProperty(n)&&(e[n]=mr(t[n]));else return t;return e}var vd=t=>Array.isArray(t)?t.filter(Boolean):[],bt=t=>t===void 0,ie=(t,e,r)=>{if(!e||!Rt(t))return r;const n=vd(e.split(/[,[\].]+?/)).reduce((i,s)=>ar(i)?i:i[s],t);return bt(n)||n===t?bt(t[e])?r:t[e]:n},Wr=t=>typeof t=="boolean",hm=t=>/^\w*$/.test(t),uE=t=>vd(t.replace(/["|']|\]/g,"").split(/\.|\[/)),Ze=(t,e,r)=>{let n=-1;const i=hm(e)?[e]:uE(e),s=i.length,a=s-1;for(;++nne.useContext(cE),IC=t=>{const{children:e,...r}=t;return ne.createElement(cE.Provider,{value:r},e)};var dE=(t,e,r,n=!0)=>{const i={defaultValues:e._defaultValues};for(const s in t)Object.defineProperty(i,s,{get:()=>{const a=s;return e._proxyFormState[a]!==fn.all&&(e._proxyFormState[a]=!n||fn.all),r&&(r[a]=!0),t[a]}});return i},gr=t=>Rt(t)&&!Object.keys(t).length,fE=(t,e,r,n)=>{r(t);const{name:i,...s}=t;return gr(s)||Object.keys(s).length>=Object.keys(e).length||Object.keys(s).find(a=>e[a]===(!n||fn.all))},bo=t=>Array.isArray(t)?t:[t],hE=(t,e,r)=>!t||!e||t===e||bo(t).some(n=>n&&(r?n===e:n.startsWith(e)||e.startsWith(n)));function pm(t){const e=ne.useRef(t);e.current=t,ne.useEffect(()=>{const r=!t.disabled&&e.current.subject&&e.current.subject.subscribe({next:e.current.next});return()=>{r&&r.unsubscribe()}},[t.disabled])}function kC(t){const e=yd(),{control:r=e.control,disabled:n,name:i,exact:s}=t||{},[a,o]=ne.useState(r._formState),l=ne.useRef(!0),u=ne.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),c=ne.useRef(i);return c.current=i,pm({disabled:n,next:d=>l.current&&hE(c.current,d.name,s)&&fE(d,u.current,r._updateFormState)&&o({...r._formState,...d}),subject:r._subjects.state}),ne.useEffect(()=>(l.current=!0,u.current.isValid&&r._updateValid(!0),()=>{l.current=!1}),[r]),dE(a,r,u.current,!1)}var Cn=t=>typeof t=="string",pE=(t,e,r,n,i)=>Cn(t)?(n&&e.watch.add(t),ie(r,t,i)):Array.isArray(t)?t.map(s=>(n&&e.watch.add(s),ie(r,s))):(n&&(e.watchAll=!0),r);function DC(t){const e=yd(),{control:r=e.control,name:n,defaultValue:i,disabled:s,exact:a}=t||{},o=ne.useRef(n);o.current=n,pm({disabled:s,subject:r._subjects.values,next:c=>{hE(o.current,c.name,a)&&u(mr(pE(o.current,r._names,c.values||r._formValues,!1,i)))}});const[l,u]=ne.useState(r._getWatch(n,i));return ne.useEffect(()=>r._removeUnmounted()),l}function PC(t){const e=yd(),{name:r,disabled:n,control:i=e.control,shouldUnregister:s}=t,a=lE(i._names.array,r),o=DC({control:i,name:r,defaultValue:ie(i._formValues,r,ie(i._defaultValues,r,t.defaultValue)),exact:!0}),l=kC({control:i,name:r,exact:!0}),u=ne.useRef(i.register(r,{...t.rules,value:o,...Wr(t.disabled)?{disabled:t.disabled}:{}}));return ne.useEffect(()=>{const c=i._options.shouldUnregister||s,d=(f,m)=>{const h=ie(i._fields,f);h&&h._f&&(h._f.mount=m)};if(d(r,!0),c){const f=mr(ie(i._options.defaultValues,r));Ze(i._defaultValues,r,f),bt(ie(i._formValues,r))&&Ze(i._formValues,r,f)}return()=>{(a?c&&!i._state.action:c)?i.unregister(r):d(r,!1)}},[r,i,a,s]),ne.useEffect(()=>{ie(i._fields,r)&&i._updateDisabledField({disabled:n,fields:i._fields,name:r,value:ie(i._fields,r)._f.value})},[n,r,i]),{field:{name:r,value:o,...Wr(n)||l.disabled?{disabled:l.disabled||n}:{},onChange:ne.useCallback(c=>u.current.onChange({target:{value:oE(c),name:r},type:vc.CHANGE}),[r]),onBlur:ne.useCallback(()=>u.current.onBlur({target:{value:ie(i._formValues,r),name:r},type:vc.BLUR}),[r,i]),ref:ne.useCallback(c=>{const d=ie(i._fields,r);d&&c&&(d._f.ref={focus:()=>c.focus(),select:()=>c.select(),setCustomValidity:f=>c.setCustomValidity(f),reportValidity:()=>c.reportValidity()})},[i._fields,r])},formState:l,fieldState:Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!ie(l.errors,r)},isDirty:{enumerable:!0,get:()=>!!ie(l.dirtyFields,r)},isTouched:{enumerable:!0,get:()=>!!ie(l.touchedFields,r)},isValidating:{enumerable:!0,get:()=>!!ie(l.validatingFields,r)},error:{enumerable:!0,get:()=>ie(l.errors,r)}})}}const OC=t=>t.render(PC(t));var mE=(t,e,r,n,i)=>e?{...r[t],types:{...r[t]&&r[t].types?r[t].types:{},[n]:i||!0}}:{},M0=t=>({isOnSubmit:!t||t===fn.onSubmit,isOnBlur:t===fn.onBlur,isOnChange:t===fn.onChange,isOnAll:t===fn.all,isOnTouch:t===fn.onTouched}),N0=(t,e,r)=>!r&&(e.watchAll||e.watch.has(t)||[...e.watch].some(n=>t.startsWith(n)&&/^\.\w+/.test(t.slice(n.length))));const Lo=(t,e,r,n)=>{for(const i of r||Object.keys(t)){const s=ie(t,i);if(s){const{_f:a,...o}=s;if(a){if(a.refs&&a.refs[0]&&e(a.refs[0],i)&&!n)return!0;if(a.ref&&e(a.ref,a.name)&&!n)return!0;if(Lo(o,e))break}else if(Rt(o)&&Lo(o,e))break}}};var MC=(t,e,r)=>{const n=bo(ie(t,r));return Ze(n,"root",e[r]),Ze(t,r,n),t},mm=t=>t.type==="file",ni=t=>typeof t=="function",yc=t=>{if(!fm)return!1;const e=t?t.ownerDocument:0;return t instanceof(e&&e.defaultView?e.defaultView.HTMLElement:HTMLElement)},_u=t=>Cn(t),gm=t=>t.type==="radio",xc=t=>t instanceof RegExp;const F0={value:!1,isValid:!1},U0={value:!0,isValid:!0};var gE=t=>{if(Array.isArray(t)){if(t.length>1){const e=t.filter(r=>r&&r.checked&&!r.disabled).map(r=>r.value);return{value:e,isValid:!!e.length}}return t[0].checked&&!t[0].disabled?t[0].attributes&&!bt(t[0].attributes.value)?bt(t[0].value)||t[0].value===""?U0:{value:t[0].value,isValid:!0}:U0:F0}return F0};const B0={isValid:!1,value:null};var vE=t=>Array.isArray(t)?t.reduce((e,r)=>r&&r.checked&&!r.disabled?{isValid:!0,value:r.value}:e,B0):B0;function $0(t,e,r="validate"){if(_u(t)||Array.isArray(t)&&t.every(_u)||Wr(t)&&!t)return{type:r,message:_u(t)?t:"",ref:e}}var Ps=t=>Rt(t)&&!xc(t)?t:{value:t,message:""},j0=async(t,e,r,n,i)=>{const{ref:s,refs:a,required:o,maxLength:l,minLength:u,min:c,max:d,pattern:f,validate:m,name:h,valueAsNumber:p,mount:v,disabled:g}=t._f,y=ie(e,h);if(!v||g)return{};const x=a?a[0]:s,S=O=>{n&&x.reportValidity&&(x.setCustomValidity(Wr(O)?"":O||""),x.reportValidity())},T={},C=gm(s),_=El(s),b=C||_,I=(p||mm(s))&&bt(s.value)&&bt(y)||yc(s)&&s.value===""||y===""||Array.isArray(y)&&!y.length,A=mE.bind(null,h,r,T),k=(O,P,G,K=Gn.maxLength,H=Gn.minLength)=>{const se=O?P:G;T[h]={type:O?K:H,message:se,ref:s,...A(O?K:H,se)}};if(i?!Array.isArray(y)||!y.length:o&&(!b&&(I||ar(y))||Wr(y)&&!y||_&&!gE(a).isValid||C&&!vE(a).isValid)){const{value:O,message:P}=_u(o)?{value:!!o,message:o}:Ps(o);if(O&&(T[h]={type:Gn.required,message:P,ref:x,...A(Gn.required,P)},!r))return S(P),T}if(!I&&(!ar(c)||!ar(d))){let O,P;const G=Ps(d),K=Ps(c);if(!ar(y)&&!isNaN(y)){const H=s.valueAsNumber||y&&+y;ar(G.value)||(O=H>G.value),ar(K.value)||(P=Hnew Date(new Date().toDateString()+" "+j),W=s.type=="time",F=s.type=="week";Cn(G.value)&&y&&(O=W?se(y)>se(G.value):F?y>G.value:H>new Date(G.value)),Cn(K.value)&&y&&(P=W?se(y)+O.value,K=!ar(P.value)&&y.length<+P.value;if((G||K)&&(k(G,O.message,P.message),!r))return S(T[h].message),T}if(f&&!I&&Cn(y)){const{value:O,message:P}=Ps(f);if(xc(O)&&!y.match(O)&&(T[h]={type:Gn.pattern,message:P,ref:s,...A(Gn.pattern,P)},!r))return S(P),T}if(m){if(ni(m)){const O=await m(y,e),P=$0(O,x);if(P&&(T[h]={...P,...A(Gn.validate,P.message)},!r))return S(P.message),T}else if(Rt(m)){let O={};for(const P in m){if(!gr(O)&&!r)break;const G=$0(await m[P](y,e),x,P);G&&(O={...G,...A(P,G.message)},S(G.message),r&&(T[h]=O))}if(!gr(O)&&(T[h]={ref:x,...O},!r))return T}}return S(!0),T};function NC(t,e){const r=e.slice(0,-1).length;let n=0;for(;n{let t=[];return{get observers(){return t},next:i=>{for(const s of t)s.next&&s.next(i)},subscribe:i=>(t.push(i),{unsubscribe:()=>{t=t.filter(s=>s!==i)}}),unsubscribe:()=>{t=[]}}},Sc=t=>ar(t)||!aE(t);function Li(t,e){if(Sc(t)||Sc(e))return t===e;if(Js(t)&&Js(e))return t.getTime()===e.getTime();const r=Object.keys(t),n=Object.keys(e);if(r.length!==n.length)return!1;for(const i of r){const s=t[i];if(!n.includes(i))return!1;if(i!=="ref"){const a=e[i];if(Js(s)&&Js(a)||Rt(s)&&Rt(a)||Array.isArray(s)&&Array.isArray(a)?!Li(s,a):s!==a)return!1}}return!0}var yE=t=>t.type==="select-multiple",UC=t=>gm(t)||El(t),af=t=>yc(t)&&t.isConnected,xE=t=>{for(const e in t)if(ni(t[e]))return!0;return!1};function Ec(t,e={}){const r=Array.isArray(t);if(Rt(t)||r)for(const n in t)Array.isArray(t[n])||Rt(t[n])&&!xE(t[n])?(e[n]=Array.isArray(t[n])?[]:{},Ec(t[n],e[n])):ar(t[n])||(e[n]=!0);return e}function SE(t,e,r){const n=Array.isArray(t);if(Rt(t)||n)for(const i in t)Array.isArray(t[i])||Rt(t[i])&&!xE(t[i])?bt(e)||Sc(r[i])?r[i]=Array.isArray(t[i])?Ec(t[i],[]):{...Ec(t[i])}:SE(t[i],ar(e)?{}:e[i],r[i]):r[i]=!Li(t[i],e[i]);return r}var Ql=(t,e)=>SE(t,e,Ec(e)),EE=(t,{valueAsNumber:e,valueAsDate:r,setValueAs:n})=>bt(t)?t:e?t===""?NaN:t&&+t:r&&Cn(t)?new Date(t):n?n(t):t;function of(t){const e=t.ref;if(!(t.refs?t.refs.every(r=>r.disabled):e.disabled))return mm(e)?e.files:gm(e)?vE(t.refs).value:yE(e)?[...e.selectedOptions].map(({value:r})=>r):El(e)?gE(t.refs).value:EE(bt(e.value)?t.ref.value:e.value,t)}var BC=(t,e,r,n)=>{const i={};for(const s of t){const a=ie(e,s);a&&Ze(i,s,a._f)}return{criteriaMode:r,names:[...t],fields:i,shouldUseNativeValidation:n}},eo=t=>bt(t)?t:xc(t)?t.source:Rt(t)?xc(t.value)?t.value.source:t.value:t;const V0="AsyncFunction";var $C=t=>(!t||!t.validate)&&!!(ni(t.validate)&&t.validate.constructor.name===V0||Rt(t.validate)&&Object.values(t.validate).find(e=>e.constructor.name===V0)),jC=t=>t.mount&&(t.required||t.min||t.max||t.maxLength||t.minLength||t.pattern||t.validate);function G0(t,e,r){const n=ie(t,r);if(n||hm(r))return{error:n,name:r};const i=r.split(".");for(;i.length;){const s=i.join("."),a=ie(e,s),o=ie(t,s);if(a&&!Array.isArray(a)&&r!==s)return{name:r};if(o&&o.type)return{name:s,error:o};i.pop()}return{name:r}}var VC=(t,e,r,n,i)=>i.isOnAll?!1:!r&&i.isOnTouch?!(e||t):(r?n.isOnBlur:i.isOnBlur)?!t:(r?n.isOnChange:i.isOnChange)?t:!0,GC=(t,e)=>!vd(ie(t,e)).length&&kt(t,e);const zC={mode:fn.onSubmit,reValidateMode:fn.onChange,shouldFocusError:!0};function HC(t={}){let e={...zC,...t},r={submitCount:0,isDirty:!1,isLoading:ni(e.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:e.errors||{},disabled:e.disabled||!1},n={},i=Rt(e.defaultValues)||Rt(e.values)?mr(e.defaultValues||e.values)||{}:{},s=e.shouldUnregister?{}:mr(i),a={action:!1,mount:!1,watch:!1},o={mount:new Set,unMount:new Set,array:new Set,watch:new Set},l,u=0;const c={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},d={values:sf(),array:sf(),state:sf()},f=M0(e.mode),m=M0(e.reValidateMode),h=e.criteriaMode===fn.all,p=R=>N=>{clearTimeout(u),u=setTimeout(R,N)},v=async R=>{if(c.isValid||R){const N=e.resolver?gr((await b()).errors):await A(n,!0);N!==r.isValid&&d.state.next({isValid:N})}},g=(R,N)=>{(c.isValidating||c.validatingFields)&&((R||Array.from(o.mount)).forEach($=>{$&&(N?Ze(r.validatingFields,$,N):kt(r.validatingFields,$))}),d.state.next({validatingFields:r.validatingFields,isValidating:!gr(r.validatingFields)}))},y=(R,N=[],$,re,Z=!0,X=!0)=>{if(re&&$){if(a.action=!0,X&&Array.isArray(ie(n,R))){const ge=$(ie(n,R),re.argA,re.argB);Z&&Ze(n,R,ge)}if(X&&Array.isArray(ie(r.errors,R))){const ge=$(ie(r.errors,R),re.argA,re.argB);Z&&Ze(r.errors,R,ge),GC(r.errors,R)}if(c.touchedFields&&X&&Array.isArray(ie(r.touchedFields,R))){const ge=$(ie(r.touchedFields,R),re.argA,re.argB);Z&&Ze(r.touchedFields,R,ge)}c.dirtyFields&&(r.dirtyFields=Ql(i,s)),d.state.next({name:R,isDirty:O(R,N),dirtyFields:r.dirtyFields,errors:r.errors,isValid:r.isValid})}else Ze(s,R,N)},x=(R,N)=>{Ze(r.errors,R,N),d.state.next({errors:r.errors})},S=R=>{r.errors=R,d.state.next({errors:r.errors,isValid:!1})},T=(R,N,$,re)=>{const Z=ie(n,R);if(Z){const X=ie(s,R,bt($)?ie(i,R):$);bt(X)||re&&re.defaultChecked||N?Ze(s,R,N?X:of(Z._f)):K(R,X),a.mount&&v()}},C=(R,N,$,re,Z)=>{let X=!1,ge=!1;const oe={name:R},xe=!!(ie(n,R)&&ie(n,R)._f&&ie(n,R)._f.disabled);if(!$||re){c.isDirty&&(ge=r.isDirty,r.isDirty=oe.isDirty=O(),X=ge!==oe.isDirty);const ce=xe||Li(ie(i,R),N);ge=!!(!xe&&ie(r.dirtyFields,R)),ce||xe?kt(r.dirtyFields,R):Ze(r.dirtyFields,R,!0),oe.dirtyFields=r.dirtyFields,X=X||c.dirtyFields&&ge!==!ce}if($){const ce=ie(r.touchedFields,R);ce||(Ze(r.touchedFields,R,$),oe.touchedFields=r.touchedFields,X=X||c.touchedFields&&ce!==$)}return X&&Z&&d.state.next(oe),X?oe:{}},_=(R,N,$,re)=>{const Z=ie(r.errors,R),X=c.isValid&&Wr(N)&&r.isValid!==N;if(t.delayError&&$?(l=p(()=>x(R,$)),l(t.delayError)):(clearTimeout(u),l=null,$?Ze(r.errors,R,$):kt(r.errors,R)),($?!Li(Z,$):Z)||!gr(re)||X){const ge={...re,...X&&Wr(N)?{isValid:N}:{},errors:r.errors,name:R};r={...r,...ge},d.state.next(ge)}},b=async R=>{g(R,!0);const N=await e.resolver(s,e.context,BC(R||o.mount,n,e.criteriaMode,e.shouldUseNativeValidation));return g(R),N},I=async R=>{const{errors:N}=await b(R);if(R)for(const $ of R){const re=ie(N,$);re?Ze(r.errors,$,re):kt(r.errors,$)}else r.errors=N;return N},A=async(R,N,$={valid:!0})=>{for(const re in R){const Z=R[re];if(Z){const{_f:X,...ge}=Z;if(X){const oe=o.array.has(X.name),xe=Z._f&&$C(Z._f);xe&&c.validatingFields&&g([re],!0);const ce=await j0(Z,s,h,e.shouldUseNativeValidation&&!N,oe);if(xe&&c.validatingFields&&g([re]),ce[X.name]&&($.valid=!1,N))break;!N&&(ie(ce,X.name)?oe?MC(r.errors,ce,X.name):Ze(r.errors,X.name,ce[X.name]):kt(r.errors,X.name))}!gr(ge)&&await A(ge,N,$)}}return $.valid},k=()=>{for(const R of o.unMount){const N=ie(n,R);N&&(N._f.refs?N._f.refs.every($=>!af($)):!af(N._f.ref))&&Ee(R)}o.unMount=new Set},O=(R,N)=>(R&&N&&Ze(s,R,N),!Li(te(),i)),P=(R,N,$)=>pE(R,o,{...a.mount?s:bt(N)?i:Cn(R)?{[R]:N}:N},$,N),G=R=>vd(ie(a.mount?s:i,R,t.shouldUnregister?ie(i,R,[]):[])),K=(R,N,$={})=>{const re=ie(n,R);let Z=N;if(re){const X=re._f;X&&(!X.disabled&&Ze(s,R,EE(N,X)),Z=yc(X.ref)&&ar(N)?"":N,yE(X.ref)?[...X.ref.options].forEach(ge=>ge.selected=Z.includes(ge.value)):X.refs?El(X.ref)?X.refs.length>1?X.refs.forEach(ge=>(!ge.defaultChecked||!ge.disabled)&&(ge.checked=Array.isArray(Z)?!!Z.find(oe=>oe===ge.value):Z===ge.value)):X.refs[0]&&(X.refs[0].checked=!!Z):X.refs.forEach(ge=>ge.checked=ge.value===Z):mm(X.ref)?X.ref.value="":(X.ref.value=Z,X.ref.type||d.values.next({name:R,values:{...s}})))}($.shouldDirty||$.shouldTouch)&&C(R,Z,$.shouldTouch,$.shouldDirty,!0),$.shouldValidate&&j(R)},H=(R,N,$)=>{for(const re in N){const Z=N[re],X=`${R}.${re}`,ge=ie(n,X);(o.array.has(R)||!Sc(Z)||ge&&!ge._f)&&!Js(Z)?H(X,Z,$):K(X,Z,$)}},se=(R,N,$={})=>{const re=ie(n,R),Z=o.array.has(R),X=mr(N);Ze(s,R,X),Z?(d.array.next({name:R,values:{...s}}),(c.isDirty||c.dirtyFields)&&$.shouldDirty&&d.state.next({name:R,dirtyFields:Ql(i,s),isDirty:O(R,X)})):re&&!re._f&&!ar(X)?H(R,X,$):K(R,X,$),N0(R,o)&&d.state.next({...r}),d.values.next({name:a.mount?R:void 0,values:{...s}})},W=async R=>{a.mount=!0;const N=R.target;let $=N.name,re=!0;const Z=ie(n,$),X=()=>N.type?of(Z._f):oE(R),ge=oe=>{re=Number.isNaN(oe)||Li(oe,ie(s,$,oe))};if(Z){let oe,xe;const ce=X(),Ge=R.type===vc.BLUR||R.type===vc.FOCUS_OUT,nr=!jC(Z._f)&&!e.resolver&&!ie(r.errors,$)&&!Z._f.deps||VC(Ge,ie(r.touchedFields,$),r.isSubmitted,m,f),mt=N0($,o,Ge);Ze(s,$,ce),Ge?(Z._f.onBlur&&Z._f.onBlur(R),l&&l(0)):Z._f.onChange&&Z._f.onChange(R);const Pe=C($,ce,Ge,!1),Le=!gr(Pe)||mt;if(!Ge&&d.values.next({name:$,type:R.type,values:{...s}}),nr)return c.isValid&&(t.mode==="onBlur"?Ge&&v():v()),Le&&d.state.next({name:$,...mt?{}:Pe});if(!Ge&&mt&&d.state.next({...r}),e.resolver){const{errors:Nt}=await b([$]);if(ge(ce),re){const Xi=G0(r.errors,n,$),hr=G0(Nt,n,Xi.name||$);oe=hr.error,$=hr.name,xe=gr(Nt)}}else g([$],!0),oe=(await j0(Z,s,h,e.shouldUseNativeValidation))[$],g([$]),ge(ce),re&&(oe?xe=!1:c.isValid&&(xe=await A(n,!0)));re&&(Z._f.deps&&j(Z._f.deps),_($,xe,oe,Pe))}},F=(R,N)=>{if(ie(r.errors,N)&&R.focus)return R.focus(),1},j=async(R,N={})=>{let $,re;const Z=bo(R);if(e.resolver){const X=await I(bt(R)?R:Z);$=gr(X),re=R?!Z.some(ge=>ie(X,ge)):$}else R?(re=(await Promise.all(Z.map(async X=>{const ge=ie(n,X);return await A(ge&&ge._f?{[X]:ge}:ge)}))).every(Boolean),!(!re&&!r.isValid)&&v()):re=$=await A(n);return d.state.next({...!Cn(R)||c.isValid&&$!==r.isValid?{}:{name:R},...e.resolver||!R?{isValid:$}:{},errors:r.errors}),N.shouldFocus&&!re&&Lo(n,F,R?Z:o.mount),re},te=R=>{const N={...a.mount?s:i};return bt(R)?N:Cn(R)?ie(N,R):R.map($=>ie(N,$))},ee=(R,N)=>({invalid:!!ie((N||r).errors,R),isDirty:!!ie((N||r).dirtyFields,R),error:ie((N||r).errors,R),isValidating:!!ie(r.validatingFields,R),isTouched:!!ie((N||r).touchedFields,R)}),fe=R=>{R&&bo(R).forEach(N=>kt(r.errors,N)),d.state.next({errors:R?r.errors:{}})},ye=(R,N,$)=>{const re=(ie(n,R,{_f:{}})._f||{}).ref,Z=ie(r.errors,R)||{},{ref:X,message:ge,type:oe,...xe}=Z;Ze(r.errors,R,{...xe,...N,ref:re}),d.state.next({name:R,errors:r.errors,isValid:!1}),$&&$.shouldFocus&&re&&re.focus&&re.focus()},Re=(R,N)=>ni(R)?d.values.subscribe({next:$=>R(P(void 0,N),$)}):P(R,N,!0),Ee=(R,N={})=>{for(const $ of R?bo(R):o.mount)o.mount.delete($),o.array.delete($),N.keepValue||(kt(n,$),kt(s,$)),!N.keepError&&kt(r.errors,$),!N.keepDirty&&kt(r.dirtyFields,$),!N.keepTouched&&kt(r.touchedFields,$),!N.keepIsValidating&&kt(r.validatingFields,$),!e.shouldUnregister&&!N.keepDefaultValue&&kt(i,$);d.values.next({values:{...s}}),d.state.next({...r,...N.keepDirty?{isDirty:O()}:{}}),!N.keepIsValid&&v()},Fe=({disabled:R,name:N,field:$,fields:re,value:Z})=>{if(Wr(R)&&a.mount||R){const X=R?void 0:bt(Z)?of($?$._f:ie(re,N)._f):Z;Ze(s,N,X),C(N,X,!1,!1,!0)}},st=(R,N={})=>{let $=ie(n,R);const re=Wr(N.disabled)||Wr(t.disabled);return Ze(n,R,{...$||{},_f:{...$&&$._f?$._f:{ref:{name:R}},name:R,mount:!0,...N}}),o.mount.add(R),$?Fe({field:$,disabled:Wr(N.disabled)?N.disabled:t.disabled,name:R,value:N.value}):T(R,!0,N.value),{...re?{disabled:N.disabled||t.disabled}:{},...e.progressive?{required:!!N.required,min:eo(N.min),max:eo(N.max),minLength:eo(N.minLength),maxLength:eo(N.maxLength),pattern:eo(N.pattern)}:{},name:R,onChange:W,onBlur:W,ref:Z=>{if(Z){st(R,N),$=ie(n,R);const X=bt(Z.value)&&Z.querySelectorAll&&Z.querySelectorAll("input,select,textarea")[0]||Z,ge=UC(X),oe=$._f.refs||[];if(ge?oe.find(xe=>xe===X):X===$._f.ref)return;Ze(n,R,{_f:{...$._f,...ge?{refs:[...oe.filter(af),X,...Array.isArray(ie(i,R))?[{}]:[]],ref:{type:X.type,name:R}}:{ref:X}}}),T(R,!1,void 0,X)}else $=ie(n,R,{}),$._f&&($._f.mount=!1),(e.shouldUnregister||N.shouldUnregister)&&!(lE(o.array,R)&&a.action)&&o.unMount.add(R)}}},br=()=>e.shouldFocusError&&Lo(n,F,o.mount),tn=R=>{Wr(R)&&(d.state.next({disabled:R}),Lo(n,(N,$)=>{const re=ie(n,$);re&&(N.disabled=re._f.disabled||R,Array.isArray(re._f.refs)&&re._f.refs.forEach(Z=>{Z.disabled=re._f.disabled||R}))},0,!1))},jn=(R,N)=>async $=>{let re;$&&($.preventDefault&&$.preventDefault(),$.persist&&$.persist());let Z=mr(s);if(d.state.next({isSubmitting:!0}),e.resolver){const{errors:X,values:ge}=await b();r.errors=X,Z=ge}else await A(n);if(kt(r.errors,"root"),gr(r.errors)){d.state.next({errors:{}});try{await R(Z,$)}catch(X){re=X}}else N&&await N({...r.errors},$),br(),setTimeout(br);if(d.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:gr(r.errors)&&!re,submitCount:r.submitCount+1,errors:r.errors}),re)throw re},rn=(R,N={})=>{ie(n,R)&&(bt(N.defaultValue)?se(R,mr(ie(i,R))):(se(R,N.defaultValue),Ze(i,R,mr(N.defaultValue))),N.keepTouched||kt(r.touchedFields,R),N.keepDirty||(kt(r.dirtyFields,R),r.isDirty=N.defaultValue?O(R,mr(ie(i,R))):O()),N.keepError||(kt(r.errors,R),c.isValid&&v()),d.state.next({...r}))},xn=(R,N={})=>{const $=R?mr(R):i,re=mr($),Z=gr(R),X=Z?i:re;if(N.keepDefaultValues||(i=$),!N.keepValues){if(N.keepDirtyValues)for(const ge of o.mount)ie(r.dirtyFields,ge)?Ze(X,ge,ie(s,ge)):se(ge,ie(X,ge));else{if(fm&&bt(R))for(const ge of o.mount){const oe=ie(n,ge);if(oe&&oe._f){const xe=Array.isArray(oe._f.refs)?oe._f.refs[0]:oe._f.ref;if(yc(xe)){const ce=xe.closest("form");if(ce){ce.reset();break}}}}n={}}s=t.shouldUnregister?N.keepDefaultValues?mr(i):{}:mr(X),d.array.next({values:{...X}}),d.values.next({values:{...X}})}o={mount:N.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,watch:new Set,watchAll:!1,focus:""},a.mount=!c.isValid||!!N.keepIsValid||!!N.keepDirtyValues,a.watch=!!t.shouldUnregister,d.state.next({submitCount:N.keepSubmitCount?r.submitCount:0,isDirty:Z?!1:N.keepDirty?r.isDirty:!!(N.keepDefaultValues&&!Li(R,i)),isSubmitted:N.keepIsSubmitted?r.isSubmitted:!1,dirtyFields:Z?{}:N.keepDirtyValues?N.keepDefaultValues&&s?Ql(i,s):r.dirtyFields:N.keepDefaultValues&&R?Ql(i,R):N.keepDirty?r.dirtyFields:{},touchedFields:N.keepTouched?r.touchedFields:{},errors:N.keepErrors?r.errors:{},isSubmitSuccessful:N.keepIsSubmitSuccessful?r.isSubmitSuccessful:!1,isSubmitting:!1})},nt=(R,N)=>xn(ni(R)?R(s):R,N);return{control:{register:st,unregister:Ee,getFieldState:ee,handleSubmit:jn,setError:ye,_executeSchema:b,_getWatch:P,_getDirty:O,_updateValid:v,_removeUnmounted:k,_updateFieldArray:y,_updateDisabledField:Fe,_getFieldArray:G,_reset:xn,_resetDefaultValues:()=>ni(e.defaultValues)&&e.defaultValues().then(R=>{nt(R,e.resetOptions),d.state.next({isLoading:!1})}),_updateFormState:R=>{r={...r,...R}},_disableForm:tn,_subjects:d,_proxyFormState:c,_setErrors:S,get _fields(){return n},get _formValues(){return s},get _state(){return a},set _state(R){a=R},get _defaultValues(){return i},get _names(){return o},set _names(R){o=R},get _formState(){return r},set _formState(R){r=R},get _options(){return e},set _options(R){e={...e,...R}}},trigger:j,register:st,handleSubmit:jn,watch:Re,setValue:se,getValues:te,reset:nt,resetField:rn,clearErrors:fe,unregister:Ee,setError:ye,setFocus:(R,N={})=>{const $=ie(n,R),re=$&&$._f;if(re){const Z=re.refs?re.refs[0]:re.ref;Z.focus&&(Z.focus(),N.shouldSelect&&Z.select())}},getFieldState:ee}}function WC(t={}){const e=ne.useRef(),r=ne.useRef(),[n,i]=ne.useState({isDirty:!1,isValidating:!1,isLoading:ni(t.defaultValues),isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,submitCount:0,dirtyFields:{},touchedFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1,defaultValues:ni(t.defaultValues)?void 0:t.defaultValues});e.current||(e.current={...HC(t),formState:n});const s=e.current.control;return s._options=t,pm({subject:s._subjects.state,next:a=>{fE(a,s._proxyFormState,s._updateFormState,!0)&&i({...s._formState})}}),ne.useEffect(()=>s._disableForm(t.disabled),[s,t.disabled]),ne.useEffect(()=>{if(s._proxyFormState.isDirty){const a=s._getDirty();a!==n.isDirty&&s._subjects.state.next({isDirty:a})}},[s,n.isDirty]),ne.useEffect(()=>{t.values&&!Li(t.values,r.current)?(s._reset(t.values,s._options.resetOptions),r.current=t.values,i(a=>({...a}))):s._resetDefaultValues()},[t.values,s]),ne.useEffect(()=>{t.errors&&s._setErrors(t.errors)},[t.errors,s]),ne.useEffect(()=>{s._state.mount||(s._updateValid(),s._state.mount=!0),s._state.watch&&(s._state.watch=!1,s._subjects.state.next({...s._formState})),s._removeUnmounted()}),ne.useEffect(()=>{t.shouldUnregister&&s._subjects.values.next({values:s._getWatch()})},[t.shouldUnregister,s]),e.current.formState=dE(n,s),e.current}const z0=(t,e,r)=>{if(t&&"reportValidity"in t){const n=ie(r,e);t.setCustomValidity(n&&n.message||""),t.reportValidity()}},TE=(t,e)=>{for(const r in e.fields){const n=e.fields[r];n&&n.ref&&"reportValidity"in n.ref?z0(n.ref,r,t):n.refs&&n.refs.forEach(i=>z0(i,r,t))}},KC=(t,e)=>{e.shouldUseNativeValidation&&TE(t,e);const r={};for(const n in t){const i=ie(e.fields,n),s=Object.assign(t[n]||{},{ref:i&&i.ref});if(YC(e.names||Object.keys(t),n)){const a=Object.assign({},ie(r,n));Ze(a,"root",s),Ze(r,n,a)}else Ze(r,n,s)}return r},YC=(t,e)=>t.some(r=>r.startsWith(e+"."));var qC=function(t,e){for(var r={};t.length;){var n=t[0],i=n.code,s=n.message,a=n.path.join(".");if(!r[a])if("unionErrors"in n){var o=n.unionErrors[0].errors[0];r[a]={message:o.message,type:o.code}}else r[a]={message:s,type:i};if("unionErrors"in n&&n.unionErrors.forEach(function(c){return c.errors.forEach(function(d){return t.push(d)})}),e){var l=r[a].types,u=l&&l[n.code];r[a]=mE(a,e,r,i,u?[].concat(u,n.message):n.message)}t.shift()}return r},XC=function(t,e,r){return r===void 0&&(r={}),function(n,i,s){try{return Promise.resolve(function(a,o){try{var l=Promise.resolve(t[r.mode==="sync"?"parse":"parseAsync"](n,e)).then(function(u){return s.shouldUseNativeValidation&&TE({},s),{errors:{},values:r.raw?n:u}})}catch(u){return o(u)}return l&&l.then?l.then(void 0,o):l}(0,function(a){if(function(o){return Array.isArray(o==null?void 0:o.errors)}(a))return{values:{},errors:KC(qC(a.errors,!s.shouldUseNativeValidation&&s.criteriaMode==="all"),s)};throw a}))}catch(a){return Promise.reject(a)}}},We;(function(t){t.assertEqual=i=>i;function e(i){}t.assertIs=e;function r(i){throw new Error}t.assertNever=r,t.arrayToEnum=i=>{const s={};for(const a of i)s[a]=a;return s},t.getValidEnumValues=i=>{const s=t.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),a={};for(const o of s)a[o]=i[o];return t.objectValues(a)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const s=[];for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},t.find=(i,s)=>{for(const a of i)if(s(a))return a},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function n(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(We||(We={}));var Fh;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Fh||(Fh={}));const ue=We.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Ai=t=>{switch(typeof t){case"undefined":return ue.undefined;case"string":return ue.string;case"number":return isNaN(t)?ue.nan:ue.number;case"boolean":return ue.boolean;case"function":return ue.function;case"bigint":return ue.bigint;case"symbol":return ue.symbol;case"object":return Array.isArray(t)?ue.array:t===null?ue.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?ue.promise:typeof Map<"u"&&t instanceof Map?ue.map:typeof Set<"u"&&t instanceof Set?ue.set:typeof Date<"u"&&t instanceof Date?ue.date:ue.object;default:return ue.unknown}},J=We.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),ZC=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:");class Mr extends Error{constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};const r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}get errors(){return this.issues}format(e){const r=e||function(s){return s.message},n={_errors:[]},i=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)n._errors.push(r(a));else{let o=n,l=0;for(;lr.message){const r={},n=[];for(const i of this.issues)i.path.length>0?(r[i.path[0]]=r[i.path[0]]||[],r[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}}Mr.create=t=>new Mr(t);const ba=(t,e)=>{let r;switch(t.code){case J.invalid_type:t.received===ue.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case J.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,We.jsonStringifyReplacer)}`;break;case J.unrecognized_keys:r=`Unrecognized key(s) in object: ${We.joinValues(t.keys,", ")}`;break;case J.invalid_union:r="Invalid input";break;case J.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${We.joinValues(t.options)}`;break;case J.invalid_enum_value:r=`Invalid enum value. Expected ${We.joinValues(t.options)}, received '${t.received}'`;break;case J.invalid_arguments:r="Invalid function arguments";break;case J.invalid_return_type:r="Invalid function return type";break;case J.invalid_date:r="Invalid date";break;case J.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:We.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case J.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case J.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case J.custom:r="Invalid input";break;case J.invalid_intersection_types:r="Intersection results could not be merged";break;case J.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case J.not_finite:r="Number must be finite";break;default:r=e.defaultError,We.assertNever(t)}return{message:r}};let wE=ba;function QC(t){wE=t}function Tc(){return wE}const wc=t=>{const{data:e,path:r,errorMaps:n,issueData:i}=t,s=[...r,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let o="";const l=n.filter(u=>!!u).slice().reverse();for(const u of l)o=u(a,{data:e,defaultError:o}).message;return{...i,path:s,message:o}},JC=[];function le(t,e){const r=Tc(),n=wc({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===ba?void 0:ba].filter(i=>!!i)});t.common.issues.push(n)}class tr{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){const n=[];for(const i of r){if(i.status==="aborted")return Ie;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){const n=[];for(const i of r){const s=await i.key,a=await i.value;n.push({key:s,value:a})}return tr.mergeObjectSync(e,n)}static mergeObjectSync(e,r){const n={};for(const i of r){const{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return Ie;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(n[s.value]=a.value)}return{status:e.value,value:n}}}const Ie=Object.freeze({status:"aborted"}),ea=t=>({status:"dirty",value:t}),cr=t=>({status:"valid",value:t}),Uh=t=>t.status==="aborted",Bh=t=>t.status==="dirty",Qo=t=>t.status==="valid",Jo=t=>typeof Promise<"u"&&t instanceof Promise;function bc(t,e,r,n){if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e.get(t)}function bE(t,e,r,n,i){if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,r),r}var Se;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(Se||(Se={}));var co,fo;class Fn{constructor(e,r,n,i){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=i}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const H0=(t,e)=>{if(Qo(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const r=new Mr(t.common.issues);return this._error=r,this._error}}};function Ne(t){if(!t)return{};const{errorMap:e,invalid_type_error:r,required_error:n,description:i}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,o)=>{var l,u;const{message:c}=t;return a.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:(l=c??n)!==null&&l!==void 0?l:o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:(u=c??r)!==null&&u!==void 0?u:o.defaultError}},description:i}}class Ve{constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this)}get description(){return this._def.description}_getType(e){return Ai(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Ai(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new tr,ctx:{common:e.parent.common,data:e.data,parsedType:Ai(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const r=this._parse(e);if(Jo(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){const r=this._parse(e);return Promise.resolve(r)}parse(e,r){const n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){var n;const i={common:{issues:[],async:(n=r==null?void 0:r.async)!==null&&n!==void 0?n:!1,contextualErrorMap:r==null?void 0:r.errorMap},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ai(e)},s=this._parseSync({data:e,path:i.path,parent:i});return H0(i,s)}async parseAsync(e,r){const n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){const n={common:{issues:[],contextualErrorMap:r==null?void 0:r.errorMap,async:!0},path:(r==null?void 0:r.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Ai(e)},i=this._parse({data:e,path:n.path,parent:n}),s=await(Jo(i)?i:Promise.resolve(i));return H0(n,s)}refine(e,r){const n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,s)=>{const a=e(i),o=()=>s.addIssue({code:J.custom,...n(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(l=>l?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(e){return new yn({schema:this,typeName:Ce.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}optional(){return Mn.create(this,this._def)}nullable(){return Gi.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return gn.create(this,this._def)}promise(){return Aa.create(this,this._def)}or(e){return nl.create([this,e],this._def)}and(e){return il.create(this,e,this._def)}transform(e){return new yn({...Ne(this._def),schema:this,typeName:Ce.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const r=typeof e=="function"?e:()=>e;return new ul({...Ne(this._def),innerType:this,defaultValue:r,typeName:Ce.ZodDefault})}brand(){return new vm({typeName:Ce.ZodBranded,type:this,...Ne(this._def)})}catch(e){const r=typeof e=="function"?e:()=>e;return new cl({...Ne(this._def),innerType:this,catchValue:r,typeName:Ce.ZodCatch})}describe(e){const r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Tl.create(this,e)}readonly(){return dl.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const eR=/^c[^\s-]{8,}$/i,tR=/^[0-9a-z]+$/,rR=/^[0-9A-HJKMNP-TV-Z]{26}$/,nR=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,iR=/^[a-z0-9_-]{21}$/i,sR=/^[-+]?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)?)??$/,aR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,oR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let lf;const lR=/^(?:(?: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])$/,uR=/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,cR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,LE="((\\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])))",dR=new RegExp(`^${LE}$`);function AE(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function fR(t){return new RegExp(`^${AE(t)}$`)}function _E(t){let e=`${LE}T${AE(t)}`;const r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function hR(t,e){return!!((e==="v4"||!e)&&lR.test(t)||(e==="v6"||!e)&&uR.test(t))}class hn extends Ve{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==ue.string){const s=this._getOrReturnCtx(e);return le(s,{code:J.invalid_type,expected:ue.string,received:s.parsedType}),Ie}const n=new tr;let i;for(const s of this._def.checks)if(s.kind==="min")e.data.lengths.value&&(i=this._getOrReturnCtx(e,i),le(i,{code:J.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){const a=e.data.length>s.value,o=e.data.lengthe.test(i),{validation:r,code:J.invalid_string,...Se.errToObj(n)})}_addCheck(e){return new hn({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Se.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Se.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Se.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Se.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Se.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Se.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Se.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Se.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Se.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Se.errToObj(e)})}datetime(e){var r,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(r=e==null?void 0:e.offset)!==null&&r!==void 0?r:!1,local:(n=e==null?void 0:e.local)!==null&&n!==void 0?n:!1,...Se.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...Se.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...Se.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...Se.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r==null?void 0:r.position,...Se.errToObj(r==null?void 0:r.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...Se.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...Se.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...Se.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...Se.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...Se.errToObj(r)})}nonempty(e){return this.min(1,Se.errToObj(e))}trim(){return new hn({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new hn({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new hn({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get minLength(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value{var e;return new hn({checks:[],typeName:Ce.ZodString,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...Ne(t)})};function pR(t,e){const r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=r>n?r:n,s=parseInt(t.toFixed(i).replace(".","")),a=parseInt(e.toFixed(i).replace(".",""));return s%a/Math.pow(10,i)}class $i extends Ve{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==ue.number){const s=this._getOrReturnCtx(e);return le(s,{code:J.invalid_type,expected:ue.number,received:s.parsedType}),Ie}let n;const i=new tr;for(const s of this._def.checks)s.kind==="int"?We.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),le(n,{code:J.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),le(n,{code:J.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?pR(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),le(n,{code:J.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),le(n,{code:J.not_finite,message:s.message}),i.dirty()):We.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,Se.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Se.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Se.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Se.toString(r))}setLimit(e,r,n,i){return new $i({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Se.toString(i)}]})}_addCheck(e){return new $i({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Se.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Se.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Se.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:Se.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Se.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Se.toString(e)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.valuee.kind==="int"||e.kind==="multipleOf"&&We.isInteger(e.value))}get isFinite(){let e=null,r=null;for(const n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.valuenew $i({checks:[],typeName:Ce.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...Ne(t)});class ji extends Ve{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce&&(e.data=BigInt(e.data)),this._getType(e)!==ue.bigint){const s=this._getOrReturnCtx(e);return le(s,{code:J.invalid_type,expected:ue.bigint,received:s.parsedType}),Ie}let n;const i=new tr;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.datas.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),le(n,{code:J.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),le(n,{code:J.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):We.assertNever(s);return{status:i.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,Se.toString(r))}gt(e,r){return this.setLimit("min",e,!1,Se.toString(r))}lte(e,r){return this.setLimit("max",e,!0,Se.toString(r))}lt(e,r){return this.setLimit("max",e,!1,Se.toString(r))}setLimit(e,r,n,i){return new ji({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:Se.toString(i)}]})}_addCheck(e){return new ji({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Se.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Se.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Se.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Se.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:Se.toString(r)})}get minValue(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.value{var e;return new ji({checks:[],typeName:Ce.ZodBigInt,coerce:(e=t==null?void 0:t.coerce)!==null&&e!==void 0?e:!1,...Ne(t)})};class el extends Ve{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==ue.boolean){const n=this._getOrReturnCtx(e);return le(n,{code:J.invalid_type,expected:ue.boolean,received:n.parsedType}),Ie}return cr(e.data)}}el.create=t=>new el({typeName:Ce.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...Ne(t)});class Es extends Ve{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==ue.date){const s=this._getOrReturnCtx(e);return le(s,{code:J.invalid_type,expected:ue.date,received:s.parsedType}),Ie}if(isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return le(s,{code:J.invalid_date}),Ie}const n=new tr;let i;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()s.value&&(i=this._getOrReturnCtx(e,i),le(i,{code:J.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):We.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Es({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:Se.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:Se.toString(r)})}get minDate(){let e=null;for(const r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const r of this._def.checks)r.kind==="max"&&(e===null||r.valuenew Es({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:Ce.ZodDate,...Ne(t)});class Lc extends Ve{_parse(e){if(this._getType(e)!==ue.symbol){const n=this._getOrReturnCtx(e);return le(n,{code:J.invalid_type,expected:ue.symbol,received:n.parsedType}),Ie}return cr(e.data)}}Lc.create=t=>new Lc({typeName:Ce.ZodSymbol,...Ne(t)});class tl extends Ve{_parse(e){if(this._getType(e)!==ue.undefined){const n=this._getOrReturnCtx(e);return le(n,{code:J.invalid_type,expected:ue.undefined,received:n.parsedType}),Ie}return cr(e.data)}}tl.create=t=>new tl({typeName:Ce.ZodUndefined,...Ne(t)});class rl extends Ve{_parse(e){if(this._getType(e)!==ue.null){const n=this._getOrReturnCtx(e);return le(n,{code:J.invalid_type,expected:ue.null,received:n.parsedType}),Ie}return cr(e.data)}}rl.create=t=>new rl({typeName:Ce.ZodNull,...Ne(t)});class La extends Ve{constructor(){super(...arguments),this._any=!0}_parse(e){return cr(e.data)}}La.create=t=>new La({typeName:Ce.ZodAny,...Ne(t)});class ds extends Ve{constructor(){super(...arguments),this._unknown=!0}_parse(e){return cr(e.data)}}ds.create=t=>new ds({typeName:Ce.ZodUnknown,...Ne(t)});class di extends Ve{_parse(e){const r=this._getOrReturnCtx(e);return le(r,{code:J.invalid_type,expected:ue.never,received:r.parsedType}),Ie}}di.create=t=>new di({typeName:Ce.ZodNever,...Ne(t)});class Ac extends Ve{_parse(e){if(this._getType(e)!==ue.undefined){const n=this._getOrReturnCtx(e);return le(n,{code:J.invalid_type,expected:ue.void,received:n.parsedType}),Ie}return cr(e.data)}}Ac.create=t=>new Ac({typeName:Ce.ZodVoid,...Ne(t)});class gn extends Ve{_parse(e){const{ctx:r,status:n}=this._processInputParams(e),i=this._def;if(r.parsedType!==ue.array)return le(r,{code:J.invalid_type,expected:ue.array,received:r.parsedType}),Ie;if(i.exactLength!==null){const a=r.data.length>i.exactLength.value,o=r.data.lengthi.maxLength.value&&(le(r,{code:J.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((a,o)=>i.type._parseAsync(new Fn(r,a,r.path,o)))).then(a=>tr.mergeArray(n,a));const s=[...r.data].map((a,o)=>i.type._parseSync(new Fn(r,a,r.path,o)));return tr.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new gn({...this._def,minLength:{value:e,message:Se.toString(r)}})}max(e,r){return new gn({...this._def,maxLength:{value:e,message:Se.toString(r)}})}length(e,r){return new gn({...this._def,exactLength:{value:e,message:Se.toString(r)}})}nonempty(e){return this.min(1,e)}}gn.create=(t,e)=>new gn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:Ce.ZodArray,...Ne(e)});function Bs(t){if(t instanceof vt){const e={};for(const r in t.shape){const n=t.shape[r];e[r]=Mn.create(Bs(n))}return new vt({...t._def,shape:()=>e})}else return t instanceof gn?new gn({...t._def,type:Bs(t.element)}):t instanceof Mn?Mn.create(Bs(t.unwrap())):t instanceof Gi?Gi.create(Bs(t.unwrap())):t instanceof Un?Un.create(t.items.map(e=>Bs(e))):t}class vt extends Ve{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),r=We.objectKeys(e);return this._cached={shape:e,keys:r}}_parse(e){if(this._getType(e)!==ue.object){const u=this._getOrReturnCtx(e);return le(u,{code:J.invalid_type,expected:ue.object,received:u.parsedType}),Ie}const{status:n,ctx:i}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof di&&this._def.unknownKeys==="strip"))for(const u in i.data)a.includes(u)||o.push(u);const l=[];for(const u of a){const c=s[u],d=i.data[u];l.push({key:{status:"valid",value:u},value:c._parse(new Fn(i,d,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof di){const u=this._def.unknownKeys;if(u==="passthrough")for(const c of o)l.push({key:{status:"valid",value:c},value:{status:"valid",value:i.data[c]}});else if(u==="strict")o.length>0&&(le(i,{code:J.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const u=this._def.catchall;for(const c of o){const d=i.data[c];l.push({key:{status:"valid",value:c},value:u._parse(new Fn(i,d,i.path,c)),alwaysSet:c in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const u=[];for(const c of l){const d=await c.key,f=await c.value;u.push({key:d,value:f,alwaysSet:c.alwaysSet})}return u}).then(u=>tr.mergeObjectSync(n,u)):tr.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return Se.errToObj,new vt({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{var i,s,a,o;const l=(a=(s=(i=this._def).errorMap)===null||s===void 0?void 0:s.call(i,r,n).message)!==null&&a!==void 0?a:n.defaultError;return r.code==="unrecognized_keys"?{message:(o=Se.errToObj(e).message)!==null&&o!==void 0?o:l}:{message:l}}}:{}})}strip(){return new vt({...this._def,unknownKeys:"strip"})}passthrough(){return new vt({...this._def,unknownKeys:"passthrough"})}extend(e){return new vt({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new vt({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:Ce.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new vt({...this._def,catchall:e})}pick(e){const r={};return We.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(r[n]=this.shape[n])}),new vt({...this._def,shape:()=>r})}omit(e){const r={};return We.objectKeys(this.shape).forEach(n=>{e[n]||(r[n]=this.shape[n])}),new vt({...this._def,shape:()=>r})}deepPartial(){return Bs(this)}partial(e){const r={};return We.objectKeys(this.shape).forEach(n=>{const i=this.shape[n];e&&!e[n]?r[n]=i:r[n]=i.optional()}),new vt({...this._def,shape:()=>r})}required(e){const r={};return We.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Mn;)s=s._def.innerType;r[n]=s}}),new vt({...this._def,shape:()=>r})}keyof(){return CE(We.objectKeys(this.shape))}}vt.create=(t,e)=>new vt({shape:()=>t,unknownKeys:"strip",catchall:di.create(),typeName:Ce.ZodObject,...Ne(e)});vt.strictCreate=(t,e)=>new vt({shape:()=>t,unknownKeys:"strict",catchall:di.create(),typeName:Ce.ZodObject,...Ne(e)});vt.lazycreate=(t,e)=>new vt({shape:t,unknownKeys:"strip",catchall:di.create(),typeName:Ce.ZodObject,...Ne(e)});class nl extends Ve{_parse(e){const{ctx:r}=this._processInputParams(e),n=this._def.options;function i(s){for(const o of s)if(o.result.status==="valid")return o.result;for(const o of s)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;const a=s.map(o=>new Mr(o.ctx.common.issues));return le(r,{code:J.invalid_union,unionErrors:a}),Ie}if(r.common.async)return Promise.all(n.map(async s=>{const a={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:a}),ctx:a}})).then(i);{let s;const a=[];for(const l of n){const u={...r,common:{...r.common,issues:[]},parent:null},c=l._parseSync({data:r.data,path:r.path,parent:u});if(c.status==="valid")return c;c.status==="dirty"&&!s&&(s={result:c,ctx:u}),u.common.issues.length&&a.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;const o=a.map(l=>new Mr(l));return le(r,{code:J.invalid_union,unionErrors:o}),Ie}}get options(){return this._def.options}}nl.create=(t,e)=>new nl({options:t,typeName:Ce.ZodUnion,...Ne(e)});const Yn=t=>t instanceof al?Yn(t.schema):t instanceof yn?Yn(t.innerType()):t instanceof ol?[t.value]:t instanceof Vi?t.options:t instanceof ll?We.objectValues(t.enum):t instanceof ul?Yn(t._def.innerType):t instanceof tl?[void 0]:t instanceof rl?[null]:t instanceof Mn?[void 0,...Yn(t.unwrap())]:t instanceof Gi?[null,...Yn(t.unwrap())]:t instanceof vm||t instanceof dl?Yn(t.unwrap()):t instanceof cl?Yn(t._def.innerType):[];class xd extends Ve{_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.object)return le(r,{code:J.invalid_type,expected:ue.object,received:r.parsedType}),Ie;const n=this.discriminator,i=r.data[n],s=this.optionsMap.get(i);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(le(r,{code:J.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),Ie)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){const i=new Map;for(const s of r){const a=Yn(s.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(const o of a){if(i.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);i.set(o,s)}}return new xd({typeName:Ce.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:i,...Ne(n)})}}function $h(t,e){const r=Ai(t),n=Ai(e);if(t===e)return{valid:!0,data:t};if(r===ue.object&&n===ue.object){const i=We.objectKeys(e),s=We.objectKeys(t).filter(o=>i.indexOf(o)!==-1),a={...t,...e};for(const o of s){const l=$h(t[o],e[o]);if(!l.valid)return{valid:!1};a[o]=l.data}return{valid:!0,data:a}}else if(r===ue.array&&n===ue.array){if(t.length!==e.length)return{valid:!1};const i=[];for(let s=0;s{if(Uh(s)||Uh(a))return Ie;const o=$h(s.value,a.value);return o.valid?((Bh(s)||Bh(a))&&r.dirty(),{status:r.value,value:o.data}):(le(n,{code:J.invalid_intersection_types}),Ie)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,a])=>i(s,a)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}}il.create=(t,e,r)=>new il({left:t,right:e,typeName:Ce.ZodIntersection,...Ne(r)});class Un extends Ve{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.array)return le(n,{code:J.invalid_type,expected:ue.array,received:n.parsedType}),Ie;if(n.data.lengththis._def.items.length&&(le(n,{code:J.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());const s=[...n.data].map((a,o)=>{const l=this._def.items[o]||this._def.rest;return l?l._parse(new Fn(n,a,n.path,o)):null}).filter(a=>!!a);return n.common.async?Promise.all(s).then(a=>tr.mergeArray(r,a)):tr.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new Un({...this._def,rest:e})}}Un.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Un({items:t,typeName:Ce.ZodTuple,rest:null,...Ne(e)})};class sl extends Ve{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.object)return le(n,{code:J.invalid_type,expected:ue.object,received:n.parsedType}),Ie;const i=[],s=this._def.keyType,a=this._def.valueType;for(const o in n.data)i.push({key:s._parse(new Fn(n,o,n.path,o)),value:a._parse(new Fn(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?tr.mergeObjectAsync(r,i):tr.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof Ve?new sl({keyType:e,valueType:r,typeName:Ce.ZodRecord,...Ne(n)}):new sl({keyType:hn.create(),valueType:e,typeName:Ce.ZodRecord,...Ne(r)})}}class _c extends Ve{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.map)return le(n,{code:J.invalid_type,expected:ue.map,received:n.parsedType}),Ie;const i=this._def.keyType,s=this._def.valueType,a=[...n.data.entries()].map(([o,l],u)=>({key:i._parse(new Fn(n,o,n.path,[u,"key"])),value:s._parse(new Fn(n,l,n.path,[u,"value"]))}));if(n.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const l of a){const u=await l.key,c=await l.value;if(u.status==="aborted"||c.status==="aborted")return Ie;(u.status==="dirty"||c.status==="dirty")&&r.dirty(),o.set(u.value,c.value)}return{status:r.value,value:o}})}else{const o=new Map;for(const l of a){const u=l.key,c=l.value;if(u.status==="aborted"||c.status==="aborted")return Ie;(u.status==="dirty"||c.status==="dirty")&&r.dirty(),o.set(u.value,c.value)}return{status:r.value,value:o}}}}_c.create=(t,e,r)=>new _c({valueType:e,keyType:t,typeName:Ce.ZodMap,...Ne(r)});class Ts extends Ve{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==ue.set)return le(n,{code:J.invalid_type,expected:ue.set,received:n.parsedType}),Ie;const i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(le(n,{code:J.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());const s=this._def.valueType;function a(l){const u=new Set;for(const c of l){if(c.status==="aborted")return Ie;c.status==="dirty"&&r.dirty(),u.add(c.value)}return{status:r.value,value:u}}const o=[...n.data.values()].map((l,u)=>s._parse(new Fn(n,l,n.path,u)));return n.common.async?Promise.all(o).then(l=>a(l)):a(o)}min(e,r){return new Ts({...this._def,minSize:{value:e,message:Se.toString(r)}})}max(e,r){return new Ts({...this._def,maxSize:{value:e,message:Se.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}}Ts.create=(t,e)=>new Ts({valueType:t,minSize:null,maxSize:null,typeName:Ce.ZodSet,...Ne(e)});class la extends Ve{constructor(){super(...arguments),this.validate=this.implement}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.function)return le(r,{code:J.invalid_type,expected:ue.function,received:r.parsedType}),Ie;function n(o,l){return wc({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Tc(),ba].filter(u=>!!u),issueData:{code:J.invalid_arguments,argumentsError:l}})}function i(o,l){return wc({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Tc(),ba].filter(u=>!!u),issueData:{code:J.invalid_return_type,returnTypeError:l}})}const s={errorMap:r.common.contextualErrorMap},a=r.data;if(this._def.returns instanceof Aa){const o=this;return cr(async function(...l){const u=new Mr([]),c=await o._def.args.parseAsync(l,s).catch(m=>{throw u.addIssue(n(l,m)),u}),d=await Reflect.apply(a,this,c);return await o._def.returns._def.type.parseAsync(d,s).catch(m=>{throw u.addIssue(i(d,m)),u})})}else{const o=this;return cr(function(...l){const u=o._def.args.safeParse(l,s);if(!u.success)throw new Mr([n(l,u.error)]);const c=Reflect.apply(a,this,u.data),d=o._def.returns.safeParse(c,s);if(!d.success)throw new Mr([i(c,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new la({...this._def,args:Un.create(e).rest(ds.create())})}returns(e){return new la({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new la({args:e||Un.create([]).rest(ds.create()),returns:r||ds.create(),typeName:Ce.ZodFunction,...Ne(n)})}}class al extends Ve{get schema(){return this._def.getter()}_parse(e){const{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}}al.create=(t,e)=>new al({getter:t,typeName:Ce.ZodLazy,...Ne(e)});class ol extends Ve{_parse(e){if(e.data!==this._def.value){const r=this._getOrReturnCtx(e);return le(r,{received:r.data,code:J.invalid_literal,expected:this._def.value}),Ie}return{status:"valid",value:e.data}}get value(){return this._def.value}}ol.create=(t,e)=>new ol({value:t,typeName:Ce.ZodLiteral,...Ne(e)});function CE(t,e){return new Vi({values:t,typeName:Ce.ZodEnum,...Ne(e)})}class Vi extends Ve{constructor(){super(...arguments),co.set(this,void 0)}_parse(e){if(typeof e.data!="string"){const r=this._getOrReturnCtx(e),n=this._def.values;return le(r,{expected:We.joinValues(n),received:r.parsedType,code:J.invalid_type}),Ie}if(bc(this,co)||bE(this,co,new Set(this._def.values)),!bc(this,co).has(e.data)){const r=this._getOrReturnCtx(e),n=this._def.values;return le(r,{received:r.data,code:J.invalid_enum_value,options:n}),Ie}return cr(e.data)}get options(){return this._def.values}get enum(){const e={};for(const r of this._def.values)e[r]=r;return e}get Values(){const e={};for(const r of this._def.values)e[r]=r;return e}get Enum(){const e={};for(const r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return Vi.create(e,{...this._def,...r})}exclude(e,r=this._def){return Vi.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}}co=new WeakMap;Vi.create=CE;class ll extends Ve{constructor(){super(...arguments),fo.set(this,void 0)}_parse(e){const r=We.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==ue.string&&n.parsedType!==ue.number){const i=We.objectValues(r);return le(n,{expected:We.joinValues(i),received:n.parsedType,code:J.invalid_type}),Ie}if(bc(this,fo)||bE(this,fo,new Set(We.getValidEnumValues(this._def.values))),!bc(this,fo).has(e.data)){const i=We.objectValues(r);return le(n,{received:n.data,code:J.invalid_enum_value,options:i}),Ie}return cr(e.data)}get enum(){return this._def.values}}fo=new WeakMap;ll.create=(t,e)=>new ll({values:t,typeName:Ce.ZodNativeEnum,...Ne(e)});class Aa extends Ve{unwrap(){return this._def.type}_parse(e){const{ctx:r}=this._processInputParams(e);if(r.parsedType!==ue.promise&&r.common.async===!1)return le(r,{code:J.invalid_type,expected:ue.promise,received:r.parsedType}),Ie;const n=r.parsedType===ue.promise?r.data:Promise.resolve(r.data);return cr(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}}Aa.create=(t,e)=>new Aa({type:t,typeName:Ce.ZodPromise,...Ne(e)});class yn extends Ve{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===Ce.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:r,ctx:n}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:a=>{le(n,a),a.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){const a=i.transform(n.data,s);if(n.common.async)return Promise.resolve(a).then(async o=>{if(r.value==="aborted")return Ie;const l=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return l.status==="aborted"?Ie:l.status==="dirty"||r.value==="dirty"?ea(l.value):l});{if(r.value==="aborted")return Ie;const o=this._def.schema._parseSync({data:a,path:n.path,parent:n});return o.status==="aborted"?Ie:o.status==="dirty"||r.value==="dirty"?ea(o.value):o}}if(i.type==="refinement"){const a=o=>{const l=i.refinement(o,s);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){const o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?Ie:(o.status==="dirty"&&r.dirty(),a(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?Ie:(o.status==="dirty"&&r.dirty(),a(o.value).then(()=>({status:r.value,value:o.value}))))}if(i.type==="transform")if(n.common.async===!1){const a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Qo(a))return a;const o=i.transform(a.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>Qo(a)?Promise.resolve(i.transform(a.value,s)).then(o=>({status:r.value,value:o})):a);We.assertNever(i)}}yn.create=(t,e,r)=>new yn({schema:t,typeName:Ce.ZodEffects,effect:e,...Ne(r)});yn.createWithPreprocess=(t,e,r)=>new yn({schema:e,effect:{type:"preprocess",transform:t},typeName:Ce.ZodEffects,...Ne(r)});class Mn extends Ve{_parse(e){return this._getType(e)===ue.undefined?cr(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Mn.create=(t,e)=>new Mn({innerType:t,typeName:Ce.ZodOptional,...Ne(e)});class Gi extends Ve{_parse(e){return this._getType(e)===ue.null?cr(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Gi.create=(t,e)=>new Gi({innerType:t,typeName:Ce.ZodNullable,...Ne(e)});class ul extends Ve{_parse(e){const{ctx:r}=this._processInputParams(e);let n=r.data;return r.parsedType===ue.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}}ul.create=(t,e)=>new ul({innerType:t,typeName:Ce.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Ne(e)});class cl extends Ve{_parse(e){const{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Jo(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Mr(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Mr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}}cl.create=(t,e)=>new cl({innerType:t,typeName:Ce.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Ne(e)});class Cc extends Ve{_parse(e){if(this._getType(e)!==ue.nan){const n=this._getOrReturnCtx(e);return le(n,{code:J.invalid_type,expected:ue.nan,received:n.parsedType}),Ie}return{status:"valid",value:e.data}}}Cc.create=t=>new Cc({typeName:Ce.ZodNaN,...Ne(t)});const mR=Symbol("zod_brand");class vm extends Ve{_parse(e){const{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}}class Tl extends Ve{_parse(e){const{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?Ie:s.status==="dirty"?(r.dirty(),ea(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{const i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?Ie:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,r){return new Tl({in:e,out:r,typeName:Ce.ZodPipeline})}}class dl extends Ve{_parse(e){const r=this._def.innerType._parse(e),n=i=>(Qo(i)&&(i.value=Object.freeze(i.value)),i);return Jo(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}}dl.create=(t,e)=>new dl({innerType:t,typeName:Ce.ZodReadonly,...Ne(e)});function RE(t,e={},r){return t?La.create().superRefine((n,i)=>{var s,a;if(!t(n)){const o=typeof e=="function"?e(n):typeof e=="string"?{message:e}:e,l=(a=(s=o.fatal)!==null&&s!==void 0?s:r)!==null&&a!==void 0?a:!0,u=typeof o=="string"?{message:o}:o;i.addIssue({code:"custom",...u,fatal:l})}}):La.create()}const gR={object:vt.lazycreate};var Ce;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(Ce||(Ce={}));const vR=(t,e={message:`Input not instance of ${t.name}`})=>RE(r=>r instanceof t,e),IE=hn.create,kE=$i.create,yR=Cc.create,xR=ji.create,DE=el.create,SR=Es.create,ER=Lc.create,TR=tl.create,wR=rl.create,bR=La.create,LR=ds.create,AR=di.create,_R=Ac.create,CR=gn.create,RR=vt.create,IR=vt.strictCreate,kR=nl.create,DR=xd.create,PR=il.create,OR=Un.create,MR=sl.create,NR=_c.create,FR=Ts.create,UR=la.create,BR=al.create,$R=ol.create,jR=Vi.create,VR=ll.create,GR=Aa.create,W0=yn.create,zR=Mn.create,HR=Gi.create,WR=yn.createWithPreprocess,KR=Tl.create,YR=()=>IE().optional(),qR=()=>kE().optional(),XR=()=>DE().optional(),ZR={string:t=>hn.create({...t,coerce:!0}),number:t=>$i.create({...t,coerce:!0}),boolean:t=>el.create({...t,coerce:!0}),bigint:t=>ji.create({...t,coerce:!0}),date:t=>Es.create({...t,coerce:!0})},QR=Ie;var to=Object.freeze({__proto__:null,defaultErrorMap:ba,setErrorMap:QC,getErrorMap:Tc,makeIssue:wc,EMPTY_PATH:JC,addIssueToContext:le,ParseStatus:tr,INVALID:Ie,DIRTY:ea,OK:cr,isAborted:Uh,isDirty:Bh,isValid:Qo,isAsync:Jo,get util(){return We},get objectUtil(){return Fh},ZodParsedType:ue,getParsedType:Ai,ZodType:Ve,datetimeRegex:_E,ZodString:hn,ZodNumber:$i,ZodBigInt:ji,ZodBoolean:el,ZodDate:Es,ZodSymbol:Lc,ZodUndefined:tl,ZodNull:rl,ZodAny:La,ZodUnknown:ds,ZodNever:di,ZodVoid:Ac,ZodArray:gn,ZodObject:vt,ZodUnion:nl,ZodDiscriminatedUnion:xd,ZodIntersection:il,ZodTuple:Un,ZodRecord:sl,ZodMap:_c,ZodSet:Ts,ZodFunction:la,ZodLazy:al,ZodLiteral:ol,ZodEnum:Vi,ZodNativeEnum:ll,ZodPromise:Aa,ZodEffects:yn,ZodTransformer:yn,ZodOptional:Mn,ZodNullable:Gi,ZodDefault:ul,ZodCatch:cl,ZodNaN:Cc,BRAND:mR,ZodBranded:vm,ZodPipeline:Tl,ZodReadonly:dl,custom:RE,Schema:Ve,ZodSchema:Ve,late:gR,get ZodFirstPartyTypeKind(){return Ce},coerce:ZR,any:bR,array:CR,bigint:xR,boolean:DE,date:SR,discriminatedUnion:DR,effect:W0,enum:jR,function:UR,instanceof:vR,intersection:PR,lazy:BR,literal:$R,map:NR,nan:yR,nativeEnum:VR,never:AR,null:wR,nullable:HR,number:kE,object:RR,oboolean:XR,onumber:qR,optional:zR,ostring:YR,pipeline:KR,preprocess:WR,promise:GR,record:MR,set:FR,strictObject:IR,string:IE,symbol:ER,transformer:W0,tuple:OR,undefined:TR,union:kR,unknown:LR,void:_R,NEVER:QR,ZodIssueCode:J,quotelessJson:ZC,ZodError:Mr});function JR(t,e){typeof t=="function"?t(e):t!=null&&(t.current=e)}function eI(...t){return e=>t.forEach(r=>JR(r,e))}var Sd=L.forwardRef((t,e)=>{const{children:r,...n}=t,i=L.Children.toArray(r),s=i.find(rI);if(s){const a=s.props.children,o=i.map(l=>l===s?L.Children.count(a)>1?L.Children.only(null):L.isValidElement(a)?a.props.children:null:l);return E.jsx(jh,{...n,ref:e,children:L.isValidElement(a)?L.cloneElement(a,void 0,o):null})}return E.jsx(jh,{...n,ref:e,children:r})});Sd.displayName="Slot";var jh=L.forwardRef((t,e)=>{const{children:r,...n}=t;if(L.isValidElement(r)){const i=iI(r);return L.cloneElement(r,{...nI(n,r.props),ref:e?eI(e,i):i})}return L.Children.count(r)>1?L.Children.only(null):null});jh.displayName="SlotClone";var tI=({children:t})=>E.jsx(E.Fragment,{children:t});function rI(t){return L.isValidElement(t)&&t.type===tI}function nI(t,e){const r={...e};for(const n in e){const i=t[n],s=e[n];/^on[A-Z]/.test(n)?i&&s?r[n]=(...o)=>{s(...o),i(...o)}:i&&(r[n]=i):n==="style"?r[n]={...i,...s}:n==="className"&&(r[n]=[i,s].filter(Boolean).join(" "))}return{...t,...r}}function iI(t){var n,i;let e=(n=Object.getOwnPropertyDescriptor(t.props,"ref"))==null?void 0:n.get,r=e&&"isReactWarning"in e&&e.isReactWarning;return r?t.ref:(e=(i=Object.getOwnPropertyDescriptor(t,"ref"))==null?void 0:i.get,r=e&&"isReactWarning"in e&&e.isReactWarning,r?t.props.ref:t.props.ref||t.ref)}function PE(t){var e,r,n="";if(typeof t=="string"||typeof t=="number")n+=t;else if(typeof t=="object")if(Array.isArray(t))for(e=0;etypeof t=="boolean"?"".concat(t):t===0?"0":t,Y0=sI,OE=(t,e)=>r=>{var n;if((e==null?void 0:e.variants)==null)return Y0(t,r==null?void 0:r.class,r==null?void 0:r.className);const{variants:i,defaultVariants:s}=e,a=Object.keys(i).map(u=>{const c=r==null?void 0:r[u],d=s==null?void 0:s[u];if(c===null)return null;const f=K0(c)||K0(d);return i[u][f]}),o=r&&Object.entries(r).reduce((u,c)=>{let[d,f]=c;return f===void 0||(u[d]=f),u},{}),l=e==null||(n=e.compoundVariants)===null||n===void 0?void 0:n.reduce((u,c)=>{let{class:d,className:f,...m}=c;return Object.entries(m).every(h=>{let[p,v]=h;return Array.isArray(v)?v.includes({...s,...o}[p]):{...s,...o}[p]===v})?[...u,d,f]:u},[]);return Y0(t,a,l,r==null?void 0:r.class,r==null?void 0:r.className)},ym="-",aI=t=>{const e=lI(t),{conflictingClassGroups:r,conflictingClassGroupModifiers:n}=t;return{getClassGroupId:a=>{const o=a.split(ym);return o[0]===""&&o.length!==1&&o.shift(),ME(o,e)||oI(a)},getConflictingClassGroupIds:(a,o)=>{const l=r[a]||[];return o&&n[a]?[...l,...n[a]]:l}}},ME=(t,e)=>{var a;if(t.length===0)return e.classGroupId;const r=t[0],n=e.nextPart.get(r),i=n?ME(t.slice(1),n):void 0;if(i)return i;if(e.validators.length===0)return;const s=t.join(ym);return(a=e.validators.find(({validator:o})=>o(s)))==null?void 0:a.classGroupId},q0=/^\[(.+)\]$/,oI=t=>{if(q0.test(t)){const e=q0.exec(t)[1],r=e==null?void 0:e.substring(0,e.indexOf(":"));if(r)return"arbitrary.."+r}},lI=t=>{const{theme:e,prefix:r}=t,n={nextPart:new Map,validators:[]};return cI(Object.entries(t.classGroups),r).forEach(([s,a])=>{Vh(a,n,s,e)}),n},Vh=(t,e,r,n)=>{t.forEach(i=>{if(typeof i=="string"){const s=i===""?e:X0(e,i);s.classGroupId=r;return}if(typeof i=="function"){if(uI(i)){Vh(i(n),e,r,n);return}e.validators.push({validator:i,classGroupId:r});return}Object.entries(i).forEach(([s,a])=>{Vh(a,X0(e,s),r,n)})})},X0=(t,e)=>{let r=t;return e.split(ym).forEach(n=>{r.nextPart.has(n)||r.nextPart.set(n,{nextPart:new Map,validators:[]}),r=r.nextPart.get(n)}),r},uI=t=>t.isThemeGetter,cI=(t,e)=>e?t.map(([r,n])=>{const i=n.map(s=>typeof s=="string"?e+s:typeof s=="object"?Object.fromEntries(Object.entries(s).map(([a,o])=>[e+a,o])):s);return[r,i]}):t,dI=t=>{if(t<1)return{get:()=>{},set:()=>{}};let e=0,r=new Map,n=new Map;const i=(s,a)=>{r.set(s,a),e++,e>t&&(e=0,n=r,r=new Map)};return{get(s){let a=r.get(s);if(a!==void 0)return a;if((a=n.get(s))!==void 0)return i(s,a),a},set(s,a){r.has(s)?r.set(s,a):i(s,a)}}},NE="!",fI=t=>{const{separator:e,experimentalParseClassName:r}=t,n=e.length===1,i=e[0],s=e.length,a=o=>{const l=[];let u=0,c=0,d;for(let v=0;vc?d-c:void 0;return{modifiers:l,hasImportantModifier:m,baseClassName:h,maybePostfixModifierPosition:p}};return r?o=>r({className:o,parseClassName:a}):a},hI=t=>{if(t.length<=1)return t;const e=[];let r=[];return t.forEach(n=>{n[0]==="["?(e.push(...r.sort(),n),r=[]):r.push(n)}),e.push(...r.sort()),e},pI=t=>({cache:dI(t.cacheSize),parseClassName:fI(t),...aI(t)}),mI=/\s+/,gI=(t,e)=>{const{parseClassName:r,getClassGroupId:n,getConflictingClassGroupIds:i}=e,s=[],a=t.trim().split(mI);let o="";for(let l=a.length-1;l>=0;l-=1){const u=a[l],{modifiers:c,hasImportantModifier:d,baseClassName:f,maybePostfixModifierPosition:m}=r(u);let h=!!m,p=n(h?f.substring(0,m):f);if(!p){if(!h){o=u+(o.length>0?" "+o:o);continue}if(p=n(f),!p){o=u+(o.length>0?" "+o:o);continue}h=!1}const v=hI(c).join(":"),g=d?v+NE:v,y=g+p;if(s.includes(y))continue;s.push(y);const x=i(p,h);for(let S=0;S0?" "+o:o)}return o};function vI(){let t=0,e,r,n="";for(;t{if(typeof t=="string")return t;let e,r="";for(let n=0;nd(c),t());return r=pI(u),n=r.cache.get,i=r.cache.set,s=o,o(l)}function o(l){const u=n(l);if(u)return u;const c=gI(l,r);return i(l,c),c}return function(){return s(vI.apply(null,arguments))}}const ct=t=>{const e=r=>r[t]||[];return e.isThemeGetter=!0,e},UE=/^\[(?:([a-z-]+):)?(.+)\]$/i,xI=/^\d+\/\d+$/,SI=new Set(["px","full","screen"]),EI=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,TI=/\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$/,wI=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,bI=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,LI=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,zn=t=>ua(t)||SI.has(t)||xI.test(t),gi=t=>Ba(t,"length",PI),ua=t=>!!t&&!Number.isNaN(Number(t)),uf=t=>Ba(t,"number",ua),ro=t=>!!t&&Number.isInteger(Number(t)),AI=t=>t.endsWith("%")&&ua(t.slice(0,-1)),Be=t=>UE.test(t),vi=t=>EI.test(t),_I=new Set(["length","size","percentage"]),CI=t=>Ba(t,_I,BE),RI=t=>Ba(t,"position",BE),II=new Set(["image","url"]),kI=t=>Ba(t,II,MI),DI=t=>Ba(t,"",OI),no=()=>!0,Ba=(t,e,r)=>{const n=UE.exec(t);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):r(n[2]):!1},PI=t=>TI.test(t)&&!wI.test(t),BE=()=>!1,OI=t=>bI.test(t),MI=t=>LI.test(t),NI=()=>{const t=ct("colors"),e=ct("spacing"),r=ct("blur"),n=ct("brightness"),i=ct("borderColor"),s=ct("borderRadius"),a=ct("borderSpacing"),o=ct("borderWidth"),l=ct("contrast"),u=ct("grayscale"),c=ct("hueRotate"),d=ct("invert"),f=ct("gap"),m=ct("gradientColorStops"),h=ct("gradientColorStopPositions"),p=ct("inset"),v=ct("margin"),g=ct("opacity"),y=ct("padding"),x=ct("saturate"),S=ct("scale"),T=ct("sepia"),C=ct("skew"),_=ct("space"),b=ct("translate"),I=()=>["auto","contain","none"],A=()=>["auto","hidden","clip","visible","scroll"],k=()=>["auto",Be,e],O=()=>[Be,e],P=()=>["",zn,gi],G=()=>["auto",ua,Be],K=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],H=()=>["solid","dashed","dotted","double","none"],se=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],W=()=>["start","end","center","between","around","evenly","stretch"],F=()=>["","0",Be],j=()=>["auto","avoid","all","avoid-page","page","left","right","column"],te=()=>[ua,Be];return{cacheSize:500,separator:":",theme:{colors:[no],spacing:[zn,gi],blur:["none","",vi,Be],brightness:te(),borderColor:[t],borderRadius:["none","","full",vi,Be],borderSpacing:O(),borderWidth:P(),contrast:te(),grayscale:F(),hueRotate:te(),invert:F(),gap:O(),gradientColorStops:[t],gradientColorStopPositions:[AI,gi],inset:k(),margin:k(),opacity:te(),padding:O(),saturate:te(),scale:te(),sepia:F(),skew:te(),space:O(),translate:O()},classGroups:{aspect:[{aspect:["auto","square","video",Be]}],container:["container"],columns:[{columns:[vi]}],"break-after":[{"break-after":j()}],"break-before":[{"break-before":j()}],"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"],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:[...K(),Be]}],overflow:[{overflow:A()}],"overflow-x":[{"overflow-x":A()}],"overflow-y":[{"overflow-y":A()}],overscroll:[{overscroll:I()}],"overscroll-x":[{"overscroll-x":I()}],"overscroll-y":[{"overscroll-y":I()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[p]}],"inset-x":[{"inset-x":[p]}],"inset-y":[{"inset-y":[p]}],start:[{start:[p]}],end:[{end:[p]}],top:[{top:[p]}],right:[{right:[p]}],bottom:[{bottom:[p]}],left:[{left:[p]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",ro,Be]}],basis:[{basis:k()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Be]}],grow:[{grow:F()}],shrink:[{shrink:F()}],order:[{order:["first","last","none",ro,Be]}],"grid-cols":[{"grid-cols":[no]}],"col-start-end":[{col:["auto",{span:["full",ro,Be]},Be]}],"col-start":[{"col-start":G()}],"col-end":[{"col-end":G()}],"grid-rows":[{"grid-rows":[no]}],"row-start-end":[{row:["auto",{span:[ro,Be]},Be]}],"row-start":[{"row-start":G()}],"row-end":[{"row-end":G()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Be]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Be]}],gap:[{gap:[f]}],"gap-x":[{"gap-x":[f]}],"gap-y":[{"gap-y":[f]}],"justify-content":[{justify:["normal",...W()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...W(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...W(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[v]}],mx:[{mx:[v]}],my:[{my:[v]}],ms:[{ms:[v]}],me:[{me:[v]}],mt:[{mt:[v]}],mr:[{mr:[v]}],mb:[{mb:[v]}],ml:[{ml:[v]}],"space-x":[{"space-x":[_]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[_]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Be,e]}],"min-w":[{"min-w":[Be,e,"min","max","fit"]}],"max-w":[{"max-w":[Be,e,"none","full","min","max","fit","prose",{screen:[vi]},vi]}],h:[{h:[Be,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Be,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Be,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Be,e,"auto","min","max","fit"]}],"font-size":[{text:["base",vi,gi]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",uf]}],"font-family":[{font:[no]}],"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-fractons"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",Be]}],"line-clamp":[{"line-clamp":["none",ua,uf]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",zn,Be]}],"list-image":[{"list-image":["none",Be]}],"list-style-type":[{list:["none","disc","decimal",Be]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[t]}],"placeholder-opacity":[{"placeholder-opacity":[g]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[t]}],"text-opacity":[{"text-opacity":[g]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...H(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",zn,gi]}],"underline-offset":[{"underline-offset":["auto",zn,Be]}],"text-decoration-color":[{decoration:[t]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:O()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Be]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",Be]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[g]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...K(),RI]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",CI]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},kI]}],"bg-color":[{bg:[t]}],"gradient-from-pos":[{from:[h]}],"gradient-via-pos":[{via:[h]}],"gradient-to-pos":[{to:[h]}],"gradient-from":[{from:[m]}],"gradient-via":[{via:[m]}],"gradient-to":[{to:[m]}],rounded:[{rounded:[s]}],"rounded-s":[{"rounded-s":[s]}],"rounded-e":[{"rounded-e":[s]}],"rounded-t":[{"rounded-t":[s]}],"rounded-r":[{"rounded-r":[s]}],"rounded-b":[{"rounded-b":[s]}],"rounded-l":[{"rounded-l":[s]}],"rounded-ss":[{"rounded-ss":[s]}],"rounded-se":[{"rounded-se":[s]}],"rounded-ee":[{"rounded-ee":[s]}],"rounded-es":[{"rounded-es":[s]}],"rounded-tl":[{"rounded-tl":[s]}],"rounded-tr":[{"rounded-tr":[s]}],"rounded-br":[{"rounded-br":[s]}],"rounded-bl":[{"rounded-bl":[s]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[g]}],"border-style":[{border:[...H(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[g]}],"divide-style":[{divide:H()}],"border-color":[{border:[i]}],"border-color-x":[{"border-x":[i]}],"border-color-y":[{"border-y":[i]}],"border-color-s":[{"border-s":[i]}],"border-color-e":[{"border-e":[i]}],"border-color-t":[{"border-t":[i]}],"border-color-r":[{"border-r":[i]}],"border-color-b":[{"border-b":[i]}],"border-color-l":[{"border-l":[i]}],"divide-color":[{divide:[i]}],"outline-style":[{outline:["",...H()]}],"outline-offset":[{"outline-offset":[zn,Be]}],"outline-w":[{outline:[zn,gi]}],"outline-color":[{outline:[t]}],"ring-w":[{ring:P()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[t]}],"ring-opacity":[{"ring-opacity":[g]}],"ring-offset-w":[{"ring-offset":[zn,gi]}],"ring-offset-color":[{"ring-offset":[t]}],shadow:[{shadow:["","inner","none",vi,DI]}],"shadow-color":[{shadow:[no]}],opacity:[{opacity:[g]}],"mix-blend":[{"mix-blend":[...se(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":se()}],filter:[{filter:["","none"]}],blur:[{blur:[r]}],brightness:[{brightness:[n]}],contrast:[{contrast:[l]}],"drop-shadow":[{"drop-shadow":["","none",vi,Be]}],grayscale:[{grayscale:[u]}],"hue-rotate":[{"hue-rotate":[c]}],invert:[{invert:[d]}],saturate:[{saturate:[x]}],sepia:[{sepia:[T]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[r]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[l]}],"backdrop-grayscale":[{"backdrop-grayscale":[u]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[c]}],"backdrop-invert":[{"backdrop-invert":[d]}],"backdrop-opacity":[{"backdrop-opacity":[g]}],"backdrop-saturate":[{"backdrop-saturate":[x]}],"backdrop-sepia":[{"backdrop-sepia":[T]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[a]}],"border-spacing-x":[{"border-spacing-x":[a]}],"border-spacing-y":[{"border-spacing-y":[a]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Be]}],duration:[{duration:te()}],ease:[{ease:["linear","in","out","in-out",Be]}],delay:[{delay:te()}],animate:[{animate:["none","spin","ping","pulse","bounce",Be]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[ro,Be]}],"translate-x":[{"translate-x":[b]}],"translate-y":[{"translate-y":[b]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Be]}],accent:[{accent:["auto",t]}],appearance:[{appearance:["none","auto"]}],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",Be]}],"caret-color":[{caret:[t]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":O()}],"scroll-mx":[{"scroll-mx":O()}],"scroll-my":[{"scroll-my":O()}],"scroll-ms":[{"scroll-ms":O()}],"scroll-me":[{"scroll-me":O()}],"scroll-mt":[{"scroll-mt":O()}],"scroll-mr":[{"scroll-mr":O()}],"scroll-mb":[{"scroll-mb":O()}],"scroll-ml":[{"scroll-ml":O()}],"scroll-p":[{"scroll-p":O()}],"scroll-px":[{"scroll-px":O()}],"scroll-py":[{"scroll-py":O()}],"scroll-ps":[{"scroll-ps":O()}],"scroll-pe":[{"scroll-pe":O()}],"scroll-pt":[{"scroll-pt":O()}],"scroll-pr":[{"scroll-pr":O()}],"scroll-pb":[{"scroll-pb":O()}],"scroll-pl":[{"scroll-pl":O()}],"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",Be]}],fill:[{fill:[t,"none"]}],"stroke-w":[{stroke:[zn,gi,uf]}],stroke:[{stroke:[t,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","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","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","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-s","border-w-e","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-s","border-color-e","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"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","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-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"]}}},FI=yI(NI);function $r(...t){return FI(ri(t))}const UI=OE("inline-flex items-center justify-center whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),xm=L.forwardRef(({className:t,variant:e,size:r,asChild:n=!1,...i},s)=>{const a=n?Sd:"button";return E.jsx(a,{className:$r(UI({variant:e,size:r,className:t})),ref:s,...i})});xm.displayName="Button";const Sm=L.forwardRef(({className:t,...e},r)=>E.jsx("div",{ref:r,className:$r("rounded-lg border bg-card text-card-foreground shadow-sm",t),...e}));Sm.displayName="Card";const Em=L.forwardRef(({className:t,...e},r)=>E.jsx("div",{ref:r,className:$r("flex flex-col space-y-1.5 p-6",t),...e}));Em.displayName="CardHeader";const Tm=L.forwardRef(({className:t,...e},r)=>E.jsx("h3",{ref:r,className:$r("text-2xl font-semibold leading-none tracking-tight",t),...e}));Tm.displayName="CardTitle";const BI=L.forwardRef(({className:t,...e},r)=>E.jsx("p",{ref:r,className:$r("text-sm text-muted-foreground",t),...e}));BI.displayName="CardDescription";const $E=L.forwardRef(({className:t,...e},r)=>E.jsx("div",{ref:r,className:$r("p-6 pt-0",t),...e}));$E.displayName="CardContent";const jE=L.forwardRef(({className:t,...e},r)=>E.jsx("div",{ref:r,className:$r("flex items-center p-6 pt-0",t),...e}));jE.displayName="CardFooter";var $I=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","span","svg","ul"],jI=$I.reduce((t,e)=>{const r=L.forwardRef((n,i)=>{const{asChild:s,...a}=n,o=s?Sd:e;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),E.jsx(o,{...a,ref:i})});return r.displayName=`Primitive.${e}`,{...t,[e]:r}},{}),VI="Label",VE=L.forwardRef((t,e)=>E.jsx(jI.label,{...t,ref:e,onMouseDown:r=>{var i;r.target.closest("button, input, select, textarea")||((i=t.onMouseDown)==null||i.call(t,r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}}));VE.displayName=VI;var GE=VE;const GI=OE("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Ao=L.forwardRef(({className:t,...e},r)=>E.jsx(GE,{ref:r,className:$r(GI(),t),...e}));Ao.displayName=GE.displayName;const zI=IC,zE=L.createContext({}),cf=({...t})=>E.jsx(zE.Provider,{value:{name:t.name},children:E.jsx(OC,{...t})}),Ed=()=>{const t=L.useContext(zE),e=L.useContext(HE),{getFieldState:r,formState:n}=yd(),i=r(t.name,n);if(!t)throw new Error("useFormField should be used within ");const{id:s}=e;return{id:s,name:t.name,formItemId:`${s}-form-item`,formDescriptionId:`${s}-form-item-description`,formMessageId:`${s}-form-item-message`,...i}},HE=L.createContext({}),Cu=L.forwardRef(({className:t,...e},r)=>{const n=L.useId();return E.jsx(HE.Provider,{value:{id:n},children:E.jsx("div",{ref:r,className:$r("space-y-2",t),...e})})});Cu.displayName="FormItem";const Ru=L.forwardRef(({className:t,...e},r)=>{const{error:n,formItemId:i}=Ed();return E.jsx(Ao,{ref:r,className:$r(n&&"text-destructive",t),htmlFor:i,...e})});Ru.displayName="FormLabel";const Iu=L.forwardRef(({...t},e)=>{const{error:r,formItemId:n,formDescriptionId:i,formMessageId:s}=Ed();return E.jsx(Sd,{ref:e,id:n,"aria-describedby":r?`${i} ${s}`:`${i}`,"aria-invalid":!!r,...t})});Iu.displayName="FormControl";const HI=L.forwardRef(({className:t,...e},r)=>{const{formDescriptionId:n}=Ed();return E.jsx("p",{ref:r,id:n,className:$r("text-sm text-muted-foreground",t),...e})});HI.displayName="FormDescription";const ku=L.forwardRef(({className:t,children:e,...r},n)=>{const{error:i,formMessageId:s}=Ed(),a=i?String(i==null?void 0:i.message):e;return a?E.jsx("p",{ref:n,id:s,className:$r("text-sm font-medium text-destructive",t),...r,children:a}):null});ku.displayName="FormMessage";const fs=L.forwardRef(({className:t,type:e,...r},n)=>E.jsx("input",{type:e,className:$r("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",t),ref:n,...r}));fs.displayName="Input";const WI=to.object({username:to.string().min(4,"Username must be at least 4 characters long").max(20,"Username must be at most 20 characters long"),password:to.string().min(8,"Password must be at least 8 characters long").max(64,"Password must be at most 64 characters long").refine(t=>/[A-Z]/.test(t),{message:"Password must contain at least one uppercase letter"}).refine(t=>/[a-z]/.test(t),{message:"Password must contain at least one lowercase letter"}).refine(t=>/[0-9]/.test(t),{message:"Password must contain at least one number"}).refine(t=>/[!@#$%^&*()_+[\]{};':"\\|,.<>/?`~\\-]/.test(t),{message:"Password must contain at least one special character"}),confirmPassword:to.string(),type:to.enum(["admin","user"])}).refine(t=>t.password===t.confirmPassword,{message:"Passwords do not match",path:["confirmPassword"]}),KI=()=>{const t=WC({resolver:XC(WI),defaultValues:{username:"",password:"",confirmPassword:"",type:"user"}}),e=Br(),{handleSubmit:r,data:n,pending:i}=Ss(),s=async a=>{console.log(a);try{await r({url:"/api/auth/signup",body:{...a,code:window.location.search.includes("code")}}),Ke.success("Registration successful"),e("/sign-in")}catch(o){Ke.error(o.message)}};return L.useEffect(()=>{n&&(n.code===200?Ke.success("Sign up successful"):Ke.error("Sign up failed"))},[n]),E.jsx("section",{className:"h-screen w-screen flex items-center justify-center",children:E.jsxs(Sm,{className:"w-1/4 py-2 px-4 pb-8",children:[E.jsx(Em,{children:E.jsx(Tm,{children:"Sign Up"})}),E.jsx(zI,{...t,children:E.jsxs("form",{onSubmit:t.handleSubmit(s),className:"flex flex-col gap-6",children:[E.jsx(cf,{control:t.control,name:"username",render:({field:a})=>E.jsxs(Cu,{children:[E.jsx(Ru,{htmlFor:"username",children:"Username"}),E.jsx(Iu,{children:E.jsx(fs,{...a,placeholder:"Username",autoComplete:"given-name"})}),E.jsx(ku,{})]})}),E.jsx(cf,{control:t.control,name:"password",render:({field:a})=>E.jsxs(Cu,{children:[E.jsx(Ru,{htmlFor:"password",children:"Password"}),E.jsx(Iu,{children:E.jsx(fs,{...a,type:"password",placeholder:"Password",autoComplete:"new-password"})}),E.jsx(ku,{})]})}),E.jsx(cf,{control:t.control,name:"confirmPassword",render:({field:a})=>E.jsxs(Cu,{children:[E.jsx(Ru,{htmlFor:"confirmPassword",children:"Confirm Password"}),E.jsx(Iu,{children:E.jsx(fs,{...a,type:"password",placeholder:"Confirm Password",autoComplete:"new-password"})}),E.jsx(ku,{})]})}),E.jsx(xm,{variant:"default",children:i?"Signing up...":"Sign Up"})]})})]})})},_s=t=>E.jsx("section",{...t,children:E.jsx("div",{className:"flex justify-center items-center h-full",children:E.jsx("img",{src:"loader.gif",alt:"Loading...",className:"w-1/4"})})}),Rn=({state:t,iconBefore:e,iconAfter:r,to:n,onClick:i,className:s="",children:a,...o})=>{const l="flex items-center justify-center gap-2 py-2 px-4 rounded-md font-medium",f=t==="primary"?"bg-neutral-200 text-neutral-900 hover:bg-neutral-300":t==="secondary"?"bg-neutral-900 text-neutral-200 hover:bg-neutral-800":"bg-red-500 text-white hover:bg-red-600",m=Br(),h=()=>{n?m(n):i&&i()};return E.jsxs("button",{onClick:h,className:`${l} ${f} ${s} transition-colors duration-300`,...o,children:[e&&E.jsx("span",{children:e}),a,r&&E.jsx("span",{children:r})]})};var WE={color:void 0,size:void 0,className:void 0,style:void 0,attr:void 0},Z0=ne.createContext&&ne.createContext(WE),YI=["attr","size","title"];function qI(t,e){if(t==null)return{};var r=XI(t,e),n,i;if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function XI(t,e){if(t==null)return{};var r={};for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)){if(e.indexOf(n)>=0)continue;r[n]=t[n]}return r}function Rc(){return Rc=Object.assign?Object.assign.bind():function(t){for(var e=1;ene.createElement(e.tag,Ic({key:r},e.attr),KE(e.child)))}function Mt(t){return e=>ne.createElement(ek,Rc({attr:Ic({},t.attr)},e),KE(t.child))}function ek(t){var e=r=>{var{attr:n,size:i,title:s}=t,a=qI(t,YI),o=i||r.size||"1em",l;return r.className&&(l=r.className),t.className&&(l=(l?l+" ":"")+t.className),ne.createElement("svg",Rc({stroke:"currentColor",fill:"currentColor",strokeWidth:"0"},r.attr,n,a,{className:l,style:Ic(Ic({color:t.color||r.color},r.style),t.style),height:o,width:o,xmlns:"http://www.w3.org/2000/svg"}),s&&ne.createElement("title",null,s),t.children)};return Z0!==void 0?ne.createElement(Z0.Consumer,null,r=>e(r)):e(WE)}function tk(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{d:"M9.5 15.584V8.416a.5.5 0 0 1 .77-.42l5.576 3.583a.5.5 0 0 1 0 .842l-5.576 3.584a.5.5 0 0 1-.77-.42Z"},child:[]},{tag:"path",attr:{d:"M1 12C1 5.925 5.925 1 12 1s11 4.925 11 11-4.925 11-11 11S1 18.075 1 12Zm11-9.5A9.5 9.5 0 0 0 2.5 12a9.5 9.5 0 0 0 9.5 9.5 9.5 9.5 0 0 0 9.5-9.5A9.5 9.5 0 0 0 12 2.5Z"},child:[]}]})(t)}const _a=({media:t})=>t?E.jsx("section",{className:"h-[85dvh] bg-cover bg-center flex items-end",style:{backgroundImage:`linear-gradient(hsl(var(--background)), transparent, hsl(var(--background))), linear-gradient(90deg, hsl(var(--background)) 5%, transparent), url(/api/medias/images/banner/${t.type}/${t.banner_id})`},children:E.jsxs("section",{className:"px-4 flex flex-col gap-4 w-3/4",children:[t.have_logo?E.jsx("img",{src:t.images.logo,alt:t.title,className:"h-48 object-contain rounded-md w-fit"}):E.jsx("h1",{className:"text-5xl font-bold",children:t.serie_title??t.title}),E.jsx("p",{children:t.description}),E.jsx("section",{className:"flex gap-4",children:E.jsx(Rn,{to:`/watch/${t.type}/${t.id}`,iconBefore:E.jsx(tk,{}),state:"primary",children:"Watch Now"})})]})}):null;function J0(t){return t!==null&&typeof t=="object"&&"constructor"in t&&t.constructor===Object}function wm(t,e){t===void 0&&(t={}),e===void 0&&(e={}),Object.keys(e).forEach(r=>{typeof t[r]>"u"?t[r]=e[r]:J0(e[r])&&J0(t[r])&&Object.keys(e[r]).length>0&&wm(t[r],e[r])})}const YE={body:{},addEventListener(){},removeEventListener(){},activeElement:{blur(){},nodeName:""},querySelector(){return null},querySelectorAll(){return[]},getElementById(){return null},createEvent(){return{initEvent(){}}},createElement(){return{children:[],childNodes:[],style:{},setAttribute(){},getElementsByTagName(){return[]}}},createElementNS(){return{}},importNode(){return null},location:{hash:"",host:"",hostname:"",href:"",origin:"",pathname:"",protocol:"",search:""}};function $a(){const t=typeof document<"u"?document:{};return wm(t,YE),t}const rk={document:YE,navigator:{userAgent:""},location:{hash:"",host:"",hostname:"",href:"",origin:"",pathname:"",protocol:"",search:""},history:{replaceState(){},pushState(){},go(){},back(){}},CustomEvent:function(){return this},addEventListener(){},removeEventListener(){},getComputedStyle(){return{getPropertyValue(){return""}}},Image(){},Date(){},screen:{},setTimeout(){},clearTimeout(){},matchMedia(){return{}},requestAnimationFrame(t){return typeof setTimeout>"u"?(t(),null):setTimeout(t,0)},cancelAnimationFrame(t){typeof setTimeout>"u"||clearTimeout(t)}};function jr(){const t=typeof window<"u"?window:{};return wm(t,rk),t}function nk(t){return t===void 0&&(t=""),t.trim().split(" ").filter(e=>!!e.trim())}function ik(t){const e=t;Object.keys(e).forEach(r=>{try{e[r]=null}catch{}try{delete e[r]}catch{}})}function Gh(t,e){return e===void 0&&(e=0),setTimeout(t,e)}function kc(){return Date.now()}function sk(t){const e=jr();let r;return e.getComputedStyle&&(r=e.getComputedStyle(t,null)),!r&&t.currentStyle&&(r=t.currentStyle),r||(r=t.style),r}function ak(t,e){e===void 0&&(e="x");const r=jr();let n,i,s;const a=sk(t);return r.WebKitCSSMatrix?(i=a.transform||a.webkitTransform,i.split(",").length>6&&(i=i.split(", ").map(o=>o.replace(",",".")).join(", ")),s=new r.WebKitCSSMatrix(i==="none"?"":i)):(s=a.MozTransform||a.OTransform||a.MsTransform||a.msTransform||a.transform||a.getPropertyValue("transform").replace("translate(","matrix(1, 0, 0, 1,"),n=s.toString().split(",")),e==="x"&&(r.WebKitCSSMatrix?i=s.m41:n.length===16?i=parseFloat(n[12]):i=parseFloat(n[4])),e==="y"&&(r.WebKitCSSMatrix?i=s.m42:n.length===16?i=parseFloat(n[13]):i=parseFloat(n[5])),i||0}function Jl(t){return typeof t=="object"&&t!==null&&t.constructor&&Object.prototype.toString.call(t).slice(8,-1)==="Object"}function ok(t){return typeof window<"u"&&typeof window.HTMLElement<"u"?t instanceof HTMLElement:t&&(t.nodeType===1||t.nodeType===11)}function Ir(){const t=Object(arguments.length<=0?void 0:arguments[0]),e=["__proto__","constructor","prototype"];for(let r=1;re.indexOf(s)<0);for(let s=0,a=i.length;ss?"next":"prev",c=(f,m)=>u==="next"&&f>=m||u==="prev"&&f<=m,d=()=>{o=new Date().getTime(),a===null&&(a=o);const f=Math.max(Math.min((o-a)/l,1),0),m=.5-Math.cos(f*Math.PI)/2;let h=s+m*(r-s);if(c(h,r)&&(h=r),e.wrapperEl.scrollTo({[n]:h}),c(h,r)){e.wrapperEl.style.overflow="hidden",e.wrapperEl.style.scrollSnapType="",setTimeout(()=>{e.wrapperEl.style.overflow="",e.wrapperEl.scrollTo({[n]:h})}),i.cancelAnimationFrame(e.cssModeFrameID);return}e.cssModeFrameID=i.requestAnimationFrame(d)};d()}function In(t,e){e===void 0&&(e="");const r=[...t.children];return t instanceof HTMLSlotElement&&r.push(...t.assignedElements()),e?r.filter(n=>n.matches(e)):r}function lk(t,e){const r=e.contains(t);return!r&&e instanceof HTMLSlotElement?[...e.assignedElements()].includes(t):r}function Dc(t){try{console.warn(t);return}catch{}}function Pc(t,e){e===void 0&&(e=[]);const r=document.createElement(t);return r.classList.add(...Array.isArray(e)?e:nk(e)),r}function uk(t,e){const r=[];for(;t.previousElementSibling;){const n=t.previousElementSibling;e?n.matches(e)&&r.push(n):r.push(n),t=n}return r}function ck(t,e){const r=[];for(;t.nextElementSibling;){const n=t.nextElementSibling;e?n.matches(e)&&r.push(n):r.push(n),t=n}return r}function Ri(t,e){return jr().getComputedStyle(t,null).getPropertyValue(e)}function ev(t){let e=t,r;if(e){for(r=0;(e=e.previousSibling)!==null;)e.nodeType===1&&(r+=1);return r}}function dk(t,e){const r=[];let n=t.parentElement;for(;n;)r.push(n),n=n.parentElement;return r}function tv(t,e,r){const n=jr();return t[e==="width"?"offsetWidth":"offsetHeight"]+parseFloat(n.getComputedStyle(t,null).getPropertyValue(e==="width"?"margin-right":"margin-top"))+parseFloat(n.getComputedStyle(t,null).getPropertyValue(e==="width"?"margin-left":"margin-bottom"))}function Hn(t){return(Array.isArray(t)?t:[t]).filter(e=>!!e)}let df;function fk(){const t=jr(),e=$a();return{smoothScroll:e.documentElement&&e.documentElement.style&&"scrollBehavior"in e.documentElement.style,touch:!!("ontouchstart"in t||t.DocumentTouch&&e instanceof t.DocumentTouch)}}function XE(){return df||(df=fk()),df}let ff;function hk(t){let{userAgent:e}=t===void 0?{}:t;const r=XE(),n=jr(),i=n.navigator.platform,s=e||n.navigator.userAgent,a={ios:!1,android:!1},o=n.screen.width,l=n.screen.height,u=s.match(/(Android);?[\s\/]+([\d.]+)?/);let c=s.match(/(iPad).*OS\s([\d_]+)/);const d=s.match(/(iPod)(.*OS\s([\d_]+))?/),f=!c&&s.match(/(iPhone\sOS|iOS)\s([\d_]+)/),m=i==="Win32";let h=i==="MacIntel";const p=["1024x1366","1366x1024","834x1194","1194x834","834x1112","1112x834","768x1024","1024x768","820x1180","1180x820","810x1080","1080x810"];return!c&&h&&r.touch&&p.indexOf(`${o}x${l}`)>=0&&(c=s.match(/(Version)\/([\d.]+)/),c||(c=[0,1,"13_0_0"]),h=!1),u&&!m&&(a.os="android",a.android=!0),(c||f||d)&&(a.os="ios",a.ios=!0),a}function ZE(t){return t===void 0&&(t={}),ff||(ff=hk(t)),ff}let hf;function pk(){const t=jr(),e=ZE();let r=!1;function n(){const o=t.navigator.userAgent.toLowerCase();return o.indexOf("safari")>=0&&o.indexOf("chrome")<0&&o.indexOf("android")<0}if(n()){const o=String(t.navigator.userAgent);if(o.includes("Version/")){const[l,u]=o.split("Version/")[1].split(" ")[0].split(".").map(c=>Number(c));r=l<16||l===16&&u<2}}const i=/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/i.test(t.navigator.userAgent),s=n(),a=s||i&&e.ios;return{isSafari:r||s,needPerspectiveFix:r,need3dFix:a,isWebView:i}}function mk(){return hf||(hf=pk()),hf}function gk(t){let{swiper:e,on:r,emit:n}=t;const i=jr();let s=null,a=null;const o=()=>{!e||e.destroyed||!e.initialized||(n("beforeResize"),n("resize"))},l=()=>{!e||e.destroyed||!e.initialized||(s=new ResizeObserver(d=>{a=i.requestAnimationFrame(()=>{const{width:f,height:m}=e;let h=f,p=m;d.forEach(v=>{let{contentBoxSize:g,contentRect:y,target:x}=v;x&&x!==e.el||(h=y?y.width:(g[0]||g).inlineSize,p=y?y.height:(g[0]||g).blockSize)}),(h!==f||p!==m)&&o()})}),s.observe(e.el))},u=()=>{a&&i.cancelAnimationFrame(a),s&&s.unobserve&&e.el&&(s.unobserve(e.el),s=null)},c=()=>{!e||e.destroyed||!e.initialized||n("orientationchange")};r("init",()=>{if(e.params.resizeObserver&&typeof i.ResizeObserver<"u"){l();return}i.addEventListener("resize",o),i.addEventListener("orientationchange",c)}),r("destroy",()=>{u(),i.removeEventListener("resize",o),i.removeEventListener("orientationchange",c)})}function vk(t){let{swiper:e,extendParams:r,on:n,emit:i}=t;const s=[],a=jr(),o=function(c,d){d===void 0&&(d={});const f=a.MutationObserver||a.WebkitMutationObserver,m=new f(h=>{if(e.__preventObserver__)return;if(h.length===1){i("observerUpdate",h[0]);return}const p=function(){i("observerUpdate",h[0])};a.requestAnimationFrame?a.requestAnimationFrame(p):a.setTimeout(p,0)});m.observe(c,{attributes:typeof d.attributes>"u"?!0:d.attributes,childList:e.isElement||(typeof d.childList>"u"?!0:d).childList,characterData:typeof d.characterData>"u"?!0:d.characterData}),s.push(m)},l=()=>{if(e.params.observer){if(e.params.observeParents){const c=dk(e.hostEl);for(let d=0;d{s.forEach(c=>{c.disconnect()}),s.splice(0,s.length)};r({observer:!1,observeParents:!1,observeSlideChildren:!1}),n("init",l),n("destroy",u)}var yk={on(t,e,r){const n=this;if(!n.eventsListeners||n.destroyed||typeof e!="function")return n;const i=r?"unshift":"push";return t.split(" ").forEach(s=>{n.eventsListeners[s]||(n.eventsListeners[s]=[]),n.eventsListeners[s][i](e)}),n},once(t,e,r){const n=this;if(!n.eventsListeners||n.destroyed||typeof e!="function")return n;function i(){n.off(t,i),i.__emitterProxy&&delete i.__emitterProxy;for(var s=arguments.length,a=new Array(s),o=0;o=0&&e.eventsAnyListeners.splice(r,1),e},off(t,e){const r=this;return!r.eventsListeners||r.destroyed||!r.eventsListeners||t.split(" ").forEach(n=>{typeof e>"u"?r.eventsListeners[n]=[]:r.eventsListeners[n]&&r.eventsListeners[n].forEach((i,s)=>{(i===e||i.__emitterProxy&&i.__emitterProxy===e)&&r.eventsListeners[n].splice(s,1)})}),r},emit(){const t=this;if(!t.eventsListeners||t.destroyed||!t.eventsListeners)return t;let e,r,n;for(var i=arguments.length,s=new Array(i),a=0;a{t.eventsAnyListeners&&t.eventsAnyListeners.length&&t.eventsAnyListeners.forEach(u=>{u.apply(n,[l,...r])}),t.eventsListeners&&t.eventsListeners[l]&&t.eventsListeners[l].forEach(u=>{u.apply(n,r)})}),t}};function xk(){const t=this;let e,r;const n=t.el;typeof t.params.width<"u"&&t.params.width!==null?e=t.params.width:e=n.clientWidth,typeof t.params.height<"u"&&t.params.height!==null?r=t.params.height:r=n.clientHeight,!(e===0&&t.isHorizontal()||r===0&&t.isVertical())&&(e=e-parseInt(Ri(n,"padding-left")||0,10)-parseInt(Ri(n,"padding-right")||0,10),r=r-parseInt(Ri(n,"padding-top")||0,10)-parseInt(Ri(n,"padding-bottom")||0,10),Number.isNaN(e)&&(e=0),Number.isNaN(r)&&(r=0),Object.assign(t,{width:e,height:r,size:t.isHorizontal()?e:r}))}function Sk(){const t=this;function e(A,k){return parseFloat(A.getPropertyValue(t.getDirectionLabel(k))||0)}const r=t.params,{wrapperEl:n,slidesEl:i,size:s,rtlTranslate:a,wrongRTL:o}=t,l=t.virtual&&r.virtual.enabled,u=l?t.virtual.slides.length:t.slides.length,c=In(i,`.${t.params.slideClass}, swiper-slide`),d=l?t.virtual.slides.length:c.length;let f=[];const m=[],h=[];let p=r.slidesOffsetBefore;typeof p=="function"&&(p=r.slidesOffsetBefore.call(t));let v=r.slidesOffsetAfter;typeof v=="function"&&(v=r.slidesOffsetAfter.call(t));const g=t.snapGrid.length,y=t.slidesGrid.length;let x=r.spaceBetween,S=-p,T=0,C=0;if(typeof s>"u")return;typeof x=="string"&&x.indexOf("%")>=0?x=parseFloat(x.replace("%",""))/100*s:typeof x=="string"&&(x=parseFloat(x)),t.virtualSize=-x,c.forEach(A=>{a?A.style.marginLeft="":A.style.marginRight="",A.style.marginBottom="",A.style.marginTop=""}),r.centeredSlides&&r.cssMode&&(eu(n,"--swiper-centered-offset-before",""),eu(n,"--swiper-centered-offset-after",""));const _=r.grid&&r.grid.rows>1&&t.grid;_?t.grid.initSlides(c):t.grid&&t.grid.unsetSlides();let b;const I=r.slidesPerView==="auto"&&r.breakpoints&&Object.keys(r.breakpoints).filter(A=>typeof r.breakpoints[A].slidesPerView<"u").length>0;for(let A=0;A1&&f.push(t.virtualSize-s)}if(l&&r.loop){const A=h[0]+x;if(r.slidesPerGroup>1){const k=Math.ceil((t.virtual.slidesBefore+t.virtual.slidesAfter)/r.slidesPerGroup),O=A*r.slidesPerGroup;for(let P=0;P!r.cssMode||r.loop?!0:O!==c.length-1).forEach(k=>{k.style[A]=`${x}px`})}if(r.centeredSlides&&r.centeredSlidesBounds){let A=0;h.forEach(O=>{A+=O+(x||0)}),A-=x;const k=A-s;f=f.map(O=>O<=0?-p:O>k?k+v:O)}if(r.centerInsufficientSlides){let A=0;h.forEach(O=>{A+=O+(x||0)}),A-=x;const k=(r.slidesOffsetBefore||0)+(r.slidesOffsetAfter||0);if(A+k{f[G]=P-O}),m.forEach((P,G)=>{m[G]=P+O})}}if(Object.assign(t,{slides:c,snapGrid:f,slidesGrid:m,slidesSizesGrid:h}),r.centeredSlides&&r.cssMode&&!r.centeredSlidesBounds){eu(n,"--swiper-centered-offset-before",`${-f[0]}px`),eu(n,"--swiper-centered-offset-after",`${t.size/2-h[h.length-1]/2}px`);const A=-t.snapGrid[0],k=-t.slidesGrid[0];t.snapGrid=t.snapGrid.map(O=>O+A),t.slidesGrid=t.slidesGrid.map(O=>O+k)}if(d!==u&&t.emit("slidesLengthChange"),f.length!==g&&(t.params.watchOverflow&&t.checkOverflow(),t.emit("snapGridLengthChange")),m.length!==y&&t.emit("slidesGridLengthChange"),r.watchSlidesProgress&&t.updateSlidesOffset(),t.emit("slidesUpdated"),!l&&!r.cssMode&&(r.effect==="slide"||r.effect==="fade")){const A=`${r.containerModifierClass}backface-hidden`,k=t.el.classList.contains(A);d<=r.maxBackfaceHiddenSlides?k||t.el.classList.add(A):k&&t.el.classList.remove(A)}}function Ek(t){const e=this,r=[],n=e.virtual&&e.params.virtual.enabled;let i=0,s;typeof t=="number"?e.setTransition(t):t===!0&&e.setTransition(e.params.speed);const a=o=>n?e.slides[e.getSlideIndexByData(o)]:e.slides[o];if(e.params.slidesPerView!=="auto"&&e.params.slidesPerView>1)if(e.params.centeredSlides)(e.visibleSlides||[]).forEach(o=>{r.push(o)});else for(s=0;se.slides.length&&!n)break;r.push(a(o))}else r.push(a(e.activeIndex));for(s=0;si?o:i}(i||i===0)&&(e.wrapperEl.style.height=`${i}px`)}function Tk(){const t=this,e=t.slides,r=t.isElement?t.isHorizontal()?t.wrapperEl.offsetLeft:t.wrapperEl.offsetTop:0;for(let n=0;n{e&&!t.classList.contains(r)?t.classList.add(r):!e&&t.classList.contains(r)&&t.classList.remove(r)};function wk(t){t===void 0&&(t=this&&this.translate||0);const e=this,r=e.params,{slides:n,rtlTranslate:i,snapGrid:s}=e;if(n.length===0)return;typeof n[0].swiperSlideOffset>"u"&&e.updateSlidesOffset();let a=-t;i&&(a=t),e.visibleSlidesIndexes=[],e.visibleSlides=[];let o=r.spaceBetween;typeof o=="string"&&o.indexOf("%")>=0?o=parseFloat(o.replace("%",""))/100*e.size:typeof o=="string"&&(o=parseFloat(o));for(let l=0;l=0&&m<=e.size-e.slidesSizesGrid[l],v=m>=0&&m1&&h<=e.size||m<=0&&h>=e.size;v&&(e.visibleSlides.push(u),e.visibleSlidesIndexes.push(l)),rv(u,v,r.slideVisibleClass),rv(u,p,r.slideFullyVisibleClass),u.progress=i?-d:d,u.originalProgress=i?-f:f}}function bk(t){const e=this;if(typeof t>"u"){const c=e.rtlTranslate?-1:1;t=e&&e.translate&&e.translate*c||0}const r=e.params,n=e.maxTranslate()-e.minTranslate();let{progress:i,isBeginning:s,isEnd:a,progressLoop:o}=e;const l=s,u=a;if(n===0)i=0,s=!0,a=!0;else{i=(t-e.minTranslate())/n;const c=Math.abs(t-e.minTranslate())<1,d=Math.abs(t-e.maxTranslate())<1;s=c||i<=0,a=d||i>=1,c&&(i=0),d&&(i=1)}if(r.loop){const c=e.getSlideIndexByData(0),d=e.getSlideIndexByData(e.slides.length-1),f=e.slidesGrid[c],m=e.slidesGrid[d],h=e.slidesGrid[e.slidesGrid.length-1],p=Math.abs(t);p>=f?o=(p-f)/h:o=(p+h-m)/h,o>1&&(o-=1)}Object.assign(e,{progress:i,progressLoop:o,isBeginning:s,isEnd:a}),(r.watchSlidesProgress||r.centeredSlides&&r.autoHeight)&&e.updateSlidesProgress(t),s&&!l&&e.emit("reachBeginning toEdge"),a&&!u&&e.emit("reachEnd toEdge"),(l&&!s||u&&!a)&&e.emit("fromEdge"),e.emit("progress",i)}const pf=(t,e,r)=>{e&&!t.classList.contains(r)?t.classList.add(r):!e&&t.classList.contains(r)&&t.classList.remove(r)};function Lk(){const t=this,{slides:e,params:r,slidesEl:n,activeIndex:i}=t,s=t.virtual&&r.virtual.enabled,a=t.grid&&r.grid&&r.grid.rows>1,o=d=>In(n,`.${r.slideClass}${d}, swiper-slide${d}`)[0];let l,u,c;if(s)if(r.loop){let d=i-t.virtual.slidesBefore;d<0&&(d=t.virtual.slides.length+d),d>=t.virtual.slides.length&&(d-=t.virtual.slides.length),l=o(`[data-swiper-slide-index="${d}"]`)}else l=o(`[data-swiper-slide-index="${i}"]`);else a?(l=e.filter(d=>d.column===i)[0],c=e.filter(d=>d.column===i+1)[0],u=e.filter(d=>d.column===i-1)[0]):l=e[i];l&&(a||(c=ck(l,`.${r.slideClass}, swiper-slide`)[0],r.loop&&!c&&(c=e[0]),u=uk(l,`.${r.slideClass}, swiper-slide`)[0],r.loop&&!u===0&&(u=e[e.length-1]))),e.forEach(d=>{pf(d,d===l,r.slideActiveClass),pf(d,d===c,r.slideNextClass),pf(d,d===u,r.slidePrevClass)}),t.emitSlidesClasses()}const Du=(t,e)=>{if(!t||t.destroyed||!t.params)return;const r=()=>t.isElement?"swiper-slide":`.${t.params.slideClass}`,n=e.closest(r());if(n){let i=n.querySelector(`.${t.params.lazyPreloaderClass}`);!i&&t.isElement&&(n.shadowRoot?i=n.shadowRoot.querySelector(`.${t.params.lazyPreloaderClass}`):requestAnimationFrame(()=>{n.shadowRoot&&(i=n.shadowRoot.querySelector(`.${t.params.lazyPreloaderClass}`),i&&i.remove())})),i&&i.remove()}},mf=(t,e)=>{if(!t.slides[e])return;const r=t.slides[e].querySelector('[loading="lazy"]');r&&r.removeAttribute("loading")},zh=t=>{if(!t||t.destroyed||!t.params)return;let e=t.params.lazyPreloadPrevNext;const r=t.slides.length;if(!r||!e||e<0)return;e=Math.min(e,r);const n=t.params.slidesPerView==="auto"?t.slidesPerViewDynamic():Math.ceil(t.params.slidesPerView),i=t.activeIndex;if(t.params.grid&&t.params.grid.rows>1){const a=i,o=[a-e];o.push(...Array.from({length:e}).map((l,u)=>a+n+u)),t.slides.forEach((l,u)=>{o.includes(l.column)&&mf(t,u)});return}const s=i+n-1;if(t.params.rewind||t.params.loop)for(let a=i-e;a<=s+e;a+=1){const o=(a%r+r)%r;(os)&&mf(t,o)}else for(let a=Math.max(i-e,0);a<=Math.min(s+e,r-1);a+=1)a!==i&&(a>s||a=e[s]&&n=e[s]&&n=e[s]&&(i=s);return r.normalizeSlideIndex&&(i<0||typeof i>"u")&&(i=0),i}function _k(t){const e=this,r=e.rtlTranslate?e.translate:-e.translate,{snapGrid:n,params:i,activeIndex:s,realIndex:a,snapIndex:o}=e;let l=t,u;const c=m=>{let h=m-e.virtual.slidesBefore;return h<0&&(h=e.virtual.slides.length+h),h>=e.virtual.slides.length&&(h-=e.virtual.slides.length),h};if(typeof l>"u"&&(l=Ak(e)),n.indexOf(r)>=0)u=n.indexOf(r);else{const m=Math.min(i.slidesPerGroupSkip,l);u=m+Math.floor((l-m)/i.slidesPerGroup)}if(u>=n.length&&(u=n.length-1),l===s&&!e.params.loop){u!==o&&(e.snapIndex=u,e.emit("snapIndexChange"));return}if(l===s&&e.params.loop&&e.virtual&&e.params.virtual.enabled){e.realIndex=c(l);return}const d=e.grid&&i.grid&&i.grid.rows>1;let f;if(e.virtual&&i.virtual.enabled&&i.loop)f=c(l);else if(d){const m=e.slides.filter(p=>p.column===l)[0];let h=parseInt(m.getAttribute("data-swiper-slide-index"),10);Number.isNaN(h)&&(h=Math.max(e.slides.indexOf(m),0)),f=Math.floor(h/i.grid.rows)}else if(e.slides[l]){const m=e.slides[l].getAttribute("data-swiper-slide-index");m?f=parseInt(m,10):f=l}else f=l;Object.assign(e,{previousSnapIndex:o,snapIndex:u,previousRealIndex:a,realIndex:f,previousIndex:s,activeIndex:l}),e.initialized&&zh(e),e.emit("activeIndexChange"),e.emit("snapIndexChange"),(e.initialized||e.params.runCallbacksOnInit)&&(a!==f&&e.emit("realIndexChange"),e.emit("slideChange"))}function Ck(t,e){const r=this,n=r.params;let i=t.closest(`.${n.slideClass}, swiper-slide`);!i&&r.isElement&&e&&e.length>1&&e.includes(t)&&[...e.slice(e.indexOf(t)+1,e.length)].forEach(o=>{!i&&o.matches&&o.matches(`.${n.slideClass}, swiper-slide`)&&(i=o)});let s=!1,a;if(i){for(let o=0;ol?c=l:n&&ta?o="next":s"u"&&(e=s.params.speed);const p=Math.min(s.params.slidesPerGroupSkip,a);let v=p+Math.floor((a-p)/s.params.slidesPerGroup);v>=l.length&&(v=l.length-1);const g=-l[v];if(o.normalizeSlideIndex)for(let x=0;x=T&&S=T&&S=T&&(a=x)}if(s.initialized&&a!==d&&(!s.allowSlideNext&&(f?g>s.translate&&g>s.minTranslate():gs.translate&&g>s.maxTranslate()&&(d||0)!==a))return!1;a!==(c||0)&&r&&s.emit("beforeSlideChangeStart"),s.updateProgress(g);let y;if(a>d?y="next":a0?(s._cssModeVirtualInitialSet=!0,requestAnimationFrame(()=>{m[x?"scrollLeft":"scrollTop"]=S})):m[x?"scrollLeft":"scrollTop"]=S,T&&requestAnimationFrame(()=>{s.wrapperEl.style.scrollSnapType="",s._immediateVirtual=!1})}else{if(!s.support.smoothScroll)return qE({swiper:s,targetPosition:S,side:x?"left":"top"}),!0;m.scrollTo({[x?"left":"top"]:S,behavior:"smooth"})}return!0}return s.setTransition(e),s.setTranslate(g),s.updateActiveIndex(a),s.updateSlidesClasses(),s.emit("beforeTransitionStart",e,n),s.transitionStart(r,y),e===0?s.transitionEnd(r,y):s.animating||(s.animating=!0,s.onSlideToWrapperTransitionEnd||(s.onSlideToWrapperTransitionEnd=function(S){!s||s.destroyed||S.target===this&&(s.wrapperEl.removeEventListener("transitionend",s.onSlideToWrapperTransitionEnd),s.onSlideToWrapperTransitionEnd=null,delete s.onSlideToWrapperTransitionEnd,s.transitionEnd(r,y))}),s.wrapperEl.addEventListener("transitionend",s.onSlideToWrapperTransitionEnd)),!0}function jk(t,e,r,n){t===void 0&&(t=0),r===void 0&&(r=!0),typeof t=="string"&&(t=parseInt(t,10));const i=this;if(i.destroyed)return;typeof e>"u"&&(e=i.params.speed);const s=i.grid&&i.params.grid&&i.params.grid.rows>1;let a=t;if(i.params.loop)if(i.virtual&&i.params.virtual.enabled)a=a+i.virtual.slidesBefore;else{let o;if(s){const f=a*i.params.grid.rows;o=i.slides.filter(m=>m.getAttribute("data-swiper-slide-index")*1===f)[0].column}else o=i.getSlideIndexByData(a);const l=s?Math.ceil(i.slides.length/i.params.grid.rows):i.slides.length,{centeredSlides:u}=i.params;let c=i.params.slidesPerView;c==="auto"?c=i.slidesPerViewDynamic():(c=Math.ceil(parseFloat(i.params.slidesPerView,10)),u&&c%2===0&&(c=c+1));let d=l-om.getAttribute("data-swiper-slide-index")*1===f)[0].column}else a=i.getSlideIndexByData(a)}return requestAnimationFrame(()=>{i.slideTo(a,e,r,n)}),i}function Vk(t,e,r){e===void 0&&(e=!0);const n=this,{enabled:i,params:s,animating:a}=n;if(!i||n.destroyed)return n;typeof t>"u"&&(t=n.params.speed);let o=s.slidesPerGroup;s.slidesPerView==="auto"&&s.slidesPerGroup===1&&s.slidesPerGroupAuto&&(o=Math.max(n.slidesPerViewDynamic("current",!0),1));const l=n.activeIndex{n.slideTo(n.activeIndex+l,t,e,r)}),!0}return s.rewind&&n.isEnd?n.slideTo(0,t,e,r):n.slideTo(n.activeIndex+l,t,e,r)}function Gk(t,e,r){e===void 0&&(e=!0);const n=this,{params:i,snapGrid:s,slidesGrid:a,rtlTranslate:o,enabled:l,animating:u}=n;if(!l||n.destroyed)return n;typeof t>"u"&&(t=n.params.speed);const c=n.virtual&&i.virtual.enabled;if(i.loop){if(u&&!c&&i.loopPreventsSliding)return!1;n.loopFix({direction:"prev"}),n._clientLeft=n.wrapperEl.clientLeft}const d=o?n.translate:-n.translate;function f(g){return g<0?-Math.floor(Math.abs(g)):Math.floor(g)}const m=f(d),h=s.map(g=>f(g));let p=s[h.indexOf(m)-1];if(typeof p>"u"&&i.cssMode){let g;s.forEach((y,x)=>{m>=y&&(g=x)}),typeof g<"u"&&(p=s[g>0?g-1:g])}let v=0;if(typeof p<"u"&&(v=a.indexOf(p),v<0&&(v=n.activeIndex-1),i.slidesPerView==="auto"&&i.slidesPerGroup===1&&i.slidesPerGroupAuto&&(v=v-n.slidesPerViewDynamic("previous",!0)+1,v=Math.max(v,0))),i.rewind&&n.isBeginning){const g=n.params.virtual&&n.params.virtual.enabled&&n.virtual?n.virtual.slides.length-1:n.slides.length-1;return n.slideTo(g,t,e,r)}else if(i.loop&&n.activeIndex===0&&i.cssMode)return requestAnimationFrame(()=>{n.slideTo(v,t,e,r)}),!0;return n.slideTo(v,t,e,r)}function zk(t,e,r){e===void 0&&(e=!0);const n=this;if(!n.destroyed)return typeof t>"u"&&(t=n.params.speed),n.slideTo(n.activeIndex,t,e,r)}function Hk(t,e,r,n){e===void 0&&(e=!0),n===void 0&&(n=.5);const i=this;if(i.destroyed)return;typeof t>"u"&&(t=i.params.speed);let s=i.activeIndex;const a=Math.min(i.params.slidesPerGroupSkip,s),o=a+Math.floor((s-a)/i.params.slidesPerGroup),l=i.rtlTranslate?i.translate:-i.translate;if(l>=i.snapGrid[o]){const u=i.snapGrid[o],c=i.snapGrid[o+1];l-u>(c-u)*n&&(s+=i.params.slidesPerGroup)}else{const u=i.snapGrid[o-1],c=i.snapGrid[o];l-u<=(c-u)*n&&(s-=i.params.slidesPerGroup)}return s=Math.max(s,0),s=Math.min(s,i.slidesGrid.length-1),i.slideTo(s,t,e,r)}function Wk(){const t=this;if(t.destroyed)return;const{params:e,slidesEl:r}=t,n=e.slidesPerView==="auto"?t.slidesPerViewDynamic():e.slidesPerView;let i=t.clickedIndex,s;const a=t.isElement?"swiper-slide":`.${e.slideClass}`;if(e.loop){if(t.animating)return;s=parseInt(t.clickedSlide.getAttribute("data-swiper-slide-index"),10),e.centeredSlides?it.slides.length-t.loopedSlides+n/2?(t.loopFix(),i=t.getSlideIndex(In(r,`${a}[data-swiper-slide-index="${s}"]`)[0]),Gh(()=>{t.slideTo(i)})):t.slideTo(i):i>t.slides.length-n?(t.loopFix(),i=t.getSlideIndex(In(r,`${a}[data-swiper-slide-index="${s}"]`)[0]),Gh(()=>{t.slideTo(i)})):t.slideTo(i)}else t.slideTo(i)}var Kk={slideTo:$k,slideToLoop:jk,slideNext:Vk,slidePrev:Gk,slideReset:zk,slideToClosest:Hk,slideToClickedSlide:Wk};function Yk(t){const e=this,{params:r,slidesEl:n}=e;if(!r.loop||e.virtual&&e.params.virtual.enabled)return;const i=()=>{In(n,`.${r.slideClass}, swiper-slide`).forEach((d,f)=>{d.setAttribute("data-swiper-slide-index",f)})},s=e.grid&&r.grid&&r.grid.rows>1,a=r.slidesPerGroup*(s?r.grid.rows:1),o=e.slides.length%a!==0,l=s&&e.slides.length%r.grid.rows!==0,u=c=>{for(let d=0;d1;u.length"u"?s=l.getSlideIndex(u.filter(P=>P.classList.contains(m.slideActiveClass))[0]):T=s;const C=n==="next"||!n,_=n==="prev"||!n;let b=0,I=0;const A=y?Math.ceil(u.length/m.grid.rows):u.length,O=(y?u[s].column:s)+(h&&typeof i>"u"?-p/2+.5:0);if(O=0;H-=1)u[H].column===K&&x.push(H)}else x.push(A-G-1)}}else if(O+p>A-g){I=Math.max(O-(A-g*2),v);for(let P=0;P{K.column===G&&S.push(H)}):S.push(G)}}if(l.__preventObserver__=!0,requestAnimationFrame(()=>{l.__preventObserver__=!1}),_&&x.forEach(P=>{u[P].swiperLoopMoveDOM=!0,f.prepend(u[P]),u[P].swiperLoopMoveDOM=!1}),C&&S.forEach(P=>{u[P].swiperLoopMoveDOM=!0,f.append(u[P]),u[P].swiperLoopMoveDOM=!1}),l.recalcSlides(),m.slidesPerView==="auto"?l.updateSlides():y&&(x.length>0&&_||S.length>0&&C)&&l.slides.forEach((P,G)=>{l.grid.updateSlide(G,P,l.slides)}),m.watchSlidesProgress&&l.updateSlidesOffset(),r){if(x.length>0&&_){if(typeof e>"u"){const P=l.slidesGrid[T],K=l.slidesGrid[T+b]-P;o?l.setTranslate(l.translate-K):(l.slideTo(T+Math.ceil(b),0,!1,!0),i&&(l.touchEventsData.startTranslate=l.touchEventsData.startTranslate-K,l.touchEventsData.currentTranslate=l.touchEventsData.currentTranslate-K))}else if(i){const P=y?x.length/m.grid.rows:x.length;l.slideTo(l.activeIndex+P,0,!1,!0),l.touchEventsData.currentTranslate=l.translate}}else if(S.length>0&&C)if(typeof e>"u"){const P=l.slidesGrid[T],K=l.slidesGrid[T-I]-P;o?l.setTranslate(l.translate-K):(l.slideTo(T-I,0,!1,!0),i&&(l.touchEventsData.startTranslate=l.touchEventsData.startTranslate-K,l.touchEventsData.currentTranslate=l.touchEventsData.currentTranslate-K))}else{const P=y?S.length/m.grid.rows:S.length;l.slideTo(l.activeIndex-P,0,!1,!0)}}if(l.allowSlidePrev=c,l.allowSlideNext=d,l.controller&&l.controller.control&&!a){const P={slideRealIndex:e,direction:n,setTranslate:i,activeSlideIndex:s,byController:!0};Array.isArray(l.controller.control)?l.controller.control.forEach(G=>{!G.destroyed&&G.params.loop&&G.loopFix({...P,slideTo:G.params.slidesPerView===m.slidesPerView?r:!1})}):l.controller.control instanceof l.constructor&&l.controller.control.params.loop&&l.controller.control.loopFix({...P,slideTo:l.controller.control.params.slidesPerView===m.slidesPerView?r:!1})}l.emit("loopFix")}function Xk(){const t=this,{params:e,slidesEl:r}=t;if(!e.loop||t.virtual&&t.params.virtual.enabled)return;t.recalcSlides();const n=[];t.slides.forEach(i=>{const s=typeof i.swiperSlideIndex>"u"?i.getAttribute("data-swiper-slide-index")*1:i.swiperSlideIndex;n[s]=i}),t.slides.forEach(i=>{i.removeAttribute("data-swiper-slide-index")}),n.forEach(i=>{r.append(i)}),t.recalcSlides(),t.slideTo(t.realIndex,0)}var Zk={loopCreate:Yk,loopFix:qk,loopDestroy:Xk};function Qk(t){const e=this;if(!e.params.simulateTouch||e.params.watchOverflow&&e.isLocked||e.params.cssMode)return;const r=e.params.touchEventsTarget==="container"?e.el:e.wrapperEl;e.isElement&&(e.__preventObserver__=!0),r.style.cursor="move",r.style.cursor=t?"grabbing":"grab",e.isElement&&requestAnimationFrame(()=>{e.__preventObserver__=!1})}function Jk(){const t=this;t.params.watchOverflow&&t.isLocked||t.params.cssMode||(t.isElement&&(t.__preventObserver__=!0),t[t.params.touchEventsTarget==="container"?"el":"wrapperEl"].style.cursor="",t.isElement&&requestAnimationFrame(()=>{t.__preventObserver__=!1}))}var eD={setGrabCursor:Qk,unsetGrabCursor:Jk};function tD(t,e){e===void 0&&(e=this);function r(n){if(!n||n===$a()||n===jr())return null;n.assignedSlot&&(n=n.assignedSlot);const i=n.closest(t);return!i&&!n.getRootNode?null:i||r(n.getRootNode().host)}return r(e)}function nv(t,e,r){const n=jr(),{params:i}=t,s=i.edgeSwipeDetection,a=i.edgeSwipeThreshold;return s&&(r<=a||r>=n.innerWidth-a)?s==="prevent"?(e.preventDefault(),!0):!1:!0}function rD(t){const e=this,r=$a();let n=t;n.originalEvent&&(n=n.originalEvent);const i=e.touchEventsData;if(n.type==="pointerdown"){if(i.pointerId!==null&&i.pointerId!==n.pointerId)return;i.pointerId=n.pointerId}else n.type==="touchstart"&&n.targetTouches.length===1&&(i.touchId=n.targetTouches[0].identifier);if(n.type==="touchstart"){nv(e,n,n.targetTouches[0].pageX);return}const{params:s,touches:a,enabled:o}=e;if(!o||!s.simulateTouch&&n.pointerType==="mouse"||e.animating&&s.preventInteractionOnTransition)return;!e.animating&&s.cssMode&&s.loop&&e.loopFix();let l=n.target;if(s.touchEventsTarget==="wrapper"&&!lk(l,e.wrapperEl)||"which"in n&&n.which===3||"button"in n&&n.button>0||i.isTouched&&i.isMoved)return;const u=!!s.noSwipingClass&&s.noSwipingClass!=="",c=n.composedPath?n.composedPath():n.path;u&&n.target&&n.target.shadowRoot&&c&&(l=c[0]);const d=s.noSwipingSelector?s.noSwipingSelector:`.${s.noSwipingClass}`,f=!!(n.target&&n.target.shadowRoot);if(s.noSwiping&&(f?tD(d,l):l.closest(d))){e.allowClick=!0;return}if(s.swipeHandler&&!l.closest(s.swipeHandler))return;a.currentX=n.pageX,a.currentY=n.pageY;const m=a.currentX,h=a.currentY;if(!nv(e,n,m))return;Object.assign(i,{isTouched:!0,isMoved:!1,allowTouchCallbacks:!0,isScrolling:void 0,startMoving:void 0}),a.startX=m,a.startY=h,i.touchStartTime=kc(),e.allowClick=!0,e.updateSize(),e.swipeDirection=void 0,s.threshold>0&&(i.allowThresholdMove=!1);let p=!0;l.matches(i.focusableElements)&&(p=!1,l.nodeName==="SELECT"&&(i.isTouched=!1)),r.activeElement&&r.activeElement.matches(i.focusableElements)&&r.activeElement!==l&&r.activeElement.blur();const v=p&&e.allowTouchMove&&s.touchStartPreventDefault;(s.touchStartForcePreventDefault||v)&&!l.isContentEditable&&n.preventDefault(),s.freeMode&&s.freeMode.enabled&&e.freeMode&&e.animating&&!s.cssMode&&e.freeMode.onTouchStart(),e.emit("touchStart",n)}function nD(t){const e=$a(),r=this,n=r.touchEventsData,{params:i,touches:s,rtlTranslate:a,enabled:o}=r;if(!o||!i.simulateTouch&&t.pointerType==="mouse")return;let l=t;if(l.originalEvent&&(l=l.originalEvent),l.type==="pointermove"&&(n.touchId!==null||l.pointerId!==n.pointerId))return;let u;if(l.type==="touchmove"){if(u=[...l.changedTouches].filter(C=>C.identifier===n.touchId)[0],!u||u.identifier!==n.touchId)return}else u=l;if(!n.isTouched){n.startMoving&&n.isScrolling&&r.emit("touchMoveOpposite",l);return}const c=u.pageX,d=u.pageY;if(l.preventedByNestedSwiper){s.startX=c,s.startY=d;return}if(!r.allowTouchMove){l.target.matches(n.focusableElements)||(r.allowClick=!1),n.isTouched&&(Object.assign(s,{startX:c,startY:d,currentX:c,currentY:d}),n.touchStartTime=kc());return}if(i.touchReleaseOnEdges&&!i.loop){if(r.isVertical()){if(ds.startY&&r.translate>=r.minTranslate()){n.isTouched=!1,n.isMoved=!1;return}}else if(cs.startX&&r.translate>=r.minTranslate())return}if(e.activeElement&&l.target===e.activeElement&&l.target.matches(n.focusableElements)){n.isMoved=!0,r.allowClick=!1;return}n.allowTouchCallbacks&&r.emit("touchMove",l),s.previousX=s.currentX,s.previousY=s.currentY,s.currentX=c,s.currentY=d;const f=s.currentX-s.startX,m=s.currentY-s.startY;if(r.params.threshold&&Math.sqrt(f**2+m**2)"u"){let C;r.isHorizontal()&&s.currentY===s.startY||r.isVertical()&&s.currentX===s.startX?n.isScrolling=!1:f*f+m*m>=25&&(C=Math.atan2(Math.abs(m),Math.abs(f))*180/Math.PI,n.isScrolling=r.isHorizontal()?C>i.touchAngle:90-C>i.touchAngle)}if(n.isScrolling&&r.emit("touchMoveOpposite",l),typeof n.startMoving>"u"&&(s.currentX!==s.startX||s.currentY!==s.startY)&&(n.startMoving=!0),n.isScrolling||l.type==="touchmove"&&n.preventTouchMoveFromPointerMove){n.isTouched=!1;return}if(!n.startMoving)return;r.allowClick=!1,!i.cssMode&&l.cancelable&&l.preventDefault(),i.touchMoveStopPropagation&&!i.nested&&l.stopPropagation();let h=r.isHorizontal()?f:m,p=r.isHorizontal()?s.currentX-s.previousX:s.currentY-s.previousY;i.oneWayMovement&&(h=Math.abs(h)*(a?1:-1),p=Math.abs(p)*(a?1:-1)),s.diff=h,h*=i.touchRatio,a&&(h=-h,p=-p);const v=r.touchesDirection;r.swipeDirection=h>0?"prev":"next",r.touchesDirection=p>0?"prev":"next";const g=r.params.loop&&!i.cssMode,y=r.touchesDirection==="next"&&r.allowSlideNext||r.touchesDirection==="prev"&&r.allowSlidePrev;if(!n.isMoved){if(g&&y&&r.loopFix({direction:r.swipeDirection}),n.startTranslate=r.getTranslate(),r.setTransition(0),r.animating){const C=new window.CustomEvent("transitionend",{bubbles:!0,cancelable:!0,detail:{bySwiperTouchMove:!0}});r.wrapperEl.dispatchEvent(C)}n.allowMomentumBounce=!1,i.grabCursor&&(r.allowSlideNext===!0||r.allowSlidePrev===!0)&&r.setGrabCursor(!0),r.emit("sliderFirstMove",l)}let x;if(new Date().getTime(),n.isMoved&&n.allowThresholdMove&&v!==r.touchesDirection&&g&&y&&Math.abs(h)>=1){Object.assign(s,{startX:c,startY:d,currentX:c,currentY:d,startTranslate:n.currentTranslate}),n.loopSwapReset=!0,n.startTranslate=n.currentTranslate;return}r.emit("sliderMove",l),n.isMoved=!0,n.currentTranslate=h+n.startTranslate;let S=!0,T=i.resistanceRatio;if(i.touchReleaseOnEdges&&(T=0),h>0?(g&&y&&!x&&n.allowThresholdMove&&n.currentTranslate>(i.centeredSlides?r.minTranslate()-r.slidesSizesGrid[r.activeIndex+1]-(i.slidesPerView!=="auto"&&r.slides.length-i.slidesPerView>=2?r.slidesSizesGrid[r.activeIndex+1]+r.params.spaceBetween:0)-r.params.spaceBetween:r.minTranslate())&&r.loopFix({direction:"prev",setTranslate:!0,activeSlideIndex:0}),n.currentTranslate>r.minTranslate()&&(S=!1,i.resistance&&(n.currentTranslate=r.minTranslate()-1+(-r.minTranslate()+n.startTranslate+h)**T))):h<0&&(g&&y&&!x&&n.allowThresholdMove&&n.currentTranslate<(i.centeredSlides?r.maxTranslate()+r.slidesSizesGrid[r.slidesSizesGrid.length-1]+r.params.spaceBetween+(i.slidesPerView!=="auto"&&r.slides.length-i.slidesPerView>=2?r.slidesSizesGrid[r.slidesSizesGrid.length-1]+r.params.spaceBetween:0):r.maxTranslate())&&r.loopFix({direction:"next",setTranslate:!0,activeSlideIndex:r.slides.length-(i.slidesPerView==="auto"?r.slidesPerViewDynamic():Math.ceil(parseFloat(i.slidesPerView,10)))}),n.currentTranslaten.startTranslate&&(n.currentTranslate=n.startTranslate),!r.allowSlidePrev&&!r.allowSlideNext&&(n.currentTranslate=n.startTranslate),i.threshold>0)if(Math.abs(h)>i.threshold||n.allowThresholdMove){if(!n.allowThresholdMove){n.allowThresholdMove=!0,s.startX=s.currentX,s.startY=s.currentY,n.currentTranslate=n.startTranslate,s.diff=r.isHorizontal()?s.currentX-s.startX:s.currentY-s.startY;return}}else{n.currentTranslate=n.startTranslate;return}!i.followFinger||i.cssMode||((i.freeMode&&i.freeMode.enabled&&r.freeMode||i.watchSlidesProgress)&&(r.updateActiveIndex(),r.updateSlidesClasses()),i.freeMode&&i.freeMode.enabled&&r.freeMode&&r.freeMode.onTouchMove(),r.updateProgress(n.currentTranslate),r.setTranslate(n.currentTranslate))}function iD(t){const e=this,r=e.touchEventsData;let n=t;n.originalEvent&&(n=n.originalEvent);let i;if(n.type==="touchend"||n.type==="touchcancel"){if(i=[...n.changedTouches].filter(T=>T.identifier===r.touchId)[0],!i||i.identifier!==r.touchId)return}else{if(r.touchId!==null||n.pointerId!==r.pointerId)return;i=n}if(["pointercancel","pointerout","pointerleave","contextmenu"].includes(n.type)&&!(["pointercancel","contextmenu"].includes(n.type)&&(e.browser.isSafari||e.browser.isWebView)))return;r.pointerId=null,r.touchId=null;const{params:a,touches:o,rtlTranslate:l,slidesGrid:u,enabled:c}=e;if(!c||!a.simulateTouch&&n.pointerType==="mouse")return;if(r.allowTouchCallbacks&&e.emit("touchEnd",n),r.allowTouchCallbacks=!1,!r.isTouched){r.isMoved&&a.grabCursor&&e.setGrabCursor(!1),r.isMoved=!1,r.startMoving=!1;return}a.grabCursor&&r.isMoved&&r.isTouched&&(e.allowSlideNext===!0||e.allowSlidePrev===!0)&&e.setGrabCursor(!1);const d=kc(),f=d-r.touchStartTime;if(e.allowClick){const T=n.path||n.composedPath&&n.composedPath();e.updateClickedSlide(T&&T[0]||n.target,T),e.emit("tap click",n),f<300&&d-r.lastClickTime<300&&e.emit("doubleTap doubleClick",n)}if(r.lastClickTime=kc(),Gh(()=>{e.destroyed||(e.allowClick=!0)}),!r.isTouched||!r.isMoved||!e.swipeDirection||o.diff===0&&!r.loopSwapReset||r.currentTranslate===r.startTranslate&&!r.loopSwapReset){r.isTouched=!1,r.isMoved=!1,r.startMoving=!1;return}r.isTouched=!1,r.isMoved=!1,r.startMoving=!1;let m;if(a.followFinger?m=l?e.translate:-e.translate:m=-r.currentTranslate,a.cssMode)return;if(a.freeMode&&a.freeMode.enabled){e.freeMode.onTouchEnd({currentPos:m});return}const h=m>=-e.maxTranslate()&&!e.params.loop;let p=0,v=e.slidesSizesGrid[0];for(let T=0;T=u[T]&&m=u[T])&&(p=T,v=u[u.length-1]-u[u.length-2])}let g=null,y=null;a.rewind&&(e.isBeginning?y=a.virtual&&a.virtual.enabled&&e.virtual?e.virtual.slides.length-1:e.slides.length-1:e.isEnd&&(g=0));const x=(m-u[p])/v,S=pa.longSwipesMs){if(!a.longSwipes){e.slideTo(e.activeIndex);return}e.swipeDirection==="next"&&(x>=a.longSwipesRatio?e.slideTo(a.rewind&&e.isEnd?g:p+S):e.slideTo(p)),e.swipeDirection==="prev"&&(x>1-a.longSwipesRatio?e.slideTo(p+S):y!==null&&x<0&&Math.abs(x)>a.longSwipesRatio?e.slideTo(y):e.slideTo(p))}else{if(!a.shortSwipes){e.slideTo(e.activeIndex);return}e.navigation&&(n.target===e.navigation.nextEl||n.target===e.navigation.prevEl)?n.target===e.navigation.nextEl?e.slideTo(p+S):e.slideTo(p):(e.swipeDirection==="next"&&e.slideTo(g!==null?g:p+S),e.swipeDirection==="prev"&&e.slideTo(y!==null?y:p))}}function iv(){const t=this,{params:e,el:r}=t;if(r&&r.offsetWidth===0)return;e.breakpoints&&t.setBreakpoint();const{allowSlideNext:n,allowSlidePrev:i,snapGrid:s}=t,a=t.virtual&&t.params.virtual.enabled;t.allowSlideNext=!0,t.allowSlidePrev=!0,t.updateSize(),t.updateSlides(),t.updateSlidesClasses();const o=a&&e.loop;(e.slidesPerView==="auto"||e.slidesPerView>1)&&t.isEnd&&!t.isBeginning&&!t.params.centeredSlides&&!o?t.slideTo(t.slides.length-1,0,!1,!0):t.params.loop&&!a?t.slideToLoop(t.realIndex,0,!1,!0):t.slideTo(t.activeIndex,0,!1,!0),t.autoplay&&t.autoplay.running&&t.autoplay.paused&&(clearTimeout(t.autoplay.resizeTimeout),t.autoplay.resizeTimeout=setTimeout(()=>{t.autoplay&&t.autoplay.running&&t.autoplay.paused&&t.autoplay.resume()},500)),t.allowSlidePrev=i,t.allowSlideNext=n,t.params.watchOverflow&&s!==t.snapGrid&&t.checkOverflow()}function sD(t){const e=this;e.enabled&&(e.allowClick||(e.params.preventClicks&&t.preventDefault(),e.params.preventClicksPropagation&&e.animating&&(t.stopPropagation(),t.stopImmediatePropagation())))}function aD(){const t=this,{wrapperEl:e,rtlTranslate:r,enabled:n}=t;if(!n)return;t.previousTranslate=t.translate,t.isHorizontal()?t.translate=-e.scrollLeft:t.translate=-e.scrollTop,t.translate===0&&(t.translate=0),t.updateActiveIndex(),t.updateSlidesClasses();let i;const s=t.maxTranslate()-t.minTranslate();s===0?i=0:i=(t.translate-t.minTranslate())/s,i!==t.progress&&t.updateProgress(r?-t.translate:t.translate),t.emit("setTranslate",t.translate,!1)}function oD(t){const e=this;Du(e,t.target),!(e.params.cssMode||e.params.slidesPerView!=="auto"&&!e.params.autoHeight)&&e.update()}function lD(){const t=this;t.documentTouchHandlerProceeded||(t.documentTouchHandlerProceeded=!0,t.params.touchReleaseOnEdges&&(t.el.style.touchAction="auto"))}const JE=(t,e)=>{const r=$a(),{params:n,el:i,wrapperEl:s,device:a}=t,o=!!n.nested,l=e==="on"?"addEventListener":"removeEventListener",u=e;!i||typeof i=="string"||(r[l]("touchstart",t.onDocumentTouchStart,{passive:!1,capture:o}),i[l]("touchstart",t.onTouchStart,{passive:!1}),i[l]("pointerdown",t.onTouchStart,{passive:!1}),r[l]("touchmove",t.onTouchMove,{passive:!1,capture:o}),r[l]("pointermove",t.onTouchMove,{passive:!1,capture:o}),r[l]("touchend",t.onTouchEnd,{passive:!0}),r[l]("pointerup",t.onTouchEnd,{passive:!0}),r[l]("pointercancel",t.onTouchEnd,{passive:!0}),r[l]("touchcancel",t.onTouchEnd,{passive:!0}),r[l]("pointerout",t.onTouchEnd,{passive:!0}),r[l]("pointerleave",t.onTouchEnd,{passive:!0}),r[l]("contextmenu",t.onTouchEnd,{passive:!0}),(n.preventClicks||n.preventClicksPropagation)&&i[l]("click",t.onClick,!0),n.cssMode&&s[l]("scroll",t.onScroll),n.updateOnWindowResize?t[u](a.ios||a.android?"resize orientationchange observerUpdate":"resize observerUpdate",iv,!0):t[u]("observerUpdate",iv,!0),i[l]("load",t.onLoad,{capture:!0}))};function uD(){const t=this,{params:e}=t;t.onTouchStart=rD.bind(t),t.onTouchMove=nD.bind(t),t.onTouchEnd=iD.bind(t),t.onDocumentTouchStart=lD.bind(t),e.cssMode&&(t.onScroll=aD.bind(t)),t.onClick=sD.bind(t),t.onLoad=oD.bind(t),JE(t,"on")}function cD(){JE(this,"off")}var dD={attachEvents:uD,detachEvents:cD};const sv=(t,e)=>t.grid&&e.grid&&e.grid.rows>1;function fD(){const t=this,{realIndex:e,initialized:r,params:n,el:i}=t,s=n.breakpoints;if(!s||s&&Object.keys(s).length===0)return;const a=t.getBreakpoint(s,t.params.breakpointsBase,t.el);if(!a||t.currentBreakpoint===a)return;const l=(a in s?s[a]:void 0)||t.originalParams,u=sv(t,n),c=sv(t,l),d=t.params.grabCursor,f=l.grabCursor,m=n.enabled;u&&!c?(i.classList.remove(`${n.containerModifierClass}grid`,`${n.containerModifierClass}grid-column`),t.emitContainerClasses()):!u&&c&&(i.classList.add(`${n.containerModifierClass}grid`),(l.grid.fill&&l.grid.fill==="column"||!l.grid.fill&&n.grid.fill==="column")&&i.classList.add(`${n.containerModifierClass}grid-column`),t.emitContainerClasses()),d&&!f?t.unsetGrabCursor():!d&&f&&t.setGrabCursor(),["navigation","pagination","scrollbar"].forEach(x=>{if(typeof l[x]>"u")return;const S=n[x]&&n[x].enabled,T=l[x]&&l[x].enabled;S&&!T&&t[x].disable(),!S&&T&&t[x].enable()});const h=l.direction&&l.direction!==n.direction,p=n.loop&&(l.slidesPerView!==n.slidesPerView||h),v=n.loop;h&&r&&t.changeDirection(),Ir(t.params,l);const g=t.params.enabled,y=t.params.loop;Object.assign(t,{allowTouchMove:t.params.allowTouchMove,allowSlideNext:t.params.allowSlideNext,allowSlidePrev:t.params.allowSlidePrev}),m&&!g?t.disable():!m&&g&&t.enable(),t.currentBreakpoint=a,t.emit("_beforeBreakpoint",l),r&&(p?(t.loopDestroy(),t.loopCreate(e),t.updateSlides()):!v&&y?(t.loopCreate(e),t.updateSlides()):v&&!y&&t.loopDestroy()),t.emit("breakpoint",l)}function hD(t,e,r){if(e===void 0&&(e="window"),!t||e==="container"&&!r)return;let n=!1;const i=jr(),s=e==="window"?i.innerHeight:r.clientHeight,a=Object.keys(t).map(o=>{if(typeof o=="string"&&o.indexOf("@")===0){const l=parseFloat(o.substr(1));return{value:s*l,point:o}}return{value:o,point:o}});a.sort((o,l)=>parseInt(o.value,10)-parseInt(l.value,10));for(let o=0;o{typeof n=="object"?Object.keys(n).forEach(i=>{n[i]&&r.push(e+i)}):typeof n=="string"&&r.push(e+n)}),r}function gD(){const t=this,{classNames:e,params:r,rtl:n,el:i,device:s}=t,a=mD(["initialized",r.direction,{"free-mode":t.params.freeMode&&r.freeMode.enabled},{autoheight:r.autoHeight},{rtl:n},{grid:r.grid&&r.grid.rows>1},{"grid-column":r.grid&&r.grid.rows>1&&r.grid.fill==="column"},{android:s.android},{ios:s.ios},{"css-mode":r.cssMode},{centered:r.cssMode&&r.centeredSlides},{"watch-progress":r.watchSlidesProgress}],r.containerModifierClass);e.push(...a),i.classList.add(...e),t.emitContainerClasses()}function vD(){const t=this,{el:e,classNames:r}=t;!e||typeof e=="string"||(e.classList.remove(...r),t.emitContainerClasses())}var yD={addClasses:gD,removeClasses:vD};function xD(){const t=this,{isLocked:e,params:r}=t,{slidesOffsetBefore:n}=r;if(n){const i=t.slides.length-1,s=t.slidesGrid[i]+t.slidesSizesGrid[i]+n*2;t.isLocked=t.size>s}else t.isLocked=t.snapGrid.length===1;r.allowSlideNext===!0&&(t.allowSlideNext=!t.isLocked),r.allowSlidePrev===!0&&(t.allowSlidePrev=!t.isLocked),e&&e!==t.isLocked&&(t.isEnd=!1),e!==t.isLocked&&t.emit(t.isLocked?"lock":"unlock")}var SD={checkOverflow:xD},Hh={init:!0,direction:"horizontal",oneWayMovement:!1,swiperElementNodeName:"SWIPER-CONTAINER",touchEventsTarget:"wrapper",initialSlide:0,speed:300,cssMode:!1,updateOnWindowResize:!0,resizeObserver:!0,nested:!1,createElements:!1,eventsPrefix:"swiper",enabled:!0,focusableElements:"input, select, option, textarea, button, video, label",width:null,height:null,preventInteractionOnTransition:!1,userAgent:null,url:null,edgeSwipeDetection:!1,edgeSwipeThreshold:20,autoHeight:!1,setWrapperSize:!1,virtualTranslate:!1,effect:"slide",breakpoints:void 0,breakpointsBase:"window",spaceBetween:0,slidesPerView:1,slidesPerGroup:1,slidesPerGroupSkip:0,slidesPerGroupAuto:!1,centeredSlides:!1,centeredSlidesBounds:!1,slidesOffsetBefore:0,slidesOffsetAfter:0,normalizeSlideIndex:!0,centerInsufficientSlides:!1,watchOverflow:!0,roundLengths:!1,touchRatio:1,touchAngle:45,simulateTouch:!0,shortSwipes:!0,longSwipes:!0,longSwipesRatio:.5,longSwipesMs:300,followFinger:!0,allowTouchMove:!0,threshold:5,touchMoveStopPropagation:!1,touchStartPreventDefault:!0,touchStartForcePreventDefault:!1,touchReleaseOnEdges:!1,uniqueNavElements:!0,resistance:!0,resistanceRatio:.85,watchSlidesProgress:!1,grabCursor:!1,preventClicks:!0,preventClicksPropagation:!0,slideToClickedSlide:!1,loop:!1,loopAddBlankSlides:!0,loopAdditionalSlides:0,loopPreventsSliding:!0,rewind:!1,allowSlidePrev:!0,allowSlideNext:!0,swipeHandler:null,noSwiping:!0,noSwipingClass:"swiper-no-swiping",noSwipingSelector:null,passiveListeners:!0,maxBackfaceHiddenSlides:10,containerModifierClass:"swiper-",slideClass:"swiper-slide",slideBlankClass:"swiper-slide-blank",slideActiveClass:"swiper-slide-active",slideVisibleClass:"swiper-slide-visible",slideFullyVisibleClass:"swiper-slide-fully-visible",slideNextClass:"swiper-slide-next",slidePrevClass:"swiper-slide-prev",wrapperClass:"swiper-wrapper",lazyPreloaderClass:"swiper-lazy-preloader",lazyPreloadPrevNext:0,runCallbacksOnInit:!0,_emitClasses:!1};function ED(t,e){return function(n){n===void 0&&(n={});const i=Object.keys(n)[0],s=n[i];if(typeof s!="object"||s===null){Ir(e,n);return}if(t[i]===!0&&(t[i]={enabled:!0}),i==="navigation"&&t[i]&&t[i].enabled&&!t[i].prevEl&&!t[i].nextEl&&(t[i].auto=!0),["pagination","scrollbar"].indexOf(i)>=0&&t[i]&&t[i].enabled&&!t[i].el&&(t[i].auto=!0),!(i in t&&"enabled"in s)){Ir(e,n);return}typeof t[i]=="object"&&!("enabled"in t[i])&&(t[i].enabled=!0),t[i]||(t[i]={enabled:!1}),Ir(e,n)}}const gf={eventsEmitter:yk,update:Rk,translate:Mk,transition:Bk,slide:Kk,loop:Zk,grabCursor:eD,events:dD,breakpoints:pD,checkOverflow:SD,classes:yD},vf={};let bm=class qn{constructor(){let e,r;for(var n=arguments.length,i=new Array(n),s=0;s1){const c=[];return a.querySelectorAll(r.el).forEach(d=>{const f=Ir({},r,{el:d});c.push(new qn(f))}),c}const o=this;o.__swiper__=!0,o.support=XE(),o.device=ZE({userAgent:r.userAgent}),o.browser=mk(),o.eventsListeners={},o.eventsAnyListeners=[],o.modules=[...o.__modules__],r.modules&&Array.isArray(r.modules)&&o.modules.push(...r.modules);const l={};o.modules.forEach(c=>{c({params:r,swiper:o,extendParams:ED(r,l),on:o.on.bind(o),once:o.once.bind(o),off:o.off.bind(o),emit:o.emit.bind(o)})});const u=Ir({},Hh,l);return o.params=Ir({},u,vf,r),o.originalParams=Ir({},o.params),o.passedParams=Ir({},r),o.params&&o.params.on&&Object.keys(o.params.on).forEach(c=>{o.on(c,o.params.on[c])}),o.params&&o.params.onAny&&o.onAny(o.params.onAny),Object.assign(o,{enabled:o.params.enabled,el:e,classNames:[],slides:[],slidesGrid:[],snapGrid:[],slidesSizesGrid:[],isHorizontal(){return o.params.direction==="horizontal"},isVertical(){return o.params.direction==="vertical"},activeIndex:0,realIndex:0,isBeginning:!0,isEnd:!1,translate:0,previousTranslate:0,progress:0,velocity:0,animating:!1,cssOverflowAdjustment(){return Math.trunc(this.translate/2**23)*2**23},allowSlideNext:o.params.allowSlideNext,allowSlidePrev:o.params.allowSlidePrev,touchEventsData:{isTouched:void 0,isMoved:void 0,allowTouchCallbacks:void 0,touchStartTime:void 0,isScrolling:void 0,currentTranslate:void 0,startTranslate:void 0,allowThresholdMove:void 0,focusableElements:o.params.focusableElements,lastClickTime:0,clickTimeout:void 0,velocities:[],allowMomentumBounce:void 0,startMoving:void 0,pointerId:null,touchId:null},allowClick:!0,allowTouchMove:o.params.allowTouchMove,touches:{startX:0,startY:0,currentX:0,currentY:0,diff:0},imagesToLoad:[],imagesLoaded:0}),o.emit("_swiper"),o.params.init&&o.init(),o}getDirectionLabel(e){return this.isHorizontal()?e:{width:"height","margin-top":"margin-left","margin-bottom ":"margin-right","margin-left":"margin-top","margin-right":"margin-bottom","padding-left":"padding-top","padding-right":"padding-bottom",marginRight:"marginBottom"}[e]}getSlideIndex(e){const{slidesEl:r,params:n}=this,i=In(r,`.${n.slideClass}, swiper-slide`),s=ev(i[0]);return ev(e)-s}getSlideIndexByData(e){return this.getSlideIndex(this.slides.filter(r=>r.getAttribute("data-swiper-slide-index")*1===e)[0])}recalcSlides(){const e=this,{slidesEl:r,params:n}=e;e.slides=In(r,`.${n.slideClass}, swiper-slide`)}enable(){const e=this;e.enabled||(e.enabled=!0,e.params.grabCursor&&e.setGrabCursor(),e.emit("enable"))}disable(){const e=this;e.enabled&&(e.enabled=!1,e.params.grabCursor&&e.unsetGrabCursor(),e.emit("disable"))}setProgress(e,r){const n=this;e=Math.min(Math.max(e,0),1);const i=n.minTranslate(),a=(n.maxTranslate()-i)*e+i;n.translateTo(a,typeof r>"u"?0:r),n.updateActiveIndex(),n.updateSlidesClasses()}emitContainerClasses(){const e=this;if(!e.params._emitClasses||!e.el)return;const r=e.el.className.split(" ").filter(n=>n.indexOf("swiper")===0||n.indexOf(e.params.containerModifierClass)===0);e.emit("_containerClasses",r.join(" "))}getSlideClasses(e){const r=this;return r.destroyed?"":e.className.split(" ").filter(n=>n.indexOf("swiper-slide")===0||n.indexOf(r.params.slideClass)===0).join(" ")}emitSlidesClasses(){const e=this;if(!e.params._emitClasses||!e.el)return;const r=[];e.slides.forEach(n=>{const i=e.getSlideClasses(n);r.push({slideEl:n,classNames:i}),e.emit("_slideClass",n,i)}),e.emit("_slideClasses",r)}slidesPerViewDynamic(e,r){e===void 0&&(e="current"),r===void 0&&(r=!1);const n=this,{params:i,slides:s,slidesGrid:a,slidesSizesGrid:o,size:l,activeIndex:u}=n;let c=1;if(typeof i.slidesPerView=="number")return i.slidesPerView;if(i.centeredSlides){let d=s[u]?Math.ceil(s[u].swiperSlideSize):0,f;for(let m=u+1;ml&&(f=!0));for(let m=u-1;m>=0;m-=1)s[m]&&!f&&(d+=s[m].swiperSlideSize,c+=1,d>l&&(f=!0))}else if(e==="current")for(let d=u+1;d=0;d-=1)a[u]-a[d]{a.complete&&Du(e,a)}),e.updateSize(),e.updateSlides(),e.updateProgress(),e.updateSlidesClasses();function i(){const a=e.rtlTranslate?e.translate*-1:e.translate,o=Math.min(Math.max(a,e.maxTranslate()),e.minTranslate());e.setTranslate(o),e.updateActiveIndex(),e.updateSlidesClasses()}let s;if(n.freeMode&&n.freeMode.enabled&&!n.cssMode)i(),n.autoHeight&&e.updateAutoHeight();else{if((n.slidesPerView==="auto"||n.slidesPerView>1)&&e.isEnd&&!n.centeredSlides){const a=e.virtual&&n.virtual.enabled?e.virtual.slides:e.slides;s=e.slideTo(a.length-1,0,!1,!0)}else s=e.slideTo(e.activeIndex,0,!1,!0);s||i()}n.watchOverflow&&r!==e.snapGrid&&e.checkOverflow(),e.emit("update")}changeDirection(e,r){r===void 0&&(r=!0);const n=this,i=n.params.direction;return e||(e=i==="horizontal"?"vertical":"horizontal"),e===i||e!=="horizontal"&&e!=="vertical"||(n.el.classList.remove(`${n.params.containerModifierClass}${i}`),n.el.classList.add(`${n.params.containerModifierClass}${e}`),n.emitContainerClasses(),n.params.direction=e,n.slides.forEach(s=>{e==="vertical"?s.style.width="":s.style.height=""}),n.emit("changeDirection"),r&&n.update()),n}changeLanguageDirection(e){const r=this;r.rtl&&e==="rtl"||!r.rtl&&e==="ltr"||(r.rtl=e==="rtl",r.rtlTranslate=r.params.direction==="horizontal"&&r.rtl,r.rtl?(r.el.classList.add(`${r.params.containerModifierClass}rtl`),r.el.dir="rtl"):(r.el.classList.remove(`${r.params.containerModifierClass}rtl`),r.el.dir="ltr"),r.update())}mount(e){const r=this;if(r.mounted)return!0;let n=e||r.params.el;if(typeof n=="string"&&(n=document.querySelector(n)),!n)return!1;n.swiper=r,n.parentNode&&n.parentNode.host&&n.parentNode.host.nodeName===r.params.swiperElementNodeName.toUpperCase()&&(r.isElement=!0);const i=()=>`.${(r.params.wrapperClass||"").trim().split(" ").join(".")}`;let a=n&&n.shadowRoot&&n.shadowRoot.querySelector?n.shadowRoot.querySelector(i()):In(n,i())[0];return!a&&r.params.createElements&&(a=Pc("div",r.params.wrapperClass),n.append(a),In(n,`.${r.params.slideClass}`).forEach(o=>{a.append(o)})),Object.assign(r,{el:n,wrapperEl:a,slidesEl:r.isElement&&!n.parentNode.host.slideSlots?n.parentNode.host:a,hostEl:r.isElement?n.parentNode.host:n,mounted:!0,rtl:n.dir.toLowerCase()==="rtl"||Ri(n,"direction")==="rtl",rtlTranslate:r.params.direction==="horizontal"&&(n.dir.toLowerCase()==="rtl"||Ri(n,"direction")==="rtl"),wrongRTL:Ri(a,"display")==="-webkit-box"}),!0}init(e){const r=this;if(r.initialized||r.mount(e)===!1)return r;r.emit("beforeInit"),r.params.breakpoints&&r.setBreakpoint(),r.addClasses(),r.updateSize(),r.updateSlides(),r.params.watchOverflow&&r.checkOverflow(),r.params.grabCursor&&r.enabled&&r.setGrabCursor(),r.params.loop&&r.virtual&&r.params.virtual.enabled?r.slideTo(r.params.initialSlide+r.virtual.slidesBefore,0,r.params.runCallbacksOnInit,!1,!0):r.slideTo(r.params.initialSlide,0,r.params.runCallbacksOnInit,!1,!0),r.params.loop&&r.loopCreate(),r.attachEvents();const i=[...r.el.querySelectorAll('[loading="lazy"]')];return r.isElement&&i.push(...r.hostEl.querySelectorAll('[loading="lazy"]')),i.forEach(s=>{s.complete?Du(r,s):s.addEventListener("load",a=>{Du(r,a.target)})}),zh(r),r.initialized=!0,zh(r),r.emit("init"),r.emit("afterInit"),r}destroy(e,r){e===void 0&&(e=!0),r===void 0&&(r=!0);const n=this,{params:i,el:s,wrapperEl:a,slides:o}=n;return typeof n.params>"u"||n.destroyed||(n.emit("beforeDestroy"),n.initialized=!1,n.detachEvents(),i.loop&&n.loopDestroy(),r&&(n.removeClasses(),s&&typeof s!="string"&&s.removeAttribute("style"),a&&a.removeAttribute("style"),o&&o.length&&o.forEach(l=>{l.classList.remove(i.slideVisibleClass,i.slideFullyVisibleClass,i.slideActiveClass,i.slideNextClass,i.slidePrevClass),l.removeAttribute("style"),l.removeAttribute("data-swiper-slide-index")})),n.emit("destroy"),Object.keys(n.eventsListeners).forEach(l=>{n.off(l)}),e!==!1&&(n.el&&typeof n.el!="string"&&(n.el.swiper=null),ik(n)),n.destroyed=!0),null}static extendDefaults(e){Ir(vf,e)}static get extendedDefaults(){return vf}static get defaults(){return Hh}static installModule(e){qn.prototype.__modules__||(qn.prototype.__modules__=[]);const r=qn.prototype.__modules__;typeof e=="function"&&r.indexOf(e)<0&&r.push(e)}static use(e){return Array.isArray(e)?(e.forEach(r=>qn.installModule(r)),qn):(qn.installModule(e),qn)}};Object.keys(gf).forEach(t=>{Object.keys(gf[t]).forEach(e=>{bm.prototype[e]=gf[t][e]})});bm.use([gk,vk]);const eT=["eventsPrefix","injectStyles","injectStylesUrls","modules","init","_direction","oneWayMovement","swiperElementNodeName","touchEventsTarget","initialSlide","_speed","cssMode","updateOnWindowResize","resizeObserver","nested","focusableElements","_enabled","_width","_height","preventInteractionOnTransition","userAgent","url","_edgeSwipeDetection","_edgeSwipeThreshold","_freeMode","_autoHeight","setWrapperSize","virtualTranslate","_effect","breakpoints","breakpointsBase","_spaceBetween","_slidesPerView","maxBackfaceHiddenSlides","_grid","_slidesPerGroup","_slidesPerGroupSkip","_slidesPerGroupAuto","_centeredSlides","_centeredSlidesBounds","_slidesOffsetBefore","_slidesOffsetAfter","normalizeSlideIndex","_centerInsufficientSlides","_watchOverflow","roundLengths","touchRatio","touchAngle","simulateTouch","_shortSwipes","_longSwipes","longSwipesRatio","longSwipesMs","_followFinger","allowTouchMove","_threshold","touchMoveStopPropagation","touchStartPreventDefault","touchStartForcePreventDefault","touchReleaseOnEdges","uniqueNavElements","_resistance","_resistanceRatio","_watchSlidesProgress","_grabCursor","preventClicks","preventClicksPropagation","_slideToClickedSlide","_loop","loopAdditionalSlides","loopAddBlankSlides","loopPreventsSliding","_rewind","_allowSlidePrev","_allowSlideNext","_swipeHandler","_noSwiping","noSwipingClass","noSwipingSelector","passiveListeners","containerModifierClass","slideClass","slideActiveClass","slideVisibleClass","slideFullyVisibleClass","slideNextClass","slidePrevClass","slideBlankClass","wrapperClass","lazyPreloaderClass","lazyPreloadPrevNext","runCallbacksOnInit","observer","observeParents","observeSlideChildren","a11y","_autoplay","_controller","coverflowEffect","cubeEffect","fadeEffect","flipEffect","creativeEffect","cardsEffect","hashNavigation","history","keyboard","mousewheel","_navigation","_pagination","parallax","_scrollbar","_thumbs","virtual","zoom","control"];function ws(t){return typeof t=="object"&&t!==null&&t.constructor&&Object.prototype.toString.call(t).slice(8,-1)==="Object"&&!t.__swiper__}function ca(t,e){const r=["__proto__","constructor","prototype"];Object.keys(e).filter(n=>r.indexOf(n)<0).forEach(n=>{typeof t[n]>"u"?t[n]=e[n]:ws(e[n])&&ws(t[n])&&Object.keys(e[n]).length>0?e[n].__swiper__?t[n]=e[n]:ca(t[n],e[n]):t[n]=e[n]})}function tT(t){return t===void 0&&(t={}),t.navigation&&typeof t.navigation.nextEl>"u"&&typeof t.navigation.prevEl>"u"}function rT(t){return t===void 0&&(t={}),t.pagination&&typeof t.pagination.el>"u"}function nT(t){return t===void 0&&(t={}),t.scrollbar&&typeof t.scrollbar.el>"u"}function iT(t){t===void 0&&(t="");const e=t.split(" ").map(n=>n.trim()).filter(n=>!!n),r=[];return e.forEach(n=>{r.indexOf(n)<0&&r.push(n)}),r.join(" ")}function TD(t){return t===void 0&&(t=""),t?t.includes("swiper-wrapper")?t:`swiper-wrapper ${t}`:"swiper-wrapper"}function wD(t){let{swiper:e,slides:r,passedParams:n,changedParams:i,nextEl:s,prevEl:a,scrollbarEl:o,paginationEl:l}=t;const u=i.filter(I=>I!=="children"&&I!=="direction"&&I!=="wrapperClass"),{params:c,pagination:d,navigation:f,scrollbar:m,virtual:h,thumbs:p}=e;let v,g,y,x,S,T,C,_;i.includes("thumbs")&&n.thumbs&&n.thumbs.swiper&&c.thumbs&&!c.thumbs.swiper&&(v=!0),i.includes("controller")&&n.controller&&n.controller.control&&c.controller&&!c.controller.control&&(g=!0),i.includes("pagination")&&n.pagination&&(n.pagination.el||l)&&(c.pagination||c.pagination===!1)&&d&&!d.el&&(y=!0),i.includes("scrollbar")&&n.scrollbar&&(n.scrollbar.el||o)&&(c.scrollbar||c.scrollbar===!1)&&m&&!m.el&&(x=!0),i.includes("navigation")&&n.navigation&&(n.navigation.prevEl||a)&&(n.navigation.nextEl||s)&&(c.navigation||c.navigation===!1)&&f&&!f.prevEl&&!f.nextEl&&(S=!0);const b=I=>{e[I]&&(e[I].destroy(),I==="navigation"?(e.isElement&&(e[I].prevEl.remove(),e[I].nextEl.remove()),c[I].prevEl=void 0,c[I].nextEl=void 0,e[I].prevEl=void 0,e[I].nextEl=void 0):(e.isElement&&e[I].el.remove(),c[I].el=void 0,e[I].el=void 0))};i.includes("loop")&&e.isElement&&(c.loop&&!n.loop?T=!0:!c.loop&&n.loop?C=!0:_=!0),u.forEach(I=>{if(ws(c[I])&&ws(n[I]))Object.assign(c[I],n[I]),(I==="navigation"||I==="pagination"||I==="scrollbar")&&"enabled"in n[I]&&!n[I].enabled&&b(I);else{const A=n[I];(A===!0||A===!1)&&(I==="navigation"||I==="pagination"||I==="scrollbar")?A===!1&&b(I):c[I]=n[I]}}),u.includes("controller")&&!g&&e.controller&&e.controller.control&&c.controller&&c.controller.control&&(e.controller.control=c.controller.control),i.includes("children")&&r&&h&&c.virtual.enabled?(h.slides=r,h.update(!0)):i.includes("virtual")&&h&&c.virtual.enabled&&(r&&(h.slides=r),h.update(!0)),i.includes("children")&&r&&c.loop&&(_=!0),v&&p.init()&&p.update(!0),g&&(e.controller.control=c.controller.control),y&&(e.isElement&&(!l||typeof l=="string")&&(l=document.createElement("div"),l.classList.add("swiper-pagination"),l.part.add("pagination"),e.el.appendChild(l)),l&&(c.pagination.el=l),d.init(),d.render(),d.update()),x&&(e.isElement&&(!o||typeof o=="string")&&(o=document.createElement("div"),o.classList.add("swiper-scrollbar"),o.part.add("scrollbar"),e.el.appendChild(o)),o&&(c.scrollbar.el=o),m.init(),m.updateSize(),m.setTranslate()),S&&(e.isElement&&((!s||typeof s=="string")&&(s=document.createElement("div"),s.classList.add("swiper-button-next"),s.innerHTML=e.hostEl.constructor.nextButtonSvg,s.part.add("button-next"),e.el.appendChild(s)),(!a||typeof a=="string")&&(a=document.createElement("div"),a.classList.add("swiper-button-prev"),a.innerHTML=e.hostEl.constructor.prevButtonSvg,a.part.add("button-prev"),e.el.appendChild(a))),s&&(c.navigation.nextEl=s),a&&(c.navigation.prevEl=a),f.init(),f.update()),i.includes("allowSlideNext")&&(e.allowSlideNext=n.allowSlideNext),i.includes("allowSlidePrev")&&(e.allowSlidePrev=n.allowSlidePrev),i.includes("direction")&&e.changeDirection(n.direction,!1),(T||_)&&e.loopDestroy(),(C||_)&&e.loopCreate(),e.update()}function bD(t,e){t===void 0&&(t={}),e===void 0&&(e=!0);const r={on:{}},n={},i={};ca(r,Hh),r._emitClasses=!0,r.init=!1;const s={},a=eT.map(l=>l.replace(/_/,"")),o=Object.assign({},t);return Object.keys(o).forEach(l=>{typeof t[l]>"u"||(a.indexOf(l)>=0?ws(t[l])?(r[l]={},i[l]={},ca(r[l],t[l]),ca(i[l],t[l])):(r[l]=t[l],i[l]=t[l]):l.search(/on[A-Z]/)===0&&typeof t[l]=="function"?e?n[`${l[2].toLowerCase()}${l.substr(3)}`]=t[l]:r.on[`${l[2].toLowerCase()}${l.substr(3)}`]=t[l]:s[l]=t[l])}),["navigation","pagination","scrollbar"].forEach(l=>{r[l]===!0&&(r[l]={}),r[l]===!1&&delete r[l]}),{params:r,passedParams:i,rest:s,events:n}}function LD(t,e){let{el:r,nextEl:n,prevEl:i,paginationEl:s,scrollbarEl:a,swiper:o}=t;tT(e)&&n&&i&&(o.params.navigation.nextEl=n,o.originalParams.navigation.nextEl=n,o.params.navigation.prevEl=i,o.originalParams.navigation.prevEl=i),rT(e)&&s&&(o.params.pagination.el=s,o.originalParams.pagination.el=s),nT(e)&&a&&(o.params.scrollbar.el=a,o.originalParams.scrollbar.el=a),o.init(r)}function AD(t,e,r,n,i){const s=[];if(!e)return s;const a=l=>{s.indexOf(l)<0&&s.push(l)};if(r&&n){const l=n.map(i),u=r.map(i);l.join("")!==u.join("")&&a("children"),n.length!==r.length&&a("children")}return eT.filter(l=>l[0]==="_").map(l=>l.replace(/_/,"")).forEach(l=>{if(l in t&&l in e)if(ws(t[l])&&ws(e[l])){const u=Object.keys(t[l]),c=Object.keys(e[l]);u.length!==c.length?a(l):(u.forEach(d=>{t[l][d]!==e[l][d]&&a(l)}),c.forEach(d=>{t[l][d]!==e[l][d]&&a(l)}))}else t[l]!==e[l]&&a(l)}),s}const _D=t=>{!t||t.destroyed||!t.params.virtual||t.params.virtual&&!t.params.virtual.enabled||(t.updateSlides(),t.updateProgress(),t.updateSlidesClasses(),t.parallax&&t.params.parallax&&t.params.parallax.enabled&&t.parallax.setTranslate())};function Oc(){return Oc=Object.assign?Object.assign.bind():function(t){for(var e=1;e{sT(r)?e.push(r):r.props&&r.props.children&&aT(r.props.children).forEach(n=>e.push(n))}),e}function CD(t){const e=[],r={"container-start":[],"container-end":[],"wrapper-start":[],"wrapper-end":[]};return ne.Children.toArray(t).forEach(n=>{if(sT(n))e.push(n);else if(n.props&&n.props.slot&&r[n.props.slot])r[n.props.slot].push(n);else if(n.props&&n.props.children){const i=aT(n.props.children);i.length>0?i.forEach(s=>e.push(s)):r["container-end"].push(n)}else r["container-end"].push(n)}),{slides:e,slots:r}}function RD(t,e,r){if(!r)return null;const n=c=>{let d=c;return c<0?d=e.length+c:d>=e.length&&(d=d-e.length),d},i=t.isHorizontal()?{[t.rtlTranslate?"right":"left"]:`${r.offset}px`}:{top:`${r.offset}px`},{from:s,to:a}=r,o=t.params.loop?-e.length:0,l=t.params.loop?e.length*2:e.length,u=[];for(let c=o;c=s&&c<=a&&u.push(e[n(c)]);return u.map((c,d)=>ne.cloneElement(c,{swiper:t,style:i,key:c.props.virtualIndex||c.key||`slide-${d}`}))}function _o(t,e){return typeof window>"u"?L.useEffect(t,e):L.useLayoutEffect(t,e)}const av=L.createContext(null),ID=L.createContext(null),oT=L.forwardRef(function(t,e){let{className:r,tag:n="div",wrapperTag:i="div",children:s,onSwiper:a,...o}=t===void 0?{}:t,l=!1;const[u,c]=L.useState("swiper"),[d,f]=L.useState(null),[m,h]=L.useState(!1),p=L.useRef(!1),v=L.useRef(null),g=L.useRef(null),y=L.useRef(null),x=L.useRef(null),S=L.useRef(null),T=L.useRef(null),C=L.useRef(null),_=L.useRef(null),{params:b,passedParams:I,rest:A,events:k}=bD(o),{slides:O,slots:P}=CD(s),G=()=>{h(!m)};Object.assign(b.on,{_containerClasses(F,j){c(j)}});const K=()=>{Object.assign(b.on,k),l=!0;const F={...b};if(delete F.wrapperClass,g.current=new bm(F),g.current.virtual&&g.current.params.virtual.enabled){g.current.virtual.slides=O;const j={cache:!1,slides:O,renderExternal:f,renderExternalUpdate:!1};ca(g.current.params.virtual,j),ca(g.current.originalParams.virtual,j)}};v.current||K(),g.current&&g.current.on("_beforeBreakpoint",G);const H=()=>{l||!k||!g.current||Object.keys(k).forEach(F=>{g.current.on(F,k[F])})},se=()=>{!k||!g.current||Object.keys(k).forEach(F=>{g.current.off(F,k[F])})};L.useEffect(()=>()=>{g.current&&g.current.off("_beforeBreakpoint",G)}),L.useEffect(()=>{!p.current&&g.current&&(g.current.emitSlidesClasses(),p.current=!0)}),_o(()=>{if(e&&(e.current=v.current),!!v.current)return g.current.destroyed&&K(),LD({el:v.current,nextEl:S.current,prevEl:T.current,paginationEl:C.current,scrollbarEl:_.current,swiper:g.current},b),a&&!g.current.destroyed&&a(g.current),()=>{g.current&&!g.current.destroyed&&g.current.destroy(!0,!1)}},[]),_o(()=>{H();const F=AD(I,y.current,O,x.current,j=>j.key);return y.current=I,x.current=O,F.length&&g.current&&!g.current.destroyed&&wD({swiper:g.current,slides:O,passedParams:I,changedParams:F,nextEl:S.current,prevEl:T.current,scrollbarEl:_.current,paginationEl:C.current}),()=>{se()}}),_o(()=>{_D(g.current)},[d]);function W(){return b.virtual?RD(g.current,O,d):O.map((F,j)=>ne.cloneElement(F,{swiper:g.current,swiperSlideIndex:j}))}return ne.createElement(n,Oc({ref:v,className:iT(`${u}${r?` ${r}`:""}`)},A),ne.createElement(ID.Provider,{value:g.current},P["container-start"],ne.createElement(i,{className:TD(b.wrapperClass)},P["wrapper-start"],W(),P["wrapper-end"]),tT(b)&&ne.createElement(ne.Fragment,null,ne.createElement("div",{ref:T,className:"swiper-button-prev"}),ne.createElement("div",{ref:S,className:"swiper-button-next"})),nT(b)&&ne.createElement("div",{ref:_,className:"swiper-scrollbar"}),rT(b)&&ne.createElement("div",{ref:C,className:"swiper-pagination"}),P["container-end"]))});oT.displayName="Swiper";const lT=L.forwardRef(function(t,e){let{tag:r="div",children:n,className:i="",swiper:s,zoom:a,lazy:o,virtualIndex:l,swiperSlideIndex:u,...c}=t===void 0?{}:t;const d=L.useRef(null),[f,m]=L.useState("swiper-slide"),[h,p]=L.useState(!1);function v(S,T,C){T===d.current&&m(C)}_o(()=>{if(typeof u<"u"&&(d.current.swiperSlideIndex=u),e&&(e.current=d.current),!(!d.current||!s)){if(s.destroyed){f!=="swiper-slide"&&m("swiper-slide");return}return s.on("_slideClass",v),()=>{s&&s.off("_slideClass",v)}}}),_o(()=>{s&&d.current&&!s.destroyed&&m(s.getSlideClasses(d.current))},[s]);const g={isActive:f.indexOf("swiper-slide-active")>=0,isVisible:f.indexOf("swiper-slide-visible")>=0,isPrev:f.indexOf("swiper-slide-prev")>=0,isNext:f.indexOf("swiper-slide-next")>=0},y=()=>typeof n=="function"?n(g):n,x=()=>{p(!0)};return ne.createElement(r,Oc({ref:d,className:iT(`${f}${i?` ${i}`:""}`),"data-swiper-slide-index":l,onLoad:x},c),a&&ne.createElement(av.Provider,{value:g},ne.createElement("div",{className:"swiper-zoom-container","data-swiper-zoom":typeof a=="number"?a:void 0},y(),o&&!h&&ne.createElement("div",{className:"swiper-lazy-preloader"}))),!a&&ne.createElement(av.Provider,{value:g},y(),o&&!h&&ne.createElement("div",{className:"swiper-lazy-preloader"})))});lT.displayName="SwiperSlide";const kD=({media:t})=>{const[e,r]=L.useState(null),[n,i]=L.useState(!1),s=L.useRef(!1),a=Br(),o=()=>{s.current=!0;const c=setTimeout(()=>{s.current&&i(!0)},500);r(c)},l=()=>{s.current=!1,e&&clearTimeout(e),i(!1)},u=()=>{a(`/watch/${t.type}/${t.id}`)};return E.jsxs("article",{onMouseEnter:o,onMouseLeave:l,onClick:u,children:[E.jsx("img",{src:`${t.images.banner}`,alt:t.serie_title||t.title,className:"w-auto max-w-none h-48 object-cover rounded-md select-none"}),t.images.logo?E.jsx("img",{src:`${t.images.logo}`,alt:t.serie_title||t.title,className:"absolute bottom-1 left-1 w-1/2 h-12 object-contain rounded-md select-none"}):E.jsx("h3",{className:"absolute bottom-1 left-1 bg-black bg-opacity-50 text-white text-xs p-1 rounded-md select-none",children:t.serie_title||t.title}),E.jsx("section",{className:`absolute bg-neutral-800 bg-opacity-50 w-full z-10 bottom-0 pointer-events-none ${n?"opacity-100":"opacity-0"} transition-opacity duration-300`,children:E.jsxs("section",{className:"w-full h-full bg-black bg-opacity-75 p-4 flex flex-col gap-2",children:[E.jsx("h3",{children:t.serie_title||t.title}),E.jsxs("section",{className:"flex flex-col gap-1",children:[E.jsxs("h2",{children:["Genres: ",t.genres.map((c,d)=>E.jsxs(E.Fragment,{children:[E.jsx("span",{children:c},d),d!==t.genres.length-1&&E.jsx("span",{children:" • "})]}))]}),E.jsxs("h2",{children:["Note: ",(+t.note).toFixed(2),"/10"]}),E.jsxs("h2",{children:["Durée: ",t.duration,t.type==="serie"?" episodes":""]})]})]})})]})};function DD(t,e,r,n){return t.params.createElements&&Object.keys(n).forEach(i=>{if(!r[i]&&r.auto===!0){let s=In(t.el,`.${n[i]}`)[0];s||(s=Pc("div",n[i]),s.className=n[i],t.el.append(s)),r[i]=s,e[i]=s}}),r}function PD(t){let{swiper:e,extendParams:r,on:n,emit:i}=t;r({navigation:{nextEl:null,prevEl:null,hideOnClick:!1,disabledClass:"swiper-button-disabled",hiddenClass:"swiper-button-hidden",lockClass:"swiper-button-lock",navigationDisabledClass:"swiper-navigation-disabled"}}),e.navigation={nextEl:null,prevEl:null};function s(h){let p;return h&&typeof h=="string"&&e.isElement&&(p=e.el.querySelector(h),p)?p:(h&&(typeof h=="string"&&(p=[...document.querySelectorAll(h)]),e.params.uniqueNavElements&&typeof h=="string"&&p&&p.length>1&&e.el.querySelectorAll(h).length===1?p=e.el.querySelector(h):p&&p.length===1&&(p=p[0])),h&&!p?h:p)}function a(h,p){const v=e.params.navigation;h=Hn(h),h.forEach(g=>{g&&(g.classList[p?"add":"remove"](...v.disabledClass.split(" ")),g.tagName==="BUTTON"&&(g.disabled=p),e.params.watchOverflow&&e.enabled&&g.classList[e.isLocked?"add":"remove"](v.lockClass))})}function o(){const{nextEl:h,prevEl:p}=e.navigation;if(e.params.loop){a(p,!1),a(h,!1);return}a(p,e.isBeginning&&!e.params.rewind),a(h,e.isEnd&&!e.params.rewind)}function l(h){h.preventDefault(),!(e.isBeginning&&!e.params.loop&&!e.params.rewind)&&(e.slidePrev(),i("navigationPrev"))}function u(h){h.preventDefault(),!(e.isEnd&&!e.params.loop&&!e.params.rewind)&&(e.slideNext(),i("navigationNext"))}function c(){const h=e.params.navigation;if(e.params.navigation=DD(e,e.originalParams.navigation,e.params.navigation,{nextEl:"swiper-button-next",prevEl:"swiper-button-prev"}),!(h.nextEl||h.prevEl))return;let p=s(h.nextEl),v=s(h.prevEl);Object.assign(e.navigation,{nextEl:p,prevEl:v}),p=Hn(p),v=Hn(v);const g=(y,x)=>{y&&y.addEventListener("click",x==="next"?u:l),!e.enabled&&y&&y.classList.add(...h.lockClass.split(" "))};p.forEach(y=>g(y,"next")),v.forEach(y=>g(y,"prev"))}function d(){let{nextEl:h,prevEl:p}=e.navigation;h=Hn(h),p=Hn(p);const v=(g,y)=>{g.removeEventListener("click",y==="next"?u:l),g.classList.remove(...e.params.navigation.disabledClass.split(" "))};h.forEach(g=>v(g,"next")),p.forEach(g=>v(g,"prev"))}n("init",()=>{e.params.navigation.enabled===!1?m():(c(),o())}),n("toEdge fromEdge lock unlock",()=>{o()}),n("destroy",()=>{d()}),n("enable disable",()=>{let{nextEl:h,prevEl:p}=e.navigation;if(h=Hn(h),p=Hn(p),e.enabled){o();return}[...h,...p].filter(v=>!!v).forEach(v=>v.classList.add(e.params.navigation.lockClass))}),n("click",(h,p)=>{let{nextEl:v,prevEl:g}=e.navigation;v=Hn(v),g=Hn(g);const y=p.target;let x=g.includes(y)||v.includes(y);if(e.isElement&&!x){const S=p.path||p.composedPath&&p.composedPath();S&&(x=S.find(T=>v.includes(T)||g.includes(T)))}if(e.params.navigation.hideOnClick&&!x){if(e.pagination&&e.params.pagination&&e.params.pagination.clickable&&(e.pagination.el===y||e.pagination.el.contains(y)))return;let S;v.length?S=v[0].classList.contains(e.params.navigation.hiddenClass):g.length&&(S=g[0].classList.contains(e.params.navigation.hiddenClass)),i(S===!0?"navigationShow":"navigationHide"),[...v,...g].filter(T=>!!T).forEach(T=>T.classList.toggle(e.params.navigation.hiddenClass))}});const f=()=>{e.el.classList.remove(...e.params.navigation.navigationDisabledClass.split(" ")),c(),o()},m=()=>{e.el.classList.add(...e.params.navigation.navigationDisabledClass.split(" ")),d()};Object.assign(e.navigation,{enable:f,disable:m,update:o,init:c,destroy:d})}const Ca=({medias:t,index:e})=>{const[r,n]=L.useState(!1),[i,s]=L.useState(!1),a=L.useRef(null),o=()=>{s(!0)},l=()=>{n(!0)},u=()=>{n(!1)};return E.jsxs("div",{className:"relative w-full",onMouseEnter:l,onMouseLeave:u,children:[E.jsx(oT,{modules:[PD],spaceBetween:10,slidesPerView:"auto",direction:"horizontal",freeMode:!0,onSlideChange:o,className:"!overflow-visible !w-full",ref:a,children:t.map((c,d)=>E.jsx(E.Fragment,{children:c?E.jsx(lT,{className:"!w-fit",children:E.jsx(kD,{media:c})},d):null}))}),i&&E.jsxs(E.Fragment,{children:[E.jsx("button",{style:{zIndex:e+1},className:`absolute left-0 top-1/2 transform -translate-y-1/2 ${r?"opacity-100":"opacity-0"} transition-opacity duration-300`,onClick:()=>{var c,d;return(d=(c=a.current)==null?void 0:c.swiper)==null?void 0:d.slidePrev()},children:"❮ "}),E.jsx("button",{style:{zIndex:e+1},className:`absolute right-0 top-1/2 transform -translate-y-1/2 ${r?"opacity-100":"opacity-0"} transition-opacity duration-300`,onClick:()=>{var c,d;return(d=(c=a.current)==null?void 0:c.swiper)==null?void 0:d.slideNext()},children:"❯ "})]})]})},wl=L.createContext({searchTerm:"",setSearchTerm:t=>{}}),OD=({children:t})=>{const[e,r]=L.useState("");return E.jsx(wl.Provider,{value:{searchTerm:e,setSearchTerm:r},children:t})};function MD(){const[t,e]=L.useState(""),[r,n]=L.useState(!0),[i,s]=L.useState(!0),{searchTerm:a}=L.useContext(wl),{data:o,loading:l}=ur(t),{data:u,loading:c,interupt:d}=ur("/api/medias/home");L.useEffect(()=>{c||setTimeout(()=>{n(!1)},500)},[c]),L.useEffect(()=>{l?s(!0):setTimeout(()=>{s(!1)},500)},[l]),L.useEffect(()=>{if(a===""||a.length<3){e("");return}e(`/api/medias/search/home?search=${a}`)},[a]),L.useEffect(()=>{const p=new URLSearchParams(window.location.search).get("query");p&&(d(),e(`/api/medias/search/home?search=${p}`))},[]);const f=["continue_watching","latest","recently_added","top_rated","best_of_year","family","comedy","animated","action","thriller","horror","drama","western"],m={continue_watching:"Continue Watching",latest:"Latest",recently_added:"Recently Added",top_rated:"Top Rated",best_of_year:"Best of the Year",family:"Family",comedy:"Comedy",animated:"Animated",action:"Action",thriller:"Thriller",horror:"Horror",drama:"Drama",western:"Western"};return E.jsxs(E.Fragment,{children:[E.jsx(_s,{className:"h-screen top-0 fixed bg-[--black] w-screen transition-all duration-300 pointer-events-none z-50 "+(r||i?"opacity-100":"opacity-0")}),!o&&u&&u.code===201&&E.jsxs("section",{className:`flex flex-col gap-8 pb-8 ${r||i?"overflow-hidden":""}`,children:[E.jsx(_a,{media:u.data.main_media}),E.jsx("section",{className:"flex flex-col gap-8 pl-4 overflow-hidden",children:f.map((h,p)=>{var v;return((v=u.data[h])==null?void 0:v.length)>0&&E.jsxs("section",{className:"flex flex-col gap-4 ",style:{zIndex:f.length-p},children:[E.jsx("h3",{className:"text-3xl font-bold",children:m[h]}),E.jsx(Ca,{medias:u.data[h],index:f.length-p})]},h)})})]}),o&&o.data.main_media&&o.code===201&&E.jsxs("section",{className:`flex flex-col gap-8 pb-8 ${r||i?"overflow-hidden":""}`,children:[E.jsx(_a,{media:o.data.main_media}),E.jsx("section",{className:"flex flex-col gap-8 pl-4 overflow-hidden",children:E.jsxs("section",{className:"flex flex-col gap-4",children:[E.jsx("h3",{className:"text-3xl font-bold",children:"Results"}),E.jsx(Ca,{medias:o.data.medias,index:0})]})})]}),(o&&o.code!==201||u&&u.code!==201)&&E.jsxs("section",{className:"h-screen flex justify-center items-center",children:[E.jsx("h1",{className:"text-4xl font-bold",children:"No data found"}),E.jsx("p",{className:"text-lg",children:"Please try again later"}),E.jsx("p",{className:"text-lg",children:"If you're the admin, ensure you have a library, and that you've scanned it."})]})]})}function ND(){var c;const[t,e]=L.useState(""),[r,n]=L.useState(!0),{searchTerm:i}=L.useContext(wl),{data:s}=ur(t),{data:a,interupt:o}=ur("/api/medias/movies");L.useEffect(()=>{(a||s)&&setTimeout(()=>{n(!1)},500)},[a]),L.useEffect(()=>{if(i===""||i.length<3){e("");return}e(`/api/medias/search/movies?search=${i}`)},[i]),L.useEffect(()=>{const f=new URLSearchParams(window.location.search).get("query");f&&(o(),e(`/api/medias/search/movies?search=${f}`))},[]);const l=["continue_watching","latest","recently_added","top_rated","best_of_year","family","comedy","animated","action","thriller","horror","drama","western"],u={continue_watching:"Continue Watching",latest:"Latest",recently_added:"Recently Added",top_rated:"Top Rated",best_of_year:"Best of the Year",family:"Family",comedy:"Comedy",animated:"Animated",action:"Action",thriller:"Thriller",horror:"Horror",drama:"Drama",western:"Western"};return E.jsxs(E.Fragment,{children:[E.jsx(_s,{className:"h-screen top-0 fixed bg-[--black] w-screen transition-all duration-300 pointer-events-none z-50 "+(r?"opacity-100":"opacity-0")}),!s&&a&&a.data&&E.jsxs("section",{className:`flex flex-col gap-8 pb-8 ${r?"overflow-hidden":""}`,children:[E.jsx(_a,{media:a.data.main_media}),E.jsx("section",{className:"flex flex-col gap-8 pl-4 overflow-hidden",children:l.map((d,f)=>{var m;return((m=a.data[d])==null?void 0:m.length)>0&&E.jsxs("section",{className:"flex flex-col gap-4 ",style:{zIndex:l.length-f},children:[E.jsx("h3",{className:"text-3xl font-bold",children:u[d]}),E.jsx(Ca,{medias:a.data[d],index:l.length-f})]},d)})})]}),s&&E.jsxs("section",{className:`flex flex-col gap-8 pb-8 ${r?"overflow-hidden":""}`,children:[E.jsx(_a,{media:(c=s.data)==null?void 0:c.main_media}),E.jsx("section",{className:"flex flex-col gap-8 pl-4 overflow-hidden",children:E.jsxs("section",{className:"flex flex-col gap-4",children:[E.jsx("h3",{className:"text-3xl font-bold",children:"Results"}),E.jsx(Ca,{medias:s.data.medias,index:0})]})})]}),(s&&s.code!==201||a&&a.code!==201)&&E.jsxs("section",{className:"h-screen flex justify-center items-center",children:[E.jsx("h1",{className:"text-4xl font-bold",children:"No data found"}),E.jsx("p",{className:"text-lg",children:"Please try again later"}),E.jsx("p",{className:"text-lg",children:"If you're the admin, ensure you have a library, and that you've scanned it."})]})]})}function FD(){var d,f,m;const[t,e]=L.useState(""),[r,n]=L.useState(!0),{searchTerm:i}=L.useContext(wl),{data:s}=ur(t),{data:a,loading:o,interupt:l}=ur("/api/medias/shows");L.useEffect(()=>{o||setTimeout(()=>{n(!1)},500)},[o]),L.useEffect(()=>{if(i===""||i.length<3){e("");return}e(`/api/medias/search/shows?search=${i}`)},[i]),L.useEffect(()=>{const p=new URLSearchParams(window.location.search).get("query");p&&(l(),e(`/api/medias/search/shows?search=${p}`))},[]);const u=["continue_watching","latest","recently_added","top_rated","best_of_year","family","comedy","animated","action","thriller","horror","drama","western"],c={continue_watching:"Continue Watching",latest:"Latest",recently_added:"Recently Added",top_rated:"Top Rated",best_of_year:"Best of the Year",family:"Family",comedy:"Comedy",animated:"Animated",action:"Action",thriller:"Thriller",horror:"Horror",drama:"Drama",western:"Western"};return E.jsxs(E.Fragment,{children:[E.jsx(_s,{className:"h-screen top-0 fixed bg-[--black] w-screen transition-all duration-300 pointer-events-none z-50 "+(r?"opacity-100":"opacity-0")}),!s&&a&&a.data&&E.jsxs("section",{className:`flex flex-col gap-8 pb-8 ${r?"overflow-hidden":""}`,children:[E.jsx(_a,{media:(d=a.data)==null?void 0:d.main_media}),E.jsx("section",{className:"flex flex-col gap-8 pl-4 overflow-hidden",children:u.map((h,p)=>{var v;return((v=a.data[h])==null?void 0:v.length)>0&&E.jsxs("section",{className:"flex flex-col gap-4 ",style:{zIndex:u.length-p},children:[E.jsx("h3",{className:"text-3xl font-bold",children:c[h]}),E.jsx(Ca,{medias:a.data[h],index:u.length-p})]},h)})})]}),s&&E.jsxs("section",{className:`flex flex-col gap-8 pb-8 ${r?"overflow-hidden":""}`,children:[E.jsx(_a,{media:(f=s.data)==null?void 0:f.main_media}),E.jsx("section",{className:"flex flex-col gap-8 pl-4 overflow-hidden",children:E.jsxs("section",{className:"flex flex-col gap-4",children:[E.jsx("h3",{className:"text-3xl font-bold",children:"Results"}),E.jsx(Ca,{medias:(m=s.data)==null?void 0:m.medias,index:0})]})})]}),(s&&s.code!==201||a&&a.code!==201)&&E.jsxs("section",{className:"h-screen flex justify-center items-center",children:[E.jsx("h1",{className:"text-4xl font-bold",children:"No data found"}),E.jsx("p",{className:"text-lg",children:"Please try again later"}),E.jsx("p",{className:"text-lg",children:"If you're the admin, ensure you have a library, and that you've scanned it."})]})]})}function UD(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var uT={exports:{}};(function(t,e){(function(r){var n=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,i=/^(?=([^\/?#]*))\1([^]*)$/,s=/(?:\/|^)\.(?=\/)/g,a=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(l,u,c){if(c=c||{},l=l.trim(),u=u.trim(),!u){if(!c.alwaysNormalize)return l;var d=o.parseURL(l);if(!d)throw new Error("Error trying to parse base URL.");return d.path=o.normalizePath(d.path),o.buildURLFromParts(d)}var f=o.parseURL(u);if(!f)throw new Error("Error trying to parse relative URL.");if(f.scheme)return c.alwaysNormalize?(f.path=o.normalizePath(f.path),o.buildURLFromParts(f)):u;var m=o.parseURL(l);if(!m)throw new Error("Error trying to parse base URL.");if(!m.netLoc&&m.path&&m.path[0]!=="/"){var h=i.exec(m.path);m.netLoc=h[1],m.path=h[2]}m.netLoc&&!m.path&&(m.path="/");var p={scheme:m.scheme,netLoc:f.netLoc,path:null,params:f.params,query:f.query,fragment:f.fragment};if(!f.netLoc&&(p.netLoc=m.netLoc,f.path[0]!=="/"))if(!f.path)p.path=m.path,f.params||(p.params=m.params,f.query||(p.query=m.query));else{var v=m.path,g=v.substring(0,v.lastIndexOf("/")+1)+f.path;p.path=o.normalizePath(g)}return p.path===null&&(p.path=c.alwaysNormalize?o.normalizePath(f.path):f.path),o.buildURLFromParts(p)},parseURL:function(l){var u=n.exec(l);return u?{scheme:u[1]||"",netLoc:u[2]||"",path:u[3]||"",params:u[4]||"",query:u[5]||"",fragment:u[6]||""}:null},normalizePath:function(l){for(l=l.split("").reverse().join("").replace(s,"");l.length!==(l=l.replace(a,"")).length;);return l.split("").reverse().join("")},buildURLFromParts:function(l){return l.scheme+l.netLoc+l.path+l.params+l.query+l.fragment}};t.exports=o})()})(uT);var Lm=uT.exports;function ov(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function jt(t){for(var e=1;e`):es}function HD(t,...e){e.forEach(function(r){Co[r]=t[r]?t[r].bind(t):zD(r)})}function WD(t,e){if(typeof console=="object"&&t===!0||typeof t=="object"){HD(t,"debug","log","info","warn","error");try{Co.log(`Debug logs enabled for "${e}" in hls.js version 1.5.15`)}catch{Co=Wh}}else Co=Wh}const U=Co,KD=/^(\d+)x(\d+)$/,lv=/(.+?)=(".*?"|.*?)(?:,|$)/g;class gt{constructor(e){typeof e=="string"&&(e=gt.parseAttrList(e)),It(this,e)}get clientAttrs(){return Object.keys(this).filter(e=>e.substring(0,2)==="X-")}decimalInteger(e){const r=parseInt(this[e],10);return r>Number.MAX_SAFE_INTEGER?1/0:r}hexadecimalInteger(e){if(this[e]){let r=(this[e]||"0x").slice(2);r=(r.length&1?"0":"")+r;const n=new Uint8Array(r.length/2);for(let i=0;iNumber.MAX_SAFE_INTEGER?1/0:r}decimalFloatingPoint(e){return parseFloat(this[e])}optionalFloat(e,r){const n=this[e];return n?parseFloat(n):r}enumeratedString(e){return this[e]}bool(e){return this[e]==="YES"}decimalResolution(e){const r=KD.exec(this[e]);if(r!==null)return{width:parseInt(r[1],10),height:parseInt(r[2],10)}}static parseAttrList(e){let r;const n={},i='"';for(lv.lastIndex=0;(r=lv.exec(e))!==null;){let s=r[2];s.indexOf(i)===0&&s.lastIndexOf(i)===s.length-1&&(s=s.slice(1,-1));const a=r[1].trim();n[a]=s}return n}}function YD(t){return t!=="ID"&&t!=="CLASS"&&t!=="START-DATE"&&t!=="DURATION"&&t!=="END-DATE"&&t!=="END-ON-NEXT"}function qD(t){return t==="SCTE35-OUT"||t==="SCTE35-IN"}class cT{constructor(e,r){if(this.attr=void 0,this._startDate=void 0,this._endDate=void 0,this._badValueForSameId=void 0,r){const n=r.attr;for(const i in n)if(Object.prototype.hasOwnProperty.call(e,i)&&e[i]!==n[i]){U.warn(`DATERANGE tag attribute: "${i}" does not match for tags with ID: "${e.ID}"`),this._badValueForSameId=i;break}e=It(new gt({}),n,e)}if(this.attr=e,this._startDate=new Date(e["START-DATE"]),"END-DATE"in this.attr){const n=new Date(this.attr["END-DATE"]);pe(n.getTime())&&(this._endDate=n)}}get id(){return this.attr.ID}get class(){return this.attr.CLASS}get startDate(){return this._startDate}get endDate(){if(this._endDate)return this._endDate;const e=this.duration;return e!==null?new Date(this._startDate.getTime()+e*1e3):null}get duration(){if("DURATION"in this.attr){const e=this.attr.decimalFloatingPoint("DURATION");if(pe(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 isValid(){return!!this.id&&!this._badValueForSameId&&pe(this.startDate.getTime())&&(this.duration===null||this.duration>=0)&&(!this.endOnNext||!!this.class)}}class Td{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}}}var Je={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class dT{constructor(e){this._byteRange=null,this._url=null,this.baseurl=void 0,this.relurl=void 0,this.elementaryStreams={[Je.AUDIO]:null,[Je.VIDEO]:null,[Je.AUDIOVIDEO]:null},this.baseurl=e}setByteRange(e,r){const n=e.split("@",2);let i;n.length===1?i=(r==null?void 0:r.byteRangeEndOffset)||0:i=parseInt(n[1]),this._byteRange=[i,parseInt(n[0])+i]}get byteRange(){return this._byteRange?this._byteRange:[]}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get url(){return!this._url&&this.baseurl&&this.relurl&&(this._url=Lm.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(e){this._url=e}}class yf extends dT{constructor(e,r){super(r),this._decryptdata=null,this.rawProgramDateTime=null,this.programDateTime=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.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.stats=new Td,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 decryptdata(){const{levelkeys:e}=this;if(!e&&!this._decryptdata)return null;if(!this._decryptdata&&this.levelkeys&&!this.levelkeys.NONE){const r=this.levelkeys.identity;if(r)this._decryptdata=r.getDecryptData(this.sn);else{const n=Object.keys(this.levelkeys);if(n.length===1)return this._decryptdata=this.levelkeys[n[0]].getDecryptData(this.sn)}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null||!pe(this.programDateTime))return null;const e=pe(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){const r=Object.keys(this.levelkeys),n=r.length;if(n>1||n===1&&this.levelkeys[r[0]].encrypted)return!0}return!1}setKeyFormat(e){if(this.levelkeys){const r=this.levelkeys[e];r&&!this._decryptdata&&(this._decryptdata=r.getDecryptData(this.sn))}}abortRequests(){var e,r;(e=this.loader)==null||e.abort(),(r=this.keyLoader)==null||r.abort()}setElementaryStreamInfo(e,r,n,i,s,a=!1){const{elementaryStreams:o}=this,l=o[e];if(!l){o[e]={startPTS:r,endPTS:n,startDTS:i,endDTS:s,partial:a};return}l.startPTS=Math.min(l.startPTS,r),l.endPTS=Math.max(l.endPTS,n),l.startDTS=Math.min(l.startDTS,i),l.endDTS=Math.max(l.endDTS,s)}clearElementaryStreamInfo(){const{elementaryStreams:e}=this;e[Je.AUDIO]=null,e[Je.VIDEO]=null,e[Je.AUDIOVIDEO]=null}}class XD extends dT{constructor(e,r,n,i,s){super(n),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.stats=new Td,this.duration=e.decimalFloatingPoint("DURATION"),this.gap=e.bool("GAP"),this.independent=e.bool("INDEPENDENT"),this.relurl=e.enumeratedString("URI"),this.fragment=r,this.index=i;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)}}const ZD=10;class QD{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.live=!0,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.availabilityDelay=void 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.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=e}reloaded(e){if(!e){this.advanced=!0,this.updated=!0;return}const r=this.lastPartSn-e.lastPartSn,n=this.lastPartIndex-e.lastPartIndex;this.updated=this.endSN!==e.endSN||!!n||!!r||!this.live,this.advanced=this.endSN>e.endSN||r>0||r===0&&n>0,this.updated||this.advanced?this.misses=Math.floor(e.misses*.6):this.misses=e.misses+1,this.availabilityDelay=e.availabilityDelay}get hasProgramDateTime(){return this.fragments.length?pe(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||ZD}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(){var e;return(e=this.fragments)!=null&&e.length?this.fragments[this.fragments.length-1].end: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 lastPartSn(){var e;return(e=this.partList)!=null&&e.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}}function Am(t){return Uint8Array.from(atob(t),e=>e.charCodeAt(0))}function JD(t){const e=Kh(t).subarray(0,16),r=new Uint8Array(16);return r.set(e,16-e.length),r}function eP(t){const e=function(n,i,s){const a=n[i];n[i]=n[s],n[s]=a};e(t,0,3),e(t,1,2),e(t,4,5),e(t,6,7)}function tP(t){const e=t.split(":");let r=null;if(e[0]==="data"&&e.length===2){const n=e[1].split(";"),i=n[n.length-1].split(",");if(i.length===2){const s=i[0]==="base64",a=i[1];s?(n.splice(-1,1),r=Am(a)):r=JD(a)}}return r}function Kh(t){return Uint8Array.from(unescape(encodeURIComponent(t)),e=>e.charCodeAt(0))}const Ra=typeof self<"u"?self:void 0;var ot={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},yr={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function uv(t){switch(t){case yr.FAIRPLAY:return ot.FAIRPLAY;case yr.PLAYREADY:return ot.PLAYREADY;case yr.WIDEVINE:return ot.WIDEVINE;case yr.CLEARKEY:return ot.CLEARKEY}}var ho={CENC:"1077efecc0b24d02ace33c1e52e2fb4b",CLEARKEY:"e2719d58a985b3c9781ab030af78d30e",FAIRPLAY:"94ce86fb07ff4f43adb893d2fa968ca2",PLAYREADY:"9a04f07998404286ab92e65be0885f95",WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function cv(t){if(t===ho.WIDEVINE)return ot.WIDEVINE;if(t===ho.PLAYREADY)return ot.PLAYREADY;if(t===ho.CENC||t===ho.CLEARKEY)return ot.CLEARKEY}function dv(t){switch(t){case ot.FAIRPLAY:return yr.FAIRPLAY;case ot.PLAYREADY:return yr.PLAYREADY;case ot.WIDEVINE:return yr.WIDEVINE;case ot.CLEARKEY:return yr.CLEARKEY}}function xf(t){const{drmSystems:e,widevineLicenseUrl:r}=t,n=e?[ot.FAIRPLAY,ot.WIDEVINE,ot.PLAYREADY,ot.CLEARKEY].filter(i=>!!e[i]):[];return!n[ot.WIDEVINE]&&r&&n.push(ot.WIDEVINE),n}const fT=function(t){return Ra!=null&&(t=Ra.navigator)!=null&&t.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function rP(t,e,r,n){let i;switch(t){case ot.FAIRPLAY:i=["cenc","sinf"];break;case ot.WIDEVINE:case ot.PLAYREADY:i=["cenc"];break;case ot.CLEARKEY:i=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${t}`)}return nP(i,e,r,n)}function nP(t,e,r,n){return[{initDataTypes:t,persistentState:n.persistentState||"optional",distinctiveIdentifier:n.distinctiveIdentifier||"optional",sessionTypes:n.sessionTypes||[n.sessionType||"temporary"],audioCapabilities:e.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 hs(t,e,r){return Uint8Array.prototype.slice?t.slice(e,r):new Uint8Array(Array.prototype.slice.call(t,e,r))}const _m=(t,e)=>e+10<=t.length&&t[e]===73&&t[e+1]===68&&t[e+2]===51&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,hT=(t,e)=>e+10<=t.length&&t[e]===51&&t[e+1]===68&&t[e+2]===73&&t[e+3]<255&&t[e+4]<255&&t[e+6]<128&&t[e+7]<128&&t[e+8]<128&&t[e+9]<128,fl=(t,e)=>{const r=e;let n=0;for(;_m(t,e);){n+=10;const i=wd(t,e+6);n+=i,hT(t,e+10)&&(n+=10),e+=n}if(n>0)return t.subarray(r,r+n)},wd=(t,e)=>{let r=0;return r=(t[e]&127)<<21,r|=(t[e+1]&127)<<14,r|=(t[e+2]&127)<<7,r|=t[e+3]&127,r},iP=(t,e)=>_m(t,e)&&wd(t,e+6)+10<=t.length-e,Cm=t=>{const e=mT(t);for(let r=0;rt&&t.key==="PRIV"&&t.info==="com.apple.streaming.transportStreamTimestamp",sP=t=>{const e=String.fromCharCode(t[0],t[1],t[2],t[3]),r=wd(t,4),n=10;return{type:e,size:r,data:t.subarray(n,n+r)}},mT=t=>{let e=0;const r=[];for(;_m(t,e);){const n=wd(t,e+6);e+=10;const i=e+n;for(;e+8t.type==="PRIV"?oP(t):t.type[0]==="W"?uP(t):lP(t),oP=t=>{if(t.size<2)return;const e=Nn(t.data,!0),r=new Uint8Array(t.data.subarray(e.length+1));return{key:t.type,info:e,data:r.buffer}},lP=t=>{if(t.size<2)return;if(t.type==="TXXX"){let r=1;const n=Nn(t.data.subarray(r),!0);r+=n.length+1;const i=Nn(t.data.subarray(r));return{key:t.type,info:n,data:i}}const e=Nn(t.data.subarray(1));return{key:t.type,data:e}},uP=t=>{if(t.type==="WXXX"){if(t.size<2)return;let r=1;const n=Nn(t.data.subarray(r),!0);r+=n.length+1;const i=Nn(t.data.subarray(r));return{key:t.type,info:n,data:i}}const e=Nn(t.data);return{key:t.type,data:e}},cP=t=>{if(t.data.byteLength===8){const e=new Uint8Array(t.data),r=e[3]&1;let n=(e[4]<<23)+(e[5]<<15)+(e[6]<<7)+e[7];return n/=45,r&&(n+=4772185884e-2),Math.round(n)}},Nn=(t,e=!1)=>{const r=dP();if(r){const u=r.decode(t);if(e){const c=u.indexOf("\0");return c!==-1?u.substring(0,c):u}return u.replace(/\0/g,"")}const n=t.length;let i,s,a,o="",l=0;for(;l>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:o+=String.fromCharCode(i);break;case 12:case 13:s=t[l++],o+=String.fromCharCode((i&31)<<6|s&63);break;case 14:s=t[l++],a=t[l++],o+=String.fromCharCode((i&15)<<12|(s&63)<<6|(a&63)<<0);break}}return o};let Sf;function dP(){if(!navigator.userAgent.includes("PlayStation 4"))return!Sf&&typeof self.TextDecoder<"u"&&(Sf=new self.TextDecoder("utf-8")),Sf}const bn={hexDump:function(t){let e="";for(let r=0;r>24,t[e+1]=r>>16&255,t[e+2]=r>>8&255,t[e+3]=r&255}function hP(t){const e=t.byteLength;for(let r=0;r8&&t[r+4]===109&&t[r+5]===111&&t[r+6]===111&&t[r+7]===102)return!0;r=n>1?r+n:e}return!1}function Oe(t,e){const r=[];if(!e.length)return r;const n=t.byteLength;for(let i=0;i1?i+s:n;if(a===e[0])if(e.length===1)r.push(t.subarray(i+8,o));else{const l=Oe(t.subarray(i+8,o),e.slice(1));l.length&&fP.apply(r,l)}i=o}return r}function pP(t){const e=[],r=t[0];let n=8;const i=Te(t,n);n+=4;let s=0,a=0;r===0?(s=Te(t,n),a=Te(t,n+4),n+=8):(s=fv(t,n),a=fv(t,n+8),n+=16),n+=2;let o=t.length+a;const l=vT(t,n);n+=2;for(let u=0;u>>31===1)return U.warn("SIDX has hierarchical references (not supported)"),null;const h=Te(t,c);c+=4,e.push({referenceSize:f,subsegmentDuration:h,info:{duration:h/i,start:o,end:o+f-1}}),o+=f,c+=4,n=c}return{earliestPresentationTime:s,timescale:i,version:r,referencesCount:l,references:e}}function xT(t){const e=[],r=Oe(t,["moov","trak"]);for(let i=0;i{const s=Te(i,4),a=e[s];a&&(a.default={duration:Te(i,12),flags:Te(i,20)})}),e}function mP(t){const e=t.subarray(8),r=e.subarray(86),n=Dt(e.subarray(4,8));let i=n;const s=n==="enca"||n==="encv";if(s){const o=Oe(e,[n])[0].subarray(n==="enca"?28:78);Oe(o,["sinf"]).forEach(u=>{const c=Oe(u,["schm"])[0];if(c){const d=Dt(c.subarray(4,8));if(d==="cbcs"||d==="cenc"){const f=Oe(u,["frma"])[0];f&&(i=Dt(f))}}})}switch(i){case"avc1":case"avc2":case"avc3":case"avc4":{const a=Oe(r,["avcC"])[0];i+="."+tu(a[1])+tu(a[2])+tu(a[3]);break}case"mp4a":{const a=Oe(e,[n])[0],o=Oe(a.subarray(28),["esds"])[0];if(o&&o.length>12){let l=4;if(o[l++]!==3)break;l=Tf(o,l),l+=2;const u=o[l++];if(u&128&&(l+=2),u&64&&(l+=o[l++]),o[l++]!==4)break;l=Tf(o,l);const c=o[l++];if(c===64)i+="."+tu(c);else break;if(l+=12,o[l++]!==5)break;l=Tf(o,l);const d=o[l++];let f=(d&248)>>3;f===31&&(f+=1+((d&7)<<3)+((o[l]&224)>>5)),i+="."+f}break}case"hvc1":case"hev1":{const a=Oe(r,["hvcC"])[0],o=a[1],l=["","A","B","C"][o>>6],u=o&31,c=Te(a,2),d=(o&32)>>5?"H":"L",f=a[12],m=a.subarray(6,12);i+="."+l+u,i+="."+c.toString(16).toUpperCase(),i+="."+d+f;let h="";for(let p=m.length;p--;){const v=m[p];(v||h)&&(h="."+v.toString(16).toUpperCase()+h)}i+=h;break}case"dvh1":case"dvhe":{const a=Oe(r,["dvcC"])[0],o=a[2]>>1&127,l=a[2]<<5&32|a[3]>>3&31;i+="."+Tn(o)+"."+Tn(l);break}case"vp09":{const a=Oe(r,["vpcC"])[0],o=a[4],l=a[5],u=a[6]>>4&15;i+="."+Tn(o)+"."+Tn(l)+"."+Tn(u);break}case"av01":{const a=Oe(r,["av1C"])[0],o=a[1]>>>5,l=a[1]&31,u=a[2]>>>7?"H":"M",c=(a[2]&64)>>6,d=(a[2]&32)>>5,f=o===2&&c?d?12:10:c?10:8,m=(a[2]&16)>>4,h=(a[2]&8)>>3,p=(a[2]&4)>>2,v=a[2]&3;i+="."+o+"."+Tn(l)+u+"."+Tn(f)+"."+m+"."+h+p+v+"."+Tn(1)+"."+Tn(1)+"."+Tn(1)+"."+0;break}}return{codec:i,encrypted:s}}function Tf(t,e){const r=e+5;for(;t[e++]&128&&e{const a=Oe(i,["mdia","minf","stbl","stsd"])[0].subarray(8);let o=Oe(a,["enca"]);const l=o.length>0;l||(o=Oe(a,["encv"])),o.forEach(u=>{const c=l?u.subarray(28):u.subarray(78);Oe(c,["sinf"]).forEach(f=>{const m=ST(f);if(m){const h=m.subarray(8,24);h.some(p=>p!==0)||(U.log(`[eme] Patching keyId in 'enc${l?"a":"v"}>sinf>>tenc' box: ${bn.hexDump(h)} -> ${bn.hexDump(r)}`),m.set(r,8))}})})}),t}function ST(t){const e=Oe(t,["schm"])[0];if(e){const r=Dt(e.subarray(4,8));if(r==="cbcs"||r==="cenc")return Oe(t,["schi","tenc"])[0]}return null}function vP(t,e){return Oe(e,["moof","traf"]).reduce((r,n)=>{const i=Oe(n,["tfdt"])[0],s=i[0],a=Oe(n,["tfhd"]).reduce((o,l)=>{const u=Te(l,4),c=t[u];if(c){let d=Te(i,4);if(s===1){if(d===Mc)return U.warn("[mp4-demuxer]: Ignoring assumed invalid signed 64-bit track fragment decode time"),o;d*=Mc+1,d+=Te(i,8)}const f=c.timescale||9e4,m=d/f;if(pe(m)&&(o===null||mm+h.info.duration||0,0);o=Math.max(o,f+d.earliestPresentationTime/d.timescale),l=o-a}}if(l&&pe(l))return l}return n||i}function xP(t){const e=Te(t,0);let r=8;e&1&&(r+=4),e&4&&(r+=4);let n=0;const i=Te(t,4);for(let s=0;s{Oe(n,["tfhd"]).forEach(i=>{const s=Te(i,4),a=t[s];if(!a)return;const o=a.timescale||9e4;Oe(n,["tfdt"]).forEach(l=>{const u=l[0],c=r*o;if(c){let d=Te(l,4);if(u===0)d-=c,d=Math.max(d,0),Ef(l,4,d);else{d*=Math.pow(2,32),d+=Te(l,8),d-=c,d=Math.max(d,0);const f=Math.floor(d/(Mc+1)),m=Math.floor(d%(Mc+1));Ef(l,4,f),Ef(l,8,m)}}})})})}function EP(t){const e={valid:null,remainder:null},r=Oe(t,["moof"]);if(r.length<2)return e.remainder=t,e;const n=r[r.length-1];return e.valid=hs(t,0,n.byteOffset-8),e.remainder=hs(t,n.byteOffset-8),e}function Jr(t,e){const r=new Uint8Array(t.length+e.length);return r.set(t),r.set(e,t.length),r}function hv(t,e){const r=[],n=e.samples,i=e.timescale,s=e.id;let a=!1;return Oe(n,["moof"]).map(l=>{const u=l.byteOffset-8;Oe(l,["traf"]).map(d=>{const f=Oe(d,["tfdt"]).map(m=>{const h=m[0];let p=Te(m,4);return h===1&&(p*=Math.pow(2,32),p+=Te(m,8)),p/i})[0];return f!==void 0&&(t=f),Oe(d,["tfhd"]).map(m=>{const h=Te(m,4),p=Te(m,0)&16777215,v=(p&1)!==0,g=(p&2)!==0,y=(p&8)!==0;let x=0;const S=(p&16)!==0;let T=0;const C=(p&32)!==0;let _=8;h===s&&(v&&(_+=8),g&&(_+=4),y&&(x=Te(m,_),_+=4),S&&(T=Te(m,_),_+=4),C&&(_+=4),e.type==="video"&&(a=TP(e.codec)),Oe(d,["trun"]).map(b=>{const I=b[0],A=Te(b,0)&16777215,k=(A&1)!==0;let O=0;const P=(A&4)!==0,G=(A&256)!==0;let K=0;const H=(A&512)!==0;let se=0;const W=(A&1024)!==0,F=(A&2048)!==0;let j=0;const te=Te(b,4);let ee=8;k&&(O=Te(b,ee),ee+=4),P&&(ee+=4);let fe=O+u;for(let ye=0;ye>1&63;return r===39||r===40}else return(e&31)===6}function ET(t,e,r,n){const i=TT(t);let s=0;s+=e;let a=0,o=0,l=0;for(;s=i.length)break;l=i[s++],a+=l}while(l===255);o=0;do{if(s>=i.length)break;l=i[s++],o+=l}while(l===255);const u=i.length-s;let c=s;if(ou){U.error(`Malformed SEI payload. ${o} is too small, only ${u} bytes left to parse.`);break}if(a===4){if(i[c++]===181){const f=vT(i,c);if(c+=2,f===49){const m=Te(i,c);if(c+=4,m===1195456820){const h=i[c++];if(h===3){const p=i[c++],v=31&p,g=64&p,y=g?2+v*3:0,x=new Uint8Array(y);if(g){x[0]=p;for(let S=1;S16){const d=[];for(let h=0;h<16;h++){const p=i[c++].toString(16);d.push(p.length==1?"0"+p:p),(h===3||h===5||h===7||h===9)&&d.push("-")}const f=o-16,m=new Uint8Array(f);for(let h=0;h>24&255,s[1]=n>>16&255,s[2]=n>>8&255,s[3]=n&255,s.set(t,4),i=0,n=8;i0?(s=new Uint8Array(4),e.length>0&&new DataView(s.buffer).setUint32(0,e.length,!1)):s=new Uint8Array;const a=new Uint8Array(4);return r&&r.byteLength>0&&new DataView(a.buffer).setUint32(0,r.byteLength,!1),LP([112,115,115,104],new Uint8Array([n,0,0,0]),t,s,i,a,r||new Uint8Array)}function _P(t){const e=[];if(t instanceof ArrayBuffer){const r=t.byteLength;let n=0;for(;n+32>>24;if(s!==0&&s!==1)return{offset:r,size:e};const a=t.buffer,o=bn.hexDump(new Uint8Array(a,r+12,16)),l=t.getUint32(28);let u=null,c=null;if(s===0){if(e-32=22&&(this.keyId=r.subarray(r.length-22,r.length-6));break;case yr.PLAYREADY:{const n=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=AP(n,null,r);const i=new Uint16Array(r.buffer,r.byteOffset,r.byteLength/2),s=String.fromCharCode.apply(null,Array.from(i)),a=s.substring(s.indexOf("<"),s.length),u=new DOMParser().parseFromString(a,"text/xml").getElementsByTagName("KID")[0];if(u){const c=u.childNodes[0]?u.childNodes[0].nodeValue:u.getAttribute("VALUE");if(c){const d=Am(c).subarray(0,16);eP(d),this.keyId=d}}break}default:{let n=r.subarray(0,16);if(n.length!==16){const i=new Uint8Array(16);i.set(n,16-n.length),n=i}this.keyId=n;break}}if(!this.keyId||this.keyId.byteLength!==16){let n=ru[this.uri];if(!n){const i=Object.keys(ru).length%Number.MAX_SAFE_INTEGER;n=new Uint8Array(16),new DataView(n.buffer,12,4).setUint32(0,i),ru[this.uri]=n}this.keyId=n}return this}}function RP(t){const e=new Uint8Array(16);for(let r=12;r<16;r++)e[r]=t>>8*(15-r)&255;return e}const wT=/\{\$([a-zA-Z0-9-_]+)\}/g;function pv(t){return wT.test(t)}function pr(t,e,r){if(t.variableList!==null||t.hasVariableRefs)for(let n=r.length;n--;){const i=r[n],s=e[i];s&&(e[i]=Yh(t,s))}}function Yh(t,e){if(t.variableList!==null||t.hasVariableRefs){const r=t.variableList;return e.replace(wT,n=>{const i=n.substring(2,n.length-1),s=r==null?void 0:r[i];return s===void 0?(t.playlistParsingError||(t.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${i}"`)),n):s})}return e}function mv(t,e,r){let n=t.variableList;n||(t.variableList=n={});let i,s;if("QUERYPARAM"in e){i=e.QUERYPARAM;try{const a=new self.URL(r).searchParams;if(a.has(i))s=a.get(i);else throw new Error(`"${i}" does not match any query parameter in URI: "${r}"`)}catch(a){t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${a.message}`))}}else i=e.NAME,s=e.VALUE;i in n?t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${i}"`)):n[i]=s||""}function IP(t,e,r){const n=e.IMPORT;if(r&&n in r){let i=t.variableList;i||(t.variableList=i={}),i[n]=r[n]}else t.playlistParsingError||(t.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${n}"`))}function bs(t=!0){return typeof self>"u"?void 0:(t||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function kP(t){return typeof self<"u"&&t===self.ManagedMediaSource}const Nc={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,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 DP(t,e){const r=Nc[e];return!!r&&!!r[t.slice(0,4)]}function wf(t,e,r=!0){return!t.split(",").some(n=>!bT(n,e,r))}function bT(t,e,r=!0){var n;const i=bs(r);return(n=i==null?void 0:i.isTypeSupported(pl(t,e)))!=null?n:!1}function pl(t,e){return`${e}/mp4;codecs="${t}"`}function gv(t){if(t){const e=t.substring(0,4);return Nc.video[e]}return 2}function Fc(t){return t.split(",").reduce((e,r)=>{const n=Nc.video[r];return n?(n*2+e)/(e?3:2):(Nc.audio[r]+e)/(e?2:1)},0)}const bf={};function PP(t,e=!0){if(bf[t])return bf[t];const r={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"]}[t];for(let n=0;nPP(r.toLowerCase(),e))}function vv(t,e){return t&&t!=="mp4a"?t:e&&e.split(",")[0]}function MP(t){const e=t.split(",");for(let r=0;r2){let i=n.shift()+".";i+=parseInt(n.shift()).toString(16),i+=("000"+parseInt(n.shift()).toString(16)).slice(-4),e[r]=i}}return e.join(",")}const yv=/#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,xv=/#EXT-X-MEDIA:(.*)/g,NP=/^#EXT(?:INF|-X-TARGETDURATION):/m,Sv=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#EXT-X-BYTERANGE:*(.+)/.source,/#EXT-X-PROGRAM-DATE-TIME:(.+)/.source,/#.*/.source].join("|"),"g"),FP=new RegExp([/#(EXTM3U)/.source,/#EXT-X-(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("|"));class kn{static findGroup(e,r){for(let n=0;n0&&s.length({id:u.attrs.AUDIO,audioCodec:u.audioCodec})),SUBTITLES:a.map(u=>({id:u.attrs.SUBTITLES,textCodec:u.textCodec})),"CLOSED-CAPTIONS":[]};let l=0;for(xv.lastIndex=0;(i=xv.exec(e))!==null;){const u=new gt(i[1]),c=u.TYPE;if(c){const d=o[c],f=s[c]||[];s[c]=f,pr(n,u,["URI","GROUP-ID","LANGUAGE","ASSOC-LANGUAGE","STABLE-RENDITION-ID","NAME","INSTREAM-ID","CHARACTERISTICS","CHANNELS"]);const m=u.LANGUAGE,h=u["ASSOC-LANGUAGE"],p=u.CHANNELS,v=u.CHARACTERISTICS,g=u["INSTREAM-ID"],y={attrs:u,bitrate:0,id:l++,groupId:u["GROUP-ID"]||"",name:u.NAME||m||"",type:c,default:u.bool("DEFAULT"),autoselect:u.bool("AUTOSELECT"),forced:u.bool("FORCED"),lang:m,url:u.URI?kn.resolve(u.URI,r):""};if(h&&(y.assocLang=h),p&&(y.channels=p),v&&(y.characteristics=v),g&&(y.instreamId=g),d!=null&&d.length){const x=kn.findGroup(d,y.groupId)||d[0];wv(y,x,"audioCodec"),wv(y,x,"textCodec")}f.push(y)}}return s}static parseLevelPlaylist(e,r,n,i,s,a){const o=new QD(r),l=o.fragments;let u=null,c=0,d=0,f=0,m=0,h=null,p=new yf(i,r),v,g,y,x=-1,S=!1,T=null;for(Sv.lastIndex=0,o.m3u8=e,o.hasVariableRefs=pv(e);(v=Sv.exec(e))!==null;){S&&(S=!1,p=new yf(i,r),p.start=f,p.sn=c,p.cc=m,p.level=n,u&&(p.initSegment=u,p.rawProgramDateTime=u.rawProgramDateTime,u.rawProgramDateTime=null,T&&(p.setByteRange(T),T=null)));const I=v[1];if(I){p.duration=parseFloat(I);const A=(" "+v[2]).slice(1);p.title=A||null,p.tagList.push(A?["INF",I,A]:["INF",I])}else if(v[3]){if(pe(p.duration)){p.start=f,y&&Av(p,y,o),p.sn=c,p.level=n,p.cc=m,l.push(p);const A=(" "+v[3]).slice(1);p.relurl=Yh(o,A),bv(p,h),h=p,f+=p.duration,c++,d=0,S=!0}}else if(v[4]){const A=(" "+v[4]).slice(1);h?p.setByteRange(A,h):p.setByteRange(A)}else if(v[5])p.rawProgramDateTime=(" "+v[5]).slice(1),p.tagList.push(["PROGRAM-DATE-TIME",p.rawProgramDateTime]),x===-1&&(x=l.length);else{if(v=v[0].match(FP),!v){U.warn("No matches on slow regex match for level playlist!");continue}for(g=1;g0&&P.bool("CAN-SKIP-DATERANGES"),o.partHoldBack=P.optionalFloat("PART-HOLD-BACK",0),o.holdBack=P.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{const P=new gt(k);o.partTarget=P.decimalFloatingPoint("PART-TARGET");break}case"PART":{let P=o.partList;P||(P=o.partList=[]);const G=d>0?P[P.length-1]:void 0,K=d++,H=new gt(k);pr(o,H,["BYTERANGE","URI"]);const se=new XD(H,p,r,K,G);P.push(se),p.duration+=se.duration;break}case"PRELOAD-HINT":{const P=new gt(k);pr(o,P,["URI"]),o.preloadHint=P;break}case"RENDITION-REPORT":{const P=new gt(k);pr(o,P,["URI"]),o.renditionReports=o.renditionReports||[],o.renditionReports.push(P);break}default:U.warn(`line parsed but not handled: ${v}`);break}}}h&&!h.relurl?(l.pop(),f-=h.duration,o.partList&&(o.fragmentHint=h)):o.partList&&(bv(p,h),p.cc=m,o.fragmentHint=p,y&&Av(p,y,o));const C=l.length,_=l[0],b=l[C-1];if(f+=o.skippedSegments*o.targetduration,f>0&&C&&b){o.averagetargetduration=f/C;const I=b.sn;o.endSN=I!=="initSegment"?I:0,o.live||(b.endList=!0),_&&(o.startCC=_.cc)}else o.endSN=0,o.startCC=0;return o.fragmentHint&&(f+=o.fragmentHint.duration),o.totalduration=f,o.endCC=m,x>0&&BP(l,x),o}}function Ev(t,e,r){var n,i;const s=new gt(t);pr(r,s,["KEYFORMAT","KEYFORMATVERSIONS","URI","IV","URI"]);const a=(n=s.METHOD)!=null?n:"",o=s.URI,l=s.hexadecimalInteger("IV"),u=s.KEYFORMATVERSIONS,c=(i=s.KEYFORMAT)!=null?i:"identity";o&&s.IV&&!l&&U.error(`Invalid IV: ${s.IV}`);const d=o?kn.resolve(o,e):"",f=(u||"1").split("/").map(Number).filter(Number.isFinite);return new hl(a,d,c,f,l)}function Tv(t){const r=new gt(t).decimalFloatingPoint("TIME-OFFSET");return pe(r)?r:null}function UP(t,e){let r=(t||"").split(/[ ,]+/).filter(n=>n);["video","audio","text"].forEach(n=>{const i=r.filter(s=>DP(s,n));i.length&&(e[`${n}Codec`]=i.join(","),r=r.filter(s=>i.indexOf(s)===-1))}),e.unknownCodecs=r}function wv(t,e,r){const n=e[r];n&&(t[r]=n)}function BP(t,e){let r=t[e];for(let n=e;n--;){const i=t[n];if(!i)return;i.programDateTime=r.programDateTime-i.duration*1e3,r=i}}function bv(t,e){t.rawProgramDateTime?t.programDateTime=Date.parse(t.rawProgramDateTime):e!=null&&e.programDateTime&&(t.programDateTime=e.endProgramDateTime),pe(t.programDateTime)||(t.programDateTime=null,t.rawProgramDateTime=null)}function Lv(t,e,r,n){t.relurl=e.URI,e.BYTERANGE&&t.setByteRange(e.BYTERANGE),t.level=r,t.sn="initSegment",n&&(t.levelkeys=n),t.initSegment=null}function Av(t,e,r){t.levelkeys=e;const{encryptedFragments:n}=r;(!n.length||n[n.length-1].levelkeys!==e)&&Object.keys(e).some(i=>e[i].isCommonEncryption)&&n.push(t)}var He={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},we={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};function _v(t){const{type:e}=t;switch(e){case He.AUDIO_TRACK:return we.AUDIO;case He.SUBTITLE_TRACK:return we.SUBTITLE;default:return we.MAIN}}function Lf(t,e){let r=t.url;return(r===void 0||r.indexOf("data:")===0)&&(r=e.url),r}class $P{constructor(e){this.hls=void 0,this.loaders=Object.create(null),this.variableList=null,this.hls=e,this.registerListeners()}startLoad(e){}stopLoad(){this.destroyInternalLoaders()}registerListeners(){const{hls:e}=this;e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.LEVEL_LOADING,this.onLevelLoading,this),e.on(w.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.on(w.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}unregisterListeners(){const{hls:e}=this;e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.LEVEL_LOADING,this.onLevelLoading,this),e.off(w.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),e.off(w.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this)}createInternalLoader(e){const r=this.hls.config,n=r.pLoader,i=r.loader,s=n||i,a=new s(r);return this.loaders[e.type]=a,a}getInternalLoader(e){return this.loaders[e.type]}resetInternalLoader(e){this.loaders[e]&&delete this.loaders[e]}destroyInternalLoaders(){for(const e in this.loaders){const r=this.loaders[e];r&&r.destroy(),this.resetInternalLoader(e)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(e,r){const{url:n}=r;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:He.MANIFEST,url:n,deliveryDirectives:null})}onLevelLoading(e,r){const{id:n,level:i,pathwayId:s,url:a,deliveryDirectives:o}=r;this.load({id:n,level:i,pathwayId:s,responseType:"text",type:He.LEVEL,url:a,deliveryDirectives:o})}onAudioTrackLoading(e,r){const{id:n,groupId:i,url:s,deliveryDirectives:a}=r;this.load({id:n,groupId:i,level:null,responseType:"text",type:He.AUDIO_TRACK,url:s,deliveryDirectives:a})}onSubtitleTrackLoading(e,r){const{id:n,groupId:i,url:s,deliveryDirectives:a}=r;this.load({id:n,groupId:i,level:null,responseType:"text",type:He.SUBTITLE_TRACK,url:s,deliveryDirectives:a})}load(e){var r;const n=this.hls.config;let i=this.getInternalLoader(e);if(i){const u=i.context;if(u&&u.url===e.url&&u.level===e.level){U.trace("[playlist-loader]: playlist request ongoing");return}U.log(`[playlist-loader]: aborting previous loader for type: ${e.type}`),i.abort()}let s;if(e.type===He.MANIFEST?s=n.manifestLoadPolicy.default:s=It({},n.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),i=this.createInternalLoader(e),pe((r=e.deliveryDirectives)==null?void 0:r.part)){let u;if(e.type===He.LEVEL&&e.level!==null?u=this.hls.levels[e.level].details:e.type===He.AUDIO_TRACK&&e.id!==null?u=this.hls.audioTracks[e.id].details:e.type===He.SUBTITLE_TRACK&&e.id!==null&&(u=this.hls.subtitleTracks[e.id].details),u){const c=u.partTarget,d=u.targetduration;if(c&&d){const f=Math.max(c*3,d*.8)*1e3;s=It({},s,{maxTimeToFirstByteMs:Math.min(f,s.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(f,s.maxTimeToFirstByteMs)})}}}const a=s.errorRetry||s.timeoutRetry||{},o={loadPolicy:s,timeout:s.maxLoadTimeMs,maxRetry:a.maxNumRetry||0,retryDelay:a.retryDelayMs||0,maxRetryDelay:a.maxRetryDelayMs||0},l={onSuccess:(u,c,d,f)=>{const m=this.getInternalLoader(d);this.resetInternalLoader(d.type);const h=u.data;if(h.indexOf("#EXTM3U")!==0){this.handleManifestParsingError(u,d,new Error("no EXTM3U delimiter"),f||null,c);return}c.parsing.start=performance.now(),kn.isMediaPlaylist(h)?this.handleTrackOrLevelPlaylist(u,c,d,f||null,m):this.handleMasterPlaylist(u,c,d,f)},onError:(u,c,d,f)=>{this.handleNetworkError(c,d,!1,u,f)},onTimeout:(u,c,d)=>{this.handleNetworkError(c,d,!0,void 0,u)}};i.load(e,o,l)}handleMasterPlaylist(e,r,n,i){const s=this.hls,a=e.data,o=Lf(e,n),l=kn.parseMasterPlaylist(a,o);if(l.playlistParsingError){this.handleManifestParsingError(e,n,l.playlistParsingError,i,r);return}const{contentSteering:u,levels:c,sessionData:d,sessionKeys:f,startTimeOffset:m,variableList:h}=l;this.variableList=h;const{AUDIO:p=[],SUBTITLES:v,"CLOSED-CAPTIONS":g}=kn.parseMasterPlaylistMedia(a,o,l);p.length&&!p.some(x=>!x.url)&&c[0].audioCodec&&!c[0].attrs.AUDIO&&(U.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),p.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new gt({}),bitrate:0,url:""})),s.trigger(w.MANIFEST_LOADED,{levels:c,audioTracks:p,subtitles:v,captions:g,contentSteering:u,url:o,stats:r,networkDetails:i,sessionData:d,sessionKeys:f,startTimeOffset:m,variableList:h})}handleTrackOrLevelPlaylist(e,r,n,i,s){const a=this.hls,{id:o,level:l,type:u}=n,c=Lf(e,n),d=0,f=pe(l)?l:pe(o)?o:0,m=_v(n),h=kn.parseLevelPlaylist(e.data,c,f,m,d,this.variableList);if(u===He.MANIFEST){const p={attrs:new gt({}),bitrate:0,details:h,name:"",url:c};a.trigger(w.MANIFEST_LOADED,{levels:[p],audioTracks:[],url:c,stats:r,networkDetails:i,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}r.parsing.end=performance.now(),n.levelDetails=h,this.handlePlaylistLoaded(h,e,r,n,i,s)}handleManifestParsingError(e,r,n,i,s){this.hls.trigger(w.ERROR,{type:_e.NETWORK_ERROR,details:z.MANIFEST_PARSING_ERROR,fatal:r.type===He.MANIFEST,url:e.url,err:n,error:n,reason:n.message,response:e,context:r,networkDetails:i,stats:s})}handleNetworkError(e,r,n=!1,i,s){let a=`A network ${n?"timeout":"error"+(i?" (status "+i.code+")":"")} occurred while loading ${e.type}`;e.type===He.LEVEL?a+=`: ${e.level} id: ${e.id}`:(e.type===He.AUDIO_TRACK||e.type===He.SUBTITLE_TRACK)&&(a+=` id: ${e.id} group-id: "${e.groupId}"`);const o=new Error(a);U.warn(`[playlist-loader]: ${a}`);let l=z.UNKNOWN,u=!1;const c=this.getInternalLoader(e);switch(e.type){case He.MANIFEST:l=n?z.MANIFEST_LOAD_TIMEOUT:z.MANIFEST_LOAD_ERROR,u=!0;break;case He.LEVEL:l=n?z.LEVEL_LOAD_TIMEOUT:z.LEVEL_LOAD_ERROR,u=!1;break;case He.AUDIO_TRACK:l=n?z.AUDIO_TRACK_LOAD_TIMEOUT:z.AUDIO_TRACK_LOAD_ERROR,u=!1;break;case He.SUBTITLE_TRACK:l=n?z.SUBTITLE_TRACK_LOAD_TIMEOUT:z.SUBTITLE_LOAD_ERROR,u=!1;break}c&&this.resetInternalLoader(e.type);const d={type:_e.NETWORK_ERROR,details:l,fatal:u,url:e.url,loader:c,context:e,error:o,networkDetails:r,stats:s};if(i){const f=(r==null?void 0:r.url)||e.url;d.response=jt({url:f,data:void 0},i)}this.hls.trigger(w.ERROR,d)}handlePlaylistLoaded(e,r,n,i,s,a){const o=this.hls,{type:l,level:u,id:c,groupId:d,deliveryDirectives:f}=i,m=Lf(r,i),h=_v(i),p=typeof i.level=="number"&&h===we.MAIN?u:void 0;if(!e.fragments.length){const g=new Error("No Segments found in Playlist");o.trigger(w.ERROR,{type:_e.NETWORK_ERROR,details:z.LEVEL_EMPTY_ERROR,fatal:!1,url:m,error:g,reason:g.message,response:r,context:i,level:p,parent:h,networkDetails:s,stats:n});return}e.targetduration||(e.playlistParsingError=new Error("Missing Target Duration"));const v=e.playlistParsingError;if(v){o.trigger(w.ERROR,{type:_e.NETWORK_ERROR,details:z.LEVEL_PARSING_ERROR,fatal:!1,url:m,error:v,reason:v.message,response:r,context:i,level:p,parent:h,networkDetails:s,stats:n});return}switch(e.live&&a&&(a.getCacheAge&&(e.ageHeader=a.getCacheAge()||0),(!a.getCacheAge||isNaN(e.ageHeader))&&(e.ageHeader=0)),l){case He.MANIFEST:case He.LEVEL:o.trigger(w.LEVEL_LOADED,{details:e,level:p||0,id:c||0,stats:n,networkDetails:s,deliveryDirectives:f});break;case He.AUDIO_TRACK:o.trigger(w.AUDIO_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:n,networkDetails:s,deliveryDirectives:f});break;case He.SUBTITLE_TRACK:o.trigger(w.SUBTITLE_TRACK_LOADED,{details:e,id:c||0,groupId:d||"",stats:n,networkDetails:s,deliveryDirectives:f});break}}}function LT(t,e){let r;try{r=new Event("addtrack")}catch{r=document.createEvent("Event"),r.initEvent("addtrack",!1,!1)}r.track=t,e.dispatchEvent(r)}function AT(t,e){const r=t.mode;if(r==="disabled"&&(t.mode="hidden"),t.cues&&!t.cues.getCueById(e.id))try{if(t.addCue(e),!t.cues.getCueById(e.id))throw new Error(`addCue is failed for: ${e}`)}catch(n){U.debug(`[texttrack-utils]: ${n}`);try{const i=new self.TextTrackCue(e.startTime,e.endTime,e.text);i.id=e.id,t.addCue(i)}catch(i){U.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${i}`)}}r==="disabled"&&(t.mode=r)}function ta(t){const e=t.mode;if(e==="disabled"&&(t.mode="hidden"),t.cues)for(let r=t.cues.length;r--;)t.removeCue(t.cues[r]);e==="disabled"&&(t.mode=e)}function qh(t,e,r,n){const i=t.mode;if(i==="disabled"&&(t.mode="hidden"),t.cues&&t.cues.length>0){const s=VP(t.cues,e,r);for(let a=0;at[r].endTime)return-1;let n=0,i=r;for(;n<=i;){const s=Math.floor((i+n)/2);if(et[s].startTime&&n-1)for(let s=i,a=t.length;s=e&&o.endTime<=r)n.push(o);else if(o.startTime>r)return n}return n}function Pu(t){const e=[];for(let r=0;r"u"))return self.VTTCue||self.TextTrackCue}function Cv(t,e,r,n,i){let s=new t(e,r,"");try{s.value=n,i&&(s.type=i)}catch{s=new t(e,r,JSON.stringify(i?jt({type:i},n):n))}return s}const nu=(()=>{const t=Xh();try{t&&new t(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();function Af(t,e){return t.getTime()/1e3-e}function zP(t){return Uint8Array.from(t.replace(/^0x/,"").replace(/([\da-fA-F]{2}) ?/g,"0x$1 ").replace(/ +$/,"").split(" ")).buffer}class HP{constructor(e){this.hls=void 0,this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=e,this._registerListeners()}destroy(){this._unregisterListeners(),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={},this.hls=null}_registerListeners(){const{hls:e}=this;e.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(w.LEVEL_UPDATED,this.onLevelUpdated,this)}_unregisterListeners(){const{hls:e}=this;e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(w.LEVEL_UPDATED,this.onLevelUpdated,this)}onMediaAttached(e,r){this.media=r.media}onMediaDetaching(){this.id3Track&&(ta(this.id3Track),this.id3Track=null,this.media=null,this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(e){const r=this.getID3Track(e.textTracks);return r.mode="hidden",r}getID3Track(e){if(this.media){for(let r=0;rnu&&(d=nu),d-c<=0&&(d=c+GP);for(let m=0;mc.type===dn.audioId3&&l:i==="video"?u=c=>c.type===dn.emsg&&o:u=c=>c.type===dn.audioId3&&l||c.type===dn.emsg&&o,qh(s,r,n,u)}}onLevelUpdated(e,{details:r}){if(!this.media||!r.hasProgramDateTime||!this.hls.config.enableDateRangeMetadataCues)return;const{dateRangeCuesAppended:n,id3Track:i}=this,{dateRanges:s}=r,a=Object.keys(s);if(i){const c=Object.keys(n).filter(d=>!a.includes(d));for(let d=c.length;d--;){const f=c[d];Object.keys(n[f].cues).forEach(m=>{i.removeCue(n[f].cues[m])}),delete n[f]}}const o=r.fragments[r.fragments.length-1];if(a.length===0||!pe(o==null?void 0:o.programDateTime))return;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=o.programDateTime/1e3-o.start,u=Xh();for(let c=0;c{if(C!==f.id){const _=s[C];if(_.class===f.class&&_.startDate>f.startDate&&(!T||f.startDatethis.timeupdate(),this.hls=e,this.config=e.config,this.registerListeners()}get latency(){return this._latency||0}get maxLatency(){const{config:e,levelDetails:r}=this;return e.liveMaxLatencyDuration!==void 0?e.liveMaxLatencyDuration:r?e.liveMaxLatencyDurationCount*r.targetduration:0}get targetLatency(){const{levelDetails:e}=this;if(e===null)return null;const{holdBack:r,partHoldBack:n,targetduration:i}=e,{liveSyncDuration:s,liveSyncDurationCount:a,lowLatencyMode:o}=this.config,l=this.hls.userConfig;let u=o&&n||r;(l.liveSyncDuration||l.liveSyncDurationCount||u===0)&&(u=s!==void 0?s:a*i);const c=i;return u+Math.min(this.stallCount*1,c)}get liveSyncPosition(){const e=this.estimateLiveEdge(),r=this.targetLatency,n=this.levelDetails;if(e===null||r===null||n===null)return null;const i=n.edge,s=e-r-this.edgeStalled,a=i-n.totalduration,o=i-(this.config.lowLatencyMode&&n.partTarget||n.targetduration);return Math.min(Math.max(a,s),o)}get drift(){const{levelDetails:e}=this;return e===null?1:e.drift}get edgeStalled(){const{levelDetails:e}=this;if(e===null)return 0;const r=(this.config.lowLatencyMode&&e.partTarget||e.targetduration)*3;return Math.max(e.age-r,0)}get forwardBufferLength(){const{media:e,levelDetails:r}=this;if(!e||!r)return 0;const n=e.buffered.length;return(n?e.buffered.end(n-1):r.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.levelDetails=null,this.hls=this.timeupdateHandler=null}registerListeners(){this.hls.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.on(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.on(w.ERROR,this.onError,this)}unregisterListeners(){this.hls.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),this.hls.off(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),this.hls.off(w.ERROR,this.onError,this)}onMediaAttached(e,r){this.media=r.media,this.media.addEventListener("timeupdate",this.timeupdateHandler)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.timeupdateHandler),this.media=null)}onManifestLoading(){this.levelDetails=null,this._latency=null,this.stallCount=0}onLevelUpdated(e,{details:r}){this.levelDetails=r,r.advanced&&this.timeupdate(),!r.live&&this.media&&this.media.removeEventListener("timeupdate",this.timeupdateHandler)}onError(e,r){var n;r.details===z.BUFFER_STALLED_ERROR&&(this.stallCount++,(n=this.levelDetails)!=null&&n.live&&U.warn("[playback-rate-controller]: Stall detected, adjusting target latency"))}timeupdate(){const{media:e,levelDetails:r}=this;if(!e||!r)return;this.currentTime=e.currentTime;const n=this.computeLatency();if(n===null)return;this._latency=n;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:s}=this.config;if(!i||s===1||!r.live)return;const a=this.targetLatency;if(a===null)return;const o=n-a,l=Math.min(this.maxLatency,a+r.targetduration);if(o.05&&this.forwardBufferLength>1){const c=Math.min(2,Math.max(1,s)),d=Math.round(2/(1+Math.exp(-.75*o-this.edgeStalled))*20)/20;e.playbackRate=Math.min(c,Math.max(1,d))}else e.playbackRate!==1&&e.playbackRate!==0&&(e.playbackRate=1)}estimateLiveEdge(){const{levelDetails:e}=this;return e===null?null:e.edge+e.age}computeLatency(){const e=this.estimateLiveEdge();return e===null?null:e-this.currentTime}}const Zh=["NONE","TYPE-0","TYPE-1",null];function KP(t){return Zh.indexOf(t)>-1}const Bc=["SDR","PQ","HLG"];function YP(t){return!!t&&Bc.indexOf(t)>-1}var Ou={No:"",Yes:"YES",v2:"v2"};function Rv(t){const{canSkipUntil:e,canSkipDateRanges:r,age:n}=t,i=n!!r).map(r=>r.substring(0,4)).join(","),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 kv(this._audioGroups,e)}hasSubtitleGroup(e){return kv(this._subtitleGroups,e)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(e,r){if(r){if(e==="audio"){let n=this._audioGroups;n||(n=this._audioGroups=[]),n.indexOf(r)===-1&&n.push(r)}else if(e==="text"){let n=this._subtitleGroups;n||(n=this._subtitleGroups=[]),n.indexOf(r)===-1&&n.push(r)}}}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 kv(t,e){return!e||!t?!1:t.indexOf(e)!==-1}function _f(t,e){const r=e.startPTS;if(pe(r)){let n=0,i;e.sn>t.sn?(n=r-t.start,i=t):(n=t.start-r,i=e),i.duration!==n&&(i.duration=n)}else e.sn>t.sn?t.cc===e.cc&&t.minEndPTS?e.start=t.start+(t.minEndPTS-t.start):e.start=t.start+t.duration:e.start=Math.max(t.start-e.duration,0)}function _T(t,e,r,n,i,s){n-r<=0&&(U.warn("Fragment should have a positive duration",e),n=r+e.duration,s=i+e.duration);let o=r,l=n;const u=e.startPTS,c=e.endPTS;if(pe(u)){const v=Math.abs(u-r);pe(e.deltaPTS)?e.deltaPTS=Math.max(v,e.deltaPTS):e.deltaPTS=v,o=Math.max(r,u),r=Math.min(r,u),i=Math.min(i,e.startDTS),l=Math.min(n,c),n=Math.max(n,c),s=Math.max(s,e.endDTS)}const d=r-e.start;e.start!==0&&(e.start=r),e.duration=n-e.start,e.startPTS=r,e.maxStartPTS=o,e.startDTS=i,e.endPTS=n,e.minEndPTS=l,e.endDTS=s;const f=e.sn;if(!t||ft.endSN)return 0;let m;const h=f-t.startSN,p=t.fragments;for(p[h]=e,m=h;m>0;m--)_f(p[m],p[m-1]);for(m=h;m=0;l--){const u=n[l].initSegment;if(u){r=u;break}}t.fragmentHint&&delete t.fragmentHint.endPTS;let i=0,s;if(QP(t,e,(l,u)=>{l.relurl&&(i=l.cc-u.cc),pe(l.startPTS)&&pe(l.endPTS)&&(u.start=u.startPTS=l.startPTS,u.startDTS=l.startDTS,u.maxStartPTS=l.maxStartPTS,u.endPTS=l.endPTS,u.endDTS=l.endDTS,u.minEndPTS=l.minEndPTS,u.duration=l.endPTS-l.startPTS,u.duration&&(s=u),e.PTSKnown=e.alignedSliding=!0),u.elementaryStreams=l.elementaryStreams,u.loader=l.loader,u.stats=l.stats,l.initSegment&&(u.initSegment=l.initSegment,r=l.initSegment)}),r&&(e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments).forEach(u=>{var c;u&&(!u.initSegment||u.initSegment.relurl===((c=r)==null?void 0:c.relurl))&&(u.initSegment=r)}),e.skippedSegments)if(e.deltaUpdateFailed=e.fragments.some(l=>!l),e.deltaUpdateFailed){U.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let l=e.skippedSegments;l--;)e.fragments.shift();e.startSN=e.fragments[0].sn,e.startCC=e.fragments[0].cc}else e.canSkipDateRanges&&(e.dateRanges=XP(t.dateRanges,e.dateRanges,e.recentlyRemovedDateranges));const a=e.fragments;if(i){U.warn("discontinuity sliding from playlist, take drift into account");for(let l=0;l{u.elementaryStreams=l.elementaryStreams,u.stats=l.stats}),s?_T(e,s,s.startPTS,s.endPTS,s.startDTS,s.endDTS):CT(t,e),a.length&&(e.totalduration=e.edge-a[0].start),e.driftStartTime=t.driftStartTime,e.driftStart=t.driftStart;const o=e.advancedDateTime;if(e.advanced&&o){const l=e.edge;e.driftStart||(e.driftStartTime=o,e.driftStart=l),e.driftEndTime=o,e.driftEnd=l}else e.driftEndTime=t.driftEndTime,e.driftEnd=t.driftEnd,e.advancedDateTime=t.advancedDateTime}function XP(t,e,r){const n=It({},t);return r&&r.forEach(i=>{delete n[i]}),Object.keys(e).forEach(i=>{const s=new cT(e[i].attr,n[i]);s.isValid?n[i]=s:U.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${JSON.stringify(e[i].attr)}"`)}),n}function ZP(t,e,r){if(t&&e){let n=0;for(let i=0,s=t.length;i<=s;i++){const a=t[i],o=e[i+n];a&&o&&a.index===o.index&&a.fragment.sn===o.fragment.sn?r(a,o):n--}}}function QP(t,e,r){const n=e.skippedSegments,i=Math.max(t.startSN,e.startSN)-e.startSN,s=(t.fragmentHint?1:0)+(n?e.endSN:Math.min(t.endSN,e.endSN))-e.startSN,a=e.startSN-t.startSN,o=e.fragmentHint?e.fragments.concat(e.fragmentHint):e.fragments,l=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments;for(let u=i;u<=s;u++){const c=l[a+u];let d=o[u];n&&!d&&u=n.length||Qh(e,n[r].start)}function Qh(t,e){if(e){const r=t.fragments;for(let n=t.skippedSegments;ne){const s=n[n.length-1].duration*1e3;s{const{details:n}=e;n!=null&&n.fragments&&n.fragments.forEach(i=>{i.level=r})})}function $c(t){switch(t.details){case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_TIMEOUT:case z.LEVEL_LOAD_TIMEOUT:case z.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function Pv(t,e){const r=$c(e);return t.default[`${r?"timeout":"error"}Retry`]}function Rm(t,e){const r=t.backoff==="linear"?1:Math.pow(2,e);return Math.min(r*t.retryDelayMs,t.maxRetryDelayMs)}function Ov(t){return jt(jt({},t),{errorRetry:null,timeoutRetry:null})}function jc(t,e,r,n){if(!t)return!1;const i=n==null?void 0:n.code,s=e499)}const kT={search:function(t,e){let r=0,n=t.length-1,i=null,s=null;for(;r<=n;){i=(r+n)/2|0,s=t[i];const a=e(s);if(a>0)r=i+1;else if(a<0)n=i-1;else return s}return null}};function rO(t,e,r){if(e===null||!Array.isArray(t)||!t.length||!pe(e))return null;const n=t[0].programDateTime;if(e<(n||0))return null;const i=t[t.length-1].endProgramDateTime;if(e>=(i||0))return null;r=r||0;for(let s=0;s0&&o<15e-7&&(r+=15e-7)}else r===0&&e[0].start===0&&(s=e[0]);if(s&&((!t||t.level===s.level)&&Jh(r,n,s)===0||nO(s,t,Math.min(i,n))))return s;const a=kT.search(e,Jh.bind(null,r,n));return a&&(a!==t||!s)?a:s}function nO(t,e,r){if(e&&e.start===0&&e.level0){const n=e.tagList.reduce((i,s)=>(s[0]==="INF"&&(i+=parseFloat(s[1])),i),r);return t.start<=n}return!1}function Jh(t=0,e=0,r){if(r.start<=t&&r.start+r.duration>t)return 0;const n=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0));return r.start+r.duration-n<=t?1:r.start-n>t&&r.start?-1:0}function iO(t,e,r){const n=Math.min(e,r.duration+(r.deltaPTS?r.deltaPTS:0))*1e3;return(r.endProgramDateTime||0)-n>t}function sO(t,e){return kT.search(t,r=>r.cce?-1:0)}var zt={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},sn={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,SwitchToSDR:4};class aO{constructor(e){this.hls=void 0,this.playlistError=0,this.penalizedRenditions={},this.log=void 0,this.warn=void 0,this.error=void 0,this.hls=e,this.log=U.log.bind(U,"[info]:"),this.warn=U.warn.bind(U,"[warning]:"),this.error=U.error.bind(U,"[error]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(w.ERROR,this.onError,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const e=this.hls;e&&(e.off(w.ERROR,this.onError,this),e.off(w.ERROR,this.onErrorOut,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.LEVEL_UPDATED,this.onLevelUpdated,this))}destroy(){this.unregisterListeners(),this.hls=null,this.penalizedRenditions={}}startLoad(e){}stopLoad(){this.playlistError=0}getVariantLevelIndex(e){return(e==null?void 0:e.type)===we.MAIN?e.level:this.hls.loadLevel}onManifestLoading(){this.playlistError=0,this.penalizedRenditions={}}onLevelUpdated(){this.playlistError=0}onError(e,r){var n,i;if(r.fatal)return;const s=this.hls,a=r.context;switch(r.details){case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:r.errorAction=this.getFragRetryOrSwitchAction(r);return;case z.FRAG_PARSING_ERROR:if((n=r.frag)!=null&&n.gap){r.errorAction={action:zt.DoNothing,flags:sn.None};return}case z.FRAG_GAP:case z.FRAG_DECRYPT_ERROR:{r.errorAction=this.getFragRetryOrSwitchAction(r),r.errorAction.action=zt.SendAlternateToPenaltyBox;return}case z.LEVEL_EMPTY_ERROR:case z.LEVEL_PARSING_ERROR:{var o,l;const u=r.parent===we.MAIN?r.level:s.loadLevel;r.details===z.LEVEL_EMPTY_ERROR&&((o=r.context)!=null&&(l=o.levelDetails)!=null&&l.live)?r.errorAction=this.getPlaylistRetryOrSwitchAction(r,u):(r.levelRetry=!1,r.errorAction=this.getLevelSwitchAction(r,u))}return;case z.LEVEL_LOAD_ERROR:case z.LEVEL_LOAD_TIMEOUT:typeof(a==null?void 0:a.level)=="number"&&(r.errorAction=this.getPlaylistRetryOrSwitchAction(r,a.level));return;case z.AUDIO_TRACK_LOAD_ERROR:case z.AUDIO_TRACK_LOAD_TIMEOUT:case z.SUBTITLE_LOAD_ERROR:case z.SUBTITLE_TRACK_LOAD_TIMEOUT:if(a){const u=s.levels[s.loadLevel];if(u&&(a.type===He.AUDIO_TRACK&&u.hasAudioGroup(a.groupId)||a.type===He.SUBTITLE_TRACK&&u.hasSubtitleGroup(a.groupId))){r.errorAction=this.getPlaylistRetryOrSwitchAction(r,s.loadLevel),r.errorAction.action=zt.SendAlternateToPenaltyBox,r.errorAction.flags=sn.MoveAllAlternatesMatchingHost;return}}return;case z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:{const u=s.levels[s.loadLevel],c=u==null?void 0:u.attrs["HDCP-LEVEL"];c?r.errorAction={action:zt.SendAlternateToPenaltyBox,flags:sn.MoveAllAlternatesMatchingHDCP,hdcpLevel:c}:this.keySystemError(r)}return;case z.BUFFER_ADD_CODEC_ERROR:case z.REMUX_ALLOC_ERROR:case z.BUFFER_APPEND_ERROR:r.errorAction=this.getLevelSwitchAction(r,(i=r.level)!=null?i:s.loadLevel);return;case z.INTERNAL_EXCEPTION:case z.BUFFER_APPENDING_ERROR:case z.BUFFER_FULL_ERROR:case z.LEVEL_SWITCH_ERROR:case z.BUFFER_STALLED_ERROR:case z.BUFFER_SEEK_OVER_HOLE:case z.BUFFER_NUDGE_ON_STALL:r.errorAction={action:zt.DoNothing,flags:sn.None};return}r.type===_e.KEY_SYSTEM_ERROR&&this.keySystemError(r)}keySystemError(e){const r=this.getVariantLevelIndex(e.frag);e.levelRetry=!1,e.errorAction=this.getLevelSwitchAction(e,r)}getPlaylistRetryOrSwitchAction(e,r){const n=this.hls,i=Pv(n.config.playlistLoadPolicy,e),s=this.playlistError++;if(jc(i,s,$c(e),e.response))return{action:zt.RetryRequest,flags:sn.None,retryConfig:i,retryCount:s};const o=this.getLevelSwitchAction(e,r);return i&&(o.retryConfig=i,o.retryCount=s),o}getFragRetryOrSwitchAction(e){const r=this.hls,n=this.getVariantLevelIndex(e.frag),i=r.levels[n],{fragLoadPolicy:s,keyLoadPolicy:a}=r.config,o=Pv(e.details.startsWith("key")?a:s,e),l=r.levels.reduce((c,d)=>c+d.fragmentError,0);if(i&&(e.details!==z.FRAG_GAP&&i.fragmentError++,jc(o,l,$c(e),e.response)))return{action:zt.RetryRequest,flags:sn.None,retryConfig:o,retryCount:l};const u=this.getLevelSwitchAction(e,n);return o&&(u.retryConfig=o,u.retryCount=l),u}getLevelSwitchAction(e,r){const n=this.hls;r==null&&(r=n.loadLevel);const i=this.hls.levels[r];if(i){var s,a;const u=e.details;i.loadError++,u===z.BUFFER_APPEND_ERROR&&i.fragmentError++;let c=-1;const{levels:d,loadLevel:f,minAutoLevel:m,maxAutoLevel:h}=n;n.autoLevelEnabled||(n.loadLevel=-1);const p=(s=e.frag)==null?void 0:s.type,g=(p===we.AUDIO&&u===z.FRAG_PARSING_ERROR||e.sourceBufferName==="audio"&&(u===z.BUFFER_ADD_CODEC_ERROR||u===z.BUFFER_APPEND_ERROR))&&d.some(({audioCodec:C})=>i.audioCodec!==C),x=e.sourceBufferName==="video"&&(u===z.BUFFER_ADD_CODEC_ERROR||u===z.BUFFER_APPEND_ERROR)&&d.some(({codecSet:C,audioCodec:_})=>i.codecSet!==C&&i.audioCodec===_),{type:S,groupId:T}=(a=e.context)!=null?a:{};for(let C=d.length;C--;){const _=(C+f)%d.length;if(_!==f&&_>=m&&_<=h&&d[_].loadError===0){var o,l;const b=d[_];if(u===z.FRAG_GAP&&p===we.MAIN&&e.frag){const I=d[_].details;if(I){const A=Vc(e.frag,I.fragments,e.frag.start);if(A!=null&&A.gap)continue}}else{if(S===He.AUDIO_TRACK&&b.hasAudioGroup(T)||S===He.SUBTITLE_TRACK&&b.hasSubtitleGroup(T))continue;if(p===we.AUDIO&&(o=i.audioGroups)!=null&&o.some(I=>b.hasAudioGroup(I))||p===we.SUBTITLE&&(l=i.subtitleGroups)!=null&&l.some(I=>b.hasSubtitleGroup(I))||g&&i.audioCodec===b.audioCodec||!g&&i.audioCodec!==b.audioCodec||x&&i.codecSet===b.codecSet)continue}c=_;break}}if(c>-1&&n.loadLevel!==c)return e.levelRetry=!0,this.playlistError=0,{action:zt.SendAlternateToPenaltyBox,flags:sn.None,nextAutoLevel:c}}return{action:zt.SendAlternateToPenaltyBox,flags:sn.MoveAllAlternatesMatchingHost}}onErrorOut(e,r){var n;switch((n=r.errorAction)==null?void 0:n.action){case zt.DoNothing:break;case zt.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(r),!r.errorAction.resolved&&r.details!==z.FRAG_GAP?r.fatal=!0:/MediaSource readyState: ended/.test(r.error.message)&&(this.warn(`MediaSource ended after "${r.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(r.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(e){const r=this.hls,n=e.errorAction;if(!n)return;const{flags:i,hdcpLevel:s,nextAutoLevel:a}=n;switch(i){case sn.None:this.switchLevel(e,a);break;case sn.MoveAllAlternatesMatchingHDCP:s&&(r.maxHdcpLevel=Zh[Zh.indexOf(s)-1],n.resolved=!0),this.warn(`Restricting playback to HDCP-LEVEL of "${r.maxHdcpLevel}" or lower`);break}n.resolved||this.switchLevel(e,a)}switchLevel(e,r){r!==void 0&&e.errorAction&&(this.warn(`switching to level ${r} after ${e.details}`),this.hls.nextAutoLevel=r,e.errorAction.resolved=!0,this.hls.nextLoadLevel=this.hls.nextAutoLevel)}}class Im{constructor(e,r){this.hls=void 0,this.timer=-1,this.requestScheduled=-1,this.canLoad=!1,this.log=void 0,this.warn=void 0,this.log=U.log.bind(U,`${r}:`),this.warn=U.warn.bind(U,`${r}:`),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.requestScheduled=-1,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(e,r,n){const i=r==null?void 0:r.renditionReports;if(i){let s=-1;for(let a=0;a=0&&c>r.partTarget&&(l+=1)}const u=n&&Rv(n);return new Iv(o,l>=0?l:void 0,u)}}}loadPlaylist(e){this.requestScheduled===-1&&(this.requestScheduled=self.performance.now())}shouldLoadPlaylist(e){return this.canLoad&&!!e&&!!e.url&&(!e.details||e.details.live)}shouldReloadPlaylist(e){return this.timer===-1&&this.requestScheduled===-1&&this.shouldLoadPlaylist(e)}playlistLoaded(e,r,n){const{details:i,stats:s}=r,a=self.performance.now(),o=s.loading.first?Math.max(0,a-s.loading.first):0;if(i.advancedDateTime=Date.now()-o,i.live||n!=null&&n.live){if(i.reloaded(n),n&&this.log(`live playlist ${e} ${i.advanced?"REFRESHED "+i.lastPartSn+"-"+i.lastPartIndex:i.updated?"UPDATED":"MISSED"}`),n&&i.fragments.length>0&&qP(n,i),!this.canLoad||!i.live)return;let l,u,c;if(i.canBlockReload&&i.endSN&&i.advanced){const v=this.hls.config.lowLatencyMode,g=i.lastPartSn,y=i.endSN,x=i.lastPartIndex,S=x!==-1,T=g===y,C=v?0:x;S?(u=T?y+1:g,c=T?C:x+1):u=y+1;const _=i.age,b=_+i.ageHeader;let I=Math.min(b-i.partTarget,i.targetduration*1.5);if(I>0){if(n&&I>n.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${n.tuneInGoal} to: ${I} with playlist age: ${i.age}`),I=0;else{const A=Math.floor(I/i.targetduration);if(u+=A,c!==void 0){const k=Math.round(I%i.targetduration/i.partTarget);c+=k}this.log(`CDN Tune-in age: ${i.ageHeader}s last advanced ${_.toFixed(2)}s goal: ${I} skip sn ${A} to part ${c}`)}i.tuneInGoal=I}if(l=this.getDeliveryDirectives(i,r.deliveryDirectives,u,c),v||!T){this.loadPlaylist(l);return}}else(i.canBlockReload||i.canSkipUntil)&&(l=this.getDeliveryDirectives(i,r.deliveryDirectives,u,c));const d=this.hls.mainForwardBufferInfo,f=d?d.end-d.len:0,m=(i.edge-f)*1e3,h=JP(i,m);i.updated&&a>this.requestScheduled+h&&(this.requestScheduled=s.loading.start),u!==void 0&&i.canBlockReload?this.requestScheduled=s.loading.first+h-(i.partTarget*1e3||1e3):this.requestScheduled===-1||this.requestScheduled+hthis.loadPlaylist(l),p)}else this.clearTimer()}getDeliveryDirectives(e,r,n,i){let s=Rv(e);return r!=null&&r.skip&&e.deltaUpdateFailed&&(n=r.msn,i=r.part,s=Ou.No),new Iv(n,i,s)}checkRetry(e){const r=e.details,n=$c(e),i=e.errorAction,{action:s,retryCount:a=0,retryConfig:o}=i||{},l=!!i&&!!o&&(s===zt.RetryRequest||!i.resolved&&s===zt.SendAlternateToPenaltyBox);if(l){var u;if(this.requestScheduled=-1,a>=o.maxNumRetry)return!1;if(n&&(u=e.context)!=null&&u.deliveryDirectives)this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${r}" without delivery-directives`),this.loadPlaylist();else{const c=Rm(o,a);this.timer=self.setTimeout(()=>this.loadPlaylist(),c),this.warn(`Retrying playlist loading ${a+1}/${o.maxNumRetry} after "${r}" in ${c}ms`)}e.levelRetry=!0,i.resolved=!0}return l}}class Os{constructor(e,r=0,n=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=e,this.alpha_=e?Math.exp(Math.log(.5)/e):0,this.estimate_=r,this.totalWeight_=n}sample(e,r){const n=Math.pow(this.alpha_,e);this.estimate_=r*(1-n)+n*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_}}class oO{constructor(e,r,n,i=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=n,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new Os(e),this.fast_=new Os(r),this.defaultTTFB_=i,this.ttfb_=new Os(e)}update(e,r){const{slow_:n,fast_:i,ttfb_:s}=this;n.halfLife!==e&&(this.slow_=new Os(e,n.getEstimate(),n.getTotalWeight())),i.halfLife!==r&&(this.fast_=new Os(r,i.getEstimate(),i.getTotalWeight())),s.halfLife!==e&&(this.ttfb_=new Os(e,s.getEstimate(),s.getTotalWeight()))}sample(e,r){e=Math.max(e,this.minDelayMs_);const n=8*r,i=e/1e3,s=n/i;this.fast_.sample(i,s),this.slow_.sample(i,s)}sampleTTFB(e){const r=e/1e3,n=Math.sqrt(2)*Math.exp(-Math.pow(r,2)/2);this.ttfb_.sample(n,Math.max(e,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}destroy(){}}const DT={supported:!0,configurations:[],decodingInfoResults:[{supported:!0,powerEfficient:!0,smooth:!0}]},Mv={};function lO(t,e,r,n,i,s){const a=t.audioCodec?t.audioGroups:null,o=s==null?void 0:s.audioCodec,l=s==null?void 0:s.channels,u=l?parseInt(l):o?1/0:2;let c=null;if(a!=null&&a.length)try{a.length===1&&a[0]?c=e.groups[a[0]].channels:c=a.reduce((d,f)=>{if(f){const m=e.groups[f];if(!m)throw new Error(`Audio track group ${f} not found`);Object.keys(m.channels).forEach(h=>{d[h]=(d[h]||0)+m.channels[h]})}return d},{2:0})}catch{return!0}return t.videoCodec!==void 0&&(t.width>1920&&t.height>1088||t.height>1920&&t.width>1088||t.frameRate>Math.max(n,30)||t.videoRange!=="SDR"&&t.videoRange!==r||t.bitrate>Math.max(i,8e6))||!!c&&pe(u)&&Object.keys(c).some(d=>parseInt(d)>u)}function uO(t,e,r){const n=t.videoCodec,i=t.audioCodec;if(!n||!i||!r)return Promise.resolve(DT);const s={width:t.width,height:t.height,bitrate:Math.ceil(Math.max(t.bitrate*.9,t.averageBitrate)),framerate:t.frameRate||30},a=t.videoRange;a!=="SDR"&&(s.transferFunction=a.toLowerCase());const o=n.split(",").map(l=>({type:"media-source",video:jt(jt({},s),{},{contentType:pl(l,"video")})}));return i&&t.audioGroups&&t.audioGroups.forEach(l=>{var u;l&&((u=e.groups[l])==null||u.tracks.forEach(c=>{if(c.groupId===l){const d=c.channels||"",f=parseFloat(d);pe(f)&&f>2&&o.push.apply(o,i.split(",").map(m=>({type:"media-source",audio:{contentType:pl(m,"audio"),channels:""+f}})))}}))}),Promise.all(o.map(l=>{const u=cO(l);return Mv[u]||(Mv[u]=r.decodingInfo(l))})).then(l=>({supported:!l.some(u=>!u.supported),configurations:o,decodingInfoResults:l})).catch(l=>({supported:!1,configurations:o,decodingInfoResults:[],error:l}))}function cO(t){const{audio:e,video:r}=t,n=r||e;if(n){const i=n.contentType.split('"')[1];if(r)return`r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${i}_${Math.ceil(r.bitrate/1e5)}`;if(e)return`c${e.channels}${e.spatialRendering?"s":"n"}_${i}`}return""}function dO(){if(typeof matchMedia=="function"){const t=matchMedia("(dynamic-range: high)"),e=matchMedia("bad query");if(t.media!==e.media)return t.matches===!0}return!1}function fO(t,e){let r=!1,n=[];return t&&(r=t!=="SDR",n=[t]),e&&(n=e.allowedVideoRanges||Bc.slice(0),r=e.preferHDR!==void 0?e.preferHDR:dO(),r?n=n.filter(i=>i!=="SDR"):n=["SDR"]),{preferHDR:r,allowedVideoRanges:n}}function hO(t,e,r,n,i){const s=Object.keys(t),a=n==null?void 0:n.channels,o=n==null?void 0:n.audioCodec,l=a&&parseInt(a)===2;let u=!0,c=!1,d=1/0,f=1/0,m=1/0,h=0,p=[];const{preferHDR:v,allowedVideoRanges:g}=fO(e,i);for(let T=s.length;T--;){const C=t[s[T]];u=C.channels[2]>0,d=Math.min(d,C.minHeight),f=Math.min(f,C.minFramerate),m=Math.min(m,C.minBitrate);const _=g.filter(b=>C.videoRanges[b]>0);_.length>0&&(c=!0,p=_)}d=pe(d)?d:0,f=pe(f)?f:0;const y=Math.max(1080,d),x=Math.max(30,f);return m=pe(m)?m:r,r=Math.max(m,r),c||(e=void 0,p=[]),{codecSet:s.reduce((T,C)=>{const _=t[C];if(C===T)return T;if(_.minBitrate>r)return Wn(C,`min bitrate of ${_.minBitrate} > current estimate of ${r}`),T;if(!_.hasDefaultAudio)return Wn(C,"no renditions with default or auto-select sound found"),T;if(o&&C.indexOf(o.substring(0,4))%5!==0)return Wn(C,`audio codec preference "${o}" not found`),T;if(a&&!l){if(!_.channels[a])return Wn(C,`no renditions with ${a} channel sound found (channels options: ${Object.keys(_.channels)})`),T}else if((!o||l)&&u&&_.channels[2]===0)return Wn(C,"no renditions with stereo sound found"),T;return _.minHeight>y?(Wn(C,`min resolution of ${_.minHeight} > maximum of ${y}`),T):_.minFramerate>x?(Wn(C,`min framerate of ${_.minFramerate} > maximum of ${x}`),T):p.some(b=>_.videoRanges[b]>0)?_.maxScore=Fc(T)||_.fragmentError>t[T].fragmentError)?T:(h=_.maxScore,C):(Wn(C,`no variants with VIDEO-RANGE of ${JSON.stringify(p)} found`),T)},void 0),videoRanges:p,preferHDR:v,minFramerate:f,minBitrate:m}}function Wn(t,e){U.log(`[abr] start candidates with "${t}" ignored because ${e}`)}function pO(t){return t.reduce((e,r)=>{let n=e.groups[r.groupId];n||(n=e.groups[r.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),n.tracks.push(r);const i=r.channels||"2";return n.channels[i]=(n.channels[i]||0)+1,n.hasDefault=n.hasDefault||r.default,n.hasAutoSelect=n.hasAutoSelect||r.autoselect,n.hasDefault&&(e.hasDefaultAudio=!0),n.hasAutoSelect&&(e.hasAutoSelectAudio=!0),e},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function mO(t,e,r,n){return t.slice(r,n+1).reduce((i,s)=>{if(!s.codecSet)return i;const a=s.audioGroups;let o=i[s.codecSet];o||(i[s.codecSet]=o={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!a,fragmentError:0}),o.minBitrate=Math.min(o.minBitrate,s.bitrate);const l=Math.min(s.height,s.width);return o.minHeight=Math.min(o.minHeight,l),o.minFramerate=Math.min(o.minFramerate,s.frameRate),o.maxScore=Math.max(o.maxScore,s.score),o.fragmentError+=s.fragmentError,o.videoRanges[s.videoRange]=(o.videoRanges[s.videoRange]||0)+1,a&&a.forEach(u=>{if(!u)return;const c=e.groups[u];c&&(o.hasDefaultAudio=o.hasDefaultAudio||e.hasDefaultAudio?c.hasDefault:c.hasAutoSelect||!e.hasDefaultAudio&&!e.hasAutoSelectAudio,Object.keys(c.channels).forEach(d=>{o.channels[d]=(o.channels[d]||0)+c.channels[d]}))}),i},{})}function Dn(t,e,r){if("attrs"in t){const n=e.indexOf(t);if(n!==-1)return n}for(let n=0;nn.indexOf(i)===-1)}function Ms(t,e){const{audioCodec:r,channels:n}=t;return(r===void 0||(e.audioCodec||"").substring(0,4)===r.substring(0,4))&&(n===void 0||n===(e.channels||"2"))}function vO(t,e,r,n,i){const s=e[n],o=e.reduce((f,m,h)=>{const p=m.uri;return(f[p]||(f[p]=[])).push(h),f},{})[s.uri];o.length>1&&(n=Math.max.apply(Math,o));const l=s.videoRange,u=s.frameRate,c=s.codecSet.substring(0,4),d=Nv(e,n,f=>{if(f.videoRange!==l||f.frameRate!==u||f.codecSet.substring(0,4)!==c)return!1;const m=f.audioGroups,h=r.filter(p=>!m||m.indexOf(p.groupId)!==-1);return Dn(t,h,i)>-1});return d>-1?d:Nv(e,n,f=>{const m=f.audioGroups,h=r.filter(p=>!m||m.indexOf(p.groupId)!==-1);return Dn(t,h,i)>-1})}function Nv(t,e,r){for(let n=e;n;n--)if(r(t[n]))return n;for(let n=e+1;n{const{fragCurrent:r,partCurrent:n,hls:i}=this,{autoLevelEnabled:s,media:a}=i;if(!r||!a)return;const o=performance.now(),l=n?n.stats:r.stats,u=n?n.duration:r.duration,c=o-l.loading.start,d=i.minAutoLevel;if(l.aborted||l.loaded&&l.loaded===l.total||r.level<=d){this.clearTimer(),this._nextAutoLevel=-1;return}if(!s||a.paused||!a.playbackRate||!a.readyState)return;const f=i.mainForwardBufferInfo;if(f===null)return;const m=this.bwEstimator.getEstimateTTFB(),h=Math.abs(a.playbackRate);if(c<=Math.max(m,1e3*(u/(h*2))))return;const p=f.len/h,v=l.loading.first?l.loading.first-l.loading.start:-1,g=l.loaded&&v>-1,y=this.getBwEstimate(),x=i.levels,S=x[r.level],T=l.total||Math.max(l.loaded,Math.round(u*S.averageBitrate/8));let C=g?c-v:c;C<1&&g&&(C=Math.min(c,l.loaded*8/y));const _=g?l.loaded*1e3/C:0,b=_?(T-l.loaded)/_:T*8/y+m/1e3;if(b<=p)return;const I=_?_*8:y;let A=Number.POSITIVE_INFINITY,k;for(k=r.level-1;k>d;k--){const P=x[k].maxBitrate;if(A=this.getTimeToLoadFrag(m/1e3,I,u*P,!x[k].details),A=b||A>u*10)return;i.nextLoadLevel=i.nextAutoLevel=k,g?this.bwEstimator.sample(c-Math.min(m,v),l.loaded):this.bwEstimator.sampleTTFB(c);const O=x[k].maxBitrate;this.getBwEstimate()*this.hls.config.abrBandWidthUpFactor>O&&this.resetEstimator(O),this.clearTimer(),U.warn(`[abr] Fragment ${r.sn}${n?" part "+n.index:""} of level ${r.level} is loading too slowly; Time to underbuffer: ${p.toFixed(3)} s Estimated load time for current fragment: ${b.toFixed(3)} s Estimated load time for down switch fragment: ${A.toFixed(3)} s TTFB estimate: ${v|0} ms Current BW estimate: ${pe(y)?y|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps - Switching to level ${k} @ ${O|0} bps`),i.trigger(w.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(U.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 lO(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.FRAG_LOADING,this.onFragLoading,this),e.on(w.FRAG_LOADED,this.onFragLoaded,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this),e.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(w.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.FRAG_LOADING,this.onFragLoading,this),e.off(w.FRAG_LOADED,this.onFragLoaded,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this),e.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(w.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(w.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,r){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,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,r){const n=r.frag;if(!this.ignoreFragment(n)){if(!n.bitrateTest){var i;this.fragCurrent=n,this.partCurrent=(i=r.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,r){this.clearTimer()}onError(e,r){if(!r.fatal)switch(r.details){case z.BUFFER_ADD_CODEC_ERROR:case z.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case z.FRAG_LOAD_TIMEOUT:{const n=r.frag,{fragCurrent:i,partCurrent:s}=this;if(n&&i&&n.sn===i.sn&&n.level===i.level){const a=performance.now(),o=s?s.stats:n.stats,l=a-o.loading.start,u=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&u>-1){const d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(d,u),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,r,n,i){const s=e+n/r,a=i?this.lastLevelLoadSec:0;return s+a}onLevelLoaded(e,r){const n=this.hls.config,{loading:i}=r.stats,s=i.end-i.start;pe(s)&&(this.lastLevelLoadSec=s/1e3),r.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD)}onFragLoaded(e,{frag:r,part:n}){const i=n?n.stats:r.stats;if(r.type===we.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const s=n?n.duration:r.duration,a=this.hls.levels[r.level],o=(a.loaded?a.loaded.bytes:0)+i.loaded,l=(a.loaded?a.loaded.duration:0)+s;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(r.bitrateTest){const s={stats:i,frag:r,part:n,id:r.type};this.onFragBuffered(w.FRAG_BUFFERED,s),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}onFragBuffered(e,r){const{frag:n,part:i}=r,s=i!=null&&i.stats.loaded?i.stats:n.stats;if(s.aborted||this.ignoreFragment(n))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(),n.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==we.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:r}=this.hls,n=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,s=this.findBestLevel(n,r,e,0,i,1,1);if(s>-1)return s;const a=this.hls.firstLevel,o=Math.min(Math.max(a,r),e);return U.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,n=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!n||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const s=n&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,s)&&a[e].loadError<=a[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:r,hls:n}=this,{maxAutoLevel:i,config:s,minAutoLevel:a}=n,o=r?r.duration:e?e.duration:0,l=this.getBwEstimate(),u=this.getStarvationDelay();let c=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(u){const v=this.findBestLevel(l,a,i,u,0,c,d);if(v>=0)return v}let f=o?Math.min(o,s.maxStarvationDelay):s.maxStarvationDelay;if(!u){const v=this.bitrateTestDelay;v&&(f=(o?Math.min(o,s.maxLoadingDelay):s.maxLoadingDelay)-v,U.info(`[abr] bitrate test took ${Math.round(1e3*v)}ms, set first fragment max fetchDuration to ${Math.round(1e3*f)} ms`),c=d=1)}const m=this.findBestLevel(l,a,i,u,f,c,d);if(U.info(`[abr] ${u?"rebuffering expected":"buffer is empty"}, optimal quality level ${m}`),m>-1)return m;const h=n.levels[a],p=n.levels[n.loadLevel];return(h==null?void 0:h.bitrate)<(p==null?void 0:p.bitrate)?a:n.loadLevel}getStarvationDelay(){const e=this.hls,r=e.media;if(!r)return 1/0;const n=r&&r.playbackRate!==0?Math.abs(r.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/n}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,r,n,i,s,a,o){var l;const u=i+s,c=this.lastLoadedFragLevel,d=c===-1?this.hls.firstLevel:c,{fragCurrent:f,partCurrent:m}=this,{levels:h,allAudioTracks:p,loadLevel:v,config:g}=this.hls;if(h.length===1)return 0;const y=h[d],x=!!(y!=null&&(l=y.details)!=null&&l.live),S=v===-1||c===-1;let T,C="SDR",_=(y==null?void 0:y.frameRate)||0;const{audioPreference:b,videoPreference:I}=g,A=this.audioTracksByGroup||(this.audioTracksByGroup=mO(p));if(S){if(this.firstSelection!==-1)return this.firstSelection;const K=this.codecTiers||(this.codecTiers=gO(h,A,r,n)),H=pO(K,C,e,b,I),{codecSet:se,videoRanges:W,minFramerate:F,minBitrate:j,preferHDR:te}=H;T=se,C=te?W[W.length-1]:W[0],_=F,e=Math.max(e,j),U.log(`[abr] picked start tier ${JSON.stringify(H)}`)}else T=y==null?void 0:y.codecSet,C=y==null?void 0:y.videoRange;const k=m?m.duration:f?f.duration:0,O=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let K=n;K>=r;K--){var G;const H=h[K],se=K>d;if(!H)continue;if(g.useMediaCapabilities&&!H.supportedResult&&!H.supportedPromise){const ye=navigator.mediaCapabilities;typeof(ye==null?void 0:ye.decodingInfo)=="function"&&uO(H,A,C,_,e,b)?(H.supportedPromise=cO(H,A,ye),H.supportedPromise.then(Re=>{if(!this.hls)return;H.supportedResult=Re;const Ee=this.hls.levels,Fe=Ee.indexOf(H);Re.error?U.warn(`[abr] MediaCapabilities decodingInfo error: "${Re.error}" for level ${Fe} ${JSON.stringify(Re)}`):Re.supported||(U.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${Fe} ${JSON.stringify(Re)}`),Fe>-1&&Ee.length>1&&(U.log(`[abr] Removing unsupported level ${Fe}`),this.hls.removeLevel(Fe)))})):H.supportedResult=DT}if(T&&H.codecSet!==T||C&&H.videoRange!==C||se&&_>H.frameRate||!se&&_>0&&_=k*2&&s===0?h[K].averageBitrate:h[K].maxBitrate,ee=this.getTimeToLoadFrag(O,j,te*F,W===void 0);if(j>=te&&(K===c||H.loadError===0&&H.fragmentError===0)&&(ee<=O||!pe(ee)||x&&!this.bitrateTestDelay||ee${K} adjustedbw(${Math.round(j)})-bitrate=${Math.round(j-te)} ttfb:${O.toFixed(1)} avgDuration:${F.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${ee.toFixed(1)} firstSelection:${S} codecSet:${T} videoRange:${C} hls.loadLevel:${v}`)),S&&(this.firstSelection=K),K}}return-1}set nextAutoLevel(e){const{maxAutoLevel:r,minAutoLevel:n}=this.hls,i=Math.min(Math.max(e,n),r);this._nextAutoLevel!==i&&(this.nextAutoLevelKey="",this._nextAutoLevel=i)}}class SO{constructor(){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(){}}var Bt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class EO{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.on(w.BUFFER_APPENDED,this.onBufferAppended,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this),e.on(w.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(w.BUFFER_APPENDED,this.onBufferAppended,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this),e.off(w.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,r){const n=this.activePartLists[r];if(n)for(let i=n.length;i--;){const s=n[i];if(!s)break;const a=s.end;if(s.start<=e&&a!==null&&e<=a)return s}return this.getBufferedFrag(e,r)}getBufferedFrag(e,r){const{fragments:n}=this,i=Object.keys(n);for(let s=i.length;s--;){const a=n[i[s]];if((a==null?void 0:a.body.type)===r&&a.buffered){const o=a.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,r,n,i){this.timeRanges&&(this.timeRanges[e]=r);const s=(i==null?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||s>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===n&&this.removeFragment(o.body);return}const l=o.range[e];l&&l.time.some(u=>{const c=!this.isTimeBuffered(u.startPTS,u.endPTS,r);return c&&this.removeFragment(o.body),c})})}detectPartialFragments(e){const r=this.timeRanges,{frag:n,part:i}=e;if(!r||n.sn==="initSegment")return;const s=Ns(n),a=this.fragments[s];if(!a||a.buffered&&n.gap)return;const o=!n.relurl;Object.keys(r).forEach(l=>{const u=n.elementaryStreams[l];if(!u)return;const c=r[l],d=o||u.partial===!0;a.range[l]=this.getBufferedTimes(n,i,d,c)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=n.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),iu(a)||this.removeParts(n.sn-1,n.type)):this.removeFragment(a.body)}removeParts(e,r){const n=this.activePartLists[r];n&&(this.activePartLists[r]=n.filter(i=>i.fragment.sn>=e))}fragBuffered(e,r){const n=Ns(e);let i=this.fragments[n];!i&&r&&(i=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(e,r,n,i){const s={time:[],partial:n},a=e.start,o=e.end,l=e.minEndPTS||o,u=e.maxStartPTS||a;for(let c=0;c=d&&l<=f){s.time.push({startPTS:Math.max(a,i.start(c)),endPTS:Math.min(o,i.end(c))});break}else if(ad){const m=Math.max(a,i.start(c)),h=Math.min(o,i.end(c));h>m&&(s.partial=!0,s.time.push({startPTS:m,endPTS:h}))}else if(o<=d)break}return s}getPartialFragment(e){let r=null,n,i,s,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(u=>{const c=l[u];c&&iu(c)&&(i=c.body.start-o,s=c.body.end+o,e>=i&&e<=s&&(n=Math.min(e-i,s-e),a<=n&&(r=c.body,a=n)))}),r}isEndListAppended(e){const r=this.endListFragments[e];return r!==void 0&&(r.buffered||iu(r))}getState(e){const r=Ns(e),n=this.fragments[r];return n?n.buffered?iu(n)?Bt.PARTIAL:Bt.OK:Bt.APPENDING:Bt.NOT_LOADED}isTimeBuffered(e,r,n){let i,s;for(let a=0;a=i&&r<=s)return!0;if(r<=i)return!1}return!1}onFragLoaded(e,r){const{frag:n,part:i}=r;if(n.sn==="initSegment"||n.bitrateTest)return;const s=i?null:r,a=Ns(n);this.fragments[a]={body:n,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,r){const{frag:n,part:i,timeRanges:s}=r;if(n.sn==="initSegment")return;const a=n.type;if(i){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(i)}this.timeRanges=s,Object.keys(s).forEach(o=>{const l=s[o];this.detectEvictedFragments(o,l,a,i)})}onFragBuffered(e,r){this.detectPartialFragments(r)}hasFragment(e){const r=Ns(e);return!!this.fragments[r]}hasParts(e){var r;return!!((r=this.activePartLists[e])!=null&&r.length)}removeFragmentsInRange(e,r,n,i,s){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==n||i&&!l.gap||l.starte&&(o.buffered||s)&&this.removeFragment(l)})}removeFragment(e){const r=Ns(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const n=this.activePartLists[e.type];if(n){const i=e.sn;this.activePartLists[e.type]=n.filter(s=>s.fragment.sn!==i)}delete this.fragments[r],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function iu(t){var e,r,n;return t.buffered&&(t.body.gap||((e=t.range.video)==null?void 0:e.partial)||((r=t.range.audio)==null?void 0:r.partial)||((n=t.range.audiovideo)==null?void 0:n.partial))}function Ns(t){return`${t.type}_${t.level}_${t.sn}`}const TO={length:0,start:()=>0,end:()=>0};class at{static isBuffered(e,r){try{if(e){const n=at.getBuffered(e);for(let i=0;i=n.start(i)&&r<=n.end(i))return!0}}catch{}return!1}static bufferInfo(e,r,n){try{if(e){const i=at.getBuffered(e),s=[];let a;for(a=0;ad&&(i[c-1].end=e[u].end):i.push(e[u])}else i.push(e[u])}else i=e;let s=0,a,o=r,l=r;for(let u=0;u=c&&rr.startCC||t&&t.cc{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(m=>m[0]==="GAP")){l($v(e));return}else e.gap=!1;const u=this.loader=e.loader=s?new s(i):new a(i),c=Bv(e),d=Ov(i.fragLoadPolicy.default),f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Uv};e.stats=u.stats,u.load(c,f,{onSuccess:(m,h,p,v)=>{this.resetLoader(e,u);let g=m.data;p.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(g.slice(0,16)),g=g.slice(16)),o({frag:e,part:null,payload:g,networkDetails:v})},onError:(m,h,p,v)=>{this.resetLoader(e,u),l(new Zn({type:_e.NETWORK_ERROR,details:z.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:jt({url:n,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:p,stats:v}))},onAbort:(m,h,p)=>{this.resetLoader(e,u),l(new Zn({type:_e.NETWORK_ERROR,details:z.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:p,stats:m}))},onTimeout:(m,h,p)=>{this.resetLoader(e,u),l(new Zn({type:_e.NETWORK_ERROR,details:z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:p,stats:m}))},onProgress:(m,h,p,v)=>{r&&r({frag:e,part:null,payload:p,networkDetails:v})}})})}loadPart(e,r,n){this.abort();const i=this.config,s=i.fLoader,a=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||r.gap){l($v(e,r));return}const u=this.loader=e.loader=s?new s(i):new a(i),c=Bv(e,r),d=Ov(i.fragLoadPolicy.default),f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Uv};r.stats=u.stats,u.load(c,f,{onSuccess:(m,h,p,v)=>{this.resetLoader(e,u),this.updateStatsFromPart(e,r);const g={frag:e,part:r,payload:m.data,networkDetails:v};n(g),o(g)},onError:(m,h,p,v)=>{this.resetLoader(e,u),l(new Zn({type:_e.NETWORK_ERROR,details:z.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:r,response:jt({url:c.url,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:p,stats:v}))},onAbort:(m,h,p)=>{e.stats.aborted=r.stats.aborted,this.resetLoader(e,u),l(new Zn({type:_e.NETWORK_ERROR,details:z.INTERNAL_ABORTED,fatal:!1,frag:e,part:r,error:new Error("Aborted"),networkDetails:p,stats:m}))},onTimeout:(m,h,p)=>{this.resetLoader(e,u),l(new Zn({type:_e.NETWORK_ERROR,details:z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:r,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:p,stats:m}))}})})}updateStatsFromPart(e,r){const n=e.stats,i=r.stats,s=i.total;if(n.loaded+=i.loaded,s){const l=Math.round(e.duration/r.duration),u=Math.min(Math.round(n.loaded/s),l),d=(l-u)*Math.round(n.loaded/u);n.total=n.loaded+d}else n.total=Math.max(n.loaded,n.total);const a=n.loading,o=i.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,r){e.loader=null,this.loader===r&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),r.destroy()}}function Bv(t,e=null){const r=e||t,n={frag:t,part:e,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},i=r.byteRangeStartOffset,s=r.byteRangeEndOffset;if(pe(i)&&pe(s)){var a;let o=i,l=s;if(t.sn==="initSegment"&&((a=t.decryptdata)==null?void 0:a.method)==="AES-128"){const u=s-i;u%16&&(l=s+(16-u%16)),i!==0&&(n.resetIV=!0,o=i-16)}n.rangeStart=o,n.rangeEnd=l}return n}function $v(t,e){const r=new Error(`GAP ${t.gap?"tag":"attribute"} found`),n={type:_e.MEDIA_ERROR,details:z.FRAG_GAP,fatal:!1,frag:t,error:r,networkDetails:null};return e&&(n.part=e),(e||t).stats.aborted=!0,new Zn(n)}class Zn extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class CO{constructor(e,r){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=r}decrypt(e,r){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},r,e)}}class RO{constructor(e,r){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=r}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function IO(t){const e=t.byteLength,r=e&&new DataView(t.buffer).getUint8(e-1);return r?hs(t,0,e-r):t}class kO{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 r=new DataView(e),n=new Uint32Array(4);for(let i=0;i<4;i++)n[i]=r.getUint32(i*4);return n}initTable(){const e=this.sBox,r=this.invSBox,n=this.subMix,i=n[0],s=n[1],a=n[2],o=n[3],l=this.invSubMix,u=l[0],c=l[1],d=l[2],f=l[3],m=new Uint32Array(256);let h=0,p=0,v=0;for(v=0;v<256;v++)v<128?m[v]=v<<1:m[v]=v<<1^283;for(v=0;v<256;v++){let g=p^p<<1^p<<2^p<<3^p<<4;g=g>>>8^g&255^99,e[h]=g,r[g]=h;const y=m[h],x=m[y],S=m[x];let T=m[g]*257^g*16843008;i[h]=T<<24|T>>>8,s[h]=T<<16|T>>>16,a[h]=T<<8|T>>>24,o[h]=T,T=S*16843009^x*65537^y*257^h*16843008,u[g]=T<<24|T>>>8,c[g]=T<<16|T>>>16,d[g]=T<<8|T>>>24,f[g]=T,h?(h=y^m[m[m[S^y]]],p^=m[m[p]]):h=p=1}}expandKey(e){const r=this.uint8ArrayToUint32Array_(e);let n=!0,i=0;for(;ithis.subtle?(this.logOnce("WebCrypto AES decrypt"),new CO(this.subtle,new Uint8Array(n)).decrypt(e.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(U.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,r,n)))}onWebCryptoError(e,r,n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,r,n);const i=this.flush();if(i)return i.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let r=e;const n=e.length-e.length%DO;return n!==e.length&&(r=hs(e,0,n),this.remainderData=hs(e,n)),r}logOnce(e){this.logEnabled&&(U.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const PO={toString:function(t){let e="";const r=t.length;for(let n=0;no.end){const d=a>c;(a{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${s.part?" p: "+s.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(s)};this._doFragLoad(e,r,n,i).then(s=>{if(!s)return;const a=this.state;if(this.fragContextChanged(e)){(a===Y.FRAG_LOADING||!this.fragCurrent&&a===Y.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=Y.IDLE);return}"payload"in s&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(w.FRAG_LOADED,s)),this._handleFragmentLoadComplete(s)}).catch(s=>{this.state===Y.STOPPED||this.state===Y.ERROR||(this.warn(`Frag error: ${(s==null?void 0:s.message)||s}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var r;const{fragmentTracker:n}=this;if(n.getState(e)===Bt.APPENDING){const s=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,s),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&n.removeFragment(e)}else((r=this.mediaBuffer)==null?void 0:r.buffered.length)===0?n.removeAllFragments():n.hasParts(e.type)&&(n.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),n.getState(e)===Bt.PARTIAL&&n.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const r=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,r,n=null){if(!(e-r))return;const i={startOffset:e,endOffset:r,type:n};this.hls.trigger(w.BUFFER_FLUSHING,i)}_loadInitSegment(e,r){this._doFragLoad(e,r).then(n=>{if(!n||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return n}).then(n=>{const{hls:i}=this,{payload:s}=n,a=e.decryptdata;if(s&&s.byteLength>0&&a!=null&&a.key&&a.iv&&a.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(s),a.key.buffer,a.iv.buffer).catch(l=>{throw i.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const u=self.performance.now();return i.trigger(w.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:o,tdecrypt:u}}),n.payload=l,this.completeInitSegmentLoad(n)})}return this.completeInitSegmentLoad(n)}).catch(n=>{this.state===Y.STOPPED||this.state===Y.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:r}=this;if(!r)throw new Error("init load aborted, missing levels");const n=e.frag.stats;this.state=Y.IDLE,e.frag.data=new Uint8Array(e.payload),n.parsing.start=n.buffering.start=self.performance.now(),n.parsing.end=n.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:r}=this;return!e||!r||e.sn!==r.sn||e.level!==r.level}fragBufferedComplete(e,r){var n,i,s,a;const o=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${r?" part: "+r.index:""} of ${this.playlistType===we.MAIN?"level":"track"} ${e.level} (frag:[${((n=e.startPTS)!=null?n:NaN).toFixed(3)}-${((i=e.endPTS)!=null?i:NaN).toFixed(3)}] > buffer:${o?PO.toString(at.getBuffered(o)):"(detached)"})`),e.sn!=="initSegment"){var l;if(e.type!==we.SUBTITLE){const c=e.elementaryStreams;if(!Object.keys(c).some(d=>!!c[d])){this.state=Y.IDLE;return}}const u=(l=this.levels)==null?void 0:l[e.level];u!=null&&u.fragmentError&&(this.log(`Resetting level fragment error count of ${u.fragmentError} on frag buffered`),u.fragmentError=0)}this.state=Y.IDLE,o&&(!this.loadedmetadata&&e.type==we.MAIN&&o.buffered.length&&((s=this.fragCurrent)==null?void 0:s.sn)===((a=this.fragPrevious)==null?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:r}=this;if(!r)return;const{frag:n,part:i,partsLoaded:s}=e,a=!s||s.length===0||s.some(l=>!l),o=new km(n.level,n.sn,n.stats.chunkCount+1,0,i?i.index:-1,!a);r.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,r,n=null,i){var s;const a=r==null?void 0:r.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((s=e.decryptdata)!=null&&s.key)?(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=Y.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(c=>{if(!this.fragContextChanged(c.frag))return this.hls.trigger(w.KEY_LOADED,c),this.state===Y.KEY_LOADING&&(this.state=Y.IDLE),c}),this.hls.trigger(w.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments),n=Math.max(e.start,n||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const c=a.partList;if(c&&i){n>e.end&&a.fragmentHint&&(e=a.fragmentHint);const d=this.getNextPart(c,e,n);if(d>-1){const f=c[d];this.log(`Loading part sn: ${e.sn} p: ${f.index} cc: ${e.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${d}-${c.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=Y.FRAG_LOADING;let m;return o?m=o.then(h=>!h||this.fragContextChanged(h.frag)?null:this.doFragPartsLoad(e,f,r,i)).catch(h=>this.handleFragLoadError(h)):m=this.doFragPartsLoad(e,f,r,i).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(w.FRAG_LOADING,{frag:e,part:f,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):m}else if(!e.url||this.loadedEndOfParts(c,n))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${a?"of ["+a.startSN+"-"+a.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(n.toFixed(3))}`),pe(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Y.FRAG_LOADING;const l=this.config.progressive;let u;return l&&o?u=o.then(c=>!c||this.fragContextChanged(c==null?void 0:c.frag)?null:this.fragmentLoader.load(e,i)).catch(c=>this.handleFragLoadError(c)):u=Promise.all([this.fragmentLoader.load(e,l?i:void 0),o]).then(([c])=>(!l&&c&&i&&i(c),c)).catch(c=>this.handleFragLoadError(c)),this.hls.trigger(w.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,r,n,i){return new Promise((s,a)=>{var o;const l=[],u=(o=n.details)==null?void 0:o.partList,c=d=>{this.fragmentLoader.loadPart(e,d,i).then(f=>{l[d.index]=f;const m=f.part;this.hls.trigger(w.FRAG_LOADED,f);const h=Dv(n,e.sn,d.index+1)||RT(u,e.sn,d.index+1);if(h)c(h);else return s({frag:e,part:m,partsLoaded:l})}).catch(a)};c(r)})}handleFragLoadError(e){if("data"in e){const r=e.data;e.data&&r.details===z.INTERNAL_ABORTED?this.handleFragLoadAborted(r.frag,r.part):this.hls.trigger(w.ERROR,r)}else this.hls.trigger(w.ERROR,{type:_e.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const r=this.getCurrentContext(e);if(!r||this.state!==Y.PARSING){!this.fragCurrent&&this.state!==Y.STOPPED&&this.state!==Y.ERROR&&(this.state=Y.IDLE);return}const{frag:n,part:i,level:s}=r,a=self.performance.now();n.stats.parsing.end=a,i&&(i.stats.parsing.end=a),this.updateLevelTiming(n,i,s,e.partial)}getCurrentContext(e){const{levels:r,fragCurrent:n}=this,{level:i,sn:s,part:a}=e;if(!(r!=null&&r[i]))return this.warn(`Levels object was unset while buffering fragment ${s} of level ${i}. The current chunk will not be buffered.`),null;const o=r[i],l=a>-1?Dv(o,s,a):null,u=l?l.fragment:tO(o,s,n);return u?(n&&n!==u&&(u.stats=n.stats),{frag:u,part:l,level:o}):null}bufferFragmentData(e,r,n,i,s){var a;if(!e||this.state!==Y.PARSING)return;const{data1:o,data2:l}=e;let u=o;if(o&&l&&(u=Jr(o,l)),!((a=u)!=null&&a.length))return;const c={type:e.type,frag:r,part:n,chunkMeta:i,parent:r.type,data:u};if(this.hls.trigger(w.BUFFER_APPENDING,c),e.dropped&&e.independent&&!n){if(s)return;this.flushBufferGap(r)}}flushBufferGap(e){const r=this.media;if(!r)return;if(!at.isBuffered(r,r.currentTime)){this.flushMainBuffer(0,e.start);return}const n=r.currentTime,i=at.bufferInfo(r,n,0),s=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,s*.25),o=Math.max(Math.min(e.start-a,i.end-a),n+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,r){const n=this.getLoadPosition();return pe(n)?this.getFwdBufferInfoAtPos(e,n,r):null}getFwdBufferInfoAtPos(e,r,n){const{config:{maxBufferHole:i}}=this,s=at.bufferInfo(e,r,i);if(s.len===0&&s.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(r,n);if(a&&s.nextStart=i?(n.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0):!1}getAppendedFrag(e,r=we.MAIN){const n=this.fragmentTracker.getAppendedFrag(e,we.MAIN);return n&&"fragment"in n?n.fragment:n}getNextFragment(e,r){const n=r.fragments,i=n.length;if(!i)return null;const{config:s}=this,a=n[0].start;let o;if(r.live){const l=s.initialLiveManifestSize;if(ir}getNextFragmentLoopLoading(e,r,n,i,s){const a=e.gap,o=this.getNextFragment(this.nextLoadPosition,r);if(o===null)return o;if(e=o,a&&e&&!e.gap&&n.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,n.nextStart,i);if(l!==null&&n.len+l.len>=s)return this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,r,n){let i=-1,s=!1,a=!0;for(let o=0,l=e.length;o-1&&nn.start&&n.loaded}getInitialLiveFragment(e,r){const n=this.fragPrevious;let i=null;if(n){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`),i=nO(r,n.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const s=n.sn+1;if(s>=e.startSN&&s<=e.endSN){const a=r[s-e.startSN];n.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=aO(r,n.cc),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const s=this.hls.liveSyncPosition;s!==null&&(i=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,r,n){const{config:i}=this;let{fragPrevious:s}=this,{fragments:a,endSN:o}=n;const{fragmentHint:l}=n,{maxFragLookUpTolerance:u}=i,c=n.partList,d=!!(i.lowLatencyMode&&c!=null&&c.length&&l);d&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn);let f;if(er-u?0:u;f=Vc(s,a,e,m)}else f=a[a.length-1];if(f){const m=f.sn-n.startSN,h=this.fragmentTracker.getState(f);if((h===Bt.OK||h===Bt.PARTIAL&&f.gap)&&(s=f),s&&f.sn===s.sn&&(!d||c[0].fragment.sn>f.sn)&&s&&f.level===s.level){const v=a[m+1];f.sn=a-r.maxFragLookUpTolerance&&s<=o;if(i!==null&&n.duration>i&&(s${e.startSN} prev-sn: ${l?l.sn:"na"} fragments: ${i}`),u}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,r){let n=this.startPosition;if(n ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const s=r.details===z.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(n,!0);const a=r.errorAction,{action:o,retryCount:l=0,retryConfig:u}=a||{};if(a&&o===zt.RetryRequest&&u){this.resetStartWhenNotLoaded(this.levelLastLoaded);const c=Rm(u,l);this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${r.details}, retrying loading ${l+1}/${u.maxNumRetry} in ${c}ms`),a.resolved=!0,this.retryDate=self.performance.now()+c,this.state=Y.FRAG_LOADING_WAITING_RETRY}else if(u&&a)if(this.resetFragmentErrors(e),l.5;s&&this.reduceMaxBufferLength(i.len,(r==null?void 0:r.duration)||10);const a=!s;return a&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${n} buffer`),r&&(this.fragmentTracker.removeFragment(r),this.nextLoadPosition=r.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===we.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Y.STOPPED&&(this.state=Y.IDLE)}afterBufferFlushed(e,r,n){if(!e)return;const i=at.getBuffered(e);this.fragmentTracker.detectEvictedFragments(r,i,n),this.state===Y.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Y.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const r=e?e.details:null;r!=null&&r.live?(this.startPosition=-1,this.setStartPosition(r,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,r,n,i){var s;const a=n.details;if(!a){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,u)=>{const c=e.elementaryStreams[u];if(c){const d=c.endPTS-c.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${e.sn} ${u} duration reliably (${d})`),l||!1;const f=i?0:_T(a,e,c.startPTS,c.endPTS,c.startDTS,c.endDTS);return this.hls.trigger(w.LEVEL_PTS_UPDATED,{details:a,level:n,drift:f,type:u,frag:e,start:c.startPTS,end:c.endPTS}),!0}return l},!1)&&((s=this.transmuxer)==null?void 0:s.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(n.fragmentError===0&&(n.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=Y.PARSED,this.hls.trigger(w.FRAG_PARSED,{frag:e,part:r})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const r=this._state;r!==e&&(this._state=e,this.log(`${r}->${e}`))}get state(){return this._state}}class OT{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:r}=this;let n;if(e.length)e.length===1?n=e[0]:n=OO(e,r);else return new Uint8Array(0);return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}}function OO(t,e){const r=new Uint8Array(e);let n=0;for(let i=0;i0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:dn.audioId3,duration:Number.POSITIVE_INFINITY});i{if(pe(t))return t*90;const n=r?r.baseTime*9e4/r.timescale:0;return e*9e4+n};function BO(t,e,r,n){let i,s,a,o;const l=navigator.userAgent.toLowerCase(),u=n,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=((e[r+2]&192)>>>6)+1;const d=(e[r+2]&60)>>>2;if(d>c.length-1){const f=new Error(`invalid ADTS sampling index:${d}`);t.emit(w.ERROR,w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}return a=(e[r+2]&1)<<2,a|=(e[r+3]&192)>>>6,U.log(`manifest codec:${n}, ADTS type:${i}, samplingIndex:${d}`),/firefox/i.test(l)?d>=6?(i=5,o=new Array(4),s=d-3):(i=2,o=new Array(2),s=d):l.indexOf("android")!==-1?(i=2,o=new Array(2),s=d):(i=5,o=new Array(4),n&&(n.indexOf("mp4a.40.29")!==-1||n.indexOf("mp4a.40.5")!==-1)||!n&&d>=6?s=d-3:((n&&n.indexOf("mp4a.40.2")!==-1&&(d>=6&&a===1||/vivaldi/i.test(l))||!n&&a===1)&&(i=2,o=new Array(2)),s=d)),o[0]=i<<3,o[0]|=(d&14)>>1,o[1]|=(d&1)<<7,o[1]|=a<<3,i===5&&(o[1]|=(s&14)>>1,o[2]=(s&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:c[d],channelCount:a,codec:"mp4a.40."+i,manifestCodec:u}}function MT(t,e){return t[e]===255&&(t[e+1]&246)===240}function NT(t,e){return t[e+1]&1?7:9}function Mm(t,e){return(t[e+3]&3)<<11|t[e+4]<<3|(t[e+5]&224)>>>5}function $O(t,e){return e+5=t.length)return!1;const n=Mm(t,e);if(n<=r)return!1;const i=e+n;return i===t.length||zc(t,i)}return!1}function FT(t,e,r,n,i){if(!t.samplerate){const s=BO(e,r,n,i);if(!s)return;t.config=s.config,t.samplerate=s.samplerate,t.channelCount=s.channelCount,t.codec=s.codec,t.manifestCodec=s.manifestCodec,U.log(`parsed codec:${t.codec}, rate:${s.samplerate}, channels:${s.channelCount}`)}}function UT(t){return 1024*9e4/t}function GO(t,e){const r=NT(t,e);if(e+r<=t.length){const n=Mm(t,e)-r;if(n>0)return{headerLength:r,frameLength:n}}}function BT(t,e,r,n,i){const s=UT(t.samplerate),a=n+i*s,o=GO(e,r);let l;if(o){const{frameLength:d,headerLength:f}=o,m=f+d,h=Math.max(0,r+m-e.length);h?(l=new Uint8Array(m-f),l.set(e.subarray(r+f,e.length),0)):l=e.subarray(r+f,r+m);const p={unit:l,pts:a};return h||t.samples.push(p),{sample:p,length:m,missing:h}}const u=e.length-r;return l=new Uint8Array(u),l.set(e.subarray(r,e.length),0),{sample:{unit:l,pts:a},length:u,missing:-1}}let au=null;const zO=[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],HO=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],WO=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],KO=[0,1,1,4];function $T(t,e,r,n,i){if(r+24>e.length)return;const s=jT(e,r);if(s&&r+s.frameLength<=e.length){const a=s.samplesPerFrame*9e4/s.sampleRate,o=n+i*a,l={unit:e.subarray(r,r+s.frameLength),pts:o,dts:o};return t.config=[],t.channelCount=s.channelCount,t.samplerate=s.sampleRate,t.samples.push(l),{sample:l,length:s.frameLength,missing:0}}}function jT(t,e){const r=t[e+1]>>3&3,n=t[e+1]>>1&3,i=t[e+2]>>4&15,s=t[e+2]>>2&3;if(r!==1&&i!==0&&i!==15&&s!==3){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=r===3?3-n:n===3?3:4,u=zO[l*14+i-1]*1e3,d=HO[(r===3?0:r===2?1:2)*3+s],f=o===3?1:2,m=WO[r][n],h=KO[n],p=m*8*h,v=Math.floor(m*u/d+a)*h;if(au===null){const x=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);au=x?parseInt(x[1]):0}return!!au&&au<=87&&n===2&&u>=224e3&&o===0&&(t[e+3]=t[e+3]|128),{sampleRate:d,channelCount:f,frameLength:v,samplesPerFrame:p}}}function Nm(t,e){return t[e]===255&&(t[e+1]&224)===224&&(t[e+1]&6)!==0}function VT(t,e){return e+1{const a=LP(s);if(XO.test(a.schemeIdUri)){const o=pe(a.presentationTime)?a.presentationTime/a.timeScale:r+a.presentationTimeDelta/a.timeScale;let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const u=a.payload;n.samples.push({data:u,len:u.byteLength,dts:o,pts:o,type:dn.emsg,duration:l})}})}return n}demuxSampleAes(e,r,n){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}const zT=(t,e)=>{let r=0,n=5;e+=n;const i=new Uint32Array(1),s=new Uint32Array(1),a=new Uint8Array(1);for(;n>0;){a[0]=t[e];const o=Math.min(n,8),l=8-o;s[0]=4278190080>>>24+l<>l,r=r?r<e.length||e[r]!==11||e[r+1]!==119)return-1;const s=e[r+4]>>6;if(s>=3)return-1;const o=[48e3,44100,32e3][s],l=e[r+4]&63,c=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+s]*2;if(r+c>e.length)return-1;const d=e[r+6]>>5;let f=0;d===2?f+=2:(d&1&&d!==1&&(f+=2),d&4&&(f+=2));const m=(e[r+6]<<8|e[r+7])>>12-f&1,p=[2,1,2,3,3,4,4,5][d]+m,v=e[r+5]>>3,g=e[r+5]&7,y=new Uint8Array([s<<6|v<<1|g>>2,(g&3)<<6|d<<3|m<<2|l>>4,l<<4&224]),x=1536/o*9e4,S=n+i*x,T=e.subarray(r,r+c);return t.config=y,t.channelCount=p,t.samplerate=o,t.samples.push({unit:T,pts:S}),c}class JO{constructor(){this.VideoSample=null}createVideoSample(e,r,n,i){return{key:e,frame:!1,pts:r,dts:n,units:[],debug:i,length:0}}getLastNalUnit(e){var r;let n=this.VideoSample,i;if((!n||n.units.length===0)&&(n=e[e.length-1]),(r=n)!=null&&r.units){const s=n.units;i=s[s.length-1]}return i}pushAccessUnit(e,r){if(e.units.length&&e.frame){if(e.pts===void 0){const n=r.samples,i=n.length;if(i){const s=n[i-1];e.pts=s.pts,e.dts=s.dts}else{r.dropped++;return}}r.samples.push(e)}e.debug.length&&U.log(e.pts+"/"+e.dts+":"+e.debug)}}class jv{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,r=this.bytesAvailable,n=e.byteLength-r,i=new Uint8Array(4),s=Math.min(4,r);if(s===0)throw new Error("no bytes available");i.set(e.subarray(n,n+s)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=s*8,this.bytesAvailable-=s}skipBits(e){let r;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,r=e>>3,e-=r<<3,this.bytesAvailable-=r,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let r=Math.min(this.bitsAvailable,e);const n=this.word>>>32-r;if(e>32&&U.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=r,this.bitsAvailable>0)this.word<<=r;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return r=e-r,r>0&&this.bitsAvailable?n<>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){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)}skipScalingList(e){let r=8,n=8,i;for(let s=0;s{var d;switch(c.type){case 1:{let p=!1;l=!0;const v=c.data;if(u&&v.length>4){const g=new jv(v).readSliceType();(g===2||g===4||g===7||g===9)&&(p=!0)}if(p){var f;(f=o)!=null&&f.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts,"")),o.frame=!0,o.key=p;break}case 5:l=!0,(d=o)!=null&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts,"")),o.key=!0,o.frame=!0;break;case 6:{l=!0,ET(c.data,1,n.pts,r.samples);break}case 7:{var m,h;l=!0,u=!0;const p=c.data,g=new jv(p).readSPS();if(!e.sps||e.width!==g.width||e.height!==g.height||((m=e.pixelRatio)==null?void 0:m[0])!==g.pixelRatio[0]||((h=e.pixelRatio)==null?void 0:h[1])!==g.pixelRatio[1]){e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[p],e.duration=s;const y=p.subarray(1,4);let x="avc1.";for(let S=0;S<3;S++){let T=y[S].toString(16);T.length<2&&(T="0"+T),x+=T}e.codec=x}break}case 8:l=!0,e.pps=[c.data];break;case 9:l=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts,"");break;case 12:l=!0;break;default:l=!1,o&&(o.debug+="unknown NAL "+c.type+" ");break}o&&l&&o.units.push(c)}),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,r){const n=r.byteLength;let i=e.naluState||0;const s=i,a=[];let o=0,l,u,c,d=-1,f=0;for(i===-1&&(d=0,f=r[0]&31,i=0,o=1);o=0){const m={data:r.subarray(d,u),type:f};a.push(m)}else{const m=this.getLastNalUnit(e.samples);m&&(s&&o<=4-s&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-s)),u>0&&(m.data=Jr(m.data,r.subarray(0,u)),m.state=0))}o=0&&i>=0){const m={data:r.subarray(d,n),type:f,state:i};a.push(m)}if(a.length===0){const m=this.getLastNalUnit(e.samples);m&&(m.data=Jr(m.data,r))}return e.naluState=i,a}}class tM{constructor(e,r,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new Dm(r,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,r,n){const i=e[r].unit;if(i.length<=16)return;const s=i.subarray(16,i.length-i.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);i.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,r+1,n)})}decryptAacSamples(e,r,n){for(;;r++){if(r>=e.length){n();return}if(!(e[r].unit.length<32)&&(this.decryptAacSample(e,r,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const r=Math.floor((e.length-48)/160)*16+16,n=new Int8Array(r);let i=0;for(let s=32;s{s.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,r,n+1,i)})}decryptAvcSamples(e,r,n,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;r++,n=0){if(r>=e.length){i();return}const s=e[r].units;for(;!(n>=s.length);n++){const a=s[n];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,r,n,i,a),!this.decrypter.isSync()))return}}}}const Ft=188;class Ti{constructor(e,r,n){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._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=r,this.typeSupported=n,this.videoParser=new eM}static probe(e){const r=Ti.syncOffset(e);return r>0&&U.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(e){const r=e.length;let n=Math.min(Ft*5,r-Ft)+1,i=0;for(;i1&&(a===0&&o>2||l+Ft>n))return a}else{if(o)return-1;break}i++}return-1}static createTrack(e,r){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:gT[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?r:void 0}}resetInitSegment(e,r,n,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ti.createTrack("video"),this._audioTrack=Ti.createTrack("audio",i),this._id3Track=Ti.createTrack("id3"),this._txtTrack=Ti.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=n,this._duration=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:r,_id3Track:n}=this;e&&(e.pesData=null),r&&(r.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,r,n=!1,i=!1){n||(this.sampleAes=null);let s;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,u=this._txtTrack;let c=a.pid,d=a.pesData,f=o.pid,m=l.pid,h=o.pesData,p=l.pesData,v=null,g=this.pmtParsed,y=this._pmtId,x=e.length;if(this.remainderData&&(e=Jr(this.remainderData,e),x=e.length,this.remainderData=null),x>4;let k;if(A>1){if(k=_+5+e[_+4],k===_+Ft)continue}else k=_+4;switch(I){case c:b&&(d&&(s=Fs(d))&&this.videoParser.parseAVCPES(a,u,s,!1,this._duration),d={data:[],size:0}),d&&(d.data.push(e.subarray(k,_+Ft)),d.size+=_+Ft-k);break;case f:if(b){if(h&&(s=Fs(h)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,s);break;case"mp3":this.parseMPEGPES(o,s);break;case"ac3":this.parseAC3PES(o,s);break}h={data:[],size:0}}h&&(h.data.push(e.subarray(k,_+Ft)),h.size+=_+Ft-k);break;case m:b&&(p&&(s=Fs(p))&&this.parseID3PES(l,s),p={data:[],size:0}),p&&(p.data.push(e.subarray(k,_+Ft)),p.size+=_+Ft-k);break;case 0:b&&(k+=e[k]+1),y=this._pmtId=rM(e,k);break;case y:{b&&(k+=e[k]+1);const O=nM(e,k,this.typeSupported,n,this.observer);c=O.videoPid,c>0&&(a.pid=c,a.segmentCodec=O.segmentVideoCodec),f=O.audioPid,f>0&&(o.pid=f,o.segmentCodec=O.segmentAudioCodec),m=O.id3Pid,m>0&&(l.pid=m),v!==null&&!g&&(U.warn(`MPEG-TS PMT found at ${_} after unknown PID '${v}'. Backtracking to sync byte @${S} to parse all TS packets.`),v=null,_=S-188),g=this.pmtParsed=!0;break}case 17:case 8191:break;default:v=I;break}}else T++;T>0&&Hc(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`)),a.pesData=d,o.pesData=h,l.pesData=p;const C={audioTrack:o,videoTrack:a,id3Track:l,textTrack:u};return i&&this.extractRemainingSamples(C),C}flush(){const{remainderData:e}=this;this.remainderData=null;let r;return e?r=this.demux(e,-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(e){const{audioTrack:r,videoTrack:n,id3Track:i,textTrack:s}=e,a=n.pesData,o=r.pesData,l=i.pesData;let u;if(a&&(u=Fs(a))?(this.videoParser.parseAVCPES(n,s,u,!0,this._duration),n.pesData=null):n.pesData=a,o&&(u=Fs(o))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,u);break;case"mp3":this.parseMPEGPES(r,u);break;case"ac3":this.parseAC3PES(r,u);break}r.pesData=null}else o!=null&&o.size&&U.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(u=Fs(l))?(this.parseID3PES(i,u),i.pesData=null):i.pesData=l}demuxSampleAes(e,r,n){const i=this.demux(e,n,!0,!this.config.progressive),s=this.sampleAes=new tM(this.observer,this.config,r);return this.decrypt(i,s)}decrypt(e,r){return new Promise(n=>{const{audioTrack:i,videoTrack:s}=e;i.samples&&i.segmentCodec==="aac"?r.decryptAacSamples(i.samples,0,()=>{s.samples?r.decryptAvcSamples(s.samples,0,0,()=>{n(e)}):n(e)}):s.samples&&r.decryptAvcSamples(s.samples,0,0,()=>{n(e)})})}destroy(){this._duration=0}parseAACPES(e,r){let n=0;const i=this.aacOverFlow;let s=r.data;if(i){this.aacOverFlow=null;const d=i.missing,f=i.sample.unit.byteLength;if(d===-1)s=Jr(i.sample.unit,s);else{const m=f-d;i.sample.unit.set(s.subarray(0,d),m),e.samples.push(i.sample),n=i.missing}}let a,o;for(a=n,o=s.length;a0;)o+=l}}parseID3PES(e,r){if(r.pts===void 0){U.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const n=It({},r,{type:this._videoTrack?dn.emsg:dn.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(n)}}function ep(t,e){return((t[e+1]&31)<<8)+t[e+2]}function rM(t,e){return(t[e+10]&31)<<8|t[e+11]}function nM(t,e,r,n,i){const s={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(t[e+1]&15)<<8|t[e+2],o=e+3+a-4,l=(t[e+10]&15)<<8|t[e+11];for(e+=12+l;e0){let d=e+5,f=c;for(;f>2;){switch(t[d]){case 106:r.ac3!==!0?U.log("AC-3 audio found, not supported in this browser for now"):(s.audioPid=u,s.segmentAudioCodec="ac3");break}const h=t[d+1]+2;d+=h,f-=h}}break;case 194:case 135:return Hc(i,new Error("Unsupported EC-3 in M2TS found")),s;case 36:return Hc(i,new Error("Unsupported HEVC in M2TS found")),s}e+=c+5}return s}function Hc(t,e,r){U.warn(`parsing error: ${e.message}`),t.emit(w.ERROR,w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:e,reason:e.message})}function Cf(t){U.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Fs(t){let e=0,r,n,i,s,a;const o=t.data;if(!t||t.size===0)return null;for(;o[0].length<19&&o.length>1;)o[0]=Jr(o[0],o[1]),o.splice(1,1);if(r=o[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(n=(r[4]<<8)+r[5],n&&n>t.size-6)return null;const u=r[7];u&192&&(s=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,u&64?(a=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,s-a>60*9e4&&(U.warn(`${Math.round((s-a)/9e4)}s delta between PTS and DTS, align them`),s=a)):a=s),i=r[8];let c=i+9;if(t.size<=c)return null;t.size-=c;const d=new Uint8Array(t.size);for(let f=0,m=o.length;fh){c-=h;continue}else r=r.subarray(c),h-=c,c=0;d.set(r,e),e+=h}return n&&(n-=i+3),{data:d,pts:s,dts:a,len:n}}return null}class iM extends Om{resetInitSegment(e,r,n,i){super.resetInitSegment(e,r,n,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const r=fl(e,0);let n=(r==null?void 0:r.length)||0;if(r&&e[n]===11&&e[n+1]===119&&Cm(r)!==void 0&&zT(e,n)<=16)return!1;for(let i=e.length;n>24&255,a[1]=n>>16&255,a[2]=n>>8&255,a[3]=n&255,a.set(e,4),i=0,n=8;i>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return B.box(B.types.mdia,B.mdhd(e.timescale,e.duration),B.hdlr(e.type),B.minf(e))}static mfhd(e){return B.box(B.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?B.box(B.types.minf,B.box(B.types.smhd,B.SMHD),B.DINF,B.stbl(e)):B.box(B.types.minf,B.box(B.types.vmhd,B.VMHD),B.DINF,B.stbl(e))}static moof(e,r,n){return B.box(B.types.moof,B.mfhd(e),B.traf(n,r))}static moov(e){let r=e.length;const n=[];for(;r--;)n[r]=B.trak(e[r]);return B.box.apply(null,[B.types.moov,B.mvhd(e[0].timescale,e[0].duration)].concat(n).concat(B.mvex(e)))}static mvex(e){let r=e.length;const n=[];for(;r--;)n[r]=B.trex(e[r]);return B.box.apply(null,[B.types.mvex,...n])}static mvhd(e,r){r*=e;const n=Math.floor(r/(yi+1)),i=Math.floor(r%(yi+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return B.box(B.types.mvhd,s)}static sdtp(e){const r=e.samples||[],n=new Uint8Array(4+r.length);let i,s;for(i=0;i>>8&255),r.push(a&255),r=r.concat(Array.prototype.slice.call(s));for(i=0;i>>8&255),n.push(a&255),n=n.concat(Array.prototype.slice.call(s));const o=B.box(B.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(n))),l=e.width,u=e.height,c=e.pixelRatio[0],d=e.pixelRatio[1];return B.box(B.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,l>>8&255,l&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,B.box(B.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),B.box(B.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){const r=e.config.length;return new Uint8Array([0,0,0,0,3,23+r,0,1,0,4,15+r,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([r]).concat(e.config).concat([6,1,2]))}static audioStsd(e){const r=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,r&255,0,0])}static mp4a(e){return B.box(B.types.mp4a,B.audioStsd(e),B.box(B.types.esds,B.esds(e)))}static mp3(e){return B.box(B.types[".mp3"],B.audioStsd(e))}static ac3(e){return B.box(B.types["ac-3"],B.audioStsd(e),B.box(B.types.dac3,e.config))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?B.box(B.types.stsd,B.STSD,B.mp3(e)):e.segmentCodec==="ac3"?B.box(B.types.stsd,B.STSD,B.ac3(e)):B.box(B.types.stsd,B.STSD,B.mp4a(e)):B.box(B.types.stsd,B.STSD,B.avc1(e))}static tkhd(e){const r=e.id,n=e.duration*e.timescale,i=e.width,s=e.height,a=Math.floor(n/(yi+1)),o=Math.floor(n%(yi+1));return B.box(B.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,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,s>>8&255,s&255,0,0]))}static traf(e,r){const n=B.sdtp(e),i=e.id,s=Math.floor(r/(yi+1)),a=Math.floor(r%(yi+1));return B.box(B.types.traf,B.box(B.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),B.box(B.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,s&255,a>>24,a>>16&255,a>>8&255,a&255])),B.trun(e,n.length+16+20+8+16+8+8),n)}static trak(e){return e.duration=e.duration||4294967295,B.box(B.types.trak,B.tkhd(e),B.mdia(e))}static trex(e){const r=e.id;return B.box(B.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(e,r){const n=e.samples||[],i=n.length,s=12+16*i,a=new Uint8Array(s);let o,l,u,c,d,f;for(r+=8+s,a.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255],0),o=0;o>>24&255,u>>>16&255,u>>>8&255,u&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,f>>>24&255,f>>>16&255,f>>>8&255,f&255],12+16*o);return B.box(B.types.trun,a)}static initSegment(e){B.types||B.init();const r=B.moov(e);return Jr(B.FTYP,r)}}B.types=void 0;B.HDLR_TYPES=void 0;B.STTS=void 0;B.STSC=void 0;B.STCO=void 0;B.STSZ=void 0;B.VMHD=void 0;B.SMHD=void 0;B.STSD=void 0;B.FTYP=void 0;B.DINF=void 0;const WT=9e4;function Fm(t,e,r=1,n=!1){const i=t*e*r;return n?Math.round(i):i}function sM(t,e,r=1,n=!1){return Fm(t,e,1/r,n)}function io(t,e=!1){return Fm(t,1e3,1/WT,e)}function aM(t,e=1){return Fm(t,WT,1/e)}const oM=10*1e3,Gv=1024,lM=1152,uM=1536;let Us=null,Rf=null;class Nu{constructor(e,r,n,i=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=r,this.typeSupported=n,this.ISGenerated=!1,Us===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Us=a?parseInt(a[1]):0}if(Rf===null){const s=navigator.userAgent.match(/Safari\/(\d+)/i);Rf=s?parseInt(s[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){U.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){U.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){U.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let r=!1;const n=e.reduce((i,s)=>{const a=s.pts-i;return a<-4294967296?(r=!0,Hr(i,s.pts)):a>0?i:s.pts},e[0].pts);return r&&U.debug("PTS rollover detected"),n}remux(e,r,n,i,s,a,o,l){let u,c,d,f,m,h,p=s,v=s;const g=e.pid>-1,y=r.pid>-1,x=r.samples.length,S=e.samples.length>0,T=o&&x>0||x>1;if((!g||S)&&(!y||T)||this.ISGenerated||o){if(this.ISGenerated){var _,b,I,A;const G=this.videoTrackConfig;G&&(r.width!==G.width||r.height!==G.height||((_=r.pixelRatio)==null?void 0:_[0])!==((b=G.pixelRatio)==null?void 0:b[0])||((I=r.pixelRatio)==null?void 0:I[1])!==((A=G.pixelRatio)==null?void 0:A[1]))&&this.resetInitSegment()}else d=this.generateIS(e,r,s,a);const k=this.isVideoContiguous;let O=-1,P;if(T&&(O=cM(r.samples),!k&&this.config.forceKeyFrameOnDiscontinuity))if(h=!0,O>0){U.warn(`[mp4-remuxer]: Dropped ${O} out of ${x} video samples due to a missing keyframe`);const G=this.getVideoStartPts(r.samples);r.samples=r.samples.slice(O),r.dropped+=O,v+=(r.samples[0].pts-G)/r.inputTimeScale,P=v}else O===-1&&(U.warn(`[mp4-remuxer]: No keyframe found out of ${x} video samples`),h=!1);if(this.ISGenerated){if(S&&T){const G=this.getVideoStartPts(r.samples),H=(Hr(e.samples[0].pts,G)-G)/r.inputTimeScale;p+=Math.max(0,H),v+=Math.max(0,-H)}if(S){if(e.samplerate||(U.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,r,s,a)),c=this.remuxAudio(e,p,this.isAudioContiguous,a,y||T||l===we.AUDIO?v:void 0),T){const G=c?c.endPTS-c.startPTS:0;r.inputTimeScale||(U.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,r,s,a)),u=this.remuxVideo(r,v,k,G)}}else T&&(u=this.remuxVideo(r,v,k,0));u&&(u.firstKeyFrame=O,u.independent=O!==-1,u.firstKeyFramePTS=P)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(m=KT(n,s,this._initPTS,this._initDTS)),i.samples.length&&(f=YT(i,s,this._initPTS))),{audio:c,video:u,initSegment:d,independent:h,text:f,id3:m}}generateIS(e,r,n,i){const s=e.samples,a=r.samples,o=this.typeSupported,l={},u=this._initPTS;let c=!u||i,d="audio/mp4",f,m,h;if(c&&(f=m=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(d="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:d,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):B.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(h=e.inputTimeScale,!u||h!==u.timescale?f=m=s[0].pts-Math.round(h*n):c=!1)}if(r.sps&&r.pps&&a.length){if(r.timescale=r.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:r.codec,initSegment:B.initSegment([r]),metadata:{width:r.width,height:r.height}},c)if(h=r.inputTimeScale,!u||h!==u.timescale){const p=this.getVideoStartPts(a),v=Math.round(h*n);m=Math.min(m,Hr(a[0].dts,p)-v),f=Math.min(f,p-v)}else c=!1;this.videoTrackConfig={width:r.width,height:r.height,pixelRatio:r.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:f,timescale:h},this._initDTS={baseTime:m,timescale:h}):f=h=void 0,{tracks:l,initPTS:f,timescale:h}}remuxVideo(e,r,n,i){const s=e.inputTimeScale,a=e.samples,o=[],l=a.length,u=this._initPTS;let c=this.nextAvcDts,d=8,f=this.videoSampleDuration,m,h,p=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,g=!1;if(!n||c===null){const F=r*s,j=a[0].pts-Hr(a[0].dts,a[0].pts);Us&&c!==null&&Math.abs(F-j-c)<15e3?n=!0:c=F-j}const y=u.baseTime*s/u.timescale;for(let F=0;F0?F-1:F].dts&&(g=!0)}g&&a.sort(function(F,j){const te=F.dts-j.dts,ee=F.pts-j.pts;return te||ee}),m=a[0].dts,h=a[a.length-1].dts;const x=h-m,S=x?Math.round(x/(l-1)):f||e.inputTimeScale/30;if(n){const F=m-c,j=F>S,te=F<-1;if((j||te)&&(j?U.warn(`AVC: ${io(F,!0)} ms (${F}dts) hole between fragments detected at ${r.toFixed(3)}`):U.warn(`AVC: ${io(-F,!0)} ms (${F}dts) overlapping between fragments detected at ${r.toFixed(3)}`),!te||c>=a[0].pts||Us)){m=c;const ee=a[0].pts-F;if(j)a[0].dts=m,a[0].pts=ee;else for(let fe=0;feee);fe++)a[fe].dts-=F,a[fe].pts-=F;U.log(`Video: Initial PTS/DTS adjusted: ${io(ee,!0)}/${io(m,!0)}, delta: ${io(F,!0)} ms`)}}m=Math.max(0,m);let T=0,C=0,_=m;for(let F=0;F0?j.dts-a[F-1].dts:S;if(fe=F>0?j.pts-a[F-1].pts:S,Re.stretchShortVideoTrack&&this.nextAudioPts!==null){const Fe=Math.floor(Re.maxBufferHole*s),st=(i?p+i*s:this.nextAudioPts)-j.pts;st>Fe?(f=st-Ee,f<0?f=Ee:k=!0,U.log(`[mp4-remuxer]: It is approximately ${st/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=Ee}else f=Ee}const ye=Math.round(j.pts-j.dts);O=Math.min(O,f),G=Math.max(G,f),P=Math.min(P,fe),K=Math.max(K,fe),o.push(new zv(j.key,f,ee,ye))}if(o.length){if(Us){if(Us<70){const F=o[0].flags;F.dependsOn=2,F.isNonSync=0}}else if(Rf&&K-P0&&(i&&Math.abs(y-g)<9e3||Math.abs(Hr(p[0].pts-x,y)-g)<20*c),p.forEach(function(H){H.pts=Hr(H.pts-x,y)}),!n||g<0){if(p=p.filter(H=>H.pts>=0),!p.length)return;s===0?g=0:i&&!h?g=Math.max(0,y):g=p[0].pts}if(e.segmentCodec==="aac"){const H=this.config.maxAudioFramesDrift;for(let se=0,W=g;se=H*c&&ee0){_+=v;try{C=new Uint8Array(_)}catch(ee){this.observer.emit(w.ERROR,w.ERROR,{type:_e.MUX_ERROR,details:z.REMUX_ALLOC_ERROR,fatal:!1,error:ee,bytes:_,reason:`fail allocating audio mdat ${_}`});return}f||(new DataView(C.buffer).setUint32(0,_),C.set(B.types.mdat,4))}else return;C.set(F,v);const te=F.byteLength;v+=te,m.push(new zv(!0,u,te,0)),T=j}const I=m.length;if(!I)return;const A=m[m.length-1];this.nextAudioPts=g=T+l*A.duration;const k=f?new Uint8Array(0):B.moof(e.sequenceNumber++,S/l,It({},e,{samples:m}));e.samples=[];const O=S/a,P=g/a,K={data1:k,data2:C,startPTS:O,endPTS:P,startDTS:O,endDTS:P,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,K}remuxEmptyAudio(e,r,n,i){const s=e.inputTimeScale,a=e.samplerate?e.samplerate:s,o=s/a,l=this.nextAudioPts,u=this._initDTS,c=u.baseTime*9e4/u.timescale,d=(l!==null?l:i.startDTS*s)+c,f=i.endDTS*s+c,m=o*Gv,h=Math.ceil((f-d)/m),p=Vv.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(U.warn("[mp4-remuxer]: remux empty Audio"),!p){U.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const v=[];for(let g=0;g4294967296;)t+=r;return t}function cM(t){for(let e=0;ea.pts-o.pts);const s=t.samples;return t.samples=[],{samples:s}}class zv{constructor(e,r,n,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=r,this.size=n,this.cts=i,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class dM{constructor(){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}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,r,n,i){this.audioCodec=r,this.videoCodec=n,this.generateInitSegment(vP(e,i)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:r,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const i=this.initData=xT(e);i.audio&&(r=Hv(i.audio,Je.AUDIO)),i.video&&(n=Hv(i.video,Je.VIDEO));const s={};i.audio&&i.video?s.audiovideo={container:"video/mp4",codec:r+","+n,initSegment:e,id:"main"}:i.audio?s.audio={container:"audio/mp4",codec:r,initSegment:e,id:"audio"}:i.video?s.video={container:"video/mp4",codec:n,initSegment:e,id:"main"}:U.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,r,n,i,s,a){var o,l;let{initPTS:u,lastEndTime:c}=this;const d={audio:void 0,video:void 0,text:i,id3:n,initSegment:void 0};pe(c)||(c=this.lastEndTime=s||0);const f=r.samples;if(!(f!=null&&f.length))return d;const m={initPTS:void 0,timescale:1};let h=this.initData;if((o=h)!=null&&o.length||(this.generateInitSegment(f),h=this.initData),!((l=h)!=null&&l.length))return U.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(m.tracks=this.initTracks,this.emitInitSegment=!1);const p=xP(f,h),v=yP(h,f),g=v===null?s:v;(fM(u,g,s,p)||m.timescale!==u.timescale&&a)&&(m.initPTS=g-s,u&&u.timescale===1&&U.warn(`Adjusting initPTS by ${m.initPTS-u.baseTime}`),this.initPTS=u={baseTime:m.initPTS,timescale:1});const y=e?g-u.baseTime/u.timescale:c,x=y+p;EP(h,f,u.baseTime/u.timescale),p>0?this.lastEndTime=x:(U.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const S=!!h.audio,T=!!h.video;let C="";S&&(C+="audio"),T&&(C+="video");const _={data1:f,startPTS:y,startDTS:y,endPTS:x,endDTS:x,type:C,hasAudio:S,hasVideo:T,nb:1,dropped:0};return d.audio=_.type==="audio"?_:void 0,d.video=_.type!=="audio"?_:void 0,d.initSegment=m,d.id3=KT(n,s,u,u),i.samples.length&&(d.text=YT(i,s,u)),d}}function fM(t,e,r,n){if(t===null)return!0;const i=Math.max(n,1),s=e-t.baseTime/t.timescale;return Math.abs(s-r)>i}function Hv(t,e){const r=t==null?void 0:t.codec;if(r&&r.length>4)return r;if(e===Je.AUDIO){if(r==="ec-3"||r==="ac-3"||r==="alac")return r;if(r==="fLaC"||r==="Opus")return Uc(r,!1);const n="mp4a.40.5";return U.info(`Parsed audio codec "${r}" or audio object type not handled. Using "${n}"`),n}return U.warn(`Unhandled video codec "${r}"`),r==="hvc1"||r==="hev1"?"hvc1.1.6.L120.90":r==="av01"?"av01.0.04M.08":"avc1.42e01e"}let Qn;try{Qn=self.performance.now.bind(self.performance)}catch{U.debug("Unable to use Performance API on this environment"),Qn=Ra==null?void 0:Ra.Date.now}const Fu=[{demux:ZO,remux:dM},{demux:Ti,remux:Nu},{demux:qO,remux:Nu},{demux:iM,remux:Nu}];Fu.splice(2,0,{demux:QO,remux:Nu});class Wv{constructor(e,r,n,i,s){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=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=r,this.config=n,this.vendor=i,this.id=s}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,r,n,i){const s=n.transmuxing;s.executeStart=Qn();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;i&&(this.currentTransmuxState=i);const{contiguous:u,discontinuity:c,trackSwitch:d,accurateTimeOffset:f,timeOffset:m,initSegmentChange:h}=i||o,{audioCodec:p,videoCodec:v,defaultInitPts:g,duration:y,initSegmentData:x}=l,S=hM(a,r);if(S&&S.method==="AES-128"){const b=this.getDecrypter();if(b.isSync()){let I=b.softwareDecrypt(a,S.key.buffer,S.iv.buffer);if(n.part>-1&&(I=b.flush()),!I)return s.executeEnd=Qn(),If(n);a=new Uint8Array(I)}else return this.decryptionPromise=b.webCryptoDecrypt(a,S.key.buffer,S.iv.buffer).then(I=>{const A=this.push(I,null,n);return this.decryptionPromise=null,A}),this.decryptionPromise}const T=this.needsProbing(c,d);if(T){const b=this.configureTransmuxer(a);if(b)return U.warn(`[transmuxer] ${b.message}`),this.observer.emit(w.ERROR,w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,error:b,reason:b.message}),s.executeEnd=Qn(),If(n)}(c||d||h||T)&&this.resetInitSegment(x,p,v,y,r),(c||h||T)&&this.resetInitialTimestamp(g),u||this.resetContiguity();const C=this.transmux(a,S,m,f,n),_=this.currentTransmuxState;return _.contiguous=!0,_.discontinuity=!1,_.trackSwitch=!1,s.executeEnd=Qn(),C}flush(e){const r=e.transmuxing;r.executeStart=Qn();const{decrypter:n,currentTransmuxState:i,decryptionPromise:s}=this;if(s)return s.then(()=>this.flush(e));const a=[],{timeOffset:o}=i;if(n){const d=n.flush();d&&a.push(this.push(d,null,e))}const{demuxer:l,remuxer:u}=this;if(!l||!u)return r.executeEnd=Qn(),[If(e)];const c=l.flush(o);return Uu(c)?c.then(d=>(this.flushRemux(a,d,e),a)):(this.flushRemux(a,c,e),a)}flushRemux(e,r,n){const{audioTrack:i,videoTrack:s,id3Track:a,textTrack:o}=r,{accurateTimeOffset:l,timeOffset:u}=this.currentTransmuxState;U.log(`[transmuxer.ts]: Flushed fragment ${n.sn}${n.part>-1?" p: "+n.part:""} of level ${n.level}`);const c=this.remuxer.remux(i,s,a,o,u,l,!0,this.id);e.push({remuxResult:c,chunkMeta:n}),n.transmuxing.executeEnd=Qn()}resetInitialTimestamp(e){const{demuxer:r,remuxer:n}=this;!r||!n||(r.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:r}=this;!e||!r||(e.resetContiguity(),r.resetNextTimestamp())}resetInitSegment(e,r,n,i,s){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,r,n,i),o.resetInitSegment(e,r,n,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,r,n,i,s){let a;return r&&r.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,r,n,i,s):a=this.transmuxUnencrypted(e,n,i,s),a}transmuxUnencrypted(e,r,n,i){const{audioTrack:s,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,r,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,a,o,l,r,n,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,r,n,i,s){return this.demuxer.demuxSampleAes(e,r,n).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,n,i,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){const{config:r,observer:n,typeSupported:i,vendor:s}=this;let a;for(let f=0,m=Fu.length;f0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(r=e),r}const If=t=>({remuxResult:{},chunkMeta:t});function Uu(t){return"then"in t&&t.then instanceof Function}class pM{constructor(e,r,n,i,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=r,this.initSegmentData=n,this.duration=i,this.defaultInitPts=s||null}}class mM{constructor(e,r,n,i,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=r,this.accurateTimeOffset=n,this.trackSwitch=i,this.timeOffset=s,this.initSegmentChange=a}}var qT={exports:{}};(function(t){var e=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function i(l,u,c){this.fn=l,this.context=u,this.once=c||!1}function s(l,u,c,d,f){if(typeof c!="function")throw new TypeError("The listener must be a function");var m=new i(c,d||l,f),h=r?r+u:u;return l._events[h]?l._events[h].fn?l._events[h]=[l._events[h],m]:l._events[h].push(m):(l._events[h]=m,l._eventsCount++),l}function a(l,u){--l._eventsCount===0?l._events=new n:delete l._events[u]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],c,d;if(this._eventsCount===0)return u;for(d in c=this._events)e.call(c,d)&&u.push(r?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(c)):u},o.prototype.listeners=function(u){var c=r?r+u:u,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var f=0,m=d.length,h=new Array(m);f{c=c||{},c.frag=this.frag,c.id=this.id,u===w.ERROR&&(this.error=c.error),this.hls.trigger(u,c)};this.observer=new Um,this.observer.on(w.FRAG_DECRYPTED,a),this.observer.on(w.ERROR,a);const o=bs(s.preferManagedMediaSource)||{isTypeSupported:()=>!1},l={mpeg:o.isTypeSupported("audio/mpeg"),mp3:o.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:o.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&typeof Worker<"u"&&(s.workerPath||MO())){try{s.workerPath?(U.log(`loading Web Worker ${s.workerPath} for "${r}"`),this.workerContext=FO(s.workerPath)):(U.log(`injecting Web Worker for "${r}"`),this.workerContext=NO()),this.onwmsg=d=>this.onWorkerMessage(d);const{worker:c}=this.workerContext;c.addEventListener("message",this.onwmsg),c.onerror=d=>{const f=new Error(`${d.message} (${d.filename}:${d.lineno})`);s.enableWorker=!1,U.warn(`Error in "${r}" Web Worker, fallback to inline`),this.hls.trigger(w.ERROR,{type:_e.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:f})},c.postMessage({cmd:"init",typeSupported:l,vendor:"",id:r,config:JSON.stringify(s)})}catch(c){U.warn(`Error setting up "${r}" Web Worker, fallback to inline`,c),this.resetWorker(),this.error=null,this.transmuxer=new Wv(this.observer,l,s,"",r)}return}this.transmuxer=new Wv(this.observer,l,s,"",r)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:r}=this.workerContext;r&&self.URL.revokeObjectURL(r),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const r=this.transmuxer;r&&(r.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,r,n,i,s,a,o,l,u,c){var d,f;u.transmuxing.start=self.performance.now();const{transmuxer:m}=this,h=a?a.start:s.start,p=s.decryptdata,v=this.frag,g=!(v&&s.cc===v.cc),y=!(v&&u.level===v.level),x=v?u.sn-v.sn:-1,S=this.part?u.part-this.part.index:-1,T=x===0&&u.id>1&&u.id===(v==null?void 0:v.stats.chunkCount),C=!y&&(x===1||x===0&&(S===1||T&&S<=0)),_=self.performance.now();(y||x||s.stats.parsing.start===0)&&(s.stats.parsing.start=_),a&&(S||!C)&&(a.stats.parsing.start=_);const b=!(v&&((d=s.initSegment)==null?void 0:d.url)===((f=v.initSegment)==null?void 0:f.url)),I=new mM(g,C,l,y,h,b);if(!C||g||b){U.log(`[transmuxer-interface, ${s.type}]: Starting new transmux session for sn: ${u.sn} p: ${u.part} level: ${u.level} id: ${u.id} + Switching to level ${k} @ ${O|0} bps`),i.trigger(w.FRAG_LOAD_EMERGENCY_ABORTED,{frag:r,part:n,stats:l})},this.hls=e,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(e){e&&(U.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 oO(e.abrEwmaSlowVoD,e.abrEwmaFastVoD,e.abrEwmaDefaultEstimate)}registerListeners(){const{hls:e}=this;e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.FRAG_LOADING,this.onFragLoading,this),e.on(w.FRAG_LOADED,this.onFragLoaded,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this),e.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(w.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e&&(e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.FRAG_LOADING,this.onFragLoading,this),e.off(w.FRAG_LOADED,this.onFragLoaded,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this),e.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(w.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),e.off(w.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(e,r){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,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,r){const n=r.frag;if(!this.ignoreFragment(n)){if(!n.bitrateTest){var i;this.fragCurrent=n,this.partCurrent=(i=r.part)!=null?i:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(e,r){this.clearTimer()}onError(e,r){if(!r.fatal)switch(r.details){case z.BUFFER_ADD_CODEC_ERROR:case z.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case z.FRAG_LOAD_TIMEOUT:{const n=r.frag,{fragCurrent:i,partCurrent:s}=this;if(n&&i&&n.sn===i.sn&&n.level===i.level){const a=performance.now(),o=s?s.stats:n.stats,l=a-o.loading.start,u=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&u>-1){const d=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(l-Math.min(d,u),o.loaded)}else this.bwEstimator.sampleTTFB(l)}break}}}getTimeToLoadFrag(e,r,n,i){const s=e+n/r,a=i?this.lastLevelLoadSec:0;return s+a}onLevelLoaded(e,r){const n=this.hls.config,{loading:i}=r.stats,s=i.end-i.start;pe(s)&&(this.lastLevelLoadSec=s/1e3),r.details.live?this.bwEstimator.update(n.abrEwmaSlowLive,n.abrEwmaFastLive):this.bwEstimator.update(n.abrEwmaSlowVoD,n.abrEwmaFastVoD)}onFragLoaded(e,{frag:r,part:n}){const i=n?n.stats:r.stats;if(r.type===we.MAIN&&this.bwEstimator.sampleTTFB(i.loading.first-i.loading.start),!this.ignoreFragment(r)){if(this.clearTimer(),r.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const s=n?n.duration:r.duration,a=this.hls.levels[r.level],o=(a.loaded?a.loaded.bytes:0)+i.loaded,l=(a.loaded?a.loaded.duration:0)+s;a.loaded={bytes:o,duration:l},a.realBitrate=Math.round(8*o/l)}if(r.bitrateTest){const s={stats:i,frag:r,part:n,id:r.type};this.onFragBuffered(w.FRAG_BUFFERED,s),r.bitrateTest=!1}else this.lastLoadedFragLevel=r.level}}onFragBuffered(e,r){const{frag:n,part:i}=r,s=i!=null&&i.stats.loaded?i.stats:n.stats;if(s.aborted||this.ignoreFragment(n))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(),n.bitrateTest?this.bitrateTestDelay=a/1e3:this.bitrateTestDelay=0}ignoreFragment(e){return e.type!==we.MAIN||e.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:e,minAutoLevel:r}=this.hls,n=this.getBwEstimate(),i=this.hls.config.maxStarvationDelay,s=this.findBestLevel(n,r,e,0,i,1,1);if(s>-1)return s;const a=this.hls.firstLevel,o=Math.min(Math.max(a,r),e);return U.warn(`[abr] Could not find best starting auto level. Defaulting to first in playlist ${a} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const e=this.forcedAutoLevel,n=this.bwEstimator.canEstimate(),i=this.lastLoadedFragLevel>-1;if(e!==-1&&(!n||!i||this.nextAutoLevelKey===this.getAutoLevelKey()))return e;const s=n&&i?this.getNextABRAutoLevel():this.firstAutoLevel;if(e!==-1){const a=this.hls.levels;if(a.length>Math.max(e,s)&&a[e].loadError<=a[s].loadError)return e}return this._nextAutoLevel=s,this.nextAutoLevelKey=this.getAutoLevelKey(),s}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:e,partCurrent:r,hls:n}=this,{maxAutoLevel:i,config:s,minAutoLevel:a}=n,o=r?r.duration:e?e.duration:0,l=this.getBwEstimate(),u=this.getStarvationDelay();let c=s.abrBandWidthFactor,d=s.abrBandWidthUpFactor;if(u){const v=this.findBestLevel(l,a,i,u,0,c,d);if(v>=0)return v}let f=o?Math.min(o,s.maxStarvationDelay):s.maxStarvationDelay;if(!u){const v=this.bitrateTestDelay;v&&(f=(o?Math.min(o,s.maxLoadingDelay):s.maxLoadingDelay)-v,U.info(`[abr] bitrate test took ${Math.round(1e3*v)}ms, set first fragment max fetchDuration to ${Math.round(1e3*f)} ms`),c=d=1)}const m=this.findBestLevel(l,a,i,u,f,c,d);if(U.info(`[abr] ${u?"rebuffering expected":"buffer is empty"}, optimal quality level ${m}`),m>-1)return m;const h=n.levels[a],p=n.levels[n.loadLevel];return(h==null?void 0:h.bitrate)<(p==null?void 0:p.bitrate)?a:n.loadLevel}getStarvationDelay(){const e=this.hls,r=e.media;if(!r)return 1/0;const n=r&&r.playbackRate!==0?Math.abs(r.playbackRate):1,i=e.mainForwardBufferInfo;return(i?i.len:0)/n}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(e,r,n,i,s,a,o){var l;const u=i+s,c=this.lastLoadedFragLevel,d=c===-1?this.hls.firstLevel:c,{fragCurrent:f,partCurrent:m}=this,{levels:h,allAudioTracks:p,loadLevel:v,config:g}=this.hls;if(h.length===1)return 0;const y=h[d],x=!!(y!=null&&(l=y.details)!=null&&l.live),S=v===-1||c===-1;let T,C="SDR",_=(y==null?void 0:y.frameRate)||0;const{audioPreference:b,videoPreference:I}=g,A=this.audioTracksByGroup||(this.audioTracksByGroup=pO(p));if(S){if(this.firstSelection!==-1)return this.firstSelection;const K=this.codecTiers||(this.codecTiers=mO(h,A,r,n)),H=hO(K,C,e,b,I),{codecSet:se,videoRanges:W,minFramerate:F,minBitrate:j,preferHDR:te}=H;T=se,C=te?W[W.length-1]:W[0],_=F,e=Math.max(e,j),U.log(`[abr] picked start tier ${JSON.stringify(H)}`)}else T=y==null?void 0:y.codecSet,C=y==null?void 0:y.videoRange;const k=m?m.duration:f?f.duration:0,O=this.bwEstimator.getEstimateTTFB()/1e3,P=[];for(let K=n;K>=r;K--){var G;const H=h[K],se=K>d;if(!H)continue;if(g.useMediaCapabilities&&!H.supportedResult&&!H.supportedPromise){const ye=navigator.mediaCapabilities;typeof(ye==null?void 0:ye.decodingInfo)=="function"&&lO(H,A,C,_,e,b)?(H.supportedPromise=uO(H,A,ye),H.supportedPromise.then(Re=>{if(!this.hls)return;H.supportedResult=Re;const Ee=this.hls.levels,Fe=Ee.indexOf(H);Re.error?U.warn(`[abr] MediaCapabilities decodingInfo error: "${Re.error}" for level ${Fe} ${JSON.stringify(Re)}`):Re.supported||(U.warn(`[abr] Unsupported MediaCapabilities decodingInfo result for level ${Fe} ${JSON.stringify(Re)}`),Fe>-1&&Ee.length>1&&(U.log(`[abr] Removing unsupported level ${Fe}`),this.hls.removeLevel(Fe)))})):H.supportedResult=DT}if(T&&H.codecSet!==T||C&&H.videoRange!==C||se&&_>H.frameRate||!se&&_>0&&_=k*2&&s===0?h[K].averageBitrate:h[K].maxBitrate,ee=this.getTimeToLoadFrag(O,j,te*F,W===void 0);if(j>=te&&(K===c||H.loadError===0&&H.fragmentError===0)&&(ee<=O||!pe(ee)||x&&!this.bitrateTestDelay||ee${K} adjustedbw(${Math.round(j)})-bitrate=${Math.round(j-te)} ttfb:${O.toFixed(1)} avgDuration:${F.toFixed(1)} maxFetchDuration:${u.toFixed(1)} fetchDuration:${ee.toFixed(1)} firstSelection:${S} codecSet:${T} videoRange:${C} hls.loadLevel:${v}`)),S&&(this.firstSelection=K),K}}return-1}set nextAutoLevel(e){const{maxAutoLevel:r,minAutoLevel:n}=this.hls,i=Math.min(Math.max(e,n),r);this._nextAutoLevel!==i&&(this.nextAutoLevelKey="",this._nextAutoLevel=i)}}class xO{constructor(){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(){}}var Bt={NOT_LOADED:"NOT_LOADED",APPENDING:"APPENDING",PARTIAL:"PARTIAL",OK:"OK"};class SO{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.on(w.BUFFER_APPENDED,this.onBufferAppended,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this),e.on(w.FRAG_LOADED,this.onFragLoaded,this)}_unregisterListeners(){const{hls:e}=this;e.off(w.BUFFER_APPENDED,this.onBufferAppended,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this),e.off(w.FRAG_LOADED,this.onFragLoaded,this)}destroy(){this._unregisterListeners(),this.fragments=this.activePartLists=this.endListFragments=this.timeRanges=null}getAppendedFrag(e,r){const n=this.activePartLists[r];if(n)for(let i=n.length;i--;){const s=n[i];if(!s)break;const a=s.end;if(s.start<=e&&a!==null&&e<=a)return s}return this.getBufferedFrag(e,r)}getBufferedFrag(e,r){const{fragments:n}=this,i=Object.keys(n);for(let s=i.length;s--;){const a=n[i[s]];if((a==null?void 0:a.body.type)===r&&a.buffered){const o=a.body;if(o.start<=e&&e<=o.end)return o}}return null}detectEvictedFragments(e,r,n,i){this.timeRanges&&(this.timeRanges[e]=r);const s=(i==null?void 0:i.fragment.sn)||-1;Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o||s>=o.body.sn)return;if(!o.buffered&&!o.loaded){o.body.type===n&&this.removeFragment(o.body);return}const l=o.range[e];l&&l.time.some(u=>{const c=!this.isTimeBuffered(u.startPTS,u.endPTS,r);return c&&this.removeFragment(o.body),c})})}detectPartialFragments(e){const r=this.timeRanges,{frag:n,part:i}=e;if(!r||n.sn==="initSegment")return;const s=Ns(n),a=this.fragments[s];if(!a||a.buffered&&n.gap)return;const o=!n.relurl;Object.keys(r).forEach(l=>{const u=n.elementaryStreams[l];if(!u)return;const c=r[l],d=o||u.partial===!0;a.range[l]=this.getBufferedTimes(n,i,d,c)}),a.loaded=null,Object.keys(a.range).length?(a.buffered=!0,(a.body.endList=n.endList||a.body.endList)&&(this.endListFragments[a.body.type]=a),iu(a)||this.removeParts(n.sn-1,n.type)):this.removeFragment(a.body)}removeParts(e,r){const n=this.activePartLists[r];n&&(this.activePartLists[r]=n.filter(i=>i.fragment.sn>=e))}fragBuffered(e,r){const n=Ns(e);let i=this.fragments[n];!i&&r&&(i=this.fragments[n]={body:e,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},e.gap&&(this.hasGaps=!0)),i&&(i.loaded=null,i.buffered=!0)}getBufferedTimes(e,r,n,i){const s={time:[],partial:n},a=e.start,o=e.end,l=e.minEndPTS||o,u=e.maxStartPTS||a;for(let c=0;c=d&&l<=f){s.time.push({startPTS:Math.max(a,i.start(c)),endPTS:Math.min(o,i.end(c))});break}else if(ad){const m=Math.max(a,i.start(c)),h=Math.min(o,i.end(c));h>m&&(s.partial=!0,s.time.push({startPTS:m,endPTS:h}))}else if(o<=d)break}return s}getPartialFragment(e){let r=null,n,i,s,a=0;const{bufferPadding:o,fragments:l}=this;return Object.keys(l).forEach(u=>{const c=l[u];c&&iu(c)&&(i=c.body.start-o,s=c.body.end+o,e>=i&&e<=s&&(n=Math.min(e-i,s-e),a<=n&&(r=c.body,a=n)))}),r}isEndListAppended(e){const r=this.endListFragments[e];return r!==void 0&&(r.buffered||iu(r))}getState(e){const r=Ns(e),n=this.fragments[r];return n?n.buffered?iu(n)?Bt.PARTIAL:Bt.OK:Bt.APPENDING:Bt.NOT_LOADED}isTimeBuffered(e,r,n){let i,s;for(let a=0;a=i&&r<=s)return!0;if(r<=i)return!1}return!1}onFragLoaded(e,r){const{frag:n,part:i}=r;if(n.sn==="initSegment"||n.bitrateTest)return;const s=i?null:r,a=Ns(n);this.fragments[a]={body:n,appendedPTS:null,loaded:s,buffered:!1,range:Object.create(null)}}onBufferAppended(e,r){const{frag:n,part:i,timeRanges:s}=r;if(n.sn==="initSegment")return;const a=n.type;if(i){let o=this.activePartLists[a];o||(this.activePartLists[a]=o=[]),o.push(i)}this.timeRanges=s,Object.keys(s).forEach(o=>{const l=s[o];this.detectEvictedFragments(o,l,a,i)})}onFragBuffered(e,r){this.detectPartialFragments(r)}hasFragment(e){const r=Ns(e);return!!this.fragments[r]}hasParts(e){var r;return!!((r=this.activePartLists[e])!=null&&r.length)}removeFragmentsInRange(e,r,n,i,s){i&&!this.hasGaps||Object.keys(this.fragments).forEach(a=>{const o=this.fragments[a];if(!o)return;const l=o.body;l.type!==n||i&&!l.gap||l.starte&&(o.buffered||s)&&this.removeFragment(l)})}removeFragment(e){const r=Ns(e);e.stats.loaded=0,e.clearElementaryStreamInfo();const n=this.activePartLists[e.type];if(n){const i=e.sn;this.activePartLists[e.type]=n.filter(s=>s.fragment.sn!==i)}delete this.fragments[r],e.endList&&delete this.endListFragments[e.type]}removeAllFragments(){this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1}}function iu(t){var e,r,n;return t.buffered&&(t.body.gap||((e=t.range.video)==null?void 0:e.partial)||((r=t.range.audio)==null?void 0:r.partial)||((n=t.range.audiovideo)==null?void 0:n.partial))}function Ns(t){return`${t.type}_${t.level}_${t.sn}`}const EO={length:0,start:()=>0,end:()=>0};class at{static isBuffered(e,r){try{if(e){const n=at.getBuffered(e);for(let i=0;i=n.start(i)&&r<=n.end(i))return!0}}catch{}return!1}static bufferInfo(e,r,n){try{if(e){const i=at.getBuffered(e),s=[];let a;for(a=0;ad&&(i[c-1].end=e[u].end):i.push(e[u])}else i.push(e[u])}else i=e;let s=0,a,o=r,l=r;for(let u=0;u=c&&rr.startCC||t&&t.cc{if(this.loader&&this.loader.destroy(),e.gap)if(e.tagList.some(m=>m[0]==="GAP")){l($v(e));return}else e.gap=!1;const u=this.loader=e.loader=s?new s(i):new a(i),c=Bv(e),d=Ov(i.fragLoadPolicy.default),f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:e.sn==="initSegment"?1/0:Uv};e.stats=u.stats,u.load(c,f,{onSuccess:(m,h,p,v)=>{this.resetLoader(e,u);let g=m.data;p.resetIV&&e.decryptdata&&(e.decryptdata.iv=new Uint8Array(g.slice(0,16)),g=g.slice(16)),o({frag:e,part:null,payload:g,networkDetails:v})},onError:(m,h,p,v)=>{this.resetLoader(e,u),l(new Zn({type:_e.NETWORK_ERROR,details:z.FRAG_LOAD_ERROR,fatal:!1,frag:e,response:jt({url:n,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:p,stats:v}))},onAbort:(m,h,p)=>{this.resetLoader(e,u),l(new Zn({type:_e.NETWORK_ERROR,details:z.INTERNAL_ABORTED,fatal:!1,frag:e,error:new Error("Aborted"),networkDetails:p,stats:m}))},onTimeout:(m,h,p)=>{this.resetLoader(e,u),l(new Zn({type:_e.NETWORK_ERROR,details:z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:p,stats:m}))},onProgress:(m,h,p,v)=>{r&&r({frag:e,part:null,payload:p,networkDetails:v})}})})}loadPart(e,r,n){this.abort();const i=this.config,s=i.fLoader,a=i.loader;return new Promise((o,l)=>{if(this.loader&&this.loader.destroy(),e.gap||r.gap){l($v(e,r));return}const u=this.loader=e.loader=s?new s(i):new a(i),c=Bv(e,r),d=Ov(i.fragLoadPolicy.default),f={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:Uv};r.stats=u.stats,u.load(c,f,{onSuccess:(m,h,p,v)=>{this.resetLoader(e,u),this.updateStatsFromPart(e,r);const g={frag:e,part:r,payload:m.data,networkDetails:v};n(g),o(g)},onError:(m,h,p,v)=>{this.resetLoader(e,u),l(new Zn({type:_e.NETWORK_ERROR,details:z.FRAG_LOAD_ERROR,fatal:!1,frag:e,part:r,response:jt({url:c.url,data:void 0},m),error:new Error(`HTTP Error ${m.code} ${m.text}`),networkDetails:p,stats:v}))},onAbort:(m,h,p)=>{e.stats.aborted=r.stats.aborted,this.resetLoader(e,u),l(new Zn({type:_e.NETWORK_ERROR,details:z.INTERNAL_ABORTED,fatal:!1,frag:e,part:r,error:new Error("Aborted"),networkDetails:p,stats:m}))},onTimeout:(m,h,p)=>{this.resetLoader(e,u),l(new Zn({type:_e.NETWORK_ERROR,details:z.FRAG_LOAD_TIMEOUT,fatal:!1,frag:e,part:r,error:new Error(`Timeout after ${f.timeout}ms`),networkDetails:p,stats:m}))}})})}updateStatsFromPart(e,r){const n=e.stats,i=r.stats,s=i.total;if(n.loaded+=i.loaded,s){const l=Math.round(e.duration/r.duration),u=Math.min(Math.round(n.loaded/s),l),d=(l-u)*Math.round(n.loaded/u);n.total=n.loaded+d}else n.total=Math.max(n.loaded,n.total);const a=n.loading,o=i.loading;a.start?a.first+=o.first-o.start:(a.start=o.start,a.first=o.first),a.end=o.end}resetLoader(e,r){e.loader=null,this.loader===r&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),r.destroy()}}function Bv(t,e=null){const r=e||t,n={frag:t,part:e,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},i=r.byteRangeStartOffset,s=r.byteRangeEndOffset;if(pe(i)&&pe(s)){var a;let o=i,l=s;if(t.sn==="initSegment"&&((a=t.decryptdata)==null?void 0:a.method)==="AES-128"){const u=s-i;u%16&&(l=s+(16-u%16)),i!==0&&(n.resetIV=!0,o=i-16)}n.rangeStart=o,n.rangeEnd=l}return n}function $v(t,e){const r=new Error(`GAP ${t.gap?"tag":"attribute"} found`),n={type:_e.MEDIA_ERROR,details:z.FRAG_GAP,fatal:!1,frag:t,error:r,networkDetails:null};return e&&(n.part=e),(e||t).stats.aborted=!0,new Zn(n)}class Zn extends Error{constructor(e){super(e.error.message),this.data=void 0,this.data=e}}class _O{constructor(e,r){this.subtle=void 0,this.aesIV=void 0,this.subtle=e,this.aesIV=r}decrypt(e,r){return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},r,e)}}class CO{constructor(e,r){this.subtle=void 0,this.key=void 0,this.subtle=e,this.key=r}expandKey(){return this.subtle.importKey("raw",this.key,{name:"AES-CBC"},!1,["encrypt","decrypt"])}}function RO(t){const e=t.byteLength,r=e&&new DataView(t.buffer).getUint8(e-1);return r?hs(t,0,e-r):t}class IO{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 r=new DataView(e),n=new Uint32Array(4);for(let i=0;i<4;i++)n[i]=r.getUint32(i*4);return n}initTable(){const e=this.sBox,r=this.invSBox,n=this.subMix,i=n[0],s=n[1],a=n[2],o=n[3],l=this.invSubMix,u=l[0],c=l[1],d=l[2],f=l[3],m=new Uint32Array(256);let h=0,p=0,v=0;for(v=0;v<256;v++)v<128?m[v]=v<<1:m[v]=v<<1^283;for(v=0;v<256;v++){let g=p^p<<1^p<<2^p<<3^p<<4;g=g>>>8^g&255^99,e[h]=g,r[g]=h;const y=m[h],x=m[y],S=m[x];let T=m[g]*257^g*16843008;i[h]=T<<24|T>>>8,s[h]=T<<16|T>>>16,a[h]=T<<8|T>>>24,o[h]=T,T=S*16843009^x*65537^y*257^h*16843008,u[g]=T<<24|T>>>8,c[g]=T<<16|T>>>16,d[g]=T<<8|T>>>24,f[g]=T,h?(h=y^m[m[m[S^y]]],p^=m[m[p]]):h=p=1}}expandKey(e){const r=this.uint8ArrayToUint32Array_(e);let n=!0,i=0;for(;ithis.subtle?(this.logOnce("WebCrypto AES decrypt"),new _O(this.subtle,new Uint8Array(n)).decrypt(e.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(U.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(e,r,n)))}onWebCryptoError(e,r,n){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(e,r,n);const i=this.flush();if(i)return i.buffer;throw new Error("WebCrypto and softwareDecrypt: failed to decrypt data")}getValidChunk(e){let r=e;const n=e.length-e.length%kO;return n!==e.length&&(r=hs(e,0,n),this.remainderData=hs(e,n)),r}logOnce(e){this.logEnabled&&(U.log(`[decrypter]: ${e}`),this.logEnabled=!1)}}const DO={toString:function(t){let e="";const r=t.length;for(let n=0;no.end){const d=a>c;(a{if(this.fragContextChanged(e)){this.warn(`Fragment ${e.sn}${s.part?" p: "+s.part.index:""} of level ${e.level} was dropped during download.`),this.fragmentTracker.removeFragment(e);return}e.stats.chunkCount++,this._handleFragmentLoadProgress(s)};this._doFragLoad(e,r,n,i).then(s=>{if(!s)return;const a=this.state;if(this.fragContextChanged(e)){(a===Y.FRAG_LOADING||!this.fragCurrent&&a===Y.PARSING)&&(this.fragmentTracker.removeFragment(e),this.state=Y.IDLE);return}"payload"in s&&(this.log(`Loaded fragment ${e.sn} of level ${e.level}`),this.hls.trigger(w.FRAG_LOADED,s)),this._handleFragmentLoadComplete(s)}).catch(s=>{this.state===Y.STOPPED||this.state===Y.ERROR||(this.warn(`Frag error: ${(s==null?void 0:s.message)||s}`),this.resetFragmentLoading(e))})}clearTrackerIfNeeded(e){var r;const{fragmentTracker:n}=this;if(n.getState(e)===Bt.APPENDING){const s=e.type,a=this.getFwdBufferInfo(this.mediaBuffer,s),o=Math.max(e.duration,a?a.len:this.config.maxBufferLength),l=this.backtrackFragment;((l?e.sn-l.sn:0)===1||this.reduceMaxBufferLength(o,e.duration))&&n.removeFragment(e)}else((r=this.mediaBuffer)==null?void 0:r.buffered.length)===0?n.removeAllFragments():n.hasParts(e.type)&&(n.detectPartialFragments({frag:e,part:null,stats:e.stats,id:e.type}),n.getState(e)===Bt.PARTIAL&&n.removeFragment(e))}checkLiveUpdate(e){if(e.updated&&!e.live){const r=e.fragments[e.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}e.fragments[0]||(e.deltaUpdateFailed=!0)}flushMainBuffer(e,r,n=null){if(!(e-r))return;const i={startOffset:e,endOffset:r,type:n};this.hls.trigger(w.BUFFER_FLUSHING,i)}_loadInitSegment(e,r){this._doFragLoad(e,r).then(n=>{if(!n||this.fragContextChanged(e)||!this.levels)throw new Error("init load aborted");return n}).then(n=>{const{hls:i}=this,{payload:s}=n,a=e.decryptdata;if(s&&s.byteLength>0&&a!=null&&a.key&&a.iv&&a.method==="AES-128"){const o=self.performance.now();return this.decrypter.decrypt(new Uint8Array(s),a.key.buffer,a.iv.buffer).catch(l=>{throw i.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:e}),l}).then(l=>{const u=self.performance.now();return i.trigger(w.FRAG_DECRYPTED,{frag:e,payload:l,stats:{tstart:o,tdecrypt:u}}),n.payload=l,this.completeInitSegmentLoad(n)})}return this.completeInitSegmentLoad(n)}).catch(n=>{this.state===Y.STOPPED||this.state===Y.ERROR||(this.warn(n),this.resetFragmentLoading(e))})}completeInitSegmentLoad(e){const{levels:r}=this;if(!r)throw new Error("init load aborted, missing levels");const n=e.frag.stats;this.state=Y.IDLE,e.frag.data=new Uint8Array(e.payload),n.parsing.start=n.buffering.start=self.performance.now(),n.parsing.end=n.buffering.end=self.performance.now(),this.tick()}fragContextChanged(e){const{fragCurrent:r}=this;return!e||!r||e.sn!==r.sn||e.level!==r.level}fragBufferedComplete(e,r){var n,i,s,a;const o=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${e.type} sn: ${e.sn}${r?" part: "+r.index:""} of ${this.playlistType===we.MAIN?"level":"track"} ${e.level} (frag:[${((n=e.startPTS)!=null?n:NaN).toFixed(3)}-${((i=e.endPTS)!=null?i:NaN).toFixed(3)}] > buffer:${o?DO.toString(at.getBuffered(o)):"(detached)"})`),e.sn!=="initSegment"){var l;if(e.type!==we.SUBTITLE){const c=e.elementaryStreams;if(!Object.keys(c).some(d=>!!c[d])){this.state=Y.IDLE;return}}const u=(l=this.levels)==null?void 0:l[e.level];u!=null&&u.fragmentError&&(this.log(`Resetting level fragment error count of ${u.fragmentError} on frag buffered`),u.fragmentError=0)}this.state=Y.IDLE,o&&(!this.loadedmetadata&&e.type==we.MAIN&&o.buffered.length&&((s=this.fragCurrent)==null?void 0:s.sn)===((a=this.fragPrevious)==null?void 0:a.sn)&&(this.loadedmetadata=!0,this.seekToStartPos()),this.tick())}seekToStartPos(){}_handleFragmentLoadComplete(e){const{transmuxer:r}=this;if(!r)return;const{frag:n,part:i,partsLoaded:s}=e,a=!s||s.length===0||s.some(l=>!l),o=new km(n.level,n.sn,n.stats.chunkCount+1,0,i?i.index:-1,!a);r.flush(o)}_handleFragmentLoadProgress(e){}_doFragLoad(e,r,n=null,i){var s;const a=r==null?void 0:r.details;if(!this.levels||!a)throw new Error(`frag load aborted, missing level${a?"":" detail"}s`);let o=null;if(e.encrypted&&!((s=e.decryptdata)!=null&&s.key)?(this.log(`Loading key for ${e.sn} of [${a.startSN}-${a.endSN}], ${this.logPrefix==="[stream-controller]"?"level":"track"} ${e.level}`),this.state=Y.KEY_LOADING,this.fragCurrent=e,o=this.keyLoader.load(e).then(c=>{if(!this.fragContextChanged(c.frag))return this.hls.trigger(w.KEY_LOADED,c),this.state===Y.KEY_LOADING&&(this.state=Y.IDLE),c}),this.hls.trigger(w.KEY_LOADING,{frag:e}),this.fragCurrent===null&&(o=Promise.reject(new Error("frag load aborted, context changed in KEY_LOADING")))):!e.encrypted&&a.encryptedFragments.length&&this.keyLoader.loadClear(e,a.encryptedFragments),n=Math.max(e.start,n||0),this.config.lowLatencyMode&&e.sn!=="initSegment"){const c=a.partList;if(c&&i){n>e.end&&a.fragmentHint&&(e=a.fragmentHint);const d=this.getNextPart(c,e,n);if(d>-1){const f=c[d];this.log(`Loading part sn: ${e.sn} p: ${f.index} cc: ${e.cc} of playlist [${a.startSN}-${a.endSN}] parts [0-${d}-${c.length-1}] ${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(n.toFixed(3))}`),this.nextLoadPosition=f.start+f.duration,this.state=Y.FRAG_LOADING;let m;return o?m=o.then(h=>!h||this.fragContextChanged(h.frag)?null:this.doFragPartsLoad(e,f,r,i)).catch(h=>this.handleFragLoadError(h)):m=this.doFragPartsLoad(e,f,r,i).catch(h=>this.handleFragLoadError(h)),this.hls.trigger(w.FRAG_LOADING,{frag:e,part:f,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):m}else if(!e.url||this.loadedEndOfParts(c,n))return Promise.resolve(null)}}this.log(`Loading fragment ${e.sn} cc: ${e.cc} ${a?"of ["+a.startSN+"-"+a.endSN+"] ":""}${this.logPrefix==="[stream-controller]"?"level":"track"}: ${e.level}, target: ${parseFloat(n.toFixed(3))}`),pe(e.sn)&&!this.bitrateTest&&(this.nextLoadPosition=e.start+e.duration),this.state=Y.FRAG_LOADING;const l=this.config.progressive;let u;return l&&o?u=o.then(c=>!c||this.fragContextChanged(c==null?void 0:c.frag)?null:this.fragmentLoader.load(e,i)).catch(c=>this.handleFragLoadError(c)):u=Promise.all([this.fragmentLoader.load(e,l?i:void 0),o]).then(([c])=>(!l&&c&&i&&i(c),c)).catch(c=>this.handleFragLoadError(c)),this.hls.trigger(w.FRAG_LOADING,{frag:e,targetBufferTime:n}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):u}doFragPartsLoad(e,r,n,i){return new Promise((s,a)=>{var o;const l=[],u=(o=n.details)==null?void 0:o.partList,c=d=>{this.fragmentLoader.loadPart(e,d,i).then(f=>{l[d.index]=f;const m=f.part;this.hls.trigger(w.FRAG_LOADED,f);const h=Dv(n,e.sn,d.index+1)||RT(u,e.sn,d.index+1);if(h)c(h);else return s({frag:e,part:m,partsLoaded:l})}).catch(a)};c(r)})}handleFragLoadError(e){if("data"in e){const r=e.data;e.data&&r.details===z.INTERNAL_ABORTED?this.handleFragLoadAborted(r.frag,r.part):this.hls.trigger(w.ERROR,r)}else this.hls.trigger(w.ERROR,{type:_e.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,err:e,error:e,fatal:!0});return null}_handleTransmuxerFlush(e){const r=this.getCurrentContext(e);if(!r||this.state!==Y.PARSING){!this.fragCurrent&&this.state!==Y.STOPPED&&this.state!==Y.ERROR&&(this.state=Y.IDLE);return}const{frag:n,part:i,level:s}=r,a=self.performance.now();n.stats.parsing.end=a,i&&(i.stats.parsing.end=a),this.updateLevelTiming(n,i,s,e.partial)}getCurrentContext(e){const{levels:r,fragCurrent:n}=this,{level:i,sn:s,part:a}=e;if(!(r!=null&&r[i]))return this.warn(`Levels object was unset while buffering fragment ${s} of level ${i}. The current chunk will not be buffered.`),null;const o=r[i],l=a>-1?Dv(o,s,a):null,u=l?l.fragment:eO(o,s,n);return u?(n&&n!==u&&(u.stats=n.stats),{frag:u,part:l,level:o}):null}bufferFragmentData(e,r,n,i,s){var a;if(!e||this.state!==Y.PARSING)return;const{data1:o,data2:l}=e;let u=o;if(o&&l&&(u=Jr(o,l)),!((a=u)!=null&&a.length))return;const c={type:e.type,frag:r,part:n,chunkMeta:i,parent:r.type,data:u};if(this.hls.trigger(w.BUFFER_APPENDING,c),e.dropped&&e.independent&&!n){if(s)return;this.flushBufferGap(r)}}flushBufferGap(e){const r=this.media;if(!r)return;if(!at.isBuffered(r,r.currentTime)){this.flushMainBuffer(0,e.start);return}const n=r.currentTime,i=at.bufferInfo(r,n,0),s=e.duration,a=Math.min(this.config.maxFragLookUpTolerance*2,s*.25),o=Math.max(Math.min(e.start-a,i.end-a),n+a);e.start-o>a&&this.flushMainBuffer(o,e.start)}getFwdBufferInfo(e,r){const n=this.getLoadPosition();return pe(n)?this.getFwdBufferInfoAtPos(e,n,r):null}getFwdBufferInfoAtPos(e,r,n){const{config:{maxBufferHole:i}}=this,s=at.bufferInfo(e,r,i);if(s.len===0&&s.nextStart!==void 0){const a=this.fragmentTracker.getBufferedFrag(r,n);if(a&&s.nextStart=i?(n.maxMaxBufferLength=s,this.warn(`Reduce max buffer length to ${s}s`),!0):!1}getAppendedFrag(e,r=we.MAIN){const n=this.fragmentTracker.getAppendedFrag(e,we.MAIN);return n&&"fragment"in n?n.fragment:n}getNextFragment(e,r){const n=r.fragments,i=n.length;if(!i)return null;const{config:s}=this,a=n[0].start;let o;if(r.live){const l=s.initialLiveManifestSize;if(ir}getNextFragmentLoopLoading(e,r,n,i,s){const a=e.gap,o=this.getNextFragment(this.nextLoadPosition,r);if(o===null)return o;if(e=o,a&&e&&!e.gap&&n.nextStart){const l=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,n.nextStart,i);if(l!==null&&n.len+l.len>=s)return this.log(`buffer full after gaps in "${i}" playlist starting at sn: ${e.sn}`),null}return e}mapToInitFragWhenRequired(e){return e!=null&&e.initSegment&&!(e!=null&&e.initSegment.data)&&!this.bitrateTest?e.initSegment:e}getNextPart(e,r,n){let i=-1,s=!1,a=!0;for(let o=0,l=e.length;o-1&&nn.start&&n.loaded}getInitialLiveFragment(e,r){const n=this.fragPrevious;let i=null;if(n){if(e.hasProgramDateTime&&(this.log(`Live playlist, switching playlist, load frag with same PDT: ${n.programDateTime}`),i=rO(r,n.endProgramDateTime,this.config.maxFragLookUpTolerance)),!i){const s=n.sn+1;if(s>=e.startSN&&s<=e.endSN){const a=r[s-e.startSN];n.cc===a.cc&&(i=a,this.log(`Live playlist, switching playlist, load frag with next SN: ${i.sn}`))}i||(i=sO(r,n.cc),i&&this.log(`Live playlist, switching playlist, load frag with same CC: ${i.sn}`))}}else{const s=this.hls.liveSyncPosition;s!==null&&(i=this.getFragmentAtPosition(s,this.bitrateTest?e.fragmentEnd:e.edge,e))}return i}getFragmentAtPosition(e,r,n){const{config:i}=this;let{fragPrevious:s}=this,{fragments:a,endSN:o}=n;const{fragmentHint:l}=n,{maxFragLookUpTolerance:u}=i,c=n.partList,d=!!(i.lowLatencyMode&&c!=null&&c.length&&l);d&&l&&!this.bitrateTest&&(a=a.concat(l),o=l.sn);let f;if(er-u?0:u;f=Vc(s,a,e,m)}else f=a[a.length-1];if(f){const m=f.sn-n.startSN,h=this.fragmentTracker.getState(f);if((h===Bt.OK||h===Bt.PARTIAL&&f.gap)&&(s=f),s&&f.sn===s.sn&&(!d||c[0].fragment.sn>f.sn)&&s&&f.level===s.level){const v=a[m+1];f.sn=a-r.maxFragLookUpTolerance&&s<=o;if(i!==null&&n.duration>i&&(s${e.startSN} prev-sn: ${l?l.sn:"na"} fragments: ${i}`),u}return s}waitForCdnTuneIn(e){return e.live&&e.canBlockReload&&e.partTarget&&e.tuneInGoal>Math.max(e.partHoldBack,e.partTarget*3)}setStartPosition(e,r){let n=this.startPosition;if(n ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const s=r.details===z.FRAG_GAP;s&&this.fragmentTracker.fragBuffered(n,!0);const a=r.errorAction,{action:o,retryCount:l=0,retryConfig:u}=a||{};if(a&&o===zt.RetryRequest&&u){this.resetStartWhenNotLoaded(this.levelLastLoaded);const c=Rm(u,l);this.warn(`Fragment ${n.sn} of ${e} ${n.level} errored with ${r.details}, retrying loading ${l+1}/${u.maxNumRetry} in ${c}ms`),a.resolved=!0,this.retryDate=self.performance.now()+c,this.state=Y.FRAG_LOADING_WAITING_RETRY}else if(u&&a)if(this.resetFragmentErrors(e),l.5;s&&this.reduceMaxBufferLength(i.len,(r==null?void 0:r.duration)||10);const a=!s;return a&&this.warn(`Buffer full error while media.currentTime is not buffered, flush ${n} buffer`),r&&(this.fragmentTracker.removeFragment(r),this.nextLoadPosition=r.start),this.resetLoadingState(),a}return!1}resetFragmentErrors(e){e===we.AUDIO&&(this.fragCurrent=null),this.loadedmetadata||(this.startFragRequested=!1),this.state!==Y.STOPPED&&(this.state=Y.IDLE)}afterBufferFlushed(e,r,n){if(!e)return;const i=at.getBuffered(e);this.fragmentTracker.detectEvictedFragments(r,i,n),this.state===Y.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state=Y.IDLE}resetStartWhenNotLoaded(e){if(!this.loadedmetadata){this.startFragRequested=!1;const r=e?e.details:null;r!=null&&r.live?(this.startPosition=-1,this.setStartPosition(r,0),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(e){this.warn(`The loading context changed while buffering fragment ${e.sn} of level ${e.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState()}removeUnbufferedFrags(e=0){this.fragmentTracker.removeFragmentsInRange(e,1/0,this.playlistType,!1,!0)}updateLevelTiming(e,r,n,i){var s;const a=n.details;if(!a){this.warn("level.details undefined");return}if(!Object.keys(e.elementaryStreams).reduce((l,u)=>{const c=e.elementaryStreams[u];if(c){const d=c.endPTS-c.startPTS;if(d<=0)return this.warn(`Could not parse fragment ${e.sn} ${u} duration reliably (${d})`),l||!1;const f=i?0:_T(a,e,c.startPTS,c.endPTS,c.startDTS,c.endDTS);return this.hls.trigger(w.LEVEL_PTS_UPDATED,{details:a,level:n,drift:f,type:u,frag:e,start:c.startPTS,end:c.endPTS}),!0}return l},!1)&&((s=this.transmuxer)==null?void 0:s.error)===null){const l=new Error(`Found no media in fragment ${e.sn} of level ${e.level} resetting transmuxer to fallback to playlist timing`);if(n.fragmentError===0&&(n.fragmentError++,e.gap=!0,this.fragmentTracker.removeFragment(e),this.fragmentTracker.fragBuffered(e,!0)),this.warn(l.message),this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,error:l,frag:e,reason:`Found no media in msn ${e.sn} of level "${n.url}"`}),!this.hls)return;this.resetTransmuxer()}this.state=Y.PARSED,this.hls.trigger(w.FRAG_PARSED,{frag:e,part:r})}resetTransmuxer(){this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null)}recoverWorkerError(e){e.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.resetTransmuxer(),this.resetStartWhenNotLoaded(this.levelLastLoaded),this.resetLoadingState())}set state(e){const r=this._state;r!==e&&(this._state=e,this.log(`${r}->${e}`))}get state(){return this._state}}class OT{constructor(){this.chunks=[],this.dataLength=0}push(e){this.chunks.push(e),this.dataLength+=e.length}flush(){const{chunks:e,dataLength:r}=this;let n;if(e.length)e.length===1?n=e[0]:n=PO(e,r);else return new Uint8Array(0);return this.reset(),n}reset(){this.chunks.length=0,this.dataLength=0}}function PO(t,e){const r=new Uint8Array(e);let n=0;for(let i=0;i0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:n,type:dn.audioId3,duration:Number.POSITIVE_INFINITY});i{if(pe(t))return t*90;const n=r?r.baseTime*9e4/r.timescale:0;return e*9e4+n};function UO(t,e,r,n){let i,s,a,o;const l=navigator.userAgent.toLowerCase(),u=n,c=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350];i=((e[r+2]&192)>>>6)+1;const d=(e[r+2]&60)>>>2;if(d>c.length-1){const f=new Error(`invalid ADTS sampling index:${d}`);t.emit(w.ERROR,w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}return a=(e[r+2]&1)<<2,a|=(e[r+3]&192)>>>6,U.log(`manifest codec:${n}, ADTS type:${i}, samplingIndex:${d}`),/firefox/i.test(l)?d>=6?(i=5,o=new Array(4),s=d-3):(i=2,o=new Array(2),s=d):l.indexOf("android")!==-1?(i=2,o=new Array(2),s=d):(i=5,o=new Array(4),n&&(n.indexOf("mp4a.40.29")!==-1||n.indexOf("mp4a.40.5")!==-1)||!n&&d>=6?s=d-3:((n&&n.indexOf("mp4a.40.2")!==-1&&(d>=6&&a===1||/vivaldi/i.test(l))||!n&&a===1)&&(i=2,o=new Array(2)),s=d)),o[0]=i<<3,o[0]|=(d&14)>>1,o[1]|=(d&1)<<7,o[1]|=a<<3,i===5&&(o[1]|=(s&14)>>1,o[2]=(s&1)<<7,o[2]|=8,o[3]=0),{config:o,samplerate:c[d],channelCount:a,codec:"mp4a.40."+i,manifestCodec:u}}function MT(t,e){return t[e]===255&&(t[e+1]&246)===240}function NT(t,e){return t[e+1]&1?7:9}function Mm(t,e){return(t[e+3]&3)<<11|t[e+4]<<3|(t[e+5]&224)>>>5}function BO(t,e){return e+5=t.length)return!1;const n=Mm(t,e);if(n<=r)return!1;const i=e+n;return i===t.length||zc(t,i)}return!1}function FT(t,e,r,n,i){if(!t.samplerate){const s=UO(e,r,n,i);if(!s)return;t.config=s.config,t.samplerate=s.samplerate,t.channelCount=s.channelCount,t.codec=s.codec,t.manifestCodec=s.manifestCodec,U.log(`parsed codec:${t.codec}, rate:${s.samplerate}, channels:${s.channelCount}`)}}function UT(t){return 1024*9e4/t}function VO(t,e){const r=NT(t,e);if(e+r<=t.length){const n=Mm(t,e)-r;if(n>0)return{headerLength:r,frameLength:n}}}function BT(t,e,r,n,i){const s=UT(t.samplerate),a=n+i*s,o=VO(e,r);let l;if(o){const{frameLength:d,headerLength:f}=o,m=f+d,h=Math.max(0,r+m-e.length);h?(l=new Uint8Array(m-f),l.set(e.subarray(r+f,e.length),0)):l=e.subarray(r+f,r+m);const p={unit:l,pts:a};return h||t.samples.push(p),{sample:p,length:m,missing:h}}const u=e.length-r;return l=new Uint8Array(u),l.set(e.subarray(r,e.length),0),{sample:{unit:l,pts:a},length:u,missing:-1}}let au=null;const GO=[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],zO=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],HO=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],WO=[0,1,1,4];function $T(t,e,r,n,i){if(r+24>e.length)return;const s=jT(e,r);if(s&&r+s.frameLength<=e.length){const a=s.samplesPerFrame*9e4/s.sampleRate,o=n+i*a,l={unit:e.subarray(r,r+s.frameLength),pts:o,dts:o};return t.config=[],t.channelCount=s.channelCount,t.samplerate=s.sampleRate,t.samples.push(l),{sample:l,length:s.frameLength,missing:0}}}function jT(t,e){const r=t[e+1]>>3&3,n=t[e+1]>>1&3,i=t[e+2]>>4&15,s=t[e+2]>>2&3;if(r!==1&&i!==0&&i!==15&&s!==3){const a=t[e+2]>>1&1,o=t[e+3]>>6,l=r===3?3-n:n===3?3:4,u=GO[l*14+i-1]*1e3,d=zO[(r===3?0:r===2?1:2)*3+s],f=o===3?1:2,m=HO[r][n],h=WO[n],p=m*8*h,v=Math.floor(m*u/d+a)*h;if(au===null){const x=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);au=x?parseInt(x[1]):0}return!!au&&au<=87&&n===2&&u>=224e3&&o===0&&(t[e+3]=t[e+3]|128),{sampleRate:d,channelCount:f,frameLength:v,samplesPerFrame:p}}}function Nm(t,e){return t[e]===255&&(t[e+1]&224)===224&&(t[e+1]&6)!==0}function VT(t,e){return e+1{const a=bP(s);if(qO.test(a.schemeIdUri)){const o=pe(a.presentationTime)?a.presentationTime/a.timeScale:r+a.presentationTimeDelta/a.timeScale;let l=a.eventDuration===4294967295?Number.POSITIVE_INFINITY:a.eventDuration/a.timeScale;l<=.001&&(l=Number.POSITIVE_INFINITY);const u=a.payload;n.samples.push({data:u,len:u.byteLength,dts:o,pts:o,type:dn.emsg,duration:l})}})}return n}demuxSampleAes(e,r,n){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){}}const zT=(t,e)=>{let r=0,n=5;e+=n;const i=new Uint32Array(1),s=new Uint32Array(1),a=new Uint8Array(1);for(;n>0;){a[0]=t[e];const o=Math.min(n,8),l=8-o;s[0]=4278190080>>>24+l<>l,r=r?r<e.length||e[r]!==11||e[r+1]!==119)return-1;const s=e[r+4]>>6;if(s>=3)return-1;const o=[48e3,44100,32e3][s],l=e[r+4]&63,c=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][l*3+s]*2;if(r+c>e.length)return-1;const d=e[r+6]>>5;let f=0;d===2?f+=2:(d&1&&d!==1&&(f+=2),d&4&&(f+=2));const m=(e[r+6]<<8|e[r+7])>>12-f&1,p=[2,1,2,3,3,4,4,5][d]+m,v=e[r+5]>>3,g=e[r+5]&7,y=new Uint8Array([s<<6|v<<1|g>>2,(g&3)<<6|d<<3|m<<2|l>>4,l<<4&224]),x=1536/o*9e4,S=n+i*x,T=e.subarray(r,r+c);return t.config=y,t.channelCount=p,t.samplerate=o,t.samples.push({unit:T,pts:S}),c}class QO{constructor(){this.VideoSample=null}createVideoSample(e,r,n,i){return{key:e,frame:!1,pts:r,dts:n,units:[],debug:i,length:0}}getLastNalUnit(e){var r;let n=this.VideoSample,i;if((!n||n.units.length===0)&&(n=e[e.length-1]),(r=n)!=null&&r.units){const s=n.units;i=s[s.length-1]}return i}pushAccessUnit(e,r){if(e.units.length&&e.frame){if(e.pts===void 0){const n=r.samples,i=n.length;if(i){const s=n[i-1];e.pts=s.pts,e.dts=s.dts}else{r.dropped++;return}}r.samples.push(e)}e.debug.length&&U.log(e.pts+"/"+e.dts+":"+e.debug)}}class jv{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,r=this.bytesAvailable,n=e.byteLength-r,i=new Uint8Array(4),s=Math.min(4,r);if(s===0)throw new Error("no bytes available");i.set(e.subarray(n,n+s)),this.word=new DataView(i.buffer).getUint32(0),this.bitsAvailable=s*8,this.bytesAvailable-=s}skipBits(e){let r;e=Math.min(e,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>e?(this.word<<=e,this.bitsAvailable-=e):(e-=this.bitsAvailable,r=e>>3,e-=r<<3,this.bytesAvailable-=r,this.loadWord(),this.word<<=e,this.bitsAvailable-=e)}readBits(e){let r=Math.min(this.bitsAvailable,e);const n=this.word>>>32-r;if(e>32&&U.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=r,this.bitsAvailable>0)this.word<<=r;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return r=e-r,r>0&&this.bitsAvailable?n<>>e)return this.word<<=e,this.bitsAvailable-=e,e;return this.loadWord(),e+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){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)}skipScalingList(e){let r=8,n=8,i;for(let s=0;s{var d;switch(c.type){case 1:{let p=!1;l=!0;const v=c.data;if(u&&v.length>4){const g=new jv(v).readSliceType();(g===2||g===4||g===7||g===9)&&(p=!0)}if(p){var f;(f=o)!=null&&f.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null)}o||(o=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts,"")),o.frame=!0,o.key=p;break}case 5:l=!0,(d=o)!=null&&d.frame&&!o.key&&(this.pushAccessUnit(o,e),o=this.VideoSample=null),o||(o=this.VideoSample=this.createVideoSample(!0,n.pts,n.dts,"")),o.key=!0,o.frame=!0;break;case 6:{l=!0,ET(c.data,1,n.pts,r.samples);break}case 7:{var m,h;l=!0,u=!0;const p=c.data,g=new jv(p).readSPS();if(!e.sps||e.width!==g.width||e.height!==g.height||((m=e.pixelRatio)==null?void 0:m[0])!==g.pixelRatio[0]||((h=e.pixelRatio)==null?void 0:h[1])!==g.pixelRatio[1]){e.width=g.width,e.height=g.height,e.pixelRatio=g.pixelRatio,e.sps=[p],e.duration=s;const y=p.subarray(1,4);let x="avc1.";for(let S=0;S<3;S++){let T=y[S].toString(16);T.length<2&&(T="0"+T),x+=T}e.codec=x}break}case 8:l=!0,e.pps=[c.data];break;case 9:l=!0,e.audFound=!0,o&&this.pushAccessUnit(o,e),o=this.VideoSample=this.createVideoSample(!1,n.pts,n.dts,"");break;case 12:l=!0;break;default:l=!1,o&&(o.debug+="unknown NAL "+c.type+" ");break}o&&l&&o.units.push(c)}),i&&o&&(this.pushAccessUnit(o,e),this.VideoSample=null)}parseAVCNALu(e,r){const n=r.byteLength;let i=e.naluState||0;const s=i,a=[];let o=0,l,u,c,d=-1,f=0;for(i===-1&&(d=0,f=r[0]&31,i=0,o=1);o=0){const m={data:r.subarray(d,u),type:f};a.push(m)}else{const m=this.getLastNalUnit(e.samples);m&&(s&&o<=4-s&&m.state&&(m.data=m.data.subarray(0,m.data.byteLength-s)),u>0&&(m.data=Jr(m.data,r.subarray(0,u)),m.state=0))}o=0&&i>=0){const m={data:r.subarray(d,n),type:f,state:i};a.push(m)}if(a.length===0){const m=this.getLastNalUnit(e.samples);m&&(m.data=Jr(m.data,r))}return e.naluState=i,a}}class eM{constructor(e,r,n){this.keyData=void 0,this.decrypter=void 0,this.keyData=n,this.decrypter=new Dm(r,{removePKCS7Padding:!1})}decryptBuffer(e){return this.decrypter.decrypt(e,this.keyData.key.buffer,this.keyData.iv.buffer)}decryptAacSample(e,r,n){const i=e[r].unit;if(i.length<=16)return;const s=i.subarray(16,i.length-i.length%16),a=s.buffer.slice(s.byteOffset,s.byteOffset+s.length);this.decryptBuffer(a).then(o=>{const l=new Uint8Array(o);i.set(l,16),this.decrypter.isSync()||this.decryptAacSamples(e,r+1,n)})}decryptAacSamples(e,r,n){for(;;r++){if(r>=e.length){n();return}if(!(e[r].unit.length<32)&&(this.decryptAacSample(e,r,n),!this.decrypter.isSync()))return}}getAvcEncryptedData(e){const r=Math.floor((e.length-48)/160)*16+16,n=new Int8Array(r);let i=0;for(let s=32;s{s.data=this.getAvcDecryptedUnit(a,l),this.decrypter.isSync()||this.decryptAvcSamples(e,r,n+1,i)})}decryptAvcSamples(e,r,n,i){if(e instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;r++,n=0){if(r>=e.length){i();return}const s=e[r].units;for(;!(n>=s.length);n++){const a=s[n];if(!(a.data.length<=48||a.type!==1&&a.type!==5)&&(this.decryptAvcSample(e,r,n,i,a),!this.decrypter.isSync()))return}}}}const Ft=188;class Ti{constructor(e,r,n){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._duration=0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=e,this.config=r,this.typeSupported=n,this.videoParser=new JO}static probe(e){const r=Ti.syncOffset(e);return r>0&&U.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(e){const r=e.length;let n=Math.min(Ft*5,r-Ft)+1,i=0;for(;i1&&(a===0&&o>2||l+Ft>n))return a}else{if(o)return-1;break}i++}return-1}static createTrack(e,r){return{container:e==="video"||e==="audio"?"video/mp2t":void 0,type:e,id:gT[e],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:e==="audio"?r:void 0}}resetInitSegment(e,r,n,i){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=Ti.createTrack("video"),this._audioTrack=Ti.createTrack("audio",i),this._id3Track=Ti.createTrack("id3"),this._txtTrack=Ti.createTrack("text"),this._audioTrack.segmentCodec="aac",this.aacOverFlow=null,this.remainderData=null,this.audioCodec=r,this.videoCodec=n,this._duration=i}resetTimeStamp(){}resetContiguity(){const{_audioTrack:e,_videoTrack:r,_id3Track:n}=this;e&&(e.pesData=null),r&&(r.pesData=null),n&&(n.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(e,r,n=!1,i=!1){n||(this.sampleAes=null);let s;const a=this._videoTrack,o=this._audioTrack,l=this._id3Track,u=this._txtTrack;let c=a.pid,d=a.pesData,f=o.pid,m=l.pid,h=o.pesData,p=l.pesData,v=null,g=this.pmtParsed,y=this._pmtId,x=e.length;if(this.remainderData&&(e=Jr(this.remainderData,e),x=e.length,this.remainderData=null),x>4;let k;if(A>1){if(k=_+5+e[_+4],k===_+Ft)continue}else k=_+4;switch(I){case c:b&&(d&&(s=Fs(d))&&this.videoParser.parseAVCPES(a,u,s,!1,this._duration),d={data:[],size:0}),d&&(d.data.push(e.subarray(k,_+Ft)),d.size+=_+Ft-k);break;case f:if(b){if(h&&(s=Fs(h)))switch(o.segmentCodec){case"aac":this.parseAACPES(o,s);break;case"mp3":this.parseMPEGPES(o,s);break;case"ac3":this.parseAC3PES(o,s);break}h={data:[],size:0}}h&&(h.data.push(e.subarray(k,_+Ft)),h.size+=_+Ft-k);break;case m:b&&(p&&(s=Fs(p))&&this.parseID3PES(l,s),p={data:[],size:0}),p&&(p.data.push(e.subarray(k,_+Ft)),p.size+=_+Ft-k);break;case 0:b&&(k+=e[k]+1),y=this._pmtId=tM(e,k);break;case y:{b&&(k+=e[k]+1);const O=rM(e,k,this.typeSupported,n,this.observer);c=O.videoPid,c>0&&(a.pid=c,a.segmentCodec=O.segmentVideoCodec),f=O.audioPid,f>0&&(o.pid=f,o.segmentCodec=O.segmentAudioCodec),m=O.id3Pid,m>0&&(l.pid=m),v!==null&&!g&&(U.warn(`MPEG-TS PMT found at ${_} after unknown PID '${v}'. Backtracking to sync byte @${S} to parse all TS packets.`),v=null,_=S-188),g=this.pmtParsed=!0;break}case 17:case 8191:break;default:v=I;break}}else T++;T>0&&Hc(this.observer,new Error(`Found ${T} TS packet/s that do not start with 0x47`)),a.pesData=d,o.pesData=h,l.pesData=p;const C={audioTrack:o,videoTrack:a,id3Track:l,textTrack:u};return i&&this.extractRemainingSamples(C),C}flush(){const{remainderData:e}=this;this.remainderData=null;let r;return e?r=this.demux(e,-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(e){const{audioTrack:r,videoTrack:n,id3Track:i,textTrack:s}=e,a=n.pesData,o=r.pesData,l=i.pesData;let u;if(a&&(u=Fs(a))?(this.videoParser.parseAVCPES(n,s,u,!0,this._duration),n.pesData=null):n.pesData=a,o&&(u=Fs(o))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,u);break;case"mp3":this.parseMPEGPES(r,u);break;case"ac3":this.parseAC3PES(r,u);break}r.pesData=null}else o!=null&&o.size&&U.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=o;l&&(u=Fs(l))?(this.parseID3PES(i,u),i.pesData=null):i.pesData=l}demuxSampleAes(e,r,n){const i=this.demux(e,n,!0,!this.config.progressive),s=this.sampleAes=new eM(this.observer,this.config,r);return this.decrypt(i,s)}decrypt(e,r){return new Promise(n=>{const{audioTrack:i,videoTrack:s}=e;i.samples&&i.segmentCodec==="aac"?r.decryptAacSamples(i.samples,0,()=>{s.samples?r.decryptAvcSamples(s.samples,0,0,()=>{n(e)}):n(e)}):s.samples&&r.decryptAvcSamples(s.samples,0,0,()=>{n(e)})})}destroy(){this._duration=0}parseAACPES(e,r){let n=0;const i=this.aacOverFlow;let s=r.data;if(i){this.aacOverFlow=null;const d=i.missing,f=i.sample.unit.byteLength;if(d===-1)s=Jr(i.sample.unit,s);else{const m=f-d;i.sample.unit.set(s.subarray(0,d),m),e.samples.push(i.sample),n=i.missing}}let a,o;for(a=n,o=s.length;a0;)o+=l}}parseID3PES(e,r){if(r.pts===void 0){U.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const n=It({},r,{type:this._videoTrack?dn.emsg:dn.audioId3,duration:Number.POSITIVE_INFINITY});e.samples.push(n)}}function ep(t,e){return((t[e+1]&31)<<8)+t[e+2]}function tM(t,e){return(t[e+10]&31)<<8|t[e+11]}function rM(t,e,r,n,i){const s={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},a=(t[e+1]&15)<<8|t[e+2],o=e+3+a-4,l=(t[e+10]&15)<<8|t[e+11];for(e+=12+l;e0){let d=e+5,f=c;for(;f>2;){switch(t[d]){case 106:r.ac3!==!0?U.log("AC-3 audio found, not supported in this browser for now"):(s.audioPid=u,s.segmentAudioCodec="ac3");break}const h=t[d+1]+2;d+=h,f-=h}}break;case 194:case 135:return Hc(i,new Error("Unsupported EC-3 in M2TS found")),s;case 36:return Hc(i,new Error("Unsupported HEVC in M2TS found")),s}e+=c+5}return s}function Hc(t,e,r){U.warn(`parsing error: ${e.message}`),t.emit(w.ERROR,w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,error:e,reason:e.message})}function Cf(t){U.log(`${t} with AES-128-CBC encryption found in unencrypted stream`)}function Fs(t){let e=0,r,n,i,s,a;const o=t.data;if(!t||t.size===0)return null;for(;o[0].length<19&&o.length>1;)o[0]=Jr(o[0],o[1]),o.splice(1,1);if(r=o[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(n=(r[4]<<8)+r[5],n&&n>t.size-6)return null;const u=r[7];u&192&&(s=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,u&64?(a=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,s-a>60*9e4&&(U.warn(`${Math.round((s-a)/9e4)}s delta between PTS and DTS, align them`),s=a)):a=s),i=r[8];let c=i+9;if(t.size<=c)return null;t.size-=c;const d=new Uint8Array(t.size);for(let f=0,m=o.length;fh){c-=h;continue}else r=r.subarray(c),h-=c,c=0;d.set(r,e),e+=h}return n&&(n-=i+3),{data:d,pts:s,dts:a,len:n}}return null}class nM extends Om{resetInitSegment(e,r,n,i){super.resetInitSegment(e,r,n,i),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:r,duration:i,inputTimeScale:9e4,dropped:0}}static probe(e){if(!e)return!1;const r=fl(e,0);let n=(r==null?void 0:r.length)||0;if(r&&e[n]===11&&e[n+1]===119&&Cm(r)!==void 0&&zT(e,n)<=16)return!1;for(let i=e.length;n>24&255,a[1]=n>>16&255,a[2]=n>>8&255,a[3]=n&255,a.set(e,4),i=0,n=8;i>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,i>>24,i>>16&255,i>>8&255,i&255,85,196,0,0]))}static mdia(e){return B.box(B.types.mdia,B.mdhd(e.timescale,e.duration),B.hdlr(e.type),B.minf(e))}static mfhd(e){return B.box(B.types.mfhd,new Uint8Array([0,0,0,0,e>>24,e>>16&255,e>>8&255,e&255]))}static minf(e){return e.type==="audio"?B.box(B.types.minf,B.box(B.types.smhd,B.SMHD),B.DINF,B.stbl(e)):B.box(B.types.minf,B.box(B.types.vmhd,B.VMHD),B.DINF,B.stbl(e))}static moof(e,r,n){return B.box(B.types.moof,B.mfhd(e),B.traf(n,r))}static moov(e){let r=e.length;const n=[];for(;r--;)n[r]=B.trak(e[r]);return B.box.apply(null,[B.types.moov,B.mvhd(e[0].timescale,e[0].duration)].concat(n).concat(B.mvex(e)))}static mvex(e){let r=e.length;const n=[];for(;r--;)n[r]=B.trex(e[r]);return B.box.apply(null,[B.types.mvex,...n])}static mvhd(e,r){r*=e;const n=Math.floor(r/(yi+1)),i=Math.floor(r%(yi+1)),s=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,e>>24&255,e>>16&255,e>>8&255,e&255,n>>24,n>>16&255,n>>8&255,n&255,i>>24,i>>16&255,i>>8&255,i&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return B.box(B.types.mvhd,s)}static sdtp(e){const r=e.samples||[],n=new Uint8Array(4+r.length);let i,s;for(i=0;i>>8&255),r.push(a&255),r=r.concat(Array.prototype.slice.call(s));for(i=0;i>>8&255),n.push(a&255),n=n.concat(Array.prototype.slice.call(s));const o=B.box(B.types.avcC,new Uint8Array([1,r[3],r[4],r[5],255,224|e.sps.length].concat(r).concat([e.pps.length]).concat(n))),l=e.width,u=e.height,c=e.pixelRatio[0],d=e.pixelRatio[1];return B.box(B.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,l>>8&255,l&255,u>>8&255,u&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),o,B.box(B.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),B.box(B.types.pasp,new Uint8Array([c>>24,c>>16&255,c>>8&255,c&255,d>>24,d>>16&255,d>>8&255,d&255])))}static esds(e){const r=e.config.length;return new Uint8Array([0,0,0,0,3,23+r,0,1,0,4,15+r,64,21,0,0,0,0,0,0,0,0,0,0,0,5].concat([r]).concat(e.config).concat([6,1,2]))}static audioStsd(e){const r=e.samplerate;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,e.channelCount,0,16,0,0,0,0,r>>8&255,r&255,0,0])}static mp4a(e){return B.box(B.types.mp4a,B.audioStsd(e),B.box(B.types.esds,B.esds(e)))}static mp3(e){return B.box(B.types[".mp3"],B.audioStsd(e))}static ac3(e){return B.box(B.types["ac-3"],B.audioStsd(e),B.box(B.types.dac3,e.config))}static stsd(e){return e.type==="audio"?e.segmentCodec==="mp3"&&e.codec==="mp3"?B.box(B.types.stsd,B.STSD,B.mp3(e)):e.segmentCodec==="ac3"?B.box(B.types.stsd,B.STSD,B.ac3(e)):B.box(B.types.stsd,B.STSD,B.mp4a(e)):B.box(B.types.stsd,B.STSD,B.avc1(e))}static tkhd(e){const r=e.id,n=e.duration*e.timescale,i=e.width,s=e.height,a=Math.floor(n/(yi+1)),o=Math.floor(n%(yi+1));return B.box(B.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,a>>24,a>>16&255,a>>8&255,a&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,i>>8&255,i&255,0,0,s>>8&255,s&255,0,0]))}static traf(e,r){const n=B.sdtp(e),i=e.id,s=Math.floor(r/(yi+1)),a=Math.floor(r%(yi+1));return B.box(B.types.traf,B.box(B.types.tfhd,new Uint8Array([0,0,0,0,i>>24,i>>16&255,i>>8&255,i&255])),B.box(B.types.tfdt,new Uint8Array([1,0,0,0,s>>24,s>>16&255,s>>8&255,s&255,a>>24,a>>16&255,a>>8&255,a&255])),B.trun(e,n.length+16+20+8+16+8+8),n)}static trak(e){return e.duration=e.duration||4294967295,B.box(B.types.trak,B.tkhd(e),B.mdia(e))}static trex(e){const r=e.id;return B.box(B.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(e,r){const n=e.samples||[],i=n.length,s=12+16*i,a=new Uint8Array(s);let o,l,u,c,d,f;for(r+=8+s,a.set([e.type==="video"?1:0,0,15,1,i>>>24&255,i>>>16&255,i>>>8&255,i&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255],0),o=0;o>>24&255,u>>>16&255,u>>>8&255,u&255,c>>>24&255,c>>>16&255,c>>>8&255,c&255,d.isLeading<<2|d.dependsOn,d.isDependedOn<<6|d.hasRedundancy<<4|d.paddingValue<<1|d.isNonSync,d.degradPrio&61440,d.degradPrio&15,f>>>24&255,f>>>16&255,f>>>8&255,f&255],12+16*o);return B.box(B.types.trun,a)}static initSegment(e){B.types||B.init();const r=B.moov(e);return Jr(B.FTYP,r)}}B.types=void 0;B.HDLR_TYPES=void 0;B.STTS=void 0;B.STSC=void 0;B.STCO=void 0;B.STSZ=void 0;B.VMHD=void 0;B.SMHD=void 0;B.STSD=void 0;B.FTYP=void 0;B.DINF=void 0;const WT=9e4;function Fm(t,e,r=1,n=!1){const i=t*e*r;return n?Math.round(i):i}function iM(t,e,r=1,n=!1){return Fm(t,e,1/r,n)}function io(t,e=!1){return Fm(t,1e3,1/WT,e)}function sM(t,e=1){return Fm(t,WT,1/e)}const aM=10*1e3,Gv=1024,oM=1152,lM=1536;let Us=null,Rf=null;class Nu{constructor(e,r,n,i=""){if(this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextAvcDts=null,this.nextAudioPts=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=e,this.config=r,this.typeSupported=n,this.ISGenerated=!1,Us===null){const a=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);Us=a?parseInt(a[1]):0}if(Rf===null){const s=navigator.userAgent.match(/Safari\/(\d+)/i);Rf=s?parseInt(s[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(e){U.log("[mp4-remuxer]: initPTS & initDTS reset"),this._initPTS=this._initDTS=e}resetNextTimestamp(){U.log("[mp4-remuxer]: reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){U.log("[mp4-remuxer]: ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(e){let r=!1;const n=e.reduce((i,s)=>{const a=s.pts-i;return a<-4294967296?(r=!0,Hr(i,s.pts)):a>0?i:s.pts},e[0].pts);return r&&U.debug("PTS rollover detected"),n}remux(e,r,n,i,s,a,o,l){let u,c,d,f,m,h,p=s,v=s;const g=e.pid>-1,y=r.pid>-1,x=r.samples.length,S=e.samples.length>0,T=o&&x>0||x>1;if((!g||S)&&(!y||T)||this.ISGenerated||o){if(this.ISGenerated){var _,b,I,A;const G=this.videoTrackConfig;G&&(r.width!==G.width||r.height!==G.height||((_=r.pixelRatio)==null?void 0:_[0])!==((b=G.pixelRatio)==null?void 0:b[0])||((I=r.pixelRatio)==null?void 0:I[1])!==((A=G.pixelRatio)==null?void 0:A[1]))&&this.resetInitSegment()}else d=this.generateIS(e,r,s,a);const k=this.isVideoContiguous;let O=-1,P;if(T&&(O=uM(r.samples),!k&&this.config.forceKeyFrameOnDiscontinuity))if(h=!0,O>0){U.warn(`[mp4-remuxer]: Dropped ${O} out of ${x} video samples due to a missing keyframe`);const G=this.getVideoStartPts(r.samples);r.samples=r.samples.slice(O),r.dropped+=O,v+=(r.samples[0].pts-G)/r.inputTimeScale,P=v}else O===-1&&(U.warn(`[mp4-remuxer]: No keyframe found out of ${x} video samples`),h=!1);if(this.ISGenerated){if(S&&T){const G=this.getVideoStartPts(r.samples),H=(Hr(e.samples[0].pts,G)-G)/r.inputTimeScale;p+=Math.max(0,H),v+=Math.max(0,-H)}if(S){if(e.samplerate||(U.warn("[mp4-remuxer]: regenerate InitSegment as audio detected"),d=this.generateIS(e,r,s,a)),c=this.remuxAudio(e,p,this.isAudioContiguous,a,y||T||l===we.AUDIO?v:void 0),T){const G=c?c.endPTS-c.startPTS:0;r.inputTimeScale||(U.warn("[mp4-remuxer]: regenerate InitSegment as video detected"),d=this.generateIS(e,r,s,a)),u=this.remuxVideo(r,v,k,G)}}else T&&(u=this.remuxVideo(r,v,k,0));u&&(u.firstKeyFrame=O,u.independent=O!==-1,u.firstKeyFramePTS=P)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(n.samples.length&&(m=KT(n,s,this._initPTS,this._initDTS)),i.samples.length&&(f=YT(i,s,this._initPTS))),{audio:c,video:u,initSegment:d,independent:h,text:f,id3:m}}generateIS(e,r,n,i){const s=e.samples,a=r.samples,o=this.typeSupported,l={},u=this._initPTS;let c=!u||i,d="audio/mp4",f,m,h;if(c&&(f=m=1/0),e.config&&s.length){switch(e.timescale=e.samplerate,e.segmentCodec){case"mp3":o.mpeg?(d="audio/mpeg",e.codec=""):o.mp3&&(e.codec="mp3");break;case"ac3":e.codec="ac-3";break}l.audio={id:"audio",container:d,codec:e.codec,initSegment:e.segmentCodec==="mp3"&&o.mpeg?new Uint8Array(0):B.initSegment([e]),metadata:{channelCount:e.channelCount}},c&&(h=e.inputTimeScale,!u||h!==u.timescale?f=m=s[0].pts-Math.round(h*n):c=!1)}if(r.sps&&r.pps&&a.length){if(r.timescale=r.inputTimeScale,l.video={id:"main",container:"video/mp4",codec:r.codec,initSegment:B.initSegment([r]),metadata:{width:r.width,height:r.height}},c)if(h=r.inputTimeScale,!u||h!==u.timescale){const p=this.getVideoStartPts(a),v=Math.round(h*n);m=Math.min(m,Hr(a[0].dts,p)-v),f=Math.min(f,p-v)}else c=!1;this.videoTrackConfig={width:r.width,height:r.height,pixelRatio:r.pixelRatio}}if(Object.keys(l).length)return this.ISGenerated=!0,c?(this._initPTS={baseTime:f,timescale:h},this._initDTS={baseTime:m,timescale:h}):f=h=void 0,{tracks:l,initPTS:f,timescale:h}}remuxVideo(e,r,n,i){const s=e.inputTimeScale,a=e.samples,o=[],l=a.length,u=this._initPTS;let c=this.nextAvcDts,d=8,f=this.videoSampleDuration,m,h,p=Number.POSITIVE_INFINITY,v=Number.NEGATIVE_INFINITY,g=!1;if(!n||c===null){const F=r*s,j=a[0].pts-Hr(a[0].dts,a[0].pts);Us&&c!==null&&Math.abs(F-j-c)<15e3?n=!0:c=F-j}const y=u.baseTime*s/u.timescale;for(let F=0;F0?F-1:F].dts&&(g=!0)}g&&a.sort(function(F,j){const te=F.dts-j.dts,ee=F.pts-j.pts;return te||ee}),m=a[0].dts,h=a[a.length-1].dts;const x=h-m,S=x?Math.round(x/(l-1)):f||e.inputTimeScale/30;if(n){const F=m-c,j=F>S,te=F<-1;if((j||te)&&(j?U.warn(`AVC: ${io(F,!0)} ms (${F}dts) hole between fragments detected at ${r.toFixed(3)}`):U.warn(`AVC: ${io(-F,!0)} ms (${F}dts) overlapping between fragments detected at ${r.toFixed(3)}`),!te||c>=a[0].pts||Us)){m=c;const ee=a[0].pts-F;if(j)a[0].dts=m,a[0].pts=ee;else for(let fe=0;feee);fe++)a[fe].dts-=F,a[fe].pts-=F;U.log(`Video: Initial PTS/DTS adjusted: ${io(ee,!0)}/${io(m,!0)}, delta: ${io(F,!0)} ms`)}}m=Math.max(0,m);let T=0,C=0,_=m;for(let F=0;F0?j.dts-a[F-1].dts:S;if(fe=F>0?j.pts-a[F-1].pts:S,Re.stretchShortVideoTrack&&this.nextAudioPts!==null){const Fe=Math.floor(Re.maxBufferHole*s),st=(i?p+i*s:this.nextAudioPts)-j.pts;st>Fe?(f=st-Ee,f<0?f=Ee:k=!0,U.log(`[mp4-remuxer]: It is approximately ${st/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=Ee}else f=Ee}const ye=Math.round(j.pts-j.dts);O=Math.min(O,f),G=Math.max(G,f),P=Math.min(P,fe),K=Math.max(K,fe),o.push(new zv(j.key,f,ee,ye))}if(o.length){if(Us){if(Us<70){const F=o[0].flags;F.dependsOn=2,F.isNonSync=0}}else if(Rf&&K-P0&&(i&&Math.abs(y-g)<9e3||Math.abs(Hr(p[0].pts-x,y)-g)<20*c),p.forEach(function(H){H.pts=Hr(H.pts-x,y)}),!n||g<0){if(p=p.filter(H=>H.pts>=0),!p.length)return;s===0?g=0:i&&!h?g=Math.max(0,y):g=p[0].pts}if(e.segmentCodec==="aac"){const H=this.config.maxAudioFramesDrift;for(let se=0,W=g;se=H*c&&ee0){_+=v;try{C=new Uint8Array(_)}catch(ee){this.observer.emit(w.ERROR,w.ERROR,{type:_e.MUX_ERROR,details:z.REMUX_ALLOC_ERROR,fatal:!1,error:ee,bytes:_,reason:`fail allocating audio mdat ${_}`});return}f||(new DataView(C.buffer).setUint32(0,_),C.set(B.types.mdat,4))}else return;C.set(F,v);const te=F.byteLength;v+=te,m.push(new zv(!0,u,te,0)),T=j}const I=m.length;if(!I)return;const A=m[m.length-1];this.nextAudioPts=g=T+l*A.duration;const k=f?new Uint8Array(0):B.moof(e.sequenceNumber++,S/l,It({},e,{samples:m}));e.samples=[];const O=S/a,P=g/a,K={data1:k,data2:C,startPTS:O,endPTS:P,startDTS:O,endDTS:P,type:"audio",hasAudio:!0,hasVideo:!1,nb:I};return this.isAudioContiguous=!0,K}remuxEmptyAudio(e,r,n,i){const s=e.inputTimeScale,a=e.samplerate?e.samplerate:s,o=s/a,l=this.nextAudioPts,u=this._initDTS,c=u.baseTime*9e4/u.timescale,d=(l!==null?l:i.startDTS*s)+c,f=i.endDTS*s+c,m=o*Gv,h=Math.ceil((f-d)/m),p=Vv.getSilentFrame(e.manifestCodec||e.codec,e.channelCount);if(U.warn("[mp4-remuxer]: remux empty Audio"),!p){U.trace("[mp4-remuxer]: Unable to remuxEmptyAudio since we were unable to get a silent frame for given audio codec");return}const v=[];for(let g=0;g4294967296;)t+=r;return t}function uM(t){for(let e=0;ea.pts-o.pts);const s=t.samples;return t.samples=[],{samples:s}}class zv{constructor(e,r,n,i){this.size=void 0,this.duration=void 0,this.cts=void 0,this.flags=void 0,this.duration=r,this.size=n,this.cts=i,this.flags={isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:e?2:1,isNonSync:e?0:1}}}class cM{constructor(){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}destroy(){}resetTimeStamp(e){this.initPTS=e,this.lastEndTime=null}resetNextTimestamp(){this.lastEndTime=null}resetInitSegment(e,r,n,i){this.audioCodec=r,this.videoCodec=n,this.generateInitSegment(gP(e,i)),this.emitInitSegment=!0}generateInitSegment(e){let{audioCodec:r,videoCodec:n}=this;if(!(e!=null&&e.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const i=this.initData=xT(e);i.audio&&(r=Hv(i.audio,Je.AUDIO)),i.video&&(n=Hv(i.video,Je.VIDEO));const s={};i.audio&&i.video?s.audiovideo={container:"video/mp4",codec:r+","+n,initSegment:e,id:"main"}:i.audio?s.audio={container:"audio/mp4",codec:r,initSegment:e,id:"audio"}:i.video?s.video={container:"video/mp4",codec:n,initSegment:e,id:"main"}:U.warn("[passthrough-remuxer.ts]: initSegment does not contain moov or trak boxes."),this.initTracks=s}remux(e,r,n,i,s,a){var o,l;let{initPTS:u,lastEndTime:c}=this;const d={audio:void 0,video:void 0,text:i,id3:n,initSegment:void 0};pe(c)||(c=this.lastEndTime=s||0);const f=r.samples;if(!(f!=null&&f.length))return d;const m={initPTS:void 0,timescale:1};let h=this.initData;if((o=h)!=null&&o.length||(this.generateInitSegment(f),h=this.initData),!((l=h)!=null&&l.length))return U.warn("[passthrough-remuxer.ts]: Failed to generate initSegment."),d;this.emitInitSegment&&(m.tracks=this.initTracks,this.emitInitSegment=!1);const p=yP(f,h),v=vP(h,f),g=v===null?s:v;(dM(u,g,s,p)||m.timescale!==u.timescale&&a)&&(m.initPTS=g-s,u&&u.timescale===1&&U.warn(`Adjusting initPTS by ${m.initPTS-u.baseTime}`),this.initPTS=u={baseTime:m.initPTS,timescale:1});const y=e?g-u.baseTime/u.timescale:c,x=y+p;SP(h,f,u.baseTime/u.timescale),p>0?this.lastEndTime=x:(U.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const S=!!h.audio,T=!!h.video;let C="";S&&(C+="audio"),T&&(C+="video");const _={data1:f,startPTS:y,startDTS:y,endPTS:x,endDTS:x,type:C,hasAudio:S,hasVideo:T,nb:1,dropped:0};return d.audio=_.type==="audio"?_:void 0,d.video=_.type!=="audio"?_:void 0,d.initSegment=m,d.id3=KT(n,s,u,u),i.samples.length&&(d.text=YT(i,s,u)),d}}function dM(t,e,r,n){if(t===null)return!0;const i=Math.max(n,1),s=e-t.baseTime/t.timescale;return Math.abs(s-r)>i}function Hv(t,e){const r=t==null?void 0:t.codec;if(r&&r.length>4)return r;if(e===Je.AUDIO){if(r==="ec-3"||r==="ac-3"||r==="alac")return r;if(r==="fLaC"||r==="Opus")return Uc(r,!1);const n="mp4a.40.5";return U.info(`Parsed audio codec "${r}" or audio object type not handled. Using "${n}"`),n}return U.warn(`Unhandled video codec "${r}"`),r==="hvc1"||r==="hev1"?"hvc1.1.6.L120.90":r==="av01"?"av01.0.04M.08":"avc1.42e01e"}let Qn;try{Qn=self.performance.now.bind(self.performance)}catch{U.debug("Unable to use Performance API on this environment"),Qn=Ra==null?void 0:Ra.Date.now}const Fu=[{demux:XO,remux:cM},{demux:Ti,remux:Nu},{demux:YO,remux:Nu},{demux:nM,remux:Nu}];Fu.splice(2,0,{demux:ZO,remux:Nu});class Wv{constructor(e,r,n,i,s){this.async=!1,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.vendor=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=r,this.config=n,this.vendor=i,this.id=s}configure(e){this.transmuxConfig=e,this.decrypter&&this.decrypter.reset()}push(e,r,n,i){const s=n.transmuxing;s.executeStart=Qn();let a=new Uint8Array(e);const{currentTransmuxState:o,transmuxConfig:l}=this;i&&(this.currentTransmuxState=i);const{contiguous:u,discontinuity:c,trackSwitch:d,accurateTimeOffset:f,timeOffset:m,initSegmentChange:h}=i||o,{audioCodec:p,videoCodec:v,defaultInitPts:g,duration:y,initSegmentData:x}=l,S=fM(a,r);if(S&&S.method==="AES-128"){const b=this.getDecrypter();if(b.isSync()){let I=b.softwareDecrypt(a,S.key.buffer,S.iv.buffer);if(n.part>-1&&(I=b.flush()),!I)return s.executeEnd=Qn(),If(n);a=new Uint8Array(I)}else return this.decryptionPromise=b.webCryptoDecrypt(a,S.key.buffer,S.iv.buffer).then(I=>{const A=this.push(I,null,n);return this.decryptionPromise=null,A}),this.decryptionPromise}const T=this.needsProbing(c,d);if(T){const b=this.configureTransmuxer(a);if(b)return U.warn(`[transmuxer] ${b.message}`),this.observer.emit(w.ERROR,w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,fatal:!1,error:b,reason:b.message}),s.executeEnd=Qn(),If(n)}(c||d||h||T)&&this.resetInitSegment(x,p,v,y,r),(c||h||T)&&this.resetInitialTimestamp(g),u||this.resetContiguity();const C=this.transmux(a,S,m,f,n),_=this.currentTransmuxState;return _.contiguous=!0,_.discontinuity=!1,_.trackSwitch=!1,s.executeEnd=Qn(),C}flush(e){const r=e.transmuxing;r.executeStart=Qn();const{decrypter:n,currentTransmuxState:i,decryptionPromise:s}=this;if(s)return s.then(()=>this.flush(e));const a=[],{timeOffset:o}=i;if(n){const d=n.flush();d&&a.push(this.push(d,null,e))}const{demuxer:l,remuxer:u}=this;if(!l||!u)return r.executeEnd=Qn(),[If(e)];const c=l.flush(o);return Uu(c)?c.then(d=>(this.flushRemux(a,d,e),a)):(this.flushRemux(a,c,e),a)}flushRemux(e,r,n){const{audioTrack:i,videoTrack:s,id3Track:a,textTrack:o}=r,{accurateTimeOffset:l,timeOffset:u}=this.currentTransmuxState;U.log(`[transmuxer.ts]: Flushed fragment ${n.sn}${n.part>-1?" p: "+n.part:""} of level ${n.level}`);const c=this.remuxer.remux(i,s,a,o,u,l,!0,this.id);e.push({remuxResult:c,chunkMeta:n}),n.transmuxing.executeEnd=Qn()}resetInitialTimestamp(e){const{demuxer:r,remuxer:n}=this;!r||!n||(r.resetTimeStamp(e),n.resetTimeStamp(e))}resetContiguity(){const{demuxer:e,remuxer:r}=this;!e||!r||(e.resetContiguity(),r.resetNextTimestamp())}resetInitSegment(e,r,n,i,s){const{demuxer:a,remuxer:o}=this;!a||!o||(a.resetInitSegment(e,r,n,i),o.resetInitSegment(e,r,n,s))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(e,r,n,i,s){let a;return r&&r.method==="SAMPLE-AES"?a=this.transmuxSampleAes(e,r,n,i,s):a=this.transmuxUnencrypted(e,n,i,s),a}transmuxUnencrypted(e,r,n,i){const{audioTrack:s,videoTrack:a,id3Track:o,textTrack:l}=this.demuxer.demux(e,r,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(s,a,o,l,r,n,!1,this.id),chunkMeta:i}}transmuxSampleAes(e,r,n,i,s){return this.demuxer.demuxSampleAes(e,r,n).then(a=>({remuxResult:this.remuxer.remux(a.audioTrack,a.videoTrack,a.id3Track,a.textTrack,n,i,!1,this.id),chunkMeta:s}))}configureTransmuxer(e){const{config:r,observer:n,typeSupported:i,vendor:s}=this;let a;for(let f=0,m=Fu.length;f0&&(e==null?void 0:e.key)!=null&&e.iv!==null&&e.method!=null&&(r=e),r}const If=t=>({remuxResult:{},chunkMeta:t});function Uu(t){return"then"in t&&t.then instanceof Function}class hM{constructor(e,r,n,i,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=r,this.initSegmentData=n,this.duration=i,this.defaultInitPts=s||null}}class pM{constructor(e,r,n,i,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=r,this.accurateTimeOffset=n,this.trackSwitch=i,this.timeOffset=s,this.initSegmentChange=a}}var qT={exports:{}};(function(t){var e=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=!1));function i(l,u,c){this.fn=l,this.context=u,this.once=c||!1}function s(l,u,c,d,f){if(typeof c!="function")throw new TypeError("The listener must be a function");var m=new i(c,d||l,f),h=r?r+u:u;return l._events[h]?l._events[h].fn?l._events[h]=[l._events[h],m]:l._events[h].push(m):(l._events[h]=m,l._eventsCount++),l}function a(l,u){--l._eventsCount===0?l._events=new n:delete l._events[u]}function o(){this._events=new n,this._eventsCount=0}o.prototype.eventNames=function(){var u=[],c,d;if(this._eventsCount===0)return u;for(d in c=this._events)e.call(c,d)&&u.push(r?d.slice(1):d);return Object.getOwnPropertySymbols?u.concat(Object.getOwnPropertySymbols(c)):u},o.prototype.listeners=function(u){var c=r?r+u:u,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var f=0,m=d.length,h=new Array(m);f{c=c||{},c.frag=this.frag,c.id=this.id,u===w.ERROR&&(this.error=c.error),this.hls.trigger(u,c)};this.observer=new Um,this.observer.on(w.FRAG_DECRYPTED,a),this.observer.on(w.ERROR,a);const o=bs(s.preferManagedMediaSource)||{isTypeSupported:()=>!1},l={mpeg:o.isTypeSupported("audio/mpeg"),mp3:o.isTypeSupported('audio/mp4; codecs="mp3"'),ac3:o.isTypeSupported('audio/mp4; codecs="ac-3"')};if(this.useWorker&&typeof Worker<"u"&&(s.workerPath||OO())){try{s.workerPath?(U.log(`loading Web Worker ${s.workerPath} for "${r}"`),this.workerContext=NO(s.workerPath)):(U.log(`injecting Web Worker for "${r}"`),this.workerContext=MO()),this.onwmsg=d=>this.onWorkerMessage(d);const{worker:c}=this.workerContext;c.addEventListener("message",this.onwmsg),c.onerror=d=>{const f=new Error(`${d.message} (${d.filename}:${d.lineno})`);s.enableWorker=!1,U.warn(`Error in "${r}" Web Worker, fallback to inline`),this.hls.trigger(w.ERROR,{type:_e.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:f})},c.postMessage({cmd:"init",typeSupported:l,vendor:"",id:r,config:JSON.stringify(s)})}catch(c){U.warn(`Error setting up "${r}" Web Worker, fallback to inline`,c),this.resetWorker(),this.error=null,this.transmuxer=new Wv(this.observer,l,s,"",r)}return}this.transmuxer=new Wv(this.observer,l,s,"",r)}resetWorker(){if(this.workerContext){const{worker:e,objectURL:r}=this.workerContext;r&&self.URL.revokeObjectURL(r),e.removeEventListener("message",this.onwmsg),e.onerror=null,e.terminate(),this.workerContext=null}}destroy(){if(this.workerContext)this.resetWorker(),this.onwmsg=void 0;else{const r=this.transmuxer;r&&(r.destroy(),this.transmuxer=null)}const e=this.observer;e&&e.removeAllListeners(),this.frag=null,this.observer=null,this.hls=null}push(e,r,n,i,s,a,o,l,u,c){var d,f;u.transmuxing.start=self.performance.now();const{transmuxer:m}=this,h=a?a.start:s.start,p=s.decryptdata,v=this.frag,g=!(v&&s.cc===v.cc),y=!(v&&u.level===v.level),x=v?u.sn-v.sn:-1,S=this.part?u.part-this.part.index:-1,T=x===0&&u.id>1&&u.id===(v==null?void 0:v.stats.chunkCount),C=!y&&(x===1||x===0&&(S===1||T&&S<=0)),_=self.performance.now();(y||x||s.stats.parsing.start===0)&&(s.stats.parsing.start=_),a&&(S||!C)&&(a.stats.parsing.start=_);const b=!(v&&((d=s.initSegment)==null?void 0:d.url)===((f=v.initSegment)==null?void 0:f.url)),I=new pM(g,C,l,y,h,b);if(!C||g||b){U.log(`[transmuxer-interface, ${s.type}]: Starting new transmux session for sn: ${u.sn} p: ${u.part} level: ${u.level} id: ${u.id} discontinuity: ${g} trackSwitch: ${y} contiguous: ${C} accurateTimeOffset: ${l} timeOffset: ${h} - initSegmentChange: ${b}`);const A=new pM(n,i,r,o,c);this.configureTransmuxer(A)}if(this.frag=s,this.part=a,this.workerContext)this.workerContext.worker.postMessage({cmd:"demux",data:e,decryptdata:p,chunkMeta:u,state:I},e instanceof ArrayBuffer?[e]:[]);else if(m){const A=m.push(e,p,u,I);Uu(A)?(m.async=!0,A.then(k=>{this.handleTransmuxComplete(k)}).catch(k=>{this.transmuxerError(k,u,"transmuxer-interface push error")})):(m.async=!1,this.handleTransmuxComplete(A))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(r){let n=r.flush(e);Uu(n)||r.async?(Uu(n)||(n=Promise.resolve(n)),n.then(s=>{this.handleFlushResult(s,e)}).catch(s=>{this.transmuxerError(s,e,"transmuxer-interface flush error")})):this.handleFlushResult(n,e)}}transmuxerError(e,r,n){this.hls&&(this.error=e,this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,chunkMeta:r,frag:this.frag||void 0,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,r){e.forEach(n=>{this.handleTransmuxComplete(n)}),this.onFlush(r)}onWorkerMessage(e){const r=e.data;if(!(r!=null&&r.event)){U.warn(`worker message received with no ${r?"event name":"data"}`);return}const n=this.hls;if(this.hls)switch(r.event){case"init":{var i;const s=(i=this.workerContext)==null?void 0:i.objectURL;s&&self.URL.revokeObjectURL(s);break}case"transmuxComplete":{this.handleTransmuxComplete(r.data);break}case"flush":{this.onFlush(r.data);break}case"workerLog":U[r.data.logType]&&U[r.data.logType](r.data.message);break;default:{r.data=r.data||{},r.data.frag=this.frag,r.data.id=this.id,n.trigger(r.event,r.data);break}}}configureTransmuxer(e){const{transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):r&&r.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function ZT(t,e){if(t.length!==e.length)return!1;for(let r=0;rt[i]!==e[i])}function tp(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}const Kv=100;class vM extends Pm{constructor(e,r,n){super(e,r,n,"[audio-stream-controller]",we.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-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.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(w.ERROR,this.onError,this),e.on(w.BUFFER_RESET,this.onBufferReset,this),e.on(w.BUFFER_CREATED,this.onBufferCreated,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(w.ERROR,this.onError,this),e.off(w.BUFFER_RESET,this.onBufferReset,this),e.off(w.BUFFER_CREATED,this.onBufferCreated,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:r,id:n,initPTS:i,timescale:s}){if(n==="main"){const a=r.cc;this.initPTS[r.cc]={baseTime:i,timescale:s},this.log(`InitPTS for cc: ${a} found from main: ${i}`),this.videoTrackCC=a,this.state===Y.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=Y.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(Kv),r>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r,this.state=Y.IDLE):(this.loadedmetadata=!1,this.state=Y.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case Y.IDLE:this.doTickIdle();break;case Y.WAITING_TRACK:{var e;const{levels:n,trackId:i}=this,s=n==null||(e=n[i])==null?void 0:e.details;if(s){if(this.waitForCdnTuneIn(s))break;this.state=Y.WAITING_INIT_PTS}break}case Y.FRAG_LOADING_WAITING_RETRY:{var r;const n=performance.now(),i=this.retryDate;if(!i||n>=i||(r=this.media)!=null&&r.seeking){const{levels:s,trackId:a}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((s==null?void 0:s[a])||null),this.state=Y.IDLE}break}case Y.WAITING_INIT_PTS:{const n=this.waitingData;if(n){const{frag:i,part:s,cache:a,complete:o}=n;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=Y.FRAG_LOADING;const l=a.flush(),u={frag:i,part:s,payload:l,networkDetails:null};this._handleFragmentLoadProgress(u),o&&super._handleFragmentLoadComplete(u)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),u=at.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);Jh(u.end,this.config.maxFragLookUpTolerance,i)<0&&(this.log(`Waiting fragment cc (${i.cc}) @ ${i.start} cancelled because another fragment at ${u.end} is needed`),this.clearWaitingFragment())}}else this.state=Y.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Y.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:r,media:n,trackId:i}=this,s=e.config;if(!n&&(this.startFragRequested||!s.startFragPrefetch)||!(r!=null&&r[i]))return;const a=r[i],o=a.details;if(!o||o.live&&this.levelLastLoaded!==a||this.waitForCdnTuneIn(o)){this.state=Y.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Je.AUDIO,we.AUDIO));const u=this.getFwdBufferInfo(l,we.AUDIO);if(u===null)return;const{bufferedTrack:c,switchingTrack:d}=this;if(!d&&this._streamEnded(u,o)){e.trigger(w.BUFFER_EOS,{type:"audio"}),this.state=Y.ENDED;return}const f=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,we.MAIN),m=u.len,h=this.getMaxBufferLength(f==null?void 0:f.len),p=o.fragments,v=p[0].start;let g=this.flushing?this.getLoadPosition():u.end;if(d&&n){const T=this.getLoadPosition();c&&!ka(d.attrs,c.attrs)&&(g=T),o.PTSKnown&&Tv||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=v+.05)}if(m>=h&&!d&&gf.end+o.targetduration;if(S||!(f!=null&&f.len)&&u.len){const T=this.getAppendedFrag(y.start,we.MAIN);if(T===null||(x||(x=!!T.gap||!!S&&f.len===0),S&&!x||x&&u.nextStart&&u.nextStartnew Ia(n))}onAudioTrackSwitching(e,r){const n=!!r.url;this.trackId=r.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),n?this.setInterval(Kv):this.resetTransmuxer(),n?(this.switchingTrack=r,this.state=Y.IDLE,this.flushAudioIfNeeded(r)):(this.switchingTrack=null,this.bufferedTrack=r,this.state=Y.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,r){this.mainDetails=r.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(w.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,r){var n;if(this.mainDetails==null){this.cachedTrackLoadedData=r;return}const{levels:i}=this,{details:s,id:a}=r;if(!i){this.warn(`Audio tracks were reset while loading level ${a}`);return}this.log(`Audio track ${a} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const o=i[a];let l=0;if(s.live||(n=o.details)!=null&&n.live){this.checkLiveUpdate(s);const c=this.mainDetails;if(s.deltaUpdateFailed||!c)return;if(!o.details&&s.hasProgramDateTime&&c.hasProgramDateTime)Gc(s,c),l=s.fragments[0].start;else{var u;l=this.alignPlaylists(s,o.details,(u=this.levelLastLoaded)==null?void 0:u.details)}}o.details=s,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!s.live)&&this.setStartPosition(this.mainDetails||s,l),this.state===Y.WAITING_TRACK&&!this.waitForCdnTuneIn(s)&&(this.state=Y.IDLE),this.tick()}_handleFragmentLoadProgress(e){var r;const{frag:n,part:i,payload:s}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const u=l[o];if(!u){this.warn("Audio track is undefined on fragment load progress");return}const c=u.details;if(!c){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}const d=a.defaultAudioCodec||u.audioCodec||"mp4a.40.2";let f=this.transmuxer;f||(f=this.transmuxer=new XT(this.hls,we.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const m=this.initPTS[n.cc],h=(r=n.initSegment)==null?void 0:r.data;if(m!==void 0){const v=i?i.index:-1,g=v!==-1,y=new km(n.level,n.sn,n.stats.chunkCount,s.byteLength,v,g);f.push(s,h,d,"",n,i,c.totalduration,!1,y,m)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${c.startSN} ,${c.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:n,part:i,cache:new OT,complete:!1};p.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=Y.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,r){const n=r.tracks.audio;n&&(this.mediaBuffer=n.buffer||null),r.tracks.video&&(this.videoBuffer=r.tracks.video.buffer||null)}onFragBuffered(e,r){const{frag:n,part:i}=r;if(n.type!==we.AUDIO){if(!this.loadedmetadata&&n.type===we.MAIN){const s=this.videoBuffer||this.media;s&&at.getBuffered(s).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${i?" p: "+i.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(n.sn!=="initSegment"){this.fragPrevious=n;const s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(w.AUDIO_TRACK_SWITCHED,jt({},s)))}this.fragBufferedComplete(n,i)}onError(e,r){var n;if(r.fatal){this.state=Y.ERROR;return}switch(r.details){case z.FRAG_GAP:case z.FRAG_PARSING_ERROR:case z.FRAG_DECRYPT_ERROR:case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(we.AUDIO,r);break;case z.AUDIO_TRACK_LOAD_ERROR:case z.AUDIO_TRACK_LOAD_TIMEOUT:case z.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===Y.WAITING_TRACK&&((n=r.context)==null?void 0:n.type)===He.AUDIO_TRACK&&(this.state=Y.IDLE);break;case z.BUFFER_APPEND_ERROR:case z.BUFFER_FULL_ERROR:if(!r.parent||r.parent!=="audio")return;if(r.details===z.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case z.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onBufferFlushing(e,{type:r}){r!==Je.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:r}){if(r!==Je.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Y.ENDED&&(this.state=Y.IDLE);const n=this.mediaBuffer||this.media;n&&(this.afterBufferFlushed(n,r,we.AUDIO),this.tick())}}_handleTransmuxComplete(e){var r;const n="audio",{hls:i}=this,{remuxResult:s,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:u,level:c}=o,{details:d}=c,{audio:f,text:m,id3:h,initSegment:p}=s;if(this.fragContextChanged(l)||!d){this.fragmentTracker.removeFragment(l);return}if(this.state=Y.PARSING,this.switchingTrack&&f&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const v=l.initSegment||l;this._bufferInitSegment(c,p.tracks,v,a),i.trigger(w.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:n,tracks:p.tracks})}if(f){const{startPTS:v,endPTS:g,startDTS:y,endDTS:x}=f;u&&(u.elementaryStreams[Je.AUDIO]={startPTS:v,endPTS:g,startDTS:y,endDTS:x}),l.setElementaryStreamInfo(Je.AUDIO,v,g,y,x),this.bufferFragmentData(f,l,u,a)}if(h!=null&&(r=h.samples)!=null&&r.length){const v=It({id:n,frag:l,details:d},h);i.trigger(w.FRAG_PARSING_METADATA,v)}if(m){const v=It({id:n,frag:l,details:d},m);i.trigger(w.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(e,r,n,i){if(this.state!==Y.PARSING)return;r.video&&delete r.video;const s=r.audio;if(!s)return;s.id="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(w.BUFFER_CODECS,r);const o=s.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:n,part:null,chunkMeta:i,parent:n.type,data:o};this.hls.trigger(w.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||i===Bt.NOT_LOADED||i===Bt.PARTIAL){var s;if(e.sn==="initSegment")this._loadInitSegment(e,r);else if((s=r.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=Y.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragments[0].start!==r.details.fragments[0].start&&Gc(r.details,a)}else this.startFragRequested=!0,super.loadFragment(e,r,n)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){const{media:r,bufferedTrack:n}=this,i=n==null?void 0:n.attrs,s=e.attrs;r&&i&&(i.CHANNELS!==s.CHANNELS||n.name!==e.name||n.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){const{hls:r}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,r.trigger(w.AUDIO_TRACK_SWITCHED,jt({},e))}}class yM extends Im{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(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.LEVEL_LOADING,this.onLevelLoading,this),e.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.LEVEL_LOADING,this.onLevelLoading,this),e.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(w.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,r){this.tracks=r.audioTracks||[]}onAudioTrackLoaded(e,r){const{id:n,groupId:i,details:s}=r,a=this.tracksInGroup[n];if(!a||a.groupId!==i){this.warn(`Audio track with id:${n} and group:${i} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=r.details,this.log(`Audio track ${n} "${a.name}" lang:${a.lang} group:${i} loaded [${s.startSN}-${s.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(e,r){this.switchLevel(r.level)}onLevelSwitching(e,r){this.switchLevel(r.level)}switchLevel(e){const r=this.hls.levels[e];if(!r)return;const n=r.audioGroups||null,i=this.groupIds;let s=this.currentTrack;if(!n||(i==null?void 0:i.length)!==(n==null?void 0:n.length)||n!=null&&n.some(o=>(i==null?void 0:i.indexOf(o))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(f=>!n||n.indexOf(f.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(f=>f.default)&&(this.selectDefaultTrack=!1),o.forEach((f,m)=>{f.id=m});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!s&&l){const f=Dn(l,o,Ms);if(f>-1)s=o[f];else{const m=Dn(l,this.tracks);s=this.tracks[m]}}let u=this.findTrackId(s);u===-1&&s&&(u=this.findTrackId(null));const c={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${n==null?void 0:n.join(",")}`),this.hls.trigger(w.AUDIO_TRACKS_UPDATED,c);const d=this.trackId;if(u!==-1&&d===-1)this.setAudioTrack(u);else if(o.length&&d===-1){var a;const f=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(f.message),this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}else this.shouldReloadPlaylist(s)&&this.setAudioTrack(this.trackId)}onError(e,r){r.fatal||!r.context||r.context.type===He.AUDIO_TRACK&&r.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(r.context.groupId)!==-1)&&(this.requestScheduled=-1,this.checkRetry(r))}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 r=this.hls;if(r.config.audioPreference=e,e){const n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){const i=this.currentTrack;if(i&&da(e,i,Ms))return i;const s=Dn(e,this.tracksInGroup,Ms);if(s>-1){const a=this.tracksInGroup[s];return this.setAudioTrack(s),a}else if(i){let a=r.loadLevel;a===-1&&(a=r.firstAutoLevel);const o=yO(e,r.levels,n,a,Ms);if(o===-1)return null;r.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Dn(e,n);if(a>-1)return n[a]}}}return null}setAudioTrack(e){const r=this.tracksInGroup;if(e<0||e>=r.length){this.warn(`Invalid audio track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const n=this.currentTrack,i=r[e],s=i.details&&!i.details.live;if(e===this.trackId&&i===n&&s||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(w.AUDIO_TRACK_SWITCHING,jt({},i)),s))return;const a=this.switchParams(i.url,n==null?void 0:n.details,i.details);this.loadPlaylist(a)}findTrackId(e){const r=this.tracksInGroup;for(let n=0;n=s[u].start&&o<=s[u].end){a=s[u];break}const l=n.start+n.duration;a?a.end=l:(a={start:o,end:l},s.push(a)),this.fragmentTracker.fragBuffered(n),this.fragBufferedComplete(n,null)}onBufferFlushing(e,r){const{startOffset:n,endOffset:i}=r;if(n===0&&i!==Number.POSITIVE_INFINITY){const s=i-1;if(s<=0)return;r.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach(a=>{for(let o=0;onew Ia(n));return}this.tracksBuffered=[],this.levels=r.map(n=>{const i=new Ia(n);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,we.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,r){var n;if(this.currentTrackId=r.id,!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval(Yv)}onSubtitleTrackLoaded(e,r){var n;const{currentTrackId:i,levels:s}=this,{details:a,id:o}=r;if(!s){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=s[o];if(o>=s.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let u=0;if(a.live||(n=l.details)!=null&&n.live){const d=this.mainDetails;if(a.deltaUpdateFailed||!d)return;const f=d.fragments[0];if(!l.details)a.hasProgramDateTime&&d.hasProgramDateTime?(Gc(a,d),u=a.fragments[0].start):f&&(u=f.start,Qh(a,u));else{var c;u=this.alignPlaylists(a,l.details,(c=this.levelLastLoaded)==null?void 0:c.details),u===0&&f&&(u=f.start,Qh(a,u))}}l.details=a,this.levelLastLoaded=l,o===i&&(!this.startFragRequested&&(this.mainDetails||!a.live)&&this.setStartPosition(this.mainDetails||a,u),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===Y.IDLE&&(Vc(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:r,payload:n}=e,i=r.decryptdata,s=this.hls;if(!this.fragContextChanged(r)&&n&&n.byteLength>0&&i!=null&&i.key&&i.iv&&i.method==="AES-128"){const a=performance.now();this.decrypter.decrypt(new Uint8Array(n),i.key.buffer,i.iv.buffer).catch(o=>{throw s.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:r}),o}).then(o=>{const l=performance.now();s.trigger(w.FRAG_DECRYPTED,{frag:r,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=Y.IDLE})}}doTick(){if(!this.media){this.state=Y.IDLE;return}if(this.state===Y.IDLE){const{currentTrackId:e,levels:r}=this,n=r==null?void 0:r[e];if(!n||!r.length||!n.details)return;const{config:i}=this,s=this.getLoadPosition(),a=at.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,i.maxBufferHole),{end:o,len:l}=a,u=this.getFwdBufferInfo(this.media,we.MAIN),c=n.details,d=this.getMaxBufferLength(u==null?void 0:u.len)+c.levelTargetDuration;if(l>d)return;const f=c.fragments,m=f.length,h=c.edge;let p=null;const v=this.fragPrevious;if(oh-g?0:g;p=Vc(v,f,Math.max(f[0].start,o),y),!p&&v&&v.start{if(i=i>>>0,i>s-1)throw new DOMException(`Failed to execute '${n}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return e[i][n]};this.buffered={get length(){return e.length},end(n){return r("end",n,e.length)},start(n){return r("start",n,e.length)}}}}class EM extends Im{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.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let r=null;const n=Pu(this.media.textTracks);for(let s=0;s-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.LEVEL_LOADING,this.onLevelLoading,this),e.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.LEVEL_LOADING,this.onLevelLoading,this),e.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(w.ERROR,this.onError,this)}onMediaAttached(e,r){this.media=r.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(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Pu(this.media.textTracks).forEach(r=>{ta(r)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,r){this.tracks=r.subtitleTracks}onSubtitleTrackLoaded(e,r){const{id:n,groupId:i,details:s}=r,a=this.tracksInGroup[n];if(!a||a.groupId!==i){this.warn(`Subtitle track with id:${n} and group:${i} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=r.details,this.log(`Subtitle track ${n} "${a.name}" lang:${a.lang} group:${i} loaded [${s.startSN}-${s.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(e,r){this.switchLevel(r.level)}onLevelSwitching(e,r){this.switchLevel(r.level)}switchLevel(e){const r=this.hls.levels[e];if(!r)return;const n=r.subtitleGroups||null,i=this.groupIds;let s=this.currentTrack;if(!n||(i==null?void 0:i.length)!==(n==null?void 0:n.length)||n!=null&&n.some(a=>(i==null?void 0:i.indexOf(a))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(c=>!n||n.indexOf(c.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(c=>c.default)&&(this.selectDefaultTrack=!1),a.forEach((c,d)=>{c.id=d});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!s&&o){this.selectDefaultTrack=!1;const c=Dn(o,a);if(c>-1)s=a[c];else{const d=Dn(o,this.tracks);s=this.tracks[d]}}let l=this.findTrackId(s);l===-1&&s&&(l=this.findTrackId(null));const u={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${n==null?void 0:n.join(",")}" group-id`),this.hls.trigger(w.SUBTITLE_TRACKS_UPDATED,u),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}else this.shouldReloadPlaylist(s)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const r=this.tracksInGroup,n=this.selectDefaultTrack;for(let i=0;i-1){const s=this.tracksInGroup[i];return this.setSubtitleTrack(i),s}else{if(n)return null;{const s=Dn(e,r);if(s>-1)return r[s]}}}}return null}loadPlaylist(e){super.loadPlaylist();const r=this.currentTrack;if(this.shouldLoadPlaylist(r)&&r){const n=r.id,i=r.groupId;let s=r.url;if(e)try{s=e.addDirectives(s)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`Loading subtitle playlist for id ${n}`),this.hls.trigger(w.SUBTITLE_TRACK_LOADING,{url:s,id:n,groupId:i,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const r=Pu(e.textTracks),n=this.currentTrack;let i;if(n&&(i=r.filter(s=>tp(n,s))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${n.name}" and language "${n.lang}"`)),[].slice.call(r).forEach(s=>{s.mode!=="disabled"&&s!==i&&(s.mode="disabled")}),i){const s=this.subtitleDisplay?"showing":"hidden";i.mode!==s&&(i.mode=s)}}setSubtitleTrack(e){const r=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=r.length||!pe(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const n=this.currentTrack,i=r[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(w.SUBTITLE_TRACK_SWITCH,{id:e});return}const s=!!i.details&&!i.details.live;if(e===this.trackId&&i===n&&s)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:a,groupId:o="",name:l,type:u,url:c}=i;this.hls.trigger(w.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:u,url:c});const d=this.switchParams(i.url,n==null?void 0:n.details,i.details);this.loadPlaylist(d)}}class TM{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,r,n){const i=this.queues[r];i.push(e),i.length===1&&!n&&this.executeNext(r)}insertAbort(e,r){this.queues[r].unshift(e),this.executeNext(r)}appendBlocker(e){let r;const n=new Promise(s=>{r=s}),i={execute:r,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(i,e),n}executeNext(e){const r=this.queues[e];if(r.length){const n=r[0];try{n.execute()}catch(i){U.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${i}`),n.onError(i);const s=this.buffers[e];s!=null&&s.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const qv=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class wM{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=n=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=n=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:n,mediaSource:i}=this;this.log("Media source opened"),n&&(n.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(w.MEDIA_ATTACHED,{media:n,mediaSource:i})),i&&i.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:n,_objectUrl:i}=this;n!==i&&U.error(`Media element src was set while attaching MediaSource (${i} > ${n})`)},this.hls=e;const r="[buffer-controller]";this.appendSource=DP(bs(e.config.preferManagedMediaSource)),this.log=U.log.bind(U,r),this.warn=U.warn.bind(U,r),this.error=U.error.bind(U,r),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:e}=this;e.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.BUFFER_RESET,this.onBufferReset,this),e.on(w.BUFFER_APPENDING,this.onBufferAppending,this),e.on(w.BUFFER_CODECS,this.onBufferCodecs,this),e.on(w.BUFFER_EOS,this.onBufferEos,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(w.FRAG_PARSED,this.onFragParsed,this),e.on(w.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.BUFFER_RESET,this.onBufferReset,this),e.off(w.BUFFER_APPENDING,this.onBufferAppending,this),e.off(w.BUFFER_CODECS,this.onBufferCodecs,this),e.off(w.BUFFER_EOS,this.onBufferEos,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(w.FRAG_PARSED,this.onFragParsed,this),e.off(w.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new TM(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,r){let n=2;(r.audio&&!r.video||!r.altAudio)&&(n=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=n,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,r){const n=this.media=r.media,i=bs(this.appendSource);if(n&&i){var s;const a=this.mediaSource=new i;this.log(`created media source: ${(s=a.constructor)==null?void 0:s.name}`),a.addEventListener("sourceopen",this._onMediaSourceOpen),a.addEventListener("sourceended",this._onMediaSourceEnded),a.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.addEventListener("startstreaming",this._onStartStreaming),a.addEventListener("endstreaming",this._onEndStreaming));const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{n.removeAttribute("src");const l=self.ManagedMediaSource;n.disableRemotePlayback=n.disableRemotePlayback||l&&a instanceof l,Xv(n),bM(n,o),n.load()}catch{n.src=o}else n.src=o;n.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source detaching"),r.readyState==="open")try{r.endOfStream()}catch(i){this.warn(`onMediaDetaching: ${i.message} while calling endOfStream`)}this.onBufferReset(),r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(e.removeAttribute("src"),this.appendSource&&Xv(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(w.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{this.resetBuffer(e)}),this._initSourceBuffer()}resetBuffer(e){const r=this.sourceBuffer[e];try{if(r){var n;this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}}catch(i){this.warn(`onBufferReset ${e}`,i)}}onBufferCodecs(e,r){const n=this.getSourceBufferTypes().length,i=Object.keys(r);if(i.forEach(a=>{if(n){const l=this.tracks[a];if(l&&typeof l.buffer.changeType=="function"){var o;const{id:u,codec:c,levelCodec:d,container:f,metadata:m}=r[a],h=vv(l.codec,l.levelCodec),p=h==null?void 0:h.replace(qv,"$1");let v=vv(c,d);const g=(o=v)==null?void 0:o.replace(qv,"$1");if(v&&p!==g){a.slice(0,5)==="audio"&&(v=Uc(v,this.appendSource));const y=`${f};codecs=${v}`;this.appendChangeType(a,y),this.log(`switching codec ${h} to ${v}`),this.tracks[a]={buffer:l.buffer,codec:c,container:f,levelCodec:d,metadata:m,id:u}}}}else this.pendingTracks[a]=r[a]}),n)return;const s=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==s&&(this.log(`${s} bufferCodec event(s) expected ${i.join(",")}`),this.bufferCodecEventsExpected=s),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks()}appendChangeType(e,r){const{operationQueue:n}=this,i={execute:()=>{const s=this.sourceBuffer[e];s&&(this.log(`changing ${e} sourceBuffer type to ${r}`),s.changeType(r)),n.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:s=>{this.warn(`Failed to change ${e} SourceBuffer type`,s)}};n.append(i,e,!!this.pendingTracks[e])}onBufferAppending(e,r){const{hls:n,operationQueue:i,tracks:s}=this,{data:a,type:o,frag:l,part:u,chunkMeta:c}=r,d=c.buffering[o],f=self.performance.now();d.start=f;const m=l.stats.buffering,h=u?u.stats.buffering:null;m.start===0&&(m.start=f),h&&h.start===0&&(h.start=f);const p=s.audio;let v=!1;o==="audio"&&(p==null?void 0:p.container)==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const g=l.start,y={execute:()=>{if(d.executeStart=self.performance.now(),v){const x=this.sourceBuffer[o];if(x){const S=g-x.timestampOffset;Math.abs(S)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${g} (delta: ${S}) sn: ${l.sn})`),x.timestampOffset=g)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();d.executeEnd=d.end=x,m.first===0&&(m.first=x),h&&h.first===0&&(h.first=x);const{sourceBuffer:S}=this,T={};for(const C in S)T[C]=at.getBuffered(S[C]);this.appendErrors[o]=0,o==="audio"||o==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(w.BUFFER_APPENDED,{type:o,frag:l,part:u,chunkMeta:c,parent:l.type,timeRanges:T})},onError:x=>{const S={type:_e.MEDIA_ERROR,parent:l.type,details:z.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:u,chunkMeta:c,error:x,err:x,fatal:!1};if(x.code===DOMException.QUOTA_EXCEEDED_ERR)S.details=z.BUFFER_FULL_ERROR;else{const T=++this.appendErrors[o];S.details=z.BUFFER_APPEND_ERROR,this.warn(`Failed ${T}/${n.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer`),T>=n.config.appendErrorMaxRetry&&(S.fatal=!0)}n.trigger(w.ERROR,S)}};i.append(y,o,!!this.pendingTracks[o])}onBufferFlushing(e,r){const{operationQueue:n}=this,i=s=>({execute:this.removeExecutor.bind(this,s,r.startOffset,r.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(w.BUFFER_FLUSHED,{type:s})},onError:a=>{this.warn(`Failed to remove from ${s} SourceBuffer`,a)}});r.type?n.append(i(r.type),r.type):this.getSourceBufferTypes().forEach(s=>{n.append(i(s),s)})}onFragParsed(e,r){const{frag:n,part:i}=r,s=[],a=i?i.elementaryStreams:n.elementaryStreams;a[Je.AUDIOVIDEO]?s.push("audiovideo"):(a[Je.AUDIO]&&s.push("audio"),a[Je.VIDEO]&&s.push("video"));const o=()=>{const l=self.performance.now();n.stats.buffering.end=l,i&&(i.stats.buffering.end=l);const u=i?i.stats:n.stats;this.hls.trigger(w.FRAG_BUFFERED,{frag:n,part:i,stats:u,id:n.type})};s.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(o,s)}onFragChanged(e,r){this.trimBuffers()}onBufferEos(e,r){this.getSourceBufferTypes().reduce((i,s)=>{const a=this.sourceBuffer[s];return a&&(!r.type||r.type===s)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${s} sourceBuffer now EOS`))),i&&!!(!a||a.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(s=>{const a=this.sourceBuffer[s];a&&(a.ending=!1)});const{mediaSource:i}=this;if(!i||i.readyState!=="open"){i&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${i.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),i.endOfStream()}))}onLevelUpdated(e,{details:r}){r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:r,media:n}=this;if(!n||r===null||!this.getSourceBufferTypes().length)return;const s=e.config,a=n.currentTime,o=r.levelTargetDuration,l=r.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:s.backBufferLength;if(pe(l)&&l>0){const u=Math.max(l,o),c=Math.floor(a/o)*o-u;this.flushBackBuffer(a,o,c)}if(pe(s.frontBufferFlushThreshold)&&s.frontBufferFlushThreshold>0){const u=Math.max(s.maxBufferLength,s.frontBufferFlushThreshold),c=Math.max(u,o),d=Math.floor(a/o)*o+c;this.flushFrontBuffer(a,o,d)}}flushBackBuffer(e,r,n){const{details:i,sourceBuffer:s}=this;this.getSourceBufferTypes().forEach(o=>{const l=s[o];if(l){const u=at.getBuffered(l);if(u.length>0&&n>u.start(0)){if(this.hls.trigger(w.BACK_BUFFER_REACHED,{bufferEnd:n}),i!=null&&i.live)this.hls.trigger(w.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(l.ended&&u.end(u.length-1)-e{const o=i[a];if(o){const l=at.getBuffered(o),u=l.length;if(u<2)return;const c=l.start(u-1),d=l.end(u-1);if(n>c||e>=c&&e<=d)return;if(o.ended&&e-d<2*r){this.log(`Cannot flush ${a} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(w.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:a})}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:r,media:n,mediaSource:i}=this,s=e.fragments[0].start+e.totalduration,a=n.duration,o=pe(i.duration)?i.duration:0;e.live&&r.config.liveDurationInfinity?(i.duration=1/0,this.updateSeekableRange(e)):(s>o&&s>a||!pe(a))&&(this.log(`Updating Media Source duration to ${s.toFixed(3)}`),i.duration=s)}updateSeekableRange(e){const r=this.mediaSource,n=e.fragments;if(n.length&&e.live&&r!=null&&r.setLiveSeekableRange){const s=Math.max(0,n[0].start),a=Math.max(s,s+e.totalduration);this.log(`Media Source duration is set to ${r.duration}. Setting seekable range to ${s}-${a}.`),r.setLiveSeekableRange(s,a)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:r,pendingTracks:n}=this,i=Object.keys(n).length;if(i&&(!e||i===2||"audiovideo"in n)){this.createSourceBuffers(n),this.pendingTracks={};const s=this.getSourceBufferTypes();if(s.length)this.hls.trigger(w.BUFFER_CREATED,{tracks:this.tracks}),s.forEach(a=>{r.executeNext(a)});else{const a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}}createSourceBuffers(e){const{sourceBuffer:r,mediaSource:n}=this;if(!n)throw Error("createSourceBuffers called when mediaSource was null");for(const s in e)if(!r[s]){var i;const a=e[s];if(!a)throw Error(`source buffer exists for track ${s}, however track does not`);let o=((i=a.levelCodec)==null?void 0:i.indexOf(","))===-1?a.levelCodec:a.codec;o&&s.slice(0,5)==="audio"&&(o=Uc(o,this.appendSource));const l=`${a.container};codecs=${o}`;this.log(`creating sourceBuffer(${l})`);try{const u=r[s]=n.addSourceBuffer(l),c=s;this.addBufferListener(c,"updatestart",this._onSBUpdateStart),this.addBufferListener(c,"updateend",this._onSBUpdateEnd),this.addBufferListener(c,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(c,"bufferedchange",(d,f)=>{const m=f.removedRanges;m!=null&&m.length&&this.hls.trigger(w.BUFFER_FLUSHED,{type:s})}),this.tracks[s]={buffer:u,codec:o,container:a.container,levelCodec:a.levelCodec,metadata:a.metadata,id:a.id}}catch(u){this.error(`error while trying to add sourceBuffer: ${u.message}`),this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:s,mimeType:l})}}}get mediaSrc(){var e,r;const n=((e=this.media)==null||(r=e.querySelector)==null?void 0:r.call(e,"source"))||this.media;return n==null?void 0:n.src}_onSBUpdateStart(e){const{operationQueue:r}=this;r.current(e).onStart()}_onSBUpdateEnd(e){var r;if(((r=this.mediaSource)==null?void 0:r.readyState)==="closed"){this.resetBuffer(e);return}const{operationQueue:n}=this;n.current(e).onComplete(),n.shiftAndExecuteNext(e)}_onSBUpdateError(e,r){var n;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(n=this.mediaSource)==null?void 0:n.readyState}`);this.error(`${i}`,r),this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const s=this.operationQueue.current(e);s&&s.onError(i)}removeExecutor(e,r,n){const{media:i,mediaSource:s,operationQueue:a,sourceBuffer:o}=this,l=o[e];if(!i||!s||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(e);return}const u=pe(i.duration)?i.duration:1/0,c=pe(s.duration)?s.duration:1/0,d=Math.max(0,r),f=Math.min(n,u,c);f>d&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${d},${f}] from the ${e} SourceBuffer`),l.remove(d,f)):a.shiftAndExecuteNext(e)}appendExecutor(e,r){const n=this.sourceBuffer[r];if(!n){if(!this.pendingTracks[r])throw new Error(`Attempting to append to the ${r} SourceBuffer, but it does not exist`);return}n.ended=!1,n.appendBuffer(e)}blockBuffers(e,r=this.getSourceBufferTypes()){if(!r.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:n}=this,i=r.map(s=>n.appendBlocker(s));Promise.all(i).then(()=>{e(),r.forEach(s=>{const a=this.sourceBuffer[s];a!=null&&a.updating||n.shiftAndExecuteNext(s)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,r,n){const i=this.sourceBuffer[e];if(!i)return;const s=n.bind(this,e);this.listeners[e].push({event:r,listener:s}),i.addEventListener(r,s)}removeBufferListeners(e){const r=this.sourceBuffer[e];r&&this.listeners[e].forEach(n=>{r.removeEventListener(n.event,n.listener)})}}function Xv(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(r=>{t.removeChild(r)})}function bM(t,e){const r=self.document.createElement("source");r.type="video/mp4",r.src=e,t.appendChild(r)}const LM={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},QT=t=>String.fromCharCode(LM[t]||t),an=15,Kn=100,AM={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},_M={17:2,18:4,21:6,22:8,23:10,19:13,20:15},CM={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},RM={25:2,26:4,29:6,30:8,31:10,27:13,28:15},IM=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class kM{constructor(){this.time=null,this.verboseLevel=0}log(e,r){if(this.verboseLevel>=e){const n=typeof r=="function"?r():r;U.log(`${this.time} [${e}] ${n}`)}}}const Zi=function(e){const r=[];for(let n=0;nKn&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Kn)}moveCursor(e){const r=this.pos+e;if(e>1)for(let n=this.pos+1;n=144&&this.backSpace();const r=QT(e);if(this.pos>=Kn){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+r+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1)}clearFromPos(e){let r;for(r=e;r"pacData = "+JSON.stringify(e));let r=e.row-1;if(this.nrRollUpRows&&r"bkgData = "+JSON.stringify(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,r=this.rows.splice(e,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const r=[];let n="",i=-1;for(let s=0;s0&&(e?n="["+r.join(" | ")+"]":n=r.join(` -`)),n}getTextAndFormat(){return this.rows}}class Zv{constructor(e,r,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new kf(n),this.nonDisplayedMemory=new kf(n),this.lastOutputScreen=new kf(n),this.currRollUpRow=this.displayedMemory.rows[an-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[an-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 n=0;nr+": "+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 r={flash:!1};if(r.underline=e%2===1,r.italics=e>=46,r.italics)r.foreground="white";else{const n=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];r.foreground=i[n]}this.logger.log(2,"MIDROW: "+JSON.stringify(r)),this.writeScreen.setPen(r)}outputDataUpdate(e=!1){const r=this.logger.time;r!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=r:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,r,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:r),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))}}class Qv{constructor(e,r,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=MM(),this.logger=void 0;const i=this.logger=new kM;this.channels=[null,new Zv(e,r,i),new Zv(e+1,n,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,r){this.channels[e].setHandler(r)}addData(e,r){this.logger.time=e;for(let n=0;n"["+Zi([r[n],r[n+1]])+"] -> ("+Zi([i,s])+")");const l=this.cmdHistory;if(i>=16&&i<=31){if(OM(i,s,l)){ou(null,null,l),this.logger.log(3,()=>"Repeated command ("+Zi([i,s])+") is dropped");continue}ou(i,s,this.cmdHistory),a=this.parseCmd(i,s),a||(a=this.parseMidrow(i,s)),a||(a=this.parsePAC(i,s)),a||(a=this.parseBackgroundAttributes(i,s))}else ou(null,null,l);if(!a&&(o=this.parseChars(i,s),o)){const c=this.currentChannel;c&&c>0?this.channels[c].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Zi([i,s])+" orig: "+Zi([r[n],r[n+1]]))}}parseCmd(e,r){const n=(e===20||e===28||e===21||e===29)&&r>=32&&r<=47,i=(e===23||e===31)&&r>=33&&r<=35;if(!(n||i))return!1;const s=e===20||e===21||e===23?1:2,a=this.channels[s];return e===20||e===21||e===28||e===29?r===32?a.ccRCL():r===33?a.ccBS():r===34?a.ccAOF():r===35?a.ccAON():r===36?a.ccDER():r===37?a.ccRU(2):r===38?a.ccRU(3):r===39?a.ccRU(4):r===40?a.ccFON():r===41?a.ccRDC():r===42?a.ccTR():r===43?a.ccRTD():r===44?a.ccEDM():r===45?a.ccCR():r===46?a.ccENM():r===47&&a.ccEOC():a.ccTO(r-32),this.currentChannel=s,!0}parseMidrow(e,r){let n=0;if((e===17||e===25)&&r>=32&&r<=47){if(e===17?n=1:n=2,n!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[n];return i?(i.ccMIDROW(r),this.logger.log(3,()=>"MIDROW ("+Zi([e,r])+")"),!0):!1}return!1}parsePAC(e,r){let n;const i=(e>=17&&e<=23||e>=25&&e<=31)&&r>=64&&r<=127,s=(e===16||e===24)&&r>=64&&r<=95;if(!(i||s))return!1;const a=e<=23?1:2;r>=64&&r<=95?n=a===1?AM[e]:CM[e]:n=a===1?_M[e]:RM[e];const o=this.channels[a];return o?(o.setPAC(this.interpretPAC(n,r)),this.currentChannel=a,!0):!1}interpretPAC(e,r){let n;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return r>95?n=r-96:n=r-64,i.underline=(n&1)===1,n<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)]:n<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((n-16)/2)*4,i}parseChars(e,r){let n,i=null,s=null;if(e>=25?(n=2,s=e-8):(n=1,s=e),s>=17&&s<=19){let a;s===17?a=r+80:s===18?a=r+112:a=r+144,this.logger.log(2,()=>"Special char '"+QT(a)+"' in channel "+n),i=[a]}else e>=32&&e<=127&&(i=r===0?[e]:[e,r]);return i&&this.logger.log(3,()=>"Char codes = "+Zi(i).join(",")),i}parseBackgroundAttributes(e,r){const n=(e===16||e===24)&&r>=32&&r<=47,i=(e===23||e===31)&&r>=45&&r<=47;if(!(n||i))return!1;let s;const a={};e===16||e===24?(s=Math.floor((r-32)/2),a.background=IM[s],r%2===1&&(a.background=a.background+"_semi")):r===45?a.background="transparent":(a.foreground="black",r===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;ee)&&(this.startTime=e),this.endTime=r,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Bm=function(){if(Ra!=null&&Ra.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function r(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const u=l.toLowerCase();return~o.indexOf(u)?u:!1}function n(o){return r(t,o)}function i(o){return r(e,o)}function s(o,...l){let u=1;for(;u100)throw new Error("Position must be between 0 and 100.");C=A,this.hasBeenReset=!0}})),Object.defineProperty(c,"positionAlign",s({},d,{get:function(){return _},set:function(A){const k=i(A);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");_=k,this.hasBeenReset=!0}})),Object.defineProperty(c,"size",s({},d,{get:function(){return b},set:function(A){if(A<0||A>100)throw new Error("Size must be between 0 and 100.");b=A,this.hasBeenReset=!0}})),Object.defineProperty(c,"align",s({},d,{get:function(){return I},set:function(A){const k=i(A);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");I=k,this.hasBeenReset=!0}})),c.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class NM{decode(e,r){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function ew(t){function e(n,i,s,a){return(n|0)*3600+(i|0)*60+(s|0)+parseFloat(a||0)}const r=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?e(r[2],r[3],0,r[4]):e(r[1],r[2],r[3],r[4]):null}let FM=class{constructor(){this.values=Object.create(null)}set(e,r){!this.get(e)&&r!==""&&(this.values[e]=r)}get(e,r,n){return n?this.has(e)?this.values[e]:r[n]:this.has(e)?this.values[e]:r}has(e){return e in this.values}alt(e,r,n){for(let i=0;i=0&&n<=100)return this.set(e,n),!0}return!1}};function tw(t,e,r,n){const i=n?t.split(n):[t];for(const s in i){if(typeof i[s]!="string")continue;const a=i[s].split(r);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const rp=new Bm(0,0,""),uu=rp.align==="middle"?"middle":"center";function UM(t,e,r){const n=t;function i(){const o=ew(t);if(o===null)throw new Error("Malformed timestamp: "+n);return t=t.replace(/^[^\sa-zA-Z-]+/,""),o}function s(o,l){const u=new FM;tw(o,function(f,m){let h;switch(f){case"region":for(let p=r.length-1;p>=0;p--)if(r[p].id===m){u.set(f,r[p].region);break}break;case"vertical":u.alt(f,m,["rl","lr"]);break;case"line":h=m.split(","),u.integer(f,h[0]),u.percent(f,h[0])&&u.set("snapToLines",!1),u.alt(f,h[0],["auto"]),h.length===2&&u.alt("lineAlign",h[1],["start",uu,"end"]);break;case"position":h=m.split(","),u.percent(f,h[0]),h.length===2&&u.alt("positionAlign",h[1],["start",uu,"end","line-left","line-right","auto"]);break;case"size":u.percent(f,m);break;case"align":u.alt(f,m,["start",uu,"end","left","right"]);break}},/:/,/\s/),l.region=u.get("region",null),l.vertical=u.get("vertical","");let c=u.get("line","auto");c==="auto"&&rp.line===-1&&(c=-1),l.line=c,l.lineAlign=u.get("lineAlign","start"),l.snapToLines=u.get("snapToLines",!0),l.size=u.get("size",100),l.align=u.get("align",uu);let d=u.get("position","auto");d==="auto"&&rp.position===50&&(d=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=d}function a(){t=t.replace(/^\s+/,"")}if(a(),e.startTime=i(),a(),t.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+n);t=t.slice(3),a(),e.endTime=i(),a(),s(t,e)}function rw(t){return t.replace(//gi,` -`)}class BM{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new NM,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const r=this;e&&(r.buffer+=r.decoder.decode(e,{stream:!0}));function n(){let s=r.buffer,a=0;for(s=rw(s);a{this.handleTransmuxComplete(k)}).catch(k=>{this.transmuxerError(k,u,"transmuxer-interface push error")})):(m.async=!1,this.handleTransmuxComplete(A))}}flush(e){e.transmuxing.start=self.performance.now();const{transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({cmd:"flush",chunkMeta:e});else if(r){let n=r.flush(e);Uu(n)||r.async?(Uu(n)||(n=Promise.resolve(n)),n.then(s=>{this.handleFlushResult(s,e)}).catch(s=>{this.transmuxerError(s,e,"transmuxer-interface flush error")})):this.handleFlushResult(n,e)}}transmuxerError(e,r,n){this.hls&&(this.error=e,this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_PARSING_ERROR,chunkMeta:r,frag:this.frag||void 0,fatal:!1,error:e,err:e,reason:n}))}handleFlushResult(e,r){e.forEach(n=>{this.handleTransmuxComplete(n)}),this.onFlush(r)}onWorkerMessage(e){const r=e.data;if(!(r!=null&&r.event)){U.warn(`worker message received with no ${r?"event name":"data"}`);return}const n=this.hls;if(this.hls)switch(r.event){case"init":{var i;const s=(i=this.workerContext)==null?void 0:i.objectURL;s&&self.URL.revokeObjectURL(s);break}case"transmuxComplete":{this.handleTransmuxComplete(r.data);break}case"flush":{this.onFlush(r.data);break}case"workerLog":U[r.data.logType]&&U[r.data.logType](r.data.message);break;default:{r.data=r.data||{},r.data.frag=this.frag,r.data.id=this.id,n.trigger(r.event,r.data);break}}}configureTransmuxer(e){const{transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({cmd:"configure",config:e}):r&&r.configure(e)}handleTransmuxComplete(e){e.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(e)}}function ZT(t,e){if(t.length!==e.length)return!1;for(let r=0;rt[i]!==e[i])}function tp(t,e){return e.label.toLowerCase()===t.name.toLowerCase()&&(!e.language||e.language.toLowerCase()===(t.lang||"").toLowerCase())}const Kv=100;class gM extends Pm{constructor(e,r,n){super(e,r,n,"[audio-stream-controller]",we.AUDIO),this.videoBuffer=null,this.videoTrackCC=-1,this.waitingVideoCC=-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.mainDetails=null,this.bufferedTrack=null,this.switchingTrack=null}_registerListeners(){const{hls:e}=this;e.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.on(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.on(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(w.ERROR,this.onError,this),e.on(w.BUFFER_RESET,this.onBufferReset,this),e.on(w.BUFFER_CREATED,this.onBufferCreated,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.on(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this)}_unregisterListeners(){const{hls:e}=this;e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),e.off(w.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),e.off(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(w.ERROR,this.onError,this),e.off(w.BUFFER_RESET,this.onBufferReset,this),e.off(w.BUFFER_CREATED,this.onBufferCreated,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(w.BUFFER_FLUSHED,this.onBufferFlushed,this),e.off(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this)}onInitPtsFound(e,{frag:r,id:n,initPTS:i,timescale:s}){if(n==="main"){const a=r.cc;this.initPTS[r.cc]={baseTime:i,timescale:s},this.log(`InitPTS for cc: ${a} found from main: ${i}`),this.videoTrackCC=a,this.state===Y.WAITING_INIT_PTS&&this.tick()}}startLoad(e){if(!this.levels){this.startPosition=e,this.state=Y.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(Kv),r>0&&e===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r,this.state=Y.IDLE):(this.loadedmetadata=!1,this.state=Y.WAITING_TRACK),this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}doTick(){switch(this.state){case Y.IDLE:this.doTickIdle();break;case Y.WAITING_TRACK:{var e;const{levels:n,trackId:i}=this,s=n==null||(e=n[i])==null?void 0:e.details;if(s){if(this.waitForCdnTuneIn(s))break;this.state=Y.WAITING_INIT_PTS}break}case Y.FRAG_LOADING_WAITING_RETRY:{var r;const n=performance.now(),i=this.retryDate;if(!i||n>=i||(r=this.media)!=null&&r.seeking){const{levels:s,trackId:a}=this;this.log("RetryDate reached, switch back to IDLE state"),this.resetStartWhenNotLoaded((s==null?void 0:s[a])||null),this.state=Y.IDLE}break}case Y.WAITING_INIT_PTS:{const n=this.waitingData;if(n){const{frag:i,part:s,cache:a,complete:o}=n;if(this.initPTS[i.cc]!==void 0){this.waitingData=null,this.waitingVideoCC=-1,this.state=Y.FRAG_LOADING;const l=a.flush(),u={frag:i,part:s,payload:l,networkDetails:null};this._handleFragmentLoadProgress(u),o&&super._handleFragmentLoadComplete(u)}else if(this.videoTrackCC!==this.waitingVideoCC)this.log(`Waiting fragment cc (${i.cc}) cancelled because video is at cc ${this.videoTrackCC}`),this.clearWaitingFragment();else{const l=this.getLoadPosition(),u=at.bufferInfo(this.mediaBuffer,l,this.config.maxBufferHole);Jh(u.end,this.config.maxFragLookUpTolerance,i)<0&&(this.log(`Waiting fragment cc (${i.cc}) @ ${i.start} cancelled because another fragment at ${u.end} is needed`),this.clearWaitingFragment())}}else this.state=Y.IDLE}}this.onTickEnd()}clearWaitingFragment(){const e=this.waitingData;e&&(this.fragmentTracker.removeFragment(e.frag),this.waitingData=null,this.waitingVideoCC=-1,this.state=Y.IDLE)}resetLoadingState(){this.clearWaitingFragment(),super.resetLoadingState()}onTickEnd(){const{media:e}=this;e!=null&&e.readyState&&(this.lastCurrentTime=e.currentTime)}doTickIdle(){const{hls:e,levels:r,media:n,trackId:i}=this,s=e.config;if(!n&&(this.startFragRequested||!s.startFragPrefetch)||!(r!=null&&r[i]))return;const a=r[i],o=a.details;if(!o||o.live&&this.levelLastLoaded!==a||this.waitForCdnTuneIn(o)){this.state=Y.WAITING_TRACK;return}const l=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&l&&(this.bufferFlushed=!1,this.afterBufferFlushed(l,Je.AUDIO,we.AUDIO));const u=this.getFwdBufferInfo(l,we.AUDIO);if(u===null)return;const{bufferedTrack:c,switchingTrack:d}=this;if(!d&&this._streamEnded(u,o)){e.trigger(w.BUFFER_EOS,{type:"audio"}),this.state=Y.ENDED;return}const f=this.getFwdBufferInfo(this.videoBuffer?this.videoBuffer:this.media,we.MAIN),m=u.len,h=this.getMaxBufferLength(f==null?void 0:f.len),p=o.fragments,v=p[0].start;let g=this.flushing?this.getLoadPosition():u.end;if(d&&n){const T=this.getLoadPosition();c&&!ka(d.attrs,c.attrs)&&(g=T),o.PTSKnown&&Tv||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),n.currentTime=v+.05)}if(m>=h&&!d&&gf.end+o.targetduration;if(S||!(f!=null&&f.len)&&u.len){const T=this.getAppendedFrag(y.start,we.MAIN);if(T===null||(x||(x=!!T.gap||!!S&&f.len===0),S&&!x||x&&u.nextStart&&u.nextStartnew Ia(n))}onAudioTrackSwitching(e,r){const n=!!r.url;this.trackId=r.id;const{fragCurrent:i}=this;i&&(i.abortRequests(),this.removeUnbufferedFrags(i.start)),this.resetLoadingState(),n?this.setInterval(Kv):this.resetTransmuxer(),n?(this.switchingTrack=r,this.state=Y.IDLE,this.flushAudioIfNeeded(r)):(this.switchingTrack=null,this.bufferedTrack=r,this.state=Y.STOPPED),this.tick()}onManifestLoading(){this.fragmentTracker.removeAllFragments(),this.startPosition=this.lastCurrentTime=0,this.bufferFlushed=this.flushing=!1,this.levels=this.mainDetails=this.waitingData=this.bufferedTrack=this.cachedTrackLoadedData=this.switchingTrack=null,this.startFragRequested=!1,this.trackId=this.videoTrackCC=this.waitingVideoCC=-1}onLevelLoaded(e,r){this.mainDetails=r.details,this.cachedTrackLoadedData!==null&&(this.hls.trigger(w.AUDIO_TRACK_LOADED,this.cachedTrackLoadedData),this.cachedTrackLoadedData=null)}onAudioTrackLoaded(e,r){var n;if(this.mainDetails==null){this.cachedTrackLoadedData=r;return}const{levels:i}=this,{details:s,id:a}=r;if(!i){this.warn(`Audio tracks were reset while loading level ${a}`);return}this.log(`Audio track ${a} loaded [${s.startSN},${s.endSN}]${s.lastPartSn?`[part-${s.lastPartSn}-${s.lastPartIndex}]`:""},duration:${s.totalduration}`);const o=i[a];let l=0;if(s.live||(n=o.details)!=null&&n.live){this.checkLiveUpdate(s);const c=this.mainDetails;if(s.deltaUpdateFailed||!c)return;if(!o.details&&s.hasProgramDateTime&&c.hasProgramDateTime)Gc(s,c),l=s.fragments[0].start;else{var u;l=this.alignPlaylists(s,o.details,(u=this.levelLastLoaded)==null?void 0:u.details)}}o.details=s,this.levelLastLoaded=o,!this.startFragRequested&&(this.mainDetails||!s.live)&&this.setStartPosition(this.mainDetails||s,l),this.state===Y.WAITING_TRACK&&!this.waitForCdnTuneIn(s)&&(this.state=Y.IDLE),this.tick()}_handleFragmentLoadProgress(e){var r;const{frag:n,part:i,payload:s}=e,{config:a,trackId:o,levels:l}=this;if(!l){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const u=l[o];if(!u){this.warn("Audio track is undefined on fragment load progress");return}const c=u.details;if(!c){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(n.start);return}const d=a.defaultAudioCodec||u.audioCodec||"mp4a.40.2";let f=this.transmuxer;f||(f=this.transmuxer=new XT(this.hls,we.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const m=this.initPTS[n.cc],h=(r=n.initSegment)==null?void 0:r.data;if(m!==void 0){const v=i?i.index:-1,g=v!==-1,y=new km(n.level,n.sn,n.stats.chunkCount,s.byteLength,v,g);f.push(s,h,d,"",n,i,c.totalduration,!1,y,m)}else{this.log(`Unknown video PTS for cc ${n.cc}, waiting for video PTS before demuxing audio frag ${n.sn} of [${c.startSN} ,${c.endSN}],track ${o}`);const{cache:p}=this.waitingData=this.waitingData||{frag:n,part:i,cache:new OT,complete:!1};p.push(new Uint8Array(s)),this.waitingVideoCC=this.videoTrackCC,this.state=Y.WAITING_INIT_PTS}}_handleFragmentLoadComplete(e){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(e)}onBufferReset(){this.mediaBuffer=this.videoBuffer=null,this.loadedmetadata=!1}onBufferCreated(e,r){const n=r.tracks.audio;n&&(this.mediaBuffer=n.buffer||null),r.tracks.video&&(this.videoBuffer=r.tracks.video.buffer||null)}onFragBuffered(e,r){const{frag:n,part:i}=r;if(n.type!==we.AUDIO){if(!this.loadedmetadata&&n.type===we.MAIN){const s=this.videoBuffer||this.media;s&&at.getBuffered(s).length&&(this.loadedmetadata=!0)}return}if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${i?" p: "+i.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(n.sn!=="initSegment"){this.fragPrevious=n;const s=this.switchingTrack;s&&(this.bufferedTrack=s,this.switchingTrack=null,this.hls.trigger(w.AUDIO_TRACK_SWITCHED,jt({},s)))}this.fragBufferedComplete(n,i)}onError(e,r){var n;if(r.fatal){this.state=Y.ERROR;return}switch(r.details){case z.FRAG_GAP:case z.FRAG_PARSING_ERROR:case z.FRAG_DECRYPT_ERROR:case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(we.AUDIO,r);break;case z.AUDIO_TRACK_LOAD_ERROR:case z.AUDIO_TRACK_LOAD_TIMEOUT:case z.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===Y.WAITING_TRACK&&((n=r.context)==null?void 0:n.type)===He.AUDIO_TRACK&&(this.state=Y.IDLE);break;case z.BUFFER_APPEND_ERROR:case z.BUFFER_FULL_ERROR:if(!r.parent||r.parent!=="audio")return;if(r.details===z.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(r)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case z.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}onBufferFlushing(e,{type:r}){r!==Je.VIDEO&&(this.flushing=!0)}onBufferFlushed(e,{type:r}){if(r!==Je.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Y.ENDED&&(this.state=Y.IDLE);const n=this.mediaBuffer||this.media;n&&(this.afterBufferFlushed(n,r,we.AUDIO),this.tick())}}_handleTransmuxComplete(e){var r;const n="audio",{hls:i}=this,{remuxResult:s,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:u,level:c}=o,{details:d}=c,{audio:f,text:m,id3:h,initSegment:p}=s;if(this.fragContextChanged(l)||!d){this.fragmentTracker.removeFragment(l);return}if(this.state=Y.PARSING,this.switchingTrack&&f&&this.completeAudioSwitch(this.switchingTrack),p!=null&&p.tracks){const v=l.initSegment||l;this._bufferInitSegment(c,p.tracks,v,a),i.trigger(w.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:n,tracks:p.tracks})}if(f){const{startPTS:v,endPTS:g,startDTS:y,endDTS:x}=f;u&&(u.elementaryStreams[Je.AUDIO]={startPTS:v,endPTS:g,startDTS:y,endDTS:x}),l.setElementaryStreamInfo(Je.AUDIO,v,g,y,x),this.bufferFragmentData(f,l,u,a)}if(h!=null&&(r=h.samples)!=null&&r.length){const v=It({id:n,frag:l,details:d},h);i.trigger(w.FRAG_PARSING_METADATA,v)}if(m){const v=It({id:n,frag:l,details:d},m);i.trigger(w.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(e,r,n,i){if(this.state!==Y.PARSING)return;r.video&&delete r.video;const s=r.audio;if(!s)return;s.id="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(w.BUFFER_CODECS,r);const o=s.initSegment;if(o!=null&&o.byteLength){const l={type:"audio",frag:n,part:null,chunkMeta:i,parent:n.type,data:o};this.hls.trigger(w.BUFFER_APPENDING,l)}this.tickImmediate()}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);if(this.fragCurrent=e,this.switchingTrack||i===Bt.NOT_LOADED||i===Bt.PARTIAL){var s;if(e.sn==="initSegment")this._loadInitSegment(e,r);else if((s=r.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=Y.WAITING_INIT_PTS;const a=this.mainDetails;a&&a.fragments[0].start!==r.details.fragments[0].start&&Gc(r.details,a)}else this.startFragRequested=!0,super.loadFragment(e,r,n)}else this.clearTrackerIfNeeded(e)}flushAudioIfNeeded(e){const{media:r,bufferedTrack:n}=this,i=n==null?void 0:n.attrs,s=e.attrs;r&&i&&(i.CHANNELS!==s.CHANNELS||n.name!==e.name||n.lang!==e.lang)&&(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null)}completeAudioSwitch(e){const{hls:r}=this;this.flushAudioIfNeeded(e),this.bufferedTrack=e,this.switchingTrack=null,r.trigger(w.AUDIO_TRACK_SWITCHED,jt({},e))}}class vM extends Im{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(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.LEVEL_LOADING,this.onLevelLoading,this),e.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.LEVEL_LOADING,this.onLevelLoading,this),e.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(w.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),e.off(w.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,r){this.tracks=r.audioTracks||[]}onAudioTrackLoaded(e,r){const{id:n,groupId:i,details:s}=r,a=this.tracksInGroup[n];if(!a||a.groupId!==i){this.warn(`Audio track with id:${n} and group:${i} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=r.details,this.log(`Audio track ${n} "${a.name}" lang:${a.lang} group:${i} loaded [${s.startSN}-${s.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(e,r){this.switchLevel(r.level)}onLevelSwitching(e,r){this.switchLevel(r.level)}switchLevel(e){const r=this.hls.levels[e];if(!r)return;const n=r.audioGroups||null,i=this.groupIds;let s=this.currentTrack;if(!n||(i==null?void 0:i.length)!==(n==null?void 0:n.length)||n!=null&&n.some(o=>(i==null?void 0:i.indexOf(o))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(f=>!n||n.indexOf(f.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(f=>f.default)&&(this.selectDefaultTrack=!1),o.forEach((f,m)=>{f.id=m});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const l=this.hls.config.audioPreference;if(!s&&l){const f=Dn(l,o,Ms);if(f>-1)s=o[f];else{const m=Dn(l,this.tracks);s=this.tracks[m]}}let u=this.findTrackId(s);u===-1&&s&&(u=this.findTrackId(null));const c={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${n==null?void 0:n.join(",")}`),this.hls.trigger(w.AUDIO_TRACKS_UPDATED,c);const d=this.trackId;if(u!==-1&&d===-1)this.setAudioTrack(u);else if(o.length&&d===-1){var a;const f=new Error(`No audio track selected for current audio group-ID(s): ${(a=this.groupIds)==null?void 0:a.join(",")} track count: ${o.length}`);this.warn(f.message),this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:f})}}else this.shouldReloadPlaylist(s)&&this.setAudioTrack(this.trackId)}onError(e,r){r.fatal||!r.context||r.context.type===He.AUDIO_TRACK&&r.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(r.context.groupId)!==-1)&&(this.requestScheduled=-1,this.checkRetry(r))}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 r=this.hls;if(r.config.audioPreference=e,e){const n=this.allAudioTracks;if(this.selectDefaultTrack=!1,n.length){const i=this.currentTrack;if(i&&da(e,i,Ms))return i;const s=Dn(e,this.tracksInGroup,Ms);if(s>-1){const a=this.tracksInGroup[s];return this.setAudioTrack(s),a}else if(i){let a=r.loadLevel;a===-1&&(a=r.firstAutoLevel);const o=vO(e,r.levels,n,a,Ms);if(o===-1)return null;r.nextLoadLevel=o}if(e.channels||e.audioCodec){const a=Dn(e,n);if(a>-1)return n[a]}}}return null}setAudioTrack(e){const r=this.tracksInGroup;if(e<0||e>=r.length){this.warn(`Invalid audio track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const n=this.currentTrack,i=r[e],s=i.details&&!i.details.live;if(e===this.trackId&&i===n&&s||(this.log(`Switching to audio-track ${e} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=e,this.currentTrack=i,this.hls.trigger(w.AUDIO_TRACK_SWITCHING,jt({},i)),s))return;const a=this.switchParams(i.url,n==null?void 0:n.details,i.details);this.loadPlaylist(a)}findTrackId(e){const r=this.tracksInGroup;for(let n=0;n=s[u].start&&o<=s[u].end){a=s[u];break}const l=n.start+n.duration;a?a.end=l:(a={start:o,end:l},s.push(a)),this.fragmentTracker.fragBuffered(n),this.fragBufferedComplete(n,null)}onBufferFlushing(e,r){const{startOffset:n,endOffset:i}=r;if(n===0&&i!==Number.POSITIVE_INFINITY){const s=i-1;if(s<=0)return;r.endOffsetSubtitles=Math.max(0,s),this.tracksBuffered.forEach(a=>{for(let o=0;onew Ia(n));return}this.tracksBuffered=[],this.levels=r.map(n=>{const i=new Ia(n);return this.tracksBuffered[i.id]=[],i}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,we.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(e,r){var n;if(this.currentTrackId=r.id,!((n=this.levels)!=null&&n.length)||this.currentTrackId===-1){this.clearInterval();return}const i=this.levels[this.currentTrackId];i!=null&&i.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,i&&this.setInterval(Yv)}onSubtitleTrackLoaded(e,r){var n;const{currentTrackId:i,levels:s}=this,{details:a,id:o}=r;if(!s){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const l=s[o];if(o>=s.length||!l)return;this.log(`Subtitle track ${o} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""},duration:${a.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let u=0;if(a.live||(n=l.details)!=null&&n.live){const d=this.mainDetails;if(a.deltaUpdateFailed||!d)return;const f=d.fragments[0];if(!l.details)a.hasProgramDateTime&&d.hasProgramDateTime?(Gc(a,d),u=a.fragments[0].start):f&&(u=f.start,Qh(a,u));else{var c;u=this.alignPlaylists(a,l.details,(c=this.levelLastLoaded)==null?void 0:c.details),u===0&&f&&(u=f.start,Qh(a,u))}}l.details=a,this.levelLastLoaded=l,o===i&&(!this.startFragRequested&&(this.mainDetails||!a.live)&&this.setStartPosition(this.mainDetails||a,u),this.tick(),a.live&&!this.fragCurrent&&this.media&&this.state===Y.IDLE&&(Vc(null,a.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),l.details=void 0)))}_handleFragmentLoadComplete(e){const{frag:r,payload:n}=e,i=r.decryptdata,s=this.hls;if(!this.fragContextChanged(r)&&n&&n.byteLength>0&&i!=null&&i.key&&i.iv&&i.method==="AES-128"){const a=performance.now();this.decrypter.decrypt(new Uint8Array(n),i.key.buffer,i.iv.buffer).catch(o=>{throw s.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:r}),o}).then(o=>{const l=performance.now();s.trigger(w.FRAG_DECRYPTED,{frag:r,payload:o,stats:{tstart:a,tdecrypt:l}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=Y.IDLE})}}doTick(){if(!this.media){this.state=Y.IDLE;return}if(this.state===Y.IDLE){const{currentTrackId:e,levels:r}=this,n=r==null?void 0:r[e];if(!n||!r.length||!n.details)return;const{config:i}=this,s=this.getLoadPosition(),a=at.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],s,i.maxBufferHole),{end:o,len:l}=a,u=this.getFwdBufferInfo(this.media,we.MAIN),c=n.details,d=this.getMaxBufferLength(u==null?void 0:u.len)+c.levelTargetDuration;if(l>d)return;const f=c.fragments,m=f.length,h=c.edge;let p=null;const v=this.fragPrevious;if(oh-g?0:g;p=Vc(v,f,Math.max(f[0].start,o),y),!p&&v&&v.start{if(i=i>>>0,i>s-1)throw new DOMException(`Failed to execute '${n}' on 'TimeRanges': The index provided (${i}) is greater than the maximum bound (${s})`);return e[i][n]};this.buffered={get length(){return e.length},end(n){return r("end",n,e.length)},start(n){return r("start",n,e.length)}}}}class SM extends Im{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.asyncPollTrackChange=()=>this.pollTrackChange(0),this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let r=null;const n=Pu(this.media.textTracks);for(let s=0;s-1&&this.toggleTrackModes()}registerListeners(){const{hls:e}=this;e.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.LEVEL_LOADING,this.onLevelLoading,this),e.on(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.on(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const{hls:e}=this;e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.LEVEL_LOADING,this.onLevelLoading,this),e.off(w.LEVEL_SWITCHING,this.onLevelSwitching,this),e.off(w.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),e.off(w.ERROR,this.onError,this)}onMediaAttached(e,r){this.media=r.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(){if(!this.media)return;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||this.media.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),Pu(this.media.textTracks).forEach(r=>{ta(r)}),this.subtitleTrack=-1,this.media=null}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(e,r){this.tracks=r.subtitleTracks}onSubtitleTrackLoaded(e,r){const{id:n,groupId:i,details:s}=r,a=this.tracksInGroup[n];if(!a||a.groupId!==i){this.warn(`Subtitle track with id:${n} and group:${i} not found in active group ${a==null?void 0:a.groupId}`);return}const o=a.details;a.details=r.details,this.log(`Subtitle track ${n} "${a.name}" lang:${a.lang} group:${i} loaded [${s.startSN}-${s.endSN}]`),n===this.trackId&&this.playlistLoaded(n,r,o)}onLevelLoading(e,r){this.switchLevel(r.level)}onLevelSwitching(e,r){this.switchLevel(r.level)}switchLevel(e){const r=this.hls.levels[e];if(!r)return;const n=r.subtitleGroups||null,i=this.groupIds;let s=this.currentTrack;if(!n||(i==null?void 0:i.length)!==(n==null?void 0:n.length)||n!=null&&n.some(a=>(i==null?void 0:i.indexOf(a))===-1)){this.groupIds=n,this.trackId=-1,this.currentTrack=null;const a=this.tracks.filter(c=>!n||n.indexOf(c.groupId)!==-1);if(a.length)this.selectDefaultTrack&&!a.some(c=>c.default)&&(this.selectDefaultTrack=!1),a.forEach((c,d)=>{c.id=d});else if(!s&&!this.tracksInGroup.length)return;this.tracksInGroup=a;const o=this.hls.config.subtitlePreference;if(!s&&o){this.selectDefaultTrack=!1;const c=Dn(o,a);if(c>-1)s=a[c];else{const d=Dn(o,this.tracks);s=this.tracks[d]}}let l=this.findTrackId(s);l===-1&&s&&(l=this.findTrackId(null));const u={subtitleTracks:a};this.log(`Updating subtitle tracks, ${a.length} track(s) found in "${n==null?void 0:n.join(",")}" group-id`),this.hls.trigger(w.SUBTITLE_TRACKS_UPDATED,u),l!==-1&&this.trackId===-1&&this.setSubtitleTrack(l)}else this.shouldReloadPlaylist(s)&&this.setSubtitleTrack(this.trackId)}findTrackId(e){const r=this.tracksInGroup,n=this.selectDefaultTrack;for(let i=0;i-1){const s=this.tracksInGroup[i];return this.setSubtitleTrack(i),s}else{if(n)return null;{const s=Dn(e,r);if(s>-1)return r[s]}}}}return null}loadPlaylist(e){super.loadPlaylist();const r=this.currentTrack;if(this.shouldLoadPlaylist(r)&&r){const n=r.id,i=r.groupId;let s=r.url;if(e)try{s=e.addDirectives(s)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}this.log(`Loading subtitle playlist for id ${n}`),this.hls.trigger(w.SUBTITLE_TRACK_LOADING,{url:s,id:n,groupId:i,deliveryDirectives:e||null})}}toggleTrackModes(){const{media:e}=this;if(!e)return;const r=Pu(e.textTracks),n=this.currentTrack;let i;if(n&&(i=r.filter(s=>tp(n,s))[0],i||this.warn(`Unable to find subtitle TextTrack with name "${n.name}" and language "${n.lang}"`)),[].slice.call(r).forEach(s=>{s.mode!=="disabled"&&s!==i&&(s.mode="disabled")}),i){const s=this.subtitleDisplay?"showing":"hidden";i.mode!==s&&(i.mode=s)}}setSubtitleTrack(e){const r=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=e;return}if(e<-1||e>=r.length||!pe(e)){this.warn(`Invalid subtitle track id: ${e}`);return}this.clearTimer(),this.selectDefaultTrack=!1;const n=this.currentTrack,i=r[e]||null;if(this.trackId=e,this.currentTrack=i,this.toggleTrackModes(),!i){this.hls.trigger(w.SUBTITLE_TRACK_SWITCH,{id:e});return}const s=!!i.details&&!i.details.live;if(e===this.trackId&&i===n&&s)return;this.log(`Switching to subtitle-track ${e}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:a,groupId:o="",name:l,type:u,url:c}=i;this.hls.trigger(w.SUBTITLE_TRACK_SWITCH,{id:a,groupId:o,name:l,type:u,url:c});const d=this.switchParams(i.url,n==null?void 0:n.details,i.details);this.loadPlaylist(d)}}class EM{constructor(e){this.buffers=void 0,this.queues={video:[],audio:[],audiovideo:[]},this.buffers=e}append(e,r,n){const i=this.queues[r];i.push(e),i.length===1&&!n&&this.executeNext(r)}insertAbort(e,r){this.queues[r].unshift(e),this.executeNext(r)}appendBlocker(e){let r;const n=new Promise(s=>{r=s}),i={execute:r,onStart:()=>{},onComplete:()=>{},onError:()=>{}};return this.append(i,e),n}executeNext(e){const r=this.queues[e];if(r.length){const n=r[0];try{n.execute()}catch(i){U.warn(`[buffer-operation-queue]: Exception executing "${e}" SourceBuffer operation: ${i}`),n.onError(i);const s=this.buffers[e];s!=null&&s.updating||this.shiftAndExecuteNext(e)}}}shiftAndExecuteNext(e){this.queues[e].shift(),this.executeNext(e)}current(e){return this.queues[e][0]}}const qv=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/;class TM{constructor(e){this.details=null,this._objectUrl=null,this.operationQueue=void 0,this.listeners=void 0,this.hls=void 0,this.bufferCodecEventsExpected=0,this._bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.appendSource=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.pendingTracks={},this.sourceBuffer=void 0,this.log=void 0,this.warn=void 0,this.error=void 0,this._onEndStreaming=n=>{this.hls&&this.hls.pauseBuffering()},this._onStartStreaming=n=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=()=>{const{media:n,mediaSource:i}=this;this.log("Media source opened"),n&&(n.removeEventListener("emptied",this._onMediaEmptied),this.updateMediaElementDuration(),this.hls.trigger(w.MEDIA_ATTACHED,{media:n,mediaSource:i})),i&&i.removeEventListener("sourceopen",this._onMediaSourceOpen),this.checkPendingTracks()},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:n,_objectUrl:i}=this;n!==i&&U.error(`Media element src was set while attaching MediaSource (${i} > ${n})`)},this.hls=e;const r="[buffer-controller]";this.appendSource=kP(bs(e.config.preferManagedMediaSource)),this.log=U.log.bind(U,r),this.warn=U.warn.bind(U,r),this.error=U.error.bind(U,r),this._initSourceBuffer(),this.registerListeners()}hasSourceTypes(){return this.getSourceBufferTypes().length>0||Object.keys(this.pendingTracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=null,this.hls=null}registerListeners(){const{hls:e}=this;e.on(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.BUFFER_RESET,this.onBufferReset,this),e.on(w.BUFFER_APPENDING,this.onBufferAppending,this),e.on(w.BUFFER_CODECS,this.onBufferCodecs,this),e.on(w.BUFFER_EOS,this.onBufferEos,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.on(w.LEVEL_UPDATED,this.onLevelUpdated,this),e.on(w.FRAG_PARSED,this.onFragParsed,this),e.on(w.FRAG_CHANGED,this.onFragChanged,this)}unregisterListeners(){const{hls:e}=this;e.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.BUFFER_RESET,this.onBufferReset,this),e.off(w.BUFFER_APPENDING,this.onBufferAppending,this),e.off(w.BUFFER_CODECS,this.onBufferCodecs,this),e.off(w.BUFFER_EOS,this.onBufferEos,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),e.off(w.LEVEL_UPDATED,this.onLevelUpdated,this),e.off(w.FRAG_PARSED,this.onFragParsed,this),e.off(w.FRAG_CHANGED,this.onFragChanged,this)}_initSourceBuffer(){this.sourceBuffer={},this.operationQueue=new EM(this.sourceBuffer),this.listeners={audio:[],video:[],audiovideo:[]},this.appendErrors={audio:0,video:0,audiovideo:0},this.lastMpegAudioChunk=null}onManifestLoading(){this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=0,this.details=null}onManifestParsed(e,r){let n=2;(r.audio&&!r.video||!r.altAudio)&&(n=1),this.bufferCodecEventsExpected=this._bufferCodecEventsTotal=n,this.log(`${this.bufferCodecEventsExpected} bufferCodec event(s) expected`)}onMediaAttaching(e,r){const n=this.media=r.media,i=bs(this.appendSource);if(n&&i){var s;const a=this.mediaSource=new i;this.log(`created media source: ${(s=a.constructor)==null?void 0:s.name}`),a.addEventListener("sourceopen",this._onMediaSourceOpen),a.addEventListener("sourceended",this._onMediaSourceEnded),a.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(a.addEventListener("startstreaming",this._onStartStreaming),a.addEventListener("endstreaming",this._onEndStreaming));const o=this._objectUrl=self.URL.createObjectURL(a);if(this.appendSource)try{n.removeAttribute("src");const l=self.ManagedMediaSource;n.disableRemotePlayback=n.disableRemotePlayback||l&&a instanceof l,Xv(n),wM(n,o),n.load()}catch{n.src=o}else n.src=o;n.addEventListener("emptied",this._onMediaEmptied)}}onMediaDetaching(){const{media:e,mediaSource:r,_objectUrl:n}=this;if(r){if(this.log("media source detaching"),r.readyState==="open")try{r.endOfStream()}catch(i){this.warn(`onMediaDetaching: ${i.message} while calling endOfStream`)}this.onBufferReset(),r.removeEventListener("sourceopen",this._onMediaSourceOpen),r.removeEventListener("sourceended",this._onMediaSourceEnded),r.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(r.removeEventListener("startstreaming",this._onStartStreaming),r.removeEventListener("endstreaming",this._onEndStreaming)),e&&(e.removeEventListener("emptied",this._onMediaEmptied),n&&self.URL.revokeObjectURL(n),this.mediaSrc===n?(e.removeAttribute("src"),this.appendSource&&Xv(e),e.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.mediaSource=null,this.media=null,this._objectUrl=null,this.bufferCodecEventsExpected=this._bufferCodecEventsTotal,this.pendingTracks={},this.tracks={}}this.hls.trigger(w.MEDIA_DETACHED,void 0)}onBufferReset(){this.getSourceBufferTypes().forEach(e=>{this.resetBuffer(e)}),this._initSourceBuffer()}resetBuffer(e){const r=this.sourceBuffer[e];try{if(r){var n;this.removeBufferListeners(e),this.sourceBuffer[e]=void 0,(n=this.mediaSource)!=null&&n.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}}catch(i){this.warn(`onBufferReset ${e}`,i)}}onBufferCodecs(e,r){const n=this.getSourceBufferTypes().length,i=Object.keys(r);if(i.forEach(a=>{if(n){const l=this.tracks[a];if(l&&typeof l.buffer.changeType=="function"){var o;const{id:u,codec:c,levelCodec:d,container:f,metadata:m}=r[a],h=vv(l.codec,l.levelCodec),p=h==null?void 0:h.replace(qv,"$1");let v=vv(c,d);const g=(o=v)==null?void 0:o.replace(qv,"$1");if(v&&p!==g){a.slice(0,5)==="audio"&&(v=Uc(v,this.appendSource));const y=`${f};codecs=${v}`;this.appendChangeType(a,y),this.log(`switching codec ${h} to ${v}`),this.tracks[a]={buffer:l.buffer,codec:c,container:f,levelCodec:d,metadata:m,id:u}}}}else this.pendingTracks[a]=r[a]}),n)return;const s=Math.max(this.bufferCodecEventsExpected-1,0);this.bufferCodecEventsExpected!==s&&(this.log(`${s} bufferCodec event(s) expected ${i.join(",")}`),this.bufferCodecEventsExpected=s),this.mediaSource&&this.mediaSource.readyState==="open"&&this.checkPendingTracks()}appendChangeType(e,r){const{operationQueue:n}=this,i={execute:()=>{const s=this.sourceBuffer[e];s&&(this.log(`changing ${e} sourceBuffer type to ${r}`),s.changeType(r)),n.shiftAndExecuteNext(e)},onStart:()=>{},onComplete:()=>{},onError:s=>{this.warn(`Failed to change ${e} SourceBuffer type`,s)}};n.append(i,e,!!this.pendingTracks[e])}onBufferAppending(e,r){const{hls:n,operationQueue:i,tracks:s}=this,{data:a,type:o,frag:l,part:u,chunkMeta:c}=r,d=c.buffering[o],f=self.performance.now();d.start=f;const m=l.stats.buffering,h=u?u.stats.buffering:null;m.start===0&&(m.start=f),h&&h.start===0&&(h.start=f);const p=s.audio;let v=!1;o==="audio"&&(p==null?void 0:p.container)==="audio/mpeg"&&(v=!this.lastMpegAudioChunk||c.id===1||this.lastMpegAudioChunk.sn!==c.sn,this.lastMpegAudioChunk=c);const g=l.start,y={execute:()=>{if(d.executeStart=self.performance.now(),v){const x=this.sourceBuffer[o];if(x){const S=g-x.timestampOffset;Math.abs(S)>=.1&&(this.log(`Updating audio SourceBuffer timestampOffset to ${g} (delta: ${S}) sn: ${l.sn})`),x.timestampOffset=g)}}this.appendExecutor(a,o)},onStart:()=>{},onComplete:()=>{const x=self.performance.now();d.executeEnd=d.end=x,m.first===0&&(m.first=x),h&&h.first===0&&(h.first=x);const{sourceBuffer:S}=this,T={};for(const C in S)T[C]=at.getBuffered(S[C]);this.appendErrors[o]=0,o==="audio"||o==="video"?this.appendErrors.audiovideo=0:(this.appendErrors.audio=0,this.appendErrors.video=0),this.hls.trigger(w.BUFFER_APPENDED,{type:o,frag:l,part:u,chunkMeta:c,parent:l.type,timeRanges:T})},onError:x=>{const S={type:_e.MEDIA_ERROR,parent:l.type,details:z.BUFFER_APPEND_ERROR,sourceBufferName:o,frag:l,part:u,chunkMeta:c,error:x,err:x,fatal:!1};if(x.code===DOMException.QUOTA_EXCEEDED_ERR)S.details=z.BUFFER_FULL_ERROR;else{const T=++this.appendErrors[o];S.details=z.BUFFER_APPEND_ERROR,this.warn(`Failed ${T}/${n.config.appendErrorMaxRetry} times to append segment in "${o}" sourceBuffer`),T>=n.config.appendErrorMaxRetry&&(S.fatal=!0)}n.trigger(w.ERROR,S)}};i.append(y,o,!!this.pendingTracks[o])}onBufferFlushing(e,r){const{operationQueue:n}=this,i=s=>({execute:this.removeExecutor.bind(this,s,r.startOffset,r.endOffset),onStart:()=>{},onComplete:()=>{this.hls.trigger(w.BUFFER_FLUSHED,{type:s})},onError:a=>{this.warn(`Failed to remove from ${s} SourceBuffer`,a)}});r.type?n.append(i(r.type),r.type):this.getSourceBufferTypes().forEach(s=>{n.append(i(s),s)})}onFragParsed(e,r){const{frag:n,part:i}=r,s=[],a=i?i.elementaryStreams:n.elementaryStreams;a[Je.AUDIOVIDEO]?s.push("audiovideo"):(a[Je.AUDIO]&&s.push("audio"),a[Je.VIDEO]&&s.push("video"));const o=()=>{const l=self.performance.now();n.stats.buffering.end=l,i&&(i.stats.buffering.end=l);const u=i?i.stats:n.stats;this.hls.trigger(w.FRAG_BUFFERED,{frag:n,part:i,stats:u,id:n.type})};s.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${n.type} level: ${n.level} sn: ${n.sn}`),this.blockBuffers(o,s)}onFragChanged(e,r){this.trimBuffers()}onBufferEos(e,r){this.getSourceBufferTypes().reduce((i,s)=>{const a=this.sourceBuffer[s];return a&&(!r.type||r.type===s)&&(a.ending=!0,a.ended||(a.ended=!0,this.log(`${s} sourceBuffer now EOS`))),i&&!!(!a||a.ended)},!0)&&(this.log("Queueing mediaSource.endOfStream()"),this.blockBuffers(()=>{this.getSourceBufferTypes().forEach(s=>{const a=this.sourceBuffer[s];a&&(a.ending=!1)});const{mediaSource:i}=this;if(!i||i.readyState!=="open"){i&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${i.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),i.endOfStream()}))}onLevelUpdated(e,{details:r}){r.fragments.length&&(this.details=r,this.getSourceBufferTypes().length?this.blockBuffers(this.updateMediaElementDuration.bind(this)):this.updateMediaElementDuration())}trimBuffers(){const{hls:e,details:r,media:n}=this;if(!n||r===null||!this.getSourceBufferTypes().length)return;const s=e.config,a=n.currentTime,o=r.levelTargetDuration,l=r.live&&s.liveBackBufferLength!==null?s.liveBackBufferLength:s.backBufferLength;if(pe(l)&&l>0){const u=Math.max(l,o),c=Math.floor(a/o)*o-u;this.flushBackBuffer(a,o,c)}if(pe(s.frontBufferFlushThreshold)&&s.frontBufferFlushThreshold>0){const u=Math.max(s.maxBufferLength,s.frontBufferFlushThreshold),c=Math.max(u,o),d=Math.floor(a/o)*o+c;this.flushFrontBuffer(a,o,d)}}flushBackBuffer(e,r,n){const{details:i,sourceBuffer:s}=this;this.getSourceBufferTypes().forEach(o=>{const l=s[o];if(l){const u=at.getBuffered(l);if(u.length>0&&n>u.start(0)){if(this.hls.trigger(w.BACK_BUFFER_REACHED,{bufferEnd:n}),i!=null&&i.live)this.hls.trigger(w.LIVE_BACK_BUFFER_REACHED,{bufferEnd:n});else if(l.ended&&u.end(u.length-1)-e{const o=i[a];if(o){const l=at.getBuffered(o),u=l.length;if(u<2)return;const c=l.start(u-1),d=l.end(u-1);if(n>c||e>=c&&e<=d)return;if(o.ended&&e-d<2*r){this.log(`Cannot flush ${a} front buffer while SourceBuffer is in ended state`);return}this.hls.trigger(w.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:a})}})}updateMediaElementDuration(){if(!this.details||!this.media||!this.mediaSource||this.mediaSource.readyState!=="open")return;const{details:e,hls:r,media:n,mediaSource:i}=this,s=e.fragments[0].start+e.totalduration,a=n.duration,o=pe(i.duration)?i.duration:0;e.live&&r.config.liveDurationInfinity?(i.duration=1/0,this.updateSeekableRange(e)):(s>o&&s>a||!pe(a))&&(this.log(`Updating Media Source duration to ${s.toFixed(3)}`),i.duration=s)}updateSeekableRange(e){const r=this.mediaSource,n=e.fragments;if(n.length&&e.live&&r!=null&&r.setLiveSeekableRange){const s=Math.max(0,n[0].start),a=Math.max(s,s+e.totalduration);this.log(`Media Source duration is set to ${r.duration}. Setting seekable range to ${s}-${a}.`),r.setLiveSeekableRange(s,a)}}checkPendingTracks(){const{bufferCodecEventsExpected:e,operationQueue:r,pendingTracks:n}=this,i=Object.keys(n).length;if(i&&(!e||i===2||"audiovideo"in n)){this.createSourceBuffers(n),this.pendingTracks={};const s=this.getSourceBufferTypes();if(s.length)this.hls.trigger(w.BUFFER_CREATED,{tracks:this.tracks}),s.forEach(a=>{r.executeNext(a)});else{const a=new Error("could not create source buffer for media codec(s)");this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:a,reason:a.message})}}}createSourceBuffers(e){const{sourceBuffer:r,mediaSource:n}=this;if(!n)throw Error("createSourceBuffers called when mediaSource was null");for(const s in e)if(!r[s]){var i;const a=e[s];if(!a)throw Error(`source buffer exists for track ${s}, however track does not`);let o=((i=a.levelCodec)==null?void 0:i.indexOf(","))===-1?a.levelCodec:a.codec;o&&s.slice(0,5)==="audio"&&(o=Uc(o,this.appendSource));const l=`${a.container};codecs=${o}`;this.log(`creating sourceBuffer(${l})`);try{const u=r[s]=n.addSourceBuffer(l),c=s;this.addBufferListener(c,"updatestart",this._onSBUpdateStart),this.addBufferListener(c,"updateend",this._onSBUpdateEnd),this.addBufferListener(c,"error",this._onSBUpdateError),this.appendSource&&this.addBufferListener(c,"bufferedchange",(d,f)=>{const m=f.removedRanges;m!=null&&m.length&&this.hls.trigger(w.BUFFER_FLUSHED,{type:s})}),this.tracks[s]={buffer:u,codec:o,container:a.container,levelCodec:a.levelCodec,metadata:a.metadata,id:a.id}}catch(u){this.error(`error while trying to add sourceBuffer: ${u.message}`),this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:s,mimeType:l})}}}get mediaSrc(){var e,r;const n=((e=this.media)==null||(r=e.querySelector)==null?void 0:r.call(e,"source"))||this.media;return n==null?void 0:n.src}_onSBUpdateStart(e){const{operationQueue:r}=this;r.current(e).onStart()}_onSBUpdateEnd(e){var r;if(((r=this.mediaSource)==null?void 0:r.readyState)==="closed"){this.resetBuffer(e);return}const{operationQueue:n}=this;n.current(e).onComplete(),n.shiftAndExecuteNext(e)}_onSBUpdateError(e,r){var n;const i=new Error(`${e} SourceBuffer error. MediaSource readyState: ${(n=this.mediaSource)==null?void 0:n.readyState}`);this.error(`${i}`,r),this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.BUFFER_APPENDING_ERROR,sourceBufferName:e,error:i,fatal:!1});const s=this.operationQueue.current(e);s&&s.onError(i)}removeExecutor(e,r,n){const{media:i,mediaSource:s,operationQueue:a,sourceBuffer:o}=this,l=o[e];if(!i||!s||!l){this.warn(`Attempting to remove from the ${e} SourceBuffer, but it does not exist`),a.shiftAndExecuteNext(e);return}const u=pe(i.duration)?i.duration:1/0,c=pe(s.duration)?s.duration:1/0,d=Math.max(0,r),f=Math.min(n,u,c);f>d&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${d},${f}] from the ${e} SourceBuffer`),l.remove(d,f)):a.shiftAndExecuteNext(e)}appendExecutor(e,r){const n=this.sourceBuffer[r];if(!n){if(!this.pendingTracks[r])throw new Error(`Attempting to append to the ${r} SourceBuffer, but it does not exist`);return}n.ended=!1,n.appendBuffer(e)}blockBuffers(e,r=this.getSourceBufferTypes()){if(!r.length){this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(e);return}const{operationQueue:n}=this,i=r.map(s=>n.appendBlocker(s));Promise.all(i).then(()=>{e(),r.forEach(s=>{const a=this.sourceBuffer[s];a!=null&&a.updating||n.shiftAndExecuteNext(s)})})}getSourceBufferTypes(){return Object.keys(this.sourceBuffer)}addBufferListener(e,r,n){const i=this.sourceBuffer[e];if(!i)return;const s=n.bind(this,e);this.listeners[e].push({event:r,listener:s}),i.addEventListener(r,s)}removeBufferListeners(e){const r=this.sourceBuffer[e];r&&this.listeners[e].forEach(n=>{r.removeEventListener(n.event,n.listener)})}}function Xv(t){const e=t.querySelectorAll("source");[].slice.call(e).forEach(r=>{t.removeChild(r)})}function wM(t,e){const r=self.document.createElement("source");r.type="video/mp4",r.src=e,t.appendChild(r)}const bM={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},QT=t=>String.fromCharCode(bM[t]||t),an=15,Kn=100,LM={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},AM={17:2,18:4,21:6,22:8,23:10,19:13,20:15},_M={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},CM={25:2,26:4,29:6,30:8,31:10,27:13,28:15},RM=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class IM{constructor(){this.time=null,this.verboseLevel=0}log(e,r){if(this.verboseLevel>=e){const n=typeof r=="function"?r():r;U.log(`${this.time} [${e}] ${n}`)}}}const Zi=function(e){const r=[];for(let n=0;nKn&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=Kn)}moveCursor(e){const r=this.pos+e;if(e>1)for(let n=this.pos+1;n=144&&this.backSpace();const r=QT(e);if(this.pos>=Kn){this.logger.log(0,()=>"Cannot insert "+e.toString(16)+" ("+r+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(r,this.currPenState),this.moveCursor(1)}clearFromPos(e){let r;for(r=e;r"pacData = "+JSON.stringify(e));let r=e.row-1;if(this.nrRollUpRows&&r"bkgData = "+JSON.stringify(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,r=this.rows.splice(e,1)[0];r.clear(),this.rows.splice(this.currRow,0,r),this.logger.log(2,"Rolling up")}getDisplayText(e){e=e||!1;const r=[];let n="",i=-1;for(let s=0;s0&&(e?n="["+r.join(" | ")+"]":n=r.join(` +`)),n}getTextAndFormat(){return this.rows}}class Zv{constructor(e,r,n){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=e,this.outputFilter=r,this.mode=null,this.verbose=0,this.displayedMemory=new kf(n),this.nonDisplayedMemory=new kf(n),this.lastOutputScreen=new kf(n),this.currRollUpRow=this.displayedMemory.rows[an-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=n}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[an-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 n=0;nr+": "+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 r={flash:!1};if(r.underline=e%2===1,r.italics=e>=46,r.italics)r.foreground="white";else{const n=Math.floor(e/2)-16,i=["white","green","blue","cyan","red","yellow","magenta"];r.foreground=i[n]}this.logger.log(2,"MIDROW: "+JSON.stringify(r)),this.writeScreen.setPen(r)}outputDataUpdate(e=!1){const r=this.logger.time;r!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=r:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,r,this.lastOutputScreen),e&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:r),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))}}class Qv{constructor(e,r,n){this.channels=void 0,this.currentChannel=0,this.cmdHistory=OM(),this.logger=void 0;const i=this.logger=new IM;this.channels=[null,new Zv(e,r,i),new Zv(e+1,n,i)]}getHandler(e){return this.channels[e].getHandler()}setHandler(e,r){this.channels[e].setHandler(r)}addData(e,r){this.logger.time=e;for(let n=0;n"["+Zi([r[n],r[n+1]])+"] -> ("+Zi([i,s])+")");const l=this.cmdHistory;if(i>=16&&i<=31){if(PM(i,s,l)){ou(null,null,l),this.logger.log(3,()=>"Repeated command ("+Zi([i,s])+") is dropped");continue}ou(i,s,this.cmdHistory),a=this.parseCmd(i,s),a||(a=this.parseMidrow(i,s)),a||(a=this.parsePAC(i,s)),a||(a=this.parseBackgroundAttributes(i,s))}else ou(null,null,l);if(!a&&(o=this.parseChars(i,s),o)){const c=this.currentChannel;c&&c>0?this.channels[c].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!a&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+Zi([i,s])+" orig: "+Zi([r[n],r[n+1]]))}}parseCmd(e,r){const n=(e===20||e===28||e===21||e===29)&&r>=32&&r<=47,i=(e===23||e===31)&&r>=33&&r<=35;if(!(n||i))return!1;const s=e===20||e===21||e===23?1:2,a=this.channels[s];return e===20||e===21||e===28||e===29?r===32?a.ccRCL():r===33?a.ccBS():r===34?a.ccAOF():r===35?a.ccAON():r===36?a.ccDER():r===37?a.ccRU(2):r===38?a.ccRU(3):r===39?a.ccRU(4):r===40?a.ccFON():r===41?a.ccRDC():r===42?a.ccTR():r===43?a.ccRTD():r===44?a.ccEDM():r===45?a.ccCR():r===46?a.ccENM():r===47&&a.ccEOC():a.ccTO(r-32),this.currentChannel=s,!0}parseMidrow(e,r){let n=0;if((e===17||e===25)&&r>=32&&r<=47){if(e===17?n=1:n=2,n!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const i=this.channels[n];return i?(i.ccMIDROW(r),this.logger.log(3,()=>"MIDROW ("+Zi([e,r])+")"),!0):!1}return!1}parsePAC(e,r){let n;const i=(e>=17&&e<=23||e>=25&&e<=31)&&r>=64&&r<=127,s=(e===16||e===24)&&r>=64&&r<=95;if(!(i||s))return!1;const a=e<=23?1:2;r>=64&&r<=95?n=a===1?LM[e]:_M[e]:n=a===1?AM[e]:CM[e];const o=this.channels[a];return o?(o.setPAC(this.interpretPAC(n,r)),this.currentChannel=a,!0):!1}interpretPAC(e,r){let n;const i={color:null,italics:!1,indent:null,underline:!1,row:e};return r>95?n=r-96:n=r-64,i.underline=(n&1)===1,n<=13?i.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(n/2)]:n<=15?(i.italics=!0,i.color="white"):i.indent=Math.floor((n-16)/2)*4,i}parseChars(e,r){let n,i=null,s=null;if(e>=25?(n=2,s=e-8):(n=1,s=e),s>=17&&s<=19){let a;s===17?a=r+80:s===18?a=r+112:a=r+144,this.logger.log(2,()=>"Special char '"+QT(a)+"' in channel "+n),i=[a]}else e>=32&&e<=127&&(i=r===0?[e]:[e,r]);return i&&this.logger.log(3,()=>"Char codes = "+Zi(i).join(",")),i}parseBackgroundAttributes(e,r){const n=(e===16||e===24)&&r>=32&&r<=47,i=(e===23||e===31)&&r>=45&&r<=47;if(!(n||i))return!1;let s;const a={};e===16||e===24?(s=Math.floor((r-32)/2),a.background=RM[s],r%2===1&&(a.background=a.background+"_semi")):r===45?a.background="transparent":(a.foreground="black",r===47&&(a.underline=!0));const o=e<=23?1:2;return this.channels[o].setBkgData(a),!0}reset(){for(let e=0;ee)&&(this.startTime=e),this.endTime=r,this.screen=n,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}var Bm=function(){if(Ra!=null&&Ra.VTTCue)return self.VTTCue;const t=["","lr","rl"],e=["start","middle","end","left","right"];function r(o,l){if(typeof l!="string"||!Array.isArray(o))return!1;const u=l.toLowerCase();return~o.indexOf(u)?u:!1}function n(o){return r(t,o)}function i(o){return r(e,o)}function s(o,...l){let u=1;for(;u100)throw new Error("Position must be between 0 and 100.");C=A,this.hasBeenReset=!0}})),Object.defineProperty(c,"positionAlign",s({},d,{get:function(){return _},set:function(A){const k=i(A);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");_=k,this.hasBeenReset=!0}})),Object.defineProperty(c,"size",s({},d,{get:function(){return b},set:function(A){if(A<0||A>100)throw new Error("Size must be between 0 and 100.");b=A,this.hasBeenReset=!0}})),Object.defineProperty(c,"align",s({},d,{get:function(){return I},set:function(A){const k=i(A);if(!k)throw new SyntaxError("An invalid or illegal string was specified.");I=k,this.hasBeenReset=!0}})),c.displayState=void 0}return a.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},a}();class MM{decode(e,r){if(!e)return"";if(typeof e!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(e))}}function ew(t){function e(n,i,s,a){return(n|0)*3600+(i|0)*60+(s|0)+parseFloat(a||0)}const r=t.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return r?parseFloat(r[2])>59?e(r[2],r[3],0,r[4]):e(r[1],r[2],r[3],r[4]):null}let NM=class{constructor(){this.values=Object.create(null)}set(e,r){!this.get(e)&&r!==""&&(this.values[e]=r)}get(e,r,n){return n?this.has(e)?this.values[e]:r[n]:this.has(e)?this.values[e]:r}has(e){return e in this.values}alt(e,r,n){for(let i=0;i=0&&n<=100)return this.set(e,n),!0}return!1}};function tw(t,e,r,n){const i=n?t.split(n):[t];for(const s in i){if(typeof i[s]!="string")continue;const a=i[s].split(r);if(a.length!==2)continue;const o=a[0],l=a[1];e(o,l)}}const rp=new Bm(0,0,""),uu=rp.align==="middle"?"middle":"center";function FM(t,e,r){const n=t;function i(){const o=ew(t);if(o===null)throw new Error("Malformed timestamp: "+n);return t=t.replace(/^[^\sa-zA-Z-]+/,""),o}function s(o,l){const u=new NM;tw(o,function(f,m){let h;switch(f){case"region":for(let p=r.length-1;p>=0;p--)if(r[p].id===m){u.set(f,r[p].region);break}break;case"vertical":u.alt(f,m,["rl","lr"]);break;case"line":h=m.split(","),u.integer(f,h[0]),u.percent(f,h[0])&&u.set("snapToLines",!1),u.alt(f,h[0],["auto"]),h.length===2&&u.alt("lineAlign",h[1],["start",uu,"end"]);break;case"position":h=m.split(","),u.percent(f,h[0]),h.length===2&&u.alt("positionAlign",h[1],["start",uu,"end","line-left","line-right","auto"]);break;case"size":u.percent(f,m);break;case"align":u.alt(f,m,["start",uu,"end","left","right"]);break}},/:/,/\s/),l.region=u.get("region",null),l.vertical=u.get("vertical","");let c=u.get("line","auto");c==="auto"&&rp.line===-1&&(c=-1),l.line=c,l.lineAlign=u.get("lineAlign","start"),l.snapToLines=u.get("snapToLines",!0),l.size=u.get("size",100),l.align=u.get("align",uu);let d=u.get("position","auto");d==="auto"&&rp.position===50&&(d=l.align==="start"||l.align==="left"?0:l.align==="end"||l.align==="right"?100:50),l.position=d}function a(){t=t.replace(/^\s+/,"")}if(a(),e.startTime=i(),a(),t.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+n);t=t.slice(3),a(),e.endTime=i(),a(),s(t,e)}function rw(t){return t.replace(//gi,` +`)}class UM{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new MM,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(e){const r=this;e&&(r.buffer+=r.decoder.decode(e,{stream:!0}));function n(){let s=r.buffer,a=0;for(s=rw(s);a")===-1){r.cue.id=s;continue}case"CUE":if(!r.cue){r.state="BADCUE";continue}try{UM(s,r.cue,r.regionList)}catch{r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":{const o=s.indexOf("-->")!==-1;if(!s||o&&(a=!0)){r.oncue&&r.cue&&r.oncue(r.cue),r.cue=null,r.state="ID";continue}if(r.cue===null)continue;r.cue.text&&(r.cue.text+=` +`&&++a,r.buffer=s.slice(a),o}function i(s){tw(s,function(a,o){},/:/)}try{let s="";if(r.state==="INITIAL"){if(!/\r\n|\n/.test(r.buffer))return this;s=n();const o=s.match(/^()?WEBVTT([ \t].*)?$/);if(!(o!=null&&o[0]))throw new Error("Malformed WebVTT signature.");r.state="HEADER"}let a=!1;for(;r.buffer;){if(!/\r\n|\n/.test(r.buffer))return this;switch(a?a=!1:s=n(),r.state){case"HEADER":/:/.test(s)?i(s):s||(r.state="ID");continue;case"NOTE":s||(r.state="ID");continue;case"ID":if(/^NOTE($|[ \t])/.test(s)){r.state="NOTE";break}if(!s)continue;if(r.cue=new Bm(0,0,""),r.state="CUE",s.indexOf("-->")===-1){r.cue.id=s;continue}case"CUE":if(!r.cue){r.state="BADCUE";continue}try{FM(s,r.cue,r.regionList)}catch{r.cue=null,r.state="BADCUE";continue}r.state="CUETEXT";continue;case"CUETEXT":{const o=s.indexOf("-->")!==-1;if(!s||o&&(a=!0)){r.oncue&&r.cue&&r.oncue(r.cue),r.cue=null,r.state="ID";continue}if(r.cue===null)continue;r.cue.text&&(r.cue.text+=` `),r.cue.text+=s}continue;case"BADCUE":s||(r.state="ID")}}}catch{r.state==="CUETEXT"&&r.cue&&r.oncue&&r.oncue(r.cue),r.cue=null,r.state=r.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const e=this;try{if((e.cue||e.state==="HEADER")&&(e.buffer+=` -`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(r){e.onparsingerror&&e.onparsingerror(r)}return e.onflush&&e.onflush(),this}}const $M=/\r\n|\n\r|\n|\r/g,Df=function(e,r,n=0){return e.slice(n,n+r.length)===r},jM=function(e){let r=parseInt(e.slice(-3));const n=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!pe(r)||!pe(n)||!pe(i)||!pe(s))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return r+=1e3*n,r+=60*1e3*i,r+=60*60*1e3*s,r},Pf=function(e){let r=5381,n=e.length;for(;n;)r=r*33^e.charCodeAt(--n);return(r>>>0).toString()};function $m(t,e,r){return Pf(t.toString())+Pf(e.toString())+Pf(r)}const VM=function(e,r,n){let i=e[r],s=e[i.prevCC];if(!s||!s.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(a=s)!=null&&a.new;){var a;e.ccOffset+=i.start-s.start,i.new=!1,i=s,s=e[i.prevCC]}e.presentationOffset=n};function GM(t,e,r,n,i,s,a){const o=new BM,l=Nn(new Uint8Array(t)).trim().replace($M,` +`,e.parse()),e.state==="INITIAL"||e.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(r){e.onparsingerror&&e.onparsingerror(r)}return e.onflush&&e.onflush(),this}}const BM=/\r\n|\n\r|\n|\r/g,Df=function(e,r,n=0){return e.slice(n,n+r.length)===r},$M=function(e){let r=parseInt(e.slice(-3));const n=parseInt(e.slice(-6,-4)),i=parseInt(e.slice(-9,-7)),s=e.length>9?parseInt(e.substring(0,e.indexOf(":"))):0;if(!pe(r)||!pe(n)||!pe(i)||!pe(s))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${e}`);return r+=1e3*n,r+=60*1e3*i,r+=60*60*1e3*s,r},Pf=function(e){let r=5381,n=e.length;for(;n;)r=r*33^e.charCodeAt(--n);return(r>>>0).toString()};function $m(t,e,r){return Pf(t.toString())+Pf(e.toString())+Pf(r)}const jM=function(e,r,n){let i=e[r],s=e[i.prevCC];if(!s||!s.new&&i.new){e.ccOffset=e.presentationOffset=i.start,i.new=!1;return}for(;(a=s)!=null&&a.new;){var a;e.ccOffset+=i.start-s.start,i.new=!1,i=s,s=e[i.prevCC]}e.presentationOffset=n};function VM(t,e,r,n,i,s,a){const o=new UM,l=Nn(new Uint8Array(t)).trim().replace(BM,` `).split(` -`),u=[],c=e?aM(e.baseTime,e.timescale):0;let d="00:00.000",f=0,m=0,h,p=!0;o.oncue=function(v){const g=r[n];let y=r.ccOffset;const x=(f-c)/9e4;if(g!=null&&g.new&&(m!==void 0?y=r.ccOffset=g.start:VM(r,n,x)),x){if(!e){h=new Error("Missing initPTS for VTT MPEGTS");return}y=x-r.presentationOffset}const S=v.endTime-v.startTime,T=Hr((v.startTime+y-m)*9e4,i*9e4)/9e4;v.startTime=Math.max(T,0),v.endTime=Math.max(T+S,0);const C=v.text.trim();v.text=decodeURIComponent(encodeURIComponent(C)),v.id||(v.id=$m(v.startTime,v.endTime,C)),v.endTime>0&&u.push(v)},o.onparsingerror=function(v){h=v},o.onflush=function(){if(h){a(h);return}s(u)},l.forEach(v=>{if(p)if(Df(v,"X-TIMESTAMP-MAP=")){p=!1,v.slice(16).split(",").forEach(g=>{Df(g,"LOCAL:")?d=g.slice(6):Df(g,"MPEGTS:")&&(f=parseInt(g.slice(7)))});try{m=jM(d)/1e3}catch(g){h=g}return}else v===""&&(p=!1);o.parse(v+` -`)}),o.flush()}const Of="stpp.ttml.im1t",nw=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,iw=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,zM={left:"start",center:"center",right:"end",start:"start",end:"end"};function Jv(t,e,r,n){const i=Oe(new Uint8Array(t),["mdat"]);if(i.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const s=i.map(o=>Nn(o)),a=sM(e.baseTime,1,e.timescale);try{s.forEach(o=>r(HM(o,a)))}catch(o){n(o)}}function HM(t,e){const i=new DOMParser().parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(s).reduce((d,f)=>(d[f]=i.getAttribute(`ttp:${f}`)||s[f],d),{}),o=i.getAttribute("xml:space")!=="preserve",l=ey(Mf(i,"styling","style")),u=ey(Mf(i,"layout","region")),c=Mf(i,"body","[begin]");return[].map.call(c,d=>{const f=sw(d,o);if(!f||!d.hasAttribute("begin"))return null;const m=Ff(d.getAttribute("begin"),a),h=Ff(d.getAttribute("dur"),a);let p=Ff(d.getAttribute("end"),a);if(m===null)throw ty(d);if(p===null){if(h===null)throw ty(d);p=m+h}const v=new Bm(m-e,p-e,f);v.id=$m(v.startTime,v.endTime,v.text);const g=u[d.getAttribute("region")],y=l[d.getAttribute("style")],x=WM(g,y,l),{textAlign:S}=x;if(S){const T=zM[S];T&&(v.lineAlign=T),v.align=S}return It(v,x),v}).filter(d=>d!==null)}function Mf(t,e,r){const n=t.getElementsByTagName(e)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function ey(t){return t.reduce((e,r)=>{const n=r.getAttribute("xml:id");return n&&(e[n]=r),e},{})}function sw(t,e){return[].slice.call(t.childNodes).reduce((r,n,i)=>{var s;return n.nodeName==="br"&&i?r+` -`:(s=n.childNodes)!=null&&s.length?sw(n,e):e?r+n.textContent.trim().replace(/\s+/g," "):r+n.textContent},"")}function WM(t,e,r){const n="http://www.w3.org/ns/ttml#styling";let i=null;const s=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=t!=null&&t.hasAttribute("style")?t.getAttribute("style"):null;return a&&r.hasOwnProperty(a)&&(i=r[a]),s.reduce((o,l)=>{const u=Nf(e,n,l)||Nf(t,n,l)||Nf(i,n,l);return u&&(o[l]=u),o},{})}function Nf(t,e,r){return t&&t.hasAttributeNS(e,r)?t.getAttributeNS(e,r):null}function ty(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Ff(t,e){if(!t)return null;let r=ew(t);return r===null&&(nw.test(t)?r=KM(t,e):iw.test(t)&&(r=YM(t,e))),r}function KM(t,e){const r=nw.exec(t),n=(r[4]|0)+(r[5]|0)/e.subFrameRate;return(r[1]|0)*3600+(r[2]|0)*60+(r[3]|0)+n/e.frameRate}function YM(t,e){const r=iw.exec(t),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/e.frameRate;case"t":return n/e.tickRate}return n}class qM{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=ny(),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(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(w.FRAG_LOADING,this.onFragLoading,this),e.on(w.FRAG_LOADED,this.onFragLoaded,this),e.on(w.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(w.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(w.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(w.FRAG_LOADING,this.onFragLoading,this),e.off(w.FRAG_LOADED,this.onFragLoaded,this),e.off(w.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(w.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(w.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new lu(this,"textTrack1"),r=new lu(this,"textTrack2"),n=new lu(this,"textTrack3"),i=new lu(this,"textTrack4");this.cea608Parser1=new Qv(1,e,r),this.cea608Parser2=new Qv(3,n,i)}}addCues(e,r,n,i,s){let a=!1;for(let o=s.length;o--;){const l=s[o],u=XM(l[0],l[1],r,n);if(u>=0&&(l[0]=Math.min(l[0],r),l[1]=Math.max(l[1],n),a=!0,u/(n-r)>.5))return}if(a||s.push([r,n]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,r,n,i)}else{const o=this.Cues.newCue(null,r,n,i);this.hls.trigger(w.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:r,id:n,initPTS:i,timescale:s}){const{unparsedVttFrags:a}=this;n==="main"&&(this.initPTS[r.cc]={baseTime:i,timescale:s}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(w.FRAG_LOADED,o)}))}getExistingTrack(e,r){const{media:n}=this;if(n)for(let i=0;i{ta(e[r]),delete e[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ny(),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 r=e.textTracks;if(r)for(let n=0;ns.textCodec===Of);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(ZT(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const a=this.media,o=a?Pu(a.textTracks):null;if(this.tracks.forEach((l,u)=>{let c;if(o){let d=null;for(let f=0;fu!==null).map(u=>u.label);l.length&&U.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(w.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,r){this.config.enableCEA708Captions&&r.captions&&r.captions.forEach(n=>{const i=/(?:CC|SERVICE)([1-4])/.exec(n.instreamId);if(!i)return;const s=`textTrack${i[1]}`,a=this.captionsProperties[s];a&&(a.label=n.name,n.lang&&(a.languageCode=n.lang),a.media=n)})}closedCaptionsForLevel(e){const r=this.hls.levels[e.level];return r==null?void 0:r.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,r){if(this.enabled&&r.frag.type===we.MAIN){var n,i;const{cea608Parser1:s,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:u}=r.frag,c=(n=(i=r.part)==null?void 0:i.index)!=null?n:-1;s&&a&&(u!==o+1||u===o&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(s.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=c}}onFragLoaded(e,r){const{frag:n,payload:i}=r;if(n.type===we.SUBTITLE)if(i.byteLength){const s=n.decryptdata,a="stats"in r;if(s==null||!s.encrypted||a){const o=this.tracks[n.level],l=this.vttCCs;l[n.cc]||(l[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),o&&o.textCodec===Of?this._parseIMSC1(n,i):this._parseVTTs(r)}}else this.hls.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,r){const n=this.hls;Jv(r,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),n.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{U.log(`Failed to parse IMSC1: ${i}`),n.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var r;const{frag:n,payload:i}=e,{initPTS:s,unparsedVttFrags:a}=this,o=s.length-1;if(!s[n.cc]&&o===-1){a.push(e);return}const l=this.hls,u=(r=n.initSegment)!=null&&r.data?Jr(n.initSegment.data,new Uint8Array(i)):i;GM(u,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,c=>{this._appendCues(c,n.level),l.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},c=>{const d=c.message==="Missing initPTS for VTT MPEGTS";d?a.push(e):this._fallbackToIMSC1(n,i),U.log(`Failed to parse VTT cue: ${c}`),!(d&&o>n.cc)&&l.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:c})})}_fallbackToIMSC1(e,r){const n=this.tracks[e.level];n.textCodec||Jv(r,this.initPTS[e.cc],()=>{n.textCodec=Of,this._parseIMSC1(e,r)},()=>{n.textCodec="wvtt"})}_appendCues(e,r){const n=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[r];if(!i||i.mode==="disabled")return;e.forEach(s=>AT(i,s))}else{const i=this.tracks[r];if(!i)return;const s=i.default?"default":"subtitles"+r;n.trigger(w.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,r){const{frag:n}=r;n.type===we.SUBTITLE&&this.onFragLoaded(w.FRAG_LOADED,r)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,r){this.initCea608Parsers();const{cea608Parser1:n,cea608Parser2:i}=this;if(!this.enabled||!n||!i)return;const{frag:s,samples:a}=r;if(!(s.type===we.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let o=0;oqh(o[l],r,n))}if(this.config.renderTextTracksNatively&&r===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>qh(o[l],r,i))}}}extractCea608Data(e){const r=[[],[]],n=e[0]&31;let i=2;for(let s=0;sthis.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=r.autoLevelCapping}}}getMaxLevel(e){const r=this.hls.levels;if(!r.length)return-1;const n=r.filter((i,s)=>this.isLevelAllowed(i)&&s<=e);return this.clientRect=null,jm.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 e=this.media,r={width:0,height:0};if(e){const n=e.getBoundingClientRect();r.width=n.width,r.height=n.height,!r.width&&!r.height&&(r.width=n.right-n.left||e.width||0,r.height=n.bottom-n.top||e.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 e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(n=>e.bitrate===n.bitrate&&e.width===n.width&&e.height===n.height)}static getMaxLevelByMediaSize(e,r,n){if(!(e!=null&&e.length))return-1;const i=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let s=e.length-1;const a=Math.max(r,n);for(let o=0;o=a||l.height>=a)&&i(l,e[o+1])){s=o;break}}return s}}class ZM{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(w.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,r){const n=this.hls.config;if(n.capLevelOnFPSDrop){const i=r.media instanceof self.HTMLVideoElement?r.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}checkFPS(e,r,n){const i=performance.now();if(r){if(this.lastTime){const s=i-this.lastTime,a=n-this.lastDroppedFrames,o=r-this.lastDecodedFrames,l=1e3*a/s,u=this.hls;if(u.trigger(w.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:n}),l>0&&a>u.config.fpsDroppedMonitoringThreshold*o){let c=u.currentLevel;U.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(u.autoLevelCapping===-1||u.autoLevelCapping>=c)&&(c=c-1,u.trigger(w.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:u.currentLevel}),u.autoLevelCapping=c,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=n,this.lastDecodedFrames=r}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const r=e.getVideoPlaybackQuality();this.checkFPS(e,r.totalVideoFrames,r.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const cu="[eme]";class fa{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=fa.CDMCleanupPromise?[fa.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=U.debug.bind(U,cu),this.log=U.log.bind(U,cu),this.warn=U.warn.bind(U,cu),this.error=U.error.bind(U,cu),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(w.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(w.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(w.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(w.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:r,widevineLicenseUrl:n}=this.config,i=r[e];if(i)return i.licenseUrl;if(e===ot.WIDEVINE&&n)return n;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:r}=this.config,n=r[e];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const r=this.hls.levels,n=(a,o,l)=>!!a&&l.indexOf(a)===o,i=r.map(a=>a.audioCodec).filter(n),s=r.map(a=>a.videoCodec).filter(n);return i.length+s.length===0&&s.push("avc1.42e01e"),new Promise((a,o)=>{const l=u=>{const c=u.shift();this.getMediaKeysPromise(c,i,s).then(d=>a({keySystem:c,mediaKeys:d})).catch(d=>{u.length?l(u):d instanceof zr?o(d):o(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};l(e)})}requestMediaKeySystemAccess(e,r){const{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${n}`;return fT===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return n(e,r)}getMediaKeysPromise(e,r,n){const i=nP(e,r,n,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let a=s==null?void 0:s.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(i)}`),a=this.requestMediaKeySystemAccess(e,i);const o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const u=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(c=>(this.log(`Media-keys created for "${e}"`),u.then(d=>d?this.setMediaKeysServerCertificate(c,e,d):c))),o.mediaKeys.catch(c=>{this.error(`Failed to create media-keys for "${e}"}: ${c}`)}),o.mediaKeys})}return a.then(()=>s.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:r,mediaKeys:n}){this.log(`Creating key-system session "${r}" keyId: ${bn.hexDump(e.keyId||[])}`);const i=n.createSession(),s={decryptdata:e,keySystem:r,mediaKeys:n,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const r=e.decryptdata;if(r.pssh){const n=this.createMediaKeySessionContext(e),i=this.getKeyIdString(r),s="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(n,s,r.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return bn.hexDump(e.keyId)}updateKeySession(e,r){var n;const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${bn.hexDump(((n=e.decryptdata)==null?void 0:n.keyId)||[])} - } (data length: ${r&&r.byteLength})`),i.update(r)}selectKeySystemFormat(e){const r=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((r,n)=>{const i=xf(this.config),s=e.map(uv).filter(a=>!!a&&i.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(s).then(({keySystem:a})=>{const o=dv(a);o?r(o):n(new Error(`Unable to find format for key-system "${a}"`))}).catch(n)})}loadKey(e){const r=e.keyInfo.decryptdata,n=this.getKeyIdString(r),i=`(keyId: ${n} format: "${r.keyFormat}" method: ${r.method} uri: ${r.uri})`;this.log(`Starting session for key ${i}`);let s=this.keyIdToKeySessionPromise[n];return s||(s=this.keyIdToKeySessionPromise[n]=this.getKeySystemForKeyPromise(r).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:r});return this.generateRequestWithPreferredKeySession(l,"cenc",r.pssh,"playlist-key")}))),s.catch(a=>this.handleError(a))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof zr?this.hls.trigger(w.ERROR,e.data):this.hls.trigger(w.ERROR,{type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const r=this.getKeyIdString(e),n=this.keyIdToKeySessionPromise[r];if(!n){const i=uv(e.keyFormat),s=i?[i]:xf(this.config);return this.attemptKeySystemAccess(s)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=xf(this.config)),e.length===0)throw new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:r,initData:n}=e,i=`"${e.type}" event: init data type: "${r}"`;if(this.debug(i),n===null)return;let s,a;if(r==="sinf"&&this.config.drmSystems[ot.FAIRPLAY]){const d=Dt(new Uint8Array(n));try{const f=Am(JSON.parse(d).sinf),m=ST(new Uint8Array(f));if(!m)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");s=m.subarray(8,24),a=ot.FAIRPLAY}catch(f){this.warn(`${i} Failed to parse sinf: ${f}`);return}}else{const d=CP(n),f=d.filter(m=>m.systemId===ho.WIDEVINE)[0];if(!f){d.length===0||d.some(m=>!m.systemId)?this.warn(`${i} contains incomplete or invalid pssh data`):this.log(`ignoring ${i} for ${d.map(m=>cv(m.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(a=cv(f.systemId),f.version===0&&f.data){const m=f.data.length-22;s=f.data.subarray(m,m+16)}}if(!a||!s)return;const o=bn.hexDump(s),{keyIdToKeySessionPromise:l,mediaKeySessions:u}=this;let c=l[o];for(let d=0;dthis.generateRequestWithPreferredKeySession(f,r,n,"encrypted-event-key-match"));break}}c||(c=l[o]=this.getKeySystemSelectionPromise([a]).then(({keySystem:d,mediaKeys:f})=>{var m;this.throwIfDestroyed();const h=new hl("ISO-23001-7",o,(m=dv(d))!=null?m:"");return h.pssh=new Uint8Array(n),h.keyId=s,this.attemptSetMediaKeys(d,f).then(()=>{this.throwIfDestroyed();const p=this.createMediaKeySessionContext({decryptdata:h,keySystem:d,mediaKeys:f});return this.generateRequestWithPreferredKeySession(p,r,n,"encrypted-event-no-match")})})),c.catch(d=>this.handleError(d))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,r){const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(n).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(r)});return this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),n.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(s=>n.indexOf(s)===-1)})}generateRequestWithPreferredKeySession(e,r,n,i){var s,a;const o=(s=this.config.drmSystems)==null||(a=s[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const h=o.call(this.hls,r,n,e);if(!h)throw new Error("Invalid response from configured generateRequest filter");r=h.initDataType,n=e.decryptdata.pssh=h.initData?new Uint8Array(h.initData):null}catch(h){var l;if(this.warn(h.message),(l=this.hls)!=null&&l.config.debug)throw h}if(n===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const u=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${i}": ${u} (init data type: ${r} length: ${n?n.byteLength:null})`);const c=new Um,d=e._onmessage=h=>{const p=e.mediaKeysSession;if(!p){c.emit("error",new Error("invalid state"));return}const{messageType:v,message:g}=h;this.log(`"${v}" message event for session "${p.sessionId}" message size: ${g.byteLength}`),v==="license-request"||v==="license-renewal"?this.renewLicense(e,g).catch(y=>{this.handleError(y),c.emit("error",y)}):v==="license-release"?e.keySystem===ot.FAIRPLAY&&(this.updateKeySession(e,Kh("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${v}"`)},f=e._onkeystatuseschange=h=>{if(!e.mediaKeysSession){c.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const v=e.keyStatus;c.emit("keyStatus",v),v==="expired"&&(this.warn(`${e.keySystem} expired for key ${u}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",d),e.mediaKeysSession.addEventListener("keystatuseschange",f);const m=new Promise((h,p)=>{c.on("error",p),c.on("keyStatus",v=>{v.startsWith("usable")?h():v==="output-restricted"?p(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):v==="internal-error"?p(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${v}"`)):v==="expired"?p(new Error("key expired while generating request")):this.warn(`unhandled key status change "${v}"`)})});return e.mediaKeysSession.generateRequest(r,n).then(()=>{var h;this.log(`Request generated for key-session "${(h=e.mediaKeysSession)==null?void 0:h.sessionId}" keyId: ${u}`)}).catch(h=>{throw new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_SESSION,error:h,fatal:!1},`Error generating key-session request: ${h}`)}).then(()=>m).catch(h=>{throw c.removeAllListeners(),this.removeSession(e),h}).then(()=>(c.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((r,n)=>{this.log(`key status change "${r}" for keyStatuses keyId: ${bn.hexDump("buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n))} session keyId: ${bn.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=r})}fetchServerCertificate(e){const r=this.config,n=r.loader,i=new n(r),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:s},u=r.certLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(f,m,h,p)=>{a(f.data)},onError:(f,m,h,p)=>{o(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:h,response:jt({url:l.url,data:void 0},f)},`"${e}" certificate request failed (${s}). Status: ${f.code} (${f.text})`))},onTimeout:(f,m,h)=>{o(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:h,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(f,m,h)=>{o(new Error("aborted"))}};i.load(l,c,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,r,n){return new Promise((i,s)=>{e.setServerCertificate(n).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${n==null?void 0:n.byteLength}) on "${r}"`),i(e)}).catch(a=>{s(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,r){return this.requestLicense(e,new Uint8Array(r)).then(n=>this.updateKeySession(e,new Uint8Array(n)).catch(i=>{throw new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:i,fatal:!0},i.message)}))}unpackPlayReadyKeyMessage(e,r){const n=String.fromCharCode.apply(null,new Uint16Array(r.buffer));if(!n.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),r;const i=new DOMParser().parseFromString(n,"application/xml"),s=i.querySelectorAll("HttpHeader");if(s.length>0){let c;for(let d=0,f=s.length;d in key message");return Kh(atob(u))}setupLicenseXHR(e,r,n,i){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,r,n,i)}).catch(a=>{if(!n.decryptdata)throw a;return e.open("POST",r,!0),s.call(this.hls,e,r,n,i)}).then(a=>(e.readyState||e.open("POST",r,!0),{xhr:e,licenseChallenge:a||i})):(e.open("POST",r,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,r){const n=this.config.keyLoadPolicy.default;return new Promise((i,s)=>{const a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const u=this.config.licenseResponseCallback;if(u)try{l=u.call(this.hls,o,a,e)}catch(c){this.error(c)}i(l)}else{const l=n.errorRetry,u=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>u||o.status>=400&&o.status<500)s(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const c=u-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} attempts left`),this.requestLicense(e,r).then(i,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,r).then(({xhr:l,licenseChallenge:u})=>{e.keySystem==ot.PLAYREADY&&(u=this.unpackPlayReadyKeyMessage(l,u)),l.send(u)})})}onMediaAttached(e,r){if(!this.config.emeEnabled)return;const n=r.media;this.media=n,n.addEventListener("encrypted",this.onMediaEncrypted),n.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,r=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},hl.clearKeyUriToKeyIdMap();const n=r.length;fa.CDMCleanupPromise=Promise.all(r.map(i=>this.removeSession(i)).concat(e==null?void 0:e.setMediaKeys(null).catch(i=>{this.log(`Could not clear media keys: ${i}`)}))).then(()=>{n&&(this.log("finished closing key sessions and clearing media keys"),r.length=0)}).catch(i=>{this.log(`Could not close sessions and clear media keys: ${i}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:r}){if(!(!r||!this.config.emeEnabled)&&!this.keyFormatPromise){const n=r.reduce((i,s)=>(i.indexOf(s.keyFormat)===-1&&i.push(s.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)}}removeSession(e){const{mediaKeysSession:r,licenseXhr:n}=e;if(r){this.log(`Remove licenses and keys and close session ${r.sessionId}`),e._onmessage&&(r.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);return i>-1&&this.mediaKeySessions.splice(i,1),r.remove().catch(s=>{this.log(`Could not remove session: ${s}`)}).then(()=>r.close()).catch(s=>{this.log(`Could not close session: ${s}`)})}}}fa.CDMCleanupPromise=void 0;class zr extends Error{constructor(e,r){super(r),this.data=void 0,e.error||(e.error=new Error(r)),this.data=e,e.err=e.error}}var Xt;(function(t){t.MANIFEST="m",t.AUDIO="a",t.VIDEO="v",t.MUXED="av",t.INIT="i",t.CAPTION="c",t.TIMED_TEXT="tt",t.KEY="k",t.OTHER="o"})(Xt||(Xt={}));var np;(function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"})(np||(np={}));var os;(function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"})(os||(os={}));const QM={[os.OBJECT]:["br","d","ot","tb"],[os.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[os.SESSION]:["cid","pr","sf","sid","st","v"],[os.STATUS]:["bs","rtp"]};class Da{constructor(e,r){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(n=>n instanceof Da?n:new Da(n))),this.value=e,this.params=r}}class ow{constructor(e){this.description=void 0,this.description=e}}const JM="Dict";function eN(t){return Array.isArray(t)?JSON.stringify(t):t instanceof Map?"Map{}":t instanceof Set?"Set{}":typeof t=="object"?JSON.stringify(t):String(t)}function tN(t,e,r,n){return new Error(`failed to ${t} "${eN(e)}" as ${r}`,{cause:n})}const iy="Bare Item",rN="Boolean",nN="Byte Sequence",iN="Decimal",sN="Integer";function aN(t){return t<-999999999999999||99999999999999912)throw Bn(t,iN);const r=e.toString();return r.includes(".")?r:`${r}.0`}const mN="String";function gN(t){if(oN.test(t))throw Bn(t,mN);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function vN(t){return t.description||t.toString().slice(7,-1)}function sy(t){const e=vN(t);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Bn(e,lN);return e}function ip(t){switch(typeof t){case"number":if(!pe(t))throw Bn(t,iy);return Number.isInteger(t)?lw(t):pN(t);case"string":return gN(t);case"symbol":return sy(t);case"boolean":return cN(t);case"object":if(t instanceof Date)return hN(t);if(t instanceof Uint8Array)return fN(t);if(t instanceof ow)return sy(t);default:throw Bn(t,iy)}}function sp(t){if(/^[a-z*][a-z0-9\-_.*]*$/.test(t)===!1)throw Bn(t,uN);return t}function Vm(t){return t==null?"":Object.entries(t).map(([e,r])=>r===!0?`;${sp(e)}`:`;${sp(e)}=${ip(r)}`).join("")}function cw(t){return t instanceof Da?`${ip(t.value)}${Vm(t.params)}`:ip(t)}function yN(t){return`(${t.value.map(cw).join(" ")})${Vm(t.params)}`}function xN(t,e={whitespace:!0}){if(typeof t!="object")throw Bn(t,JM);const r=t instanceof Map?t.entries():Object.entries(t),n=e!=null&&e.whitespace?" ":"";return Array.from(r).map(([i,s])=>{s instanceof Da||(s=new Da(s));let a=sp(i);return s.value===!0?a+=Vm(s.params):(a+="=",Array.isArray(s.value)?a+=yN(s):a+=cw(s)),a}).join(`,${n}`)}function SN(t,e){return xN(t,e)}const EN=t=>t==="ot"||t==="sf"||t==="st",TN=t=>typeof t=="number"?pe(t):t!=null&&t!==""&&t!==!1;function wN(t,e){const r=new URL(t),n=new URL(e);if(r.origin!==n.origin)return t;const i=r.pathname.split("/").slice(1),s=n.pathname.split("/").slice(1,-1);for(;i[0]===s[0];)i.shift(),s.shift();for(;s.length;)s.shift(),i.unshift("..");return i.join("/")}function bN(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),r=e.toString();return URL.revokeObjectURL(e),r.slice(r.lastIndexOf("/")+1)}catch{let r=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const s=(r+Math.random()*16)%16|0;return r=Math.floor(r/16),(i=="x"?s:s&3|8).toString(16)})}}}const Bu=t=>Math.round(t),LN=(t,e)=>(e!=null&&e.baseUrl&&(t=wN(t,e.baseUrl)),encodeURIComponent(t)),du=t=>Bu(t/100)*100,AN={br:Bu,d:Bu,bl:du,dl:du,mtp:du,nor:LN,rtp:du,tb:Bu};function _N(t,e){const r={};if(t==null||typeof t!="object")return r;const n=Object.keys(t).sort(),i=It({},AN,e==null?void 0:e.formatters),s=e==null?void 0:e.filter;return n.forEach(a=>{if(s!=null&&s(a))return;let o=t[a];const l=i[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||TN(o)&&(EN(a)&&typeof o=="string"&&(o=new ow(o)),r[a]=o))}),r}function dw(t,e={}){return t?SN(_N(t,e),It({whitespace:!1},e)):""}function CN(t,e={}){if(!t)return{};const r=Object.entries(t),n=Object.entries(QM).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),i=r.reduce((s,a)=>{var o,l;const[u,c]=a,d=((o=n.find(f=>f[1].includes(u)))==null?void 0:o[0])||os.REQUEST;return(l=s[d])!=null||(s[d]={}),s[d][u]=c,s},{});return Object.entries(i).reduce((s,[a,o])=>(s[a]=dw(o,e),s),{})}function RN(t,e,r){return It(t,CN(e,r))}const IN="CMCD";function kN(t,e={}){if(!t)return"";const r=dw(t,e);return`${IN}=${encodeURIComponent(r)}`}const ay=/CMCD=[^&#]+/;function DN(t,e,r){const n=kN(e,r);if(!n)return t;if(ay.test(t))return t.replace(ay,n);const i=t.includes("?")?"&":"?";return`${t}${i}${n}`}class PN{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=i=>{try{this.apply(i,{ot:Xt.MANIFEST,su:!this.initialized})}catch(s){U.warn("Could not generate manifest CMCD data.",s)}},this.applyFragmentData=i=>{try{const s=i.frag,a=this.hls.levels[s.level],o=this.getObjectType(s),l={d:s.duration*1e3,ot:o};(o===Xt.VIDEO||o===Xt.AUDIO||o==Xt.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(i,l)}catch(s){U.warn("Could not generate segment CMCD data.",s)}},this.hls=e;const r=this.config=e.config,{cmcd:n}=r;n!=null&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||bN(),this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.includeKeys=n.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHED,this.onMediaDetached,this),e.on(w.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHED,this.onMediaDetached,this),e.off(w.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,r){this.media=r.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,r){var n,i;this.audioBuffer=(n=r.tracks.audio)==null?void 0:n.buffer,this.videoBuffer=(i=r.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:np.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,r={}){It(r,this.createData());const n=r.ot===Xt.INIT||r.ot===Xt.VIDEO||r.ot===Xt.MUXED;this.starved&&n&&(r.bs=!0,r.su=!0,this.starved=!1),r.su==null&&(r.su=this.buffering);const{includeKeys:i}=this;i&&(r=Object.keys(r).reduce((s,a)=>(i.includes(a)&&(s[a]=r[a]),s),{})),this.useHeaders?(e.headers||(e.headers={}),RN(e.headers,r)):e.url=DN(e.url,r)}getObjectType(e){const{type:r}=e;if(r==="subtitle")return Xt.TIMED_TEXT;if(e.sn==="initSegment")return Xt.INIT;if(r==="audio")return Xt.AUDIO;if(r==="main")return this.hls.audioTracks.length?Xt.VIDEO:Xt.MUXED}getTopBandwidth(e){let r=0,n;const i=this.hls;if(e===Xt.AUDIO)n=i.audioTracks;else{const s=i.maxAutoLevel,a=s>-1?s+1:i.levels.length;n=i.levels.slice(0,a)}for(const s of n)s.bitrate>r&&(r=s.bitrate);return r>0?r:NaN}getBufferLength(e){const r=this.hls.media,n=e===Xt.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!r?NaN:at.bufferInfo(n,r.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,r=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new n(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,a,o){r(s),this.loader.load(s,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,r=this.applyFragmentData,n=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new n(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,a,o){r(s),this.loader.load(s,a,o)}}}}const ON=3e5;class MN{constructor(e){this.hls=void 0,this.log=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.log=U.log.bind(U,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.ERROR,this.onError,this))}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 r=this.levels;r&&(this.levels=r.filter(n=>n!==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,r){const{contentSteering:n}=r;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,r){this.audioTracks=r.audioTracks,this.subtitleTracks=r.subtitleTracks}onError(e,r){const{errorAction:n}=r;if((n==null?void 0:n.action)===zt.SendAlternateToPenaltyBox&&n.flags===sn.MoveAllAlternatesMatchingHost){const i=this.levels;let s=this.pathwayPriority,a=this.pathwayId;if(r.context){const{groupId:o,pathwayId:l,type:u}=r.context;o&&i?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!s&&i&&(s=i.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),s&&s.length>1&&(this.updatePathwayPriority(s),n.resolved=this.pathwayId!==a),n.resolved||U.warn(`Could not resolve ${r.details} ("${r.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${JSON.stringify(s)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let r=this.getLevelsForPathway(this.pathwayId);if(r.length===0){const n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),r=this.getLevelsForPathway(n),this.pathwayId=n}return r.length!==e.length?(this.log(`Found ${r.length}/${e.length} levels in Pathway "${this.pathwayId}"`),r):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(r=>e===r.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let r;const n=this.penalizedPathways,i=performance.now();Object.keys(n).forEach(s=>{i-n[s]>ON&&delete n[s]});for(let s=0;s0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,IT(r),this.hls.trigger(w.LEVELS_UPDATED,{levels:r});const u=this.hls.levels[o];l&&u&&this.levels&&(u.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&u.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${u.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,r,n){const i=this.getLevelsForPathway(n).concat(this.levels||[]);for(let s=0;s{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=s;if(r.some(c=>c.pathwayId===a))return;const u=this.getLevelsForPathway(o).map(c=>{const d=new gt(c.attrs);d["PATHWAY-ID"]=a;const f=d.AUDIO&&`${d.AUDIO}_clone_${a}`,m=d.SUBTITLES&&`${d.SUBTITLES}_clone_${a}`;f&&(n[d.AUDIO]=f,d.AUDIO=f),m&&(i[d.SUBTITLES]=m,d.SUBTITLES=m);const h=fw(c.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new Ia({attrs:d,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:h,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let v=1;v{this.log(`Loaded steering manifest: "${i}"`);const h=c.data;if(h.VERSION!==1){this.log(`Steering VERSION ${h.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=h.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":v,"PATHWAY-PRIORITY":g}=h;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||f.url),v&&this.clonePathways(v);const y={steeringManifest:h,url:i.toString()};this.hls.trigger(w.STEERING_MANIFEST_LOADED,y),g&&this.updatePathwayPriority(g)},onError:(c,d,f,m)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${d.url})`),this.stopLoad(),c.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let h=this.timeToLoad*1e3;if(c.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const v=p.getResponseHeader("Retry-After");v&&(h=parseFloat(v)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,h)},onTimeout:(c,d,f)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(s,l,u)}scheduleRefresh(e,r=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var n;const i=(n=this.hls)==null?void 0:n.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},r)}}function oy(t,e,r,n){t&&Object.keys(e).forEach(i=>{const s=t.filter(a=>a.groupId===i).map(a=>{const o=It({},a);return o.details=void 0,o.attrs=new gt(o.attrs),o.url=o.attrs.URI=fw(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=n,o});t.push(...s)})}function fw(t,e,r,n){const{HOST:i,PARAMS:s,[r]:a}=n;let o;e&&(o=a==null?void 0:a[e],o&&(t=o));const l=new self.URL(t);return i&&!o&&(l.host=i),s&&Object.keys(s).sort().forEach(u=>{u&&l.searchParams.set(u,s[u])}),l.href}const NN=/^age:\s*[\d.]+\s*$/im;class hw{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 Td,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,r,n){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=r,this.callbacks=n,this.loadInternal()}loadInternal(){const{config:e,context:r}=this;if(!e||!r)return;const n=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return s(n,r.url)}).catch(a=>{if(!(this.loader!==n||this.stats.aborted))return n.open("GET",r.url,!0),s(n,r.url)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,r,e)}).catch(a=>{this.callbacks.onError({code:n.status,text:a.message},r,n,i)}):this.openAndSendXhr(n,r,e)}openAndSendXhr(e,r,n){e.readyState||e.open("GET",r.url,!0);const i=r.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:a}=n.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);r.rangeEnd&&e.setRequestHeader("Range","bytes="+r.rangeStart+"-"+(r.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=r.responseType,self.clearTimeout(this.requestTimeout),n.timeout=s&&pe(s)?s:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){const{context:e,loader:r,stats:n}=this;if(!e||!r)return;const i=r.readyState,s=this.config;if(!n.aborted&&i>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.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-(n.loading.first-n.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),r.onreadystatechange=null,r.onprogress=null;const a=r.status,o=r.responseType!=="text";if(a>=200&&a<300&&(o&&r.response||r.responseText!==null)){n.loading.end=Math.max(self.performance.now(),n.loading.first);const l=o?r.response:r.responseText,u=r.responseType==="arraybuffer"?l.byteLength:l.length;if(n.loaded=n.total=u,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first),!this.callbacks)return;const c=this.callbacks.onProgress;if(c&&c(n,e,l,r),!this.callbacks)return;const d={url:r.responseURL,data:l,code:a};this.callbacks.onSuccess(d,n,e,r)}else{const l=s.loadPolicy.errorRetry,u=n.retry,c={url:e.url,data:void 0,code:a};jc(l,u,!1,c)?this.retry(l):(U.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:r.statusText},e,r,n))}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,r=this.stats.retry;if(jc(e,r,!0))this.retry(e);else{var n;U.warn(`timeout while loading ${(n=this.context)==null?void 0:n.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:r,stats:n}=this;this.retryDelay=Rm(e,n.retry),n.retry++,U.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${r==null?void 0:r.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const r=this.stats;r.loaded=e.loaded,e.lengthComputable&&(r.total=e.total)}getCacheAge(){let e=null;if(this.loader&&NN.test(this.loader.getAllResponseHeaders())){const r=this.loader.getResponseHeader("age");e=r?parseFloat(r):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}function FN(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const UN=/(\d+)-(\d+)\/(\d+)/;class ly{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||VN,this.controller=new self.AbortController,this.stats=new Td}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,r,n){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const s=BN(e,this.controller.signal),a=n.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:u,maxLoadTimeMs:c}=r.loadPolicy;this.context=e,this.config=r,this.callbacks=n,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),r.timeout=u&&pe(u)?u:c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),n.onTimeout(i,e,this.response)},r.timeout),self.fetch(this.request).then(d=>{this.response=this.loader=d;const f=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),r.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),n.onTimeout(i,e,this.response)},c-(f-i.loading.start)),!d.ok){const{status:m,statusText:h}=d;throw new GN(h||"fetch, bad network response",m,d)}return i.loading.first=f,i.total=jN(d.headers)||i.total,a&&pe(r.highWaterMark)?this.loadProgressively(d,i,e,r.highWaterMark,a):o?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const m=d[l];m&&(i.loaded=i.total=m);const h={url:f.url,data:d,code:f.status};a&&!pe(r.highWaterMark)&&a(i,e,d,f),n.onSuccess(h,i,e,f)}).catch(d=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const f=d&&d.code||0,m=d?d.message:null;n.onError({code:f,text:m},e,d?d.details:null,i)})}getCacheAge(){let e=null;if(this.response){const r=this.response.headers.get("age");e=r?parseFloat(r):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,r,n,i=0,s){const a=new OT,o=e.body.getReader(),l=()=>o.read().then(u=>{if(u.done)return a.dataLength&&s(r,n,a.flush(),e),Promise.resolve(new ArrayBuffer(0));const c=u.value,d=c.length;return r.loaded+=d,d=i&&s(r,n,a.flush(),e)):s(r,n,c,e),l()}).catch(()=>Promise.reject());return l()}}function BN(t,e){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(It({},t.headers))};return t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),r}function $N(t){const e=UN.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}function jN(t){const e=t.get("Content-Range");if(e){const n=$N(e);if(pe(n))return n}const r=t.get("Content-Length");if(r)return parseInt(r)}function VN(t,e){return new self.Request(t.url,e)}class GN extends Error{constructor(e,r,n){super(e),this.code=void 0,this.details=void 0,this.code=r,this.details=n}}const zN=/\s/,HN={newCue(t,e,r,n){const i=[];let s,a,o,l,u;const c=self.VTTCue||self.TextTrackCue;for(let f=0;f=16?l--:l++;const m=rw(u.trim()),h=$m(e,r,m);t!=null&&(d=t.cues)!=null&&d.getCueById(h)||(a=new c(e,r,m),a.id=h,a.line=f+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(a))}return t&&i.length&&(i.sort((f,m)=>f.line==="auto"||m.line==="auto"?0:f.line>8&&m.line>8?m.line-f.line:f.line-m.line),i.forEach(f=>AT(t,f))),i}},WN={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},pw=jt(jt({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,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,loader:hw,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:xO,bufferController:wM,capLevelController:jm,errorController:oO,fpsController:ZM,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:fT,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:WN},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}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},KN()),{},{subtitleStreamController:xM,subtitleTrackController:EM,timelineController:qM,audioStreamController:vM,audioTrackController:yM,emeController:fa,cmcdController:PN,contentSteeringController:MN});function KN(){return{cueHandler:HN,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 YN(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=ap(t),n=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(s=>{const a=`${s==="level"?"playlist":s}LoadPolicy`,o=e[a]===void 0,l=[];i.forEach(u=>{const c=`${s}Loading${u}`,d=e[c];if(d!==void 0&&o){l.push(c);const f=r[a].default;switch(e[a]={default:f},u){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&U.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),jt(jt({},r),e)}function ap(t){return t&&typeof t=="object"?Array.isArray(t)?t.map(ap):Object.keys(t).reduce((e,r)=>(e[r]=ap(t[r]),e),{}):t}function qN(t){const e=t.loader;e!==ly&&e!==hw?(U.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):FN()&&(t.loader=ly,t.progressive=!0,t.enableSoftwareAES=!0,U.log("[config]: Progressive streaming enabled, using FetchLoader"))}let Uf;class XN extends Im{constructor(e,r){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=r,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this),e.on(w.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this),e.off(w.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(r=>{r.loadError=0,r.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,r){this.resetLevels()}onManifestLoaded(e,r){const n=this.hls.config.preferManagedMediaSource,i=[],s={},a={};let o=!1,l=!1,u=!1;r.levels.forEach(c=>{var d,f;const m=c.attrs;let{audioCodec:h,videoCodec:p}=c;((d=h)==null?void 0:d.indexOf("mp4a.40.34"))!==-1&&(Uf||(Uf=/chrome|firefox/i.test(navigator.userAgent)),Uf&&(c.audioCodec=h=void 0)),h&&(c.audioCodec=h=Uc(h,n)),((f=p)==null?void 0:f.indexOf("avc1"))===0&&(p=c.videoCodec=NP(p));const{width:v,height:g,unknownCodecs:y}=c;if(o||(o=!!(v&&g)),l||(l=!!p),u||(u=!!h),y!=null&&y.length||h&&!wf(h,"audio",n)||p&&!wf(p,"video",n))return;const{CODECS:x,"FRAME-RATE":S,"HDCP-LEVEL":T,"PATHWAY-ID":C,RESOLUTION:_,"VIDEO-RANGE":b}=m,A=`${`${C||"."}-`}${c.bitrate}-${_}-${S}-${x}-${b}-${T}`;if(s[A])if(s[A].uri!==c.url&&!c.attrs["PATHWAY-ID"]){const k=a[A]+=1;c.attrs["PATHWAY-ID"]=new Array(k+1).join(".");const O=new Ia(c);s[A]=O,i.push(O)}else s[A].addGroupId("audio",m.AUDIO),s[A].addGroupId("text",m.SUBTITLES);else{const k=new Ia(c);s[A]=k,a[A]=1,i.push(k)}}),this.filterAndSortMediaOptions(i,r,o,l,u)}filterAndSortMediaOptions(e,r,n,i,s){let a=[],o=[],l=e;if((n||i)&&s&&(l=l.filter(({videoCodec:h,videoRange:p,width:v,height:g})=>(!!h||!!(v&&g))&&qP(p))),l.length===0){Promise.resolve().then(()=>{if(this.hls){r.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(r.levels[0].attrs)}`);const h=new Error("no level with compatible codecs found in manifest");this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:r.url,error:h,reason:h.message})}});return}if(r.audioTracks){const{preferManagedMediaSource:h}=this.hls.config;a=r.audioTracks.filter(p=>!p.audioCodec||wf(p.audioCodec,"audio",h)),uy(a)}r.subtitles&&(o=r.subtitles,uy(o));const u=l.slice(0);l.sort((h,p)=>{if(h.attrs["HDCP-LEVEL"]!==p.attrs["HDCP-LEVEL"])return(h.attrs["HDCP-LEVEL"]||"")>(p.attrs["HDCP-LEVEL"]||"")?1:-1;if(n&&h.height!==p.height)return h.height-p.height;if(h.frameRate!==p.frameRate)return h.frameRate-p.frameRate;if(h.videoRange!==p.videoRange)return Bc.indexOf(h.videoRange)-Bc.indexOf(p.videoRange);if(h.videoCodec!==p.videoCodec){const v=gv(h.videoCodec),g=gv(p.videoCodec);if(v!==g)return g-v}if(h.uri===p.uri&&h.codecSet!==p.codecSet){const v=Fc(h.codecSet),g=Fc(p.codecSet);if(v!==g)return g-v}return h.averageBitrate!==p.averageBitrate?h.averageBitrate-p.averageBitrate:0});let c=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==u.length)){for(let h=0;hv&&v===pw.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=g)}break}const f=s&&!i,m={levels:l,audioTracks:a,subtitleTracks:o,sessionData:r.sessionData,sessionKeys:r.sessionKeys,firstLevel:this._firstLevel,stats:r.stats,audio:s,video:i,altAudio:!f&&a.some(h=>!!h.url)};this.hls.trigger(w.MANIFEST_PARSED,m),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const r=this._levels;if(r.length===0)return;if(e<0||e>=r.length){const c=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(w.ERROR,{type:_e.OTHER_ERROR,details:z.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:c,reason:c.message}),d)return;e=Math.min(e,r.length-1)}const n=this.currentLevelIndex,i=this.currentLevel,s=i?i.attrs["PATHWAY-ID"]:void 0,a=r[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,n===e&&a.details&&i&&s===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${n}${s?" with Pathway "+s:""}`);const l={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(w.LEVEL_SWITCHING,l);const u=a.details;if(!u||u.live){const c=this.switchParams(a.uri,i==null?void 0:i.details,u);this.loadPlaylist(c)}}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}onError(e,r){r.fatal||!r.context||r.context.type===He.LEVEL&&r.context.level===this.level&&this.checkRetry(r)}onFragBuffered(e,{frag:r}){if(r!==void 0&&r.type===we.MAIN){const n=r.elementaryStreams;if(!Object.keys(n).some(s=>!!n[s]))return;const i=this._levels[r.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,r){var n;const{level:i,details:s}=r,a=this._levels[i];if(!a){var o;this.warn(`Invalid level index ${i}`),(o=r.deliveryDirectives)!=null&&o.skip&&(s.deltaUpdateFailed=!0);return}i===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(i,r,a.details)):(n=r.deliveryDirectives)!=null&&n.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const r=this.currentLevelIndex,n=this.currentLevel;if(n&&this.shouldLoadPlaylist(n)){let i=n.uri;if(e)try{i=e.addDirectives(i)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const s=n.attrs["PATHWAY-ID"];this.log(`Loading level index ${r}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${s?" Pathway "+s:""} ${i}`),this.clearTimer(),this.hls.trigger(w.LEVEL_LOADING,{url:i,level:r,pathwayId:n.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||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 r;const n=this._levels.filter((i,s)=>s!==e?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(a=>a.level=-1)),!1));IT(n),this._levels=n,this.currentLevelIndex>-1&&(r=this.currentLevel)!=null&&r.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(w.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:r}){this._levels=r}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:r,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(w.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}}function uy(t){const e={};t.forEach(r=>{const n=r.groupId||"";r.id=e[n]=e[n]||0,e[n]++})}class ZN{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const n in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[n].loader;if(i){var r;if(e&&e!==((r=i.context)==null?void 0:r.frag.type))return;i.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[e];(r.mediaKeySessionContext||r.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[e].loader;r&&r.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,r=z.KEY_LOAD_ERROR,n,i,s){return new Zn({type:_e.NETWORK_ERROR,details:r,fatal:!1,frag:e,response:s,error:n,networkDetails:i})}loadClear(e,r){if(this.emeController&&this.config.emeEnabled){const{sn:n,cc:i}=e;for(let s=0;s{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(r=>this.loadInternal(e,r)):this.loadInternal(e)}loadInternal(e,r){var n,i;r&&e.setKeyFormat(r);const s=e.decryptdata;if(!s){const u=new Error(r?`Expected frag.decryptdata to be defined after setting format ${r}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,u))}const a=s.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((n=o)!=null&&n.decryptdata.key)return s.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((i=o)!=null&&i.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(u=>(s.key=u.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return s.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,r){const n={frag:r,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const i=this.emeController.loadKey(n);if(i)return(e.keyLoadPromise=i.then(s=>(e.mediaKeySessionContext=s,n))).catch(s=>{throw e.keyLoadPromise=null,s})}return Promise.resolve(n)}loadKeyHTTP(e,r){const n=this.config,i=n.loader,s=new i(n);return r.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:r,responseType:"arraybuffer",url:e.decryptdata.uri},u=n.keyLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(f,m,h,p)=>{const{frag:v,keyInfo:g,url:y}=h;if(!v.decryptdata||g!==this.keyUriToKeyInfo[y])return o(this.createKeyLoadError(v,z.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));g.decryptdata.key=v.decryptdata.key=new Uint8Array(f.data),v.keyLoader=null,g.loader=null,a({frag:v,keyInfo:g})},onError:(f,m,h,p)=>{this.resetLoader(m),o(this.createKeyLoadError(r,z.KEY_LOAD_ERROR,new Error(`HTTP Error ${f.code} loading key ${f.text}`),h,jt({url:l.url,data:void 0},f)))},onTimeout:(f,m,h)=>{this.resetLoader(m),o(this.createKeyLoadError(r,z.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),h))},onAbort:(f,m,h)=>{this.resetLoader(m),o(this.createKeyLoadError(r,z.INTERNAL_ABORTED,new Error("key loading aborted"),h))}};s.load(l,c,d)})}resetLoader(e){const{frag:r,keyInfo:n,url:i}=e,s=n.loader;r.keyLoader===s&&(r.keyLoader=null,n.loader=null),delete this.keyUriToKeyInfo[i],s&&s.destroy()}}function mw(){return self.SourceBuffer||self.WebKitSourceBuffer}function gw(){if(!bs())return!1;const e=mw();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function QN(){if(!gw())return!1;const t=bs();return typeof(t==null?void 0:t.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(pl(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(pl(e,"audio"))))}function JN(){var t;const e=mw();return typeof(e==null||(t=e.prototype)==null?void 0:t.changeType)=="function"}const eF=250,$u=2,tF=.1,rF=.05;class nF{constructor(e,r,n,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=r,this.fragmentTracker=n,this.hls=i}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,r){const{config:n,media:i,stalled:s}=this;if(i===null)return;const{currentTime:a,seeking:o}=i,l=this.seeking&&!o,u=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),s!==null){if(this.stallReported){const v=self.performance.now()-s;U.warn(`playback not stuck anymore @${a}, after ${Math.round(v)}ms`),this.stallReported=!1}this.stalled=null}return}if(u||l){this.stalled=null;return}if(i.paused&&!o||i.ended||i.playbackRate===0||!at.getBuffered(i).length){this.nudgeRetry=0;return}const c=at.bufferInfo(i,a,0),d=c.nextStart||0;if(o){const v=c.len>$u,g=!d||r&&r.start<=a||d-a>$u&&!this.fragmentTracker.getPartialFragment(a);if(v||g)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var f;if(!(c.len>0)&&!d)return;const g=Math.max(d,c.start||0)-a,y=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,S=(y==null||(f=y.details)==null?void 0:f.live)?y.details.targetduration*2:$u,T=this.fragmentTracker.getPartialFragment(a);if(g>0&&(g<=S||T)){i.paused||this._trySkipBufferHole(T);return}}const m=self.performance.now();if(s===null){this.stalled=m;return}const h=m-s;if(!o&&h>=eF&&(this._reportStall(c),!this.media))return;const p=at.bufferInfo(i,a,n.maxBufferHole);this._tryFixBufferStall(p,h)}_tryFixBufferStall(e,r){const{config:n,fragmentTracker:i,media:s}=this;if(s===null)return;const a=s.currentTime,o=i.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>n.maxBufferHole||e.nextStart&&e.nextStart-an.highBufferWatchdogPeriod*1e3&&(U.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:r,media:n,stallReported:i}=this;if(!i&&n){this.stallReported=!0;const s=new Error(`Playback stalling at @${n.currentTime} due to low buffer (${JSON.stringify(e)})`);U.warn(s.message),r.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:e.len})}}_trySkipBufferHole(e){const{config:r,hls:n,media:i}=this;if(i===null)return 0;const s=i.currentTime,a=at.bufferInfo(i,s,0),o=s0&&a.len<1&&i.readyState<3,c=o-s;if(c>0&&(l||u)){if(c>r.maxBufferHole){const{fragmentTracker:f}=this;let m=!1;if(s===0){const h=f.getAppendedFrag(0,we.MAIN);h&&o1?(i=0,this.bitrateTest=!0):i=n.firstAutoLevel),n.nextLoadLevel=i,this.level=n.loadLevel,this.loadedmetadata=!1}r>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=Y.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=Y.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Y.WAITING_LEVEL:{const{levels:r,level:n}=this,i=r==null?void 0:r[n],s=i==null?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(s))break;this.state=Y.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Y.IDLE;break}break}case Y.FRAG_LOADING_WAITING_RETRY:{var e;const r=self.performance.now(),n=this.retryDate;if(!n||r>=n||(e=this.media)!=null&&e.seeking){const{levels:i,level:s}=this,a=i==null?void 0:i[s];this.resetStartWhenNotLoaded(a||null),this.state=Y.IDLE}}break}this.state===Y.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:r,levels:n,media:i}=this;if(r===null||!i&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const s=e.nextLoadLevel;if(!(n!=null&&n[s]))return;const a=n[s],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const p={};this.altAudio&&(p.type="video"),this.hls.trigger(w.BUFFER_EOS,p),this.state=Y.ENDED;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===Y.WAITING_LEVEL||u.live&&this.levelLastLoaded!==a){this.level=s,this.state=Y.WAITING_LEVEL;return}const c=o.len,d=this.getMaxBufferLength(a.maxBitrate);if(c>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:o.end;let m=this.getNextFragment(f,u);if(this.couldBacktrack&&!this.fragPrevious&&m&&m.sn!=="initSegment"&&this.fragmentTracker.getState(m)!==Bt.OK){var h;const v=((h=this.backtrackFragment)!=null?h:m).sn-u.startSN,g=u.fragments[v-1];g&&m.cc===g.cc&&(m=g,this.fragmentTracker.removeFragment(g))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(m&&this.isLoopLoading(m,f)){if(!m.gap){const v=this.audioOnly&&!this.altAudio?Je.AUDIO:Je.VIDEO,g=(v===Je.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;g&&this.afterBufferFlushed(g,v,we.MAIN)}m=this.getNextFragmentLoopLoading(m,u,o,we.MAIN,d)}m&&(m.initSegment&&!m.initSegment.data&&!this.bitrateTest&&(m=m.initSegment),this.loadFragment(m,a,f))}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);this.fragCurrent=e,i===Bt.NOT_LOADED||i===Bt.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,r):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,r)):(this.startFragRequested=!0,super.loadFragment(e,r,n)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,we.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:r}=this;if(r!=null&&r.readyState){let n;const i=this.getAppendedFrag(r.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const s=this.getLevelDetails();if(s!=null&&s.live){const o=this.getMainFwdBufferInfo();if(!o||o.len{const a=s.audioCodec;a&&(n=n||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=n&&i&&!JN(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=r.levels,this.startFragRequested=!1}onLevelLoading(e,r){const{levels:n}=this;if(!n||this.state!==Y.IDLE)return;const i=n[r.level];(!i.details||i.details.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(i.details))&&(this.state=Y.WAITING_LEVEL)}onLevelLoaded(e,r){var n;const{levels:i}=this,s=r.level,a=r.details,o=a.totalduration;if(!i){this.warn(`Levels were reset while loading level ${s}`);return}this.log(`Level ${s} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=i[s],u=this.fragCurrent;u&&(this.state===Y.FRAG_LOADING||this.state===Y.FRAG_LOADING_WAITING_RETRY)&&u.level!==r.level&&u.loader&&this.abortCurrentFrag();let c=0;if(a.live||(n=l.details)!=null&&n.live){var d;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(w.LEVEL_UPDATED,{details:a,level:s}),this.state===Y.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=Y.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,c),this.tick()}_handleFragmentLoadProgress(e){var r;const{frag:n,part:i,payload:s}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const o=a[n.level],l=o.details;if(!l){this.warn(`Dropping fragment ${n.sn} of level ${n.level} after level details were reset`),this.fragmentTracker.removeFragment(n);return}const u=o.videoCodec,c=l.PTSKnown||!l.live,d=(r=n.initSegment)==null?void 0:r.data,f=this._getAudioCodec(o),m=this.transmuxer=this.transmuxer||new XT(this.hls,we.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),h=i?i.index:-1,p=h!==-1,v=new km(n.level,n.sn,n.stats.chunkCount,s.byteLength,h,p),g=this.initPTS[n.cc];m.push(s,d,f,u,n,i,l.totalduration,c,v,g)}onAudioTrackSwitching(e,r){const n=this.altAudio;if(!!!r.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const s=this.hls;n&&(s.trigger(w.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),s.trigger(w.AUDIO_TRACK_SWITCHED,r)}}onAudioTrackSwitched(e,r){const n=r.id,i=!!this.hls.audioTracks[n].url;if(i){const s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i,this.tick()}onBufferCreated(e,r){const n=r.tracks;let i,s,a=!1;for(const o in n){const l=n[o];if(l.id==="main"){if(s=o,i=l,o==="video"){const u=n[o];u&&(this.videoBuffer=u.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,r){const{frag:n,part:i}=r;if(n&&n.type!==we.MAIN)return;if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${i?" p: "+i.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Y.PARSED&&(this.state=Y.IDLE);return}const s=i?i.stats:n.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),n.sn!=="initSegment"&&(this.fragPrevious=n),this.fragBufferedComplete(n,i)}onError(e,r){var n;if(r.fatal){this.state=Y.ERROR;return}switch(r.details){case z.FRAG_GAP:case z.FRAG_PARSING_ERROR:case z.FRAG_DECRYPT_ERROR:case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(we.MAIN,r);break;case z.LEVEL_LOAD_ERROR:case z.LEVEL_LOAD_TIMEOUT:case z.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===Y.WAITING_LEVEL&&((n=r.context)==null?void 0:n.type)===He.LEVEL&&(this.state=Y.IDLE);break;case z.BUFFER_APPEND_ERROR:case z.BUFFER_FULL_ERROR:if(!r.parent||r.parent!=="main")return;if(r.details===z.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(r)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case z.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}checkBuffer(){const{media:e,gapController:r}=this;if(!(!e||!r||!e.readyState)){if(this.loadedmetadata||!at.getBuffered(e).length){const n=this.state!==Y.IDLE?this.fragCurrent:null;r.poll(this.lastCurrentTime,n)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=Y.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:r}){if(r!==Je.AUDIO||this.audioOnly&&!this.altAudio){const n=(r===Je.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(n,r,we.MAIN),this.tick()}}onLevelsUpdated(e,r){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=r.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const r=e.currentTime;let n=this.startPosition;if(n>=0&&r0&&(a{const{hls:i}=this;if(!n||this.fragContextChanged(e))return;r.fragmentError=0,this.state=Y.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const s=e.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),i.trigger(w.FRAG_LOADED,n),e.bitrateTest=!1})}_handleTransmuxComplete(e){var r;const n="main",{hls:i}=this,{remuxResult:s,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:u,level:c}=o,{video:d,text:f,id3:m,initSegment:h}=s,{details:p}=c,v=this.altAudio?void 0:s.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=Y.PARSING,h){if(h!=null&&h.tracks){const x=l.initSegment||l;this._bufferInitSegment(c,h.tracks,x,a),i.trigger(w.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:n,tracks:h.tracks})}const g=h.initPTS,y=h.timescale;pe(g)&&(this.initPTS[l.cc]={baseTime:g,timescale:y},i.trigger(w.INIT_PTS_FOUND,{frag:l,id:n,initPTS:g,timescale:y}))}if(d&&p&&l.sn!=="initSegment"){const g=p.fragments[l.sn-1-p.startSN],y=l.sn===p.startSN,x=!g||l.cc>g.cc;if(s.independent!==!1){const{startPTS:S,endPTS:T,startDTS:C,endDTS:_}=d;if(u)u.elementaryStreams[d.type]={startPTS:S,endPTS:T,startDTS:C,endDTS:_};else if(d.firstKeyFrame&&d.independent&&a.id===1&&!x&&(this.couldBacktrack=!0),d.dropped&&d.independent){const b=this.getMainFwdBufferInfo(),I=(b?b.end:this.getLoadPosition())+this.config.maxBufferHole,A=d.firstKeyFramePTS?d.firstKeyFramePTS:S;if(!y&&I$u&&(l.gap=!0);l.setElementaryStreamInfo(d.type,S,T,C,_),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(d,l,u,a,y||x)}else if(y||x)l.gap=!0;else{this.backtrack(l);return}}if(v){const{startPTS:g,endPTS:y,startDTS:x,endDTS:S}=v;u&&(u.elementaryStreams[Je.AUDIO]={startPTS:g,endPTS:y,startDTS:x,endDTS:S}),l.setElementaryStreamInfo(Je.AUDIO,g,y,x,S),this.bufferFragmentData(v,l,u,a)}if(p&&m!=null&&(r=m.samples)!=null&&r.length){const g={id:n,frag:l,details:p,samples:m.samples};i.trigger(w.FRAG_PARSING_METADATA,g)}if(p&&f){const g={id:n,frag:l,details:p,samples:f.samples};i.trigger(w.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(e,r,n,i){if(this.state!==Y.PARSING)return;this.audioOnly=!!r.audio&&!r.video,this.altAudio&&!this.audioOnly&&delete r.audio;const{audio:s,video:a,audiovideo:o}=r;if(s){let l=e.audioCodec;const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");const c=s.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(l="mp4a.40.5")}l&&l.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&s.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),s.levelCodec=l,s.id="main",this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${s.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(w.BUFFER_CODECS,r),Object.keys(r).forEach(l=>{const c=r[l].initSegment;c!=null&&c.byteLength&&this.hls.trigger(w.BUFFER_APPENDING,{type:l,data:c,frag:n,part:null,chunkMeta:i,parent:n.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,we.MAIN)}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=Y.IDLE}checkFragmentChanged(){const e=this.media;let r=null;if(e&&e.readyState>1&&e.seeking===!1){const n=e.currentTime;if(at.isBuffered(e,n)?r=this.getAppendedFrag(n):at.isBuffered(e,n+.1)&&(r=this.getAppendedFrag(n+.1)),r){this.backtrackFragment=null;const i=this.fragPlaying,s=r.level;(!i||r.sn!==i.sn||i.level!==s)&&(this.fragPlaying=r,this.hls.trigger(w.FRAG_CHANGED,{frag:r}),(!i||i.level!==s)&&this.hls.trigger(w.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const r=e.currentTime,n=this.currentFrag;if(n&&pe(r)&&pe(n.programDateTime)){const i=n.programDateTime+(r-n.start)*1e3;return new Date(i)}}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}}class kr{static get version(){return"1.5.15"}static isMSESupported(){return gw()}static isSupported(){return QN()}static getMediaSource(){return bs()}static get Events(){return w}static get ErrorTypes(){return _e}static get ErrorDetails(){return z}static get DefaultConfig(){return kr.defaultConfig?kr.defaultConfig:pw}static set DefaultConfig(e){kr.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Um,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.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,KD(e.debug||!1,"Hls instance");const r=this.config=YN(kr.DefaultConfig,e);this.userConfig=e,r.progressive&&qN(r);const{abrController:n,bufferController:i,capLevelController:s,errorController:a,fpsController:o}=r,l=new a(this),u=this.abrController=new n(this),c=this.bufferController=new i(this),d=this.capLevelController=new s(this),f=new o(this),m=new jP(this),h=new WP(this),p=r.contentSteeringController,v=p?new p(this):null,g=this.levelController=new XN(this,v),y=new EO(this),x=new ZN(this.config),S=this.streamController=new sF(this,y,x);d.setStreamController(S),f.setStreamController(S);const T=[m,g,S];v&&T.splice(1,0,v),this.networkControllers=T;const C=[u,c,d,f,h,y];this.audioTrackController=this.createController(r.audioTrackController,T);const _=r.audioStreamController;_&&T.push(new _(this,y,x)),this.subtitleTrackController=this.createController(r.subtitleTrackController,T);const b=r.subtitleStreamController;b&&T.push(new b(this,y,x)),this.createController(r.timelineController,C),x.emeController=this.emeController=this.createController(r.emeController,C),this.cmcdController=this.createController(r.cmcdController,C),this.latencyController=this.createController(KP,C),this.coreComponents=C,T.push(l);const I=l.onErrorOut;typeof I=="function"&&this.on(w.ERROR,I,l)}createController(e,r){if(e){const n=new e(this);return r&&r.push(n),n}return null}on(e,r,n=this){this._emitter.on(e,r,n)}once(e,r,n=this){this._emitter.once(e,r,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,r,n=this,i){this._emitter.off(e,r,n,i)}listeners(e){return this._emitter.listeners(e)}emit(e,r,n){return this._emitter.emit(e,r,n)}trigger(e,r){if(this.config.debug)return this.emit(e,e,r);try{return this.emit(e,e,r)}catch(n){if(U.error("An internal error happened while handling event "+e+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;const i=e===w.ERROR;this.trigger(w.ERROR,{type:_e.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,fatal:i,event:e,error:n}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){U.log("destroy"),this.trigger(w.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 e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){U.log("attachMedia"),this._media=e,this.trigger(w.MEDIA_ATTACHING,{media:e})}detachMedia(){U.log("detachMedia"),this.trigger(w.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const r=this.media,n=this.url,i=this.url=Lm.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,U.log(`loadSource:${i}`),r&&n&&(n!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(w.MANIFEST_LOADING,{url:e})}startLoad(e=-1){U.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(r=>{r.startLoad(e)})}stopLoad(){U.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){U.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){U.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){U.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){U.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){U.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){U.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){U.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const r=!!e;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:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(U.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){YP(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:r}}=this;if(!e)return 0;const n=e.length;for(let i=0;i=r)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:r,maxHdcpLevel:n}=this;let i;if(r===-1&&e!=null&&e.length?i=e.length-1:i=r,n)for(let s=i;s--;){const a=e[s].attrs["HDCP-LEVEL"];if(a&&a<=n)return s}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var r;return(r=this.audioTrackController)==null?void 0:r.setAudioOption(e)}setSubtitleOption(e){var r;return(r=this.subtitleTrackController)==null||r.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const r=this.audioTrackController;r&&(r.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const r=this.subtitleTrackController;r&&(r.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const r=this.subtitleTrackController;r&&(r.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}kr.defaultConfig=void 0;function aF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M208 432h-48a16 16 0 0 1-16-16V96a16 16 0 0 1 16-16h48a16 16 0 0 1 16 16v320a16 16 0 0 1-16 16zm144 0h-48a16 16 0 0 1-16-16V96a16 16 0 0 1 16-16h48a16 16 0 0 1 16 16v320a16 16 0 0 1-16 16z"},child:[]}]})(t)}function oF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M133 440a35.37 35.37 0 0 1-17.5-4.67c-12-6.8-19.46-20-19.46-34.33V111c0-14.37 7.46-27.53 19.46-34.33a35.13 35.13 0 0 1 35.77.45l247.85 148.36a36 36 0 0 1 0 61l-247.89 148.4A35.5 35.5 0 0 1 133 440z"},child:[]}]})(t)}function lF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-8 12H9.5v-2h-2v2H6V9h1.5v2.5h2V9H11v6zm2-6h4c.55 0 1 .45 1 1v4c0 .55-.45 1-1 1h-4V9zm1.5 4.5h2v-3h-2v3z"},child:[]}]})(t)}function uF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM4 12h4v2H4v-2zm10 6H4v-2h10v2zm6 0h-4v-2h4v2zm0-4H10v-2h10v2z"},child:[]}]})(t)}function cF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M18.5 12A4.5 4.5 0 0 0 16 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 9v6h4l5 5V4L9 9H5z"},child:[]}]})(t)}function dF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M7 9v6h4l5 5V4l-5 5H7z"},child:[]}]})(t)}function fF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M16.5 12A4.5 4.5 0 0 0 14 7.97v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51A8.796 8.796 0 0 0 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3 3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06a8.99 8.99 0 0 0 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4 9.91 6.09 12 8.18V4z"},child:[]}]})(t)}function hF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M3 9v6h4l5 5V4L7 9H3zm13.5 3A4.5 4.5 0 0 0 14 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"},child:[]}]})(t)}function pF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z",opacity:".1"},child:[]},{tag:"path",attr:{d:"M21 3H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm0-4v2a9 9 0 0 1 9 9h2c0-6.08-4.93-11-11-11z"},child:[]}]})(t)}function mF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M12 3a9 9 0 0 0-9 9v7c0 1.1.9 2 2 2h4v-8H5v-1c0-3.87 3.13-7 7-7s7 3.13 7 7v1h-4v8h4c1.1 0 2-.9 2-2v-7a9 9 0 0 0-9-9z"},child:[]}]})(t)}function gF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z"},child:[]}]})(t)}function vw(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"},child:[]}]})(t)}function vF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"},child:[]}]})(t)}function yF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"},child:[]}]})(t)}function xF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"},child:[]}]})(t)}function SF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"},child:[]}]})(t)}const Bf=({icon:t,values:e,selectedValue:r,canDeselect:n,setSelectedValue:i})=>{const[s,a]=L.useState(!1),o=L.useRef(null),l=()=>{a(!s)},u=c=>{n&&(r==null?void 0:r.id)===c.id?i(null):i(c),a(!1)};return L.useEffect(()=>{const c=d=>{o.current&&!o.current.contains(d.target)&&a(!1)};return document.addEventListener("click",c),()=>{document.removeEventListener("click",c)}},[]),E.jsxs("div",{className:"relative hover:bg-neutral-700 p-1 rounded",ref:o,children:[E.jsx("button",{className:"py-1 rounded flex items-center gap-2",onClick:l,children:t!==void 0&&t}),s&&E.jsx("ul",{className:"absolute bottom-[120%] min-w-fit w-full right-0 bg-neutral-800 border border-neutral-700 rounded mt-2",children:e.map(c=>E.jsxs("li",{className:"px-4 py-2 cursor-pointer hover:bg-neutral-700 w-full flex gap-2 items-center justify-start overflow-visible text-nowrap",onClick:()=>u(c),children:[c.id!==(r==null?void 0:r.id)&&t,c.id===(r==null?void 0:r.id)&&E.jsx(vw,{}),c.name||`${c.height}p`]},c.id))})]})},EF=({icon:t,seasons:e=[],currentEpisodeId:r,onSelect:n})=>{const[i,s]=L.useState(!1),[a,o]=L.useState(null),[l,u]=L.useState(null),c=L.useRef(null),d=p=>{p.stopPropagation(),s(!i)},f=(p,v)=>{p.stopPropagation(),o(v)},m=(p,v)=>{p.stopPropagation(),u(v),n(v),s(!1)},h=p=>{p.stopPropagation(),o(null)};return L.useEffect(()=>{const p=v=>{c.current&&!c.current.contains(v.target)&&s(!1)};return document.addEventListener("click",p),()=>{document.removeEventListener("click",p)}},[]),E.jsxs("section",{className:"relative","aria-label":"Episode selector",ref:c,children:[E.jsxs("button",{className:"p-2 rounded flex items-center gap-2 hover:bg-neutral-700",onClick:d,"aria-haspopup":"true","aria-expanded":i,children:[t,!t&&E.jsx("span",{className:"sr-only",children:"Select episode:"})]}),i&&E.jsx("section",{className:"absolute bottom-full right-0 mb-2 bg-neutral-800 border border-neutral-700 rounded shadow-lg max-h-[300px] overflow-y-auto w-auto",role:"menu",onClick:p=>p.stopPropagation(),children:a?E.jsxs("ul",{className:"py-2",role:"list",children:[E.jsxs("li",{className:"px-4 py-2 cursor-pointer hover:bg-neutral-700 flex items-center",onClick:h,role:"menuitem",children:[E.jsx(vF,{className:"h-4 w-4 mr-2","aria-hidden":"true"}),"Back to Seasons"]}),a.episodes.map(p=>E.jsxs("li",{className:"px-4 py-2 cursor-pointer hover:bg-neutral-700 flex gap-4 items-center min-w-max",onClick:v=>m(v,p),role:"menuitem",children:[(l==null?void 0:l.id)===p.id||r===p.id?E.jsx(vw,{className:"h-4 w-4","aria-hidden":"true"}):E.jsx("section",{className:"h-4 w-4"}),E.jsx("img",{src:p.images.banner,alt:p.title,className:"w-16 h-9 rounded-md"}),E.jsxs("span",{className:"text-nowrap",children:["Episode ",p.number,": ",p.title]})]},p.id))]}):E.jsx("ul",{className:"py-2",role:"list",children:e.length>0?e.map(p=>E.jsxs("li",{className:"px-4 py-2 cursor-pointer hover:bg-neutral-700 flex justify-between items-center",onClick:v=>f(v,p),role:"menuitem",children:[E.jsxs("span",{className:"text-nowrap",children:["Season ",p.season_number]}),E.jsx(yF,{className:"h-4 w-4","aria-hidden":"true"})]},p.season_id)):E.jsx("li",{className:"px-4 py-2 text-neutral-400",role:"menuitem",children:"No seasons available"})})})]})},TF=()=>{var tn,jn,rn,xn,nt,Gr;const t=L.useRef(null),e=L.useRef(null),r=L.useRef(null),[n,i]=L.useState(0),[s,a]=L.useState(null),[o,l]=L.useState([]),[u,c]=L.useState([]),[d,f]=L.useState([]),[m,h]=L.useState(null),[p,v]=L.useState(null),[g,y]=L.useState(null),[x,S]=L.useState(!0),[T,C]=L.useState(!1),[_,b]=L.useState(!1),[I,A]=L.useState(1),[k,O]=L.useState(I),{id:P,type:G}=VS(),K=Br(),{data:H}=ur(`/api/medias/media/${G}/${P}`);let se;const W=L.useCallback(Ae=>{K(`/watch/${G}/${Ae.id}`)},[K,G]),F=Ae=>{if(!Ae)return"0:00";const qe=Math.floor(Ae/3600),R=Math.floor((Ae-qe*3600)/60),N=Math.floor(Ae-qe*3600-R*60),$=String(N).padStart(2,"0"),re=String(R).padStart(2,"0"),Z=String(qe).padStart(2,"0");return qe>0?`${Z}:${re}:${$}`:R>0?`${re}:${$}`:`00:${$}`},{updateProfileData:j,updateAccessToken:te}=Ua();L.useEffect(()=>{var qe;i(0),S(!0),l([]),c([]),f([]),h(null),v(null),y(null),s&&(s.destroy(),a(null)),t.current&&(t.current.src="",t.current.load());let Ae=`/api/watch/${G}/${P}`;if((qe=H==null?void 0:H.data)!=null&&qe._source&&(Ae=H.data._source),t.current)if(kr.isSupported()){const R=new kr({xhrSetup:(N,$)=>{var re;N.open("GET",$,!0),$.includes("")&&(N.setRequestHeader("Authorization",`Bearer ${localStorage.getItem("access_token")}`),N.setRequestHeader("X-Current-Time",String(((re=t.current)==null?void 0:re.currentTime)||0))),N.onreadystatechange=async()=>{var Z;if(N.readyState===4&&N.status===200)try{if(JSON.parse(N.responseText).code===246){const oe=await(await fetch("/api/auth/refresh",{method:"POST",body:JSON.stringify({refresh_token:localStorage.getItem("refresh_token")}),headers:{"Content-Type":"application/json"}})).json();if(oe.error){K("/login");return}else{let xe=oe.data.access_token;localStorage.setItem("access_token",xe),te(oe.data.access_token),j(oe.data.user),N.open("GET",$,!0),$.includes("")&&(N.setRequestHeader("Authorization",`Bearer ${xe}`),N.setRequestHeader("X-Current-Time",String(((Z=t.current)==null?void 0:Z.currentTime)||0))),N.send()}}}catch(X){console.error(`Error parsing response: ${X}`)}}}});R.loadSource(Ae),R.attachMedia(t.current),R.on(kr.Events.MANIFEST_PARSED,()=>{var N;(N=t.current)==null||N.play()}),R.on(kr.Events.AUDIO_TRACKS_UPDATED,()=>{l(R.audioTracks);let N=R.audioTracks.find($=>$.default);N||(N=R.audioTracks[0]),h(N)}),R.on(kr.Events.SUBTITLE_TRACKS_UPDATED,()=>{c(R.subtitleTracks)}),R.on(kr.Events.BUFFER_CREATED,()=>{S(!0)}),R.on(kr.Events.FRAG_BUFFERED,()=>{S(!1)}),t.current.addEventListener("timeupdate",()=>{var $;i((($=t.current)==null?void 0:$.currentTime)||0);let N=R.levels;N.find(re=>re.height===-1)===void 0&&N.push({height:-1,name:"auto"}),f(N)}),a(R)}else t.current.canPlayType("application/vnd.apple.mpegurl")&&(t.current.src=Ae);return()=>{s&&s.destroy()}},[P,G,(tn=H==null?void 0:H.data)==null?void 0:tn._source]),L.useEffect(()=>{if(!t.current)return;const Ae=()=>{var R;(R=H==null?void 0:H.data)!=null&&R.last_duration&&t.current&&(t.current.currentTime=H.data.last_duration,t.current.play())},qe=()=>{t.current&&t.current.play()};return t.current.addEventListener("loadedmetadata",Ae),t.current.addEventListener("loadeddata",qe),()=>{t.current&&(t.current.removeEventListener("loadedmetadata",Ae),t.current.removeEventListener("loadeddata",qe))}},[(jn=H==null?void 0:H.data)==null?void 0:jn.last_duration]),L.useEffect(()=>{const Ae=localStorage.getItem("video-volume");if(Ae&&t.current){const qe=Number(Ae);A(qe),t.current.volume=qe}},[]);const ee=Ae=>{t.current&&(t.current.currentTime=Number(Ae.target.value),i(Number(Ae.target.value)))},fe=Ae=>{const qe=Number(Ae.target.value);A(qe),t.current&&(t.current.volume=qe),localStorage.setItem("video-volume",String(qe))};L.useEffect(()=>{if(s){if(m)try{s.audioTrack=s.audioTracks.findIndex(Ae=>Ae.id===m.id)}catch{}p?s.subtitleTrack=s.subtitleTracks.findIndex(Ae=>Ae.id===p.id):s.subtitleTrack=-1,g&&(s.currentLevel=s.levels.findIndex(Ae=>Ae.height===g.height))}},[m,p,g,s]);const ye=()=>{e.current&&(_?document.exitFullscreen():e.current.requestFullscreen().catch(Ae=>console.log(Ae)),b(!_))},Re=()=>{C(!0),clearTimeout(se),se=setTimeout(()=>{var Ae;(Ae=r.current)!=null&&Ae.matches(":hover")||C(!1)},5e3)},Ee=()=>{I>0?(O(I),A(0),t.current&&(t.current.volume=0)):(A(k),t.current&&(t.current.volume=k))},Fe=()=>{if(s){const Ae=s.subtitleTrack===-1?0:-1;s.subtitleTrack=Ae}},st=L.useCallback(Ae=>{var qe,R;if(t.current)switch(Ae.key){case"f":ye();break;case"m":Ee();break;case"c":Fe();break;case" ":Ae.preventDefault(),t.current.paused?t.current.play():t.current.pause();break;case"ArrowLeft":t.current.currentTime=Math.max(0,t.current.currentTime-10);break;case"ArrowRight":t.current.currentTime=Math.min(t.current.duration,t.current.currentTime+10);break;case"ArrowUp":A(N=>{const $=Math.min(1,N+.05);return t.current&&(t.current.volume=$),$});break;case"ArrowDown":A(N=>{const $=Math.max(0,N-.05);return t.current&&(t.current.volume=$),$});break;case"PageUp":(qe=H==null?void 0:H.data)!=null&&qe._next&&K(`/watch/${G}/${H.data._next}`);break;case"PageDown":(R=H==null?void 0:H.data)!=null&&R._previous&&K(`/watch/${G}/${H.data._previous}`);break}},[ye,Ee,Fe]);L.useEffect(()=>(document.addEventListener("keydown",st),()=>{document.removeEventListener("keydown",st)}),[st]);const br=()=>I===0?E.jsx(fF,{}):I<=.3?E.jsx(dF,{}):I<=.6?E.jsx(cF,{}):E.jsx(hF,{});return E.jsxs("section",{className:`bg-black relative ${T?"":"cursor-none"}`,ref:e,onMouseMove:Re,children:[E.jsx("video",{ref:t,className:"w-full h-screen"},P),E.jsx(_s,{className:`top-0 left-0 fixed h-screen w-screen transition-all duration-300 pointer-events-none z-50 ${x?"opacity-100":"opacity-0"}`}),E.jsx("section",{className:`absolute bottom-0 w-full flex flex-col justify-end z-20 ${T?"opacity-100":"opacity-0"} transition-opacity duration-300`,ref:r,children:E.jsxs("section",{className:"flex items-center justify-between px-4 py-2 bg-neutral-800 bg-opacity-75 gap-4",children:[E.jsx("button",{onClick:()=>{var Ae,qe,R;return(Ae=t.current)!=null&&Ae.paused?(qe=t.current)==null?void 0:qe.play():(R=t.current)==null?void 0:R.pause()},className:"hover:bg-neutral-700 p-1 rounded",children:(rn=t.current)!=null&&rn.paused?E.jsx(oF,{}):E.jsx(aF,{})}),E.jsx("div",{className:"volume-hover relative group flex items-center",children:E.jsxs("div",{className:"flex items-center group-hover:bg-neutral-700 p-1 rounded relative",children:[E.jsx("button",{className:"flex items-center",title:"Volume",onClick:Ee,children:br()}),E.jsx("input",{type:"range",min:0,max:1,step:.01,value:I,onChange:fe,className:"volume-slider"})]})}),E.jsx("input",{type:"range",className:"w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700",min:0,max:((xn=t.current)==null?void 0:xn.duration)||0,value:n,onChange:ee}),E.jsxs("span",{children:[F(n),"/",F((nt=t.current)==null?void 0:nt.duration)]}),E.jsxs("section",{className:"flex gap-2 items-center",children:[(o==null?void 0:o.length)>1&&E.jsx(Bf,{icon:E.jsx(mF,{}),values:o,selectedValue:m,setSelectedValue:h}),(u==null?void 0:u.length)>0&&E.jsx(Bf,{icon:E.jsx(uF,{}),values:u,selectedValue:p,setSelectedValue:v,canDeselect:!0}),((Gr=H==null?void 0:H.data)==null?void 0:Gr.serie_representation)&&E.jsx(EF,{seasons:H.data.serie_representation,onSelect:W,icon:E.jsx(gF,{}),currentEpisodeId:parseInt(P||"0")}),E.jsx(Bf,{icon:E.jsx(lF,{}),values:d,selectedValue:g,setSelectedValue:y}),E.jsx("button",{className:"hover:bg-neutral-700 p-1 rounded",children:E.jsx(pF,{})}),E.jsx("button",{onClick:ye,className:"hover:bg-neutral-700 p-1 rounded",children:_?E.jsx(xF,{}):E.jsx(SF,{})})]})]})})]})};var me={},op={exports:{}};(function(t,e){(function(r,n){var i="1.0.38",s="",a="?",o="function",l="undefined",u="object",c="string",d="major",f="model",m="name",h="type",p="vendor",v="version",g="architecture",y="console",x="mobile",S="tablet",T="smarttv",C="wearable",_="embedded",b=500,I="Amazon",A="Apple",k="ASUS",O="BlackBerry",P="Browser",G="Chrome",K="Edge",H="Firefox",se="Google",W="Huawei",F="LG",j="Microsoft",te="Motorola",ee="Opera",fe="Samsung",ye="Sharp",Re="Sony",Ee="Xiaomi",Fe="Zebra",st="Facebook",br="Chromium OS",tn="Mac OS",jn=function(oe,xe){var ce={};for(var Ge in oe)xe[Ge]&&xe[Ge].length%2===0?ce[Ge]=xe[Ge].concat(oe[Ge]):ce[Ge]=oe[Ge];return ce},rn=function(oe){for(var xe={},ce=0;ce0?Pe.length===2?typeof Pe[1]==o?this[Pe[0]]=Pe[1].call(this,Nt):this[Pe[0]]=Pe[1]:Pe.length===3?typeof Pe[1]===o&&!(Pe[1].exec&&Pe[1].test)?this[Pe[0]]=Nt?Pe[1].call(this,Nt,Pe[2]):n:this[Pe[0]]=Nt?Nt.replace(Pe[1],Pe[2]):n:Pe.length===4&&(this[Pe[0]]=Nt?Pe[3].call(this,Nt.replace(Pe[1],Pe[2])):n):this[Pe]=Nt||n;ce+=2}},R=function(oe,xe){for(var ce in xe)if(typeof xe[ce]===u&&xe[ce].length>0){for(var Ge=0;Ge2&&(Le[f]="iPad",Le[h]=S),Le},this.getEngine=function(){var Le={};return Le[m]=n,Le[v]=n,qe.call(Le,Ge,mt.engine),Le},this.getOS=function(){var Le={};return Le[m]=n,Le[v]=n,qe.call(Le,Ge,mt.os),Pe&&!Le[m]&&nr&&nr.platform&&nr.platform!="Unknown"&&(Le[m]=nr.platform.replace(/chrome os/i,br).replace(/macos/i,tn)),Le},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return Ge},this.setUA=function(Le){return Ge=typeof Le===c&&Le.length>b?Ae(Le,b):Le,this},this.setUA(Ge),this};Z.VERSION=i,Z.BROWSER=rn([m,v,d]),Z.CPU=rn([g]),Z.DEVICE=rn([f,p,h,y,x,T,S,C,_]),Z.ENGINE=Z.OS=rn([m,v]),t.exports&&(e=t.exports=Z),e.UAParser=Z;var X=typeof r!==l&&(r.jQuery||r.Zepto);if(X&&!X.ua){var ge=new Z;X.ua=ge.getResult(),X.ua.get=function(){return ge.getUA()},X.ua.set=function(oe){ge.setUA(oe);var xe=ge.getResult();for(var ce in xe)X.ua[ce]=xe[ce]}}})(typeof window=="object"?window:wb)})(op,op.exports);var wF=op.exports;Object.defineProperty(me,"__esModule",{value:!0});function bF(t){return t&&typeof t=="object"&&"default"in t?t.default:t}var Jt=L,ut=bF(Jt),yw=wF,Yi=new yw,rr=Yi.getBrowser(),LF=Yi.getCPU(),Vr=Yi.getDevice(),Gm=Yi.getEngine(),qi=Yi.getOS(),bl=Yi.getUA(),xw=function(e){return Yi.setUA(e)},Ll=function(e){if(!e){console.error("No userAgent string was provided");return}var r=new yw(e);return{UA:r,browser:r.getBrowser(),cpu:r.getCPU(),device:r.getDevice(),engine:r.getEngine(),os:r.getOS(),ua:r.getUA(),setUserAgent:function(i){return r.setUA(i)}}},Sw=Object.freeze({ClientUAInstance:Yi,browser:rr,cpu:LF,device:Vr,engine:Gm,os:qi,ua:bl,setUa:xw,parseUserAgent:Ll});function cy(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function AF(t){for(var e=1;e=0)&&(r[i]=t[i]);return r}function en(t,e){if(t==null)return{};var r=DF(t,e),n,i;if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function ju(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function PF(t,e){if(e&&(typeof e=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ju(t)}function OF(t,e){return MF(t)||NF(t,e)||FF(t,e)||UF()}function MF(t){if(Array.isArray(t))return t}function NF(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],i=!0,s=!1,a,o;try{for(r=r.call(t);!(i=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));i=!0);}catch(l){s=!0,o=l}finally{try{!i&&r.return!=null&&r.return()}finally{if(s)throw o}}return n}}function FF(t,e){if(t){if(typeof t=="string")return dy(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return dy(t,e)}}function dy(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r1&&arguments[1]!==void 0?arguments[1]:"none";return e||r},zm=function(){return typeof window<"u"&&(window.navigator||navigator)?window.navigator||navigator:!1},Hm=function(e){var r=zm();return r&&r.platform&&(r.platform.indexOf(e)!==-1||r.platform==="MacIntel"&&r.maxTouchPoints>1&&!window.MSStream)},VF=function(e,r,n,i,s){return{isBrowser:e,browserMajorVersion:De(r.major),browserFullVersion:De(r.version),browserName:De(r.name),engineName:De(n.name),engineVersion:De(n.version),osName:De(i.name),osVersion:De(i.version),userAgent:De(s)}},fy=function(e,r,n,i){return AF({},e,{vendor:De(r.vendor),model:De(r.model),os:De(n.name),osVersion:De(n.version),ua:De(i)})},GF=function(e,r,n,i){return{isSmartTV:e,engineName:De(r.name),engineVersion:De(r.version),osName:De(n.name),osVersion:De(n.version),userAgent:De(i)}},zF=function(e,r,n,i){return{isConsole:e,engineName:De(r.name),engineVersion:De(r.version),osName:De(n.name),osVersion:De(n.version),userAgent:De(i)}},HF=function(e,r,n,i){return{isWearable:e,engineName:De(r.name),engineVersion:De(r.version),osName:De(n.name),osVersion:De(n.version),userAgent:De(i)}},WF=function(e,r,n,i,s){return{isEmbedded:e,vendor:De(r.vendor),model:De(r.model),engineName:De(n.name),engineVersion:De(n.version),osName:De(i.name),osVersion:De(i.version),userAgent:De(s)}};function KF(t){var e=t?Ll(t):Sw,r=e.device,n=e.browser,i=e.engine,s=e.os,a=e.ua,o=$F(r.type),l=o.isBrowser,u=o.isMobile,c=o.isTablet,d=o.isSmartTV,f=o.isConsole,m=o.isWearable,h=o.isEmbedded;if(l)return VF(l,n,i,s,a);if(d)return GF(d,i,s,a);if(f)return zF(f,i,s,a);if(u||c)return fy(o,r,s,a);if(m)return HF(m,i,s,a);if(h)return WF(h,r,i,s,a)}var Ew=function(e){var r=e.type;return r===Zt.Mobile},Tw=function(e){var r=e.type;return r===Zt.Tablet},ww=function(e){var r=e.type;return r===Zt.Mobile||r===Zt.Tablet},bw=function(e){var r=e.type;return r===Zt.SmartTv},Wc=function(e){var r=e.type;return r===Zt.Browser},Lw=function(e){var r=e.type;return r===Zt.Wearable},Aw=function(e){var r=e.type;return r===Zt.Console},_w=function(e){var r=e.type;return r===Zt.Embedded},Cw=function(e){var r=e.vendor;return De(r)},Rw=function(e){var r=e.model;return De(r)},Iw=function(e){var r=e.type;return De(r,"browser")},kw=function(e){var r=e.name;return r===ja.Android},Dw=function(e){var r=e.name;return r===ja.Windows},Pw=function(e){var r=e.name;return r===ja.MAC_OS},Ow=function(e){var r=e.name;return r===ja.WindowsPhone},Mw=function(e){var r=e.name;return r===ja.IOS},Nw=function(e){var r=e.version;return De(r)},Fw=function(e){var r=e.name;return De(r)},Uw=function(e){var r=e.name;return r===wr.Chrome},Bw=function(e){var r=e.name;return r===wr.Firefox},$w=function(e){var r=e.name;return r===wr.Chromium},Kc=function(e){var r=e.name;return r===wr.Edge},jw=function(e){var r=e.name;return r===wr.Yandex},Vw=function(e){var r=e.name;return r===wr.Safari||r===wr.MobileSafari},Gw=function(e){var r=e.name;return r===wr.MobileSafari},zw=function(e){var r=e.name;return r===wr.Opera},Hw=function(e){var r=e.name;return r===wr.InternetExplorer||r===wr.Ie},Ww=function(e){var r=e.name;return r===wr.MIUI},Kw=function(e){var r=e.name;return r===wr.SamsungBrowser},Yw=function(e){var r=e.version;return De(r)},qw=function(e){var r=e.major;return De(r)},Xw=function(e){var r=e.name;return De(r)},Zw=function(e){var r=e.name;return De(r)},Qw=function(e){var r=e.version;return De(r)},Jw=function(){var e=zm(),r=e&&e.userAgent&&e.userAgent.toLowerCase();return typeof r=="string"?/electron/.test(r):!1},ha=function(e){return typeof e=="string"&&e.indexOf("Edg/")!==-1},eb=function(){var e=zm();return e&&(/iPad|iPhone|iPod/.test(e.platform)||e.platform==="MacIntel"&&e.maxTouchPoints>1)&&!window.MSStream},_n=function(){return Hm("iPad")},tb=function(){return Hm("iPhone")},rb=function(){return Hm("iPod")},nb=function(e){return De(e)};function ib(t){var e=t||Sw,r=e.device,n=e.browser,i=e.os,s=e.engine,a=e.ua;return{isSmartTV:bw(r),isConsole:Aw(r),isWearable:Lw(r),isEmbedded:_w(r),isMobileSafari:Gw(n)||_n(),isChromium:$w(n),isMobile:ww(r)||_n(),isMobileOnly:Ew(r),isTablet:Tw(r)||_n(),isBrowser:Wc(r),isDesktop:Wc(r),isAndroid:kw(i),isWinPhone:Ow(i),isIOS:Mw(i)||_n(),isChrome:Uw(n),isFirefox:Bw(n),isSafari:Vw(n),isOpera:zw(n),isIE:Hw(n),osVersion:Nw(i),osName:Fw(i),fullBrowserVersion:Yw(n),browserVersion:qw(n),browserName:Xw(n),mobileVendor:Cw(r),mobileModel:Rw(r),engineName:Zw(s),engineVersion:Qw(s),getUA:nb(a),isEdge:Kc(n)||ha(a),isYandex:jw(n),deviceType:Iw(r),isIOS13:eb(),isIPad13:_n(),isIPhone13:tb(),isIPod13:rb(),isElectron:Jw(),isEdgeChromium:ha(a),isLegacyEdge:Kc(n)&&!ha(a),isWindows:Dw(i),isMacOs:Pw(i),isMIUI:Ww(n),isSamsungBrowser:Kw(n)}}var sb=bw(Vr),ab=Aw(Vr),ob=Lw(Vr),YF=_w(Vr),qF=Gw(rr)||_n(),XF=$w(rr),bd=ww(Vr)||_n(),lb=Ew(Vr),ub=Tw(Vr)||_n(),cb=Wc(Vr),ZF=Wc(Vr),db=kw(qi),fb=Ow(qi),hb=Mw(qi)||_n(),QF=Uw(rr),JF=Bw(rr),e2=Vw(rr),t2=zw(rr),pb=Hw(rr),r2=Nw(qi),n2=Fw(qi),i2=Yw(rr),s2=qw(rr),a2=Xw(rr),o2=Cw(Vr),l2=Rw(Vr),u2=Zw(Gm),c2=Qw(Gm),d2=nb(bl),f2=Kc(rr)||ha(bl),h2=jw(rr),p2=Iw(Vr),m2=eb(),g2=_n(),v2=tb(),y2=rb(),x2=Jw(),S2=ha(bl),E2=Kc(rr)&&!ha(bl),T2=Dw(qi),w2=Pw(qi),b2=Ww(rr),L2=Kw(rr),A2=function(e){if(!e||typeof e!="string"){console.error("No valid user agent string was provided");return}var r=Ll(e),n=r.device,i=r.browser,s=r.os,a=r.engine,o=r.ua;return ib({device:n,browser:i,os:s,engine:a,ua:o})},_2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return db?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},C2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return cb?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},R2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return pb?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},I2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return hb?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},k2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return bd?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},D2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return ub?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},P2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return fb?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},O2=function(e){var r=e.renderWithFragment,n=e.children;e.viewClassName,e.style;var i=en(e,["renderWithFragment","children","viewClassName","style"]);return lb?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},M2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return sb?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},N2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return ab?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},F2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return ob?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},U2=function(e){var r=e.renderWithFragment,n=e.children;e.viewClassName,e.style;var i=e.condition,s=en(e,["renderWithFragment","children","viewClassName","style","condition"]);return i?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",s,n):null};function B2(t){return function(e){kF(r,e);function r(n){var i;return _F(this,r),i=PF(this,up(r).call(this,n)),i.isEventListenerAdded=!1,i.handleOrientationChange=i.handleOrientationChange.bind(ju(i)),i.onOrientationChange=i.onOrientationChange.bind(ju(i)),i.onPageLoad=i.onPageLoad.bind(ju(i)),i.state={isLandscape:!1,isPortrait:!1},i}return RF(r,[{key:"handleOrientationChange",value:function(){this.isEventListenerAdded||(this.isEventListenerAdded=!0);var i=window.innerWidth>window.innerHeight?90:0;this.setState({isPortrait:i===0,isLandscape:i===90})}},{key:"onOrientationChange",value:function(){this.handleOrientationChange()}},{key:"onPageLoad",value:function(){this.handleOrientationChange()}},{key:"componentDidMount",value:function(){(typeof window>"u"?"undefined":Ro(window))!==void 0&&bd&&(this.isEventListenerAdded?window.removeEventListener("load",this.onPageLoad,!1):(this.handleOrientationChange(),window.addEventListener("load",this.onPageLoad,!1)),window.addEventListener("resize",this.onOrientationChange,!1))}},{key:"componentWillUnmount",value:function(){window.removeEventListener("resize",this.onOrientationChange,!1)}},{key:"render",value:function(){return ut.createElement(t,lp({},this.props,{isLandscape:this.state.isLandscape,isPortrait:this.state.isPortrait}))}}]),r}(ut.Component)}function $2(){var t=Jt.useState(function(){var s=window.innerWidth>window.innerHeight?90:0;return{isPortrait:s===0,isLandscape:s===90,orientation:s===0?"portrait":"landscape"}}),e=OF(t,2),r=e[0],n=e[1],i=Jt.useCallback(function(){var s=window.innerWidth>window.innerHeight?90:0,a={isPortrait:s===0,isLandscape:s===90,orientation:s===0?"portrait":"landscape"};r.orientation!==a.orientation&&n(a)},[r.orientation]);return Jt.useEffect(function(){return(typeof window>"u"?"undefined":Ro(window))!==void 0&&bd&&(i(),window.addEventListener("load",i,!1),window.addEventListener("resize",i,!1)),function(){window.removeEventListener("resize",i,!1),window.removeEventListener("load",i,!1)}},[i]),r}function mb(t){var e=t||window.navigator.userAgent;return Ll(e)}function j2(t){var e=t||window.navigator.userAgent,r=mb(e),n=ib(r);return[n,r]}me.AndroidView=_2;me.BrowserTypes=wr;me.BrowserView=C2;me.ConsoleView=N2;me.CustomView=U2;me.IEView=R2;me.IOSView=I2;me.MobileOnlyView=O2;me.MobileView=k2;me.OsTypes=ja;me.SmartTVView=M2;me.TabletView=D2;me.WearableView=F2;me.WinPhoneView=P2;me.browserName=a2;me.browserVersion=s2;me.deviceDetect=KF;me.deviceType=p2;me.engineName=u2;me.engineVersion=c2;me.fullBrowserVersion=i2;me.getSelectorsByUserAgent=A2;me.getUA=d2;me.isAndroid=db;me.isBrowser=cb;me.isChrome=QF;me.isChromium=XF;me.isConsole=ab;me.isDesktop=ZF;me.isEdge=f2;me.isEdgeChromium=S2;me.isElectron=x2;me.isEmbedded=YF;me.isFirefox=JF;me.isIE=pb;me.isIOS=hb;me.isIOS13=m2;me.isIPad13=g2;me.isIPhone13=v2;me.isIPod13=y2;me.isLegacyEdge=E2;me.isMIUI=b2;me.isMacOs=w2;var gb=me.isMobile=bd;me.isMobileOnly=lb;me.isMobileSafari=qF;me.isOpera=t2;me.isSafari=e2;me.isSamsungBrowser=L2;me.isSmartTV=sb;me.isTablet=ub;me.isWearable=ob;me.isWinPhone=fb;me.isWindows=T2;me.isYandex=h2;me.mobileModel=l2;me.mobileVendor=o2;me.osName=n2;me.osVersion=r2;me.parseUserAgent=Ll;me.setUserAgent=jF;me.useDeviceData=mb;me.useDeviceSelectors=j2;me.useMobileOrientation=$2;me.withOrientationChange=B2;function V2(t){return Mt({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M233.4 406.6c12.5 12.5 32.8 12.5 45.3 0l192-192c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L256 338.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l192 192z"},child:[]}]})(t)}const hy=()=>{const[t,e]=L.useState(!1),{profileData:r}=dm(),n=()=>{e(!1)};return E.jsxs("section",{className:"relative flex items-center gap-4",children:[E.jsx("img",{src:r==null?void 0:r.profile_picture,alt:r==null?void 0:r.name,className:"w-8 h-8 rounded-md"}),E.jsx(V2,{onClick:()=>e(!t),className:`cursor-pointer ${t?"transform -rotate-180":""} transition-transform duration-300`}),E.jsxs("ul",{className:`absolute top-[100%] right-0 bg-neutral-900 rounded-lg px-4 overflow-hidden ${t?"h-auto p-4":"h-0 p-0"} transition-all duration-300`,children:[E.jsx("li",{children:E.jsx(Lu,{to:"/profil",onClick:n,children:"Profil"})}),E.jsx("li",{children:E.jsx(Lu,{to:"/settings",onClick:n,children:"Settings"})}),E.jsx("li",{children:E.jsx(Lu,{to:"/logout",onClick:n,children:"Logout"})})]})]})};function G2(t){return Mt({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z"},child:[]}]})(t)}const py=({onSearch:t})=>{const[e,r]=L.useState(""),n=Br(),i=a=>{r(a.target.value)},s=a=>{a.preventDefault(),t(e),n(`?query=${e}`)};return L.useEffect(()=>{const a=new URLSearchParams(window.location.search).get("query");a&&r(a)},[]),E.jsxs("form",{onSubmit:s,className:`flex gap-2 ${gb?"items-center":""}`,children:[E.jsx("input",{className:"w-48 sm:w-auto px-4 py-2 rounded-lg bg-neutral-900 focus:outline-none focus:ring-2 focus:ring-neutral-500",type:"text",placeholder:"Search...",value:e,onChange:i}),E.jsx("button",{type:"submit",children:E.jsx(G2,{})})]})},z2=()=>{const[t,e]=L.useState(!1),{setSearchTerm:r}=L.useContext(wl),n=Br(),i=s=>{r(s)};return gb?E.jsxs("section",{className:`${t?"overflow-hidden":""}`,children:[E.jsxs("section",{children:[E.jsxs("header",{className:"flex justify-between items-center py-4 px-8 text-white",children:[E.jsx("button",{onClick:()=>e(!t),className:"pointer-events-auto",children:E.jsxs("div",{className:`hamburger ${t?"active":""}`,children:[E.jsx("div",{className:"line"}),E.jsx("div",{className:"line"}),E.jsx("div",{className:"line"})]})}),E.jsx(py,{onSearch:i}),E.jsx(hy,{})]}),E.jsxs("aside",{className:`fixed pl-8 pt-4 flex flex-col gap-24 top-0 left-0 h-full bg-[--black] z-40 transform transition-transform duration-300 ease-in-out overflow-hidden w-full ${t?"translate-x-0":"-translate-x-full"}`,children:[E.jsxs("section",{className:"flex justify-between items-center py-4 pr-8",children:[E.jsx("img",{src:"/logo.png",alt:"Logo",className:"w-12 h-12"}),E.jsx("button",{onClick:()=>e(!t),className:"pointer-events-auto",children:E.jsxs("div",{className:`hamburger ${t?"active":""}`,children:[E.jsx("div",{className:"line"}),E.jsx("div",{className:"line"}),E.jsx("div",{className:"line"})]})})]}),E.jsxs("nav",{className:"flex flex-col gap-6",children:[E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/home",children:"Home"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/movies",children:"Movies"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/shows",children:"TV Shows"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/live-tv",children:"Live TV"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/musics",children:"Musics"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/books",children:"Books"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/games",children:"Games"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/others",children:"Others"})]})]})]}),E.jsx(_0,{})]}):E.jsxs("section",{children:[E.jsxs("header",{className:"flex justify-between items-center py-4 px-16 text-white sticky top-0 left-0 w-full z-[99999]",children:[E.jsxs("section",{className:"flex gap-4 items-center",children:[E.jsx("img",{src:"/logo.png",alt:"Logo",className:"w-12 h-12 cursor-pointer",onClick:()=>n("/home")}),E.jsxs("nav",{className:"flex gap-4",children:[E.jsx(qt,{to:"/home",children:"Home"}),E.jsx(qt,{to:"/movies",children:"Movies"}),E.jsx(qt,{to:"/shows",children:"TV Shows"}),E.jsx(qt,{to:"/live-tv",children:"Live TV"}),E.jsx(qt,{to:"/musics",children:"Musics"}),E.jsx(qt,{to:"/books",children:"Books"}),E.jsx(qt,{to:"/games",children:"Games"}),E.jsx(qt,{to:"/others",children:"Others"})]})]}),E.jsxs("section",{className:"flex gap-8",children:[E.jsx(py,{onSearch:i}),E.jsx(hy,{})]})]}),E.jsx(_0,{})]})},my=({children:t})=>{const{data:e}=ur("/api/settings/libraries"),r=Br();return L.useEffect(()=>{e&&(!e.data||e.data.length==0)&&r("/settings#libraries")},[e]),E.jsxs(E.Fragment,{children:[E.jsx(z2,{}),E.jsx("main",{children:t})]})},H2=()=>{const[t,e]=L.useState(!0),[r,n]=L.useState(""),[i,s]=L.useState(""),[a,o]=L.useState(""),[l,u]=L.useState(""),[c,d]=L.useState(!1),{handleSubmit:f}=Ss(),m=async()=>{await f({url:"/api/settings/general",body:{ChocolateSettings:{language:r,allowdownload:c},APIKeys:{tmdb:i,igdbid:a,igdbsecret:l}}})},{data:h,loading:p}=ur("/api/settings/general"),{data:v,loading:g}=ur("/api/settings/languages");return L.useEffect(()=>{e(p&&g)},[p,g]),L.useEffect(()=>{h&&h.data&&h.data.ChocolateSettings&&h.data.APIKeys&&(n(h.data.ChocolateSettings.language),d(h.data.ChocolateSettings.allowdownload==="true"),s(h.data.APIKeys.tmdb),o(h.data.APIKeys.igdbid),u(h.data.APIKeys.igdbsecret))},[h]),E.jsxs(E.Fragment,{children:[E.jsx(_s,{className:"w-3/4 h-screen top-0 fixed bg-[--black] transition-all duration-300 pointer-events-none z-50 "+(t?"opacity-100":"opacity-0")}),E.jsx("h2",{className:`text-xl font-bold mb-4 ${t?"hidden":""}`,children:"General Settings"}),E.jsxs("div",{className:`flex flex-col items-start gap-6 px-8 ${t?"hidden":""}`,children:[E.jsxs("div",{className:"w-full max-w-md",children:[E.jsx("h2",{className:"text-xl font-bold mb-4",children:"Settings"}),E.jsxs("div",{className:"mb-4",children:[E.jsx("label",{htmlFor:"language-select",className:"block mb-2",children:"Language:"}),E.jsx("select",{id:"language-select",value:r,onChange:y=>n(y.target.value),className:"w-full px-4 py-2 rounded-lg bg-neutral-900 focus:outline-none focus:ring-2 focus:ring-neutral-500",children:v&&v.data&&v.data.map(y=>E.jsx("option",{value:y.code,children:y.name},y.code))})]}),E.jsxs("div",{className:"mb-4 flex items-center gap-4",children:[E.jsx("label",{htmlFor:"allow-downloads",className:"block",children:"Allow Downloads:"}),E.jsx("input",{type:"checkbox",id:"allow-downloads",checked:c,onChange:y=>d(y.target.checked),className:"w-4 h-4 rounded-lg bg-neutral-900 border-0 outline-none ring-0 focus:outline-none focus:ring-2 focus:ring-neutral-500"})]})]}),E.jsxs("div",{className:"w-full max-w-md",children:[E.jsx("h2",{className:"text-xl font-bold mb-4",children:"API Keys"}),E.jsxs("div",{className:"mb-4",children:[E.jsx("label",{htmlFor:"tmdb-api-key",className:"block mb-2",children:"TMDB API Key:"}),E.jsx("input",{type:"text",id:"tmdb-api-key",value:i,onChange:y=>s(y.target.value),placeholder:"afa...fdp",className:"w-full px-4 py-2 rounded-lg bg-neutral-900 focus:outline-none focus:ring-2 focus:ring-neutral-500"})]}),E.jsxs("div",{className:"mb-4",children:[E.jsx("label",{htmlFor:"igdb-id-key",className:"block mb-2",children:"IGDB ID Key:"}),E.jsx("input",{type:"text",id:"igdb-id-key",value:a,onChange:y=>o(y.target.value),placeholder:"161...b3f",className:"w-full px-4 py-2 rounded-lg bg-neutral-900 focus:outline-none focus:ring-2 focus:ring-neutral-500"})]}),E.jsxs("div",{className:"mb-4",children:[E.jsx("label",{htmlFor:"igdb-secret-key",className:"block mb-2",children:"IGDB Secret Key:"}),E.jsx("input",{type:"password",id:"igdb-secret-key",autoComplete:"new-password",value:l,onChange:y=>u(y.target.value),placeholder:"161...b3f",className:"w-full px-4 py-2 rounded-lg bg-neutral-900 focus:outline-none focus:ring-2 focus:ring-neutral-500"})]})]}),E.jsx(Rn,{state:"primary",onClick:m,children:"Save Settings"})]})]})},Ar=-161,W2=()=>{var h,p,v;const[t,e]=L.useState([]),[r,n]=L.useState(!0),{data:i,loading:s,fetchData:a}=ur("/api/settings/accounts"),{handleSubmit:o}=Ss(),{handleSubmit:l}=iE(),{handleSubmit:u}=sE();L.useEffect(()=>{i&&i.data&&e(i.data),n(s)},[i,s]),L.useEffect(()=>{t.find(y=>y.id===Ar)||e(y=>[...y,{id:Ar,name:"",account_type:"Admin"}])},[i,t]);const c=(g,y,x)=>{e(S=>S.map(T=>T.id===g?{...T,[y]:x}:T))},d=async g=>{await o({url:"/api/settings/accounts",body:g}),a()},f=async g=>{await l({url:"/api/settings/accounts",body:g}),a()},m=async()=>{const g=t.find(y=>y.id===Ar);g&&await u({url:"/api/settings/accounts",body:{...g}}),a(),c(Ar,"name",""),c(Ar,"password",""),c(Ar,"account_type","Admin")};return E.jsxs(E.Fragment,{children:[E.jsx(_s,{className:"w-3/4 h-screen top-0 fixed bg-[--black] transition-all duration-300 pointer-events-none z-50 "+(r?"opacity-100":"opacity-0")}),E.jsx("h2",{className:`text-xl font-bold mb-4 ${r?"hidden":""}`,children:"Accounts Settings"}),E.jsxs("div",{className:`grid grid-cols-4 items-start gap-6 w-full ${r?"hidden":""}`,children:[t.map(g=>g.id!==Ar&&E.jsxs("div",{className:"max-w-md p-4 mb-4 rounded-lg bg-neutral-900 flex flex-col gap-2",children:[E.jsxs("h3",{className:"text-lg font-bold",children:["Account ID: ",g.id]}),E.jsx("input",{type:"text",value:g.name,onChange:y=>c(g.id,"name",y.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsxs("select",{value:g.account_type,onChange:y=>c(g.id,"account_type",y.target.value),className:"p-2 rounded bg-neutral-800 text-white",children:[E.jsx("option",{value:"Admin",children:"Admin"}),E.jsx("option",{value:"Adult",children:"Adult"}),E.jsx("option",{value:"Teen",children:"Teen"}),E.jsx("option",{value:"Kid",children:"Kid"})]}),E.jsx(Rn,{state:"primary",onClick:()=>d(g),children:"Save Account"}),E.jsx(Rn,{state:"danger",onClick:()=>f(g),children:"Delete Account"})]},g.id)),E.jsxs("div",{className:"max-w-md p-4 mb-4 rounded-lg bg-neutral-900 flex flex-col gap-2",children:[E.jsx("h3",{className:"text-lg font-bold",children:"Create New Account"}),E.jsx("input",{type:"text",placeholder:"Name",autoComplete:"new-password",value:(h=t.find(g=>g.id===Ar))==null?void 0:h.name,onChange:g=>c(Ar,"name",g.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsxs("select",{value:(p=t.find(g=>g.id===Ar))==null?void 0:p.account_type,onChange:g=>c(Ar,"account_type",g.target.value),className:" p-2 rounded bg-neutral-800 text-white",children:[E.jsx("option",{value:"Admin",children:"Admin"}),E.jsx("option",{value:"Adult",children:"Adult"}),E.jsx("option",{value:"Teen",children:"Teen"}),E.jsx("option",{value:"Kid",children:"Kid"})]}),E.jsx("input",{type:"password",placeholder:"Password",autoComplete:"new-password",value:(v=t.find(g=>g.id===Ar))==null?void 0:v.password,onChange:g=>c(Ar,"password",g.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsx(Rn,{state:"primary",onClick:m,children:"Create Account"})]})]})]})},_r=-162,K2=()=>{var v,g,y;const[t,e]=L.useState([]),[r,n]=L.useState(!0),{data:i,loading:s,fetchData:a}=ur("/api/settings/libraries"),{handleSubmit:o}=Ss(),{handleSubmit:l}=Ss(),{handleSubmit:u}=iE(),{handleSubmit:c}=sE();L.useEffect(()=>{i&&i.data&&e(i.data),n(s)},[i,s]),L.useEffect(()=>{t.find(S=>S.id===_r)||e(S=>[...S,{id:_r,name:"",path:"",type:"movies"}])},[i,t]);const d=(x,S,T)=>{e(C=>C.map(_=>_.id===x?{..._,[S]:T}:_))},f=async x=>{await o({url:"/api/settings/libraries",body:x}),a()},m=async x=>{await l({url:"/api/settings/libraries",body:{...x,scan:!0}})},h=async x=>{await u({url:"/api/settings/libraries",body:x}),a()},p=async()=>{const x=t.find(S=>S.id===_r);x&&await c({url:"/api/settings/libraries",body:{...x}}),a(),d(_r,"name",""),d(_r,"path",""),d(_r,"type","movies")};return E.jsxs(E.Fragment,{children:[E.jsx(_s,{className:"w-3/4 h-screen top-0 fixed bg-[--black] transition-all duration-300 pointer-events-none z-50 "+(r?"opacity-100":"opacity-0")}),E.jsx("h2",{className:`text-xl font-bold mb-4 ${r?"hidden":""}`,children:"Libraries Settings"}),E.jsxs("div",{className:`grid grid-cols-4 items-start gap-6 w-full ${r?"hidden":""}`,children:[t.map(x=>x.id!==_r&&E.jsxs("div",{className:"max-w-md p-4 mb-4 rounded-lg bg-neutral-900 flex flex-col gap-2",children:[E.jsxs("h3",{className:"text-lg font-bold",children:["Library ID: ",x.id]}),E.jsx("input",{type:"text",value:x.name,onChange:S=>d(x.id,"name",S.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsx("input",{type:"text",value:x.path,onChange:S=>d(x.id,"path",S.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsxs("select",{value:x.type,onChange:S=>d(x.id,"type",S.target.value),className:"p-2 rounded bg-neutral-800 text-white",children:[E.jsx("option",{value:"movies",children:"Movies"}),E.jsx("option",{value:"series",children:"Series"}),E.jsx("option",{value:"tv",children:"TV"}),E.jsx("option",{value:"books",children:"Books"}),E.jsx("option",{value:"music",children:"Music"}),E.jsx("option",{value:"other",children:"Other"})]}),E.jsx(Rn,{state:"primary",onClick:()=>f(x),children:"Save Library"}),E.jsx(Rn,{state:"secondary",className:"border border-zinc-700",onClick:()=>m(x),children:"Scan Library"}),E.jsx(Rn,{state:"danger",onClick:()=>h(x),children:"Delete Library"})]},x.id)),E.jsxs("div",{className:"max-w-md p-4 mb-4 rounded-lg bg-neutral-900 flex flex-col gap-2",children:[E.jsx("h3",{className:"text-lg font-bold",children:"Create New Library"}),E.jsx("input",{type:"text",placeholder:"Name",value:(v=t.find(x=>x.id===_r))==null?void 0:v.name,onChange:x=>d(_r,"name",x.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsx("input",{type:"text",placeholder:"Path",value:(g=t.find(x=>x.id===_r))==null?void 0:g.path,onChange:x=>d(_r,"path",x.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsxs("select",{value:(y=t.find(x=>x.id===_r))==null?void 0:y.type,onChange:x=>d(_r,"type",x.target.value),className:"p-2 rounded bg-neutral-800 text-white",children:[E.jsx("option",{value:"movies",children:"Movies"}),E.jsx("option",{value:"series",children:"Series"}),E.jsx("option",{value:"tv",children:"TV"}),E.jsx("option",{value:"books",children:"Books"}),E.jsx("option",{value:"music",children:"Music"}),E.jsx("option",{value:"other",children:"Other"})]}),E.jsx(Rn,{state:"primary",onClick:p,children:"Create Library"})]})]})]})},Y2=()=>{const[t,e]=L.useState(window.location.hash||"#general"),{data:r}=ur("/api/auth/check"),n=Br();return L.useEffect(()=>{r&&(!r.data||r.data.account_type!=="Admin")&&n("/")},[r]),L.useEffect(()=>{const i=()=>{e(window.location.hash||"#general")};return window.addEventListener("hashchange",i),()=>{window.removeEventListener("hashchange",i)}},[]),E.jsxs("div",{className:"flex h-screen",children:[E.jsxs("div",{className:"w-1/6 border-r-2 border-zinc-800 text-white p-4",children:[E.jsx("h2",{className:"text-xl font-bold mb-4",children:"Settings"}),E.jsxs("ul",{children:[E.jsx("li",{className:"mb-2",children:E.jsx("a",{href:"#general",className:`hover:underline ${t==="#general"?"font-bold":""}`,children:"General"})}),E.jsx("li",{className:"mb-2",children:E.jsx("a",{href:"#accounts",className:`hover:underline ${t==="#accounts"?"font-bold":""}`,children:"Accounts"})}),E.jsx("li",{className:"mb-2",children:E.jsx("a",{href:"#libraries",className:`hover:underline ${t==="#libraries"?"font-bold":""}`,children:"Libraries"})})]})]}),E.jsxs("div",{className:"w-5/6 p-4 overflow-y-scroll",children:[t==="#general"&&E.jsx(H2,{}),t==="#accounts"&&E.jsx(W2,{}),t==="#libraries"&&E.jsx(K2,{})]})]})};function q2(){const{data:t}=ur("/api/profil"),{handleSubmit:e}=Ss(),[r,n]=L.useState(null),[i,s]=L.useState(""),[a,o]=L.useState(""),[l,u]=L.useState(""),[c,d]=L.useState(null);L.useEffect(()=>{t&&(n(t.data.id),s(t.data.name),u(t.data.profile_picture))},[t]);const f=h=>{var v;const p=(v=h.target.files)==null?void 0:v[0];if(p){d(p);const g=new FileReader;g.onloadend=()=>{const y=new Image;y.src=g.result,y.onload=()=>{const x=document.createElement("canvas"),S=Math.min(y.width,y.height);x.width=S,x.height=S;const T=x.getContext("2d");T&&(T.drawImage(y,(y.width-S)/2,(y.height-S)/2,S,S,0,0,S,S),u(x.toDataURL("image/jpeg")))}},g.readAsDataURL(p)}},m=async h=>{h.preventDefault();const p={id:r,name:i,image:l,password:a};try{await e({url:"/api/profil",body:p}).then(()=>{Ke.success("Profil updated")})}catch{Ke.error("Error updating profil")}};return E.jsxs(Sm,{className:"w-full max-w-md mx-auto mt-8",children:[E.jsx(Em,{children:E.jsx(Tm,{className:"text-2xl font-bold text-center",children:"Profil"})}),E.jsx($E,{children:E.jsxs("form",{onSubmit:m,className:"space-y-4",children:[E.jsxs("div",{className:"space-y-2",children:[E.jsx(Ao,{htmlFor:"avatar",children:"Photo de profil"}),E.jsxs("div",{className:"flex items-center space-x-4",children:[E.jsx("img",{src:l,alt:"avatar",className:"w-12 h-12 rounded-full"}),E.jsx(fs,{id:"avatar",type:"file",accept:"image/*",onChange:f,className:"w-full"})]})]}),E.jsxs("div",{className:"space-y-2",children:[E.jsx(Ao,{htmlFor:"name",children:"Nom"}),E.jsx(fs,{id:"name",type:"text",value:i,onChange:h=>s(h.target.value),placeholder:"Votre nom"})]}),E.jsxs("div",{className:"space-y-2",children:[E.jsx(Ao,{htmlFor:"password",children:"Mot de passe"}),E.jsx(fs,{id:"password",type:"password",value:a,onChange:h=>o(h.target.value),placeholder:"Nouveau mot de passe"})]})]})}),E.jsx(jE,{children:E.jsx(xm,{onClick:m,className:"w-full",children:"Enregistrer"})})]})}const X2=()=>E.jsx("section",{className:"flex justify-center items-center w-screen h-screen fixed top-0",children:E.jsxs("div",{className:"text-center flex flex-col items-center gap-2",children:[E.jsx("h1",{className:"font-bold text-4xl",children:"404"}),E.jsx("h1",{className:"font-bold text-2xl",children:"Page Not Found"}),E.jsx("p",{children:"Sorry, the page you are looking for does not exist."}),E.jsx("p",{children:"If you were redirected here, the page is not implemented yet."}),E.jsx(Rn,{state:"primary",to:"/",className:"mt-4 w-fit",children:"Go Home"})]})}),Z2=()=>{const{type:t}=VS();return t&&["movie","show","live-tv","other"].includes(t)?E.jsx(TF,{}):E.jsx(HS,{to:"/home"})},Q2=g_([{path:"/login",element:E.jsx(AC,{})},{path:"/logout",element:E.jsx(_C,{})},{path:"/invite",element:E.jsx(KI,{})},{path:"/",element:E.jsx(my,{}),children:[{path:"/",element:E.jsx(HS,{to:"/home"})},{path:"/home",element:E.jsx(ND,{})},{path:"/movies",element:E.jsx(FD,{})},{path:"/shows",element:E.jsx(UD,{})},{path:"/watch/:type/:id",element:E.jsx(Z2,{})},{path:"/settings",element:E.jsx(Y2,{})},{path:"/profil",element:E.jsx(q2,{})}]},{path:"*",element:E.jsx(my,{}),children:[{path:"*",element:E.jsx(X2,{})}]}]);RS(document.getElementById("root")).render(E.jsxs(E.Fragment,{children:[E.jsx(MD,{children:E.jsx(b_,{router:Q2})}),E.jsx(G_,{theme:"colored",position:"bottom-right"})]})); +`),u=[],c=e?sM(e.baseTime,e.timescale):0;let d="00:00.000",f=0,m=0,h,p=!0;o.oncue=function(v){const g=r[n];let y=r.ccOffset;const x=(f-c)/9e4;if(g!=null&&g.new&&(m!==void 0?y=r.ccOffset=g.start:jM(r,n,x)),x){if(!e){h=new Error("Missing initPTS for VTT MPEGTS");return}y=x-r.presentationOffset}const S=v.endTime-v.startTime,T=Hr((v.startTime+y-m)*9e4,i*9e4)/9e4;v.startTime=Math.max(T,0),v.endTime=Math.max(T+S,0);const C=v.text.trim();v.text=decodeURIComponent(encodeURIComponent(C)),v.id||(v.id=$m(v.startTime,v.endTime,C)),v.endTime>0&&u.push(v)},o.onparsingerror=function(v){h=v},o.onflush=function(){if(h){a(h);return}s(u)},l.forEach(v=>{if(p)if(Df(v,"X-TIMESTAMP-MAP=")){p=!1,v.slice(16).split(",").forEach(g=>{Df(g,"LOCAL:")?d=g.slice(6):Df(g,"MPEGTS:")&&(f=parseInt(g.slice(7)))});try{m=$M(d)/1e3}catch(g){h=g}return}else v===""&&(p=!1);o.parse(v+` +`)}),o.flush()}const Of="stpp.ttml.im1t",nw=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,iw=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,GM={left:"start",center:"center",right:"end",start:"start",end:"end"};function Jv(t,e,r,n){const i=Oe(new Uint8Array(t),["mdat"]);if(i.length===0){n(new Error("Could not parse IMSC1 mdat"));return}const s=i.map(o=>Nn(o)),a=iM(e.baseTime,1,e.timescale);try{s.forEach(o=>r(zM(o,a)))}catch(o){n(o)}}function zM(t,e){const i=new DOMParser().parseFromString(t,"text/xml").getElementsByTagName("tt")[0];if(!i)throw new Error("Invalid ttml");const s={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},a=Object.keys(s).reduce((d,f)=>(d[f]=i.getAttribute(`ttp:${f}`)||s[f],d),{}),o=i.getAttribute("xml:space")!=="preserve",l=ey(Mf(i,"styling","style")),u=ey(Mf(i,"layout","region")),c=Mf(i,"body","[begin]");return[].map.call(c,d=>{const f=sw(d,o);if(!f||!d.hasAttribute("begin"))return null;const m=Ff(d.getAttribute("begin"),a),h=Ff(d.getAttribute("dur"),a);let p=Ff(d.getAttribute("end"),a);if(m===null)throw ty(d);if(p===null){if(h===null)throw ty(d);p=m+h}const v=new Bm(m-e,p-e,f);v.id=$m(v.startTime,v.endTime,v.text);const g=u[d.getAttribute("region")],y=l[d.getAttribute("style")],x=HM(g,y,l),{textAlign:S}=x;if(S){const T=GM[S];T&&(v.lineAlign=T),v.align=S}return It(v,x),v}).filter(d=>d!==null)}function Mf(t,e,r){const n=t.getElementsByTagName(e)[0];return n?[].slice.call(n.querySelectorAll(r)):[]}function ey(t){return t.reduce((e,r)=>{const n=r.getAttribute("xml:id");return n&&(e[n]=r),e},{})}function sw(t,e){return[].slice.call(t.childNodes).reduce((r,n,i)=>{var s;return n.nodeName==="br"&&i?r+` +`:(s=n.childNodes)!=null&&s.length?sw(n,e):e?r+n.textContent.trim().replace(/\s+/g," "):r+n.textContent},"")}function HM(t,e,r){const n="http://www.w3.org/ns/ttml#styling";let i=null;const s=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],a=t!=null&&t.hasAttribute("style")?t.getAttribute("style"):null;return a&&r.hasOwnProperty(a)&&(i=r[a]),s.reduce((o,l)=>{const u=Nf(e,n,l)||Nf(t,n,l)||Nf(i,n,l);return u&&(o[l]=u),o},{})}function Nf(t,e,r){return t&&t.hasAttributeNS(e,r)?t.getAttributeNS(e,r):null}function ty(t){return new Error(`Could not parse ttml timestamp ${t}`)}function Ff(t,e){if(!t)return null;let r=ew(t);return r===null&&(nw.test(t)?r=WM(t,e):iw.test(t)&&(r=KM(t,e))),r}function WM(t,e){const r=nw.exec(t),n=(r[4]|0)+(r[5]|0)/e.subFrameRate;return(r[1]|0)*3600+(r[2]|0)*60+(r[3]|0)+n/e.frameRate}function KM(t,e){const r=iw.exec(t),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/e.frameRate;case"t":return n/e.tickRate}return n}class YM{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=ny(),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(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.on(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.on(w.FRAG_LOADING,this.onFragLoading,this),e.on(w.FRAG_LOADED,this.onFragLoaded,this),e.on(w.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.on(w.FRAG_DECRYPTED,this.onFragDecrypted,this),e.on(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.on(w.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.on(w.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:e}=this;e.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this),e.off(w.MEDIA_DETACHING,this.onMediaDetaching,this),e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(w.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),e.off(w.FRAG_LOADING,this.onFragLoading,this),e.off(w.FRAG_LOADED,this.onFragLoaded,this),e.off(w.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),e.off(w.FRAG_DECRYPTED,this.onFragDecrypted,this),e.off(w.INIT_PTS_FOUND,this.onInitPtsFound,this),e.off(w.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),e.off(w.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){if(this.config.enableCEA708Captions&&(!this.cea608Parser1||!this.cea608Parser2)){const e=new lu(this,"textTrack1"),r=new lu(this,"textTrack2"),n=new lu(this,"textTrack3"),i=new lu(this,"textTrack4");this.cea608Parser1=new Qv(1,e,r),this.cea608Parser2=new Qv(3,n,i)}}addCues(e,r,n,i,s){let a=!1;for(let o=s.length;o--;){const l=s[o],u=qM(l[0],l[1],r,n);if(u>=0&&(l[0]=Math.min(l[0],r),l[1]=Math.max(l[1],n),a=!0,u/(n-r)>.5))return}if(a||s.push([r,n]),this.config.renderTextTracksNatively){const o=this.captionsTracks[e];this.Cues.newCue(o,r,n,i)}else{const o=this.Cues.newCue(null,r,n,i);this.hls.trigger(w.CUES_PARSED,{type:"captions",cues:o,track:e})}}onInitPtsFound(e,{frag:r,id:n,initPTS:i,timescale:s}){const{unparsedVttFrags:a}=this;n==="main"&&(this.initPTS[r.cc]={baseTime:i,timescale:s}),a.length&&(this.unparsedVttFrags=[],a.forEach(o=>{this.onFragLoaded(w.FRAG_LOADED,o)}))}getExistingTrack(e,r){const{media:n}=this;if(n)for(let i=0;i{ta(e[r]),delete e[r]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=ny(),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 r=e.textTracks;if(r)for(let n=0;ns.textCodec===Of);if(this.config.enableWebVTT||i&&this.config.enableIMSC1){if(ZT(this.tracks,n)){this.tracks=n;return}if(this.textTracks=[],this.tracks=n,this.config.renderTextTracksNatively){const a=this.media,o=a?Pu(a.textTracks):null;if(this.tracks.forEach((l,u)=>{let c;if(o){let d=null;for(let f=0;fu!==null).map(u=>u.label);l.length&&U.warn(`Media element contains unused subtitle tracks: ${l.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const a=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(w.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}}}onManifestLoaded(e,r){this.config.enableCEA708Captions&&r.captions&&r.captions.forEach(n=>{const i=/(?:CC|SERVICE)([1-4])/.exec(n.instreamId);if(!i)return;const s=`textTrack${i[1]}`,a=this.captionsProperties[s];a&&(a.label=n.name,n.lang&&(a.languageCode=n.lang),a.media=n)})}closedCaptionsForLevel(e){const r=this.hls.levels[e.level];return r==null?void 0:r.attrs["CLOSED-CAPTIONS"]}onFragLoading(e,r){if(this.enabled&&r.frag.type===we.MAIN){var n,i;const{cea608Parser1:s,cea608Parser2:a,lastSn:o}=this,{cc:l,sn:u}=r.frag,c=(n=(i=r.part)==null?void 0:i.index)!=null?n:-1;s&&a&&(u!==o+1||u===o&&c!==this.lastPartIndex+1||l!==this.lastCc)&&(s.reset(),a.reset()),this.lastCc=l,this.lastSn=u,this.lastPartIndex=c}}onFragLoaded(e,r){const{frag:n,payload:i}=r;if(n.type===we.SUBTITLE)if(i.byteLength){const s=n.decryptdata,a="stats"in r;if(s==null||!s.encrypted||a){const o=this.tracks[n.level],l=this.vttCCs;l[n.cc]||(l[n.cc]={start:n.start,prevCC:this.prevCC,new:!0},this.prevCC=n.cc),o&&o.textCodec===Of?this._parseIMSC1(n,i):this._parseVTTs(r)}}else this.hls.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:new Error("Empty subtitle payload")})}_parseIMSC1(e,r){const n=this.hls;Jv(r,this.initPTS[e.cc],i=>{this._appendCues(i,e.level),n.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:e})},i=>{U.log(`Failed to parse IMSC1: ${i}`),n.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:e,error:i})})}_parseVTTs(e){var r;const{frag:n,payload:i}=e,{initPTS:s,unparsedVttFrags:a}=this,o=s.length-1;if(!s[n.cc]&&o===-1){a.push(e);return}const l=this.hls,u=(r=n.initSegment)!=null&&r.data?Jr(n.initSegment.data,new Uint8Array(i)):i;VM(u,this.initPTS[n.cc],this.vttCCs,n.cc,n.start,c=>{this._appendCues(c,n.level),l.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n})},c=>{const d=c.message==="Missing initPTS for VTT MPEGTS";d?a.push(e):this._fallbackToIMSC1(n,i),U.log(`Failed to parse VTT cue: ${c}`),!(d&&o>n.cc)&&l.trigger(w.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,error:c})})}_fallbackToIMSC1(e,r){const n=this.tracks[e.level];n.textCodec||Jv(r,this.initPTS[e.cc],()=>{n.textCodec=Of,this._parseIMSC1(e,r)},()=>{n.textCodec="wvtt"})}_appendCues(e,r){const n=this.hls;if(this.config.renderTextTracksNatively){const i=this.textTracks[r];if(!i||i.mode==="disabled")return;e.forEach(s=>AT(i,s))}else{const i=this.tracks[r];if(!i)return;const s=i.default?"default":"subtitles"+r;n.trigger(w.CUES_PARSED,{type:"subtitles",cues:e,track:s})}}onFragDecrypted(e,r){const{frag:n}=r;n.type===we.SUBTITLE&&this.onFragLoaded(w.FRAG_LOADED,r)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(e,r){this.initCea608Parsers();const{cea608Parser1:n,cea608Parser2:i}=this;if(!this.enabled||!n||!i)return;const{frag:s,samples:a}=r;if(!(s.type===we.MAIN&&this.closedCaptionsForLevel(s)==="NONE"))for(let o=0;oqh(o[l],r,n))}if(this.config.renderTextTracksNatively&&r===0&&i!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(l=>qh(o[l],r,i))}}}extractCea608Data(e){const r=[[],[]],n=e[0]&31;let i=2;for(let s=0;sthis.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=r.autoLevelCapping}}}getMaxLevel(e){const r=this.hls.levels;if(!r.length)return-1;const n=r.filter((i,s)=>this.isLevelAllowed(i)&&s<=e);return this.clientRect=null,jm.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 e=this.media,r={width:0,height:0};if(e){const n=e.getBoundingClientRect();r.width=n.width,r.height=n.height,!r.width&&!r.height&&(r.width=n.right-n.left||e.width||0,r.height=n.bottom-n.top||e.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 e=1;if(!this.hls.config.ignoreDevicePixelRatio)try{e=self.devicePixelRatio}catch{}return e}isLevelAllowed(e){return!this.restrictedLevels.some(n=>e.bitrate===n.bitrate&&e.width===n.width&&e.height===n.height)}static getMaxLevelByMediaSize(e,r,n){if(!(e!=null&&e.length))return-1;const i=(o,l)=>l?o.width!==l.width||o.height!==l.height:!0;let s=e.length-1;const a=Math.max(r,n);for(let o=0;o=a||l.height>=a)&&i(l,e[o+1])){s=o;break}}return s}}class XM{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(w.MEDIA_ATTACHING,this.onMediaAttaching,this)}unregisterListeners(){this.hls.off(w.MEDIA_ATTACHING,this.onMediaAttaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(e,r){const n=this.hls.config;if(n.capLevelOnFPSDrop){const i=r.media instanceof self.HTMLVideoElement?r.media:null;this.media=i,i&&typeof i.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),n.fpsDroppedMonitoringPeriod)}}checkFPS(e,r,n){const i=performance.now();if(r){if(this.lastTime){const s=i-this.lastTime,a=n-this.lastDroppedFrames,o=r-this.lastDecodedFrames,l=1e3*a/s,u=this.hls;if(u.trigger(w.FPS_DROP,{currentDropped:a,currentDecoded:o,totalDroppedFrames:n}),l>0&&a>u.config.fpsDroppedMonitoringThreshold*o){let c=u.currentLevel;U.warn("drop FPS ratio greater than max allowed value for currentLevel: "+c),c>0&&(u.autoLevelCapping===-1||u.autoLevelCapping>=c)&&(c=c-1,u.trigger(w.FPS_DROP_LEVEL_CAPPING,{level:c,droppedLevel:u.currentLevel}),u.autoLevelCapping=c,this.streamController.nextLevelSwitch())}}this.lastTime=i,this.lastDroppedFrames=n,this.lastDecodedFrames=r}}checkFPSInterval(){const e=this.media;if(e)if(this.isVideoPlaybackQualityAvailable){const r=e.getVideoPlaybackQuality();this.checkFPS(e,r.totalVideoFrames,r.droppedVideoFrames)}else this.checkFPS(e,e.webkitDecodedFrameCount,e.webkitDroppedFrameCount)}}const cu="[eme]";class fa{constructor(e){this.hls=void 0,this.config=void 0,this.media=null,this.keyFormatPromise=null,this.keySystemAccessPromises={},this._requestLicenseFailureCount=0,this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},this.setMediaKeysQueue=fa.CDMCleanupPromise?[fa.CDMCleanupPromise]:[],this.onMediaEncrypted=this._onMediaEncrypted.bind(this),this.onWaitingForKey=this._onWaitingForKey.bind(this),this.debug=U.debug.bind(U,cu),this.log=U.log.bind(U,cu),this.warn=U.warn.bind(U,cu),this.error=U.error.bind(U,cu),this.hls=e,this.config=e.config,this.registerListeners()}destroy(){this.unregisterListeners(),this.onMediaDetached();const e=this.config;e.requestMediaKeySystemAccessFunc=null,e.licenseXhrSetup=e.licenseResponseCallback=void 0,e.drmSystems=e.drmSystemOptions={},this.hls=this.onMediaEncrypted=this.onWaitingForKey=this.keyIdToKeySessionPromise=null,this.config=null}registerListeners(){this.hls.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(w.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(w.MANIFEST_LOADED,this.onManifestLoaded,this)}unregisterListeners(){this.hls.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(w.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(w.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(w.MANIFEST_LOADED,this.onManifestLoaded,this)}getLicenseServerUrl(e){const{drmSystems:r,widevineLicenseUrl:n}=this.config,i=r[e];if(i)return i.licenseUrl;if(e===ot.WIDEVINE&&n)return n;throw new Error(`no license server URL configured for key-system "${e}"`)}getServerCertificateUrl(e){const{drmSystems:r}=this.config,n=r[e];if(n)return n.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${e}"]`)}attemptKeySystemAccess(e){const r=this.hls.levels,n=(a,o,l)=>!!a&&l.indexOf(a)===o,i=r.map(a=>a.audioCodec).filter(n),s=r.map(a=>a.videoCodec).filter(n);return i.length+s.length===0&&s.push("avc1.42e01e"),new Promise((a,o)=>{const l=u=>{const c=u.shift();this.getMediaKeysPromise(c,i,s).then(d=>a({keySystem:c,mediaKeys:d})).catch(d=>{u.length?l(u):d instanceof zr?o(d):o(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_ACCESS,error:d,fatal:!0},d.message))})};l(e)})}requestMediaKeySystemAccess(e,r){const{requestMediaKeySystemAccessFunc:n}=this.config;if(typeof n!="function"){let i=`Configured requestMediaKeySystemAccess is not a function ${n}`;return fT===null&&self.location.protocol==="http:"&&(i=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(i))}return n(e,r)}getMediaKeysPromise(e,r,n){const i=rP(e,r,n,this.config.drmSystemOptions),s=this.keySystemAccessPromises[e];let a=s==null?void 0:s.keySystemAccess;if(!a){this.log(`Requesting encrypted media "${e}" key-system access with config: ${JSON.stringify(i)}`),a=this.requestMediaKeySystemAccess(e,i);const o=this.keySystemAccessPromises[e]={keySystemAccess:a};return a.catch(l=>{this.log(`Failed to obtain access to key-system "${e}": ${l}`)}),a.then(l=>{this.log(`Access for key-system "${l.keySystem}" obtained`);const u=this.fetchServerCertificate(e);return this.log(`Create media-keys for "${e}"`),o.mediaKeys=l.createMediaKeys().then(c=>(this.log(`Media-keys created for "${e}"`),u.then(d=>d?this.setMediaKeysServerCertificate(c,e,d):c))),o.mediaKeys.catch(c=>{this.error(`Failed to create media-keys for "${e}"}: ${c}`)}),o.mediaKeys})}return a.then(()=>s.mediaKeys)}createMediaKeySessionContext({decryptdata:e,keySystem:r,mediaKeys:n}){this.log(`Creating key-system session "${r}" keyId: ${bn.hexDump(e.keyId||[])}`);const i=n.createSession(),s={decryptdata:e,keySystem:r,mediaKeys:n,mediaKeysSession:i,keyStatus:"status-pending"};return this.mediaKeySessions.push(s),s}renewKeySession(e){const r=e.decryptdata;if(r.pssh){const n=this.createMediaKeySessionContext(e),i=this.getKeyIdString(r),s="cenc";this.keyIdToKeySessionPromise[i]=this.generateRequestWithPreferredKeySession(n,s,r.pssh,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(e)}getKeyIdString(e){if(!e)throw new Error("Could not read keyId of undefined decryptdata");if(e.keyId===null)throw new Error("keyId is null");return bn.hexDump(e.keyId)}updateKeySession(e,r){var n;const i=e.mediaKeysSession;return this.log(`Updating key-session "${i.sessionId}" for keyID ${bn.hexDump(((n=e.decryptdata)==null?void 0:n.keyId)||[])} + } (data length: ${r&&r.byteLength})`),i.update(r)}selectKeySystemFormat(e){const r=Object.keys(e.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${e.sn} ${e.type}: ${e.level}) key formats ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)),this.keyFormatPromise}getKeyFormatPromise(e){return new Promise((r,n)=>{const i=xf(this.config),s=e.map(uv).filter(a=>!!a&&i.indexOf(a)!==-1);return this.getKeySystemSelectionPromise(s).then(({keySystem:a})=>{const o=dv(a);o?r(o):n(new Error(`Unable to find format for key-system "${a}"`))}).catch(n)})}loadKey(e){const r=e.keyInfo.decryptdata,n=this.getKeyIdString(r),i=`(keyId: ${n} format: "${r.keyFormat}" method: ${r.method} uri: ${r.uri})`;this.log(`Starting session for key ${i}`);let s=this.keyIdToKeySessionPromise[n];return s||(s=this.keyIdToKeySessionPromise[n]=this.getKeySystemForKeyPromise(r).then(({keySystem:a,mediaKeys:o})=>(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${e.frag.sn} ${e.frag.type}: ${e.frag.level} using key ${i}`),this.attemptSetMediaKeys(a,o).then(()=>{this.throwIfDestroyed();const l=this.createMediaKeySessionContext({keySystem:a,mediaKeys:o,decryptdata:r});return this.generateRequestWithPreferredKeySession(l,"cenc",r.pssh,"playlist-key")}))),s.catch(a=>this.handleError(a))),s}throwIfDestroyed(e="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(e){this.hls&&(this.error(e.message),e instanceof zr?this.hls.trigger(w.ERROR,e.data):this.hls.trigger(w.ERROR,{type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_KEYS,error:e,fatal:!0}))}getKeySystemForKeyPromise(e){const r=this.getKeyIdString(e),n=this.keyIdToKeySessionPromise[r];if(!n){const i=uv(e.keyFormat),s=i?[i]:xf(this.config);return this.attemptKeySystemAccess(s)}return n}getKeySystemSelectionPromise(e){if(e.length||(e=xf(this.config)),e.length===0)throw new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${JSON.stringify({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(e)}_onMediaEncrypted(e){const{initDataType:r,initData:n}=e,i=`"${e.type}" event: init data type: "${r}"`;if(this.debug(i),n===null)return;let s,a;if(r==="sinf"&&this.config.drmSystems[ot.FAIRPLAY]){const d=Dt(new Uint8Array(n));try{const f=Am(JSON.parse(d).sinf),m=ST(new Uint8Array(f));if(!m)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");s=m.subarray(8,24),a=ot.FAIRPLAY}catch(f){this.warn(`${i} Failed to parse sinf: ${f}`);return}}else{const d=_P(n),f=d.filter(m=>m.systemId===ho.WIDEVINE)[0];if(!f){d.length===0||d.some(m=>!m.systemId)?this.warn(`${i} contains incomplete or invalid pssh data`):this.log(`ignoring ${i} for ${d.map(m=>cv(m.systemId)).join(",")} pssh data in favor of playlist keys`);return}if(a=cv(f.systemId),f.version===0&&f.data){const m=f.data.length-22;s=f.data.subarray(m,m+16)}}if(!a||!s)return;const o=bn.hexDump(s),{keyIdToKeySessionPromise:l,mediaKeySessions:u}=this;let c=l[o];for(let d=0;dthis.generateRequestWithPreferredKeySession(f,r,n,"encrypted-event-key-match"));break}}c||(c=l[o]=this.getKeySystemSelectionPromise([a]).then(({keySystem:d,mediaKeys:f})=>{var m;this.throwIfDestroyed();const h=new hl("ISO-23001-7",o,(m=dv(d))!=null?m:"");return h.pssh=new Uint8Array(n),h.keyId=s,this.attemptSetMediaKeys(d,f).then(()=>{this.throwIfDestroyed();const p=this.createMediaKeySessionContext({decryptdata:h,keySystem:d,mediaKeys:f});return this.generateRequestWithPreferredKeySession(p,r,n,"encrypted-event-no-match")})})),c.catch(d=>this.handleError(d))}_onWaitingForKey(e){this.log(`"${e.type}" event`)}attemptSetMediaKeys(e,r){const n=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${e}"`);const i=Promise.all(n).then(()=>{if(!this.media)throw new Error("Attempted to set mediaKeys without media element attached");return this.media.setMediaKeys(r)});return this.setMediaKeysQueue.push(i),i.then(()=>{this.log(`Media-keys set for "${e}"`),n.push(i),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(s=>n.indexOf(s)===-1)})}generateRequestWithPreferredKeySession(e,r,n,i){var s,a;const o=(s=this.config.drmSystems)==null||(a=s[e.keySystem])==null?void 0:a.generateRequest;if(o)try{const h=o.call(this.hls,r,n,e);if(!h)throw new Error("Invalid response from configured generateRequest filter");r=h.initDataType,n=e.decryptdata.pssh=h.initData?new Uint8Array(h.initData):null}catch(h){var l;if(this.warn(h.message),(l=this.hls)!=null&&l.config.debug)throw h}if(n===null)return this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(e);const u=this.getKeyIdString(e.decryptdata);this.log(`Generating key-session request for "${i}": ${u} (init data type: ${r} length: ${n?n.byteLength:null})`);const c=new Um,d=e._onmessage=h=>{const p=e.mediaKeysSession;if(!p){c.emit("error",new Error("invalid state"));return}const{messageType:v,message:g}=h;this.log(`"${v}" message event for session "${p.sessionId}" message size: ${g.byteLength}`),v==="license-request"||v==="license-renewal"?this.renewLicense(e,g).catch(y=>{this.handleError(y),c.emit("error",y)}):v==="license-release"?e.keySystem===ot.FAIRPLAY&&(this.updateKeySession(e,Kh("acknowledged")),this.removeSession(e)):this.warn(`unhandled media key message type "${v}"`)},f=e._onkeystatuseschange=h=>{if(!e.mediaKeysSession){c.emit("error",new Error("invalid state"));return}this.onKeyStatusChange(e);const v=e.keyStatus;c.emit("keyStatus",v),v==="expired"&&(this.warn(`${e.keySystem} expired for key ${u}`),this.renewKeySession(e))};e.mediaKeysSession.addEventListener("message",d),e.mediaKeysSession.addEventListener("keystatuseschange",f);const m=new Promise((h,p)=>{c.on("error",p),c.on("keyStatus",v=>{v.startsWith("usable")?h():v==="output-restricted"?p(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED,fatal:!1},"HDCP level output restricted")):v==="internal-error"?p(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_STATUS_INTERNAL_ERROR,fatal:!0},`key status changed to "${v}"`)):v==="expired"?p(new Error("key expired while generating request")):this.warn(`unhandled key status change "${v}"`)})});return e.mediaKeysSession.generateRequest(r,n).then(()=>{var h;this.log(`Request generated for key-session "${(h=e.mediaKeysSession)==null?void 0:h.sessionId}" keyId: ${u}`)}).catch(h=>{throw new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_NO_SESSION,error:h,fatal:!1},`Error generating key-session request: ${h}`)}).then(()=>m).catch(h=>{throw c.removeAllListeners(),this.removeSession(e),h}).then(()=>(c.removeAllListeners(),e))}onKeyStatusChange(e){e.mediaKeysSession.keyStatuses.forEach((r,n)=>{this.log(`key status change "${r}" for keyStatuses keyId: ${bn.hexDump("buffer"in n?new Uint8Array(n.buffer,n.byteOffset,n.byteLength):new Uint8Array(n))} session keyId: ${bn.hexDump(new Uint8Array(e.decryptdata.keyId||[]))} uri: ${e.decryptdata.uri}`),e.keyStatus=r})}fetchServerCertificate(e){const r=this.config,n=r.loader,i=new n(r),s=this.getServerCertificateUrl(e);return s?(this.log(`Fetching server certificate for "${e}"`),new Promise((a,o)=>{const l={responseType:"arraybuffer",url:s},u=r.certLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(f,m,h,p)=>{a(f.data)},onError:(f,m,h,p)=>{o(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:h,response:jt({url:l.url,data:void 0},f)},`"${e}" certificate request failed (${s}). Status: ${f.code} (${f.text})`))},onTimeout:(f,m,h)=>{o(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:h,response:{url:l.url,data:void 0}},`"${e}" certificate request timed out (${s})`))},onAbort:(f,m,h)=>{o(new Error("aborted"))}};i.load(l,c,d)})):Promise.resolve()}setMediaKeysServerCertificate(e,r,n){return new Promise((i,s)=>{e.setServerCertificate(n).then(a=>{this.log(`setServerCertificate ${a?"success":"not supported by CDM"} (${n==null?void 0:n.byteLength}) on "${r}"`),i(e)}).catch(a=>{s(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:a,fatal:!0},a.message))})})}renewLicense(e,r){return this.requestLicense(e,new Uint8Array(r)).then(n=>this.updateKeySession(e,new Uint8Array(n)).catch(i=>{throw new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_SESSION_UPDATE_FAILED,error:i,fatal:!0},i.message)}))}unpackPlayReadyKeyMessage(e,r){const n=String.fromCharCode.apply(null,new Uint16Array(r.buffer));if(!n.includes("PlayReadyKeyMessage"))return e.setRequestHeader("Content-Type","text/xml; charset=utf-8"),r;const i=new DOMParser().parseFromString(n,"application/xml"),s=i.querySelectorAll("HttpHeader");if(s.length>0){let c;for(let d=0,f=s.length;d in key message");return Kh(atob(u))}setupLicenseXHR(e,r,n,i){const s=this.config.licenseXhrSetup;return s?Promise.resolve().then(()=>{if(!n.decryptdata)throw new Error("Key removed");return s.call(this.hls,e,r,n,i)}).catch(a=>{if(!n.decryptdata)throw a;return e.open("POST",r,!0),s.call(this.hls,e,r,n,i)}).then(a=>(e.readyState||e.open("POST",r,!0),{xhr:e,licenseChallenge:a||i})):(e.open("POST",r,!0),Promise.resolve({xhr:e,licenseChallenge:i}))}requestLicense(e,r){const n=this.config.keyLoadPolicy.default;return new Promise((i,s)=>{const a=this.getLicenseServerUrl(e.keySystem);this.log(`Sending license request to URL: ${a}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!e.mediaKeysSession)return s(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let l=o.response;this.log(`License received ${l instanceof ArrayBuffer?l.byteLength:l}`);const u=this.config.licenseResponseCallback;if(u)try{l=u.call(this.hls,o,a,e)}catch(c){this.error(c)}i(l)}else{const l=n.errorRetry,u=l?l.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>u||o.status>=400&&o.status<500)s(new zr({type:_e.KEY_SYSTEM_ERROR,details:z.KEY_SYSTEM_LICENSE_REQUEST_FAILED,fatal:!0,networkDetails:o,response:{url:a,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${a}). Status: ${o.status} (${o.statusText})`));else{const c=u-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${c} attempts left`),this.requestLicense(e,r).then(i,s)}}},e.licenseXhr&&e.licenseXhr.readyState!==XMLHttpRequest.DONE&&e.licenseXhr.abort(),e.licenseXhr=o,this.setupLicenseXHR(o,a,e,r).then(({xhr:l,licenseChallenge:u})=>{e.keySystem==ot.PLAYREADY&&(u=this.unpackPlayReadyKeyMessage(l,u)),l.send(u)})})}onMediaAttached(e,r){if(!this.config.emeEnabled)return;const n=r.media;this.media=n,n.addEventListener("encrypted",this.onMediaEncrypted),n.addEventListener("waitingforkey",this.onWaitingForKey)}onMediaDetached(){const e=this.media,r=this.mediaKeySessions;e&&(e.removeEventListener("encrypted",this.onMediaEncrypted),e.removeEventListener("waitingforkey",this.onWaitingForKey),this.media=null),this._requestLicenseFailureCount=0,this.setMediaKeysQueue=[],this.mediaKeySessions=[],this.keyIdToKeySessionPromise={},hl.clearKeyUriToKeyIdMap();const n=r.length;fa.CDMCleanupPromise=Promise.all(r.map(i=>this.removeSession(i)).concat(e==null?void 0:e.setMediaKeys(null).catch(i=>{this.log(`Could not clear media keys: ${i}`)}))).then(()=>{n&&(this.log("finished closing key sessions and clearing media keys"),r.length=0)}).catch(i=>{this.log(`Could not close sessions and clear media keys: ${i}`)})}onManifestLoading(){this.keyFormatPromise=null}onManifestLoaded(e,{sessionKeys:r}){if(!(!r||!this.config.emeEnabled)&&!this.keyFormatPromise){const n=r.reduce((i,s)=>(i.indexOf(s.keyFormat)===-1&&i.push(s.keyFormat),i),[]);this.log(`Selecting key-system from session-keys ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)}}removeSession(e){const{mediaKeysSession:r,licenseXhr:n}=e;if(r){this.log(`Remove licenses and keys and close session ${r.sessionId}`),e._onmessage&&(r.removeEventListener("message",e._onmessage),e._onmessage=void 0),e._onkeystatuseschange&&(r.removeEventListener("keystatuseschange",e._onkeystatuseschange),e._onkeystatuseschange=void 0),n&&n.readyState!==XMLHttpRequest.DONE&&n.abort(),e.mediaKeysSession=e.decryptdata=e.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(e);return i>-1&&this.mediaKeySessions.splice(i,1),r.remove().catch(s=>{this.log(`Could not remove session: ${s}`)}).then(()=>r.close()).catch(s=>{this.log(`Could not close session: ${s}`)})}}}fa.CDMCleanupPromise=void 0;class zr extends Error{constructor(e,r){super(r),this.data=void 0,e.error||(e.error=new Error(r)),this.data=e,e.err=e.error}}var Xt;(function(t){t.MANIFEST="m",t.AUDIO="a",t.VIDEO="v",t.MUXED="av",t.INIT="i",t.CAPTION="c",t.TIMED_TEXT="tt",t.KEY="k",t.OTHER="o"})(Xt||(Xt={}));var np;(function(t){t.DASH="d",t.HLS="h",t.SMOOTH="s",t.OTHER="o"})(np||(np={}));var os;(function(t){t.OBJECT="CMCD-Object",t.REQUEST="CMCD-Request",t.SESSION="CMCD-Session",t.STATUS="CMCD-Status"})(os||(os={}));const ZM={[os.OBJECT]:["br","d","ot","tb"],[os.REQUEST]:["bl","dl","mtp","nor","nrr","su"],[os.SESSION]:["cid","pr","sf","sid","st","v"],[os.STATUS]:["bs","rtp"]};class Da{constructor(e,r){this.value=void 0,this.params=void 0,Array.isArray(e)&&(e=e.map(n=>n instanceof Da?n:new Da(n))),this.value=e,this.params=r}}class ow{constructor(e){this.description=void 0,this.description=e}}const QM="Dict";function JM(t){return Array.isArray(t)?JSON.stringify(t):t instanceof Map?"Map{}":t instanceof Set?"Set{}":typeof t=="object"?JSON.stringify(t):String(t)}function eN(t,e,r,n){return new Error(`failed to ${t} "${JM(e)}" as ${r}`,{cause:n})}const iy="Bare Item",tN="Boolean",rN="Byte Sequence",nN="Decimal",iN="Integer";function sN(t){return t<-999999999999999||99999999999999912)throw Bn(t,nN);const r=e.toString();return r.includes(".")?r:`${r}.0`}const pN="String";function mN(t){if(aN.test(t))throw Bn(t,pN);return`"${t.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function gN(t){return t.description||t.toString().slice(7,-1)}function sy(t){const e=gN(t);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(e)===!1)throw Bn(e,oN);return e}function ip(t){switch(typeof t){case"number":if(!pe(t))throw Bn(t,iy);return Number.isInteger(t)?lw(t):hN(t);case"string":return mN(t);case"symbol":return sy(t);case"boolean":return uN(t);case"object":if(t instanceof Date)return fN(t);if(t instanceof Uint8Array)return dN(t);if(t instanceof ow)return sy(t);default:throw Bn(t,iy)}}function sp(t){if(/^[a-z*][a-z0-9\-_.*]*$/.test(t)===!1)throw Bn(t,lN);return t}function Vm(t){return t==null?"":Object.entries(t).map(([e,r])=>r===!0?`;${sp(e)}`:`;${sp(e)}=${ip(r)}`).join("")}function cw(t){return t instanceof Da?`${ip(t.value)}${Vm(t.params)}`:ip(t)}function vN(t){return`(${t.value.map(cw).join(" ")})${Vm(t.params)}`}function yN(t,e={whitespace:!0}){if(typeof t!="object")throw Bn(t,QM);const r=t instanceof Map?t.entries():Object.entries(t),n=e!=null&&e.whitespace?" ":"";return Array.from(r).map(([i,s])=>{s instanceof Da||(s=new Da(s));let a=sp(i);return s.value===!0?a+=Vm(s.params):(a+="=",Array.isArray(s.value)?a+=vN(s):a+=cw(s)),a}).join(`,${n}`)}function xN(t,e){return yN(t,e)}const SN=t=>t==="ot"||t==="sf"||t==="st",EN=t=>typeof t=="number"?pe(t):t!=null&&t!==""&&t!==!1;function TN(t,e){const r=new URL(t),n=new URL(e);if(r.origin!==n.origin)return t;const i=r.pathname.split("/").slice(1),s=n.pathname.split("/").slice(1,-1);for(;i[0]===s[0];)i.shift(),s.shift();for(;s.length;)s.shift(),i.unshift("..");return i.join("/")}function wN(){try{return crypto.randomUUID()}catch{try{const e=URL.createObjectURL(new Blob),r=e.toString();return URL.revokeObjectURL(e),r.slice(r.lastIndexOf("/")+1)}catch{let r=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,i=>{const s=(r+Math.random()*16)%16|0;return r=Math.floor(r/16),(i=="x"?s:s&3|8).toString(16)})}}}const Bu=t=>Math.round(t),bN=(t,e)=>(e!=null&&e.baseUrl&&(t=TN(t,e.baseUrl)),encodeURIComponent(t)),du=t=>Bu(t/100)*100,LN={br:Bu,d:Bu,bl:du,dl:du,mtp:du,nor:bN,rtp:du,tb:Bu};function AN(t,e){const r={};if(t==null||typeof t!="object")return r;const n=Object.keys(t).sort(),i=It({},LN,e==null?void 0:e.formatters),s=e==null?void 0:e.filter;return n.forEach(a=>{if(s!=null&&s(a))return;let o=t[a];const l=i[a];l&&(o=l(o,e)),!(a==="v"&&o===1)&&(a=="pr"&&o===1||EN(o)&&(SN(a)&&typeof o=="string"&&(o=new ow(o)),r[a]=o))}),r}function dw(t,e={}){return t?xN(AN(t,e),It({whitespace:!1},e)):""}function _N(t,e={}){if(!t)return{};const r=Object.entries(t),n=Object.entries(ZM).concat(Object.entries((e==null?void 0:e.customHeaderMap)||{})),i=r.reduce((s,a)=>{var o,l;const[u,c]=a,d=((o=n.find(f=>f[1].includes(u)))==null?void 0:o[0])||os.REQUEST;return(l=s[d])!=null||(s[d]={}),s[d][u]=c,s},{});return Object.entries(i).reduce((s,[a,o])=>(s[a]=dw(o,e),s),{})}function CN(t,e,r){return It(t,_N(e,r))}const RN="CMCD";function IN(t,e={}){if(!t)return"";const r=dw(t,e);return`${RN}=${encodeURIComponent(r)}`}const ay=/CMCD=[^&#]+/;function kN(t,e,r){const n=IN(e,r);if(!n)return t;if(ay.test(t))return t.replace(ay,n);const i=t.includes("?")?"&":"?";return`${t}${i}${n}`}class DN{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=i=>{try{this.apply(i,{ot:Xt.MANIFEST,su:!this.initialized})}catch(s){U.warn("Could not generate manifest CMCD data.",s)}},this.applyFragmentData=i=>{try{const s=i.frag,a=this.hls.levels[s.level],o=this.getObjectType(s),l={d:s.duration*1e3,ot:o};(o===Xt.VIDEO||o===Xt.AUDIO||o==Xt.MUXED)&&(l.br=a.bitrate/1e3,l.tb=this.getTopBandwidth(o)/1e3,l.bl=this.getBufferLength(o)),this.apply(i,l)}catch(s){U.warn("Could not generate segment CMCD data.",s)}},this.hls=e;const r=this.config=e.config,{cmcd:n}=r;n!=null&&(r.pLoader=this.createPlaylistLoader(),r.fLoader=this.createFragmentLoader(),this.sid=n.sessionId||wN(),this.cid=n.contentId,this.useHeaders=n.useHeaders===!0,this.includeKeys=n.includeKeys,this.registerListeners())}registerListeners(){const e=this.hls;e.on(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.on(w.MEDIA_DETACHED,this.onMediaDetached,this),e.on(w.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const e=this.hls;e.off(w.MEDIA_ATTACHED,this.onMediaAttached,this),e.off(w.MEDIA_DETACHED,this.onMediaDetached,this),e.off(w.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=null}onMediaAttached(e,r){this.media=r.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,r){var n,i;this.audioBuffer=(n=r.tracks.audio)==null?void 0:n.buffer,this.videoBuffer=(i=r.tracks.video)==null?void 0:i.buffer}createData(){var e;return{v:1,sf:np.HLS,sid:this.sid,cid:this.cid,pr:(e=this.media)==null?void 0:e.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(e,r={}){It(r,this.createData());const n=r.ot===Xt.INIT||r.ot===Xt.VIDEO||r.ot===Xt.MUXED;this.starved&&n&&(r.bs=!0,r.su=!0,this.starved=!1),r.su==null&&(r.su=this.buffering);const{includeKeys:i}=this;i&&(r=Object.keys(r).reduce((s,a)=>(i.includes(a)&&(s[a]=r[a]),s),{})),this.useHeaders?(e.headers||(e.headers={}),CN(e.headers,r)):e.url=kN(e.url,r)}getObjectType(e){const{type:r}=e;if(r==="subtitle")return Xt.TIMED_TEXT;if(e.sn==="initSegment")return Xt.INIT;if(r==="audio")return Xt.AUDIO;if(r==="main")return this.hls.audioTracks.length?Xt.VIDEO:Xt.MUXED}getTopBandwidth(e){let r=0,n;const i=this.hls;if(e===Xt.AUDIO)n=i.audioTracks;else{const s=i.maxAutoLevel,a=s>-1?s+1:i.levels.length;n=i.levels.slice(0,a)}for(const s of n)s.bitrate>r&&(r=s.bitrate);return r>0?r:NaN}getBufferLength(e){const r=this.hls.media,n=e===Xt.AUDIO?this.audioBuffer:this.videoBuffer;return!n||!r?NaN:at.bufferInfo(n,r.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:e}=this.config,r=this.applyPlaylistData,n=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new n(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,a,o){r(s),this.loader.load(s,a,o)}}}createFragmentLoader(){const{fLoader:e}=this.config,r=this.applyFragmentData,n=e||this.config.loader;return class{constructor(s){this.loader=void 0,this.loader=new n(s)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(s,a,o){r(s),this.loader.load(s,a,o)}}}}const PN=3e5;class ON{constructor(e){this.hls=void 0,this.log=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.log=U.log.bind(U,"[content-steering]:"),this.registerListeners()}registerListeners(){const e=this.hls;e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(w.MANIFEST_PARSED,this.onManifestParsed,this),e.on(w.ERROR,this.onError,this)}unregisterListeners(){const e=this.hls;e&&(e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(w.MANIFEST_PARSED,this.onManifestParsed,this),e.off(w.ERROR,this.onError,this))}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 r=this.levels;r&&(this.levels=r.filter(n=>n!==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,r){const{contentSteering:n}=r;n!==null&&(this.pathwayId=n.pathwayId,this.uri=n.uri,this.started&&this.startLoad())}onManifestParsed(e,r){this.audioTracks=r.audioTracks,this.subtitleTracks=r.subtitleTracks}onError(e,r){const{errorAction:n}=r;if((n==null?void 0:n.action)===zt.SendAlternateToPenaltyBox&&n.flags===sn.MoveAllAlternatesMatchingHost){const i=this.levels;let s=this.pathwayPriority,a=this.pathwayId;if(r.context){const{groupId:o,pathwayId:l,type:u}=r.context;o&&i?a=this.getPathwayForGroupId(o,u,a):l&&(a=l)}a in this.penalizedPathways||(this.penalizedPathways[a]=performance.now()),!s&&i&&(s=i.reduce((o,l)=>(o.indexOf(l.pathwayId)===-1&&o.push(l.pathwayId),o),[])),s&&s.length>1&&(this.updatePathwayPriority(s),n.resolved=this.pathwayId!==a),n.resolved||U.warn(`Could not resolve ${r.details} ("${r.error.message}") with content-steering for Pathway: ${a} levels: ${i&&i.length} priorities: ${JSON.stringify(s)} penalized: ${JSON.stringify(this.penalizedPathways)}`)}}filterParsedLevels(e){this.levels=e;let r=this.getLevelsForPathway(this.pathwayId);if(r.length===0){const n=e[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${n}"`),r=this.getLevelsForPathway(n),this.pathwayId=n}return r.length!==e.length?(this.log(`Found ${r.length}/${e.length} levels in Pathway "${this.pathwayId}"`),r):e}getLevelsForPathway(e){return this.levels===null?[]:this.levels.filter(r=>e===r.pathwayId)}updatePathwayPriority(e){this.pathwayPriority=e;let r;const n=this.penalizedPathways,i=performance.now();Object.keys(n).forEach(s=>{i-n[s]>PN&&delete n[s]});for(let s=0;s0){this.log(`Setting Pathway to "${a}"`),this.pathwayId=a,IT(r),this.hls.trigger(w.LEVELS_UPDATED,{levels:r});const u=this.hls.levels[o];l&&u&&this.levels&&(u.attrs["STABLE-VARIANT-ID"]!==l.attrs["STABLE-VARIANT-ID"]&&u.bitrate!==l.bitrate&&this.log(`Unstable Pathways change from bitrate ${l.bitrate} to ${u.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(e,r,n){const i=this.getLevelsForPathway(n).concat(this.levels||[]);for(let s=0;s{const{ID:a,"BASE-ID":o,"URI-REPLACEMENT":l}=s;if(r.some(c=>c.pathwayId===a))return;const u=this.getLevelsForPathway(o).map(c=>{const d=new gt(c.attrs);d["PATHWAY-ID"]=a;const f=d.AUDIO&&`${d.AUDIO}_clone_${a}`,m=d.SUBTITLES&&`${d.SUBTITLES}_clone_${a}`;f&&(n[d.AUDIO]=f,d.AUDIO=f),m&&(i[d.SUBTITLES]=m,d.SUBTITLES=m);const h=fw(c.uri,d["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",l),p=new Ia({attrs:d,audioCodec:c.audioCodec,bitrate:c.bitrate,height:c.height,name:c.name,url:h,videoCodec:c.videoCodec,width:c.width});if(c.audioGroups)for(let v=1;v{this.log(`Loaded steering manifest: "${i}"`);const h=c.data;if(h.VERSION!==1){this.log(`Steering VERSION ${h.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=h.TTL;const{"RELOAD-URI":p,"PATHWAY-CLONES":v,"PATHWAY-PRIORITY":g}=h;if(p)try{this.uri=new self.URL(p,i).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${p}`);return}this.scheduleRefresh(this.uri||f.url),v&&this.clonePathways(v);const y={steeringManifest:h,url:i.toString()};this.hls.trigger(w.STEERING_MANIFEST_LOADED,y),g&&this.updatePathwayPriority(g)},onError:(c,d,f,m)=>{if(this.log(`Error loading steering manifest: ${c.code} ${c.text} (${d.url})`),this.stopLoad(),c.code===410){this.enabled=!1,this.log(`Steering manifest ${d.url} no longer available`);return}let h=this.timeToLoad*1e3;if(c.code===429){const p=this.loader;if(typeof(p==null?void 0:p.getResponseHeader)=="function"){const v=p.getResponseHeader("Retry-After");v&&(h=parseFloat(v)*1e3)}this.log(`Steering manifest ${d.url} rate limited`);return}this.scheduleRefresh(this.uri||d.url,h)},onTimeout:(c,d,f)=>{this.log(`Timeout loading steering manifest (${d.url})`),this.scheduleRefresh(this.uri||d.url)}};this.log(`Requesting steering manifest: ${i}`),this.loader.load(s,l,u)}scheduleRefresh(e,r=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var n;const i=(n=this.hls)==null?void 0:n.media;if(i&&!i.ended){this.loadSteeringManifest(e);return}this.scheduleRefresh(e,this.timeToLoad*1e3)},r)}}function oy(t,e,r,n){t&&Object.keys(e).forEach(i=>{const s=t.filter(a=>a.groupId===i).map(a=>{const o=It({},a);return o.details=void 0,o.attrs=new gt(o.attrs),o.url=o.attrs.URI=fw(a.url,a.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",r),o.groupId=o.attrs["GROUP-ID"]=e[i],o.attrs["PATHWAY-ID"]=n,o});t.push(...s)})}function fw(t,e,r,n){const{HOST:i,PARAMS:s,[r]:a}=n;let o;e&&(o=a==null?void 0:a[e],o&&(t=o));const l=new self.URL(t);return i&&!o&&(l.host=i),s&&Object.keys(s).sort().forEach(u=>{u&&l.searchParams.set(u,s[u])}),l.href}const MN=/^age:\s*[\d.]+\s*$/im;class hw{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 Td,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,r,n){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=r,this.callbacks=n,this.loadInternal()}loadInternal(){const{config:e,context:r}=this;if(!e||!r)return;const n=this.loader=new self.XMLHttpRequest,i=this.stats;i.loading.first=0,i.loaded=0,i.aborted=!1;const s=this.xhrSetup;s?Promise.resolve().then(()=>{if(!(this.loader!==n||this.stats.aborted))return s(n,r.url)}).catch(a=>{if(!(this.loader!==n||this.stats.aborted))return n.open("GET",r.url,!0),s(n,r.url)}).then(()=>{this.loader!==n||this.stats.aborted||this.openAndSendXhr(n,r,e)}).catch(a=>{this.callbacks.onError({code:n.status,text:a.message},r,n,i)}):this.openAndSendXhr(n,r,e)}openAndSendXhr(e,r,n){e.readyState||e.open("GET",r.url,!0);const i=r.headers,{maxTimeToFirstByteMs:s,maxLoadTimeMs:a}=n.loadPolicy;if(i)for(const o in i)e.setRequestHeader(o,i[o]);r.rangeEnd&&e.setRequestHeader("Range","bytes="+r.rangeStart+"-"+(r.rangeEnd-1)),e.onreadystatechange=this.readystatechange.bind(this),e.onprogress=this.loadprogress.bind(this),e.responseType=r.responseType,self.clearTimeout(this.requestTimeout),n.timeout=s&&pe(s)?s:a,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),n.timeout),e.send()}readystatechange(){const{context:e,loader:r,stats:n}=this;if(!e||!r)return;const i=r.readyState,s=this.config;if(!n.aborted&&i>=2&&(n.loading.first===0&&(n.loading.first=Math.max(self.performance.now(),n.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-(n.loading.first-n.loading.start)))),i===4)){self.clearTimeout(this.requestTimeout),r.onreadystatechange=null,r.onprogress=null;const a=r.status,o=r.responseType!=="text";if(a>=200&&a<300&&(o&&r.response||r.responseText!==null)){n.loading.end=Math.max(self.performance.now(),n.loading.first);const l=o?r.response:r.responseText,u=r.responseType==="arraybuffer"?l.byteLength:l.length;if(n.loaded=n.total=u,n.bwEstimate=n.total*8e3/(n.loading.end-n.loading.first),!this.callbacks)return;const c=this.callbacks.onProgress;if(c&&c(n,e,l,r),!this.callbacks)return;const d={url:r.responseURL,data:l,code:a};this.callbacks.onSuccess(d,n,e,r)}else{const l=s.loadPolicy.errorRetry,u=n.retry,c={url:e.url,data:void 0,code:a};jc(l,u,!1,c)?this.retry(l):(U.error(`${a} while loading ${e.url}`),this.callbacks.onError({code:a,text:r.statusText},e,r,n))}}}loadtimeout(){if(!this.config)return;const e=this.config.loadPolicy.timeoutRetry,r=this.stats.retry;if(jc(e,r,!0))this.retry(e);else{var n;U.warn(`timeout while loading ${(n=this.context)==null?void 0:n.url}`);const i=this.callbacks;i&&(this.abortInternal(),i.onTimeout(this.stats,this.context,this.loader))}}retry(e){const{context:r,stats:n}=this;this.retryDelay=Rm(e,n.retry),n.retry++,U.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${r==null?void 0:r.url}, retrying ${n.retry}/${e.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(e){const r=this.stats;r.loaded=e.loaded,e.lengthComputable&&(r.total=e.total)}getCacheAge(){let e=null;if(this.loader&&MN.test(this.loader.getAllResponseHeaders())){const r=this.loader.getResponseHeader("age");e=r?parseFloat(r):null}return e}getResponseHeader(e){return this.loader&&new RegExp(`^${e}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(e):null}}function NN(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const FN=/(\d+)-(\d+)\/(\d+)/;class ly{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||jN,this.controller=new self.AbortController,this.stats=new Td}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,r,n){const i=this.stats;if(i.loading.start)throw new Error("Loader can only be used once.");i.loading.start=self.performance.now();const s=UN(e,this.controller.signal),a=n.onProgress,o=e.responseType==="arraybuffer",l=o?"byteLength":"length",{maxTimeToFirstByteMs:u,maxLoadTimeMs:c}=r.loadPolicy;this.context=e,this.config=r,this.callbacks=n,this.request=this.fetchSetup(e,s),self.clearTimeout(this.requestTimeout),r.timeout=u&&pe(u)?u:c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),n.onTimeout(i,e,this.response)},r.timeout),self.fetch(this.request).then(d=>{this.response=this.loader=d;const f=Math.max(self.performance.now(),i.loading.start);if(self.clearTimeout(this.requestTimeout),r.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.abortInternal(),n.onTimeout(i,e,this.response)},c-(f-i.loading.start)),!d.ok){const{status:m,statusText:h}=d;throw new VN(h||"fetch, bad network response",m,d)}return i.loading.first=f,i.total=$N(d.headers)||i.total,a&&pe(r.highWaterMark)?this.loadProgressively(d,i,e,r.highWaterMark,a):o?d.arrayBuffer():e.responseType==="json"?d.json():d.text()}).then(d=>{const f=this.response;if(!f)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),i.loading.end=Math.max(self.performance.now(),i.loading.first);const m=d[l];m&&(i.loaded=i.total=m);const h={url:f.url,data:d,code:f.status};a&&!pe(r.highWaterMark)&&a(i,e,d,f),n.onSuccess(h,i,e,f)}).catch(d=>{if(self.clearTimeout(this.requestTimeout),i.aborted)return;const f=d&&d.code||0,m=d?d.message:null;n.onError({code:f,text:m},e,d?d.details:null,i)})}getCacheAge(){let e=null;if(this.response){const r=this.response.headers.get("age");e=r?parseFloat(r):null}return e}getResponseHeader(e){return this.response?this.response.headers.get(e):null}loadProgressively(e,r,n,i=0,s){const a=new OT,o=e.body.getReader(),l=()=>o.read().then(u=>{if(u.done)return a.dataLength&&s(r,n,a.flush(),e),Promise.resolve(new ArrayBuffer(0));const c=u.value,d=c.length;return r.loaded+=d,d=i&&s(r,n,a.flush(),e)):s(r,n,c,e),l()}).catch(()=>Promise.reject());return l()}}function UN(t,e){const r={method:"GET",mode:"cors",credentials:"same-origin",signal:e,headers:new self.Headers(It({},t.headers))};return t.rangeEnd&&r.headers.set("Range","bytes="+t.rangeStart+"-"+String(t.rangeEnd-1)),r}function BN(t){const e=FN.exec(t);if(e)return parseInt(e[2])-parseInt(e[1])+1}function $N(t){const e=t.get("Content-Range");if(e){const n=BN(e);if(pe(n))return n}const r=t.get("Content-Length");if(r)return parseInt(r)}function jN(t,e){return new self.Request(t.url,e)}class VN extends Error{constructor(e,r,n){super(e),this.code=void 0,this.details=void 0,this.code=r,this.details=n}}const GN=/\s/,zN={newCue(t,e,r,n){const i=[];let s,a,o,l,u;const c=self.VTTCue||self.TextTrackCue;for(let f=0;f=16?l--:l++;const m=rw(u.trim()),h=$m(e,r,m);t!=null&&(d=t.cues)!=null&&d.getCueById(h)||(a=new c(e,r,m),a.id=h,a.line=f+1,a.align="left",a.position=10+Math.min(80,Math.floor(l*8/32)*10),i.push(a))}return t&&i.length&&(i.sort((f,m)=>f.line==="auto"||m.line==="auto"?0:f.line>8&&m.line>8?m.line-f.line:f.line-m.line),i.forEach(f=>AT(t,f))),i}},HN={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},pw=jt(jt({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,preferManagedMediaSource:!0,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,maxBufferSize:60*1e3*1e3,maxBufferHole:.1,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,maxFragLookUpTolerance:.25,liveSyncDurationCount:3,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,loader:hw,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:yO,bufferController:TM,capLevelController:jm,errorController:aO,fpsController:XM,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:fT,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableID3MetadataCues:!0,useMediaCapabilities:!0,certLoadPolicy:{default:HN},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}}},manifestLoadingTimeOut:1e4,manifestLoadingMaxRetry:1,manifestLoadingRetryDelay:1e3,manifestLoadingMaxRetryTimeout:64e3,levelLoadingTimeOut:1e4,levelLoadingMaxRetry:4,levelLoadingRetryDelay:1e3,levelLoadingMaxRetryTimeout:64e3,fragLoadingTimeOut:2e4,fragLoadingMaxRetry:6,fragLoadingRetryDelay:1e3,fragLoadingMaxRetryTimeout:64e3},WN()),{},{subtitleStreamController:yM,subtitleTrackController:SM,timelineController:YM,audioStreamController:gM,audioTrackController:vM,emeController:fa,cmcdController:DN,contentSteeringController:ON});function WN(){return{cueHandler:zN,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 KN(t,e){if((e.liveSyncDurationCount||e.liveMaxLatencyDurationCount)&&(e.liveSyncDuration||e.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(e.liveMaxLatencyDurationCount!==void 0&&(e.liveSyncDurationCount===void 0||e.liveMaxLatencyDurationCount<=e.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(e.liveMaxLatencyDuration!==void 0&&(e.liveSyncDuration===void 0||e.liveMaxLatencyDuration<=e.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=ap(t),n=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return n.forEach(s=>{const a=`${s==="level"?"playlist":s}LoadPolicy`,o=e[a]===void 0,l=[];i.forEach(u=>{const c=`${s}Loading${u}`,d=e[c];if(d!==void 0&&o){l.push(c);const f=r[a].default;switch(e[a]={default:f},u){case"TimeOut":f.maxLoadTimeMs=d,f.maxTimeToFirstByteMs=d;break;case"MaxRetry":f.errorRetry.maxNumRetry=d,f.timeoutRetry.maxNumRetry=d;break;case"RetryDelay":f.errorRetry.retryDelayMs=d,f.timeoutRetry.retryDelayMs=d;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=d,f.timeoutRetry.maxRetryDelayMs=d;break}}}),l.length&&U.warn(`hls.js config: "${l.join('", "')}" setting(s) are deprecated, use "${a}": ${JSON.stringify(e[a])}`)}),jt(jt({},r),e)}function ap(t){return t&&typeof t=="object"?Array.isArray(t)?t.map(ap):Object.keys(t).reduce((e,r)=>(e[r]=ap(t[r]),e),{}):t}function YN(t){const e=t.loader;e!==ly&&e!==hw?(U.log("[config]: Custom loader detected, cannot enable progressive streaming"),t.progressive=!1):NN()&&(t.loader=ly,t.progressive=!0,t.enableSoftwareAES=!0,U.log("[config]: Progressive streaming enabled, using FetchLoader"))}let Uf;class qN extends Im{constructor(e,r){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=r,this._registerListeners()}_registerListeners(){const{hls:e}=this;e.on(w.MANIFEST_LOADING,this.onManifestLoading,this),e.on(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.on(w.LEVEL_LOADED,this.onLevelLoaded,this),e.on(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.on(w.FRAG_BUFFERED,this.onFragBuffered,this),e.on(w.ERROR,this.onError,this)}_unregisterListeners(){const{hls:e}=this;e.off(w.MANIFEST_LOADING,this.onManifestLoading,this),e.off(w.MANIFEST_LOADED,this.onManifestLoaded,this),e.off(w.LEVEL_LOADED,this.onLevelLoaded,this),e.off(w.LEVELS_UPDATED,this.onLevelsUpdated,this),e.off(w.FRAG_BUFFERED,this.onFragBuffered,this),e.off(w.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(r=>{r.loadError=0,r.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,r){this.resetLevels()}onManifestLoaded(e,r){const n=this.hls.config.preferManagedMediaSource,i=[],s={},a={};let o=!1,l=!1,u=!1;r.levels.forEach(c=>{var d,f;const m=c.attrs;let{audioCodec:h,videoCodec:p}=c;((d=h)==null?void 0:d.indexOf("mp4a.40.34"))!==-1&&(Uf||(Uf=/chrome|firefox/i.test(navigator.userAgent)),Uf&&(c.audioCodec=h=void 0)),h&&(c.audioCodec=h=Uc(h,n)),((f=p)==null?void 0:f.indexOf("avc1"))===0&&(p=c.videoCodec=MP(p));const{width:v,height:g,unknownCodecs:y}=c;if(o||(o=!!(v&&g)),l||(l=!!p),u||(u=!!h),y!=null&&y.length||h&&!wf(h,"audio",n)||p&&!wf(p,"video",n))return;const{CODECS:x,"FRAME-RATE":S,"HDCP-LEVEL":T,"PATHWAY-ID":C,RESOLUTION:_,"VIDEO-RANGE":b}=m,A=`${`${C||"."}-`}${c.bitrate}-${_}-${S}-${x}-${b}-${T}`;if(s[A])if(s[A].uri!==c.url&&!c.attrs["PATHWAY-ID"]){const k=a[A]+=1;c.attrs["PATHWAY-ID"]=new Array(k+1).join(".");const O=new Ia(c);s[A]=O,i.push(O)}else s[A].addGroupId("audio",m.AUDIO),s[A].addGroupId("text",m.SUBTITLES);else{const k=new Ia(c);s[A]=k,a[A]=1,i.push(k)}}),this.filterAndSortMediaOptions(i,r,o,l,u)}filterAndSortMediaOptions(e,r,n,i,s){let a=[],o=[],l=e;if((n||i)&&s&&(l=l.filter(({videoCodec:h,videoRange:p,width:v,height:g})=>(!!h||!!(v&&g))&&YP(p))),l.length===0){Promise.resolve().then(()=>{if(this.hls){r.levels.length&&this.warn(`One or more CODECS in variant not supported: ${JSON.stringify(r.levels[0].attrs)}`);const h=new Error("no level with compatible codecs found in manifest");this.hls.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:r.url,error:h,reason:h.message})}});return}if(r.audioTracks){const{preferManagedMediaSource:h}=this.hls.config;a=r.audioTracks.filter(p=>!p.audioCodec||wf(p.audioCodec,"audio",h)),uy(a)}r.subtitles&&(o=r.subtitles,uy(o));const u=l.slice(0);l.sort((h,p)=>{if(h.attrs["HDCP-LEVEL"]!==p.attrs["HDCP-LEVEL"])return(h.attrs["HDCP-LEVEL"]||"")>(p.attrs["HDCP-LEVEL"]||"")?1:-1;if(n&&h.height!==p.height)return h.height-p.height;if(h.frameRate!==p.frameRate)return h.frameRate-p.frameRate;if(h.videoRange!==p.videoRange)return Bc.indexOf(h.videoRange)-Bc.indexOf(p.videoRange);if(h.videoCodec!==p.videoCodec){const v=gv(h.videoCodec),g=gv(p.videoCodec);if(v!==g)return g-v}if(h.uri===p.uri&&h.codecSet!==p.codecSet){const v=Fc(h.codecSet),g=Fc(p.codecSet);if(v!==g)return g-v}return h.averageBitrate!==p.averageBitrate?h.averageBitrate-p.averageBitrate:0});let c=u[0];if(this.steering&&(l=this.steering.filterParsedLevels(l),l.length!==u.length)){for(let h=0;hv&&v===pw.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=g)}break}const f=s&&!i,m={levels:l,audioTracks:a,subtitleTracks:o,sessionData:r.sessionData,sessionKeys:r.sessionKeys,firstLevel:this._firstLevel,stats:r.stats,audio:s,video:i,altAudio:!f&&a.some(h=>!!h.url)};this.hls.trigger(w.MANIFEST_PARSED,m),(this.hls.config.autoStartLoad||this.hls.forceStartLoad)&&this.hls.startLoad(this.hls.config.startPosition)}get levels(){return this._levels.length===0?null:this._levels}get level(){return this.currentLevelIndex}set level(e){const r=this._levels;if(r.length===0)return;if(e<0||e>=r.length){const c=new Error("invalid level idx"),d=e<0;if(this.hls.trigger(w.ERROR,{type:_e.OTHER_ERROR,details:z.LEVEL_SWITCH_ERROR,level:e,fatal:d,error:c,reason:c.message}),d)return;e=Math.min(e,r.length-1)}const n=this.currentLevelIndex,i=this.currentLevel,s=i?i.attrs["PATHWAY-ID"]:void 0,a=r[e],o=a.attrs["PATHWAY-ID"];if(this.currentLevelIndex=e,this.currentLevel=a,n===e&&a.details&&i&&s===o)return;this.log(`Switching to level ${e} (${a.height?a.height+"p ":""}${a.videoRange?a.videoRange+" ":""}${a.codecSet?a.codecSet+" ":""}@${a.bitrate})${o?" with Pathway "+o:""} from level ${n}${s?" with Pathway "+s:""}`);const l={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(w.LEVEL_SWITCHING,l);const u=a.details;if(!u||u.live){const c=this.switchParams(a.uri,i==null?void 0:i.details,u);this.loadPlaylist(c)}}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}onError(e,r){r.fatal||!r.context||r.context.type===He.LEVEL&&r.context.level===this.level&&this.checkRetry(r)}onFragBuffered(e,{frag:r}){if(r!==void 0&&r.type===we.MAIN){const n=r.elementaryStreams;if(!Object.keys(n).some(s=>!!n[s]))return;const i=this._levels[r.level];i!=null&&i.loadError&&(this.log(`Resetting level error count of ${i.loadError} on frag buffered`),i.loadError=0)}}onLevelLoaded(e,r){var n;const{level:i,details:s}=r,a=this._levels[i];if(!a){var o;this.warn(`Invalid level index ${i}`),(o=r.deliveryDirectives)!=null&&o.skip&&(s.deltaUpdateFailed=!0);return}i===this.currentLevelIndex?(a.fragmentError===0&&(a.loadError=0),this.playlistLoaded(i,r,a.details)):(n=r.deliveryDirectives)!=null&&n.skip&&(s.deltaUpdateFailed=!0)}loadPlaylist(e){super.loadPlaylist();const r=this.currentLevelIndex,n=this.currentLevel;if(n&&this.shouldLoadPlaylist(n)){let i=n.uri;if(e)try{i=e.addDirectives(i)}catch(a){this.warn(`Could not construct new URL with HLS Delivery Directives: ${a}`)}const s=n.attrs["PATHWAY-ID"];this.log(`Loading level index ${r}${(e==null?void 0:e.msn)!==void 0?" at sn "+e.msn+" part "+e.part:""} with${s?" Pathway "+s:""} ${i}`),this.clearTimer(),this.hls.trigger(w.LEVEL_LOADING,{url:i,level:r,pathwayId:n.attrs["PATHWAY-ID"],id:0,deliveryDirectives:e||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 r;const n=this._levels.filter((i,s)=>s!==e?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(a=>a.level=-1)),!1));IT(n),this._levels=n,this.currentLevelIndex>-1&&(r=this.currentLevel)!=null&&r.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.hls.trigger(w.LEVELS_UPDATED,{levels:n})}onLevelsUpdated(e,{levels:r}){this._levels=r}checkMaxAutoUpdated(){const{autoLevelCapping:e,maxAutoLevel:r,maxHdcpLevel:n}=this.hls;this._maxAutoLevel!==r&&(this._maxAutoLevel=r,this.hls.trigger(w.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:e,levels:this.levels,maxAutoLevel:r,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:n}))}}function uy(t){const e={};t.forEach(r=>{const n=r.groupId||"";r.id=e[n]=e[n]||0,e[n]++})}class XN{constructor(e){this.config=void 0,this.keyUriToKeyInfo={},this.emeController=null,this.config=e}abort(e){for(const n in this.keyUriToKeyInfo){const i=this.keyUriToKeyInfo[n].loader;if(i){var r;if(e&&e!==((r=i.context)==null?void 0:r.frag.type))return;i.abort()}}}detach(){for(const e in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[e];(r.mediaKeySessionContext||r.decryptdata.isCommonEncryption)&&delete this.keyUriToKeyInfo[e]}}destroy(){this.detach();for(const e in this.keyUriToKeyInfo){const r=this.keyUriToKeyInfo[e].loader;r&&r.destroy()}this.keyUriToKeyInfo={}}createKeyLoadError(e,r=z.KEY_LOAD_ERROR,n,i,s){return new Zn({type:_e.NETWORK_ERROR,details:r,fatal:!1,frag:e,response:s,error:n,networkDetails:i})}loadClear(e,r){if(this.emeController&&this.config.emeEnabled){const{sn:n,cc:i}=e;for(let s=0;s{a.setKeyFormat(o)});break}}}}load(e){return!e.decryptdata&&e.encrypted&&this.emeController?this.emeController.selectKeySystemFormat(e).then(r=>this.loadInternal(e,r)):this.loadInternal(e)}loadInternal(e,r){var n,i;r&&e.setKeyFormat(r);const s=e.decryptdata;if(!s){const u=new Error(r?`Expected frag.decryptdata to be defined after setting format ${r}`:"Missing decryption data on fragment in onKeyLoading");return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,u))}const a=s.uri;if(!a)return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${a}"`)));let o=this.keyUriToKeyInfo[a];if((n=o)!=null&&n.decryptdata.key)return s.key=o.decryptdata.key,Promise.resolve({frag:e,keyInfo:o});if((i=o)!=null&&i.keyLoadPromise){var l;switch((l=o.mediaKeySessionContext)==null?void 0:l.keyStatus){case void 0:case"status-pending":case"usable":case"usable-in-future":return o.keyLoadPromise.then(u=>(s.key=u.keyInfo.decryptdata.key,{frag:e,keyInfo:o}))}}switch(o=this.keyUriToKeyInfo[a]={decryptdata:s,keyLoadPromise:null,loader:null,mediaKeySessionContext:null},s.method){case"ISO-23001-7":case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return s.keyFormat==="identity"?this.loadKeyHTTP(o,e):this.loadKeyEME(o,e);case"AES-128":return this.loadKeyHTTP(o,e);default:return Promise.reject(this.createKeyLoadError(e,z.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${s.method}"`)))}}loadKeyEME(e,r){const n={frag:r,keyInfo:e};if(this.emeController&&this.config.emeEnabled){const i=this.emeController.loadKey(n);if(i)return(e.keyLoadPromise=i.then(s=>(e.mediaKeySessionContext=s,n))).catch(s=>{throw e.keyLoadPromise=null,s})}return Promise.resolve(n)}loadKeyHTTP(e,r){const n=this.config,i=n.loader,s=new i(n);return r.keyLoader=e.loader=s,e.keyLoadPromise=new Promise((a,o)=>{const l={keyInfo:e,frag:r,responseType:"arraybuffer",url:e.decryptdata.uri},u=n.keyLoadPolicy.default,c={loadPolicy:u,timeout:u.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},d={onSuccess:(f,m,h,p)=>{const{frag:v,keyInfo:g,url:y}=h;if(!v.decryptdata||g!==this.keyUriToKeyInfo[y])return o(this.createKeyLoadError(v,z.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),p));g.decryptdata.key=v.decryptdata.key=new Uint8Array(f.data),v.keyLoader=null,g.loader=null,a({frag:v,keyInfo:g})},onError:(f,m,h,p)=>{this.resetLoader(m),o(this.createKeyLoadError(r,z.KEY_LOAD_ERROR,new Error(`HTTP Error ${f.code} loading key ${f.text}`),h,jt({url:l.url,data:void 0},f)))},onTimeout:(f,m,h)=>{this.resetLoader(m),o(this.createKeyLoadError(r,z.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),h))},onAbort:(f,m,h)=>{this.resetLoader(m),o(this.createKeyLoadError(r,z.INTERNAL_ABORTED,new Error("key loading aborted"),h))}};s.load(l,c,d)})}resetLoader(e){const{frag:r,keyInfo:n,url:i}=e,s=n.loader;r.keyLoader===s&&(r.keyLoader=null,n.loader=null),delete this.keyUriToKeyInfo[i],s&&s.destroy()}}function mw(){return self.SourceBuffer||self.WebKitSourceBuffer}function gw(){if(!bs())return!1;const e=mw();return!e||e.prototype&&typeof e.prototype.appendBuffer=="function"&&typeof e.prototype.remove=="function"}function ZN(){if(!gw())return!1;const t=bs();return typeof(t==null?void 0:t.isTypeSupported)=="function"&&(["avc1.42E01E,mp4a.40.2","av01.0.01M.08","vp09.00.50.08"].some(e=>t.isTypeSupported(pl(e,"video")))||["mp4a.40.2","fLaC"].some(e=>t.isTypeSupported(pl(e,"audio"))))}function QN(){var t;const e=mw();return typeof(e==null||(t=e.prototype)==null?void 0:t.changeType)=="function"}const JN=250,$u=2,eF=.1,tF=.05;class rF{constructor(e,r,n,i){this.config=void 0,this.media=null,this.fragmentTracker=void 0,this.hls=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.config=e,this.media=r,this.fragmentTracker=n,this.hls=i}destroy(){this.media=null,this.hls=this.fragmentTracker=null}poll(e,r){const{config:n,media:i,stalled:s}=this;if(i===null)return;const{currentTime:a,seeking:o}=i,l=this.seeking&&!o,u=!this.seeking&&o;if(this.seeking=o,a!==e){if(this.moved=!0,o||(this.nudgeRetry=0),s!==null){if(this.stallReported){const v=self.performance.now()-s;U.warn(`playback not stuck anymore @${a}, after ${Math.round(v)}ms`),this.stallReported=!1}this.stalled=null}return}if(u||l){this.stalled=null;return}if(i.paused&&!o||i.ended||i.playbackRate===0||!at.getBuffered(i).length){this.nudgeRetry=0;return}const c=at.bufferInfo(i,a,0),d=c.nextStart||0;if(o){const v=c.len>$u,g=!d||r&&r.start<=a||d-a>$u&&!this.fragmentTracker.getPartialFragment(a);if(v||g)return;this.moved=!1}if(!this.moved&&this.stalled!==null){var f;if(!(c.len>0)&&!d)return;const g=Math.max(d,c.start||0)-a,y=this.hls.levels?this.hls.levels[this.hls.currentLevel]:null,S=(y==null||(f=y.details)==null?void 0:f.live)?y.details.targetduration*2:$u,T=this.fragmentTracker.getPartialFragment(a);if(g>0&&(g<=S||T)){i.paused||this._trySkipBufferHole(T);return}}const m=self.performance.now();if(s===null){this.stalled=m;return}const h=m-s;if(!o&&h>=JN&&(this._reportStall(c),!this.media))return;const p=at.bufferInfo(i,a,n.maxBufferHole);this._tryFixBufferStall(p,h)}_tryFixBufferStall(e,r){const{config:n,fragmentTracker:i,media:s}=this;if(s===null)return;const a=s.currentTime,o=i.getPartialFragment(a);o&&(this._trySkipBufferHole(o)||!this.media)||(e.len>n.maxBufferHole||e.nextStart&&e.nextStart-an.highBufferWatchdogPeriod*1e3&&(U.warn("Trying to nudge playhead over buffer-hole"),this.stalled=null,this._tryNudgeBuffer())}_reportStall(e){const{hls:r,media:n,stallReported:i}=this;if(!i&&n){this.stallReported=!0;const s=new Error(`Playback stalling at @${n.currentTime} due to low buffer (${JSON.stringify(e)})`);U.warn(s.message),r.trigger(w.ERROR,{type:_e.MEDIA_ERROR,details:z.BUFFER_STALLED_ERROR,fatal:!1,error:s,buffer:e.len})}}_trySkipBufferHole(e){const{config:r,hls:n,media:i}=this;if(i===null)return 0;const s=i.currentTime,a=at.bufferInfo(i,s,0),o=s0&&a.len<1&&i.readyState<3,c=o-s;if(c>0&&(l||u)){if(c>r.maxBufferHole){const{fragmentTracker:f}=this;let m=!1;if(s===0){const h=f.getAppendedFrag(0,we.MAIN);h&&o1?(i=0,this.bitrateTest=!0):i=n.firstAutoLevel),n.nextLoadLevel=i,this.level=n.loadLevel,this.loadedmetadata=!1}r>0&&e===-1&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),e=r),this.state=Y.IDLE,this.nextLoadPosition=this.startPosition=this.lastCurrentTime=e,this.tick()}else this._forceStartLoad=!0,this.state=Y.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Y.WAITING_LEVEL:{const{levels:r,level:n}=this,i=r==null?void 0:r[n],s=i==null?void 0:i.details;if(s&&(!s.live||this.levelLastLoaded===i)){if(this.waitForCdnTuneIn(s))break;this.state=Y.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Y.IDLE;break}break}case Y.FRAG_LOADING_WAITING_RETRY:{var e;const r=self.performance.now(),n=this.retryDate;if(!n||r>=n||(e=this.media)!=null&&e.seeking){const{levels:i,level:s}=this,a=i==null?void 0:i[s];this.resetStartWhenNotLoaded(a||null),this.state=Y.IDLE}}break}this.state===Y.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){super.onTickEnd(),this.checkBuffer(),this.checkFragmentChanged()}doTickIdle(){const{hls:e,levelLastLoaded:r,levels:n,media:i}=this;if(r===null||!i&&(this.startFragRequested||!e.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const s=e.nextLoadLevel;if(!(n!=null&&n[s]))return;const a=n[s],o=this.getMainFwdBufferInfo();if(o===null)return;const l=this.getLevelDetails();if(l&&this._streamEnded(o,l)){const p={};this.altAudio&&(p.type="video"),this.hls.trigger(w.BUFFER_EOS,p),this.state=Y.ENDED;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===Y.WAITING_LEVEL||u.live&&this.levelLastLoaded!==a){this.level=s,this.state=Y.WAITING_LEVEL;return}const c=o.len,d=this.getMaxBufferLength(a.maxBitrate);if(c>=d)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const f=this.backtrackFragment?this.backtrackFragment.start:o.end;let m=this.getNextFragment(f,u);if(this.couldBacktrack&&!this.fragPrevious&&m&&m.sn!=="initSegment"&&this.fragmentTracker.getState(m)!==Bt.OK){var h;const v=((h=this.backtrackFragment)!=null?h:m).sn-u.startSN,g=u.fragments[v-1];g&&m.cc===g.cc&&(m=g,this.fragmentTracker.removeFragment(g))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(m&&this.isLoopLoading(m,f)){if(!m.gap){const v=this.audioOnly&&!this.altAudio?Je.AUDIO:Je.VIDEO,g=(v===Je.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;g&&this.afterBufferFlushed(g,v,we.MAIN)}m=this.getNextFragmentLoopLoading(m,u,o,we.MAIN,d)}m&&(m.initSegment&&!m.initSegment.data&&!this.bitrateTest&&(m=m.initSegment),this.loadFragment(m,a,f))}loadFragment(e,r,n){const i=this.fragmentTracker.getState(e);this.fragCurrent=e,i===Bt.NOT_LOADED||i===Bt.PARTIAL?e.sn==="initSegment"?this._loadInitSegment(e,r):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,r)):(this.startFragRequested=!0,super.loadFragment(e,r,n)):this.clearTrackerIfNeeded(e)}getBufferedFrag(e){return this.fragmentTracker.getBufferedFrag(e,we.MAIN)}followingBufferedFrag(e){return e?this.getBufferedFrag(e.end+.5):null}immediateLevelSwitch(){this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY)}nextLevelSwitch(){const{levels:e,media:r}=this;if(r!=null&&r.readyState){let n;const i=this.getAppendedFrag(r.currentTime);i&&i.start>1&&this.flushMainBuffer(0,i.start-1);const s=this.getLevelDetails();if(s!=null&&s.live){const o=this.getMainFwdBufferInfo();if(!o||o.len{const a=s.audioCodec;a&&(n=n||a.indexOf("mp4a.40.2")!==-1,i=i||a.indexOf("mp4a.40.5")!==-1)}),this.audioCodecSwitch=n&&i&&!QN(),this.audioCodecSwitch&&this.log("Both AAC/HE-AAC audio found in levels; declaring level codec as HE-AAC"),this.levels=r.levels,this.startFragRequested=!1}onLevelLoading(e,r){const{levels:n}=this;if(!n||this.state!==Y.IDLE)return;const i=n[r.level];(!i.details||i.details.live&&this.levelLastLoaded!==i||this.waitForCdnTuneIn(i.details))&&(this.state=Y.WAITING_LEVEL)}onLevelLoaded(e,r){var n;const{levels:i}=this,s=r.level,a=r.details,o=a.totalduration;if(!i){this.warn(`Levels were reset while loading level ${s}`);return}this.log(`Level ${s} loaded [${a.startSN},${a.endSN}]${a.lastPartSn?`[part-${a.lastPartSn}-${a.lastPartIndex}]`:""}, cc [${a.startCC}, ${a.endCC}] duration:${o}`);const l=i[s],u=this.fragCurrent;u&&(this.state===Y.FRAG_LOADING||this.state===Y.FRAG_LOADING_WAITING_RETRY)&&u.level!==r.level&&u.loader&&this.abortCurrentFrag();let c=0;if(a.live||(n=l.details)!=null&&n.live){var d;if(this.checkLiveUpdate(a),a.deltaUpdateFailed)return;c=this.alignPlaylists(a,l.details,(d=this.levelLastLoaded)==null?void 0:d.details)}if(l.details=a,this.levelLastLoaded=l,this.hls.trigger(w.LEVEL_UPDATED,{details:a,level:s}),this.state===Y.WAITING_LEVEL){if(this.waitForCdnTuneIn(a))return;this.state=Y.IDLE}this.startFragRequested?a.live&&this.synchronizeToLiveEdge(a):this.setStartPosition(a,c),this.tick()}_handleFragmentLoadProgress(e){var r;const{frag:n,part:i,payload:s}=e,{levels:a}=this;if(!a){this.warn(`Levels were reset while fragment load was in progress. Fragment ${n.sn} of level ${n.level} will not be buffered`);return}const o=a[n.level],l=o.details;if(!l){this.warn(`Dropping fragment ${n.sn} of level ${n.level} after level details were reset`),this.fragmentTracker.removeFragment(n);return}const u=o.videoCodec,c=l.PTSKnown||!l.live,d=(r=n.initSegment)==null?void 0:r.data,f=this._getAudioCodec(o),m=this.transmuxer=this.transmuxer||new XT(this.hls,we.MAIN,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)),h=i?i.index:-1,p=h!==-1,v=new km(n.level,n.sn,n.stats.chunkCount,s.byteLength,h,p),g=this.initPTS[n.cc];m.push(s,d,f,u,n,i,l.totalduration,c,v,g)}onAudioTrackSwitching(e,r){const n=this.altAudio;if(!!!r.url){if(this.mediaBuffer!==this.media){this.log("Switching on main audio, use media.buffered to schedule main fragment loading"),this.mediaBuffer=this.media;const a=this.fragCurrent;a&&(this.log("Switching to main audio track, cancel main fragment load"),a.abortRequests(),this.fragmentTracker.removeFragment(a)),this.resetTransmuxer(),this.resetLoadingState()}else this.audioOnly&&this.resetTransmuxer();const s=this.hls;n&&(s.trigger(w.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null}),this.fragmentTracker.removeAllFragments()),s.trigger(w.AUDIO_TRACK_SWITCHED,r)}}onAudioTrackSwitched(e,r){const n=r.id,i=!!this.hls.audioTracks[n].url;if(i){const s=this.videoBuffer;s&&this.mediaBuffer!==s&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=s)}this.altAudio=i,this.tick()}onBufferCreated(e,r){const n=r.tracks;let i,s,a=!1;for(const o in n){const l=n[o];if(l.id==="main"){if(s=o,i=l,o==="video"){const u=n[o];u&&(this.videoBuffer=u.buffer)}}else a=!0}a&&i?(this.log(`Alternate track found, use ${s}.buffered to schedule main fragment loading`),this.mediaBuffer=i.buffer):this.mediaBuffer=this.media}onFragBuffered(e,r){const{frag:n,part:i}=r;if(n&&n.type!==we.MAIN)return;if(this.fragContextChanged(n)){this.warn(`Fragment ${n.sn}${i?" p: "+i.index:""} of level ${n.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Y.PARSED&&(this.state=Y.IDLE);return}const s=i?i.stats:n.stats;this.fragLastKbps=Math.round(8*s.total/(s.buffering.end-s.loading.first)),n.sn!=="initSegment"&&(this.fragPrevious=n),this.fragBufferedComplete(n,i)}onError(e,r){var n;if(r.fatal){this.state=Y.ERROR;return}switch(r.details){case z.FRAG_GAP:case z.FRAG_PARSING_ERROR:case z.FRAG_DECRYPT_ERROR:case z.FRAG_LOAD_ERROR:case z.FRAG_LOAD_TIMEOUT:case z.KEY_LOAD_ERROR:case z.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(we.MAIN,r);break;case z.LEVEL_LOAD_ERROR:case z.LEVEL_LOAD_TIMEOUT:case z.LEVEL_PARSING_ERROR:!r.levelRetry&&this.state===Y.WAITING_LEVEL&&((n=r.context)==null?void 0:n.type)===He.LEVEL&&(this.state=Y.IDLE);break;case z.BUFFER_APPEND_ERROR:case z.BUFFER_FULL_ERROR:if(!r.parent||r.parent!=="main")return;if(r.details===z.BUFFER_APPEND_ERROR){this.resetLoadingState();return}this.reduceLengthAndFlushBuffer(r)&&this.flushMainBuffer(0,Number.POSITIVE_INFINITY);break;case z.INTERNAL_EXCEPTION:this.recoverWorkerError(r);break}}checkBuffer(){const{media:e,gapController:r}=this;if(!(!e||!r||!e.readyState)){if(this.loadedmetadata||!at.getBuffered(e).length){const n=this.state!==Y.IDLE?this.fragCurrent:null;r.poll(this.lastCurrentTime,n)}this.lastCurrentTime=e.currentTime}}onFragLoadEmergencyAborted(){this.state=Y.IDLE,this.loadedmetadata||(this.startFragRequested=!1,this.nextLoadPosition=this.startPosition),this.tickImmediate()}onBufferFlushed(e,{type:r}){if(r!==Je.AUDIO||this.audioOnly&&!this.altAudio){const n=(r===Je.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;this.afterBufferFlushed(n,r,we.MAIN),this.tick()}}onLevelsUpdated(e,r){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level),this.levels=r.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:e}=this;if(!e)return;const r=e.currentTime;let n=this.startPosition;if(n>=0&&r0&&(a{const{hls:i}=this;if(!n||this.fragContextChanged(e))return;r.fragmentError=0,this.state=Y.IDLE,this.startFragRequested=!1,this.bitrateTest=!1;const s=e.stats;s.parsing.start=s.parsing.end=s.buffering.start=s.buffering.end=self.performance.now(),i.trigger(w.FRAG_LOADED,n),e.bitrateTest=!1})}_handleTransmuxComplete(e){var r;const n="main",{hls:i}=this,{remuxResult:s,chunkMeta:a}=e,o=this.getCurrentContext(a);if(!o){this.resetWhenMissingContext(a);return}const{frag:l,part:u,level:c}=o,{video:d,text:f,id3:m,initSegment:h}=s,{details:p}=c,v=this.altAudio?void 0:s.audio;if(this.fragContextChanged(l)){this.fragmentTracker.removeFragment(l);return}if(this.state=Y.PARSING,h){if(h!=null&&h.tracks){const x=l.initSegment||l;this._bufferInitSegment(c,h.tracks,x,a),i.trigger(w.FRAG_PARSING_INIT_SEGMENT,{frag:x,id:n,tracks:h.tracks})}const g=h.initPTS,y=h.timescale;pe(g)&&(this.initPTS[l.cc]={baseTime:g,timescale:y},i.trigger(w.INIT_PTS_FOUND,{frag:l,id:n,initPTS:g,timescale:y}))}if(d&&p&&l.sn!=="initSegment"){const g=p.fragments[l.sn-1-p.startSN],y=l.sn===p.startSN,x=!g||l.cc>g.cc;if(s.independent!==!1){const{startPTS:S,endPTS:T,startDTS:C,endDTS:_}=d;if(u)u.elementaryStreams[d.type]={startPTS:S,endPTS:T,startDTS:C,endDTS:_};else if(d.firstKeyFrame&&d.independent&&a.id===1&&!x&&(this.couldBacktrack=!0),d.dropped&&d.independent){const b=this.getMainFwdBufferInfo(),I=(b?b.end:this.getLoadPosition())+this.config.maxBufferHole,A=d.firstKeyFramePTS?d.firstKeyFramePTS:S;if(!y&&I$u&&(l.gap=!0);l.setElementaryStreamInfo(d.type,S,T,C,_),this.backtrackFragment&&(this.backtrackFragment=l),this.bufferFragmentData(d,l,u,a,y||x)}else if(y||x)l.gap=!0;else{this.backtrack(l);return}}if(v){const{startPTS:g,endPTS:y,startDTS:x,endDTS:S}=v;u&&(u.elementaryStreams[Je.AUDIO]={startPTS:g,endPTS:y,startDTS:x,endDTS:S}),l.setElementaryStreamInfo(Je.AUDIO,g,y,x,S),this.bufferFragmentData(v,l,u,a)}if(p&&m!=null&&(r=m.samples)!=null&&r.length){const g={id:n,frag:l,details:p,samples:m.samples};i.trigger(w.FRAG_PARSING_METADATA,g)}if(p&&f){const g={id:n,frag:l,details:p,samples:f.samples};i.trigger(w.FRAG_PARSING_USERDATA,g)}}_bufferInitSegment(e,r,n,i){if(this.state!==Y.PARSING)return;this.audioOnly=!!r.audio&&!r.video,this.altAudio&&!this.audioOnly&&delete r.audio;const{audio:s,video:a,audiovideo:o}=r;if(s){let l=e.audioCodec;const u=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){l&&(l.indexOf("mp4a.40.5")!==-1?l="mp4a.40.2":l="mp4a.40.5");const c=s.metadata;c&&"channelCount"in c&&(c.channelCount||1)!==1&&u.indexOf("firefox")===-1&&(l="mp4a.40.5")}l&&l.indexOf("mp4a.40.5")!==-1&&u.indexOf("android")!==-1&&s.container!=="audio/mpeg"&&(l="mp4a.40.2",this.log(`Android: force audio codec to ${l}`)),e.audioCodec&&e.audioCodec!==l&&this.log(`Swapping manifest audio codec "${e.audioCodec}" for "${l}"`),s.levelCodec=l,s.id="main",this.log(`Init audio buffer, container:${s.container}, codecs[selected/level/parsed]=[${l||""}/${e.audioCodec||""}/${s.codec}]`)}a&&(a.levelCodec=e.videoCodec,a.id="main",this.log(`Init video buffer, container:${a.container}, codecs[level/parsed]=[${e.videoCodec||""}/${a.codec}]`)),o&&this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${e.codecs}/${o.codec}]`),this.hls.trigger(w.BUFFER_CODECS,r),Object.keys(r).forEach(l=>{const c=r[l].initSegment;c!=null&&c.byteLength&&this.hls.trigger(w.BUFFER_APPENDING,{type:l,data:c,frag:n,part:null,chunkMeta:i,parent:n.type})}),this.tickImmediate()}getMainFwdBufferInfo(){return this.getFwdBufferInfo(this.mediaBuffer?this.mediaBuffer:this.media,we.MAIN)}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=Y.IDLE}checkFragmentChanged(){const e=this.media;let r=null;if(e&&e.readyState>1&&e.seeking===!1){const n=e.currentTime;if(at.isBuffered(e,n)?r=this.getAppendedFrag(n):at.isBuffered(e,n+.1)&&(r=this.getAppendedFrag(n+.1)),r){this.backtrackFragment=null;const i=this.fragPlaying,s=r.level;(!i||r.sn!==i.sn||i.level!==s)&&(this.fragPlaying=r,this.hls.trigger(w.FRAG_CHANGED,{frag:r}),(!i||i.level!==s)&&this.hls.trigger(w.LEVEL_SWITCHED,{level:s}))}}}get nextLevel(){const e=this.nextBufferedFrag;return e?e.level:-1}get currentFrag(){const e=this.media;return e?this.fragPlaying||this.getAppendedFrag(e.currentTime):null}get currentProgramDateTime(){const e=this.media;if(e){const r=e.currentTime,n=this.currentFrag;if(n&&pe(r)&&pe(n.programDateTime)){const i=n.programDateTime+(r-n.start)*1e3;return new Date(i)}}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}}class kr{static get version(){return"1.5.15"}static isMSESupported(){return gw()}static isSupported(){return ZN()}static getMediaSource(){return bs()}static get Events(){return w}static get ErrorTypes(){return _e}static get ErrorDetails(){return z}static get DefaultConfig(){return kr.defaultConfig?kr.defaultConfig:pw}static set DefaultConfig(e){kr.defaultConfig=e}constructor(e={}){this.config=void 0,this.userConfig=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this.started=!1,this._emitter=new Um,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.audioTrackController=void 0,this.subtitleTrackController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this.url=null,this.triggeringException=void 0,WD(e.debug||!1,"Hls instance");const r=this.config=KN(kr.DefaultConfig,e);this.userConfig=e,r.progressive&&YN(r);const{abrController:n,bufferController:i,capLevelController:s,errorController:a,fpsController:o}=r,l=new a(this),u=this.abrController=new n(this),c=this.bufferController=new i(this),d=this.capLevelController=new s(this),f=new o(this),m=new $P(this),h=new HP(this),p=r.contentSteeringController,v=p?new p(this):null,g=this.levelController=new qN(this,v),y=new SO(this),x=new XN(this.config),S=this.streamController=new iF(this,y,x);d.setStreamController(S),f.setStreamController(S);const T=[m,g,S];v&&T.splice(1,0,v),this.networkControllers=T;const C=[u,c,d,f,h,y];this.audioTrackController=this.createController(r.audioTrackController,T);const _=r.audioStreamController;_&&T.push(new _(this,y,x)),this.subtitleTrackController=this.createController(r.subtitleTrackController,T);const b=r.subtitleStreamController;b&&T.push(new b(this,y,x)),this.createController(r.timelineController,C),x.emeController=this.emeController=this.createController(r.emeController,C),this.cmcdController=this.createController(r.cmcdController,C),this.latencyController=this.createController(WP,C),this.coreComponents=C,T.push(l);const I=l.onErrorOut;typeof I=="function"&&this.on(w.ERROR,I,l)}createController(e,r){if(e){const n=new e(this);return r&&r.push(n),n}return null}on(e,r,n=this){this._emitter.on(e,r,n)}once(e,r,n=this){this._emitter.once(e,r,n)}removeAllListeners(e){this._emitter.removeAllListeners(e)}off(e,r,n=this,i){this._emitter.off(e,r,n,i)}listeners(e){return this._emitter.listeners(e)}emit(e,r,n){return this._emitter.emit(e,r,n)}trigger(e,r){if(this.config.debug)return this.emit(e,e,r);try{return this.emit(e,e,r)}catch(n){if(U.error("An internal error happened while handling event "+e+'. Error message: "'+n.message+'". Here is a stacktrace:',n),!this.triggeringException){this.triggeringException=!0;const i=e===w.ERROR;this.trigger(w.ERROR,{type:_e.OTHER_ERROR,details:z.INTERNAL_EXCEPTION,fatal:i,event:e,error:n}),this.triggeringException=!1}}return!1}listenerCount(e){return this._emitter.listenerCount(e)}destroy(){U.log("destroy"),this.trigger(w.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 e=this.config;e.xhrSetup=e.fetchSetup=void 0,this.userConfig=null}attachMedia(e){U.log("attachMedia"),this._media=e,this.trigger(w.MEDIA_ATTACHING,{media:e})}detachMedia(){U.log("detachMedia"),this.trigger(w.MEDIA_DETACHING,void 0),this._media=null}loadSource(e){this.stopLoad();const r=this.media,n=this.url,i=this.url=Lm.buildAbsoluteURL(self.location.href,e,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,U.log(`loadSource:${i}`),r&&n&&(n!==i||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(w.MANIFEST_LOADING,{url:e})}startLoad(e=-1){U.log(`startLoad(${e})`),this.started=!0,this.networkControllers.forEach(r=>{r.startLoad(e)})}stopLoad(){U.log("stopLoad"),this.started=!1,this.networkControllers.forEach(e=>{e.stopLoad()})}resumeBuffering(){this.started&&this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.startLoad(-1)})}pauseBuffering(){this.networkControllers.forEach(e=>{"fragmentLoader"in e&&e.stopLoad()})}swapAudioCodec(){U.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){U.log("recoverMediaError");const e=this._media;this.detachMedia(),e&&this.attachMedia(e)}removeLevel(e){this.levelController.removeLevel(e)}get levels(){const e=this.levelController.levels;return e||[]}get currentLevel(){return this.streamController.currentLevel}set currentLevel(e){U.log(`set currentLevel:${e}`),this.levelController.manualLevel=e,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(e){U.log(`set nextLevel:${e}`),this.levelController.manualLevel=e,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(e){U.log(`set loadLevel:${e}`),this.levelController.manualLevel=e}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(e){this.levelController.nextLoadLevel=e}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(e){U.log(`set firstLevel:${e}`),this.levelController.firstLevel=e}get startLevel(){const e=this.levelController.startLevel;return e===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:e}set startLevel(e){U.log(`set startLevel:${e}`),e!==-1&&(e=Math.max(e,this.minAutoLevel)),this.levelController.startLevel=e}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(e){const r=!!e;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:e}=this.abrController;return e?e.getEstimate():NaN}set bandwidthEstimate(e){this.abrController.resetEstimator(e)}get ttfbEstimate(){const{bwEstimator:e}=this.abrController;return e?e.getEstimateTTFB():NaN}set autoLevelCapping(e){this._autoLevelCapping!==e&&(U.log(`set autoLevelCapping:${e}`),this._autoLevelCapping=e,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(e){KP(e)&&this._maxHdcpLevel!==e&&(this._maxHdcpLevel=e,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:e,config:{minAutoBitrate:r}}=this;if(!e)return 0;const n=e.length;for(let i=0;i=r)return i;return 0}get maxAutoLevel(){const{levels:e,autoLevelCapping:r,maxHdcpLevel:n}=this;let i;if(r===-1&&e!=null&&e.length?i=e.length-1:i=r,n)for(let s=i;s--;){const a=e[s].attrs["HDCP-LEVEL"];if(a&&a<=n)return s}return i}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(e){this.abrController.nextAutoLevel=e}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}setAudioOption(e){var r;return(r=this.audioTrackController)==null?void 0:r.setAudioOption(e)}setSubtitleOption(e){var r;return(r=this.subtitleTrackController)==null||r.setSubtitleOption(e),null}get allAudioTracks(){const e=this.audioTrackController;return e?e.allAudioTracks:[]}get audioTracks(){const e=this.audioTrackController;return e?e.audioTracks:[]}get audioTrack(){const e=this.audioTrackController;return e?e.audioTrack:-1}set audioTrack(e){const r=this.audioTrackController;r&&(r.audioTrack=e)}get allSubtitleTracks(){const e=this.subtitleTrackController;return e?e.allSubtitleTracks:[]}get subtitleTracks(){const e=this.subtitleTrackController;return e?e.subtitleTracks:[]}get subtitleTrack(){const e=this.subtitleTrackController;return e?e.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(e){const r=this.subtitleTrackController;r&&(r.subtitleTrack=e)}get subtitleDisplay(){const e=this.subtitleTrackController;return e?e.subtitleDisplay:!1}set subtitleDisplay(e){const r=this.subtitleTrackController;r&&(r.subtitleDisplay=e)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(e){this.config.lowLatencyMode=e}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}}kr.defaultConfig=void 0;function sF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M208 432h-48a16 16 0 0 1-16-16V96a16 16 0 0 1 16-16h48a16 16 0 0 1 16 16v320a16 16 0 0 1-16 16zm144 0h-48a16 16 0 0 1-16-16V96a16 16 0 0 1 16-16h48a16 16 0 0 1 16 16v320a16 16 0 0 1-16 16z"},child:[]}]})(t)}function aF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M133 440a35.37 35.37 0 0 1-17.5-4.67c-12-6.8-19.46-20-19.46-34.33V111c0-14.37 7.46-27.53 19.46-34.33a35.13 35.13 0 0 1 35.77.45l247.85 148.36a36 36 0 0 1 0 61l-247.89 148.4A35.5 35.5 0 0 1 133 440z"},child:[]}]})(t)}function oF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M19 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-8 12H9.5v-2h-2v2H6V9h1.5v2.5h2V9H11v6zm2-6h4c.55 0 1 .45 1 1v4c0 .55-.45 1-1 1h-4V9zm1.5 4.5h2v-3h-2v3z"},child:[]}]})(t)}function lF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM4 12h4v2H4v-2zm10 6H4v-2h10v2zm6 0h-4v-2h4v2zm0-4H10v-2h10v2z"},child:[]}]})(t)}function uF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M18.5 12A4.5 4.5 0 0 0 16 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02zM5 9v6h4l5 5V4L9 9H5z"},child:[]}]})(t)}function cF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M7 9v6h4l5 5V4l-5 5H7z"},child:[]}]})(t)}function dF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M16.5 12A4.5 4.5 0 0 0 14 7.97v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51A8.796 8.796 0 0 0 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3 3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06a8.99 8.99 0 0 0 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4 9.91 6.09 12 8.18V4z"},child:[]}]})(t)}function fF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M3 9v6h4l5 5V4L7 9H3zm13.5 3A4.5 4.5 0 0 0 14 7.97v8.05c1.48-.73 2.5-2.25 2.5-4.02zM14 3.23v2.06c2.89.86 5 3.54 5 6.71s-2.11 5.85-5 6.71v2.06c4.01-.91 7-4.49 7-8.77s-2.99-7.86-7-8.77z"},child:[]}]})(t)}function hF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z",opacity:".1"},child:[]},{tag:"path",attr:{d:"M21 3H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm0-4v2a9 9 0 0 1 9 9h2c0-6.08-4.93-11-11-11z"},child:[]}]})(t)}function pF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M12 3a9 9 0 0 0-9 9v7c0 1.1.9 2 2 2h4v-8H5v-1c0-3.87 3.13-7 7-7s7 3.13 7 7v1h-4v8h4c1.1 0 2-.9 2-2v-7a9 9 0 0 0-9-9z"},child:[]}]})(t)}function mF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z"},child:[]}]})(t)}function vw(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M9 16.17 4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"},child:[]}]})(t)}function gF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M15.41 7.41 14 6l-6 6 6 6 1.41-1.41L10.83 12z"},child:[]}]})(t)}function vF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M10 6 8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"},child:[]}]})(t)}function yF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"},child:[]}]})(t)}function xF(t){return Mt({tag:"svg",attr:{viewBox:"0 0 24 24"},child:[{tag:"path",attr:{fill:"none",d:"M0 0h24v24H0z"},child:[]},{tag:"path",attr:{d:"M7 14H5v5h5v-2H7v-3zm-2-4h2V7h3V5H5v5zm12 7h-3v2h5v-5h-2v3zM14 5v2h3v3h2V5h-5z"},child:[]}]})(t)}const Bf=({icon:t,values:e,selectedValue:r,canDeselect:n,setSelectedValue:i})=>{const[s,a]=L.useState(!1),o=L.useRef(null),l=()=>{a(!s)},u=c=>{n&&(r==null?void 0:r.id)===c.id?i(null):i(c),a(!1)};return L.useEffect(()=>{const c=d=>{o.current&&!o.current.contains(d.target)&&a(!1)};return document.addEventListener("click",c),()=>{document.removeEventListener("click",c)}},[]),E.jsxs("div",{className:"relative hover:bg-neutral-700 p-1 rounded",ref:o,children:[E.jsx("button",{className:"py-1 rounded flex items-center gap-2",onClick:l,children:t!==void 0&&t}),s&&E.jsx("ul",{className:"absolute bottom-[120%] min-w-fit w-full right-0 bg-neutral-800 border border-neutral-700 rounded mt-2",children:e.map(c=>E.jsxs("li",{className:"px-4 py-2 cursor-pointer hover:bg-neutral-700 w-full flex gap-2 items-center justify-start overflow-visible text-nowrap",onClick:()=>u(c),children:[c.id!==(r==null?void 0:r.id)&&t,c.id===(r==null?void 0:r.id)&&E.jsx(vw,{}),c.name||`${c.height}p`]},c.id))})]})},SF=({icon:t,seasons:e=[],currentEpisodeId:r,onSelect:n})=>{const[i,s]=L.useState(!1),[a,o]=L.useState(null),[l,u]=L.useState(null),c=L.useRef(null),d=p=>{p.stopPropagation(),s(!i)},f=(p,v)=>{p.stopPropagation(),o(v)},m=(p,v)=>{p.stopPropagation(),u(v),n(v),s(!1)},h=p=>{p.stopPropagation(),o(null)};return L.useEffect(()=>{const p=v=>{c.current&&!c.current.contains(v.target)&&s(!1)};return document.addEventListener("click",p),()=>{document.removeEventListener("click",p)}},[]),E.jsxs("section",{className:"relative","aria-label":"Episode selector",ref:c,children:[E.jsxs("button",{className:"p-2 rounded flex items-center gap-2 hover:bg-neutral-700",onClick:d,"aria-haspopup":"true","aria-expanded":i,children:[t,!t&&E.jsx("span",{className:"sr-only",children:"Select episode:"})]}),i&&E.jsx("section",{className:"absolute bottom-full right-0 mb-2 bg-neutral-800 border border-neutral-700 rounded shadow-lg max-h-[300px] overflow-y-auto w-auto",role:"menu",onClick:p=>p.stopPropagation(),children:a?E.jsxs("ul",{className:"py-2",role:"list",children:[E.jsxs("li",{className:"px-4 py-2 cursor-pointer hover:bg-neutral-700 flex items-center",onClick:h,role:"menuitem",children:[E.jsx(gF,{className:"h-4 w-4 mr-2","aria-hidden":"true"}),"Back to Seasons"]}),a.episodes.map(p=>E.jsxs("li",{className:"px-4 py-2 cursor-pointer hover:bg-neutral-700 flex gap-4 items-center min-w-max",onClick:v=>m(v,p),role:"menuitem",children:[(l==null?void 0:l.id)===p.id||r===p.id?E.jsx(vw,{className:"h-4 w-4","aria-hidden":"true"}):E.jsx("section",{className:"h-4 w-4"}),E.jsx("img",{src:p.images.banner,alt:p.title,className:"w-16 h-9 rounded-md"}),E.jsxs("span",{className:"text-nowrap",children:["Episode ",p.number,": ",p.title]})]},p.id))]}):E.jsx("ul",{className:"py-2",role:"list",children:e.length>0?e.map(p=>E.jsxs("li",{className:"px-4 py-2 cursor-pointer hover:bg-neutral-700 flex justify-between items-center",onClick:v=>f(v,p),role:"menuitem",children:[E.jsxs("span",{className:"text-nowrap",children:["Season ",p.season_number]}),E.jsx(vF,{className:"h-4 w-4","aria-hidden":"true"})]},p.season_id)):E.jsx("li",{className:"px-4 py-2 text-neutral-400",role:"menuitem",children:"No seasons available"})})})]})},EF=()=>{var tn,jn,rn,xn,nt,Gr;const t=L.useRef(null),e=L.useRef(null),r=L.useRef(null),[n,i]=L.useState(0),[s,a]=L.useState(null),[o,l]=L.useState([]),[u,c]=L.useState([]),[d,f]=L.useState([]),[m,h]=L.useState(null),[p,v]=L.useState(null),[g,y]=L.useState(null),[x,S]=L.useState(!0),[T,C]=L.useState(!1),[_,b]=L.useState(!1),[I,A]=L.useState(1),[k,O]=L.useState(I),{id:P,type:G}=VS(),K=Br(),{data:H}=ur(`/api/medias/media/${G}/${P}`);let se;const W=L.useCallback(Ae=>{K(`/watch/${G}/${Ae.id}`)},[K,G]),F=Ae=>{if(!Ae)return"0:00";const qe=Math.floor(Ae/3600),R=Math.floor((Ae-qe*3600)/60),N=Math.floor(Ae-qe*3600-R*60),$=String(N).padStart(2,"0"),re=String(R).padStart(2,"0"),Z=String(qe).padStart(2,"0");return qe>0?`${Z}:${re}:${$}`:R>0?`${re}:${$}`:`00:${$}`},{updateProfileData:j,updateAccessToken:te}=Ua();L.useEffect(()=>{var qe;i(0),S(!0),l([]),c([]),f([]),h(null),v(null),y(null),s&&(s.destroy(),a(null)),t.current&&(t.current.src="",t.current.load());let Ae=`/api/watch/${G}/${P}`;if((qe=H==null?void 0:H.data)!=null&&qe._source&&(Ae=H.data._source),t.current)if(kr.isSupported()){const R=new kr({xhrSetup:(N,$)=>{var re;N.open("GET",$,!0),$.includes("")&&(N.setRequestHeader("Authorization",`Bearer ${localStorage.getItem("access_token")}`),N.setRequestHeader("X-Current-Time",String(((re=t.current)==null?void 0:re.currentTime)||0))),N.onreadystatechange=async()=>{var Z;if(N.readyState===4&&N.status===200)try{if(JSON.parse(N.responseText).code===246){const oe=await(await fetch("/api/auth/refresh",{method:"POST",body:JSON.stringify({refresh_token:localStorage.getItem("refresh_token")}),headers:{"Content-Type":"application/json"}})).json();if(oe.error){K("/login");return}else{let xe=oe.data.access_token;localStorage.setItem("access_token",xe),te(oe.data.access_token),j(oe.data.user),N.open("GET",$,!0),$.includes("")&&(N.setRequestHeader("Authorization",`Bearer ${xe}`),N.setRequestHeader("X-Current-Time",String(((Z=t.current)==null?void 0:Z.currentTime)||0))),N.send()}}}catch(X){console.error(`Error parsing response: ${X}`)}}}});R.loadSource(Ae),R.attachMedia(t.current),R.on(kr.Events.MANIFEST_PARSED,()=>{var N;(N=t.current)==null||N.play()}),R.on(kr.Events.AUDIO_TRACKS_UPDATED,()=>{l(R.audioTracks);let N=R.audioTracks.find($=>$.default);N||(N=R.audioTracks[0]),h(N)}),R.on(kr.Events.SUBTITLE_TRACKS_UPDATED,()=>{c(R.subtitleTracks)}),R.on(kr.Events.BUFFER_CREATED,()=>{S(!0)}),R.on(kr.Events.FRAG_BUFFERED,()=>{S(!1)}),t.current.addEventListener("timeupdate",()=>{var $;i((($=t.current)==null?void 0:$.currentTime)||0);let N=R.levels;N.find(re=>re.height===-1)===void 0&&N.push({height:-1,name:"auto"}),f(N)}),a(R)}else t.current.canPlayType("application/vnd.apple.mpegurl")&&(t.current.src=Ae);return()=>{s&&s.destroy()}},[P,G,(tn=H==null?void 0:H.data)==null?void 0:tn._source]),L.useEffect(()=>{if(!t.current)return;const Ae=()=>{var R;(R=H==null?void 0:H.data)!=null&&R.last_duration&&t.current&&(t.current.currentTime=H.data.last_duration,t.current.play())},qe=()=>{t.current&&t.current.play()};return t.current.addEventListener("loadedmetadata",Ae),t.current.addEventListener("loadeddata",qe),()=>{t.current&&(t.current.removeEventListener("loadedmetadata",Ae),t.current.removeEventListener("loadeddata",qe))}},[(jn=H==null?void 0:H.data)==null?void 0:jn.last_duration]),L.useEffect(()=>{const Ae=localStorage.getItem("video-volume");if(Ae&&t.current){const qe=Number(Ae);A(qe),t.current.volume=qe}},[]);const ee=Ae=>{t.current&&(t.current.currentTime=Number(Ae.target.value),i(Number(Ae.target.value)))},fe=Ae=>{const qe=Number(Ae.target.value);A(qe),t.current&&(t.current.volume=qe),localStorage.setItem("video-volume",String(qe))};L.useEffect(()=>{if(s){if(m)try{s.audioTrack=s.audioTracks.findIndex(Ae=>Ae.id===m.id)}catch{}p?s.subtitleTrack=s.subtitleTracks.findIndex(Ae=>Ae.id===p.id):s.subtitleTrack=-1,g&&(s.currentLevel=s.levels.findIndex(Ae=>Ae.height===g.height))}},[m,p,g,s]);const ye=()=>{e.current&&(_?document.exitFullscreen():e.current.requestFullscreen().catch(Ae=>console.log(Ae)),b(!_))},Re=()=>{C(!0),clearTimeout(se),se=setTimeout(()=>{var Ae;(Ae=r.current)!=null&&Ae.matches(":hover")||C(!1)},5e3)},Ee=()=>{I>0?(O(I),A(0),t.current&&(t.current.volume=0)):(A(k),t.current&&(t.current.volume=k))},Fe=()=>{if(s){const Ae=s.subtitleTrack===-1?0:-1;s.subtitleTrack=Ae}},st=L.useCallback(Ae=>{var qe,R;if(t.current)switch(Ae.key){case"f":ye();break;case"m":Ee();break;case"c":Fe();break;case" ":Ae.preventDefault(),t.current.paused?t.current.play():t.current.pause();break;case"ArrowLeft":t.current.currentTime=Math.max(0,t.current.currentTime-10);break;case"ArrowRight":t.current.currentTime=Math.min(t.current.duration,t.current.currentTime+10);break;case"ArrowUp":A(N=>{const $=Math.min(1,N+.05);return t.current&&(t.current.volume=$),$});break;case"ArrowDown":A(N=>{const $=Math.max(0,N-.05);return t.current&&(t.current.volume=$),$});break;case"PageUp":(qe=H==null?void 0:H.data)!=null&&qe._next&&K(`/watch/${G}/${H.data._next}`);break;case"PageDown":(R=H==null?void 0:H.data)!=null&&R._previous&&K(`/watch/${G}/${H.data._previous}`);break}},[ye,Ee,Fe]);L.useEffect(()=>(document.addEventListener("keydown",st),()=>{document.removeEventListener("keydown",st)}),[st]);const br=()=>I===0?E.jsx(dF,{}):I<=.3?E.jsx(cF,{}):I<=.6?E.jsx(uF,{}):E.jsx(fF,{});return E.jsxs("section",{className:`bg-black relative ${T?"":"cursor-none"}`,ref:e,onMouseMove:Re,children:[E.jsx("video",{ref:t,className:"w-full h-screen"},P),E.jsx(_s,{className:`top-0 left-0 fixed h-screen w-screen transition-all duration-300 pointer-events-none z-50 ${x?"opacity-100":"opacity-0"}`}),E.jsx("section",{className:`absolute bottom-0 w-full flex flex-col justify-end z-20 ${T?"opacity-100":"opacity-0"} transition-opacity duration-300`,ref:r,children:E.jsxs("section",{className:"flex items-center justify-between px-4 py-2 bg-neutral-800 bg-opacity-75 gap-4",children:[E.jsx("button",{onClick:()=>{var Ae,qe,R;return(Ae=t.current)!=null&&Ae.paused?(qe=t.current)==null?void 0:qe.play():(R=t.current)==null?void 0:R.pause()},className:"hover:bg-neutral-700 p-1 rounded",children:(rn=t.current)!=null&&rn.paused?E.jsx(aF,{}):E.jsx(sF,{})}),E.jsx("div",{className:"volume-hover relative group flex items-center",children:E.jsxs("div",{className:"flex items-center group-hover:bg-neutral-700 p-1 rounded relative",children:[E.jsx("button",{className:"flex items-center",title:"Volume",onClick:Ee,children:br()}),E.jsx("input",{type:"range",min:0,max:1,step:.01,value:I,onChange:fe,className:"volume-slider"})]})}),E.jsx("input",{type:"range",className:"w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer dark:bg-gray-700",min:0,max:((xn=t.current)==null?void 0:xn.duration)||0,value:n,onChange:ee}),E.jsxs("span",{children:[F(n),"/",F((nt=t.current)==null?void 0:nt.duration)]}),E.jsxs("section",{className:"flex gap-2 items-center",children:[(o==null?void 0:o.length)>1&&E.jsx(Bf,{icon:E.jsx(pF,{}),values:o,selectedValue:m,setSelectedValue:h}),(u==null?void 0:u.length)>0&&E.jsx(Bf,{icon:E.jsx(lF,{}),values:u,selectedValue:p,setSelectedValue:v,canDeselect:!0}),((Gr=H==null?void 0:H.data)==null?void 0:Gr.serie_representation)&&E.jsx(SF,{seasons:H.data.serie_representation,onSelect:W,icon:E.jsx(mF,{}),currentEpisodeId:parseInt(P||"0")}),E.jsx(Bf,{icon:E.jsx(oF,{}),values:d,selectedValue:g,setSelectedValue:y}),E.jsx("button",{className:"hover:bg-neutral-700 p-1 rounded",children:E.jsx(hF,{})}),E.jsx("button",{onClick:ye,className:"hover:bg-neutral-700 p-1 rounded",children:_?E.jsx(yF,{}):E.jsx(xF,{})})]})]})})]})};var me={},op={exports:{}};(function(t,e){(function(r,n){var i="1.0.38",s="",a="?",o="function",l="undefined",u="object",c="string",d="major",f="model",m="name",h="type",p="vendor",v="version",g="architecture",y="console",x="mobile",S="tablet",T="smarttv",C="wearable",_="embedded",b=500,I="Amazon",A="Apple",k="ASUS",O="BlackBerry",P="Browser",G="Chrome",K="Edge",H="Firefox",se="Google",W="Huawei",F="LG",j="Microsoft",te="Motorola",ee="Opera",fe="Samsung",ye="Sharp",Re="Sony",Ee="Xiaomi",Fe="Zebra",st="Facebook",br="Chromium OS",tn="Mac OS",jn=function(oe,xe){var ce={};for(var Ge in oe)xe[Ge]&&xe[Ge].length%2===0?ce[Ge]=xe[Ge].concat(oe[Ge]):ce[Ge]=oe[Ge];return ce},rn=function(oe){for(var xe={},ce=0;ce0?Pe.length===2?typeof Pe[1]==o?this[Pe[0]]=Pe[1].call(this,Nt):this[Pe[0]]=Pe[1]:Pe.length===3?typeof Pe[1]===o&&!(Pe[1].exec&&Pe[1].test)?this[Pe[0]]=Nt?Pe[1].call(this,Nt,Pe[2]):n:this[Pe[0]]=Nt?Nt.replace(Pe[1],Pe[2]):n:Pe.length===4&&(this[Pe[0]]=Nt?Pe[3].call(this,Nt.replace(Pe[1],Pe[2])):n):this[Pe]=Nt||n;ce+=2}},R=function(oe,xe){for(var ce in xe)if(typeof xe[ce]===u&&xe[ce].length>0){for(var Ge=0;Ge2&&(Le[f]="iPad",Le[h]=S),Le},this.getEngine=function(){var Le={};return Le[m]=n,Le[v]=n,qe.call(Le,Ge,mt.engine),Le},this.getOS=function(){var Le={};return Le[m]=n,Le[v]=n,qe.call(Le,Ge,mt.os),Pe&&!Le[m]&&nr&&nr.platform&&nr.platform!="Unknown"&&(Le[m]=nr.platform.replace(/chrome os/i,br).replace(/macos/i,tn)),Le},this.getResult=function(){return{ua:this.getUA(),browser:this.getBrowser(),engine:this.getEngine(),os:this.getOS(),device:this.getDevice(),cpu:this.getCPU()}},this.getUA=function(){return Ge},this.setUA=function(Le){return Ge=typeof Le===c&&Le.length>b?Ae(Le,b):Le,this},this.setUA(Ge),this};Z.VERSION=i,Z.BROWSER=rn([m,v,d]),Z.CPU=rn([g]),Z.DEVICE=rn([f,p,h,y,x,T,S,C,_]),Z.ENGINE=Z.OS=rn([m,v]),t.exports&&(e=t.exports=Z),e.UAParser=Z;var X=typeof r!==l&&(r.jQuery||r.Zepto);if(X&&!X.ua){var ge=new Z;X.ua=ge.getResult(),X.ua.get=function(){return ge.getUA()},X.ua.set=function(oe){ge.setUA(oe);var xe=ge.getResult();for(var ce in xe)X.ua[ce]=xe[ce]}}})(typeof window=="object"?window:wb)})(op,op.exports);var TF=op.exports;Object.defineProperty(me,"__esModule",{value:!0});function wF(t){return t&&typeof t=="object"&&"default"in t?t.default:t}var Jt=L,ut=wF(Jt),yw=TF,Yi=new yw,rr=Yi.getBrowser(),bF=Yi.getCPU(),Vr=Yi.getDevice(),Gm=Yi.getEngine(),qi=Yi.getOS(),bl=Yi.getUA(),xw=function(e){return Yi.setUA(e)},Ll=function(e){if(!e){console.error("No userAgent string was provided");return}var r=new yw(e);return{UA:r,browser:r.getBrowser(),cpu:r.getCPU(),device:r.getDevice(),engine:r.getEngine(),os:r.getOS(),ua:r.getUA(),setUserAgent:function(i){return r.setUA(i)}}},Sw=Object.freeze({ClientUAInstance:Yi,browser:rr,cpu:bF,device:Vr,engine:Gm,os:qi,ua:bl,setUa:xw,parseUserAgent:Ll});function cy(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(t);e&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(t,i).enumerable})),r.push.apply(r,n)}return r}function LF(t){for(var e=1;e=0)&&(r[i]=t[i]);return r}function en(t,e){if(t==null)return{};var r=kF(t,e),n,i;if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(t);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(t,n)&&(r[n]=t[n])}return r}function ju(t){if(t===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function DF(t,e){if(e&&(typeof e=="object"||typeof e=="function"))return e;if(e!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return ju(t)}function PF(t,e){return OF(t)||MF(t,e)||NF(t,e)||FF()}function OF(t){if(Array.isArray(t))return t}function MF(t,e){var r=t==null?null:typeof Symbol<"u"&&t[Symbol.iterator]||t["@@iterator"];if(r!=null){var n=[],i=!0,s=!1,a,o;try{for(r=r.call(t);!(i=(a=r.next()).done)&&(n.push(a.value),!(e&&n.length===e));i=!0);}catch(l){s=!0,o=l}finally{try{!i&&r.return!=null&&r.return()}finally{if(s)throw o}}return n}}function NF(t,e){if(t){if(typeof t=="string")return dy(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r==="Object"&&t.constructor&&(r=t.constructor.name),r==="Map"||r==="Set")return Array.from(t);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return dy(t,e)}}function dy(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,n=new Array(e);r1&&arguments[1]!==void 0?arguments[1]:"none";return e||r},zm=function(){return typeof window<"u"&&(window.navigator||navigator)?window.navigator||navigator:!1},Hm=function(e){var r=zm();return r&&r.platform&&(r.platform.indexOf(e)!==-1||r.platform==="MacIntel"&&r.maxTouchPoints>1&&!window.MSStream)},jF=function(e,r,n,i,s){return{isBrowser:e,browserMajorVersion:De(r.major),browserFullVersion:De(r.version),browserName:De(r.name),engineName:De(n.name),engineVersion:De(n.version),osName:De(i.name),osVersion:De(i.version),userAgent:De(s)}},fy=function(e,r,n,i){return LF({},e,{vendor:De(r.vendor),model:De(r.model),os:De(n.name),osVersion:De(n.version),ua:De(i)})},VF=function(e,r,n,i){return{isSmartTV:e,engineName:De(r.name),engineVersion:De(r.version),osName:De(n.name),osVersion:De(n.version),userAgent:De(i)}},GF=function(e,r,n,i){return{isConsole:e,engineName:De(r.name),engineVersion:De(r.version),osName:De(n.name),osVersion:De(n.version),userAgent:De(i)}},zF=function(e,r,n,i){return{isWearable:e,engineName:De(r.name),engineVersion:De(r.version),osName:De(n.name),osVersion:De(n.version),userAgent:De(i)}},HF=function(e,r,n,i,s){return{isEmbedded:e,vendor:De(r.vendor),model:De(r.model),engineName:De(n.name),engineVersion:De(n.version),osName:De(i.name),osVersion:De(i.version),userAgent:De(s)}};function WF(t){var e=t?Ll(t):Sw,r=e.device,n=e.browser,i=e.engine,s=e.os,a=e.ua,o=BF(r.type),l=o.isBrowser,u=o.isMobile,c=o.isTablet,d=o.isSmartTV,f=o.isConsole,m=o.isWearable,h=o.isEmbedded;if(l)return jF(l,n,i,s,a);if(d)return VF(d,i,s,a);if(f)return GF(f,i,s,a);if(u||c)return fy(o,r,s,a);if(m)return zF(m,i,s,a);if(h)return HF(h,r,i,s,a)}var Ew=function(e){var r=e.type;return r===Zt.Mobile},Tw=function(e){var r=e.type;return r===Zt.Tablet},ww=function(e){var r=e.type;return r===Zt.Mobile||r===Zt.Tablet},bw=function(e){var r=e.type;return r===Zt.SmartTv},Wc=function(e){var r=e.type;return r===Zt.Browser},Lw=function(e){var r=e.type;return r===Zt.Wearable},Aw=function(e){var r=e.type;return r===Zt.Console},_w=function(e){var r=e.type;return r===Zt.Embedded},Cw=function(e){var r=e.vendor;return De(r)},Rw=function(e){var r=e.model;return De(r)},Iw=function(e){var r=e.type;return De(r,"browser")},kw=function(e){var r=e.name;return r===ja.Android},Dw=function(e){var r=e.name;return r===ja.Windows},Pw=function(e){var r=e.name;return r===ja.MAC_OS},Ow=function(e){var r=e.name;return r===ja.WindowsPhone},Mw=function(e){var r=e.name;return r===ja.IOS},Nw=function(e){var r=e.version;return De(r)},Fw=function(e){var r=e.name;return De(r)},Uw=function(e){var r=e.name;return r===wr.Chrome},Bw=function(e){var r=e.name;return r===wr.Firefox},$w=function(e){var r=e.name;return r===wr.Chromium},Kc=function(e){var r=e.name;return r===wr.Edge},jw=function(e){var r=e.name;return r===wr.Yandex},Vw=function(e){var r=e.name;return r===wr.Safari||r===wr.MobileSafari},Gw=function(e){var r=e.name;return r===wr.MobileSafari},zw=function(e){var r=e.name;return r===wr.Opera},Hw=function(e){var r=e.name;return r===wr.InternetExplorer||r===wr.Ie},Ww=function(e){var r=e.name;return r===wr.MIUI},Kw=function(e){var r=e.name;return r===wr.SamsungBrowser},Yw=function(e){var r=e.version;return De(r)},qw=function(e){var r=e.major;return De(r)},Xw=function(e){var r=e.name;return De(r)},Zw=function(e){var r=e.name;return De(r)},Qw=function(e){var r=e.version;return De(r)},Jw=function(){var e=zm(),r=e&&e.userAgent&&e.userAgent.toLowerCase();return typeof r=="string"?/electron/.test(r):!1},ha=function(e){return typeof e=="string"&&e.indexOf("Edg/")!==-1},eb=function(){var e=zm();return e&&(/iPad|iPhone|iPod/.test(e.platform)||e.platform==="MacIntel"&&e.maxTouchPoints>1)&&!window.MSStream},_n=function(){return Hm("iPad")},tb=function(){return Hm("iPhone")},rb=function(){return Hm("iPod")},nb=function(e){return De(e)};function ib(t){var e=t||Sw,r=e.device,n=e.browser,i=e.os,s=e.engine,a=e.ua;return{isSmartTV:bw(r),isConsole:Aw(r),isWearable:Lw(r),isEmbedded:_w(r),isMobileSafari:Gw(n)||_n(),isChromium:$w(n),isMobile:ww(r)||_n(),isMobileOnly:Ew(r),isTablet:Tw(r)||_n(),isBrowser:Wc(r),isDesktop:Wc(r),isAndroid:kw(i),isWinPhone:Ow(i),isIOS:Mw(i)||_n(),isChrome:Uw(n),isFirefox:Bw(n),isSafari:Vw(n),isOpera:zw(n),isIE:Hw(n),osVersion:Nw(i),osName:Fw(i),fullBrowserVersion:Yw(n),browserVersion:qw(n),browserName:Xw(n),mobileVendor:Cw(r),mobileModel:Rw(r),engineName:Zw(s),engineVersion:Qw(s),getUA:nb(a),isEdge:Kc(n)||ha(a),isYandex:jw(n),deviceType:Iw(r),isIOS13:eb(),isIPad13:_n(),isIPhone13:tb(),isIPod13:rb(),isElectron:Jw(),isEdgeChromium:ha(a),isLegacyEdge:Kc(n)&&!ha(a),isWindows:Dw(i),isMacOs:Pw(i),isMIUI:Ww(n),isSamsungBrowser:Kw(n)}}var sb=bw(Vr),ab=Aw(Vr),ob=Lw(Vr),KF=_w(Vr),YF=Gw(rr)||_n(),qF=$w(rr),bd=ww(Vr)||_n(),lb=Ew(Vr),ub=Tw(Vr)||_n(),cb=Wc(Vr),XF=Wc(Vr),db=kw(qi),fb=Ow(qi),hb=Mw(qi)||_n(),ZF=Uw(rr),QF=Bw(rr),JF=Vw(rr),e2=zw(rr),pb=Hw(rr),t2=Nw(qi),r2=Fw(qi),n2=Yw(rr),i2=qw(rr),s2=Xw(rr),a2=Cw(Vr),o2=Rw(Vr),l2=Zw(Gm),u2=Qw(Gm),c2=nb(bl),d2=Kc(rr)||ha(bl),f2=jw(rr),h2=Iw(Vr),p2=eb(),m2=_n(),g2=tb(),v2=rb(),y2=Jw(),x2=ha(bl),S2=Kc(rr)&&!ha(bl),E2=Dw(qi),T2=Pw(qi),w2=Ww(rr),b2=Kw(rr),L2=function(e){if(!e||typeof e!="string"){console.error("No valid user agent string was provided");return}var r=Ll(e),n=r.device,i=r.browser,s=r.os,a=r.engine,o=r.ua;return ib({device:n,browser:i,os:s,engine:a,ua:o})},A2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return db?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},_2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return cb?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},C2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return pb?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},R2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return hb?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},I2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return bd?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},k2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return ub?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},D2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return fb?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},P2=function(e){var r=e.renderWithFragment,n=e.children;e.viewClassName,e.style;var i=en(e,["renderWithFragment","children","viewClassName","style"]);return lb?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},O2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return sb?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},M2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return ab?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},N2=function(e){var r=e.renderWithFragment,n=e.children,i=en(e,["renderWithFragment","children"]);return ob?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",i,n):null},F2=function(e){var r=e.renderWithFragment,n=e.children;e.viewClassName,e.style;var i=e.condition,s=en(e,["renderWithFragment","children","viewClassName","style","condition"]);return i?r?ut.createElement(Jt.Fragment,null,n):ut.createElement("div",s,n):null};function U2(t){return function(e){IF(r,e);function r(n){var i;return AF(this,r),i=DF(this,up(r).call(this,n)),i.isEventListenerAdded=!1,i.handleOrientationChange=i.handleOrientationChange.bind(ju(i)),i.onOrientationChange=i.onOrientationChange.bind(ju(i)),i.onPageLoad=i.onPageLoad.bind(ju(i)),i.state={isLandscape:!1,isPortrait:!1},i}return CF(r,[{key:"handleOrientationChange",value:function(){this.isEventListenerAdded||(this.isEventListenerAdded=!0);var i=window.innerWidth>window.innerHeight?90:0;this.setState({isPortrait:i===0,isLandscape:i===90})}},{key:"onOrientationChange",value:function(){this.handleOrientationChange()}},{key:"onPageLoad",value:function(){this.handleOrientationChange()}},{key:"componentDidMount",value:function(){(typeof window>"u"?"undefined":Ro(window))!==void 0&&bd&&(this.isEventListenerAdded?window.removeEventListener("load",this.onPageLoad,!1):(this.handleOrientationChange(),window.addEventListener("load",this.onPageLoad,!1)),window.addEventListener("resize",this.onOrientationChange,!1))}},{key:"componentWillUnmount",value:function(){window.removeEventListener("resize",this.onOrientationChange,!1)}},{key:"render",value:function(){return ut.createElement(t,lp({},this.props,{isLandscape:this.state.isLandscape,isPortrait:this.state.isPortrait}))}}]),r}(ut.Component)}function B2(){var t=Jt.useState(function(){var s=window.innerWidth>window.innerHeight?90:0;return{isPortrait:s===0,isLandscape:s===90,orientation:s===0?"portrait":"landscape"}}),e=PF(t,2),r=e[0],n=e[1],i=Jt.useCallback(function(){var s=window.innerWidth>window.innerHeight?90:0,a={isPortrait:s===0,isLandscape:s===90,orientation:s===0?"portrait":"landscape"};r.orientation!==a.orientation&&n(a)},[r.orientation]);return Jt.useEffect(function(){return(typeof window>"u"?"undefined":Ro(window))!==void 0&&bd&&(i(),window.addEventListener("load",i,!1),window.addEventListener("resize",i,!1)),function(){window.removeEventListener("resize",i,!1),window.removeEventListener("load",i,!1)}},[i]),r}function mb(t){var e=t||window.navigator.userAgent;return Ll(e)}function $2(t){var e=t||window.navigator.userAgent,r=mb(e),n=ib(r);return[n,r]}me.AndroidView=A2;me.BrowserTypes=wr;me.BrowserView=_2;me.ConsoleView=M2;me.CustomView=F2;me.IEView=C2;me.IOSView=R2;me.MobileOnlyView=P2;me.MobileView=I2;me.OsTypes=ja;me.SmartTVView=O2;me.TabletView=k2;me.WearableView=N2;me.WinPhoneView=D2;me.browserName=s2;me.browserVersion=i2;me.deviceDetect=WF;me.deviceType=h2;me.engineName=l2;me.engineVersion=u2;me.fullBrowserVersion=n2;me.getSelectorsByUserAgent=L2;me.getUA=c2;me.isAndroid=db;me.isBrowser=cb;me.isChrome=ZF;me.isChromium=qF;me.isConsole=ab;me.isDesktop=XF;me.isEdge=d2;me.isEdgeChromium=x2;me.isElectron=y2;me.isEmbedded=KF;me.isFirefox=QF;me.isIE=pb;me.isIOS=hb;me.isIOS13=p2;me.isIPad13=m2;me.isIPhone13=g2;me.isIPod13=v2;me.isLegacyEdge=S2;me.isMIUI=w2;me.isMacOs=T2;var gb=me.isMobile=bd;me.isMobileOnly=lb;me.isMobileSafari=YF;me.isOpera=e2;me.isSafari=JF;me.isSamsungBrowser=b2;me.isSmartTV=sb;me.isTablet=ub;me.isWearable=ob;me.isWinPhone=fb;me.isWindows=E2;me.isYandex=f2;me.mobileModel=o2;me.mobileVendor=a2;me.osName=r2;me.osVersion=t2;me.parseUserAgent=Ll;me.setUserAgent=$F;me.useDeviceData=mb;me.useDeviceSelectors=$2;me.useMobileOrientation=B2;me.withOrientationChange=U2;function j2(t){return Mt({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M233.4 406.6c12.5 12.5 32.8 12.5 45.3 0l192-192c12.5-12.5 12.5-32.8 0-45.3s-32.8-12.5-45.3 0L256 338.7 86.6 169.4c-12.5-12.5-32.8-12.5-45.3 0s-12.5 32.8 0 45.3l192 192z"},child:[]}]})(t)}const hy=()=>{const[t,e]=L.useState(!1),{profileData:r}=dm(),n=()=>{e(!1)};return E.jsxs("section",{className:"relative flex items-center gap-4",children:[E.jsx("img",{src:r==null?void 0:r.profile_picture,alt:r==null?void 0:r.name,className:"w-8 h-8 rounded-md"}),E.jsx(j2,{onClick:()=>e(!t),className:`cursor-pointer ${t?"transform -rotate-180":""} transition-transform duration-300`}),E.jsxs("ul",{className:`absolute top-[100%] right-0 bg-neutral-900 rounded-lg px-4 overflow-hidden ${t?"h-auto p-4":"h-0 p-0"} transition-all duration-300`,children:[E.jsx("li",{children:E.jsx(Lu,{to:"/profil",onClick:n,children:"Profil"})}),E.jsx("li",{children:E.jsx(Lu,{to:"/settings",onClick:n,children:"Settings"})}),E.jsx("li",{children:E.jsx(Lu,{to:"/logout",onClick:n,children:"Logout"})})]})]})};function V2(t){return Mt({tag:"svg",attr:{viewBox:"0 0 512 512"},child:[{tag:"path",attr:{d:"M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z"},child:[]}]})(t)}const py=({onSearch:t})=>{const[e,r]=L.useState(""),n=Br(),i=a=>{r(a.target.value)},s=a=>{a.preventDefault(),t(e),n(`?query=${e}`)};return L.useEffect(()=>{const a=new URLSearchParams(window.location.search).get("query");a&&r(a)},[]),E.jsxs("form",{onSubmit:s,className:`flex gap-2 ${gb?"items-center":""}`,children:[E.jsx("input",{className:"w-48 sm:w-auto px-4 py-2 rounded-lg bg-neutral-900 focus:outline-none focus:ring-2 focus:ring-neutral-500",type:"text",placeholder:"Search...",value:e,onChange:i}),E.jsx("button",{type:"submit",children:E.jsx(V2,{})})]})},G2=()=>{const[t,e]=L.useState(!1),{setSearchTerm:r}=L.useContext(wl),n=Br(),i=s=>{r(s)};return gb?E.jsxs("section",{className:`${t?"overflow-hidden":""}`,children:[E.jsxs("section",{children:[E.jsxs("header",{className:"flex justify-between items-center py-4 px-8 text-white",children:[E.jsx("button",{onClick:()=>e(!t),className:"pointer-events-auto",children:E.jsxs("div",{className:`hamburger ${t?"active":""}`,children:[E.jsx("div",{className:"line"}),E.jsx("div",{className:"line"}),E.jsx("div",{className:"line"})]})}),E.jsx(py,{onSearch:i}),E.jsx(hy,{})]}),E.jsxs("aside",{className:`fixed pl-8 pt-4 flex flex-col gap-24 top-0 left-0 h-full bg-[--black] z-40 transform transition-transform duration-300 ease-in-out overflow-hidden w-full ${t?"translate-x-0":"-translate-x-full"}`,children:[E.jsxs("section",{className:"flex justify-between items-center py-4 pr-8",children:[E.jsx("img",{src:"/logo.png",alt:"Logo",className:"w-12 h-12"}),E.jsx("button",{onClick:()=>e(!t),className:"pointer-events-auto",children:E.jsxs("div",{className:`hamburger ${t?"active":""}`,children:[E.jsx("div",{className:"line"}),E.jsx("div",{className:"line"}),E.jsx("div",{className:"line"})]})})]}),E.jsxs("nav",{className:"flex flex-col gap-6",children:[E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/home",children:"Home"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/movies",children:"Movies"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/shows",children:"TV Shows"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/live-tv",children:"Live TV"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/musics",children:"Musics"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/books",children:"Books"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/games",children:"Games"}),E.jsx(qt,{onClick:()=>e(!1),className:"text-2xl",to:"/others",children:"Others"})]})]})]}),E.jsx(_0,{})]}):E.jsxs("section",{children:[E.jsxs("header",{className:"flex justify-between items-center py-4 px-16 text-white sticky top-0 left-0 w-full z-[99999]",children:[E.jsxs("section",{className:"flex gap-4 items-center",children:[E.jsx("img",{src:"/logo.png",alt:"Logo",className:"w-12 h-12 cursor-pointer",onClick:()=>n("/home")}),E.jsxs("nav",{className:"flex gap-4",children:[E.jsx(qt,{to:"/home",children:"Home"}),E.jsx(qt,{to:"/movies",children:"Movies"}),E.jsx(qt,{to:"/shows",children:"TV Shows"}),E.jsx(qt,{to:"/live-tv",children:"Live TV"}),E.jsx(qt,{to:"/musics",children:"Musics"}),E.jsx(qt,{to:"/books",children:"Books"}),E.jsx(qt,{to:"/games",children:"Games"}),E.jsx(qt,{to:"/others",children:"Others"})]})]}),E.jsxs("section",{className:"flex gap-8",children:[E.jsx(py,{onSearch:i}),E.jsx(hy,{})]})]}),E.jsx(_0,{})]})},my=({children:t})=>{const{data:e}=ur("/api/settings/libraries"),r=Br();return L.useEffect(()=>{e&&(!e.data||e.data.length==0)&&r("/settings#libraries")},[e]),E.jsxs(E.Fragment,{children:[E.jsx(G2,{}),E.jsx("main",{children:t})]})},z2=()=>{const[t,e]=L.useState(!0),[r,n]=L.useState(""),[i,s]=L.useState(""),[a,o]=L.useState(""),[l,u]=L.useState(""),[c,d]=L.useState(!1),{handleSubmit:f}=Ss(),m=async()=>{await f({url:"/api/settings/general",body:{ChocolateSettings:{language:r,allowdownload:c},APIKeys:{tmdb:i,igdbid:a,igdbsecret:l}}})},{data:h,loading:p}=ur("/api/settings/general"),{data:v,loading:g}=ur("/api/settings/languages");return L.useEffect(()=>{e(p&&g)},[p,g]),L.useEffect(()=>{h&&h.data&&h.data.ChocolateSettings&&h.data.APIKeys&&(n(h.data.ChocolateSettings.language),d(h.data.ChocolateSettings.allowdownload==="true"),s(h.data.APIKeys.tmdb),o(h.data.APIKeys.igdbid),u(h.data.APIKeys.igdbsecret))},[h]),E.jsxs(E.Fragment,{children:[E.jsx(_s,{className:"w-3/4 h-screen top-0 fixed bg-[--black] transition-all duration-300 pointer-events-none z-50 "+(t?"opacity-100":"opacity-0")}),E.jsx("h2",{className:`text-xl font-bold mb-4 ${t?"hidden":""}`,children:"General Settings"}),E.jsxs("div",{className:`flex flex-col items-start gap-6 px-8 ${t?"hidden":""}`,children:[E.jsxs("div",{className:"w-full max-w-md",children:[E.jsx("h2",{className:"text-xl font-bold mb-4",children:"Settings"}),E.jsxs("div",{className:"mb-4",children:[E.jsx("label",{htmlFor:"language-select",className:"block mb-2",children:"Language:"}),E.jsx("select",{id:"language-select",value:r,onChange:y=>n(y.target.value),className:"w-full px-4 py-2 rounded-lg bg-neutral-900 focus:outline-none focus:ring-2 focus:ring-neutral-500",children:v&&v.data&&v.data.map(y=>E.jsx("option",{value:y.code,children:y.name},y.code))})]}),E.jsxs("div",{className:"mb-4 flex items-center gap-4",children:[E.jsx("label",{htmlFor:"allow-downloads",className:"block",children:"Allow Downloads:"}),E.jsx("input",{type:"checkbox",id:"allow-downloads",checked:c,onChange:y=>d(y.target.checked),className:"w-4 h-4 rounded-lg bg-neutral-900 border-0 outline-none ring-0 focus:outline-none focus:ring-2 focus:ring-neutral-500"})]})]}),E.jsxs("div",{className:"w-full max-w-md",children:[E.jsx("h2",{className:"text-xl font-bold mb-4",children:"API Keys"}),E.jsxs("div",{className:"mb-4",children:[E.jsx("label",{htmlFor:"tmdb-api-key",className:"block mb-2",children:"TMDB API Key:"}),E.jsx("input",{type:"text",id:"tmdb-api-key",value:i,onChange:y=>s(y.target.value),placeholder:"afa...fdp",className:"w-full px-4 py-2 rounded-lg bg-neutral-900 focus:outline-none focus:ring-2 focus:ring-neutral-500"})]}),E.jsxs("div",{className:"mb-4",children:[E.jsx("label",{htmlFor:"igdb-id-key",className:"block mb-2",children:"IGDB ID Key:"}),E.jsx("input",{type:"text",id:"igdb-id-key",value:a,onChange:y=>o(y.target.value),placeholder:"161...b3f",className:"w-full px-4 py-2 rounded-lg bg-neutral-900 focus:outline-none focus:ring-2 focus:ring-neutral-500"})]}),E.jsxs("div",{className:"mb-4",children:[E.jsx("label",{htmlFor:"igdb-secret-key",className:"block mb-2",children:"IGDB Secret Key:"}),E.jsx("input",{type:"password",id:"igdb-secret-key",autoComplete:"new-password",value:l,onChange:y=>u(y.target.value),placeholder:"161...b3f",className:"w-full px-4 py-2 rounded-lg bg-neutral-900 focus:outline-none focus:ring-2 focus:ring-neutral-500"})]})]}),E.jsx(Rn,{state:"primary",onClick:m,children:"Save Settings"})]})]})},Ar=-161,H2=()=>{var h,p,v;const[t,e]=L.useState([]),[r,n]=L.useState(!0),{data:i,loading:s,fetchData:a}=ur("/api/settings/accounts"),{handleSubmit:o}=Ss(),{handleSubmit:l}=iE(),{handleSubmit:u}=sE();L.useEffect(()=>{i&&i.data&&e(i.data),n(s)},[i,s]),L.useEffect(()=>{t.find(y=>y.id===Ar)||e(y=>[...y,{id:Ar,name:"",account_type:"Admin"}])},[i,t]);const c=(g,y,x)=>{e(S=>S.map(T=>T.id===g?{...T,[y]:x}:T))},d=async g=>{await o({url:"/api/settings/accounts",body:g}),a()},f=async g=>{await l({url:"/api/settings/accounts",body:g}),a()},m=async()=>{const g=t.find(y=>y.id===Ar);g&&await u({url:"/api/settings/accounts",body:{...g}}),a(),c(Ar,"name",""),c(Ar,"password",""),c(Ar,"account_type","Admin")};return E.jsxs(E.Fragment,{children:[E.jsx(_s,{className:"w-3/4 h-screen top-0 fixed bg-[--black] transition-all duration-300 pointer-events-none z-50 "+(r?"opacity-100":"opacity-0")}),E.jsx("h2",{className:`text-xl font-bold mb-4 ${r?"hidden":""}`,children:"Accounts Settings"}),E.jsxs("div",{className:`grid grid-cols-4 items-start gap-6 w-full ${r?"hidden":""}`,children:[t.map(g=>g.id!==Ar&&E.jsxs("div",{className:"max-w-md p-4 mb-4 rounded-lg bg-neutral-900 flex flex-col gap-2",children:[E.jsxs("h3",{className:"text-lg font-bold",children:["Account ID: ",g.id]}),E.jsx("input",{type:"text",value:g.name,onChange:y=>c(g.id,"name",y.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsxs("select",{value:g.account_type,onChange:y=>c(g.id,"account_type",y.target.value),className:"p-2 rounded bg-neutral-800 text-white",children:[E.jsx("option",{value:"Admin",children:"Admin"}),E.jsx("option",{value:"Adult",children:"Adult"}),E.jsx("option",{value:"Teen",children:"Teen"}),E.jsx("option",{value:"Kid",children:"Kid"})]}),E.jsx(Rn,{state:"primary",onClick:()=>d(g),children:"Save Account"}),E.jsx(Rn,{state:"danger",onClick:()=>f(g),children:"Delete Account"})]},g.id)),E.jsxs("div",{className:"max-w-md p-4 mb-4 rounded-lg bg-neutral-900 flex flex-col gap-2",children:[E.jsx("h3",{className:"text-lg font-bold",children:"Create New Account"}),E.jsx("input",{type:"text",placeholder:"Name",autoComplete:"new-password",value:(h=t.find(g=>g.id===Ar))==null?void 0:h.name,onChange:g=>c(Ar,"name",g.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsxs("select",{value:(p=t.find(g=>g.id===Ar))==null?void 0:p.account_type,onChange:g=>c(Ar,"account_type",g.target.value),className:" p-2 rounded bg-neutral-800 text-white",children:[E.jsx("option",{value:"Admin",children:"Admin"}),E.jsx("option",{value:"Adult",children:"Adult"}),E.jsx("option",{value:"Teen",children:"Teen"}),E.jsx("option",{value:"Kid",children:"Kid"})]}),E.jsx("input",{type:"password",placeholder:"Password",autoComplete:"new-password",value:(v=t.find(g=>g.id===Ar))==null?void 0:v.password,onChange:g=>c(Ar,"password",g.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsx(Rn,{state:"primary",onClick:m,children:"Create Account"})]})]})]})},_r=-162,W2=()=>{var v,g,y;const[t,e]=L.useState([]),[r,n]=L.useState(!0),{data:i,loading:s,fetchData:a}=ur("/api/settings/libraries"),{handleSubmit:o}=Ss(),{handleSubmit:l}=Ss(),{handleSubmit:u}=iE(),{handleSubmit:c}=sE();L.useEffect(()=>{i&&i.data&&e(i.data),n(s)},[i,s]),L.useEffect(()=>{t.find(S=>S.id===_r)||e(S=>[...S,{id:_r,name:"",path:"",type:"movies"}])},[i,t]);const d=(x,S,T)=>{e(C=>C.map(_=>_.id===x?{..._,[S]:T}:_))},f=async x=>{await o({url:"/api/settings/libraries",body:x}),a()},m=async x=>{await l({url:"/api/settings/libraries",body:{...x,scan:!0}})},h=async x=>{await u({url:"/api/settings/libraries",body:x}),a()},p=async()=>{const x=t.find(S=>S.id===_r);x&&await c({url:"/api/settings/libraries",body:{...x}}),a(),d(_r,"name",""),d(_r,"path",""),d(_r,"type","movies")};return E.jsxs(E.Fragment,{children:[E.jsx(_s,{className:"w-3/4 h-screen top-0 fixed bg-[--black] transition-all duration-300 pointer-events-none z-50 "+(r?"opacity-100":"opacity-0")}),E.jsx("h2",{className:`text-xl font-bold mb-4 ${r?"hidden":""}`,children:"Libraries Settings"}),E.jsxs("div",{className:`grid grid-cols-4 items-start gap-6 w-full ${r?"hidden":""}`,children:[t.map(x=>x.id!==_r&&E.jsxs("div",{className:"max-w-md p-4 mb-4 rounded-lg bg-neutral-900 flex flex-col gap-2",children:[E.jsxs("h3",{className:"text-lg font-bold",children:["Library ID: ",x.id]}),E.jsx("input",{type:"text",value:x.name,onChange:S=>d(x.id,"name",S.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsx("input",{type:"text",value:x.path,onChange:S=>d(x.id,"path",S.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsxs("select",{value:x.type,onChange:S=>d(x.id,"type",S.target.value),className:"p-2 rounded bg-neutral-800 text-white",children:[E.jsx("option",{value:"movies",children:"Movies"}),E.jsx("option",{value:"series",children:"Series"}),E.jsx("option",{value:"tv",children:"TV"}),E.jsx("option",{value:"books",children:"Books"}),E.jsx("option",{value:"music",children:"Music"}),E.jsx("option",{value:"other",children:"Other"})]}),E.jsx(Rn,{state:"primary",onClick:()=>f(x),children:"Save Library"}),E.jsx(Rn,{state:"secondary",className:"border border-zinc-700",onClick:()=>m(x),children:"Scan Library"}),E.jsx(Rn,{state:"danger",onClick:()=>h(x),children:"Delete Library"})]},x.id)),E.jsxs("div",{className:"max-w-md p-4 mb-4 rounded-lg bg-neutral-900 flex flex-col gap-2",children:[E.jsx("h3",{className:"text-lg font-bold",children:"Create New Library"}),E.jsx("input",{type:"text",placeholder:"Name",value:(v=t.find(x=>x.id===_r))==null?void 0:v.name,onChange:x=>d(_r,"name",x.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsx("input",{type:"text",placeholder:"Path",value:(g=t.find(x=>x.id===_r))==null?void 0:g.path,onChange:x=>d(_r,"path",x.target.value),className:"p-2 rounded bg-neutral-800 text-white"}),E.jsxs("select",{value:(y=t.find(x=>x.id===_r))==null?void 0:y.type,onChange:x=>d(_r,"type",x.target.value),className:"p-2 rounded bg-neutral-800 text-white",children:[E.jsx("option",{value:"movies",children:"Movies"}),E.jsx("option",{value:"series",children:"Series"}),E.jsx("option",{value:"tv",children:"TV"}),E.jsx("option",{value:"books",children:"Books"}),E.jsx("option",{value:"music",children:"Music"}),E.jsx("option",{value:"other",children:"Other"})]}),E.jsx(Rn,{state:"primary",onClick:p,children:"Create Library"})]})]})]})},K2=()=>{const[t,e]=L.useState(window.location.hash||"#general"),{data:r}=ur("/api/auth/check"),n=Br();return L.useEffect(()=>{r&&(!r.data||r.data.account_type!=="Admin")&&n("/")},[r]),L.useEffect(()=>{const i=()=>{e(window.location.hash||"#general")};return window.addEventListener("hashchange",i),()=>{window.removeEventListener("hashchange",i)}},[]),E.jsxs("div",{className:"flex h-screen",children:[E.jsxs("div",{className:"w-1/6 border-r-2 border-zinc-800 text-white p-4",children:[E.jsx("h2",{className:"text-xl font-bold mb-4",children:"Settings"}),E.jsxs("ul",{children:[E.jsx("li",{className:"mb-2",children:E.jsx("a",{href:"#general",className:`hover:underline ${t==="#general"?"font-bold":""}`,children:"General"})}),E.jsx("li",{className:"mb-2",children:E.jsx("a",{href:"#accounts",className:`hover:underline ${t==="#accounts"?"font-bold":""}`,children:"Accounts"})}),E.jsx("li",{className:"mb-2",children:E.jsx("a",{href:"#libraries",className:`hover:underline ${t==="#libraries"?"font-bold":""}`,children:"Libraries"})})]})]}),E.jsxs("div",{className:"w-5/6 p-4 overflow-y-scroll",children:[t==="#general"&&E.jsx(z2,{}),t==="#accounts"&&E.jsx(H2,{}),t==="#libraries"&&E.jsx(W2,{})]})]})};function Y2(){const{data:t}=ur("/api/profil"),{handleSubmit:e}=Ss(),[r,n]=L.useState(null),[i,s]=L.useState(""),[a,o]=L.useState(""),[l,u]=L.useState(""),[c,d]=L.useState(null);L.useEffect(()=>{t&&(n(t.data.id),s(t.data.name),u(t.data.profile_picture))},[t]);const f=h=>{var v;const p=(v=h.target.files)==null?void 0:v[0];if(p){d(p);const g=new FileReader;g.onloadend=()=>{const y=new Image;y.src=g.result,y.onload=()=>{const x=document.createElement("canvas"),S=Math.min(y.width,y.height);x.width=S,x.height=S;const T=x.getContext("2d");T&&(T.drawImage(y,(y.width-S)/2,(y.height-S)/2,S,S,0,0,S,S),u(x.toDataURL("image/jpeg")))}},g.readAsDataURL(p)}},m=async h=>{h.preventDefault();const p={id:r,name:i,image:l,password:a};try{await e({url:"/api/profil",body:p}).then(()=>{Ke.success("Profil updated")})}catch{Ke.error("Error updating profil")}};return E.jsxs(Sm,{className:"w-full max-w-md mx-auto mt-8",children:[E.jsx(Em,{children:E.jsx(Tm,{className:"text-2xl font-bold text-center",children:"Profil"})}),E.jsx($E,{children:E.jsxs("form",{onSubmit:m,className:"space-y-4",children:[E.jsxs("div",{className:"space-y-2",children:[E.jsx(Ao,{htmlFor:"avatar",children:"Photo de profil"}),E.jsxs("div",{className:"flex items-center space-x-4",children:[E.jsx("img",{src:l,alt:"avatar",className:"w-12 h-12 rounded-full"}),E.jsx(fs,{id:"avatar",type:"file",accept:"image/*",onChange:f,className:"w-full"})]})]}),E.jsxs("div",{className:"space-y-2",children:[E.jsx(Ao,{htmlFor:"name",children:"Nom"}),E.jsx(fs,{id:"name",type:"text",value:i,onChange:h=>s(h.target.value),placeholder:"Votre nom"})]}),E.jsxs("div",{className:"space-y-2",children:[E.jsx(Ao,{htmlFor:"password",children:"Mot de passe"}),E.jsx(fs,{id:"password",type:"password",value:a,onChange:h=>o(h.target.value),placeholder:"Nouveau mot de passe"})]})]})}),E.jsx(jE,{children:E.jsx(xm,{onClick:m,className:"w-full",children:"Enregistrer"})})]})}const q2=()=>E.jsx("section",{className:"flex justify-center items-center w-screen h-screen fixed top-0",children:E.jsxs("div",{className:"text-center flex flex-col items-center gap-2",children:[E.jsx("h1",{className:"font-bold text-4xl",children:"404"}),E.jsx("h1",{className:"font-bold text-2xl",children:"Page Not Found"}),E.jsx("p",{children:"Sorry, the page you are looking for does not exist."}),E.jsx("p",{children:"If you were redirected here, the page is not implemented yet."}),E.jsx(Rn,{state:"primary",to:"/",className:"mt-4 w-fit",children:"Go Home"})]})}),X2=()=>{const{type:t}=VS();return t&&["movie","show","live-tv","other"].includes(t)?E.jsx(EF,{}):E.jsx(HS,{to:"/home"})},Z2=g_([{path:"/login",element:E.jsx(AC,{})},{path:"/logout",element:E.jsx(_C,{})},{path:"/invite",element:E.jsx(KI,{})},{path:"/",element:E.jsx(my,{}),children:[{path:"/",element:E.jsx(HS,{to:"/home"})},{path:"/home",element:E.jsx(MD,{})},{path:"/movies",element:E.jsx(ND,{})},{path:"/shows",element:E.jsx(FD,{})},{path:"/watch/:type/:id",element:E.jsx(X2,{})},{path:"/settings",element:E.jsx(K2,{})},{path:"/profil",element:E.jsx(Y2,{})}]},{path:"*",element:E.jsx(my,{}),children:[{path:"*",element:E.jsx(q2,{})}]}]);RS(document.getElementById("root")).render(E.jsxs(E.Fragment,{children:[E.jsx(OD,{children:E.jsx(b_,{router:Z2})}),E.jsx(G_,{theme:"colored",position:"bottom-right"})]})); diff --git a/src/chocolate_app/templates/index.html b/src/chocolate_app/templates/index.html index 2e5576a..aa80c16 100644 --- a/src/chocolate_app/templates/index.html +++ b/src/chocolate_app/templates/index.html @@ -5,7 +5,7 @@ Chocolate - +