const K = "https://decordinated.github.io/moodlabs-ext-downloads/matching", le = `${K}/latest.json`, ge = `${K}/versions.json`, q = "moodlabs-matching-data-check", me = 360;
var k;
(function(e) {
  e.Local = "local", e.Sync = "sync", e.Managed = "managed", e.Session = "session";
})(k || (k = {}));
var G;
(function(e) {
  e.ExtensionPagesOnly = "TRUSTED_CONTEXTS", e.ExtensionPagesAndContentScripts = "TRUSTED_AND_UNTRUSTED_CONTEXTS";
})(G || (G = {}));
const h = globalThis.chrome, Q = async (e, r) => {
  const s = (t) => typeof t == "function", i = (t) => (
    // Use ReturnType to infer the return type of the function and check if it's a Promise
    t instanceof Promise
  );
  return s(e) ? (i(e), e(r)) : e;
};
let Y = !1;
const ee = (e) => {
  if (h && !h.storage[e])
    throw new Error(`"storage" permission in manifest.ts: "storage ${e}" isn't defined`);
}, Z = (e, r, s) => {
  var U, I;
  let i = null, t = !1, l = [];
  const c = (s == null ? void 0 : s.storageEnum) ?? k.Local, v = (s == null ? void 0 : s.liveUpdate) ?? !1, E = ((U = s == null ? void 0 : s.serialization) == null ? void 0 : U.serialize) ?? ((A) => A), y = ((I = s == null ? void 0 : s.serialization) == null ? void 0 : I.deserialize) ?? ((A) => A);
  Y === !1 && c === k.Session && (s == null ? void 0 : s.sessionAccessForContentScripts) === !0 && (ee(c), h == null || h.storage[c].setAccessLevel({
    accessLevel: G.ExtensionPagesAndContentScripts
  }).catch((A) => {
    console.error(A), console.error("Please call .setAccessLevel() into different context, like a background script.");
  }), Y = !0);
  const p = async () => {
    ee(c);
    const A = await (h == null ? void 0 : h.storage[c].get([e]));
    return A ? y(A[e]) ?? r : r;
  }, j = async (A) => {
    t || (i = await p()), i = await Q(A, i), await (h == null ? void 0 : h.storage[c].set({ [e]: E(i) })), S();
  }, F = (A) => (l = [...l, A], () => {
    l = l.filter((C) => C !== A);
  }), P = () => i, S = () => {
    l.forEach((A) => A());
  }, _ = async (A) => {
    if (A[e] === void 0)
      return;
    const C = y(A[e].newValue);
    i !== C && (i = await Q(C, i), S());
  };
  return p().then((A) => {
    i = A, t = !0, S();
  }), v && (h == null || h.storage[c].onChanged.addListener(_)), {
    get: p,
    set: j,
    getSnapshot: P,
    subscribe: F
  };
}, te = {
  version: null,
  appliedAt: null,
  data: null
}, H = Z("moodlabs-matching-applied", te, {
  storageEnum: k.Local,
  liveUpdate: !0
}), J = {
  ...H,
  apply: async (e) => {
    await H.set({
      version: e.matchingVersion,
      appliedAt: (/* @__PURE__ */ new Date()).toISOString(),
      data: e
    });
  },
  reset: async () => {
    await H.set(te);
  }
}, ne = {
  count: 0,
  lastIncrementAt: null,
  triggeredForVersion: null
}, O = Z("moodlabs-matching-failure-counter", ne, {
  storageEnum: k.Local,
  liveUpdate: !0
}), N = {
  ...O,
  increment: async () => {
    let e = 0;
    return await O.set((r) => (e = r.count + 1, {
      ...r,
      count: e,
      lastIncrementAt: (/* @__PURE__ */ new Date()).toISOString()
    })), e;
  },
  reset: async () => {
    await O.set(ne);
  },
  markTriggered: async (e) => {
    await O.set((r) => ({
      ...r,
      triggeredForVersion: e
    }));
  }
}, ce = {
  latest: null,
  versions: [],
  versionsFetchedAt: null,
  lastCheckedAt: null,
  lastCheckError: null,
  pendingPrompt: null,
  promptVersion: null,
  dismissedVersions: []
}, L = Z("moodlabs-matching-update-status", ce, {
  storageEnum: k.Local,
  liveUpdate: !0
}), T = {
  ...L,
  recordCheckSuccess: async (e) => {
    await L.set((r) => ({
      ...r,
      latest: e.latest,
      versions: e.versions ?? r.versions,
      versionsFetchedAt: e.versions ? (/* @__PURE__ */ new Date()).toISOString() : r.versionsFetchedAt,
      lastCheckedAt: (/* @__PURE__ */ new Date()).toISOString(),
      lastCheckError: null
    }));
  },
  recordCheckError: async (e) => {
    await L.set((r) => ({
      ...r,
      lastCheckedAt: (/* @__PURE__ */ new Date()).toISOString(),
      lastCheckError: e
    }));
  },
  setPendingPrompt: async (e, r) => {
    await L.set((s) => ({
      ...s,
      pendingPrompt: e,
      promptVersion: r
    }));
  },
  dismissVersion: async (e) => {
    await L.set((r) => ({
      ...r,
      pendingPrompt: null,
      promptVersion: null,
      dismissedVersions: r.dismissedVersions.includes(e) ? r.dismissedVersions : [...r.dismissedVersions, e]
    }));
  },
  clearDismissals: async () => {
    await L.set((e) => ({ ...e, dismissedVersions: [] }));
  }
}, z = async (e) => {
  const r = await fetch(e, { cache: "no-store" });
  if (!r.ok)
    throw new Error(`${e} 요청 실패 (${r.status})`);
  return await r.json();
}, Ae = (e, r) => {
  const s = e.split(".").map(Number), i = r.split(".").map(Number), t = Math.max(s.length, i.length);
  for (let l = 0; l < t; l += 1) {
    const c = (s[l] ?? 0) - (i[l] ?? 0);
    if (c !== 0) return c;
  }
  return 0;
}, de = (e, r) => r ? Ae(e, r) > 0 : !0, R = async (e) => {
  try {
    const [r, s] = await Promise.all([
      z(le),
      z(ge).catch(() => null)
    ]), i = (s == null ? void 0 : s.versions) ?? (r ? [r] : []);
    await T.recordCheckSuccess({ latest: r, versions: i });
    const t = await J.get(), l = de(r.version, t.version);
    return l && (e != null && e.promptKind) && ((await T.get()).dismissedVersions.includes(r.version) || await T.setPendingPrompt(e.promptKind, r.version)), { latest: r, versions: i, hasUpdate: l, appliedVersion: t.version };
  } catch (r) {
    const s = r instanceof Error ? r.message : "매칭 업데이트 확인 실패";
    throw await T.recordCheckError(s), r;
  }
}, ue = async (e) => {
  const r = await T.get(), s = r.versions.find((t) => t.version === e) ?? (r.latest && r.latest.version === e ? r.latest : null), i = (s == null ? void 0 : s.downloadUrl) ?? `${K}/moodlabs-matching-v${e}.json`;
  return await z(i);
}, he = async (e) => {
  const r = await ue(e);
  if (r.matchingVersion !== e)
    throw new Error(
      `다운로드한 매칭 데이터의 버전이 일치하지 않습니다: 요청=${e} 응답=${r.matchingVersion}`
    );
  return await J.apply(r), await N.reset(), await T.setPendingPrompt(null, null), r;
}, xe = async () => {
  await J.reset(), await N.reset(), await T.setPendingPrompt(null, null);
}, pe = async () => {
  if (!(await N.increment() < 2))
    try {
      const s = await R({ promptKind: "failure-threshold" });
      s.hasUpdate && s.latest ? await N.markTriggered(s.latest.version) : await N.reset();
    } catch {
    }
};
var V = { exports: {} }, fe = V.exports, re;
function we() {
  return re || (re = 1, (function(e, r) {
    (function(s, i) {
      i(e);
    })(typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : fe, function(s) {
      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)
        s.exports = globalThis.browser;
      else {
        const i = "The message port closed before a response was received.", t = (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 v extends WeakMap {
            constructor(a, g = void 0) {
              super(g), this.createItem = a;
            }
            get(a) {
              return this.has(a) || this.set(a, this.createItem(a)), super.get(a);
            }
          }
          const E = (n) => n && typeof n == "object" && typeof n.then == "function", y = (n, a) => (...g) => {
            l.runtime.lastError ? n.reject(new Error(l.runtime.lastError.message)) : a.singleCallbackArg || g.length <= 1 && a.singleCallbackArg !== !1 ? n.resolve(g[0]) : n.resolve(g);
          }, p = (n) => n == 1 ? "argument" : "arguments", j = (n, a) => function(m, ...u) {
            if (u.length < a.minArgs)
              throw new Error(`Expected at least ${a.minArgs} ${p(a.minArgs)} for ${n}(), got ${u.length}`);
            if (u.length > a.maxArgs)
              throw new Error(`Expected at most ${a.maxArgs} ${p(a.maxArgs)} for ${n}(), got ${u.length}`);
            return new Promise((x, f) => {
              if (a.fallbackToNoCallback)
                try {
                  m[n](...u, y({
                    resolve: x,
                    reject: f
                  }, a));
                } catch (o) {
                  console.warn(`${n} API method doesn't seem to support the callback parameter, falling back to call it without a callback: `, o), m[n](...u), a.fallbackToNoCallback = !1, a.noCallback = !0, x();
                }
              else a.noCallback ? (m[n](...u), x()) : m[n](...u, y({
                resolve: x,
                reject: f
              }, a));
            });
          }, F = (n, a, g) => new Proxy(a, {
            apply(m, u, x) {
              return g.call(u, n, ...x);
            }
          });
          let P = Function.call.bind(Object.prototype.hasOwnProperty);
          const S = (n, a = {}, g = {}) => {
            let m = /* @__PURE__ */ Object.create(null), u = {
              has(f, o) {
                return o in n || o in m;
              },
              get(f, o, w) {
                if (o in m)
                  return m[o];
                if (!(o in n))
                  return;
                let d = n[o];
                if (typeof d == "function")
                  if (typeof a[o] == "function")
                    d = F(n, n[o], a[o]);
                  else if (P(g, o)) {
                    let M = j(o, g[o]);
                    d = F(n, n[o], M);
                  } else
                    d = d.bind(n);
                else if (typeof d == "object" && d !== null && (P(a, o) || P(g, o)))
                  d = S(d, a[o], g[o]);
                else if (P(g, "*"))
                  d = S(d, a[o], g["*"]);
                else
                  return Object.defineProperty(m, o, {
                    configurable: !0,
                    enumerable: !0,
                    get() {
                      return n[o];
                    },
                    set(M) {
                      n[o] = M;
                    }
                  }), d;
                return m[o] = d, d;
              },
              set(f, o, w, d) {
                return o in m ? m[o] = w : n[o] = w, !0;
              },
              defineProperty(f, o, w) {
                return Reflect.defineProperty(m, o, w);
              },
              deleteProperty(f, o) {
                return Reflect.deleteProperty(m, o);
              }
            }, x = Object.create(n);
            return new Proxy(x, u);
          }, _ = (n) => ({
            addListener(a, g, ...m) {
              a.addListener(n.get(g), ...m);
            },
            hasListener(a, g) {
              return a.hasListener(n.get(g));
            },
            removeListener(a, g) {
              a.removeListener(n.get(g));
            }
          }), U = new v((n) => typeof n != "function" ? n : function(g) {
            const m = S(g, {}, {
              getContent: {
                minArgs: 0,
                maxArgs: 0
              }
            });
            n(m);
          }), I = new v((n) => typeof n != "function" ? n : function(g, m, u) {
            let x = !1, f, o = new Promise((D) => {
              f = function(b) {
                x = !0, D(b);
              };
            }), w;
            try {
              w = n(g, m, f);
            } catch (D) {
              w = Promise.reject(D);
            }
            const d = w !== !0 && E(w);
            if (w !== !0 && !d && !x)
              return !1;
            const M = (D) => {
              D.then((b) => {
                u(b);
              }, (b) => {
                let W;
                b && (b instanceof Error || typeof b.message == "string") ? W = b.message : W = "An unexpected error occurred", u({
                  __mozWebExtensionPolyfillReject__: !0,
                  message: W
                });
              }).catch((b) => {
                console.error("Failed to send onMessage rejected reply", b);
              });
            };
            return M(d ? w : o), !0;
          }), A = ({
            reject: n,
            resolve: a
          }, g) => {
            l.runtime.lastError ? l.runtime.lastError.message === i ? a() : n(new Error(l.runtime.lastError.message)) : g && g.__mozWebExtensionPolyfillReject__ ? n(new Error(g.message)) : a(g);
          }, C = (n, a, g, ...m) => {
            if (m.length < a.minArgs)
              throw new Error(`Expected at least ${a.minArgs} ${p(a.minArgs)} for ${n}(), got ${m.length}`);
            if (m.length > a.maxArgs)
              throw new Error(`Expected at most ${a.maxArgs} ${p(a.maxArgs)} for ${n}(), got ${m.length}`);
            return new Promise((u, x) => {
              const f = A.bind(null, {
                resolve: u,
                reject: x
              });
              m.push(f), g.sendMessage(...m);
            });
          }, oe = {
            devtools: {
              network: {
                onRequestFinished: _(U)
              }
            },
            runtime: {
              onMessage: _(I),
              onMessageExternal: _(I),
              sendMessage: C.bind(null, "sendMessage", {
                minArgs: 1,
                maxArgs: 3
              })
            },
            tabs: {
              sendMessage: C.bind(null, "sendMessage", {
                minArgs: 2,
                maxArgs: 3
              })
            }
          }, B = {
            clear: {
              minArgs: 1,
              maxArgs: 1
            },
            get: {
              minArgs: 1,
              maxArgs: 1
            },
            set: {
              minArgs: 1,
              maxArgs: 1
            }
          };
          return c.privacy = {
            network: {
              "*": B
            },
            services: {
              "*": B
            },
            websites: {
              "*": B
            }
          }, S(l, oe, c);
        };
        s.exports = t(chrome);
      }
    });
  })(V)), V.exports;
}
we();
console.log("Background loaded");
const be = (e, r) => {
  if (!e || typeof e != "object")
    return null;
  const s = e, i = Array.isArray(s.alternativeSelectors) ? s.alternativeSelectors.filter(
    (l) => typeof l == "string" && l.trim().length > 0
  ) : [], t = s.confidence;
  return {
    bestSelector: typeof s.bestSelector == "string" && s.bestSelector.trim().length > 0 ? s.bestSelector : null,
    alternativeSelectors: i,
    reason: typeof s.reason == "string" ? s.reason : "",
    confidence: t === "low" || t === "medium" || t === "high" ? t : "unknown",
    targetStrategyId: typeof s.targetStrategyId == "string" ? s.targetStrategyId : void 0,
    failedStep: typeof s.failedStep == "string" ? s.failedStep : void 0,
    rawText: r
  };
}, ye = 12e3, $ = [], ae = (e) => {
  const r = $.indexOf(e);
  r >= 0 && $.splice(r, 1);
}, Se = (e) => [e.filename, e.finalUrl, e.url, e.referrer].filter(Boolean).join(" ").toLowerCase(), se = (e, r) => e.actionId === "download.single.wav" ? r.includes(".wav") || /\bwav\b/.test(r) : e.actionId === "download.single.mp3" ? r.includes(".mp3") || /\bmp3\b/.test(r) : !0, Te = (e) => {
  const r = Se(e), s = [...$].sort((t, l) => t.registeredAt - l.registeredAt), i = s.find(
    (t) => !!t.expectedUuid && r.includes(t.expectedUuid.toLowerCase()) && se(t, r)
  ) ?? s.find((t) => se(t, r)) ?? s.find((t) => !!t.actionId) ?? s[0];
  i && (ae(i), clearTimeout(i.timeoutId), i.sendResponse({
    data: {
      downloadId: e.id,
      filename: e.filename,
      url: e.finalUrl || e.url
    }
  }));
};
chrome.downloads.onCreated.addListener((e) => {
  Te(e);
});
const X = () => {
  chrome.alarms.get(q, (e) => {
    e || chrome.alarms.create(q, {
      periodInMinutes: me,
      delayInMinutes: 1
    });
  });
}, ie = () => {
  R({ promptKind: "startup" }).catch(() => {
  });
};
chrome.runtime.onInstalled.addListener(() => {
  X(), ie();
});
chrome.runtime.onStartup.addListener(() => {
  X(), ie();
});
X();
chrome.alarms.onAlarm.addListener((e) => {
  e.name === q && R().catch(() => {
  });
});
chrome.runtime.onMessage.addListener((e, r, s) => {
  var i;
  if (e.type === "requestSongs")
    return Ee(e).then((t) => s(t)).catch((t) => s({ error: t.message })), !0;
  if (e.type === "geminiRecover")
    return Me(e.payload.apiKey, e.payload.prompt).then((t) => s(t)).catch(
      (t) => s({
        data: null,
        error: t instanceof Error ? t.message : "Gemini 복구 요청에 실패했습니다."
      })
    ), !0;
  if (e.type === "awaitDownloadStart")
    return Pe(e, s), !0;
  if (e.type === "openOptionsPage") {
    const t = typeof ((i = e.payload) == null ? void 0 : i.hash) == "string" ? e.payload.hash : "", l = chrome.runtime.getURL(`options/index.html${t}`);
    return chrome.tabs.create({ url: l }).then((c) => s({ data: { tabId: c.id ?? -1 } })).catch(
      (c) => s({
        data: null,
        error: c instanceof Error ? c.message : "옵션 페이지를 열지 못했습니다."
      })
    ), !0;
  }
  return e.type === "matchingCheck" ? (ve().then((t) => s(t)).catch(
    (t) => s({
      data: null,
      error: t instanceof Error ? t.message : "매칭 업데이트 확인에 실패했습니다."
    })
  ), !0) : e.type === "matchingApply" ? (Ce(e).then((t) => s(t)).catch(
    (t) => s({
      data: null,
      error: t instanceof Error ? t.message : "매칭 데이터 적용에 실패했습니다."
    })
  ), !0) : e.type === "matchingReset" ? (xe().then(() => ({ data: { ok: !0 } })).catch((t) => ({
    data: null,
    error: t instanceof Error ? t.message : "매칭 데이터 초기화에 실패했습니다."
  })).then((t) => s(t)), !0) : e.type === "matchingDismissPrompt" ? (ke(e).then((t) => s(t)).catch(
    (t) => s({
      data: null,
      error: t instanceof Error ? t.message : "프롬프트 무시 처리에 실패했습니다."
    })
  ), !0) : (e.type === "matchingFailureSignal" && (pe(), s({ data: { ok: !0 } })), !1);
});
const ve = async () => {
  var r;
  const e = await R();
  return {
    data: {
      latestVersion: ((r = e.latest) == null ? void 0 : r.version) ?? null,
      appliedVersion: e.appliedVersion,
      hasUpdate: e.hasUpdate
    }
  };
}, Ce = async (e) => ({ data: { appliedVersion: (await he(e.payload.version)).matchingVersion } }), ke = async (e) => (await T.dismissVersion(e.payload.version), { data: { ok: !0 } }), Ee = async (e) => {
  var i;
  const r = new FormData();
  return (i = e.payload) != null && i.id && r.append("id", e.payload.id), await (await fetch("http://192.168.86.99:9001/api/song-sets/gen-songs", {
    method: "POST",
    body: r
  })).json();
}, Pe = (e, r) => {
  var t, l, c;
  const s = Math.max(1e3, ((t = e.payload) == null ? void 0 : t.timeoutMs) ?? ye), i = {
    sendResponse: r,
    expectedUuid: (l = e.payload) == null ? void 0 : l.uuid,
    actionId: (c = e.payload) == null ? void 0 : c.actionId,
    registeredAt: Date.now(),
    timeoutId: setTimeout(() => {
      ae(i), r({
        data: null,
        error: `다운로드 시작을 ${s}ms 안에 감지하지 못했습니다.`
      });
    }, s)
  };
  $.push(i);
}, Me = async (e, r) => {
  var c, v, E, y;
  const s = await fetch(
    `https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${e}`,
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        generationConfig: {
          responseMimeType: "application/json",
          temperature: 0.2
        },
        contents: [
          {
            role: "user",
            parts: [{ text: r }]
          }
        ]
      })
    }
  );
  if (!s.ok) {
    const p = await s.text();
    throw new Error(`Gemini 복구 요청 실패: ${s.status} ${p}`);
  }
  const t = ((y = (E = (v = (c = (await s.json()).candidates) == null ? void 0 : c[0]) == null ? void 0 : v.content) == null ? void 0 : E.parts) == null ? void 0 : y.map((p) => p.text ?? "").join(`
`).trim()) ?? "";
  let l = null;
  if (t)
    try {
      l = be(JSON.parse(t), t);
    } catch {
      l = null;
    }
  return {
    data: {
      text: t,
      suggestion: l
    }
  };
};
