/**
 * Grax Page Guard
 *
 * Runs in Chrome's MAIN world at document_start, before page scripts.
 * It provides a hardened, compatibility-gated pop-under containment layer:
 * - Locks window.open and event interception surfaces before page scripts execute.
 * - Arms dynamic, parsed, detached, embedded, and shadow-root realms synchronously.
 * - Defuses high-confidence scripted _blank navigations and click-under dispatch.
 * - Applies a destination lock to every programmatic new-window surface, including media-origin gestures.
 * - Guards direct onclick/onpointer-style assignments across DOM globals.
 * - Contains suspicious worker, service-worker, Blob, and data/blob URL execution while preserving verified media pipelines.
 * - Starves hostile pointer/mouse/click sequences in the earliest capture phase.
 * - Preserves protected authentication, CAPTCHA, payment, and trusted first-party application destinations.
 * - Grants a scoped structural pass to verified WAF/anti-bot challenge machinery without relaxing popup destination locks.
 *
 * This file intentionally has no access to extension APIs. Runtime state is
 * synchronized by the isolated content script through a DOM CustomEvent.
 */
try {
(() => {
  'use strict';

  if (globalThis.__graxPageGuardInstalled) return;
  Object.defineProperty(globalThis, '__graxPageGuardInstalled', {
    value: true,
    configurable: false,
    enumerable: false,
    writable: false
  });

  const CONFIG = Object.freeze({
    stateEvent: '__grax_guard_state_v1__',
    riskEvent: '__grax_guard_risk_v1__',
    gestureWindowMs: 1400,
    elevatedRiskMs: 30_000,
    maxCrossOriginOpensPerGesture: 1,
    ignoredLifecycleEvents: Object.freeze(new Set(['unload'])),
    maxMarkupScanBytes: 2_000_000,
    maxBlobInspectionBytes: 350_000,
    mediaRuntimeGraceMs: 20_000,
    securityStructuralPassMs: 12_000,
    maxSecurityScriptScanBytes: 80_000,
    rootRebindDelayMs: 0
  });

  const PROTECTED_DESTINATIONS = Object.freeze([
    'stripe.com',
    'paypal.com',
    'paypalobjects.com',
    'accounts.google.com',
    'oauth2.googleapis.com',
    'appleid.apple.com',
    'login.microsoftonline.com',
    'login.live.com',
    'github.com',
    'facebook.com',
    'hcaptcha.com',
    'recaptcha.net',
    'challenges.cloudflare.com',
    'arkoselabs.com',
    'funcaptcha.com'
  ]);

  // These first-party application origins run large, self-contained media and UI
  // runtimes. Grax deliberately leaves their MAIN worlds untouched. Their CDN
  // families are destination-safelisted separately, so an embedded player can
  // use native framework navigation without granting the embedding site broad
  // cross-origin popup authority.
  const TRUSTED_APPLICATION_ORIGINS = Object.freeze([
    // Grok/X application family: native framework, worker, socket, and UI code
    // must remain untouched while the network layer applies an entity-scoped
    // allow policy. This does not affect any unrelated origin, including Filma24.
    'grok.com',
    'x.com',
    'twitter.com',
    'twimg.com',
    'youtube.com',
    'youtube-nocookie.com',
    'googlevideo.com',
    'ytimg.com',
    'ggpht.com',
    'google.com',
    'twitch.tv',
    'netflix.com'
  ]);


  // Official authenticated dashboards and first-party application shells are
  // granted a structural compatibility pass only. New-window destinations
  // remain governed by the unchanged window.open / anchor / form locks.
  const OFFICIAL_APPLICATION_SHELL_ORIGINS = Object.freeze([
    'cloudflare.com',
    'cloudflareaccess.com',
    'github.com',
    'gitlab.com',
    'microsoft.com',
    'azure.com',
    'amazon.com',
    'aws.amazon.com',
    'atlassian.net',
    'vercel.com',
    'netlify.com',
    'render.com',
    'digitalocean.com',
    'heroku.com',
    'stripe.com',
    'paypal.com',
    'shopify.com',
    'discord.com',
    'slack.com',
    'notion.so',
    'figma.com'
  ]);
  const APPLICATION_SHELL_HOST_PATTERN = /^(?:app|apps|admin|account|accounts|console|dash|dashboard|developer|developers|manage|management|portal|secure|studio)\./i;
  const APPLICATION_SHELL_PATH_PATTERN = /^\/(?:app|admin|account|accounts|console|dash|dashboard|developer|developers|manage|management|portal|secure|settings|studio)(?:\/|$)/i;

  const TRUSTED_PLATFORM_DESTINATIONS = Object.freeze([
    // YouTube and Google media/application delivery.
    'youtube.com',
    'youtube-nocookie.com',
    'youtu.be',
    'googlevideo.com',
    'ytimg.com',
    'ggpht.com',
    'google.com',
    'googleapis.com',
    'gstatic.com',
    'googleusercontent.com',
    // Twitch application and media delivery.
    'twitch.tv',
    'twitchcdn.net',
    'jtvnw.net',
    'ttvnw.net',
    // Netflix application and media delivery.
    'netflix.com',
    'netflix.net',
    'nflxvideo.net',
    'nflximg.net',
    'nflximg.com',
    'nflxext.com',
    'nflxso.net',
    'nflxsearch.net'
  ]);

  // Security-verification infrastructure is intentionally separate from the
  // popup destination safelist. These domains and signatures may receive a
  // temporary structural compatibility pass, but they never gain new-window
  // authority unless they were already explicitly protected above.
  const SECURITY_VERIFICATION_PROVIDERS = Object.freeze([
    'challenges.cloudflare.com',
    'hcaptcha.com',
    'recaptcha.net',
    'captcha-delivery.com',
    'datadome.co',
    'arkoselabs.com',
    'funcaptcha.com'
  ]);

  const SECURITY_VERIFICATION_PATH_PATTERN = /(?:\/cdn-cgi\/(?:challenge-platform|challenge|turnstile)(?:\/|$)|\/turnstile\/v0\/|\/recaptcha\/(?:api|enterprise|releases)(?:\/|$)|\/(?:1|2)\/api\.js(?:[?#]|$)|\/(?:checksiteconfig|captcha|device-check|fc\/gt2\/public_key)(?:[/?#]|$))/i;
  const SECURITY_VERIFICATION_TOKEN_PATTERN = /(?:__cf_chl_(?:f_tk|tk|rt_tk)|cf_chl_|cf-turnstile-response|chlPageData|turnstile|h-captcha-response|g-recaptcha-response|recaptcha|hcaptcha|captcha[-_.]?delivery|datadome|ddv|ddid|arkose|funcaptcha|fc-token|rqdata)/i;
  const SECURITY_VERIFICATION_ELEMENT_PATTERN = /(?:^|[-_\s])(?:cf[-_]?turnstile|cloudflare[-_]?challenge|cf[-_]?chl|h[-_]?captcha|g[-_]?recaptcha|recaptcha|captcha[-_]?delivery|datadome|dd[-_]?captcha|arkose|funcaptcha|security[-_]?challenge|bot[-_]?challenge)(?:[-_\s]|$)/i;
  const SECURITY_VERIFICATION_SCRIPT_PATTERN = /(?:\/cdn-cgi\/challenge-platform\/|challenges\.cloudflare\.com|js\.hcaptcha\.com|hcaptcha(?:\.render|\.execute)?|grecaptcha(?:\.enterprise)?|recaptcha\/(?:api|enterprise)|captcha-delivery\.com|js\.datadome\.co|ddjskey|DataDome|ArkoseEnforcement|FunCaptcha)/i;
  const SECURITY_RELEVANT_ATTRIBUTES = Object.freeze(new Set([
    'src', 'data', 'class', 'id', 'name', 'title', 'role',
    'data-sitekey', 'data-rqdata', 'data-cdata', 'data-chl-page-data',
    'data-callback', 'data-action'
  ]));

  const AGGRESSIVE_SITE_PATTERN = /(?:^|\.)(?:filma24|fmovies|putlocker|soap2day|123movies|gomovies|yesmovies|watchseries|moviesjoy|moviebox|streamm4u|lookmovie|solarmovie|cineb|flixhq)(?:\.|$)/i;
  const AD_DESTINATION_PATTERN = /(?:^|\.)(?:popads|popcash|propellerads|onclicka|onclickads|onclickperformance|adsterra|admaven|ad-maven|exoclick|exosrv|clickadu|clickaine|clickadilla|hilltopads|evadav|richads|trafficstars|trafficjunky|juicyads|plugrush|adsession|supertracker200|dogsprotectedfeed|eagamerz|affforce|rcdn-web)\./i;
  const SUSPICIOUS_URL_PATTERN = /(?:[?&#](?:zoneid|campaignid|clickid|subid|pubid|siteid)=|\/(?:popunder|pop-up|popads|onclicka|propellerads|exoclick)(?:[/?#._-]|$))/i;
  const HIGH_RISK_LISTENER_SOURCE = /(?:popunder|clickunder|pop.?magic|onclicka|propeller|exoclick|adsterra|clickadu|popads|popcash|admaven|hilltopads|trafficstars)/i;
  const DIRECT_POPUP_SOURCE = /(?:\b(?:window|self|top|parent|globalThis)\s*(?:\.\s*open|\[\s*['"]open['"]\s*\])\s*(?:\.\s*(?:call|apply)\s*)?\(|\bopen\s*\(\s*(?:['"`]|(?:atob|decodeURIComponent|unescape)\s*\())/i;
  const POPUP_ALIAS_SOURCE = /\b(?:open|popup|popunder|clickunder|newtab)\w*\s*=\s*(?:window|self|top|parent|globalThis)\s*(?:\.\s*open|\[\s*['"]open['"]\s*\])/i;
  const OBFUSCATION_SOURCE = /(?:\b(?:eval|atob|Function|unescape|decodeURIComponent|String\.fromCharCode)\s*\(|\\x[0-9a-f]{2}|\\u[0-9a-f]{4}|(?:base64|btoa)\b)/i;
  const DYNAMIC_EXECUTION_SOURCE = /\b(?:setTimeout|setInterval)\s*\(\s*(?:['"`]|(?:eval|atob|Function)\s*\()/i;
  const OVERLAY_CONSTRUCTION_SOURCE = /(?:createElement\s*\(\s*['"](?:a|div|iframe)['"]|appendChild\s*\(|insertBefore\s*\(|style\s*\.\s*(?:position|inset|zIndex|pointerEvents|opacity)|setAttribute\s*\(\s*['"](?:target|href|style)['"])/i;
  const POINTER_TRACKING_SOURCE = /(?:\.\s*(?:clientX|clientY|pageX|pageY|screenX|screenY|offsetX|offsetY)\b|\b(?:mousemove|pointermove|touchmove)\b)/i;
  const LISTENER_SIDE_EFFECT_SOURCE = /(?:preventDefault|stopImmediatePropagation|stopPropagation|returnValue\s*=\s*false|location\s*(?:\.href|\.assign|\.replace|=)|document\s*\.\s*location|target\s*=\s*['"]_blank['"])/i;
  const INLINE_POPUP_PATTERN = /(?:window\s*\.\s*open|(?:self|top|parent|globalThis)\s*\.\s*open|popunder|clickunder|onclicka|propeller|exoclick|adsterra|clickadu|popads|popcash|admaven)/i;
  const OVERLAY_NAME_PATTERN = /(?:^|[-_\s])(?:popunder|popup|clickunder|interstitial|ad[-_\s]?overlay|underlay|click[-_\s]?layer)(?:[-_\s]|$)/i;
  const REALM_TAG_PATTERN = /<(?:iframe|object|embed)\b/i;
  const HIDDEN_REALM_MARKUP_PATTERN = /(?:\b(?:width|height)\s*=\s*['"]?0(?:px)?|display\s*:\s*none|visibility\s*:\s*hidden|opacity\s*:\s*0(?:\D|$)|position\s*:\s*(?:fixed|absolute)[^>]{0,180}z-index\s*:\s*(?:999|[1-9]\d{3,}))/i;
  const MARKUP_POPUP_SOURCE = /(?:window\s*\.\s*open|clients\s*\.\s*openWindow|target\s*=\s*['"]_blank['"]|popunder|clickunder|onclicka|propellerads|exoclick|adsterra|clickadu|popads|popcash|admaven|rcdn-web)/i;
  const WORKER_NAVIGATION_SOURCE = /(?:clients\s*\.\s*openWindow|window\s*\.\s*open|self\s*\.\s*open|location\s*(?:\.href|\.assign|\.replace|=)|target\s*=\s*['"]_blank['"])/i;
  const WORKER_SUSPICIOUS_SOURCE = /(?:popunder|clickunder|onclicka|propellerads|exoclick|adsterra|clickadu|popads|popcash|admaven|rcdn-web|eval\s*\(|Function\s*\(|atob\s*\(|String\.fromCharCode)/i;
  const EXECUTABLE_BLOB_MIME = /(?:javascript|ecmascript|html|svg|worker)/i;
  const WORKER_POPUP_SOURCE = /(?:clients\s*\.\s*openWindow|(?:window|self|top|parent|globalThis)\s*\.\s*open\s*\(|target\s*=\s*['"]_blank['"]|postMessage\s*\([^)]*(?:popunder|clickunder|rcdn-web|onclicka|popads|popcash))/i;
  const MEDIA_FRAMEWORK_SOURCE = /(?:\bhls(?:\.js)?\b|video(?:\.js|js)|jwplayer|jw[-_]?player|shaka(?:[-_. ]?player)?|dash(?:\.js)?|mpegts|mpeg[-_]?ts|flv(?:\.js)?|mp4box|mux(?:\.js)?|transmux|demux|remux|MediaSource|ManagedMediaSource|SourceBuffer|appendBuffer|changeType|endOfStream|VideoDecoder|AudioDecoder|EncodedVideoChunk|EncodedAudioChunk|WebCodecs|m3u8|\.mpd\b|#EXTM3U|#EXT-X-|<MPD\b)/i;
  const MEDIA_MIME_PATTERN = /^(?:video|audio)\//i;
  const MEDIA_APPLICATION_MIME_PATTERN = /application\/(?:vnd\.apple\.mpegurl|x-mpegurl|dash\+xml|mp4|mpeg|mp2t|ogg|webm)/i;
  const MEDIA_WORKER_URL_PATTERN = /(?:^|[\/_?&.=+-])(?:hls|m3u8|dash|mpd|video(?:js)?|jwplayer|shaka|mpegts|flv|mp4box|mux|transmux|demux|remux|media|stream|segment|chunk|m4s|mp4|webm|aac|opus)(?:[\/_?&.=+-]|$)/i;
  const MEDIA_PLAYER_CONTAINER_SELECTOR = 'video,audio,video-js,.video-js,.jwplayer,.jw-wrapper,.jwplayer-container,.plyr,.plyr__video-wrapper,.shaka-video-container,.shaka-controls-container,[data-player],[data-video-player],[class*="video-player"],[class*="media-player"],[id*="video-player"],[id^="player"]';
  const MEDIA_CONTROL_HINT = /(?:^|[-_\s])(?:play|pause|mute|unmute|volume|seek|progress|timeline|scrub|fullscreen|full-screen|captions|subtitles|quality|settings|pip|picture-in-picture|replay|forward|rewind|control|controls)(?:[-_\s]|$)/i;
  const MEDIA_PLAYER_HINT = /(?:video-js|vjs-|jwplayer|jw-|plyr|shaka|hls|dash|media-player|video-player|player-container|player-wrapper)/i;
  const AD_UI_HINT = /(?:popunder|clickunder|popup|interstitial|advert|advertisement|ad[-_\s]?(?:overlay|layer|click|link|container)|tracking|tracker|sponsor|rcdn|onclicka|popads|popcash|propeller|exoclick|adsterra|clickadu)/i;
  const PROTECTED_GESTURE_HINT = /(?:oauth|auth|login|log[-_ ]?in|sign[-_ ]?in|google|apple|facebook|github|microsoft|stripe|paypal|checkout|captcha|recaptcha|hcaptcha)/i;
  const CLICK_TYPES = new Set(['click', 'auxclick', 'mousedown', 'mouseup', 'pointerdown', 'pointerup', 'touchstart', 'touchend']);
  const PROGRAMMATIC_CLICK_TYPES = new Set(['click', 'auxclick']);
  const DIRECT_EVENT_PROPERTIES = Object.freeze({
    onclick: 'click',
    onmousedown: 'mousedown',
    onpointerdown: 'pointerdown',
    onmouseup: 'mouseup',
    ontouchstart: 'touchstart'
  });

  const currentHostname = safeHostname(location.href) || safeHostname(document.referrer);
  const trustedApplicationContext = isTrustedApplicationHostname(currentHostname);
  const applicationShellContext = isApplicationShellDocumentContext(currentHostname, location.href);
  const securityVerificationContext = isSecurityVerificationDocumentContext(location.href, document.referrer);
  const protectedCurrentOrigin = trustedApplicationContext || (isProtectedFlowHostname(currentHostname) && !securityVerificationContext);
  const aggressiveByHostname = AGGRESSIVE_SITE_PATTERN.test(currentHostname || '');

  let enabled = !protectedCurrentOrigin;
  let elevatedRiskUntil = aggressiveByHostname ? Number.POSITIVE_INFINITY : 0;
  let gestureSerial = 0;
  let opensInGesture = 0;
  let directHandlerRiskDepth = 0;
  let suppressedGestureUntil = 0;
  let suppressedGestureTarget = null;
  let mediaRuntimeUntil = 0;
  let securityStructuralPassUntil = securityVerificationContext ? Number.POSITIVE_INFINITY : 0;
  let lastTrustedGestureEvent = null;
  let lastTrustedGestureTarget = null;
  let lastTrustedGestureMedia = false;
  let lastTrustedGestureRecordedAt = 0;
  let delegateOpen = typeof window.open === 'function' ? window.open.bind(window) : null;
  let lastGesture = Object.freeze({
    at: 0,
    serial: 0,
    interactive: false,
    suspicious: false,
    targetTag: '',
    intendedUrl: '',
    protectedIntent: false
  });

  const nativeAddEventListener = EventTarget.prototype.addEventListener;
  const nativeRemoveEventListener = EventTarget.prototype.removeEventListener;
  const nativeDispatchEvent = EventTarget.prototype.dispatchEvent;
  const nativeFunctionToString = Function.prototype.toString;
  const nativeDomRuntime = (() => {
    try { return /\[native code\]/.test(nativeFunctionToString.call(nativeAddEventListener)); } catch { return true; }
  })();
  const blockedGestureEvents = new WeakSet();
  const guardedFrameWindows = new WeakMap();
  const armedIframes = new WeakSet();
  const iframeDescriptorRecords = new WeakMap();
  const directEventHandlerRecords = new WeakMap();
  const listenerWrapperRecords = new WeakMap();
  const boundCaptureTargets = new WeakSet();
  const observedRoots = new WeakSet();
  const armedEmbeddedRealms = new WeakSet();
  const guardedShadowRoots = new WeakSet();
  const protectedDocuments = new WeakSet();
  const blobRiskRecords = new WeakMap();
  const objectUrlRiskRecords = new Map();
  const securityVerificationElements = new WeakSet();
  const compatibilityShimNames = new Set();

  const windowPrototype = typeof Window === 'function'
    ? Window.prototype
    : Object.getPrototypeOf(window);
  const htmlElementPrototype = typeof HTMLElement === 'function'
    ? HTMLElement.prototype
    : null;
  const documentPrototype = typeof Document === 'function'
    ? Document.prototype
    : Object.getPrototypeOf(document);
  const elementPrototype = typeof Element === 'function' ? Element.prototype : null;
  const eventTargetPrototype = typeof EventTarget === 'function' ? EventTarget.prototype : null;
  const domImplementationPrototype = typeof DOMImplementation === 'function'
    ? DOMImplementation.prototype
    : null;
  const domParserPrototype = typeof DOMParser === 'function' ? DOMParser.prototype : null;
  const serviceWorkerContainerPrototype = typeof ServiceWorkerContainer === 'function'
    ? ServiceWorkerContainer.prototype
    : null;
  const nativeSetAttribute = elementPrototype && typeof elementPrototype.setAttribute === 'function'
    ? elementPrototype.setAttribute
    : null;
  const nativeCreateElement = documentPrototype && typeof documentPrototype.createElement === 'function'
    ? documentPrototype.createElement
    : null;
  const nativeCreateElementNS = documentPrototype && typeof documentPrototype.createElementNS === 'function'
    ? documentPrototype.createElementNS
    : null;
  const nativeAnchorClick = typeof HTMLAnchorElement === 'function' && typeof HTMLAnchorElement.prototype.click === 'function'
    ? HTMLAnchorElement.prototype.click
    : null;
  const nativeFormSubmit = typeof HTMLFormElement === 'function' && typeof HTMLFormElement.prototype.submit === 'function'
    ? HTMLFormElement.prototype.submit
    : null;
  const nativeFormRequestSubmit = typeof HTMLFormElement === 'function' && typeof HTMLFormElement.prototype.requestSubmit === 'function'
    ? HTMLFormElement.prototype.requestSubmit
    : null;
  const nativeElementDispatchEvent = typeof Element === 'function' && typeof Element.prototype.dispatchEvent === 'function'
    ? Element.prototype.dispatchEvent
    : nativeDispatchEvent;
  const iframeContentWindowDescriptor = typeof HTMLIFrameElement === 'function'
    ? findPropertyDescriptor(HTMLIFrameElement.prototype, 'contentWindow')
    : null;
  const iframeContentDocumentDescriptor = typeof HTMLIFrameElement === 'function'
    ? findPropertyDescriptor(HTMLIFrameElement.prototype, 'contentDocument')
    : null;
  const nativeInnerHTMLDescriptor = elementPrototype ? findPropertyDescriptor(elementPrototype, 'innerHTML') : null;
  const nativeOuterHTMLDescriptor = elementPrototype ? findPropertyDescriptor(elementPrototype, 'outerHTML') : null;
  const nativeInsertAdjacentHTML = elementPrototype && typeof elementPrototype.insertAdjacentHTML === 'function'
    ? elementPrototype.insertAdjacentHTML
    : null;
  const nativeAttachShadow = elementPrototype && typeof elementPrototype.attachShadow === 'function'
    ? elementPrototype.attachShadow
    : null;
  const nativeDocumentWrite = documentPrototype && typeof documentPrototype.write === 'function'
    ? documentPrototype.write
    : null;
  const nativeDocumentWriteln = documentPrototype && typeof documentPrototype.writeln === 'function'
    ? documentPrototype.writeln
    : null;
  const nativeCreateHTMLDocument = domImplementationPrototype && typeof domImplementationPrototype.createHTMLDocument === 'function'
    ? domImplementationPrototype.createHTMLDocument
    : null;
  const nativeParseFromString = domParserPrototype && typeof domParserPrototype.parseFromString === 'function'
    ? domParserPrototype.parseFromString
    : null;
  const NativeWorker = typeof Worker === 'function' ? Worker : null;
  const NativeSharedWorker = typeof SharedWorker === 'function' ? SharedWorker : null;
  const NativeBlob = typeof Blob === 'function' ? Blob : null;
  const nativeCreateObjectURL = typeof URL?.createObjectURL === 'function' ? URL.createObjectURL.bind(URL) : null;
  const nativeRevokeObjectURL = typeof URL?.revokeObjectURL === 'function' ? URL.revokeObjectURL.bind(URL) : null;
  const nativeServiceWorkerRegister = serviceWorkerContainerPrototype && typeof serviceWorkerContainerPrototype.register === 'function'
    ? serviceWorkerContainerPrototype.register
    : null;
  const nativeScriptSrcDescriptor = typeof HTMLScriptElement === 'function'
    ? findPropertyDescriptor(HTMLScriptElement.prototype, 'src')
    : null;
  const nativeIframeSrcDescriptor = typeof HTMLIFrameElement === 'function'
    ? findPropertyDescriptor(HTMLIFrameElement.prototype, 'src')
    : null;
  const nativeObjectDataDescriptor = typeof HTMLObjectElement === 'function'
    ? findPropertyDescriptor(HTMLObjectElement.prototype, 'data')
    : null;

  nativeAddEventListener.call(document, CONFIG.stateEvent, event => {
    const next = event?.detail?.enabled;
    if (typeof next === 'boolean') setRuntimeEnabled(next);
  }, true);

  nativeAddEventListener.call(document, CONFIG.riskEvent, () => {
    elevateRisk();
  }, true);

  installSecurityContextHeuristic();
  installWindowOpenGuard();
  installDirectEventPropertyGuards();
  installSelectiveEventListenerDefuser();
  installCapturePhaseSmothering();
  installDynamicIframeGuard();
  installMarkupRealmGuards();
  installShadowDomGuard();
  installWorkerExecutionGuards();
  installProgrammaticNavigationGuard();
  installRealmMutationObserver();
  installCompatibilityShims();

  function setRuntimeEnabled(next) {
    enabled = Boolean(next) && !protectedCurrentOrigin;
    if (!enabled) {
      elevatedRiskUntil = aggressiveByHostname ? Number.POSITIVE_INFINITY : 0;
      opensInGesture = 0;
      directHandlerRiskDepth = 0;
      suppressedGestureUntil = 0;
      suppressedGestureTarget = null;
      lastTrustedGestureEvent = null;
      lastTrustedGestureTarget = null;
      lastTrustedGestureMedia = false;
      lastTrustedGestureRecordedAt = 0;
      lastGesture = Object.freeze({
        at: 0,
        serial: gestureSerial,
        interactive: false,
        suspicious: false,
        targetTag: '',
        intendedUrl: '',
        protectedIntent: false
      });
      removeCompatibilityShims();
      return;
    }
    installCompatibilityShims();
    bindDocumentShellTargets();
  }

  function installSecurityContextHeuristic() {
    if (trustedApplicationContext || applicationShellContext || (protectedCurrentOrigin && !securityVerificationContext)) return;

    installSecurityUrlPropertyGuard(
      typeof HTMLScriptElement === 'function' ? HTMLScriptElement.prototype : null,
      'src',
      nativeScriptSrcDescriptor
    );
    installSecurityUrlPropertyGuard(
      typeof HTMLIFrameElement === 'function' ? HTMLIFrameElement.prototype : null,
      'src',
      nativeIframeSrcDescriptor
    );
    installSecurityUrlPropertyGuard(
      typeof HTMLObjectElement === 'function' ? HTMLObjectElement.prototype : null,
      'data',
      nativeObjectDataDescriptor
    );

    if (nativeSetAttribute && elementPrototype) {
      const guardedSetAttribute = function graxSecurityAwareSetAttribute(name, value) {
        const normalized = String(name || '').toLowerCase();
        if (SECURITY_RELEVANT_ATTRIBUTES.has(normalized)) {
          markSecurityVerificationElement(this, normalized, value);
        }
        return Reflect.apply(nativeSetAttribute, this, arguments);
      };
      disguiseFunction(guardedSetAttribute, nativeSetAttribute, 'setAttribute', nativeSetAttribute.length);
      hardenFunction(guardedSetAttribute);
      defineLockedValue(elementPrototype, 'setAttribute', guardedSetAttribute, false);
    }

    scanSecurityVerificationNodes(document);
  }

  function installSecurityUrlPropertyGuard(owner, property, descriptor) {
    if (!owner || !descriptor?.set || descriptor.configurable === false) return;
    const nativeGetter = descriptor.get;
    const nativeSetter = descriptor.set;
    const guardedGetter = function graxSecurityUrlGetter() {
      return nativeGetter ? Reflect.apply(nativeGetter, this, []) : '';
    };
    const guardedSetter = function graxSecurityUrlSetter(value) {
      markSecurityVerificationElement(this, property, value);
      return Reflect.apply(nativeSetter, this, [value]);
    };
    disguiseFunction(guardedGetter, nativeGetter || function getSecurityUrl() {}, `get ${property}`, 0);
    disguiseFunction(guardedSetter, nativeSetter, `set ${property}`, 1);
    hardenFunction(guardedGetter);
    hardenFunction(guardedSetter);
    try {
      Object.defineProperty(owner, property, {
        configurable: !nativeDomRuntime,
        enumerable: descriptor.enumerable,
        get: guardedGetter,
        set: guardedSetter
      });
    } catch {}
  }

  function grantSecurityStructuralPass(duration = CONFIG.securityStructuralPassMs) {
    if (securityVerificationContext) {
      securityStructuralPassUntil = Number.POSITIVE_INFINITY;
      return;
    }
    securityStructuralPassUntil = Math.max(securityStructuralPassUntil, Date.now() + Math.max(0, Number(duration) || 0));
  }

  function isDirectSecurityExecutionContext() {
    if (securityVerificationContext) return true;
    let currentScript = null;
    try { currentScript = document.currentScript; } catch {}
    if (!currentScript) return false;
    if (markSecurityVerificationElement(currentScript)) return true;
    let source = '';
    try {
      source = String(currentScript.textContent || '').slice(0, CONFIG.maxSecurityScriptScanBytes);
    } catch {}
    if (source && SECURITY_VERIFICATION_SCRIPT_PATTERN.test(source)) {
      securityVerificationElements.add(currentScript);
      grantSecurityStructuralPass();
      return true;
    }
    return false;
  }

  function isSecurityStructuralPassActive() {
    if (isDirectSecurityExecutionContext()) return true;
    return Date.now() < securityStructuralPassUntil;
  }

  function markSecurityVerificationElement(element, pendingName = '', pendingValue = '') {
    if (!element || typeof element !== 'object') return false;
    if (securityVerificationElements.has(element)) return true;

    const tag = String(element.localName || element.tagName || '').toLowerCase();
    let urlCandidate = '';
    if (['src', 'data', 'href'].includes(String(pendingName || '').toLowerCase())) {
      urlCandidate = String(pendingValue || '');
    }
    if (!urlCandidate) {
      try {
        urlCandidate = String(
          safeGetAttribute(element, tag === 'object' ? 'data' : 'src') ||
          (tag === 'object' ? element.data : element.src) ||
          ''
        );
      } catch {}
    }

    let identity = '';
    try {
      const className = typeof element.className === 'string' ? element.className : element.className?.baseVal || '';
      identity = `${element.id || ''} ${className} ${element.name || ''} ${safeGetAttribute(element, 'title') || ''} ${safeGetAttribute(element, 'role') || ''} ${safeGetAttribute(element, 'data-sitekey') || ''} ${safeGetAttribute(element, 'data-rqdata') || ''} ${safeGetAttribute(element, 'data-cdata') || ''} ${pendingName} ${pendingValue}`;
    } catch {}

    let scriptText = '';
    if (tag === 'script') {
      try { scriptText = String(element.textContent || '').slice(0, CONFIG.maxSecurityScriptScanBytes); } catch {}
    }

    const verified = Boolean(
      isSecurityVerificationReference(urlCandidate, location.href) ||
      SECURITY_VERIFICATION_ELEMENT_PATTERN.test(identity) ||
      SECURITY_VERIFICATION_SCRIPT_PATTERN.test(scriptText)
    );
    if (!verified) return false;

    securityVerificationElements.add(element);
    grantSecurityStructuralPass();
    return true;
  }

  function scanSecurityVerificationNodes(root) {
    if (!root) return;
    try { markSecurityVerificationElement(root); } catch {}
    let nodes = [];
    try {
      nodes = root.querySelectorAll?.('script,iframe,object,embed,[data-sitekey],.cf-turnstile,.h-captcha,.g-recaptcha') || [];
    } catch {}
    for (const node of nodes) markSecurityVerificationElement(node);
  }

  function isSecurityVerificationInteraction(event, target) {
    if (securityVerificationContext) return true;
    if (markSecurityVerificationElement(target)) return true;
    try {
      const path = event?.composedPath?.() || [];
      return path.some(node => markSecurityVerificationElement(node));
    } catch {
      return false;
    }
  }

  function installCapturePhaseSmothering() {
    if (protectedCurrentOrigin || securityVerificationContext || applicationShellContext) return;
    bindCaptureTarget(window);
    bindCaptureTarget(document);
    bindDocumentShellTargets();

    try {
      nativeAddEventListener.call(document, 'readystatechange', bindDocumentShellTargets, true);
      nativeAddEventListener.call(document, 'DOMContentLoaded', bindDocumentShellTargets, true);
    } catch {}
  }

  function bindDocumentShellTargets() {
    bindCaptureTarget(document.documentElement);
    bindCaptureTarget(document.body);
  }

  function bindCaptureTarget(target, addEventListenerDelegate = nativeAddEventListener) {
    if (!target || boundCaptureTargets.has(target) || typeof addEventListenerDelegate !== 'function') return;
    boundCaptureTargets.add(target);
    const options = Object.freeze({ capture: true, passive: false });
    for (const type of CLICK_TYPES) {
      try {
        Reflect.apply(addEventListenerDelegate, target, [type, captureTrustedInteraction, options]);
      } catch {}
    }
  }

  function captureTrustedInteraction(event) {
    if (!enabled || !event?.isTrusted) return;
    if (blockedGestureEvents.has(event)) {
      blockEvent(event);
      return;
    }

    const target = firstElementInPath(event);
    if (isSecurityVerificationInteraction(event, target)) {
      rememberTrustedGesture(event, target, false);
      return;
    }
    if (isSuppressedGestureContinuation(event, target)) {
      elevateRisk();
      blockedGestureEvents.add(event);
      blockEvent(event);
      if (String(event.type || '').toLowerCase() === 'click') clearSuppressedGesture();
      return;
    }

    const mediaInteraction = isMediaInteractionEvent(event, target);
    rememberTrustedGesture(event, target, mediaInteraction);
    if (mediaInteraction) markMediaRuntime();
    const suspiciousSurface = mediaInteraction ? null : findSuspiciousClickSurface(event);
    // A media click must be allowed to reach the player. Dangerous direct handlers
    // execute inside a destination-locked scope so their playback branch survives
    // while every external popup branch is still denied by inspectWindowOpen().
    const dangerousDirectHandler = mediaInteraction ? null : findDangerousDirectHandlerForEvent(event);
    const dangerousAnchor = findDangerousAnchorInEvent(event, mediaInteraction);
    const dangerousForm = findDangerousFormInEvent(event, mediaInteraction);
    const interactive = mediaInteraction || isLegitimateInteractiveTarget(target);
    const suspicious = Boolean(suspiciousSurface || dangerousDirectHandler || dangerousAnchor || dangerousForm);
    const intendedUrl = intendedNavigationUrl(target);
    const protectedIntent = hasProtectedGestureIntent(target, intendedUrl);

    gestureSerial += 1;
    opensInGesture = 0;
    lastGesture = Object.freeze({
      at: Date.now(),
      serial: gestureSerial,
      interactive,
      mediaInteraction,
      suspicious,
      targetTag: target?.tagName || '',
      intendedUrl,
      protectedIntent
    });

    if (!enabled || protectedCurrentOrigin || !suspicious) return;
    elevateRisk();
    suppressGestureSequence(target);
    blockedGestureEvents.add(event);
    blockEvent(event);
    if (String(event.type || '').toLowerCase() === 'click') clearSuppressedGesture();
  }

  function suppressGestureSequence(target) {
    suppressedGestureUntil = Date.now() + CONFIG.gestureWindowMs;
    suppressedGestureTarget = target || null;
  }

  function clearSuppressedGesture() {
    suppressedGestureUntil = 0;
    suppressedGestureTarget = null;
  }

  function isSuppressedGestureContinuation(event, target) {
    if (!enabled || protectedCurrentOrigin || Date.now() > suppressedGestureUntil) {
      if (suppressedGestureUntil) clearSuppressedGesture();
      return false;
    }
    const type = String(event?.type || '').toLowerCase();
    if (!CLICK_TYPES.has(type)) return false;
    if (!suppressedGestureTarget || !target) return true;
    if (target === suppressedGestureTarget) return true;
    try {
      if (suppressedGestureTarget.contains?.(target)) return true;
      if (target.contains?.(suppressedGestureTarget)) return true;
    } catch {}
    return false;
  }

  function installWindowOpenGuard() {
    if (!delegateOpen || protectedCurrentOrigin) return;

    const guardedOpen = function graxGuardedWindowOpen(...args) {
      if (!enabled) return safeDelegateOpen(args);

      const decision = inspectWindowOpen(args[0], window, args[1]);
      if (decision.block) {
        starveActivePopupGesture();
        return createSyntheticWindowProxy();
      }

      if (decision.crossOrigin || decision.isBlankOpen) opensInGesture += 1;
      return safeDelegateOpen(args);
    };

    disguiseFunction(guardedOpen, delegateOpen, 'open', 3);
    hardenFunction(guardedOpen);
    defineLockedValue(window, 'open', guardedOpen, true);
    defineLockedValue(windowPrototype, 'open', guardedOpen, true);
  }

  function inspectWindowOpen(rawUrl, ownerWindow, requestedTarget = '') {
    const baseHref = safeWindowHref(ownerWindow) || location.href;
    const ownerOrigin = safeWindowOrigin(ownerWindow) || location.origin;
    const parsed = parseDestination(rawUrl, baseHref);
    const recentGesture = Date.now() - lastGesture.at <= CONFIG.gestureWindowMs;
    const browserActivation = safeWindowActivation(ownerWindow) || Boolean(navigator.userActivation?.isActive);
    const trustedActivation = recentGesture || browserActivation;
    const crossOrigin = parsed.url ? parsed.url.origin !== ownerOrigin : false;
    const protectedDestination = parsed.hostname && isProtectedHostname(parsed.hostname);
    const adDestination = parsed.hostname && AD_DESTINATION_PATTERN.test(parsed.hostname);
    const suspiciousUrl = parsed.url && SUSPICIOUS_URL_PATTERN.test(parsed.url.href);
    const riskElevated = Date.now() < elevatedRiskUntil;
    const isBlankOpen = rawUrl == null || rawUrl === '' || rawUrl === 'about:blank';
    const dangerousScheme = isPopupCapableScheme(parsed.url);
    const intendedNavigation = matchesIntendedNavigation(parsed.url, lastGesture.intendedUrl);
    const protectedPopupIntent = lastGesture.protectedIntent || PROTECTED_GESTURE_HINT.test(String(requestedTarget || ''));
    const externalDestinationLocked = Boolean(crossOrigin && !protectedDestination);

    let block = false;

    // Programmatic new-window creation is destination-authorized, never gesture-authorized.
    // A media/player click may retain playback activation, but it cannot authorize an
    // unrelated external tab. Only same-origin or explicitly safelisted destinations pass.
    if (externalDestinationLocked || dangerousScheme) {
      block = true;
    } else if (protectedDestination) {
      block = false;
    } else if (isBlankOpen && protectedPopupIntent && trustedActivation && lastGesture.interactive && !lastGesture.suspicious) {
      block = false;
    } else if (isBlankOpen) {
      block = true;
    } else if (adDestination || suspiciousUrl) {
      block = true;
    } else if (!trustedActivation && crossOrigin) {
      block = true;
    } else if (lastGesture.suspicious && crossOrigin) {
      block = true;
    } else if (directHandlerRiskDepth > 0 && crossOrigin && !intendedNavigation) {
      block = true;
    } else if ((riskElevated || aggressiveByHostname) && crossOrigin && !intendedNavigation) {
      block = true;
    } else if (crossOrigin && !lastGesture.interactive) {
      block = true;
    } else if (crossOrigin && opensInGesture >= CONFIG.maxCrossOriginOpensPerGesture) {
      block = true;
    }

    return {
      block,
      crossOrigin,
      isBlankOpen,
      protectedDestination: Boolean(protectedDestination),
      destinationLocked: externalDestinationLocked || dangerousScheme
    };
  }

  function installDirectEventPropertyGuards() {
    if (protectedCurrentOrigin || securityVerificationContext || applicationShellContext) return;
    const targets = [
      { owner: htmlElementPrototype, descriptorSource: htmlElementPrototype },
      { owner: documentPrototype, descriptorSource: documentPrototype },
      // Chromium exposes Window event-handler accessors as own properties on
      // the WindowProxy rather than on Window.prototype. Capture that native
      // descriptor once, then guard both surfaces so direct assignments cannot
      // bypass the MAIN-world scanner in either representation.
      { owner: windowPrototype, descriptorSource: window },
      { owner: window, descriptorSource: window }
    ].filter(({ owner }, index, list) => owner && list.findIndex(entry => entry.owner === owner) === index);

    const plans = [];
    for (const { owner, descriptorSource } of targets) {
      for (const [property, eventType] of Object.entries(DIRECT_EVENT_PROPERTIES)) {
        const nativeDescriptor = findPropertyDescriptor(descriptorSource, property);
        if (nativeDescriptor && typeof nativeDescriptor.set === 'function') {
          plans.push({ owner, property, eventType, nativeDescriptor });
        }
      }
    }

    for (const plan of plans) installDirectEventPropertyGuard(plan);
  }

  function installDirectEventPropertyGuard({ owner, property, eventType, nativeDescriptor }) {

    const nativeGetter = typeof nativeDescriptor.get === 'function'
      ? nativeDescriptor.get
      : null;
    const nativeSetter = nativeDescriptor.set;

    const guardedGetter = function graxDirectEventGetter() {
      const record = getDirectEventHandlerRecord(this, property);
      if (record?.wrapped) return record.wrapped;
      try {
        return nativeGetter ? Reflect.apply(nativeGetter, this, []) : null;
      } catch {
        return null;
      }
    };

    const guardedSetter = function graxDirectEventSetter(candidate) {
      if (!enabled || applicationShellContext || isSecurityStructuralPassActive() || markSecurityVerificationElement(this)) {
        deleteDirectEventHandlerRecord(this, property);
        try { return Reflect.apply(nativeSetter, this, [candidate]); } catch { return undefined; }
      }
      if (typeof candidate !== 'function') {
        deleteDirectEventHandlerRecord(this, property);
        try {
          return Reflect.apply(nativeSetter, this, [candidate]);
        } catch {
          return undefined;
        }
      }

      const analysis = analyzePopunderListener(candidate, eventType);
      const wrapped = createGuardedDirectEventHandler(candidate, eventType, analysis);
      setDirectEventHandlerRecord(this, property, {
        original: candidate,
        wrapped,
        eventType,
        dangerous: analysis.highConfidence,
        suspicious: analysis.suspicious
      });

      try {
        return Reflect.apply(nativeSetter, this, [wrapped]);
      } catch {
        deleteDirectEventHandlerRecord(this, property);
        return undefined;
      }
    };

    disguiseFunction(guardedGetter, nativeGetter || function getEventHandler() {}, `get ${property}`, 0);
    disguiseFunction(guardedSetter, nativeSetter, `set ${property}`, 1);
    hardenFunction(guardedGetter);
    hardenFunction(guardedSetter);

    try {
      Object.defineProperty(owner, property, {
        configurable: !nativeDomRuntime,
        enumerable: nativeDescriptor.enumerable,
        get: guardedGetter,
        set: guardedSetter
      });
    } catch {}
  }

  function createGuardedDirectEventHandler(handler, eventType, analysis) {
    const wrapped = function graxDirectEventHandler(event) {
      if (!enabled || protectedCurrentOrigin || securityVerificationContext || isSecurityVerificationInteraction(event, firstElementInPath(event))) {
        return Reflect.apply(handler, this, arguments);
      }

      const mediaInteraction = Boolean(event?.isTrusted && isMediaInteractionEvent(event, firstElementInPath(event)));
      if (mediaInteraction) markMediaRuntime();
      const suspiciousSurface = Boolean(event?.isTrusted && !mediaInteraction && findSuspiciousClickSurface(event));
      if ((analysis.highConfidence || suspiciousSurface) && !mediaInteraction) {
        elevateRisk();
        blockEvent(event);
        return false;
      }

      const riskScoped = analysis.suspicious || analysis.highConfidence;
      if (riskScoped) directHandlerRiskDepth += 1;
      try {
        return Reflect.apply(handler, this, arguments);
      } finally {
        if (riskScoped) directHandlerRiskDepth = Math.max(0, directHandlerRiskDepth - 1);
      }
    };

    disguiseFunction(wrapped, handler, handler.name || `on${eventType}`, handler.length);
    return wrapped;
  }

  function setDirectEventHandlerRecord(target, property, record) {
    if (!target) return;
    let records = directEventHandlerRecords.get(target);
    if (!records) {
      records = new Map();
      directEventHandlerRecords.set(target, records);
    }
    records.set(property, record);
  }

  function getDirectEventHandlerRecord(target, property) {
    try {
      return directEventHandlerRecords.get(target)?.get(property) || null;
    } catch {
      return null;
    }
  }

  function deleteDirectEventHandlerRecord(target, property) {
    try {
      const records = directEventHandlerRecords.get(target);
      if (!records) return;
      records.delete(property);
      if (!records.size) directEventHandlerRecords.delete(target);
    } catch {}
  }

  function findDangerousDirectHandlerForEvent(event) {
    const eventType = String(event?.type || '').toLowerCase();
    const property = Object.keys(DIRECT_EVENT_PROPERTIES)
      .find(name => DIRECT_EVENT_PROPERTIES[name] === eventType);
    if (!property) return null;

    const candidates = [];
    try {
      candidates.push(...(event.composedPath?.() || []));
    } catch {}
    candidates.push(event?.target, document.body, document.documentElement, document, window);

    const seen = new Set();
    for (const candidate of candidates) {
      if (!candidate || seen.has(candidate)) continue;
      seen.add(candidate);
      const record = getDirectEventHandlerRecord(candidate, property);
      if (record?.dangerous) return record;
    }
    return null;
  }

  function installDynamicIframeGuard() {
    if (protectedCurrentOrigin || securityVerificationContext || applicationShellContext) return;
    if (!nativeCreateElement || !documentPrototype) return;

    const guardedCreateElement = function graxCreateElement(localName, options) {
      const element = Reflect.apply(nativeCreateElement, this, arguments);
      markSecurityVerificationElement(element);
      armEmbeddedRealm(element, localName);
      return element;
    };

    disguiseFunction(guardedCreateElement, nativeCreateElement, 'createElement', nativeCreateElement.length);

    try {
      Object.defineProperty(documentPrototype, 'createElement', {
        configurable: !nativeDomRuntime,
        enumerable: false,
        writable: !nativeDomRuntime,
        value: guardedCreateElement
      });
    } catch {}

    if (!nativeCreateElementNS) return;

    const guardedCreateElementNS = function graxCreateElementNS(namespace, qualifiedName, options) {
      const element = Reflect.apply(nativeCreateElementNS, this, arguments);
      markSecurityVerificationElement(element);
      armEmbeddedRealm(element, qualifiedName);
      return element;
    };

    disguiseFunction(guardedCreateElementNS, nativeCreateElementNS, 'createElementNS', nativeCreateElementNS.length);

    try {
      Object.defineProperty(documentPrototype, 'createElementNS', {
        configurable: !nativeDomRuntime,
        enumerable: false,
        writable: !nativeDomRuntime,
        value: guardedCreateElementNS
      });
    } catch {}
  }

  function armDynamicIframe(iframe) {
    if (!enabled || applicationShellContext || !iframe || armedIframes.has(iframe)) return iframe;
    if (markSecurityVerificationElement(iframe)) return iframe;
    armedIframes.add(iframe);
    const localPrototype = Object.getPrototypeOf(iframe);
    iframeDescriptorRecords.set(iframe, {
      window: findPropertyDescriptor(localPrototype, 'contentWindow') || iframeContentWindowDescriptor,
      document: findPropertyDescriptor(localPrototype, 'contentDocument') || iframeContentDocumentDescriptor
    });

    protectIframeWindow(readNativeIframeWindow(iframe));
    protectIframeDocument(readNativeIframeDocument(iframe));

    const localDescriptors = iframeDescriptorRecords.get(iframe);
    if (localDescriptors?.window?.get) {
      try {
        Object.defineProperty(iframe, 'contentWindow', {
          configurable: !nativeDomRuntime,
          enumerable: localDescriptors.window.enumerable,
          get() {
            const frameWindow = readNativeIframeWindow(this);
            if (enabled && !applicationShellContext && !markSecurityVerificationElement(this)) protectIframeWindow(frameWindow);
            return frameWindow;
          }
        });
      } catch {}
    }

    if (localDescriptors?.document?.get) {
      try {
        Object.defineProperty(iframe, 'contentDocument', {
          configurable: !nativeDomRuntime,
          enumerable: localDescriptors.document.enumerable,
          get() {
            const frameDocument = readNativeIframeDocument(this);
            if (enabled && !applicationShellContext && !markSecurityVerificationElement(this)) protectIframeDocument(frameDocument);
            return frameDocument;
          }
        });
      } catch {}
    }

    try {
      nativeAddEventListener.call(iframe, 'load', () => {
        if (!enabled || applicationShellContext || markSecurityVerificationElement(iframe)) return;
        protectIframeWindow(readNativeIframeWindow(iframe));
        protectIframeDocument(readNativeIframeDocument(iframe));
      }, { capture: true, passive: true });
    } catch {}

    return iframe;
  }

  function readNativeIframeWindow(iframe) {
    try {
      const descriptor = iframeDescriptorRecords.get(iframe)?.window || iframeContentWindowDescriptor;
      return descriptor?.get ? Reflect.apply(descriptor.get, iframe, []) : null;
    } catch {
      return null;
    }
  }

  function readNativeIframeDocument(iframe) {
    try {
      const descriptor = iframeDescriptorRecords.get(iframe)?.document || iframeContentDocumentDescriptor;
      return descriptor?.get ? Reflect.apply(descriptor.get, iframe, []) : null;
    } catch {
      return null;
    }
  }

  function protectIframeDocument(frameDocument) {
    try {
      protectIframeWindow(frameDocument?.defaultView || null);
    } catch {}
  }

  function protectIframeWindow(frameWindow) {
    if (!enabled || applicationShellContext || !frameWindow || frameWindow === window || guardedFrameWindows.has(frameWindow)) return;
    const frameHref = safeWindowHref(frameWindow);
    if (isSecurityVerificationReference(frameHref, location.href)) {
      grantSecurityStructuralPass();
      return;
    }

    let frameDelegate;
    try {
      if (typeof frameWindow.open !== 'function') return;
      frameDelegate = frameWindow.open.bind(frameWindow);
    } catch {
      return;
    }

    const state = { delegate: frameDelegate, guarded: null };
    guardedFrameWindows.set(frameWindow, state);

    const guardedOpen = function graxGuardedFrameOpen(...args) {
      if (!enabled || protectedCurrentOrigin) {
        return safeApplyOpen(state.delegate, frameWindow, args);
      }

      const decision = inspectWindowOpen(args[0], frameWindow, args[1]);
      if (decision.block) {
        starveActivePopupGesture();
        return createSyntheticWindowProxy();
      }

      if (decision.crossOrigin || decision.isBlankOpen) opensInGesture += 1;
      return safeApplyOpen(state.delegate, frameWindow, args);
    };

    state.guarded = guardedOpen;
    disguiseFunction(guardedOpen, frameDelegate, 'open', 3);
    hardenFunction(guardedOpen);

    try {
      defineLockedValue(frameWindow, 'open', guardedOpen, true);
      const frameWindowPrototype = frameWindow.Window?.prototype || Object.getPrototypeOf(frameWindow);
      defineLockedValue(frameWindowPrototype, 'open', guardedOpen, true);
      if (!frameWindow.__graxPageGuardInstalled) installExtractedRealmBridges(frameWindow);
    } catch {}
  }

  function installExtractedRealmBridges(frameWindow) {
    try {
      const frameDocument = frameWindow.document;
      const frameDocumentPrototype = frameWindow.Document?.prototype;
      const frameElementPrototype = frameWindow.Element?.prototype;
      const frameAnchorPrototype = frameWindow.HTMLAnchorElement?.prototype;
      const frameEventTargetPrototype = frameWindow.EventTarget?.prototype;

      const frameCreateElement = frameDocumentPrototype?.createElement;
      if (typeof frameCreateElement === 'function' && frameCreateElement !== nativeCreateElement) {
        const guardedFrameCreateElement = function graxFrameCreateElement(localName) {
          const element = Reflect.apply(frameCreateElement, this, arguments);
          armEmbeddedRealm(element, localName);
          return element;
        };
        disguiseFunction(guardedFrameCreateElement, frameCreateElement, 'createElement', frameCreateElement.length);
        hardenFunction(guardedFrameCreateElement);
        defineLockedValue(frameDocumentPrototype, 'createElement', guardedFrameCreateElement, false);
      }

      const frameCreateElementNS = frameDocumentPrototype?.createElementNS;
      if (typeof frameCreateElementNS === 'function' && frameCreateElementNS !== nativeCreateElementNS) {
        const guardedFrameCreateElementNS = function graxFrameCreateElementNS(namespace, qualifiedName) {
          const element = Reflect.apply(frameCreateElementNS, this, arguments);
          armEmbeddedRealm(element, qualifiedName);
          return element;
        };
        disguiseFunction(guardedFrameCreateElementNS, frameCreateElementNS, 'createElementNS', frameCreateElementNS.length);
        hardenFunction(guardedFrameCreateElementNS);
        defineLockedValue(frameDocumentPrototype, 'createElementNS', guardedFrameCreateElementNS, false);
      }

      installExtractedRealmMarkupProperty(frameElementPrototype, 'innerHTML', element => element);
      installExtractedRealmMarkupProperty(frameElementPrototype, 'outerHTML', element => element?.parentNode || frameDocument);

      const frameInsertAdjacentHTML = frameElementPrototype?.insertAdjacentHTML;
      if (typeof frameInsertAdjacentHTML === 'function' && frameInsertAdjacentHTML !== nativeInsertAdjacentHTML) {
        const guardedFrameInsertAdjacentHTML = function graxFrameInsertAdjacentHTML(position, markup) {
          const result = Reflect.apply(frameInsertAdjacentHTML, this, [position, sanitizeRealmMarkup(markup)]);
          scanRealmNodes(this?.parentNode || this);
          return result;
        };
        disguiseFunction(guardedFrameInsertAdjacentHTML, frameInsertAdjacentHTML, 'insertAdjacentHTML', frameInsertAdjacentHTML.length);
        hardenFunction(guardedFrameInsertAdjacentHTML);
        defineLockedValue(frameElementPrototype, 'insertAdjacentHTML', guardedFrameInsertAdjacentHTML, false);
      }

      for (const method of ['write', 'writeln']) {
        const frameMethod = frameDocumentPrototype?.[method];
        if (typeof frameMethod !== 'function') continue;
        const guardedFrameWrite = function graxFrameDocumentWrite(...parts) {
          const result = Reflect.apply(frameMethod, this, parts.map(sanitizeRealmMarkup));
          scanRealmNodes(this);
          return result;
        };
        disguiseFunction(guardedFrameWrite, frameMethod, method, frameMethod.length);
        hardenFunction(guardedFrameWrite);
        defineLockedValue(frameDocumentPrototype, method, guardedFrameWrite, false);
      }

      const frameAttachShadow = frameElementPrototype?.attachShadow;
      if (typeof frameAttachShadow === 'function' && frameAttachShadow !== nativeAttachShadow) {
        const guardedFrameAttachShadow = function graxFrameAttachShadow(init) {
          const requested = init && typeof init === 'object' ? init : { mode: 'open' };
          const elevated = aggressiveByHostname || Date.now() < elevatedRiskUntil;
          const safeInit = elevated && requested.mode === 'closed' ? { ...requested, mode: 'open' } : requested;
          const root = Reflect.apply(frameAttachShadow, this, [safeInit]);
          guardShadowRoot(root);
          return root;
        };
        disguiseFunction(guardedFrameAttachShadow, frameAttachShadow, 'attachShadow', frameAttachShadow.length);
        hardenFunction(guardedFrameAttachShadow);
        defineLockedValue(frameElementPrototype, 'attachShadow', guardedFrameAttachShadow, false);
      }

      const frameAnchorClick = frameAnchorPrototype?.click;
      if (typeof frameAnchorClick === 'function' && frameAnchorClick !== nativeAnchorClick) {
        const guardedFrameAnchorClick = function graxFrameAnchorClick() {
          if (shouldBlockProgrammaticAnchor(this)) {
            starveActivePopupGesture(this);
            cancelProgrammaticAnchorNavigation(this);
            return false;
          }
          try { return Reflect.apply(frameAnchorClick, this, arguments); } catch { return undefined; }
        };
        disguiseFunction(guardedFrameAnchorClick, frameAnchorClick, 'click', frameAnchorClick.length);
        hardenFunction(guardedFrameAnchorClick);
        defineLockedValue(frameAnchorPrototype, 'click', guardedFrameAnchorClick, false);
      }

      const frameDispatchEvent = frameElementPrototype?.dispatchEvent;
      if (typeof frameDispatchEvent === 'function' && frameDispatchEvent !== nativeElementDispatchEvent) {
        const guardedFrameDispatchEvent = function graxFrameDispatchEvent(event) {
          const eventType = String(event?.type || '').toLowerCase();
          if (PROGRAMMATIC_CLICK_TYPES.has(eventType)) {
            const anchor = anchorFromElement(this);
            if (anchor && shouldBlockProgrammaticAnchor(anchor)) {
              starveActivePopupGesture(anchor);
              blockEvent(event);
              return false;
            }
          }
          try { return Reflect.apply(frameDispatchEvent, this, [event]); } catch { return false; }
        };
        disguiseFunction(guardedFrameDispatchEvent, frameDispatchEvent, 'dispatchEvent', 1);
        hardenFunction(guardedFrameDispatchEvent);
        defineLockedValue(frameElementPrototype, 'dispatchEvent', guardedFrameDispatchEvent, false);
      }

      const frameAdd = frameEventTargetPrototype?.addEventListener;
      if (typeof frameAdd === 'function' && frameAdd !== nativeAddEventListener) {
        const guardedFrameAdd = createGuardedAddEventListener(frameAdd, frameWindow, frameDocument);
        defineLockedValue(frameEventTargetPrototype, 'addEventListener', guardedFrameAdd, false);
        defineLockedValue(frameWindow, 'addEventListener', guardedFrameAdd, false);
        bindCaptureTarget(frameWindow, frameAdd);
        bindCaptureTarget(frameDocument, frameAdd);
      }

      try {
        if (window.Blob && frameWindow.Blob !== window.Blob) defineLockedValue(frameWindow, 'Blob', window.Blob, false);
        if (window.Worker && frameWindow.Worker !== window.Worker) defineLockedValue(frameWindow, 'Worker', window.Worker, false);
        if (window.SharedWorker && frameWindow.SharedWorker !== window.SharedWorker) defineLockedValue(frameWindow, 'SharedWorker', window.SharedWorker, false);
        if (frameWindow.URL && URL.createObjectURL) defineLockedValue(frameWindow.URL, 'createObjectURL', URL.createObjectURL, false);
      } catch {}
    } catch {}
  }

  function installExtractedRealmMarkupProperty(owner, property, rootResolver) {
    if (!owner) return;
    const descriptor = findPropertyDescriptor(owner, property);
    if (!descriptor?.set || descriptor.configurable === false) return;
    const getter = descriptor.get;
    const setter = descriptor.set;
    const guardedGetter = function graxFrameMarkupGetter() {
      return getter ? Reflect.apply(getter, this, []) : '';
    };
    const guardedSetter = function graxFrameMarkupSetter(markup) {
      const root = rootResolver(this);
      const result = Reflect.apply(setter, this, [sanitizeRealmMarkup(markup)]);
      scanRealmNodes(root || this);
      return result;
    };
    disguiseFunction(guardedGetter, getter || function getMarkup() {}, `get ${property}`, 0);
    disguiseFunction(guardedSetter, setter, `set ${property}`, 1);
    hardenFunction(guardedGetter);
    hardenFunction(guardedSetter);
    try {
      Object.defineProperty(owner, property, {
        configurable: !nativeDomRuntime,
        enumerable: descriptor.enumerable,
        get: guardedGetter,
        set: guardedSetter
      });
    } catch {}
  }

  function installMarkupRealmGuards() {
    if (protectedCurrentOrigin || securityVerificationContext || applicationShellContext) return;

    installMarkupPropertyGuard('innerHTML', nativeInnerHTMLDescriptor, elementPrototype, element => element);
    installMarkupPropertyGuard('outerHTML', nativeOuterHTMLDescriptor, elementPrototype, element => element?.parentNode || document);

    if (nativeInsertAdjacentHTML && elementPrototype) {
      const guardedInsertAdjacentHTML = function graxInsertAdjacentHTML(position, markup) {
        const safeMarkup = sanitizeRealmMarkup(markup);
        const result = Reflect.apply(nativeInsertAdjacentHTML, this, [position, safeMarkup]);
        scanRealmNodes(this?.parentNode || this);
        return result;
      };
      disguiseFunction(guardedInsertAdjacentHTML, nativeInsertAdjacentHTML, 'insertAdjacentHTML', nativeInsertAdjacentHTML.length);
      hardenFunction(guardedInsertAdjacentHTML);
      defineLockedValue(elementPrototype, 'insertAdjacentHTML', guardedInsertAdjacentHTML, false);
    }

    if (nativeDocumentWrite && documentPrototype) {
      const guardedWrite = function graxDocumentWrite(...parts) {
        const result = Reflect.apply(nativeDocumentWrite, this, parts.map(sanitizeRealmMarkup));
        scanRealmNodes(this);
        return result;
      };
      disguiseFunction(guardedWrite, nativeDocumentWrite, 'write', nativeDocumentWrite.length);
      hardenFunction(guardedWrite);
      defineLockedValue(documentPrototype, 'write', guardedWrite, false);
    }

    if (nativeDocumentWriteln && documentPrototype) {
      const guardedWriteln = function graxDocumentWriteln(...parts) {
        const result = Reflect.apply(nativeDocumentWriteln, this, parts.map(sanitizeRealmMarkup));
        scanRealmNodes(this);
        return result;
      };
      disguiseFunction(guardedWriteln, nativeDocumentWriteln, 'writeln', nativeDocumentWriteln.length);
      hardenFunction(guardedWriteln);
      defineLockedValue(documentPrototype, 'writeln', guardedWriteln, false);
    }

    if (nativeCreateHTMLDocument && domImplementationPrototype) {
      const guardedCreateHTMLDocument = function graxCreateHTMLDocument(title) {
        const created = Reflect.apply(nativeCreateHTMLDocument, this, arguments);
        protectCreatedDocument(created);
        return created;
      };
      disguiseFunction(guardedCreateHTMLDocument, nativeCreateHTMLDocument, 'createHTMLDocument', nativeCreateHTMLDocument.length);
      hardenFunction(guardedCreateHTMLDocument);
      defineLockedValue(domImplementationPrototype, 'createHTMLDocument', guardedCreateHTMLDocument, false);
    }

    if (nativeParseFromString && domParserPrototype) {
      const guardedParseFromString = function graxParseFromString(input, mimeType) {
        const source = typeof input === 'string' && /html|xml|svg/i.test(String(mimeType || ''))
          ? sanitizeRealmMarkup(input)
          : input;
        const parsed = Reflect.apply(nativeParseFromString, this, [source, mimeType]);
        protectCreatedDocument(parsed);
        return parsed;
      };
      disguiseFunction(guardedParseFromString, nativeParseFromString, 'parseFromString', nativeParseFromString.length);
      hardenFunction(guardedParseFromString);
      defineLockedValue(domParserPrototype, 'parseFromString', guardedParseFromString, false);
    }
  }

  function installMarkupPropertyGuard(property, nativeDescriptor, owner, rootResolver) {
    if (!owner || !nativeDescriptor?.set) return;
    const nativeGetter = nativeDescriptor.get;
    const nativeSetter = nativeDescriptor.set;
    const guardedGetter = function graxMarkupGetter() {
      return nativeGetter ? Reflect.apply(nativeGetter, this, []) : '';
    };
    const guardedSetter = function graxMarkupSetter(markup) {
      const scanRoot = rootResolver(this);
      const result = Reflect.apply(nativeSetter, this, [sanitizeRealmMarkup(markup)]);
      scanRealmNodes(scanRoot || this);
      return result;
    };
    disguiseFunction(guardedGetter, nativeGetter || function getMarkup() {}, `get ${property}`, 0);
    disguiseFunction(guardedSetter, nativeSetter, `set ${property}`, 1);
    hardenFunction(guardedGetter);
    hardenFunction(guardedSetter);
    try {
      Object.defineProperty(owner, property, {
        configurable: !nativeDomRuntime,
        enumerable: nativeDescriptor.enumerable,
        get: guardedGetter,
        set: guardedSetter
      });
    } catch {}
  }

  function sanitizeRealmMarkup(value) {
    if (!enabled || protectedCurrentOrigin || securityVerificationContext || isDirectSecurityExecutionContext() || typeof value !== 'string') return value;
    if (!REALM_TAG_PATTERN.test(value)) return value;
    const sample = value.length > CONFIG.maxMarkupScanBytes ? value.slice(0, CONFIG.maxMarkupScanBytes) : value;
    const elevated = aggressiveByHostname || Date.now() < elevatedRiskUntil;
    const highRisk = MARKUP_POPUP_SOURCE.test(sample) || HIDDEN_REALM_MARKUP_PATTERN.test(sample) || containsAdDestinationText(sample);
    if (!highRisk && !elevated) return value;

    const result = rewriteRealmOpeningTags(value, elevated);
    if (result.changed) elevateRisk();
    return result.changed ? result.markup : value;
  }

  function rewriteRealmOpeningTags(markup, elevated) {
    const tagPattern = /<(iframe|object|embed)\b/gi;
    let cursor = 0;
    let changed = false;
    let output = '';
    let match;

    while ((match = tagPattern.exec(markup))) {
      let quote = '';
      let end = tagPattern.lastIndex;
      for (; end < markup.length; end += 1) {
        const character = markup[end];
        if (quote) {
          if (character === quote) quote = '';
          continue;
        }
        if (character === '"' || character === "'") {
          quote = character;
          continue;
        }
        if (character === '>') break;
      }
      if (end >= markup.length) break;

      const tag = String(match[1]).toLowerCase();
      const attributes = markup.slice(tagPattern.lastIndex, end);
      if (!isSuspiciousRealmMarkup(tag, attributes, elevated)) continue;

      output += markup.slice(cursor, match.index);
      output += tag === 'iframe'
        ? `<iframe${sanitizeIframeAttributes(attributes)}>`
        : `<${tag}${sanitizePluginAttributes(attributes)}>`;
      cursor = end + 1;
      tagPattern.lastIndex = cursor;
      changed = true;
    }

    if (!changed) return { changed: false, markup };
    output += markup.slice(cursor);
    return { changed: true, markup: output };
  }

  function isSuspiciousRealmMarkup(tag, attributes, elevated) {
    const lower = attributes.toLowerCase();
    const urlValue = extractMarkupAttribute(attributes, tag === 'object' ? 'data' : 'src');
    if (isSecurityVerificationMarkup(tag, attributes, urlValue)) return false;
    const srcdoc = extractMarkupAttribute(attributes, 'srcdoc');
    const parsed = parseDestination(urlValue, location.href);
    if (parsed.hostname && isProtectedHostname(parsed.hostname)) return false;
    const adDestination = parsed.hostname && AD_DESTINATION_PATTERN.test(parsed.hostname);
    const suspiciousUrl = urlValue && (SUSPICIOUS_URL_PATTERN.test(urlValue) || /^(?:javascript:|data:text\/html|blob:)/i.test(urlValue));
    const hidden = HIDDEN_REALM_MARKUP_PATTERN.test(lower) || /\bhidden\b|aria-hidden\s*=\s*['"]?true/i.test(lower);
    const popupCode = MARKUP_POPUP_SOURCE.test(srcdoc || '') || MARKUP_POPUP_SOURCE.test(lower);
    return Boolean(adDestination || suspiciousUrl || popupCode || (elevated && hidden));
  }

  function sanitizeIframeAttributes(attributes) {
    if (isSecurityVerificationMarkup('iframe', attributes, extractMarkupAttribute(attributes, 'src'))) return String(attributes || '');
    let next = String(attributes || '');
    next = next.replace(/\s+sandbox\s*=\s*(['"])(.*?)\1/gi, (_full, quote, tokens) => {
      const safeTokens = String(tokens).split(/\s+/).filter(token => token && !/^allow-popups(?:-to-escape-sandbox)?$/i.test(token));
      return ` sandbox=${quote}${safeTokens.join(' ')}${quote}`;
    });
    if (!/\ssandbox(?:\s|=|$)/i.test(next)) next += ' sandbox="allow-scripts allow-forms allow-presentation"';
    next = next.replace(/\s+srcdoc\s*=\s*(['"])([\s\S]*?)\1/gi, (_full, quote, srcdoc) => {
      return MARKUP_POPUP_SOURCE.test(srcdoc) ? ` srcdoc=${quote}<!doctype html>${quote}` : _full;
    });
    const src = extractMarkupAttribute(next, 'src');
    const parsed = parseDestination(src, location.href);
    if ((parsed.hostname && AD_DESTINATION_PATTERN.test(parsed.hostname)) || /^(?:javascript:|data:text\/html)/i.test(src)) {
      next = replaceMarkupAttribute(next, 'src', 'about:blank');
    }
    if (!/\sreferrerpolicy\s*=/i.test(next)) next += ' referrerpolicy="no-referrer"';
    return next;
  }

  function sanitizePluginAttributes(attributes) {
    if (isSecurityVerificationMarkup('object', attributes, extractMarkupAttribute(attributes, 'data') || extractMarkupAttribute(attributes, 'src'))) return String(attributes || '');
    let next = String(attributes || '');
    for (const name of ['src', 'data']) {
      const value = extractMarkupAttribute(next, name);
      const parsed = parseDestination(value, location.href);
      if ((parsed.hostname && AD_DESTINATION_PATTERN.test(parsed.hostname)) || /^(?:javascript:|data:text\/html|blob:)/i.test(value)) {
        next = replaceMarkupAttribute(next, name, 'about:blank');
      }
    }
    if (!/\saria-hidden\s*=/i.test(next)) next += ' aria-hidden="true"';
    return next;
  }

  function isSecurityVerificationMarkup(tag, attributes, urlValue = '') {
    const source = `${String(tag || '')} ${String(attributes || '')}`;
    if (isSecurityVerificationReference(urlValue, location.href)) {
      grantSecurityStructuralPass();
      return true;
    }
    if (SECURITY_VERIFICATION_ELEMENT_PATTERN.test(source) || SECURITY_VERIFICATION_TOKEN_PATTERN.test(source)) {
      grantSecurityStructuralPass();
      return true;
    }
    return false;
  }

  function extractMarkupAttribute(attributes, name) {
    const pattern = new RegExp(`\\b${name}\\s*=\\s*(?:([\"'])([\\s\\S]*?)\\1|([^\\s>]+))`, 'i');
    const match = pattern.exec(String(attributes || ''));
    return String(match?.[2] || match?.[3] || '');
  }

  function replaceMarkupAttribute(attributes, name, value) {
    const pattern = new RegExp(`(\\b${name}\\s*=\\s*)(?:([\"'])([\\s\\S]*?)\\2|([^\\s>]+))`, 'i');
    if (pattern.test(attributes)) return attributes.replace(pattern, `$1"${value}"`);
    return `${attributes} ${name}="${value}"`;
  }

  function containsAdDestinationText(text) {
    const matches = String(text || '').match(/(?:https?:)?\/\/([a-z0-9.-]+)/ig) || [];
    return matches.some(value => AD_DESTINATION_PATTERN.test(safeHostname(value.startsWith('//') ? `https:${value}` : value)));
  }

  function protectCreatedDocument(createdDocument) {
    if (!createdDocument || protectedDocuments.has(createdDocument) || isDirectSecurityExecutionContext()) return createdDocument;
    protectedDocuments.add(createdDocument);
    try { protectIframeWindow(createdDocument.defaultView); } catch {}
    scanRealmNodes(createdDocument);
    return createdDocument;
  }

  function scanRealmNodes(root) {
    if (!enabled || applicationShellContext || !root) return;
    scanSecurityVerificationNodes(root);
    if (isEmbeddedRealmElement(root)) armEmbeddedRealm(root, root.localName || root.tagName);
    let nodes = [];
    try { nodes = root.querySelectorAll?.('iframe,object,embed') || []; } catch {}
    for (const node of nodes) armEmbeddedRealm(node, node.localName || node.tagName);
  }

  function armEmbeddedRealm(element, requestedName = '') {
    if (!enabled || applicationShellContext || !element) return element;
    if (markSecurityVerificationElement(element)) return element;
    const name = String(requestedName || element.localName || element.tagName || '').toLowerCase().split(':').pop();
    if (name === 'iframe' || isIframeElement(element, name)) return armDynamicIframe(element);
    if (!['object', 'embed'].includes(name) || armedEmbeddedRealms.has(element)) return element;
    armedEmbeddedRealms.add(element);
    protectEmbeddedRealmWindow(element);
    try {
      nativeAddEventListener.call(element, 'load', () => protectEmbeddedRealmWindow(element), { capture: true, passive: true });
    } catch {}
    return element;
  }

  function isEmbeddedRealmElement(value) {
    const name = String(value?.localName || value?.tagName || '').toLowerCase();
    return name === 'iframe' || name === 'object' || name === 'embed';
  }

  function protectEmbeddedRealmWindow(element) {
    try { protectIframeDocument(element.contentDocument || null); } catch {}
    try { protectIframeWindow(element.contentWindow || element.getSVGDocument?.()?.defaultView || null); } catch {}
  }

  function installShadowDomGuard() {
    if (!nativeAttachShadow || !elementPrototype || protectedCurrentOrigin || securityVerificationContext || applicationShellContext) return;
    const guardedAttachShadow = function graxAttachShadow(init) {
      const requested = init && typeof init === 'object' ? init : { mode: 'open' };
      if (!enabled || applicationShellContext || isSecurityStructuralPassActive() || markSecurityVerificationElement(this)) {
        return Reflect.apply(nativeAttachShadow, this, [requested]);
      }
      const elevated = aggressiveByHostname || Date.now() < elevatedRiskUntil;
      const safeInit = elevated && requested.mode === 'closed'
        ? { ...requested, mode: 'open' }
        : requested;
      const root = Reflect.apply(nativeAttachShadow, this, [safeInit]);
      guardShadowRoot(root);
      return root;
    };
    disguiseFunction(guardedAttachShadow, nativeAttachShadow, 'attachShadow', nativeAttachShadow.length);
    hardenFunction(guardedAttachShadow);
    defineLockedValue(elementPrototype, 'attachShadow', guardedAttachShadow, false);
  }

  function guardShadowRoot(root) {
    if (!enabled || applicationShellContext || !root || guardedShadowRoots.has(root) || securityVerificationContext || isSecurityStructuralPassActive() || markSecurityVerificationElement(root.host)) return root;
    guardedShadowRoots.add(root);
    const rootAdd = typeof root.addEventListener === 'function' ? nativeAddEventListener : null;
    bindCaptureTarget(root, rootAdd);
    observeRealmRoot(root);
    scanRealmNodes(root);
    return root;
  }

  function installWorkerExecutionGuards() {
    if (protectedCurrentOrigin || securityVerificationContext || applicationShellContext) return;
    installBlobAndObjectUrlGuards();
    installWorkerConstructorGuard('Worker', NativeWorker, false);
    installWorkerConstructorGuard('SharedWorker', NativeSharedWorker, true);
    installServiceWorkerGuard();
  }

  function installBlobAndObjectUrlGuards() {
    if (NativeBlob) {
      const GuardedBlob = new Proxy(NativeBlob, {
        construct(target, args, newTarget) {
          const parts = Array.isArray(args[0]) ? args[0] : [];
          const options = args[1] && typeof args[1] === 'object' ? args[1] : {};
          const analysis = (!enabled || applicationShellContext || isSecurityStructuralPassActive())
            ? { block: false, suspicious: false, executable: false, navigation: false, popupNavigation: false, media: false, mediaSafe: false, securityVerification: true, type: String(options?.type || '').toLowerCase() }
            : analyzeBlobPayload(parts, options);
          if (analysis.media) markMediaRuntime();
          const finalParts = analysis.block ? [benignPayloadForMime(options.type)] : parts;
          const blob = Reflect.construct(target, [finalParts, options], newTarget === GuardedBlob ? target : newTarget);
          blobRiskRecords.set(blob, analysis);
          return blob;
        },
        apply(target, thisArg, args) {
          return Reflect.apply(target, thisArg, args);
        }
      });
      try { Object.setPrototypeOf(GuardedBlob, NativeBlob); } catch {}
      try { GuardedBlob.prototype = NativeBlob.prototype; } catch {}
      defineLockedValue(window, 'Blob', GuardedBlob, false);
    }

    if (nativeCreateObjectURL) {
      const guardedCreateObjectURL = function graxCreateObjectURL(object) {
        if (!enabled || applicationShellContext) return Reflect.apply(nativeCreateObjectURL, URL, [object]);
        const analysis = blobRiskRecords.get(object) || analyzeObjectUrlTarget(object);
        if (analysis.media) markMediaRuntime();
        let targetObject = object;
        if (analysis.block && NativeBlob) {
          targetObject = new NativeBlob([benignPayloadForMime(object?.type)], { type: object?.type || 'text/javascript' });
        }
        const url = Reflect.apply(nativeCreateObjectURL, URL, [targetObject]);
        objectUrlRiskRecords.set(String(url), analysis);
        return url;
      };
      disguiseFunction(guardedCreateObjectURL, nativeCreateObjectURL, 'createObjectURL', 1);
      hardenFunction(guardedCreateObjectURL);
      defineLockedValue(URL, 'createObjectURL', guardedCreateObjectURL, false);
    }

    if (nativeRevokeObjectURL) {
      const guardedRevokeObjectURL = function graxRevokeObjectURL(url) {
        objectUrlRiskRecords.delete(String(url));
        return Reflect.apply(nativeRevokeObjectURL, URL, [url]);
      };
      disguiseFunction(guardedRevokeObjectURL, nativeRevokeObjectURL, 'revokeObjectURL', 1);
      hardenFunction(guardedRevokeObjectURL);
      defineLockedValue(URL, 'revokeObjectURL', guardedRevokeObjectURL, false);
    }
  }

  function analyzeBlobPayload(parts, options) {
    const type = String(options?.type || '').toLowerCase();
    let source = '';
    let binaryMedia = false;
    let binaryPayload = false;
    for (const part of parts) {
      if (typeof part === 'string') {
        const remaining = CONFIG.maxBlobInspectionBytes - source.length;
        if (remaining > 0) source += part.slice(0, remaining);
        continue;
      }
      const binary = inspectBinaryMediaPart(part);
      binaryPayload ||= binary.binary;
      binaryMedia ||= binary.media;
    }
    const executable = EXECUTABLE_BLOB_MIME.test(type) || (!type && /(?:importScripts|onmessage|clients\s*\.|window\s*\.)/i.test(source));
    const navigation = WORKER_NAVIGATION_SOURCE.test(source);
    const popupNavigation = WORKER_POPUP_SOURCE.test(source);
    const suspicious = WORKER_SUSPICIOUS_SOURCE.test(source) || containsAdDestinationText(source);
    const media = isMediaPayload(type, source, binaryMedia, binaryPayload);
    const mediaSafe = Boolean(media && !popupNavigation && !containsAdDestinationText(source) && !HIGH_RISK_LISTENER_SOURCE.test(source));
    const elevated = aggressiveByHostname || Date.now() < elevatedRiskUntil;
    const block = Boolean(executable && navigation && (suspicious || elevated) && !mediaSafe);
    if (block) elevateRisk();
    return { block, suspicious, executable, navigation, popupNavigation, media, mediaSafe, type };
  }

  function analyzeObjectUrlTarget(object) {
    const type = String(object?.type || '').toLowerCase();
    const nativeMediaObject = isNativeMediaObject(object);
    const media = nativeMediaObject || MEDIA_MIME_PATTERN.test(type) || MEDIA_APPLICATION_MIME_PATTERN.test(type);
    return { block: false, suspicious: false, executable: false, navigation: false, popupNavigation: false, media, mediaSafe: media, type };
  }

  function isMediaPayload(type, source, binaryMedia, binaryPayload) {
    if (MEDIA_MIME_PATTERN.test(type) || MEDIA_APPLICATION_MIME_PATTERN.test(type)) return true;
    if (binaryMedia) return true;
    if (MEDIA_FRAMEWORK_SOURCE.test(source)) return true;
    if (binaryPayload && /(?:mpeg|mp4|webm|segment|media|stream)/i.test(type)) return true;
    return false;
  }

  function inspectBinaryMediaPart(part) {
    let bytes = null;
    try {
      if (typeof ArrayBuffer === 'function' && part instanceof ArrayBuffer) {
        bytes = new Uint8Array(part, 0, Math.min(part.byteLength, 512));
      } else if (typeof ArrayBuffer === 'function' && ArrayBuffer.isView?.(part)) {
        bytes = new Uint8Array(part.buffer, part.byteOffset, Math.min(part.byteLength, 512));
      }
    } catch {}
    if (!bytes) return { binary: false, media: false };
    if (!bytes.length) return { binary: true, media: false };
    const ascii = bytesToAscii(bytes, 32);
    const mpegTs = bytes[0] === 0x47 && (bytes.length < 189 || bytes[188] === 0x47);
    const webm = bytes.length >= 4 && bytes[0] === 0x1a && bytes[1] === 0x45 && bytes[2] === 0xdf && bytes[3] === 0xa3;
    const mp4 = bytes.length >= 8 && /^(?:ftyp|styp|moov|moof|mdat)$/i.test(bytesToAscii(bytes.subarray(4, 8), 4));
    const id3 = ascii.startsWith('ID3');
    const ogg = ascii.startsWith('OggS');
    const riff = ascii.startsWith('RIFF') && /(?:WAVE|AVI )/.test(bytesToAscii(bytes.subarray(8, 12), 4));
    const adts = bytes.length >= 2 && bytes[0] === 0xff && (bytes[1] & 0xf6) === 0xf0;
    return { binary: true, media: Boolean(mpegTs || webm || mp4 || id3 || ogg || riff || adts) };
  }

  function bytesToAscii(bytes, limit = 32) {
    let text = '';
    const length = Math.min(bytes?.length || 0, limit);
    for (let index = 0; index < length; index += 1) text += String.fromCharCode(bytes[index]);
    return text;
  }

  function isNativeMediaObject(object) {
    if (!object) return false;
    try {
      if (typeof MediaSource === 'function' && object instanceof MediaSource) return true;
    } catch {}
    try {
      if (typeof MediaStream === 'function' && object instanceof MediaStream) return true;
    } catch {}
    return false;
  }

  function benignPayloadForMime(type) {
    return /html|svg/i.test(String(type || ''))
      ? '<!doctype html><meta charset="utf-8">'
      : '/* Grax: hostile dynamic execution neutralized */\nself.onmessage = function () {};';
  }

  function installWorkerConstructorGuard(name, NativeConstructor, shared) {
    if (typeof NativeConstructor !== 'function') return;
    let inertUrl = '';
    const GuardedConstructor = new Proxy(NativeConstructor, {
      construct(target, args, newTarget) {
        const scriptUrl = args[0];
        if (!shouldBlockWorker(scriptUrl)) return Reflect.construct(target, args, newTarget === GuardedConstructor ? target : newTarget);
        elevateRisk();
        try {
          if (!inertUrl && NativeBlob && nativeCreateObjectURL) {
            const code = shared
              ? 'onconnect=function(e){try{e.ports[0].start();}catch(_){}};'
              : 'self.onmessage=function(){};';
            inertUrl = nativeCreateObjectURL(new NativeBlob([code], { type: 'text/javascript' }));
          }
          const replacementArgs = [inertUrl || 'data:text/javascript,self.onmessage=function(){};', ...args.slice(1)];
          return Reflect.construct(target, replacementArgs, newTarget === GuardedConstructor ? target : newTarget);
        } catch {
          return createSyntheticWorker(shared);
        }
      }
    });
    try { Object.setPrototypeOf(GuardedConstructor, NativeConstructor); } catch {}
    defineLockedValue(window, name, GuardedConstructor, false);
  }

  function shouldBlockWorker(rawUrl) {
    if (!enabled || protectedCurrentOrigin || securityVerificationContext || applicationShellContext || isSecurityStructuralPassActive()) return false;
    const value = String(rawUrl || '');
    if (isSecurityVerificationReference(value, location.href)) {
      grantSecurityStructuralPass();
      return false;
    }
    const parsed = parseDestination(value, location.href);
    if (parsed.hostname && isProtectedHostname(parsed.hostname)) return false;
    if (parsed.hostname && AD_DESTINATION_PATTERN.test(parsed.hostname)) return true;
    if (parsed.url && SUSPICIOUS_URL_PATTERN.test(parsed.url.href)) return true;
    if (/^data:/i.test(value)) {
      const source = decodeDataUrl(value);
      const analysis = analyzeBlobPayload([source], { type: dataUrlMime(value) || 'text/javascript' });
      if (analysis.mediaSafe) {
        markMediaRuntime();
        return false;
      }
      return Boolean(analysis.block || (WORKER_POPUP_SOURCE.test(source) && (analysis.suspicious || aggressiveByHostname)));
    }
    if (/^blob:/i.test(value)) {
      const record = objectUrlRiskRecords.get(value);
      if (record?.mediaSafe || record?.media) {
        markMediaRuntime();
        return false;
      }
      return Boolean(record?.block);
    }
    if (isMediaWorkerReference(value, parsed.url)) {
      markMediaRuntime();
      return false;
    }
    return false;
  }

  function dataUrlMime(value) {
    const match = String(value || '').match(/^data:([^;,]+)/i);
    return match?.[1] || '';
  }

  function isMediaWorkerReference(value, parsedUrl = null) {
    const candidate = `${String(value || '')} ${parsedUrl?.pathname || ''} ${parsedUrl?.search || ''}`;
    return MEDIA_WORKER_URL_PATTERN.test(candidate);
  }

  function decodeDataUrl(value) {
    try {
      const comma = value.indexOf(',');
      if (comma < 0) return '';
      const header = value.slice(0, comma);
      const payload = value.slice(comma + 1);
      return /;base64/i.test(header) ? atob(payload) : decodeURIComponent(payload);
    } catch {
      return '';
    }
  }

  function createSyntheticWorker(shared) {
    const port = Object.freeze({ start() {}, close() {}, postMessage() {}, addEventListener() {}, removeEventListener() {} });
    return Object.freeze({
      port: shared ? port : undefined,
      postMessage() {},
      terminate() {},
      addEventListener() {},
      removeEventListener() {},
      dispatchEvent() { return true; }
    });
  }

  function installServiceWorkerGuard() {
    if (!nativeServiceWorkerRegister || !serviceWorkerContainerPrototype) return;
    const guardedRegister = function graxServiceWorkerRegister(scriptURL, options) {
      if (!shouldBlockServiceWorker(scriptURL)) {
        return Reflect.apply(nativeServiceWorkerRegister, this, arguments);
      }
      elevateRisk();
      return Promise.resolve(createSyntheticServiceWorkerRegistration(scriptURL, options));
    };
    disguiseFunction(guardedRegister, nativeServiceWorkerRegister, 'register', nativeServiceWorkerRegister.length);
    hardenFunction(guardedRegister);
    defineLockedValue(serviceWorkerContainerPrototype, 'register', guardedRegister, false);
  }

  function shouldBlockServiceWorker(scriptURL) {
    if (!enabled || protectedCurrentOrigin || securityVerificationContext || applicationShellContext || isSecurityStructuralPassActive()) return false;
    if (isSecurityVerificationReference(scriptURL, location.href)) {
      grantSecurityStructuralPass();
      return false;
    }
    const parsed = parseDestination(scriptURL, location.href);
    if (parsed.hostname && isProtectedHostname(parsed.hostname)) return false;
    if (parsed.hostname && AD_DESTINATION_PATTERN.test(parsed.hostname)) return true;
    if (parsed.url && SUSPICIOUS_URL_PATTERN.test(parsed.url.href)) return true;
    const sameOrigin = !parsed.url || parsed.url.origin === location.origin;
    if (sameOrigin && isMediaWorkerReference(scriptURL, parsed.url) && (isMediaRuntimeActive() || documentHasMediaPlaybackSurface())) {
      markMediaRuntime();
      return false;
    }
    return aggressiveByHostname;
  }

  function createSyntheticServiceWorkerRegistration(scriptURL, options) {
    const scope = (() => {
      try { return new URL(options?.scope || './', location.href).href; } catch { return location.origin + '/'; }
    })();
    return Object.freeze({
      scope,
      active: null,
      installing: null,
      waiting: null,
      navigationPreload: Object.freeze({ enable: async () => {}, disable: async () => {}, getState: async () => ({ enabled: false, headerValue: '' }), setHeaderValue: async () => {} }),
      pushManager: undefined,
      update: async () => undefined,
      unregister: async () => true,
      addEventListener() {},
      removeEventListener() {},
      dispatchEvent() { return true; },
      scriptURL: String(scriptURL || '')
    });
  }

  function installRealmMutationObserver() {
    if (protectedCurrentOrigin || securityVerificationContext || applicationShellContext) return;
    bindDocumentShellTargets();
    observeRealmRoot(document);
  }

  function observeRealmRoot(root) {
    if (!root || observedRoots.has(root) || typeof MutationObserver !== 'function') return;
    observedRoots.add(root);
    try {
      const observer = new MutationObserver(records => {
        if (!enabled || applicationShellContext) return;
        bindDocumentShellTargets();
        for (const record of records) {
          if (record.type === 'attributes') {
            markSecurityVerificationElement(record.target, record.attributeName || '', safeGetAttribute(record.target, record.attributeName || ''));
            scanRealmNodes(record.target);
          }
          for (const node of record.addedNodes || []) {
            if (!node) continue;
            scanRealmNodes(node);
            if (node.shadowRoot) guardShadowRoot(node.shadowRoot);
          }
        }
      });
      observer.observe(root, {
        childList: true,
        subtree: true,
        attributes: true,
        attributeFilter: ['src', 'data', 'class', 'id', 'name', 'title', 'data-sitekey', 'data-rqdata', 'data-cdata']
      });
    } catch {}
  }

  function installProgrammaticNavigationGuard() {
    if (protectedCurrentOrigin) return;
    if (nativeAnchorClick && typeof HTMLAnchorElement === 'function') {
      const guardedAnchorClick = function graxAnchorClick() {
        if (shouldBlockProgrammaticAnchor(this)) {
          starveActivePopupGesture(this);
          cancelProgrammaticAnchorNavigation(this);
          return false;
        }
        try {
          return Reflect.apply(nativeAnchorClick, this, arguments);
        } catch {
          return undefined;
        }
      };

      disguiseFunction(guardedAnchorClick, nativeAnchorClick, 'click', nativeAnchorClick.length);

      try {
        hardenFunction(guardedAnchorClick);
        Object.defineProperty(HTMLAnchorElement.prototype, 'click', {
          configurable: !nativeDomRuntime,
          enumerable: false,
          writable: !nativeDomRuntime,
          value: guardedAnchorClick
        });
      } catch {}
    }

    installProgrammaticFormGuards();

    if (!nativeElementDispatchEvent || typeof Element !== 'function') return;

    const guardedElementDispatchEvent = function graxElementDispatchEvent(event) {
      const eventType = String(event?.type || '').toLowerCase();
      if (PROGRAMMATIC_CLICK_TYPES.has(eventType)) {
        const anchor = anchorFromElement(this);
        if (anchor && shouldBlockProgrammaticAnchor(anchor)) {
          starveActivePopupGesture(anchor);
          blockEvent(event);
          return false;
        }
      }

      try {
        return Reflect.apply(nativeElementDispatchEvent, this, [event]);
      } catch {
        return false;
      }
    };

    disguiseFunction(guardedElementDispatchEvent, nativeElementDispatchEvent, 'dispatchEvent', 1);

    try {
      hardenFunction(guardedElementDispatchEvent);
      Object.defineProperty(Element.prototype, 'dispatchEvent', {
        configurable: !nativeDomRuntime,
        enumerable: false,
        writable: !nativeDomRuntime,
        value: guardedElementDispatchEvent
      });
    } catch {}
  }

  function installProgrammaticFormGuards() {
    if (typeof HTMLFormElement !== 'function') return;

    if (nativeFormSubmit) {
      const guardedSubmit = function graxFormSubmit() {
        if (shouldBlockProgrammaticForm(this)) {
          starveActivePopupGesture(this);
          return false;
        }
        try { return Reflect.apply(nativeFormSubmit, this, arguments); } catch { return undefined; }
      };
      disguiseFunction(guardedSubmit, nativeFormSubmit, 'submit', nativeFormSubmit.length);
      hardenFunction(guardedSubmit);
      defineLockedValue(HTMLFormElement.prototype, 'submit', guardedSubmit, false);
    }

    if (nativeFormRequestSubmit) {
      const guardedRequestSubmit = function graxFormRequestSubmit() {
        if (shouldBlockProgrammaticForm(this)) {
          starveActivePopupGesture(this);
          return false;
        }
        try { return Reflect.apply(nativeFormRequestSubmit, this, arguments); } catch { return undefined; }
      };
      disguiseFunction(guardedRequestSubmit, nativeFormRequestSubmit, 'requestSubmit', nativeFormRequestSubmit.length);
      hardenFunction(guardedRequestSubmit);
      defineLockedValue(HTMLFormElement.prototype, 'requestSubmit', guardedRequestSubmit, false);
    }
  }

  function shouldBlockProgrammaticForm(form) {
    if (!enabled || protectedCurrentOrigin || !isFormElement(form)) return false;
    const target = String(form.target || safeGetAttribute(form, 'target') || '').toLowerCase();
    if (target !== '_blank') return false;
    const rawAction = String(form.action || safeGetAttribute(form, 'action') || location.href);
    const parsed = parseDestination(rawAction, location.href);
    if (parsed.hostname && isProtectedHostname(parsed.hostname)) return false;
    if (isPopupCapableScheme(parsed.url)) return true;
    const crossOrigin = parsed.url ? parsed.url.origin !== location.origin : false;
    // Form APIs are programmatic new-window surfaces. External destinations require
    // an explicit global safelist entry regardless of where the source gesture began.
    return Boolean(crossOrigin);
  }

  function isStealthForm(form) {
    try {
      if (form.isConnected === false || safeHasAttribute(form, 'hidden') || safeGetAttribute(form, 'aria-hidden') === 'true') return true;
      const rect = form.getBoundingClientRect?.();
      const style = getComputedStyle?.(form);
      const hiddenStyle = style && (style.display === 'none' || style.visibility === 'hidden' || Number.parseFloat(style.opacity || '1') <= 0.05);
      const tiny = rect && (rect.width <= 2 || rect.height <= 2);
      return Boolean(hiddenStyle || tiny || OVERLAY_NAME_PATTERN.test(`${form.id || ''} ${form.className || ''}`));
    } catch {
      return true;
    }
  }

  function cancelProgrammaticAnchorNavigation(anchor) {
    try {
      const cancellation = new Event('click', { bubbles: false, cancelable: true });
      cancellation.preventDefault();
      cancellation.stopImmediatePropagation();
    } catch {}
    try { anchor?.blur?.(); } catch {}
    return false;
  }

  function shouldBlockProgrammaticAnchor(anchor) {
    if (!enabled || protectedCurrentOrigin || !isAnchorElement(anchor)) return false;
    if (safeHasAttribute(anchor, 'download')) return false;

    const target = String(safeAnchorProperty(anchor, 'target') || safeGetAttribute(anchor, 'target') || '').toLowerCase();
    if (target !== '_blank') return false;

    const rawHref = String(safeGetAttribute(anchor, 'href') || safeAnchorProperty(anchor, 'href') || '').trim();
    if (!rawHref) return false;

    const parsed = parseDestination(safeAnchorProperty(anchor, 'href') || rawHref, location.href);
    if (parsed.hostname && isProtectedHostname(parsed.hostname)) return false;
    if (isPopupCapableScheme(parsed.url) || /^(?:javascript:|data:text\/html|blob:)/i.test(rawHref)) return true;

    const crossOrigin = parsed.url ? parsed.url.origin !== location.origin : true;
    // HTMLElement.click() and synthetic dispatch are script-authorized navigation.
    // External _blank destinations never inherit trust from a player gesture.
    return Boolean(crossOrigin);
  }

  function isStealthProgrammaticAnchor(anchor) {
    try {
      if (anchor.isConnected === false) return true;
      if (safeHasAttribute(anchor, 'hidden') || safeGetAttribute(anchor, 'aria-hidden') === 'true') return true;

      const rect = typeof anchor.getBoundingClientRect === 'function'
        ? anchor.getBoundingClientRect()
        : null;
      const style = typeof getComputedStyle === 'function'
        ? getComputedStyle(anchor)
        : null;
      const text = String(anchor.innerText || anchor.textContent || safeGetAttribute(anchor, 'aria-label') || '').trim();
      const tiny = rect ? rect.width <= 2 || rect.height <= 2 : false;
      const hiddenStyle = style && (
        style.display === 'none' ||
        style.visibility === 'hidden' ||
        style.pointerEvents === 'none' ||
        Number.parseFloat(style.opacity || '1') <= 0.05
      );
      const named = OVERLAY_NAME_PATTERN.test(`${anchor.id || ''} ${anchor.className || ''}`);
      return Boolean(hiddenStyle || tiny || named || (!text && rect && rect.width <= 8 && rect.height <= 8));
    } catch {
      return true;
    }
  }

  function installSelectiveEventListenerDefuser() {
    if (!eventTargetPrototype || protectedCurrentOrigin || securityVerificationContext || applicationShellContext) return;

    const guardedAddEventListener = createGuardedAddEventListener(nativeAddEventListener, window, document);
    const guardedRemoveEventListener = function graxRemoveEventListener(type, listener, options) {
      const registered = resolveWrappedEventListener(this, type, listener, options);
      try {
        return Reflect.apply(nativeRemoveEventListener, this, [type, registered || listener, options]);
      } catch {
        return undefined;
      }
    };

    disguiseFunction(guardedRemoveEventListener, nativeRemoveEventListener, 'removeEventListener', nativeRemoveEventListener.length);
    hardenFunction(guardedAddEventListener);
    hardenFunction(guardedRemoveEventListener);

    defineLockedValue(eventTargetPrototype, 'addEventListener', guardedAddEventListener, false);
    defineLockedValue(eventTargetPrototype, 'removeEventListener', guardedRemoveEventListener, false);

    for (const owner of [windowPrototype, documentPrototype, htmlElementPrototype, window]) {
      defineLockedValue(owner, 'addEventListener', guardedAddEventListener, false);
    }
  }

  function createGuardedAddEventListener(delegate, realmWindow = window, realmDocument = document) {
    const guardedAddEventListener = function graxAddEventListener(type, listener, options) {
      const normalizedType = String(type || '').toLowerCase();

      if (isSecurityStructuralPassActive() || markSecurityVerificationElement(this)) {
        try { return Reflect.apply(delegate, this, [type, listener, options]); } catch { return undefined; }
      }

      if (enabled && !protectedCurrentOrigin && CONFIG.ignoredLifecycleEvents.has(normalizedType)) {
        return undefined;
      }

      const analysis = CLICK_TYPES.has(normalizedType)
        ? analyzePopunderListener(listener, normalizedType)
        : { suspicious: false, highConfidence: false };
      const globalTarget = isGlobalEventTarget(this, realmWindow, realmDocument);

      let registered = listener;
      const highConfidenceGlobal = enabled && !protectedCurrentOrigin && CLICK_TYPES.has(normalizedType) && globalTarget && analysis.highConfidence;
      const shouldRiskScope = enabled && !protectedCurrentOrigin && CLICK_TYPES.has(normalizedType) && globalTarget && (analysis.suspicious || aggressiveByHostname);
      if (highConfidenceGlobal && listener) {
        elevateRisk();
        registered = createMediaCompatibleHighConfidenceListener(listener);
        rememberWrappedEventListener(this, normalizedType, listener, options, registered);
      } else if (shouldRiskScope && listener) {
        registered = createRiskScopedEventListener(listener);
        rememberWrappedEventListener(this, normalizedType, listener, options, registered);
      }

      try {
        return Reflect.apply(delegate, this, [type, registered, options]);
      } catch {
        return undefined;
      }
    };

    disguiseFunction(guardedAddEventListener, delegate, 'addEventListener', delegate.length);
    hardenFunction(guardedAddEventListener);
    return guardedAddEventListener;
  }

  function createMediaCompatibleHighConfidenceListener(listener) {
    const invoke = (candidate, receiver, event) => {
      if (!enabled) return Reflect.apply(candidate, receiver, [event]);
      const target = firstElementInPath(event);
      const mediaInteraction = Boolean(event?.isTrusted && isMediaInteractionEvent(event, target));
      if (!mediaInteraction) {
        elevateRisk();
        blockEvent(event);
        return false;
      }

      markMediaRuntime();
      directHandlerRiskDepth += 1;
      try {
        return Reflect.apply(candidate, receiver, [event]);
      } finally {
        directHandlerRiskDepth = Math.max(0, directHandlerRiskDepth - 1);
      }
    };

    if (typeof listener === 'function') {
      const wrapped = function graxMediaCompatibleHighConfidenceListener(event) {
        return invoke(listener, this, event);
      };
      disguiseFunction(wrapped, listener, listener.name || 'listener', listener.length);
      return wrapped;
    }

    if (listener && typeof listener.handleEvent === 'function') {
      return {
        handleEvent(event) {
          return invoke(listener.handleEvent, listener, event);
        }
      };
    }
    return listener;
  }

  function createRiskScopedEventListener(listener) {
    if (typeof listener === 'function') {
      const wrapped = function graxRiskScopedListener() {
        if (!enabled) return Reflect.apply(listener, this, arguments);
        directHandlerRiskDepth += 1;
        try {
          return Reflect.apply(listener, this, arguments);
        } finally {
          directHandlerRiskDepth = Math.max(0, directHandlerRiskDepth - 1);
        }
      };
      disguiseFunction(wrapped, listener, listener.name || 'listener', listener.length);
      return wrapped;
    }

    if (listener && typeof listener.handleEvent === 'function') {
      return {
        handleEvent(event) {
          if (!enabled) return Reflect.apply(listener.handleEvent, listener, [event]);
          directHandlerRiskDepth += 1;
          try {
            return Reflect.apply(listener.handleEvent, listener, [event]);
          } finally {
            directHandlerRiskDepth = Math.max(0, directHandlerRiskDepth - 1);
          }
        }
      };
    }
    return listener;
  }

  function eventListenerKey(type, options) {
    const capture = typeof options === 'boolean' ? options : Boolean(options?.capture);
    return `${String(type || '').toLowerCase()}:${capture ? 1 : 0}`;
  }

  function rememberWrappedEventListener(target, type, original, options, wrapped) {
    if (!target || !original || original === wrapped) return;
    let byTarget = listenerWrapperRecords.get(target);
    if (!byTarget) {
      byTarget = new WeakMap();
      listenerWrapperRecords.set(target, byTarget);
    }
    let byListener = byTarget.get(original);
    if (!byListener) {
      byListener = new Map();
      byTarget.set(original, byListener);
    }
    byListener.set(eventListenerKey(type, options), wrapped);
  }

  function resolveWrappedEventListener(target, type, original, options) {
    try {
      return listenerWrapperRecords.get(target)?.get(original)?.get(eventListenerKey(type, options)) || null;
    } catch {
      return null;
    }
  }

  function installCompatibilityShims() {
    if (protectedCurrentOrigin || securityVerificationContext || applicationShellContext || !enabled) return;
    defineWritableIfMissing('canRunAds', true);
    defineWritableIfMissing('google_ad_status', 1);
    defineWritableIfMissing('adBlockDetected', false);
    defineWritableIfMissing('isAdBlockActive', false);
    if (!Object.prototype.hasOwnProperty.call(window, 'adsbygoogle')) {
      try {
        Object.defineProperty(window, 'adsbygoogle', {
          value: [],
          configurable: true,
          enumerable: true,
          writable: true
        });
        compatibilityShimNames.add('adsbygoogle');
      } catch {}
    }
  }

  function removeCompatibilityShims() {
    for (const name of compatibilityShimNames) {
      try { delete window[name]; } catch {}
    }
    compatibilityShimNames.clear();
  }

  function defineWritableIfMissing(name, value) {
    if (name in window) return;
    try {
      Object.defineProperty(window, name, {
        value,
        configurable: true,
        enumerable: true,
        writable: true
      });
      compatibilityShimNames.add(name);
    } catch {}
  }

  function safeDelegateOpen(args) {
    return safeApplyOpen(delegateOpen, window, args);
  }

  function safeApplyOpen(delegate, ownerWindow, args) {
    try {
      return delegate ? Reflect.apply(delegate, ownerWindow, args) : null;
    } catch {
      return null;
    }
  }

  function createSyntheticWindowProxy() {
    let proxy;
    let closed = false;

    const locationTarget = {
      assign() {},
      replace() {},
      reload() {},
      toString() {
        return 'about:blank';
      }
    };
    const locationShim = new Proxy(locationTarget, {
      get(object, property) {
        if (property === 'href' || property === 'origin' || property === 'protocol' || property === 'host' || property === 'hostname') {
          return property === 'href' ? 'about:blank' : '';
        }
        if (property === Symbol.toStringTag) return 'Location';
        return Reflect.get(object, property);
      },
      set() {
        return true;
      },
      defineProperty() {
        return true;
      },
      deleteProperty() {
        return true;
      }
    });

    const documentShim = Object.freeze({
      write() {},
      writeln() {},
      open() { return documentShim; },
      close() {},
      body: null,
      documentElement: null
    });

    const target = {
      focus() {},
      blur() {},
      close() { closed = true; },
      postMessage() {},
      stop() {},
      open() { return proxy; },
      location: locationShim,
      opener: null,
      document: documentShim
    };

    proxy = new Proxy(target, {
      get(object, property) {
        if (property === 'closed') return closed;
        if (property === 'window' || property === 'self' || property === 'top' || property === 'parent' || property === 'frames') return proxy;
        if (property === Symbol.toStringTag) return 'Window';
        return Reflect.get(object, property);
      },
      set(_object, property, value) {
        if (property === 'closed') closed = Boolean(value);
        return true;
      },
      defineProperty() {
        return true;
      },
      deleteProperty() {
        return true;
      }
    });
    return proxy;
  }

  function analyzePopunderListener(listener, type = '') {
    if (!listener) return { score: 0, strongSignal: false, suspicious: false, highConfidence: false };

    let candidate = listener;
    if (typeof listener !== 'function') {
      candidate = listener && typeof listener.handleEvent === 'function'
        ? listener.handleEvent
        : null;
    }
    if (typeof candidate !== 'function') {
      return { score: 0, strongSignal: false, suspicious: false, highConfidence: false };
    }

    let source = '';
    try {
      source = nativeFunctionToString.call(candidate);
    } catch {
      return { score: 0, strongSignal: false, suspicious: false, highConfidence: false };
    }

    if (!source || source.length > 250_000) {
      return { score: 0, strongSignal: false, suspicious: false, highConfidence: false };
    }

    const directPopup = DIRECT_POPUP_SOURCE.test(source);
    const popupAlias = POPUP_ALIAS_SOURCE.test(source);
    const knownPopunder = HIGH_RISK_LISTENER_SOURCE.test(source);
    const obfuscated = OBFUSCATION_SOURCE.test(source);
    const dynamicExecution = DYNAMIC_EXECUTION_SOURCE.test(source);
    const overlayConstruction = OVERLAY_CONSTRUCTION_SOURCE.test(source);
    const pointerTracking = POINTER_TRACKING_SOURCE.test(source);
    const sideEffect = LISTENER_SIDE_EFFECT_SOURCE.test(source);

    let score = 0;
    if (knownPopunder) score += 5;
    if (directPopup) score += 4;
    if (popupAlias) score += 3;
    if (obfuscated) score += 2;
    if (dynamicExecution) score += 2;
    if (overlayConstruction) score += 2;
    if (pointerTracking) score += 1;
    if (sideEffect) score += 1;
    if (['mousedown', 'mouseup', 'pointerdown', 'pointerup'].includes(type)) {
      score += directPopup || knownPopunder ? 1 : 0;
    }

    const strongSignal = Boolean(directPopup || popupAlias || knownPopunder);
    const elevated = aggressiveByHostname || Date.now() < elevatedRiskUntil;
    const highConfidence = strongSignal && score >= (elevated ? 4 : 7);
    const suspicious = strongSignal && score >= (elevated ? 3 : 5);
    return { score, strongSignal, suspicious, highConfidence };
  }

  function isHighConfidencePopunderListener(listener, type = '') {
    return analyzePopunderListener(listener, type).highConfidence;
  }

  function isGlobalEventTarget(target, realmWindow = window, realmDocument = document) {
    return target === realmWindow || target === realmDocument || target === realmDocument?.documentElement || target === realmDocument?.body || guardedShadowRoots.has(target);
  }

  function firstElementInPath(event) {
    try {
      const path = event.composedPath?.() || [];
      return path.find(node => node instanceof Element) || null;
    } catch {
      return event.target instanceof Element ? event.target : null;
    }
  }

  function findSuspiciousClickSurface(event) {
    try {
      const path = event.composedPath?.() || [];
      for (const node of path) {
        if (node instanceof Element && isSuspiciousClickSurface(node)) return node;
      }
    } catch {}

    const target = event?.target;
    return target instanceof Element && isSuspiciousClickSurface(target)
      ? target
      : null;
  }

  function findDangerousAnchorInEvent(event, mediaInteraction = false) {
    const target = firstElementInPath(event);
    const anchor = anchorFromElement(target);
    return anchor && shouldBlockTrustedAnchor(anchor, mediaInteraction) ? anchor : null;
  }

  function shouldBlockTrustedAnchor(anchor, mediaInteraction = false) {
    if (!enabled || protectedCurrentOrigin || !isAnchorElement(anchor)) return false;
    const target = String(safeAnchorProperty(anchor, 'target') || safeGetAttribute(anchor, 'target') || '').toLowerCase();
    if (target !== '_blank') return false;
    const href = String(safeAnchorProperty(anchor, 'href') || safeGetAttribute(anchor, 'href') || '');
    const parsed = parseDestination(href, location.href);
    if (parsed.hostname && isProtectedHostname(parsed.hostname)) return false;
    const crossOrigin = parsed.url ? parsed.url.origin !== location.origin : true;
    if (!crossOrigin) return false;
    const adDestination = parsed.hostname && AD_DESTINATION_PATTERN.test(parsed.hostname);
    const suspiciousUrl = parsed.url && SUSPICIOUS_URL_PATTERN.test(parsed.url.href);
    const dangerousScheme = /^(?:javascript:|data:text\/html|blob:)/i.test(href);
    if (mediaInteraction && crossOrigin) return true;
    return Boolean(adDestination || suspiciousUrl || dangerousScheme || ((aggressiveByHostname || Date.now() < elevatedRiskUntil) && isStealthProgrammaticAnchor(anchor)));
  }

  function findDangerousFormInEvent(event, mediaInteraction = false) {
    const target = firstElementInPath(event);
    if (!(target instanceof Element)) return null;
    let form = null;
    try { form = target.closest('form[target]'); } catch {}
    return form && shouldBlockProgrammaticForm(form) ? form : null;
  }

  function hasProtectedGestureIntent(target, intendedUrl = '') {
    const parsed = parseDestination(intendedUrl, location.href);
    if (parsed.hostname && isProtectedHostname(parsed.hostname)) return true;
    if (!(target instanceof Element)) return false;
    let candidate = target;
    try { candidate = target.closest('a,button,input,[role="button"],[role="link"]') || target; } catch {}
    const text = String(candidate.innerText || candidate.textContent || candidate.getAttribute?.('aria-label') || '').slice(0, 300);
    const identity = `${candidate.id || ''} ${candidate.className || ''} ${candidate.getAttribute?.('name') || ''} ${candidate.getAttribute?.('data-provider') || ''}`;
    return PROTECTED_GESTURE_HINT.test(`${text} ${identity}`);
  }

  function rememberTrustedGesture(event, target, mediaInteraction) {
    lastTrustedGestureEvent = event || null;
    lastTrustedGestureTarget = target || null;
    lastTrustedGestureMedia = Boolean(mediaInteraction);
    lastTrustedGestureRecordedAt = Date.now();
  }

  function starveActivePopupGesture(sourceTarget = null) {
    elevateRisk();
    const recent = Date.now() - lastTrustedGestureRecordedAt <= CONFIG.gestureWindowMs;
    const event = recent ? lastTrustedGestureEvent : null;
    const target = sourceTarget || lastTrustedGestureTarget;

    if (event) {
      try { event.preventDefault?.(); } catch {}
      try { event.returnValue = false; } catch {}
      // Keep verified native/player control handlers alive. The popup backend is
      // already denied, so media playback does not need propagation suppression.
      if (!lastTrustedGestureMedia) {
        try { event.stopImmediatePropagation?.(); } catch {}
        try { event.stopPropagation?.(); } catch {}
        try { event.cancelBubble = true; } catch {}
        blockedGestureEvents.add(event);
        suppressGestureSequence(target);
      }
    }
    return false;
  }

  function isPopupCapableScheme(url) {
    if (!(url instanceof URL)) return false;
    return /^(?:javascript:|data:|blob:|filesystem:)/i.test(String(url.protocol || ''));
  }

  function intendedNavigationUrl(target) {
    if (!(target instanceof Element)) return '';
    const anchor = target.closest('a[href]');
    if (isAnchorElement(anchor)) {
      try {
        return new URL(anchor.href, location.href).href;
      } catch {}
    }
    const form = target.closest('form[action]');
    if (isFormElement(form)) {
      try {
        return new URL(form.action, location.href).href;
      } catch {}
    }
    return '';
  }

  function matchesIntendedNavigation(destination, intendedUrl) {
    if (!(destination instanceof URL) || !intendedUrl) return false;
    try {
      const intended = new URL(intendedUrl, location.href);
      return destination.href === intended.href || destination.hostname === intended.hostname;
    } catch {
      return false;
    }
  }

  function isLegitimateInteractiveTarget(target) {
    if (!(target instanceof Element)) return false;
    if (isMediaControlElement(target)) return true;
    return Boolean(target.closest('a[href],button,input,select,textarea,summary,[role="button"],[role="link"],[contenteditable="true"],video,audio'));
  }

  function isMediaInteractionEvent(event, fallbackTarget = null) {
    if (!event?.isTrusted) return false;
    const nodes = [];
    try { nodes.push(...(event.composedPath?.() || [])); } catch {}
    if (fallbackTarget) nodes.push(fallbackTarget);
    if (event.target) nodes.push(event.target);
    const seen = new Set();
    let mediaCandidate = false;
    for (const node of nodes) {
      if (!(node instanceof Element) || seen.has(node)) continue;
      seen.add(node);
      if (hasExplicitAdSurfaceSignals(node)) return false;
      mediaCandidate ||= isMediaControlElement(node);
    }
    return mediaCandidate;
  }

  function isMediaControlElement(element) {
    if (!(element instanceof Element)) return false;
    const tag = String(element.localName || element.tagName || '').toLowerCase();
    if (tag === 'video' || tag === 'audio') return true;
    if (hasExplicitAdSurfaceSignals(element)) return false;

    const identity = mediaElementIdentity(element);
    const role = String(safeGetAttribute(element, 'role') || '').toLowerCase();
    const inputType = String(safeGetAttribute(element, 'type') || '').toLowerCase();
    const controlLike = tag === 'button' || role === 'button' || role === 'slider' || (tag === 'input' && inputType === 'range') || MEDIA_CONTROL_HINT.test(identity);
    let playerContainer = null;
    try { playerContainer = element.closest(MEDIA_PLAYER_CONTAINER_SELECTOR); } catch {}
    if (controlLike && (playerContainer || MEDIA_PLAYER_HINT.test(identity))) return true;

    if (tag === 'canvas' && (playerContainer || documentHasMediaPlaybackSurface())) return true;
    return false;
  }

  function mediaElementIdentity(element) {
    if (!(element instanceof Element)) return '';
    let className = '';
    try { className = typeof element.className === 'string' ? element.className : element.className?.baseVal || ''; } catch {}
    return `${element.id || ''} ${className} ${safeGetAttribute(element, 'aria-label') || ''} ${safeGetAttribute(element, 'title') || ''} ${safeGetAttribute(element, 'data-control') || ''} ${safeGetAttribute(element, 'data-testid') || ''}`.toLowerCase();
  }

  function hasExplicitAdSurfaceSignals(element) {
    if (!(element instanceof Element)) return false;
    const identity = mediaElementIdentity(element);
    const inline = safeGetAttribute(element, 'onclick') || '';
    if (AD_UI_HINT.test(identity) || INLINE_POPUP_PATTERN.test(inline)) return true;
    if (!(element instanceof HTMLElement)) return false;
    try {
      const style = getComputedStyle(element);
      const rect = element.getBoundingClientRect();
      const viewportArea = Math.max(1, innerWidth * innerHeight);
      const areaRatio = Math.max(0, rect.width) * Math.max(0, rect.height) / viewportArea;
      const transparent = Number.parseFloat(style.opacity || '1') <= 0.08 || style.visibility === 'hidden' || style.display === 'none';
      const positioned = ['fixed', 'absolute', 'sticky'].includes(style.position);
      const highZ = Number.parseInt(style.zIndex || '0', 10) >= 1000;
      return Boolean(positioned && areaRatio >= 0.45 && transparent && highZ);
    } catch {
      return false;
    }
  }

  function documentHasMediaPlaybackSurface() {
    try {
      return Boolean(document.querySelector('video,audio,video-js,.video-js,.jwplayer,.plyr,.shaka-video-container,[data-video-player],[class*="video-player"]'));
    } catch {
      return false;
    }
  }

  function markMediaRuntime() {
    mediaRuntimeUntil = Math.max(mediaRuntimeUntil, Date.now() + CONFIG.mediaRuntimeGraceMs);
  }

  function isMediaRuntimeActive() {
    return Date.now() < mediaRuntimeUntil;
  }

  function isSuspiciousClickSurface(target) {
    if (!(target instanceof HTMLElement) || protectedCurrentOrigin || markSecurityVerificationElement(target)) return false;
    const candidate = target.closest('[onclick],[role="button"],[role="link"],div,span,a') || target;
    if (!(candidate instanceof HTMLElement)) return false;
    if (candidate.closest('form,input,button,select,textarea,[contenteditable="true"]')) return false;
    if (candidate.querySelector('video,audio,button,input,select,textarea,[contenteditable="true"]')) return false;

    const text = (candidate.innerText || candidate.textContent || '').replace(/\s+/g, ' ').trim();
    const name = `${candidate.id} ${candidate.className}`.toLowerCase();
    const inlineHandler = candidate.getAttribute('onclick') || '';
    if (isMediaControlElement(candidate) && !AD_UI_HINT.test(`${name} ${inlineHandler}`)) return false;
    const style = getComputedStyle(candidate);
    const rect = candidate.getBoundingClientRect();
    const viewportArea = Math.max(1, innerWidth * innerHeight);
    const areaRatio = Math.max(0, rect.width) * Math.max(0, rect.height) / viewportArea;
    const positioned = ['fixed', 'absolute', 'sticky'].includes(style.position);
    const transparent = Number.parseFloat(style.opacity || '1') <= 0.16 || style.backgroundColor === 'rgba(0, 0, 0, 0)';
    const highZ = Number.parseInt(style.zIndex || '0', 10) >= 100;
    const named = OVERLAY_NAME_PATTERN.test(name);
    const scripted = INLINE_POPUP_PATTERN.test(inlineHandler);

    return (
      (positioned && areaRatio >= 0.55 && (transparent || highZ) && text.length < 120) ||
      (named && areaRatio >= 0.2 && text.length < 160) ||
      scripted
    );
  }

  function isAnchorElement(value) {
    if (!value || typeof value !== 'object') return false;
    try {
      if (typeof HTMLAnchorElement === 'function' && value instanceof HTMLAnchorElement) return true;
    } catch {}
    return String(value.localName || value.tagName || '').toLowerCase() === 'a' && 'href' in value;
  }

  function isFormElement(value) {
    if (!value || typeof value !== 'object') return false;
    try {
      if (typeof HTMLFormElement === 'function' && value instanceof HTMLFormElement) return true;
    } catch {}
    return String(value.localName || value.tagName || '').toLowerCase() === 'form';
  }

  function anchorFromElement(element) {
    if (element instanceof HTMLAnchorElement) return element;
    if (!(element instanceof Element)) return null;
    try {
      const anchor = element.closest('a[href]');
      return isAnchorElement(anchor) ? anchor : null;
    } catch {
      return null;
    }
  }

  function blockEvent(event) {
    try { event?.stopImmediatePropagation?.(); } catch {}
    try { event?.preventDefault?.(); } catch {}
    try { event?.stopPropagation?.(); } catch {}
    try { event.returnValue = false; } catch {}
    try { event.cancelBubble = true; } catch {}
    return false;
  }

  function elevateRisk() {
    elevatedRiskUntil = Math.max(elevatedRiskUntil, Date.now() + CONFIG.elevatedRiskMs);
  }

  function disguiseFunction(wrapper, nativeFunction, name, length) {
    try {
      Object.defineProperty(wrapper, 'name', {
        value: name,
        configurable: true
      });
      Object.defineProperty(wrapper, 'length', {
        value: Number.isInteger(length) ? length : nativeFunction.length,
        configurable: true
      });
      Object.defineProperty(wrapper, 'toString', {
        value: () => nativeFunctionToString.call(nativeFunction),
        configurable: true
      });
    } catch {}
  }

  function hardenFunction(value) {
    if (typeof value !== 'function') return value;
    try { Object.freeze(value); } catch {}
    return value;
  }

  function defineLockedValue(owner, property, value, enumerable = false) {
    if (!owner) return false;
    try {
      const existing = Object.getOwnPropertyDescriptor(owner, property);
      if (existing && existing.configurable === false) return existing.value === value || existing.get?.call?.(owner) === value;
      Object.defineProperty(owner, property, {
        configurable: !nativeDomRuntime,
        enumerable: existing?.enumerable ?? enumerable,
        writable: !nativeDomRuntime,
        value
      });
      return true;
    } catch {
      return false;
    }
  }

  function findPropertyDescriptor(prototype, property) {
    let cursor = prototype;
    while (cursor) {
      const descriptor = Object.getOwnPropertyDescriptor(cursor, property);
      if (descriptor) return descriptor;
      cursor = Object.getPrototypeOf(cursor);
    }
    return null;
  }

  function isIframeElement(element, requestedName) {
    const name = String(requestedName || '').toLowerCase().split(':').pop();
    if (name !== 'iframe') return false;
    if (typeof HTMLIFrameElement !== 'function') return true;
    return element instanceof HTMLIFrameElement;
  }

  function safeWindowHref(ownerWindow) {
    try {
      return String(ownerWindow?.location?.href || '');
    } catch {
      return '';
    }
  }

  function safeWindowOrigin(ownerWindow) {
    try {
      const origin = ownerWindow?.location?.origin;
      if (origin && origin !== 'null') return String(origin);
      const href = safeWindowHref(ownerWindow);
      return href ? new URL(href, location.href).origin : '';
    } catch {
      return '';
    }
  }

  function safeWindowActivation(ownerWindow) {
    try {
      return Boolean(ownerWindow?.navigator?.userActivation?.isActive);
    } catch {
      return false;
    }
  }

  function safeAnchorProperty(anchor, property) {
    try {
      return anchor[property];
    } catch {
      return '';
    }
  }

  function safeGetAttribute(element, name) {
    try {
      return element.getAttribute(name);
    } catch {
      return null;
    }
  }

  function safeHasAttribute(element, name) {
    try {
      return element.hasAttribute(name);
    } catch {
      return false;
    }
  }

  function parseDestination(value, baseHref = location.href) {
    if (value == null || value === '' || value === 'about:blank') {
      return { url: null, hostname: '' };
    }
    try {
      const url = new URL(String(value), baseHref || location.href);
      return { url, hostname: url.hostname.toLowerCase() };
    } catch {
      return { url: null, hostname: '' };
    }
  }

  function safeHostname(value) {
    try {
      return new URL(value).hostname.toLowerCase();
    } catch {
      return '';
    }
  }

  function hostnameMatchesAny(hostname, domains) {
    return Boolean(hostname && domains.some(domain => hostname === domain || hostname.endsWith(`.${domain}`)));
  }

  function isSecurityVerificationProviderHostname(hostname) {
    return hostnameMatchesAny(hostname, SECURITY_VERIFICATION_PROVIDERS);
  }

  function isSecurityVerificationReference(value, baseHref = location.href) {
    const raw = String(value || '').trim();
    if (!raw) return false;
    let parsed = null;
    try { parsed = new URL(raw, baseHref || location.href); } catch {}
    const hostname = String(parsed?.hostname || '').toLowerCase();
    const pathname = String(parsed?.pathname || '');
    const search = String(parsed?.search || '');
    const hash = String(parsed?.hash || '');
    const combined = `${pathname}${search}${hash}`;

    if (SECURITY_VERIFICATION_PATH_PATTERN.test(combined)) return true;
    if (SECURITY_VERIFICATION_TOKEN_PATTERN.test(combined) && (isSecurityVerificationProviderHostname(hostname) || hostname === currentHostname || !hostname)) return true;
    if (isSecurityVerificationProviderHostname(hostname)) return true;
    if ((hostname === 'google.com' || hostname.endsWith('.google.com') || hostname === 'gstatic.com' || hostname.endsWith('.gstatic.com')) && /\/recaptcha\//i.test(pathname)) return true;
    return false;
  }

  function isSecurityVerificationDocumentContext(href, referrer) {
    if (isSecurityVerificationReference(href, href || location.href)) return true;
    if (isSecurityVerificationReference(referrer, href || location.href)) return true;
    try {
      const name = String(window.name || '');
      if (SECURITY_VERIFICATION_TOKEN_PATTERN.test(name) || SECURITY_VERIFICATION_ELEMENT_PATTERN.test(name)) return true;
    } catch {}
    return false;
  }

  function isProtectedFlowHostname(hostname) {
    return hostnameMatchesAny(hostname, PROTECTED_DESTINATIONS);
  }

  function isTrustedApplicationHostname(hostname) {
    return hostnameMatchesAny(hostname, TRUSTED_APPLICATION_ORIGINS);
  }

  function isApplicationShellDocumentContext(hostname, href = location.href) {
    if (!hostname || AGGRESSIVE_SITE_PATTERN.test(hostname) || AD_DESTINATION_PATTERN.test(hostname)) return false;
    let parsed = null;
    try { parsed = new URL(href, location.href); } catch {}
    if (!parsed || !['http:', 'https:'].includes(parsed.protocol)) {
      try { parsed = new URL(document.referrer || '', location.href); } catch {}
    }
    if (parsed && parsed.protocol !== 'https:') return false;
    if (hostnameMatchesAny(hostname, OFFICIAL_APPLICATION_SHELL_ORIGINS)) return true;
    if (APPLICATION_SHELL_HOST_PATTERN.test(hostname)) return true;
    return Boolean(parsed && APPLICATION_SHELL_PATH_PATTERN.test(parsed.pathname || ''));
  }

  function isTrustedPlatformDestinationHostname(hostname) {
    return hostnameMatchesAny(hostname, TRUSTED_PLATFORM_DESTINATIONS);
  }

  function isProtectedHostname(hostname) {
    return isProtectedFlowHostname(hostname) || isTrustedPlatformDestinationHostname(hostname);
  }
})();
} catch {}
