var G = { exports: {} }, Xe = G.exports, he;
function Ye() {
  return he || (he = 1, (function(t, r) {
    (function(n, o) {
      o(t);
    })(typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : Xe, function(n) {
      if (!(globalThis.chrome && globalThis.chrome.runtime && globalThis.chrome.runtime.id))
        throw new Error("This script should only be loaded in a browser extension.");
      if (globalThis.browser && globalThis.browser.runtime && globalThis.browser.runtime.id)
        n.exports = globalThis.browser;
      else {
        const o = "The message port closed before a response was received.", a = (l) => {
          const c = {
            alarms: {
              clear: {
                minArgs: 0,
                maxArgs: 1
              },
              clearAll: {
                minArgs: 0,
                maxArgs: 0
              },
              get: {
                minArgs: 0,
                maxArgs: 1
              },
              getAll: {
                minArgs: 0,
                maxArgs: 0
              }
            },
            bookmarks: {
              create: {
                minArgs: 1,
                maxArgs: 1
              },
              get: {
                minArgs: 1,
                maxArgs: 1
              },
              getChildren: {
                minArgs: 1,
                maxArgs: 1
              },
              getRecent: {
                minArgs: 1,
                maxArgs: 1
              },
              getSubTree: {
                minArgs: 1,
                maxArgs: 1
              },
              getTree: {
                minArgs: 0,
                maxArgs: 0
              },
              move: {
                minArgs: 2,
                maxArgs: 2
              },
              remove: {
                minArgs: 1,
                maxArgs: 1
              },
              removeTree: {
                minArgs: 1,
                maxArgs: 1
              },
              search: {
                minArgs: 1,
                maxArgs: 1
              },
              update: {
                minArgs: 2,
                maxArgs: 2
              }
            },
            browserAction: {
              disable: {
                minArgs: 0,
                maxArgs: 1,
                fallbackToNoCallback: !0
              },
              enable: {
                minArgs: 0,
                maxArgs: 1,
                fallbackToNoCallback: !0
              },
              getBadgeBackgroundColor: {
                minArgs: 1,
                maxArgs: 1
              },
              getBadgeText: {
                minArgs: 1,
                maxArgs: 1
              },
              getPopup: {
                minArgs: 1,
                maxArgs: 1
              },
              getTitle: {
                minArgs: 1,
                maxArgs: 1
              },
              openPopup: {
                minArgs: 0,
                maxArgs: 0
              },
              setBadgeBackgroundColor: {
                minArgs: 1,
                maxArgs: 1,
                fallbackToNoCallback: !0
              },
              setBadgeText: {
                minArgs: 1,
                maxArgs: 1,
                fallbackToNoCallback: !0
              },
              setIcon: {
                minArgs: 1,
                maxArgs: 1
              },
              setPopup: {
                minArgs: 1,
                maxArgs: 1,
                fallbackToNoCallback: !0
              },
              setTitle: {
                minArgs: 1,
                maxArgs: 1,
                fallbackToNoCallback: !0
              }
            },
            browsingData: {
              remove: {
                minArgs: 2,
                maxArgs: 2
              },
              removeCache: {
                minArgs: 1,
                maxArgs: 1
              },
              removeCookies: {
                minArgs: 1,
                maxArgs: 1
              },
              removeDownloads: {
                minArgs: 1,
                maxArgs: 1
              },
              removeFormData: {
                minArgs: 1,
                maxArgs: 1
              },
              removeHistory: {
                minArgs: 1,
                maxArgs: 1
              },
              removeLocalStorage: {
                minArgs: 1,
                maxArgs: 1
              },
              removePasswords: {
                minArgs: 1,
                maxArgs: 1
              },
              removePluginData: {
                minArgs: 1,
                maxArgs: 1
              },
              settings: {
                minArgs: 0,
                maxArgs: 0
              }
            },
            commands: {
              getAll: {
                minArgs: 0,
                maxArgs: 0
              }
            },
            contextMenus: {
              remove: {
                minArgs: 1,
                maxArgs: 1
              },
              removeAll: {
                minArgs: 0,
                maxArgs: 0
              },
              update: {
                minArgs: 2,
                maxArgs: 2
              }
            },
            cookies: {
              get: {
                minArgs: 1,
                maxArgs: 1
              },
              getAll: {
                minArgs: 1,
                maxArgs: 1
              },
              getAllCookieStores: {
                minArgs: 0,
                maxArgs: 0
              },
              remove: {
                minArgs: 1,
                maxArgs: 1
              },
              set: {
                minArgs: 1,
                maxArgs: 1
              }
            },
            devtools: {
              inspectedWindow: {
                eval: {
                  minArgs: 1,
                  maxArgs: 2,
                  singleCallbackArg: !1
                }
              },
              panels: {
                create: {
                  minArgs: 3,
                  maxArgs: 3,
                  singleCallbackArg: !0
                },
                elements: {
                  createSidebarPane: {
                    minArgs: 1,
                    maxArgs: 1
                  }
                }
              }
            },
            downloads: {
              cancel: {
                minArgs: 1,
                maxArgs: 1
              },
              download: {
                minArgs: 1,
                maxArgs: 1
              },
              erase: {
                minArgs: 1,
                maxArgs: 1
              },
              getFileIcon: {
                minArgs: 1,
                maxArgs: 2
              },
              open: {
                minArgs: 1,
                maxArgs: 1,
                fallbackToNoCallback: !0
              },
              pause: {
                minArgs: 1,
                maxArgs: 1
              },
              removeFile: {
                minArgs: 1,
                maxArgs: 1
              },
              resume: {
                minArgs: 1,
                maxArgs: 1
              },
              search: {
                minArgs: 1,
                maxArgs: 1
              },
              show: {
                minArgs: 1,
                maxArgs: 1,
                fallbackToNoCallback: !0
              }
            },
            extension: {
              isAllowedFileSchemeAccess: {
                minArgs: 0,
                maxArgs: 0
              },
              isAllowedIncognitoAccess: {
                minArgs: 0,
                maxArgs: 0
              }
            },
            history: {
              addUrl: {
                minArgs: 1,
                maxArgs: 1
              },
              deleteAll: {
                minArgs: 0,
                maxArgs: 0
              },
              deleteRange: {
                minArgs: 1,
                maxArgs: 1
              },
              deleteUrl: {
                minArgs: 1,
                maxArgs: 1
              },
              getVisits: {
                minArgs: 1,
                maxArgs: 1
              },
              search: {
                minArgs: 1,
                maxArgs: 1
              }
            },
            i18n: {
              detectLanguage: {
                minArgs: 1,
                maxArgs: 1
              },
              getAcceptLanguages: {
                minArgs: 0,
                maxArgs: 0
              }
            },
            identity: {
              launchWebAuthFlow: {
                minArgs: 1,
                maxArgs: 1
              }
            },
            idle: {
              queryState: {
                minArgs: 1,
                maxArgs: 1
              }
            },
            management: {
              get: {
                minArgs: 1,
                maxArgs: 1
              },
              getAll: {
                minArgs: 0,
                maxArgs: 0
              },
              getSelf: {
                minArgs: 0,
                maxArgs: 0
              },
              setEnabled: {
                minArgs: 2,
                maxArgs: 2
              },
              uninstallSelf: {
                minArgs: 0,
                maxArgs: 1
              }
            },
            notifications: {
              clear: {
                minArgs: 1,
                maxArgs: 1
              },
              create: {
                minArgs: 1,
                maxArgs: 2
              },
              getAll: {
                minArgs: 0,
                maxArgs: 0
              },
              getPermissionLevel: {
                minArgs: 0,
                maxArgs: 0
              },
              update: {
                minArgs: 2,
                maxArgs: 2
              }
            },
            pageAction: {
              getPopup: {
                minArgs: 1,
                maxArgs: 1
              },
              getTitle: {
                minArgs: 1,
                maxArgs: 1
              },
              hide: {
                minArgs: 1,
                maxArgs: 1,
                fallbackToNoCallback: !0
              },
              setIcon: {
                minArgs: 1,
                maxArgs: 1
              },
              setPopup: {
                minArgs: 1,
                maxArgs: 1,
                fallbackToNoCallback: !0
              },
              setTitle: {
                minArgs: 1,
                maxArgs: 1,
                fallbackToNoCallback: !0
              },
              show: {
                minArgs: 1,
                maxArgs: 1,
                fallbackToNoCallback: !0
              }
            },
            permissions: {
              contains: {
                minArgs: 1,
                maxArgs: 1
              },
              getAll: {
                minArgs: 0,
                maxArgs: 0
              },
              remove: {
                minArgs: 1,
                maxArgs: 1
              },
              request: {
                minArgs: 1,
                maxArgs: 1
              }
            },
            runtime: {
              getBackgroundPage: {
                minArgs: 0,
                maxArgs: 0
              },
              getPlatformInfo: {
                minArgs: 0,
                maxArgs: 0
              },
              openOptionsPage: {
                minArgs: 0,
                maxArgs: 0
              },
              requestUpdateCheck: {
                minArgs: 0,
                maxArgs: 0
              },
              sendMessage: {
                minArgs: 1,
                maxArgs: 3
              },
              sendNativeMessage: {
                minArgs: 2,
                maxArgs: 2
              },
              setUninstallURL: {
                minArgs: 1,
                maxArgs: 1
              }
            },
            sessions: {
              getDevices: {
                minArgs: 0,
                maxArgs: 1
              },
              getRecentlyClosed: {
                minArgs: 0,
                maxArgs: 1
              },
              restore: {
                minArgs: 0,
                maxArgs: 1
              }
            },
            storage: {
              local: {
                clear: {
                  minArgs: 0,
                  maxArgs: 0
                },
                get: {
                  minArgs: 0,
                  maxArgs: 1
                },
                getBytesInUse: {
                  minArgs: 0,
                  maxArgs: 1
                },
                remove: {
                  minArgs: 1,
                  maxArgs: 1
                },
                set: {
                  minArgs: 1,
                  maxArgs: 1
                }
              },
              managed: {
                get: {
                  minArgs: 0,
                  maxArgs: 1
                },
                getBytesInUse: {
                  minArgs: 0,
                  maxArgs: 1
                }
              },
              sync: {
                clear: {
                  minArgs: 0,
                  maxArgs: 0
                },
                get: {
                  minArgs: 0,
                  maxArgs: 1
                },
                getBytesInUse: {
                  minArgs: 0,
                  maxArgs: 1
                },
                remove: {
                  minArgs: 1,
                  maxArgs: 1
                },
                set: {
                  minArgs: 1,
                  maxArgs: 1
                }
              }
            },
            tabs: {
              captureVisibleTab: {
                minArgs: 0,
                maxArgs: 2
              },
              create: {
                minArgs: 1,
                maxArgs: 1
              },
              detectLanguage: {
                minArgs: 0,
                maxArgs: 1
              },
              discard: {
                minArgs: 0,
                maxArgs: 1
              },
              duplicate: {
                minArgs: 1,
                maxArgs: 1
              },
              executeScript: {
                minArgs: 1,
                maxArgs: 2
              },
              get: {
                minArgs: 1,
                maxArgs: 1
              },
              getCurrent: {
                minArgs: 0,
                maxArgs: 0
              },
              getZoom: {
                minArgs: 0,
                maxArgs: 1
              },
              getZoomSettings: {
                minArgs: 0,
                maxArgs: 1
              },
              goBack: {
                minArgs: 0,
                maxArgs: 1
              },
              goForward: {
                minArgs: 0,
                maxArgs: 1
              },
              highlight: {
                minArgs: 1,
                maxArgs: 1
              },
              insertCSS: {
                minArgs: 1,
                maxArgs: 2
              },
              move: {
                minArgs: 2,
                maxArgs: 2
              },
              query: {
                minArgs: 1,
                maxArgs: 1
              },
              reload: {
                minArgs: 0,
                maxArgs: 2
              },
              remove: {
                minArgs: 1,
                maxArgs: 1
              },
              removeCSS: {
                minArgs: 1,
                maxArgs: 2
              },
              sendMessage: {
                minArgs: 2,
                maxArgs: 3
              },
              setZoom: {
                minArgs: 1,
                maxArgs: 2
              },
              setZoomSettings: {
                minArgs: 1,
                maxArgs: 2
              },
              update: {
                minArgs: 1,
                maxArgs: 2
              }
            },
            topSites: {
              get: {
                minArgs: 0,
                maxArgs: 0
              }
            },
            webNavigation: {
              getAllFrames: {
                minArgs: 1,
                maxArgs: 1
              },
              getFrame: {
                minArgs: 1,
                maxArgs: 1
              }
            },
            webRequest: {
              handlerBehaviorChanged: {
                minArgs: 0,
                maxArgs: 0
              }
            },
            windows: {
              create: {
                minArgs: 0,
                maxArgs: 1
              },
              get: {
                minArgs: 1,
                maxArgs: 2
              },
              getAll: {
                minArgs: 0,
                maxArgs: 1
              },
              getCurrent: {
                minArgs: 0,
                maxArgs: 1
              },
              getLastFocused: {
                minArgs: 0,
                maxArgs: 1
              },
              remove: {
                minArgs: 1,
                maxArgs: 1
              },
              update: {
                minArgs: 2,
                maxArgs: 2
              }
            }
          };
          if (Object.keys(c).length === 0)
            throw new Error("api-metadata.json has not been included in browser-polyfill");
          class w extends WeakMap {
            constructor(s, d = void 0) {
              super(d), this.createItem = s;
            }
            get(s) {
              return this.has(s) || this.set(s, this.createItem(s)), super.get(s);
            }
          }
          const h = (i) => i && typeof i == "object" && typeof i.then == "function", A = (i, s) => (...d) => {
            l.runtime.lastError ? i.reject(new Error(l.runtime.lastError.message)) : s.singleCallbackArg || d.length <= 1 && s.singleCallbackArg !== !1 ? i.resolve(d[0]) : i.resolve(d);
          }, M = (i) => i == 1 ? "argument" : "arguments", ze = (i, s) => function(g, ...y) {
            if (y.length < s.minArgs)
              throw new Error(`Expected at least ${s.minArgs} ${M(s.minArgs)} for ${i}(), got ${y.length}`);
            if (y.length > s.maxArgs)
              throw new Error(`Expected at most ${s.maxArgs} ${M(s.maxArgs)} for ${i}(), got ${y.length}`);
            return new Promise((x, I) => {
              if (s.fallbackToNoCallback)
                try {
                  g[i](...y, A({
                    resolve: x,
                    reject: I
                  }, s));
                } catch (u) {
                  console.warn(`${i} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `, u), g[i](...y), s.fallbackToNoCallback = !1, s.noCallback = !0, x();
                }
              else s.noCallback ? (g[i](...y), x()) : g[i](...y, A({
                resolve: x,
                reject: I
              }, s));
            });
          }, we = (i, s, d) => new Proxy(s, {
            apply(g, y, x) {
              return d.call(y, i, ...x);
            }
          });
          let j = Function.call.bind(Object.prototype.hasOwnProperty);
          const z = (i, s = {}, d = {}) => {
            let g = /* @__PURE__ */ Object.create(null), y = {
              has(I, u) {
                return u in i || u in g;
              },
              get(I, u, v) {
                if (u in g)
                  return g[u];
                if (!(u in i))
                  return;
                let b = i[u];
                if (typeof b == "function")
                  if (typeof s[u] == "function")
                    b = we(i, i[u], s[u]);
                  else if (j(d, u)) {
                    let D = ze(u, d[u]);
                    b = we(i, i[u], D);
                  } else
                    b = b.bind(i);
                else if (typeof b == "object" && b !== null && (j(s, u) || j(d, u)))
                  b = z(b, s[u], d[u]);
                else if (j(d, "*"))
                  b = z(b, s[u], d["*"]);
                else
                  return Object.defineProperty(g, u, {
                    configurable: !0,
                    enumerable: !0,
                    get() {
                      return i[u];
                    },
                    set(D) {
                      i[u] = D;
                    }
                  }), b;
                return g[u] = b, b;
              },
              set(I, u, v, b) {
                return u in g ? g[u] = v : i[u] = v, !0;
              },
              defineProperty(I, u, v) {
                return Reflect.defineProperty(g, u, v);
              },
              deleteProperty(I, u) {
                return Reflect.deleteProperty(g, u);
              }
            }, x = Object.create(i);
            return new Proxy(x, y);
          }, Q = (i) => ({
            addListener(s, d, ...g) {
              s.addListener(i.get(d), ...g);
            },
            hasListener(s, d) {
              return s.hasListener(i.get(d));
            },
            removeListener(s, d) {
              s.removeListener(i.get(d));
            }
          }), Ge = new w((i) => typeof i != "function" ? i : function(d) {
            const g = z(d, {}, {
              getContent: {
                minArgs: 0,
                maxArgs: 0
              }
            });
            i(g);
          }), Ae = new w((i) => typeof i != "function" ? i : function(d, g, y) {
            let x = !1, I, u = new Promise((N) => {
              I = function(O) {
                x = !0, N(O);
              };
            }), v;
            try {
              v = i(d, g, I);
            } catch (N) {
              v = Promise.reject(N);
            }
            const b = v !== !0 && h(v);
            if (v !== !0 && !b && !x)
              return !1;
            const D = (N) => {
              N.then((O) => {
                y(O);
              }, (O) => {
                let te;
                O && (O instanceof Error || typeof O.message == "string") ? te = O.message : te = "An unexpected error occurred", y({
                  __mozWebExtensionPolyfillReject__: !0,
                  message: te
                });
              }).catch((O) => {
                console.error("Failed to send onMessage rejected reply", O);
              });
            };
            return D(b ? v : u), !0;
          }), Ke = ({
            reject: i,
            resolve: s
          }, d) => {
            l.runtime.lastError ? l.runtime.lastError.message === o ? s() : i(new Error(l.runtime.lastError.message)) : d && d.__mozWebExtensionPolyfillReject__ ? i(new Error(d.message)) : s(d);
          }, pe = (i, s, d, ...g) => {
            if (g.length < s.minArgs)
              throw new Error(`Expected at least ${s.minArgs} ${M(s.minArgs)} for ${i}(), got ${g.length}`);
            if (g.length > s.maxArgs)
              throw new Error(`Expected at most ${s.maxArgs} ${M(s.maxArgs)} for ${i}(), got ${g.length}`);
            return new Promise((y, x) => {
              const I = Ke.bind(null, {
                resolve: y,
                reject: x
              });
              g.push(I), d.sendMessage(...g);
            });
          }, Ve = {
            devtools: {
              network: {
                onRequestFinished: Q(Ge)
              }
            },
            runtime: {
              onMessage: Q(Ae),
              onMessageExternal: Q(Ae),
              sendMessage: pe.bind(null, "sendMessage", {
                minArgs: 1,
                maxArgs: 3
              })
            },
            tabs: {
              sendMessage: pe.bind(null, "sendMessage", {
                minArgs: 2,
                maxArgs: 3
              })
            }
          }, ee = {
            clear: {
              minArgs: 1,
              maxArgs: 1
            },
            get: {
              minArgs: 1,
              maxArgs: 1
            },
            set: {
              minArgs: 1,
              maxArgs: 1
            }
          };
          return c.privacy = {
            network: {
              "*": ee
            },
            services: {
              "*": ee
            },
            websites: {
              "*": ee
            }
          }, z(l, Ve, c);
        };
        n.exports = a(chrome);
      }
    });
  })(G)), G.exports;
}
Ye();
var le = { CEB_EXTENSION_TOKEN_SECRET: "1a3efe027cf906e2b987c0a61f498dfb84a4840ab317cd1d1d99944b9259e8fb" };
const ae = "trends_runner_runtime_v1", ve = "trends-runner-keepalive", Je = "trends-web-bridge", Ze = "trends-popup-control", Qe = 3e3, be = 3, et = 15e3, tt = 45e3, Te = 960, rt = 760, ye = 24;
function Se(t, r) {
  const n = Number(t);
  return !Number.isFinite(n) || n <= 0 ? r : Math.floor(n);
}
const nt = "https://trends.google.com", re = Se(le.CEB_EXTENSION_MAX_CAPTURE_BODY_CHARS, 12e4), ke = Se(le.CEB_EXTENSION_MAX_OUTBOX_ITEMS, 200), P = {
  queryInterval: 8e3,
  randomDelay: 3e3,
  batchPause: 30,
  batchPauseTime: 12e4,
  pageDataTimeoutMs: 2e4,
  taskHardTimeoutMs: 6e4
}, L = {
  windowMode: "dedicated-window",
  reuseTab: !0,
  keepOpen: !0,
  focusPolicy: "never",
  refreshAfterTasks: 0,
  recreateOnFailure: !0
}, e = {
  runId: null,
  token: "",
  state: "idle",
  config: { ...P },
  collectorConfig: { ...L },
  queue: [],
  currentTask: null,
  currentData: [],
  completedCount: 0,
  failedCount: 0,
  totalTasks: 0,
  seq: 0,
  ackSeq: 0,
  outbox: [],
  lastTaskStartedAt: 0,
  collectorWindowId: null,
  collectorTabId: null,
  collectorNavigateCount: 0,
  splitWindowId: null,
  splitOriginalBounds: null,
  splitApplied: !1,
  popupCollectorWindowModeOverride: null,
  pausedByBridgeLoss: !1,
  bridgeConnected: !1,
  bridgeLastSeenAt: 0,
  bridgeDisconnectedAt: 0,
  lastError: null,
  consecutivePageDataTimeouts: 0
};
let V = null, E = null, T = null, k = null, ne = null, K = null, oe = !1;
const $ = /* @__PURE__ */ new Set(), X = /* @__PURE__ */ new Set();
function C() {
  return Date.now();
}
function Ee() {
  return `${Date.now()}-${Math.random().toString(16).slice(2)}`;
}
function m(t, ...r) {
  console.log(`[Collector] ${t}`, ...r);
}
function W(t, ...r) {
  console.log(`[Runner] ${t}`, ...r);
}
function U(t) {
  return t instanceof Error ? t.message : String(t);
}
function B(t) {
  return typeof t == "object" && t !== null;
}
function We(t) {
  return !B(t) || t.v !== 1 ? !1 : typeof t.runId == "string" && typeof t.seq == "number" && typeof t.ts == "number" && typeof t.nonce == "string" && typeof t.type == "string" && typeof t.token == "string" && "payload" in t;
}
function Me(t) {
  if (!B(t) || typeof t.type != "string") return null;
  const r = Number(t.seq ?? 0), n = Number(t.ts ?? C());
  return {
    v: 1,
    runId: typeof t.runId == "string" && t.runId.length > 0 ? t.runId : e.runId ?? "no-run",
    seq: Number.isFinite(r) ? r : 0,
    ts: Number.isFinite(n) ? n : C(),
    nonce: typeof t.nonce == "string" && t.nonce.length > 0 ? t.nonce : Ee(),
    type: t.type,
    token: typeof t.token == "string" ? t.token : "",
    payload: t.payload ?? {}
  };
}
function ot(t) {
  try {
    return new URL(t).href;
  } catch {
    return t;
  }
}
function at(t) {
  const r = t.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
  return new RegExp(`^${r}$`);
}
function it(t, r) {
  if (t === "*") return !0;
  if (t.startsWith("*.")) {
    const n = t.slice(2);
    return r === n || r.endsWith(`.${n}`);
  }
  return r === t;
}
function st(t, r) {
  if (r === "<all_urls>") return !1;
  const n = r.match(/^(\*|https?|file|ftp):\/\/([^/]+)(\/.*)$/);
  if (!n) return !1;
  const [, o, a, l] = n;
  let c;
  try {
    c = new URL(t);
  } catch {
    return !1;
  }
  if (!(o === "*" ? c.protocol === "http:" || c.protocol === "https:" : c.protocol === `${o}:`) || !it(a, c.hostname)) return !1;
  const h = at(l), A = `${c.pathname}${c.search}`;
  return h.test(A);
}
function Oe(t) {
  var l;
  const r = (t == null ? void 0 : t.url) ?? (t == null ? void 0 : t.origin);
  if (!r) return !1;
  const o = ((l = chrome.runtime.getManifest().externally_connectable) == null ? void 0 : l.matches) ?? [];
  if (!o.length) return !1;
  const a = ot(r);
  return o.some((c) => st(a, c));
}
function q(t) {
  return typeof (t == null ? void 0 : t.url) == "string" ? t.url : typeof (t == null ? void 0 : t.origin) == "string" ? t.origin : "unknown";
}
function lt(t) {
  return !B(t) || t.type !== Ze ? !1 : t.action === "start-or-resume" || t.action === "pause" || t.action === "stop" || t.action === "clear-tasks" || t.action === "clear-cache" ? !0 : t.action !== "set-window-mode" ? !1 : t.mode === "dedicated-window" || t.mode === "current-window";
}
function Y(t) {
  const r = t.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(t.length / 4) * 4, "=");
  return atob(r);
}
function _e(t) {
  const r = Y(t), n = new ArrayBuffer(r.length), o = new Uint8Array(n);
  for (let a = 0; a < r.length; a += 1)
    o[a] = r.charCodeAt(a);
  return n;
}
function ct(t) {
  const r = t.split(".");
  if (r.length !== 3) return null;
  try {
    return JSON.parse(Y(r[1]));
  } catch {
    return null;
  }
}
function ut(t) {
  const r = t.split(".");
  if (r.length !== 2) return null;
  try {
    return JSON.parse(Y(r[0]));
  } catch {
    return null;
  }
}
async function dt(t, r) {
  const n = t.split(".");
  if (n.length !== 3) return !1;
  const [o, a, l] = n;
  let c = "";
  try {
    c = JSON.parse(Y(o)).alg ?? "";
  } catch {
    return !1;
  }
  if (c !== "HS256") return !1;
  const w = new TextEncoder(), h = await crypto.subtle.importKey(
    "raw",
    w.encode(r),
    {
      name: "HMAC",
      hash: "SHA-256"
    },
    !1,
    ["verify"]
  );
  return crypto.subtle.verify(
    "HMAC",
    h,
    _e(l),
    w.encode(`${o}.${a}`)
  );
}
async function gt(t, r) {
  const n = t.split(".");
  if (n.length !== 2) return !1;
  const [o, a] = n, l = new TextEncoder(), c = await crypto.subtle.importKey(
    "raw",
    l.encode(r),
    {
      name: "HMAC",
      hash: "SHA-256"
    },
    !1,
    ["verify"]
  );
  return crypto.subtle.verify("HMAC", c, _e(a), l.encode(o));
}
function Pe(t) {
  return t > 1e12 ? t : t * 1e3;
}
function mt(t) {
  return typeof t.exp != "number" ? !1 : Pe(t.exp) <= C();
}
function ft(t) {
  return typeof t.nbf != "number" ? !1 : Pe(t.nbf) > C();
}
async function wt(t, r) {
  var h;
  if (!t || t.trim().length < 8) return { ok: !1, reason: "token_invalid" };
  const n = t.trim(), o = ct(n), a = o ? null : ut(n), l = ((h = le.CEB_EXTENSION_TOKEN_SECRET) == null ? void 0 : h.trim()) ?? "";
  if (!l || l.length < 16) return { ok: !1, reason: "token_invalid" };
  if (!o && !a) return { ok: !1, reason: "token_invalid" };
  const c = o ?? a;
  if (!c) return { ok: !1, reason: "token_invalid" };
  if (mt(c)) return { ok: !1, reason: "token_expired" };
  if (ft(c)) return { ok: !1, reason: "token_invalid" };
  const w = c.runId ?? c.rid;
  return typeof w == "string" && w !== r ? { ok: !1, reason: "token_invalid" } : o && !await dt(n, l) ? { ok: !1, reason: "token_invalid" } : a && !await gt(n, l) ? { ok: !1, reason: "token_invalid" } : { ok: !0 };
}
function xe(t) {
  return {
    queryInterval: (t == null ? void 0 : t.queryInterval) ?? P.queryInterval,
    randomDelay: (t == null ? void 0 : t.randomDelay) ?? P.randomDelay,
    batchPause: (t == null ? void 0 : t.batchPause) ?? P.batchPause,
    batchPauseTime: (t == null ? void 0 : t.batchPauseTime) ?? P.batchPauseTime,
    pageDataTimeoutMs: (t == null ? void 0 : t.pageDataTimeoutMs) ?? P.pageDataTimeoutMs,
    taskHardTimeoutMs: (t == null ? void 0 : t.taskHardTimeoutMs) ?? P.taskHardTimeoutMs
  };
}
function At(t) {
  var r, n, o, a, l;
  return {
    windowMode: ((r = t == null ? void 0 : t.collector) == null ? void 0 : r.windowMode) ?? L.windowMode,
    reuseTab: ((n = t == null ? void 0 : t.collector) == null ? void 0 : n.reuseTab) ?? L.reuseTab,
    keepOpen: ((o = t == null ? void 0 : t.collector) == null ? void 0 : o.keepOpen) ?? L.keepOpen,
    focusPolicy: ((a = t == null ? void 0 : t.collector) == null ? void 0 : a.focusPolicy) ?? L.focusPolicy,
    // 强制关闭周期性重建，仅在故障场景下由 recreateOnFailure 触发重建
    refreshAfterTasks: 0,
    recreateOnFailure: ((l = t == null ? void 0 : t.collector) == null ? void 0 : l.recreateOnFailure) ?? L.recreateOnFailure
  };
}
function ce(t) {
  const r = e.popupCollectorWindowModeOverride;
  if (!r) return t;
  const n = {
    ...t,
    windowMode: r
  };
  return r === "current-window" && n.focusPolicy !== "never" && (n.focusPolicy = "per-task"), m("apply popup windowMode override=%s effectiveFocusPolicy=%s", r, n.focusPolicy), n;
}
function pt() {
  return {
    runId: e.runId,
    token: e.token,
    state: e.state,
    config: e.config,
    collectorConfig: e.collectorConfig,
    queue: e.queue,
    currentTask: e.currentTask,
    currentData: e.currentData,
    completedCount: e.completedCount,
    failedCount: e.failedCount,
    totalTasks: e.totalTasks,
    seq: e.seq,
    ackSeq: e.ackSeq,
    outbox: e.outbox,
    lastTaskStartedAt: e.lastTaskStartedAt,
    collectorWindowId: e.collectorWindowId,
    collectorTabId: e.collectorTabId,
    collectorNavigateCount: e.collectorNavigateCount,
    splitWindowId: e.splitWindowId,
    splitOriginalBounds: e.splitOriginalBounds,
    splitApplied: e.splitApplied,
    popupCollectorWindowModeOverride: e.popupCollectorWindowModeOverride,
    pausedByBridgeLoss: e.pausedByBridgeLoss,
    bridgeConnected: e.bridgeConnected,
    bridgeLastSeenAt: e.bridgeLastSeenAt,
    bridgeDisconnectedAt: e.bridgeDisconnectedAt,
    lastError: e.lastError,
    consecutivePageDataTimeouts: e.consecutivePageDataTimeouts
  };
}
async function f() {
  await chrome.storage.local.set({ [ae]: pt() });
}
async function ht() {
  const r = (await chrome.storage.local.get(ae))[ae];
  r && (e.runId = r.runId ?? null, e.token = r.token ?? "", e.state = r.state ?? "idle", e.config = { ...P, ...r.config ?? {} }, e.collectorConfig = { ...L, ...r.collectorConfig ?? {} }, e.collectorConfig.refreshAfterTasks = 0, e.queue = r.queue ?? [], e.currentTask = r.currentTask ?? null, e.currentData = r.currentData ?? [], e.completedCount = r.completedCount ?? 0, e.failedCount = r.failedCount ?? 0, e.totalTasks = r.totalTasks ?? 0, e.seq = r.seq ?? 0, e.ackSeq = r.ackSeq ?? 0, e.outbox = r.outbox ?? [], e.lastTaskStartedAt = r.lastTaskStartedAt ?? 0, e.collectorWindowId = r.collectorWindowId ?? null, e.collectorTabId = r.collectorTabId ?? null, e.collectorNavigateCount = r.collectorNavigateCount ?? 0, e.splitWindowId = r.splitWindowId ?? null, e.splitOriginalBounds = r.splitOriginalBounds ?? null, e.splitApplied = r.splitApplied ?? !1, e.popupCollectorWindowModeOverride = r.popupCollectorWindowModeOverride ?? null, e.pausedByBridgeLoss = r.pausedByBridgeLoss ?? !1, e.bridgeConnected = !1, e.bridgeLastSeenAt = r.bridgeLastSeenAt ?? 0, e.bridgeDisconnectedAt = r.bridgeDisconnectedAt ?? 0, e.lastError = r.lastError ?? null, e.consecutivePageDataTimeouts = r.consecutivePageDataTimeouts ?? 0, e.collectorConfig = ce(e.collectorConfig), e.state === "running" && (e.currentTask && (e.queue.unshift(e.currentTask), e.currentTask = null, e.currentData = []), e.state = "recovering", _(1e3)));
}
function Le(t) {
  if (!V) return !1;
  try {
    return V.postMessage(t), !0;
  } catch {
    return !1;
  }
}
async function S(t, r) {
  e.seq += 1;
  const n = {
    v: 1,
    runId: e.runId ?? "no-run",
    seq: e.seq,
    ts: C(),
    nonce: Ee(),
    type: t,
    token: e.token,
    payload: r
  };
  e.outbox.push(n), e.outbox.length > ke && e.outbox.splice(0, e.outbox.length - ke), Le(n), await f();
}
function bt(t) {
  try {
    const r = new URL(t);
    return r.origin === nt && r.pathname.startsWith("/trends/api/widgetdata/");
  } catch {
    return !1;
  }
}
function Tt(t) {
  const r = typeof t == "string" ? t : String(t ?? ""), n = Number.isFinite(re) && re > 0 ? Math.floor(re) : 12e4;
  return r.length <= n ? r : r.slice(0, n);
}
function yt(t) {
  t <= e.ackSeq || (e.ackSeq = t, e.outbox = e.outbox.filter((r) => r.seq > t), f());
}
function Be(t) {
  const r = e.outbox.filter((n) => n.seq >= t);
  for (const n of r)
    Le(n);
}
async function p() {
  var t;
  await S("status-update", {
    state: e.state,
    runId: e.runId,
    currentTaskId: ((t = e.currentTask) == null ? void 0 : t.id) ?? null,
    completedCount: e.completedCount,
    failedCount: e.failedCount,
    totalTasks: e.totalTasks
  });
}
function ue() {
  E && clearTimeout(E), T && clearTimeout(T), k && clearTimeout(k), E = null, T = null, k = null;
}
function H() {
  K && (clearTimeout(K), K = null);
}
function de() {
  e.bridgeConnected = !0, e.bridgeLastSeenAt = C(), e.bridgeDisconnectedAt = 0, H();
}
async function De(t) {
  e.bridgeConnected = !1, e.bridgeDisconnectedAt = C(), e.lastError = t, await f();
}
function ge() {
  T && clearTimeout(T), k && clearTimeout(k), T = setTimeout(() => {
    Pt();
  }, e.config.pageDataTimeoutMs), k = setTimeout(() => {
    F("task hard timeout");
  }, e.config.taskHardTimeoutMs);
}
function _(t) {
  E && clearTimeout(E), E = setTimeout(() => {
    E = null, He();
  }, t);
}
function kt() {
  return e.collectorConfig.focusPolicy === "never" ? !1 : e.collectorConfig.focusPolicy === "per-task" ? !0 : e.collectorNavigateCount === 0;
}
async function xt() {
  if (!e.collectorTabId) return null;
  try {
    return await chrome.tabs.get(e.collectorTabId);
  } catch {
    return null;
  }
}
async function Ne() {
  if (!e.collectorWindowId) return null;
  try {
    return await chrome.windows.get(e.collectorWindowId, { populate: !0 });
  } catch {
    return null;
  }
}
function Ct(t) {
  return !!t && typeof t.left == "number" && typeof t.top == "number" && typeof t.width == "number" && typeof t.height == "number";
}
async function Ce(t) {
  try {
    return (await chrome.windows.get(t)).state !== "normal" && await chrome.windows.update(t, { state: "normal" }), await chrome.windows.get(t);
  } catch {
    return null;
  }
}
async function It() {
  const t = e.collectorWindowId;
  if (!t) return null;
  if (e.splitWindowId && e.splitWindowId !== t)
    try {
      return await chrome.windows.get(e.splitWindowId), e.splitWindowId;
    } catch {
      e.splitWindowId = null, e.splitOriginalBounds = null, e.splitApplied = !1;
    }
  try {
    const r = await chrome.windows.getLastFocused();
    if (r.id && r.id !== t)
      return r.id;
  } catch {
  }
  try {
    const n = (await chrome.windows.getAll()).find((o) => o.id && o.id !== t);
    return (n == null ? void 0 : n.id) ?? null;
  } catch {
    return null;
  }
}
async function ie(t) {
  if (e.collectorConfig.windowMode !== "dedicated-window" || !e.collectorWindowId) return;
  const r = await It();
  if (!r || r === e.collectorWindowId || e.splitApplied && e.splitWindowId === r)
    return;
  const n = await Ce(r);
  if (!Ct(n)) return;
  (!e.splitOriginalBounds || e.splitWindowId !== r) && (e.splitOriginalBounds = {
    left: n.left,
    top: n.top,
    width: n.width,
    height: n.height,
    state: n.state ?? "normal"
  }, e.splitWindowId = r);
  const o = await Ce(e.collectorWindowId);
  if (!(o != null && o.id)) return;
  const a = e.splitOriginalBounds.width, l = e.splitOriginalBounds.height, c = e.splitOriginalBounds.left, w = e.splitOriginalBounds.top, h = Math.max(Math.floor(a * 3 / 4), 720), A = Math.max(a - h, 320), M = a - A;
  if (await chrome.windows.update(r, {
    state: "normal",
    left: c,
    top: w,
    width: M,
    height: l,
    focused: !1
  }), await chrome.windows.update(e.collectorWindowId, {
    state: "normal",
    left: c + M,
    top: w,
    width: A,
    height: l,
    focused: e.collectorConfig.focusPolicy === "per-task"
  }), e.splitApplied = !0, m(
    "apply 3:1 split reason=%s leftWindow=%s collectorWindow=%s leftWidth=%d rightWidth=%d",
    t,
    String(r),
    String(e.collectorWindowId),
    M,
    A
  ), e.collectorConfig.focusPolicy === "never")
    try {
      await chrome.windows.update(r, { focused: !0 });
    } catch {
    }
}
async function qe(t) {
  if (!e.splitApplied || !e.splitWindowId || !e.splitOriginalBounds) return;
  const r = e.splitWindowId, n = e.splitOriginalBounds;
  try {
    await chrome.windows.update(r, {
      state: "normal",
      left: n.left,
      top: n.top,
      width: n.width,
      height: n.height,
      focused: !0
    }), n.state && n.state !== "normal" && await chrome.windows.update(r, { state: n.state }), m("restore split layout reason=%s window=%s", t, String(r));
  } catch {
  }
  e.splitApplied = !1, e.splitWindowId = null, e.splitOriginalBounds = null;
}
async function vt(t, r) {
  const n = {
    url: t,
    focused: r,
    type: "normal",
    width: Te,
    height: rt
  };
  try {
    const o = await chrome.windows.getLastFocused();
    typeof o.left == "number" && typeof o.top == "number" && typeof o.width == "number" && typeof o.height == "number" && (n.left = Math.max(o.left + o.width - Te - ye, 0), n.top = Math.max(o.top + ye, 0));
  } catch {
  }
  return n;
}
async function me(t, r) {
  if (e.collectorConfig.windowMode === "dedicated-window" && e.collectorWindowId)
    try {
      (await chrome.windows.get(e.collectorWindowId)).state === "minimized" ? (await chrome.windows.update(e.collectorWindowId, {
        state: "normal",
        focused: r
      }), m("window minimized -> restored reason=%s focus=%s", t, String(r))) : r && (await chrome.windows.update(e.collectorWindowId, { focused: !0 }), m("window focused reason=%s", t));
    } catch {
    }
}
async function St() {
  if (e.collectorConfig.focusPolicy === "per-task") {
    if (await me("per-task focus", !0), e.collectorTabId)
      try {
        await chrome.tabs.update(e.collectorTabId, { active: !0 });
      } catch {
      }
    m("focus policy per-task, focused collector window/tab");
  }
}
async function Re(t, r) {
  $.add(t);
  try {
    await chrome.tabs.remove(t);
  } catch {
    $.delete(t);
  }
  m("close tab %d, reason=%s", t, r);
}
async function Et(t) {
  const r = e.collectorTabId;
  r && (await Re(r, t), e.collectorTabId = null);
}
async function Wt(t) {
  const r = e.collectorWindowId;
  if (r) {
    try {
      const n = await chrome.tabs.query({ windowId: r });
      for (const o of n)
        o.id && $.add(o.id);
    } catch {
    }
    X.add(r);
    try {
      await chrome.windows.remove(r);
    } catch {
      X.delete(r);
    }
    m("close window %d, reason=%s", r, t), e.collectorWindowId = null, e.collectorTabId = null;
  }
}
async function J(t) {
  e.collectorConfig.windowMode === "dedicated-window" ? await Wt(t) : await Et(t), e.collectorWindowId = null, e.collectorTabId = null, e.collectorNavigateCount = 0;
}
async function Mt() {
  const t = await xt();
  if (!(t != null && t.id))
    return e.collectorTabId = null, e.collectorWindowId = null, !1;
  if (e.collectorTabId = t.id, e.collectorWindowId = t.windowId ?? e.collectorWindowId, e.collectorConfig.windowMode === "dedicated-window") {
    const r = await Ne();
    if (!(r != null && r.id))
      return e.collectorWindowId = null, e.collectorTabId = null, !1;
  }
  return !0;
}
async function Ie(t, r) {
  var a, l;
  const n = e.collectorConfig.focusPolicy === "never" ? !1 : e.collectorConfig.windowMode === "current-window" ? !0 : kt();
  let o = null;
  if (!n)
    try {
      o = (await chrome.windows.getLastFocused()).id ?? null;
    } catch {
    }
  if (e.collectorConfig.windowMode === "dedicated-window") {
    const c = await Ne();
    if (c != null && c.id) {
      await me("create tab in dedicated window", n);
      const w = await chrome.tabs.create({
        windowId: c.id,
        url: t,
        active: n
      });
      if (e.collectorWindowId = w.windowId ?? c.id, e.collectorTabId = w.id ?? null, n)
        try {
          await chrome.windows.update(e.collectorWindowId, { focused: !0 });
        } catch {
        }
      m(
        "create tab in dedicated window window=%s tab=%s reason=%s focus=%s",
        String(e.collectorWindowId),
        String(e.collectorTabId),
        r,
        String(n)
      ), await ie("reuse dedicated collector window");
    } else {
      const w = await vt(t, n), h = await chrome.windows.create(w), A = ((a = h.tabs) == null ? void 0 : a[0]) ?? null;
      if (e.collectorWindowId = h.id ?? (A == null ? void 0 : A.windowId) ?? null, e.collectorTabId = (A == null ? void 0 : A.id) ?? null, !e.collectorTabId) {
        const M = e.collectorWindowId ? await chrome.tabs.query({ windowId: e.collectorWindowId, active: !0 }) : [];
        e.collectorTabId = ((l = M[0]) == null ? void 0 : l.id) ?? null;
      }
      m(
        "create dedicated normal window %s tab=%s reason=%s focus=%s",
        String(e.collectorWindowId),
        String(e.collectorTabId),
        r,
        String(n)
      ), await ie("collector window created");
    }
  } else {
    const c = { url: t, active: n };
    try {
      const h = await chrome.windows.getLastFocused();
      h.id && (c.windowId = h.id);
    } catch {
    }
    if (e.collectorWindowId)
      try {
        await chrome.windows.get(e.collectorWindowId), c.windowId || (c.windowId = e.collectorWindowId);
      } catch {
        e.collectorWindowId = null;
      }
    const w = await chrome.tabs.create(c);
    if (e.collectorTabId = w.id ?? null, e.collectorWindowId = w.windowId ?? e.collectorWindowId, m(
      "create tab in current window window=%s tab=%s reason=%s focus=%s",
      String(e.collectorWindowId),
      String(e.collectorTabId),
      r,
      String(n)
    ), e.collectorWindowId && n)
      try {
        await chrome.windows.update(e.collectorWindowId, { focused: !0 });
      } catch {
      }
  }
  if (!e.collectorTabId)
    throw new Error("collector tab create failed");
  if (e.collectorNavigateCount += 1, !n && o && o !== e.collectorWindowId)
    try {
      await chrome.windows.update(o, { focused: !0 }), m("bounce focus back to window %d", o);
    } catch {
    }
}
async function Ot(t) {
  if (!e.collectorTabId) throw new Error("collector tab missing for reuse");
  await ie("navigate collector tab");
  const r = e.collectorConfig.focusPolicy !== "never" && (e.collectorConfig.windowMode === "current-window" || e.collectorConfig.focusPolicy === "per-task");
  await me("navigate collector tab", r), e.collectorConfig.focusPolicy === "per-task" && await St();
  const n = r, o = await chrome.tabs.update(e.collectorTabId, {
    url: t,
    active: n
  });
  if (e.collectorTabId = (o == null ? void 0 : o.id) ?? e.collectorTabId, e.collectorWindowId = (o == null ? void 0 : o.windowId) ?? e.collectorWindowId, e.collectorNavigateCount += 1, r && e.collectorWindowId)
    try {
      await chrome.windows.update(e.collectorWindowId, { focused: !0 });
    } catch {
    }
  m(
    "reuse tab navigate window=%s tab=%s focus=%s url=%s",
    String(e.collectorWindowId),
    String(e.collectorTabId),
    String(n),
    t
  );
}
async function _t() {
}
async function fe(t, r, n = !1) {
  if (n && (m("force recreate collector due to %s", r), await J(`force recreate: ${r}`)), await _t(), e.collectorConfig.reuseTab) {
    if (!await Mt()) {
      if (!e.collectorConfig.recreateOnFailure && e.collectorNavigateCount > 0)
        throw new Error("collector missing and recreateOnFailure is false");
      await Ie(t.url, `${r} (reuse create)`);
      return;
    }
    await Ot(t.url);
    return;
  }
  const o = e.collectorTabId;
  await Ie(t.url, `${r} (new tab)`), o && o !== e.collectorTabId && await Re(o, `${r} (reuseTab=false rotate tab)`);
}
async function $e(t) {
  if (e.currentTask && !(e.state !== "running" && e.state !== "recovering") && !oe) {
    if (!e.collectorConfig.recreateOnFailure) {
      m("collector lost (%s), recreateOnFailure=false", t), await F(`collector lost: ${t}`);
      return;
    }
    oe = !0, m("collector lost (%s), recreating for current task %s", t, e.currentTask.id);
    try {
      await fe(e.currentTask, `collector loss: ${t}`, !0), e.lastTaskStartedAt = C(), ge(), await f(), await p();
    } catch (r) {
      await F(`collector recreate failed: ${U(r)}`);
    } finally {
      oe = !1;
    }
  }
}
async function Pt() {
  const t = e.currentTask;
  if (!t) return;
  T && clearTimeout(T), k && clearTimeout(k), T = null, k = null, e.consecutivePageDataTimeouts += 1;
  const r = e.consecutivePageDataTimeouts;
  if (e.lastError = `page data timeout x${r}`, r < be) {
    await S("error", {
      code: "PAGE_DATA_TIMEOUT_RETRY",
      message: `page data timeout detected (${r}/${be}). Auto reopening collector window.`
    });
    try {
      await J(`page data timeout retry ${r}`), await fe(t, `page data timeout retry ${r}`, !0), e.lastTaskStartedAt = C(), await f(), await p(), ge();
      return;
    } catch (n) {
      e.lastError = `page data timeout reopen failed: ${U(n)}`;
    }
  }
  e.queue.unshift(t), e.currentTask = null, e.currentData = [], await S("error", {
    code: "PAGE_DATA_TIMEOUT_BLOCKED",
    message: "Repeated page data timeout. Possible network issue or collector window was blocked. Resume after fixing network/window visibility."
  }), await Z({
    byBridgeLoss: !1,
    reason: "Repeated page data timeout. Possible network issue or collector window blocked. Click Start after recovery to continue unfinished tasks."
  });
}
function Lt() {
  e.state = "idle", e.currentTask = null, e.currentData = [], e.queue = [], e.totalTasks = 0, e.completedCount = 0, e.failedCount = 0, e.runId = null, e.token = "", e.lastTaskStartedAt = 0, e.pausedByBridgeLoss = !1, e.consecutivePageDataTimeouts = 0;
}
async function Z(t) {
  e.currentTask && (e.queue.unshift(e.currentTask), e.currentTask = null, e.currentData = []), ue(), e.pausedByBridgeLoss = (t == null ? void 0 : t.byBridgeLoss) ?? !1, t != null && t.reason && (e.lastError = t.reason), e.state = "paused", await f(), await p();
}
async function R(t) {
  const r = (t == null ? void 0 : t.allowIdleQueue) ?? !1;
  if (e.state === "paused" || e.state === "batch-pause" || e.state === "recovering") {
    e.pausedByBridgeLoss = !1, e.state = "running", await f(), await p(), _(200);
    return;
  }
  r && e.state === "idle" && (e.queue.length > 0 || e.currentTask) && (e.currentTask && (e.queue.unshift(e.currentTask), e.currentTask = null, e.currentData = []), e.pausedByBridgeLoss = !1, e.state = "running", await f(), await p(), _(200));
}
async function se(t) {
  const r = (t == null ? void 0 : t.forceCloseCollector) ?? !1, n = (t == null ? void 0 : t.clearOutbox) ?? !1;
  ue(), H(), e.pausedByBridgeLoss = !1, r || !e.collectorConfig.keepOpen ? await J(r ? "force stop" : "stop-run keepOpen=false") : m(
    "stop-run keepOpen=true, keep collector window=%s tab=%s",
    String(e.collectorWindowId),
    String(e.collectorTabId)
  ), await qe(r ? "force stop" : "stop-run"), Lt(), n && (e.outbox = [], e.seq = 0, e.ackSeq = 0), await f(), await p();
}
async function Fe() {
  e.outbox = [], e.currentData = [], e.seq = 0, e.ackSeq = 0, await f(), await p();
}
async function Bt() {
  const t = e.currentTask;
  if (!t) return;
  if (T && clearTimeout(T), k && clearTimeout(k), T = null, k = null, e.completedCount += 1, e.consecutivePageDataTimeouts = 0, e.lastError = null, await S("task-complete", {
    runId: e.runId ?? "",
    taskId: t.id,
    data: e.currentData
  }), e.currentTask = null, e.currentData = [], !e.queue.length) {
    e.state = "paused", await f(), await p();
    return;
  }
  await f(), await p();
  const r = e.config.queryInterval + Math.floor(Math.random() * e.config.randomDelay);
  _(r);
}
async function F(t) {
  const r = e.currentTask;
  if (r) {
    if (T && clearTimeout(T), k && clearTimeout(k), T = null, k = null, e.failedCount += 1, e.consecutivePageDataTimeouts = 0, await S("task-failed", {
      runId: e.runId ?? "",
      taskId: r.id,
      error: t
    }), e.currentTask = null, e.currentData = [], !e.queue.length) {
      e.state = "paused", await p(), await f();
      return;
    }
    await p(), await f(), _(3e3);
  }
}
async function Dt(t) {
  e.bridgeConnected || e.pausedByBridgeLoss && e.state === "paused" && (await J(`bridge disconnect timeout: ${t}`), await f(), await p());
}
function Nt(t) {
  H(), K = setTimeout(() => {
    Dt(t);
  }, tt);
}
async function Ue(t) {
  e.state !== "running" && e.state !== "recovering" && e.state !== "batch-pause" || (await Z({
    byBridgeLoss: !0,
    reason: `bridge disconnected: ${t}`
  }), Nt(t));
}
async function He() {
  if (!(e.state !== "running" && e.state !== "recovering")) {
    if (!e.queue.length) {
      e.state = "paused", await f(), await p();
      return;
    }
    if (e.completedCount > 0 && e.config.batchPause > 0 && e.completedCount % e.config.batchPause === 0) {
      e.state = "batch-pause", await p(), E && clearTimeout(E), E = setTimeout(() => {
        e.state = "running", f(), p(), He();
      }, e.config.batchPauseTime);
      return;
    }
    if (e.state = "running", e.currentTask = e.queue.shift() ?? null, e.currentData = [], !e.currentTask) {
      _(1e3);
      return;
    }
    try {
      await fe(e.currentTask, "execute task"), e.lastTaskStartedAt = C(), ge();
    } catch (t) {
      await F(`open collector failed: ${U(t)}`);
      return;
    }
    await f(), await p();
  }
}
function qt(t) {
  return t === "trends-relatedsearches" || t === "trends-multiline" || t === "trends-lifecycle";
}
chrome.runtime.onMessage.addListener((t) => {
  if (!B(t) || !qt(t.type)) return;
  const r = B(t.payload) ? t.payload : {};
  if (t.type === "trends-lifecycle") {
    if (e.state !== "running" && e.state !== "recovering" && e.state !== "batch-pause") return;
    m(
      "lifecycle event=%s visibility=%s hidden=%s focus=%s href=%s extra=%s",
      String(r.event ?? "unknown"),
      String(r.visibilityState ?? "unknown"),
      String(r.hidden ?? "unknown"),
      String(r.hasFocus ?? "unknown"),
      String(r.href ?? "unknown"),
      String(r.extra ?? "")
    );
    return;
  }
  if (!e.currentTask) return;
  const o = {
    type: t.type === "trends-relatedsearches" ? "relatedsearches" : "multiline",
    url: typeof r.url == "string" ? r.url : "",
    status: Number(r.status ?? 0),
    body: Tt(r.body),
    timestamp: C()
  };
  bt(o.url) && (e.currentData.push(o), T && clearTimeout(T), T = setTimeout(() => {
    Bt();
  }, Qe), f());
});
chrome.runtime.onMessage.addListener((t, r, n) => !lt(t) || r.id && r.id !== chrome.runtime.id ? void 0 : (W("popup control action=%s", t.action), (async () => {
  switch (t.action) {
    case "start-or-resume":
      await R({ allowIdleQueue: !0 });
      break;
    case "pause":
      await Z();
      break;
    case "stop":
      await se({ forceCloseCollector: !0 });
      break;
    case "clear-tasks":
      await se({ forceCloseCollector: !0, clearOutbox: !0 });
      break;
    case "clear-cache":
      await Fe();
      break;
    case "set-window-mode": {
      if (!t.mode)
        throw new Error("set-window-mode requires mode");
      if (e.state === "running" || e.state === "recovering" || e.state === "batch-pause")
        throw new Error("cannot change window mode while run is active");
      e.popupCollectorWindowModeOverride = t.mode, e.collectorConfig = ce({
        ...e.collectorConfig,
        windowMode: t.mode
      }), await qe("popup set-window-mode"), e.collectorWindowId = null, e.collectorTabId = null, e.collectorNavigateCount = 0, m("popup set window mode override=%s", t.mode), await f(), await p();
      break;
    }
    default:
      throw new Error(`unsupported popup action: ${String(t.action)}`);
  }
})().then(() => n({ ok: !0 })).catch((a) => n({ ok: !1, error: U(a) })), !0));
chrome.tabs.onRemoved.addListener((t, r) => {
  if ($.has(t)) {
    $.delete(t);
    return;
  }
  e.collectorTabId === t && (e.collectorTabId = null, r.isWindowClosing && (e.collectorWindowId = null), m("collector tab removed unexpectedly, tab=%d", t), f(), $e("tab removed"));
});
chrome.windows.onRemoved.addListener((t) => {
  if (e.splitWindowId === t && (e.splitWindowId = null, e.splitOriginalBounds = null, e.splitApplied = !1, m("split primary window removed, clear split state window=%d", t), f()), X.has(t)) {
    X.delete(t);
    return;
  }
  e.collectorWindowId === t && (e.collectorWindowId = null, e.collectorTabId = null, m("collector window removed unexpectedly, window=%d", t), f(), $e("window removed"));
});
chrome.windows.onBoundsChanged.addListener((t) => {
  if (!t.id || e.collectorConfig.windowMode !== "dedicated-window" || e.collectorWindowId !== t.id || t.state !== "minimized" || e.state !== "running" && e.state !== "recovering") return;
  const r = e.collectorConfig.focusPolicy === "per-task";
  m("collector window minimized during run, auto-restore focus=%s", String(r)), chrome.windows.update(t.id, {
    state: "normal",
    focused: r
  }).catch(() => {
  });
});
async function je(t) {
  var o;
  const r = t.type;
  if (de(), W("command received type=%s runId=%s seq=%s", r, t.runId, String(t.seq)), r === "ack") {
    const a = t.payload, l = Number((a == null ? void 0 : a.ackSeq) ?? -1);
    Number.isFinite(l) && l >= 0 && yt(l);
    return;
  }
  if (r === "ping") {
    e.pausedByBridgeLoss && e.state === "paused" && e.queue.length > 0 && await R(), await S("pong", { version: chrome.runtime.getManifest().version });
    return;
  }
  const n = await wt(t.token, t.runId);
  if (!n.ok) {
    W("command rejected type=%s reason=%s", r, n.reason ?? "token_invalid"), await S("need-reauth", { reason: n.reason ?? "token_invalid" });
    return;
  }
  if (r !== "start-run" && e.runId && t.runId !== e.runId) {
    W("command rejected type=%s reason=run_mismatch expected=%s got=%s", r, e.runId, t.runId), await S("error", {
      code: "RUN_MISMATCH",
      message: `Expected runId ${e.runId}, got ${t.runId}`
    });
    return;
  }
  switch (r !== "start-run" && e.runId && t.runId === e.runId && t.token && t.token !== e.token && (e.token = t.token), r) {
    case "start-run": {
      const a = t.payload;
      if (!a || !Array.isArray(a.tasks) || a.tasks.length === 0) {
        await S("error", {
          code: "INVALID_START_PAYLOAD",
          message: "start-run requires non-empty tasks array"
        });
        return;
      }
      const l = ce(At(a.config));
      if (e.runId === t.runId && e.state !== "idle") {
        const w = new Set(e.queue.map((A) => A.id));
        (o = e.currentTask) != null && o.id && w.add(e.currentTask.id);
        const h = a.tasks.filter((A) => !w.has(A.id));
        if (e.token = t.token, e.config = xe(a.config), e.collectorConfig = l, e.collectorConfig.refreshAfterTasks = 0, e.queue.push(...h), e.totalTasks += h.length, e.lastError = null, e.state === "paused" && e.pausedByBridgeLoss && e.queue.length > 0) {
          H(), await R();
          break;
        }
        e.state !== "running" && e.state !== "recovering" && e.state !== "batch-pause" && (e.state = "running"), !e.currentTask && !E && _(200), await f(), await p();
        break;
      }
      ue(), e.collectorConfig.windowMode !== l.windowMode && (m(
        "collector mode changed %s -> %s, reset tracked target ids",
        e.collectorConfig.windowMode,
        l.windowMode
      ), e.collectorWindowId = null, e.collectorTabId = null), e.runId = t.runId, e.token = t.token, e.queue = [...a.tasks], e.totalTasks = a.tasks.length, e.completedCount = 0, e.failedCount = 0, e.currentTask = null, e.currentData = [], e.config = xe(a.config), e.collectorConfig = l, e.collectorConfig.refreshAfterTasks = 0, e.collectorNavigateCount = 0, e.state = "running", e.pausedByBridgeLoss = !1, e.seq = 0, e.ackSeq = 0, e.outbox = [], e.lastTaskStartedAt = 0, e.lastError = null, m("start run collector config", e.collectorConfig), await f(), await p(), _(200);
      break;
    }
    case "pause-run": {
      await Z({ byBridgeLoss: !1 });
      break;
    }
    case "resume-run": {
      await R();
      break;
    }
    case "stop-run": {
      await se();
      break;
    }
    case "get-status": {
      await p();
      break;
    }
    case "request-replay": {
      const a = t.payload, l = Number((a == null ? void 0 : a.fromSeq) ?? e.ackSeq + 1);
      Be(Number.isNaN(l) ? e.ackSeq + 1 : l);
      break;
    }
    case "clear-local-cache": {
      await Fe();
      break;
    }
    default:
      await S("error", {
        code: "UNKNOWN_COMMAND",
        message: `Unsupported command: ${String(r)}`
      });
  }
}
chrome.runtime.onConnectExternal.addListener((t) => {
  if (t.name && t.name !== Je && W("external connect with unexpected port name=%s, still accepted", t.name), W("external connect name=%s sender=%s", t.name || "(empty)", q(t.sender)), !Oe(t.sender)) {
    W("external connect rejected sender=%s", q(t.sender)), t.disconnect();
    return;
  }
  V = t, de(), H(), t.onMessage.addListener((r) => {
    if (!B(r)) return;
    if (r.type === "ping" && r.v !== 1) {
      W("legacy ping received via port"), S("pong", { version: chrome.runtime.getManifest().version });
      return;
    }
    const n = We(r) ? r : Me(r);
    if (!n) {
      W("invalid envelope from port sender=%s", q(t.sender)), S("error", {
        code: "INVALID_ENVELOPE",
        message: "Message must include at least type + payload object"
      });
      return;
    }
    je(n);
  }), t.onDisconnect.addListener(() => {
    V = null, De("web bridge port disconnected"), Ue("port disconnected");
  }), p(), Be(e.ackSeq + 1), e.pausedByBridgeLoss && e.state === "paused" && e.queue.length > 0 && R();
});
chrome.runtime.onMessageExternal.addListener((t, r, n) => {
  if (W("external message sender=%s", q(r)), !Oe(r)) {
    W("external message rejected sender=%s", q(r)), n({ ok: !1, error: "SENDER_NOT_ALLOWED" });
    return;
  }
  if (de(), B(t) && t.type === "ping" && t.v !== 1) {
    n({ ok: !0, type: "pong", version: chrome.runtime.getManifest().version });
    return;
  }
  const o = We(t) ? t : Me(t);
  if (!o) {
    n({ ok: !1, error: "INVALID_ENVELOPE" });
    return;
  }
  return je(o).then(() => {
    n({ ok: !0 });
  }).catch((a) => {
    n({ ok: !1, error: U(a) });
  }), !0;
});
chrome.alarms.create(ve, { periodInMinutes: 0.4 });
chrome.alarms.onAlarm.addListener((t) => {
  t.name === ve && (e.state === "running" && e.currentTask && e.lastTaskStartedAt > 0 && C() - e.lastTaskStartedAt > e.config.taskHardTimeoutMs + 5e3 && F("keepalive timeout recovery"), e.state === "recovering" && !E && _(1e3));
});
function Rt() {
  ne && clearInterval(ne), ne = setInterval(() => {
    e.state !== "running" && e.state !== "recovering" && e.state !== "batch-pause" || !e.bridgeConnected || !e.bridgeLastSeenAt || C() - e.bridgeLastSeenAt <= et || (De("web heartbeat timeout"), Ue("heartbeat timeout"));
  }, 3e3);
}
ht().then(() => {
  e.state === "recovering" && _(1e3), Rt();
});
console.log("[TrendsExtension] background runner loaded");
