Lightweight HLS/Video downloader. Pause/Resume. AES-128. fMP4. Mobile + Desktop.
// ==UserScript==
// @name StreamGrabber
// @namespace https://github.com/streamgrabber-lite
// @version 2.4.0
// @author StreamGrabber
// @description Lightweight HLS/Video downloader. Pause/Resume. AES-128. fMP4. Mobile + Desktop.
// @license MIT
// @match *://*/*
// @exclude *://*.gov/*
// @exclude *://*.gov.*/*
// @exclude *://*.mil/*
// @exclude *://*.mil.*/*
// @exclude *://*.int/*
// @exclude *://*.edu/*
// @exclude *://*.edu.*/*
// @exclude *://*.ac.*/*
// @exclude *://*.nic.in/*
// @exclude *://localhost/*
// @exclude *://127.0.0.1/*
// @exclude *://[::1]/*
// @exclude *://10.*.*.*/*
// @exclude *://192.168.*.*/*
// @exclude *://172.1[6-9].*/*
// @exclude *://172.2[0-9].*/*
// @exclude *://172.3[0-1].*/*
// @exclude *://*.google.*/*
// @exclude *://*.bing.com/*
// @exclude *://*.duckduckgo.com/*
// @exclude *://*.baidu.com/*
// @exclude *://*.yahoo.com/*
// @exclude *://*.yandex.*/*
// @exclude *://*.facebook.com/*
// @exclude *://*.instagram.com/*
// @exclude *://*.x.com/*
// @exclude *://*.twitter.com/*
// @exclude *://*.linkedin.com/*
// @exclude *://*.tiktok.com/*
// @exclude *://*.reddit.com/*
// @exclude *://*.redd.it/*
// @exclude *://*.pinterest.com/*
// @exclude *://*.snapchat.com/*
// @exclude *://*.tumblr.com/*
// @exclude *://*.threads.net/*
// @exclude *://*.bluesky.social/*
// @exclude *://*.mastodon.social/*
// @exclude *://*.youtube.*/*
// @exclude *://*.twitch.tv/*
// @exclude *://*.netflix.com/*
// @exclude *://*.disneyplus.com/*
// @exclude *://*.hulu.com/*
// @exclude *://*.hbomax.com/*
// @exclude *://*.max.com/*
// @exclude *://*.paramountplus.com/*
// @exclude *://*.peacocktv.com/*
// @exclude *://*.primevideo.com/*
// @exclude *://*.spotify.com/*
// @exclude *://*.soundcloud.com/*
// @exclude *://*.deezer.com/*
// @exclude *://*.tidal.com/*
// @exclude *://*.whatsapp.*/*
// @exclude *://*.telegram.*/*
// @exclude *://*.discord.*/*
// @exclude *://*.skype.com/*
// @exclude *://*.chase.com/*
// @exclude *://*.bankofamerica.com/*
// @exclude *://*.wellsfargo.com/*
// @exclude *://*.citibank.com/*
// @exclude *://*.capitalone.com/*
// @exclude *://*.americanexpress.com/*
// @exclude *://*.paypal.com/*
// @exclude *://*.stripe.com/*
// @exclude *://*.venmo.com/*
// @exclude *://*.coinbase.com/*
// @exclude *://*.binance.com/*
// @exclude *://*.fidelity.com/*
// @exclude *://*.vanguard.com/*
// @exclude *://*.schwab.com/*
// @exclude *://*.robinhood.com/*
// @exclude *://*.amazon.*/*
// @exclude *://*.ebay.com/*
// @exclude *://*.target.com/*
// @exclude *://*.walmart.com/*
// @exclude *://*.bestbuy.com/*
// @exclude *://*.etsy.com/*
// @exclude *://*.aliexpress.com/*
// @exclude *://*.alibaba.com/*
// @exclude *://*.shopify.com/*
// @exclude *://*.nytimes.com/*
// @exclude *://*.cnn.com/*
// @exclude *://*.bbc.*/*
// @exclude *://*.reuters.com/*
// @exclude *://*.theguardian.*/*
// @exclude *://*.forbes.com/*
// @exclude *://*.bloomberg.com/*
// @exclude *://*.wsj.com/*
// @exclude *://*.wikipedia.*/*
// @exclude *://*.wikimedia.*/*
// @exclude *://*.coursera.org/*
// @exclude *://*.udemy.com/*
// @exclude *://*.khanacademy.org/*
// @exclude *://*.duolingo.com/*
// @exclude *://*.quora.com/*
// @exclude *://*.github.*/*
// @exclude *://*.gitlab.*/*
// @exclude *://*.stackoverflow.com/*
// @exclude *://*.npmjs.com/*
// @exclude *://*.docker.com/*
// @exclude *://*.git-scm.com/*
// @exclude *://*.atlassian.*/*
// @exclude *://*.jira.com/*
// @exclude *://*.slack.com/*
// @exclude *://*.zoom.*/*
// @exclude *://*.microsoft.com/*
// @exclude *://*.office.com/*
// @exclude *://*.outlook.com/*
// @exclude *://*.live.com/*
// @exclude *://*.notion.so/*
// @exclude *://*.trello.com/*
// @exclude *://*.asana.com/*
// @exclude *://*.monday.com/*
// @exclude *://*.dropbox.com/*
// @exclude *://*.box.com/*
// @exclude *://*.wetransfer.com/*
// @exclude *://*.mega.nz/*
// @exclude *://*.icloud.com/*
// @exclude *://*.speedtest.net/*
// @exclude *://*.canva.com/*
// @exclude *://*.adobe.com/*
// @exclude *://*.figma.com/*
// @exclude *://*.lastpass.com/*
// @exclude *://*.1password.com/*
// @exclude *://*.bitwarden.com/*
// @exclude *://*.dashlane.com/*
// @exclude *://*.okta.com/*
// @exclude *://*.chatgpt.com/*
// @exclude *://*.openai.com/*
// @exclude *://*.claude.ai/*
// @exclude *://*.anthropic.com/*
// @exclude *://*.perplexity.ai/*
// @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},Qt={TEXT_MAX:256,DB_MAX:120,CLEAR_MS:12e4},$e={EXCLUDE_SMALL:"sg_exclude_small"};function xr(e,t){return GM_getValue(e,t)}function Mr(e,t){GM_setValue(e,t);}const ut=new Map;function qe(e){const t=[];for(const[r,n]of ut)e(r,n)&&(ut.delete(r),t.push(r));return t}class Ke{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 kr{items=new Map;watchedVideos=new WeakSet;excludeSmall;_validCount=0;_validCountDirty=true;events={itemAdded:new Ke,updated:new Ke};constructor(){this.excludeSmall=xr($e.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>Qt.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()}filterItems(t){return this.excludeSmall?t.filter(r=>r.size==null||r.size>=Z.SMALL_BYTES):t}getFilteredItems(){return this.filterItems(this.getAllItems())}setExcludeSmall(t){this.excludeSmall=t,Mr($e.EXCLUDE_SMALL,t);}clear(){this.items.clear(),qe(()=>true),this.invalidateCount(),this.events.updated.dispatch();}trim(){this.enforceLimit();const t=Date.now(),r=qe((n,u)=>{const h=t-(u.ts||0);return !!(u.revoked&&h>Qt.CLEAR_MS)});for(const n of r)this.items.has(n)&&(this.items.delete(n),this.invalidateCount());}}const et=new kr;Z.IS_TOP&&(setInterval(()=>et.trim(),Qt.CLEAR_MS),window.addEventListener("pagehide",()=>et.trim()),window.addEventListener("beforeunload",()=>et.trim()));const yt={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},Ur=e=>typeof e=="string"&&yt.http.test(e),Kt=e=>typeof e=="string"&&yt.blob.test(e),_r=e=>yt.m3u8.test(e||""),Fr=e=>yt.video.test(e||""),Yr=e=>yt.segment.test(e||""),Vr=e=>yt.m3u8Type.test(e||""),Gr=e=>yt.videoType.test(e||"")||yt.videoTypeAlt.test(e||"");function oe(e,t){try{return new URL(e,t).href}catch{return e}}const We=["B","KB","MB","GB","TB"];function Wt(e){if(e==null)return "";let t=0,r=e;for(;r>=1024&&t<We.length-1;)r/=1024,t++;const n=r<10&&t>0?1:0;return `${r.toFixed(n)} ${We[t]}`}function Br(e){if(!e||e<=0)return null;const t=Math.floor(e/3600),r=Math.floor(e%3600/60),n=Math.floor(e%60),u=h=>String(h).padStart(2,"0");return t>0?`${t}:${u(r)}:${u(n)}`:`${r}:${u(n)}`}document.createElement("div");function De(){return Math.random().toString(36).slice(2)}const zr=["url","kind","label","sublabel","size","type","origin","pageTitle","enriched","enriching","hlsType","isLive","encrypted","duration","segCount","resolution","isVod","isFmp4","variantCount","variants","bestVariant","variant"];function jr(e){const t={};for(const r of zr)e[r]!==void 0&&(t[r]=e[r]);return t}function be(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 Hr(e,t){if(!e.has(t))return;const r=e.get(t);return e.delete(t),e.set(t,r),r}function $r(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 u=e.keys().next().value;u!==void 0&&e.delete(u);}}function Xe(e,t,r,n,u){const h=Hr(e,r);if(h!==void 0)return Promise.resolve(h);if(t.has(r))return t.get(r);const l=(async()=>{try{const b=await n();return $r(e,r,b,u),b}finally{t.delete(r);}})();return t.set(r,l),l}function qr(e){return (e||"video").replace(/[\\/:*?"<>|]/g,"_").slice(0,120).trim()||"video"}const Kr={webm:"webm",matroska:"mkv",mkv:"mkv",quicktime:"mov",mov:"mov",mp2t:"ts",mpegts:"ts",ogg:"ogg",mp4:"mp4"};function Wr(e){const t=e.toLowerCase();for(const[r,n]of Object.entries(Kr))if(t.includes(r))return n;return "mp4"}function ur(e,t){const r=/(?:\.([a-z0-9]+))([?#]|$)/i.exec(e||"");return r?r[1].toLowerCase():t?Wr(t):"mp4"}function dr(e){const t=qr(e.title||document.title),r=e.quality?`_${e.quality}`:"",n=e.ext||"mp4";return `${t}${r}.${n}`}function xe(e){return [...e].sort((t,r)=>(r.h||0)-(t.h||0)||(r.avg||r.peak||0)-(t.avg||t.peak||0))}function fr(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=Br(e.duration);r&&t.push(r);}return e.size!=null&&t.push(`~${Wt(e.size)}`),e.extra&&t.push(...e.extra),t.length>0?t.join(" • "):"Video Stream"}function Qr(e,t){return `${e} segments • ${t?"fMP4":"TS"}`}function pr(e){if(!e)return null;const t=yt.resolutionCombined.exec(e);if(t){if(t[1]){const n=parseInt(t[1],10),u=t[2],h=t[3];if(u==="x"&&h)return `${n}x${h}`;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 Me(e,t){if(!Kt(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=be(t);return r?e.slice(r.start,r.end==null?e.size:r.end+1):e}function Jr(e,t={}){GM_notification({text:e,title:t.title??"StreamGrabber",timeout:t.timeout??3e3,onclick:t.onclick});}function fe(e){Jr(`Download complete: ${e}`);}function tn(e){return e instanceof Error?e.message:typeof e=="string"?e:String(e)}function hr(e,t){const r=tn(e);alert(r);}let Ie=null;const se=[],ce=new Set;setInterval(()=>{ce.size>0&&ce.clear();},Qt.CLEAR_MS);function en(e){if(Ie=e,se.length>0){const t=[...se];se.length=0,t.forEach(({url:r,metadata:n})=>e(r,n));}}function ke(e){return typeof e!="string"?false:/^\s*#EXTM3U/i.test(e)}function rn(e){const t=window.location.href,r=[/[#?&]ep(?:isode)?[=:](\d+)/i,/\/ep(?:isode)?[-_]?(\d+)/i,/\/e(\d+)(?:[^a-z0-9]|$)/i,/[-_]ep(?:isode)?[-_]?(\d+)/i,/[-_](\d{1,3})(?:[^0-9]|$)/];for(const n of r){const u=t.match(n);if(u?.[1])return `Episode ${u[1]}`}return null}function nn(){const e=document.title,t=rn();return t&&!/episode\s*\d+/i.test(e)?`${e} • ${t}`:e}function Rt(e,t){const r={...t,pageTitle:nn()};Ie?Ie(e,r):se.push({url:e,metadata:r});}function an(){const e=URL.createObjectURL;URL.createObjectURL=function(t){const r=e.call(this,t);try{const n=Date.now();if(t instanceof Blob){const u=t.type||"",h={blob:t,type:u,size:t.size,kind:"other",ts:n};Vr(u)?(h.kind="m3u8",ut.set(r,h),Rt(r)):Gr(u)?(h.kind="video",ut.set(r,h),Rt(r)):/octet-stream|text\/plain|^$/.test(u)&&t.size>0&&t.size<5*1024*1024&&t.slice(0,Math.min(2048,t.size)).text().then(b=>{ke(b)&&(ce.has(r)||(h.kind="m3u8",ut.set(r,h),Rt(r)));}).catch(()=>{});}}catch(n){console.error("[SG] createObjectURL hook error:",n);}return r};}function on(){const e=URL.revokeObjectURL;URL.revokeObjectURL=function(t){try{const r=ut.get(t);r?(r.revoked=!0,r.ts=Date.now()):ce.add(t);}catch{}return e.call(this,t)};}function sn(){const e=window.fetch,t=window.Response.prototype.text;typeof e=="function"&&(window.Response.prototype.text=function(){const r=this;return t.call(this).then(n=>{try{ke(n)&&Rt(r.url);}catch(u){console.error("[SG] Detection error in Response.text:",u);}return n})},window.fetch=function(...r){try{const n=r[0],u=typeof n=="string"?n:n instanceof Request?n.url:n.href;u&&Rt(u);}catch{}return e.apply(this,r)});}function ln(){const e=XMLHttpRequest.prototype.open;XMLHttpRequest.prototype.open=function(t,r,...n){try{const h=typeof r=="string"?r:r?.href;h&&Rt(h);}catch{}const u=e.call(this,t,r,...n);return this.addEventListener("load",()=>{try{if(!this.responseType||this.responseType==="text"){const h=this.responseText,l=typeof r=="string"?r:r?.href;l&&ke(h)&&Rt(l);}}catch{}}),u};}function cn(){try{new PerformanceObserver(t=>{for(const r of t.getEntries())"name"in r&&typeof r.name=="string"&&Rt(r.name);}).observe({entryTypes:["resource"]});}catch{}}let Qe=false;function un(){Qe||(Qe=true,an(),on(),sn(),ln(),cn());}let mr=()=>{};function dn(e){mr=e;}function fn(e){if(et.watchedVideos.has(e))return;et.watchedVideos.add(e);const t=()=>{[e.currentSrc||e.src,...Array.from(e.querySelectorAll("source")).map(u=>u.src)].filter(Boolean).forEach(mr);};["loadstart","loadedmetadata","canplay"].forEach(n=>e.addEventListener(n,t)),t();}function we(){document.querySelectorAll("video").forEach(e=>fn(e));}let me=null,ne;function Ze(){me||(me=new MutationObserver(()=>{ne&&clearTimeout(ne),ne=window.setTimeout(()=>{we(),ne=void 0;},1e3);}),me.observe(document.documentElement,{childList:true,subtree:true}));}const ge=new Set;function Je(e,t){ge.has(e)||(ge.add(e),setTimeout(()=>{ge.delete(e),t(e);},Z.DETECT_DEBOUNCE));}function pn(e,t,r={}){const{size:n=null,type:u=null,pageTitle:h}=r;let l;if(t==="hls"){const b=pr(e);l=b?`${b} • Analyzing...`:"Analyzing...";}else l=ur(e,u).toUpperCase();return {url:e,kind:t,label:l,sublabel:null,size:n,type:u,origin:document.location.origin,pageTitle:h,enriched:false,enriching:false,hlsType:null,isLive:false,encrypted:false,_enrichPromise:null}}let gr=()=>{};function hn(e){gr=e;}function tr(e,t){try{if(!e||!Ur(e)&&!Kt(e)||Yr(e))return;const r=e.toLowerCase();if(r.includes("ping.gif")||r.includes("jwpltx.com")||r.includes("doubleclick")||r.includes("analytics")||r.includes("/stats/")||et.hasItem(e))return;let n=t?.size??null,u=t?.type??null;const h=t?.pageTitle;if(Kt(e)){const S=ut.get(e);if(S&&(n=n??S.size,u=u??S.type),n!=null&&n<512*1024&&S?.kind!=="m3u8")return}const l=_r(e)||Kt(e)&&ut.get(e)?.kind==="m3u8",b=Fr(e)||Kt(e)&&ut.get(e)?.kind==="video",y=l?"hls":b?"video":null;if(!y)return;const I=pn(e,y,{size:n,type:u,pageTitle:h});et.addItem(I)&&gr(I);}catch(r){console.error("[SG] processUrl error:",r);}}let er=false;function mn(){er||(er=true,en((e,t)=>Je(e,r=>tr(r,t))),dn(e=>Je(e,t=>tr(t))),un(),document.readyState==="loading"?document.addEventListener("DOMContentLoaded",()=>{we(),Ze();}):(we(),Ze()));}function gn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ve={exports:{}},rr;function vn(){return rr||(rr=1,(function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}Object.create&&(n.prototype=Object.create(null),new n().__proto__||(r=false));function u(y,I,S){this.fn=y,this.context=I,this.once=S||false;}function h(y,I,S,O,k){if(typeof S!="function")throw new TypeError("The listener must be a function");var E=new u(S,O||y,k),L=r?r+I:I;return y._events[L]?y._events[L].fn?y._events[L]=[y._events[L],E]:y._events[L].push(E):(y._events[L]=E,y._eventsCount++),y}function l(y,I){--y._eventsCount===0?y._events=new n:delete y._events[I];}function b(){this._events=new n,this._eventsCount=0;}b.prototype.eventNames=function(){var I=[],S,O;if(this._eventsCount===0)return I;for(O in S=this._events)t.call(S,O)&&I.push(r?O.slice(1):O);return Object.getOwnPropertySymbols?I.concat(Object.getOwnPropertySymbols(S)):I},b.prototype.listeners=function(I){var S=r?r+I:I,O=this._events[S];if(!O)return [];if(O.fn)return [O.fn];for(var k=0,E=O.length,L=new Array(E);k<E;k++)L[k]=O[k].fn;return L},b.prototype.listenerCount=function(I){var S=r?r+I:I,O=this._events[S];return O?O.fn?1:O.length:0},b.prototype.emit=function(I,S,O,k,E,L){var A=r?r+I:I;if(!this._events[A])return false;var f=this._events[A],T=arguments.length,p,x;if(f.fn){switch(f.once&&this.removeListener(I,f.fn,void 0,true),T){case 1:return f.fn.call(f.context),true;case 2:return f.fn.call(f.context,S),true;case 3:return f.fn.call(f.context,S,O),true;case 4:return f.fn.call(f.context,S,O,k),true;case 5:return f.fn.call(f.context,S,O,k,E),true;case 6:return f.fn.call(f.context,S,O,k,E,L),true}for(x=1,p=new Array(T-1);x<T;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(I,f[x].fn,void 0,true),T){case 1:f[x].fn.call(f[x].context);break;case 2:f[x].fn.call(f[x].context,S);break;case 3:f[x].fn.call(f[x].context,S,O);break;case 4:f[x].fn.call(f[x].context,S,O,k);break;default:if(!p)for(G=1,p=new Array(T-1);G<T;G++)p[G-1]=arguments[G];f[x].fn.apply(f[x].context,p);}}return true},b.prototype.on=function(I,S,O){return h(this,I,S,O,false)},b.prototype.once=function(I,S,O){return h(this,I,S,O,true)},b.prototype.removeListener=function(I,S,O,k){var E=r?r+I:I;if(!this._events[E])return this;if(!S)return l(this,E),this;var L=this._events[E];if(L.fn)L.fn===S&&(!k||L.once)&&(!O||L.context===O)&&l(this,E);else {for(var A=0,f=[],T=L.length;A<T;A++)(L[A].fn!==S||k&&!L[A].once||O&&L[A].context!==O)&&f.push(L[A]);f.length?this._events[E]=f.length===1?f[0]:f:l(this,E);}return this},b.prototype.removeAllListeners=function(I){var S;return I?(S=r?r+I:I,this._events[S]&&l(this,S)):(this._events=new n,this._eventsCount=0),this},b.prototype.off=b.prototype.removeListener,b.prototype.addListener=b.prototype.on,b.prefixed=r,b.EventEmitter=b,e.exports=b;})(ve)),ve.exports}var En=vn();const yn=gn(En);class Ue extends Error{name="TimeoutError";constructor(t,r){super(t,r),Error.captureStackTrace?.(this,Ue);}}const nr=e=>e.reason??new DOMException("This operation was aborted.","AbortError");function Tn(e,t){const{milliseconds:r,fallback:n,message:u,customTimers:h={setTimeout,clearTimeout},signal:l}=t;let b,y;const S=new Promise((O,k)=>{if(typeof r!="number"||Math.sign(r)!==1)throw new TypeError(`Expected \`milliseconds\` to be a positive number, got \`${r}\``);if(l?.aborted){k(nr(l));return}if(l&&(y=()=>{k(nr(l));},l.addEventListener("abort",y,{once:true})),e.then(O,k),r===Number.POSITIVE_INFINITY)return;const E=new Ue;b=h.setTimeout.call(void 0,()=>{if(n){try{O(n());}catch(L){k(L);}return}typeof e.cancel=="function"&&e.cancel(),u===false?O():u instanceof Error?k(u):(E.message=u??`Promise timed out after ${r} milliseconds`,k(E));},r);}).finally(()=>{S.clear(),y&&l&&l.removeEventListener("abort",y);});return S.clear=()=>{h.clearTimeout.call(void 0,b),b=void 0;},S}function bn(e,t,r){let n=0,u=e.length;for(;u>0;){const h=Math.trunc(u/2);let l=n+h;r(e[l],t)<=0?(n=++l,u-=h+1):u=h;}return n}class In{#r=[];enqueue(t,r){const{priority:n=0,id:u}=r??{},h={priority:n,id:u,run:t};if(this.size===0||this.#r[this.size-1].priority>=n){this.#r.push(h);return}const l=bn(this.#r,h,(b,y)=>y.priority-b.priority);this.#r.splice(l,0,h);}setPriority(t,r){const n=this.#r.findIndex(h=>h.id===t);if(n===-1)throw new ReferenceError(`No promise function with the id "${t}" exists in the queue.`);const[u]=this.#r.splice(n,1);this.enqueue(u.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 vr extends yn{#r;#o;#s=0;#p;#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:In,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.#p=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.#p:this.#s<this.#p}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.#O(),this.#C();}#F(t){if(this.#a){if(this.#T(t),this.#b()>=this.#p){const n=this.#i[this.#n],u=this.#l-(t-n);return this.#I(u),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 u=this.#t.dequeue();this.#o||(this.#X(r),this.#h()),this.emit("active"),u(),n&&this.#C(),t=true;}}return t}#C(){this.#o||this.#c!==void 0||this.#a||(this.#c=setInterval(()=>{this.#O();},this.#l),this.#N=Date.now()+this.#l);}#O(){this.#a||(this.#s===0&&this.#e===0&&this.#c&&this.#w(),this.#s=this.#r?this.#e:0),this.#A(),this.#h();}#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,u)=>{const h=Symbol(`task-${r.id}`);this.#t.enqueue(async()=>{this.#e++,this.#v.set(h,{id:r.id,priority:r.priority??0,startTime:Date.now(),timeout:r.timeout});let l;try{try{r.signal?.throwIfAborted();}catch(I){throw this.#V(),this.#v.delete(h),I}this.#y=Date.now();let b=t({signal:r.signal});if(r.timeout&&(b=Tn(Promise.resolve(b),{milliseconds:r.timeout,message:`Task timed out after ${r.timeout}ms (queue has ${this.#e} running, ${this.#t.size} waiting)`})),r.signal){const{signal:I}=r;b=Promise.race([b,new Promise((S,O)=>{l=()=>{O(I.reason);},I.addEventListener("abort",l,{once:!0});})]);}const y=await b;n(y),this.emit("completed",y);}catch(b){u(b),this.emit("error",b);}finally{l&&r.signal?.removeEventListener("abort",l),this.#v.delete(h),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.#P(),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=u=>{this.off("error",n),r(u);};this.on("error",n);})}async#f(t,r){return new Promise(n=>{const u=()=>{r&&!r()||(this.off(t,u),n());};this.on(t,u);})}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.#h();}),this.on("next",()=>{this.#h();}));}#h(){this.#o||this.#E||(this.#E=true,queueMicrotask(()=>{this.#E=false,this.#P();}));}#V(){this.#o||(this.#x(),this.#h());}#P(){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 u=Date.now();this.#T(u),r=this.#b();}else r=this.#s;const n=r>=this.#p;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 wn=Object.prototype.toString,Sn=e=>wn.call(e)==="[object Error]",An=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 Nn(e){if(!(e&&Sn(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:An.has(r)}function Rn(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 ie(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 Mt 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 Ln(e,t){const r=Math.max(1,e+1),n=t.randomize?Math.random()+1:1;let u=Math.round(n*t.minTimeout*t.factor**(r-1));return u=Math.min(u,t.maxTimeout),u}function ir(e,t){return Number.isFinite(t)?t-(performance.now()-e):t}async function Cn({error:e,attemptNumber:t,retriesConsumed:r,startTime:n,options:u}){const h=e instanceof Error?e:new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`);if(h instanceof Mt)throw h.originalError;const l=Number.isFinite(u.retries)?Math.max(0,u.retries-r):u.retries,b=u.maxRetryTime??Number.POSITIVE_INFINITY,y=Object.freeze({error:h,attemptNumber:t,retriesLeft:l,retriesConsumed:r});if(await u.onFailedAttempt(y),ir(n,b)<=0)throw h;const I=await u.shouldConsumeRetry(y),S=ir(n,b);if(S<=0||l<=0)throw h;if(h instanceof TypeError&&!Nn(h)){if(I)throw h;return u.signal?.throwIfAborted(),false}if(!await u.shouldRetry(y))throw h;if(!I)return u.signal?.throwIfAborted(),false;const O=Ln(r,u),k=Math.min(O,S);return u.signal?.throwIfAborted(),k>0&&await new Promise((E,L)=>{const A=()=>{clearTimeout(f),u.signal?.removeEventListener("abort",A),L(u.signal.reason);},f=setTimeout(()=>{u.signal?.removeEventListener("abort",A),E();},k);u.unref&&f.unref?.(),u.signal?.addEventListener("abort",A,{once:true});}),u.signal?.throwIfAborted(),true}async function Er(e,t={}){if(t={...t},Rn(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,ie("factor",t.factor,{min:0,allowInfinity:false}),ie("minTimeout",t.minTimeout,{min:0,allowInfinity:false}),ie("maxTimeout",t.maxTimeout,{min:0,allowInfinity:true}),ie("maxRetryTime",t.maxRetryTime,{min:0,allowInfinity:true}),t.factor>0||(t.factor=1),t.signal?.throwIfAborted();let r=0,n=0;const u=performance.now();for(;!Number.isFinite(t.retries)||n<=t.retries;){r++;try{t.signal?.throwIfAborted();const h=await e(r);return t.signal?.throwIfAborted(),h}catch(h){await Cn({error:h,attemptNumber:r,retriesConsumed:n,startTime:u,options:t})&&n++;}}throw new Error("Retry attempts exhausted without throwing an error.")}const On=new Map,Pn=new Map;function yr(e){return new Promise((t,r)=>{const n=()=>r(new Error("Aborted"));if(e.signal){if(e.signal.aborted)return n();e.signal.addEventListener("abort",n,{once:true});}const u=()=>{e.signal&&e.signal.removeEventListener("abort",n);},h=GM_xmlhttpRequest({method:"GET",url:e.url,responseType:e.responseType,headers:e.headers||{},timeout:e.timeout??Z.REQUEST_TIMEOUT,onprogress:l=>e.onprogress?.({loaded:l.loaded,total:l.total}),onload:l=>{u(),l.status>=200&&l.status<300?t(l.response):r(new Error(`HTTP ${l.status}`));},onerror:()=>{u(),r(new Error("Network error"));},ontimeout:()=>{u(),r(new Error("Timeout"));},onabort:()=>{u(),r(new Error("Aborted"));}});e.signal&&e.signal.addEventListener("abort",()=>h.abort(),{once:true});})}async function Dn(e,t){const r=Me(e,ut);if(r){if(!r.blob)throw new Error("Blob not found");return r.blob.text()}return Er(n=>{if(t?.aborted)throw new Error("Aborted");return yr({url:e,responseType:"text",timeout:Z.MANIFEST_TIMEOUT,signal:t})},{retries:Z.RETRIES,onFailedAttempt:n=>{if(t?.aborted)throw new Error("Aborted");console.warn(`[SG] Fetch text failed (attempt ${n.attemptNumber}): ${n.error.message}`);},signal:t})}function Tr(e,t){return Xe(On,Pn,e,()=>Dn(e,t),Qt.TEXT_MAX)}class Xn{async fetch(t,r){const n=Me(t,ut);if(!n||!n.blob)throw new Error("Blob not found");if(r.signal?.aborted)throw new Error("Aborted");const u=Zr(n.blob,r.headers?.Range);return r.onprogress&&setTimeout(()=>{r.signal?.aborted||r.onprogress({loaded:u.size,total:u.size});},0),new Promise((h,l)=>{const b=new FileReader,y=()=>{b.abort(),l(new Error("Aborted"));};r.signal&&r.signal.addEventListener("abort",y,{once:true}),b.onload=()=>{r.signal&&r.signal.removeEventListener("abort",y),h(b.result);},b.onerror=()=>{r.signal&&r.signal.removeEventListener("abort",y),l(b.error||new Error("Blob read error"));},b.readAsArrayBuffer(u);})}}class xn{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 u=n.body.getReader(),h=+(n.headers.get("Content-Length")||"0");let l=0;const b=[];for(;;){const{done:S,value:O}=await u.read();if(S)break;b.push(O),l+=O.length,r.onprogress&&h&&r.onprogress({loaded:l,total:h});}const y=new Uint8Array(l);let I=0;for(const S of b)y.set(S,I),I+=S.length;return y.buffer}}class Mn{async fetch(t,r){return yr({url:t,responseType:"arraybuffer",headers:r.headers,timeout:r.timeout,onprogress:r.onprogress,signal:r.signal})}}function Ee(e,t={},r=Z.REQUEST_TIMEOUT,n,u){return Me(e,ut)?new Xn().fetch(e,{headers:t,timeout:r,onprogress:n,signal:u}):new xn().fetch(e,{headers:t,timeout:r,onprogress:n,signal:u}).catch(l=>{if(u?.aborted||l.name==="AbortError"||l.message==="Aborted")throw l;return new Mn().fetch(e,{headers:t,timeout:r,onprogress:n,signal:u})})}var ye={exports:{}};var ar;function kn(){return ar||(ar=1,(function(e,t){(function(r,n){e.exports=n();})(self,(()=>(()=>{var r={31:function(h,l,b){function y(d){return y=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},y(d)}function I(d,a){var s=Object.keys(d);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(d);a&&(i=i.filter((function(g){return Object.getOwnPropertyDescriptor(d,g).enumerable}))),s.push.apply(s,i);}return s}function S(d){for(var a=1;a<arguments.length;a++){var s=arguments[a]!=null?arguments[a]:{};a%2?I(Object(s),true).forEach((function(i){p(d,i,s[i]);})):Object.getOwnPropertyDescriptors?Object.defineProperties(d,Object.getOwnPropertyDescriptors(s)):I(Object(s)).forEach((function(i){Object.defineProperty(d,i,Object.getOwnPropertyDescriptor(s,i));}));}return d}function O(d,a,s){return a=E(a),(function(i,g){if(g&&(y(g)=="object"||typeof g=="function"))return g;if(g!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return (function(v){if(v===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return v})(i)})(d,k()?Reflect.construct(a,s||[],E(d).constructor):a.apply(d,s))}function k(){try{var d=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})));}catch{}return (k=function(){return !!d})()}function E(d){return E=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(a){return a.__proto__||Object.getPrototypeOf(a)},E(d)}function L(d,a){if(typeof a!="function"&&a!==null)throw new TypeError("Super expression must either be null or a function");d.prototype=Object.create(a&&a.prototype,{constructor:{value:d,writable:true,configurable:true}}),Object.defineProperty(d,"prototype",{writable:false}),a&&A(d,a);}function A(d,a){return A=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(s,i){return s.__proto__=i,s},A(d,a)}function f(d,a,s){return Object.defineProperty(d,"prototype",{writable:false}),d}function T(d,a){if(!(d instanceof a))throw new TypeError("Cannot call a class as a function")}function p(d,a,s){return (a=x(a))in d?Object.defineProperty(d,a,{value:s,enumerable:true,configurable:true,writable:true}):d[a]=s,d}function x(d){var a=(function(s,i){if(y(s)!="object"||!s)return s;var g=s[Symbol.toPrimitive];if(g!==void 0){var v=g.call(s,i);if(y(v)!="object")return v;throw new TypeError("@@toPrimitive must return a primitive value.")}return (i==="string"?String:Number)(s)})(d,"string");return y(a)=="symbol"?a:a+""}var Y,G=this&&this.__createBinding||(Object.create?function(d,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(d,i,g);}:function(d,a,s,i){i===void 0&&(i=s),d[i]=a[s];}),it=this&&this.__setModuleDefault||(Object.create?function(d,a){Object.defineProperty(d,"default",{enumerable:true,value:a});}:function(d,a){d.default=a;}),lt=this&&this.__importStar||(Y=function(d){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(d)},function(d){if(d&&d.__esModule)return d;var a={};if(d!=null)for(var s=Y(d),i=0;i<s.length;i++)s[i]!=="default"&&G(a,d,s[i]);return it(a,d),a});Object.defineProperty(l,"__esModule",{value:true}),l.ContentSteering=l.RenditionReport=l.PrefetchSegment=l.PartialSegment=l.Segment=l.MediaPlaylist=l.MasterPlaylist=l.Playlist=l.SpliceInfo=l.DateRange=l.MediaInitializationSection=l.Key=l.SessionData=l.Variant=l.Rendition=void 0;var H=lt(b(203)),Tt=f((function d(a){var s=a.type,i=a.uri,g=a.groupId,v=a.language,P=a.assocLanguage,C=a.name,M=a.isDefault,N=a.autoselect,X=a.forced,U=a.instreamId,_=a.characteristics,V=a.channels,D=a.pathwayId;T(this,d),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,C),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=v,this.assocLanguage=P,this.name=C,this.isDefault=M,this.autoselect=N,this.forced=X,this.instreamId=U,this.characteristics=_,this.channels=V,this.pathwayId=D;}));l.Rendition=Tt;var at=f((function d(a){var s=a.uri,i=a.isIFrameOnly,g=i!==void 0&&i,v=a.bandwidth,P=a.averageBandwidth,C=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,z=a.programId,K=a.audio,J=K===void 0?[]:K,j=a.video,W=j===void 0?[]:j,$=a.subtitles,tt=$===void 0?[]:$,Q=a.closedCaptions,rt=Q===void 0?[]:Q,ct=a.currentRenditions,dt=ct===void 0?{audio:0,video:0,subtitles:0,closedCaptions:0}:ct;T(this,d),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,v),this.uri=s,this.isIFrameOnly=g,this.bandwidth=v,this.averageBandwidth=P,this.score=C,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=z,this.audio=J,this.video=W,this.subtitles=tt,this.closedCaptions=rt,this.currentRenditions=dt;}));l.Variant=at;var zt=f((function d(a){var s=a.id,i=a.value,g=a.uri,v=a.language;T(this,d),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=v;}));l.SessionData=zt;var Ut=f((function d(a){var s=a.method,i=a.uri,g=a.iv,v=a.format,P=a.formatVersion;T(this,d),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||v||P)]),this.method=s,this.uri=i,this.iv=g,this.format=v,this.formatVersion=P;}));l.Key=Ut;var _t=f((function d(a){var s=a.serverUri,i=a.pathwayId;T(this,d),p(this,"serverUri",void 0),p(this,"pathwayId",void 0),this.serverUri=s,this.pathwayId=i;}));l.ContentSteering=_t;var Ct=f((function d(a){var s=a.hint,i=s!==void 0&&s,g=a.uri,v=a.mimeType,P=a.byterange;T(this,d),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=v,this.byterange=P;}));l.MediaInitializationSection=Ct;var jt=f((function d(a){var s=a.id,i=a.classId,g=a.start,v=a.cue,P=a.end,C=a.duration,M=a.plannedDuration,N=a.endOnNext,X=a.attributes,U=X===void 0?{}:X;T(this,d),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([P,g],[P,g<=P],[C,C>=0],[M,M>=0]),this.id=s,this.classId=i,this.start=g,this.cue=v,this.end=P,this.duration=C,this.plannedDuration=M,this.endOnNext=N,this.attributes=U;}));l.DateRange=jt;var Ot=f((function d(a){var s=a.type,i=a.duration,g=a.tagName,v=a.value;T(this,d),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=v;}));l.SpliceInfo=Ot;var bt=f((function d(a){T(this,d),p(this,"type",void 0),H.PARAMCHECK(a),this.type=a;})),gt=(function(d){function a(s){var i,g=s.isMasterPlaylist,v=s.uri,P=s.version,C=s.independentSegments,M=C!==void 0&&C,N=s.start,X=s.source,U=s.defines;return T(this,a),p(i=O(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=v,i.version=P,i.independentSegments=M,i.start=N,i.source=X,i.defines=U,i}return L(a,d),f(a)})(bt);l.Playlist=gt;var Pt=(function(d){function a(){var s,i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};T(this,a),p(s=O(this,a,[S(S({},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,v=g===void 0?[]:g,P=i.currentVariant,C=i.sessionDataList,M=C===void 0?[]:C,N=i.sessionKeyList,X=N===void 0?[]:N,U=i.contentSteering,_=U===void 0?void 0:U;return s.variants=v,s.currentVariant=P,s.sessionDataList=M,s.sessionKeyList=X,s.contentSteering=_,s}return L(a,d),f(a)})(gt);l.MasterPlaylist=Pt;var R=(function(d){function a(){var s,i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};T(this,a),p(s=O(this,a,[S(S({},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,v=i.mediaSequenceBase,P=v===void 0?0:v,C=i.discontinuitySequenceBase,M=C===void 0?0:C,N=i.endlist,X=N!==void 0&&N,U=i.playlistType,_=i.isIFrame,V=i.segments,D=V===void 0?[]:V,F=i.prefetchSegments,z=F===void 0?[]:F,K=i.lowLatencyCompatibility,J=i.partTargetDuration,j=i.renditionReports,W=j===void 0?[]:j,$=i.skip,tt=$===void 0?0:$,Q=i.hash;return s.targetDuration=g,s.mediaSequenceBase=P,s.discontinuitySequenceBase=M,s.endlist=X,s.playlistType=U,s.isIFrame=_,s.segments=D,s.prefetchSegments=z,s.lowLatencyCompatibility=K,s.partTargetDuration=J,s.renditionReports=W,s.skip=tt,s.hash=Q,s}return L(a,d),f(a)})(gt);l.MediaPlaylist=R;var w=(function(d){function a(s){var i,g=s.uri,v=s.mimeType,P=s.data,C=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,z=s.map,K=s.programDateTime,J=s.dateRange,j=s.markers,W=j===void 0?[]:j,$=s.parts,tt=$===void 0?[]:$,Q=s.gap;return T(this,a),p(i=O(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=v,i.data=P,i.duration=C,i.title=M,i.byterange=N,i.discontinuity=X,i.mediaSequenceNumber=_,i.discontinuitySequence=D,i.key=F,i.map=z,i.programDateTime=K,i.dateRange=J,i.markers=W,i.parts=tt,i.gap=Q,i}return L(a,d),f(a)})(bt);l.Segment=w;var c=(function(d){function a(s){var i,g=s.hint,v=g!==void 0&&g,P=s.uri,C=s.duration,M=s.independent,N=s.byterange,X=s.gap;return T(this,a),p(i=O(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(P),i.hint=v,i.uri=P,i.duration=C,i.independent=M,i.duration=C,i.byterange=N,i.gap=X,i}return L(a,d),f(a)})(bt);l.PartialSegment=c;var o=(function(d){function a(s){var i,g=s.uri,v=s.discontinuity,P=s.mediaSequenceNumber,C=P===void 0?0:P,M=s.discontinuitySequence,N=M===void 0?0:M,X=s.key;return T(this,a),p(i=O(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=v,i.mediaSequenceNumber=C,i.discontinuitySequence=N,i.key=X,i}return L(a,d),f(a)})(bt);l.PrefetchSegment=o;var m=f((function d(a){var s=a.uri,i=a.lastMSN,g=a.lastPart;T(this,d),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;}));l.RenditionReport=m;},73:function(h,l,b){var y,I=this&&this.__createBinding||(Object.create?function(T,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(T,Y,G);}:function(T,p,x,Y){Y===void 0&&(Y=x),T[Y]=p[x];}),S=this&&this.__setModuleDefault||(Object.create?function(T,p){Object.defineProperty(T,"default",{enumerable:true,value:p});}:function(T,p){T.default=p;}),O=this&&this.__importStar||(y=function(T){return y=Object.getOwnPropertyNames||function(p){var x=[];for(var Y in p)Object.prototype.hasOwnProperty.call(p,Y)&&(x[x.length]=Y);return x},y(T)},function(T){if(T&&T.__esModule)return T;var p={};if(T!=null)for(var x=y(T),Y=0;Y<x.length;Y++)x[Y]!=="default"&&I(p,T,x[Y]);return S(p,T),p}),k=this&&this.__importDefault||function(T){return T&&T.__esModule?T:{default:T}};Object.defineProperty(l,"__esModule",{value:true}),l.setOptions=l.getOptions=l.types=l.stringify=l.parse=void 0;const E=b(203);Object.defineProperty(l,"getOptions",{enumerable:true,get:function(){return E.getOptions}}),Object.defineProperty(l,"setOptions",{enumerable:true,get:function(){return E.setOptions}});const L=k(b(377));l.parse=L.default;const A=k(b(887));l.stringify=A.default;const f=O(b(31));l.types=f;},203:(h,l)=>{function b(E,L){return (function(A){if(Array.isArray(A))return A})(E)||(function(A,f){var T=A==null?null:typeof Symbol<"u"&&A[Symbol.iterator]||A["@@iterator"];if(T!=null){var p,x,Y,G,it=[],lt=true,H=false;try{if(Y=(T=T.call(A)).next,f!==0)for(;!(lt=(p=Y.call(T)).done)&&(it.push(p.value),it.length!==f);lt=!0);}catch(Tt){H=true,x=Tt;}finally{try{if(!lt&&T.return!=null&&(G=T.return(),Object(G)!==G))return}finally{if(H)throw x}}return it}})(E,L)||I(E,L)||(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 y(E,L){var A=typeof Symbol<"u"&&E[Symbol.iterator]||E["@@iterator"];if(!A){if(Array.isArray(E)||(A=I(E))||L){A&&(E=A);var f=0,T=function(){};return {s:T,n:function(){return f>=E.length?{done:true}:{done:false,value:E[f++]}},e:function(G){throw G},f:T}}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(){A=A.call(E);},n:function(){var G=A.next();return x=G.done,G},e:function(G){Y=true,p=G;},f:function(){try{x||A.return==null||A.return();}finally{if(Y)throw p}}}}function I(E,L){if(E){if(typeof E=="string")return S(E,L);var A={}.toString.call(E).slice(8,-1);return A==="Object"&&E.constructor&&(A=E.constructor.name),A==="Map"||A==="Set"?Array.from(E):A==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(A)?S(E,L):void 0}}function S(E,L){(L==null||L>E.length)&&(L=E.length);for(var A=0,f=Array(L);A<L;A++)f[A]=E[A];return f}Object.defineProperty(l,"__esModule",{value:true}),l.THROW=k,l.ASSERT=function(E){for(var L=arguments.length,A=new Array(L>1?L-1:0),f=1;f<L;f++)A[f-1]=arguments[f];var T,p=y(A.entries());try{for(p.s();!(T=p.n()).done;){var x=b(T.value,2),Y=x[0];x[1]||k(new Error("".concat(E," : Failed at [").concat(Y,"]")));}}catch(G){p.e(G);}finally{p.f();}},l.CONDITIONALASSERT=function(){for(var E=arguments.length,L=new Array(E),A=0;A<E;A++)L[A]=arguments[A];var f,T=y(L.entries());try{for(T.s();!(f=T.n()).done;){var p=b(f.value,2),x=p[0],Y=b(p[1],2),G=Y[0],it=Y[1];G&&(it||k(new Error("Conditional Assert : Failed at [".concat(x,"]"))));}}catch(lt){T.e(lt);}finally{T.f();}},l.PARAMCHECK=function(){for(var E=arguments.length,L=new Array(E),A=0;A<E;A++)L[A]=arguments[A];var f,T=y(L.entries());try{for(T.s();!(f=T.n()).done;){var p=b(f.value,2),x=p[0];p[1]===void 0&&k(new Error("Param Check : Failed at [".concat(x,"]")));}}catch(Y){T.e(Y);}finally{T.f();}},l.CONDITIONALPARAMCHECK=function(){for(var E=arguments.length,L=new Array(E),A=0;A<E;A++)L[A]=arguments[A];var f,T=y(L.entries());try{for(T.s();!(f=T.n()).done;){var p=b(f.value,2),x=p[0],Y=b(p[1],2),G=Y[0],it=Y[1];G&&it===void 0&&k(new Error("Conditional Param Check : Failed at [".concat(x,"]")));}}catch(lt){T.e(lt);}finally{T.f();}},l.INVALIDPLAYLIST=function(E){k(new Error("Invalid Playlist : ".concat(E)));},l.toNumber=function(E){var L=arguments.length>1&&arguments[1]!==void 0?arguments[1]:10;if(typeof E=="number")return E;var A=L===10?Number.parseFloat(E):Number.parseInt(E,L);return Number.isNaN(A)?0:A},l.hexToByteSequence=function(E){(E.startsWith("0x")||E.startsWith("0X"))&&(E=E.slice(2));for(var L=new Uint8Array(E.length/2),A=0;A<E.length;A+=2)L[A/2]=Number.parseInt(E.slice(A,A+2),16);return L},l.byteSequenceToHex=function(E){var L=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:E.byteLength;A<=L&&k(new Error("end must be larger than start : start=".concat(L,", end=").concat(A)));for(var f=[],T=L;T<A;T++)f.push("0".concat((255&E[T]).toString(16).toUpperCase()).slice(-2));return "0x".concat(f.join(""))},l.tryCatch=function(E,L){try{return E()}catch(A){return L(A)}},l.splitAt=function(E,L){for(var A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,f=-1,T=0,p=0;T<E.length;T++)if(E[T]===L){if(p++===A)return [E.slice(0,T),E.slice(T+1)];f=T;}return f!==-1?[E.slice(0,f),E.slice(f+1)]:[E]},l.trim=function(E){var L=arguments.length>1&&arguments[1]!==void 0?arguments[1]:" ";return !E||(E=E.trim(),L===" ")||(E.startsWith(L)&&(E=E.slice(1)),E.endsWith(L)&&(E=E.slice(0,-1))),E},l.splitByCommaWithPreservingQuotes=function(E){for(var L=[],A=true,f=0,T=[],p=0;p<E.length;p++){var x=E[p];A&&x===","?(L.push(E.slice(f,p).trim()),f=p+1):x!=='"'&&x!=="'"||(A?(T.push(x),A=false):x===T.at(-1)?(T.pop(),A=true):T.push(x));}return L.push(E.slice(f).trim()),L},l.camelify=function(E){var L,A=[],f=false,T=y(E);try{for(T.s();!(L=T.n()).done;){var p=L.value;p!=="-"&&p!=="_"?f?(A.push(p.toUpperCase()),f=!1):A.push(p.toLowerCase()):f=!0;}}catch(x){T.e(x);}finally{T.f();}return A.join("")},l.formatDate=function(E){var L=E.getUTCFullYear(),A=("0"+(E.getUTCMonth()+1)).slice(-2),f=("0"+E.getUTCDate()).slice(-2),T=("0"+E.getUTCHours()).slice(-2),p=("0"+E.getUTCMinutes()).slice(-2),x=("0"+E.getUTCSeconds()).slice(-2),Y=("00"+E.getUTCMilliseconds()).slice(-3);return "".concat(L,"-").concat(A,"-").concat(f,"T").concat(T,":").concat(p,":").concat(x,".").concat(Y,"Z")},l.hasOwnProp=function(E,L){return Object.hasOwn(E,L)},l.setOptions=function(){var E=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};O=Object.assign(O,E);},l.getOptions=function(){return Object.assign({},O)};var O={};function k(E){if(O.strictMode)throw E;O.silent||console.error(E.message);}},377:function(h,l,b){function y(R,w){return (function(c){if(Array.isArray(c))return c})(R)||(function(c,o){var m=c==null?null:typeof Symbol<"u"&&c[Symbol.iterator]||c["@@iterator"];if(m!=null){var d,a,s,i,g=[],v=true,P=false;try{if(s=(m=m.call(c)).next,o===0){if(Object(m)!==m)return;v=!1;}else for(;!(v=(d=s.call(m)).done)&&(g.push(d.value),g.length!==o);v=!0);}catch(C){P=true,a=C;}finally{try{if(!v&&m.return!=null&&(i=m.return(),Object(i)!==i))return}finally{if(P)throw a}}return g}})(R,w)||S(R,w)||(function(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)})()}function I(R,w){var c=typeof Symbol<"u"&&R[Symbol.iterator]||R["@@iterator"];if(!c){if(Array.isArray(R)||(c=S(R))||w){c&&(R=c);var o=0,m=function(){};return {s:m,n:function(){return o>=R.length?{done:true}:{done:false,value:R[o++]}},e:function(i){throw i},f:m}}throw new TypeError(`Invalid attempt to iterate non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var d,a=true,s=false;return {s:function(){c=c.call(R);},n:function(){var i=c.next();return a=i.done,i},e:function(i){s=true,d=i;},f:function(){try{a||c.return==null||c.return();}finally{if(s)throw d}}}}function S(R,w){if(R){if(typeof R=="string")return O(R,w);var c={}.toString.call(R).slice(8,-1);return c==="Object"&&R.constructor&&(c=R.constructor.name),c==="Map"||c==="Set"?Array.from(R):c==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(c)?O(R,w):void 0}}function O(R,w){(w==null||w>R.length)&&(w=R.length);for(var c=0,o=Array(w);c<w;c++)o[c]=R[c];return o}var k,E=this&&this.__createBinding||(Object.create?function(R,w,c,o){o===void 0&&(o=c);var m=Object.getOwnPropertyDescriptor(w,c);m&&!("get"in m?!w.__esModule:m.writable||m.configurable)||(m={enumerable:true,get:function(){return w[c]}}),Object.defineProperty(R,o,m);}:function(R,w,c,o){o===void 0&&(o=c),R[o]=w[c];}),L=this&&this.__setModuleDefault||(Object.create?function(R,w){Object.defineProperty(R,"default",{enumerable:true,value:w});}:function(R,w){R.default=w;}),A=this&&this.__importStar||(k=function(R){return k=Object.getOwnPropertyNames||function(w){var c=[];for(var o in w)Object.prototype.hasOwnProperty.call(w,o)&&(c[c.length]=o);return c},k(R)},function(R){if(R&&R.__esModule)return R;var w={};if(R!=null)for(var c=k(R),o=0;o<c.length;o++)c[o]!=="default"&&E(w,R,c[o]);return L(w,R),w});Object.defineProperty(l,"__esModule",{value:true});var f=A(b(203)),T=b(31);function p(R){return f.trim(R,'"')}function x(R){var w=f.splitAt(R,",");return {duration:f.toNumber(w[0]),title:decodeURIComponent(escape(w[1]))}}function Y(R){var w=f.splitAt(R,"@");return {length:f.toNumber(w[0]),offset:w[1]?f.toNumber(w[1]):-1}}function G(R){var w=f.splitAt(R,"x");return {width:f.toNumber(w[0]),height:f.toNumber(w[1])}}function it(R){var w="ALLOWED-CPC: Each entry must consit of KEYFORMAT and Content Protection Configuration",c=R.split(",");c.length===0&&f.INVALIDPLAYLIST(w);var o,m=[],d=I(c);try{for(d.s();!(o=d.n()).done;){var a=o.value,s=y(f.splitAt(a,":"),2),i=s[0],g=s[1];i&&g?m.push({format:i,cpcList:g.split("/")}):f.INVALIDPLAYLIST(w);}}catch(v){d.e(v);}finally{d.f();}return m}function lt(R){return R.startsWith('"')?p(R):R.startsWith("0x")||R.startsWith("0X")?f.hexToByteSequence(R):f.toNumber(R)}function H(R,w){w.IV&&R.compatibleVersion<2&&(R.compatibleVersion=2),(w.KEYFORMAT||w.KEYFORMATVERSIONS)&&R.compatibleVersion<5&&(R.compatibleVersion=5);}function Tt(R){var w,c,o,m={},d=I(f.splitByCommaWithPreservingQuotes(R));try{for(d.s();!(w=d.n()).done;){var a=w.value,s=y(f.splitAt(a,"="),2),i=s[0],g=s[1],v=p(g);switch(i){case "URI":m[i]=v;break;case "START-DATE":case "END-DATE":m[i]=new Date(v);break;case "IV":m[i]=(c=v,o=void 0,(o=f.hexToByteSequence(c)).length!==16&&f.INVALIDPLAYLIST("IV must be a 128-bit unsigned integer"),o);break;case "BYTERANGE":m[i]=Y(v);break;case "RESOLUTION":m[i]=G(v);break;case "ALLOWED-CPC":m[i]=it(v);break;case "END-ON-NEXT":case "DEFAULT":case "AUTOSELECT":case "FORCED":case "PRECISE":case "CAN-BLOCK-RELOAD":case "INDEPENDENT":case "GAP":m[i]=v==="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":m[i]=f.toNumber(v);break;default:i.startsWith("SCTE35-")?m[i]=f.hexToByteSequence(v):i.startsWith("X-")?m[i]=lt(g):(i==="VIDEO-RANGE"&&v!=="SDR"&&v!=="HLG"&&v!=="PQ"&&f.INVALIDPLAYLIST('VIDEO-RANGE: unknown value "'.concat(v,'"')),m[i]=v);}}}catch(P){d.e(P);}finally{d.f();}return m}function at(){f.INVALIDPLAYLIST("The file contains both media and master playlist tags.");}function zt(R,w,c){var o,m=(o=w.attributes,new T.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"]})),d=R[f.camelify(c)],a=(function(s,i){var g,v=false,P=I(s);try{for(P.s();!(g=P.n()).done;){var C=g.value;if(C.name===i.name)return "All EXT-X-MEDIA tags in the same Group MUST have different NAME attributes.";C.isDefault&&(v=!0);}}catch(M){P.e(M);}finally{P.f();}return v&&i.isDefault?"EXT-X-MEDIA A Group MUST NOT have more than one member with a DEFAULT attribute of YES.":""})(d,m);a&&f.INVALIDPLAYLIST(a),d.push(m),m.isDefault&&(R.currentRenditions[f.camelify(c)]=d.length-1);}function Ut(R,w,c,o,m){var d,a=new T.Variant({uri:c,bandwidth:w.BANDWIDTH,averageBandwidth:w["AVERAGE-BANDWIDTH"],score:w.SCORE,codecs:w.CODECS,resolution:w.RESOLUTION,frameRate:w["FRAME-RATE"],hdcpLevel:w["HDCP-LEVEL"],allowedCpc:w["ALLOWED-CPC"],videoRange:w["VIDEO-RANGE"],stableVariantId:w["STABLE-VARIANT-ID"],pathwayId:w["STABLE-PATHWAY-ID"],programId:w["PROGRAM-ID"]}),s=I(R);try{for(s.s();!(d=s.n()).done;){var i=d.value;if(i.name==="EXT-X-MEDIA"){var g=i.attributes,v=g.TYPE;if(v&&g["GROUP-ID"]||f.INVALIDPLAYLIST("EXT-X-MEDIA TYPE attribute is REQUIRED."),w[v]===g["GROUP-ID"]&&(zt(a,i,v),v==="CLOSED-CAPTIONS")){var P,C=I(a.closedCaptions);try{for(C.s();!(P=C.n()).done;){var M=P.value.instreamId;if(M&&M.startsWith("SERVICE")&&m.compatibleVersion<7){m.compatibleVersion=7;break}}}catch(N){C.e(N);}finally{C.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(z){return z.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++)_();})(w,a,m),a.isIFrameOnly=o,a}function _t(R,w,c,o,m,d,a){for(var s=new T.Segment({uri:w,mediaSequenceNumber:m,discontinuitySequence:d}),i=false,g=false,v=c;v<=o;v++){var P=Pt(R[v]),C=P.name,M=P.value,N=P.attributes;if(C==="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(C==="EXT-X-BYTERANGE")a.compatibleVersion<4&&(a.compatibleVersion=4),s.byterange=M;else if(C==="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(C==="EXT-X-GAP")a.compatibleVersion<8&&(a.compatibleVersion=8),s.gap=true;else if(C==="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 T.Key({method:N.METHOD,uri:N.URI,iv:N.IV,format:N.KEYFORMAT,formatVersion:N.KEYFORMATVERSIONS});else if(C==="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 T.MediaInitializationSection({uri:N.URI,byterange:N.BYTERANGE});else if(C==="EXT-X-PROGRAM-DATE-TIME")s.programDateTime=M;else if(C==="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 T.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(C==="EXT-X-CUE-OUT")s.markers.push(new T.SpliceInfo({type:"OUT",duration:N&&N.DURATION||M}));else if(C==="EXT-X-CUE-IN")s.markers.push(new T.SpliceInfo({type:"IN"}));else if(C==="EXT-X-CUE-OUT-CONT"||C==="EXT-X-CUE"||C==="EXT-OATCLS-SCTE35"||C==="EXT-X-ASSET"||C==="EXT-X-SCTE35")s.markers.push(new T.SpliceInfo({type:"RAW",tagName:C,value:M}));else if(C!=="EXT-X-PRELOAD-HINT"||N.TYPE)if(C==="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(C!=="EXT-X-PART"&&C!=="EXT-X-PRELOAD-HINT"||N.URI){if(C==="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 T.MediaInitializationSection({hint:true,uri:N.URI,byterange:{length:N["BYTERANGE-LENGTH"],offset:N["BYTERANGE-START"]||0}});else if(C==="EXT-X-PART"||C==="EXT-X-PRELOAD-HINT"&&N.TYPE==="PART"){C!=="EXT-X-PART"||N.DURATION||f.INVALIDPLAYLIST("EXT-X-PART: DURATION attribute is mandatory"),C==="EXT-X-PRELOAD-HINT"&&(g=true);var D=new T.PartialSegment({hint:C==="EXT-X-PRELOAD-HINT",uri:N.URI,byterange:C==="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 Ct(R,w,c,o,m,d,a){for(var s=new T.PrefetchSegment({uri:w,mediaSequenceNumber:m,discontinuitySequence:d}),i=c;i<=o;i++){var g=R[i],v=g.name,P=g.attributes;v==="EXTINF"?f.INVALIDPLAYLIST("A prefetch segment must not be advertised with an EXTINF tag."):v==="EXT-X-DISCONTINUITY"?f.INVALIDPLAYLIST("A prefetch segment must not be advertised with an EXT-X-DISCONTINUITY tag."):v==="EXT-X-PREFETCH-DISCONTINUITY"?s.discontinuity=true:v==="EXT-X-KEY"?(H(a,P),s.key=new T.Key({method:P.METHOD,uri:P.URI,iv:P.IV,format:P.KEYFORMAT,formatVersion:P.KEYFORMATVERSIONS})):v==="EXT-X-MAP"&&f.INVALIDPLAYLIST("Prefetch segments must not be advertised with an EXT-X-MAP tag.");}return s}function jt(R,w){var c,o=new T.MediaPlaylist,m=-1,d=0,a=false,s=false,i=0,g=null,v=null,P=false,C=I(R.entries());try{for(C.s();!(c=C.n()).done;){var M=y(c.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=w.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=d=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")w.compatibleVersion<4&&(w.compatibleVersion=4),o.isIFrame=!0;else if(_==="EXT-X-INDEPENDENT-SEGMENTS")o.independentSegments&&f.INVALIDPLAYLIST("EXT-X-INDEPENDENT-SEGMENTS tag MUST NOT appear more than once in a Playlist"),o.independentSegments=!0;else if(_==="EXT-X-START")o.start&&f.INVALIDPLAYLIST("EXT-X-START tag MUST NOT appear more than once in a Playlist"),typeof D["TIME-OFFSET"]!="number"&&f.INVALIDPLAYLIST("EXT-X-START: TIME-OFFSET attribute is REQUIRED"),o.start={offset:D["TIME-OFFSET"],precise:D.PRECISE||!1};else if(_==="EXT-X-SERVER-CONTROL")D["CAN-BLOCK-RELOAD"]||f.INVALIDPLAYLIST("EXT-X-SERVER-CONTROL: CAN-BLOCK-RELOAD=YES is mandatory for Low-Latency HLS"),o.lowLatencyCompatibility={canBlockReload:D["CAN-BLOCK-RELOAD"],canSkipUntil:D["CAN-SKIP-UNTIL"],holdBack:D["HOLD-BACK"],partHoldBack:D["PART-HOLD-BACK"]};else if(_==="EXT-X-PART-INF")D["PART-TARGET"]||f.INVALIDPLAYLIST("EXT-X-PART-INF: PART-TARGET attribute is mandatory"),o.partTargetDuration=D["PART-TARGET"];else if(_==="EXT-X-RENDITION-REPORT")D.URI||f.INVALIDPLAYLIST("EXT-X-RENDITION-REPORT: URI attribute is mandatory"),D.URI.search(/^[a-z]+:/)===0&&f.INVALIDPLAYLIST("EXT-X-RENDITION-REPORT: URI must be relative to the playlist uri"),o.renditionReports.push(new T.RenditionReport({uri:D.URI,lastMSN:D["LAST-MSN"],lastPart:D["LAST-PART"]}));else if(_==="EXT-X-SKIP")D["SKIPPED-SEGMENTS"]||f.INVALIDPLAYLIST("EXT-X-SKIP: SKIPPED-SEGMENTS attribute is mandatory"),w.compatibleVersion<9&&(w.compatibleVersion=9),o.skip=D["SKIPPED-SEGMENTS"],d+=o.skip;else if(_==="EXT-X-PREFETCH"){var F=Ct(R,V,m===-1?N:m,N-1,d++,i,w);F&&(F.discontinuity&&(F.discontinuitySequence++,i=F.discontinuitySequence),F.key?g=F.key:F.key=g,o.prefetchSegments.push(F)),s=!0,m=-1;}else if(_==="EXT-X-DEFINE")o.defines||(o.defines=[]),o.defines.push(D);else if(typeof X=="string"){m===-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 z=_t(R,X,m,N-1,d++,i,w);if(z){var K=y(Ot(o,z,i,g,v),3);i=K[0],g=K[1],v=K[2],!P&&z.parts.length>0&&(P=!0);}m=-1;}}else m===-1&&(m=N),_==="EXT-X-DISCONTINUITY"&&(a=!0);}}catch($){C.e($);}finally{C.f();}if(m!==-1){var J=_t(R,"",m,R.length-1,d++,i,w);if(J){var j,W=J.parts;!(W.length>0)||o.endlist||(j=W.at(-1))!==null&&j!==void 0&&j.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,v),!P&&J.parts.length>0&&(P=true);}}return (function($){for(var tt=new Map,Q=new Map,rt=false,ct=false,dt=$.length-1;dt>=0;dt--){var Et=$[dt],It=Et.programDateTime,q=Et.dateRange;if(It&&(ct=true),q&&q.start){rt=true,q.endOnNext&&(q.end||q.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=q.start.getTime(),te=q.duration||0;q.end&&q.duration&&ot+1e3*te!==q.end.getTime()&&f.INVALIDPLAYLIST("END-DATE MUST be equal to the value of the START-DATE attribute plus the value of the DURATION"),q.endOnNext&&(q.end=tt.get(q.classId)),tt.set(q.classId,q.start);var wt=q.end?q.end.getTime():q.start.getTime()+1e3*(q.duration||0),Ft=Q.get(q.classId);if(Ft){var ee,St=I(Ft);try{for(St.s();!(ee=St.n()).done;){var Dt=ee.value;(Dt.start<=ot&&Dt.end>ot||Dt.start>=ot&&Dt.start<wt)&&f.INVALIDPLAYLIST("DATERANGE tags with the same CLASS should not overlap");}}catch(Yt){St.e(Yt);}finally{St.f();}Ft.push({start:ot,end:wt});}else q.classId&&Q.set(q.classId,[{start:ot,end:wt}]);}}rt&&!ct&&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($,tt){var Q=$.lowLatencyCompatibility,rt=$.targetDuration,ct=$.partTargetDuration,dt=$.segments,Et=$.renditionReports,It=Q.canSkipUntil,q=Q.holdBack,ot=Q.partHoldBack;if(It<6*rt&&f.INVALIDPLAYLIST("The Skip Boundary must be at least six times the EXT-X-TARGETDURATION."),q<3*rt&&f.INVALIDPLAYLIST("HOLD-BACK must be at least three times the EXT-X-TARGETDURATION."),tt){ct===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<ct&&f.INVALIDPLAYLIST("PART-HOLD-BACK must be at least PART-TARGET");var te,wt=I(dt.entries());try{for(wt.s();!(te=wt.n()).done;){var Ft=y(te.value,2),ee=Ft[0],St=Ft[1].parts;St.length>0&&ee<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 Dt,Yt=I(St.entries());try{for(Yt.s();!(Dt=Yt.n()).done;){var ze=y(Dt.value,2),Xr=ze[0],pe=ze[1].duration;pe!==void 0&&(pe>ct&&f.INVALIDPLAYLIST("PART-TARGET is the maximum duration of any Partial Segment"),Xr<St.length-1&&pe<.85*ct&&f.INVALIDPLAYLIST("All Partial Segments except the last part of a segment must have a duration of at least 85% of PART-TARGET"));}}catch($t){Yt.e($t);}finally{Yt.f();}}}catch($t){wt.e($t);}finally{wt.f();}}var je,re=I(Et);try{for(re.s();!(je=re.n()).done;){var He,Ht=je.value,he=dt.at(-1);(He=Ht.lastMSN)!==null&&He!==void 0||(Ht.lastMSN=he.mediaSequenceNumber),(Ht.lastPart===null||Ht.lastPart===void 0)&&he.parts.length>0&&(Ht.lastPart=he.parts.length-1);}}catch($t){re.e($t);}finally{re.f();}})(o,P),o}function Ot(R,w,c,o,m){var d=w.discontinuity,a=w.key,s=w.map,i=w.byterange,g=w.uri;if(d&&(w.discontinuitySequence=c+1),a||(w.key=o),s||(w.map=m),i&&i.offset===-1){var v=R.segments;if(v.length>0){var P=v.at(-1);P.byterange&&P.uri===g?i.offset=P.byterange.offset+P.byterange.length:f.INVALIDPLAYLIST("If offset of EXT-X-BYTERANGE is not present, a previous Media Segment MUST be a sub-range of the same media resource");}else f.INVALIDPLAYLIST("If offset of EXT-X-BYTERANGE is not present, a previous Media Segment MUST appear in the Playlist file");}return R.segments.push(w),[w.discontinuitySequence,w.key,w.map]}function bt(R,w){var c=(function(g){var v=g.indexOf(":");return v===-1?[g.slice(1).trim(),null]:[g.slice(1,v).trim(),g.slice(v+1).trim()]})(R),o=y(c,2),m=o[0],d=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"}})(m);if((function(g,v){if(g==="Segment"||g==="MediaPlaylist")return v.isMasterPlaylist===void 0?void(v.isMasterPlaylist=false):void(v.isMasterPlaylist&&at());if(g==="MasterPlaylist"){if(v.isMasterPlaylist===void 0)return void(v.isMasterPlaylist=true);v.isMasterPlaylist===false&&at();}})(a,w),a==="Unknown")return null;a==="MediaPlaylist"&&m!=="EXT-X-RENDITION-REPORT"&&m!=="EXT-X-PREFETCH"&&(w.hash[m]&&f.INVALIDPLAYLIST("There MUST NOT be more than one Media Playlist tag of each type in any Media Playlist"),w.hash[m]=true);var s=(function(g,v){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(v),null];case "EXT-X-CUE-OUT":return Number.isNaN(Number(v))?[null,Tt(v)]:[f.toNumber(v),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,Tt(v)];case "EXTINF":return [x(v),null];case "EXT-X-BYTERANGE":return [Y(v),null];case "EXT-X-PROGRAM-DATE-TIME":return [new Date(v),null];default:return [v,null]}})(m,d),i=y(s,2);return {name:m,category:a,value:i[0],attributes:i[1]}}function gt(R,w){var c;return w.isMasterPlaylist?c=(function(o,m){var d,a=new T.MasterPlaylist,s=false,i=I(o.entries());try{var g=function(){var N=y(d.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 T.ContentSteering({serverUri:D["SERVER-URI"],pathwayId:D["PATHWAY-ID"]});a.contentSteering=F;}else if(_==="EXT-X-STREAM-INF"){var z=o[X+1];(typeof z!="string"||z.startsWith("#EXT"))&&f.INVALIDPLAYLIST("EXT-X-STREAM-INF must be followed by a URI line");var K=Ut(o,D,z,!1,m);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=Ut(o,D,D.URI,!0,m);J&&a.variants.push(J);}else if(_==="EXT-X-SESSION-DATA"){var j=new T.SessionData({id:D["DATA-ID"],value:D.VALUE,uri:D.URI,language:D.LANGUAGE});a.sessionDataList.some((function($){return $.id===j.id&&$.language===j.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(j);}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 T.Key({method:D.METHOD,uri:D.URI,iv:D.IV,format:D.KEYFORMAT,formatVersion:D.KEYFORMATVERSIONS});a.sessionKeyList.some((function($){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})($,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(m,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();!(d=i.n()).done;)g();}catch(N){i.e(N);}finally{i.f();}if(s){var v,P=I(a.variants);try{for(P.s();!(v=P.n()).done;)typeof v.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){P.e(N);}finally{P.f();}}if(m.isClosedCaptionsNone){var C,M=I(a.variants);try{for(M.s();!(C=M.n()).done;)C.value.closedCaptions.length>0&&f.INVALIDPLAYLIST("If there is a variant with CLOSED-CAPTIONS attribute of NONE, all EXT-X-STREAM-INF tags MUST have this attribute with a value of NONE");}catch(N){M.e(N);}finally{M.f();}}return a})(R,w):!(c=jt(R,w)).isIFrame&&w.hasMap&&w.compatibleVersion<6&&(w.compatibleVersion=6),w.compatibleVersion>1&&(!c.version||c.version<w.compatibleVersion)&&f.INVALIDPLAYLIST("EXT-X-VERSION needs to be ".concat(w.compatibleVersion," or higher.")),c}function Pt(R){return typeof R=="string"?{}:R}l.default=function(R){var w={version:void 0,isMasterPlaylist:void 0,hasMap:false,targetDuration:0,compatibleVersion:1,isClosedCaptionsNone:false,hash:{}},c=gt((function(o,m){var d,a=[],s=I(o.split(`
`));try{for(s.s();!(d=s.n()).done;){var i=d.value.trim();if(i)if(i.startsWith("#")){if(i.startsWith("#EXT")){var g=bt(i,m);g&&a.push(g);}}else a.push(i);}}catch(v){s.e(v);}finally{s.f();}return a.length!==0&&a[0].name==="EXTM3U"||f.INVALIDPLAYLIST("The EXTM3U tag MUST be the first line."),a})(R,w),w);return c.source=R,c};},887:function(h,l,b){function y(c){return y=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},y(c)}function I(c,o){return (function(m){if(Array.isArray(m))return m})(c)||(function(m,d){var a=m==null?null:typeof Symbol<"u"&&m[Symbol.iterator]||m["@@iterator"];if(a!=null){var s,i,g,v,P=[],C=true,M=false;try{if(g=(a=a.call(m)).next,d===0){if(Object(a)!==a)return;C=!1;}else for(;!(C=(s=g.call(a)).done)&&(P.push(s.value),P.length!==d);C=!0);}catch(N){M=true,i=N;}finally{try{if(!C&&a.return!=null&&(v=a.return(),Object(v)!==v))return}finally{if(M)throw i}}return P}})(c,o)||O(c,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 S(c,o){var m=typeof Symbol<"u"&&c[Symbol.iterator]||c["@@iterator"];if(!m){if(Array.isArray(c)||(m=O(c))||o){m&&(c=m);var d=0,a=function(){};return {s:a,n:function(){return d>=c.length?{done:true}:{done:false,value:c[d++]}},e:function(v){throw v},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(){m=m.call(c);},n:function(){var v=m.next();return i=v.done,v},e:function(v){g=true,s=v;},f:function(){try{i||m.return==null||m.return();}finally{if(g)throw s}}}}function O(c,o){if(c){if(typeof c=="string")return k(c,o);var m={}.toString.call(c).slice(8,-1);return m==="Object"&&c.constructor&&(m=c.constructor.name),m==="Map"||m==="Set"?Array.from(c):m==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(m)?k(c,o):void 0}}function k(c,o){(o==null||o>c.length)&&(o=c.length);for(var m=0,d=Array(o);m<o;m++)d[m]=c[m];return d}function E(c,o){for(var m=0;m<o.length;m++){var d=o[m];d.enumerable=d.enumerable||false,d.configurable=true,"value"in d&&(d.writable=true),Object.defineProperty(c,G(d.key),d);}}function L(c,o,m){return o=Y(o),(function(d,a){if(a&&(y(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})(d)})(c,p()?Reflect.construct(o,[],Y(c).constructor):o.apply(c,m))}function A(c,o,m,d){var a=f(Y(c.prototype),o,m);return 2&d&&typeof a=="function"?function(s){return a.apply(m,s)}:a}function f(){return f=typeof Reflect<"u"&&Reflect.get?Reflect.get.bind():function(c,o,m){var d=(function(s,i){for(;!{}.hasOwnProperty.call(s,i)&&(s=Y(s))!==null;);return s})(c,o);if(d){var a=Object.getOwnPropertyDescriptor(d,o);return a.get?a.get.call(arguments.length<3?c:m):a.value}},f.apply(null,arguments)}function T(c){var o=typeof Map=="function"?new Map:void 0;return T=function(m){if(m===null||!(function(a){try{return Function.toString.call(a).indexOf("[native code]")!==-1}catch{return typeof a=="function"}})(m))return m;if(typeof m!="function")throw new TypeError("Super expression must either be null or a function");if(o!==void 0){if(o.has(m))return o.get(m);o.set(m,d);}function d(){return (function(a,s,i){if(p())return Reflect.construct.apply(null,arguments);var g=[null];g.push.apply(g,s);var v=new(a.bind.apply(a,g));return i&&x(v,i.prototype),v})(m,arguments,Y(this).constructor)}return d.prototype=Object.create(m.prototype,{constructor:{value:d,enumerable:false,writable:true,configurable:true}}),x(d,m)},T(c)}function p(){try{var c=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})));}catch{}return (p=function(){return !!c})()}function x(c,o){return x=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(m,d){return m.__proto__=d,m},x(c,o)}function Y(c){return Y=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(o){return o.__proto__||Object.getPrototypeOf(o)},Y(c)}function G(c){var o=(function(m,d){if(y(m)!="object"||!m)return m;var a=m[Symbol.toPrimitive];if(a!==void 0){var s=a.call(m,d);if(y(s)!="object")return s;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(m)})(c,"string");return y(o)=="symbol"?o:o+""}var it,lt=this&&this.__createBinding||(Object.create?function(c,o,m,d){d===void 0&&(d=m);var a=Object.getOwnPropertyDescriptor(o,m);a&&!("get"in a?!o.__esModule:a.writable||a.configurable)||(a={enumerable:true,get:function(){return o[m]}}),Object.defineProperty(c,d,a);}:function(c,o,m,d){d===void 0&&(d=m),c[d]=o[m];}),H=this&&this.__setModuleDefault||(Object.create?function(c,o){Object.defineProperty(c,"default",{enumerable:true,value:o});}:function(c,o){c.default=o;}),Tt=this&&this.__importStar||(it=function(c){return it=Object.getOwnPropertyNames||function(o){var m=[];for(var d in o)Object.prototype.hasOwnProperty.call(o,d)&&(m[m.length]=d);return m},it(c)},function(c){if(c&&c.__esModule)return c;var o={};if(c!=null)for(var m=it(c),d=0;d<m.length;d++)m[d]!=="default"&<(o,c,m[d]);return H(o,c),o});Object.defineProperty(l,"__esModule",{value:true});var at=Tt(b(203)),zt=["#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"],Ut=["#EXT-X-MEDIA"],_t=(function(c){function o(s){var i,g,v,P;return (function(C,M){if(!(C instanceof M))throw new TypeError("Cannot call a class as a function")})(this,o),i=L(this,o),g=i,P=void 0,(v=G(v="baseUri"))in g?Object.defineProperty(g,v,{value:P,enumerable:true,configurable:true,writable:true}):g[v]=P,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,c),m=o,d=[{key:"push",value:function(){for(var s=this,i=arguments.length,g=new Array(i),v=0;v<i;v++)g[v]=arguments[v];for(var P=function(){var N=M[C];if(!N.startsWith("#"))return A(o,"push",s,3)([N]),0;if(zt.some((function(X){return N.startsWith(X)})))return A(o,"push",s,3)([N]),0;if(s.includes(N)){if(Ut.some((function(X){return N.startsWith(X)})))return 0;at.INVALIDPLAYLIST("Redundant item (".concat(N,")"));}A(o,"push",s,3)([N]);},C=0,M=g;C<M.length;C++)P();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 A(o,"join",this,3)([s])}}],d&&E(m.prototype,d),a&&E(m,a),Object.defineProperty(m,"prototype",{writable:false}),m;var m,d,a;})(T(Array));function Ct(c,o){var m=1e3;o&&(m=Math.pow(10,o));var d=Math.round(c*m)/m;return o?d.toFixed(o):d}function jt(c){var o=['DATA-ID="'.concat(c.id,'"')];return c.language&&o.push('LANGUAGE="'.concat(c.language,'"')),c.value?o.push('VALUE="'.concat(c.value,'"')):c.uri&&o.push('URI="'.concat(c.uri,'"')),"#EXT-X-SESSION-DATA:".concat(o.join(","))}function Ot(c,o){var m=o?"#EXT-X-SESSION-KEY":"#EXT-X-KEY",d=["METHOD=".concat(c.method)];return c.uri&&d.push('URI="'.concat(c.uri,'"')),c.iv&&(c.iv.byteLength!==16&&at.INVALIDPLAYLIST("IV must be a 128-bit unsigned integer"),d.push("IV=".concat(at.byteSequenceToHex(c.iv)))),c.format&&d.push('KEYFORMAT="'.concat(c.format,'"')),c.formatVersion&&d.push('KEYFORMATVERSIONS="'.concat(c.formatVersion,'"')),"".concat(m,":").concat(d.join(","))}function bt(c,o){var m=o.isIFrameOnly?"#EXT-X-I-FRAME-STREAM-INF":"#EXT-X-STREAM-INF",d=["BANDWIDTH=".concat(o.bandwidth)];if(o.averageBandwidth&&d.push("AVERAGE-BANDWIDTH=".concat(o.averageBandwidth)),o.isIFrameOnly&&d.push('URI="'.concat(o.uri,'"')),o.codecs&&d.push('CODECS="'.concat(o.codecs,'"')),o.resolution&&d.push("RESOLUTION=".concat(o.resolution.width,"x").concat(o.resolution.height)),o.frameRate&&d.push("FRAME-RATE=".concat(Ct(o.frameRate,3))),o.hdcpLevel&&d.push("HDCP-LEVEL=".concat(o.hdcpLevel)),o.audio.length>0){d.push('AUDIO="'.concat(o.audio[0].groupId,'"'));var a,s=S(o.audio);try{for(s.s();!(a=s.n()).done;){var i=a.value;c.push(gt(i));}}catch(j){s.e(j);}finally{s.f();}}if(o.video.length>0){d.push('VIDEO="'.concat(o.video[0].groupId,'"'));var g,v=S(o.video);try{for(v.s();!(g=v.n()).done;){var P=g.value;c.push(gt(P));}}catch(j){v.e(j);}finally{v.f();}}if(o.subtitles.length>0){d.push('SUBTITLES="'.concat(o.subtitles[0].groupId,'"'));var C,M=S(o.subtitles);try{for(M.s();!(C=M.n()).done;){var N=C.value;c.push(gt(N));}}catch(j){M.e(j);}finally{M.f();}}if(at.getOptions().allowClosedCaptionsNone&&o.closedCaptions.length===0)d.push("CLOSED-CAPTIONS=NONE");else if(o.closedCaptions.length>0){d.push('CLOSED-CAPTIONS="'.concat(o.closedCaptions[0].groupId,'"'));var X,U=S(o.closedCaptions);try{for(U.s();!(X=U.n()).done;){var _=X.value;c.push(gt(_));}}catch(j){U.e(j);}finally{U.f();}}if(o.score&&d.push("SCORE=".concat(o.score)),o.allowedCpc){var V,D=[],F=S(o.allowedCpc);try{for(F.s();!(V=F.n()).done;){var z=V.value,K=z.format,J=z.cpcList;D.push("".concat(K,":").concat(J.join("/")));}}catch(j){F.e(j);}finally{F.f();}d.push('ALLOWED-CPC="'.concat(D.join(","),'"'));}o.videoRange&&d.push("VIDEO-RANGE=".concat(o.videoRange)),o.stableVariantId&&d.push('STABLE-VARIANT-ID="'.concat(o.stableVariantId,'"')),o.pathwayId&&d.push('PATHWAY-ID="'.concat(o.pathwayId,'"')),o.programId&&d.push("PROGRAM-ID=".concat(o.programId)),c.push("".concat(m,":").concat(d.join(","))),o.isIFrameOnly||c.push("".concat(o.uri));}function gt(c){var o=["TYPE=".concat(c.type),'GROUP-ID="'.concat(c.groupId,'"'),'NAME="'.concat(c.name,'"')];return c.isDefault!==void 0&&o.push("DEFAULT=".concat(c.isDefault?"YES":"NO")),c.autoselect!==void 0&&o.push("AUTOSELECT=".concat(c.autoselect?"YES":"NO")),c.forced!==void 0&&o.push("FORCED=".concat(c.forced?"YES":"NO")),c.language&&o.push('LANGUAGE="'.concat(c.language,'"')),c.assocLanguage&&o.push('ASSOC-LANGUAGE="'.concat(c.assocLanguage,'"')),c.instreamId&&o.push('INSTREAM-ID="'.concat(c.instreamId,'"')),c.characteristics&&o.push('CHARACTERISTICS="'.concat(c.characteristics,'"')),c.channels&&o.push('CHANNELS="'.concat(c.channels,'"')),c.uri&&o.push('URI="'.concat(c.uri,'"')),"#EXT-X-MEDIA:".concat(o.join(","))}function Pt(c,o,m,d){var a,s,i,g=arguments.length>4&&arguments[4]!==void 0?arguments[4]:1,v=false,P="";if(o.discontinuity&&c.push("#EXT-X-DISCONTINUITY"),o.gap&&c.push("#EXT-X-GAP"),o.key){var C=Ot(o.key);C!==m&&(c.push(C),m=C);}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!==d&&(c.push(M),d=M);}if(o.programDateTime&&c.push("#EXT-X-PROGRAM-DATE-TIME:".concat(at.formatDate(o.programDateTime))),o.dateRange&&c.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&&(P=(function(X,U){var _,V="",D=S(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 z=F.value?":".concat(F.value):"";X.push("#".concat(F.tagName).concat(z));}}}catch(K){D.e(K);}finally{D.f();}return V})(c,o.markers)),o.parts.length>0&&(v=(function(X,U){var _,V=false,D=S(U);try{for(D.s();!(_=D.n()).done;){var F=_.value;if(F.hint){var z=[];if(z.push("TYPE=PART",'URI="'.concat(F.uri,'"')),F.byterange){var K=F.byterange,J=K.offset,j=K.length;z.push("BYTERANGE-START=".concat(J)),j&&z.push("BYTERANGE-LENGTH=".concat(j));}X.push("#EXT-X-PRELOAD-HINT:".concat(z.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($){D.e($);}finally{D.f();}return V})(c,o.parts)),v)return [m,d];if(typeof o.duration=="number"&&!Number.isNaN(o.duration)){var N=g<3?Math.round(o.duration):Ct(o.duration,(a=o.duration,s=a.toString(10),(i=s.indexOf("."))===-1?0:s.length-i-1));c.push("#EXTINF:".concat(N,",").concat(unescape(encodeURIComponent(o.title||""))));}return o.byterange&&c.push("#EXT-X-BYTERANGE:".concat(R(o.byterange))),Array.prototype.push.call(c,"".concat(o.uri)),[m,d,P]}function R(c){var o=c.offset,m=c.length;return "".concat(m,"@").concat(o)}function w(c){var o=[];for(var m in c)o.push("".concat(m,'="').concat(c[m],'"'));return "#EXT-X-DEFINE:".concat(o.join(","))}l.default=function(c,o){at.PARAMCHECK(c),at.ASSERT("Not a playlist",c.type==="playlist");var m=new _t(c.uri);if(m.push("#EXTM3U"),c.version&&m.push("#EXT-X-VERSION:".concat(c.version)),c.independentSegments&&m.push("#EXT-X-INDEPENDENT-SEGMENTS"),c.start&&m.push("#EXT-X-START:TIME-OFFSET=".concat(Ct(c.start.offset)).concat(c.start.precise?",PRECISE=YES":"")),c.defines){var d,a=S(c.defines);try{for(a.s();!(d=a.n()).done;){var s=d.value;m.push(w(s));}}catch(i){a.e(i);}finally{a.f();}}return c.isMasterPlaylist?(function(i,g,v){var P,C;g.contentSteering&&i.push((P=g.contentSteering,C=['SERVER-URI="'.concat(P.serverUri,'"'),'PATHWAY-ID="'.concat(P.pathwayId,'"')],"#EXT-X-CONTENT-STEERING:".concat(C.join(","))));var M,N=S(g.sessionDataList);try{for(N.s();!(M=N.n()).done;){var X=M.value;i.push(jt(X));}}catch(W){N.e(W);}finally{N.f();}var U,_=S(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=S(g.variants.entries());try{for(F.s();!(D=F.n()).done;){var z=I(D.value,2),K=z[0],J=z[1],j=i.length;bt(i,J),v!=null&&v.variantProcessor&&v.variantProcessor(i,j,i.length-1,J,K);}}catch(W){F.e(W);}finally{F.f();}})(m,c,o):(function(i,g,v){var P="",C="",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,z=S(g.segments.entries());try{for(z.s();!(F=z.n()).done;){var K,J=I(F.value,2),j=J[0],W=J[1],$=i.length,tt=I(Pt(i,W,P,C,g.version),3);P=tt[0],C=tt[1],(K=tt[2])==="OUT"?M=!0:K==="IN"&&M&&(M=!1),v!=null&&v.segmentProcessor&&v.segmentProcessor(i,$,i.length-1,W,j);}}catch(ot){z.e(ot);}finally{z.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=S(g.prefetchSegments);try{for(rt.s();!(Q=rt.n()).done;){var ct=Q.value;ct.discontinuity&&i.push("#EXT-X-PREFETCH-DISCONTINUITY"),i.push("#EXT-X-PREFETCH:".concat(ct.uri));}}catch(ot){rt.e(ot);}finally{rt.f();}g.endlist&&i.push("#EXT-X-ENDLIST");var dt,Et=S(g.renditionReports);try{for(Et.s();!(dt=Et.n()).done;){var It=dt.value,q=[];q.push('URI="'.concat(It.uri,'"'),"LAST-MSN=".concat(It.lastMSN)),It.lastPart!==void 0&&q.push("LAST-PART=".concat(It.lastPart)),i.push("#EXT-X-RENDITION-REPORT:".concat(q.join(",")));}}catch(ot){Et.e(ot);}finally{Et.f();}})(m,c,o),m.join(`
`)};}},n={},u=(function h(l){var b=n[l];if(b!==void 0)return b.exports;var y=n[l]={exports:{}};return r[l].call(y.exports,y,y.exports,h),y.exports})(73);return u})()));})(ye)),ye.exports}var Un=kn();function br(e,t){const r=Un.parse(e);if(r.isMasterPlaylist)return {isMaster:true,variants:_n(r,t)};const n=r,u=Fn(n,t);return {isMaster:false,segments:u.segs,mediaSeq:u.mediaSeq,endList:u.endList,targetDuration:n.targetDuration}}function _n(e,t){const r=[];for(const n of e.variants){if(!n.uri)continue;const u=n.resolution,h=u?.width??null,l=u?.height??null;r.push({url:oe(n.uri,t),res:h&&l?`${h}x${l}`:null,w:h,h:l,peak:n.bandwidth??null,avg:n.averageBandwidth??null,codecs:n.codecs??null});}return r}function or(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 Fn(e,t){const r=[];let n=0,u=null;for(let h=0;h<e.segments.length;h++){const l=e.segments[h];let b=null;if(l.byterange){const O=or(l.byterange,n);b=O.header,n=O.next;}else n=0;let y=null,I=false;if(l.map?.uri){const O=oe(l.map.uri,t);let k=null;l.map.byterange&&(k=or(l.map.byterange,0).header),y={uri:O,rangeHeader:k};const E=`${O}|${k||""}`;I=E!==u,I&&(u=E);}let S=null;l.key?.method&&l.key.method!=="NONE"&&(S={method:String(l.key.method).toUpperCase(),uri:l.key.uri?oe(l.key.uri,t):null,iv:l.key.iv?.toString()??null}),r.push({uri:oe(l.uri,t),dur:l.duration||0,range:b,key:S,map:y,needMap:I});}return {segs:r,mediaSeq:e.mediaSequenceBase||0,endList:e.endlist??false}}function Yn(e){let t=true,r=0;const n=new Set;for(const u of e.segs){if(u.range){const h=be(u.range);!h||h.end==null?t=false:r+=h.end-h.start+1;}else t=false;if(u.needMap&&u.map)if(u.map.rangeHeader){const h=`${u.map.uri}|${u.map.rangeHeader}`;if(!n.has(h)){n.add(h);const l=be(u.map.rangeHeader);!l||l.end==null?t=false:r+=l.end-l.start+1;}}else t=false;}return t?r:null}function Vn(e){return e.reduce((t,r)=>t+r.dur,0)}function Ir(e){return e.length===0?false:e.some(t=>t.map)||/\.m4s(\?|$)/i.test(e[0].uri)}function Gn(e){return e.some(t=>t.key?.method==="AES-128")}const Bn=new vr({concurrency:2}),Te=new Set;async function Se(e,t,r,n){const u=await Tr(e,n),h=br(u,e);if(h.isMaster&&h.variants){const b=xe(h.variants)[0],y=h.variants.length,S=[`${y} ${y===1?"quality":"qualities"}`];return b?.res?S.push(`up to ${b.res}`):b?.h&&S.push(`up to ${b.h}p`),{label:S.join(" • "),hlsType:"master",variantCount:y,variants:h.variants,bestVariant:b,enriched:true}}if(h.segments&&h.segments.length>0){const l=h.segments,b=l.length,y=Vn(l),I=h.endList??false,S=Yn({segs:l,mediaSeq:h.mediaSeq??0}),O=r?.res??pr(e),k=Ir(l),E=Gn(l);return {label:fr({resolution:O,duration:y,size:S}),sublabel:Qr(b,k),hlsType:"media",duration:y,segCount:b,resolution:O,isVod:I,isFmp4:k,encrypted:E,isLive:!I,size:S??null,enriched:true}}return {label:"Empty or Invalid",hlsType:"invalid",enriched:true}}async function zn(e,t){try{const r=await Se(e.url,void 0,void 0,t);return Object.assign(e,r),!0}catch(r){return console.error("[SG] Enrichment failed:",r),e.label="Parse Error",e.hlsType="error",e.enriched=true,false}}async function wr(e){if(!e||e.enriched||e.enriching)return false;e.enriching=true;const t=new AbortController,r=setTimeout(()=>t.abort(),Z.ENRICH_TIMEOUT);try{return e._enrichPromise=zn(e,t.signal),await e._enrichPromise,clearTimeout(r),!0}catch(n){clearTimeout(r);const u=n,h=u.message==="Aborted"||u.name==="AbortError";return console.error(`[SG] enrichItem error: ${u.message}`),e.label=h?"Timeout":"Parse Error",e.hlsType="error",e.enriched=true,false}finally{e.enriching=false,e._enrichPromise=null;}}function Sr(e,t){Te.has(e.url)||(Te.add(e.url),Bn.add(async()=>{try{e&&e.kind==="hls"&&!e.enriched&&(await wr(e),t?.());}finally{Te.delete(e.url);}}));}async function jn(e){return e._enrichPromise?(await e._enrichPromise,e.enriched&&e.hlsType!=="error"&&e.hlsType!=="invalid"):wr(e)}const sr="SG_MSG_v1";class st{static instance;handlers=new Map;initialized=false;constructor(){this.handleMessage=this.handleMessage.bind(this);}static get(){return st.instance||(st.instance=new st),st.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 u={type:t,payload:r,magic:sr};n.postMessage(u,"*");}catch(u){console.error("[SG] Failed to send message:",t,u);}}sendToTop(t,r={}){window.top&&this.send(t,r,window.top);}handleMessage(t){const r=t.data;if(!r||typeof r!="object"||!r.type||r.magic!==sr||t.source===window)return;const n=this.handlers.get(r.type);n&&n.forEach(u=>{try{u(r.payload||{},t.source);}catch(h){console.error("[SG] Error in message handler:",h);}});}}const Ae=new Map;function Hn(e){st.get().sendToTop("SG_DETECT",{item:jr(e)});}function $n(e,t){Ae.set(e,t);}function qn(e,t){const r=Ae.get(e);r&&(Ae.delete(e),r(t));}function Kn(){st.get().init(),console.log("[SG] Messaging initialized");}function Wn(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(u=>parseInt(u,16))):new Uint8Array(0)}function Qn(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}const Zn=new Map,Jn=new Map,ti=10;function ei(e){let t="";for(let r=0;r<e.length;r++)t+=e[r].toString(16).padStart(2,"0");return t}async function ri(e,t,r){const n=ei(t),u=await Xe(Zn,Jn,n,()=>crypto.subtle.importKey("raw",t,{name:"AES-CBC"},!1,["decrypt"]),ti);return crypto.subtle.decrypt({name:"AES-CBC",iv:r},u,e)}const ue={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)},ni=(e,t=ue.URL_REVOKE_DELAY)=>{setTimeout(()=>URL.revokeObjectURL(e),t);},Ar=e=>new Error(`Failed to save file: ${e.message}`),Nr=e=>e.abort().catch(()=>{}),Ne=(e,t)=>e.removeEntry(t).catch(()=>{}),ii=(e,t="")=>e.split(".").pop()||t,ai=(e,t)=>{const r=e.lastIndexOf(".");return r===-1?`${e}.part${t}`:`${e.slice(0,r)}.part${t}${e.slice(r)}`};class _e{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 oi(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 si(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 li(e,t,r){return new Promise((n,u)=>{GM_download({url:e,name:t,saveAs:true,onload:()=>{r?.(),n();},onerror:h=>{u(new Error(oi(h?.error,h?.details)));},ontimeout:()=>{u(new Error("Download timed out"));}});})}async function Rr(e,t,r){try{typeof GM_download=="function"?await li(e,t,r):(nt.info("GM_download unavailable, using anchor fallback"),await si(e,t),r?.());}finally{ni(e);}}async function ci(e,t){if(typeof window.showSaveFilePicker!="function"||window.isSecureContext===false)return null;try{const r=ii(e,"mp4"),u=await(await window.showSaveFilePicker({suggestedName:e,types:[{description:"Video file",accept:{[t]:[`.${r}`]}}]})).createWritable(),h=new _e;return {async write(l){h.assertWritable(!0)&&await u.write(l);},async close(){if(h.isAborted)throw new Error("Writer was aborted");if(!h.isClosed){h.setClosed();try{await u.close(),fe(e);}catch(l){throw nt.error("Native close error:",l),Ar(l)}}},abort(){h.isClosed||h.isAborted||(h.setAborted(),Nr(u));}}}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 ui=1440*60*1e3;async function di(e){try{const t=Date.now(),r=[];for await(const[n,u]of e.entries())if(u.kind==="file"&&n.endsWith(".tmp")&&n.startsWith("sg_download_")){const h=n.split("_");if(h.length>=3){const l=parseInt(h[2],10);!isNaN(l)&&t-l>ui&&(nt.info(`Cleaning up stale temp file: ${n}`),r.push(Ne(e,n)));}}r.length>0&&await Promise.all(r);}catch(t){nt.warn("Failed to cleanup stale temp files:",t);}}async function fi(e,t){if(!navigator.storage?.getDirectory)return null;try{const r=await navigator.storage.getDirectory();di(r).catch(()=>{});const n=`sg_download_${Date.now()}_${Math.random().toString(36).slice(2)}.tmp`,u=await r.getFileHandle(n,{create:!0}),h=await u.createWritable(),l=new _e;return {async write(b){l.assertWritable(!0)&&await h.write(b);},async close(){if(l.isAborted)throw new Error("Writer was aborted");if(!l.isClosed){l.setClosed();try{await h.close();const b=await u.getFile(),y=URL.createObjectURL(b);await Rr(y,e,()=>{fe(e);}),setTimeout(()=>{Ne(r,n);},ue.URL_REVOKE_DELAY+5e3);}catch(b){throw nt.error("OPFS close error:",b),Ar(b)}}},abort(){l.isClosed||l.isAborted||(l.setAborted(),Nr(h),Ne(r,n));}}}catch(r){return nt.warn("OPFS initialization failed:",r),null}}function pi(e,t){const r=[];let n=[],u=0,h=0,l=1;const b=new _e,y=()=>{if(u===0)return;const O=new Blob(n,{type:t});r.push(O),n=[],u=0;},I=()=>{n=[],u=0,r.length=0,h=0;},S=async O=>{if(y(),r.length===0&&!O)return;r.length===0&&O&&l===1&&nt.warn("Saving empty file");let k=e;(l>1||!O&&l===1)&&(k=ai(e,l)),nt.info(`Saving part ${l}: ${k}, Size: ${(h/1024/1024).toFixed(2)} MB`);const E=new Blob(r,{type:t});r.length=0,n=[],u=0,h=0;const L=URL.createObjectURL(E);await Rr(L,k,()=>{O&&fe(e);});};return {async write(O){b.assertWritable(true)&&(h+O.length>ue.MAX_FILE_SIZE&&(nt.warn(`File part ${l} limit reached (~1.9GB). Splitting file...`),await S(false),l++),n.push(O),u+=O.length,h+=O.length,u>=ue.MAX_BUFFER_SIZE&&(y(),r.length%5===0&&nt.info(`Part ${l} Buffer: ${r.length} blobs, Size: ${(h/1024/1024).toFixed(2)} MB`)));},async close(){if(b.isAborted)throw new Error("Writer was aborted");b.isClosed||(b.setClosed(),await S(true));},abort(){b.isClosed||b.isAborted||(b.setAborted(),I());}}}async function hi(e,t){try{const n=await ci(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 fi(e);return r?(nt.info("Using OPFS writer"),r):(nt.info("Using blob fallback for download"),pi(e,t))}const mi=100,gi=50,vi=50;class lr{cache=new Map;inflight=new Map;async fetch(t,r,n){if(n?.aborted)throw new Mt(new Error("Aborted"));const u=await Xe(this.cache,this.inflight,t,r,mi);if(n?.aborted)throw new Mt(new Error("Aborted"));return u}clear(){this.cache.clear(),this.inflight.clear();}}class Ei{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>=gi}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 yi{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 Ti{constructor(t){this.mediaSeq=t;}keyCache=new lr;mapCache=new lr;async fetch(t,r,n,u){this.validateEncryption(t);const[h,l]=await Promise.all([this.fetchKey(t,n),this.fetchMap(t,n)]),b=await this.download(t,n,u),y=h?await this.decrypt(b,h,t,r):b;return this.prependMap(new Uint8Array(y),l)}validateEncryption(t){if(t.key?.method&&t.key.method!=="AES-128")throw new Mt(new Error(`Unsupported key method: ${t.key.method}`))}async download(t,r,n){const u=t.range?{Range:t.range}:{};try{return await Ee(t.uri,u,Z.REQUEST_TIMEOUT,h=>n(h.loaded,h.total),r)}catch(h){throw r.aborted?new Mt(new Error("Aborted")):h}}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 Ee(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 u=t.map.rangeHeader?{Range:t.map.rangeHeader}:{},h=await Ee(t.map.uri,u,Z.REQUEST_TIMEOUT,void 0,r);return new Uint8Array(h)},r)}async decrypt(t,r,n,u){const h=n.key.iv?Wn(n.key.iv):Qn(this.mediaSeq+u);return ri(t,r,h)}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 bi{constructor(t,r,n,u,h){this.segments=t,this.onProgress=u,this.onComplete=h,this.queue=new vr({concurrency:Z.CONCURRENCY}),this.writer=new Ei(n),this.progress=new yi(t.length,u),this.fetcher=new Ti(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 Er(async()=>{if(this.canceled)throw new Mt(new Error("Canceled"));const n=await this.fetcher.fetch(this.segments[t],t,r.signal,(u,h)=>{this.progress.setProgress(t,u,h);});this.writer.enqueue(t,n),this.progress.markComplete(t,n.length);},{retries:Z.RETRIES,signal:r.signal,onFailedAttempt:({error:n,attemptNumber:u})=>{this.canceled||console.warn(`[SG] Segment ${t} failed (attempt ${u}): ${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,vi));}handleSegmentError(t,r){this.progress.clear(t),!(this.canceled||r instanceof Mt)&&(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 Ii(e,t,r,n){const u=e.segs.length;console.log("[SG] Starting segment download:",{filename:t,segments:u});const h=r?"video/mp4":"video/mp2t";let l;try{l=await hi(t,h);}catch(y){if(y.name==="AbortError"){n.remove();return}throw y}const b=new bi(e.segs,e.mediaSeq,l,(y,I,S)=>{n.update(y,`${I}/${S}`);},(y,I)=>{y?(n.update(100,""),n.done(true)):n.done(false,I);});n.setOnStop(()=>b.togglePause()?"paused":"resumed"),n.setOnCancel(()=>{b.cancel(),n.remove();}),await b.start();}async function Re(e,t,r){console.log("[SG] Direct download:",e);const n=ut.get(e),u=ur(e,n?.type),h=dr({title:r,ext:u});let l=e,b=()=>{};n?.blob&&(l=URL.createObjectURL(n.blob),b=()=>URL.revokeObjectURL(l));const y=t.createCard(h,e);y.setOnCancel(()=>{b(),y.remove();}),GM_download({url:l,name:h,saveAs:true,onprogress:I=>{I.lengthComputable?y.update(I.loaded/I.total*100,`${Wt(I.loaded)}/${Wt(I.total)}`):y.update(0,Wt(I.loaded));},onload:()=>{y.update(100,""),y.done(true),b(),fe(h);},onerror:I=>{const S=I?.error||"unknown";console.error("[SG] Download error:",{error:S,url:e}),y.done(false,S==="not_succeeded"?"Save failed":S),b();},ontimeout:()=>{y.done(false,"Timeout"),b();}});}async function le(e,t,r,n){console.log("[SG] HLS download:",e);const u=await Se(e);let h=t?t.url:e,l=t;if(!t&&u.hlsType==="master"&&u.variants&&u.variants.length>0){const L=xe(u.variants);if(L.length===0)throw new Error("No variants found");const A=[];for(const T of L){let p;try{p=await Se(T.url,void 0,T);}catch{p={label:fr({resolution:T.res}),hlsType:"error"};}A.push({url:T.url,kind:"variant",label:p.label||"Unknown",sublabel:p.sublabel||null,size:p.size??null,type:null,origin:document.location.origin,pageTitle:n,enriched:true,enriching:false,hlsType:"media",isLive:false,encrypted:false,variant:T});}const f=await r.pickVariant(A);if(!f)return;l=f.variant??null,h=f.url;}const b=await Tr(h),y=br(b,h);if(!y.segments||y.segments.length===0)throw new Error("Invalid playlist: no segments");const I={segs:y.segments,mediaSeq:y.mediaSeq??0,endList:y.endList??false},S=Ir(I.segs),k=dr({title:n,ext:S?"mp4":"ts",quality:l?.res}),E=r.createCard(k,e,I.segs.length);await Ii(I,k,S,E);}async function wi(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"||e.kind==="variant")return le(e.url,e.variant??null,t,e.pageTitle);if(e.kind==="video")return Re(e.url,t,e.pageTitle)}e.remoteWin.postMessage({type:"SG_CMD_DOWNLOAD",payload:{url:e.url,kind:e.kind,variant:e.variant,pageTitle:e.pageTitle}},"*");return}if(e.kind==="hls"&&!e.enriched){t.setBusy(true);try{e._enrichPromise?await e._enrichPromise:await jn(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 Re(e.url,t,e.pageTitle);if(e.kind==="variant")return le(e.url,e.variant??null,t,e.pageTitle);if(e.kind==="hls")return le(e.url,null,t,e.pageTitle)}const Si='@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-title-context{all:initial!important;display:block!important;font-size:13px!important;color:var(--sg-text-gold)!important;margin-bottom:6px!important;font-family:var(--sg-font-body)!important;font-weight:500!important;opacity:.85!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}.sg-variants{all:initial!important;display:flex!important;flex-wrap:wrap!important;gap:8px!important;margin-top:10px!important;padding-top:10px!important;border-top:1px dashed var(--sg-border-subtle)!important;font-family:var(--sg-font-body)!important}.sg-variant-chip{all:initial!important;display:inline-flex!important;align-items:center!important;justify-content:center!important;font-size:13px!important;font-weight:500!important;color:var(--sg-text-main)!important;font-family:var(--sg-font-body)!important;background:#ffffff1a!important;border:1px solid var(--sg-border-subtle)!important;border-radius:6px!important;padding:6px 14px!important;min-width:40px!important;cursor:pointer!important;transition:var(--sg-transition)!important}.sg-variant-chip:hover{background:#ffffff1a!important;color:var(--sg-gold)!important;border-color:#ffffff26!important;transform:translateY(-1px)!important}.sg-variant-chip:active{transform:translateY(0)!important}.sg-variant-chip:focus{border-color:var(--sg-gold)!important;box-shadow:0 0 8px var(--sg-gold-glow)!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}}',Ai=Si,mt={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>`},Le=(...e)=>e.filter(Boolean).join(" ");function B(e,t,r){const n=document.createElement(e);if(t)for(const[u,h]of Object.entries(t))h==null||h===false||n.setAttribute(u,h===true?"":String(h));if(r)if(typeof r=="string")n.innerHTML=r;else for(const u of r)n.append(typeof u=="string"?document.createTextNode(u):u);return n}async function Ni(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"}),u=t.getRootNode();(u instanceof ShadowRoot||u instanceof Document?u:document.body).appendChild(n),n.select();const l=document.execCommand("copy");if(n.remove(),!l)return false}const r=t.innerHTML;return t.innerHTML=mt.check,t.classList.add("copied"),setTimeout(()=>{t.innerHTML=r,t.classList.remove("copied");},1200),true}let At=null,cr=null,qt=null;function Ri(e,t,r){At||(At=B("button",{class:"sg-fab",type:"button"}),cr=B("span",{class:"sg-fab-icon"},mt.download),qt=B("span",{class:"sg-badge"}),At.append(cr,qt),At.addEventListener("click",n=>{n.preventDefault(),n.stopPropagation(),r();}),e.appendChild(At)),At.className=Le("sg-fab",t.show&&"show",t.busy&&"busy",t.idle&&"idle"),At.disabled=t.busy,At.title=`Download media (${t.count})`,qt&&(qt.className=Le("sg-badge",t.count>0&&"show"),qt.textContent=t.count>99?"99+":String(t.count));}let ft=null,Xt=null,ae=null,xt=null;function Li(e,t,r,n,u,h,l,b,y){if(!t){ft&&(ft.classList.remove("show"),e.contains(ft)||(ft=null,Xt=null));return}if(!ft||!e.contains(ft)){e.innerHTML="",ft=B("div",{class:"sg-modal"}),ft.addEventListener("click",E=>E.target===ft&&l());const I=B("div",{class:"sg-card",role:"dialog","aria-modal":"true"}),S=B("div",{class:"sg-card-head"});ae=B("div",{class:"sg-card-title"}),S.append(ae,Ci(mt.close,"Close (Esc)",l)),I.appendChild(S);const O=B("div",{class:"sg-card-body"}),k=B("label",{class:"sg-option"});xt=B("input",{type:"checkbox"}),xt.addEventListener("change",()=>y(xt.checked)),k.append(xt," Exclude small (< 1MB)"),O.appendChild(k),Xt=B("div",{class:"sg-list"}),O.appendChild(Xt),I.appendChild(O),ft.appendChild(I),e.appendChild(ft);}if(ft.classList.add("show"),ae&&(ae.textContent=r),xt){xt.checked=h||false;const I=xt.parentElement;I&&(I.style.display=u&&n.some(S=>S.size!=null)?"flex":"none");}if(Xt)if(Xt.innerHTML="",n.length===0){const I=B("div",{class:"sg-empty"});I.innerHTML="No media detected.<br><small>Play a video to detect streams.</small>",Xt.appendChild(I);}else n.forEach(I=>Xt.appendChild(Oi(I,b)));}function Ci(e,t,r){const n=B("button",{class:"sg-btn",title:t,type:"button"},e);return n.addEventListener("click",u=>{u.preventDefault(),r();}),n}function Oi(e,t){const r=B("div",{class:"sg-item",role:"button",tabindex:"0"}),n=B("div",{class:"sg-item-top"}),u=B("div",{class:"sg-item-title"});u.appendChild(Object.assign(B("span"),{textContent:e.label})),Pi(e).forEach(l=>u.appendChild(l)),n.appendChild(u),e.size&&n.appendChild(Object.assign(B("span",{class:"sg-item-size"}),{textContent:Wt(e.size)}));const h=B("button",{class:"sg-copy-btn",title:"Copy URL",type:"button"},mt.copy);if(h.addEventListener("click",l=>{l.stopPropagation(),Ni(e.url,h);}),n.appendChild(h),r.appendChild(n),e.sublabel&&r.appendChild(Object.assign(B("div",{class:"sg-item-sub"}),{textContent:e.sublabel})),e.pageTitle&&r.appendChild(Object.assign(B("div",{class:"sg-item-title-context"}),{textContent:e.pageTitle})),e.hlsType==="master"&&e.variants&&e.variants.length>0){const l=B("div",{class:"sg-variants"}),b=xe(e.variants).slice(0,6);for(const y of b){if(!y.res&&!y.peak)continue;const I=y.res||(y.peak?`${Math.round(y.peak/1024)}k`:"?"),S=B("button",{class:"sg-variant-chip",type:"button"});S.textContent=I,S.addEventListener("click",O=>{O.stopPropagation(),t({...e,kind:"variant",variant:y,label:I,hlsType:"media",size:null});}),l.appendChild(S);}l.children.length>0&&r.appendChild(l);}return r.addEventListener("click",l=>{l.target.closest(".sg-copy-btn")||l.target.closest(".sg-variant-chip")||t(e);}),r.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),t(e));}),r}function Pi(e){const t=[],r=(n,u)=>{const h=B("span",{class:`sg-badge-type ${u}`});h.textContent=n,t.push(h);};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 Di{constructor(t,r,n,u=0){this.container=t,this.title=r,this.src=n,this.status=u?`${u} segments`:"Starting...",this.el=B("div",{class:"sg-progress",id:`sg-progress-${De()}`});const h=B("div",{class:"sg-progress-row"});h.appendChild(Object.assign(B("div",{class:"sg-progress-name",title:n}),{textContent:r}));const l=B("div",{class:"sg-progress-ctrls"});this.minBtn=B("button",{class:"sg-btn sg-btn-sm btn-minimize",title:"Minimize",type:"button"},mt.minimize),this.minBtn.addEventListener("click",()=>this.toggleMinimize()),l.appendChild(this.minBtn);const b=B("button",{class:"sg-btn sg-btn-sm",title:"Cancel",type:"button"},mt.cancel);b.addEventListener("click",()=>this.onCancelFn?.()),l.appendChild(b),h.appendChild(l),this.el.appendChild(h);const y=B("div",{class:"sg-progress-bar"});this.fillEl=B("div",{class:"sg-progress-fill"}),y.appendChild(this.fillEl),this.el.appendChild(y);const I=B("div",{class:"sg-progress-status"});this.statusEl=B("span"),this.statusEl.textContent=this.status,this.percentEl=B("span"),this.percentEl.textContent="0%",I.append(this.statusEl,this.percentEl),this.el.appendChild(I),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?mt.maximize:mt.minimize,this.minBtn.title=this.minimized?"Expand":"Minimize",this.updateClass();}updateClass(){this.el.className=Le("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"},mt.pause),this.pauseBtn.addEventListener("click",()=>{if(!this.onStop)return;const r=this.onStop();this.paused=r==="paused",this.pauseBtn.innerHTML=this.paused?mt.play:mt.pause,this.pauseBtn.title=this.paused?"Resume":"Pause",this.updateClass();}),this.minBtn.before(this.pauseBtn));}setOnCancel(t){this.onCancelFn=t;}}function Xi(e,t,r,n=0){return new Di(e,t,r,n)}let ht=false,Nt=null,Gt=null,Bt=null;const kt={show:false,busy:false,idle:false,count:0},pt={show:false,title:"Select Media",items:[]};let Ce=null,Lt=null,Lr=null,Cr=null;function Fe(){if(!Z.IS_TOP||ht)return;if(!document.body){const n=document.readyState==="loading"?"DOMContentLoaded":"load";window.addEventListener(n,()=>Fe(),{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=Ai,t.append(r),Nt=document.createElement("div"),Nt.id="sg-fab-container",Nt.style.pointerEvents="auto",Gt=document.createElement("div"),Gt.id="sg-modal-container",Gt.style.pointerEvents="auto",Bt=document.createElement("div"),Bt.id="sg-toast-container",Bt.className="sg-toast",t.append(Nt,Gt,Bt),document.documentElement.append(e),Nt.addEventListener("mouseenter",Ve),Nt.addEventListener("mouseleave",Ye),document.addEventListener("keydown",n=>n.key==="Escape"&&pt.show&&Ge()),ht=true,vt();}function Jt(){return Z.IS_TOP?(ht||Fe(),ht):false}function vt(){if(!ht||!Nt||!Gt)return;Ri(Nt,kt,Or);const e=pt.show?xi():[];Li(Gt,pt.show,pt.title,e,Lt?.filterable??true,et.excludeSmall,Ge,ki,Ui);}function de(){Z.IS_TOP&&(kt.show=true,kt.count=et.validCount,Jt()&&(vt(),Ye()));}function Oe(e){kt.busy=e,ht&&vt();}function Zt(){kt.count=et.validCount,ht&&vt();}function Ye(){Ve(),Ce=setTimeout(()=>{kt.idle=true,ht&&vt();},Z.UI_IDLE_MS);}function Ve(){kt.idle=false,Ce&&clearTimeout(Ce),ht&&vt();}function xi(){const e=pt.items.length>0?pt.items:et.getAllItems();return et.filterItems(e)}function Mi(e="Select Media",t){Jt()&&(pt.show=true,pt.title=e,pt.items=t??[],vt());}function Ge(){pt.show=false,pt.items=[],ht&&vt(),Lt&&(Lt.resolve(null),Lt=null);}function ki(e){Ge(),Lt?(Lt.resolve(e),Lt=null):Cr?.(e);}function Ui(e){et.setExcludeSmall(e),vt();}function Or(){ht&&(Ve(),Ye(),Lr?.());}function Be(e,{title:t="Select Media",filterable:r=true}={}){return Jt()?new Promise(n=>{Lt={resolve:n,title:t,filterable:r},Mi(t,e);}):Promise.resolve(null)}function Pr(e,t,r=0){return !Jt()||!Bt?{update(){},done(){},remove(){},setOnStop(){},setOnCancel(){}}:Xi(Bt,e,t,r)}function _i(){Z.IS_TOP&&(GM_registerMenuCommand("Show Download Panel",()=>{Jt(),de(),Or();}),GM_registerMenuCommand("Clear Cache",()=>{et.clear(),Zt(),GM_notification({text:"Cache cleared",title:"StreamGrabber",timeout:2e3});}));}function Fi(e){e.onFabClick&&(Lr=e.onFabClick),e.onItemSelected&&(Cr=e.onItemSelected);}function Pe(){Z.IS_TOP&&(Zt(),ht&&pt.show&&vt());}class Yi{id;bus;onStopFn;onCancelFn;constructor(t,r){this.id=De(),this.bus=st.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 Vt=new Map;function Vi(){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)}),Fi({onFabClick:ji,onItemSelected:Dr}),Z.IS_TOP&&(Fe(),_i()),Kn(),Z.IS_TOP?Gi():zi(),hn(e=>{Z.IS_TOP?(console.log("[SG] Detected:",e.kind,e.url.slice(0,60)),de(),Zt(),e.kind==="hls"&&Sr(e,()=>Pe())):(console.log("[SG] [iframe] Forwarding detection:",e.kind,e.url.slice(0,60)),Hn(e));}),et.events.itemAdded.subscribe(()=>{de(),Zt();}),et.events.updated.subscribe(()=>{Pe();}),mn(),console.log("[SG] Initialization complete",{isTop:Z.IS_TOP});}function Gi(){const e=st.get();Bi(),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)&&(de(),Zt(),n.kind==="hls"&&Sr(n,()=>Pe())));}),e.on("SG_PROGRESS_START",(t,r)=>{const{id:n,title:u,src:h}=t;if(!Vt.has(n))try{const l=Pr(u,h);l.setOnStop(()=>(st.get().send("SG_CMD_CONTROL",{id:n,action:"stop"},r),"paused")),l.setOnCancel(()=>{st.get().send("SG_CMD_CONTROL",{id:n,action:"cancel"},r),l.remove(),Vt.delete(n);}),Vt.set(n,l);}catch(l){console.error("[SG] Failed to create remote progress card:",l);}}),e.on("SG_PROGRESS_UPDATE",t=>{const{id:r,p:n,txt:u}=t;Vt.get(r)?.update(n,u);}),e.on("SG_PROGRESS_DONE",t=>{const{id:r,ok:n,msg:u}=t,h=Vt.get(r);h&&(h.done(n,u),setTimeout(()=>Vt.delete(r),2500));}),e.on("SG_CMD_PICK",(t,r)=>{const{id:n,items:u,title:h}=t;Be(u,{title:h,filterable:true}).then(l=>{st.get().send("SG_CMD_PICK_RESULT",{id:n,item:l},r);});});}function Bi(){window.addEventListener("popstate",()=>{console.log("[SG] Navigation detected (popstate), clearing state..."),et.clear();}),window.addEventListener("hashchange",()=>{console.log("[SG] Hash change detected, clearing state..."),et.clear();});const e=history.pushState;history.pushState=function(...r){const n=e.apply(this,r);return console.log("[SG] Navigation detected (pushState), clearing state..."),et.clear(),n};const t=history.replaceState;history.replaceState=function(...r){const n=t.apply(this,r);return console.log("[SG] Navigation detected (replaceState), clearing state..."),et.clear(),n};}function zi(){const e=st.get();e.on("SG_CMD_DOWNLOAD",t=>{const{url:r,kind:n,variant:u,pageTitle:h}=t;console.log("[SG] [iframe] Received download command:",{url:r,kind:n}),Hi(r,n,u,h);}),e.on("SG_CMD_PICK_RESULT",t=>{const{id:r,item:n}=t;qn(r,n);});}async function ji(){Oe(true);try{const e=et.getFilteredItems();if(e.length===0){alert("No media detected yet. Try playing a video first.");return}const t=await Be(e,{title:"Select Media",filterable:!0});if(!t)return;await Dr(t);}catch(e){hr(e);}finally{Oe(false);}}async function Dr(e){try{await wi(e,{createCard:Pr,pickVariant:t=>Be(t,{title:"Select Quality",filterable:!0}),setBusy:Oe});}catch(t){hr(t);}}async function Hi(e,t,r,n){console.log("[SG] [iframe] Received download command:",{url:e,kind:t});try{const u=(h,l)=>new Yi(h,l);t==="hls"||t==="variant"?await le(e,r,{createCard:u,pickVariant:async h=>new Promise(l=>{const b=De();$n(b,l),st.get().sendToTop("SG_CMD_PICK",{id:b,items:h,title:"Select Quality"});}),setBusy:()=>{}},n):t==="video"&&await Re(e,{createCard:u,pickVariant:async()=>null,setBusy:()=>{}},n);}catch(u){console.error("[SG] [iframe] Download error:",u);}}Vi();
})();