UNPKG

@telegram-apps/sdk

Version:

TypeScript Source Development Kit for Telegram Mini Apps client application.

2,005 lines 57.1 kB
import { setDebug as un, invokeCustomMethod as ln, retrieveLaunchParams as Co, createPostEvent as pn, request as dn, postEvent as mn, supports as oe, isTMA as Jt, on as m, off as S, retrieveRawInitData as _n, captureSameReq as fn } from "@telegram-apps/bridge";
import { AbortablePromise as Ql, CancelledError as Kl, InvalidLaunchParamsError as Yl, InvokeCustomMethodError as Xl, LaunchParamsRetrieveError as Zl, ManualPromise as Jl, MethodParameterUnsupportedError as ep, MethodUnsupportedError as tp, TimeoutError as op, UnknownEnvError as sp, applyPolyfills as np, logger as rp, createPostEvent as ap, createStartParam as ip, decodeBase64Url as cp, decodeStartParam as up, emitEvent as lp, encodeBase64Url as pp, isCancelledError as dp, isInvalidLaunchParamsError as mp, isInvokeCustomMethodError as _p, isLaunchParamsRetrieveError as fp, isMethodMethodParameterUnsupportedError as hp, isMethodUnsupportedError as bp, isSafeToCreateStartParam as gp, isTMA as Sp, isTimeoutError as Ep, isUnknownEnvError as Cp, mockTelegramEnv as wp, off as $p, on as Mp, postMessage as Ap, postMessageImplementation as vp, retrieveLaunchParams as yp, retrieveRawInitData as Bp, retrieveRawLaunchParams as Pp, supports as Tp, targetOrigin as kp } from "@telegram-apps/bridge";
import { createLogger as hn, getStorageValue as E, setStorageValue as M, snakeToKebab as bn, createCbCollector as tt, camelToKebab as wo } from "@telegram-apps/toolkit";
import { createLogger as Ip } from "@telegram-apps/toolkit";
import { isPageReload as C } from "@telegram-apps/navigation";
import { computed as gn, signal as $o, batch as se } from "@telegram-apps/signals";
import { errorClass as A } from "error-kid";
import { AbortablePromise as f, isCancelledError as Sn, ManualPromise as En } from "better-promises";
import { parse as ne, array as Cn, string as $, record as wn, ValiError as eo, pipe as fe, union as $n, instance as Mn, looseObject as to, transform as Mo, date as Ao, optional as An, number as vo, integer as vn } from "valibot";
import { toRGB as yn, isRGB as Ce, transformQueryUsing as Bn, jsonParse as Pn } from "@telegram-apps/transformers";
import { isRGB as qp, isRGBShort as xp, parseInitDataQuery as Np, parseLaunchParamsQuery as Dp, serializeInitDataQuery as Hp, serializeLaunchParamsQuery as Lp, serializeToQuery as Rp, toRGB as jp, transformQueryUsing as Fp } from "@telegram-apps/transformers";
// @__NO_SIDE_EFFECTS__
function z(e, t) {
  return $o(e, t);
}
// @__NO_SIDE_EFFECTS__
function c(e, t) {
  return gn(e, t);
}
// @__NO_SIDE_EFFECTS__
function u(e, t) {
  const o = /* @__PURE__ */ z(e, t);
  return [o, /* @__PURE__ */ c(o)];
}
let yo = !1;
function Pu(e) {
  yo = e, un(e);
}
const Qe = $o(hn("Bridge", {
  bgColor: "forestgreen",
  textColor: "white",
  shouldLog() {
    return yo;
  }
})), je = /* @__PURE__ */ z(0), Bo = /* @__PURE__ */ z(mn), [oo, le] = /* @__PURE__ */ u({
  tgWebAppPlatform: "unknown",
  tgWebAppVersion: "0.0"
}), O = /* @__PURE__ */ c(() => le().tgWebAppVersion);
function Tn(e) {
  e || (e = {});
  const { postEvent: t } = e, o = e.launchParams || Co();
  oo.set(o), Bo.set(
    typeof t == "function" ? t : pn(o.tgWebAppVersion)
  ), Qe().log("The package was configured. Launch params:", oo());
}
function Po() {
  return je.set(je() + 1), je().toString();
}
function W(e, t, o) {
  return ln(e, t, Po(), {
    ...o || {},
    postEvent: i
  });
}
const d = (e, t, o) => (o || (o = {}), o.postEvent || (o.postEvent = i), dn(e, t, o)), i = (e, t) => Bo()(e, t);
function v(e) {
  return /* @__PURE__ */ c(() => oe(e, O()));
}
function L(e) {
  return [e];
}
const [
  ot,
  Tu
] = A("CSSVarsBoundError", "CSS variables are already bound"), [
  To,
  ku
] = A("NotAvailableError", L), [
  Ou,
  Iu
] = A("InvalidEnvError", L), [
  Z,
  Vu
] = A("FunctionNotAvailableError", L), [
  y,
  qu
] = A(
  "InvalidArgumentsError",
  (e, t) => [e, { cause: t }]
), [
  kn,
  xu
] = A("ConcurrentCallError", L), [
  On,
  Nu
] = A(
  "SetEmojiStatusError",
  (e) => [`Failed to set emoji status: ${e}`]
), [
  ko,
  Du
] = A("AccessDeniedError", L), [
  In,
  Hu
] = A("FullscreenFailedError", L), [
  Vn,
  Lu
] = A("ShareMessageError", L), [
  st,
  Ru
] = A("UnknownThemeParamsKeyError", (e) => [`Unknown theme params key passed: ${e}`]);
function so() {
  return typeof window > "u";
}
// @__NO_SIDE_EFFECTS__
function p(e, t, o) {
  o || (o = {});
  const {
    isSupported: s,
    isMounted: n,
    isMounting: r,
    component: a,
    supports: l
  } = o || {}, P = `${a ? `${a}.` : ""}${e}()`, T = s ? Array.isArray(s) || typeof s == "object" && "any" in s ? s : [s] : void 0;
  function X(g) {
    if (l) {
      const _ = l[g];
      return oe(_[0], _[1], O());
    }
    return !0;
  }
  function k() {
    if (!T)
      return;
    function g(U) {
      return typeof U == "function" ? U() : oe(U, O()) ? void 0 : `it is unsupported in Mini Apps version ${O()}`;
    }
    const _ = Array.isArray(T) ? T : T.any, x = _.map(g).filter(Boolean);
    return Array.isArray(T) ? x[0] : x.length === _.length ? x[x.length - 1] : void 0;
  }
  function an(...g) {
    for (const _ in l)
      if (l[_][2](...g) && !X(_))
        return `option ${_} is not supported in Mini Apps version ${O()}`;
  }
  let _e;
  if (l) {
    _e = {};
    for (const g in l)
      _e[g] = /* @__PURE__ */ c(() => X(g));
  }
  const Kt = /* @__PURE__ */ c(() => !k()), Yt = /* @__PURE__ */ c(() => O() !== "0.0"), Xt = /* @__PURE__ */ c(() => !n || n()), Zt = /* @__PURE__ */ c(
    () => Jt() && !so() && Yt() && Kt() && Xt()
  );
  return Object.assign(
    (...g) => {
      const _ = `Unable to call the ${P} ${a ? "method" : "function"}:`;
      if (so() || !Jt())
        throw new Z(`${_} it can't be called outside Mini Apps`);
      if (!Yt())
        throw new Z(`${_} the SDK was not initialized. Use the SDK init() function`);
      const x = k();
      if (x)
        throw new Z(`${_} ${x}`);
      const U = an(...g);
      if (U)
        throw new Z(`${_} ${U}`);
      if (!Xt()) {
        const cn = r && r() ? "mounting. Wait for the mount completion" : `unmounted. Use the ${a}.mount() method`;
        throw new Z(`${_} the component is ${cn}`);
      }
      return t(...g);
    },
    t,
    {
      isAvailable: Zt,
      ifAvailable(...g) {
        return Zt() ? [!0, t(...g)] : [!1];
      }
    },
    T ? { isSupported: Kt } : {},
    _e ? { supports: _e } : {}
  );
}
function we(e, t) {
  return t || (t = {}), (o, s, n, r) => /* @__PURE__ */ p(o, s, {
    ...t,
    isSupported: n || t.isSupported,
    supports: r,
    component: e
  });
}
function I(e, t, o) {
  return we(e, { isSupported: o, isMounted: t });
}
function w(e, t) {
  return we(e, { isSupported: t });
}
const $e = "web_app_setup_back_button", Oo = "back_button_pressed", Me = "backButton", [no, qn] = /* @__PURE__ */ u(!1), [he, xn] = /* @__PURE__ */ u(!1), Nn = v($e), Io = I(Me, he, $e), nt = w(Me, $e), Dn = Io("hide", () => {
  rt(!1);
}), Hn = nt("mount", () => {
  he() || (rt(C() && E(Me) || !1), he.set(!0));
});
function rt(e) {
  e !== no() && (i($e, { is_visible: e }), M(Me, e), no.set(e));
}
const Ln = nt(
  "onClick",
  (e) => m(Oo, e)
), Rn = nt(
  "offClick",
  (e) => {
    S(Oo, e);
  }
), jn = Io("show", () => {
  rt(!0);
});
function Fn() {
  he.set(!1);
}
const ju = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  hide: Dn,
  isMounted: xn,
  isSupported: Nn,
  isVisible: qn,
  mount: Hn,
  offClick: Rn,
  onClick: Ln,
  show: jn,
  unmount: Fn
}, Symbol.toStringTag, { value: "Module" }));
function b(e, t, o) {
  o || (o = {});
  const {
    promise: s,
    error: n
  } = o, [r, a] = s ? [s, /* @__PURE__ */ c(s)] : /* @__PURE__ */ u(), [l, P] = n ? [n, /* @__PURE__ */ c(n)] : /* @__PURE__ */ u();
  return [
    Object.assign((...T) => {
      if (r()) {
        const k = new kn(t);
        return l.set(k), f.reject(k);
      }
      se(() => {
        r.set(e(...T)), l.set(void 0);
      });
      let X;
      return r().catch((k) => {
        throw X = k, k;
      }).finally(() => {
        se(() => {
          r.set(void 0), l.set(X);
        });
      });
    }, e),
    [r, a, /* @__PURE__ */ c(() => !!r())],
    [l, P]
  ];
}
// @__NO_SIDE_EFFECTS__
function pe(e, t, o) {
  const [s, ...n] = b(t, `The ${e} component is already mounting`), [r, a] = /* @__PURE__ */ u(!1);
  return [
    (...l) => r() ? f.resolve() : s(...l).then((P) => {
      se(() => {
        r.set(!0), o(P);
      });
    }),
    ...n,
    [r, a]
  ];
}
const [at, Un] = /* @__PURE__ */ u({
  available: !1,
  type: "",
  accessGranted: !1,
  accessRequested: !1,
  deviceId: "",
  tokenSaved: !1
}), Gn = /* @__PURE__ */ c(() => at().available), ro = "web_app_biometry_get_info", zn = /* @__PURE__ */ p(
  "requestBiometry",
  (e) => d(ro, "biometry_info_received", e),
  { isSupported: ro }
);
function Vo(e) {
  if (!Sn(e))
    throw e;
}
function Q(e) {
  const t = e();
  t && t.catch(Vo).cancel();
}
const re = "biometry", Ae = "web_app_biometry_request_auth", it = "biometry_info_received", qo = (e) => {
  ve(ct(e));
};
function xo() {
  throw new To("Biometry is not available");
}
function ct(e) {
  let t = !1, o = !1, s = "", n = !1, r = "", a = !1;
  return e.available && (t = !0, o = e.token_saved, s = e.device_id, n = e.access_requested, r = e.type, a = e.access_granted), { available: t, tokenSaved: o, deviceId: s, type: r, accessGranted: a, accessRequested: n };
}
const Wn = v(Ae), [
  Qn,
  Kn,
  Yn,
  No
] = /* @__PURE__ */ pe(
  re,
  (e) => {
    const t = C() && E(re);
    return t ? f.resolve(t) : zn({ abortSignal: e }).then(ct);
  },
  (e) => {
    m(it, qo), ve(e);
  }
), Do = w(re, Ae), ut = I(re, No[0], Ae), Xn = Do("mount", Qn), [, Ho, Zn] = Kn, [, Jn] = Yn, [er, tr] = No, [
  or,
  sr,
  nr
] = b(
  (e) => f.fn(async (t) => {
    const o = at();
    o.available || xo();
    const s = await d(Ae, "biometry_auth_requested", {
      ...e,
      ...t,
      params: { reason: ((e || {}).reason || "").trim() }
    }), { token: n } = s;
    return typeof n == "string" && ve({ ...o, token: n }), s;
  }, e),
  "Biometry authentication is already in progress"
), rr = ut("authenticate", or), [, Lo, ar] = sr, [, ir] = nr, cr = Do("openSettings", () => {
  i("web_app_biometry_open_settings");
}), [
  ur,
  lr,
  pr
] = b(
  (e) => f.fn(async (t) => {
    const o = await d("web_app_biometry_request_access", it, {
      ...e,
      ...t,
      params: { reason: (e || {}).reason || "" }
    }).then(ct);
    return o.available || xo(), ve(o), o.accessGranted;
  }, e),
  "Biometry access request is already in progress"
), dr = ut("requestAccess", ur), [, Ro, mr] = lr, [, _r] = pr;
function ve(e) {
  at.set(e), M(re, e);
}
function fr() {
  [Lo, Ro, Ho].forEach(Q), S(it, qo), er.set(!1);
}
const hr = ut(
  "updateToken",
  (e) => (e || (e = {}), d("web_app_biometry_update_token", "biometry_token_updated", {
    ...e,
    params: {
      token: e.token || "",
      reason: e.reason
    }
  }).then((t) => t.status))
), Fu = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  authError: ir,
  authPromise: Lo,
  authenticate: rr,
  isAuthenticating: ar,
  isAvailable: Gn,
  isMounted: tr,
  isMounting: Zn,
  isRequestingAccess: mr,
  isSupported: Wn,
  mount: Xn,
  mountError: Jn,
  mountPromise: Ho,
  openSettings: cr,
  requestAccess: dr,
  requestAccessError: _r,
  requestAccessPromise: Ro,
  state: Un,
  unmount: fr,
  updateToken: hr
}, Symbol.toStringTag, { value: "Module" }));
function ye(e, t) {
  return we(e, { isMounted: t });
}
const V = we, Be = "closingBehavior", [ao, br] = /* @__PURE__ */ u(!1), [Ke, jo] = /* @__PURE__ */ u(!1), Fo = ye(Be, jo), gr = V(Be), Sr = Fo("disableConfirmation", () => {
  lt(!1);
}), Er = Fo("enableConfirmation", () => {
  lt(!0);
}), Cr = gr("mount", () => {
  Ke() || (lt(
    C() && E(Be) || !1
  ), Ke.set(!0));
});
function lt(e) {
  e !== ao() && (i("web_app_setup_closing_behavior", { need_confirmation: e }), M(Be, e), ao.set(e));
}
function wr() {
  Ke.set(!1);
}
const Uu = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  disableConfirmation: Sr,
  enableConfirmation: Er,
  isConfirmationEnabled: br,
  isMounted: jo,
  mount: Cr,
  unmount: wr
}, Symbol.toStringTag, { value: "Module" })), Uo = "web_app_invoke_custom_method", de = w("cloudStorage", Uo), $r = v(Uo), Go = de("deleteItem", (e, t) => {
  const o = Array.isArray(e) ? e : [e];
  return o.length ? W("deleteStorageValues", { keys: o }, t).then() : f.resolve();
});
function Mr(e, t) {
  const o = Array.isArray(e) ? e : [e];
  return o.length ? W("getStorageValues", { keys: o }, t).then((s) => {
    const n = {
      // Fulfill the response with probably missing keys.
      ...o.reduce((r, a) => (r[a] = "", r), {}),
      ...ne(wn($(), $()), s)
    };
    return typeof e == "string" ? n[e] : n;
  }) : f.resolve(Array.isArray(e) ? {} : "");
}
const Ar = de("getItem", Mr), zo = de("getKeys", (e) => W("getStorageKeys", {}, e).then(
  (t) => ne(Cn($()), t)
)), vr = de("setItem", (e, t, o) => W("saveStorageValue", {
  key: e,
  value: t
}, o).then()), yr = de("clear", (e) => zo(e).then(Go)), Gu = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  clear: yr,
  deleteItem: Go,
  getItem: Ar,
  getKeys: zo,
  isSupported: $r,
  setItem: vr
}, Symbol.toStringTag, { value: "Module" })), me = "web_app_trigger_haptic_feedback", pt = w("hapticFeedback", me), Br = v(me), Pr = pt(
  "impactOccurred",
  (e) => {
    i(me, {
      type: "impact",
      impact_style: e
    });
  }
), Tr = pt(
  "notificationOccurred",
  (e) => {
    i(me, {
      type: "notification",
      notification_type: e
    });
  }
), kr = pt(
  "selectionChanged",
  () => {
    i(me, { type: "selection_change" });
  }
), zu = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  impactOccurred: Pr,
  isSupported: Br,
  notificationOccurred: Tr,
  selectionChanged: kr
}, Symbol.toStringTag, { value: "Module" })), [Wo, Or] = /* @__PURE__ */ u(void 0);
function B(e) {
  return /* @__PURE__ */ c(() => {
    const t = Wo();
    return t ? t[e] : void 0;
  });
}
const Qo = B("auth_date"), Ko = B("can_send_after"), Ir = /* @__PURE__ */ c(() => {
  const e = Qo(), t = Ko();
  return t && e ? new Date(e.getTime() + t * 1e3) : void 0;
}), Vr = B("chat"), qr = B("chat_type"), xr = B("chat_instance"), Nr = B("hash"), Dr = B("query_id"), [Hr, Lr] = /* @__PURE__ */ u(), Rr = B("receiver");
function jr() {
  const e = Co();
  Wo.set(e.tgWebAppData), Hr.set(_n());
}
const Fr = B("start_param"), Ur = B("user"), Wu = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  authDate: Qo,
  canSendAfter: Ko,
  canSendAfterDate: Ir,
  chat: Vr,
  chatInstance: xr,
  chatType: qr,
  hash: Nr,
  queryId: Dr,
  raw: Lr,
  receiver: Rr,
  restore: jr,
  startParam: Fr,
  state: Or,
  user: Ur
}, Symbol.toStringTag, { value: "Module" })), dt = "web_app_open_invoice", Gr = w("invoice", dt), zr = v(dt);
function Wr(e, t, o) {
  let s;
  if (t === "url") {
    const { hostname: n, pathname: r } = new URL(e, window.location.href);
    if (n !== "t.me")
      throw new y(`Link has unexpected hostname: ${n}`);
    const a = r.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);
    if (!a)
      throw new y(
        'Expected to receive a link with a pathname in format "/invoice/{slug}" or "/${slug}"'
      );
    [, , s] = a;
  } else
    s = e, o = t;
  return d(dt, "invoice_closed", {
    ...o,
    params: { slug: s },
    capture: (n) => s === n.slug
  }).then((n) => n.status);
}
const [
  Qr,
  Kr,
  Yr
] = b(Wr, "Invoice is already opened"), Xr = Gr("open", Qr), [, Zr, Jr] = Kr, [, ea] = Yr, Qu = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  isOpened: Jr,
  isSupported: zr,
  open: Xr,
  openError: ea,
  openPromise: Zr
}, Symbol.toStringTag, { value: "Module" })), J = "locationManager", mt = "web_app_check_location", io = "web_app_open_location_settings", be = /* @__PURE__ */ z({
  available: !1,
  accessGranted: !1,
  accessRequested: !1
});
function _t(e) {
  return /* @__PURE__ */ c(() => be()[e]);
}
const ta = v(mt), oa = _t("available"), sa = _t("accessGranted"), na = _t("accessRequested");
function ra(e) {
  let t = !1, o, s;
  return e.available && (t = !0, o = e.access_requested, s = e.access_granted), {
    available: t,
    accessGranted: s || !1,
    accessRequested: o || !1
  };
}
const [
  aa,
  ia,
  ca,
  Yo
] = /* @__PURE__ */ pe(
  J,
  (e) => {
    const t = C() && E(J);
    return t ? f.resolve(t) : d("web_app_check_location", "location_checked", e).then(ra);
  },
  (e) => {
    be.set(e), M(J, e);
  }
), Xo = w(J, mt), ua = I(J, Yo[0], mt), la = Xo("mount", aa), [, pa, da] = ia, [, ma] = ca, [_a, fa] = Yo, [
  ha,
  ba,
  ga
] = b(
  (e) => d("web_app_request_location", "location_requested", e).then((t) => {
    if (!t.available)
      throw be.set({ ...be(), available: !1 }), new To("Location data tracking is not available");
    const { available: o, ...s } = t;
    return s;
  }),
  "Location request is currently in progress"
), Sa = ua("requestLocation", ha), [, Zo, Ea] = ba, [, Ca] = ga, wa = Xo("openSettings", () => {
  i(io);
}, io);
function $a() {
  Q(Zo), _a.set(!1);
}
const Ku = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  isAccessGranted: sa,
  isAccessRequested: na,
  isAvailable: oa,
  isMounted: fa,
  isMounting: da,
  isRequestingLocation: Ea,
  isSupported: ta,
  mount: la,
  mountError: ma,
  mountPromise: pa,
  openSettings: wa,
  requestLocation: Sa,
  requestLocationError: Ca,
  requestLocationPromise: Zo,
  unmount: $a
}, Symbol.toStringTag, { value: "Module" }));
function ft(e) {
  const t = {};
  for (const o in e) {
    const s = e[o];
    s !== void 0 && (t[o] = s);
  }
  return t;
}
function Jo(e) {
  const t = yn(e);
  return Math.sqrt(
    [0.299, 0.587, 0.114].reduce((o, s, n) => {
      const r = parseInt(t.slice(1 + n * 2, 1 + (n + 1) * 2), 16);
      return o + r * r * s;
    }, 0)
  ) < 120;
}
const [Fe, Ma] = /* @__PURE__ */ u(!1), [D, K] = /* @__PURE__ */ u({});
function h(e) {
  return /* @__PURE__ */ c(() => D()[e]);
}
const Aa = h("accent_text_color"), es = h("bg_color"), ht = h("button_color"), ts = h("button_text_color"), va = h("bottom_bar_bg_color"), ya = h("destructive_text_color"), Ba = h("header_bg_color"), Pa = h("hint_color"), Ta = /* @__PURE__ */ c(() => {
  const e = es();
  return !e || Jo(e);
}), ka = h("link_color"), os = h("secondary_bg_color"), Oa = h("section_bg_color"), Ia = h("section_header_text_color"), Va = h("section_separator_color"), qa = h("subtitle_text_color"), xa = h("text_color");
function R(e) {
  return /* @__PURE__ */ c(() => bt()[e]);
}
const ee = /* @__PURE__ */ z({
  hasShineEffect: !1,
  isEnabled: !0,
  isLoaderVisible: !1,
  isVisible: !1,
  text: "Continue"
}), bt = /* @__PURE__ */ c(() => {
  const e = ee();
  return {
    ...e,
    backgroundColor: e.backgroundColor || ht() || "#2481cc",
    textColor: e.textColor || ts() || "#ffffff"
  };
}), [Ye, ss] = /* @__PURE__ */ u(!1), Na = R("backgroundColor"), Da = R("hasShineEffect"), Ha = R("isEnabled"), La = R("isLoaderVisible"), Ra = R("isVisible"), ja = R("text"), Fa = R("textColor"), Ua = "web_app_setup_main_button", ns = "main_button_pressed", Pe = "mainButton", gt = V(Pe), Ga = ye(Pe, ss), za = gt("mount", () => {
  if (!Ye()) {
    const e = C() && E(Pe);
    e && ee.set(e), Ye.set(!0);
  }
}), Wa = gt(
  "onClick",
  (e) => m(ns, e)
), Qa = gt(
  "offClick",
  (e) => {
    S(ns, e);
  }
), Ka = Ga(
  "setParams",
  (e) => {
    ee.set({ ...ee(), ...ft(e) }), M(Pe, ee());
    const t = bt();
    t.text && i(Ua, {
      color: t.backgroundColor,
      has_shine_effect: t.hasShineEffect,
      is_active: t.isEnabled,
      is_progress_visible: t.isLoaderVisible,
      is_visible: t.isVisible,
      text: t.text,
      text_color: t.textColor
    });
  }
);
function Ya() {
  Ye.set(!1);
}
const Yu = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  backgroundColor: Na,
  hasShineEffect: Da,
  isEnabled: Ha,
  isLoaderVisible: La,
  isMounted: ss,
  isVisible: Ra,
  mount: za,
  offClick: Qa,
  onClick: Wa,
  setParams: Ka,
  state: bt,
  text: ja,
  textColor: Fa,
  unmount: Ya
}, Symbol.toStringTag, { value: "Module" }));
function St(e, t) {
  document.documentElement.style.setProperty(e, t);
}
function Et(e) {
  document.documentElement.style.removeProperty(e);
}
const G = "themeParams", Ct = "theme_changed", rs = V(G), wt = ({ theme_params: e }) => {
  D.set(e), M(G, e);
}, [
  Xa,
  as,
  Za,
  is
] = /* @__PURE__ */ pe(
  G,
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  (e) => f.resolve(
    C() && E(G) || le().tgWebAppThemeParams || {}
  ),
  (e) => {
    m(Ct, wt), D.set(e);
  }
), Ja = ye(G, is[0]), ei = Ja(
  "bindCssVars",
  (e) => {
    if (Fe())
      throw new ot();
    e || (e = (s) => `--tg-theme-${bn(s)}`);
    function t(s) {
      Object.entries(D()).forEach(([n, r]) => {
        r && s(n, r);
      });
    }
    function o() {
      t((s, n) => {
        St(e(s), n);
      });
    }
    return o(), D.sub(o), Fe.set(!0), () => {
      t(Et), D.unsub(o), Fe.set(!1);
    };
  }
), cs = rs("mount", Xa), ti = as[2], us = as[1], oi = Za[1], [Xe, si] = is, ls = rs("mountSync", () => {
  if (!Xe()) {
    const e = C() && E(G) || le().tgWebAppThemeParams || {};
    m(Ct, wt), se(() => {
      D.set(e), Xe.set(!0);
    });
  }
});
function ni() {
  Q(us), S(Ct, wt), Xe.set(!1);
}
// @__NO_SIDE_EFFECTS__
function ps(e) {
  return /* @__PURE__ */ c(() => Te(e()));
}
function Te(e) {
  return Ce(e) ? e : K()[e];
}
const [ae, ri] = /* @__PURE__ */ u("bg_color"), $t = /* @__PURE__ */ ps(ae), [ie, ai] = /* @__PURE__ */ u("bottom_bar_bg_color"), Mt = /* @__PURE__ */ c(() => {
  const e = ie();
  return Ce(e) ? e : K()[e] || os();
}), [ce, ii] = /* @__PURE__ */ u("bg_color"), ds = /* @__PURE__ */ ps(ce), [Ue, ci] = /* @__PURE__ */ u(!1), ui = /* @__PURE__ */ c(() => {
  const e = $t();
  return e ? Jo(e) : !1;
}), [ke, li] = /* @__PURE__ */ u(!0), ms = /* @__PURE__ */ c(() => ({
  backgroundColor: ae(),
  bottomBarColor: ie(),
  headerColor: ce(),
  isActive: ke()
})), Xu = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  accentTextColor: Aa,
  backgroundColor: es,
  bindCssVars: ei,
  bottomBarBgColor: va,
  buttonColor: ht,
  buttonTextColor: ts,
  destructiveTextColor: ya,
  headerBackgroundColor: Ba,
  hintColor: Pa,
  isCssVarsBound: Ma,
  isDark: Ta,
  isMounted: si,
  isMounting: ti,
  linkColor: ka,
  mount: cs,
  mountError: oi,
  mountPromise: us,
  mountSync: ls,
  secondaryBackgroundColor: os,
  sectionBackgroundColor: Oa,
  sectionHeaderTextColor: Ia,
  sectionSeparatorColor: Va,
  state: K,
  subtitleTextColor: qa,
  textColor: xa,
  unmount: ni
}, Symbol.toStringTag, { value: "Module" })), ge = "web_app_set_background_color", Se = "web_app_set_bottom_bar_color", N = "web_app_set_header_color", At = "visibility_changed", H = "miniApp", vt = {
  any: [
    ge,
    Se,
    N
  ]
}, pi = /* @__PURE__ */ c(() => vt.any.some((e) => oe(e, O()))), yt = (e) => {
  ke.set(e.is_visible), Ie();
}, Bt = (e) => {
  [
    [ce, N],
    [ae, ge],
    [ie, Se]
  ].forEach(([t, o]) => {
    const s = t();
    if (!Ce(s) && // Header color setter uses additional checks. We don't apply changes if the current
    // value is a known color key because it updates automatically by itself.
    (o !== N || s !== "bg_color" && s !== "secondary_bg_color")) {
      const n = e[s];
      n && i(o, { color: n });
    }
  });
}, [
  di,
  _s,
  mi,
  fs
] = /* @__PURE__ */ pe(
  H,
  (e) => cs(e).then(() => C() && E(H) || void 0),
  (e) => {
    Pt.ifAvailable(e ? e.backgroundColor : "bg_color"), Tt.ifAvailable(e ? e.bottomBarColor : "bottom_bar_bg_color"), kt.ifAvailable(e ? e.headerColor : "bg_color"), ke.set(e ? e.isActive : !0), m(At, yt), K.sub(Bt);
  }
), hs = V(H), bs = w(H, vt), Oe = I(H, fs[0], vt), _i = Oe(
  "bindCssVars",
  (e) => {
    if (Ue())
      throw new ot();
    const [t, o] = tt();
    function s(n, r) {
      function a() {
        St(n, r() || null);
      }
      a(), t(r.sub(a), Et.bind(null, n));
    }
    return e || (e = (n) => `--tg-${wo(n)}`), s(e("bgColor"), $t), s(e("bottomBarColor"), Mt), s(e("headerColor"), ds), t(() => {
      Ue.set(!1);
    }), Ue.set(!0), o;
  }
), fi = hs("close", (e) => {
  i("web_app_close", { return_back: e });
}), hi = bs("mount", di), bi = _s[2], gs = _s[1], gi = mi[1], [Ze, Si] = fs, Ei = bs("mountSync", () => {
  if (!Ze()) {
    ls();
    const e = C() && E(H) || void 0;
    Pt.ifAvailable(e ? e.backgroundColor : "bg_color"), Tt.ifAvailable(e ? e.bottomBarColor : "bottom_bar_bg_color"), kt.ifAvailable(e ? e.headerColor : "bg_color"), m(At, yt), K.sub(Bt), se(() => {
      ke.set(e ? e.isActive : !0), Ze.set(!0);
    });
  }
}), Ci = hs("ready", () => {
  i("web_app_ready");
});
function Ie() {
  M(H, ms());
}
const Pt = Oe(
  "setBackgroundColor",
  (e) => {
    if (e === ae())
      return;
    const t = Te(e);
    if (!t)
      throw new st(e);
    i(ge, { color: t }), ae.set(e), Ie();
  },
  ge
), Tt = Oe(
  "setBottomBarColor",
  (e) => {
    if (e === ie())
      return;
    const t = Te(e);
    if (!t)
      throw new st(e);
    i(Se, { color: t }), ie.set(e), Ie();
  },
  Se
), kt = Oe(
  "setHeaderColor",
  (e) => {
    if (e !== ce()) {
      if (e === "bg_color" || e === "secondary_bg_color")
        i(N, { color_key: e });
      else {
        const t = Te(e);
        if (!t)
          throw new st(e);
        i(N, { color: t });
      }
      ce.set(e), Ie();
    }
  },
  N,
  {
    rgb: [N, "color", Ce]
  }
);
function wi() {
  Q(gs), S(At, yt), K.unsub(Bt), Ze.set(!1);
}
const Zu = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  backgroundColor: ri,
  backgroundColorRGB: $t,
  bindCssVars: _i,
  bottomBarColor: ai,
  bottomBarColorRGB: Mt,
  close: fi,
  headerColor: ii,
  headerColorRGB: ds,
  isActive: li,
  isCssVarsBound: ci,
  isDark: ui,
  isMounted: Si,
  isMounting: bi,
  isSupported: pi,
  mount: hi,
  mountError: gi,
  mountPromise: gs,
  mountSync: Ei,
  ready: Ci,
  setBackgroundColor: Pt,
  setBottomBarColor: Tt,
  setHeaderColor: kt,
  state: ms,
  unmount: wi
}, Symbol.toStringTag, { value: "Module" }));
function $i(e) {
  const t = e.message.trim(), o = (e.title || "").trim(), s = e.buttons || [];
  if (o.length > 64)
    throw new y(`Invalid title: ${o}`);
  if (!t || t.length > 256)
    throw new y(`Invalid message: ${t}`);
  if (s.length > 3)
    throw new y(`Invalid buttons count: ${s.length}`);
  return {
    title: o,
    message: t,
    buttons: s.length ? s.map((n, r) => {
      const a = n.id || "";
      if (a.length > 64)
        throw new y(`Button with index ${r} has invalid id: ${a}`);
      if (!n.type || n.type === "default" || n.type === "destructive") {
        const l = n.text.trim();
        if (!l || l.length > 64)
          throw new y(`Button with index ${r} has invalid text: ${l}`);
        return { type: n.type, text: l, id: a };
      }
      return { type: n.type, id: a };
    }) : [{ type: "close", id: "" }]
  };
}
const Ot = "web_app_open_popup", Ss = w("popup", Ot), Mi = v(Ot), [Es, It, Cs] = b(
  (e) => d(Ot, "popup_closed", {
    ...e,
    params: $i(e)
  }).then(({ button_id: t }) => t === void 0 ? null : t),
  "A popup is already opened"
), Ai = Ss("open", Es), vi = It[1], yi = It[2], Bi = Cs[1], Pi = Ss("show", Es), [, Ti, ki] = It, [, Oi] = Cs, Ju = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  isOpened: yi,
  isShown: ki,
  isSupported: Mi,
  open: Ai,
  openError: Bi,
  openPromise: vi,
  show: Pi,
  showError: Oi,
  showPromise: Ti
}, Symbol.toStringTag, { value: "Module" })), ws = "web_app_close_scan_qr_popup", Vt = "web_app_open_scan_qr_popup", Ii = "scan_qr_popup_closed", Vi = "qr_text_received", $s = w("qrScanner", Vt), qi = $s("close", () => {
  i(ws), Q(Ms);
}), xi = v(Vt);
function Ni(e) {
  e || (e = {});
  const { onCaptured: t, text: o, capture: s } = e, [, n] = tt(
    m(Ii, () => {
      r.resolve();
    }),
    m(Vi, (a) => {
      t ? t(a.data) : (!s || s(a.data)) && (r.resolve(a.data), i(ws));
    })
  ), r = new En(e);
  return (e.postEvent || i)(Vt, { text: o }), f.resolve(r).catch(Vo).finally(n);
}
const [
  Di,
  Hi,
  Li
] = b(Ni, "The QR Scanner is already opened"), Ri = $s("open", Di), [, Ms, ji] = Hi, [, Fi] = Li, el = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  close: qi,
  isOpened: ji,
  isSupported: xi,
  open: Ri,
  openError: Fi,
  openPromise: Ms
}, Symbol.toStringTag, { value: "Module" }));
function q(e) {
  return /* @__PURE__ */ c(() => qt()[e]);
}
const te = /* @__PURE__ */ z({
  hasShineEffect: !1,
  isEnabled: !0,
  isLoaderVisible: !1,
  isVisible: !1,
  position: "left",
  text: "Cancel"
}), qt = /* @__PURE__ */ c(() => {
  const e = te();
  return {
    ...e,
    backgroundColor: e.backgroundColor || Mt() || "#000000",
    textColor: e.textColor || ht() || "#2481cc"
  };
}), [Je, As] = /* @__PURE__ */ u(!1), Ui = q("backgroundColor"), Gi = q("hasShineEffect"), zi = q("isEnabled"), Wi = q("isLoaderVisible"), Qi = q("isVisible"), Ki = q("position"), Yi = q("text"), Xi = q("textColor"), Ve = "web_app_setup_secondary_button", vs = "secondary_button_pressed", qe = "secondaryButton", xt = w(qe, Ve), Zi = I(qe, As, Ve), Ji = v(Ve), ec = xt("mount", () => {
  if (!Je()) {
    const e = C() && E(qe);
    e && te.set(e), Je.set(!0);
  }
}), tc = xt(
  "onClick",
  (e) => m(vs, e)
), oc = xt(
  "offClick",
  (e) => {
    S(vs, e);
  }
), sc = Zi(
  "setParams",
  (e) => {
    te.set({ ...te(), ...ft(e) }), M(qe, te());
    const t = qt();
    t.text && i(Ve, {
      color: t.backgroundColor,
      has_shine_effect: t.hasShineEffect,
      is_active: t.isEnabled,
      is_progress_visible: t.isLoaderVisible,
      is_visible: t.isVisible,
      position: t.position,
      text: t.text,
      text_color: t.textColor
    });
  }
);
function nc() {
  Je.set(!1);
}
const tl = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  backgroundColor: Ui,
  hasShineEffect: Gi,
  isEnabled: zi,
  isLoaderVisible: Wi,
  isMounted: As,
  isSupported: Ji,
  isVisible: Qi,
  mount: ec,
  offClick: oc,
  onClick: tc,
  position: Ki,
  setParams: sc,
  state: qt,
  text: Yi,
  textColor: Xi,
  unmount: nc
}, Symbol.toStringTag, { value: "Module" })), xe = "web_app_setup_settings_button", ys = "settings_button_pressed", Ne = "settingsButton", [co, rc] = /* @__PURE__ */ u(!1), [Ee, ac] = /* @__PURE__ */ u(!1), ic = v(xe), Nt = w(Ne, xe), Bs = I(Ne, Ee, xe), cc = Bs("hide", () => {
  Dt(!1);
}), uc = Nt("mount", () => {
  Ee() || (Dt(C() && E(Ne) || !1), Ee.set(!0));
});
function Dt(e) {
  e !== co() && (i(xe, { is_visible: e }), M(Ne, e), co.set(e));
}
const lc = Nt(
  "onClick",
  (e) => m(ys, e)
), pc = Nt(
  "offClick",
  (e) => {
    S(ys, e);
  }
), dc = Bs("show", () => {
  Dt(!0);
});
function mc() {
  Ee.set(!1);
}
const ol = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  hide: cc,
  isMounted: ac,
  isSupported: ic,
  isVisible: rc,
  mount: uc,
  offClick: pc,
  onClick: lc,
  show: dc,
  unmount: mc
}, Symbol.toStringTag, { value: "Module" })), De = "web_app_setup_swipe_behavior", He = "swipeBehavior", [ue, _c] = /* @__PURE__ */ u(!1), fc = v(De), [et, hc] = /* @__PURE__ */ u(!0), bc = w(He, De), Ps = I(He, ue, De), gc = Ps("disableVertical", () => {
  Ht(!1);
}), Sc = Ps("enableVertical", () => {
  Ht(!0);
}), Ec = bc("mount", () => {
  ue() || (Ht(
    C() && E(He) || !1,
    !0
  ), ue.set(!0));
});
function Ht(e, t) {
  (e !== et() || t) && (i(De, { allow_vertical_swipe: e }), M(He, e), et.set(e));
}
function Cc() {
  ue.set(!1);
}
const sl = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  _isMounted: ue,
  _isVerticalEnabled: et,
  disableVertical: gc,
  enableVertical: Sc,
  isMounted: _c,
  isSupported: fc,
  isVerticalEnabled: hc,
  mount: Ec,
  unmount: Cc
}, Symbol.toStringTag, { value: "Module" })), j = "viewport", Lt = "fullscreen_changed", Rt = "safe_area_changed", jt = "content_safe_area_changed", Ft = "viewport_changed", Ts = V(j), uo = { left: 0, top: 0, bottom: 0, right: 0 };
function Ge(e) {
  return Math.max(e, 0);
}
const [ze, ks] = /* @__PURE__ */ u({
  contentSafeAreaInsets: uo,
  height: 0,
  isExpanded: !1,
  isFullscreen: !1,
  safeAreaInsets: uo,
  stableHeight: 0,
  width: 0
});
function F(e) {
  return /* @__PURE__ */ c(() => ks()[e]);
}
const Ut = F("height"), Gt = F("stableHeight"), Os = F("width"), wc = F("isExpanded"), $c = /* @__PURE__ */ c(() => Ut() === Gt());
function Y(e) {
  const { height: t, stableHeight: o, width: s } = e;
  ze.set({
    ...ze(),
    ...ft({
      ...e,
      height: t ? Ge(t) : void 0,
      width: s ? Ge(s) : void 0,
      stableHeight: o ? Ge(o) : void 0
    })
  }), M(j, ze());
}
function Mc() {
  return E(j);
}
function Le(e) {
  return /* @__PURE__ */ c(() => zt()[e]);
}
const zt = F("contentSafeAreaInsets"), Is = Le("bottom"), Vs = Le("left"), qs = Le("right"), xs = Le("top");
function Re(e) {
  return /* @__PURE__ */ c(() => Wt()[e]);
}
const Wt = F("safeAreaInsets"), Ns = Re("bottom"), Ds = Re("left"), Hs = Re("right"), Ls = Re("top"), Rs = "web_app_request_safe_area", js = w(j, Rs), lo = js(
  "requestContentSafeAreaInsets",
  (e) => d("web_app_request_content_safe_area", jt, e)
);
function Ac(e) {
  return d("web_app_request_viewport", Ft, e);
}
const po = js(
  "requestSafeAreaInsets",
  (e) => d(Rs, Rt, e)
), Fs = (e) => {
  const { height: t } = e;
  Y({
    isExpanded: e.is_expanded,
    height: t,
    width: e.width,
    stableHeight: e.is_state_stable ? t : void 0
  });
}, Us = (e) => {
  Y({ isFullscreen: e.is_fullscreen });
}, Gs = (e) => {
  Y({ safeAreaInsets: e });
}, zs = (e) => {
  Y({ contentSafeAreaInsets: e });
}, [
  vc,
  yc,
  Bc,
  Pc
] = /* @__PURE__ */ pe(
  j,
  (e) => {
    const t = C() && Mc();
    return t ? f.resolve(t) : f.fn(async (o) => {
      const s = await f.all([
        po.isAvailable() ? po(o) : Wt(),
        lo.isAvailable() ? lo(o) : zt()
      ]), n = le(), r = {
        contentSafeAreaInsets: s[1],
        isFullscreen: !!n.tgWebAppFullscreen,
        safeAreaInsets: s[0]
      };
      if (["macos", "tdesktop", "unigram", "webk", "weba", "web"].includes(n.tgWebAppPlatform)) {
        const a = window;
        return {
          ...r,
          height: a.innerHeight,
          isExpanded: !0,
          stableHeight: a.innerHeight,
          width: a.innerWidth
        };
      }
      return Ac(o).then((a) => ({
        ...r,
        height: a.height,
        isExpanded: a.is_expanded,
        stableHeight: a.is_state_stable ? a.height : 0,
        width: a.width
      }));
    }, e);
  },
  (e) => {
    m(Ft, Fs), m(Lt, Us), m(Rt, Gs), m(jt, zs), Y(e);
  }
), Tc = Ts("mount", vc), [, Ws, kc] = yc, [, Oc] = Bc, [Qt, Ic] = Pc;
function Vc() {
  Q(Ws), S(Ft, Fs), S(Lt, Us), S(Rt, Gs), S(jt, zs), Qt.set(!1);
}
const qc = ye(j, Qt), [We, xc] = /* @__PURE__ */ u(!1), Nc = qc(
  "bindCssVars",
  (e) => {
    if (We())
      throw new ot();
    e || (e = (o) => `--tg-viewport-${wo(o)}`);
    const t = [
      ["height", Ut],
      ["stableHeight", Gt],
      ["width", Os],
      ["safeAreaInsetTop", Ls],
      ["safeAreaInsetBottom", Ns],
      ["safeAreaInsetLeft", Ds],
      ["safeAreaInsetRight", Hs],
      ["contentSafeAreaInsetTop", xs],
      ["contentSafeAreaInsetBottom", Is],
      ["contentSafeAreaInsetLeft", Vs],
      ["contentSafeAreaInsetRight", qs]
    ].reduce((o, [s, n]) => {
      const r = e(s);
      if (r) {
        const a = () => {
          St(r, `${n()}px`);
        };
        o.push([a, n.sub(a), r]);
      }
      return o;
    }, []);
    return t.forEach((o) => {
      o[0]();
    }), We.set(!0), () => {
      t.forEach((o) => {
        o[1](), Et(o[2]);
      }), We.set(!1);
    };
  }
), Dc = Ts("expand", () => {
  i("web_app_expand");
}), Qs = "web_app_request_fullscreen", Hc = I(j, Qt, Qs), Ks = F("isFullscreen"), [
  Lc,
  Rc
] = /* @__PURE__ */ u(), [
  jc,
  Fc
] = /* @__PURE__ */ u();
function Ys(e, t) {
  return Hc(
    e,
    b(
      (o) => d(
        t ? Qs : "web_app_exit_fullscreen",
        [Lt, "fullscreen_failed"],
        o
      ).then((s) => {
        if ("error" in s && s.error !== "ALREADY_FULLSCREEN")
          throw new In(s.error);
        const n = "is_fullscreen" in s ? s.is_fullscreen : !0;
        n !== Ks() && Y({ isFullscreen: n });
      }),
      "Fullscreen mode change is already being requested",
      {
        promise: Lc,
        error: jc
      }
    )[0]
  );
}
const Uc = Ys("requestFullscreen", !0), Gc = Ys("exitFullscreen"), nl = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
  __proto__: null,
  bindCssVars: Nc,
  changeFullscreenError: Fc,
  changeFullscreenPromise: Rc,
  contentSafeAreaInsetBottom: Is,
  contentSafeAreaInsetLeft: Vs,
  contentSafeAreaInsetRight: qs,
  contentSafeAreaInsetTop: xs,
  contentSafeAreaInsets: zt,
  exitFullscreen: Gc,
  expand: Dc,
  height: Ut,
  isCssVarsBound: xc,
  isExpanded: wc,
  isFullscreen: Ks,
  isMounted: Ic,
  isMounting: kc,
  isStable: $c,
  mount: Tc,
  mountError: Oc,
  mountPromise: Ws,
  requestFullscreen: Uc,
  safeAreaInsetBottom: Ns,
  safeAreaInsetLeft: Ds,
  safeAreaInsetRight: Hs,
  safeAreaInsetTop: Ls,
  safeAreaInsets: Wt,
  stableHeight: Gt,
  state: ks,
  unmount: Vc,
  width: Os
}, Symbol.toStringTag, { value: "Module" })), Xs = "web_app_request_emoji_status_access", [
  zc,
  Wc,
  Qc
] = b((e) => d(Xs, "emoji_status_access_requested", e).then((t) => t.status), "Emoji status access request is already in progress"), rl = /* @__PURE__ */ p(
  "requestEmojiStatusAccess",
  zc,
  { isSupported: Xs }
), [, al, il] = Wc, [, cl] = Qc, Zs = "web_app_set_emoji_status", [
  Kc,
  Yc,
  Xc
] = b(
  (e, t) => d(Zs, ["emoji_status_set", "emoji_status_failed"], {
    params: {
      custom_emoji_id: e,
      duration: (t || {}).duration
    },
    ...t
  }).then((o) => {
    if (o && "error" in o)
      throw new On(o.error);
  }),
  "Emoji status set request is currently in progress"
), ul = /* @__PURE__ */ p("setEmojiStatus", Kc, {
  isSupported: Zs
}), [, ll, pl] = Yc, [, dl] = Xc, Zc = { isSupported: "web_app_add_to_home_screen" }, Js = "home_screen_failed", ml = /* @__PURE__ */ p(
  "onAddToHomeScreenFailed",
  (e, t) => m(Js, e, t),
  { isSupported: "web_app_add_to_home_screen" }
), _l = /* @__PURE__ */ p(
  "offAddToHomeScreenFailed",
  (e) => {
    S(Js, e);
  },
  Zc
), en = { isSupported: "web_app_add_to_home_screen" }, tn = "home_screen_added", fl = /* @__PURE__ */ p(
  "onAddedToHomeScreen",
  (e, t) => m(tn, e, t),
  en
), hl = /* @__PURE__ */ p(
  "offAddedToHomeScreen",
  (e) => {
    S(tn, e);
  },
  en
), mo = "web_app_add_to_home_screen", bl = /* @__PURE__ */ p(
  "addToHomeScreen",
  () => {
    i(mo);
  },
  { isSupported: mo }
), on = "web_app_check_home_screen", [
  Jc,
  eu,
  tu
] = b((e) => d(on, "home_screen_checked", e).then((t) => t.status || "unknown"), "Check home screen status request is currently in progress"), gl = /* @__PURE__ */ p("checkHomeScreenStatus", Jc, {
  isSupported: on
}), [, Sl, El] = eu, [, Cl] = tu, ou = V(), wl = ou(
  "openLink",
  (e, t) => {
    if (typeof e == "string")
      try {
        e = new URL(e);
      } catch (o) {
        throw new y(`"${e.toString()}" is invalid URL`, o);
      }
    t || (t = {}), i("web_app_open_link", {
      url: e.toString(),
      try_browser: t.tryBrowser,
      try_instant_view: t.tryInstantView
    });
  }
), _o = "web_app_open_tg_link", su = V(), nu = su(
  "openTelegramLink",
  (e) => {
    const t = e.toString();
    if (!t.match(/^https:\/\/t.me\/.+/))
      throw new y(`"${t}" is invalid URL`);
    if (!oe(_o, O())) {
      window.location.href = t;
      return;
    }
    e = new URL(e), i(_o, { path_full: e.pathname + e.search });
  }
), ru = V(), $l = ru(
  "shareURL",
  (e, t) => {
    nu(
      "https://t.me/share/url?" + new URLSearchParams({ url: e, text: t || "" }).toString().replace(/\+/g, "%20")
    );
  }
);
function au(e, t) {
  return new f({ abortSignal: t, timeout: e }).catch(() => {
  });
}
const sn = "web_app_request_phone", [
  iu,
  cu,
  uu
] = b((e) => d(sn, "phone_requested", e).then((t) => t.status), "Phone access request is currently in progress"), lu = /* @__PURE__ */ p("requestPhoneAccess", iu, {
  isSupported: sn
}), [, Ml, Al] = cu, [, vl] = uu, nn = {
  isSupported: "web_app_request_phone"
};
async function fo(e) {
  const t = ne($(), await W("getRequestedContact", {}, {
    ...e,
    timeout: (e || {}).timeout || 5e3
  }));
  return {
    raw: t,
    parsed: ne(
      fe(
        // todo: Union is unnecessary here, but we use it to comply TypeScript checker.
        $n([$(), Mn(URLSearchParams)]),
        Bn(
          to({
            contact: fe(
              $(),
              Pn(),
              to({
                user_id: vo(),
                phone_number: $(),
                first_name: $(),
                last_name: An($())
              })
            ),
            auth_date: fe(
              $(),
              Mo((o) => new Date(Number(o) * 1e3)),
              Ao()
            ),
            hash: $()
          })
        )
      ),
      t
    )
  };
}
const [pu, du, mu] = b(
  (e) => new f(
    async (t, o, s) => {
      try {
        return t(await fo(s));
      } catch (a) {
        if (a instanceof eo)
          throw a;
      }
      if (await lu(s) !== "sent")
        throw new ko("User denied access");
      let r = 50;
      for (; !s.isAborted(); ) {
        try {
          return t(await fo(s));
        } catch (a) {
          if (a instanceof eo)
            throw a;
        }
        await au(r), r += 50;
      }
    },
    e
  ),
  "Contact is already being requested"
), _u = /* @__PURE__ */ p("requestContactComplete", pu, nn), yl = /* @__PURE__ */ p(
  "requestContact",
  (e) => _u(e).then((t) => t.parsed),
  nn
), [, Bl, Pl] = du, [, Tl] = mu, rn = "web_app_request_write_access", [
  fu,
  hu,
  bu
] = b(
  (e) => d(rn, "write_access_requested", e).then((t) => t.status),
  "Write access request is currently in progress"
), kl = /* @__PURE__ */ p("requestWriteAccess", fu, {
  isSupported: rn
}), [, Ol, Il] = hu, [, Vl] = bu;
function gu(e) {
  const t = document.createElement("textarea");
  t.value = e, t.style.top = "0", t.style.left = "0", t.style.position = "fixed", document.body.appendChild(t), t.focus(), t.select();
  try {
    document.execCommand("copy");
  } finally {
    document.body.removeChild(t);
  }
}
async function ql(e) {
  try {
    const { clipboard: t } = navigator;
    if (t)
      return await t.writeText(e);
  } catch {
  }
  gu(e);
}
const ho = "web_app_request_file_download", xl = /* @__PURE__ */ p(
  "downloadFile",
  (e, t, o) => d(
    ho,
    "file_download_requested",
    { ...o, params: { url: e, file_name: t } }
  ).then((s) => {
    if (s.status !== "downloading")
      throw new ko("User denied the action");
  }),
  { isSupported: ho }
), Nl = /* @__PURE__ */ p(
  "getCurrentTime",
  (e) => W("getCurrentTime", {}, e).then((t) => ne(
    fe(vo(), vn(), Mo((o) => new Date(o * 1e3)), Ao()),
    t
  )),
  { isSupported: "web_app_invoke_custom_method" }
), bo = "web_app_read_text_from_clipboard", Dl = /* @__PURE__ */ p(
  "readTextFromClipboard",
  (e) => {
    const t = Po();
    return d(bo, "clipboard_text_received", {
      ...e,
      params: { req_id: t },
      capture: fn(t)
    }).then(({ data: o = null }) => o);
  },
  { isSupported: bo }
);
function Su(e) {
  const t = {}, o = e.match(/Telegram-Android(?:\/([^ ]+))?(?: (\([^)]+\))?|$)/);
  if (o) {
    const [, s, n] = o;
    s && (t.appVersion = s), n && n.slice(1, n.length - 1).split(";").forEach((r) => {
      const [a, l] = r.trim().split(" ");
      if (a === "Android")
        t.androidVersion = l;
      else if (a === "SDK") {
        const P = parseInt(l, 10);
        P && (t.sdkVersion = P);
      } else l ? (t.manufacturer = a, t.model = l) : t.performanceClass = a;
    });
  }
  return t;
}
function Hl() {
  return Su(navigator.userAgent);
}
const go = "web_app_data_send", Ll = /* @__PURE__ */ p(
  "sendData",
  (e) => {
    const { size: t } = new Blob([e]);
    if (!t || t > 4096)
      throw new y(t ? "Maximum size of data to send is 4096 bytes" : "Attempted to send empty data");
    i(go, { data: e });
  },
  { isSupported: go }
), So = "web_app_send_prepared_message", Rl = /* @__PURE__ */ p(
  "shareMessage",
  (e, t) => d(So, ["prepared_message_failed", "prepared_message_sent"], {
    ...t,
    params: { id: e }
  }).then((o) => {
    if (o && "error" in o)
      throw new Vn(o.error);
  }),
  { isSupported: So }
), Eo = "web_app_share_to_story", jl = /* @__PURE__ */ p(
  "shareStory",
  (e, t) => {
    t || (t = {}), i(Eo, {
      text: t.text,
      media_url: e,
      widget_link: t.widgetLink
    });
  },
  { isSupported: Eo }
), Eu = "web_app_switch_inline_query", Fl = /* @__PURE__ */ p(
  "switchInlineQuery",
  (e, t) => {
    i(Eu, {
      query: e,
      chat_types: t || []
    });
  },
  {
    isSupported() {
      return le().tgWebAppBotInline ? void 0 : "The application must be launched in the inline mode";
    }
  }
);
function Ul(e) {
  try {
    return [!0, e()];
  } catch (t) {
    return [!1, t];
  }
}
function Gl(e) {
  Tn(e);
  const [t, o] = tt(
    m("reload_iframe", () => {
      Qe().log("Received a request to reload the page"), i("iframe_will_reload"), window.location.reload();
    })
  ), { acceptCustomStyles: s = !0 } = e || {};
  if (s) {
    const n = document.createElement("style");
    n.id = "telegram-custom-styles", document.head.appendChild(n), t(
      m("set_custom_style", (r) => {
        n.innerHTML = r;
      }),
      () => {
        document.head.removeChild(n);
      }
    );
  }
  return i("iframe_ready", { reload_supported: !0 }), Qe().log("The package was initialized"), o;
}
export {
  Ql as AbortablePromise,
  ko as AccessDeniedError,
  ot as CSSVarsBoundError,
  Kl as CancelledError,
  kn as ConcurrentCallError,
  In as FullscreenFailedError,
  Z as FunctionUnavailableError,
  y as InvalidArgumentsError,
  Ou as InvalidEnvError,
  Yl as InvalidLaunchParamsError,
  Xl as InvokeCustomMethodError,
  Zl as LaunchParamsRetrieveError,
  Jl as ManualPromise,
  ep as MethodParameterUnsupportedError,
  tp as MethodUnsupportedError,
  To as NotAvailableError,
  On as SetEmojiStatusError,
  Vn as ShareMessageError,
  op as TimeoutError,
  sp as UnknownEnvError,
  st as UnknownThemeParamsKeyError,
  bl as addToHomeScreen,
  np as applyPolyfills,
  rr as authenticateBiometry,
  ju as backButton,
  _i as bindMiniAppCssVars,
  ei as bindThemeParamsCssVars,
  Nc as bindViewportCssVars,
  Fu as biometry,
  ir as biometryAuthError,
  Lo as biometryAuthPromise,
  Jn as biometryMountError,
  Un as biometryState,
  rp as bridgeLogger,
  Fc as changeFullscreenError,
  Rc as changeFullscreenPromise,
  gl as checkHomeScreenStatus,
  Cl as checkHomeScreenStatusError,
  Sl as checkHomeScreenStatusPromise,
  fi as closeMiniApp,
  qi as closeQrScanner,
  Uu as closingBehavior,
  Gu as cloudStorage,
  Tn as configure,
  ql as copyTextToClipboard,
  Ip as createLogger,
  ap as createPostEvent,
  Po as createRequestId,
  ip as createStartParam,
  cp as decodeBase64Url,
  up as decodeStartParam,
  Go as deleteCloudStorageItem,
  Sr as disableClosingConfirmation,
  gc as disableVerticalSwipes,
  xl as downloadFile,
  lp as emitEvent,
  Er as enableClosingConfirmation,
  Sc as enableVerticalSwipes,
  pp as encodeBase64Url,
  Gc as exitFullscreen,
  Dc as expandViewport,
  Ar as getCloudStorageItem,
  zo as getCloudStorageKeys,
  Nl as getCurrentTime,
  zu as hapticFeedback,
  Pr as hapticFeedbackImpactOccurred,
  Tr as hapticFeedbackNotificationOccurred,
  kr as hapticFeedbackSelectionChanged,
  Dn as hideBackButton,
  cc as hideSettingsButton,
  Vo as ignoreCanceled,
  Gl as init,
  Wu as initData,
  Qo as initDataAuthDate,
  Ko as initDataCanSendAfter,
  Ir as initDataCanSendAfterDate,
  Vr as initDataChat,
  xr as initDataChatInstance,
  qr as initDataChatType,
  Nr as initDataHash,
  Dr as initDataQueryId,
  Lr as initDataRaw,
  Rr as initDataReceiver,
  Fr as initDataStartParam,
  Or as initDataState,
  Ur as initDataUser,
  Qu as invoice,
  W as invokeCustomMethod,
  Du as isAccessDeniedError,
  ar as isAuthenticatingBiometry,
  xn as isBackButtonMounted,
  Nn as isBackButtonSupported,
  qn as isBackButtonVisible,
  Gn as isBiometryAvailable,
  tr as isBiometryMounted,
  Zn as isBiometryMounting,
  Wn as isBiometrySupported,
  Tu as isCSSVarsBoundError,
  dp as isCancelledError,
  El as isCheckingHomeScreenStatus,
  jo as isClosingBehaviorMounted,
  br as isClosingConfirmationEnabled,
  $r as isCloudStorageSupported,
  Jo as isColorDark,
  xu as isConcurrentCallError,
  Ks as isFullscreen,
  Hu as isFullscreenFailedError,
  Vu as isFunctionNotAvailableError,
  Br as isHapticFeedbackSupported,
  qu as isInvalidArguments,
  Iu as isInvalidEnvError,
  mp as isInvalidLaunchParamsError,
  Jr as isInvoiceOpened,
  zr as isInvoiceSupported,
  _p as isInvokeCustomMethodError,
  fp as isLaunchParamsRetrieveError,
  sa as isLocationManagerAccessGranted,
  na as isLocationManagerAccessRequested,
  oa as isLocationManagerAvailable,
  fa as isLocationManagerMounted,
  da as isLocationManagerMounting,
  ta as isLocationManagerSupported,
  Ha as isMainButtonEnabled,
  La as isMainButtonLoaderVisible,
  ss as isMainButtonMounted,
  Ra as isMainButtonVisible,
  hp as isMethodMethodParameterUnsupportedError,
  bp as isMethodUnsupportedError,
  li as isMiniAppActive,
  ci as isMiniAppCssVarsBound,
  ui as isMiniAppDark,
  Si as isMiniAppMounted,
  bi as isMiniAppMounting,
  pi as isMiniAppSupported,
  ku as isNotAvailableError,
  yi as isPopupOpened,
  ki as isPopupShown,
  Mi as isPopupSupported,
  ji as isQrScannerOpened,
  xi as isQrScannerSupported,
  qp as isRGB,
  xp as isRGBShort,
  mr as isRequestingBiometryAccess,
  Pl as isRequestingContact,
  il as isRequestingEmojiStatusAccess,
  Ea as isRequestingLocation,
  Al as isRequestingPhoneAccess,
  Il as isRequestingWriteAccess,
  so as isSSR,
  gp as isSafeToCreateStartParam,
  zi as isSecondaryButtonEnabled,
  Wi as isSecondaryButtonLoaderVisible,
  As as isSecondaryButtonMounted,
  Ji as isSecondaryButtonSupported,
  Qi as isSecondaryButtonVisible,
  Nu as isSetEmojiStatusError,
  pl as isSettingEmojiStatus,
  ac as isSettingsButtonMounted,
  ic as isSettingsButtonSupported,
  rc as isSettingsButtonVisible,
  Lu as isShareMessageError,
  _c as isSwipeBehaviorMounted,
  fc as isSwipeBehaviorSupported,
  Sp as isTMA,
  Ma as isThemeParamsCssVarsBound,
  Ta as isThemeParamsDark,
  si as isThemeParamsMounted,
  ti as isThemeParamsMounting,
  Ep as isTimeoutError,
  Cp as isUnknownEnvError,
  Ru as isUnknownThemeParamsKeyError,
  hc as isVerticalSwipesEnabled,
  xc as isViewportCssVarsBound,
  wc as isViewportExpanded,
  Ic as isViewportMounted,
  kc as isViewportMounting,
  $c as isViewportStable,
  Ku as locationManager,
  ma as locationManagerMountError,
  pa as locationManagerMountPromise,
  Yu as mainButton,
  Na as mainButtonBackgroundColor,
  Da as mainButtonHasShineEffect,
  bt as mainButtonState,
  ja as mainButtonText,
  Fa as mainButtonTextColor,
  Zu as miniApp,
  ri as miniAppBackgroundColor,
  $t as miniAppBackgroundColorRGB,
  ai as miniAppBottomBarColor,
  Mt as miniAppBottomBarColorRGB,
  ii as miniAppHeaderColor,
  ds as miniAppHeaderColorRGB,
  gi as miniAppMountError,
  gs as miniAppMountPromise,
  Ci as miniAppReady,
  ms as miniAppState,
  wp as mockTelegramEnv,
  Hn as mountBackButton,
  Xn as mountBiometry,
  Ho as mountBiometryPromise,
  Cr as mountClosingBehavior,
  la as mountLocationManager,
  za as mountMainButton,
  hi as mountMiniApp,
  Ei as mountMiniAppSync,
  ec as mountSecondaryButton,
  uc as mountSettingsButton,
  Ec as mountSwipeBehavior,
  cs as mountThemeParams,
  ls as mountThemeParamsSync,
  Tc as mountViewport,
  $p as off,
  _l as offAddToHomeScreenFailed,
  hl as offAddedToHomeScreen,
  Rn as offBackButtonClick,
  Qa as offMainButtonClick,
  oc as offSecondaryButtonClick,
  pc as offSettingsButtonClick,
  Mp as on,
  ml as onAddToHomeScreenFailed,
  fl as onAddedToHomeScreen,
  Ln as onBackButtonClick,
  Wa as onMainButtonClick,
  tc as onSecondaryButtonClick,
  lc as onSettingsButtonClick,
  cr as openBiometrySettings,
  Xr as openInvoice,
  ea as openInvoiceError,
  Zr as openInvoicePromise,
  wl as openLink,
  wa as openLocationManagerSettings,
  Ai as openPopup,
  Bi as openPopupError,
  vi as openPopupPromise,
  Ri as openQrScanner,
  Fi as openQrScannerError,
  Ms as openQrScannerPromise,
  nu as openTelegramLink,
  Np as parseInitDataQuery,
  Dp as parseLaunchParamsQuery,
  Ju as popup,
  i as postEvent,
  Ap as postMessage,
  vp as postMessageImplementation,
  el as qrScanner,
  Dl as readTextFromClipboard,
  d as request,
  zn as requestBiometry,
  dr as requestBiometryAccess,
  _r as requestBiometryAccessError,
  Ro as requestBiometryAccessPromise,
  yl as requestContact,
  _u as requestContactComplete,
  Tl as requestContactError,
  Bl as requestContactPromise,
  lo as requestContentSafeAreaInsets,
  rl as requestEmojiStatusAccess,
  cl as requestEmojiStatusAccessError,
  al as requestEmojiStatusAccessPromise,
  Uc as requestFullscreen,
  Sa as requestLocation,
  Ca as requestLocationError,
  Zo as requestLocationPromise,
  lu as requestPhoneAccess,
  vl as requestPhoneAccessError,
  Ml as requestPhoneAccessPromise,
  po as requestSafeAreaInsets,
  Ac as requestViewport,
  kl as requestWriteAccess,
  Vl as requestWriteAccessError,
  Ol as requestWriteAccessPromise,
  jr as restoreInitData,
  Hl as retrieveAndroidDeviceData,
  Su as retrieveAndroidDeviceDataFrom,
  yp as retrieveLaunchParams,
  Bp as retrieveRawInitData,
  Pp as retrieveRawLaunchParams,
  Ul as safeCall,
  Qe as sdkLogger,
  tl as secondaryButton,
  Ui as secondaryButtonBackgroundColor,
  Gi as secondaryButtonHasShineEffect,
  Ki as secondaryButtonPosition,
  qt as secondaryButtonState,
  Yi as secondaryButtonText,
  Xi as secondaryButtonTextColor,
  Ll as sendData,
  Hp as serializeInitDataQuery,
  Lp as serializeLaunchParamsQuery,
  Rp as serializeToQuery,
  vr as setCloudStorageItem,
  Pu as setDebug,
  ul as setEmojiStatus,
  dl as setEmojiStatusError,
  ll as setEmojiStatusPromise,
  Ka as setMainButtonParams,
  Pt as setMiniAppBackgroundColor,
  Tt as setMiniAppBottomBarColor,
  kt as setMiniAppHeaderColor,
  sc as setSecondaryButtonParams,
  ol as settingsButton,
  Rl as shareMessage,
  jl as shareStory,
  $l as shareURL,
  jn as showBackButton,
  Pi as showPopup,
  Oi as showPopupError,
  Ti as showPopupPromise,
  dc as showSettingsButton,
  Tp as supports,
  sl as swipeBehavior,
  Fl as switchInlineQuery,
  kp as targetOrigin,
  Xu as themeParams,
  Aa as themeParamsAccentTextColor,
  es as themeParamsBackgroundColor,
  va as themeParamsBottomBarBgColor,
  ht as themeParamsButtonColor,
  ts as themeParamsButtonTextColor,
  ya as themeParamsDestructiveTextColor,
  Ba as themeParamsHeaderBackgroundColor,
  Pa as themeParamsHintColor,
  ka as themeParamsLinkColor,
  oi as themeParamsMountError,
  us as themeParamsMountPromise,
  os as themeParamsSecondaryBackgroundColor,
  Oa as themeParamsSectionBackgroundColor,
  Ia as themeParamsSectionHeaderTextColor,
  Va as themeParamsSectionSeparatorColor,
  K as themeParamsState,
  qa as themeParamsSubtitleTextColor,
  xa as themeParamsTextColor,
  jp as toRGB,
  Fp as transformQueryUsing,
  Fn as unmountBackButton,
  fr as unmountBiometry,
  wr as unmountClosingBehavior,
  $a as unmountLocationManager,
  Ya as unmountMainButton,
  wi as unmountMiniApp,
  nc as unmountSecondaryButton,
  mc as unmountSettingsButton,
  Cc as unmountSwipeBehavior,
  ni as unmountThemeParams,
  Vc as unmountViewport,
  hr as updateBiometryToken,
  nl as viewport,
  Is as viewportContentSafeAreaInsetBottom,
  Vs as viewportContentSafeAreaInsetLeft,
  qs as viewportContentSafeAreaInsetRight,
  xs as viewportContentSafeAreaInsetTop,
  zt as viewportContentSafeAreaInsets,
  Ut as viewportHeight,
  Oc as viewportMountError,
  Ws as viewportMountPromise,
  Ns as viewportSafeAreaInsetBottom,
  Ds as viewportSafeAreaInsetLeft,
  Hs as viewportSafeAreaInsetRight,
  Ls as viewportSafeAreaInsetTop,
  Wt as viewportSafeAreaInsets,
  Gt as viewportStableHeight,
  ks as viewportState,
  Os as viewportWidth,
  p as wrapSafe
};
//# sourceMappingURL=index.js.map