var youtube=(function(){"use strict";var Ye=Object.defineProperty;var Ue=(_,y,w)=>y in _?Ye(_,y,{enumerable:!0,configurable:!0,writable:!0,value:w}):_[y]=w;var r=(_,y,w)=>Ue(_,typeof y!="symbol"?y+"":y,w);var Ct,xt,I,It,v;function _(n){return n}const y={masterEnabled:!0,adEngineEnabled:!0,sponsorEngineEnabled:!0,blockAllAds:!1,blockTrackers:!1,blockCookieNotices:!1,blockSocial:!1,blockPopups:!1,blockMalware:!0,allowlist:[],confidenceThreshold:.7,sponsorBlockEnabled:!0,sponsorBlockCategories:["sponsor","selfpromo","interaction"],showSkipToast:!0,aiEnhancements:!0,aggressivePruning:!1,resumePlayback:!0,defuseAntiAdblock:!0,blockUrlTracking:!1,ytHideShorts:!1,ytDismissStillWatching:!1,ytDisableEndCards:!1,localOnlyMode:!1,debugLogging:!1,telemetryEnabled:!0,filterUpdatesEnabled:!0,llmProvider:"builtin",apiKeys:{},model:"",fallbackProvider:"builtin",openclawUrl:"http://127.0.0.1:18789/v1/chat/completions"},w="skipSensei.settings";function E(){let n=Promise.resolve();return t=>(n=n.then(t).catch(()=>{}),n)}async function L(){const n=await chrome.storage.local.get(w);return{...y,...n[w]??{}}}E(),E();function V(n){chrome.storage.onChanged.addListener((t,e)=>{e==="local"&&t[w]&&n({...y,...t[w].newValue})})}E(),E();const tt="skipSensei.resumePositions",Rt=720*60*1e3;E();async function Lt(n){const e=((await chrome.storage.local.get(tt))[tt]??{})[n];return!e||Date.now()-e.at>=Rt?null:e.t}const et=E();E();const N="skipSensei.healedSelectors";async function W(){return(await chrome.storage.local.get(N))[N]??{}}function st(n,t){return et(async()=>{const e=await W(),s=e[n]??[];s.includes(t)||s.unshift(t),e[n]=s.slice(0,8),await chrome.storage.local.set({[N]:e})})}function nt(n,t){return et(async()=>{const e=await W();e[n]=t,await chrome.storage.local.set({[N]:e})})}E(),E();let z=!1;L().then(n=>z=n.debugLogging),V(n=>z=n.debugLogging);function u(...n){z&&console.log("[skipSensei]",...n)}const C="#movie_player",A=`${C} video.html5-main-video`,$t=["ad-showing","ad-interrupting"],Dt=[".ytp-ad-skip-button-modern",".ytp-ad-skip-button",".ytp-skip-ad-button"],Nt=[".ytp-ad-overlay-slot",".ytp-ad-overlay-container",".ytp-ad-image-overlay",".ytp-ad-text-overlay"],Pt=[".ytp-ad-overlay-close-button",".ytp-ad-overlay-close-container"],Mt=[".ytp-pause-overlay-container"],Ot=`${C} .ytp-live`,it="ytd-enforcement-message-view-model",Ft="#error-screen, yt-playability-error-supported-renderers",Bt="ytd-popup-container tp-yt-paper-dialog",qt="tp-yt-iron-overlay-backdrop",Ht=[".ytp-ad-simple-ad-badge",".ytp-ad-badge",".ytp-ad-player-overlay-layout"],Yt=10;function P(n){return/[.#[]/.test(n)&&!/^[a-z*\s>+~]+$/i.test(n)}function ot(n){const t=`${n.textContent??""} ${n.getAttribute("aria-label")??""}`;return/skip/i.test(t)}function rt(n){const t=(n.textContent??"").slice(0,600);return/ad ?blocker?|ad[-\s]?block/i.test(t)&&/allow|disable|turn off|violates|terms of service|not allowed|blocked/i.test(t)}function Ut(n){const t=Math.max(0,Math.floor(n)),e=String(t%60).padStart(2,"0"),s=Math.floor(t/60)%60,i=Math.floor(t/3600);return i>0?`${i}:${String(s).padStart(2,"0")}:${e}`:`${s}:${e}`}const Vt=16;function M(n=document.querySelector(C)){return n?$t.some(t=>n.classList.contains(t))?!0:Ht.some(t=>n.querySelector(t)):!1}const Wt=7e3,zt=250,Kt=400,jt=700,Gt=500,Xt=3e3,at=3,h="skip-sensei-ad-cloak",lt="skip-sensei-ad-cloak-style",Jt=`
#${h} {
  position: absolute;
  inset: 0;
  z-index: 9999;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 36px;
  background: #0c0c0c;
  color: #f1f1f1;
  font-family: Roboto, Arial, sans-serif;
  cursor: default;
  overflow: hidden;
}
#${h} .so-anim { position: relative; width: 96px; height: 96px; }
#${h} .so-slash {
  position: absolute; left: 50%; top: 50%;
  width: 230.4px; height: 3px; margin-left: -115.2px; margin-top: -1.5px;
  border-radius: 2px; transform-origin: center;
  background: linear-gradient(90deg, transparent, #ffffff 45%, #7c3aed);
  box-shadow: 0 0 14px #7c3aed;
  animation: so-slash 0.7s ease-out 0.05s both;
}
#${h} .so-enso {
  position: absolute; inset: 0; overflow: visible;
  animation: so-spin 1.5s linear infinite;
  filter: drop-shadow(0 0 12px rgba(124, 58, 237, 0.4));
}
#${h} .so-enso circle {
  animation: so-draw 0.8s cubic-bezier(0.33, 1, 0.68, 1) both;
}
#${h} .so-glyph {
  position: absolute; left: 50%; top: 50%;
  transform: translate(-50%, -50%);
}
#${h} .so-glyph .pop {
  animation: so-pop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1) 0.55s both;
}
#${h} .so-label {
  font-size: 22px; font-weight: 400; color: #f1f1f1; letter-spacing: 0.2px;
}
#${h} .so-brand {
  display: flex; gap: 6px; font-size: 11px; font-weight: 700;
  letter-spacing: 0.2em; margin-top: -14px;
}
#${h} .so-brand .ad { color: #7c3aed; }
#${h} .so-brand .sensei { color: #6a6a6a; }
@keyframes so-spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
@keyframes so-draw { from { stroke-dasharray: 3 100; opacity: 0; } to { stroke-dasharray: 85 100; opacity: 1; } }
@keyframes so-pop { 0% { transform: scale(0); } 70% { transform: scale(1.15); } 100% { transform: scale(1); } }
@keyframes so-slash { 0% { opacity: 0; transform: rotate(122.6deg) scaleX(0.05); } 25% { opacity: 1; } 100% { opacity: 0; transform: rotate(122.6deg) scaleX(1); } }
@media (prefers-reduced-motion: reduce) {
  #${h} .so-anim, #${h} .so-anim * { animation: none !important; }
}
`,d="skip-sensei-hard-block",ct="skip-sensei-hard-block-style",Qt=`
#${d} {
  position: absolute;
  inset: 0;
  z-index: 10000;
  /* Only matters on the fallback host (#movie_player), which YouTube sets to
   * visibility:hidden during the enforcement error \u2014 visibility inherits, but
   * a descendant can override an ancestor's hidden with visibility:visible. */
  visibility: visible !important;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 14px;
  padding: 24px;
  background: #0c0c0c;
  color: #f1f1f1;
  font-family: Roboto, Arial, sans-serif;
  text-align: center;
  cursor: default;
}
#${d} .hb-title { font-size: 20px; font-weight: 500; }
#${d} .hb-body {
  max-width: 460px; font-size: 14px; line-height: 1.5; color: #aaaaaa;
}
#${d} .hb-clear {
  margin-top: 6px; padding: 10px 20px; border: none; border-radius: 18px;
  background: #7c3aed; color: #ffffff; font: 500 14px Roboto, Arial, sans-serif;
  cursor: pointer;
}
#${d} .hb-clear:hover { background: #8b5cf6; }
#${d} .hb-clear:disabled { opacity: 0.6; cursor: default; }
/* The escape hatch that always works, but costs the sign-in: outlined so it
 * reads as a real choice next to the primary action, not as fine print like
 * the dismiss link below it. */
#${d} .hb-secondary {
  padding: 9px 18px; border: 1px solid #3f3f3f; border-radius: 18px;
  background: transparent; color: #d0d0d0;
  font: 400 13px Roboto, Arial, sans-serif; cursor: pointer;
}
#${d} .hb-secondary:hover { border-color: #6a6a6a; color: #ffffff; }
#${d} .hb-secondary:disabled { opacity: 0.6; cursor: default; }
#${d} .hb-dismiss {
  padding: 6px 12px; border: none; border-radius: 14px;
  background: transparent; color: #6a6a6a;
  font: 400 12px Roboto, Arial, sans-serif; cursor: pointer;
}
#${d} .hb-dismiss:hover { color: #aaaaaa; }
#${d} .hb-brand {
  display: flex; gap: 6px; font-size: 11px; font-weight: 700;
  letter-spacing: 0.2em; margin-top: 10px;
}
#${d} .hb-brand .ad { color: #7c3aed; }
#${d} .hb-brand .sensei { color: #6a6a6a; }
`;class Zt{constructor(t){r(this,"observer",null);r(this,"fallbackTimer",null);r(this,"player",null);r(this,"fastForwarding",!1);r(this,"mutedForAd",!1);r(this,"attachRetryTimer",null);r(this,"skipClickedAt",null);r(this,"lastCheckAt",0);r(this,"lastClickDispatchAt",0);r(this,"adClassLast",!1);r(this,"ffLastTime",-1);r(this,"ffLastAdvanceAt",0);r(this,"ffLastSeekAt",0);r(this,"stuckRecoveries",0);r(this,"failureReported",!1);r(this,"cloak",null);r(this,"wallsSeen",0);r(this,"hardBlockSeen",!1);r(this,"hardBlockPanelDismissed",!1);r(this,"healedSkipSelectors",[]);r(this,"wallSelectors",[]);r(this,"wallHealInFlight",!1);r(this,"lastContentTime",0);r(this,"adShowingSince",null);r(this,"healInFlight",!1);r(this,"breakMethods",[]);r(this,"breakAdSeconds",0);r(this,"curAdDuration",0);this.onSkip=t}start(){this.loadHealedSelectors(),this.attachWhenPlayerExists()}async loadHealedSelectors(){const t=await W(),e=t.skipButton??[];this.healedSkipSelectors=e.filter(P),this.healedSkipSelectors.length!==e.length&&(u("purged unsafe healed skip selectors:",e),nt("skipButton",this.healedSkipSelectors));const s=t.enforcementWall??[];this.wallSelectors=s.filter(P),this.wallSelectors.length!==s.length&&nt("enforcementWall",this.wallSelectors)}stop(){var e,s;(e=this.observer)==null||e.disconnect(),this.observer=null,this.fallbackTimer!==null&&clearInterval(this.fallbackTimer),this.fallbackTimer=null,this.attachRetryTimer!==null&&clearTimeout(this.attachRetryTimer),this.attachRetryTimer=null,this.player=null,this.fastForwarding=!1,this.skipClickedAt=null,this.removeCloak(),(s=document.getElementById(d))==null||s.remove();const t=document.querySelector(A);t&&(t.playbackRate!==1&&(t.playbackRate=1),this.mutedForAd&&(t.muted=!1)),this.mutedForAd=!1}get isActive(){return this.observer!==null}attachWhenPlayerExists(t=0){const e=document.querySelector(C);if(!e){t<80&&(this.attachRetryTimer=window.setTimeout(()=>this.attachWhenPlayerExists(t+1),250));return}this.player=e,this.observer=new MutationObserver(()=>this.check()),this.observer.observe(e,{attributes:!0,attributeFilter:["class"],childList:!0,subtree:!0}),this.fallbackTimer=window.setInterval(()=>this.check(),Kt),this.check()}check(){var o;if(!((o=chrome.runtime)!=null&&o.id)){this.stop();return}if(!this.player)return;const t=Date.now(),e=M(this.player),s=e&&!this.adClassLast;if(this.adClassLast=e,!s&&t-this.lastCheckAt<zt)return;if(this.lastCheckAt=t,this.dismissEnforcementWall(),this.removeOverlayAds(),this.dismissPauseOverlays(),!this.adIsShowing()){if(this.sampleContentTime(),this.adShowingSince!==null){const a=(Date.now()-this.adShowingSince)/1e3;a>=.3&&this.reportBreakCleared(a)}this.endFastForward(),this.removeCloak(),this.adShowingSince=null,this.skipClickedAt=null,this.healInFlight=!1,this.ffLastTime=-1,this.ffLastSeekAt=0,this.stuckRecoveries=0,this.failureReported=!1,this.breakMethods=[],this.breakAdSeconds=0,this.curAdDuration=0;return}this.adShowingSince===null&&(this.adShowingSince=Date.now()),this.applyCloak(),this.clickSkipButton()||(this.skipClickedAt=null),Date.now()-this.adShowingSince>Wt&&this.trySelfHeal(),this.fastForwardAd()}sampleContentTime(){const t=document.querySelector(A),e=(t==null?void 0:t.currentTime)??0;Number.isFinite(e)&&e>0&&(this.lastContentTime=e)}resumeSeconds(){return this.lastContentTime}async trySelfHeal(){if(!(this.healInFlight||!this.player)&&(await L()).aiEnhancements){this.healInFlight=!0;try{const e=(this.player.querySelector(".ytp-chrome-bottom")??this.player).outerHTML,s=await this.send({type:"skipSensei:findSelector",html:e,description:'the button that skips or dismisses the currently-playing video ad (e.g. a "Skip Ad" / "Skip Ads" button)'});if(!s||!P(s))return;const i=this.player.querySelector(s);i&&i.offsetParent!==null&&ot(i)&&(u("self-healed skip button selector:",s),this.healedSkipSelectors.includes(s)||this.healedSkipSelectors.push(s),await st("skipButton",s),this.recordHeal("skipButton",s),this.check())}catch{}}}recordHeal(t,e){const s=t==="skipButton"?`self-healed the skip button \u2192 ${e}`:`self-healed the ad-blocker wall \u2192 ${e}`;this.send({type:"skipSensei:logActivity",feature:"AI enhancements",action:s}),this.send({type:"skipSensei:event",kind:"self_heal",fields:{target:t,selector:e}})}tallySkip(t){this.breakMethods.push(t)}noteAdDuration(t){!Number.isFinite(t)||t<.5||t>600||(this.curAdDuration!==0&&Math.abs(t-this.curAdDuration)>1&&(this.breakAdSeconds+=this.curAdDuration),this.curAdDuration=t)}reportBreakCleared(t){const e=t.toFixed(1),s=this.breakMethods.length,i=this.breakMethods.filter(f=>f==="skip-button").length,o=this.breakMethods.filter(f=>f==="fast-forward").length,a=s-i-o,p=Math.round(this.breakAdSeconds+this.curAdDuration),b=p>0?`${p}s of ads`:null,k=i>0?"skip button":o>0?"fast-forward":a>0?"stuck recovery":"skipped";let m;if(s===0)m=`an ad ended on its own after ${e}s`;else if(s===1)m=b?`skipped ${b} in ${e}s (${k})`:`skipped an ad in ${e}s (${k})`;else{const f=[i>0?`${i} skip button`:"",o>0?`${o} fast-forwarded`:"",a>0?`${a} stuck recovery`:""].filter(Boolean);m=`skipped ${s} ads${b?` (${b})`:""} in ${e}s (${f.join(", ")})`}if(this.send({type:"skipSensei:logActivity",feature:"Skip YouTube ads",action:m}),s>0){const f=i>0?"skip-button":o>0?"fast-forward":"stuck-recovery";this.onSkip(f,s,!0)}s>0&&this.send({type:"skipSensei:skipTiming",s:Number(e),m:k,ads:s}),this.send({type:"skipSensei:event",kind:"ad_skip_timing",fields:{seconds:e,method:k,ads:String(s),adSeconds:String(p)}})}send(t){try{return chrome.runtime.sendMessage(t).catch(()=>null)}catch{return Promise.resolve(null)}}applyCloak(){var s,i;const t=document.querySelector(A);if(t&&!t.muted&&(this.mutedForAd=!0,t.muted=!0),(s=this.cloak)!=null&&s.isConnected)return;if(!document.getElementById(lt)){const o=document.createElement("style");o.id=lt,o.textContent=Jt,document.head.appendChild(o)}const e=document.createElement("div");e.id=h,e.innerHTML=`
      <div class="so-anim" aria-hidden="true">
        <div class="so-slash"></div>
        <svg class="so-enso" width="96" height="96" viewBox="0 0 100 100">
          <circle cx="50" cy="50" r="42" fill="none" stroke="#7c3aed"
            stroke-width="6.2" stroke-linecap="round" pathLength="100"
            stroke-dasharray="85 100" transform="rotate(18 50 50)" />
        </svg>
        <div class="so-glyph"><div class="pop">
          <svg width="38.4" height="23.04" viewBox="0 0 100 60">
            <polygon points="0,0 34,30 0,60" fill="#7c3aed" />
            <polygon points="38,0 72,30 38,60" fill="#7c3aed" />
            <rect x="80" y="0" width="12" height="60" rx="5" fill="#7c3aed" />
          </svg>
        </div></div>
      </div>
      <div class="so-label">Skipping ad&hellip;</div>
      <div class="so-brand"><span class="ad">AD</span><span class="sensei">SENSEI</span></div>
    `,(i=this.player)==null||i.appendChild(e),this.cloak=e}removeCloak(){var t;(t=document.getElementById(h))==null||t.remove(),this.cloak=null}endFastForward(){if(!this.fastForwarding&&!this.mutedForAd)return;const t=document.querySelector(A);t&&(t.playbackRate!==1&&(t.playbackRate=1),this.mutedForAd&&(t.muted=!1)),this.mutedForAd=!1,this.fastForwarding=!1}adIsShowing(){return M(this.player)?!0:this.findSkipButton()!==null}findSkipButton(){for(const t of Dt){const e=this.player.querySelector(t);if(e&&e.offsetParent!==null)return e}for(const t of this.healedSkipSelectors){let e=null;try{e=this.player.querySelector(t)}catch{continue}if(e&&e.offsetParent!==null&&ot(e))return e}for(const t of this.player.querySelectorAll("button")){if(t.offsetParent===null)continue;const e=(t.textContent??"").trim(),s=t.getAttribute("aria-label")??"";if(/^skip( ads?)?$/i.test(e)||/\bskip ads?\b/i.test(s))return t}return null}clickSkipButton(){const t=this.findSkipButton();if(!t)return!1;const e=Date.now();return e-this.lastClickDispatchAt>=Gt&&(this.lastClickDispatchAt=e,this.dispatchRealisticClick(t)),this.skipClickedAt===null&&(this.skipClickedAt=e,this.tallySkip("skip-button")),!0}dispatchRealisticClick(t){const e=t.getBoundingClientRect(),s={bubbles:!0,cancelable:!0,view:window,clientX:e.left+e.width/2,clientY:e.top+e.height/2};t.dispatchEvent(new PointerEvent("pointerdown",{...s,pointerId:1,isPrimary:!0})),t.dispatchEvent(new MouseEvent("mousedown",s)),t.dispatchEvent(new PointerEvent("pointerup",{...s,pointerId:1,isPrimary:!0})),t.dispatchEvent(new MouseEvent("mouseup",s)),t.click()}fastForwardAd(){const t=document.querySelector(A);if(!t||!Number.isFinite(t.duration)||t.duration<=0)return;this.noteAdDuration(t.duration);const e=Date.now();if(t.seeking)this.ffLastAdvanceAt=e;else if(t.currentTime!==this.ffLastTime)this.ffLastTime=t.currentTime,this.ffLastAdvanceAt=e;else if(e-this.ffLastAdvanceAt>Xt&&this.stuckRecoveries<at){this.stuckRecoveries++,this.ffLastAdvanceAt=e,this.stuckRecoveries===at&&!this.failureReported&&(this.failureReported=!0,this.send({type:"skipSensei:event",kind:"skip_failed",fields:{reason:"stuck",adSeconds:String(Math.round(t.duration||0))}})),u("ad player looks stuck; recovery attempt",this.stuckRecoveries),t.playbackRate=1,t.currentTime=Math.max(0,t.duration-1),t.play().catch(()=>{}),this.tallySkip("stuck-recovery");return}t.muted||(this.mutedForAd=!0,t.muted=!0),t.playbackRate=Vt,t.paused&&!t.ended&&t.play().catch(()=>{});const s=t.duration-.4;!t.seeking&&s>t.currentTime+1&&e-this.ffLastSeekAt>jt&&(this.skipClickedAt===null||M(this.player))&&(this.ffLastSeekAt=e,t.currentTime=s),this.fastForwarding||(this.fastForwarding=!0,this.skipClickedAt===null&&this.tallySkip("fast-forward"))}dismissEnforcementWall(){var i;let t=document.querySelector(it);if(!t)for(const o of this.wallSelectors){let a=null;try{a=document.querySelector(o)}catch{continue}if(a&&rt(a)){t=a;break}}if(!t){this.trySelfHealWall();return}const e=t.closest(Ft);if(e){this.handleHardBlock(e);return}this.wallsSeen++,this.send({type:"skipSensei:wallSeen",walls:this.wallsSeen}),document.querySelectorAll(Bt).forEach(o=>{o.querySelector(it)&&o.remove()}),(i=t.closest("ytd-popup-container"))==null||i.remove(),t.remove(),document.querySelectorAll(qt).forEach(o=>o.remove()),document.documentElement.style.overflow="",document.body.style.overflow="";const s=document.querySelector(A);s&&s.paused&&s.play().catch(()=>{})}handleHardBlock(t){this.hardBlockSeen||(this.hardBlockSeen=!0,this.wallsSeen++,this.send({type:"skipSensei:wallSeen",walls:this.wallsSeen}),u("YouTube hard playback block detected \u2014 showing recovery panel")),this.showHardBlockPanel(t)}showHardBlockPanel(t){if(this.hardBlockPanelDismissed||document.getElementById(d))return;const e=t??this.player??document.querySelector(C);if(!e)return;if(getComputedStyle(e).position==="static"&&(e.style.position="relative"),!document.getElementById(ct)){const T=document.createElement("style");T.id=ct,T.textContent=Qt,document.head.appendChild(T)}const s=document.createElement("div");s.id=d;const i=document.createElement("div");i.className="hb-title",i.textContent="YouTube has blocked playback for this session";const o=document.createElement("div");o.className="hb-body";const a=this.lastContentTime,p=a>=Yt?` Either way we\u2019ll pick the video back up at ${Ut(a)}.`:"";o.textContent="YouTube flagged this browser session for ad blocking, so it refuses to play videos \u2014 reloading won\u2019t help. Clearing its cookies lifts the flag. Try the first option below \u2014 it keeps you signed in, though it doesn\u2019t always work. Clearing everything always does, but signs you out."+p;const b="Try it without signing me out",k="Clear all cookies & reload (signs you out)",m=document.createElement("button");m.className="hb-clear",m.textContent=b;const f=document.createElement("button");f.className="hb-secondary",f.textContent=k;const _t=(T,D,qe)=>{D.disabled=!0;const He=D.textContent;D.textContent="Clearing\u2026",this.send({type:"skipSensei:clearYtCookies",scope:T,resumeSeconds:this.lastContentTime}).then(Z=>{Z!=null&&Z.ok||(D.disabled=!1,D.textContent=He??qe,o.textContent="Clearing failed \u2014 you can clear cookies for youtube.com from the browser\u2019s site settings instead, then reload.")})};m.addEventListener("click",()=>_t("visitor",m,b)),f.addEventListener("click",()=>_t("all",f,k)),this.send({type:"skipSensei:getWallState"}).then(T=>{!(T!=null&&T.triedVisitorClear)||!s.isConnected||(o.textContent="Still blocked after clearing the visitor cookies \u2014 YouTube is holding the flag somewhere that survives a partial clear. Clearing everything does lift it, at the cost of signing you out of YouTube."+p,m.remove(),f.className="hb-clear")});const U=document.createElement("button");U.className="hb-dismiss",U.textContent="Dismiss and show YouTube's message",U.addEventListener("click",()=>{this.hardBlockPanelDismissed=!0,s.remove()});const X=document.createElement("div");X.className="hb-brand";const J=document.createElement("span");J.className="ad",J.textContent="AD";const Q=document.createElement("span");Q.className="sensei",Q.textContent="SENSEI",X.append(J,Q),s.append(i,o,m,f,U,X),e.appendChild(s)}async trySelfHealWall(){if(this.wallHealInFlight)return;const t=document.querySelector(A),e=document.querySelector("ytd-popup-container tp-yt-paper-dialog, tp-yt-paper-dialog");if(!(!t||!t.paused||!e)&&(await L()).aiEnhancements){this.wallHealInFlight=!0;try{const s=await this.send({type:"skipSensei:findSelector",html:e.outerHTML.slice(0,6e3),description:"the YouTube ad-blocker enforcement message that says video playback will be blocked (the modal to remove), if present"});if(!s||!P(s))return;let i=null;try{i=document.querySelector(s)}catch{return}i&&rt(i)?(u("self-healed enforcement wall selector:",s),this.wallSelectors.includes(s)||this.wallSelectors.push(s),await st("enforcementWall",s),this.recordHeal("enforcementWall",s),this.dismissEnforcementWall()):i&&u("rejected healed wall selector \u2014 does not read as enforcement copy:",s)}catch{}finally{setTimeout(()=>this.wallHealInFlight=!1,5e3)}}}removeOverlayAds(){for(const e of Pt)document.querySelectorAll(e).forEach(s=>s.click());let t=!1;for(const e of Nt)document.querySelectorAll(e).forEach(s=>{s.remove(),t=!0});t&&this.onSkip("overlay-removed")}dismissPauseOverlays(){let t=!1;for(const e of Mt)document.querySelectorAll(e).forEach(s=>{s.remove(),t=!0});t&&this.onSkip("pause-overlay-dismissed")}}function K(n){try{chrome.runtime.sendMessage(n).catch(()=>{})}catch{}}const te=5e3,dt=30,ut=15,ee=5,se=80,ne=250;class ie{constructor(t){r(this,"video",null);r(this,"timer",null);r(this,"attachTimer",null);r(this,"tries",0);r(this,"restoreDone",!1);r(this,"lastSaved",-1);this.videoId=t}start(){oe()&&(this.restoreDone=!0,u("resume: URL carries an explicit timestamp; not restoring")),this.attach()}stop(){this.timer!==null&&clearInterval(this.timer),this.attachTimer!==null&&clearTimeout(this.attachTimer),this.timer=null,this.attachTimer=null,this.save(),this.video=null}attach(){const t=document.querySelector(A);if(!t){if(this.tries++>=se)return;this.attachTimer=setTimeout(()=>this.attach(),ne);return}this.video=t,this.maybeRestore(),this.timer=setInterval(()=>this.save(),te)}async maybeRestore(){if(this.restoreDone)return;this.restoreDone=!0;const t=await Lt(this.videoId);if(t===null||t<dt)return;const e=this.video;if(e){if(!Number.isFinite(e.duration)||e.duration===0){e.addEventListener("loadedmetadata",()=>void this.restore(t),{once:!0});return}this.restore(t)}}async restore(t){const e=this.video;if(!(!e||!Number.isFinite(e.duration))){if(t>=e.duration-ut){K({type:"skipSensei:resumeForget",videoId:this.videoId});return}if(!(e.currentTime>ee)){if(ht()){this.restoreDone=!1,setTimeout(()=>void this.maybeRestore(),1e3);return}e.currentTime=t,u(`resume: restored to ${Math.floor(t)}s`)}}}save(){const t=this.video;if(!t||ht())return;const e=t.currentTime;if(!(!Number.isFinite(e)||e<dt)){if(Number.isFinite(t.duration)&&e>=t.duration-ut){K({type:"skipSensei:resumeForget",videoId:this.videoId}),this.lastSaved=-1;return}Math.abs(e-this.lastSaved)<1||(this.lastSaved=e,K({type:"skipSensei:resumeSave",videoId:this.videoId,seconds:e}))}}}function oe(){const n=new URLSearchParams(location.search);return n.has("t")||n.has("start")}function ht(){const n=document.querySelector(C);return!!n&&/(^|\s)ad-(showing|interrupting)(\s|$)/.test(n.className)}const re=10,ae=200,le="2.20260706.00.00";async function ce(n){try{const t=await de(n);if(t.length>0)return{status:"ok",lines:yt(t)};const e=await fe(n);return e.length>0?{status:"ok",lines:yt(e)}:{status:"no-transcript",lines:[]}}catch{return{status:"error",lines:[]}}}async function de(n){const t=await fetch("https://www.youtube.com/youtubei/v1/get_panel?prettyPrint=false",{method:"POST",credentials:"same-origin",headers:{"content-type":"application/json"},body:JSON.stringify({context:{client:{clientName:"WEB",clientVersion:pt(),hl:"en"}},panelId:"PAmodern_transcript_view",params:ue(n)})});if(!t.ok)return[];const e=await t.json(),s=[];return ft(e,s),s.sort((i,o)=>i.start-o.start),s.map((i,o)=>({start:i.start,end:o+1<s.length?s[o+1].start:i.start+8,text:i.text}))}function ue(n){const t=new TextEncoder().encode(n),e=[10,t.length,...t,24,1],s=[170,9,e.length,...e];return btoa(String.fromCharCode(...s))}function pt(){var n;for(const t of document.querySelectorAll("script")){const e=(n=t.textContent)==null?void 0:n.match(/"INNERTUBE_CLIENT_VERSION":"([^"]+)"/);if(e)return e[1]}return le}function ft(n,t){var o;if(!n||typeof n!="object")return;const e=n,s=e.transcriptSegmentViewModel;if(s!=null&&s.timestamp&&typeof s.simpleText=="string"){const a=s.simpleText.replace(/\s+/g," ").trim();a&&t.push({start:he(s.timestamp),text:a})}const i=e.transcriptSegmentRenderer;if((i==null?void 0:i.startMs)!==void 0){const a=(((o=i.snippet)==null?void 0:o.runs)??[]).map(p=>p.text??"").join("").replace(/\s+/g," ").trim();a&&t.push({start:Number(i.startMs)/1e3,text:a})}for(const a of Object.values(e))ft(a,t)}function he(n){return n.trim().split(":").reduce((t,e)=>t*60+Number(e),0)}async function pe(n){try{const t=await fetch("https://www.youtube.com/youtubei/v1/next?prettyPrint=false",{method:"POST",credentials:"same-origin",headers:{"content-type":"application/json"},body:JSON.stringify({context:{client:{clientName:"WEB",clientVersion:pt(),hl:"en"}},videoId:n})});if(!t.ok)return[];const e=[];return mt(await t.json(),e),e.sort((s,i)=>s.start-i.start)}catch{return[]}}function mt(n,t){var i,o;if(!n||typeof n!="object")return;const e=n,s=e.chapterRenderer;if((s==null?void 0:s.timeRangeStartMillis)!==void 0){const a=((i=s.title)==null?void 0:i.simpleText)??(((o=s.title)==null?void 0:o.runs)??[]).map(p=>p.text??"").join("");a&&t.push({start:Number(s.timeRangeStartMillis)/1e3,title:a})}for(const a of Object.values(e))mt(a,t)}async function fe(n){var o,a;const t=await me(n),e=((a=(o=t==null?void 0:t.captions)==null?void 0:o.playerCaptionsTracklistRenderer)==null?void 0:a.captionTracks)??[],s=Se(e);if(!s)return[];const i=await ge(s.baseUrl);return i.length>0?i:ve(s.baseUrl)}async function me(n){const t=await fetch(`https://www.youtube.com/watch?v=${encodeURIComponent(n)}`,{credentials:"same-origin"});if(!t.ok)return null;const e=await t.text(),s="ytInitialPlayerResponse = ",i=e.indexOf(s);if(i===-1)return null;const o=ye(e,i+s.length);if(!o)return null;try{return JSON.parse(o)}catch{return null}}function ye(n,t){if(n[t]!=="{")return null;let e=0,s=!1;for(let i=t;i<n.length;i++){const o=n[i];if(s)o==="\\"?i++:o==='"'&&(s=!1);else if(o==='"')s=!0;else if(o==="{")e++;else if(o==="}"&&(e--,e===0))return n.slice(t,i+1)}return null}function Se(n){if(n.length===0)return null;const t=n.filter(e=>{var s;return(s=e.languageCode)==null?void 0:s.startsWith("en")});return t.find(e=>e.kind!=="asr")??t[0]??n.find(e=>e.kind!=="asr")??n[0]}async function ge(n){try{const t=await fetch(`${n}&fmt=json3`,{credentials:"same-origin"});if(!t.ok)return[];const e=await t.json(),s=[];for(const i of e.events??[]){if(!i.segs)continue;const o=i.segs.map(p=>p.utf8??"").join("").replace(/\s+/g," ").trim();if(!o)continue;const a=(i.tStartMs??0)/1e3;s.push({start:a,end:a+(i.dDurationMs??0)/1e3,text:o})}return s}catch{return[]}}async function ve(n){try{const t=await fetch(n,{credentials:"same-origin"});if(!t.ok)return[];const e=new DOMParser().parseFromString(await t.text(),"text/xml"),s=[];return e.querySelectorAll("text").forEach(i=>{const o=(i.textContent??"").replace(/\s+/g," ").trim();if(!o)return;const a=Number(i.getAttribute("start")??0);s.push({start:a,end:a+Number(i.getAttribute("dur")??0),text:o})}),s}catch{return[]}}function yt(n){const t=[];for(const e of n){const s=t[t.length-1];s&&e.end-s.start<=re&&s.text.length+e.text.length<=ae?(s.text=`${s.text} ${e.text}`,s.end=Math.max(s.end,e.end)):t.push({...e})}return t}const St="skip-sensei-toast-style",R="skip-sensei-toast",be=5e3,ke=`
.${R} {
  position: absolute;
  left: 12px;
  bottom: 64px;
  z-index: 60;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  border-radius: 8px;
  background: rgba(20, 20, 20, 0.92);
  color: #fff;
  font: 500 13px/1.3 "Roboto", "Arial", sans-serif;
  opacity: 0;
  transform: translateY(6px);
  transition: opacity 0.2s, transform 0.2s;
  pointer-events: auto;
}
.${R}.skip-sensei-visible {
  opacity: 1;
  transform: translateY(0);
}
.${R} button {
  border: 1px solid rgba(255, 255, 255, 0.35);
  border-radius: 6px;
  background: transparent;
  color: #fff;
  font: inherit;
  padding: 3px 10px;
  cursor: pointer;
}
.${R} button:hover {
  background: rgba(255, 255, 255, 0.15);
}
`;let O=null;function we(n,t){const e=document.querySelector(C);if(!e)return;if(!document.getElementById(St)){const a=document.createElement("style");a.id=St,a.textContent=ke,document.head.appendChild(a)}F();const s=document.createElement("div");s.className=R;const i=document.createElement("span");i.textContent=`Skipped sponsor (${Math.round(n)}s)`;const o=document.createElement("button");o.textContent="Unskip",o.title="That was wrong \u2014 go back and don\u2019t skip this again",o.addEventListener("click",()=>{F(),t()}),s.append(i,o),e.appendChild(s),requestAnimationFrame(()=>s.classList.add("skip-sensei-visible")),O=window.setTimeout(F,be)}function F(){O!==null&&clearTimeout(O),O=null,document.querySelectorAll(`.${R}`).forEach(n=>n.remove())}const Ee=120,Ae=/^\s*(ads?|ad ?breaks?|sponsors?|sponsor ?breaks?|sponsored( segment)?|promos?|advertisements?|commercial( break)?s?)\s*$/i,gt=180,B=n=>n.map(t=>`${Math.round(t.start)}-${Math.round(t.end)}s ${t.type}@${t.confidence}`).join(", ")||"(none)";class Te{constructor(t,e){r(this,"status","analyzing");r(this,"reason");r(this,"analyzingSince",Date.now());r(this,"progressDone");r(this,"progressTotal");r(this,"segments",[]);r(this,"chapterSegments",[]);r(this,"externalSegments",[]);r(this,"stopped",!1);r(this,"video",null);r(this,"lastSkipAt",new Map);r(this,"onTimeUpdate",()=>this.checkPlayback());this.videoId=t,this.getSettings=e}get segmentCount(){return this.segments.length}get activeSegments(){const t=this.getSettings().confidenceThreshold;return this.segments.filter(e=>!e.dismissed&&e.confidence>=t)}noteProgress(t,e,s){t!==this.videoId||this.status!=="analyzing"||(this.progressDone=e,this.progressTotal=s,s>1&&e<s&&(this.reason=`chunk ${e+1} of ${s}`))}start(){this.run()}stop(){var t;this.stopped=!0,(t=this.video)==null||t.removeEventListener("timeupdate",this.onTimeUpdate),this.video=null,F(),this.send({type:"skipSensei:abandonAnalysis",videoId:this.videoId})}async reanalyze(){this.stopped||!this.video||this.status==="analyzing"||(await this.send({type:"skipSensei:clearVideoAnalysis",videoId:this.videoId}),!this.stopped&&(this.segments=[...this.externalSegments],this.analyzingSince=Date.now(),this.progressDone=void 0,this.progressTotal=void 0,this.setStatus("analyzing"),await this.analyze(this.video)))}async run(){const t=await this.waitForVideo();if(this.stopped)return;if(!t){this.setStatus("error","Video player not found");return}if(this.video=t,t.addEventListener("timeupdate",this.onTimeUpdate),await this.waitUntilAdFree(t),this.stopped||(this.chapterSegments=await this.loadChapterSegments(t.duration),this.stopped))return;this.chapterSegments.length>0&&(this.segments=[...this.chapterSegments],u("ad chapters:",B(this.chapterSegments)));const e=await this.send({type:"skipSensei:fetchSponsorBlock",videoId:this.videoId})??[];this.stopped||(this.externalSegments=this.dedupeOverlaps([...this.chapterSegments,...e]),this.externalSegments.length>0&&(this.segments=[...this.externalSegments],e.length>0&&u("SponsorBlock:",B(e)),this.setStatus("ready")),await this.analyze(t))}dedupeOverlaps(t){const e=[];for(const s of t)e.some(i=>s.start<i.end&&s.end>i.start)||e.push(s);return e.sort((s,i)=>s.start-i.start)}async loadChapterSegments(t){const e=await pe(this.videoId),s=[];return e.forEach((i,o)=>{var k;if(!Ae.test(i.title))return;const a=(k=e[o+1])==null?void 0:k.start,p=Number.isFinite(t)?t:i.start+gt,b=Math.min(a??p,i.start+gt,p);b>i.start+1&&s.push({start:i.start,end:b,type:"ad-read",confidence:1,source:"chapter"})}),s}mergeSegments(t){const e=[...this.externalSegments];for(const s of t)e.some(o=>s.start<o.end&&s.end>o.start)||e.push({...s,source:"llm"});return e.sort((s,i)=>s.start-i.start)}async analyze(t){const e=await this.send({type:"skipSensei:getAnalysis",videoId:this.videoId});if(this.stopped)return;if(e){u("using cached analysis",e.status,B(e.segments)),this.applyAnalysis(e);return}if(document.querySelector(Ot)||!Number.isFinite(t.duration)){this.setStatusOrKeepExternal("unavailable","live stream has no complete transcript");return}const s=t.duration;if(s<Ee){this.setStatusOrKeepExternal("unavailable","video too short to scan");return}const i=await ce(this.videoId);if(this.stopped)return;if(u("transcript fetch:",i.status,`${i.lines.length} lines`),i.status==="no-transcript"){this.setStatusOrKeepExternal("no-transcript");return}if(i.status==="error"){this.setStatusOrKeepExternal("error","Could not load transcript");return}const o=await this.send({type:"skipSensei:analyzeVideo",videoId:this.videoId,lines:i.lines,durationSeconds:s});if(!this.stopped){if(!o){this.setStatusOrKeepExternal("error","Analysis did not complete");return}u("analysis:",o.status,o.reason??"",B(o.segments)),this.applyAnalysis(o)}}applyAnalysis(t){t.status==="ok"?(this.segments=this.mergeSegments(t.segments),this.setStatus("ready")):this.setStatusOrKeepExternal(t.status==="no-transcript"?"no-transcript":t.status,t.reason)}setStatusOrKeepExternal(t,e){this.externalSegments.length>0?this.setStatus("ready"):this.setStatus(t,e)}setStatus(t,e){this.status=t,this.reason=e,e&&u("status:",t,"\u2014",e)}waitForVideo(){return new Promise(t=>{let e=0;const s=()=>{if(this.stopped)return t(null);const i=document.querySelector(A);if(i&&i.readyState>=1||++e>80)return t(i);setTimeout(s,250)};s()})}waitUntilAdFree(t){return new Promise(e=>{let s=0;const i=()=>{if(this.stopped)return e();if(!M()&&t.readyState>=1)return this.reason==="waiting for the ad to finish"&&(this.reason=void 0),e();if(this.status==="analyzing"&&(this.reason="waiting for the ad to finish"),++s>240)return e();setTimeout(i,500)};i()})}checkPlayback(){var s;if(this.stopped||!this.video||this.segments.length===0)return;if(!((s=chrome.runtime)!=null&&s.id)){this.stop();return}const t=this.getSettings(),e=this.video.currentTime;for(const i of this.segments){if(i.dismissed)continue;const o=this.lastSkipAt.get(i.start);if(!(o!==void 0&&Date.now()-o<5e3||i.confidence<t.confidenceThreshold||!(e>=i.start&&e<i.end-.5)||i.end-e<1)){this.lastSkipAt.set(i.start,Date.now()),this.video.currentTime=i.end,u(`skipped sponsor segment ${i.start}s \u2192 ${i.end}s`),this.send({type:"skipSensei:sponsorSkipped",videoId:this.videoId}),t.showSkipToast&&we(i.end-i.start,()=>this.unskip(i));return}}}unskip(t){t.dismissed=!0,this.video&&(this.video.currentTime=t.start),this.send({type:"skipSensei:reportCorrection",videoId:this.videoId,start:t.start,end:t.end})}send(t){try{return chrome.runtime.sendMessage(t).catch(()=>null)}catch{return Promise.resolve(null)}}}const vt="skip-sensei-yt-annoyances",Ce='ytd-rich-shelf-renderer[is-shorts],ytd-reel-shelf-renderer,ytd-rich-section-renderer:has(ytd-rich-shelf-renderer[is-shorts]),ytd-guide-entry-renderer:has(a[title="Shorts"]),ytd-mini-guide-entry-renderer:has(a[title="Shorts"]){display:none!important}',xe=".ytp-ce-element,.ytp-endscreen-content{display:none!important}";function bt(n){const t=[];n.ytHideShorts&&t.push(Ce),n.ytDisableEndCards&&t.push(xe);const e=document.getElementById(vt);if(t.length===0){e==null||e.remove();return}const s=e??document.createElement("style");s.id=vt,s.textContent=t.join(""),e||(document.head??document.documentElement).appendChild(s)}let kt=0;function Ie(n){if(n.ytDismissStillWatching)for(const t of document.querySelectorAll("yt-confirm-dialog-renderer, tp-yt-paper-dialog")){if(t.offsetParent===null||!/still watching|continue watching|video paused/i.test(t.textContent??""))continue;const e=t.querySelector("#confirm-button")??Array.from(t.querySelectorAll("button, tp-yt-paper-button")).find(s=>s.offsetParent!==null&&/yes|continue|resume|still/i.test(`${s.textContent??""} ${s.getAttribute("aria-label")??""}`));e==null||e.click()}if(n.ytDisableEndCards){const t=document.querySelector('.ytp-autonav-toggle-button[aria-checked="true"]'),e=Date.now();t&&e-kt>3e3&&(kt=e,t.click())}}let x=null,$=null;function wt(){const n=x&&(x.ytDismissStillWatching||x.ytDisableEndCards);n&&$===null?$=window.setInterval(()=>{x&&Ie(x)},2e3):!n&&$!==null&&(clearInterval($),$=null)}function _e(){L().then(n=>{x=n,bt(n),wt()}),V(n=>{x=n,bt(n),wt()})}let S=null,c=null,l=null,g=null;function Et(){return location.pathname==="/watch"}function Re(){return new URLSearchParams(location.search).get("v")}function Le(n,t=1,e=!1){const s={type:"skipSensei:adSkipped",method:n,count:t,quiet:e};try{chrome.runtime.sendMessage(s).catch(()=>{})}catch{c==null||c.stop(),c=null,l==null||l.stop(),l=null,document.removeEventListener("yt-navigate-finish",At)}}function j(){if(!S)return;const n=Et(),t=Re(),e=n&&S.masterEnabled&&S.adEngineEnabled;e&&!c?(c=new Zt(Le),c.start()):!e&&c&&(c.stop(),c=null);const s=n&&t!==null&&S.masterEnabled&&S.resumePlayback;s&&!g?(g=new ie(t),g.start()):!s&&g&&(g.stop(),g=null);const i=n&&t!==null&&S.masterEnabled&&S.sponsorEngineEnabled;i&&!l?(l=new Te(t,()=>S),l.start()):!i&&l&&(l.stop(),l=null)}function At(){c==null||c.stop(),c=null,l==null||l.stop(),l=null,g==null||g.stop(),g=null,j()}function $e(){return{isWatchPage:Et(),adEngineActive:(c==null?void 0:c.isActive)??!1,sponsorStatus:(l==null?void 0:l.status)??"off",sponsorReason:l==null?void 0:l.reason,segmentCount:(l==null?void 0:l.segmentCount)??0,segments:(l==null?void 0:l.activeSegments)??[],analyzingSince:l==null?void 0:l.analyzingSince,progressDone:l==null?void 0:l.progressDone,progressTotal:l==null?void 0:l.progressTotal}}async function De(){S=await L(),V(n=>{S=n,j()}),chrome.runtime.sendMessage({type:"skipSensei:tabNeedsReload",needsReload:!1}).catch(()=>{}),document.addEventListener("yt-navigate-finish",At),_e(),chrome.runtime.onMessage.addListener((n,t,e)=>{(n==null?void 0:n.type)==="skipSensei:getPageStatus"?e($e()):(n==null?void 0:n.type)==="skipSensei:getResumePosition"?e((c==null?void 0:c.resumeSeconds())??0):(n==null?void 0:n.type)==="skipSensei:analysisProgress"?(u(`analyzing chunk ${n.done}/${n.total}`),l==null||l.noteProgress(n.videoId,n.done,n.total)):(n==null?void 0:n.type)==="skipSensei:reanalyzeSponsors"&&(l==null||l.reanalyze())}),j()}De();const Ne={matches:["*://*.youtube.com/*"],runAt:"document_start",main(){}};function q(n,...t){}const Pe={debug:(...n)=>q(console.debug,...n),log:(...n)=>q(console.log,...n),warn:(...n)=>q(console.warn,...n),error:(...n)=>q(console.error,...n)},H=(xt=(Ct=globalThis.browser)==null?void 0:Ct.runtime)!=null&&xt.id?globalThis.browser:globalThis.chrome;var Tt=(I=class extends Event{constructor(t,e){super(I.EVENT_NAME,{}),this.newUrl=t,this.oldUrl=e}},r(I,"EVENT_NAME",G("wxt:locationchange")),I);function G(n){var t;return`${(t=H==null?void 0:H.runtime)==null?void 0:t.id}:youtube:${n}`}const Me=typeof((It=globalThis.navigation)==null?void 0:It.addEventListener)=="function";function Oe(n){let t,e=!1;return{run(){e||(e=!0,t=new URL(location.href),Me?globalThis.navigation.addEventListener("navigate",s=>{const i=new URL(s.destination.url);i.href!==t.href&&(window.dispatchEvent(new Tt(i,t)),t=i)},{signal:n.signal}):n.setInterval(()=>{const s=new URL(location.href);s.href!==t.href&&(window.dispatchEvent(new Tt(s,t)),t=s)},1e3))}}}var Fe=(v=class{constructor(t,e){r(this,"id");r(this,"abortController");r(this,"locationWatcher",Oe(this));this.contentScriptName=t,this.options=e,this.id=Math.random().toString(36).slice(2),this.abortController=new AbortController,this.stopOldScripts(),this.listenForNewerScripts()}get signal(){return this.abortController.signal}abort(t){return this.abortController.abort(t)}get isInvalid(){var t;return((t=H.runtime)==null?void 0:t.id)==null&&this.notifyInvalidated(),this.signal.aborted}get isValid(){return!this.isInvalid}onInvalidated(t){return this.signal.addEventListener("abort",t),()=>this.signal.removeEventListener("abort",t)}block(){return new Promise(()=>{})}setInterval(t,e){const s=setInterval(()=>{this.isValid&&t()},e);return this.onInvalidated(()=>clearInterval(s)),s}setTimeout(t,e){const s=setTimeout(()=>{this.isValid&&t()},e);return this.onInvalidated(()=>clearTimeout(s)),s}requestAnimationFrame(t){const e=requestAnimationFrame((...s)=>{this.isValid&&t(...s)});return this.onInvalidated(()=>cancelAnimationFrame(e)),e}requestIdleCallback(t,e){const s=requestIdleCallback((...i)=>{this.signal.aborted||t(...i)},e);return this.onInvalidated(()=>cancelIdleCallback(s)),s}addEventListener(t,e,s,i){var o;e==="wxt:locationchange"&&this.isValid&&this.locationWatcher.run(),(o=t.addEventListener)==null||o.call(t,e.startsWith("wxt:")?G(e):e,s,{...i,signal:this.signal})}notifyInvalidated(){this.abort("Content script context invalidated"),Pe.debug(`Content script "${this.contentScriptName}" context invalidated`)}stopOldScripts(){var t;document.dispatchEvent(new CustomEvent(v.SCRIPT_STARTED_MESSAGE_TYPE,{detail:{contentScriptName:this.contentScriptName,messageId:this.id}})),(t=this.options)!=null&&t.noScriptStartedPostMessage||window.postMessage({type:v.SCRIPT_STARTED_MESSAGE_TYPE,contentScriptName:this.contentScriptName,messageId:this.id},"*")}verifyScriptStartedEvent(t){var i,o;const e=((i=t.detail)==null?void 0:i.contentScriptName)===this.contentScriptName,s=((o=t.detail)==null?void 0:o.messageId)===this.id;return e&&!s}listenForNewerScripts(){const t=e=>{!(e instanceof CustomEvent)||!this.verifyScriptStartedEvent(e)||this.notifyInvalidated()};document.addEventListener(v.SCRIPT_STARTED_MESSAGE_TYPE,t),this.onInvalidated(()=>document.removeEventListener(v.SCRIPT_STARTED_MESSAGE_TYPE,t))}},r(v,"SCRIPT_STARTED_MESSAGE_TYPE",G("wxt:content-script-started")),v);function We(){}function Y(n,...t){}const Be={debug:(...n)=>Y(console.debug,...n),log:(...n)=>Y(console.log,...n),warn:(...n)=>Y(console.warn,...n),error:(...n)=>Y(console.error,...n)};return(async()=>{try{const{main:n,...t}=Ne;return await n(new Fe("youtube",t))}catch(n){throw Be.error('The content script "youtube" crashed on startup!',n),n}})()})();

youtube;