Lightweight HLS/Video downloader. Pause/Resume. AES-128. fMP4. Mobile + Desktop.
// ==UserScript==
// @name StreamGrabber
// @namespace https://github.com/streamgrabber-lite
// @version 2.1.3
// @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_info
// @grant GM_notification
// @grant GM_registerMenuCommand
// @grant GM_setValue
// @grant GM_xmlhttpRequest
// @grant unsafeWindow
// @run-at document-start
// ==/UserScript==
(function () {
'use strict';
const Z={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},ie={TEXT_MAX:256,DB_MAX:120,CLEAR_MS:12e4},Ve={EXCLUDE_SMALL:"sg_exclude_small"},ut=new Map;function Ge(e){const t=[];for(const[r,n]of ut)e(r,n)&&(ut.delete(r),t.push(r));return t}class Be{listeners=new Set;subscribe(t){return this.listeners.add(t),()=>this.listeners.delete(t)}dispatch(t){for(const r of this.listeners)try{r(t);}catch(n){console.error("[SG] Event dispatch error:",n);}}}class Or{items=new Map;watchedVideos=new WeakSet;excludeSmall;_validCount=0;_validCountDirty=true;events={itemAdded:new Be,updated:new Be};constructor(){this.excludeSmall=GM_getValue(Ve.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),this.invalidateCount(),this.enforceLimit(),this.events.itemAdded.dispatch(t),this.events.updated.dispatch(),true)}enforceLimit(){for(;this.items.size>ie.DB_MAX;){const t=this.items.keys().next().value;if(t===void 0)break;this.items.get(t),this.items.delete(t);}this.invalidateCount();}get validCount(){if(this._validCountDirty){let t=0;for(const r of this.items.values())r.hlsType!=="invalid"&&r.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(r=>r.size==null||r.size>=Z.SMALL_BYTES):t}setExcludeSmall(t){this.excludeSmall=t,GM_setValue(Ve.EXCLUDE_SMALL,t);}clear(){this.items.clear(),this.items.clear(),Ge(()=>true),this.invalidateCount();}trim(){this.enforceLimit();const t=Date.now(),r=Ge((n,c)=>{const m=t-(c.ts||0);return !!(c.revoked&&m>ie.CLEAR_MS)});for(const n of r)this.items.has(n)&&(this.items.delete(n),this.invalidateCount());}}const et=new Or;Z.IS_TOP&&(setInterval(()=>et.trim(),ie.CLEAR_MS),window.addEventListener("pagehide",()=>et.trim()),window.addEventListener("beforeunload",()=>et.trim()));const Et={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},Pr=e=>typeof e=="string"&&Et.http.test(e),Ht=e=>typeof e=="string"&&Et.blob.test(e),Cr=e=>Et.m3u8.test(e||""),Dr=e=>Et.video.test(e||""),Xr=e=>Et.segment.test(e||""),xr=e=>Et.m3u8Type.test(e||""),Mr=e=>Et.videoType.test(e||"")||Et.videoTypeAlt.test(e||"");function ee(e,t){try{return new URL(e,t).href}catch{return e}}const je=["B","KB","MB","GB","TB"];function qt(e){if(e==null)return "";let t=0,r=e;for(;r>=1024&&t<je.length-1;)r/=1024,t++;const n=r<10&&t>0?1:0;return `${r.toFixed(n)} ${je[t]}`}function kr(e){if(!e||e<=0)return null;const t=Math.floor(e/3600),r=Math.floor(e%3600/60),n=Math.floor(e%60),c=m=>String(m).padStart(2,"0");return t>0?`${t}:${c(r)}:${c(n)}`:`${r}:${c(n)}`}document.createElement("div");function Le(){return Math.random().toString(36).slice(2)}const Ur=["url","kind","label","sublabel","size","type","origin","enriched","enriching","hlsType","isLive","encrypted","duration","segCount","resolution","isVod","isFmp4","variantCount","variants","bestVariant","variant"];function _r(e){const t={};for(const r of Ur)e[r]!==void 0&&(t[r]=e[r]);return t}function ve(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 Fr(e,t){if(!e.has(t))return;const r=e.get(t);return e.delete(t),e.set(t,r),r}function Yr(e,t,r,n){if(e.has(t)&&e.delete(t),e.set(t,r),typeof n=="number"&&isFinite(n))for(;e.size>n;){const c=e.keys().next().value;c!==void 0&&e.delete(c);}}function nr(e,t,r,n,c){const m=Fr(e,r);if(m!==void 0)return Promise.resolve(m);if(t.has(r))return t.get(r);const d=(async()=>{try{const y=await n();return Yr(e,r,y,c),y}finally{t.delete(r);}})();return t.set(r,d),d}function Vr(e){return (e||"video").replace(/[\\/:*?"<>|]/g,"_").slice(0,120).trim()||"video"}const Gr={webm:"webm",matroska:"mkv",mkv:"mkv",quicktime:"mov",mov:"mov",mp2t:"ts",mpegts:"ts",ogg:"ogg",mp4:"mp4"};function Br(e){const t=e.toLowerCase();for(const[r,n]of Object.entries(Gr))if(t.includes(r))return n;return "mp4"}function ir(e,t){const r=/(?:\.([a-z0-9]+))([?#]|$)/i.exec(e||"");return r?r[1].toLowerCase():t?Br(t):"mp4"}function ar(e){const t=Vr(e.title||document.title),r=e.quality?`_${e.quality}`:"",n=e.ext||"mp4";return `${t}${r}.${n}`}function or(e){return [...e].sort((t,r)=>(r.h||0)-(t.h||0)||(r.avg||r.peak||0)-(t.avg||t.peak||0))}function sr(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 r=kr(e.duration);r&&t.push(r);}return e.size!=null&&t.push(`~${qt(e.size)}`),e.extra&&t.push(...e.extra),t.length>0?t.join(" • "):"Video Stream"}function jr(e,t){return `${e} segments • ${t?"fMP4":"TS"}`}function lr(e){if(!e)return null;const t=Et.resolutionCombined.exec(e);if(t){if(t[1]){const n=parseInt(t[1],10),c=t[2],m=t[3];if(c==="x"&&m)return `${n}x${m}`;if(n>=144&&n<=4320)return `${n}p`}const r=t[4]||t[5]||t[6]||t[7];if(r){const n=parseInt(r,10);if(n>=144&&n<=4320)return `${n}p`}}return null}function Oe(e,t){if(!Ht(e))return null;const r=t.get(e);return r?(r.ts=Date.now(),r):null}function zr(e,t){if(!t)return e;const r=ve(t);return r?e.slice(r.start,r.end==null?e.size:r.end+1):e}function Hr(e,t={}){GM_notification({text:e,title:t.title??"StreamGrabber",timeout:t.timeout??3e3,onclick:t.onclick});}function le(e){Hr(`Download complete: ${e}`);}function qr(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}function cr(e,t){const r=qr(e);alert(r);}let Ee=null;const re=[],ae=new Set;setInterval(()=>{ae.size>0&&ae.clear();},5e3);function $r(e){if(Ee=e,re.length>0){const t=[...re];re.length=0,t.forEach(({url:r,metadata:n})=>e(r,n));}}function Pe(e){return typeof e!="string"?false:/^\s*#EXTM3U/i.test(e)}function Nt(e,t){Ee?Ee(e,t):re.push({url:e,metadata:t});}function Kr(){const e=URL.createObjectURL;URL.createObjectURL=function(t){const r=e.call(this,t);try{const n=Date.now();if(t instanceof Blob){const c=t.type||"",m={blob:t,type:c,size:t.size,kind:"other",ts:n};xr(c)?(m.kind="m3u8",ut.set(r,m),Nt(r)):Mr(c)?(m.kind="video",ut.set(r,m),Nt(r)):/octet-stream|text\/plain|^$/.test(c)&&t.size>0&&t.size<5*1024*1024&&t.slice(0,Math.min(2048,t.size)).text().then(y=>{Pe(y)&&(ae.has(r)||(m.kind="m3u8",ut.set(r,m),Nt(r)));}).catch(()=>{});}}catch(n){console.error("[SG] createObjectURL hook error:",n);}return r};}function Wr(){const e=URL.revokeObjectURL;URL.revokeObjectURL=function(t){try{const r=ut.get(t);r?(r.revoked=!0,r.ts=Date.now()):ae.add(t);}catch{}return e.call(this,t)};}function Qr(){const e=window.fetch,t=window.Response.prototype.text;typeof e=="function"&&(window.Response.prototype.text=function(){return new Promise((r,n)=>{t.call(this).then(c=>{r(c);try{Pe(c)&&Nt(this.url);}catch(m){console.error("[SG] Detection error in Response.text:",m);}}).catch(n);})},window.fetch=function(...r){try{const n=r[0],c=typeof n=="string"?n:n instanceof Request?n.url:n.href;c&&Nt(c);}catch{}return e.apply(this,r)});}function Zr(){const e=XMLHttpRequest.prototype.open;XMLHttpRequest.prototype.open=function(t,r,...n){try{const m=typeof r=="string"?r:r?.href;m&&Nt(m);}catch{}const c=e.call(this,t,r,...n);return this.addEventListener("load",()=>{try{if(!this.responseType||this.responseType==="text"){const m=this.responseText,d=typeof r=="string"?r:r?.href;d&&Pe(m)&&Nt(d);}}catch{}}),c};}function Jr(){try{new PerformanceObserver(t=>{for(const r of t.getEntries())"name"in r&&typeof r.name=="string"&&Nt(r.name);}).observe({entryTypes:["resource"]});}catch{}}let ze=false;function tn(){ze||(ze=true,Kr(),Wr(),Qr(),Zr(),Jr());}let ur=()=>{};function en(e){ur=e;}function rn(e){if(et.watchedVideos.has(e))return;et.watchedVideos.add(e);const t=()=>{[e.currentSrc||e.src,...Array.from(e.querySelectorAll("source")).map(c=>c.src)].filter(Boolean).forEach(ur);};["loadstart","loadedmetadata","canplay"].forEach(n=>e.addEventListener(n,t)),t();}function ye(){document.querySelectorAll("video").forEach(e=>rn(e));}let de=null,Jt;function He(){de||(de=new MutationObserver(()=>{Jt&&clearTimeout(Jt),Jt=window.setTimeout(()=>{ye(),Jt=void 0;},1e3);}),de.observe(document.documentElement,{childList:true,subtree:true}));}const fe=new Set;function qe(e,t){fe.has(e)||(fe.add(e),setTimeout(()=>{fe.delete(e),t(e);},Z.DETECT_DEBOUNCE));}function nn(e,t,r={}){const{size:n=null,type:c=null}=r;let m;if(t==="hls"){const d=lr(e);m=d?`${d} • Analyzing...`:"Analyzing...";}else m=ir(e,c).toUpperCase();return {url:e,kind:t,label:m,sublabel:null,size:n,type:c,origin:document.location.origin,enriched:false,enriching:false,hlsType:null,isLive:false,encrypted:false,_enrichPromise:null}}let dr=()=>{};function an(e){dr=e;}function $e(e){try{if(!e||!Pr(e)&&!Ht(e)||Xr(e))return;const t=e.toLowerCase();if(t.includes("ping.gif")||t.includes("jwpltx.com")||t.includes("doubleclick")||t.includes("analytics")||t.includes("/stats/")||et.hasItem(e))return;let r=null,n=null;if(Ht(e)){const T=ut.get(e);if(T&&(r=T.size,n=T.type),r!=null&&r<512*1024&&T?.kind!=="m3u8")return}const c=Cr(e)||Ht(e)&&ut.get(e)?.kind==="m3u8",m=Dr(e)||Ht(e)&&ut.get(e)?.kind==="video",d=c?"hls":m?"video":null;if(!d)return;const y=nn(e,d,{size:r,type:n});et.addItem(y)&&dr(y);}catch(t){console.error("[SG] processUrl error:",t);}}let Ke=false;function on(){Ke||(Ke=true,$r(e=>qe(e,$e)),en(e=>qe(e,$e)),tn(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{ye(),He();}):(ye(),He()));}function sn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var he={exports:{}},We;function ln(){return We||(We=1,(function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=false));function c(T,A,O){this.fn=T,this.context=A,this.once=O||false;}function m(T,A,O,P,k){if(typeof O!="function")throw new TypeError("The listener must be a function");var v=new c(O,P||T,k),w=r?r+A:A;return T._events[w]?T._events[w].fn?T._events[w]=[T._events[w],v]:T._events[w].push(v):(T._events[w]=v,T._eventsCount++),T}function d(T,A){--T._eventsCount===0?T._events=new n:delete T._events[A];}function y(){this._events=new n,this._eventsCount=0;}y.prototype.eventNames=function(){var A=[],O,P;if(this._eventsCount===0)return A;for(P in O=this._events)t.call(O,P)&&A.push(r?P.slice(1):P);return Object.getOwnPropertySymbols?A.concat(Object.getOwnPropertySymbols(O)):A},y.prototype.listeners=function(A){var O=r?r+A:A,P=this._events[O];if(!P)return [];if(P.fn)return [P.fn];for(var k=0,v=P.length,w=new Array(v);k<v;k++)w[k]=P[k].fn;return w},y.prototype.listenerCount=function(A){var O=r?r+A:A,P=this._events[O];return P?P.fn?1:P.length:0},y.prototype.emit=function(A,O,P,k,v,w){var S=r?r+A:A;if(!this._events[S])return false;var f=this._events[S],b=arguments.length,p,x;if(f.fn){switch(f.once&&this.removeListener(A,f.fn,void 0,true),b){case 1:return f.fn.call(f.context),true;case 2:return f.fn.call(f.context,O),true;case 3:return f.fn.call(f.context,O,P),true;case 4:return f.fn.call(f.context,O,P,k),true;case 5:return f.fn.call(f.context,O,P,k,v),true;case 6:return f.fn.call(f.context,O,P,k,v,w),true}for(x=1,p=new Array(b-1);x<b;x++)p[x-1]=arguments[x];f.fn.apply(f.context,p);}else {var Y=f.length,G;for(x=0;x<Y;x++)switch(f[x].once&&this.removeListener(A,f[x].fn,void 0,true),b){case 1:f[x].fn.call(f[x].context);break;case 2:f[x].fn.call(f[x].context,O);break;case 3:f[x].fn.call(f[x].context,O,P);break;case 4:f[x].fn.call(f[x].context,O,P,k);break;default:if(!p)for(G=1,p=new Array(b-1);G<b;G++)p[G-1]=arguments[G];f[x].fn.apply(f[x].context,p);}}return true},y.prototype.on=function(A,O,P){return m(this,A,O,P,false)},y.prototype.once=function(A,O,P){return m(this,A,O,P,true)},y.prototype.removeListener=function(A,O,P,k){var v=r?r+A:A;if(!this._events[v])return this;if(!O)return d(this,v),this;var w=this._events[v];if(w.fn)w.fn===O&&(!k||w.once)&&(!P||w.context===P)&&d(this,v);else {for(var S=0,f=[],b=w.length;S<b;S++)(w[S].fn!==O||k&&!w[S].once||P&&w[S].context!==P)&&f.push(w[S]);f.length?this._events[v]=f.length===1?f[0]:f:d(this,v);}return this},y.prototype.removeAllListeners=function(A){var O;return A?(O=r?r+A:A,this._events[O]&&d(this,O)):(this._events=new n,this._eventsCount=0),this},y.prototype.off=y.prototype.removeListener,y.prototype.addListener=y.prototype.on,y.prefixed=r,y.EventEmitter=y,e.exports=y;})(he)),he.exports}var cn=ln();const un=sn(cn);class Ce extends Error{name="TimeoutError";constructor(t,r){super(t,r),Error.captureStackTrace?.(this,Ce);}}const Qe=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function dn(e,t){const{milliseconds:r,fallback:n,message:c,customTimers:m={setTimeout,clearTimeout},signal:d}=t;let y,T;const O=new Promise((P,k)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(d?.aborted){k(Qe(d));return}if(d&&(T=()=>{k(Qe(d));},d.addEventListener("abort",T,{once:true})),e.then(P,k),r===Number.POSITIVE_INFINITY)return;const v=new Ce;y=m.setTimeout.call(void 0,()=>{if(n){try{P(n());}catch(w){k(w);}return}typeof e.cancel=="function"&&e.cancel(),c===false?P():c instanceof Error?k(c):(v.message=c??`Promise timed out after ${r} milliseconds`,k(v));},r);}).finally(()=>{O.clear(),T&&d&&d.removeEventListener("abort",T);});return O.clear=()=>{m.clearTimeout.call(void 0,y),y=void 0;},O}function fn(e,t,r){let n=0,c=e.length;for(;c>0;){const m=Math.trunc(c/2);let d=n+m;r(e[d],t)<=0?(n=++d,c-=m+1):c=m;}return n}class hn{#r=[];enqueue(t,r){const{priority:n=0,id:c}=r??{},m={priority:n,id:c,run:t};if(this.size===0||this.#r[this.size-1].priority>=n){this.#r.push(m);return}const d=fn(this.#r,m,(y,T)=>T.priority-y.priority);this.#r.splice(d,0,m);}setPriority(t,r){const n=this.#r.findIndex(m=>m.id===t);if(n===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);const[c]=this.#r.splice(n,1);this.enqueue(c.run,{priority:r,id:t});}dequeue(){return this.#r.shift()?.run}filter(t){return this.#r.filter(r=>r.priority===t.priority).map(r=>r.run)}get size(){return this.#r.length}}class fr extends un{#r;#o;#s=0;#h;#m=false;#E=false;#l;#N=0;#y=0;#c;#u;#a;#i=[];#n=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:hn,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.#r=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.#n<this.#i.length;){const n=this.#i[this.#n];if(n!==void 0&&t-n>=this.#l)this.#n++;else break}(this.#n>100&&this.#n>this.#i.length/2||this.#n===this.#i.length)&&(this.#i=this.#i.slice(this.#n),this.#n=0);}#X(t){this.#a?this.#i.push(t):this.#s++;}#x(){this.#a?this.#i.length>this.#n&&this.#i.pop():this.#s>0&&this.#s--;}#b(){return this.#i.length-this.#n}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.#S(),this.emit("next");}#_(){this.#u=void 0,this.#P(),this.#O();}#F(t){if(this.#a){if(this.#T(t),this.#b()>=this.#h){const n=this.#i[this.#n],c=this.#l-(t-n);return this.#I(c),true}return false}if(this.#c===void 0){const r=this.#N-t;if(r<0){if(this.#y>0){const n=t-this.#y;if(n<this.#l)return this.#I(this.#l-n),true}this.#s=this.#r?this.#e:0;}else return this.#I(r),true}return false}#I(t){this.#u===void 0&&(this.#u=setTimeout(()=>{this.#_();},t));}#w(){this.#c&&(clearInterval(this.#c),this.#c=void 0);}#L(){this.#u&&(clearTimeout(this.#u),this.#u=void 0);}#S(){if(this.#t.size===0){if(this.#w(),this.emit("empty"),this.#e===0){if(this.#L(),this.#a&&this.#n>0){const r=Date.now();this.#T(r);}this.emit("idle");}return false}let t=false;if(!this.#d){const r=Date.now(),n=!this.#F(r);if(this.#M&&this.#k){const c=this.#t.dequeue();this.#o||(this.#X(r),this.#p()),this.emit("active"),c(),n&&this.#O(),t=true;}}return t}#O(){this.#o||this.#c!==void 0||this.#a||(this.#c=setInterval(()=>{this.#P();},this.#l),this.#N=Date.now()+this.#l);}#P(){this.#a||(this.#s===0&&this.#e===0&&this.#c&&this.#w(),this.#s=this.#r?this.#e:0),this.#A(),this.#p();}#A(){for(;this.#S(););}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,r){if(typeof r!="number"||!Number.isFinite(r))throw new TypeError(`Expected \`priority\` to be a finite number, got \`${r}\` (${typeof r})`);this.#t.setPriority(t,r);}async add(t,r={}){return r={timeout:this.timeout,...r,id:r.id??(this.#D++).toString()},new Promise((n,c)=>{const m=Symbol(`task-${r.id}`);this.#t.enqueue(async()=>{this.#e++,this.#v.set(m,{id:r.id,priority:r.priority??0,startTime:Date.now(),timeout:r.timeout});let d;try{try{r.signal?.throwIfAborted();}catch(A){throw this.#V(),this.#v.delete(m),A}this.#y=Date.now();let y=t({signal:r.signal});if(r.timeout&&(y=dn(Promise.resolve(y),{milliseconds:r.timeout,message:`Task timed out after ${r.timeout}ms (queue has ${this.#e} running, ${this.#t.size} waiting)`})),r.signal){const{signal:A}=r;y=Promise.race([y,new Promise((O,P)=>{d=()=>{P(A.reason);},A.addEventListener("abort",d,{once:!0});})]);}const T=await y;n(T),this.emit("completed",T);}catch(y){c(y),this.emit("error",y);}finally{d&&r.signal?.removeEventListener("abort",d),this.#v.delete(m),queueMicrotask(()=>{this.#U();});}},r),this.emit("add"),this.#S();})}async addAll(t,r){return Promise.all(t.map(async n=>this.add(n,r)))}start(){return this.#d?(this.#d=false,this.#A(),this):this}pause(){this.#d=true;}clear(){this.#t=new this.#R,this.#w(),this.#C(),this.emit("empty"),this.#e===0&&(this.#L(),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,r)=>{const n=c=>{this.off("error",n),r(c);};this.on("error",n);})}async#f(t,r){return new Promise(n=>{const c=()=>{r&&!r()||(this.off(t,c),n());};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.#C();}));}#V(){this.#o||(this.#x(),this.#p());}#C(){const t=this.#m;if(this.#o||this.#t.size===0){t&&(this.#m=false,this.emit("rateLimitCleared"));return}let r;if(this.#a){const c=Date.now();this.#T(c),r=this.#b();}else r=this.#s;const n=r>=this.#h;n!==t&&(this.#m=n,this.emit(n?"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}))}}const pn=Object.prototype.toString,mn=e=>pn.call(e)==="[object Error]",gn=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 vn(e){if(!(e&&mn(e)&&e.name==="TypeError"&&typeof e.message=="string"))return false;const{message:r,stack:n}=e;return r==="Load failed"?n===void 0||"__sentry_captured__"in e:r.startsWith("error sending request for url")?true:gn.has(r)}function En(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 te(e,t,{min:r=0,allowInfinity:n=false}={}){if(t!==void 0){if(typeof t!="number"||Number.isNaN(t))throw new TypeError(`Expected \`${e}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(t))throw new TypeError(`Expected \`${e}\` to be a finite number.`);if(t<r)throw new TypeError(`Expected \`${e}\` to be ≥ ${r}.`)}}class Dt 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 yn(e,t){const r=Math.max(1,e+1),n=t.randomize?Math.random()+1:1;let c=Math.round(n*t.minTimeout*t.factor**(r-1));return c=Math.min(c,t.maxTimeout),c}function Ze(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function Tn({error:e,attemptNumber:t,retriesConsumed:r,startTime:n,options:c}){const m=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(m instanceof Dt)throw m.originalError;const d=Number.isFinite(c.retries)?Math.max(0,c.retries-r):c.retries,y=c.maxRetryTime??Number.POSITIVE_INFINITY,T=Object.freeze({error:m,attemptNumber:t,retriesLeft:d,retriesConsumed:r});if(await c.onFailedAttempt(T),Ze(n,y)<=0)throw m;const A=await c.shouldConsumeRetry(T),O=Ze(n,y);if(O<=0||d<=0)throw m;if(m instanceof TypeError&&!vn(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 P=yn(r,c),k=Math.min(P,O);return c.signal?.throwIfAborted(),k>0&&await new Promise((v,w)=>{const S=()=>{clearTimeout(f),c.signal?.removeEventListener("abort",S),w(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 hr(e,t={}){if(t={...t},En(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,te("factor",t.factor,{min:0,allowInfinity:false}),te("minTimeout",t.minTimeout,{min:0,allowInfinity:false}),te("maxTimeout",t.maxTimeout,{min:0,allowInfinity:true}),te("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:true}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let r=0,n=0;const c=performance.now();for(;!Number.isFinite(t.retries)||n<=t.retries;){r++;try{t.signal?.throwIfAborted();const m=await e(r);return t.signal?.throwIfAborted(),m}catch(m){await Tn({error:m,attemptNumber:r,retriesConsumed:n,startTime:c,options:t})&&n++;}}throw new Error("Retry attempts exhausted without throwing an error.")}const bn=new Map,In=new Map;function pr(e){return new Promise((t,r)=>{if(e.signal?.aborted)return r(new Error("Aborted"));const n=GM_xmlhttpRequest({method:"GET",url:e.url,responseType:e.responseType,headers:e.headers||{},timeout:e.timeout??Z.REQUEST_TIMEOUT,onprogress:c=>e.onprogress?.({loaded:c.loaded,total:c.total}),onload:c=>{c.status>=200&&c.status<300?t(c.response):r(new Error(`HTTP ${c.status}`));},onerror:()=>r(new Error("Network error")),ontimeout:()=>r(new Error("Timeout"))});e.signal&&e.signal.addEventListener("abort",()=>n.abort(),{once:true});})}async function wn(e){const t=Oe(e,ut);if(t){if(!t.blob)throw new Error("Blob not found");return t.blob.text()}return hr(()=>pr({url:e,responseType:"text",timeout:Z.MANIFEST_TIMEOUT}),{retries:Z.RETRIES,onFailedAttempt:r=>console.warn(`[SG] Fetch text failed (attempt ${r.attemptNumber}): ${r.error.message}`)})}function mr(e){return nr(bn,In,e,()=>wn(e),ie.TEXT_MAX)}class Sn{async fetch(t,r){const n=Oe(t,ut);if(!n||!n.blob)throw new Error("Blob not found");if(r.signal?.aborted)throw new Error("Aborted");const c=zr(n.blob,r.headers?.Range);return r.onprogress&&setTimeout(()=>{r.signal?.aborted||r.onprogress({loaded:c.size,total:c.size});},0),new Promise((m,d)=>{const y=new FileReader,T=()=>{y.abort(),d(new Error("Aborted"));};r.signal&&r.signal.addEventListener("abort",T,{once:true}),y.onload=()=>{r.signal&&r.signal.removeEventListener("abort",T),m(y.result);},y.onerror=()=>{r.signal&&r.signal.removeEventListener("abort",T),d(y.error||new Error("Blob read error"));},y.readAsArrayBuffer(c);})}}class An{async fetch(t,r){const n=await fetch(t,{method:"GET",headers:r.headers,signal:r.signal});if(!n.ok)throw new Error(`Status ${n.status}`);if(!n.body)throw new Error("No body");const c=n.body.getReader(),m=+(n.headers.get("Content-Length")||"0");let d=0;const y=[];for(;;){const{done:O,value:P}=await c.read();if(O)break;y.push(P),d+=P.length,r.onprogress&&m&&r.onprogress({loaded:d,total:m});}const T=new Uint8Array(d);let A=0;for(const O of y)T.set(O,A),A+=O.length;return T.buffer}}class Nn{async fetch(t,r){return pr({url:t,responseType:"arraybuffer",headers:r.headers,timeout:r.timeout,onprogress:r.onprogress,signal:r.signal})}}function pe(e,t={},r=Z.REQUEST_TIMEOUT,n,c){return Oe(e,ut)?new Sn().fetch(e,{headers:t,timeout:r,onprogress:n,signal:c}):new An().fetch(e,{headers:t,timeout:r,onprogress:n,signal:c}).catch(d=>{if(c?.aborted||d.name==="AbortError"||d.message==="Aborted")throw d;return new Nn().fetch(e,{headers:t,timeout:r,onprogress:n,signal:c})})}var me={exports:{}};var Je;function Rn(){return Je||(Je=1,(function(e,t){(function(r,n){e.exports=n();})(self,(()=>(()=>{var r={31:function(m,d,y){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 O(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){p(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 P(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 w(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 b(u,a){if(!(u instanceof a))throw new TypeError("Cannot call a class as a function")}function p(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 Y,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];}),it=this&&this.__setModuleDefault||(Object.create?function(u,a){Object.defineProperty(u,"default",{enumerable:true,value:a});}:function(u,a){u.default=a;}),st=this&&this.__importStar||(Y=function(u){return Y=Object.getOwnPropertyNames||function(a){var s=[];for(var i in a)Object.prototype.hasOwnProperty.call(a,i)&&(s[s.length]=i);return s},Y(u)},function(u){if(u&&u.__esModule)return u;var a={};if(u!=null)for(var s=Y(u),i=0;i<s.length;i++)s[i]!=="default"&&G(a,u,s[i]);return it(a,u),a});Object.defineProperty(d,"__esModule",{value:true}),d.ContentSteering=d.RenditionReport=d.PrefetchSegment=d.PartialSegment=d.Segment=d.MediaPlaylist=d.MasterPlaylist=d.Playlist=d.SpliceInfo=d.DateRange=d.MediaInitializationSection=d.Key=d.SessionData=d.Variant=d.Rendition=void 0;var H=st(y(203)),yt=f((function u(a){var s=a.type,i=a.uri,g=a.groupId,E=a.language,C=a.assocLanguage,L=a.name,M=a.isDefault,N=a.autoselect,X=a.forced,U=a.instreamId,_=a.characteristics,V=a.channels,D=a.pathwayId;b(this,u),p(this,"type",void 0),p(this,"uri",void 0),p(this,"groupId",void 0),p(this,"language",void 0),p(this,"assocLanguage",void 0),p(this,"name",void 0),p(this,"isDefault",void 0),p(this,"autoselect",void 0),p(this,"forced",void 0),p(this,"instreamId",void 0),p(this,"characteristics",void 0),p(this,"channels",void 0),p(this,"pathwayId",void 0),H.PARAMCHECK(s,g,L),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=L,this.isDefault=M,this.autoselect=N,this.forced=X,this.instreamId=U,this.characteristics=_,this.channels=V,this.pathwayId=D;}));d.Rendition=yt;var at=f((function u(a){var s=a.uri,i=a.isIFrameOnly,g=i!==void 0&&i,E=a.bandwidth,C=a.averageBandwidth,L=a.score,M=a.codecs,N=a.resolution,X=a.frameRate,U=a.hdcpLevel,_=a.allowedCpc,V=a.videoRange,D=a.stableVariantId,F=a.pathwayId,j=a.programId,K=a.audio,J=K===void 0?[]:K,z=a.video,W=z===void 0?[]:z,q=a.subtitles,tt=q===void 0?[]:q,Q=a.closedCaptions,rt=Q===void 0?[]:Q,lt=a.currentRenditions,dt=lt===void 0?{audio:0,video:0,subtitles:0,closedCaptions:0}:lt;b(this,u),p(this,"uri",void 0),p(this,"isIFrameOnly",void 0),p(this,"bandwidth",void 0),p(this,"averageBandwidth",void 0),p(this,"score",void 0),p(this,"codecs",void 0),p(this,"resolution",void 0),p(this,"frameRate",void 0),p(this,"hdcpLevel",void 0),p(this,"allowedCpc",void 0),p(this,"videoRange",void 0),p(this,"stableVariantId",void 0),p(this,"pathwayId",void 0),p(this,"programId",void 0),p(this,"audio",void 0),p(this,"video",void 0),p(this,"subtitles",void 0),p(this,"closedCaptions",void 0),p(this,"currentRenditions",void 0),H.PARAMCHECK(s,E),this.uri=s,this.isIFrameOnly=g,this.bandwidth=E,this.averageBandwidth=C,this.score=L,this.codecs=M,this.resolution=N,this.frameRate=X,this.hdcpLevel=U,this.allowedCpc=_,this.videoRange=V,this.stableVariantId=D,this.pathwayId=F,this.programId=j,this.audio=J,this.video=W,this.subtitles=tt,this.closedCaptions=rt,this.currentRenditions=dt;}));d.Variant=at;var Vt=f((function u(a){var s=a.id,i=a.value,g=a.uri,E=a.language;b(this,u),p(this,"id",void 0),p(this,"value",void 0),p(this,"uri",void 0),p(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;}));d.SessionData=Vt;var xt=f((function u(a){var s=a.method,i=a.uri,g=a.iv,E=a.format,C=a.formatVersion;b(this,u),p(this,"method",void 0),p(this,"uri",void 0),p(this,"iv",void 0),p(this,"format",void 0),p(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;}));d.Key=xt;var Mt=f((function u(a){var s=a.serverUri,i=a.pathwayId;b(this,u),p(this,"serverUri",void 0),p(this,"pathwayId",void 0),this.serverUri=s,this.pathwayId=i;}));d.ContentSteering=Mt;var Lt=f((function u(a){var s=a.hint,i=s!==void 0&&s,g=a.uri,E=a.mimeType,C=a.byterange;b(this,u),p(this,"hint",void 0),p(this,"uri",void 0),p(this,"mimeType",void 0),p(this,"byterange",void 0),H.PARAMCHECK(g),this.hint=i,this.uri=g,this.mimeType=E,this.byterange=C;}));d.MediaInitializationSection=Lt;var Gt=f((function u(a){var s=a.id,i=a.classId,g=a.start,E=a.cue,C=a.end,L=a.duration,M=a.plannedDuration,N=a.endOnNext,X=a.attributes,U=X===void 0?{}:X;b(this,u),p(this,"id",void 0),p(this,"classId",void 0),p(this,"start",void 0),p(this,"cue",void 0),p(this,"end",void 0),p(this,"duration",void 0),p(this,"plannedDuration",void 0),p(this,"endOnNext",void 0),p(this,"attributes",void 0),H.PARAMCHECK(s),H.CONDITIONALPARAMCHECK([N===true,i]),H.CONDITIONALASSERT([C,g],[C,g<=C],[L,L>=0],[M,M>=0]),this.id=s,this.classId=i,this.start=g,this.cue=E,this.end=C,this.duration=L,this.plannedDuration=M,this.endOnNext=N,this.attributes=U;}));d.DateRange=Gt;var Ot=f((function u(a){var s=a.type,i=a.duration,g=a.tagName,E=a.value;b(this,u),p(this,"type",void 0),p(this,"duration",void 0),p(this,"tagName",void 0),p(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;}));d.SpliceInfo=Ot;var Tt=f((function u(a){b(this,u),p(this,"type",void 0),H.PARAMCHECK(a),this.type=a;})),mt=(function(u){function a(s){var i,g=s.isMasterPlaylist,E=s.uri,C=s.version,L=s.independentSegments,M=L!==void 0&&L,N=s.start,X=s.source,U=s.defines;return b(this,a),p(i=P(this,a,["playlist"]),"isMasterPlaylist",void 0),p(i,"uri",void 0),p(i,"version",void 0),p(i,"independentSegments",void 0),p(i,"start",void 0),p(i,"source",void 0),p(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 w(a,u),f(a)})(Tt);d.Playlist=mt;var Pt=(function(u){function a(){var s,i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};b(this,a),p(s=P(this,a,[O(O({},i),{},{isMasterPlaylist:true})]),"variants",void 0),p(s,"currentVariant",void 0),p(s,"sessionDataList",void 0),p(s,"sessionKeyList",void 0),p(s,"contentSteering",void 0);var g=i.variants,E=g===void 0?[]:g,C=i.currentVariant,L=i.sessionDataList,M=L===void 0?[]:L,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 w(a,u),f(a)})(mt);d.MasterPlaylist=Pt;var R=(function(u){function a(){var s,i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};b(this,a),p(s=P(this,a,[O(O({},i),{},{isMasterPlaylist:false})]),"targetDuration",void 0),p(s,"mediaSequenceBase",void 0),p(s,"discontinuitySequenceBase",void 0),p(s,"endlist",void 0),p(s,"playlistType",void 0),p(s,"isIFrame",void 0),p(s,"segments",void 0),p(s,"prefetchSegments",void 0),p(s,"lowLatencyCompatibility",void 0),p(s,"partTargetDuration",void 0),p(s,"renditionReports",void 0),p(s,"skip",void 0),p(s,"hash",void 0);var g=i.targetDuration,E=i.mediaSequenceBase,C=E===void 0?0:E,L=i.discontinuitySequenceBase,M=L===void 0?0:L,N=i.endlist,X=N!==void 0&&N,U=i.playlistType,_=i.isIFrame,V=i.segments,D=V===void 0?[]:V,F=i.prefetchSegments,j=F===void 0?[]:F,K=i.lowLatencyCompatibility,J=i.partTargetDuration,z=i.renditionReports,W=z===void 0?[]:z,q=i.skip,tt=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=J,s.renditionReports=W,s.skip=tt,s.hash=Q,s}return w(a,u),f(a)})(mt);d.MediaPlaylist=R;var I=(function(u){function a(s){var i,g=s.uri,E=s.mimeType,C=s.data,L=s.duration,M=s.title,N=s.byterange,X=s.discontinuity,U=s.mediaSequenceNumber,_=U===void 0?0:U,V=s.discontinuitySequence,D=V===void 0?0:V,F=s.key,j=s.map,K=s.programDateTime,J=s.dateRange,z=s.markers,W=z===void 0?[]:z,q=s.parts,tt=q===void 0?[]:q,Q=s.gap;return b(this,a),p(i=P(this,a,["segment"]),"uri",void 0),p(i,"mimeType",void 0),p(i,"data",void 0),p(i,"duration",void 0),p(i,"title",void 0),p(i,"byterange",void 0),p(i,"discontinuity",void 0),p(i,"mediaSequenceNumber",void 0),p(i,"discontinuitySequence",void 0),p(i,"key",void 0),p(i,"map",void 0),p(i,"programDateTime",void 0),p(i,"dateRange",void 0),p(i,"markers",void 0),p(i,"parts",void 0),p(i,"gap",void 0),i.uri=g,i.mimeType=E,i.data=C,i.duration=L,i.title=M,i.byterange=N,i.discontinuity=X,i.mediaSequenceNumber=_,i.discontinuitySequence=D,i.key=F,i.map=j,i.programDateTime=K,i.dateRange=J,i.markers=W,i.parts=tt,i.gap=Q,i}return w(a,u),f(a)})(Tt);d.Segment=I;var l=(function(u){function a(s){var i,g=s.hint,E=g!==void 0&&g,C=s.uri,L=s.duration,M=s.independent,N=s.byterange,X=s.gap;return b(this,a),p(i=P(this,a,["part"]),"hint",void 0),p(i,"uri",void 0),p(i,"duration",void 0),p(i,"independent",void 0),p(i,"byterange",void 0),p(i,"gap",void 0),H.PARAMCHECK(C),i.hint=E,i.uri=C,i.duration=L,i.independent=M,i.duration=L,i.byterange=N,i.gap=X,i}return w(a,u),f(a)})(Tt);d.PartialSegment=l;var o=(function(u){function a(s){var i,g=s.uri,E=s.discontinuity,C=s.mediaSequenceNumber,L=C===void 0?0:C,M=s.discontinuitySequence,N=M===void 0?0:M,X=s.key;return b(this,a),p(i=P(this,a,["prefetch"]),"uri",void 0),p(i,"discontinuity",void 0),p(i,"mediaSequenceNumber",void 0),p(i,"discontinuitySequence",void 0),p(i,"key",void 0),H.PARAMCHECK(g),i.uri=g,i.discontinuity=E,i.mediaSequenceNumber=L,i.discontinuitySequence=N,i.key=X,i}return w(a,u),f(a)})(Tt);d.PrefetchSegment=o;var h=f((function u(a){var s=a.uri,i=a.lastMSN,g=a.lastPart;b(this,u),p(this,"uri",void 0),p(this,"lastMSN",void 0),p(this,"lastPart",void 0),H.PARAMCHECK(s),this.uri=s,this.lastMSN=i,this.lastPart=g;}));d.RenditionReport=h;},73:function(m,d,y){var T,A=this&&this.__createBinding||(Object.create?function(b,p,x,Y){Y===void 0&&(Y=x);var G=Object.getOwnPropertyDescriptor(p,x);G&&!("get"in G?!p.__esModule:G.writable||G.configurable)||(G={enumerable:true,get:function(){return p[x]}}),Object.defineProperty(b,Y,G);}:function(b,p,x,Y){Y===void 0&&(Y=x),b[Y]=p[x];}),O=this&&this.__setModuleDefault||(Object.create?function(b,p){Object.defineProperty(b,"default",{enumerable:true,value:p});}:function(b,p){b.default=p;}),P=this&&this.__importStar||(T=function(b){return T=Object.getOwnPropertyNames||function(p){var x=[];for(var Y in p)Object.prototype.hasOwnProperty.call(p,Y)&&(x[x.length]=Y);return x},T(b)},function(b){if(b&&b.__esModule)return b;var p={};if(b!=null)for(var x=T(b),Y=0;Y<x.length;Y++)x[Y]!=="default"&&A(p,b,x[Y]);return O(p,b),p}),k=this&&this.__importDefault||function(b){return b&&b.__esModule?b:{default:b}};Object.defineProperty(d,"__esModule",{value:true}),d.setOptions=d.getOptions=d.types=d.stringify=d.parse=void 0;const v=y(203);Object.defineProperty(d,"getOptions",{enumerable:true,get:function(){return v.getOptions}}),Object.defineProperty(d,"setOptions",{enumerable:true,get:function(){return v.setOptions}});const w=k(y(377));d.parse=w.default;const S=k(y(887));d.stringify=S.default;const f=P(y(31));d.types=f;},203:(m,d)=>{function y(v,w){return (function(S){if(Array.isArray(S))return S})(v)||(function(S,f){var b=S==null?null:typeof Symbol<"u"&&S[Symbol.iterator]||S["@@iterator"];if(b!=null){var p,x,Y,G,it=[],st=true,H=false;try{if(Y=(b=b.call(S)).next,f!==0)for(;!(st=(p=Y.call(b)).done)&&(it.push(p.value),it.length!==f);st=!0);}catch(yt){H=true,x=yt;}finally{try{if(!st&&b.return!=null&&(G=b.return(),Object(G)!==G))return}finally{if(H)throw x}}return it}})(v,w)||A(v,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 T(v,w){var S=typeof Symbol<"u"&&v[Symbol.iterator]||v["@@iterator"];if(!S){if(Array.isArray(v)||(S=A(v))||w){S&&(v=S);var f=0,b=function(){};return {s:b,n:function(){return f>=v.length?{done:true}:{done:false,value:v[f++]}},e:function(G){throw G},f:b}}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 p,x=true,Y=false;return {s:function(){S=S.call(v);},n:function(){var G=S.next();return x=G.done,G},e:function(G){Y=true,p=G;},f:function(){try{x||S.return==null||S.return();}finally{if(Y)throw p}}}}function A(v,w){if(v){if(typeof v=="string")return O(v,w);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)?O(v,w):void 0}}function O(v,w){(w==null||w>v.length)&&(w=v.length);for(var S=0,f=Array(w);S<w;S++)f[S]=v[S];return f}Object.defineProperty(d,"__esModule",{value:true}),d.THROW=k,d.ASSERT=function(v){for(var w=arguments.length,S=new Array(w>1?w-1:0),f=1;f<w;f++)S[f-1]=arguments[f];var b,p=T(S.entries());try{for(p.s();!(b=p.n()).done;){var x=y(b.value,2),Y=x[0];x[1]||k(new Error("".concat(v," : Failed at [").concat(Y,"]")));}}catch(G){p.e(G);}finally{p.f();}},d.CONDITIONALASSERT=function(){for(var v=arguments.length,w=new Array(v),S=0;S<v;S++)w[S]=arguments[S];var f,b=T(w.entries());try{for(b.s();!(f=b.n()).done;){var p=y(f.value,2),x=p[0],Y=y(p[1],2),G=Y[0],it=Y[1];G&&(it||k(new Error("Conditional Assert : Failed at [".concat(x,"]"))));}}catch(st){b.e(st);}finally{b.f();}},d.PARAMCHECK=function(){for(var v=arguments.length,w=new Array(v),S=0;S<v;S++)w[S]=arguments[S];var f,b=T(w.entries());try{for(b.s();!(f=b.n()).done;){var p=y(f.value,2),x=p[0];p[1]===void 0&&k(new Error("Param Check : Failed at [".concat(x,"]")));}}catch(Y){b.e(Y);}finally{b.f();}},d.CONDITIONALPARAMCHECK=function(){for(var v=arguments.length,w=new Array(v),S=0;S<v;S++)w[S]=arguments[S];var f,b=T(w.entries());try{for(b.s();!(f=b.n()).done;){var p=y(f.value,2),x=p[0],Y=y(p[1],2),G=Y[0],it=Y[1];G&&it===void 0&&k(new Error("Conditional Param Check : Failed at [".concat(x,"]")));}}catch(st){b.e(st);}finally{b.f();}},d.INVALIDPLAYLIST=function(v){k(new Error("Invalid Playlist : ".concat(v)));},d.toNumber=function(v){var w=arguments.length>1&&arguments[1]!==void 0?arguments[1]:10;if(typeof v=="number")return v;var S=w===10?Number.parseFloat(v):Number.parseInt(v,w);return Number.isNaN(S)?0:S},d.hexToByteSequence=function(v){(v.startsWith("0x")||v.startsWith("0X"))&&(v=v.slice(2));for(var w=new Uint8Array(v.length/2),S=0;S<v.length;S+=2)w[S/2]=Number.parseInt(v.slice(S,S+2),16);return w},d.byteSequenceToHex=function(v){var w=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:v.byteLength;S<=w&&k(new Error("end must be larger than start : start=".concat(w,", end=").concat(S)));for(var f=[],b=w;b<S;b++)f.push("0".concat((255&v[b]).toString(16).toUpperCase()).slice(-2));return "0x".concat(f.join(""))},d.tryCatch=function(v,w){try{return v()}catch(S){return w(S)}},d.splitAt=function(v,w){for(var S=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,f=-1,b=0,p=0;b<v.length;b++)if(v[b]===w){if(p++===S)return [v.slice(0,b),v.slice(b+1)];f=b;}return f!==-1?[v.slice(0,f),v.slice(f+1)]:[v]},d.trim=function(v){var w=arguments.length>1&&arguments[1]!==void 0?arguments[1]:" ";return !v||(v=v.trim(),w===" ")||(v.startsWith(w)&&(v=v.slice(1)),v.endsWith(w)&&(v=v.slice(0,-1))),v},d.splitByCommaWithPreservingQuotes=function(v){for(var w=[],S=true,f=0,b=[],p=0;p<v.length;p++){var x=v[p];S&&x===","?(w.push(v.slice(f,p).trim()),f=p+1):x!=='"'&&x!=="'"||(S?(b.push(x),S=false):x===b.at(-1)?(b.pop(),S=true):b.push(x));}return w.push(v.slice(f).trim()),w},d.camelify=function(v){var w,S=[],f=false,b=T(v);try{for(b.s();!(w=b.n()).done;){var p=w.value;p!=="-"&&p!=="_"?f?(S.push(p.toUpperCase()),f=!1):S.push(p.toLowerCase()):f=!0;}}catch(x){b.e(x);}finally{b.f();}return S.join("")},d.formatDate=function(v){var w=v.getUTCFullYear(),S=("0"+(v.getUTCMonth()+1)).slice(-2),f=("0"+v.getUTCDate()).slice(-2),b=("0"+v.getUTCHours()).slice(-2),p=("0"+v.getUTCMinutes()).slice(-2),x=("0"+v.getUTCSeconds()).slice(-2),Y=("00"+v.getUTCMilliseconds()).slice(-3);return "".concat(w,"-").concat(S,"-").concat(f,"T").concat(b,":").concat(p,":").concat(x,".").concat(Y,"Z")},d.hasOwnProp=function(v,w){return Object.hasOwn(v,w)},d.setOptions=function(){var v=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};P=Object.assign(P,v);},d.getOptions=function(){return Object.assign({},P)};var P={};function k(v){if(P.strictMode)throw v;P.silent||console.error(v.message);}},377:function(m,d,y){function T(R,I){return (function(l){if(Array.isArray(l))return l})(R)||(function(l,o){var h=l==null?null:typeof Symbol<"u"&&l[Symbol.iterator]||l["@@iterator"];if(h!=null){var u,a,s,i,g=[],E=true,C=false;try{if(s=(h=h.call(l)).next,o===0){if(Object(h)!==h)return;E=!1;}else for(;!(E=(u=s.call(h)).done)&&(g.push(u.value),g.length!==o);E=!0);}catch(L){C=true,a=L;}finally{try{if(!E&&h.return!=null&&(i=h.return(),Object(i)!==i))return}finally{if(C)throw a}}return g}})(R,I)||O(R,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 A(R,I){var l=typeof Symbol<"u"&&R[Symbol.iterator]||R["@@iterator"];if(!l){if(Array.isArray(R)||(l=O(R))||I){l&&(R=l);var o=0,h=function(){};return {s:h,n:function(){return o>=R.length?{done:true}:{done:false,value:R[o++]}},e:function(i){throw i},f:h}}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 O(R,I){if(R){if(typeof R=="string")return P(R,I);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)?P(R,I):void 0}}function P(R,I){(I==null||I>R.length)&&(I=R.length);for(var l=0,o=Array(I);l<I;l++)o[l]=R[l];return o}var k,v=this&&this.__createBinding||(Object.create?function(R,I,l,o){o===void 0&&(o=l);var h=Object.getOwnPropertyDescriptor(I,l);h&&!("get"in h?!I.__esModule:h.writable||h.configurable)||(h={enumerable:true,get:function(){return I[l]}}),Object.defineProperty(R,o,h);}:function(R,I,l,o){o===void 0&&(o=l),R[o]=I[l];}),w=this&&this.__setModuleDefault||(Object.create?function(R,I){Object.defineProperty(R,"default",{enumerable:true,value:I});}:function(R,I){R.default=I;}),S=this&&this.__importStar||(k=function(R){return k=Object.getOwnPropertyNames||function(I){var l=[];for(var o in I)Object.prototype.hasOwnProperty.call(I,o)&&(l[l.length]=o);return l},k(R)},function(R){if(R&&R.__esModule)return R;var I={};if(R!=null)for(var l=k(R),o=0;o<l.length;o++)l[o]!=="default"&&v(I,R,l[o]);return w(I,R),I});Object.defineProperty(d,"__esModule",{value:true});var f=S(y(203)),b=y(31);function p(R){return f.trim(R,'"')}function x(R){var I=f.splitAt(R,",");return {duration:f.toNumber(I[0]),title:decodeURIComponent(escape(I[1]))}}function Y(R){var I=f.splitAt(R,"@");return {length:f.toNumber(I[0]),offset:I[1]?f.toNumber(I[1]):-1}}function G(R){var I=f.splitAt(R,"x");return {width:f.toNumber(I[0]),height:f.toNumber(I[1])}}function it(R){var I="ALLOWED-CPC: Each entry must consit of KEYFORMAT and Content Protection Configuration",l=R.split(",");l.length===0&&f.INVALIDPLAYLIST(I);var o,h=[],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?h.push({format:i,cpcList:g.split("/")}):f.INVALIDPLAYLIST(I);}}catch(E){u.e(E);}finally{u.f();}return h}function st(R){return R.startsWith('"')?p(R):R.startsWith("0x")||R.startsWith("0X")?f.hexToByteSequence(R):f.toNumber(R)}function H(R,I){I.IV&&R.compatibleVersion<2&&(R.compatibleVersion=2),(I.KEYFORMAT||I.KEYFORMATVERSIONS)&&R.compatibleVersion<5&&(R.compatibleVersion=5);}function yt(R){var I,l,o,h={},u=A(f.splitByCommaWithPreservingQuotes(R));try{for(u.s();!(I=u.n()).done;){var a=I.value,s=T(f.splitAt(a,"="),2),i=s[0],g=s[1],E=p(g);switch(i){case "URI":h[i]=E;break;case "START-DATE":case "END-DATE":h[i]=new Date(E);break;case "IV":h[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":h[i]=Y(E);break;case "RESOLUTION":h[i]=G(E);break;case "ALLOWED-CPC":h[i]=it(E);break;case "END-ON-NEXT":case "DEFAULT":case "AUTOSELECT":case "FORCED":case "PRECISE":case "CAN-BLOCK-RELOAD":case "INDEPENDENT":case "GAP":h[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":h[i]=f.toNumber(E);break;default:i.startsWith("SCTE35-")?h[i]=f.hexToByteSequence(E):i.startsWith("X-")?h[i]=st(g):(i==="VIDEO-RANGE"&&E!=="SDR"&&E!=="HLG"&&E!=="PQ"&&f.INVALIDPLAYLIST('VIDEO-RANGE: unknown value "'.concat(E,'"')),h[i]=E);}}}catch(C){u.e(C);}finally{u.f();}return h}function at(){f.INVALIDPLAYLIST("The file contains both media and master playlist tags.");}function Vt(R,I,l){var o,h=(o=I.attributes,new b.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 L=g.value;if(L.name===i.name)return "All EXT-X-MEDIA tags in the same Group MUST have different NAME attributes.";L.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,h);a&&f.INVALIDPLAYLIST(a),u.push(h),h.isDefault&&(R.currentRenditions[f.camelify(l)]=u.length-1);}function xt(R,I,l,o,h){var u,a=new b.Variant({uri:l,bandwidth:I.BANDWIDTH,averageBandwidth:I["AVERAGE-BANDWIDTH"],score:I.SCORE,codecs:I.CODECS,resolution:I.RESOLUTION,frameRate:I["FRAME-RATE"],hdcpLevel:I["HDCP-LEVEL"],allowedCpc:I["ALLOWED-CPC"],videoRange:I["VIDEO-RANGE"],stableVariantId:I["STABLE-VARIANT-ID"],pathwayId:I["STABLE-PATHWAY-ID"],programId:I["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."),I[E]===g["GROUP-ID"]&&(Vt(a,i,E),E==="CLOSED-CAPTIONS")){var C,L=A(a.closedCaptions);try{for(L.s();!(C=L.n()).done;){var M=C.value.instreamId;if(M&&M.startsWith("SERVICE")&&h.compatibleVersion<7){h.compatibleVersion=7;break}}}catch(N){L.e(N);}finally{L.f();}}}}}catch(N){s.e(N);}finally{s.f();}return (function(N,X,U){for(var _=function(){var F=D[V];F==="CLOSED-CAPTIONS"&&N[F]==="NONE"?(U.isClosedCaptionsNone=true,X.closedCaptions=[]):N[F]&&!X[f.camelify(F)].some((function(j){return j.groupId===N[F]}))&&f.INVALIDPLAYLIST("".concat(F," attribute MUST match the value of the GROUP-ID attribute of an EXT-X-MEDIA tag whose TYPE attribute is ").concat(F,"."));},V=0,D=["AUDIO","VIDEO","SUBTITLES","CLOSED-CAPTIONS"];V<D.length;V++)_();})(I,a,h),a.isIFrameOnly=o,a}function Mt(R,I,l,o,h,u,a){for(var s=new b.Segment({uri:I,mediaSequenceNumber:h,discontinuitySequence:u}),i=false,g=false,E=l;E<=o;E++){var C=Pt(R[E]),L=C.name,M=C.value,N=C.attributes;if(L==="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(L==="EXT-X-BYTERANGE")a.compatibleVersion<4&&(a.compatibleVersion=4),s.byterange=M;else if(L==="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(L==="EXT-X-GAP")a.compatibleVersion<8&&(a.compatibleVersion=8),s.gap=true;else if(L==="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 b.Key({method:N.METHOD,uri:N.URI,iv:N.IV,format:N.KEYFORMAT,formatVersion:N.KEYFORMATVERSIONS});else if(L==="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 b.MediaInitializationSection({uri:N.URI,byterange:N.BYTERANGE});else if(L==="EXT-X-PROGRAM-DATE-TIME")s.programDateTime=M;else if(L==="EXT-X-DATERANGE"){for(var X={},U=0,_=Object.keys(N);U<_.length;U++){var V=_[U];(V.startsWith("SCTE35-")||V.startsWith("X-"))&&(X[V]=N[V]);}s.dateRange=new b.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(L==="EXT-X-CUE-OUT")s.markers.push(new b.SpliceInfo({type:"OUT",duration:N&&N.DURATION||M}));else if(L==="EXT-X-CUE-IN")s.markers.push(new b.SpliceInfo({type:"IN"}));else if(L==="EXT-X-CUE-OUT-CONT"||L==="EXT-X-CUE"||L==="EXT-OATCLS-SCTE35"||L==="EXT-X-ASSET"||L==="EXT-X-SCTE35")s.markers.push(new b.SpliceInfo({type:"RAW",tagName:L,value:M}));else if(L!=="EXT-X-PRELOAD-HINT"||N.TYPE)if(L==="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(L!=="EXT-X-PART"&&L!=="EXT-X-PRELOAD-HINT"||N.URI){if(L==="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 b.MediaInitializationSection({hint:true,uri:N.URI,byterange:{length:N["BYTERANGE-LENGTH"],offset:N["BYTERANGE-START"]||0}});else if(L==="EXT-X-PART"||L==="EXT-X-PRELOAD-HINT"&&N.TYPE==="PART"){L!=="EXT-X-PART"||N.DURATION||f.INVALIDPLAYLIST("EXT-X-PART: DURATION attribute is mandatory"),L==="EXT-X-PRELOAD-HINT"&&(g=true);var D=new b.PartialSegment({hint:L==="EXT-X-PRELOAD-HINT",uri:N.URI,byterange:L==="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 Lt(R,I,l,o,h,u,a){for(var s=new b.PrefetchSegment({uri:I,mediaSequenceNumber:h,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 b.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 Gt(R,I){var l,o=new b.MediaPlaylist,h=-1,u=0,a=false,s=false,i=0,g=null,E=null,C=false,L=A(R.entries());try{for(L.s();!(l=L.n()).done;){var M=T(l.value,2),N=M[0],X=M[1],U=Pt(X),_=U.name,V=U.value,D=U.attributes;if(U.category!=="Segment"){if(_==="EXT-X-VERSION")o.version===void 0?o.version=V:f.INVALIDPLAYLIST("A Playlist file MUST NOT contain more than one EXT-X-VERSION tag.");else if(_==="EXT-X-TARGETDURATION")o.targetDuration=I.targetDuration=V;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=V;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=V;else if(_==="EXT-X-ENDLIST")o.endlist=!0;else if(_==="EXT-X-PLAYLIST-TYPE")o.playlistType=V;else if(_==="EXT-X-I-FRAMES-ONLY")I.compatibleVersion<4&&(I.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 b.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"),I.compatibleVersion<9&&(I.compatibleVersion=9),o.skip=D["SKIPPED-SEGMENTS"],u+=o.skip;else if(_==="EXT-X-PREFETCH"){var F=Lt(R,V,h===-1?N:h,N-1,u++,i,I);F&&(F.discontinuity&&(F.discontinuitySequence++,i=F.discontinuitySequence),F.key?g=F.key:F.key=g,o.prefetchSegments.push(F)),s=!0,h=-1;}else if(_==="EXT-X-DEFINE")o.defines||(o.defines=[]),o.defines.push(D);else if(typeof X=="string"){h===-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=Mt(R,X,h,N-1,u++,i,I);if(j){var K=T(Ot(o,j,i,g,E),3);i=K[0],g=K[1],E=K[2],!C&&j.parts.length>0&&(C=!0);}h=-1;}}else h===-1&&(h=N),_==="EXT-X-DISCONTINUITY"&&(a=!0);}}catch(q){L.e(q);}finally{L.f();}if(h!==-1){var J=Mt(R,"",h,R.length-1,u++,i,I);if(J){var z,W=J.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"),Ot(o,J,g,E),!C&&J.parts.length>0&&(C=true);}}return (function(q){for(var tt=new Map,Q=new Map,rt=false,lt=false,dt=q.length-1;dt>=0;dt--){var vt=q[dt],bt=vt.programDateTime,$=vt.dateRange;if(bt&&(lt=true),$&&$.start){rt=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(),Wt=$.duration||0;$.end&&$.duration&&ot+1e3*Wt!==$.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=tt.get($.classId)),tt.set($.classId,$.start);var It=$.end?$.end.getTime():$.start.getTime()+1e3*($.duration||0),kt=Q.get($.classId);if(kt){var Qt,wt=A(kt);try{for(wt.s();!(Qt=wt.n()).done;){var Ct=Qt.value;(Ct.start<=ot&&Ct.end>ot||Ct.start>=ot&&Ct.start<It)&&f.INVALIDPLAYLIST("DATERANGE tags with the same CLASS should not overlap");}}catch(Ut){wt.e(Ut);}finally{wt.f();}kt.push({start:ot,end:It});}else $.classId&&Q.set($.classId,[{start:ot,end:It}]);}}rt&&!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,tt){var Q=q.lowLatencyCompatibility,rt=q.targetDuration,lt=q.partTargetDuration,dt=q.segments,vt=q.renditionReports,bt=Q.canSkipUntil,$=Q.holdBack,ot=Q.partHoldBack;if(bt<6*rt&&f.INVALIDPLAYLIST("The Skip Boundary must be at least six times the EXT-X-TARGETDURATION."),$<3*rt&&f.INVALIDPLAYLIST("HOLD-BACK must be at least three times the EXT-X-TARGETDURATION."),tt){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 Wt,It=A(dt.entries());try{for(It.s();!(Wt=It.n()).done;){var kt=T(Wt.value,2),Qt=kt[0],wt=kt[1].parts;wt.length>0&&Qt<dt.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 Ct,Ut=A(wt.entries());try{for(Ut.s();!(Ct=Ut.n()).done;){var _e=T(Ct.value,2),Lr=_e[0],ce=_e[1].duration;ce!==void 0&&(ce>lt&&f.INVALIDPLAYLIST("PART-TARGET is the maximum duration of any Partial Segment"),Lr<wt.length-1&&ce<.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(jt){Ut.e(jt);}finally{Ut.f();}}}catch(jt){It.e(jt);}finally{It.f();}}var Fe,Zt=A(vt);try{for(Zt.s();!(Fe=Zt.n()).done;){var Ye,Bt=Fe.value,ue=dt.at(-1);(Ye=Bt.lastMSN)!==null&&Ye!==void 0||(Bt.lastMSN=ue.mediaSequenceNumber),(Bt.lastPart===null||Bt.lastPart===void 0)&&ue.parts.length>0&&(Bt.lastPart=ue.parts.length-1);}}catch(jt){Zt.e(jt);}finally{Zt.f();}})(o,C),o}function Ot(R,I,l,o,h){var u=I.discontinuity,a=I.key,s=I.map,i=I.byterange,g=I.uri;if(u&&(I.discontinuitySequence=l+1),a||(I.key=o),s||(I.map=h),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(I),[I.discontinuitySequence,I.key,I.map]}function Tt(R,I){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),h=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"}})(h);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,I),a==="Unknown")return null;a==="MediaPlaylist"&&h!=="EXT-X-RENDITION-REPORT"&&h!=="EXT-X-PREFETCH"&&(I.hash[h]&&f.INVALIDPLAYLIST("There MUST NOT be more than one Media Playlist tag of each type in any Media Playlist"),I.hash[h]=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,yt(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,yt(E)];case "EXTINF":return [x(E),null];case "EXT-X-BYTERANGE":return [Y(E),null];case "EXT-X-PROGRAM-DATE-TIME":return [new Date(E),null];default:return [E,null]}})(h,u),i=T(s,2);return {name:h,category:a,value:i[0],attributes:i[1]}}function mt(R,I){var l;return I.isMasterPlaylist?l=(function(o,h){var u,a=new b.MasterPlaylist,s=false,i=A(o.entries());try{var g=function(){var N=T(u.value,2),X=N[0],U=Pt(N[1]),_=U.name,V=U.value,D=U.attributes;if(_==="EXT-X-VERSION")a.version=V;else if(_==="EXT-X-CONTENT-STEERING-SERVER"){var F=new b.ContentSteering({serverUri:D["SERVER-URI"],pathwayId:D["PATHWAY-ID"]});a.contentSteering=F;}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,h);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 J=xt(o,D,D.URI,!0,h);J&&a.variants.push(J);}else if(_==="EXT-X-SESSION-DATA"){var z=new b.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 b.Key({method:D.METHOD,uri:D.URI,iv:D.IV,format:D.KEYFORMAT,formatVersion:D.KEYFORMATVERSIONS});a.sessionKeyList.some((function(q){return (function(tt,Q){if(tt.method!==Q.method||tt.uri!==Q.uri)return !1;if(tt.iv){if(!Q.iv||tt.iv.byteLength!==Q.iv.byteLength)return !1;for(var rt=0;rt<tt.iv.byteLength;rt++)if(tt.iv[rt]!==Q.iv[rt])return !1}else if(Q.iv)return !1;return tt.format===Q.format&&tt.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(h,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(h.isClosedCaptionsNone){var L,M=A(a.variants);try{for(M.s();!(L=M.n()).done;)L.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,I):!(l=Gt(R,I)).isIFrame&&I.hasMap&&I.compatibleVersion<6&&(I.compatibleVersion=6),I.compatibleVersion>1&&(!l.version||l.version<I.compatibleVersion)&&f.INVALIDPLAYLIST("EXT-X-VERSION needs to be ".concat(I.compatibleVersion," or higher.")),l}function Pt(R){return typeof R=="string"?{}:R}d.default=function(R){var I={version:void 0,isMasterPlaylist:void 0,hasMap:false,targetDuration:0,compatibleVersion:1,isClosedCaptionsNone:false,hash:{}},l=mt((function(o,h){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=Tt(i,h);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,I),I);return l.source=R,l};},887:function(m,d,y){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(h){if(Array.isArray(h))return h})(l)||(function(h,u){var a=h==null?null:typeof Symbol<"u"&&h[Symbol.iterator]||h["@@iterator"];if(a!=null){var s,i,g,E,C=[],L=true,M=false;try{if(g=(a=a.call(h)).next,u===0){if(Object(a)!==a)return;L=!1;}else for(;!(L=(s=g.call(a)).done)&&(C.push(s.value),C.length!==u);L=!0);}catch(N){M=true,i=N;}finally{try{if(!L&&a.return!=null&&(E=a.return(),Object(E)!==E))return}finally{if(M)throw i}}return C}})(l,o)||P(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 O(l,o){var h=typeof Symbol<"u"&&l[Symbol.iterator]||l["@@iterator"];if(!h){if(Array.isArray(l)||(h=P(l))||o){h&&(l=h);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(){h=h.call(l);},n:function(){var E=h.next();return i=E.done,E},e:function(E){g=true,s=E;},f:function(){try{i||h.return==null||h.return();}finally{if(g)throw s}}}}function P(l,o){if(l){if(typeof l=="string")return k(l,o);var h={}.toString.call(l).slice(8,-1);return h==="Object"&&l.constructor&&(h=l.constructor.name),h==="Map"||h==="Set"?Array.from(l):h==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(h)?k(l,o):void 0}}function k(l,o){(o==null||o>l.length)&&(o=l.length);for(var h=0,u=Array(o);h<o;h++)u[h]=l[h];return u}function v(l,o){for(var h=0;h<o.length;h++){var u=o[h];u.enumerable=u.enumerable||false,u.configurable=true,"value"in u&&(u.writable=true),Object.defineProperty(l,G(u.key),u);}}function w(l,o,h){return o=Y(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,p()?Reflect.construct(o,[],Y(l).constructor):o.apply(l,h))}function S(l,o,h,u){var a=f(Y(l.prototype),o,h);return 2&u&&typeof a=="function"?function(s){return a.apply(h,s)}:a}function f(){return f=typeof Reflect<"u"&&Reflect.get?Reflect.get.bind():function(l,o,h){var u=(function(s,i){for(;!{}.hasOwnProperty.call(s,i)&&(s=Y(s))!==null;);return s})(l,o);if(u){var a=Object.getOwnPropertyDescriptor(u,o);return a.get?a.get.call(arguments.length<3?l:h):a.value}},f.apply(null,arguments)}function b(l){var o=typeof Map=="function"?new Map:void 0;return b=function(h){if(h===null||!(function(a){try{return Function.toString.call(a).indexOf("[native code]")!==-1}catch{return typeof a=="function"}})(h))return h;if(typeof h!="function")throw new TypeError("Super expression must either be null or a function");if(o!==void 0){if(o.has(h))return o.get(h);o.set(h,u);}function u(){return (function(a,s,i){if(p())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})(h,arguments,Y(this).constructor)}return u.prototype=Object.create(h.prototype,{constructor:{value:u,enumerable:false,writable:true,configurable:true}}),x(u,h)},b(l)}function p(){try{var l=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})));}catch{}return (p=function(){return !!l})()}function x(l,o){return x=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(h,u){return h.__proto__=u,h},x(l,o)}function Y(l){return Y=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(o){return o.__proto__||Object.getPrototypeOf(o)},Y(l)}function G(l){var o=(function(h,u){if(T(h)!="object"||!h)return h;var a=h[Symbol.toPrimitive];if(a!==void 0){var s=a.call(h,u);if(T(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(h)})(l,"string");return T(o)=="symbol"?o:o+""}var it,st=this&&this.__createBinding||(Object.create?function(l,o,h,u){u===void 0&&(u=h);var a=Object.getOwnPropertyDescriptor(o,h);a&&!("get"in a?!o.__esModule:a.writable||a.configurable)||(a={enumerable:true,get:function(){return o[h]}}),Object.defineProperty(l,u,a);}:function(l,o,h,u){u===void 0&&(u=h),l[u]=o[h];}),H=this&&this.__setModuleDefault||(Object.create?function(l,o){Object.defineProperty(l,"default",{enumerable:true,value:o});}:function(l,o){l.default=o;}),yt=this&&this.__importStar||(it=function(l){return it=Object.getOwnPropertyNames||function(o){var h=[];for(var u in o)Object.prototype.hasOwnProperty.call(o,u)&&(h[h.length]=u);return h},it(l)},function(l){if(l&&l.__esModule)return l;var o={};if(l!=null)for(var h=it(l),u=0;u<h.length;u++)h[u]!=="default"&&st(o,l,h[u]);return H(o,l),o});Object.defineProperty(d,"__esModule",{value:true});var at=yt(y(203)),Vt=["#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"],Mt=(function(l){function o(s){var i,g,E,C;return (function(L,M){if(!(L instanceof M))throw new TypeError("Cannot call a class as a function")})(this,o),i=w(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),h=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[L];if(!N.startsWith("#"))return S(o,"push",s,3)([N]),0;if(Vt.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]);},L=0,M=g;L<M.length;L++)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(h.prototype,u),a&&v(h,a),Object.defineProperty(h,"prototype",{writable:false}),h;var h,u,a;})(b(Array));function Lt(l,o){var h=1e3;o&&(h=Math.pow(10,o));var u=Math.round(l*h)/h;return o?u.toFixed(o):u}function Gt(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 Ot(l,o){var h=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(h,":").concat(u.join(","))}function Tt(l,o){var h=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(Lt(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=O(o.audio);try{for(s.s();!(a=s.n()).done;){var i=a.value;l.push(mt(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=O(o.video);try{for(E.s();!(g=E.n()).done;){var C=g.value;l.push(mt(C));}}catch(z){E.e(z);}finally{E.f();}}if(o.subtitles.length>0){u.push('SUBTITLES="'.concat(o.subtitles[0].groupId,'"'));var L,M=O(o.subtitles);try{for(M.s();!(L=M.n()).done;){var N=L.value;l.push(mt(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=O(o.closedCaptions);try{for(U.s();!(X=U.n()).done;){var _=X.value;l.push(mt(_));}}catch(z){U.e(z);}finally{U.f();}}if(o.score&&u.push("SCORE=".concat(o.score)),o.allowedCpc){var V,D=[],F=O(o.allowedCpc);try{for(F.s();!(V=F.n()).done;){var j=V.value,K=j.format,J=j.cpcList;D.push("".concat(K,":").concat(J.join("/")));}}catch(z){F.e(z);}finally{F.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(h,":").concat(u.join(","))),o.isIFrameOnly||l.push("".concat(o.uri));}function mt(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 Pt(l,o,h,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 L=Ot(o.key);L!==h&&(l.push(L),h=L);}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,V=Object.keys(X.attributes);_<V.length;_++){var D=V[_];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 _,V="",D=O(U);try{for(D.s();!(_=D.n()).done;){var F=_.value;if(F.type==="OUT")V="OUT",X.push("#EXT-X-CUE-OUT:DURATION=".concat(F.duration));else if(F.type==="IN")V="IN",X.push("#EXT-X-CUE-IN");else if(F.type==="RAW"){var j=F.value?":".concat(F.value):"";X.push("#".concat(F.tagName).concat(j));}}}catch(K){D.e(K);}finally{D.f();}return V})(l,o.markers)),o.parts.length>0&&(E=(function(X,U){var _,V=false,D=O(U);try{for(D.s();!(_=D.n()).done;){var F=_.value;if(F.hint){var j=[];if(j.push("TYPE=PART",'URI="'.concat(F.uri,'"')),F.byterange){var K=F.byterange,J=K.offset,z=K.length;j.push("BYTERANGE-START=".concat(J)),z&&j.push("BYTERANGE-LENGTH=".concat(z));}X.push("#EXT-X-PRELOAD-HINT:".concat(j.join(","))),V=!0;}else {var W=[];W.push("DURATION=".concat(F.duration),'URI="'.concat(F.uri,'"')),F.byterange&&W.push("BYTERANGE=".concat(R(F.byterange))),F.independent&&W.push("INDEPENDENT=YES"),F.gap&&W.push("GAP=YES"),X.push("#EXT-X-PART:".concat(W.join(",")));}}}catch(q){D.e(q);}finally{D.f();}return V})(l,o.parts)),E)return [h,u];if(typeof o.duration=="number"&&!Number.isNaN(o.duration)){var N=g<3?Math.round(o.duration):Lt(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)),[h,u,C]}function R(l){var o=l.offset,h=l.length;return "".concat(h,"@").concat(o)}function I(l){var o=[];for(var h in l)o.push("".concat(h,'="').concat(l[h],'"'));return "#EXT-X-DEFINE:".concat(o.join(","))}d.default=function(l,o){at.PARAMCHECK(l),at.ASSERT("Not a playlist",l.type==="playlist");var h=new Mt(l.uri);if(h.push("#EXTM3U"),l.version&&h.push("#EXT-X-VERSION:".concat(l.version)),l.independentSegments&&h.push("#EXT-X-INDEPENDENT-SEGMENTS"),l.start&&h.push("#EXT-X-START:TIME-OFFSET=".concat(Lt(l.start.offset)).concat(l.start.precise?",PRECISE=YES":"")),l.defines){var u,a=O(l.defines);try{for(a.s();!(u=a.n()).done;){var s=u.value;h.push(I(s));}}catch(i){a.e(i);}finally{a.f();}}return l.isMasterPlaylist?(function(i,g,E){var C,L;g.contentSteering&&i.push((C=g.contentSteering,L=['SERVER-URI="'.concat(C.serverUri,'"'),'PATHWAY-ID="'.concat(C.pathwayId,'"')],"#EXT-X-CONTENT-STEERING:".concat(L.join(","))));var M,N=O(g.sessionDataList);try{for(N.s();!(M=N.n()).done;){var X=M.value;i.push(Gt(X));}}catch(W){N.e(W);}finally{N.f();}var U,_=O(g.sessionKeyList);try{for(_.s();!(U=_.n()).done;){var V=U.value;i.push(Ot(V,!0));}}catch(W){_.e(W);}finally{_.f();}var D,F=O(g.variants.entries());try{for(F.s();!(D=F.n()).done;){var j=A(D.value,2),K=j[0],J=j[1],z=i.length;Tt(i,J),E!=null&&E.variantProcessor&&E.variantProcessor(i,z,i.length-1,J,K);}}catch(W){F.e(W);}finally{F.f();}})(h,l,o):(function(i,g,E){var C="",L="",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,V=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(_)),V!==void 0&&D.push("PART-HOLD-BACK=".concat(V)),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 F,j=O(g.segments.entries());try{for(j.s();!(F=j.n()).done;){var K,J=A(F.value,2),z=J[0],W=J[1],q=i.length,tt=A(Pt(i,W,C,L,g.version),3);C=tt[0],L=tt[1],(K=tt[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,rt=O(g.prefetchSegments);try{for(rt.s();!(Q=rt.n()).done;){var lt=Q.value;lt.discontinuity&&i.push("#EXT-X-PREFETCH-DISCONTINUITY"),i.push("#EXT-X-PREFETCH:".concat(lt.uri));}}catch(ot){rt.e(ot);}finally{rt.f();}g.endlist&&i.push("#EXT-X-ENDLIST");var dt,vt=O(g.renditionReports);try{for(vt.s();!(dt=vt.n()).done;){var bt=dt.value,$=[];$.push('URI="'.concat(bt.uri,'"'),"LAST-MSN=".concat(bt.lastMSN)),bt.lastPart!==void 0&&$.push("LAST-PART=".concat(bt.lastPart)),i.push("#EXT-X-RENDITION-REPORT:".concat($.join(",")));}}catch(ot){vt.e(ot);}finally{vt.f();}})(h,l,o),h.join(`
`)};}},n={},c=(function m(d){var y=n[d];if(y!==void 0)return y.exports;var T=n[d]={exports:{}};return r[d].call(T.exports,T,T.exports,m),T.exports})(73);return c})()));})(me)),me.exports}var Ln=Rn();function gr(e,t){const r=Ln.parse(e);if(r.isMasterPlaylist)return {isMaster:true,variants:On(r,t)};const n=r,c=Pn(n,t);return {isMaster:false,segments:c.segs,mediaSeq:c.mediaSeq,endList:c.endList,targetDuration:n.targetDuration}}function On(e,t){const r=[];for(const n of e.variants){if(!n.uri)continue;const c=n.resolution,m=c?.width??null,d=c?.height??null;r.push({url:ee(n.uri,t),res:m&&d?`${m}x${d}`:null,w:m,h:d,peak:n.bandwidth??null,avg:n.averageBandwidth??null,codecs:n.codecs??null});}return r}function tr(e,t){if(!e||typeof e.length!="number")return {header:null,next:t};const r=typeof e.offset=="number"?e.offset:t,n=r+e.length-1;return {header:`bytes=${r}-${n}`,next:n+1}}function Pn(e,t){const r=[];let n=0,c=null;for(let m=0;m<e.segments.length;m++){const d=e.segments[m];let y=null;if(d.byterange){const P=tr(d.byterange,n);y=P.header,n=P.next;}else n=0;let T=null,A=false;if(d.map?.uri){const P=ee(d.map.uri,t);let k=null;d.map.byterange&&(k=tr(d.map.byterange,0).header),T={uri:P,rangeHeader:k};const v=`${P}|${k||""}`;A=v!==c,A&&(c=v);}let O=null;d.key?.method&&d.key.method!=="NONE"&&(O={method:String(d.key.method).toUpperCase(),uri:d.key.uri?ee(d.key.uri,t):null,iv:d.key.iv?.toString()??null}),r.push({uri:ee(d.uri,t),dur:d.duration||0,range:y,key:O,map:T,needMap:A});}return {segs:r,mediaSeq:e.mediaSequenceBase||0,endList:e.endlist??false}}function Cn(e){let t=true,r=0;const n=new Set;for(const c of e.segs){if(c.range){const m=ve(c.range);!m||m.end==null?t=false:r+=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(!n.has(m)){n.add(m);const d=ve(c.map.rangeHeader);!d||d.end==null?t=false:r+=d.end-d.start+1;}}else t=false;}return t?r:null}function Dn(e){return e.reduce((t,r)=>t+r.dur,0)}function vr(e){return e.length===0?false:e.some(t=>t.map)||/\.m4s(\?|$)/i.test(e[0].uri)}function Xn(e){return e.some(t=>t.key?.method==="AES-128")}const xn=new fr({concurrency:2}),ge=new Set;async function Te(e,t,r){const n=await mr(e),c=gr(n,e);if(c.isMaster&&c.variants){const d=or(c.variants)[0],y=c.variants.length,A=[`${y} ${y===1?"quality":"qualities"}`];return d?.res?A.push(`up to ${d.res}`):d?.h&&A.push(`up to ${d.h}p`),{label:A.join(" • "),hlsType:"master",variantCount:y,variants:c.variants,bestVariant:d,enriched:true}}if(c.segments&&c.segments.length>0){const m=c.segments,d=m.length,y=Dn(m),T=c.endList??false,A=Cn({segs:m,mediaSeq:c.mediaSeq??0}),O=r?.res??lr(e),P=vr(m),k=Xn(m);return {label:sr({resolution:O,duration:y,size:A}),sublabel:jr(d,P),hlsType:"media",duration:y,segCount:d,resolution:O,isVod:T,isFmp4:P,encrypted:k,isLive:!T,size:A??null,enriched:true}}return {label:"Empty or Invalid",hlsType:"invalid",enriched:true}}async function Mn(e){try{const t=await Te(e.url);return Object.assign(e,t),!0}catch(t){return console.error("[SG] Enrichment failed:",t),e.label="Parse Error",e.hlsType="error",e.enriched=true,false}}async function Er(e){if(!e||e.enriched||e.enriching)return false;e.enriching=true;const t=new Promise((r,n)=>setTimeout(()=>n(new Error("Timeout")),Z.ENRICH_TIMEOUT));try{return e._enrichPromise=Promise.race([Mn(e),t]),await e._enrichPromise,!0}catch(r){const n=r;return console.error("[SG] enrichItem error:",n),e.label=n.message==="Timeout"?"Timeout":"Parse Error",e.hlsType="error",e.enriched=true,false}finally{e.enriching=false,e._enrichPromise=null;}}function yr(e,t){ge.has(e.url)||(ge.add(e.url),xn.add(async()=>{try{e&&e.kind==="hls"&&!e.enriched&&(await Er(e),t?.());}finally{ge.delete(e.url);}}));}async function kn(e){return e._enrichPromise?(await e._enrichPromise,e.enriched&&e.hlsType!=="error"&&e.hlsType!=="invalid"):Er(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,r){this.handlers.has(t)||this.handlers.set(t,new Set),this.handlers.get(t).add(r);}off(t,r){const n=this.handlers.get(t);n&&(n.delete(r),n.size===0&&this.handlers.delete(t));}send(t,r={},n=window.top){try{const c={type:t,payload:r};n.postMessage(c,"*");}catch(c){console.error("[SG] Failed to send message:",t,c);}}sendToTop(t,r={}){window.top&&this.send(t,r,window.top);}handleMessage(t){const r=t.data;if(!r||typeof r!="object"||!r.type||t.source===window)return;const n=this.handlers.get(r.type);n&&n.forEach(c=>{try{c(r.payload||{},t.source);}catch(m){console.error("[SG] Error in message handler:",m);}});}}const be=new Map;function Un(e){ct.get().sendToTop("SG_DETECT",{item:_r(e)});}function _n(e,t){be.set(e,t);}function Fn(e,t){const r=be.get(e);r&&(be.delete(e),r(t));}function Yn(){ct.get().init(),console.log("[SG] Messaging initialized");}function Vn(e){const t=(e||"").replace(/^0x/i,"").replace(/[^0-9a-f]/gi,"");if(t.length===0)return new Uint8Array(0);const n=(t.length%2===0?t:"0"+t).match(/.{1,2}/g);return n?new Uint8Array(n.map(c=>parseInt(c,16))):new Uint8Array(0)}function Gn(e){let t=BigInt(e>>>0);const r=new Uint8Array(16);for(let n=15;n>=0;n--)r[n]=Number(t&0xffn),t>>=8n;return r}async function Bn(e,t,r){const n=await crypto.subtle.importKey("raw",t,{name:"AES-CBC"},false,["decrypt"]);return crypto.subtle.decrypt({name:"AES-CBC",iv:r},n,e)}const oe={MAX_BUFFER_SIZE:100*1024*1024,MAX_FILE_SIZE:1.9*1024*1024*1024,URL_REVOKE_DELAY:6e4},nt={info:e=>console.log(`[SG] ${e}`),warn:(e,...t)=>console.warn(`[SG] ${e}`,...t),error:(e,...t)=>console.error(`[SG] ${e}`,...t)},jn=(e,t=oe.URL_REVOKE_DELAY)=>{setTimeout(()=>URL.revokeObjectURL(e),t);},Tr=e=>new Error(`Failed to save file: ${e.message}`),br=e=>e.abort().catch(()=>{}),Ie=(e,t)=>e.removeEntry(t).catch(()=>{}),zn=(e,t="")=>e.split(".").pop()||t,Hn=(e,t)=>{const r=e.lastIndexOf(".");return r===-1?`${e}.part${t}`:`${e.slice(0,r)}.part${t}${e.slice(r)}`};class De{closed=false;aborted=false;get isClosed(){return this.closed}get isAborted(){return this.aborted}setClosed(){this.closed=true;}setAborted(){this.aborted=true;}assertWritable(t=false){if(this.aborted)throw new Error("Writer was aborted");if(this.closed){if(t)return nt.warn("Attempted to write after close"),false;throw new Error("Writer was closed")}return true}}function qn(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 $n(e,t){return new Promise(r=>{const n=document.createElement("a");n.href=e,n.download=t,n.style.display="none",document.body.appendChild(n),n.click(),document.body.removeChild(n),setTimeout(()=>{r();},500);})}function Kn(e,t,r){return new Promise((n,c)=>{GM_download({url:e,name:t,saveAs:true,onload:()=>{r?.(),n();},onerror:m=>{c(new Error(qn(m?.error,m?.details)));},ontimeout:()=>{c(new Error("Download timed out"));}});})}async function Ir(e,t,r){try{typeof GM_download=="function"?await Kn(e,t,r):(nt.info("GM_download unavailable, using anchor fallback"),await $n(e,t),r?.());}finally{jn(e);}}async function Wn(e,t){if(typeof window.showSaveFilePicker!="function"||window.isSecureContext===false)return null;try{const r=zn(e,"mp4"),c=await(await window.showSaveFilePicker({suggestedName:e,types:[{description:"Video file",accept:{[t]:[`.${r}`]}}]})).createWritable(),m=new De;return {async write(d){m.assertWritable(!0)&&await c.write(d);},async close(){if(m.isAborted)throw new Error("Writer was aborted");if(!m.isClosed){m.setClosed();try{await c.close(),le(e);}catch(d){throw nt.error("Native close error:",d),Tr(d)}}},abort(){m.isClosed||m.isAborted||(m.setAborted(),br(c));}}}catch(r){const n=r;if(n.name==="AbortError")throw r;return nt.warn("File System Access API failed, using fallback:",n.message),null}}const Qn=1440*60*1e3;async function Zn(e){try{const t=Date.now(),r=[];for await(const[n,c]of e.entries())if(c.kind==="file"&&n.endsWith(".tmp")&&n.startsWith("sg_download_")){const m=n.split("_");if(m.length>=3){const d=parseInt(m[2],10);!isNaN(d)&&t-d>Qn&&(nt.info(`Cleaning up stale temp file: ${n}`),r.push(Ie(e,n)));}}r.length>0&&await Promise.all(r);}catch(t){nt.warn("Failed to cleanup stale temp files:",t);}}async function Jn(e,t){if(!navigator.storage?.getDirectory)return null;try{const r=await navigator.storage.getDirectory();Zn(r).catch(()=>{});const n=`sg_download_${Date.now()}_${Math.random().toString(36).slice(2)}.tmp`,c=await r.getFileHandle(n,{create:!0}),m=await c.createWritable(),d=new De;return {async write(y){d.assertWritable(!0)&&await m.write(y);},async close(){if(d.isAborted)throw new Error("Writer was aborted");if(!d.isClosed){d.setClosed();try{await m.close();const y=await c.getFile(),T=URL.createObjectURL(y);await Ir(T,e,()=>{le(e);}),setTimeout(()=>{Ie(r,n);},oe.URL_REVOKE_DELAY+5e3);}catch(y){throw nt.error("OPFS close error:",y),Tr(y)}}},abort(){d.isClosed||d.isAborted||(d.setAborted(),br(m),Ie(r,n));}}}catch(r){return nt.warn("OPFS initialization failed:",r),null}}function ti(e,t){const r=[];let n=[],c=0,m=0,d=1;const y=new De,T=()=>{if(c===0)return;const P=new Blob(n,{type:t});r.push(P),n=[],c=0;},A=()=>{n=[],c=0,r.length=0,m=0;},O=async P=>{if(T(),r.length===0&&!P)return;r.length===0&&P&&d===1&&nt.warn("Saving empty file");let k=e;(d>1||!P&&d===1)&&(k=Hn(e,d)),nt.info(`Saving part ${d}: ${k}, Size: ${(m/1024/1024).toFixed(2)} MB`);const v=new Blob(r,{type:t});r.length=0,n=[],c=0,m=0;const w=URL.createObjectURL(v);await Ir(w,k,()=>{P&&le(e);});};return {async write(P){y.assertWritable(true)&&(m+P.length>oe.MAX_FILE_SIZE&&(nt.warn(`File part ${d} limit reached (~1.9GB). Splitting file...`),await O(false),d++),n.push(P),c+=P.length,m+=P.length,c>=oe.MAX_BUFFER_SIZE&&(T(),r.length%5===0&&nt.info(`Part ${d} Buffer: ${r.length} blobs, Size: ${(m/1024/1024).toFixed(2)} MB`)));},async close(){if(y.isAborted)throw new Error("Writer was aborted");y.isClosed||(y.setClosed(),await O(true));},abort(){y.isClosed||y.isAborted||(y.setAborted(),A());}}}async function ei(e,t){try{const n=await Wn(e,t);if(n)return nt.info("Using native File System Access API"),n}catch(n){if(n.name==="AbortError")throw nt.info("User cancelled file picker"),n;nt.warn("Native writer creation failed:",n);}const r=await Jn(e);return r?(nt.info("Using OPFS writer"),r):(nt.info("Using blob fallback for download"),ti(e,t))}const ri=100,ni=50,ii=50;class er{cache=new Map;inflight=new Map;async fetch(t,r,n){if(n?.aborted)throw new Dt(new Error("Aborted"));const c=await nr(this.cache,this.inflight,t,r,ri);if(n?.aborted)throw new Dt(new Error("Aborted"));return c}clear(){this.cache.clear(),this.inflight.clear();}}class ai{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>=ni}enqueue(t,r){this.buffers.set(t,r),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(r){throw this.writeError=r,r}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 oi{constructor(t,r){this.total=t,this.onUpdate=r;}inProgress=new Map;rafId=0;_done=0;byteDone=0;avgLen=0;get done(){return this._done}get averageSize(){return this.avgLen}setProgress(t,r,n){this.inProgress.set(t,{loaded:r,total:n}),this.scheduleUpdate();}markComplete(t,r){this.inProgress.delete(t),this._done++,this.byteDone+=r,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(),r=(this._done+t)/this.total*100;this.onUpdate(r,this._done,this.total);}));}calculatePartial(){let t=0;return this.inProgress.forEach(({loaded:r,total:n})=>{n>0?t+=Math.min(1,r/n):this.avgLen>0&&(t+=Math.min(1,r/this.avgLen));}),t}}class si{constructor(t){this.mediaSeq=t;}keyCache=new er;mapCache=new er;async fetch(t,r,n,c){this.validateEncryption(t);const[m,d]=await Promise.all([this.fetchKey(t,n),this.fetchMap(t,n)]),y=await this.download(t,n,c),T=m?await this.decrypt(y,m,t,r):y;return this.prependMap(new Uint8Array(T),d)}validateEncryption(t){if(t.key?.method&&t.key.method!=="AES-128")throw new Dt(new Error(`Unsupported key method: ${t.key.method}`))}async download(t,r,n){const c=t.range?{Range:t.range}:{};try{return await pe(t.uri,c,Z.REQUEST_TIMEOUT,m=>n(m.loaded,m.total),r)}catch(m){throw r.aborted?new Dt(new Error("Aborted")):m}}async fetchKey(t,r){return !t.key||t.key.method!=="AES-128"||!t.key.uri?null:this.keyCache.fetch(t.key.uri,async()=>{const n=await pe(t.key.uri,{},Z.REQUEST_TIMEOUT,void 0,r);return new Uint8Array(n)},r)}async fetchMap(t,r){if(!t.needMap||!t.map?.uri)return null;const n=`${t.map.uri}|${t.map.rangeHeader||""}`;return this.mapCache.fetch(n,async()=>{const c=t.map.rangeHeader?{Range:t.map.rangeHeader}:{},m=await pe(t.map.uri,c,Z.REQUEST_TIMEOUT,void 0,r);return new Uint8Array(m)},r)}async decrypt(t,r,n,c){const m=n.key.iv?Vn(n.key.iv):Gn(this.mediaSeq+c);return Bn(t,r,m)}prependMap(t,r){if(!r?.length)return t;const n=new Uint8Array(r.length+t.length);return n.set(r,0),n.set(t,r.length),n}clear(){this.keyCache.clear(),this.mapCache.clear();}}class li{constructor(t,r,n,c,m){this.segments=t,this.onProgress=c,this.onComplete=m,this.queue=new fr({concurrency:Z.CONCURRENCY}),this.writer=new ai(n),this.progress=new oi(t.length,c),this.fetcher=new si(r);}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 r=new AbortController;this.controllers.set(t,r);try{await hr(async()=>{if(this.canceled)throw new Dt(new Error("Canceled"));const n=await this.fetcher.fetch(this.segments[t],t,r.signal,(c,m)=>{this.progress.setProgress(t,c,m);});this.writer.enqueue(t,n),this.progress.markComplete(t,n.length);},{retries:Z.RETRIES,signal:r.signal,onFailedAttempt:({error:n,attemptNumber:c})=>{this.canceled||console.warn(`[SG] Segment ${t} failed (attempt ${c}): ${n.message}`);}});}catch(n){this.handleSegmentError(t,n);}finally{this.controllers.delete(t);}}async waitForBackpressure(){for(;this.writer.shouldThrottle()&&!this.canceled;)await new Promise(t=>setTimeout(t,ii));}handleSegmentError(t,r){this.progress.clear(t),!(this.canceled||r instanceof Dt)&&(console.error(`[SG] Segment ${t} fatal error:`,r),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 r=this.writer.error?"Write failed":this.canceled?"Canceled":"Incomplete download";this.onComplete(!1,r);}}catch(r){console.error("[SG] Finalize error:",r),this.onComplete(false,"Finalization failed");}finally{this.cleanup();}}cleanup(){this.fetcher.clear();}}async function ci(e,t,r,n){const c=e.segs.length;console.log("[SG] Starting segment download:",{filename:t,segments:c});const m=r?"video/mp4":"video/mp2t";let d;try{d=await ei(t,m);}catch(T){if(T.name==="AbortError"){n.remove();return}throw T}const y=new li(e.segs,e.mediaSeq,d,(T,A,O)=>{n.update(T,`${A}/${O}`);},(T,A)=>{T?(n.update(100,""),n.done(true)):n.done(false,A);});n.setOnStop(()=>y.togglePause()?"paused":"resumed"),n.setOnCancel(()=>{y.cancel(),n.remove();}),await y.start();}async function we(e,t){console.log("[SG] Direct download:",e);const r=ut.get(e),n=ir(e,r?.type),c=ar({title:document.title,ext:n});let m=e,d=()=>{};r?.blob&&(m=URL.createObjectURL(r.blob),d=()=>URL.revokeObjectURL(m));const y=t.createCard(c,e);y.setOnCancel(()=>{d(),y.remove();}),GM_download({url:m,name:c,saveAs:true,onprogress:T=>{T.lengthComputable?y.update(T.loaded/T.total*100,`${qt(T.loaded)}/${qt(T.total)}`):y.update(0,qt(T.loaded));},onload:()=>{y.update(100,""),y.done(true),d(),le(c);},onerror:T=>{const A=T?.error||"unknown";console.error("[SG] Download error:",{error:A,url:e}),y.done(false,A==="not_succeeded"?"Save failed":A),d();},ontimeout:()=>{y.done(false,"Timeout"),d();}});}async function ne(e,t,r){console.log("[SG] HLS download:",e);const n=await Te(e);let c=e,m=t;if(n.hlsType==="master"&&n.variants&&n.variants.length>0){const v=or(n.variants);if(v.length===0)throw new Error("No variants found");const w=[];for(const f of v){let b;try{b=await Te(f.url,void 0,f);}catch{b={label:sr({resolution:f.res}),hlsType:"error"};}w.push({url:f.url,kind:"variant",label:b.label||"Unknown",sublabel:b.sublabel||null,size:b.size??null,type:null,origin:document.location.origin,enriched:true,enriching:false,hlsType:"media",isLive:false,encrypted:false,variant:f});}const S=await r.pickVariant(w);if(!S)return;m=S.variant??null,c=S.url;}const d=await mr(c),y=gr(d,c);if(!y.segments||y.segments.length===0)throw new Error("Invalid playlist: no segments");const T={segs:y.segments,mediaSeq:y.mediaSeq??0,endList:y.endList??false},A=vr(T.segs),O=A?"mp4":"ts",P=ar({title:document.title,ext:O,quality:m?.res}),k=r.createCard(P,e,T.segs.length);await ci(T,P,A,k);}async function ui(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 ne(e.url,null,t);if(e.kind==="video")return we(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 kn(e);}catch(r){throw new Error(`Failed to analyze stream: ${r.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 we(e.url,t);if(e.kind==="variant")return ne(e.url,e.variant??null,t);if(e.kind==="hls")return ne(e.url,null,t)}const di='@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{color-scheme:dark;forced-color-adjust:none;--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}}',fi=di,pt={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>`},Se=(...e)=>e.filter(Boolean).join(" ");function B(e,t,r){const n=document.createElement(e);if(t)for(const[c,m]of Object.entries(t))m==null||m===false||n.setAttribute(c,m===true?"":String(m));if(r)if(typeof r=="string")n.innerHTML=r;else for(const c of r)n.append(typeof c=="string"?document.createTextNode(c):c);return n}async function hi(e,t){try{await navigator.clipboard.writeText(e);}catch{const n=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(n),n.select();const d=document.execCommand("copy");if(n.remove(),!d)return false}const r=t.innerHTML;return t.innerHTML=pt.check,t.classList.add("copied"),setTimeout(()=>{t.innerHTML=r,t.classList.remove("copied");},1200),true}let St=null,rr=null,zt=null;function pi(e,t,r){St||(St=B("button",{class:"sg-fab",type:"button"}),rr=B("span",{class:"sg-fab-icon"},pt.download),zt=B("span",{class:"sg-badge"}),St.append(rr,zt),St.addEventListener("click",n=>{n.preventDefault(),n.stopPropagation(),r();}),e.appendChild(St)),St.className=Se("sg-fab",t.show&&"show",t.busy&&"busy",t.idle&&"idle"),St.disabled=t.busy,St.title=`Download media (${t.count})`,zt&&(zt.className=Se("sg-badge",t.count>0&&"show"),zt.textContent=t.count>99?"99+":String(t.count));}function mi(e,t,r,n,c,m,d,y,T){if(e.innerHTML="",!t)return;const A=B("div",{class:"sg-modal show"});A.addEventListener("click",w=>w.target===A&&d());const O=B("div",{class:"sg-card",role:"dialog","aria-modal":"true"}),P=B("div",{class:"sg-card-head"});P.append(Object.assign(B("div",{class:"sg-card-title"}),{textContent:r}),gi(pt.close,"Close (Esc)",d)),O.appendChild(P);const k=B("div",{class:"sg-card-body"});if(c&&n.some(w=>w.size!=null)){const w=B("label",{class:"sg-option"}),S=B("input",{type:"checkbox",checked:m||null});S.addEventListener("change",()=>T(S.checked)),w.append(S," Exclude small (< 1MB)"),k.appendChild(w);}const v=B("div",{class:"sg-list"});if(n.length===0){const w=B("div",{class:"sg-empty"});w.innerHTML="No media detected.<br><small>Play a video to detect streams.</small>",v.appendChild(w);}else n.forEach(w=>v.appendChild(vi(w,y)));k.appendChild(v),O.appendChild(k),A.appendChild(O),e.appendChild(A);}function gi(e,t,r){const n=B("button",{class:"sg-btn",title:t,type:"button"},e);return n.addEventListener("click",c=>{c.preventDefault(),r();}),n}function vi(e,t){const r=B("div",{class:"sg-item",role:"button",tabindex:"0"}),n=B("div",{class:"sg-item-top"}),c=B("div",{class:"sg-item-title"});c.appendChild(Object.assign(B("span"),{textContent:e.label})),Ei(e).forEach(y=>c.appendChild(y)),n.appendChild(c),e.size&&n.appendChild(Object.assign(B("span",{class:"sg-item-size"}),{textContent:qt(e.size)}));const m=B("button",{class:"sg-copy-btn",title:"Copy URL",type:"button"},pt.copy);m.addEventListener("click",y=>{y.stopPropagation(),hi(e.url,m);}),n.appendChild(m),r.appendChild(n),e.sublabel&&r.appendChild(Object.assign(B("div",{class:"sg-item-sub"}),{textContent:e.sublabel}));const d=B("div",{class:"sg-item-url",title:e.url});return d.textContent=e.url.length>60?e.url.slice(0,60)+"…":e.url,r.appendChild(d),r.addEventListener("click",y=>{y.target.closest(".sg-copy-btn")||t(e);}),r.addEventListener("keydown",y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),t(e));}),r}function Ei(e){const t=[],r=(n,c)=>{const m=B("span",{class:`sg-badge-type ${c}`});m.textContent=n,t.push(m);};return e.kind==="hls"?(e.hlsType==="error"||e.hlsType==="invalid"?r(e.hlsType==="error"?"Error":"Invalid","error"):e.hlsType==="master"?r("Master","master"):e.hlsType==="media"?r("Video","video"):e.enriching?r("...","analyzing"):r("HLS","video"),e.isLive&&r("Live","live"),e.encrypted&&r("🔒","encrypted")):e.kind==="video"?r("Direct","direct"):e.kind==="variant"&&r("Quality","video"),e.isRemote&&r("iFrame","remote"),t}class yi{constructor(t,r,n,c=0){this.container=t,this.title=r,this.src=n,this.status=c?`${c} segments`:"Starting...",this.el=B("div",{class:"sg-progress",id:`sg-progress-${Le()}`});const m=B("div",{class:"sg-progress-row"});m.appendChild(Object.assign(B("div",{class:"sg-progress-name",title:n}),{textContent:r}));const d=B("div",{class:"sg-progress-ctrls"});this.minBtn=B("button",{class:"sg-btn sg-btn-sm btn-minimize",title:"Minimize",type:"button"},pt.minimize),this.minBtn.addEventListener("click",()=>this.toggleMinimize()),d.appendChild(this.minBtn);const y=B("button",{class:"sg-btn sg-btn-sm",title:"Cancel",type:"button"},pt.cancel);y.addEventListener("click",()=>this.onCancelFn?.()),d.appendChild(y),m.appendChild(d),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?pt.maximize:pt.minimize,this.minBtn.title=this.minimized?"Expand":"Minimize",this.updateClass();}updateClass(){this.el.className=Se("sg-progress",this.minimized&&"minimized",this.paused&&"paused");}update(t,r=""){this.percent=Math.max(0,Math.min(100,t)),r&&(this.status=r),this.fillEl.style.setProperty("width",`${this.percent}%`,"important"),this.statusEl.textContent=this.status,this.percentEl.textContent=`${Math.floor(this.percent)}%`;}done(t=true,r){this.fillEl.style.width="100%",this.fillEl.classList.add(t?"success":"error"),this.statusEl.textContent=r||(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"},pt.pause),this.pauseBtn.addEventListener("click",()=>{if(!this.onStop)return;const r=this.onStop();this.paused=r==="paused",this.pauseBtn.innerHTML=this.paused?pt.play:pt.pause,this.pauseBtn.title=this.paused?"Resume":"Pause",this.updateClass();}),this.minBtn.before(this.pauseBtn));}setOnCancel(t){this.onCancelFn=t;}}function Ti(e,t,r,n=0){return new yi(e,t,r,n)}let ht=false,At=null,Ft=null,Yt=null;const Xt={show:false,busy:false,idle:false,count:0},ft={show:false,title:"Select Media",items:[]};let Ae=null,Rt=null,wr=null,Sr=null;function Xe(){if(!Z.IS_TOP||ht)return;if(!document.body){const n=document.readyState==="loading"?"DOMContentLoaded":"load";window.addEventListener(n,()=>Xe(),{once:true});return}const e=document.createElement("div");e.id="sg-host",e.setAttribute("data-darkreader-ignore","true"),e.classList.add("darkreader"),Object.assign(e.style,{position:"fixed",top:"0",left:"0",width:"0",height:"0",zIndex:"2147483647",pointerEvents:"none",colorScheme:"dark"});const t=e.attachShadow({mode:"open"}),r=document.createElement("style");r.classList.add("darkreader"),r.textContent=fi,t.append(r),At=document.createElement("div"),At.id="sg-fab-container",At.style.pointerEvents="auto",Ft=document.createElement("div"),Ft.id="sg-modal-container",Ft.style.pointerEvents="auto",Yt=document.createElement("div"),Yt.id="sg-toast-container",Yt.className="sg-toast",t.append(At,Ft,Yt),document.documentElement.append(e),At.addEventListener("mouseenter",Me),At.addEventListener("mouseleave",xe),document.addEventListener("keydown",n=>n.key==="Escape"&&ft.show&&ke()),ht=true,gt();}function Kt(){return Z.IS_TOP?(ht||Xe(),ht):false}function gt(){if(!ht||!At||!Ft)return;pi(At,Xt,Ar);const e=ft.show?bi():[];mi(Ft,ft.show,ft.title,e,Rt?.filterable??true,et.excludeSmall,ke,wi,Si);}function se(){Z.IS_TOP&&(Xt.show=true,Xt.count=et.validCount,Kt()&&(gt(),xe()));}function Ne(e){Xt.busy=e,ht&>();}function $t(){Xt.count=et.validCount,ht&>();}function xe(){Me(),Ae=setTimeout(()=>{Xt.idle=true,ht&>();},Z.UI_IDLE_MS);}function Me(){Xt.idle=false,Ae&&clearTimeout(Ae),ht&>();}function bi(){const e=ft.items.length>0?ft.items:et.getFilteredItems();return et.excludeSmall?e.filter(t=>t.size==null||t.size>=Z.SMALL_BYTES):e}function Ii(e="Select Media",t){Kt()&&(ft.show=true,ft.title=e,ft.items=t??[],gt());}function ke(){ft.show=false,ft.items=[],ht&>(),Rt&&(Rt.resolve(null),Rt=null);}function wi(e){ke(),Rt?(Rt.resolve(e),Rt=null):Sr?.(e);}function Si(e){et.setExcludeSmall(e),gt();}function Ar(){ht&&(Me(),xe(),wr?.());}function Ue(e,{title:t="Select Media",filterable:r=true}={}){return Kt()?new Promise(n=>{Rt={resolve:n,title:t,filterable:r},Ii(t,e);}):Promise.resolve(null)}function Nr(e,t,r=0){return !Kt()||!Yt?{update(){},done(){},remove(){},setOnStop(){},setOnCancel(){}}:Ti(Yt,e,t,r)}function Ai(){Z.IS_TOP&&(GM_registerMenuCommand("Show Download Panel",()=>{Kt(),se(),Ar();}),GM_registerMenuCommand("Clear Cache",()=>{et.clear(),$t(),GM_notification({text:"Cache cleared",title:"StreamGrabber",timeout:2e3});}));}function Ni(e){e.onFabClick&&(wr=e.onFabClick),e.onItemSelected&&(Sr=e.onItemSelected);}function Re(){Z.IS_TOP&&($t(),ht&&ft.show&>());}class Ri{id;bus;onStopFn;onCancelFn;constructor(t,r){this.id=Le(),this.bus=ct.get(),this.bus.sendToTop("SG_PROGRESS_START",{id:this.id,title:t,src:r}),this.handleControl=this.handleControl.bind(this),this.bus.on("SG_CMD_CONTROL",this.handleControl);}handleControl(t){if(t.id!==this.id)return;const r=t.action;r==="stop"&&this.onStopFn?this.onStopFn():r==="cancel"&&this.onCancelFn&&this.onCancelFn();}update(t,r){this.bus.sendToTop("SG_PROGRESS_UPDATE",{id:this.id,p:t,txt:r||""});}done(t=true,r=""){this.bus.sendToTop("SG_PROGRESS_DONE",{id:this.id,ok:t,msg:r}),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 _t=new Map;function Li(){console.log(`[SG] StreamGrabber v${GM_info?.script?.version||"2.1.3"} initializing...`,{isTop:Z.IS_TOP,readyState:document.readyState,href:location.href.slice(0,100)}),Ni({onFabClick:Pi,onItemSelected:Rr}),Z.IS_TOP&&(Xe(),Ai()),Yn(),Oi(),an(e=>{Z.IS_TOP?(console.log("[SG] Detected:",e.kind,e.url.slice(0,60)),se(),$t(),e.kind==="hls"&&yr(e,()=>Re())):(console.log("[SG] [iframe] Forwarding detection:",e.kind,e.url.slice(0,60)),Un(e));}),et.events.itemAdded.subscribe(()=>{se(),$t();}),et.events.updated.subscribe(()=>{Re();}),on(),console.log("[SG] Initialization complete",{isTop:Z.IS_TOP});}function Oi(){const e=ct.get();Z.IS_TOP?(e.on("SG_DETECT",(t,r)=>{const n=t.item;n&&(n.remoteWin=r,n.isRemote=true,console.log("[SG] Received detection from iframe:",n.kind,n.url.slice(0,60)),et.addItem(n)&&(se(),$t(),n.kind==="hls"&&yr(n,()=>Re())));}),e.on("SG_PROGRESS_START",(t,r)=>{const{id:n,title:c,src:m}=t;if(!_t.has(n))try{const d=Nr(c,m);d.setOnStop(()=>(ct.get().send("SG_CMD_CONTROL",{id:n,action:"stop"},r),"paused")),d.setOnCancel(()=>{ct.get().send("SG_CMD_CONTROL",{id:n,action:"cancel"},r),d.remove(),_t.delete(n);}),_t.set(n,d);}catch(d){console.error("[SG] Failed to create remote progress card:",d);}}),e.on("SG_PROGRESS_UPDATE",t=>{const{id:r,p:n,txt:c}=t;_t.get(r)?.update(n,c);}),e.on("SG_PROGRESS_DONE",t=>{const{id:r,ok:n,msg:c}=t,m=_t.get(r);m&&(m.done(n,c),setTimeout(()=>_t.delete(r),2500));}),e.on("SG_CMD_PICK",(t,r)=>{const{id:n,items:c,title:m}=t;Ue(c,{title:m,filterable:true}).then(d=>{ct.get().send("SG_CMD_PICK_RESULT",{id:n,item:d},r);});})):(e.on("SG_CMD_DOWNLOAD",t=>{const{url:r,kind:n,variant:c}=t;console.log("[SG] [iframe] Received download command:",{url:r,kind:n}),Ci(r,n,c);}),e.on("SG_CMD_PICK_RESULT",t=>{const{id:r,item:n}=t;Fn(r,n);}));}async function Pi(){Ne(true);try{const e=et.getFilteredItems();if(e.length===0){alert("No media detected yet. Try playing a video first.");return}const t=await Ue(e,{title:"Select Media",filterable:!0});if(!t)return;await Rr(t);}catch(e){cr(e);}finally{Ne(false);}}async function Rr(e){try{await ui(e,{createCard:Nr,pickVariant:t=>Ue(t,{title:"Select Quality",filterable:!0}),setBusy:Ne});}catch(t){cr(t);}}async function Ci(e,t,r){console.log("[SG] [iframe] Received download command:",{url:e,kind:t});try{const n=(c,m)=>new Ri(c,m);t==="hls"?await ne(e,r,{createCard:n,pickVariant:async c=>new Promise(m=>{const d=Le();_n(d,m),ct.get().sendToTop("SG_CMD_PICK",{id:d,items:c,title:"Select Quality"});}),setBusy:()=>{}}):t==="video"&&await we(e,{createCard:n,pickVariant:async()=>null,setBusy:()=>{}});}catch(n){console.error("[SG] [iframe] Download error:",n);}}Li();
})();