StreamGrabber

Lightweight HLS/Video downloader. Pause/Resume. AES-128. fMP4. Mobile + Desktop.

Tendrás que instalar una extensión para tu navegador como Tampermonkey, Greasemonkey o Violentmonkey si quieres utilizar este script.

You will need to install an extension such as Tampermonkey to install this script.

Tendrás que instalar una extensión como Tampermonkey o Violentmonkey para instalar este script.

Necesitarás instalar una extensión como Tampermonkey o Userscripts para instalar este script.

Tendrás que instalar una extensión como Tampermonkey antes de poder instalar este script.

Necesitarás instalar una extensión para administrar scripts de usuario si quieres instalar este script.

(Ya tengo un administrador de scripts de usuario, déjame instalarlo)

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Tendrás que instalar una extensión como Stylus antes de poder instalar este script.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

Para poder instalar esto tendrás que instalar primero una extensión de estilos de usuario.

(Ya tengo un administrador de estilos de usuario, déjame instalarlo)

// ==UserScript==
// @name         StreamGrabber
// @namespace    https://github.com/streamgrabber-lite
// @version      2.1.0
// @author       StreamGrabber
// @description  Lightweight HLS/Video downloader. Pause/Resume. AES-128. fMP4. Mobile + Desktop.
// @license      MIT
// @match        *://*/*
// @exclude      *://*.youtube.com/*
// @exclude      *://*.youtu.be/*
// @exclude      *://*.x.com/*
// @exclude      *://*.twitch.tv/*
// @exclude      *://*.reddit.com/*
// @exclude      *://*.redd.it/*
// @exclude      *://*.facebook.com/*
// @exclude      *://*.instagram.com/*
// @exclude      *://*.tiktok.com/*
// @exclude      *://*.netflix.com/*
// @exclude      *://*.hulu.com/*
// @exclude      *://*.disneyplus.com/*
// @exclude      *://*.primevideo.com/*
// @exclude      *://*.spotify.com/*
// @exclude      *://music.youtube.com/*
// @exclude      *://*.soundcloud.com/*
// @exclude      *://*.deezer.com/*
// @exclude      *://*.lastpass.com/*
// @exclude      *://*.1password.com/*
// @exclude      *://*.bitwarden.com/*
// @exclude      *://*.dashlane.com/*
// @exclude      *://*.irctc.co.in/*
// @connect      *
// @grant        GM_addStyle
// @grant        GM_download
// @grant        GM_getValue
// @grant        GM_notification
// @grant        GM_registerMenuCommand
// @grant        GM_setValue
// @grant        GM_xmlhttpRequest
// @grant        unsafeWindow
// @run-at       document-start
// ==/UserScript==

(function () {
  'use strict';

  const tt={RETRIES:3,CONCURRENCY:6,REQUEST_TIMEOUT:6e4,MANIFEST_TIMEOUT:3e4,SMALL_BYTES:1048576,UI_IDLE_MS:5e3,ENRICH_DELAY:150,DETECT_DEBOUNCE:50,ENRICH_TIMEOUT:1e4,IS_TOP:window.self===window.top},ae={TEXT_MAX:256,DB_MAX:120,CLEAR_MS:12e4},Xe={EXCLUDE_SMALL:"sg_exclude_small"},st=new Map;function xe(e){const t=[];for(const[n,r]of st)e(n,r)&&(st.delete(n),t.push(n));return t}class Me{listeners=new Set;subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}dispatch(t){for(const n of this.listeners)try{n(t);}catch(r){console.error("[SG] Event dispatch error:",r);}}}class Cn{items=new Map;m3u8Urls=new Set;videoUrls=new Set;watchedVideos=new WeakSet;excludeSmall;_validCount=0;_validCountDirty=true;events={itemAdded:new Me,updated:new Me};constructor(){this.excludeSmall=GM_getValue(Xe.EXCLUDE_SMALL,true);}hasItem(t){return this.items.has(t)}getItem(t){return this.items.get(t)}addItem(t){return this.items.has(t.url)?false:(this.items.set(t.url,t),t.kind==="hls"?this.m3u8Urls.add(t.url):this.videoUrls.add(t.url),this.invalidateCount(),this.enforceLimit(),this.events.itemAdded.dispatch(t),this.events.updated.dispatch(),true)}enforceLimit(){for(;this.items.size>ae.DB_MAX;){const t=this.items.keys().next().value;if(t===void 0)break;const n=this.items.get(t);this.items.delete(t),n&&(this.m3u8Urls.delete(n.url),this.videoUrls.delete(n.url));}this.invalidateCount();}get validCount(){if(this._validCountDirty){let t=0;for(const n of this.items.values())n.hlsType!=="invalid"&&n.hlsType!=="error"&&t++;this._validCount=t,this._validCountDirty=false;}return this._validCount}invalidateCount(){this._validCountDirty=true;}getAllItems(){return Array.from(this.items.values()).reverse()}getFilteredItems(){const t=this.getAllItems();return this.excludeSmall?t.filter(n=>n.size==null||n.size>=tt.SMALL_BYTES):t}setExcludeSmall(t){this.excludeSmall=t,GM_setValue(Xe.EXCLUDE_SMALL,t);}clear(){this.items.clear(),this.m3u8Urls.clear(),this.videoUrls.clear(),xe(()=>true),this.invalidateCount();}trim(){this.enforceLimit();const t=Date.now(),n=xe((r,c)=>{const m=t-(c.ts||0);return !!(c.revoked&&m>ae.CLEAR_MS)});for(const r of n)this.items.has(r)&&(this.items.delete(r),this.m3u8Urls.delete(r),this.videoUrls.delete(r),this.invalidateCount());}}const nt=new Cn;tt.IS_TOP&&(setInterval(()=>nt.trim(),ae.CLEAR_MS),window.addEventListener("pagehide",()=>nt.trim()),window.addEventListener("beforeunload",()=>nt.trim()));const vt={http:/^https?:/i,blob:/^blob:/i,m3u8:/\.m3u8(\b|[?#]|$)/i,video:/\.(mp4|mkv|webm|avi|mov|m4v|flv|ogv|ogg)([?#]|$)/i,segment:/\.(m4s|init|seg|fmp4|ts|m2ts)([?#]|$)/i,m3u8Type:/mpegurl|vnd\.apple\.mpegurl|application\/x-mpegurl/i,videoType:/^video\//i,videoTypeAlt:/(matroska|mp4|webm|quicktime)/i,resolutionCombined:/(?:^|[_\-\/])(\d{3,4})([px])(\d{3,4})?(?:[_\-\/\.]|$)|resolution[=_]?(\d{3,4})|quality[=_]?(\d{3,4})|[_\-]hd(\d{3,4})|(\d{3,4})\.m3u8/i},On=e=>typeof e=="string"&&vt.http.test(e),zt=e=>typeof e=="string"&&vt.blob.test(e),Dn=e=>vt.m3u8.test(e||""),Xn=e=>vt.video.test(e||""),xn=e=>vt.segment.test(e||""),Mn=e=>vt.m3u8Type.test(e||""),kn=e=>vt.videoType.test(e||"")||vt.videoTypeAlt.test(e||"");function Jt(e,t){try{return new URL(e,t).href}catch{return e}}function Qe(e){if(!e)return null;const t=vt.resolutionCombined.exec(e);if(t){if(t[1]){const r=parseInt(t[1],10),c=t[2],m=t[3];if(c==="x"&&m)return `${r}x${m}`;if(r>=144&&r<=4320)return `${r}p`}const n=t[4]||t[5]||t[6]||t[7];if(n){const r=parseInt(n,10);if(r>=144&&r<=4320)return `${r}p`}}return null}const ke=["B","KB","MB","GB","TB"];function Ht(e){if(e==null)return "";let t=0,n=e;for(;n>=1024&&t<ke.length-1;)n/=1024,t++;const r=n<10&&t>0?1:0;return `${n.toFixed(r)} ${ke[t]}`}function Un(e){if(!e||e<=0)return null;const t=Math.floor(e/3600),n=Math.floor(e%3600/60),r=Math.floor(e%60),c=m=>String(m).padStart(2,"0");return t>0?`${t}:${c(n)}:${c(r)}`:`${n}:${c(r)}`}function Ze(e){return (e||"video").replace(/[\\/:*?"<>|]/g,"_").slice(0,120).trim()||"video"}const _n={webm:"webm",matroska:"mkv",mkv:"mkv",quicktime:"mov",mov:"mov",mp2t:"ts",mpegts:"ts",ogg:"ogg",mp4:"mp4"};function Vn(e){const t=e.toLowerCase();for(const[n,r]of Object.entries(_n))if(t.includes(n))return r;return "mp4"}function Je(e,t){const n=/(?:\.([a-z0-9]+))([?#]|$)/i.exec(e||"");return n?n[1].toLowerCase():t?Vn(t):"mp4"}function pe(e){if(!e)return null;const t=/bytes=(\d+)-(\d+)?/i.exec(e);return t?{start:+t[1],end:t[2]!=null?+t[2]:null}:null}function Yn(e,t){if(!e.has(t))return;const n=e.get(t);return e.delete(t),e.set(t,n),n}function Fn(e,t,n,r){if(e.has(t)&&e.delete(t),e.set(t,n),typeof r=="number"&&isFinite(r))for(;e.size>r;){const c=e.keys().next().value;c!==void 0&&e.delete(c);}}function tn(e,t,n,r,c){const m=Yn(e,n);if(m!==void 0)return Promise.resolve(m);if(t.has(n))return t.get(n);const h=(async()=>{try{const b=await r();return Fn(e,n,b,c),b}finally{t.delete(n);}})();return t.set(n,h),h}document.createElement("div");let me=null;const te=[];function Gn(e){if(me=e,te.length>0){const t=[...te];te.length=0,t.forEach(({url:n,metadata:r})=>e(n,r));}}function en(e){return typeof e=="string"&&e.trim().startsWith("#EXTM3U")}function At(e,t){me?me(e,t):te.push({url:e,metadata:t});}function Bn(){const e=URL.createObjectURL;URL.createObjectURL=function(t){const n=e.call(this,t);try{const r=Date.now();if(t instanceof Blob){const c=t.type||"",m={blob:t,type:c,size:t.size,kind:"other",ts:r};Mn(c)?(m.kind="m3u8",st.set(n,m),At(n)):kn(c)?(m.kind="video",st.set(n,m),At(n)):/octet-stream|text\/plain|^$/.test(c)&&t.size>0?t.slice(0,Math.min(2048,t.size)).text().then(b=>{/^#EXTM3U/i.test(b)&&(m.kind="m3u8"),st.set(n,m),m.kind==="m3u8"&&At(n);}).catch(()=>{st.set(n,m);}):st.set(n,m);}else st.set(n,{blob:null,type:"mediasource",size:0,kind:"other",ts:r});}catch(r){console.error("[SG] createObjectURL hook error:",r);}return n};}function jn(){const e=URL.revokeObjectURL;URL.revokeObjectURL=function(t){try{const n=st.get(t);n&&(n.revoked=!0,n.ts=Date.now());}catch{}return e.call(this,t)};}function zn(){const e=window.fetch,t=window.Response.prototype.text;typeof e=="function"&&(window.Response.prototype.text=function(){return new Promise((n,r)=>{t.call(this).then(c=>{n(c);try{en(c)&&At(this.url);}catch(m){console.error("[SG] Detection error in Response.text:",m);}}).catch(r);})},window.fetch=function(...n){try{const r=n[0],c=typeof r=="string"?r:r instanceof Request?r.url:r.href;c&&At(c);}catch{}return e.apply(this,n)});}function Hn(){const e=XMLHttpRequest.prototype.open;XMLHttpRequest.prototype.open=function(t,n,...r){try{const m=typeof n=="string"?n:n?.href;m&&At(m);}catch{}const c=e.call(this,t,n,...r);return this.addEventListener("load",()=>{try{if(!this.responseType||this.responseType==="text"){const m=this.responseText,h=typeof n=="string"?n:n?.href;h&&en(m)&&At(h);}}catch{}}),c};}function qn(){try{new PerformanceObserver(t=>{for(const n of t.getEntries())"name"in n&&typeof n.name=="string"&&At(n.name);}).observe({entryTypes:["resource"]});}catch{}}let Ue=false;function $n(){Ue||(Ue=true,Bn(),jn(),zn(),Hn(),qn());}let nn=()=>{};function Kn(e){nn=e;}function ge(e){if(nt.watchedVideos.has(e))return;nt.watchedVideos.add(e);const t=()=>{[e.currentSrc||e.src,...Array.from(e.querySelectorAll("source")).map(c=>c.src)].filter(Boolean).forEach(nn);};["loadstart","loadedmetadata","canplay"].forEach(r=>e.addEventListener(r,t)),t();}function _e(){document.querySelectorAll("video").forEach(e=>ge(e));}let le=null;function Ve(){le||(le=new MutationObserver(e=>{for(const t of e)for(const n of t.addedNodes)n instanceof Element&&(n.tagName==="VIDEO"?ge(n):n.querySelectorAll?.("video")?.forEach(r=>{ge(r);}));}),le.observe(document.documentElement,{childList:true,subtree:true}));}const ce=new Set;function Ye(e,t){ce.has(e)||(ce.add(e),setTimeout(()=>{ce.delete(e),t(e);},tt.DETECT_DEBOUNCE));}function Wn(e,t,n={}){const{size:r=null,type:c=null}=n;let m;if(t==="hls"){const h=Qe(e);m=h?`${h} • Analyzing...`:"Analyzing...";}else m=Je(e,c).toUpperCase();return {url:e,kind:t,label:m,sublabel:null,size:r,type:c,origin:document.location.origin,enriched:false,enriching:false,hlsType:null,isLive:false,encrypted:false,_enrichPromise:null}}let rn=()=>{};function Qn(e){rn=e;}function Fe(e){try{if(!e||!On(e)&&!zt(e)||xn(e))return;const t=e.toLowerCase();if(t.includes("ping.gif")||t.includes("jwpltx.com")||t.includes("doubleclick")||t.includes("analytics")||t.includes("/stats/")||nt.hasItem(e))return;let n=null,r=null;if(zt(e)){const T=st.get(e);if(T&&(n=T.size,r=T.type),n!=null&&n<512*1024&&T?.kind!=="m3u8")return}const c=Dn(e)||zt(e)&&st.get(e)?.kind==="m3u8",m=Xn(e)||zt(e)&&st.get(e)?.kind==="video",h=c?"hls":m?"video":null;if(!h)return;const b=Wn(e,h,{size:n,type:r});nt.addItem(b)&&rn(b);}catch(t){console.error("[SG] processUrl error:",t);}}let Ge=false;function Zn(){Ge||(Ge=true,Gn(e=>Ye(e,Fe)),Kn(e=>Ye(e,Fe)),$n(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{_e(),Ve();}):(_e(),Ve()));}function Jn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ue={exports:{}},Be;function tr(){return Be||(Be=1,(function(e){var t=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=false));function c(T,A,L){this.fn=T,this.context=A,this.once=L||false;}function m(T,A,L,O,k){if(typeof L!="function")throw new TypeError("The listener must be a function");var v=new c(L,O||T,k),I=n?n+A:A;return T._events[I]?T._events[I].fn?T._events[I]=[T._events[I],v]:T._events[I].push(v):(T._events[I]=v,T._eventsCount++),T}function h(T,A){--T._eventsCount===0?T._events=new r:delete T._events[A];}function b(){this._events=new r,this._eventsCount=0;}b.prototype.eventNames=function(){var A=[],L,O;if(this._eventsCount===0)return A;for(O in L=this._events)t.call(L,O)&&A.push(n?O.slice(1):O);return Object.getOwnPropertySymbols?A.concat(Object.getOwnPropertySymbols(L)):A},b.prototype.listeners=function(A){var L=n?n+A:A,O=this._events[L];if(!O)return [];if(O.fn)return [O.fn];for(var k=0,v=O.length,I=new Array(v);k<v;k++)I[k]=O[k].fn;return I},b.prototype.listenerCount=function(A){var L=n?n+A:A,O=this._events[L];return O?O.fn?1:O.length:0},b.prototype.emit=function(A,L,O,k,v,I){var S=n?n+A:A;if(!this._events[S])return  false;var f=this._events[S],y=arguments.length,d,X;if(f.fn){switch(f.once&&this.removeListener(A,f.fn,void 0,true),y){case 1:return f.fn.call(f.context),true;case 2:return f.fn.call(f.context,L),true;case 3:return f.fn.call(f.context,L,O),true;case 4:return f.fn.call(f.context,L,O,k),true;case 5:return f.fn.call(f.context,L,O,k,v),true;case 6:return f.fn.call(f.context,L,O,k,v,I),true}for(X=1,d=new Array(y-1);X<y;X++)d[X-1]=arguments[X];f.fn.apply(f.context,d);}else {var V=f.length,G;for(X=0;X<V;X++)switch(f[X].once&&this.removeListener(A,f[X].fn,void 0,true),y){case 1:f[X].fn.call(f[X].context);break;case 2:f[X].fn.call(f[X].context,L);break;case 3:f[X].fn.call(f[X].context,L,O);break;case 4:f[X].fn.call(f[X].context,L,O,k);break;default:if(!d)for(G=1,d=new Array(y-1);G<y;G++)d[G-1]=arguments[G];f[X].fn.apply(f[X].context,d);}}return  true},b.prototype.on=function(A,L,O){return m(this,A,L,O,false)},b.prototype.once=function(A,L,O){return m(this,A,L,O,true)},b.prototype.removeListener=function(A,L,O,k){var v=n?n+A:A;if(!this._events[v])return this;if(!L)return h(this,v),this;var I=this._events[v];if(I.fn)I.fn===L&&(!k||I.once)&&(!O||I.context===O)&&h(this,v);else {for(var S=0,f=[],y=I.length;S<y;S++)(I[S].fn!==L||k&&!I[S].once||O&&I[S].context!==O)&&f.push(I[S]);f.length?this._events[v]=f.length===1?f[0]:f:h(this,v);}return this},b.prototype.removeAllListeners=function(A){var L;return A?(L=n?n+A:A,this._events[L]&&h(this,L)):(this._events=new r,this._eventsCount=0),this},b.prototype.off=b.prototype.removeListener,b.prototype.addListener=b.prototype.on,b.prefixed=n,b.EventEmitter=b,e.exports=b;})(ue)),ue.exports}var er=tr();const nr=Jn(er);class Ie extends Error{name="TimeoutError";constructor(t,n){super(t,n),Error.captureStackTrace?.(this,Ie);}}const je=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function rr(e,t){const{milliseconds:n,fallback:r,message:c,customTimers:m={setTimeout,clearTimeout},signal:h}=t;let b,T;const L=new Promise((O,k)=>{if(typeof n!="number"||Math.sign(n)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${n}\``);if(h?.aborted){k(je(h));return}if(h&&(T=()=>{k(je(h));},h.addEventListener("abort",T,{once:true})),e.then(O,k),n===Number.POSITIVE_INFINITY)return;const v=new Ie;b=m.setTimeout.call(void 0,()=>{if(r){try{O(r());}catch(I){k(I);}return}typeof e.cancel=="function"&&e.cancel(),c===false?O():c instanceof Error?k(c):(v.message=c??`Promise timed out after ${n} milliseconds`,k(v));},n);}).finally(()=>{L.clear(),T&&h&&h.removeEventListener("abort",T);});return L.clear=()=>{m.clearTimeout.call(void 0,b),b=void 0;},L}function ir(e,t,n){let r=0,c=e.length;for(;c>0;){const m=Math.trunc(c/2);let h=r+m;n(e[h],t)<=0?(r=++h,c-=m+1):c=m;}return r}class ar{#n=[];enqueue(t,n){const{priority:r=0,id:c}=n??{},m={priority:r,id:c,run:t};if(this.size===0||this.#n[this.size-1].priority>=r){this.#n.push(m);return}const h=ir(this.#n,m,(b,T)=>T.priority-b.priority);this.#n.splice(h,0,m);}setPriority(t,n){const r=this.#n.findIndex(m=>m.id===t);if(r===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);const[c]=this.#n.splice(r,1);this.enqueue(c.run,{priority:n,id:t});}dequeue(){return this.#n.shift()?.run}filter(t){return this.#n.filter(n=>n.priority===t.priority).map(n=>n.run)}get size(){return this.#n.length}}class an extends nr{#n;#o;#s=0;#h;#m=false;#E=false;#l;#N=0;#y=0;#c;#u;#a;#i=[];#r=0;#t;#R;#e=0;#g;#d;#D=1n;#v=new Map;timeout;constructor(t){if(super(),t={carryoverIntervalCount:false,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:true,queueClass:ar,strict:false,...t},!(typeof t.intervalCap=="number"&&t.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${t.intervalCap?.toString()??""}\` (${typeof t.intervalCap})`);if(t.interval===void 0||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${t.interval?.toString()??""}\` (${typeof t.interval})`);if(t.strict&&t.interval===0)throw new TypeError("The `strict` option requires a non-zero `interval`");if(t.strict&&t.intervalCap===Number.POSITIVE_INFINITY)throw new TypeError("The `strict` option requires a finite `intervalCap`");if(this.#n=t.carryoverIntervalCount??t.carryoverConcurrencyCount??false,this.#o=t.intervalCap===Number.POSITIVE_INFINITY||t.interval===0,this.#h=t.intervalCap,this.#l=t.interval,this.#a=t.strict,this.#t=new t.queueClass,this.#R=t.queueClass,this.concurrency=t.concurrency,t.timeout!==void 0&&!(Number.isFinite(t.timeout)&&t.timeout>0))throw new TypeError(`Expected \`timeout\` to be a positive finite number, got \`${t.timeout}\` (${typeof t.timeout})`);this.timeout=t.timeout,this.#d=t.autoStart===false,this.#Y();}#T(t){for(;this.#r<this.#i.length;){const r=this.#i[this.#r];if(r!==void 0&&t-r>=this.#l)this.#r++;else break}(this.#r>100&&this.#r>this.#i.length/2||this.#r===this.#i.length)&&(this.#i=this.#i.slice(this.#r),this.#r=0);}#X(t){this.#a?this.#i.push(t):this.#s++;}#x(){this.#a?this.#i.length>this.#r&&this.#i.pop():this.#s>0&&this.#s--;}#b(){return this.#i.length-this.#r}get#M(){return this.#o?true:this.#a?this.#b()<this.#h:this.#s<this.#h}get#k(){return this.#e<this.#g}#U(){this.#e--,this.#e===0&&this.emit("pendingZero"),this.#w(),this.emit("next");}#_(){this.#u=void 0,this.#C(),this.#L();}#V(t){if(this.#a){if(this.#T(t),this.#b()>=this.#h){const r=this.#i[this.#r],c=this.#l-(t-r);return this.#I(c),true}return  false}if(this.#c===void 0){const n=this.#N-t;if(n<0){if(this.#y>0){const r=t-this.#y;if(r<this.#l)return this.#I(this.#l-r),true}this.#s=this.#n?this.#e:0;}else return this.#I(n),true}return  false}#I(t){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#_();},t));}#S(){this.#c&&(clearInterval(this.#c),this.#c=void 0);}#P(){this.#u&&(clearTimeout(this.#u),this.#u=void 0);}#w(){if(this.#t.size===0){if(this.#S(),this.emit("empty"),this.#e===0){if(this.#P(),this.#a&&this.#r>0){const n=Date.now();this.#T(n);}this.emit("idle");}return  false}let t=false;if(!this.#d){const n=Date.now(),r=!this.#V(n);if(this.#M&&this.#k){const c=this.#t.dequeue();this.#o||(this.#X(n),this.#p()),this.emit("active"),c(),r&&this.#L(),t=true;}}return t}#L(){this.#o||this.#c!==void 0||this.#a||(this.#c=setInterval(()=>{this.#C();},this.#l),this.#N=Date.now()+this.#l);}#C(){this.#a||(this.#s===0&&this.#e===0&&this.#c&&this.#S(),this.#s=this.#n?this.#e:0),this.#A(),this.#p();}#A(){for(;this.#w(););}get concurrency(){return this.#g}set concurrency(t){if(!(typeof t=="number"&&t>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${t}\` (${typeof t})`);this.#g=t,this.#A();}setPriority(t,n){if(typeof n!="number"||!Number.isFinite(n))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${n}\` (${typeof n})`);this.#t.setPriority(t,n);}async add(t,n={}){return n={timeout:this.timeout,...n,id:n.id??(this.#D++).toString()},new Promise((r,c)=>{const m=Symbol(`task-${n.id}`);this.#t.enqueue(async()=>{this.#e++,this.#v.set(m,{id:n.id,priority:n.priority??0,startTime:Date.now(),timeout:n.timeout});let h;try{try{n.signal?.throwIfAborted();}catch(A){throw this.#F(),this.#v.delete(m),A}this.#y=Date.now();let b=t({signal:n.signal});if(n.timeout&&(b=rr(Promise.resolve(b),{milliseconds:n.timeout,message:`Task timed out after ${n.timeout}ms (queue has ${this.#e} running, ${this.#t.size} waiting)`})),n.signal){const{signal:A}=n;b=Promise.race([b,new Promise((L,O)=>{h=()=>{O(A.reason);},A.addEventListener("abort",h,{once:!0});})]);}const T=await b;r(T),this.emit("completed",T);}catch(b){c(b),this.emit("error",b);}finally{h&&n.signal?.removeEventListener("abort",h),this.#v.delete(m),queueMicrotask(()=>{this.#U();});}},n),this.emit("add"),this.#w();})}async addAll(t,n){return Promise.all(t.map(async r=>this.add(r,n)))}start(){return this.#d?(this.#d=false,this.#A(),this):this}pause(){this.#d=true;}clear(){this.#t=new this.#R,this.#S(),this.#O(),this.emit("empty"),this.#e===0&&(this.#P(),this.emit("idle")),this.emit("next");}async onEmpty(){this.#t.size!==0&&await this.#f("empty");}async onSizeLessThan(t){this.#t.size<t||await this.#f("next",()=>this.#t.size<t);}async onIdle(){this.#e===0&&this.#t.size===0||await this.#f("idle");}async onPendingZero(){this.#e!==0&&await this.#f("pendingZero");}async onRateLimit(){this.isRateLimited||await this.#f("rateLimit");}async onRateLimitCleared(){this.isRateLimited&&await this.#f("rateLimitCleared");}onError(){return new Promise((t,n)=>{const r=c=>{this.off("error",r),n(c);};this.on("error",r);})}async#f(t,n){return new Promise(r=>{const c=()=>{n&&!n()||(this.off(t,c),r());};this.on(t,c);})}get size(){return this.#t.size}sizeBy(t){return this.#t.filter(t).length}get pending(){return this.#e}get isPaused(){return this.#d}#Y(){this.#o||(this.on("add",()=>{this.#t.size>0&&this.#p();}),this.on("next",()=>{this.#p();}));}#p(){this.#o||this.#E||(this.#E=true,queueMicrotask(()=>{this.#E=false,this.#O();}));}#F(){this.#o||(this.#x(),this.#p());}#O(){const t=this.#m;if(this.#o||this.#t.size===0){t&&(this.#m=false,this.emit("rateLimitCleared"));return}let n;if(this.#a){const c=Date.now();this.#T(c),n=this.#b();}else n=this.#s;const r=n>=this.#h;r!==t&&(this.#m=r,this.emit(r?"rateLimit":"rateLimitCleared"));}get isRateLimited(){return this.#m}get isSaturated(){return this.#e===this.#g&&this.#t.size>0||this.isRateLimited&&this.#t.size>0}get runningTasks(){return [...this.#v.values()].map(t=>({...t}))}}function on(e){return [...e].sort((t,n)=>(n.h||0)-(t.h||0)||(n.avg||n.peak||0)-(t.avg||t.peak||0))}function sn(e){const t=[];if(e.resolution&&t.push(e.resolution),e.bitrate&&t.push(`${Math.round(e.bitrate/1e3)}k`),e.duration&&e.duration>0){const n=Un(e.duration);n&&t.push(n);}return e.size!=null&&t.push(`~${Ht(e.size)}`),e.extra&&t.push(...e.extra),t.length>0?t.join(" • "):"Video Stream"}function or(e,t){return `${e} segments • ${t?"fMP4":"TS"}`}function sr(e,t={}){GM_notification({text:e,title:t.title??"StreamGrabber",timeout:t.timeout??3e3,onclick:t.onclick});}function Se(e){sr(`Download complete: ${e}`);}function lr(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}function ln(e,t){const n=lr(e);alert(n);}function we(){return Math.random().toString(36).slice(2)}const cr=["url","kind","label","sublabel","size","type","origin","enriched","enriching","hlsType","isLive","encrypted","duration","segCount","resolution","isVod","isFmp4","variantCount","variants","bestVariant","variant"];function ur(e){const t={};for(const n of cr)e[n]!==void 0&&(t[n]=e[n]);return t}function cn(e,t){if(!zt(e))return null;const n=t.get(e);return n?(n.ts=Date.now(),n):null}function dr(e,t){if(!t)return e;const n=pe(t);return n?e.slice(n.start,n.end==null?e.size:n.end+1):e}const fr=new Map,hr=new Map;function un(e){let t=null;const n=new Promise((r,c)=>{t=GM_xmlhttpRequest({method:"GET",url:e.url,responseType:e.responseType,headers:e.headers||{},timeout:e.timeout??tt.REQUEST_TIMEOUT,onprogress:m=>e.onprogress?.({loaded:m.loaded,total:m.total}),onload:m=>{m.status>=200&&m.status<300?r(m.response):c(new Error(`HTTP ${m.status}`));},onerror:()=>c(new Error("Network error")),ontimeout:()=>c(new Error("Timeout"))});});return n.abort=()=>{try{t?.abort();}catch{}},n}async function pr(e){const t=cn(e,st);if(t){if(!t.blob)throw new Error("Blob not found");return t.blob.text()}return un({url:e,responseType:"text",timeout:tt.MANIFEST_TIMEOUT})}function ee(e){return tn(fr,hr,e,()=>pr(e),ae.TEXT_MAX)}function de(e,t={},n=tt.REQUEST_TIMEOUT,r){const c=cn(e,st);if(c){if(!c.blob){const O=Promise.reject(new Error("Blob not found"));return O.abort=()=>{},O}const T=dr(c.blob,t.Range);r&&setTimeout(()=>r({loaded:T.size,total:T.size}),0);let A=false;const L=T.arrayBuffer().then(O=>{if(A)throw new Error("Aborted");return O});return L.abort=()=>{A=true;},L}let m=null,h=false;const b=new Promise(async(T,A)=>{try{if(h)throw new Error("Aborted");const O=new AbortController;m=()=>O.abort();const k=await fetch(e,{method:"GET",headers:t,signal:O.signal});if(!k.ok)throw new Error(`Status ${k.status}`);if(!k.body)throw new Error("No body");const v=k.body.getReader(),I=+(k.headers.get("Content-Length")||"0");let S=0;const f=[];for(;;){if(h)throw v.cancel(),new Error("Aborted");const{done:X,value:V}=await v.read();if(X)break;f.push(V),S+=V.length,r&&I&&r({loaded:S,total:I});}const y=new Uint8Array(S);let d=0;for(const X of f)y.set(X,d),d+=X.length;T(y.buffer);return}catch(O){if(h||O.name==="AbortError"){A(new Error("Aborted"));return}}if(h){A(new Error("Aborted"));return}const L=un({url:e,responseType:"arraybuffer",headers:t,timeout:n,onprogress:r});m=()=>L.abort(),L.then(T).catch(A);});return b.abort=()=>{h=true,m&&m();},b}var fe={exports:{}};var ze;function mr(){return ze||(ze=1,(function(e,t){(function(n,r){e.exports=r();})(self,(()=>(()=>{var n={31:function(m,h,b){function T(u){return T=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(a){return typeof a}:function(a){return a&&typeof Symbol=="function"&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},T(u)}function A(u,a){var s=Object.keys(u);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(u);a&&(i=i.filter((function(g){return Object.getOwnPropertyDescriptor(u,g).enumerable}))),s.push.apply(s,i);}return s}function L(u){for(var a=1;a<arguments.length;a++){var s=arguments[a]!=null?arguments[a]:{};a%2?A(Object(s),true).forEach((function(i){d(u,i,s[i]);})):Object.getOwnPropertyDescriptors?Object.defineProperties(u,Object.getOwnPropertyDescriptors(s)):A(Object(s)).forEach((function(i){Object.defineProperty(u,i,Object.getOwnPropertyDescriptor(s,i));}));}return u}function O(u,a,s){return a=v(a),(function(i,g){if(g&&(T(g)=="object"||typeof g=="function"))return g;if(g!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return (function(E){if(E===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return E})(i)})(u,k()?Reflect.construct(a,s||[],v(u).constructor):a.apply(u,s))}function k(){try{var u=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})));}catch{}return (k=function(){return !!u})()}function v(u){return v=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(a){return a.__proto__||Object.getPrototypeOf(a)},v(u)}function I(u,a){if(typeof a!="function"&&a!==null)throw new TypeError("Super expression must either be null or a function");u.prototype=Object.create(a&&a.prototype,{constructor:{value:u,writable:true,configurable:true}}),Object.defineProperty(u,"prototype",{writable:false}),a&&S(u,a);}function S(u,a){return S=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(s,i){return s.__proto__=i,s},S(u,a)}function f(u,a,s){return Object.defineProperty(u,"prototype",{writable:false}),u}function y(u,a){if(!(u instanceof a))throw new TypeError("Cannot call a class as a function")}function d(u,a,s){return (a=X(a))in u?Object.defineProperty(u,a,{value:s,enumerable:true,configurable:true,writable:true}):u[a]=s,u}function X(u){var a=(function(s,i){if(T(s)!="object"||!s)return s;var g=s[Symbol.toPrimitive];if(g!==void 0){var E=g.call(s,i);if(T(E)!="object")return E;throw new TypeError("@@toPrimitive must return a primitive value.")}return (i==="string"?String:Number)(s)})(u,"string");return T(a)=="symbol"?a:a+""}var V,G=this&&this.__createBinding||(Object.create?function(u,a,s,i){i===void 0&&(i=s);var g=Object.getOwnPropertyDescriptor(a,s);g&&!("get"in g?!a.__esModule:g.writable||g.configurable)||(g={enumerable:true,get:function(){return a[s]}}),Object.defineProperty(u,i,g);}:function(u,a,s,i){i===void 0&&(i=s),u[i]=a[s];}),rt=this&&this.__setModuleDefault||(Object.create?function(u,a){Object.defineProperty(u,"default",{enumerable:true,value:a});}:function(u,a){u.default=a;}),et=this&&this.__importStar||(V=function(u){return V=Object.getOwnPropertyNames||function(a){var s=[];for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(s[s.length]=i);return s},V(u)},function(u){if(u&&u.__esModule)return u;var a={};if(u!=null)for(var s=V(u),i=0;i<s.length;i++)s[i]!=="default"&&G(a,u,s[i]);return rt(a,u),a});Object.defineProperty(h,"__esModule",{value:true}),h.ContentSteering=h.RenditionReport=h.PrefetchSegment=h.PartialSegment=h.Segment=h.MediaPlaylist=h.MasterPlaylist=h.Playlist=h.SpliceInfo=h.DateRange=h.MediaInitializationSection=h.Key=h.SessionData=h.Variant=h.Rendition=void 0;var H=et(b(203)),Et=f((function u(a){var s=a.type,i=a.uri,g=a.groupId,E=a.language,C=a.assocLanguage,P=a.name,M=a.isDefault,N=a.autoselect,x=a.forced,U=a.instreamId,_=a.characteristics,F=a.channels,D=a.pathwayId;y(this,u),d(this,"type",void 0),d(this,"uri",void 0),d(this,"groupId",void 0),d(this,"language",void 0),d(this,"assocLanguage",void 0),d(this,"name",void 0),d(this,"isDefault",void 0),d(this,"autoselect",void 0),d(this,"forced",void 0),d(this,"instreamId",void 0),d(this,"characteristics",void 0),d(this,"channels",void 0),d(this,"pathwayId",void 0),H.PARAMCHECK(s,g,P),H.CONDITIONALASSERT([s==="SUBTITLES",i],[s==="CLOSED-CAPTIONS",U],[s==="CLOSED-CAPTIONS",!i],[x,s==="SUBTITLES"]),this.type=s,this.uri=i,this.groupId=g,this.language=E,this.assocLanguage=C,this.name=P,this.isDefault=M,this.autoselect=N,this.forced=x,this.instreamId=U,this.characteristics=_,this.channels=F,this.pathwayId=D;}));h.Rendition=Et;var at=f((function u(a){var s=a.uri,i=a.isIFrameOnly,g=i!==void 0&&i,E=a.bandwidth,C=a.averageBandwidth,P=a.score,M=a.codecs,N=a.resolution,x=a.frameRate,U=a.hdcpLevel,_=a.allowedCpc,F=a.videoRange,D=a.stableVariantId,Y=a.pathwayId,j=a.programId,K=a.audio,Z=K===void 0?[]:K,z=a.video,W=z===void 0?[]:z,q=a.subtitles,J=q===void 0?[]:q,Q=a.closedCaptions,it=Q===void 0?[]:Q,lt=a.currentRenditions,ut=lt===void 0?{audio:0,video:0,subtitles:0,closedCaptions:0}:lt;y(this,u),d(this,"uri",void 0),d(this,"isIFrameOnly",void 0),d(this,"bandwidth",void 0),d(this,"averageBandwidth",void 0),d(this,"score",void 0),d(this,"codecs",void 0),d(this,"resolution",void 0),d(this,"frameRate",void 0),d(this,"hdcpLevel",void 0),d(this,"allowedCpc",void 0),d(this,"videoRange",void 0),d(this,"stableVariantId",void 0),d(this,"pathwayId",void 0),d(this,"programId",void 0),d(this,"audio",void 0),d(this,"video",void 0),d(this,"subtitles",void 0),d(this,"closedCaptions",void 0),d(this,"currentRenditions",void 0),H.PARAMCHECK(s,E),this.uri=s,this.isIFrameOnly=g,this.bandwidth=E,this.averageBandwidth=C,this.score=P,this.codecs=M,this.resolution=N,this.frameRate=x,this.hdcpLevel=U,this.allowedCpc=_,this.videoRange=F,this.stableVariantId=D,this.pathwayId=Y,this.programId=j,this.audio=Z,this.video=W,this.subtitles=J,this.closedCaptions=it,this.currentRenditions=ut;}));h.Variant=at;var Yt=f((function u(a){var s=a.id,i=a.value,g=a.uri,E=a.language;y(this,u),d(this,"id",void 0),d(this,"value",void 0),d(this,"uri",void 0),d(this,"language",void 0),H.PARAMCHECK(s,i||g),H.ASSERT("SessionData cannot have both value and uri, shoud be either.",!(i&&g)),this.id=s,this.value=i,this.uri=g,this.language=E;}));h.SessionData=Yt;var Xt=f((function u(a){var s=a.method,i=a.uri,g=a.iv,E=a.format,C=a.formatVersion;y(this,u),d(this,"method",void 0),d(this,"uri",void 0),d(this,"iv",void 0),d(this,"format",void 0),d(this,"formatVersion",void 0),H.PARAMCHECK(s),H.CONDITIONALPARAMCHECK([s!=="NONE",i]),H.CONDITIONALASSERT([s==="NONE",!(i||g||E||C)]),this.method=s,this.uri=i,this.iv=g,this.format=E,this.formatVersion=C;}));h.Key=Xt;var xt=f((function u(a){var s=a.serverUri,i=a.pathwayId;y(this,u),d(this,"serverUri",void 0),d(this,"pathwayId",void 0),this.serverUri=s,this.pathwayId=i;}));h.ContentSteering=xt;var Pt=f((function u(a){var s=a.hint,i=s!==void 0&&s,g=a.uri,E=a.mimeType,C=a.byterange;y(this,u),d(this,"hint",void 0),d(this,"uri",void 0),d(this,"mimeType",void 0),d(this,"byterange",void 0),H.PARAMCHECK(g),this.hint=i,this.uri=g,this.mimeType=E,this.byterange=C;}));h.MediaInitializationSection=Pt;var Ft=f((function u(a){var s=a.id,i=a.classId,g=a.start,E=a.cue,C=a.end,P=a.duration,M=a.plannedDuration,N=a.endOnNext,x=a.attributes,U=x===void 0?{}:x;y(this,u),d(this,"id",void 0),d(this,"classId",void 0),d(this,"start",void 0),d(this,"cue",void 0),d(this,"end",void 0),d(this,"duration",void 0),d(this,"plannedDuration",void 0),d(this,"endOnNext",void 0),d(this,"attributes",void 0),H.PARAMCHECK(s),H.CONDITIONALPARAMCHECK([N===true,i]),H.CONDITIONALASSERT([C,g],[C,g<=C],[P,P>=0],[M,M>=0]),this.id=s,this.classId=i,this.start=g,this.cue=E,this.end=C,this.duration=P,this.plannedDuration=M,this.endOnNext=N,this.attributes=U;}));h.DateRange=Ft;var Lt=f((function u(a){var s=a.type,i=a.duration,g=a.tagName,E=a.value;y(this,u),d(this,"type",void 0),d(this,"duration",void 0),d(this,"tagName",void 0),d(this,"value",void 0),H.PARAMCHECK(s),H.CONDITIONALPARAMCHECK([s==="OUT",i]),H.CONDITIONALPARAMCHECK([s==="RAW",g]),this.type=s,this.duration=i,this.tagName=g,this.value=E;}));h.SpliceInfo=Lt;var yt=f((function u(a){y(this,u),d(this,"type",void 0),H.PARAMCHECK(a),this.type=a;})),pt=(function(u){function a(s){var i,g=s.isMasterPlaylist,E=s.uri,C=s.version,P=s.independentSegments,M=P!==void 0&&P,N=s.start,x=s.source,U=s.defines;return y(this,a),d(i=O(this,a,["playlist"]),"isMasterPlaylist",void 0),d(i,"uri",void 0),d(i,"version",void 0),d(i,"independentSegments",void 0),d(i,"start",void 0),d(i,"source",void 0),d(i,"defines",void 0),H.PARAMCHECK(g),i.isMasterPlaylist=g,i.uri=E,i.version=C,i.independentSegments=M,i.start=N,i.source=x,i.defines=U,i}return I(a,u),f(a)})(yt);h.Playlist=pt;var Ct=(function(u){function a(){var s,i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};y(this,a),d(s=O(this,a,[L(L({},i),{},{isMasterPlaylist:true})]),"variants",void 0),d(s,"currentVariant",void 0),d(s,"sessionDataList",void 0),d(s,"sessionKeyList",void 0),d(s,"contentSteering",void 0);var g=i.variants,E=g===void 0?[]:g,C=i.currentVariant,P=i.sessionDataList,M=P===void 0?[]:P,N=i.sessionKeyList,x=N===void 0?[]:N,U=i.contentSteering,_=U===void 0?void 0:U;return s.variants=E,s.currentVariant=C,s.sessionDataList=M,s.sessionKeyList=x,s.contentSteering=_,s}return I(a,u),f(a)})(pt);h.MasterPlaylist=Ct;var R=(function(u){function a(){var s,i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};y(this,a),d(s=O(this,a,[L(L({},i),{},{isMasterPlaylist:false})]),"targetDuration",void 0),d(s,"mediaSequenceBase",void 0),d(s,"discontinuitySequenceBase",void 0),d(s,"endlist",void 0),d(s,"playlistType",void 0),d(s,"isIFrame",void 0),d(s,"segments",void 0),d(s,"prefetchSegments",void 0),d(s,"lowLatencyCompatibility",void 0),d(s,"partTargetDuration",void 0),d(s,"renditionReports",void 0),d(s,"skip",void 0),d(s,"hash",void 0);var g=i.targetDuration,E=i.mediaSequenceBase,C=E===void 0?0:E,P=i.discontinuitySequenceBase,M=P===void 0?0:P,N=i.endlist,x=N!==void 0&&N,U=i.playlistType,_=i.isIFrame,F=i.segments,D=F===void 0?[]:F,Y=i.prefetchSegments,j=Y===void 0?[]:Y,K=i.lowLatencyCompatibility,Z=i.partTargetDuration,z=i.renditionReports,W=z===void 0?[]:z,q=i.skip,J=q===void 0?0:q,Q=i.hash;return s.targetDuration=g,s.mediaSequenceBase=C,s.discontinuitySequenceBase=M,s.endlist=x,s.playlistType=U,s.isIFrame=_,s.segments=D,s.prefetchSegments=j,s.lowLatencyCompatibility=K,s.partTargetDuration=Z,s.renditionReports=W,s.skip=J,s.hash=Q,s}return I(a,u),f(a)})(pt);h.MediaPlaylist=R;var w=(function(u){function a(s){var i,g=s.uri,E=s.mimeType,C=s.data,P=s.duration,M=s.title,N=s.byterange,x=s.discontinuity,U=s.mediaSequenceNumber,_=U===void 0?0:U,F=s.discontinuitySequence,D=F===void 0?0:F,Y=s.key,j=s.map,K=s.programDateTime,Z=s.dateRange,z=s.markers,W=z===void 0?[]:z,q=s.parts,J=q===void 0?[]:q,Q=s.gap;return y(this,a),d(i=O(this,a,["segment"]),"uri",void 0),d(i,"mimeType",void 0),d(i,"data",void 0),d(i,"duration",void 0),d(i,"title",void 0),d(i,"byterange",void 0),d(i,"discontinuity",void 0),d(i,"mediaSequenceNumber",void 0),d(i,"discontinuitySequence",void 0),d(i,"key",void 0),d(i,"map",void 0),d(i,"programDateTime",void 0),d(i,"dateRange",void 0),d(i,"markers",void 0),d(i,"parts",void 0),d(i,"gap",void 0),i.uri=g,i.mimeType=E,i.data=C,i.duration=P,i.title=M,i.byterange=N,i.discontinuity=x,i.mediaSequenceNumber=_,i.discontinuitySequence=D,i.key=Y,i.map=j,i.programDateTime=K,i.dateRange=Z,i.markers=W,i.parts=J,i.gap=Q,i}return I(a,u),f(a)})(yt);h.Segment=w;var l=(function(u){function a(s){var i,g=s.hint,E=g!==void 0&&g,C=s.uri,P=s.duration,M=s.independent,N=s.byterange,x=s.gap;return y(this,a),d(i=O(this,a,["part"]),"hint",void 0),d(i,"uri",void 0),d(i,"duration",void 0),d(i,"independent",void 0),d(i,"byterange",void 0),d(i,"gap",void 0),H.PARAMCHECK(C),i.hint=E,i.uri=C,i.duration=P,i.independent=M,i.duration=P,i.byterange=N,i.gap=x,i}return I(a,u),f(a)})(yt);h.PartialSegment=l;var o=(function(u){function a(s){var i,g=s.uri,E=s.discontinuity,C=s.mediaSequenceNumber,P=C===void 0?0:C,M=s.discontinuitySequence,N=M===void 0?0:M,x=s.key;return y(this,a),d(i=O(this,a,["prefetch"]),"uri",void 0),d(i,"discontinuity",void 0),d(i,"mediaSequenceNumber",void 0),d(i,"discontinuitySequence",void 0),d(i,"key",void 0),H.PARAMCHECK(g),i.uri=g,i.discontinuity=E,i.mediaSequenceNumber=P,i.discontinuitySequence=N,i.key=x,i}return I(a,u),f(a)})(yt);h.PrefetchSegment=o;var p=f((function u(a){var s=a.uri,i=a.lastMSN,g=a.lastPart;y(this,u),d(this,"uri",void 0),d(this,"lastMSN",void 0),d(this,"lastPart",void 0),H.PARAMCHECK(s),this.uri=s,this.lastMSN=i,this.lastPart=g;}));h.RenditionReport=p;},73:function(m,h,b){var T,A=this&&this.__createBinding||(Object.create?function(y,d,X,V){V===void 0&&(V=X);var G=Object.getOwnPropertyDescriptor(d,X);G&&!("get"in G?!d.__esModule:G.writable||G.configurable)||(G={enumerable:true,get:function(){return d[X]}}),Object.defineProperty(y,V,G);}:function(y,d,X,V){V===void 0&&(V=X),y[V]=d[X];}),L=this&&this.__setModuleDefault||(Object.create?function(y,d){Object.defineProperty(y,"default",{enumerable:true,value:d});}:function(y,d){y.default=d;}),O=this&&this.__importStar||(T=function(y){return T=Object.getOwnPropertyNames||function(d){var X=[];for(var V in d)Object.prototype.hasOwnProperty.call(d,V)&&(X[X.length]=V);return X},T(y)},function(y){if(y&&y.__esModule)return y;var d={};if(y!=null)for(var X=T(y),V=0;V<X.length;V++)X[V]!=="default"&&A(d,y,X[V]);return L(d,y),d}),k=this&&this.__importDefault||function(y){return y&&y.__esModule?y:{default:y}};Object.defineProperty(h,"__esModule",{value:true}),h.setOptions=h.getOptions=h.types=h.stringify=h.parse=void 0;const v=b(203);Object.defineProperty(h,"getOptions",{enumerable:true,get:function(){return v.getOptions}}),Object.defineProperty(h,"setOptions",{enumerable:true,get:function(){return v.setOptions}});const I=k(b(377));h.parse=I.default;const S=k(b(887));h.stringify=S.default;const f=O(b(31));h.types=f;},203:(m,h)=>{function b(v,I){return (function(S){if(Array.isArray(S))return S})(v)||(function(S,f){var y=S==null?null:typeof Symbol<"u"&&S[Symbol.iterator]||S["@@iterator"];if(y!=null){var d,X,V,G,rt=[],et=true,H=false;try{if(V=(y=y.call(S)).next,f!==0)for(;!(et=(d=V.call(y)).done)&&(rt.push(d.value),rt.length!==f);et=!0);}catch(Et){H=true,X=Et;}finally{try{if(!et&&y.return!=null&&(G=y.return(),Object(G)!==G))return}finally{if(H)throw X}}return rt}})(v,I)||A(v,I)||(function(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function T(v,I){var S=typeof Symbol<"u"&&v[Symbol.iterator]||v["@@iterator"];if(!S){if(Array.isArray(v)||(S=A(v))||I){S&&(v=S);var f=0,y=function(){};return {s:y,n:function(){return f>=v.length?{done:true}:{done:false,value:v[f++]}},e:function(G){throw G},f:y}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var d,X=true,V=false;return {s:function(){S=S.call(v);},n:function(){var G=S.next();return X=G.done,G},e:function(G){V=true,d=G;},f:function(){try{X||S.return==null||S.return();}finally{if(V)throw d}}}}function A(v,I){if(v){if(typeof v=="string")return L(v,I);var S={}.toString.call(v).slice(8,-1);return S==="Object"&&v.constructor&&(S=v.constructor.name),S==="Map"||S==="Set"?Array.from(v):S==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(S)?L(v,I):void 0}}function L(v,I){(I==null||I>v.length)&&(I=v.length);for(var S=0,f=Array(I);S<I;S++)f[S]=v[S];return f}Object.defineProperty(h,"__esModule",{value:true}),h.THROW=k,h.ASSERT=function(v){for(var I=arguments.length,S=new Array(I>1?I-1:0),f=1;f<I;f++)S[f-1]=arguments[f];var y,d=T(S.entries());try{for(d.s();!(y=d.n()).done;){var X=b(y.value,2),V=X[0];X[1]||k(new Error("".concat(v," : Failed at [").concat(V,"]")));}}catch(G){d.e(G);}finally{d.f();}},h.CONDITIONALASSERT=function(){for(var v=arguments.length,I=new Array(v),S=0;S<v;S++)I[S]=arguments[S];var f,y=T(I.entries());try{for(y.s();!(f=y.n()).done;){var d=b(f.value,2),X=d[0],V=b(d[1],2),G=V[0],rt=V[1];G&&(rt||k(new Error("Conditional Assert : Failed at [".concat(X,"]"))));}}catch(et){y.e(et);}finally{y.f();}},h.PARAMCHECK=function(){for(var v=arguments.length,I=new Array(v),S=0;S<v;S++)I[S]=arguments[S];var f,y=T(I.entries());try{for(y.s();!(f=y.n()).done;){var d=b(f.value,2),X=d[0];d[1]===void 0&&k(new Error("Param Check : Failed at [".concat(X,"]")));}}catch(V){y.e(V);}finally{y.f();}},h.CONDITIONALPARAMCHECK=function(){for(var v=arguments.length,I=new Array(v),S=0;S<v;S++)I[S]=arguments[S];var f,y=T(I.entries());try{for(y.s();!(f=y.n()).done;){var d=b(f.value,2),X=d[0],V=b(d[1],2),G=V[0],rt=V[1];G&&rt===void 0&&k(new Error("Conditional Param Check : Failed at [".concat(X,"]")));}}catch(et){y.e(et);}finally{y.f();}},h.INVALIDPLAYLIST=function(v){k(new Error("Invalid Playlist : ".concat(v)));},h.toNumber=function(v){var I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:10;if(typeof v=="number")return v;var S=I===10?Number.parseFloat(v):Number.parseInt(v,I);return Number.isNaN(S)?0:S},h.hexToByteSequence=function(v){(v.startsWith("0x")||v.startsWith("0X"))&&(v=v.slice(2));for(var I=new Uint8Array(v.length/2),S=0;S<v.length;S+=2)I[S/2]=Number.parseInt(v.slice(S,S+2),16);return I},h.byteSequenceToHex=function(v){var I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:v.byteLength;S<=I&&k(new Error("end must be larger than start : start=".concat(I,", end=").concat(S)));for(var f=[],y=I;y<S;y++)f.push("0".concat((255&v[y]).toString(16).toUpperCase()).slice(-2));return "0x".concat(f.join(""))},h.tryCatch=function(v,I){try{return v()}catch(S){return I(S)}},h.splitAt=function(v,I){for(var S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,f=-1,y=0,d=0;y<v.length;y++)if(v[y]===I){if(d++===S)return [v.slice(0,y),v.slice(y+1)];f=y;}return f!==-1?[v.slice(0,f),v.slice(f+1)]:[v]},h.trim=function(v){var I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:" ";return !v||(v=v.trim(),I===" ")||(v.startsWith(I)&&(v=v.slice(1)),v.endsWith(I)&&(v=v.slice(0,-1))),v},h.splitByCommaWithPreservingQuotes=function(v){for(var I=[],S=true,f=0,y=[],d=0;d<v.length;d++){var X=v[d];S&&X===","?(I.push(v.slice(f,d).trim()),f=d+1):X!=='"'&&X!=="'"||(S?(y.push(X),S=false):X===y.at(-1)?(y.pop(),S=true):y.push(X));}return I.push(v.slice(f).trim()),I},h.camelify=function(v){var I,S=[],f=false,y=T(v);try{for(y.s();!(I=y.n()).done;){var d=I.value;d!=="-"&&d!=="_"?f?(S.push(d.toUpperCase()),f=!1):S.push(d.toLowerCase()):f=!0;}}catch(X){y.e(X);}finally{y.f();}return S.join("")},h.formatDate=function(v){var I=v.getUTCFullYear(),S=("0"+(v.getUTCMonth()+1)).slice(-2),f=("0"+v.getUTCDate()).slice(-2),y=("0"+v.getUTCHours()).slice(-2),d=("0"+v.getUTCMinutes()).slice(-2),X=("0"+v.getUTCSeconds()).slice(-2),V=("00"+v.getUTCMilliseconds()).slice(-3);return "".concat(I,"-").concat(S,"-").concat(f,"T").concat(y,":").concat(d,":").concat(X,".").concat(V,"Z")},h.hasOwnProp=function(v,I){return Object.hasOwn(v,I)},h.setOptions=function(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};O=Object.assign(O,v);},h.getOptions=function(){return Object.assign({},O)};var O={};function k(v){if(O.strictMode)throw v;O.silent||console.error(v.message);}},377:function(m,h,b){function T(R,w){return (function(l){if(Array.isArray(l))return l})(R)||(function(l,o){var p=l==null?null:typeof Symbol<"u"&&l[Symbol.iterator]||l["@@iterator"];if(p!=null){var u,a,s,i,g=[],E=true,C=false;try{if(s=(p=p.call(l)).next,o===0){if(Object(p)!==p)return;E=!1;}else for(;!(E=(u=s.call(p)).done)&&(g.push(u.value),g.length!==o);E=!0);}catch(P){C=true,a=P;}finally{try{if(!E&&p.return!=null&&(i=p.return(),Object(i)!==i))return}finally{if(C)throw a}}return g}})(R,w)||L(R,w)||(function(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function A(R,w){var l=typeof Symbol<"u"&&R[Symbol.iterator]||R["@@iterator"];if(!l){if(Array.isArray(R)||(l=L(R))||w){l&&(R=l);var o=0,p=function(){};return {s:p,n:function(){return o>=R.length?{done:true}:{done:false,value:R[o++]}},e:function(i){throw i},f:p}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var u,a=true,s=false;return {s:function(){l=l.call(R);},n:function(){var i=l.next();return a=i.done,i},e:function(i){s=true,u=i;},f:function(){try{a||l.return==null||l.return();}finally{if(s)throw u}}}}function L(R,w){if(R){if(typeof R=="string")return O(R,w);var l={}.toString.call(R).slice(8,-1);return l==="Object"&&R.constructor&&(l=R.constructor.name),l==="Map"||l==="Set"?Array.from(R):l==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(l)?O(R,w):void 0}}function O(R,w){(w==null||w>R.length)&&(w=R.length);for(var l=0,o=Array(w);l<w;l++)o[l]=R[l];return o}var k,v=this&&this.__createBinding||(Object.create?function(R,w,l,o){o===void 0&&(o=l);var p=Object.getOwnPropertyDescriptor(w,l);p&&!("get"in p?!w.__esModule:p.writable||p.configurable)||(p={enumerable:true,get:function(){return w[l]}}),Object.defineProperty(R,o,p);}:function(R,w,l,o){o===void 0&&(o=l),R[o]=w[l];}),I=this&&this.__setModuleDefault||(Object.create?function(R,w){Object.defineProperty(R,"default",{enumerable:true,value:w});}:function(R,w){R.default=w;}),S=this&&this.__importStar||(k=function(R){return k=Object.getOwnPropertyNames||function(w){var l=[];for(var o in w)Object.prototype.hasOwnProperty.call(w,o)&&(l[l.length]=o);return l},k(R)},function(R){if(R&&R.__esModule)return R;var w={};if(R!=null)for(var l=k(R),o=0;o<l.length;o++)l[o]!=="default"&&v(w,R,l[o]);return I(w,R),w});Object.defineProperty(h,"__esModule",{value:true});var f=S(b(203)),y=b(31);function d(R){return f.trim(R,'"')}function X(R){var w=f.splitAt(R,",");return {duration:f.toNumber(w[0]),title:decodeURIComponent(escape(w[1]))}}function V(R){var w=f.splitAt(R,"@");return {length:f.toNumber(w[0]),offset:w[1]?f.toNumber(w[1]):-1}}function G(R){var w=f.splitAt(R,"x");return {width:f.toNumber(w[0]),height:f.toNumber(w[1])}}function rt(R){var w="ALLOWED-CPC: Each entry must consit of KEYFORMAT and Content Protection Configuration",l=R.split(",");l.length===0&&f.INVALIDPLAYLIST(w);var o,p=[],u=A(l);try{for(u.s();!(o=u.n()).done;){var a=o.value,s=T(f.splitAt(a,":"),2),i=s[0],g=s[1];i&&g?p.push({format:i,cpcList:g.split("/")}):f.INVALIDPLAYLIST(w);}}catch(E){u.e(E);}finally{u.f();}return p}function et(R){return R.startsWith('"')?d(R):R.startsWith("0x")||R.startsWith("0X")?f.hexToByteSequence(R):f.toNumber(R)}function H(R,w){w.IV&&R.compatibleVersion<2&&(R.compatibleVersion=2),(w.KEYFORMAT||w.KEYFORMATVERSIONS)&&R.compatibleVersion<5&&(R.compatibleVersion=5);}function Et(R){var w,l,o,p={},u=A(f.splitByCommaWithPreservingQuotes(R));try{for(u.s();!(w=u.n()).done;){var a=w.value,s=T(f.splitAt(a,"="),2),i=s[0],g=s[1],E=d(g);switch(i){case "URI":p[i]=E;break;case "START-DATE":case "END-DATE":p[i]=new Date(E);break;case "IV":p[i]=(l=E,o=void 0,(o=f.hexToByteSequence(l)).length!==16&&f.INVALIDPLAYLIST("IV must be a 128-bit unsigned integer"),o);break;case "BYTERANGE":p[i]=V(E);break;case "RESOLUTION":p[i]=G(E);break;case "ALLOWED-CPC":p[i]=rt(E);break;case "END-ON-NEXT":case "DEFAULT":case "AUTOSELECT":case "FORCED":case "PRECISE":case "CAN-BLOCK-RELOAD":case "INDEPENDENT":case "GAP":p[i]=E==="YES";break;case "DURATION":case "PLANNED-DURATION":case "BANDWIDTH":case "AVERAGE-BANDWIDTH":case "FRAME-RATE":case "TIME-OFFSET":case "CAN-SKIP-UNTIL":case "HOLD-BACK":case "PART-HOLD-BACK":case "PART-TARGET":case "BYTERANGE-START":case "BYTERANGE-LENGTH":case "LAST-MSN":case "LAST-PART":case "SKIPPED-SEGMENTS":case "SCORE":case "PROGRAM-ID":p[i]=f.toNumber(E);break;default:i.startsWith("SCTE35-")?p[i]=f.hexToByteSequence(E):i.startsWith("X-")?p[i]=et(g):(i==="VIDEO-RANGE"&&E!=="SDR"&&E!=="HLG"&&E!=="PQ"&&f.INVALIDPLAYLIST('VIDEO-RANGE: unknown value "'.concat(E,'"')),p[i]=E);}}}catch(C){u.e(C);}finally{u.f();}return p}function at(){f.INVALIDPLAYLIST("The file contains both media and master playlist tags.");}function Yt(R,w,l){var o,p=(o=w.attributes,new y.Rendition({type:o.TYPE,uri:o.URI,groupId:o["GROUP-ID"],language:o.LANGUAGE,assocLanguage:o["ASSOC-LANGUAGE"],name:o.NAME,isDefault:o.DEFAULT,autoselect:o.AUTOSELECT,forced:o.FORCED,instreamId:o["INSTREAM-ID"],characteristics:o.CHARACTERISTICS,channels:o.CHANNELS,pathwayId:o["PATHWAY-ID"]})),u=R[f.camelify(l)],a=(function(s,i){var g,E=false,C=A(s);try{for(C.s();!(g=C.n()).done;){var P=g.value;if(P.name===i.name)return "All EXT-X-MEDIA tags in the same Group MUST have different NAME attributes.";P.isDefault&&(E=!0);}}catch(M){C.e(M);}finally{C.f();}return E&&i.isDefault?"EXT-X-MEDIA A Group MUST NOT have more than one member with a DEFAULT attribute of YES.":""})(u,p);a&&f.INVALIDPLAYLIST(a),u.push(p),p.isDefault&&(R.currentRenditions[f.camelify(l)]=u.length-1);}function Xt(R,w,l,o,p){var u,a=new y.Variant({uri:l,bandwidth:w.BANDWIDTH,averageBandwidth:w["AVERAGE-BANDWIDTH"],score:w.SCORE,codecs:w.CODECS,resolution:w.RESOLUTION,frameRate:w["FRAME-RATE"],hdcpLevel:w["HDCP-LEVEL"],allowedCpc:w["ALLOWED-CPC"],videoRange:w["VIDEO-RANGE"],stableVariantId:w["STABLE-VARIANT-ID"],pathwayId:w["STABLE-PATHWAY-ID"],programId:w["PROGRAM-ID"]}),s=A(R);try{for(s.s();!(u=s.n()).done;){var i=u.value;if(i.name==="EXT-X-MEDIA"){var g=i.attributes,E=g.TYPE;if(E&&g["GROUP-ID"]||f.INVALIDPLAYLIST("EXT-X-MEDIA TYPE attribute is REQUIRED."),w[E]===g["GROUP-ID"]&&(Yt(a,i,E),E==="CLOSED-CAPTIONS")){var C,P=A(a.closedCaptions);try{for(P.s();!(C=P.n()).done;){var M=C.value.instreamId;if(M&&M.startsWith("SERVICE")&&p.compatibleVersion<7){p.compatibleVersion=7;break}}}catch(N){P.e(N);}finally{P.f();}}}}}catch(N){s.e(N);}finally{s.f();}return (function(N,x,U){for(var _=function(){var Y=D[F];Y==="CLOSED-CAPTIONS"&&N[Y]==="NONE"?(U.isClosedCaptionsNone=true,x.closedCaptions=[]):N[Y]&&!x[f.camelify(Y)].some((function(j){return j.groupId===N[Y]}))&&f.INVALIDPLAYLIST("".concat(Y," attribute MUST match the value of the GROUP-ID attribute of an EXT-X-MEDIA tag whose TYPE attribute is ").concat(Y,"."));},F=0,D=["AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS"];F<D.length;F++)_();})(w,a,p),a.isIFrameOnly=o,a}function xt(R,w,l,o,p,u,a){for(var s=new y.Segment({uri:w,mediaSequenceNumber:p,discontinuitySequence:u}),i=false,g=false,E=l;E<=o;E++){var C=Ct(R[E]),P=C.name,M=C.value,N=C.attributes;if(P==="EXTINF")!Number.isInteger(M.duration)&&a.compatibleVersion<3&&(a.compatibleVersion=3),Math.round(M.duration)>a.targetDuration&&f.INVALIDPLAYLIST("EXTINF duration, when rounded to the nearest integer, MUST be less than or equal to the target duration"),s.duration=M.duration,s.title=M.title;else if(P==="EXT-X-BYTERANGE")a.compatibleVersion<4&&(a.compatibleVersion=4),s.byterange=M;else if(P==="EXT-X-DISCONTINUITY")s.parts.length>0&&f.INVALIDPLAYLIST("EXT-X-DISCONTINUITY must appear before the first EXT-X-PART tag of the Parent Segment."),s.discontinuity=true;else if(P==="EXT-X-GAP")a.compatibleVersion<8&&(a.compatibleVersion=8),s.gap=true;else if(P==="EXT-X-KEY")s.parts.length>0&&f.INVALIDPLAYLIST("EXT-X-KEY must appear before the first EXT-X-PART tag of the Parent Segment."),H(a,N),s.key=new y.Key({method:N.METHOD,uri:N.URI,iv:N.IV,format:N.KEYFORMAT,formatVersion:N.KEYFORMATVERSIONS});else if(P==="EXT-X-MAP")s.parts.length>0&&f.INVALIDPLAYLIST("EXT-X-MAP must appear before the first EXT-X-PART tag of the Parent Segment."),a.compatibleVersion<5&&(a.compatibleVersion=5),a.hasMap=true,s.map=new y.MediaInitializationSection({uri:N.URI,byterange:N.BYTERANGE});else if(P==="EXT-X-PROGRAM-DATE-TIME")s.programDateTime=M;else if(P==="EXT-X-DATERANGE"){for(var x={},U=0,_=Object.keys(N);U<_.length;U++){var F=_[U];(F.startsWith("SCTE35-")||F.startsWith("X-"))&&(x[F]=N[F]);}s.dateRange=new y.DateRange({id:N.ID,classId:N.CLASS,start:N["START-DATE"],cue:N.CUE,end:N["END-DATE"],duration:N.DURATION,plannedDuration:N["PLANNED-DURATION"],endOnNext:N["END-ON-NEXT"],attributes:x});}else if(P==="EXT-X-CUE-OUT")s.markers.push(new y.SpliceInfo({type:"OUT",duration:N&&N.DURATION||M}));else if(P==="EXT-X-CUE-IN")s.markers.push(new y.SpliceInfo({type:"IN"}));else if(P==="EXT-X-CUE-OUT-CONT"||P==="EXT-X-CUE"||P==="EXT-OATCLS-SCTE35"||P==="EXT-X-ASSET"||P==="EXT-X-SCTE35")s.markers.push(new y.SpliceInfo({type:"RAW",tagName:P,value:M}));else if(P!=="EXT-X-PRELOAD-HINT"||N.TYPE)if(P==="EXT-X-PRELOAD-HINT"&&N.TYPE==="PART"&&g)f.INVALIDPLAYLIST("Servers should not add more than one EXT-X-PRELOAD-HINT tag with the same TYPE attribute to a Playlist.");else if(P!=="EXT-X-PART"&&P!=="EXT-X-PRELOAD-HINT"||N.URI){if(P==="EXT-X-PRELOAD-HINT"&&N.TYPE==="MAP")i&&f.INVALIDPLAYLIST("Servers should not add more than one EXT-X-PRELOAD-HINT tag with the same TYPE attribute to a Playlist."),i=true,a.hasMap=true,s.map=new y.MediaInitializationSection({hint:true,uri:N.URI,byterange:{length:N["BYTERANGE-LENGTH"],offset:N["BYTERANGE-START"]||0}});else if(P==="EXT-X-PART"||P==="EXT-X-PRELOAD-HINT"&&N.TYPE==="PART"){P!=="EXT-X-PART"||N.DURATION||f.INVALIDPLAYLIST("EXT-X-PART: DURATION attribute is mandatory"),P==="EXT-X-PRELOAD-HINT"&&(g=true);var D=new y.PartialSegment({hint:P==="EXT-X-PRELOAD-HINT",uri:N.URI,byterange:P==="EXT-X-PART"?N.BYTERANGE:{length:N["BYTERANGE-LENGTH"],offset:N["BYTERANGE-START"]||0},duration:N.DURATION,independent:N.INDEPENDENT,gap:N.GAP});s.gap&&!D.gap&&f.INVALIDPLAYLIST("Partial segments must have GAP=YES if they are in a gap (EXT-X-GAP)"),s.parts.push(D);}}else f.INVALIDPLAYLIST("EXT-X-PART / EXT-X-PRELOAD-HINT: URI attribute is mandatory");else f.INVALIDPLAYLIST("EXT-X-PRELOAD-HINT: TYPE attribute is mandatory");}return s}function Pt(R,w,l,o,p,u,a){for(var s=new y.PrefetchSegment({uri:w,mediaSequenceNumber:p,discontinuitySequence:u}),i=l;i<=o;i++){var g=R[i],E=g.name,C=g.attributes;E==="EXTINF"?f.INVALIDPLAYLIST("A prefetch segment must not be advertised with an EXTINF tag."):E==="EXT-X-DISCONTINUITY"?f.INVALIDPLAYLIST("A prefetch segment must not be advertised with an EXT-X-DISCONTINUITY tag."):E==="EXT-X-PREFETCH-DISCONTINUITY"?s.discontinuity=true:E==="EXT-X-KEY"?(H(a,C),s.key=new y.Key({method:C.METHOD,uri:C.URI,iv:C.IV,format:C.KEYFORMAT,formatVersion:C.KEYFORMATVERSIONS})):E==="EXT-X-MAP"&&f.INVALIDPLAYLIST("Prefetch segments must not be advertised with an EXT-X-MAP tag.");}return s}function Ft(R,w){var l,o=new y.MediaPlaylist,p=-1,u=0,a=false,s=false,i=0,g=null,E=null,C=false,P=A(R.entries());try{for(P.s();!(l=P.n()).done;){var M=T(l.value,2),N=M[0],x=M[1],U=Ct(x),_=U.name,F=U.value,D=U.attributes;if(U.category!=="Segment"){if(_==="EXT-X-VERSION")o.version===void 0?o.version=F:f.INVALIDPLAYLIST("A Playlist file MUST NOT contain more than one EXT-X-VERSION tag.");else if(_==="EXT-X-TARGETDURATION")o.targetDuration=w.targetDuration=F;else if(_==="EXT-X-MEDIA-SEQUENCE")o.segments.length>0&&f.INVALIDPLAYLIST("The EXT-X-MEDIA-SEQUENCE tag MUST appear before the first Media Segment in the Playlist."),o.mediaSequenceBase=u=F;else if(_==="EXT-X-DISCONTINUITY-SEQUENCE")o.segments.length>0&&f.INVALIDPLAYLIST("The EXT-X-DISCONTINUITY-SEQUENCE tag MUST appear before the first Media Segment in the Playlist."),a&&f.INVALIDPLAYLIST("The EXT-X-DISCONTINUITY-SEQUENCE tag MUST appear before any EXT-X-DISCONTINUITY tag."),o.discontinuitySequenceBase=i=F;else if(_==="EXT-X-ENDLIST")o.endlist=!0;else if(_==="EXT-X-PLAYLIST-TYPE")o.playlistType=F;else if(_==="EXT-X-I-FRAMES-ONLY")w.compatibleVersion<4&&(w.compatibleVersion=4),o.isIFrame=!0;else if(_==="EXT-X-INDEPENDENT-SEGMENTS")o.independentSegments&&f.INVALIDPLAYLIST("EXT-X-INDEPENDENT-SEGMENTS tag MUST NOT appear more than once in a Playlist"),o.independentSegments=!0;else if(_==="EXT-X-START")o.start&&f.INVALIDPLAYLIST("EXT-X-START tag MUST NOT appear more than once in a Playlist"),typeof D["TIME-OFFSET"]!="number"&&f.INVALIDPLAYLIST("EXT-X-START: TIME-OFFSET attribute is REQUIRED"),o.start={offset:D["TIME-OFFSET"],precise:D.PRECISE||!1};else if(_==="EXT-X-SERVER-CONTROL")D["CAN-BLOCK-RELOAD"]||f.INVALIDPLAYLIST("EXT-X-SERVER-CONTROL: CAN-BLOCK-RELOAD=YES is mandatory for Low-Latency HLS"),o.lowLatencyCompatibility={canBlockReload:D["CAN-BLOCK-RELOAD"],canSkipUntil:D["CAN-SKIP-UNTIL"],holdBack:D["HOLD-BACK"],partHoldBack:D["PART-HOLD-BACK"]};else if(_==="EXT-X-PART-INF")D["PART-TARGET"]||f.INVALIDPLAYLIST("EXT-X-PART-INF: PART-TARGET attribute is mandatory"),o.partTargetDuration=D["PART-TARGET"];else if(_==="EXT-X-RENDITION-REPORT")D.URI||f.INVALIDPLAYLIST("EXT-X-RENDITION-REPORT: URI attribute is mandatory"),D.URI.search(/^[a-z]+:/)===0&&f.INVALIDPLAYLIST("EXT-X-RENDITION-REPORT: URI must be relative to the playlist uri"),o.renditionReports.push(new y.RenditionReport({uri:D.URI,lastMSN:D["LAST-MSN"],lastPart:D["LAST-PART"]}));else if(_==="EXT-X-SKIP")D["SKIPPED-SEGMENTS"]||f.INVALIDPLAYLIST("EXT-X-SKIP: SKIPPED-SEGMENTS attribute is mandatory"),w.compatibleVersion<9&&(w.compatibleVersion=9),o.skip=D["SKIPPED-SEGMENTS"],u+=o.skip;else if(_==="EXT-X-PREFETCH"){var Y=Pt(R,F,p===-1?N:p,N-1,u++,i,w);Y&&(Y.discontinuity&&(Y.discontinuitySequence++,i=Y.discontinuitySequence),Y.key?g=Y.key:Y.key=g,o.prefetchSegments.push(Y)),s=!0,p=-1;}else if(_==="EXT-X-DEFINE")o.defines||(o.defines=[]),o.defines.push(D);else if(typeof x=="string"){p===-1&&f.INVALIDPLAYLIST("A URI line is not preceded by any segment tags"),o.targetDuration||f.INVALIDPLAYLIST("The EXT-X-TARGETDURATION tag is REQUIRED"),s&&f.INVALIDPLAYLIST("These segments must appear after all complete segments.");var j=xt(R,x,p,N-1,u++,i,w);if(j){var K=T(Lt(o,j,i,g,E),3);i=K[0],g=K[1],E=K[2],!C&&j.parts.length>0&&(C=!0);}p=-1;}}else p===-1&&(p=N),_==="EXT-X-DISCONTINUITY"&&(a=!0);}}catch(q){P.e(q);}finally{P.f();}if(p!==-1){var Z=xt(R,"",p,R.length-1,u++,i,w);if(Z){var z,W=Z.parts;!(W.length>0)||o.endlist||(z=W.at(-1))!==null&&z!==void 0&&z.hint||f.INVALIDPLAYLIST("If the Playlist contains EXT-X-PART tags and does not contain an EXT-X-ENDLIST tag, the Playlist must contain an EXT-X-PRELOAD-HINT tag with a TYPE=PART attribute"),Lt(o,Z,g,E),!C&&Z.parts.length>0&&(C=true);}}return (function(q){for(var J=new Map,Q=new Map,it=false,lt=false,ut=q.length-1;ut>=0;ut--){var gt=q[ut],Tt=gt.programDateTime,$=gt.dateRange;if(Tt&&(lt=true),$&&$.start){it=true,$.endOnNext&&($.end||$.duration)&&f.INVALIDPLAYLIST("An EXT-X-DATERANGE tag with an END-ON-NEXT=YES attribute MUST NOT contain DURATION or END-DATE attributes.");var ot=$.start.getTime(),Kt=$.duration||0;$.end&&$.duration&&ot+1e3*Kt!==$.end.getTime()&&f.INVALIDPLAYLIST("END-DATE MUST be equal to the value of the START-DATE attribute plus the value of the DURATION"),$.endOnNext&&($.end=J.get($.classId)),J.set($.classId,$.start);var bt=$.end?$.end.getTime():$.start.getTime()+1e3*($.duration||0),Mt=Q.get($.classId);if(Mt){var Wt,It=A(Mt);try{for(It.s();!(Wt=It.n()).done;){var Ot=Wt.value;(Ot.start<=ot&&Ot.end>ot||Ot.start>=ot&&Ot.start<bt)&&f.INVALIDPLAYLIST("DATERANGE tags with the same CLASS should not overlap");}}catch(kt){It.e(kt);}finally{It.f();}Mt.push({start:ot,end:bt});}else $.classId&&Q.set($.classId,[{start:ot,end:bt}]);}}it&&!lt&&f.INVALIDPLAYLIST("If a Playlist contains an EXT-X-DATERANGE tag, it MUST also contain at least one EXT-X-PROGRAM-DATE-TIME tag.");})(o.segments),o.lowLatencyCompatibility&&(function(q,J){var Q=q.lowLatencyCompatibility,it=q.targetDuration,lt=q.partTargetDuration,ut=q.segments,gt=q.renditionReports,Tt=Q.canSkipUntil,$=Q.holdBack,ot=Q.partHoldBack;if(Tt<6*it&&f.INVALIDPLAYLIST("The Skip Boundary must be at least six times the EXT-X-TARGETDURATION."),$<3*it&&f.INVALIDPLAYLIST("HOLD-BACK must be at least three times the EXT-X-TARGETDURATION."),J){lt===void 0&&f.INVALIDPLAYLIST("EXT-X-PART-INF is required if a Playlist contains one or more EXT-X-PART tags"),ot===void 0&&f.INVALIDPLAYLIST("EXT-X-PART: PART-HOLD-BACK attribute is mandatory"),ot<lt&&f.INVALIDPLAYLIST("PART-HOLD-BACK must be at least PART-TARGET");var Kt,bt=A(ut.entries());try{for(bt.s();!(Kt=bt.n()).done;){var Mt=T(Kt.value,2),Wt=Mt[0],It=Mt[1].parts;It.length>0&&Wt<ut.length-3&&f.INVALIDPLAYLIST("Remove EXT-X-PART tags from the Playlist after they are greater than three target durations from the end of the Playlist.");var Ot,kt=A(It.entries());try{for(kt.s();!(Ot=kt.n()).done;){var Ce=T(Ot.value,2),Ln=Ce[0],oe=Ce[1].duration;oe!==void 0&&(oe>lt&&f.INVALIDPLAYLIST("PART-TARGET is the maximum duration of any Partial Segment"),Ln<It.length-1&&oe<.85*lt&&f.INVALIDPLAYLIST("All Partial Segments except the last part of a segment must have a duration of at least 85% of PART-TARGET"));}}catch(Bt){kt.e(Bt);}finally{kt.f();}}}catch(Bt){bt.e(Bt);}finally{bt.f();}}var Oe,Qt=A(gt);try{for(Qt.s();!(Oe=Qt.n()).done;){var De,Gt=Oe.value,se=ut.at(-1);(De=Gt.lastMSN)!==null&&De!==void 0||(Gt.lastMSN=se.mediaSequenceNumber),(Gt.lastPart===null||Gt.lastPart===void 0)&&se.parts.length>0&&(Gt.lastPart=se.parts.length-1);}}catch(Bt){Qt.e(Bt);}finally{Qt.f();}})(o,C),o}function Lt(R,w,l,o,p){var u=w.discontinuity,a=w.key,s=w.map,i=w.byterange,g=w.uri;if(u&&(w.discontinuitySequence=l+1),a||(w.key=o),s||(w.map=p),i&&i.offset===-1){var E=R.segments;if(E.length>0){var C=E.at(-1);C.byterange&&C.uri===g?i.offset=C.byterange.offset+C.byterange.length:f.INVALIDPLAYLIST("If offset of EXT-X-BYTERANGE is not present, a previous Media Segment MUST be a sub-range of the same media resource");}else f.INVALIDPLAYLIST("If offset of EXT-X-BYTERANGE is not present, a previous Media Segment MUST appear in the Playlist file");}return R.segments.push(w),[w.discontinuitySequence,w.key,w.map]}function yt(R,w){var l=(function(g){var E=g.indexOf(":");return E===-1?[g.slice(1).trim(),null]:[g.slice(1,E).trim(),g.slice(E+1).trim()]})(R),o=T(l,2),p=o[0],u=o[1],a=(function(g){switch(g){case "EXTM3U":case "EXT-X-VERSION":case "EXT-X-CONTENT-STEERING":return "Basic";case "EXTINF":case "EXT-X-BYTERANGE":case "EXT-X-DISCONTINUITY":case "EXT-X-PREFETCH-DISCONTINUITY":case "EXT-X-KEY":case "EXT-X-MAP":case "EXT-X-PROGRAM-DATE-TIME":case "EXT-X-DATERANGE":case "EXT-X-CUE-OUT":case "EXT-X-CUE-IN":case "EXT-X-CUE-OUT-CONT":case "EXT-X-CUE":case "EXT-OATCLS-SCTE35":case "EXT-X-ASSET":case "EXT-X-SCTE35":case "EXT-X-PART":case "EXT-X-PRELOAD-HINT":case "EXT-X-GAP":return "Segment";case "EXT-X-TARGETDURATION":case "EXT-X-MEDIA-SEQUENCE":case "EXT-X-DISCONTINUITY-SEQUENCE":case "EXT-X-ENDLIST":case "EXT-X-PLAYLIST-TYPE":case "EXT-X-I-FRAMES-ONLY":case "EXT-X-SERVER-CONTROL":case "EXT-X-PART-INF":case "EXT-X-PREFETCH":case "EXT-X-RENDITION-REPORT":case "EXT-X-SKIP":return "MediaPlaylist";case "EXT-X-MEDIA":case "EXT-X-STREAM-INF":case "EXT-X-I-FRAME-STREAM-INF":case "EXT-X-SESSION-DATA":case "EXT-X-SESSION-KEY":return "MasterPlaylist";case "EXT-X-INDEPENDENT-SEGMENTS":case "EXT-X-START":case "EXT-X-DEFINE":return "MediaorMasterPlaylist";default:return "Unknown"}})(p);if((function(g,E){if(g==="Segment"||g==="MediaPlaylist")return E.isMasterPlaylist===void 0?void(E.isMasterPlaylist=false):void(E.isMasterPlaylist&&at());if(g==="MasterPlaylist"){if(E.isMasterPlaylist===void 0)return void(E.isMasterPlaylist=true);E.isMasterPlaylist===false&&at();}})(a,w),a==="Unknown")return null;a==="MediaPlaylist"&&p!=="EXT-X-RENDITION-REPORT"&&p!=="EXT-X-PREFETCH"&&(w.hash[p]&&f.INVALIDPLAYLIST("There MUST NOT be more than one Media Playlist tag of each type in any Media Playlist"),w.hash[p]=true);var s=(function(g,E){switch(g){case "EXTM3U":case "EXT-X-DISCONTINUITY":case "EXT-X-ENDLIST":case "EXT-X-I-FRAMES-ONLY":case "EXT-X-INDEPENDENT-SEGMENTS":case "EXT-X-CUE-IN":case "EXT-X-GAP":return [null,null];case "EXT-X-VERSION":case "EXT-X-TARGETDURATION":case "EXT-X-MEDIA-SEQUENCE":case "EXT-X-DISCONTINUITY-SEQUENCE":return [f.toNumber(E),null];case "EXT-X-CUE-OUT":return Number.isNaN(Number(E))?[null,Et(E)]:[f.toNumber(E),null];case "EXT-X-KEY":case "EXT-X-MAP":case "EXT-X-DATERANGE":case "EXT-X-MEDIA":case "EXT-X-STREAM-INF":case "EXT-X-I-FRAME-STREAM-INF":case "EXT-X-SESSION-DATA":case "EXT-X-SESSION-KEY":case "EXT-X-START":case "EXT-X-SERVER-CONTROL":case "EXT-X-PART-INF":case "EXT-X-PART":case "EXT-X-PRELOAD-HINT":case "EXT-X-RENDITION-REPORT":case "EXT-X-SKIP":case "EXT-X-DEFINE":return [null,Et(E)];case "EXTINF":return [X(E),null];case "EXT-X-BYTERANGE":return [V(E),null];case "EXT-X-PROGRAM-DATE-TIME":return [new Date(E),null];default:return [E,null]}})(p,u),i=T(s,2);return {name:p,category:a,value:i[0],attributes:i[1]}}function pt(R,w){var l;return w.isMasterPlaylist?l=(function(o,p){var u,a=new y.MasterPlaylist,s=false,i=A(o.entries());try{var g=function(){var N=T(u.value,2),x=N[0],U=Ct(N[1]),_=U.name,F=U.value,D=U.attributes;if(_==="EXT-X-VERSION")a.version=F;else if(_==="EXT-X-CONTENT-STEERING-SERVER"){var Y=new y.ContentSteering({serverUri:D["SERVER-URI"],pathwayId:D["PATHWAY-ID"]});a.contentSteering=Y;}else if(_==="EXT-X-STREAM-INF"){var j=o[x+1];(typeof j!="string"||j.startsWith("#EXT"))&&f.INVALIDPLAYLIST("EXT-X-STREAM-INF must be followed by a URI line");var K=Xt(o,D,j,!1,p);K&&(typeof K.score=="number"&&(s=!0,K.score<0&&f.INVALIDPLAYLIST("SCORE attribute on EXT-X-STREAM-INF must be positive decimal-floating-point number.")),a.variants.push(K));}else if(_==="EXT-X-I-FRAME-STREAM-INF"){var Z=Xt(o,D,D.URI,!0,p);Z&&a.variants.push(Z);}else if(_==="EXT-X-SESSION-DATA"){var z=new y.SessionData({id:D["DATA-ID"],value:D.VALUE,uri:D.URI,language:D.LANGUAGE});a.sessionDataList.some((function(q){return q.id===z.id&&q.language===z.language}))&&f.INVALIDPLAYLIST("A Playlist MUST NOT contain more than one EXT-X-SESSION-DATA tag with the same DATA-ID attribute and the same LANGUAGE attribute."),a.sessionDataList.push(z);}else if(_==="EXT-X-SESSION-KEY"){D.METHOD==="NONE"&&f.INVALIDPLAYLIST("EXT-X-SESSION-KEY: The value of the METHOD attribute MUST NOT be NONE");var W=new y.Key({method:D.METHOD,uri:D.URI,iv:D.IV,format:D.KEYFORMAT,formatVersion:D.KEYFORMATVERSIONS});a.sessionKeyList.some((function(q){return (function(J,Q){if(J.method!==Q.method||J.uri!==Q.uri)return !1;if(J.iv){if(!Q.iv||J.iv.byteLength!==Q.iv.byteLength)return !1;for(var it=0;it<J.iv.byteLength;it++)if(J.iv[it]!==Q.iv[it])return !1}else if(Q.iv)return !1;return J.format===Q.format&&J.formatVersion===Q.formatVersion})(q,W)}))&&f.INVALIDPLAYLIST("A Master Playlist MUST NOT contain more than one EXT-X-SESSION-KEY tag with the same METHOD, URI, IV, KEYFORMAT, and KEYFORMATVERSIONS attribute values."),H(p,D),a.sessionKeyList.push(W);}else _==="EXT-X-INDEPENDENT-SEGMENTS"?(a.independentSegments&&f.INVALIDPLAYLIST("EXT-X-INDEPENDENT-SEGMENTS tag MUST NOT appear more than once in a Playlist"),a.independentSegments=!0):_==="EXT-X-START"?(a.start&&f.INVALIDPLAYLIST("EXT-X-START tag MUST NOT appear more than once in a Playlist"),typeof D["TIME-OFFSET"]!="number"&&f.INVALIDPLAYLIST("EXT-X-START: TIME-OFFSET attribute is REQUIRED"),a.start={offset:D["TIME-OFFSET"],precise:D.PRECISE||!1}):_==="EXT-X-DEFINE"&&(a.defines||(a.defines=[]),a.defines.push(D));};for(i.s();!(u=i.n()).done;)g();}catch(N){i.e(N);}finally{i.f();}if(s){var E,C=A(a.variants);try{for(C.s();!(E=C.n()).done;)typeof E.value.score!="number"&&f.INVALIDPLAYLIST("If any Variant Stream contains the SCORE attribute, then all Variant Streams in the Master Playlist SHOULD have a SCORE attribute");}catch(N){C.e(N);}finally{C.f();}}if(p.isClosedCaptionsNone){var P,M=A(a.variants);try{for(M.s();!(P=M.n()).done;)P.value.closedCaptions.length>0&&f.INVALIDPLAYLIST("If there is a variant with CLOSED-CAPTIONS attribute of NONE, all EXT-X-STREAM-INF tags MUST have this attribute with a value of NONE");}catch(N){M.e(N);}finally{M.f();}}return a})(R,w):!(l=Ft(R,w)).isIFrame&&w.hasMap&&w.compatibleVersion<6&&(w.compatibleVersion=6),w.compatibleVersion>1&&(!l.version||l.version<w.compatibleVersion)&&f.INVALIDPLAYLIST("EXT-X-VERSION needs to be ".concat(w.compatibleVersion," or higher.")),l}function Ct(R){return typeof R=="string"?{}:R}h.default=function(R){var w={version:void 0,isMasterPlaylist:void 0,hasMap:false,targetDuration:0,compatibleVersion:1,isClosedCaptionsNone:false,hash:{}},l=pt((function(o,p){var u,a=[],s=A(o.split(`
`));try{for(s.s();!(u=s.n()).done;){var i=u.value.trim();if(i)if(i.startsWith("#")){if(i.startsWith("#EXT")){var g=yt(i,p);g&&a.push(g);}}else a.push(i);}}catch(E){s.e(E);}finally{s.f();}return a.length!==0&&a[0].name==="EXTM3U"||f.INVALIDPLAYLIST("The EXTM3U tag MUST be the first line."),a})(R,w),w);return l.source=R,l};},887:function(m,h,b){function T(l){return T=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(o){return typeof o}:function(o){return o&&typeof Symbol=="function"&&o.constructor===Symbol&&o!==Symbol.prototype?"symbol":typeof o},T(l)}function A(l,o){return (function(p){if(Array.isArray(p))return p})(l)||(function(p,u){var a=p==null?null:typeof Symbol<"u"&&p[Symbol.iterator]||p["@@iterator"];if(a!=null){var s,i,g,E,C=[],P=true,M=false;try{if(g=(a=a.call(p)).next,u===0){if(Object(a)!==a)return;P=!1;}else for(;!(P=(s=g.call(a)).done)&&(C.push(s.value),C.length!==u);P=!0);}catch(N){M=true,i=N;}finally{try{if(!P&&a.return!=null&&(E=a.return(),Object(E)!==E))return}finally{if(M)throw i}}return C}})(l,o)||O(l,o)||(function(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function L(l,o){var p=typeof Symbol<"u"&&l[Symbol.iterator]||l["@@iterator"];if(!p){if(Array.isArray(l)||(p=O(l))||o){p&&(l=p);var u=0,a=function(){};return {s:a,n:function(){return u>=l.length?{done:true}:{done:false,value:l[u++]}},e:function(E){throw E},f:a}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var s,i=true,g=false;return {s:function(){p=p.call(l);},n:function(){var E=p.next();return i=E.done,E},e:function(E){g=true,s=E;},f:function(){try{i||p.return==null||p.return();}finally{if(g)throw s}}}}function O(l,o){if(l){if(typeof l=="string")return k(l,o);var p={}.toString.call(l).slice(8,-1);return p==="Object"&&l.constructor&&(p=l.constructor.name),p==="Map"||p==="Set"?Array.from(l):p==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(p)?k(l,o):void 0}}function k(l,o){(o==null||o>l.length)&&(o=l.length);for(var p=0,u=Array(o);p<o;p++)u[p]=l[p];return u}function v(l,o){for(var p=0;p<o.length;p++){var u=o[p];u.enumerable=u.enumerable||false,u.configurable=true,"value"in u&&(u.writable=true),Object.defineProperty(l,G(u.key),u);}}function I(l,o,p){return o=V(o),(function(u,a){if(a&&(T(a)=="object"||typeof a=="function"))return a;if(a!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return (function(s){if(s===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return s})(u)})(l,d()?Reflect.construct(o,[],V(l).constructor):o.apply(l,p))}function S(l,o,p,u){var a=f(V(l.prototype),o,p);return 2&u&&typeof a=="function"?function(s){return a.apply(p,s)}:a}function f(){return f=typeof Reflect<"u"&&Reflect.get?Reflect.get.bind():function(l,o,p){var u=(function(s,i){for(;!{}.hasOwnProperty.call(s,i)&&(s=V(s))!==null;);return s})(l,o);if(u){var a=Object.getOwnPropertyDescriptor(u,o);return a.get?a.get.call(arguments.length<3?l:p):a.value}},f.apply(null,arguments)}function y(l){var o=typeof Map=="function"?new Map:void 0;return y=function(p){if(p===null||!(function(a){try{return Function.toString.call(a).indexOf("[native code]")!==-1}catch{return typeof a=="function"}})(p))return p;if(typeof p!="function")throw new TypeError("Super expression must either be null or a function");if(o!==void 0){if(o.has(p))return o.get(p);o.set(p,u);}function u(){return (function(a,s,i){if(d())return Reflect.construct.apply(null,arguments);var g=[null];g.push.apply(g,s);var E=new(a.bind.apply(a,g));return i&&X(E,i.prototype),E})(p,arguments,V(this).constructor)}return u.prototype=Object.create(p.prototype,{constructor:{value:u,enumerable:false,writable:true,configurable:true}}),X(u,p)},y(l)}function d(){try{var l=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})));}catch{}return (d=function(){return !!l})()}function X(l,o){return X=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(p,u){return p.__proto__=u,p},X(l,o)}function V(l){return V=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(o){return o.__proto__||Object.getPrototypeOf(o)},V(l)}function G(l){var o=(function(p,u){if(T(p)!="object"||!p)return p;var a=p[Symbol.toPrimitive];if(a!==void 0){var s=a.call(p,u);if(T(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(p)})(l,"string");return T(o)=="symbol"?o:o+""}var rt,et=this&&this.__createBinding||(Object.create?function(l,o,p,u){u===void 0&&(u=p);var a=Object.getOwnPropertyDescriptor(o,p);a&&!("get"in a?!o.__esModule:a.writable||a.configurable)||(a={enumerable:true,get:function(){return o[p]}}),Object.defineProperty(l,u,a);}:function(l,o,p,u){u===void 0&&(u=p),l[u]=o[p];}),H=this&&this.__setModuleDefault||(Object.create?function(l,o){Object.defineProperty(l,"default",{enumerable:true,value:o});}:function(l,o){l.default=o;}),Et=this&&this.__importStar||(rt=function(l){return rt=Object.getOwnPropertyNames||function(o){var p=[];for(var u in o)Object.prototype.hasOwnProperty.call(o,u)&&(p[p.length]=u);return p},rt(l)},function(l){if(l&&l.__esModule)return l;var o={};if(l!=null)for(var p=rt(l),u=0;u<p.length;u++)p[u]!=="default"&&et(o,l,p[u]);return H(o,l),o});Object.defineProperty(h,"__esModule",{value:true});var at=Et(b(203)),Yt=["#EXTINF","#EXT-X-BYTERANGE","#EXT-X-DISCONTINUITY","#EXT-X-STREAM-INF","#EXT-X-CUE-OUT","#EXT-X-CUE-IN","#EXT-X-KEY","#EXT-X-MAP"],Xt=["#EXT-X-MEDIA"],xt=(function(l){function o(s){var i,g,E,C;return (function(P,M){if(!(P instanceof M))throw new TypeError("Cannot call a class as a function")})(this,o),i=I(this,o),g=i,C=void 0,(E=G(E="baseUri"))in g?Object.defineProperty(g,E,{value:C,enumerable:true,configurable:true,writable:true}):g[E]=C,i.baseUri=s,i}return (function(s,i){if(typeof i!="function"&&i!==null)throw new TypeError("Super expression must either be null or a function");s.prototype=Object.create(i&&i.prototype,{constructor:{value:s,writable:true,configurable:true}}),Object.defineProperty(s,"prototype",{writable:false}),i&&X(s,i);})(o,l),p=o,u=[{key:"push",value:function(){for(var s=this,i=arguments.length,g=new Array(i),E=0;E<i;E++)g[E]=arguments[E];for(var C=function(){var N=M[P];if(!N.startsWith("#"))return S(o,"push",s,3)([N]),0;if(Yt.some((function(x){return N.startsWith(x)})))return S(o,"push",s,3)([N]),0;if(s.includes(N)){if(Xt.some((function(x){return N.startsWith(x)})))return 0;at.INVALIDPLAYLIST("Redundant item (".concat(N,")"));}S(o,"push",s,3)([N]);},P=0,M=g;P<M.length;P++)C();return this.length}},{key:"join",value:function(){for(var s=arguments.length>0&&arguments[0]!==void 0?arguments[0]:",",i=this.length-1;i>=0;i--)this[i]||this.splice(i,1);return S(o,"join",this,3)([s])}}],u&&v(p.prototype,u),a&&v(p,a),Object.defineProperty(p,"prototype",{writable:false}),p;var p,u,a;})(y(Array));function Pt(l,o){var p=1e3;o&&(p=Math.pow(10,o));var u=Math.round(l*p)/p;return o?u.toFixed(o):u}function Ft(l){var o=['DATA-ID="'.concat(l.id,'"')];return l.language&&o.push('LANGUAGE="'.concat(l.language,'"')),l.value?o.push('VALUE="'.concat(l.value,'"')):l.uri&&o.push('URI="'.concat(l.uri,'"')),"#EXT-X-SESSION-DATA:".concat(o.join(","))}function Lt(l,o){var p=o?"#EXT-X-SESSION-KEY":"#EXT-X-KEY",u=["METHOD=".concat(l.method)];return l.uri&&u.push('URI="'.concat(l.uri,'"')),l.iv&&(l.iv.byteLength!==16&&at.INVALIDPLAYLIST("IV must be a 128-bit unsigned integer"),u.push("IV=".concat(at.byteSequenceToHex(l.iv)))),l.format&&u.push('KEYFORMAT="'.concat(l.format,'"')),l.formatVersion&&u.push('KEYFORMATVERSIONS="'.concat(l.formatVersion,'"')),"".concat(p,":").concat(u.join(","))}function yt(l,o){var p=o.isIFrameOnly?"#EXT-X-I-FRAME-STREAM-INF":"#EXT-X-STREAM-INF",u=["BANDWIDTH=".concat(o.bandwidth)];if(o.averageBandwidth&&u.push("AVERAGE-BANDWIDTH=".concat(o.averageBandwidth)),o.isIFrameOnly&&u.push('URI="'.concat(o.uri,'"')),o.codecs&&u.push('CODECS="'.concat(o.codecs,'"')),o.resolution&&u.push("RESOLUTION=".concat(o.resolution.width,"x").concat(o.resolution.height)),o.frameRate&&u.push("FRAME-RATE=".concat(Pt(o.frameRate,3))),o.hdcpLevel&&u.push("HDCP-LEVEL=".concat(o.hdcpLevel)),o.audio.length>0){u.push('AUDIO="'.concat(o.audio[0].groupId,'"'));var a,s=L(o.audio);try{for(s.s();!(a=s.n()).done;){var i=a.value;l.push(pt(i));}}catch(z){s.e(z);}finally{s.f();}}if(o.video.length>0){u.push('VIDEO="'.concat(o.video[0].groupId,'"'));var g,E=L(o.video);try{for(E.s();!(g=E.n()).done;){var C=g.value;l.push(pt(C));}}catch(z){E.e(z);}finally{E.f();}}if(o.subtitles.length>0){u.push('SUBTITLES="'.concat(o.subtitles[0].groupId,'"'));var P,M=L(o.subtitles);try{for(M.s();!(P=M.n()).done;){var N=P.value;l.push(pt(N));}}catch(z){M.e(z);}finally{M.f();}}if(at.getOptions().allowClosedCaptionsNone&&o.closedCaptions.length===0)u.push("CLOSED-CAPTIONS=NONE");else if(o.closedCaptions.length>0){u.push('CLOSED-CAPTIONS="'.concat(o.closedCaptions[0].groupId,'"'));var x,U=L(o.closedCaptions);try{for(U.s();!(x=U.n()).done;){var _=x.value;l.push(pt(_));}}catch(z){U.e(z);}finally{U.f();}}if(o.score&&u.push("SCORE=".concat(o.score)),o.allowedCpc){var F,D=[],Y=L(o.allowedCpc);try{for(Y.s();!(F=Y.n()).done;){var j=F.value,K=j.format,Z=j.cpcList;D.push("".concat(K,":").concat(Z.join("/")));}}catch(z){Y.e(z);}finally{Y.f();}u.push('ALLOWED-CPC="'.concat(D.join(","),'"'));}o.videoRange&&u.push("VIDEO-RANGE=".concat(o.videoRange)),o.stableVariantId&&u.push('STABLE-VARIANT-ID="'.concat(o.stableVariantId,'"')),o.pathwayId&&u.push('PATHWAY-ID="'.concat(o.pathwayId,'"')),o.programId&&u.push("PROGRAM-ID=".concat(o.programId)),l.push("".concat(p,":").concat(u.join(","))),o.isIFrameOnly||l.push("".concat(o.uri));}function pt(l){var o=["TYPE=".concat(l.type),'GROUP-ID="'.concat(l.groupId,'"'),'NAME="'.concat(l.name,'"')];return l.isDefault!==void 0&&o.push("DEFAULT=".concat(l.isDefault?"YES":"NO")),l.autoselect!==void 0&&o.push("AUTOSELECT=".concat(l.autoselect?"YES":"NO")),l.forced!==void 0&&o.push("FORCED=".concat(l.forced?"YES":"NO")),l.language&&o.push('LANGUAGE="'.concat(l.language,'"')),l.assocLanguage&&o.push('ASSOC-LANGUAGE="'.concat(l.assocLanguage,'"')),l.instreamId&&o.push('INSTREAM-ID="'.concat(l.instreamId,'"')),l.characteristics&&o.push('CHARACTERISTICS="'.concat(l.characteristics,'"')),l.channels&&o.push('CHANNELS="'.concat(l.channels,'"')),l.uri&&o.push('URI="'.concat(l.uri,'"')),"#EXT-X-MEDIA:".concat(o.join(","))}function Ct(l,o,p,u){var a,s,i,g=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1,E=false,C="";if(o.discontinuity&&l.push("#EXT-X-DISCONTINUITY"),o.gap&&l.push("#EXT-X-GAP"),o.key){var P=Lt(o.key);P!==p&&(l.push(P),p=P);}if(o.map){var M=(function(x){var U=['URI="'.concat(x.uri,'"')];return x.byterange&&U.push('BYTERANGE="'.concat(R(x.byterange),'"')),"#EXT-X-MAP:".concat(U.join(","))})(o.map);M!==u&&(l.push(M),u=M);}if(o.programDateTime&&l.push("#EXT-X-PROGRAM-DATE-TIME:".concat(at.formatDate(o.programDateTime))),o.dateRange&&l.push((function(x){var U=['ID="'.concat(x.id,'"')];x.start&&U.push('START-DATE="'.concat(at.formatDate(x.start),'"')),x.cue&&U.push('CUE="'.concat(x.cue,'"')),x.end&&U.push('END-DATE="'.concat(at.formatDate(x.end),'"')),x.duration&&U.push("DURATION=".concat(x.duration)),x.plannedDuration&&U.push("PLANNED-DURATION=".concat(x.plannedDuration)),x.classId&&U.push('CLASS="'.concat(x.classId,'"')),x.endOnNext&&U.push("END-ON-NEXT=YES");for(var _=0,F=Object.keys(x.attributes);_<F.length;_++){var D=F[_];D.startsWith("X-")?typeof x.attributes[D]=="number"?U.push("".concat(D,"=").concat(x.attributes[D])):U.push("".concat(D,'="').concat(x.attributes[D],'"')):D.startsWith("SCTE35-")&&U.push("".concat(D,"=").concat(at.byteSequenceToHex(x.attributes[D])));}return "#EXT-X-DATERANGE:".concat(U.join(","))})(o.dateRange)),o.markers.length>0&&(C=(function(x,U){var _,F="",D=L(U);try{for(D.s();!(_=D.n()).done;){var Y=_.value;if(Y.type==="OUT")F="OUT",x.push("#EXT-X-CUE-OUT:DURATION=".concat(Y.duration));else if(Y.type==="IN")F="IN",x.push("#EXT-X-CUE-IN");else if(Y.type==="RAW"){var j=Y.value?":".concat(Y.value):"";x.push("#".concat(Y.tagName).concat(j));}}}catch(K){D.e(K);}finally{D.f();}return F})(l,o.markers)),o.parts.length>0&&(E=(function(x,U){var _,F=false,D=L(U);try{for(D.s();!(_=D.n()).done;){var Y=_.value;if(Y.hint){var j=[];if(j.push("TYPE=PART",'URI="'.concat(Y.uri,'"')),Y.byterange){var K=Y.byterange,Z=K.offset,z=K.length;j.push("BYTERANGE-START=".concat(Z)),z&&j.push("BYTERANGE-LENGTH=".concat(z));}x.push("#EXT-X-PRELOAD-HINT:".concat(j.join(","))),F=!0;}else {var W=[];W.push("DURATION=".concat(Y.duration),'URI="'.concat(Y.uri,'"')),Y.byterange&&W.push("BYTERANGE=".concat(R(Y.byterange))),Y.independent&&W.push("INDEPENDENT=YES"),Y.gap&&W.push("GAP=YES"),x.push("#EXT-X-PART:".concat(W.join(",")));}}}catch(q){D.e(q);}finally{D.f();}return F})(l,o.parts)),E)return [p,u];if(typeof o.duration=="number"&&!Number.isNaN(o.duration)){var N=g<3?Math.round(o.duration):Pt(o.duration,(a=o.duration,s=a.toString(10),(i=s.indexOf("."))===-1?0:s.length-i-1));l.push("#EXTINF:".concat(N,",").concat(unescape(encodeURIComponent(o.title||""))));}return o.byterange&&l.push("#EXT-X-BYTERANGE:".concat(R(o.byterange))),Array.prototype.push.call(l,"".concat(o.uri)),[p,u,C]}function R(l){var o=l.offset,p=l.length;return "".concat(p,"@").concat(o)}function w(l){var o=[];for(var p in l)o.push("".concat(p,'="').concat(l[p],'"'));return "#EXT-X-DEFINE:".concat(o.join(","))}h.default=function(l,o){at.PARAMCHECK(l),at.ASSERT("Not a playlist",l.type==="playlist");var p=new xt(l.uri);if(p.push("#EXTM3U"),l.version&&p.push("#EXT-X-VERSION:".concat(l.version)),l.independentSegments&&p.push("#EXT-X-INDEPENDENT-SEGMENTS"),l.start&&p.push("#EXT-X-START:TIME-OFFSET=".concat(Pt(l.start.offset)).concat(l.start.precise?",PRECISE=YES":"")),l.defines){var u,a=L(l.defines);try{for(a.s();!(u=a.n()).done;){var s=u.value;p.push(w(s));}}catch(i){a.e(i);}finally{a.f();}}return l.isMasterPlaylist?(function(i,g,E){var C,P;g.contentSteering&&i.push((C=g.contentSteering,P=['SERVER-URI="'.concat(C.serverUri,'"'),'PATHWAY-ID="'.concat(C.pathwayId,'"')],"#EXT-X-CONTENT-STEERING:".concat(P.join(","))));var M,N=L(g.sessionDataList);try{for(N.s();!(M=N.n()).done;){var x=M.value;i.push(Ft(x));}}catch(W){N.e(W);}finally{N.f();}var U,_=L(g.sessionKeyList);try{for(_.s();!(U=_.n()).done;){var F=U.value;i.push(Lt(F,!0));}}catch(W){_.e(W);}finally{_.f();}var D,Y=L(g.variants.entries());try{for(Y.s();!(D=Y.n()).done;){var j=A(D.value,2),K=j[0],Z=j[1],z=i.length;yt(i,Z),E!=null&&E.variantProcessor&&E.variantProcessor(i,z,i.length-1,Z,K);}}catch(W){Y.e(W);}finally{Y.f();}})(p,l,o):(function(i,g,E){var C="",P="",M=false;if(g.targetDuration&&i.push("#EXT-X-TARGETDURATION:".concat(g.targetDuration)),g.lowLatencyCompatibility){var N=g.lowLatencyCompatibility,x=N.canBlockReload,U=N.canSkipUntil,_=N.holdBack,F=N.partHoldBack,D=[];D.push("CAN-BLOCK-RELOAD=".concat(x?"YES":"NO")),U!==void 0&&D.push("CAN-SKIP-UNTIL=".concat(U)),_!==void 0&&D.push("HOLD-BACK=".concat(_)),F!==void 0&&D.push("PART-HOLD-BACK=".concat(F)),i.push("#EXT-X-SERVER-CONTROL:".concat(D.join(",")));}g.partTargetDuration&&i.push("#EXT-X-PART-INF:PART-TARGET=".concat(g.partTargetDuration)),g.mediaSequenceBase&&i.push("#EXT-X-MEDIA-SEQUENCE:".concat(g.mediaSequenceBase)),g.discontinuitySequenceBase&&i.push("#EXT-X-DISCONTINUITY-SEQUENCE:".concat(g.discontinuitySequenceBase)),g.playlistType&&i.push("#EXT-X-PLAYLIST-TYPE:".concat(g.playlistType)),g.isIFrame&&i.push("#EXT-X-I-FRAMES-ONLY"),g.skip>0&&i.push("#EXT-X-SKIP:SKIPPED-SEGMENTS=".concat(g.skip));var Y,j=L(g.segments.entries());try{for(j.s();!(Y=j.n()).done;){var K,Z=A(Y.value,2),z=Z[0],W=Z[1],q=i.length,J=A(Ct(i,W,C,P,g.version),3);C=J[0],P=J[1],(K=J[2])==="OUT"?M=!0:K==="IN"&&M&&(M=!1),E!=null&&E.segmentProcessor&&E.segmentProcessor(i,q,i.length-1,W,z);}}catch(ot){j.e(ot);}finally{j.f();}g.playlistType==="VOD"&&M&&i.push("#EXT-X-CUE-IN"),g.prefetchSegments.length>2&&at.INVALIDPLAYLIST("The server must deliver no more than two prefetch segments");var Q,it=L(g.prefetchSegments);try{for(it.s();!(Q=it.n()).done;){var lt=Q.value;lt.discontinuity&&i.push("#EXT-X-PREFETCH-DISCONTINUITY"),i.push("#EXT-X-PREFETCH:".concat(lt.uri));}}catch(ot){it.e(ot);}finally{it.f();}g.endlist&&i.push("#EXT-X-ENDLIST");var ut,gt=L(g.renditionReports);try{for(gt.s();!(ut=gt.n()).done;){var Tt=ut.value,$=[];$.push('URI="'.concat(Tt.uri,'"'),"LAST-MSN=".concat(Tt.lastMSN)),Tt.lastPart!==void 0&&$.push("LAST-PART=".concat(Tt.lastPart)),i.push("#EXT-X-RENDITION-REPORT:".concat($.join(",")));}}catch(ot){gt.e(ot);}finally{gt.f();}})(p,l,o),p.join(`
`)};}},r={},c=(function m(h){var b=r[h];if(b!==void 0)return b.exports;var T=r[h]={exports:{}};return n[h].call(T.exports,T,T.exports,m),T.exports})(73);return c})()));})(fe)),fe.exports}var gr=mr();function ne(e,t){const n=gr.parse(e);if(n.isMasterPlaylist)return {isMaster:true,variants:vr(n,t)};const r=n,c=Er(r,t);return {isMaster:false,segments:c.segs,mediaSeq:c.mediaSeq,endList:c.endList,targetDuration:r.targetDuration}}function vr(e,t){const n=[];for(const r of e.variants){if(!r.uri)continue;const c=r.resolution,m=c?.width??null,h=c?.height??null;n.push({url:Jt(r.uri,t),res:m&&h?`${m}x${h}`:null,w:m,h,peak:r.bandwidth??null,avg:r.averageBandwidth??null,codecs:r.codecs??null});}return n}function He(e,t){if(!e||typeof e.length!="number")return {header:null,next:t};const n=typeof e.offset=="number"?e.offset:t,r=n+e.length-1;return {header:`bytes=${n}-${r}`,next:r+1}}function Er(e,t){const n=[];let r=0,c=null;for(let m=0;m<e.segments.length;m++){const h=e.segments[m];let b=null;if(h.byterange){const O=He(h.byterange,r);b=O.header,r=O.next;}else r=0;let T=null,A=false;if(h.map?.uri){const O=Jt(h.map.uri,t);let k=null;h.map.byterange&&(k=He(h.map.byterange,0).header),T={uri:O,rangeHeader:k};const v=`${O}|${k||""}`;A=v!==c,A&&(c=v);}let L=null;h.key?.method&&h.key.method!=="NONE"&&(L={method:String(h.key.method).toUpperCase(),uri:h.key.uri?Jt(h.key.uri,t):null,iv:h.key.iv?.toString()??null}),n.push({uri:Jt(h.uri,t),dur:h.duration||0,range:b,key:L,map:T,needMap:A});}return {segs:n,mediaSeq:e.mediaSequenceBase||0,endList:e.endlist??false}}function dn(e){let t=true,n=0;const r=new Set;for(const c of e.segs){if(c.range){const m=pe(c.range);!m||m.end==null?t=false:n+=m.end-m.start+1;}else t=false;if(c.needMap&&c.map)if(c.map.rangeHeader){const m=`${c.map.uri}|${c.map.rangeHeader}`;if(!r.has(m)){r.add(m);const h=pe(c.map.rangeHeader);!h||h.end==null?t=false:n+=h.end-h.start+1;}}else t=false;}return t?n:null}function yr(e,t,n){const r=e.endList,c=dn(e);if(c!=null)return {bytes:c,seconds:t,vod:r,via:"byterange"};const m=n?.avg??n?.peak??null;return r&&m&&t>0?{bytes:Math.round(m/8*t),seconds:t,vod:r,via:"avg-bw"}:{bytes:null,seconds:t,vod:r,via:"unknown"}}function fn(e){return e.reduce((t,n)=>t+n.dur,0)}function hn(e){return e.length===0?false:e.some(t=>t.map)||/\.m4s(\?|$)/i.test(e[0].uri)}function Tr(e){return e.some(t=>t.key?.method==="AES-128")}const br=new an({concurrency:2}),he=new Set;let pn=()=>{},mn=()=>{};function Ir(e){pn=e;}function Sr(e){mn=e;}async function wr(e){const t=await ee(e.url),n=ne(t,e.url);if(n.isMaster&&n.variants){const c=on(n.variants)[0],m=n.variants.length,b=[`${m} ${m===1?"quality":"qualities"}`];c?.res?b.push(`up to ${c.res}`):c?.h&&b.push(`up to ${c.h}p`),e.label=b.join(" • "),e.hlsType="master",e.variantCount=m,e.variants=n.variants,e.bestVariant=c;}else if(n.segments&&n.segments.length>0){const r=n.segments,c=r.length,m=fn(r),h=n.endList??false,b=dn({segs:r,mediaSeq:n.mediaSeq??0}),T=Qe(e.url),A=hn(r),L=Tr(r);e.label=sn({resolution:T,duration:m,size:b}),e.sublabel=or(c,A),e.hlsType="media",e.duration=m,e.segCount=c,e.resolution=T,e.isVod=h,e.isFmp4=A,e.encrypted=L,e.isLive=!h,b!=null&&(e.size=b);}else e.label="Empty or Invalid",e.hlsType="invalid";return e.enriched=true,true}async function gn(e){if(!e||e.enriched||e.enriching)return  false;e.enriching=true;const t=new Promise((n,r)=>setTimeout(()=>r(new Error("Timeout")),tt.ENRICH_TIMEOUT));try{return e._enrichPromise=Promise.race([wr(e),t]),await e._enrichPromise,!0}catch(n){const r=n;return console.error("[SG] enrichItem error:",r),e.label=r.message==="Timeout"?"Timeout":"Parse Error",e.hlsType="error",e.enriched=true,false}finally{e.enriching=false,e._enrichPromise=null;}}function vn(e){he.has(e)||(he.add(e),br.add(async()=>{try{const t=mn(e);t&&t.kind==="hls"&&!t.enriched&&(await gn(t),pn());}finally{he.delete(e);}}));}async function Ar(e){return e._enrichPromise?(await e._enrichPromise,e.enriched&&e.hlsType!=="error"&&e.hlsType!=="invalid"):gn(e)}class ct{static instance;handlers=new Map;initialized=false;constructor(){this.handleMessage=this.handleMessage.bind(this);}static get(){return ct.instance||(ct.instance=new ct),ct.instance}init(){this.initialized||(this.initialized=true,window.addEventListener("message",this.handleMessage),console.log("[SG] MessageBus initialized"));}on(t,n){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(n);}off(t,n){const r=this.handlers.get(t);r&&(r.delete(n),r.size===0&&this.handlers.delete(t));}send(t,n={},r=window.top){try{const c={type:t,payload:n};r.postMessage(c,"*");}catch(c){console.error("[SG] Failed to send message:",t,c);}}sendToTop(t,n={}){window.top&&this.send(t,n,window.top);}handleMessage(t){const n=t.data;if(!n||typeof n!="object"||!n.type||t.source===window)return;const r=this.handlers.get(n.type);r&&r.forEach(c=>{try{c(n.payload||{},t.source);}catch(m){console.error("[SG] Error in message handler:",m);}});}}const ve=new Map;let En=()=>{},yn=()=>{},Tn=()=>{},bn=()=>{},In=()=>{},Sn=()=>{};function Nr(e){e.onRemoteItem&&(En=e.onRemoteItem),e.onProgressStart&&(yn=e.onProgressStart),e.onProgressUpdate&&(Tn=e.onProgressUpdate),e.onProgressDone&&(bn=e.onProgressDone),e.onPick&&(In=e.onPick),e.onDownloadCommand&&(Sn=e.onDownloadCommand);}function Rr(){const e=ct.get();tt.IS_TOP?(e.on("SG_DETECT",(t,n)=>{if(t.item,!t.item)return;const r=t.item;r.remoteWin=n,r.isRemote=true,console.log("[SG] Received detection from iframe:",r.kind,r.url.slice(0,60)),nt.addItem(r)&&(En(r),r.kind==="hls"&&vn(r.url));}),e.on("SG_PROGRESS_START",(t,n)=>{const{id:r,title:c,src:m}=t;yn(r,c,m,n);}),e.on("SG_PROGRESS_UPDATE",t=>{const{id:n,p:r,txt:c}=t;Tn(n,r,c);}),e.on("SG_PROGRESS_DONE",t=>{const{id:n,ok:r,msg:c}=t;bn(n,r,c);}),e.on("SG_CMD_PICK",(t,n)=>{const{id:r,items:c,title:m}=t;In(r,c,m,n);})):(e.on("SG_CMD_DOWNLOAD",t=>{const{url:n,kind:r,variant:c}=t;console.log("[SG] [iframe] Received download command:",{url:n,kind:r}),Sn(n,r,c);}),e.on("SG_CMD_PICK_RESULT",t=>{const{id:n,item:r}=t,c=ve.get(n);c&&(ve.delete(n),c(r));}));}function Pr(e){ct.get().sendToTop("SG_DETECT",{item:ur(e)});}function Lr(e,t){ve.set(e,t);}function Cr(){ct.get().init(),Rr(),console.log("[SG] Messaging handlers set up via MessageBus");}const Or=Object.prototype.toString,Dr=e=>Or.call(e)==="[object Error]",Xr=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function xr(e){if(!(e&&Dr(e)&&e.name==="TypeError"&&typeof e.message=="string"))return  false;const{message:n,stack:r}=e;return n==="Load failed"?r===void 0||"__sentry_captured__"in e:n.startsWith("error sending request for url")?true:Xr.has(n)}function Mr(e){if(typeof e=="number"){if(e<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(e))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(e!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Zt(e,t,{min:n=0,allowInfinity:r=false}={}){if(t!==void 0){if(typeof t!="number"||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<n)throw new TypeError(`Expected \`${e}\` to be ≥ ${n}.`)}}class Nt extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t;}}function kr(e,t){const n=Math.max(1,e+1),r=t.randomize?Math.random()+1:1;let c=Math.round(r*t.minTimeout*t.factor**(n-1));return c=Math.min(c,t.maxTimeout),c}function qe(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function Ur({error:e,attemptNumber:t,retriesConsumed:n,startTime:r,options:c}){const m=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(m instanceof Nt)throw m.originalError;const h=Number.isFinite(c.retries)?Math.max(0,c.retries-n):c.retries,b=c.maxRetryTime??Number.POSITIVE_INFINITY,T=Object.freeze({error:m,attemptNumber:t,retriesLeft:h,retriesConsumed:n});if(await c.onFailedAttempt(T),qe(r,b)<=0)throw m;const A=await c.shouldConsumeRetry(T),L=qe(r,b);if(L<=0||h<=0)throw m;if(m instanceof TypeError&&!xr(m)){if(A)throw m;return c.signal?.throwIfAborted(),false}if(!await c.shouldRetry(T))throw m;if(!A)return c.signal?.throwIfAborted(),false;const O=kr(n,c),k=Math.min(O,L);return c.signal?.throwIfAborted(),k>0&&await new Promise((v,I)=>{const S=()=>{clearTimeout(f),c.signal?.removeEventListener("abort",S),I(c.signal.reason);},f=setTimeout(()=>{c.signal?.removeEventListener("abort",S),v();},k);c.unref&&f.unref?.(),c.signal?.addEventListener("abort",S,{once:true});}),c.signal?.throwIfAborted(),true}async function _r(e,t={}){if(t={...t},Mr(t.retries),Object.hasOwn(t,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");t.retries??=10,t.factor??=2,t.minTimeout??=1e3,t.maxTimeout??=Number.POSITIVE_INFINITY,t.maxRetryTime??=Number.POSITIVE_INFINITY,t.randomize??=false,t.onFailedAttempt??=()=>{},t.shouldRetry??=()=>true,t.shouldConsumeRetry??=()=>true,Zt("factor",t.factor,{min:0,allowInfinity:false}),Zt("minTimeout",t.minTimeout,{min:0,allowInfinity:false}),Zt("maxTimeout",t.maxTimeout,{min:0,allowInfinity:true}),Zt("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:true}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let n=0,r=0;const c=performance.now();for(;!Number.isFinite(t.retries)||r<=t.retries;){n++;try{t.signal?.throwIfAborted();const m=await e(n);return t.signal?.throwIfAborted(),m}catch(m){await Ur({error:m,attemptNumber:n,retriesConsumed:r,startTime:c,options:t})&&r++;}}throw new Error("Retry attempts exhausted without throwing an error.")}function Vr(e){const t=(e||"").replace(/^0x/i,"").replace(/[^0-9a-f]/gi,"");if(t.length===0)return new Uint8Array(0);const r=(t.length%2===0?t:"0"+t).match(/.{1,2}/g);return r?new Uint8Array(r.map(c=>parseInt(c,16))):new Uint8Array(0)}function Yr(e){let t=BigInt(e>>>0);const n=new Uint8Array(16);for(let r=15;r>=0;r--)n[r]=Number(t&0xffn),t>>=8n;return n}async function Fr(e,t,n){const r=await crypto.subtle.importKey("raw",t,{name:"AES-CBC"},false,["decrypt"]);return crypto.subtle.decrypt({name:"AES-CBC",iv:n},r,e)}const Gr=(e,t=5e3)=>{setTimeout(()=>URL.revokeObjectURL(e),t);};function Br(e,t){switch(e){case "not_enabled":return "Downloads are disabled in userscript settings";case "not_whitelisted":return "URL not whitelisted for download. Check userscript settings.";case "not_permitted":return "Download not permitted. Try allowing downloads in browser settings.";case "not_supported":return "Download not supported by your userscript manager";case "not_succeeded":return t||"Download failed. Check if the file location is writable.";default:return `Download failed: ${e||"unknown"}${t?` - ${t}`:""}`}}function jr(e,t){return new Promise(n=>{const r=document.createElement("a");r.href=e,r.download=t,r.style.display="none",document.body.appendChild(r),r.click(),document.body.removeChild(r),setTimeout(()=>{n();},500);})}function zr(e,t,n){return new Promise((r,c)=>{GM_download({url:e,name:t,saveAs:true,onload:()=>{n?.(),r();},onerror:m=>{c(new Error(Br(m?.error,m?.details)));},ontimeout:()=>{c(new Error("Download timed out"));}});})}async function Hr(e,t,n){try{typeof GM_download=="function"?await zr(e,t,n):(console.log("[SG] GM_download unavailable, using anchor fallback"),await jr(e,t),n?.());}finally{Gr(e);}}async function qr(e,t){if(typeof window.showSaveFilePicker!="function"||window.isSecureContext===false)return null;try{const n=e.split(".").pop()||"mp4",c=await(await window.showSaveFilePicker({suggestedName:e,types:[{description:"Video file",accept:{[t]:[`.${n}`]}}]})).createWritable();let m=!1,h=!1;return {async write(b){if(h)throw new Error("Writer was aborted");if(m){console.warn("[SG] Attempted to write after close");return}await c.write(b);},async close(){if(h)throw new Error("Writer was aborted");if(!m){m=!0;try{await c.close(),Se(e);}catch(b){throw console.error("[SG] Native close error:",b),new Error(`Failed to save file: ${b.message}`)}}},abort(){m||h||(h=!0,c.abort().catch(()=>{}));}}}catch(n){const r=n;if(r.name==="AbortError")throw n;return console.warn("[SG] File System Access API failed, using fallback:",r.message),null}}function $r(e,t){const n=[];let r=[],c=0,m=0,h=1,b=false,T=false;const A=100*1024*1024,L=1.9*1024*1024*1024,O=()=>{if(c===0)return;const I=new Blob(r,{type:t});n.push(I),r=[],c=0;},k=()=>{r=[],c=0,n.length=0,m=0;},v=async I=>{if(O(),n.length===0&&!I)return;if(n.length===0&&I&&h===1)throw new Error("No data to save");let S=e;if(h>1||!I&&h===1){const d=e.lastIndexOf(".");d!==-1?S=`${e.substring(0,d)}.part${h}${e.substring(d)}`:S=`${e}.part${h}`;}console.log(`[SG] Saving part ${h}: ${S}, Size: ${(m/1024/1024).toFixed(2)} MB`);const f=new Blob(n,{type:t});n.length=0,r=[],c=0,m=0;const y=URL.createObjectURL(f);await Hr(y,S,()=>{I&&Se(e);});};return {async write(I){if(T)throw new Error("Writer was aborted");if(b){console.warn("[SG] Attempted to write after close");return}m+I.length>L&&(console.warn(`[SG] File part ${h} limit reached (~1.9GB). Splitting file...`),await v(false),h++),r.push(I),c+=I.length,m+=I.length,c>=A&&(O(),n.length%5===0&&console.log(`[SG] Part ${h} Buffer: ${n.length} blobs, Size: ${(m/1024/1024).toFixed(2)} MB`));},async close(){if(T)throw new Error("Writer was aborted");b||(b=true,await v(true),k());},abort(){b||T||(T=true,k());}}}async function Kr(e,t){const n=await qr(e,t);return n?(console.log("[SG] Using native File System Access API"),n):(console.log("[SG] Using blob fallback for download"),$r(e,t))}const Wr=100,Qr=50,Zr=50;class $e{cache=new Map;inflight=new Map;async fetch(t,n,r){if(r?.aborted)throw new Nt(new Error("Aborted"));const c=await tn(this.cache,this.inflight,t,n,Wr);if(r?.aborted)throw new Nt(new Error("Aborted"));return c}clear(){this.cache.clear(),this.inflight.clear();}}class Jr{constructor(t){this.writer=t;}buffers=new Map;writePtr=0;writeChain=Promise.resolve();totalBytes=0;writeError=null;get bufferedCount(){return this.buffers.size}get bytesWritten(){return this.totalBytes}get error(){return this.writeError}shouldThrottle(){return this.buffers.size>=Qr}enqueue(t,n){this.buffers.set(t,n),this.flush();}flush(){this.writeChain=this.writeChain.then(async()=>{for(;this.buffers.has(this.writePtr);){const t=this.buffers.get(this.writePtr);this.buffers.delete(this.writePtr);try{await this.writer.write(t),this.totalBytes+=t.length;}catch(n){throw this.writeError=n,n}this.writePtr++;}});}async finalize(){if(await this.writeChain,this.writeError)throw this.writeError}async close(){await this.finalize(),await this.writer.close();}abort(){this.buffers.clear(),this.writer.abort();}}class ti{constructor(t,n){this.total=t,this.onUpdate=n;}inProgress=new Map;rafId=0;_done=0;byteDone=0;avgLen=0;get done(){return this._done}get averageSize(){return this.avgLen}setProgress(t,n,r){this.inProgress.set(t,{loaded:n,total:r}),this.scheduleUpdate();}markComplete(t,n){this.inProgress.delete(t),this._done++,this.byteDone+=n,this.avgLen=this.byteDone/this._done,this.scheduleUpdate();}clear(t){this.inProgress.delete(t);}scheduleUpdate(){this.rafId||(this.rafId=requestAnimationFrame(()=>{this.rafId=0;const t=this.calculatePartial(),n=(this._done+t)/this.total*100;this.onUpdate(n,this._done,this.total);}));}calculatePartial(){let t=0;return this.inProgress.forEach(({loaded:n,total:r})=>{r>0?t+=Math.min(1,n/r):this.avgLen>0&&(t+=Math.min(1,n/this.avgLen));}),t}}class ei{constructor(t){this.mediaSeq=t;}keyCache=new $e;mapCache=new $e;async fetch(t,n,r,c){this.validateEncryption(t);const[m,h]=await Promise.all([this.fetchKey(t,r),this.fetchMap(t,r)]),b=await this.download(t,r,c),T=m?await this.decrypt(b,m,t,n):b;return this.prependMap(new Uint8Array(T),h)}validateEncryption(t){if(t.key?.method&&t.key.method!=="AES-128")throw new Nt(new Error(`Unsupported key method: ${t.key.method}`))}async download(t,n,r){const c=t.range?{Range:t.range}:{},m=de(t.uri,c,tt.REQUEST_TIMEOUT,b=>{r(b.loaded,b.total);}),h=()=>m.abort();n.addEventListener("abort",h,{once:true});try{if(n.aborted)throw m.abort(),new Nt(new Error("Aborted"));return await m}catch(b){throw n.aborted?new Nt(new Error("Aborted")):b}finally{n.removeEventListener("abort",h);}}async fetchKey(t,n){return !t.key||t.key.method!=="AES-128"||!t.key.uri?null:this.keyCache.fetch(t.key.uri,async()=>{const r=await de(t.key.uri);return new Uint8Array(r)},n)}async fetchMap(t,n){if(!t.needMap||!t.map?.uri)return null;const r=`${t.map.uri}|${t.map.rangeHeader||""}`;return this.mapCache.fetch(r,async()=>{const c=t.map.rangeHeader?{Range:t.map.rangeHeader}:{},m=await de(t.map.uri,c);return new Uint8Array(m)},n)}async decrypt(t,n,r,c){const m=r.key.iv?Vr(r.key.iv):Yr(this.mediaSeq+c);return Fr(t,n,m)}prependMap(t,n){if(!n?.length)return t;const r=new Uint8Array(n.length+t.length);return r.set(n,0),r.set(t,n.length),r}clear(){this.keyCache.clear(),this.mapCache.clear();}}class ni{constructor(t,n,r,c,m){this.segments=t,this.onProgress=c,this.onComplete=m,this.queue=new an({concurrency:tt.CONCURRENCY}),this.writer=new Jr(r),this.progress=new ti(t.length,c),this.fetcher=new ei(n);}queue;controllers=new Map;writer;progress;fetcher;paused=false;canceled=false;finalized=false;async start(){for(let t=0;t<this.segments.length;t++)this.queue.add(()=>this.downloadSegment(t));await this.queue.onIdle(),await this.finalize();}togglePause(){return this.paused=!this.paused,this.paused?this.queue.pause():this.queue.start(),this.paused}cancel(){this.canceled||(this.canceled=true,this.abortAll(),this.queue.clear(),this.writer.abort(),this.cleanup());}async downloadSegment(t){if(this.canceled||(await this.waitForBackpressure(),this.canceled))return;const n=new AbortController;this.controllers.set(t,n);try{await _r(async()=>{if(this.canceled)throw new Nt(new Error("Canceled"));const r=await this.fetcher.fetch(this.segments[t],t,n.signal,(c,m)=>{this.progress.setProgress(t,c,m);});this.writer.enqueue(t,r),this.progress.markComplete(t,r.length);},{retries:tt.RETRIES,signal:n.signal,onFailedAttempt:({error:r,attemptNumber:c})=>{this.canceled||console.warn(`[SG] Segment ${t} failed (attempt ${c}): ${r.message}`);}});}catch(r){this.handleSegmentError(t,r);}finally{this.controllers.delete(t);}}async waitForBackpressure(){for(;this.writer.shouldThrottle()&&!this.canceled;)await new Promise(t=>setTimeout(t,Zr));}handleSegmentError(t,n){this.progress.clear(t),!(this.canceled||n instanceof Nt)&&(console.error(`[SG] Segment ${t} fatal error:`,n),this.canceled=true,this.abortAll(),this.queue.clear());}abortAll(){for(const t of this.controllers.values())t.abort();this.controllers.clear();}async finalize(){if(this.finalized)return;this.finalized=true;const t=!this.canceled&&this.progress.done===this.segments.length&&!this.writer.error;try{if(t)await this.writer.close(),this.onComplete(!0);else {this.writer.abort();const n=this.writer.error?"Write failed":this.canceled?"Canceled":"Incomplete download";this.onComplete(!1,n);}}catch(n){console.error("[SG] Finalize error:",n),this.onComplete(false,"Finalization failed");}finally{this.cleanup();}}cleanup(){this.fetcher.clear();}}async function ri(e,t,n,r){const c=e.segs.length;console.log("[SG] Starting segment download:",{filename:t,segments:c});const m=n?"video/mp4":"video/mp2t";let h;try{h=await Kr(t,m);}catch(T){if(T.name==="AbortError"){r.remove();return}throw T}const b=new ni(e.segs,e.mediaSeq,h,(T,A,L)=>{r.update(T,`${A}/${L}`);},(T,A)=>{T?(r.update(100,""),r.done(true)):r.done(false,A);});r.setOnStop(()=>b.togglePause()?"paused":"resumed"),r.setOnCancel(()=>{b.cancel(),r.remove();}),await b.start();}async function Ee(e,t){console.log("[SG] Direct download:",e);const n=st.get(e),r=Je(e,n?.type),c=`${Ze(document.title)}.${r}`;let m=e,h=()=>{};n?.blob&&(m=URL.createObjectURL(n.blob),h=()=>URL.revokeObjectURL(m));const b=t.createCard(c,e);b.setOnCancel(()=>{h(),b.remove();}),GM_download({url:m,name:c,saveAs:true,onprogress:T=>{T.lengthComputable?b.update(T.loaded/T.total*100,`${Ht(T.loaded)}/${Ht(T.total)}`):b.update(0,Ht(T.loaded));},onload:()=>{b.update(100,""),b.done(true),h(),Se(c);},onerror:T=>{const A=T?.error||"unknown";console.error("[SG] Download error:",{error:A,url:e}),b.done(false,A==="not_succeeded"?"Save failed":A),h();},ontimeout:()=>{b.done(false,"Timeout"),h();}});}async function re(e,t,n){console.log("[SG] HLS download:",e);const r=await ee(e),c=ne(r,e);let m=e,h=t;if(c.isMaster&&c.variants&&c.variants.length>0){const S=on(c.variants);if(S.length===0)throw new Error("No variants found");const f=[];for(const d of S){let X=null,V=0;try{const rt=await ee(d.url),et=ne(rt,d.url);et.segments&&(V=fn(et.segments),X=yr({segs:et.segments,mediaSeq:et.mediaSeq??0,endList:et.endList??!1},V,d).bytes);}catch{}const G=sn({resolution:d.res,bitrate:d.avg||d.peak,duration:V,size:X});f.push({url:d.url,kind:"variant",label:G,sublabel:null,size:X,type:null,origin:document.location.origin,enriched:true,enriching:false,hlsType:"media",isLive:false,encrypted:false,variant:d});}const y=await n.pickVariant(f);if(!y)return;h=y.variant??null,m=y.url;}const b=await ee(m),T=ne(b,m);if(!T.segments||T.segments.length===0)throw new Error("Invalid playlist: no segments");const A={segs:T.segments,mediaSeq:T.mediaSeq??0,endList:T.endList??false},L=hn(A.segs),O=L?"mp4":"ts",k=Ze(document.title),v=h?.res?`_${h.res}`:"",I=`${k}${v}.${O}`;n.createCard(I,e,A.segs.length),await ri(A,I,L,e);}async function ii(e,t){if(e.isRemote&&e.remoteWin){if(e.remoteWin.closed)throw new Error("Source frame is gone");if(!e.url.startsWith("blob:")){if(e.kind==="hls")return re(e.url,null,t);if(e.kind==="video")return Ee(e.url,t)}e.remoteWin.postMessage({type:"SG_CMD_DOWNLOAD",payload:{url:e.url,kind:e.kind,variant:e.variant}},"*");return}if(e.kind==="hls"&&!e.enriched){t.setBusy(true);try{e._enrichPromise?await e._enrichPromise:await Ar(e);}catch(n){throw new Error(`Failed to analyze stream: ${n.message}`)}finally{t.setBusy(false);}if(e.hlsType==="error"||e.hlsType==="invalid")throw new Error("Cannot download: Stream analysis failed or invalid")}if(e.kind==="video")return Ee(e.url,t);if(e.kind==="variant")return re(e.url,e.variant??null,t);if(e.kind==="hls")return re(e.url,null,t)}const ai='@import"https://fonts.googleapis.com/css2?family=Cinzel:wght@400;600;700&family=Urbanist:wght@300;400;500;600;700&display=swap";#sg-fab-container,#sg-modal-container,#sg-toast-container{font-family:Urbanist,system-ui,-apple-system,sans-serif!important;font-size:14px!important;line-height:1.5!important;box-sizing:border-box!important;letter-spacing:.02em!important}#sg-fab-container *,#sg-modal-container *,#sg-toast-container *{box-sizing:border-box!important;outline:none!important}:host{--sg-bg-deep: #050505;--sg-bg-surface: #0a0a0a;--sg-bg-glass: rgba(10, 10, 10, .7);--sg-gold-dim: #8a7e58;--sg-gold: #D4AF37;--sg-gold-bright: #f4d060;--sg-gold-glow: rgba(212, 175, 55, .3);--sg-border-subtle: rgba(255, 255, 255, .08);--sg-border-gold: rgba(212, 175, 55, .25);--sg-text-main: #f0f0f0;--sg-text-muted: #888888;--sg-text-gold: #e5c55d;--sg-success: #10b981;--sg-error: #ef4444;--sg-warn: #f59e0b;--sg-radius-lg: 16px;--sg-radius-md: 10px;--sg-radius-sm: 6px;--sg-shadow-glow: 0 0 20px var(--sg-gold-glow);--sg-glass-blur: blur(16px);--sg-font-display: "Cinzel", serif;--sg-font-body: "Urbanist", sans-serif;--sg-transition: all .3s cubic-bezier(.25, .8, .25, 1)}@keyframes sg-spin{to{transform:rotate(360deg)}}@keyframes sg-breathe{0%,to{box-shadow:0 0 10px var(--sg-gold-glow);border-color:var(--sg-gold)}50%{box-shadow:0 0 25px var(--sg-gold-glow);border-color:var(--sg-gold-bright)}}@keyframes sg-fade-up{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes sg-scale-in{0%{opacity:0;transform:scale(.95)}to{opacity:1;transform:scale(1)}}.sg-fab{all:initial!important;position:fixed!important;right:30px!important;bottom:30px!important;z-index:2147483647!important;width:60px!important;height:60px!important;border-radius:20px!important;padding:0!important;display:none!important;align-items:center!important;justify-content:center!important;background:linear-gradient(145deg,#151515,#000)!important;color:var(--sg-gold)!important;border:1px solid var(--sg-border-gold)!important;border-top:1px solid var(--sg-border-subtle)!important;cursor:pointer!important;font-family:var(--sg-font-body)!important;box-shadow:0 10px 30px #00000080,0 0 0 1px #00000080!important;transition:var(--sg-transition)!important}.sg-fab.show{display:flex!important;animation:sg-scale-in .4s ease-out backwards!important}.sg-fab:hover{transform:translateY(-2px) scale(1.05)!important;box-shadow:0 15px 40px #0009,var(--sg-shadow-glow)!important;border-color:var(--sg-gold-bright)!important;color:var(--sg-gold-bright)!important}.sg-fab:active{transform:translateY(0) scale(.95)!important}.sg-fab.busy{pointer-events:none!important;animation:sg-breathe 2s infinite!important}.sg-fab.busy>.sg-fab-icon{opacity:0!important}.sg-fab.busy:after{content:""!important;position:absolute!important;inset:0!important;margin:auto!important;width:24px!important;height:24px!important;border:2px solid transparent!important;border-top-color:var(--sg-gold)!important;border-right-color:var(--sg-gold)!important;border-radius:50%!important;animation:sg-spin .8s linear infinite!important}.sg-fab-icon{all:initial!important;display:flex!important;align-items:center!important;justify-content:center!important;color:inherit!important;font-size:0!important}.sg-fab svg{width:26px!important;height:26px!important;fill:none!important;stroke:currentColor!important;stroke-width:2!important;filter:drop-shadow(0 0 2px rgba(212,175,55,.5))!important}.sg-badge{all:initial!important;position:absolute!important;top:-6px!important;right:-6px!important;background:var(--sg-gold)!important;color:#000!important;font-weight:700!important;font-size:11px!important;font-family:var(--sg-font-body)!important;padding:2px 7px!important;border-radius:10px!important;display:none!important;border:2px solid #000!important;min-width:22px!important;text-align:center!important;box-shadow:0 4px 8px #00000080!important}.sg-badge.show{display:inline-block!important;animation:sg-scale-in .3s cubic-bezier(.18,.89,.32,1.28)!important}.sg-modal{all:initial!important;position:fixed!important;inset:0!important;z-index:2147483647!important;display:none!important;align-items:center!important;justify-content:center!important;background:#0009!important;backdrop-filter:blur(8px)!important;font-family:var(--sg-font-body)!important;opacity:0!important;transition:opacity .3s ease!important}.sg-modal.show{display:flex!important;opacity:1!important}.sg-card{all:initial!important;display:flex!important;flex-direction:column!important;background:#0a0a0ad9!important;backdrop-filter:var(--sg-glass-blur) saturate(180%)!important;-webkit-backdrop-filter:var(--sg-glass-blur) saturate(180%)!important;border:1px solid var(--sg-border-gold)!important;border-radius:var(--sg-radius-lg)!important;color:var(--sg-text-main)!important;width:min(580px,94vw)!important;max-height:85vh!important;overflow:hidden!important;box-shadow:0 20px 50px #000000b3,0 0 0 1px #ffffff0d!important;font-family:var(--sg-font-body)!important;transform:translateY(20px)!important;transition:transform .4s cubic-bezier(.19,1,.22,1)!important}.sg-modal.show .sg-card{transform:translateY(0)!important}.sg-card-head{all:initial!important;display:grid!important;grid-template-columns:1fr auto!important;align-items:center!important;padding:24px 28px 20px!important;border-bottom:1px solid var(--sg-border-subtle)!important;background:linear-gradient(to bottom,rgba(255,255,255,.03),transparent)!important;font-family:var(--sg-font-body)!important;position:relative!important}.sg-card-head:after{content:""!important;position:absolute!important;bottom:0!important;left:28px!important;width:40px!important;height:2px!important;background:var(--sg-gold)!important;box-shadow:0 0 8px var(--sg-gold)!important}.sg-card-title{all:initial!important;font-family:var(--sg-font-display)!important;font-size:20px!important;letter-spacing:.05em!important;font-weight:600!important;color:var(--sg-text-gold)!important;text-transform:uppercase!important;text-shadow:0 2px 10px rgba(0,0,0,.5)!important}.sg-card-body{all:initial!important;display:flex!important;flex-direction:column!important;gap:16px!important;padding:24px 28px 28px!important;overflow-y:auto!important;max-height:calc(85vh - 80px)!important;font-family:var(--sg-font-body)!important;background-image:radial-gradient(circle at 100% 0%,rgba(212,175,55,.03) 0%,transparent 25%),radial-gradient(circle at 0% 100%,rgba(212,175,55,.02) 0%,transparent 20%)!important}.sg-card-body::-webkit-scrollbar{width:6px!important}.sg-card-body::-webkit-scrollbar-thumb{background:#ffffff1a!important;border-radius:3px!important}.sg-card-body::-webkit-scrollbar-thumb:hover{background:var(--sg-gold-dim)!important}.sg-btn{all:initial!important;display:flex!important;align-items:center!important;justify-content:center!important;background:#ffffff08!important;border:1px solid var(--sg-border-subtle)!important;color:var(--sg-text-muted)!important;border-radius:var(--sg-radius-sm)!important;padding:8px!important;cursor:pointer!important;min-width:36px!important;min-height:36px!important;transition:var(--sg-transition)!important;font-family:var(--sg-font-body)!important}.sg-btn:hover{background:#ffffff14!important;color:var(--sg-text-main)!important;border-color:#fff3!important;transform:translateY(-1px)!important}.sg-btn svg{width:18px!important;height:18px!important;fill:none!important;stroke:currentColor!important}.sg-btn-small{padding:6px!important;min-width:28px!important;min-height:28px!important}.sg-btn-small svg{width:14px!important;height:14px!important}.sg-option{all:initial!important;display:flex!important;align-items:center!important;gap:12px!important;font-size:14px!important;color:var(--sg-text-muted)!important;padding:14px 18px!important;background:#0003!important;border:1px solid var(--sg-border-subtle)!important;border-radius:var(--sg-radius-md)!important;cursor:pointer!important;font-family:var(--sg-font-body)!important;transition:var(--sg-transition)!important}.sg-option:hover{background:#ffffff08!important;border-color:#ffffff26!important;color:var(--sg-text-main)!important}.sg-option input[type=checkbox]{width:18px!important;height:18px!important;cursor:pointer!important;accent-color:var(--sg-gold)!important;margin:0!important;filter:sepia(100%) hue-rotate(5deg) brightness(.9) saturate(1.5)!important}.sg-list{all:initial!important;display:flex!important;flex-direction:column!important;gap:12px!important;font-family:var(--sg-font-body)!important}.sg-item{all:initial!important;display:block!important;background:linear-gradient(90deg,#ffffff05,#fff0)!important;border:1px solid var(--sg-border-subtle)!important;border-left:2px solid transparent!important;border-radius:var(--sg-radius-md)!important;padding:16px 20px!important;cursor:pointer!important;transition:var(--sg-transition)!important;font-family:var(--sg-font-body)!important;animation:sg-fade-up .5s ease-out backwards!important}.sg-item:nth-child(1){animation-delay:.05s!important}.sg-item:nth-child(2){animation-delay:.1s!important}.sg-item:nth-child(3){animation-delay:.15s!important}.sg-item:nth-child(4){animation-delay:.2s!important}.sg-item:hover{background:#ffffff0a!important;border-color:#ffffff1a!important;border-left-color:var(--sg-gold)!important;transform:translate(4px)!important;box-shadow:0 4px 20px #0000004d!important}.sg-item:focus{outline:1px solid var(--sg-gold)!important}.sg-item-top{all:initial!important;display:flex!important;align-items:flex-start!important;justify-content:space-between!important;gap:14px!important;margin-bottom:8px!important;font-family:var(--sg-font-body)!important}.sg-item-title{all:initial!important;display:flex!important;align-items:center!important;flex-wrap:wrap!important;gap:10px!important;font-weight:600!important;font-size:15px!important;color:var(--sg-text-main)!important;line-height:1.4!important;flex:1!important;font-family:var(--sg-font-body)!important}.sg-item-url{all:initial!important;display:block!important;font-size:12px!important;color:#555!important;white-space:nowrap!important;overflow:hidden!important;text-overflow:ellipsis!important;font-family:Consolas,Monaco,monospace!important;opacity:.6!important}.sg-item-sub{all:initial!important;display:flex!important;align-items:center!important;gap:10px!important;font-size:12px!important;color:var(--sg-text-muted)!important;margin-bottom:6px!important;font-family:var(--sg-font-body)!important}.sg-item-size{color:var(--sg-gold-dim)!important}.sg-badge-type{all:initial!important;display:inline-flex!important;align-items:center!important;font-size:10px!important;padding:4px 8px!important;border-radius:4px!important;font-weight:700!important;text-transform:uppercase!important;letter-spacing:.5px!important;white-space:nowrap!important;font-family:var(--sg-font-body)!important;border:1px solid transparent!important;background:#ffffff0d!important;color:#fff!important}.sg-badge-type.master{border-color:#6366f166!important;color:#a5b4fc!important;background:#6366f11a!important}.sg-badge-type.video{border-color:#10b98166!important;color:#6ee7b7!important;background:#10b9811a!important}.sg-badge-type.direct{background:#f59e0b!important;color:#fff!important}.sg-badge-type.live{background:#ef4444!important;color:#fff!important}.sg-badge-type.encrypted{background:#8b5cf6!important;color:#fff!important}.sg-badge-type.analyzing{background:#6b7280!important;color:#fff!important;animation:sg-pulse 1s infinite!important}.sg-badge-type.remote{background:#06b6d4!important;color:#fff!important}.sg-badge-type.error{background:#e74c3c!important;color:#fff!important}.sg-copy-btn{all:initial!important;display:flex!important;align-items:center!important;justify-content:center!important;background:transparent!important;border:1px solid var(--sg-border-subtle)!important;color:var(--sg-gold)!important;border-radius:6px!important;padding:8px!important;cursor:pointer!important;flex-shrink:0!important;transition:var(--sg-transition)!important;font-family:var(--sg-font-body)!important}.sg-copy-btn svg{width:18px!important;height:18px!important;display:block!important}.sg-copy-btn:hover{border-color:var(--sg-gold-dim)!important;color:var(--sg-gold)!important;background:#d4af370d!important}.sg-copy-btn.copied{border-color:var(--sg-success)!important;color:var(--sg-success)!important}.sg-empty{all:initial!important;display:flex!important;flex-direction:column!important;align-items:center!important;padding:60px 40px!important;color:var(--sg-text-muted)!important;font-size:15px!important;text-align:center!important;line-height:1.6!important;font-family:var(--sg-font-body)!important;border:1px dashed var(--sg-border-subtle)!important;border-radius:var(--sg-radius-md)!important}.sg-empty small{display:block!important;margin-top:12px!important;font-size:13px!important;color:#555!important;font-style:italic!important}.sg-toast{all:initial!important;position:fixed!important;right:30px!important;bottom:110px!important;z-index:2147483648!important;display:flex!important;flex-direction:column!important;gap:16px!important;max-width:400px!important;max-height:70vh!important;overflow-y:auto!important;align-items:flex-end!important;font-family:var(--sg-font-body)!important;pointer-events:none!important}.sg-toast>*{pointer-events:auto!important}.sg-progress{all:initial!important;display:flex!important;flex-direction:column!important;background:#0f0f0ff2!important;backdrop-filter:blur(10px)!important;color:var(--sg-text-main)!important;border:1px solid var(--sg-border-gold)!important;border-left:3px solid var(--sg-gold)!important;border-radius:var(--sg-radius-md)!important;padding:16px 20px!important;min-width:340px!important;box-shadow:0 10px 40px #0009!important;font-family:var(--sg-font-body)!important;animation:sg-fade-up .4s cubic-bezier(.18,.89,.32,1.28)!important}.sg-progress-row{all:initial!important;display:flex!important;align-items:center!important;justify-content:space-between!important;gap:12px!important;margin-bottom:12px!important;font-family:var(--sg-font-body)!important}.sg-progress-name{all:initial!important;font-weight:600!important;font-size:14px!important;white-space:nowrap!important;overflow:hidden!important;text-overflow:ellipsis!important;max-width:220px!important;color:var(--sg-text-main)!important;font-family:var(--sg-font-body)!important;letter-spacing:.01em!important}.sg-progress-ctrls{all:initial!important;display:flex!important;gap:6px!important;margin-left:auto!important;font-family:system-ui,sans-serif!important}.sg-progress-bar{all:initial!important;display:block!important;height:6px!important;background:#ffffff1a!important;border-radius:3px!important;overflow:hidden!important;margin-bottom:12px!important}.sg-progress-fill{display:block!important;height:100%!important;width:0;min-width:0!important;background-color:var(--sg-gold)!important;background:linear-gradient(90deg,var(--sg-gold),var(--sg-gold-bright))!important;box-shadow:0 0 10px var(--sg-gold-glow)!important;transition:width .2s linear!important}.sg-progress-status{all:initial!important;display:flex!important;justify-content:space-between!important;font-size:12px!important;font-family:var(--sg-font-body)!important}.sg-progress-status span:first-child{color:var(--sg-text-muted)!important;font-variant-numeric:tabular-nums!important}.sg-progress-status span:last-child{color:#e0e0e0!important}.sg-progress.paused .sg-progress-fill{background:#f59e0b!important}.sg-progress.minimized{padding:10px 14px!important;min-width:auto!important;background:#000!important;border-left-width:1px!important}.sg-progress.minimized .sg-progress-bar,.sg-progress.minimized .sg-progress-status,.sg-progress.minimized .sg-progress-name{display:none!important}.sg-progress.minimized .sg-progress-row{margin-bottom:0!important;justify-content:center!important}.sg-progress.minimized .sg-progress-ctrls{margin:0!important;gap:0!important}.sg-progress.minimized .sg-progress-ctrls>*:not(.btn-minimize){display:none!important}@media(max-width:640px){.sg-fab{right:20px!important;bottom:20px!important}.sg-toast{left:16px!important;right:16px!important;bottom:80px!important;max-width:none!important;align-items:stretch!important}.sg-progress{min-width:0!important;width:100%!important}.sg-card{max-height:90vh!important;width:100%!important;margin:8px!important;border-radius:10px!important}.sg-card-body{max-height:calc(90vh - 70px)!important}}',oi=ai,ht={download:`<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    <path d="M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"/>
    <path d="M7 10l5 5 5-5"/>
    <path d="M12 15V3"/>
  </svg>`,close:`<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    <path d="M18 6L6 18M6 6l12 12"/>
  </svg>`,copy:`<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
    <rect x="8" y="8" width="12" height="12" rx="2"/>
    <path d="M16 8V6a2 2 0 00-2-2H6a2 2 0 00-2 2v8a2 2 0 002 2h2"/>
  </svg>`,check:`<svg viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
    <path d="M20 6L9 17l-5-5"/>
  </svg>`,pause:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <rect x="6" y="4" width="4" height="16"/>
    <rect x="14" y="4" width="4" height="16"/>
  </svg>`,play:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <polygon points="5 3 19 12 5 21 5 3"/>
  </svg>`,cancel:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <circle cx="12" cy="12" r="10"/>
    <path d="M15 9l-6 6M9 9l6 6"/>
  </svg>`,minimize:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <path d="M19 9l-7 7-7-7"/>
  </svg>`,maximize:`<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
    <path d="M5 15l7-7 7 7"/>
  </svg>`},ye=(...e)=>e.filter(Boolean).join(" ");function B(e,t,n){const r=document.createElement(e);if(t)for(const[c,m]of Object.entries(t))m==null||m===false||r.setAttribute(c,m===true?"":String(m));if(n)if(typeof n=="string")r.innerHTML=n;else for(const c of n)r.append(typeof c=="string"?document.createTextNode(c):c);return r}async function si(e,t){try{await navigator.clipboard.writeText(e);}catch{const r=Object.assign(document.createElement("textarea"),{value:e,style:"position:fixed;opacity:0;pointer-events:none"}),c=t.getRootNode();(c instanceof ShadowRoot||c instanceof Document?c:document.body).appendChild(r),r.select();const h=document.execCommand("copy");if(r.remove(),!h)return  false}const n=t.innerHTML;return t.innerHTML=ht.check,t.classList.add("copied"),setTimeout(()=>{t.innerHTML=n,t.classList.remove("copied");},1200),true}let St=null,Ke=null,jt=null;function li(e,t,n){St||(St=B("button",{class:"sg-fab",type:"button"}),Ke=B("span",{class:"sg-fab-icon"},ht.download),jt=B("span",{class:"sg-badge"}),St.append(Ke,jt),St.addEventListener("click",r=>{r.preventDefault(),r.stopPropagation(),n();}),e.appendChild(St)),St.className=ye("sg-fab",t.show&&"show",t.busy&&"busy",t.idle&&"idle"),St.disabled=t.busy,St.title=`Download media (${t.count})`,jt&&(jt.className=ye("sg-badge",t.count>0&&"show"),jt.textContent=t.count>99?"99+":String(t.count));}function ci(e,t,n,r,c,m,h,b,T){if(e.innerHTML="",!t)return;const A=B("div",{class:"sg-modal show"});A.addEventListener("click",I=>I.target===A&&h());const L=B("div",{class:"sg-card",role:"dialog","aria-modal":"true"}),O=B("div",{class:"sg-card-head"});O.append(Object.assign(B("div",{class:"sg-card-title"}),{textContent:n}),ui(ht.close,"Close (Esc)",h)),L.appendChild(O);const k=B("div",{class:"sg-card-body"});if(c&&r.some(I=>I.size!=null)){const I=B("label",{class:"sg-option"}),S=B("input",{type:"checkbox",checked:m||null});S.addEventListener("change",()=>T(S.checked)),I.append(S," Exclude small (< 1MB)"),k.appendChild(I);}const v=B("div",{class:"sg-list"});if(r.length===0){const I=B("div",{class:"sg-empty"});I.innerHTML="No media detected.<br><small>Play a video to detect streams.</small>",v.appendChild(I);}else r.forEach(I=>v.appendChild(di(I,b)));k.appendChild(v),L.appendChild(k),A.appendChild(L),e.appendChild(A);}function ui(e,t,n){const r=B("button",{class:"sg-btn",title:t,type:"button"},e);return r.addEventListener("click",c=>{c.preventDefault(),n();}),r}function di(e,t){const n=B("div",{class:"sg-item",role:"button",tabindex:"0"}),r=B("div",{class:"sg-item-top"}),c=B("div",{class:"sg-item-title"});c.appendChild(Object.assign(B("span"),{textContent:e.label})),fi(e).forEach(b=>c.appendChild(b)),r.appendChild(c),e.size&&r.appendChild(Object.assign(B("span",{class:"sg-item-size"}),{textContent:Ht(e.size)}));const m=B("button",{class:"sg-copy-btn",title:"Copy URL",type:"button"},ht.copy);m.addEventListener("click",b=>{b.stopPropagation(),si(e.url,m);}),r.appendChild(m),n.appendChild(r),e.sublabel&&n.appendChild(Object.assign(B("div",{class:"sg-item-sub"}),{textContent:e.sublabel}));const h=B("div",{class:"sg-item-url",title:e.url});return h.textContent=e.url.length>60?e.url.slice(0,60)+"…":e.url,n.appendChild(h),n.addEventListener("click",b=>{b.target.closest(".sg-copy-btn")||t(e);}),n.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),t(e));}),n}function fi(e){const t=[],n=(r,c)=>{const m=B("span",{class:`sg-badge-type ${c}`});m.textContent=r,t.push(m);};return e.kind==="hls"?(e.hlsType==="error"||e.hlsType==="invalid"?n(e.hlsType==="error"?"Error":"Invalid","error"):e.hlsType==="master"?n("Master","master"):e.hlsType==="media"?n("Video","video"):e.enriching?n("...","analyzing"):n("HLS","video"),e.isLive&&n("Live","live"),e.encrypted&&n("🔒","encrypted")):e.kind==="video"?n("Direct","direct"):e.kind==="variant"&&n("Quality","video"),e.isRemote&&n("iFrame","remote"),t}class hi{constructor(t,n,r,c=0){this.container=t,this.title=n,this.src=r,this.status=c?`${c} segments`:"Starting...",this.el=B("div",{class:"sg-progress",id:`sg-progress-${we()}`});const m=B("div",{class:"sg-progress-row"});m.appendChild(Object.assign(B("div",{class:"sg-progress-name",title:r}),{textContent:n}));const h=B("div",{class:"sg-progress-ctrls"});this.minBtn=B("button",{class:"sg-btn sg-btn-sm btn-minimize",title:"Minimize",type:"button"},ht.minimize),this.minBtn.addEventListener("click",()=>this.toggleMinimize()),h.appendChild(this.minBtn);const b=B("button",{class:"sg-btn sg-btn-sm",title:"Cancel",type:"button"},ht.cancel);b.addEventListener("click",()=>this.onCancelFn?.()),h.appendChild(b),m.appendChild(h),this.el.appendChild(m);const T=B("div",{class:"sg-progress-bar"});this.fillEl=B("div",{class:"sg-progress-fill"}),T.appendChild(this.fillEl),this.el.appendChild(T);const A=B("div",{class:"sg-progress-status"});this.statusEl=B("span"),this.statusEl.textContent=this.status,this.percentEl=B("span"),this.percentEl.textContent="0%",A.append(this.statusEl,this.percentEl),this.el.appendChild(A),t.appendChild(this.el);}el;fillEl;statusEl;percentEl;pauseBtn=null;minBtn;minimized=false;paused=false;percent=0;status;onStop;onCancelFn;toggleMinimize(){this.minimized=!this.minimized,this.minBtn.innerHTML=this.minimized?ht.maximize:ht.minimize,this.minBtn.title=this.minimized?"Expand":"Minimize",this.updateClass();}updateClass(){this.el.className=ye("sg-progress",this.minimized&&"minimized",this.paused&&"paused");}update(t,n=""){this.percent=Math.max(0,Math.min(100,t)),n&&(this.status=n),this.fillEl.style.setProperty("width",`${this.percent}%`,"important"),this.statusEl.textContent=this.status,this.percentEl.textContent=`${Math.floor(this.percent)}%`;}done(t=true,n){this.fillEl.style.width="100%",this.fillEl.classList.add(t?"success":"error"),this.statusEl.textContent=n||(t?"Complete ✓":"Failed ✗"),this.percentEl.textContent="100%",setTimeout(()=>this.remove(),2500);}remove(){this.el.remove();}setOnStop(t){this.onStop=t,!this.pauseBtn&&(this.pauseBtn=B("button",{class:"sg-btn sg-btn-sm",title:"Pause",type:"button"},ht.pause),this.pauseBtn.addEventListener("click",()=>{if(!this.onStop)return;const n=this.onStop();this.paused=n==="paused",this.pauseBtn.innerHTML=this.paused?ht.play:ht.pause,this.pauseBtn.title=this.paused?"Resume":"Pause",this.updateClass();}),this.minBtn.before(this.pauseBtn));}setOnCancel(t){this.onCancelFn=t;}}function pi(e,t,n,r=0){return new hi(e,t,n,r)}let ft=false,wt=null,_t=null,Vt=null;const Dt={show:false,busy:false,idle:false,count:0},dt={show:false,title:"Select Media",items:[]};let Te=null,Rt=null,wn=null,An=null;function Ae(){if(!tt.IS_TOP||ft)return;if(!document.body){const r=document.readyState==="loading"?"DOMContentLoaded":"load";window.addEventListener(r,()=>Ae(),{once:true});return}const e=document.createElement("div");e.id="sg-host",Object.assign(e.style,{position:"fixed",top:"0",left:"0",width:"0",height:"0",zIndex:"2147483647",pointerEvents:"none"});const t=e.attachShadow({mode:"open"}),n=document.createElement("style");n.textContent=oi,t.append(n),wt=document.createElement("div"),wt.id="sg-fab-container",wt.style.pointerEvents="auto",_t=document.createElement("div"),_t.id="sg-modal-container",_t.style.pointerEvents="auto",Vt=document.createElement("div"),Vt.id="sg-toast-container",Vt.className="sg-toast",t.append(wt,_t,Vt),document.documentElement.append(e),wt.addEventListener("mouseenter",Re),wt.addEventListener("mouseleave",Ne),document.addEventListener("keydown",r=>r.key==="Escape"&&dt.show&&Pe()),ft=true,mt();}function $t(){return tt.IS_TOP?(ft||Ae(),ft):false}function mt(){if(!ft||!wt||!_t)return;li(wt,Dt,Nn);const e=dt.show?mi():[];ci(_t,dt.show,dt.title,e,Rt?.filterable??true,nt.excludeSmall,Pe,vi,Ei);}function ie(){tt.IS_TOP&&(Dt.show=true,Dt.count=nt.validCount,$t()&&(mt(),Ne()));}function be(e){Dt.busy=e,ft&&mt();}function qt(){Dt.count=nt.validCount,ft&&mt();}function Ne(){Re(),Te=setTimeout(()=>{Dt.idle=true,ft&&mt();},tt.UI_IDLE_MS);}function Re(){Dt.idle=false,Te&&clearTimeout(Te),ft&&mt();}function mi(){const e=dt.items.length>0?dt.items:nt.getFilteredItems();return nt.excludeSmall?e.filter(t=>t.size==null||t.size>=tt.SMALL_BYTES):e}function gi(e="Select Media",t){$t()&&(dt.show=true,dt.title=e,dt.items=t??[],mt());}function Pe(){dt.show=false,dt.items=[],ft&&mt(),Rt&&(Rt.resolve(null),Rt=null);}function vi(e){Pe(),Rt?(Rt.resolve(e),Rt=null):An?.(e);}function Ei(e){nt.setExcludeSmall(e),mt();}function Nn(){ft&&(Re(),Ne(),wn?.());}function Le(e,{title:t="Select Media",filterable:n=true}={}){return $t()?new Promise(r=>{Rt={resolve:r,title:t,filterable:n},gi(t,e);}):Promise.resolve(null)}function Rn(e,t,n=0){return !$t()||!Vt?{update(){},done(){},remove(){},setOnStop(){},setOnCancel(){}}:pi(Vt,e,t,n)}function yi(){tt.IS_TOP&&(GM_registerMenuCommand("Show Download Panel",()=>{$t(),ie(),Nn();}),GM_registerMenuCommand("Clear Cache",()=>{nt.clear(),qt(),GM_notification({text:"Cache cleared",title:"StreamGrabber",timeout:2e3});}));}function Ti(e){e.onFabClick&&(wn=e.onFabClick),e.onItemSelected&&(An=e.onItemSelected);}function We(){tt.IS_TOP&&(qt(),ft&&dt.show&&mt());}class bi{id;bus;onStopFn;onCancelFn;constructor(t,n){this.id=we(),this.bus=ct.get(),this.bus.sendToTop("SG_PROGRESS_START",{id:this.id,title:t,src:n}),this.handleControl=this.handleControl.bind(this),this.bus.on("SG_CMD_CONTROL",this.handleControl);}handleControl(t){if(t.id!==this.id)return;const n=t.action;n==="stop"&&this.onStopFn?this.onStopFn():n==="cancel"&&this.onCancelFn&&this.onCancelFn();}update(t,n){this.bus.sendToTop("SG_PROGRESS_UPDATE",{id:this.id,p:t,txt:n||""});}done(t=true,n=""){this.bus.sendToTop("SG_PROGRESS_DONE",{id:this.id,ok:t,msg:n}),this.cleanup();}remove(){this.cleanup();}setOnStop(t){this.onStopFn=t;}setOnCancel(t){this.onCancelFn=t;}cleanup(){this.bus.off("SG_CMD_CONTROL",this.handleControl);}}const Ut=new Map;function Ii(){console.log("[SG] StreamGrabber v2.0.0 initializing...",{isTop:tt.IS_TOP,readyState:document.readyState,href:location.href.slice(0,100)}),Sr(e=>nt.getItem(e)),Ti({onFabClick:Si,onItemSelected:Pn}),tt.IS_TOP&&(Ae(),yi()),Cr(),Nr({onRemoteItem:()=>{ie(),qt();},onProgressStart:(e,t,n,r)=>{if(!Ut.has(e))try{const c=Rn(t,n);c.setOnStop(()=>(ct.get().send("SG_CMD_CONTROL",{id:e,action:"stop"},r),"paused")),c.setOnCancel(()=>{ct.get().send("SG_CMD_CONTROL",{id:e,action:"cancel"},r),c.remove(),Ut.delete(e);}),Ut.set(e,c);}catch(c){console.error("[SG] Failed to create remote progress card:",c);}},onProgressUpdate:(e,t,n)=>{Ut.get(e)?.update(t,n);},onProgressDone:(e,t,n)=>{const r=Ut.get(e);r&&(r.done(t,n),setTimeout(()=>Ut.delete(e),2500));},onPick:(e,t,n,r)=>{Le(t,{title:n,filterable:true}).then(c=>{ct.get().send("SG_CMD_PICK_RESULT",{id:e,item:c},r);});},onDownloadCommand:wi}),Qn(e=>{tt.IS_TOP?(console.log("[SG] Detected:",e.kind,e.url.slice(0,60)),ie(),qt(),e.kind==="hls"&&vn(e.url)):(console.log("[SG] [iframe] Forwarding detection:",e.kind,e.url.slice(0,60)),Pr(e));}),Ir(()=>{We();}),nt.events.itemAdded.subscribe(()=>{ie(),qt();}),nt.events.updated.subscribe(()=>{We();}),Zn(),console.log("[SG] Initialization complete",{isTop:tt.IS_TOP});}async function Si(){be(true);try{const e=nt.getFilteredItems();if(e.length===0){alert("No media detected yet. Try playing a video first.");return}const t=await Le(e,{title:"Select Media",filterable:!0});if(!t)return;await Pn(t);}catch(e){ln(e);}finally{be(false);}}async function Pn(e){try{await ii(e,{createCard:Rn,pickVariant:t=>Le(t,{title:"Select Quality",filterable:!0}),setBusy:be});}catch(t){ln(t);}}async function wi(e,t,n){console.log("[SG] [iframe] Received download command:",{url:e,kind:t});try{const r=(c,m)=>new bi(c,m);t==="hls"?await re(e,n,{createCard:r,pickVariant:async c=>new Promise(m=>{const h=we();Lr(h,m),ct.get().sendToTop("SG_CMD_PICK",{id:h,items:c,title:"Select Quality"});}),setBusy:()=>{}}):t==="video"&&await Ee(e,{createCard:r,pickVariant:async()=>null,setBusy:()=>{}});}catch(r){console.error("[SG] [iframe] Download error:",r);}}Ii();

})();