Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@telegram-apps/sdk

Package Overview
Dependencies
Maintainers
0
Versions
28
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@telegram-apps/sdk - npm Package Compare versions

Comparing version 2.6.2 to 2.7.0

dist/dts/scopes/components/full-screen/exports.d.ts

13

dist/dts/classnames/mergeClassNames.d.ts

@@ -1,8 +0,2 @@

type UnionStringKeys<U> = U extends U ? {
[K in keyof U]-?: U[K] extends string | undefined ? K : never;
}[keyof U] : never;
type UnionRequiredKeys<U> = U extends U ? {
[K in UnionStringKeys<U>]: ({} extends Pick<U, K> ? never : K);
}[UnionStringKeys<U>] : never;
type UnionOptionalKeys<U> = Exclude<UnionStringKeys<U>, UnionRequiredKeys<U>>;
import { UnionRequiredKeys, UnionOptionalKeys } from '@telegram-apps/toolkit';
export type MergeClassNames<Tuple extends any[]> = Exclude<Tuple[number], number | string | null | undefined | any[] | boolean> extends infer Union ? {

@@ -16,4 +10,4 @@ [K in UnionRequiredKeys<Union>]: string;

*
* The function expects to pass an array of objects with values that could be passed to
* the `classNames` function.
* The function expects to pass an array of objects with values that could be
* passed to the `classNames` function.
* @returns An object with keys from all objects with merged values.

@@ -23,2 +17,1 @@ * @see classNames

export declare function mergeClassNames<T extends any[]>(...partials: T): MergeClassNames<T>;
export {};

@@ -14,1 +14,2 @@ export declare const ERR_POPUP_INVALID_PARAMS = "ERR_POPUP_INVALID_PARAMS";

export declare const ERR_NOT_MOUNTED = "ERR_NOT_MOUNTED";
export declare const ERR_FULLSCREEN_FAILED = "ERR_FULLSCREEN_FAILED";

@@ -7,2 +7,3 @@ export { classNames } from './classnames/classNames.js';

export * from './scopes/components/cloud-storage/exports.js';
export * from './scopes/components/full-screen/exports.js';
export * from './scopes/components/haptic-feedback/exports.js';

@@ -27,6 +28,6 @@ export * from './scopes/components/init-data/exports.js';

export { safeCall } from './utils/safeCall.js';
export { ERR_POPUP_INVALID_PARAMS, ERR_INVALID_URL, ERR_INVALID_SLUG, ERR_ACCESS_DENIED, ERR_DATA_INVALID_SIZE, ERR_NOT_AVAILABLE, ERR_NOT_SUPPORTED, ERR_NOT_MOUNTED, ERR_NOT_INITIALIZED, ERR_ALREADY_OPENED, ERR_CSS_VARS_ALREADY_BOUND, ERR_ALREADY_MOUNTING, ERR_ALREADY_REQUESTING } from './errors.js';
export { ERR_POPUP_INVALID_PARAMS, ERR_INVALID_URL, ERR_INVALID_SLUG, ERR_ACCESS_DENIED, ERR_DATA_INVALID_SIZE, ERR_NOT_AVAILABLE, ERR_NOT_SUPPORTED, ERR_NOT_MOUNTED, ERR_NOT_INITIALIZED, ERR_ALREADY_OPENED, ERR_CSS_VARS_ALREADY_BOUND, ERR_ALREADY_MOUNTING, ERR_ALREADY_REQUESTING, ERR_FULLSCREEN_FAILED, } from './errors.js';
export { init, type InitOptions } from './init.js';
export { CancelablePromise, defineEventHandlers, emitMiniAppsEvent, isIframe, removeEventHandlers, compareVersions, createPostEvent, $debug, ERR_CANCELED, ERR_ABORTED, ERR_METHOD_PARAMETER_UNSUPPORTED, ERR_METHOD_UNSUPPORTED, ERR_TIMED_OUT, ERR_UNKNOWN_ENV, ERR_RETRIEVE_LP_FAILED, ERR_CUSTOM_METHOD_ERR_RESPONSE, invokeCustomMethod, isTMA, on, off, postEvent, $targetOrigin, request, subscribe, supports, unsubscribe, mockTelegramEnv, deleteCssVar, setCssVar, isAbortError, isTimeoutError, isCanceledError, addEventListener, retrieveLaunchParams, TypedError, } from '@telegram-apps/bridge';
export type { AsyncOptions, AnyHapticFeedbackParams, AnyInvokeCustomMethodParams, BottomBarColor, BiometryAuthRequestStatus, BiometryTokenUpdateStatus, BiometryType, Chat, ChatType, CustomMethodName, CustomMethodParams, CustomMethodsParams, EventListener, EventName, EventPayload, Events, ExecuteWithOptions, ExecuteWithPostEvent, HeaderColorKey, ImpactHapticFeedbackParams, ImpactHapticFeedbackStyle, InvoiceStatus, LaunchParams, MethodName, MethodNameWithOptionalParams, MethodNameWithoutParams, MethodNameWithRequiredParams, MethodNameWithVersionedParams, MethodParams, Methods, MethodVersionedParams, NotificationHapticFeedbackParams, NotificationHapticFeedbackType, OpenLinkBrowser, OnUnsupportedFn, PhoneRequestedStatus, Platform, PopupButton, PopupParams, PostEventFn, RequestCaptureEventFn, RequestCaptureEventsFn, RGB, RGBShort, SelectionHapticFeedbackParams, SwitchInlineQueryChatType, ThemeParamsKey, User, Version, WriteAccessRequestedStatus, CreatePostEventMode, RequestBasicOptions, RequestCaptureFn, RequestFn, RequestResult, SubscribeListener, TypedErrorOptions, } from '@telegram-apps/bridge';
export type { AsyncOptions, AnyHapticFeedbackParams, AnyInvokeCustomMethodParams, BottomBarColor, BiometryAuthRequestStatus, BiometryTokenUpdateStatus, BiometryType, Chat, ChatType, CustomMethodName, CustomMethodParams, CustomMethodsParams, EventListener, EventName, EventPayload, Events, ExecuteWithOptions, ExecuteWithPostEvent, FullScreenErrorStatus, HeaderColorKey, ImpactHapticFeedbackParams, ImpactHapticFeedbackStyle, InvoiceStatus, LaunchParams, MethodName, MethodNameWithOptionalParams, MethodNameWithoutParams, MethodNameWithRequiredParams, MethodNameWithVersionedParams, MethodParams, Methods, MethodVersionedParams, NotificationHapticFeedbackParams, NotificationHapticFeedbackType, OpenLinkBrowser, OnUnsupportedFn, PhoneRequestedStatus, Platform, PopupButton, PopupParams, PostEventFn, RequestCaptureEventFn, RequestCaptureEventsFn, RGB, RGBShort, SelectionHapticFeedbackParams, SwitchInlineQueryChatType, ThemeParamsKey, User, Version, WriteAccessRequestedStatus, CreatePostEventMode, RequestBasicOptions, RequestCaptureFn, RequestFn, RequestResult, SubscribeListener, TypedErrorOptions, } from '@telegram-apps/bridge';
export { isRGB, isRGBShort, isRecord, toRecord, toRGB, ERR_UNEXPECTED_VALUE, ERR_PARSE, ERR_INVALID_VALUE, ERR_UNEXPECTED_TYPE, serializeLaunchParams, serializeThemeParams, } from '@telegram-apps/transformers';

@@ -55,3 +55,3 @@ import { EventListener } from '@telegram-apps/bridge';

*/
export declare const onClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<'back_button_pressed'>) => VoidFunction, true, never>;
export declare const onClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<"back_button_pressed">) => VoidFunction, true, never>;
/**

@@ -73,3 +73,3 @@ * Removes the Back Button click listener.

*/
export declare const offClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<'back_button_pressed'>) => void, true, never>;
export declare const offClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<"back_button_pressed">) => void, true, never>;
/**

@@ -76,0 +76,0 @@ * Shows the Back Button.

import { CancelablePromise, BiometryTokenUpdateStatus, BiometryAuthRequestStatus } from '@telegram-apps/bridge';
import { AuthenticateOptions, RequestAccessOptions, UpdateTokenOptions } from './types.js';
import { State, AuthenticateOptions, RequestAccessOptions, UpdateTokenOptions } from './types.js';
/**

@@ -80,3 +80,3 @@ * @returns True if the biometry manager is supported.

*/
export declare const mount: import('../../toolkit/wrapSafe.js').SafeWrapped<(options?: import('@telegram-apps/bridge').AsyncOptions | undefined) => CancelablePromise<void>, false, never>;
export declare const mount: import('../../toolkit/wrapSafe.js').SafeWrapped<(options?: import('@telegram-apps/bridge').AsyncOptions) => CancelablePromise<State>, false, never>;
/**

@@ -83,0 +83,0 @@ * Unmounts the component.

@@ -0,1 +1,2 @@

import { CancelablePromise } from '@telegram-apps/toolkit';
import { State } from './types.js';

@@ -5,3 +6,3 @@ /**

*/
export declare const state: import('@telegram-apps/signals').Signal<State | undefined>;
export declare const state: import('@telegram-apps/signals').Signal<State>;
/**

@@ -16,16 +17,20 @@ * True if the manager is currently authenticating.

/**
* True if the component is currently mounted.
* Signal indicating if the component is currently mounted.
*/
export declare const isMounted: import('@telegram-apps/signals').Signal<boolean>;
/**
* True if the component is currently mounting.
* Signal indicating if the component is currently mounting.
*/
export declare const isMounting: import('@telegram-apps/signals').Signal<boolean>;
export declare const isMounting: import('@telegram-apps/signals').Computed<boolean>;
/**
* Error occurred while mounting the component.
* Signal containing the error occurred during mount.
*/
export declare const mountError: import('@telegram-apps/signals').Signal<Error | undefined>;
/**
* Signal containing the mount process promise.
*/
export declare const mountPromise: import('@telegram-apps/signals').Signal<CancelablePromise<State> | undefined>;
/**
* Signal indicating biometry is available.
*/
export declare const isAvailable: import('@telegram-apps/signals').Computed<boolean | undefined>;
export declare const isAvailable: import('@telegram-apps/signals').Computed<boolean>;

@@ -27,3 +27,3 @@ import { EventListener } from '@telegram-apps/bridge';

*/
export declare const onClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<'main_button_pressed'>) => VoidFunction, false, never>;
export declare const onClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<"main_button_pressed">) => VoidFunction, false, never>;
/**

@@ -43,3 +43,3 @@ * Removes the Main Button click listener.

*/
export declare const offClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<'main_button_pressed'>) => void, false, never>;
export declare const offClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<"main_button_pressed">) => void, false, never>;
/**

@@ -46,0 +46,0 @@ * Updates the Main Button state.

@@ -33,3 +33,3 @@ import { EventListener } from '@telegram-apps/bridge';

*/
export declare const onClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<'secondary_button_pressed'>) => VoidFunction, true, never>;
export declare const onClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<"secondary_button_pressed">) => VoidFunction, true, never>;
/**

@@ -50,3 +50,3 @@ * Removes the Secondary Button click listener.

*/
export declare const offClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<'secondary_button_pressed'>) => void, true, never>;
export declare const offClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<"secondary_button_pressed">) => void, true, never>;
/**

@@ -53,0 +53,0 @@ * Updates the Secondary Button state.

@@ -55,3 +55,3 @@ import { EventListener } from '@telegram-apps/bridge';

*/
export declare const onClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<'settings_button_pressed'>) => VoidFunction, true, never>;
export declare const onClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<"settings_button_pressed">) => VoidFunction, true, never>;
/**

@@ -73,3 +73,3 @@ * Removes the Settings Button click listener.

*/
export declare const offClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<'settings_button_pressed'>) => void, true, never>;
export declare const offClick: import('../../toolkit/wrapSafe.js').SafeWrapped<(fn: EventListener<"settings_button_pressed">) => void, true, never>;
/**

@@ -76,0 +76,0 @@ * Shows the Settings Button.

@@ -1,4 +0,4 @@

export { bindCssVars as bindViewportCssVars, expand as expandViewport, height as viewportHeight, isExpanded as isViewportExpanded, isStable as isViewportStable, isCssVarsBound as isViewportCssVarsBound, isMounting as isViewportMounting, isMounted as isViewportMounted, mount as mountViewport, mountError as viewportMountError, state as viewportState, stableHeight as viewportStableHeight, unmount as unmountViewport, width as viewportWidth, } from './exports.variable.js';
export { bindCssVars as bindViewportCssVars, expand as expandViewport, exitFullscreen, height as viewportHeight, isExpanded as isViewportExpanded, isStable as isViewportStable, isCssVarsBound as isViewportCssVarsBound, isChangingFullscreen, isFullscreen, isMounting as isViewportMounting, isMounted as isViewportMounted, mount as mountViewport, mountError as viewportMountError, mountPromise as viewportMountPromise, requestFullscreen, changeFullscreenPromise, changeFullscreenError, state as viewportState, stableHeight as viewportStableHeight, unmount as unmountViewport, width as viewportWidth, } from './exports.variable.js';
export * as viewport from './exports.variable.js';
export { requestViewport, type RequestViewportResult } from './requestViewport.js';
export type { State as ViewportState, GetCSSVarNameFn as ViewportGetCSSVarNameFn, } from './types.js';

@@ -1,2 +0,2 @@

export * from './signals.js';
export * from './methods.js';
export { changeFullscreenError, changeFullscreenPromise, height, isMounted, isStable, isChangingFullscreen, isMounting, isExpanded, isFullscreen, isCssVarsBound, mountPromise, mountError, state, stableHeight, width, } from './signals.js';
export { bindCssVars, exitFullscreen, expand, mount, requestFullscreen, unmount, } from './methods.js';

@@ -1,7 +0,10 @@

import { GetCSSVarNameFn } from './types.js';
import { CancelablePromise, AsyncOptions } from '@telegram-apps/bridge';
import { GetCSSVarNameFn, State } from './types.js';
/**
* Creates CSS variables connected with the current viewport.
*
* By default, created CSS variables names are following the pattern "--tg-theme-{name}", where
* {name} is a theme parameters key name converted from camel case to kebab case.
* By default, created CSS variables names are following the pattern
* "--tg-theme-{name}", where
* {name} is a theme parameters key name converted from camel case to kebab
* case.
*

@@ -15,4 +18,4 @@ * Default variables:

*
* @param getCSSVarName - function, returning complete CSS variable name for the specified
* viewport property.
* @param getCSSVarName - function, returning complete CSS variable name for
* the specified viewport property.
* @returns Function to stop updating variables.

@@ -34,4 +37,5 @@ * @throws {TypedError} ERR_UNKNOWN_ENV

/**
* A method that expands the Mini App to the maximum available height. To find out if the Mini
* App is expanded to the maximum height, refer to the value of the `isExpanded`.
* A method that expands the Mini App to the maximum available height. To find
* out if the Mini App is expanded to the maximum height, refer to the value of
* the `isExpanded`.
* @throws {TypedError} ERR_UNKNOWN_ENV

@@ -56,6 +60,48 @@ * @throws {TypedError} ERR_NOT_INITIALIZED

*/
export declare const mount: import('../../toolkit/wrapSafe.js').SafeWrapped<(options?: import('@telegram-apps/bridge').AsyncOptions | undefined) => import('@telegram-apps/bridge').CancelablePromise<void>, false, never>;
export declare const mount: import('../../toolkit/wrapSafe.js').SafeWrapped<(options?: AsyncOptions) => CancelablePromise<State | {
height: number;
isExpanded: boolean;
isFullscreen: boolean;
stableHeight: number;
width: number;
}>, false, never>;
/**
* Requests fullscreen mode for the mini application.
* @since Mini Apps v8.0
* @throws {TypedError} ERR_UNKNOWN_ENV
* @throws {TypedError} ERR_NOT_INITIALIZED
* @throws {TypedError} ERR_NOT_MOUNTED
* @throws {TypedError} ERR_NOT_SUPPORTED
* @throws {TypedError} ERR_FULLSCREEN_FAILED
* @example Using `isAvailable()`
* if (requestFullscreen.isAvailable() && !isChangingFullscreen()) {
* await requestFullscreen();
* }
* @example Using `ifAvailable()`
* if (!isChangingFullscreen()) {
* await requestFullscreen.ifAvailable();
* }
*/
export declare const requestFullscreen: import('../../toolkit/wrapSafe.js').SafeWrapped<(options?: AsyncOptions) => CancelablePromise<void>, true, never>;
/**
* Exits mini application fullscreen mode.
* @since Mini Apps v8.0
* @throws {TypedError} ERR_UNKNOWN_ENV
* @throws {TypedError} ERR_NOT_INITIALIZED
* @throws {TypedError} ERR_NOT_MOUNTED
* @throws {TypedError} ERR_NOT_SUPPORTED
* @throws {TypedError} ERR_FULLSCREEN_FAILED
* @example Using `isAvailable()`
* if (exitFullscreen.isAvailable() && !isChangingFullscreen()) {
* await exitFullscreen();
* }
* @example Using `ifAvailable()`
* if (!isChangingFullscreen()) {
* await exitFullscreen.ifAvailable();
* }
*/
export declare const exitFullscreen: import('../../toolkit/wrapSafe.js').SafeWrapped<(options?: AsyncOptions) => CancelablePromise<void>, true, never>;
/**
* Unmounts the Viewport.
*/
export declare function unmount(): void;
import { Computed } from '@telegram-apps/signals';
import { CancelablePromise } from '@telegram-apps/toolkit';
import { State } from './types.js';

@@ -8,30 +9,34 @@ /**

/**
* True if the component is currently mounted.
* Signal indicating if the component is currently mounted.
*/
export declare const isMounted: import('@telegram-apps/signals').Signal<boolean>;
/**
* True if CSS variables are currently bound.
* Signal indicating if the component is currently mounting.
*/
export declare const isCssVarsBound: import('@telegram-apps/signals').Signal<boolean>;
export declare const isMounting: Computed<boolean>;
/**
* True if the component is currently mounting.
* Signal containing the error occurred during mount.
*/
export declare const isMounting: import('@telegram-apps/signals').Signal<boolean>;
export declare const mountError: import('@telegram-apps/signals').Signal<Error | undefined>;
/**
* Error occurred while mounting the component.
* Signal containing the mount process promise.
*/
export declare const mountError: import('@telegram-apps/signals').Signal<Error | undefined>;
export declare const mountPromise: import('@telegram-apps/signals').Signal<CancelablePromise<State> | undefined>;
/**
* True if CSS variables are currently bound.
*/
export declare const isCssVarsBound: import('@telegram-apps/signals').Signal<boolean>;
/**
* The current height of the **visible area** of the Mini App.
*
* The application can display just the top part of the Mini App, with its lower part remaining
* outside the screen area. From this position, the user can "pull" the Mini App to its
* maximum height, while the bot can do the same by calling `expand` method. As the position of
* the Mini App changes, the current height value of the visible area will be updated in real
* time.
* The application can display just the top part of the Mini App, with its
* lower part remaining outside the screen area. From this position, the user
* can "pull" the Mini App to its maximum height, while the bot can do the same
* by calling `expand` method. As the position of the Mini App changes, the
* current height value of the visible area will be updated in real time.
*
* Please note that the refresh rate of this value is not sufficient to smoothly follow the
* lower border of the window. It should not be used to pin interface elements to the bottom
* of the visible area. It's more appropriate to use the value of the `stableHeight`
* field for this purpose.
* Please note that the refresh rate of this value is not sufficient to
* smoothly follow the lower border of the window. It should not be used to pin
* interface elements to the bottom of the visible area. It's more appropriate
* to use the value of the `stableHeight` field for this purpose.
*

@@ -42,4 +47,5 @@ * @see stableHeight

/**
* True if the Mini App is expanded to the maximum available height. Otherwise, if
* the Mini App occupies part of the screen and can be expanded to the full height using
* True if the Mini App is expanded to the maximum available height. Otherwise,
* if the Mini App occupies part of the screen and can be expanded to the full
* height using
* `expand` method.

@@ -50,3 +56,4 @@ * @see expand

/**
* True if the current viewport height is stable and is not going to change in the next moment.
* True if the current viewport height is stable and is not going to change in
* the next moment.
*/

@@ -57,10 +64,11 @@ export declare const isStable: Computed<boolean>;

*
* The application can display just the top part of the Mini App, with its lower part remaining
* outside the screen area. From this position, the user can "pull" the Mini App to its
* maximum height, while the application can do the same by calling `expand` method.
* The application can display just the top part of the Mini App, with its
* lower part remaining outside the screen area. From this position, the user
* can "pull" the Mini App to its maximum height, while the application can do
* the same by calling `expand` method.
*
* Unlike the value of `height`, the value of `stableHeight` does not change as the position
* of the Mini App changes with user gestures or during animations. The value of `stableHeight`
* will be updated after all gestures and animations are completed and the Mini App reaches its
* final size.
* Unlike the value of `height`, the value of `stableHeight` does not change as
* the position of the Mini App changes with user gestures or during
* animations. The value of `stableHeight` will be updated after all gestures
* and animations are completed and the Mini App reaches its final size.
*

@@ -74,1 +82,17 @@ * @see height

export declare const width: Computed<number | undefined>;
/**
* Signal indicating if the viewport is currently in fullscreen mode.
*/
export declare const isFullscreen: Computed<boolean | undefined>;
/**
* Signal containing fullscreen request or exit promise.
*/
export declare const changeFullscreenPromise: import('@telegram-apps/signals').Signal<CancelablePromise<void> | undefined>;
/**
* Signal indicating if the fullscreen mode request is currently in progress.
*/
export declare const isChangingFullscreen: Computed<boolean>;
/**
* Signal containing an error received during the last fullscreen mode request.
*/
export declare const changeFullscreenError: import('@telegram-apps/signals').Signal<Error | undefined>;
export interface State {
height: number;
isExpanded: boolean;
isFullscreen: boolean;
stableHeight: number;

@@ -5,0 +6,0 @@ width: number;

@@ -5,13 +5,10 @@ import { Signal } from '@telegram-apps/signals';

* Creates a mount function for a component.
* @param component - the component name.
* @param mount - function mounting the component.
* @param onMounted - callback which will be called with the mount result.
* @param mountPromise - signal containing mount promise.
* @param isMounted - signal containing mount state.
* @param mountError - signal containing mount error.
* @param component - the component name
* @param mount - function mounting the component
* @param onMounted - function that will be called whenever mount was completed.
* @param isMounted - signal containing the current mount completion state
* @param data - signal containing the current mount state
* @param promise - signal containing the mount promise
* @param error - signal containing the mount error
*/
export declare function createMountFn<T = void>(component: string, mount: (options: AsyncOptions) => (T | CancelablePromise<T>), onMounted: (result: T) => void, { isMounting, isMounted, mountError, }: {
isMounted: Signal<boolean>;
isMounting: Signal<boolean>;
mountError: Signal<Error | undefined>;
}): (options?: AsyncOptions) => CancelablePromise<void>;
export declare function createMountFn<R>(component: string, mount: (options?: AsyncOptions) => R | CancelablePromise<R>, onMounted: (result: R) => void, isMounted: Signal<boolean>, data: Signal<R>, promise: Signal<CancelablePromise<R> | undefined>, error: Signal<Error | undefined>): (options?: AsyncOptions) => CancelablePromise<R>;

@@ -1,2 +0,2 @@

import { postEvent as _postEvent, request as _request, PostEventFn, Version, CancelablePromise, ExecuteWithOptions, CustomMethodParams, CustomMethodName } from '@telegram-apps/bridge';
import { postEvent as _postEvent, PostEventFn, Version, RequestFn, CancelablePromise, ExecuteWithOptions, CustomMethodParams, CustomMethodName } from '@telegram-apps/bridge';
export interface ConfigureOptions {

@@ -64,6 +64,6 @@ /**

*/
export declare const request: typeof _request;
export declare const request: RequestFn;
/**
* Shortcut for $postEvent call.
*/
export declare const postEvent: typeof _postEvent;
export declare const postEvent: PostEventFn;

@@ -1,5 +0,5 @@

this.telegramApps=this.telegramApps||{};this.telegramApps.sdk=function(o){"use strict";let he=class Es extends Error{constructor(t,n,i){super(typeof n=="object"?n.message:n||t,{cause:typeof n=="object"?n.cause:i}),this.type=t,Object.setPrototypeOf(this,Es.prototype)}};function Ln(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Ss(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}const Un="ERR_INVALID_VALUE",jn="ERR_UNEXPECTED_VALUE",qn="ERR_UNEXPECTED_TYPE",Ot="ERR_PARSE";function Hn(e,t){const n={};for(const i in e){const r=e[i];if(!r)continue;let s,a;typeof r=="function"?(s=i,a=r):[s,a]=r;try{const c=a(t(s));c!==void 0&&(n[i]=c)}catch(c){throw new he(Ot,`Parser for "${i}" property failed${s===i?"":`. Source field: "${s}"`}`,c)}}return n}function Bt(e){let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new he(Un,{cause:n})}if(typeof t!="object"||!t||Array.isArray(t))throw new he(jn);return t}function U(e,t){return n=>{const i=r=>{if(!(n&&r===void 0))try{return t(r)}catch(s){throw new he(Ot,{message:`"${e}" transformer failed to parse the value`,cause:s})}};return Object.assign(i,{isValid(r){try{return i(r),!0}catch{return!1}}})}}function Ue(e,t){return U(t||"object",n=>{const i=Bt(n);return Hn(e,r=>i[r])})}function be(e){throw new he(qn,`Unexpected value received: ${JSON.stringify(e)}`)}const Cs=U("boolean",e=>{if(typeof e=="boolean")return e;const t=String(e);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;be(e)}),j=U("string",e=>{if(typeof e=="string"||typeof e=="number")return e.toString();be(e)}),je=U("number",e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}be(e)}),Mt=U("date",e=>e instanceof Date?e:new Date(je()(e)*1e3));function Wn(e,t){return U(t||"searchParams",n=>{typeof n!="string"&&!(n instanceof URLSearchParams)&&be(n);const i=typeof n=="string"?new URLSearchParams(n):n;return Hn(e,r=>{const s=i.get(r);return s===null?void 0:s})})}function Dt(e){for(const t in e)e[t]=[Ln(t),e[t]];return e}const $s=e=>{const t=je(),n=je(!0),i=j(),r=j(!0),s=Cs(!0),a=Ue(Dt({addedToAttachmentMenu:s,allowsWriteToPm:s,firstName:i,id:t,isBot:s,isPremium:s,languageCode:r,lastName:r,photoUrl:r,username:r}),"User")(!0);return Wn(Dt({authDate:Mt(),canSendAfter:n,chat:Ue(Dt({id:t,type:i,title:i,photoUrl:r,username:r}),"Chat")(!0),chatInstance:r,chatType:r,hash:i,queryId:r,receiver:a,startParam:r,user:a}),"initData")(e)};function K(e){return/^#[\da-f]{6}$/i.test(e)}function Gn(e){return/^#[\da-f]{3}$/i.test(e)}function Nt(e){const t=e.replace(/\s/g,"").toLowerCase();if(K(t))return t;if(Gn(t)){let i="#";for(let r=0;r<3;r+=1)i+=t[1+r].repeat(2);return i}const n=t.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||t.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(!n)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return n.slice(1).reduce((i,r)=>{const s=parseInt(r,10).toString(16);return i+(s.length===1?"0":"")+s},"#")}const As=U("rgb",e=>Nt(j()(e))),vs=U("themeParams",e=>{const t=As(!0);return Object.entries(Bt(e)).reduce((n,[i,r])=>(n[Ss(i)]=t(r),n),{})});function zn(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,n])=>[Ln(t),n])))}function Rs(e){const{initDataRaw:t,startParam:n,showSettings:i,botInline:r}=e,s=new URLSearchParams;return s.set("tgWebAppPlatform",e.platform),s.set("tgWebAppThemeParams",zn(e.themeParams)),s.set("tgWebAppVersion",e.version),t&&s.set("tgWebAppData",t),n&&s.set("tgWebAppStartParam",n),typeof i=="boolean"&&s.set("tgWebAppShowSettings",i?"1":"0"),typeof r=="boolean"&&s.set("tgWebAppBotInline",r?"1":"0"),s.toString()}function Ts(e,t){return U("array",n=>{let i;if(Array.isArray(n))i=n;else if(typeof n=="string")try{const r=JSON.parse(n);Array.isArray(r)&&(i=r)}catch{}return i||be(n),i.map(e)})}function It(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function qe(...e){return e.map(t=>{if(typeof t=="string")return t;if(It(t))return qe(Object.entries(t).map(n=>n[1]&&n[0]));if(Array.isArray(t))return qe(...t)}).filter(Boolean).join(" ")}function Ps(...e){return e.reduce((t,n)=>(It(n)&&Object.entries(n).forEach(([i,r])=>{const s=qe(t[i],r);s&&(t[i]=s)}),t),{})}let ge=class ws extends Error{constructor(t,n,i){super(typeof n=="object"?n.message:n||t,{cause:typeof n=="object"?n.cause:i}),this.type=t,Object.setPrototypeOf(this,ws.prototype)}};function Fn(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Os(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}const Bs="ERR_INVALID_VALUE",Ms="ERR_UNEXPECTED_VALUE",Ds="ERR_UNEXPECTED_TYPE",Qn="ERR_PARSE";function Yn(e,t){const n={};for(const i in e){const r=e[i];if(!r)continue;let s,a;typeof r=="function"?(s=i,a=r):[s,a]=r;try{const c=a(t(s));c!==void 0&&(n[i]=c)}catch(c){throw new ge(Qn,`Parser for "${i}" property failed${s===i?"":`. Source field: "${s}"`}`,c)}}return n}function Jn(e){let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new ge(Bs,{cause:n})}if(typeof t!="object"||!t||Array.isArray(t))throw new ge(Ms);return t}function B(e,t){return n=>{const i=r=>{if(!(n&&r===void 0))try{return t(r)}catch(s){throw new ge(Qn,{message:`"${e}" transformer failed to parse the value`,cause:s})}};return Object.assign(i,{isValid(r){try{return i(r),!0}catch{return!1}}})}}function M(e,t){return B(t||"object",n=>{const i=Jn(n);return Yn(e,r=>i[r])})}function Ee(e){throw new ge(Ds,`Unexpected value received: ${JSON.stringify(e)}`)}const He=B("boolean",e=>{if(typeof e=="boolean")return e;const t=String(e);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;Ee(e)}),A=B("string",e=>{if(typeof e=="string"||typeof e=="number")return e.toString();Ee(e)}),we=B("number",e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}Ee(e)}),Ns=B("date",e=>e instanceof Date?e:new Date(we()(e)*1e3));function Zn(e,t){return B(t||"searchParams",n=>{typeof n!="string"&&!(n instanceof URLSearchParams)&&Ee(n);const i=typeof n=="string"?new URLSearchParams(n):n;return Yn(e,r=>{const s=i.get(r);return s===null?void 0:s})})}function kt(e){for(const t in e)e[t]=[Fn(t),e[t]];return e}const Is=e=>{const t=we(),n=we(!0),i=A(),r=A(!0),s=He(!0),a=M(kt({addedToAttachmentMenu:s,allowsWriteToPm:s,firstName:i,id:t,isBot:s,isPremium:s,languageCode:r,lastName:r,photoUrl:r,username:r}),"User")(!0);return Zn(kt({authDate:Ns(),canSendAfter:n,chat:M(kt({id:t,type:i,title:i,photoUrl:r,username:r}),"Chat")(!0),chatInstance:r,chatType:r,hash:i,queryId:r,receiver:a,startParam:r,user:a}),"initData")(e)};function ks(e){return/^#[\da-f]{6}$/i.test(e)}function Vs(e){return/^#[\da-f]{3}$/i.test(e)}function Ls(e){const t=e.replace(/\s/g,"").toLowerCase();if(ks(t))return t;if(Vs(t)){let i="#";for(let r=0;r<3;r+=1)i+=t[1+r].repeat(2);return i}const n=t.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||t.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(!n)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return n.slice(1).reduce((i,r)=>{const s=parseInt(r,10).toString(16);return i+(s.length===1?"0":"")+s},"#")}const Us=B("rgb",e=>Ls(A()(e))),js=B("themeParams",e=>{const t=Us(!0);return Object.entries(Jn(e)).reduce((n,[i,r])=>(n[Os(i)]=t(r),n),{})});function Kn(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,n])=>[Fn(t),n])))}const qs=e=>{const t=A(),n=A(!0),i=He(!0);return Zn({botInline:["tgWebAppBotInline",i],initData:["tgWebAppData",Is(!0)],initDataRaw:["tgWebAppData",n],platform:["tgWebAppPlatform",t],showSettings:["tgWebAppShowSettings",i],startParam:["tgWebAppStartParam",n],themeParams:["tgWebAppThemeParams",js()],version:["tgWebAppVersion",t]},"launchParams")(e)};function Hs(e){const{initDataRaw:t,startParam:n,showSettings:i,botInline:r}=e,s=new URLSearchParams;return s.set("tgWebAppPlatform",e.platform),s.set("tgWebAppThemeParams",Kn(e.themeParams)),s.set("tgWebAppVersion",e.version),t&&s.set("tgWebAppData",t),n&&s.set("tgWebAppStartParam",n),typeof i=="boolean"&&s.set("tgWebAppShowSettings",i?"1":"0"),typeof r=="boolean"&&s.set("tgWebAppBotInline",r?"1":"0"),s.toString()}const Xn=M({eventType:A(),eventData:e=>e},"miniAppsMessage"),xn=B("fn",e=>{if(typeof e=="function")return e;Ee(e)});function Ws(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}const Gs=M({TelegramWebviewProxy:M({postEvent:xn()})()});function eo(e){return Gs().isValid(e)}function to(){try{return window.self!==window.top}catch{return!0}}var zs=Object.defineProperty,Fs=(e,t,n)=>t in e?zs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,no=(e,t,n)=>Fs(e,typeof t!="symbol"?t+"":t,n);let d=class ys extends Error{constructor(t,n,i){super(typeof n=="object"?n.message:n||t,{cause:typeof n=="object"?n.cause:i}),this.type=t,Object.setPrototypeOf(this,ys.prototype)}};function We(e,t,n){return e.addEventListener(t,n),()=>e.removeEventListener(t,n)}function X(...e){const t=e.flat(1);return[t.push.bind(t),()=>{t.forEach(n=>{n()})}]}function Qs(e,t){return e instanceof d&&e.type===t}function Vt(e){return t=>Qs(t,e)}const Lt="ERR_ABORTED",Ut="ERR_CANCELED",jt="ERR_TIMED_OUT";function oo(e){return new d(Lt,{cause:e})}const Ys=Vt(jt),Js=Vt(Lt),Zs=Vt(Ut);function ro(e,t){return e.reject=t.reject,e}class g extends Promise{constructor(t,n){let i,r;typeof t=="function"?(i=t,r=n):r=t;let s,a;super((c,_)=>{r||(r={});const{abortSignal:u}=r;if(u&&u.aborted)return _(oo(u.reason));const[p,E]=X(),S=h=>(...Z)=>(E(),h(...Z)),W=new AbortController,{signal:$}=W;a=S(h=>{W.abort(h),_(h)}),s=S(c),u&&p(We(u,"abort",()=>{a(oo(u.reason))}));const{timeout:b}=r;if(b){const h=setTimeout(()=>{a(new d(jt,`Timeout reached: ${b}ms`))},b);p(()=>{clearTimeout(h)})}i&&i(s,a,$)}),no(this,"reject"),this.reject=a}static withFn(t,n){return new g((i,r,s)=>{try{const a=t(s);return a instanceof Promise?a.then(i,r):i(a)}catch(a){r(a)}},n)}static resolve(t){return new g(n=>{n(t)})}static reject(t){return new g((n,i)=>{i(t)})}cancel(){this.reject(new d(Ut))}catch(t){return this.then(void 0,t)}finally(t){return ro(super.finally(t),this)}then(t,n){return ro(super.then(t,n),this)}}function io(e,t){return e.resolve=t.resolve,e}class ye extends g{constructor(t,n){let i,r;typeof t=="function"?(i=t,r=n):r=t;let s;super((a,c,_)=>{s=a,i&&i(a,c,_)},r),no(this,"resolve"),this.resolve=s}static withFn(t,n){return new ye((i,r,s)=>g.withFn(t,{abortSignal:s}).then(i,r),n)}static resolve(t){return new ye(n=>{n(t)})}static reject(t){return new ye((n,i)=>{i(t)})}catch(t){return this.then(void 0,t)}finally(t){return io(super.finally(t),this)}then(t,n){return io(super.then(t,n),this)}}function Ks(e,t){return new g(n=>{setTimeout(n,e)},{abortSignal:t})}function so(e){return`tapps/${e}`}function v(e,t){sessionStorage.setItem(so(e),JSON.stringify(t))}function R(e){const t=sessionStorage.getItem(so(e));try{return t?JSON.parse(t):void 0}catch{}}function qt(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function Xs(e,t){t||(t={});const{textColor:n,bgColor:i,shouldLog:r=!0}=t;function s(a,...c){if(!r||typeof r=="function"&&!r())return;const _="font-weight:bold;padding:0 5px;border-radius:5px";console[a](`%c${Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(new Date)}%c / %c${e}`,`${_};background-color: lightblue;color:black`,"",`${_};${n?`color:${n};`:""}${i?`background-color:${i}`:""}`,...c)}return[function(...a){s("log",...a)},function(...a){s("error",...a)}]}function Ge(e,t){document.documentElement.style.setProperty(e,t)}function ze(e){document.documentElement.style.removeProperty(e)}function xs(e,t){t()}function x(e,t){t||(t={});const n=t.equals||Object.is;let i=[],r=e;const s=u=>{if(!n(r,u)){const p=r;r=u,xs(_,()=>{[...i].forEach(([E,S])=>{E(u,p),S&&c(E,!0)})})}};function a(u){const p=typeof u!="object"?{once:u}:u;return{once:p.once||!1,signal:p.signal||!1}}const c=(u,p)=>{const E=a(p),S=i.findIndex(([W,$])=>W===u&&$.once===E.once&&$.signal===E.signal);S>=0&&i.splice(S,1)},_=Object.assign(function(){return ea(_),r},{destroy(){i=[]},set:s,reset(){s(e)},sub(u,p){return i.push([u,a(p)]),()=>c(u,p)},unsub:c,unsubAll(){i=i.filter(u=>u[1].signal)}});return _}const Ht=[];function ea(e){Ht.length&&Ht[Ht.length-1].add(e)}const ao=x(!1),[Wt,ta]=Xs("Bridge",{bgColor:"#9147ff",textColor:"white",shouldLog:ao}),na={clipboard_text_received:M({req_id:A(),data:e=>e===null?e:A(!0)(e)},"clipboard_text_received"),custom_method_invoked:M({req_id:A(),result:e=>e,error:A(!0)},"custom_method_invoked"),popup_closed:B("popup_closed",e=>e?M({button_id:t=>t==null?void 0:A()(t)})()(e):{}),viewport_changed:M({height:we(),width:e=>e==null?window.innerWidth:we()(e),is_state_stable:He(),is_expanded:He()},"viewport_changed")};function oa(e){const t=window,[,n]=X(We(t,"resize",()=>{e(["viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0}])}),We(t,"message",i=>{if(i.source!==t.parent)return;let r;try{r=Xn()(i.data)}catch{return}const{eventType:s,eventData:a}=r,c=na[s];try{const _=c?c()(a):a;Wt("Event received:",_?{eventType:s,eventData:_}:{eventType:s}),e([s,_])}catch(_){ta([`An error occurred processing the "${s}" event from the Telegram application.`,"Please, file an issue here:","https://github.com/Telegram-Mini-Apps/telegram-apps/issues/new/choose"].join(`
`),r,_)}}));return n}const Gt=x(),co=x();function uo(){return co()||co.set(oa(Gt.set)),Gt}const zt=x({});function lo(e){let t=zt()[e];return t||(t=x(void 0,{equals(){return!1}}),uo().sub(n=>{n&&n[0]===e&&t.set(n[1])}),zt.set({...zt(),[e]:t})),t}function C(e,t,n){return lo(e).sub(t,n)}const _o="ERR_METHOD_UNSUPPORTED",fo="ERR_RETRIEVE_LP_FAILED",po="ERR_METHOD_PARAMETER_UNSUPPORTED",Ft="ERR_UNKNOWN_ENV",mo="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",ho=x("https://web.telegram.org");function Fe(e,t){Wt("Posting event:",t?{eventType:e,eventData:t}:{eventType:e});const n=window;if(eo(n)){n.TelegramWebviewProxy.postEvent(e,JSON.stringify(t));return}const i=JSON.stringify({eventType:e,eventData:t});if(to())return n.parent.postMessage(i,ho());const{external:r}=n;if(M({notify:xn()})().isValid(r)){r.notify(i);return}throw new d(Ft)}function Qe(e,t,n){n||(n={});const{capture:i}=n,[r,s]=X();return new g(a=>{(Array.isArray(t)?t:[t]).forEach(c=>{r(C(c,_=>{(!i||(Array.isArray(t)?i({event:c,payload:_}):i(_)))&&a(_)}))}),(n.postEvent||Fe)(e,n.params)},n).finally(s)}function Qt(e){return qs()(e)}function bo(e){return Qt(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function ra(){return bo(window.location.href)}function ia(){const e=performance.getEntriesByType("navigation")[0];if(!e)throw new Error("Unable to get first navigation entry.");return bo(e.name)}const sa="launchParams";function aa(){return Qt(R(sa)||"")}function go(e){v("launchParams",Hs(e))}function Eo(e){return e instanceof Error?e.message+(e.cause?`
${Eo(e.cause)}`:""):JSON.stringify(e)}function Q(){const e=[];for(const t of[ra,ia,aa])try{const n=t();return go(n),n}catch(n){e.push(n)}throw new d(fo,["Unable to retrieve launch parameters from any known source. Perhaps, you have opened your app outside Telegram?","📖 Refer to docs for more information:","https://docs.telegram-mini-apps.com/packages/telegram-apps-sdk/environment","Collected errors:",...e.map(t=>`— ${Eo(t)}`)].join(`
`))}function Yt(e){if(e==="simple")try{return Q(),!0}catch{return!1}return g.withFn(async()=>{if(eo(window))return!0;try{return await Qe("web_app_request_theme","theme_changed",{timeout:100}),!0}catch{return!1}},e)}function Ye(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function ca(e,t){if(typeof t=="string")try{const{eventType:n}=Xn()(t);n==="web_app_request_theme"&&Ye("theme_changed",{theme_params:JSON.parse(Kn(e))}),n==="web_app_request_viewport"&&Ye("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}catch{}}function ua(e){var t;const n=typeof e=="string"?Qt(e):e;go(n);const i=(t=window.TelegramWebviewProxy)==null?void 0:t.postEvent;window.TelegramWebviewProxy={postEvent(r,s){ca(n.themeParams,JSON.stringify({eventType:r,eventData:s})),i==null||i(r,s)}},Wt("Environment was mocked by the mockTelegramEnv function")}function wo(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((n,i,r)=>{if(i===r.length-1){t[n]=Ye;return}n in t||(t[n]={}),t=t[n]})})}function yo(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function G(e,t,n){lo(e).unsub(t,n)}function la(e,t){return uo().sub(e,t)}function _a(e,t){Gt.unsub(e,t)}function So(e){return({req_id:t})=>t===e}function Co(e){return e.split(".").map(Number)}function $o(e,t){const n=Co(e),i=Co(t),r=Math.max(n.length,i.length);for(let s=0;s<r;s+=1){const a=n[s]||0,c=i[s]||0;if(a!==c)return a>c?1:-1}return 0}function w(e,t){return $o(e,t)<=0}function z(e,t,n){if(typeof n=="string"){if(e==="web_app_open_link"){if(t==="try_instant_view")return w("6.4",n);if(t==="try_browser")return w("7.6",n)}if(e==="web_app_set_header_color"&&t==="color")return w("6.9",n);if(e==="web_app_close"&&t==="return_back")return w("7.6",n);if(e==="web_app_setup_main_button"&&t==="has_shine_effect")return w("7.10",n)}switch(e){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return w("6.1",t);case"web_app_open_popup":return w("6.2",t);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return w("6.4",t);case"web_app_switch_inline_query":return w("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return w("6.9",t);case"web_app_setup_settings_button":return w("6.10",t);case"web_app_biometry_get_info":case"web_app_biometry_open_settings":case"web_app_biometry_request_access":case"web_app_biometry_request_auth":case"web_app_biometry_update_token":return w("7.2",t);case"web_app_setup_swipe_behavior":return w("7.7",t);case"web_app_share_to_story":return w("7.8",t);case"web_app_setup_secondary_button":case"web_app_set_bottom_bar_color":return w("7.10",t);default:return["iframe_ready","iframe_will_reload","web_app_close","web_app_data_send","web_app_expand","web_app_open_link","web_app_ready","web_app_request_theme","web_app_request_viewport","web_app_setup_main_button","web_app_setup_closing_behavior"].includes(e)}}function Ao(e,t){t||(t="strict");const n=typeof t=="function"?t:i=>{const{method:r,version:s}=i;let a,c;if("param"in i?(a=`Parameter "${i.param}" of "${r}" method is unsupported in Mini Apps version ${s}`,c=po):(a=`Method "${r}" is unsupported in Mini Apps version ${s}`,c=_o),t==="strict")throw new d(c,a);return console.warn(a)};return(i,r)=>z(i,e)?Ws(r)&&i==="web_app_set_header_color"&&"color"in r&&!z(i,"color",e)?n({version:e,method:i,param:"color"}):Fe(i,r):n({version:e,method:i})}function vo(e,t,n,i){return Qe("web_app_invoke_custom_method","custom_method_invoked",{...i||{},params:{method:e,params:t,req_id:n},capture:So(n)}).then(({result:r,error:s})=>{if(s)throw new d(mo,s);return r})}function da(){return performance.getEntriesByType("navigation")[0]}function D(){const e=da();return!!e&&e.type==="reload"}let ee;function fa(e,t){ee&&ee.set(e,t)||t()}function pa(e){if(ee)return e();ee=new Map;try{e()}finally{ee.forEach(t=>t()),ee=void 0}}function l(e,t){t||(t={});const n=t.equals||Object.is;let i=[],r=e;const s=u=>{if(!n(r,u)){const p=r;r=u,fa(_,()=>{[...i].forEach(([E,S])=>{E(u,p),S&&c(E,!0)})})}};function a(u){const p=typeof u!="object"?{once:u}:u;return{once:p.once||!1,signal:p.signal||!1}}const c=(u,p)=>{const E=a(p),S=i.findIndex(([W,$])=>W===u&&$.once===E.once&&$.signal===E.signal);S>=0&&i.splice(S,1)},_=Object.assign(function(){return ma(_),r},{destroy(){i=[]},set:s,reset(){s(e)},sub(u,p){return i.push([u,a(p)]),()=>c(u,p)},unsub:c,unsubAll(){i=i.filter(u=>u[1].signal)}});return _}const Se=[];function ma(e){Se.length&&Se[Se.length-1].add(e)}function m(e,t){let n=new Set,i;function r(){return i||(i=l(a(),t))}function s(){r().set(a())}function a(){n.forEach(u=>{u.unsub(s,{signal:!0})});const c=new Set;let _;Se.push(c);try{_=e()}finally{Se.pop()}return c.forEach(u=>{u.sub(s,{signal:!0})}),n=c,_}return Object.assign(function(){return r()()},{destroy(){r().destroy()},sub(...c){return r().sub(...c)},unsub(...c){r().unsub(...c)},unsubAll(...c){r().unsubAll(...c)}})}const Ro=l((()=>{let e=0;return()=>(e+=1).toString()})()),Jt=l(Fe),N=l("0.0");function ha(e){e||(e={});const{postEvent:t}=e,n=e.version||Q().version;N.set(n),Jt.set(typeof t=="function"?t:Ao(n))}function To(){return Ro()()}function te(e,t,n){return vo(e,t,To(),{...n||{},postEvent:f})}const I=(e,t,n)=>(n||(n={}),n.postEvent||(n.postEvent=f),Qe(e,t,n)),f=(e,t)=>Jt()(e,t);function k(e){return m(()=>z(e,N()))}const ne="ERR_POPUP_INVALID_PARAMS",Je="ERR_INVALID_URL",Po="ERR_INVALID_SLUG",Oo="ERR_DATA_INVALID_SIZE",Bo="ERR_ACCESS_DENIED",Ce="ERR_ALREADY_REQUESTING",Ze="ERR_ALREADY_OPENED",Mo="ERR_ALREADY_MOUNTING",Do="ERR_VARS_ALREADY_BOUND",No="ERR_NOT_AVAILABLE",Io="ERR_NOT_INITIALIZED",Zt="ERR_NOT_SUPPORTED",ko="ERR_NOT_MOUNTED";function Kt(){return typeof window>"u"}function V(e,t,{isSupported:n,isMounted:i,component:r,supports:s}={}){const a=`${r?`${r}.`:""}${e}()`;n=n?Array.isArray(n)||typeof n=="object"&&"any"in n?n:[n]:void 0;function c(b){if(s){const h=s[b];return z(h[0],h[1],N())}return!0}const _=()=>{if(!n)return;const b=`it is unsupported in Mini Apps version ${N()}`;function h(O){return typeof O=="string"?z(O,N())?void 0:b:O.fn()?void 0:O.error}if(Array.isArray(n)){for(const O of n){const gs=h(O);if(gs)return gs}return}let Z;for(const O of n.any)if(Z=h(O),!Z)return;return b},u=(...b)=>{if(s){for(const h in s)if(s[h][2](...b)&&!c(h))return`option ${h} is not supported in Mini Apps version ${N()}`}},p=m(()=>!_()),E=m(()=>N()!=="0.0"),S=m(()=>!i||i()),W=m(()=>Yt("simple")&&!Kt()&&E()&&p()&&S());let $;if(s){$={};for(const b in s)$[b]=m(()=>c(b))}return Object.assign((...b)=>{const h=`Unable to call the ${a} ${r?"method":"function"}:`;if(Kt()||!Yt("simple"))throw new d(Ft,`${h} it can't be called outside Mini Apps`);if(!E())throw new d(Io,`${h} the SDK was not initialized. Use the SDK init() function`);const Z=_();if(Z)throw new d(Zt,`${h} ${Z}`);const O=u(...b);if(O)throw new d(Zt,`${h} ${O}`);if(!S())throw new d(ko,`${h} the component is not mounted. Use the ${r}.mount() method`);return t(...b)},t,{isAvailable:W,ifAvailable(...b){return W()?t(...b):void 0}},n?{isSupported:p}:{},$?{supports:$}:{})}function Ke(e,t){return t||(t={}),(n,i,r,s)=>V(n,i,{...t,isSupported:r||t.isSupported,supports:s,component:e})}function oe(e,t,n){return Ke(e,{isSupported:n,isMounted:t})}function T(e,t){return Ke(e,{isSupported:t})}const Xe="web_app_setup_back_button",Vo="back_button_pressed",xe="backButton",et=l(!1),re=l(!1),Lo=k(Xe),Uo=oe(xe,re,Xe),Xt=T(xe,Xe),jo=Uo("hide",()=>{xt(!1)}),qo=Xt("mount",()=>{re()||(xt(D()&&R(xe)||!1),re.set(!0))});function xt(e){e!==et()&&(f(Xe,{is_visible:e}),v(xe,e),et.set(e))}const Ho=Xt("onClick",e=>C(Vo,e)),Wo=Xt("offClick",e=>{G(Vo,e)}),Go=Uo("show",()=>{xt(!0)});function zo(){re.set(!1)}const ba=Object.freeze(Object.defineProperty({__proto__:null,hide:jo,isMounted:re,isSupported:Lo,isVisible:et,mount:qo,offClick:Wo,onClick:Ho,show:Go,unmount:zo},Symbol.toStringTag,{value:"Module"}));function Fo(e,t,n,{isMounting:i,isMounted:r,mountError:s}){return a=>g.withFn(async c=>{if(r())return;if(i())throw new d(Mo,`The ${e} component is already mounting`);i.set(!0);let _;try{_=[!0,await t({abortSignal:c})]}catch(u){_=[!1,u]}pa(()=>{if(i.set(!1),r.set(!0),_[0])n(_[1]);else{const u=_[1];throw s.set(u),u}})},a)}const q=Ke,$e=l(),Ae=l(!1),ve=l(!1),Re=l(!1),en=l(!1),tn=l(void 0),ga=m(()=>{const e=$e();return e&&e.available});function nn(e){return e.available?{available:!0,tokenSaved:e.token_saved,deviceId:e.device_id,accessRequested:e.access_requested,type:e.type,accessGranted:e.access_granted}:{available:!1}}const Qo="web_app_biometry_get_info",Yo=V("requestBiometry",e=>I(Qo,"biometry_info_received",e).then(nn),{isSupported:Qo}),tt="web_app_biometry_request_auth",Ea="web_app_biometry_request_access",wa="web_app_biometry_open_settings",ya="web_app_biometry_update_token",on="biometry_info_received",ie="biometry",Jo=k(tt),Sa=q(ie),Ca=T(ie,tt),rn=oe(ie,Re,tt);function Zo(){throw new d(No,"Biometry is not available")}const Ko=rn("authenticate",e=>g.withFn(async t=>{if(Ae())throw new d(Ce,"Authentication is already in progress");const n=$e();(!n||!n.available)&&Zo(),Ae.set(!0);try{const i=await I(tt,"biometry_auth_requested",{abortSignal:t,params:{reason:((e||{}).reason||"").trim()}}),{token:r}=i;return typeof r=="string"&&nt({...n,token:r}),i}finally{Ae.set(!1)}},e)),Xo=Ca("openSettings",()=>{f(wa)}),xo=rn("requestAccess",e=>g.withFn(async t=>{if(ve())throw new d(Ce,"Access request is already in progress");ve.set(!0);try{const n=await I(Ea,on,{abortSignal:t,params:{reason:(e||{}).reason||""}}).then(nn);return n.available||Zo(),nt(n),n.accessGranted}finally{ve.set(!1)}},e)),er=Sa("mount",Fo(ie,e=>{const t=D()&&R(ie);return t||Yo(e)},e=>{C(on,tr),nt(e)},{isMounted:Re,mountError:tn,isMounting:en})),tr=e=>{nt(nn(e))};function nt(e){$e.set(e),v(ie,e)}function nr(){G(on,tr),Re.set(!1)}const or=rn("updateToken",e=>(e||(e={}),I(ya,"biometry_token_updated",{...e,params:{token:e.token||"",reason:e.reason}}).then(t=>t.status))),$a=Object.freeze(Object.defineProperty({__proto__:null,authenticate:Ko,isAuthenticating:Ae,isAvailable:ga,isMounted:Re,isMounting:en,isRequestingAccess:ve,isSupported:Jo,mount:er,mountError:tn,openSettings:Xo,requestAccess:xo,state:$e,unmount:nr,updateToken:or},Symbol.toStringTag,{value:"Module"}));function ot(e,t){return Ke(e,{isMounted:t})}const rt="closingBehavior",it=l(!1),se=l(!1),rr=ot(rt,se),Aa=q(rt),ir=rr("disableConfirmation",()=>{sn(!1)}),sr=rr("enableConfirmation",()=>{sn(!0)}),ar=Aa("mount",()=>{se()||(sn(D()&&R(rt)||!1),se.set(!0))});function sn(e){e!==it()&&(f("web_app_setup_closing_behavior",{need_confirmation:e}),v(rt,e),it.set(e))}function cr(){se.set(!1)}const va=Object.freeze(Object.defineProperty({__proto__:null,disableConfirmation:ir,enableConfirmation:sr,isConfirmationEnabled:it,isMounted:se,mount:ar,unmount:cr},Symbol.toStringTag,{value:"Module"})),ur="web_app_invoke_custom_method",st=T("cloudStorage",ur),lr=k(ur),_r=st("deleteItem",(e,t)=>{const n=Array.isArray(e)?e:[e];return n.length?te("deleteStorageValues",{keys:n},t).then():g.resolve()});function Ra(e,t){const n=Array.isArray(e)?e:[e];return n.length?te("getStorageValues",{keys:n},t).then(i=>{const r=Ue(Object.fromEntries(n.map(s=>[s,j()])))()(i);return Array.isArray(e)?r:r[e]}):g.resolve(typeof e=="string"?"":{})}const dr=st("getItem",Ra),fr=st("getKeys",e=>te("getStorageKeys",{},e).then(Ts(j())())),pr=st("setItem",(e,t,n)=>te("saveStorageValue",{key:e,value:t},n).then()),Ta=Object.freeze(Object.defineProperty({__proto__:null,deleteItem:_r,getItem:dr,getKeys:fr,isSupported:lr,setItem:pr},Symbol.toStringTag,{value:"Module"})),Te="web_app_trigger_haptic_feedback",an=T("hapticFeedback",Te),mr=k(Te),hr=an("impactOccurred",e=>{f(Te,{type:"impact",impact_style:e})}),br=an("notificationOccurred",e=>{f(Te,{type:"notification",notification_type:e})}),gr=an("selectionChanged",()=>{f(Te,{type:"selection_change"})}),Pa=Object.freeze(Object.defineProperty({__proto__:null,impactOccurred:hr,isSupported:mr,notificationOccurred:br,selectionChanged:gr},Symbol.toStringTag,{value:"Module"})),at=l(void 0);function L(e){return m(()=>{const t=at();return t?t[e]:void 0})}const cn=L("authDate"),un=L("canSendAfter"),Er=m(()=>{const e=cn(),t=un();return t&&e?new Date(e.getTime()+t*1e3):void 0}),wr=L("chat"),yr=L("chatType"),Sr=L("chatInstance"),Cr=L("hash"),$r=L("queryId"),ln=l(),Ar=L("receiver");function vr(){const e=Q();at.set(e.initData),ln.set(e.initDataRaw)}const Rr=L("startParam"),Tr=L("user"),Oa=Object.freeze(Object.defineProperty({__proto__:null,authDate:cn,canSendAfter:un,canSendAfterDate:Er,chat:wr,chatInstance:Sr,chatType:yr,hash:Cr,queryId:$r,raw:ln,receiver:Ar,restore:vr,startParam:Rr,state:at,user:Tr},Symbol.toStringTag,{value:"Module"}));function Ba(e){return $s()(e)}const _n="web_app_open_invoice",Ma=T("invoice",_n),Pe=l(!1),Pr=k(_n);async function Or(e,t,n){if(Pe())throw new d(Ze,"An invoice is already opened");let i;if(t==="url"){const{hostname:r,pathname:s}=new URL(e,window.location.href);if(r!=="t.me")throw new d(Je,`Link has unexpected hostname: ${r}`);const a=s.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!a)throw new d(Po,'Expected to receive a link with a pathname in format "/invoice/{slug}" or "/${slug}"');[,,i]=a}else i=e,n=t;return Pe.set(!0),I(_n,"invoice_closed",{...n,params:{slug:i},capture:r=>i===r.slug}).then(r=>r.status).finally(()=>{Pe.set(!1)})}const Br=Ma("open",Or),Da=Object.freeze(Object.defineProperty({__proto__:null,_open:Or,isOpened:Pe,isSupported:Pr,open:Br},Symbol.toStringTag,{value:"Module"}));function dn(e){const t=Nt(e);return Math.sqrt([.299,.587,.114].reduce((n,i,r)=>{const s=parseInt(t.slice(1+r*2,1+(r+1)*2),16);return n+s*s*i},0))<120}const ae=l(!1),Oe=l(!1),H=l({});function y(e){return m(()=>H()[e])}const Mr=y("accentTextColor"),ct=y("bgColor"),ut=y("buttonColor"),fn=y("buttonTextColor"),pn=y("bottomBarBgColor"),Dr=y("destructiveTextColor"),Nr=y("headerBgColor"),Ir=y("hintColor"),kr=m(()=>{const{bgColor:e}=H();return!e||dn(e)}),Vr=y("linkColor"),Be=y("secondaryBgColor"),Lr=y("sectionBgColor"),Ur=y("sectionHeaderTextColor"),jr=y("sectionSeparatorColor"),qr=y("subtitleTextColor"),Hr=y("textColor");function Y(e){return m(()=>lt()[e])}const Me=l({hasShineEffect:!1,isEnabled:!0,isLoaderVisible:!1,isVisible:!1,text:"Continue"}),lt=m(()=>{const e=Me();return{...e,backgroundColor:e.backgroundColor||ut()||"#2481cc",textColor:e.textColor||fn()||"#ffffff"}}),ce=l(!1),Wr=Y("backgroundColor"),Gr=Y("hasShineEffect"),zr=Y("isEnabled"),Fr=Y("isLoaderVisible"),Qr=Y("isVisible"),Yr=Y("text"),Jr=Y("textColor"),Na="web_app_setup_main_button",Zr="main_button_pressed",_t="mainButton",mn=q(_t),Ia=ot(_t,ce),Kr=mn("mount",()=>{if(!ce()){const e=D()&&R(_t);e&&Me.set(e),ce.set(!0)}}),Xr=mn("onClick",e=>C(Zr,e)),xr=mn("offClick",e=>{G(Zr,e)}),ei=Ia("setParams",e=>{Me.set({...Me(),...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))}),v(_t,Me());const t=lt();t.text&&f(Na,{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 ti(){ce.set(!1)}const ka=Object.freeze(Object.defineProperty({__proto__:null,backgroundColor:Wr,hasShineEffect:Gr,isEnabled:zr,isLoaderVisible:Fr,isMounted:ce,isVisible:Qr,mount:Kr,offClick:xr,onClick:Xr,setParams:ei,state:lt,text:Yr,textColor:Jr,unmount:ti},Symbol.toStringTag,{value:"Module"}));function hn(){throw new d(Do,"CSS variables are already bound")}function ni(e){return vs()(e)}const dt="themeParams",oi="theme_changed",Va=q(dt),ri=ot(dt,ae)("bindCssVars",e=>{Oe()&&hn(),e||(e=i=>`--tg-theme-${qt(i)}`);function t(i){Object.entries(H()).forEach(([r,s])=>{s&&i(r,s)})}function n(){t((i,r)=>{Ge(e(i),r)})}return n(),H.sub(n),Oe.set(!0),()=>{t(ze),H.unsub(n),Oe.set(!1)}}),bn=Va("mount",()=>{ae()||(C(oi,ii),H.set(D()&&R(dt)||Q().themeParams),ae.set(!0))}),ii=e=>{const t=ni(e.theme_params);H.set(t),v(dt,t)};function si(){G(oi,ii),ae.set(!1)}function ai(e){return m(()=>{const t=e();return K(t)?t:t==="bg_color"?ct():Be()})}const ue=l("bg_color"),gn=ai(ue),le=l("bottom_bar_bg_color"),ft=m(()=>{const e=le();return K(e)?e:e==="bottom_bar_bg_color"?pn()||Be():e==="secondary_bg_color"?Be():ct()}),_e=l("bg_color"),En=ai(_e),de=l(!1),De=l(!1),ci=m(()=>{const e=gn();return e?dn(e):!1}),wn=m(()=>({backgroundColor:ue(),bottomBarColor:le(),headerColor:_e()})),yn="web_app_set_background_color",Sn="web_app_set_bottom_bar_color",pt="web_app_set_header_color",Ne="miniApp",Cn={any:[yn,Sn,pt]},ui=m(()=>Cn.any.some(e=>z(e,N()))),li=q(Ne),La=T(Ne,Cn),mt=oe(Ne,de,Cn),_i=mt("bindCssVars",e=>{De()&&hn();const[t,n]=X();function i(r,s){function a(){Ge(r,s()||null)}a(),t(s.sub(a),ze.bind(null,r))}return e||(e=r=>`--tg-${qt(r)}`),i(e("bgColor"),gn),i(e("bottomBarColor"),ft),i(e("headerColor"),En),t(()=>{De.set(!1)}),De.set(!0),n}),di=li("close",e=>{f("web_app_close",{return_back:e})}),fi=La("mount",()=>{if(!de()){const e=D()&&R(Ne);bn(),An.ifAvailable(e?e.backgroundColor:"bg_color"),vn.ifAvailable(e?e.bottomBarColor:"bottom_bar_bg_color"),Rn.ifAvailable(e?e.headerColor:"bg_color"),de.set(!0)}}),pi=li("ready",()=>{f("web_app_ready")});function $n(){v(Ne,wn())}const An=mt("setBackgroundColor",e=>{e!==ue()&&(f(yn,{color:e}),ue.set(e),$n())},yn),vn=mt("setBottomBarColor",e=>{e!==le()&&(f(Sn,{color:e}),le.set(e),$n())},Sn),Rn=mt("setHeaderColor",e=>{e!==_e()&&(f(pt,K(e)?{color:e}:{color_key:e}),_e.set(e),$n())},pt,{rgb:[pt,"color",K]});function mi(){de.set(!1)}const Ua=Object.freeze(Object.defineProperty({__proto__:null,backgroundColor:ue,backgroundColorRGB:gn,bindCssVars:_i,bottomBarColor:le,bottomBarColorRGB:ft,close:di,headerColor:_e,headerColorRGB:En,isCssVarsBound:De,isDark:ci,isMounted:de,isSupported:ui,mount:fi,ready:pi,setBackgroundColor:An,setBottomBarColor:vn,setHeaderColor:Rn,state:wn,unmount:mi},Symbol.toStringTag,{value:"Module"}));function ja(e){const t=e.message.trim(),n=(e.title||"").trim(),i=e.buttons||[];if(n.length>64)throw new d(ne,`Invalid title: ${n}`);if(!t||t.length>256)throw new d(ne,`Invalid message: ${t}`);if(i.length>3)throw new d(ne,`Invalid buttons count: ${i.length}`);return{title:n,message:t,buttons:i.length?i.map((r,s)=>{const a=r.id||"";if(a.length>64)throw new d(ne,`Button with index ${s} has invalid id: ${a}`);if(!r.type||r.type==="default"||r.type==="destructive"){const c=r.text.trim();if(!c||c.length>64)throw new d(ne,`Button with index ${s} has invalid text: ${c}`);return{type:r.type,text:c,id:a}}return{type:r.type,id:a}}):[{type:"close",id:""}]}}const Tn="web_app_open_popup",qa=T("popup",Tn),Ie=l(!1),hi=k(Tn),bi=qa("open",async e=>{if(Ie())throw new d(Ze,"A popup is already opened");Ie.set(!0);try{const{button_id:t=null}=await I(Tn,"popup_closed",{...e,params:ja(e)});return t}finally{Ie.set(!1)}}),Ha=Object.freeze(Object.defineProperty({__proto__:null,isOpened:Ie,isSupported:hi,open:bi},Symbol.toStringTag,{value:"Module"})),Wa="web_app_close_scan_qr_popup",Pn="web_app_open_scan_qr_popup",Ga="scan_qr_popup_closed",za="qr_text_received",gi=T("qrScanner",Pn),ht=gi("close",()=>{J.set(!1),f(Wa)}),J=l(!1),Ei=k(Pn);function Fa(e){return g.withFn(t=>{if(J())throw new d(Ze,"The QR Scanner is already opened");J.set(!0),e||(e={});const{onCaptured:n,text:i,capture:r}=e,[,s]=X(J.sub(()=>{a.resolve()}),C(Ga,()=>{J.set(!1)}),C(za,c=>{n?n(c.data):(!r||r(c.data))&&(a.resolve(c.data),ht())})),a=new ye({abortSignal:t}).catch(ht).finally(s);return(e.postEvent||f)(Pn,{text:i}),a},e)}const wi=gi("open",Fa),Qa=Object.freeze(Object.defineProperty({__proto__:null,close:ht,isOpened:J,isSupported:Ei,open:wi},Symbol.toStringTag,{value:"Module"}));function F(e){return m(()=>bt()[e])}const ke=l({hasShineEffect:!1,isEnabled:!0,isLoaderVisible:!1,isVisible:!1,position:"left",text:"Cancel"}),bt=m(()=>{const e=ke();return{...e,backgroundColor:e.backgroundColor||ft()||"#000000",textColor:e.textColor||ut()||"#2481cc"}}),fe=l(!1),yi=F("backgroundColor"),Si=F("hasShineEffect"),Ci=F("isEnabled"),$i=F("isLoaderVisible"),Ai=F("isVisible"),vi=F("position"),Ri=F("text"),Ti=F("textColor"),gt="web_app_setup_secondary_button",Pi="secondary_button_pressed",Et="secondaryButton",On=T(Et,gt),Ya=oe(Et,fe,gt),Oi=k(gt),Bi=On("mount",()=>{if(!fe()){const e=D()&&R(Et);e&&ke.set(e),fe.set(!0)}}),Mi=On("onClick",e=>C(Pi,e)),Di=On("offClick",e=>{G(Pi,e)}),Ni=Ya("setParams",e=>{ke.set({...ke(),...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))}),v(Et,ke());const t=bt();t.text&&f(gt,{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 Ii(){fe.set(!1)}const Ja=Object.freeze(Object.defineProperty({__proto__:null,backgroundColor:yi,hasShineEffect:Si,isEnabled:Ci,isLoaderVisible:$i,isMounted:fe,isSupported:Oi,isVisible:Ai,mount:Bi,offClick:Di,onClick:Mi,position:vi,setParams:Ni,state:bt,text:Ri,textColor:Ti,unmount:Ii},Symbol.toStringTag,{value:"Module"})),wt="web_app_setup_settings_button",ki="settings_button_pressed",yt="settingsButton",St=l(!1),pe=l(!1),Vi=k(wt),Bn=T(yt,wt),Li=oe(yt,pe,wt),Ui=Li("hide",()=>{Mn(!1)}),ji=Bn("mount",()=>{pe()||(Mn(D()&&R(yt)||!1),pe.set(!0))});function Mn(e){e!==St()&&(f(wt,{is_visible:e}),v(yt,e),St.set(e))}const qi=Bn("onClick",e=>C(ki,e)),Hi=Bn("offClick",e=>{G(ki,e)}),Wi=Li("show",()=>{Mn(!0)});function Gi(){pe.set(!1)}const Za=Object.freeze(Object.defineProperty({__proto__:null,hide:Ui,isMounted:pe,isSupported:Vi,isVisible:St,mount:ji,offClick:Hi,onClick:qi,show:Wi,unmount:Gi},Symbol.toStringTag,{value:"Module"})),Ct="web_app_setup_swipe_behavior",$t="swipeBehavior",me=l(!1),zi=k(Ct),At=l(!0),Ka=T($t,Ct),Fi=oe($t,me,Ct),Qi=Fi("disableVertical",()=>{Dn(!1)}),Yi=Fi("enableVertical",()=>{Dn(!0)}),Ji=Ka("mount",()=>{me()||(Dn(D()&&R($t)||!1,!0),me.set(!0))});function Dn(e,t){(e!==At()||t)&&(f(Ct,{allow_vertical_swipe:e}),v($t,e),At.set(e))}function Zi(){me.set(!1)}const Xa=Object.freeze(Object.defineProperty({__proto__:null,disableVertical:Qi,enableVertical:Yi,isMounted:me,isSupported:zi,isVerticalEnabled:At,mount:Ji,unmount:Zi},Symbol.toStringTag,{value:"Module"})),xa=Object.freeze(Object.defineProperty({__proto__:null,accentTextColor:Mr,backgroundColor:ct,bindCssVars:ri,bottomBarBgColor:pn,buttonColor:ut,buttonTextColor:fn,destructiveTextColor:Dr,headerBackgroundColor:Nr,hintColor:Ir,isCssVarsBound:Oe,isDark:kr,isMounted:ae,linkColor:Vr,mount:bn,secondaryBackgroundColor:Be,sectionBackgroundColor:Lr,sectionHeaderTextColor:Ur,sectionSeparatorColor:jr,state:H,subtitleTextColor:qr,textColor:Hr,unmount:si},Symbol.toStringTag,{value:"Module"})),P=l({height:0,width:0,isExpanded:!1,stableHeight:0}),Ve=l(!1),Le=l(!1),Nn=l(!1),In=l(void 0);function vt(e){return m(()=>P()[e])}const Ki=vt("height"),Xi=vt("isExpanded"),xi=m(()=>{const e=P();return e.height===e.stableHeight}),es=vt("stableHeight"),ts=vt("width");function ns(e){return I("web_app_request_viewport","viewport_changed",e).then(t=>({height:t.height,width:t.width,isExpanded:t.is_expanded,isStable:t.is_state_stable}))}const Rt="viewport",os=q(Rt),rs=ot(Rt,Ve)("bindCssVars",e=>{Le()&&hn(),e||(e=i=>`--tg-viewport-${qt(i)}`);const t=["height","width","stableHeight"];function n(){t.forEach(i=>{Ge(e(i),`${P()[i]}px`)})}return n(),P.sub(n),Le.set(!0),()=>{t.forEach(ze),P.unsub(n),Le.set(!1)}}),is=os("expand",()=>{f("web_app_expand")}),ss=os("mount",Fo(Rt,e=>{const t=D()&&R(Rt);if(t)return t;if(["macos","tdesktop","unigram","webk","weba","web"].includes(Q().platform)){const n=window;return{isExpanded:!0,height:n.innerHeight,width:n.innerWidth,stableHeight:n.innerHeight}}return e.timeout||(e.timeout=1e3),ns(e).then(n=>({height:n.height,isExpanded:n.isExpanded,stableHeight:n.isStable?n.height:P().stableHeight,width:n.width}))},e=>{C("viewport_changed",as),cs(e)},{isMounted:Ve,isMounting:Nn,mountError:In})),as=e=>{cs({height:e.height,isExpanded:e.is_expanded,stableHeight:e.is_state_stable?e.height:P().stableHeight,width:e.width})};function cs(e){P.set({isExpanded:e.isExpanded,height:kn(e.height),width:kn(e.width),stableHeight:kn(e.stableHeight)}),v("viewport",P())}function kn(e){return Math.max(e,0)}function us(){G("viewport_changed",as),Ve.set(!1)}const ec=Object.freeze(Object.defineProperty({__proto__:null,bindCssVars:rs,expand:is,height:Ki,isCssVarsBound:Le,isExpanded:Xi,isMounted:Ve,isMounting:Nn,isStable:xi,mount:ss,mountError:In,stableHeight:es,state:P,unmount:us,width:ts},Symbol.toStringTag,{value:"Module"})),tc=q()("openLink",(e,t)=>{if(typeof e=="string")try{e=new URL(e)}catch(n){throw new d(Je,`"${e.toString()}" is invalid URL`,n)}t||(t={}),f("web_app_open_link",{url:e.toString(),try_browser:t.tryBrowser,try_instant_view:t.tryInstantView})}),ls="web_app_open_tg_link",_s=q()("openTelegramLink",e=>{const t=e.toString();if(!t.match(/^https:\/\/t.me\/.+/))throw new d(Je,`"${t}" is invalid URL`);if(!z(ls,N())){window.location.href=t;return}e=new URL(e),f(ls,{path_full:e.pathname+e.search})}),nc=q()("shareURL",(e,t)=>{_s("https://t.me/share/url?"+new URLSearchParams({url:e,text:t||""}).toString().replace(/\+/g,"%20"))}),Vn="web_app_request_phone",Tt=l(!1),ds=V("requestPhoneAccess",e=>{if(Tt())throw new d(Ce,"Phone access request is currently in progress");return Tt.set(!0),I(Vn,"phone_requested",e).then(t=>t.status).finally(()=>{Tt.set(!1)})},{isSupported:Vn});function fs(e){return e||(e={}),te("getRequestedContact",{},{...e,timeout:e.timeout||5e3}).then(Wn({contact:Ue({userId:["user_id",je()],phoneNumber:["phone_number",j()],firstName:["first_name",j()],lastName:["last_name",j(!0)]})(),authDate:["auth_date",Mt()],hash:j()})())}const oc=V("requestContact",e=>g.withFn(async t=>{const n={abortSignal:t};try{return await fs(n)}catch{}if(await ds(n)!=="sent")throw new d(Bo,"User denied access");let r=50;for(;!t.aborted;){try{return await fs(n)}catch{}await Ks(r),r+=50}return null},e),{isSupported:Vn}),ps="web_app_request_write_access",Pt=l(!1),rc=V("requestWriteAccess",e=>{if(Pt())throw new d(Ce,"Write access request is currently in progress");return Pt.set(!0),I(ps,"write_access_requested",e).then(t=>t.status).finally(()=>{Pt.set(!1)})},{isSupported:ps}),ic=V("getCurrentTime",e=>te("getCurrentTime",{},e).then(Mt()),{isSupported:"web_app_invoke_custom_method"}),ms="web_app_read_text_from_clipboard",sc=V("readTextFromClipboard",e=>{const t=To();return I(ms,"clipboard_text_received",{...e,params:{req_id:t},capture:So(t)}).then(({data:n=null})=>n)},{isSupported:ms}),ac=V("sendData",e=>{const{size:t}=new Blob([e]);if(!t||t>4096)throw new d(Oo,t?"Maximum size of data to send is 4096 bytes":"Attempted to send empty data");f("web_app_data_send",{data:e})}),hs="web_app_share_to_story",cc=V("shareStory",(e,t)=>{t||(t={}),f(hs,{text:t.text,media_url:e,widget_link:t.widgetLink})},{isSupported:hs}),bs="web_app_switch_inline_query",uc=V("switchInlineQuery",(e,t)=>{f(bs,{query:e,chat_types:t||[]})},{isSupported:[bs,{fn:()=>!!Q().botInline,error:"Mini App should be ran in Bot inline mode"}]});function lc(e){try{return{result:e()}}catch(t){return{error:t}}}function _c(e){ha(e),wo();const[t,n]=X(C("reload_iframe",()=>{f("iframe_will_reload"),window.location.reload()}),yo),{acceptCustomStyles:i=!0}=e||{};if(i){const r=document.createElement("style");r.id="telegram-custom-styles",document.head.appendChild(r),t(C("set_custom_style",s=>{r.innerHTML=s}),()=>{document.head.removeChild(r)})}return f("iframe_ready",{reload_supported:!0}),n}return o.$createRequestId=Ro,o.$debug=ao,o.$postEvent=Jt,o.$targetOrigin=ho,o.$version=N,o.CancelablePromise=g,o.ERR_ABORTED=Lt,o.ERR_ACCESS_DENIED=Bo,o.ERR_ALREADY_MOUNTING=Mo,o.ERR_ALREADY_OPENED=Ze,o.ERR_ALREADY_REQUESTING=Ce,o.ERR_CANCELED=Ut,o.ERR_CSS_VARS_ALREADY_BOUND=Do,o.ERR_CUSTOM_METHOD_ERR_RESPONSE=mo,o.ERR_DATA_INVALID_SIZE=Oo,o.ERR_INVALID_SLUG=Po,o.ERR_INVALID_URL=Je,o.ERR_INVALID_VALUE=Un,o.ERR_METHOD_PARAMETER_UNSUPPORTED=po,o.ERR_METHOD_UNSUPPORTED=_o,o.ERR_NOT_AVAILABLE=No,o.ERR_NOT_INITIALIZED=Io,o.ERR_NOT_MOUNTED=ko,o.ERR_NOT_SUPPORTED=Zt,o.ERR_PARSE=Ot,o.ERR_POPUP_INVALID_PARAMS=ne,o.ERR_RETRIEVE_LP_FAILED=fo,o.ERR_TIMED_OUT=jt,o.ERR_UNEXPECTED_TYPE=qn,o.ERR_UNEXPECTED_VALUE=jn,o.ERR_UNKNOWN_ENV=Ft,o.TypedError=d,o.addEventListener=We,o.authenticateBiometry=Ko,o.backButton=ba,o.bindMiniAppCssVars=_i,o.bindThemeParamsCssVars=ri,o.bindViewportCssVars=rs,o.biometry=$a,o.biometryMountError=tn,o.biometryState=$e,o.classNames=qe,o.closeMiniApp=di,o.closeQrScanner=ht,o.closingBehavior=va,o.cloudStorage=Ta,o.compareVersions=$o,o.createPostEvent=Ao,o.defineEventHandlers=wo,o.deleteCloudStorageItem=_r,o.deleteCssVar=ze,o.disableClosingConfirmation=ir,o.disableVerticalSwipes=Qi,o.emitMiniAppsEvent=Ye,o.enableClosingConfirmation=sr,o.enableVerticalSwipes=Yi,o.expandViewport=is,o.getCloudStorageItem=dr,o.getCloudStorageKeys=fr,o.getCurrentTime=ic,o.hapticFeedback=Pa,o.hapticFeedbackImpactOccurred=hr,o.hapticFeedbackNotificationOccurred=br,o.hapticFeedbackSelectionChanged=gr,o.hideBackButton=jo,o.hideSettingsButton=Ui,o.init=_c,o.initData=Oa,o.initDataAuthDate=cn,o.initDataCanSendAfter=un,o.initDataCanSendAfterDate=Er,o.initDataChat=wr,o.initDataChatInstance=Sr,o.initDataChatType=yr,o.initDataHash=Cr,o.initDataQueryId=$r,o.initDataRaw=ln,o.initDataReceiver=Ar,o.initDataStartParam=Rr,o.initDataState=at,o.initDataUser=Tr,o.invoice=Da,o.invokeCustomMethod=vo,o.isAbortError=Js,o.isAuthenticatingBiometry=Ae,o.isBackButtonMounted=re,o.isBackButtonSupported=Lo,o.isBackButtonVisible=et,o.isBiometryMounted=Re,o.isBiometryMounting=en,o.isBiometrySupported=Jo,o.isCanceledError=Zs,o.isClosingBehaviorMounted=se,o.isClosingConfirmationEnabled=it,o.isCloudStorageSupported=lr,o.isColorDark=dn,o.isHapticFeedbackSupported=mr,o.isIframe=to,o.isInvoiceOpened=Pe,o.isInvoiceSupported=Pr,o.isMainButtonEnabled=zr,o.isMainButtonLoaderVisible=Fr,o.isMainButtonMounted=ce,o.isMainButtonVisible=Qr,o.isMiniAppCssVarsBound=De,o.isMiniAppDark=ci,o.isMiniAppMounted=de,o.isMiniAppSupported=ui,o.isPopupOpened=Ie,o.isPopupSupported=hi,o.isQrScannerOpened=J,o.isQrScannerSupported=Ei,o.isRGB=K,o.isRGBShort=Gn,o.isRecord=It,o.isRequestingBiometryAccess=ve,o.isRequestingPhoneAccess=Tt,o.isRequestingWriteAccess=Pt,o.isSSR=Kt,o.isSecondaryButtonEnabled=Ci,o.isSecondaryButtonLoaderVisible=$i,o.isSecondaryButtonMounted=fe,o.isSecondaryButtonSupported=Oi,o.isSecondaryButtonVisible=Ai,o.isSettingsButtonMounted=pe,o.isSettingsButtonSupported=Vi,o.isSettingsButtonVisible=St,o.isSwipeBehaviorMounted=me,o.isSwipeBehaviorSupported=zi,o.isTMA=Yt,o.isThemeParamsCssVarsBound=Oe,o.isThemeParamsDark=kr,o.isThemeParamsMounted=ae,o.isTimeoutError=Ys,o.isVerticalSwipesEnabled=At,o.isViewportCssVarsBound=Le,o.isViewportExpanded=Xi,o.isViewportMounted=Ve,o.isViewportMounting=Nn,o.isViewportStable=xi,o.mainButton=ka,o.mainButtonBackgroundColor=Wr,o.mainButtonHasShineEffect=Gr,o.mainButtonState=lt,o.mainButtonText=Yr,o.mainButtonTextColor=Jr,o.mergeClassNames=Ps,o.miniApp=Ua,o.miniAppBackgroundColor=ue,o.miniAppBottomBarColor=le,o.miniAppBottomBarColorRGB=ft,o.miniAppHeaderColor=_e,o.miniAppHeaderColorRGB=En,o.miniAppReady=pi,o.miniAppState=wn,o.mockTelegramEnv=ua,o.mountBackButton=qo,o.mountBiometry=er,o.mountClosingBehavior=ar,o.mountMainButton=Kr,o.mountMiniApp=fi,o.mountSecondaryButton=Bi,o.mountSettingsButton=ji,o.mountSwipeBehavior=Ji,o.mountThemeParams=bn,o.mountViewport=ss,o.off=G,o.offBackButtonClick=Wo,o.offMainButtonClick=xr,o.offSecondaryButtonClick=Di,o.offSettingsButtonClick=Hi,o.on=C,o.onBackButtonClick=Ho,o.onMainButtonClick=Xr,o.onSecondaryButtonClick=Mi,o.onSettingsButtonClick=qi,o.openBiometrySettings=Xo,o.openInvoice=Br,o.openLink=tc,o.openPopup=bi,o.openQrScanner=wi,o.openTelegramLink=_s,o.parseInitData=Ba,o.parseThemeParams=ni,o.popup=Ha,o.postEvent=Fe,o.qrScanner=Qa,o.readTextFromClipboard=sc,o.removeEventHandlers=yo,o.request=Qe,o.requestBiometry=Yo,o.requestBiometryAccess=xo,o.requestContact=oc,o.requestPhoneAccess=ds,o.requestViewport=ns,o.requestWriteAccess=rc,o.restoreInitData=vr,o.retrieveLaunchParams=Q,o.safeCall=lc,o.secondaryButton=Ja,o.secondaryButtonBackgroundColor=yi,o.secondaryButtonHasShineEffect=Si,o.secondaryButtonPosition=vi,o.secondaryButtonState=bt,o.secondaryButtonText=Ri,o.secondaryButtonTextColor=Ti,o.sendData=ac,o.serializeLaunchParams=Rs,o.serializeThemeParams=zn,o.setCloudStorageItem=pr,o.setCssVar=Ge,o.setMainButtonParams=ei,o.setMiniAppBackgroundColor=An,o.setMiniAppBottomBarColor=vn,o.setMiniAppHeaderColor=Rn,o.setSecondaryButtonParams=Ni,o.settingsButton=Za,o.shareStory=cc,o.shareURL=nc,o.showBackButton=Go,o.showSettingsButton=Wi,o.subscribe=la,o.supports=z,o.swipeBehavior=Xa,o.switchInlineQuery=uc,o.themeParams=xa,o.themeParamsAccentTextColor=Mr,o.themeParamsBackgroundColor=ct,o.themeParamsBottomBarBgColor=pn,o.themeParamsButtonColor=ut,o.themeParamsButtonTextColor=fn,o.themeParamsDestructiveTextColor=Dr,o.themeParamsHeaderBackgroundColor=Nr,o.themeParamsHintColor=Ir,o.themeParamsLinkColor=Vr,o.themeParamsSecondaryBackgroundColor=Be,o.themeParamsSectionBackgroundColor=Lr,o.themeParamsSectionHeaderTextColor=Ur,o.themeParamsSectionSeparatorColor=jr,o.themeParamsState=H,o.themeParamsSubtitleTextColor=qr,o.themeParamsTextColor=Hr,o.toRGB=Nt,o.toRecord=Bt,o.unmountBackButton=zo,o.unmountBiometry=nr,o.unmountClosingBehavior=cr,o.unmountMainButton=ti,o.unmountMiniApp=mi,o.unmountSecondaryButton=Ii,o.unmountSettingsButton=Gi,o.unmountSwipeBehavior=Zi,o.unmountThemeParams=si,o.unmountViewport=us,o.unsubscribe=_a,o.updateBiometryToken=or,o.viewport=ec,o.viewportHeight=Ki,o.viewportMountError=In,o.viewportStableHeight=es,o.viewportState=P,o.viewportWidth=ts,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),o}({});
this.telegramApps=this.telegramApps||{};this.telegramApps.sdk=function(o){"use strict";class J extends Error{constructor(t,n,r){super(typeof n=="object"?n.message:n||t,{cause:typeof n=="object"?n.cause:r}),this.type=t,Object.setPrototypeOf(this,J.prototype)}}function Xn(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function ta(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}const xn="ERR_INVALID_VALUE",eo="ERR_UNEXPECTED_VALUE",to="ERR_UNEXPECTED_TYPE",Vt="ERR_PARSE";function no(e,t){const n={};for(const r in e){const s=e[r];if(!s)continue;let i,a;typeof s=="function"?(i=r,a=s):[i,a]=s;try{const c=a(t(i));c!==void 0&&(n[r]=c)}catch(c){throw new J(Vt,`Parser for "${r}" property failed${i===r?"":`. Source field: "${i}"`}`,c)}}return n}function Ut(e){let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new J(xn,{cause:n})}if(typeof t!="object"||!t||Array.isArray(t))throw new J(eo);return t}function j(e,t){return n=>{const r=s=>{if(!(n&&s===void 0))try{return t(s)}catch(i){throw new J(Vt,{message:`"${e}" transformer failed to parse the value`,cause:i})}};return Object.assign(r,{isValid(s){try{return r(s),!0}catch{return!1}}})}}function Ge(e,t){return j(t||"object",n=>{const r=Ut(n);return no(e,s=>r[s])})}function Se(e){throw new J(to,`Unexpected value received: ${JSON.stringify(e)}`)}const na=j("boolean",e=>{if(typeof e=="boolean")return e;const t=String(e);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;Se(e)}),q=j("string",e=>{if(typeof e=="string"||typeof e=="number")return e.toString();Se(e)}),ze=j("number",e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}Se(e)}),jt=j("date",e=>e instanceof Date?e:new Date(ze()(e)*1e3));function oo(e,t){return j(t||"searchParams",n=>{typeof n!="string"&&!(n instanceof URLSearchParams)&&Se(n);const r=typeof n=="string"?new URLSearchParams(n):n;return no(e,s=>{const i=r.get(s);return i===null?void 0:i})})}function qt(e){for(const t in e)e[t]=[Xn(t),e[t]];return e}const oa=e=>{const t=ze(),n=ze(!0),r=q(),s=q(!0),i=na(!0),a=Ge(qt({addedToAttachmentMenu:i,allowsWriteToPm:i,firstName:r,id:t,isBot:i,isPremium:i,languageCode:s,lastName:s,photoUrl:s,username:s}),"User")(!0);return oo(qt({authDate:jt(),canSendAfter:n,chat:Ge(qt({id:t,type:r,title:r,photoUrl:s,username:s}),"Chat")(!0),chatInstance:s,chatType:s,hash:r,queryId:s,receiver:a,startParam:s,user:a}),"initData")(e)};function x(e){return/^#[\da-f]{6}$/i.test(e)}function ro(e){return/^#[\da-f]{3}$/i.test(e)}function Ft(e){const t=e.replace(/\s/g,"").toLowerCase();if(x(t))return t;if(ro(t)){let r="#";for(let s=0;s<3;s+=1)r+=t[1+s].repeat(2);return r}const n=t.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||t.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(!n)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return n.slice(1).reduce((r,s)=>{const i=parseInt(s,10).toString(16);return r+(i.length===1?"0":"")+i},"#")}const ra=j("rgb",e=>Ft(q()(e))),sa=j("themeParams",e=>{const t=ra(!0);return Object.entries(Ut(e)).reduce((n,[r,s])=>(n[ta(r)]=t(s),n),{})});function Ht(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,n])=>[Xn(t),n])))}function ia(e){const{initDataRaw:t,startParam:n,showSettings:r,botInline:s,fullscreen:i,defaultColors:a}=e,c=new URLSearchParams;return c.set("tgWebAppPlatform",e.platform),c.set("tgWebAppThemeParams",Ht(e.themeParams)),c.set("tgWebAppVersion",e.version),t&&c.set("tgWebAppData",t),n&&c.set("tgWebAppStartParam",n),typeof r=="boolean"&&c.set("tgWebAppShowSettings",r?"1":"0"),typeof s=="boolean"&&c.set("tgWebAppBotInline",s?"1":"0"),typeof i=="boolean"&&c.set("tgWebAppFullscreen",i?"1":"0"),a&&c.set("tgWebAppDefaultColors",Ht(a)),c.toString()}function aa(e,t){return j("array",n=>{let r;if(Array.isArray(n))r=n;else if(typeof n=="string")try{const s=JSON.parse(n);Array.isArray(s)&&(r=s)}catch{}return r||Se(n),r.map(e)})}function Wt(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function Ye(...e){return e.map(t=>{if(typeof t=="string")return t;if(Wt(t))return Ye(Object.entries(t).map(n=>n[1]&&n[0]));if(Array.isArray(t))return Ye(...t)}).filter(Boolean).join(" ")}function ca(...e){return e.reduce((t,n)=>(Wt(n)&&Object.entries(n).forEach(([r,s])=>{const i=Ye(t[r],s);i&&(t[r]=i)}),t),{})}let Ce=class xi extends Error{constructor(t,n,r){super(typeof n=="object"?n.message:n||t,{cause:typeof n=="object"?n.cause:r}),this.type=t,Object.setPrototypeOf(this,xi.prototype)}};function so(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function ua(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}const la="ERR_INVALID_VALUE",_a="ERR_UNEXPECTED_VALUE",fa="ERR_UNEXPECTED_TYPE",io="ERR_PARSE";function ao(e,t){const n={};for(const r in e){const s=e[r];if(!s)continue;let i,a;typeof s=="function"?(i=r,a=s):[i,a]=s;try{const c=a(t(i));c!==void 0&&(n[r]=c)}catch(c){throw new Ce(io,`Parser for "${r}" property failed${i===r?"":`. Source field: "${i}"`}`,c)}}return n}function co(e){let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch(n){throw new Ce(la,{cause:n})}if(typeof t!="object"||!t||Array.isArray(t))throw new Ce(_a);return t}function I(e,t){return n=>{const r=s=>{if(!(n&&s===void 0))try{return t(s)}catch(i){throw new Ce(io,{message:`"${e}" transformer failed to parse the value`,cause:i})}};return Object.assign(r,{isValid(s){try{return r(s),!0}catch{return!1}}})}}function k(e,t){return I(t||"object",n=>{const r=co(n);return ao(e,s=>r[s])})}function Ae(e){throw new Ce(fa,`Unexpected value received: ${JSON.stringify(e)}`)}const Qe=I("boolean",e=>{if(typeof e=="boolean")return e;const t=String(e);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;Ae(e)}),D=I("string",e=>{if(typeof e=="string"||typeof e=="number")return e.toString();Ae(e)}),$e=I("number",e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}Ae(e)}),da=I("date",e=>e instanceof Date?e:new Date($e()(e)*1e3));function uo(e,t){return I(t||"searchParams",n=>{typeof n!="string"&&!(n instanceof URLSearchParams)&&Ae(n);const r=typeof n=="string"?new URLSearchParams(n):n;return ao(e,s=>{const i=r.get(s);return i===null?void 0:i})})}function Gt(e){for(const t in e)e[t]=[so(t),e[t]];return e}const pa=e=>{const t=$e(),n=$e(!0),r=D(),s=D(!0),i=Qe(!0),a=k(Gt({addedToAttachmentMenu:i,allowsWriteToPm:i,firstName:r,id:t,isBot:i,isPremium:i,languageCode:s,lastName:s,photoUrl:s,username:s}),"User")(!0);return uo(Gt({authDate:da(),canSendAfter:n,chat:k(Gt({id:t,type:r,title:r,photoUrl:s,username:s}),"Chat")(!0),chatInstance:s,chatType:s,hash:r,queryId:s,receiver:a,startParam:s,user:a}),"initData")(e)};function ma(e){return/^#[\da-f]{6}$/i.test(e)}function ha(e){return/^#[\da-f]{3}$/i.test(e)}function ba(e){const t=e.replace(/\s/g,"").toLowerCase();if(ma(t))return t;if(ha(t)){let r="#";for(let s=0;s<3;s+=1)r+=t[1+s].repeat(2);return r}const n=t.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||t.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(!n)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return n.slice(1).reduce((r,s)=>{const i=parseInt(s,10).toString(16);return r+(i.length===1?"0":"")+i},"#")}const Ea=I("rgb",e=>ba(D()(e))),lo=I("themeParams",e=>{const t=Ea(!0);return Object.entries(co(e)).reduce((n,[r,s])=>(n[ua(r)]=t(s),n),{})});function zt(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,n])=>[so(t),n])))}const ga=e=>{const t=D(),n=D(!0),r=Qe(!0);return uo({botInline:["tgWebAppBotInline",r],defaultColors:["tgWebAppDefaultColors",lo(!0)],fullscreen:["tgWebAppFullscreen",r],initData:["tgWebAppData",pa(!0)],initDataRaw:["tgWebAppData",n],platform:["tgWebAppPlatform",t],showSettings:["tgWebAppShowSettings",r],startParam:["tgWebAppStartParam",n],themeParams:["tgWebAppThemeParams",lo()],version:["tgWebAppVersion",t]},"launchParams")(e)};function wa(e){const{initDataRaw:t,startParam:n,showSettings:r,botInline:s,fullscreen:i,defaultColors:a}=e,c=new URLSearchParams;return c.set("tgWebAppPlatform",e.platform),c.set("tgWebAppThemeParams",zt(e.themeParams)),c.set("tgWebAppVersion",e.version),t&&c.set("tgWebAppData",t),n&&c.set("tgWebAppStartParam",n),typeof r=="boolean"&&c.set("tgWebAppShowSettings",r?"1":"0"),typeof s=="boolean"&&c.set("tgWebAppBotInline",s?"1":"0"),typeof i=="boolean"&&c.set("tgWebAppFullscreen",i?"1":"0"),a&&c.set("tgWebAppDefaultColors",zt(a)),c.toString()}const _o=k({eventType:D(),eventData:e=>e},"miniAppsMessage"),fo=I("fn",e=>{if(typeof e=="function")return e;Ae(e)});function ya(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}const Sa=k({TelegramWebviewProxy:k({postEvent:fo()})()});function po(e){return Sa().isValid(e)}function mo(){try{return window.self!==window.top}catch{return!0}}var Ca=Object.defineProperty,Aa=(e,t,n)=>t in e?Ca(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,ho=(e,t,n)=>Aa(e,typeof t!="symbol"?t+"":t,n);let _=class ea extends Error{constructor(t,n,r){super(typeof n=="object"?n.message:n||t,{cause:typeof n=="object"?n.cause:r}),this.type=t,Object.setPrototypeOf(this,ea.prototype)}};function Yt(e,t,n){return e.addEventListener(t,n),()=>e.removeEventListener(t,n)}function ee(...e){const t=e.flat(1);return[t.push.bind(t),()=>{t.forEach(n=>{n()})}]}function $a(e,t){return e instanceof _&&e.type===t}function Qt(e){return t=>$a(t,e)}const Jt="ERR_ABORTED",Zt="ERR_CANCELED",Kt="ERR_TIMED_OUT";function bo(e){return new _(Jt,{cause:e})}const Ra=Qt(Kt),va=Qt(Jt),Ta=Qt(Zt);function Eo(e,t){return e.reject=t.reject,e}class w extends Promise{constructor(t,n){let r,s;typeof t=="function"?(r=t,s=n):s=t;let i,a;super((c,f)=>{s||(s={});const{abortSignal:u}=s;if(u&&u.aborted)return f(bo(u.reason));const[p,E]=ee(),g=d=>(...G)=>(E(),d(...G)),M=new AbortController,{signal:A}=M;a=g(d=>{M.abort(d),f(d)}),i=g(c),u&&p(Yt(u,"abort",()=>{a(bo(u.reason))}));const{timeout:b}=s;if(b){const d=setTimeout(()=>{a(new _(Kt,`Timeout reached: ${b}ms`))},b);p(()=>{clearTimeout(d)})}r&&r(i,a,A)}),ho(this,"reject"),this.reject=a}static withFn(t,n){return new w((r,s,i)=>{try{const a=t(i);return a instanceof Promise?a.then(r,s):r(a)}catch(a){s(a)}},n)}static resolve(t){return new w(n=>{n(t)})}static reject(t){return new w((n,r)=>{r(t)})}cancel(){this.reject(new _(Zt))}catch(t){return this.then(void 0,t)}finally(t){return Eo(super.finally(t),this)}then(t,n){return Eo(super.then(t,n),this)}}function go(e,t){return e.resolve=t.resolve,e}let Oa=class Lt extends w{constructor(t,n){let r,s;typeof t=="function"?(r=t,s=n):s=t;let i;super((a,c,f)=>{i=a,r&&r(a,c,f)},s),ho(this,"resolve"),this.resolve=i}static withFn(t,n){return new Lt((r,s,i)=>w.withFn(t,{abortSignal:i}).then(r,s),n)}static resolve(t){return new Lt(n=>{n(t)})}static reject(t){return new Lt((n,r)=>{r(t)})}catch(t){return this.then(void 0,t)}finally(t){return go(super.finally(t),this)}then(t,n){return go(super.then(t,n),this)}};function Pa(e,t){return new w(n=>{setTimeout(n,e)},{abortSignal:t})}function wo(e){return`tapps/${e}`}function $(e,t){sessionStorage.setItem(wo(e),JSON.stringify(t))}function R(e){const t=sessionStorage.getItem(wo(e));try{return t?JSON.parse(t):void 0}catch{}}function Xt(e){return e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}function Ma(e,t){t||(t={});const{textColor:n,bgColor:r,shouldLog:s=!0}=t;function i(a,...c){if(!s||typeof s=="function"&&!s())return;const f="font-weight:bold;padding:0 5px;border-radius:5px";console[a](`%c${Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(new Date)}%c / %c${e}`,`${f};background-color: lightblue;color:black`,"",`${f};${n?`color:${n};`:""}${r?`background-color:${r}`:""}`,...c)}return[function(...a){i("log",...a)},function(...a){i("error",...a)}]}function Je(e,t){document.documentElement.style.setProperty(e,t)}function Ze(e){document.documentElement.style.removeProperty(e)}function Da(e,t){t()}function te(e,t){t||(t={});const n=t.equals||Object.is;let r=[],s=e;const i=u=>{if(!n(s,u)){const p=s;s=u,Da(f,()=>{[...r].forEach(([E,g])=>{E(u,p),g&&c(E,!0)})})}};function a(u){const p=typeof u!="object"?{once:u}:u;return{once:p.once||!1,signal:p.signal||!1}}const c=(u,p)=>{const E=a(p),g=r.findIndex(([M,A])=>M===u&&A.once===E.once&&A.signal===E.signal);g>=0&&r.splice(g,1)},f=Object.assign(function(){return Na(f),s},{destroy(){r=[]},set:i,reset(){i(e)},sub(u,p){return r.push([u,a(p)]),()=>c(u,p)},unsub:c,unsubAll(){r=r.filter(u=>u[1].signal)}});return f}const xt=[];function Na(e){xt.length&&xt[xt.length-1].add(e)}const yo=te(!1),[en,Ba]=Ma("Bridge",{bgColor:"#9147ff",textColor:"white",shouldLog:yo}),Ia={clipboard_text_received:k({req_id:D(),data:e=>e===null?e:D(!0)(e)},"clipboard_text_received"),custom_method_invoked:k({req_id:D(),result:e=>e,error:D(!0)},"custom_method_invoked"),popup_closed:I("popup_closed",e=>e?k({button_id:t=>t==null?void 0:D()(t)})()(e):{}),viewport_changed:k({height:$e(),width:e=>e==null?window.innerWidth:$e()(e),is_state_stable:Qe(),is_expanded:Qe()},"viewport_changed")};function ka(e){const t=window,[,n]=ee(Yt(t,"message",r=>{if(r.source!==t.parent)return;let s;try{s=_o()(r.data)}catch{return}const{eventType:i,eventData:a}=s,c=Ia[i];try{const f=c?c()(a):a;en("Event received:",f?{eventType:i,eventData:f}:{eventType:i}),e([i,f])}catch(f){Ba([`An error occurred processing the "${i}" event from the Telegram application.`,"Please, file an issue here:","https://github.com/Telegram-Mini-Apps/telegram-apps/issues/new/choose"].join(`
`),s,f)}}));return n}const tn=te(),So=te();function Co(){return So()||So.set(ka(tn.set)),tn}const nn=te({});function Ao(e){let t=nn()[e];return t||(t=te(void 0,{equals(){return!1}}),Co().sub(n=>{n&&n[0]===e&&t.set(n[1])}),nn.set({...nn(),[e]:t})),t}function C(e,t,n){return Ao(e).sub(t,n)}const $o="ERR_METHOD_UNSUPPORTED",Ro="ERR_RETRIEVE_LP_FAILED",vo="ERR_METHOD_PARAMETER_UNSUPPORTED",on="ERR_UNKNOWN_ENV",To="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",Oo=te("https://web.telegram.org");function Ke(e,t){en("Posting event:",t?{eventType:e,eventData:t}:{eventType:e});const n=window;if(po(n)){n.TelegramWebviewProxy.postEvent(e,JSON.stringify(t));return}const r=JSON.stringify({eventType:e,eventData:t});if(mo())return n.parent.postMessage(r,Oo());const{external:s}=n;if(k({notify:fo()})().isValid(s)){s.notify(r);return}throw new _(on)}function Xe(e,t,n){n||(n={});const{capture:r}=n,[s,i]=ee();return new w(a=>{(Array.isArray(t)?t:[t]).forEach(c=>{s(C(c,f=>{(!r||(Array.isArray(t)?r({event:c,payload:f}):r(f)))&&a(f)}))}),(n.postEvent||Ke)(e,n.params)},n).finally(i)}function rn(e){return ga()(e)}function Po(e){return rn(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function La(){return Po(window.location.href)}function Va(){const e=performance.getEntriesByType("navigation")[0];if(!e)throw new Error("Unable to get first navigation entry.");return Po(e.name)}const Ua="launchParams";function ja(){return rn(R(Ua)||"")}function Mo(e){$("launchParams",wa(e))}function Do(e){return e instanceof Error?e.message+(e.cause?`
${Do(e.cause)}`:""):JSON.stringify(e)}function Z(){const e=[];for(const t of[La,Va,ja])try{const n=t();return Mo(n),n}catch(n){e.push(n)}throw new _(Ro,["Unable to retrieve launch parameters from any known source. Perhaps, you have opened your app outside Telegram?","📖 Refer to docs for more information:","https://docs.telegram-mini-apps.com/packages/telegram-apps-sdk/environment","Collected errors:",...e.map(t=>`— ${Do(t)}`)].join(`
`))}function sn(e){if(e==="simple")try{return Z(),!0}catch{return!1}return w.withFn(async()=>{if(po(window))return!0;try{return await Xe("web_app_request_theme","theme_changed",{timeout:100}),!0}catch{return!1}},e)}function xe(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function qa(e,t){if(typeof t=="string")try{const{eventType:n}=_o()(t);n==="web_app_request_theme"&&xe("theme_changed",{theme_params:JSON.parse(zt(e))}),n==="web_app_request_viewport"&&xe("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}catch{}}function Fa(e){var t;const n=typeof e=="string"?rn(e):e;Mo(n);const r=(t=window.TelegramWebviewProxy)==null?void 0:t.postEvent;window.TelegramWebviewProxy={postEvent(s,i){qa(n.themeParams,JSON.stringify({eventType:s,eventData:i})),r==null||r(s,i)}},en("Environment was mocked by the mockTelegramEnv function")}function No(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((n,r,s)=>{if(r===s.length-1){t[n]=xe;return}n in t||(t[n]={}),t=t[n]})})}function Bo(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function F(e,t,n){Ao(e).unsub(t,n)}function Ha(e,t){return Co().sub(e,t)}function Wa(e,t){tn.unsub(e,t)}function Io(e){return({req_id:t})=>t===e}function ko(e){return e.split(".").map(Number)}function Lo(e,t){const n=ko(e),r=ko(t),s=Math.max(n.length,r.length);for(let i=0;i<s;i+=1){const a=n[i]||0,c=r[i]||0;if(a!==c)return a>c?1:-1}return 0}function y(e,t){return Lo(e,t)<=0}function z(e,t,n){if(typeof n=="string"){if(e==="web_app_open_link"){if(t==="try_instant_view")return y("6.4",n);if(t==="try_browser")return y("7.6",n)}if(e==="web_app_set_header_color"&&t==="color")return y("6.9",n);if(e==="web_app_close"&&t==="return_back")return y("7.6",n);if(e==="web_app_setup_main_button"&&t==="has_shine_effect")return y("7.10",n)}switch(e){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return y("6.1",t);case"web_app_open_popup":return y("6.2",t);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return y("6.4",t);case"web_app_switch_inline_query":return y("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return y("6.9",t);case"web_app_setup_settings_button":return y("6.10",t);case"web_app_biometry_get_info":case"web_app_biometry_open_settings":case"web_app_biometry_request_access":case"web_app_biometry_request_auth":case"web_app_biometry_update_token":return y("7.2",t);case"web_app_setup_swipe_behavior":return y("7.7",t);case"web_app_share_to_story":return y("7.8",t);case"web_app_setup_secondary_button":case"web_app_set_bottom_bar_color":return y("7.10",t);case"web_app_request_fullscreen":case"web_app_exit_fullscreen":return y("8.0",t);default:return["iframe_ready","iframe_will_reload","web_app_close","web_app_data_send","web_app_expand","web_app_open_link","web_app_ready","web_app_request_theme","web_app_request_viewport","web_app_setup_main_button","web_app_setup_closing_behavior"].includes(e)}}function Vo(e,t){t||(t="strict");const n=typeof t=="function"?t:r=>{const{method:s,version:i}=r;let a,c;if("param"in r?(a=`Parameter "${r.param}" of "${s}" method is unsupported in Mini Apps version ${i}`,c=vo):(a=`Method "${s}" is unsupported in Mini Apps version ${i}`,c=$o),t==="strict")throw new _(c,a);return console.warn(a)};return(r,s)=>z(r,e)?ya(s)&&r==="web_app_set_header_color"&&"color"in s&&!z(r,"color",e)?n({version:e,method:r,param:"color"}):Ke(r,s):n({version:e,method:r})}function Uo(e,t,n,r){return Xe("web_app_invoke_custom_method","custom_method_invoked",{...r||{},params:{method:e,params:t,req_id:n},capture:Io(n)}).then(({result:s,error:i})=>{if(i)throw new _(To,i);return s})}function Ga(){return performance.getEntriesByType("navigation")[0]}function N(){const e=Ga();return!!e&&e.type==="reload"}let ne;function za(e,t){ne&&ne.set(e,t)||t()}function an(e){if(ne)return e();ne=new Map;try{e()}finally{ne.forEach(t=>t()),ne=void 0}}function l(e,t){t||(t={});const n=t.equals||Object.is;let r=[],s=e;const i=u=>{if(!n(s,u)){const p=s;s=u,za(f,()=>{[...r].forEach(([E,g])=>{E(u,p),g&&c(E,!0)})})}};function a(u){const p=typeof u!="object"?{once:u}:u;return{once:p.once||!1,signal:p.signal||!1}}const c=(u,p)=>{const E=a(p),g=r.findIndex(([M,A])=>M===u&&A.once===E.once&&A.signal===E.signal);g>=0&&r.splice(g,1)},f=Object.assign(function(){return Ya(f),s},{destroy(){r=[]},set:i,reset(){i(e)},sub(u,p){return r.push([u,a(p)]),()=>c(u,p)},unsub:c,unsubAll(){r=r.filter(u=>u[1].signal)}});return f}const Re=[];function Ya(e){Re.length&&Re[Re.length-1].add(e)}function h(e,t){let n=new Set,r;function s(){return r||(r=l(a(),t))}function i(){s().set(a())}function a(){n.forEach(u=>{u.unsub(i,{signal:!0})});const c=new Set;let f;Re.push(c);try{f=e()}finally{Re.pop()}return c.forEach(u=>{u.sub(i,{signal:!0})}),n=c,f}return Object.assign(function(){return s()()},{destroy(){s().destroy()},sub(...c){return s().sub(...c)},unsub(...c){s().unsub(...c)},unsubAll(...c){s().unsubAll(...c)}})}const jo=l((()=>{let e=0;return()=>(e+=1).toString()})()),cn=l(Ke),L=l("0.0");function Qa(e){e||(e={});const{postEvent:t}=e,n=e.version||Z().version;L.set(n),cn.set(typeof t=="function"?t:Vo(n))}function qo(){return jo()()}function oe(e,t,n){return Uo(e,t,qo(),{...n||{},postEvent:m})}const v=(e,t,n)=>(n||(n={}),n.postEvent||(n.postEvent=m),Xe(e,t,n)),m=(e,t)=>cn()(e,t);function T(e){return h(()=>z(e,L()))}const re="ERR_POPUP_INVALID_PARAMS",et="ERR_INVALID_URL",Fo="ERR_INVALID_SLUG",Ho="ERR_DATA_INVALID_SIZE",Wo="ERR_ACCESS_DENIED",ve="ERR_ALREADY_REQUESTING",tt="ERR_ALREADY_OPENED",Go="ERR_ALREADY_MOUNTING",zo="ERR_VARS_ALREADY_BOUND",Yo="ERR_NOT_AVAILABLE",Qo="ERR_NOT_INITIALIZED",un="ERR_NOT_SUPPORTED",Jo="ERR_NOT_MOUNTED",Zo="ERR_FULLSCREEN_FAILED";function ln(){return typeof window>"u"}function V(e,t,{isSupported:n,isMounted:r,component:s,supports:i}={}){const a=`${s?`${s}.`:""}${e}()`;n=n?Array.isArray(n)||typeof n=="object"&&"any"in n?n:[n]:void 0;function c(b){if(i){const d=i[b];return z(d[0],d[1],L())}return!0}const f=()=>{if(!n)return;const b=`it is unsupported in Mini Apps version ${L()}`;function d(B){return typeof B=="string"?z(B,L())?void 0:b:B.fn()?void 0:B.error}if(Array.isArray(n)){for(const B of n){const Xi=d(B);if(Xi)return Xi}return}let G;for(const B of n.any)if(G=d(B),!G)return;return b},u=(...b)=>{if(i){for(const d in i)if(i[d][2](...b)&&!c(d))return`option ${d} is not supported in Mini Apps version ${L()}`}},p=h(()=>!f()),E=h(()=>L()!=="0.0"),g=h(()=>!r||r()),M=h(()=>sn("simple")&&!ln()&&E()&&p()&&g());let A;if(i){A={};for(const b in i)A[b]=h(()=>c(b))}return Object.assign((...b)=>{const d=`Unable to call the ${a} ${s?"method":"function"}:`;if(ln()||!sn("simple"))throw new _(on,`${d} it can't be called outside Mini Apps`);if(!E())throw new _(Qo,`${d} the SDK was not initialized. Use the SDK init() function`);const G=f();if(G)throw new _(un,`${d} ${G}`);const B=u(...b);if(B)throw new _(un,`${d} ${B}`);if(!g())throw new _(Jo,`${d} the component is not mounted. Use the ${s}.mount() method`);return t(...b)},t,{isAvailable:M,ifAvailable(...b){return M()?t(...b):void 0}},n?{isSupported:p}:{},A?{supports:A}:{})}function nt(e,t){return t||(t={}),(n,r,s,i)=>V(n,r,{...t,isSupported:s||t.isSupported,supports:i,component:e})}function Y(e,t,n){return nt(e,{isSupported:n,isMounted:t})}function O(e,t){return nt(e,{isSupported:t})}const ot="web_app_setup_back_button",Ko="back_button_pressed",rt="backButton",st=l(!1),se=l(!1),Xo=T(ot),xo=Y(rt,se,ot),_n=O(rt,ot),er=xo("hide",()=>{fn(!1)}),tr=_n("mount",()=>{se()||(fn(N()&&R(rt)||!1),se.set(!0))});function fn(e){e!==st()&&(m(ot,{is_visible:e}),$(rt,e),st.set(e))}const nr=_n("onClick",e=>C(Ko,e)),or=_n("offClick",e=>{F(Ko,e)}),rr=xo("show",()=>{fn(!0)});function sr(){se.set(!1)}const Ja=Object.freeze(Object.defineProperty({__proto__:null,hide:er,isMounted:se,isSupported:Xo,isVisible:st,mount:tr,offClick:or,onClick:nr,show:rr,unmount:sr},Symbol.toStringTag,{value:"Module"}));var Za=Object.defineProperty,Ka=(e,t,n)=>t in e?Za(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,Xa=(e,t,n)=>Ka(e,t+"",n);class Te extends Error{constructor(t,n,r){super(typeof n=="object"?n.message:n||t,{cause:typeof n=="object"?n.cause:r}),this.type=t,Object.setPrototypeOf(this,Te.prototype)}}function xa(e,t,n){return e.addEventListener(t,n),()=>e.removeEventListener(t,n)}function ec(...e){const t=e.flat(1);return[t.push.bind(t),()=>{t.forEach(n=>{n()})}]}const tc="ERR_ABORTED",nc="ERR_CANCELED",oc="ERR_TIMED_OUT";function ir(e){return new Te(tc,{cause:e})}function ar(e,t){return e.reject=t.reject,e}class ie extends Promise{constructor(t,n){let r,s;typeof t=="function"?(r=t,s=n):s=t;let i,a;super((c,f)=>{s||(s={});const{abortSignal:u}=s;if(u&&u.aborted)return f(ir(u.reason));const[p,E]=ec(),g=d=>(...G)=>(E(),d(...G)),M=new AbortController,{signal:A}=M;a=g(d=>{M.abort(d),f(d)}),i=g(c),u&&p(xa(u,"abort",()=>{a(ir(u.reason))}));const{timeout:b}=s;if(b){const d=setTimeout(()=>{a(new Te(oc,`Timeout reached: ${b}ms`))},b);p(()=>{clearTimeout(d)})}r&&r(i,a,A)}),Xa(this,"reject"),this.reject=a}static withFn(t,n){return new ie((r,s,i)=>{try{const a=t(i);return a instanceof Promise?a.then(r,s):r(a)}catch(a){s(a)}},n)}static resolve(t){return new ie(n=>{n(t)})}static reject(t){return new ie((n,r)=>{r(t)})}cancel(){this.reject(new Te(nc))}catch(t){return this.then(void 0,t)}finally(t){return ar(super.finally(t),this)}then(t,n){return ar(super.then(t,n),this)}}function cr(e,t,n,r){return Object.assign(s=>ie.resolve().then(async()=>{if(n()){const a=t();throw r.set(a),a}an(()=>{n.set(ie.resolve(e(s))),r.set(void 0)});let i;try{i=[!0,await n()]}catch(a){i=[!1,a]}if(an(()=>{n.set(void 0),r.set(i[0]?void 0:i[1])}),!i[0])throw i[1];return i[1]}),e)}function ur(e,t,n,r,s,i,a){const c=cr(t,()=>new _(Go,`The ${e} component is already mounting`),i,a);return f=>w.resolve().then(async()=>{if(!r()){const u=await c(f);an(()=>{s.set(u),r.set(!0),n(u)})}return s()})}const H=nt,ae=l({available:!1}),Oe=l(!1),Pe=l(!1),Me=l(!1),lr=h(()=>!!pn()),dn=l(),pn=l(),rc=h(()=>{const e=ae();return e&&e.available});function mn(e){return e.available?{available:!0,tokenSaved:e.token_saved,deviceId:e.device_id,accessRequested:e.access_requested,type:e.type,accessGranted:e.access_granted}:{available:!1}}const _r="web_app_biometry_get_info",fr=V("requestBiometry",e=>v(_r,"biometry_info_received",e).then(mn),{isSupported:_r}),it="web_app_biometry_request_auth",sc="web_app_biometry_request_access",ic="web_app_biometry_open_settings",ac="web_app_biometry_update_token",hn="biometry_info_received",ce="biometry",dr=T(it),cc=H(ce),uc=O(ce,it),bn=Y(ce,Me,it);function pr(){throw new _(Yo,"Biometry is not available")}const mr=bn("authenticate",e=>w.withFn(async t=>{if(Oe())throw new _(ve,"Authentication is already in progress");const n=ae();(!n||!n.available)&&pr(),Oe.set(!0);try{const r=await v(it,"biometry_auth_requested",{abortSignal:t,params:{reason:((e||{}).reason||"").trim()}}),{token:s}=r;return typeof s=="string"&&at({...n,token:s}),r}finally{Oe.set(!1)}},e)),hr=uc("openSettings",()=>{m(ic)}),br=bn("requestAccess",e=>w.withFn(async t=>{if(Pe())throw new _(ve,"Access request is already in progress");Pe.set(!0);try{const n=await v(sc,hn,{abortSignal:t,params:{reason:(e||{}).reason||""}}).then(mn);return n.available||pr(),at(n),n.accessGranted}finally{Pe.set(!1)}},e)),Er=cc("mount",ur(ce,e=>{const t=N()&&R(ce);return t||fr(e)},e=>{C(hn,gr),at(e)},Me,ae,pn,dn)),gr=e=>{at(mn(e))};function at(e){ae.set(e),$(ce,e)}function wr(){F(hn,gr),Me.set(!1)}const yr=bn("updateToken",e=>(e||(e={}),v(ac,"biometry_token_updated",{...e,params:{token:e.token||"",reason:e.reason}}).then(t=>t.status))),lc=Object.freeze(Object.defineProperty({__proto__:null,authenticate:mr,isAuthenticating:Oe,isAvailable:rc,isMounted:Me,isMounting:lr,isRequestingAccess:Pe,isSupported:dr,mount:Er,mountError:dn,mountPromise:pn,openSettings:hr,requestAccess:br,state:ae,unmount:wr,updateToken:yr},Symbol.toStringTag,{value:"Module"}));function ct(e,t){return nt(e,{isMounted:t})}const ut="closingBehavior",lt=l(!1),ue=l(!1),Sr=ct(ut,ue),_c=H(ut),Cr=Sr("disableConfirmation",()=>{En(!1)}),Ar=Sr("enableConfirmation",()=>{En(!0)}),$r=_c("mount",()=>{ue()||(En(N()&&R(ut)||!1),ue.set(!0))});function En(e){e!==lt()&&(m("web_app_setup_closing_behavior",{need_confirmation:e}),$(ut,e),lt.set(e))}function Rr(){ue.set(!1)}const fc=Object.freeze(Object.defineProperty({__proto__:null,disableConfirmation:Cr,enableConfirmation:Ar,isConfirmationEnabled:lt,isMounted:ue,mount:$r,unmount:Rr},Symbol.toStringTag,{value:"Module"})),vr="web_app_invoke_custom_method",_t=O("cloudStorage",vr),Tr=T(vr),Or=_t("deleteItem",(e,t)=>{const n=Array.isArray(e)?e:[e];return n.length?oe("deleteStorageValues",{keys:n},t).then():w.resolve()});function dc(e,t){const n=Array.isArray(e)?e:[e];return n.length?oe("getStorageValues",{keys:n},t).then(r=>{const s=Ge(Object.fromEntries(n.map(i=>[i,q()])))()(r);return Array.isArray(e)?s:s[e]}):w.resolve(typeof e=="string"?"":{})}const Pr=_t("getItem",dc),Mr=_t("getKeys",e=>oe("getStorageKeys",{},e).then(aa(q())())),Dr=_t("setItem",(e,t,n)=>oe("saveStorageValue",{key:e,value:t},n).then()),pc=Object.freeze(Object.defineProperty({__proto__:null,deleteItem:Or,getItem:Pr,getKeys:Mr,isSupported:Tr,setItem:Dr},Symbol.toStringTag,{value:"Module"})),ft="web_app_request_fullscreen",Nr="web_app_exit_fullscreen",mc="fullscreen_changed",hc="fullscreen_failed",dt="fullScreen",le=l(!1),Br=T(ft)||T(Nr),De=l(!1),bc=O(dt,ft),Ir=Y(dt,le,ft),kr=Ir("requestFullScreen",()=>Ur(!0)),Lr=Ir("exitFullScreen",()=>Ur(!1)),Vr=bc("mount",()=>{le()||(pt(N()&&R(dt)||!1),le.set(!0))});async function Ur(e){const n=await v(e?ft:Nr,[mc,hc]);return"error"in n?Ec(n.error):(pt(n.is_fullscreen),De())}function pt(e){$(dt,e),De.set(e)}function Ec(e){switch(e){case"ALREADY_FULLSCREEN":return De()||pt(!0),"ALREADY_FULLSCREEN";case"UNSUPPORTED":return pt(!1),"UNSUPPORTED";default:return e}}function jr(){le.set(!1)}const gc=Object.freeze(Object.defineProperty({__proto__:null,exitFullScreen:Lr,isFullScreen:De,isMounted:le,isSupported:Br,mount:Vr,requestFullScreen:kr,unmount:jr},Symbol.toStringTag,{value:"Module"})),Ne="web_app_trigger_haptic_feedback",gn=O("hapticFeedback",Ne),qr=T(Ne),Fr=gn("impactOccurred",e=>{m(Ne,{type:"impact",impact_style:e})}),Hr=gn("notificationOccurred",e=>{m(Ne,{type:"notification",notification_type:e})}),Wr=gn("selectionChanged",()=>{m(Ne,{type:"selection_change"})}),wc=Object.freeze(Object.defineProperty({__proto__:null,impactOccurred:Fr,isSupported:qr,notificationOccurred:Hr,selectionChanged:Wr},Symbol.toStringTag,{value:"Module"})),mt=l(void 0);function U(e){return h(()=>{const t=mt();return t?t[e]:void 0})}const wn=U("authDate"),yn=U("canSendAfter"),Gr=h(()=>{const e=wn(),t=yn();return t&&e?new Date(e.getTime()+t*1e3):void 0}),zr=U("chat"),Yr=U("chatType"),Qr=U("chatInstance"),Jr=U("hash"),Zr=U("queryId"),Sn=l(),Kr=U("receiver");function Xr(){const e=Z();mt.set(e.initData),Sn.set(e.initDataRaw)}const xr=U("startParam"),es=U("user"),yc=Object.freeze(Object.defineProperty({__proto__:null,authDate:wn,canSendAfter:yn,canSendAfterDate:Gr,chat:zr,chatInstance:Qr,chatType:Yr,hash:Jr,queryId:Zr,raw:Sn,receiver:Kr,restore:Xr,startParam:xr,state:mt,user:es},Symbol.toStringTag,{value:"Module"}));function Sc(e){return oa()(e)}const Cn="web_app_open_invoice",Cc=O("invoice",Cn),Be=l(!1),ts=T(Cn);async function ns(e,t,n){if(Be())throw new _(tt,"An invoice is already opened");let r;if(t==="url"){const{hostname:s,pathname:i}=new URL(e,window.location.href);if(s!=="t.me")throw new _(et,`Link has unexpected hostname: ${s}`);const a=i.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!a)throw new _(Fo,'Expected to receive a link with a pathname in format "/invoice/{slug}" or "/${slug}"');[,,r]=a}else r=e,n=t;return Be.set(!0),v(Cn,"invoice_closed",{...n,params:{slug:r},capture:s=>r===s.slug}).then(s=>s.status).finally(()=>{Be.set(!1)})}const os=Cc("open",ns),Ac=Object.freeze(Object.defineProperty({__proto__:null,_open:ns,isOpened:Be,isSupported:ts,open:os},Symbol.toStringTag,{value:"Module"}));function rs(e){return Object.fromEntries(Object.entries(e).filter(t=>t[1]!==void 0))}function An(e){const t=Ft(e);return Math.sqrt([.299,.587,.114].reduce((n,r,s)=>{const i=parseInt(t.slice(1+s*2,1+(s+1)*2),16);return n+i*i*r},0))<120}const _e=l(!1),Ie=l(!1),W=l({});function S(e){return h(()=>W()[e])}const ss=S("accentTextColor"),ht=S("bgColor"),bt=S("buttonColor"),$n=S("buttonTextColor"),Rn=S("bottomBarBgColor"),is=S("destructiveTextColor"),as=S("headerBgColor"),cs=S("hintColor"),us=h(()=>{const{bgColor:e}=W();return!e||An(e)}),ls=S("linkColor"),ke=S("secondaryBgColor"),_s=S("sectionBgColor"),fs=S("sectionHeaderTextColor"),ds=S("sectionSeparatorColor"),ps=S("subtitleTextColor"),ms=S("textColor");function K(e){return h(()=>Et()[e])}const Le=l({hasShineEffect:!1,isEnabled:!0,isLoaderVisible:!1,isVisible:!1,text:"Continue"}),Et=h(()=>{const e=Le();return{...e,backgroundColor:e.backgroundColor||bt()||"#2481cc",textColor:e.textColor||$n()||"#ffffff"}}),fe=l(!1),hs=K("backgroundColor"),bs=K("hasShineEffect"),Es=K("isEnabled"),gs=K("isLoaderVisible"),ws=K("isVisible"),ys=K("text"),Ss=K("textColor"),$c="web_app_setup_main_button",Cs="main_button_pressed",gt="mainButton",vn=H(gt),Rc=ct(gt,fe),As=vn("mount",()=>{if(!fe()){const e=N()&&R(gt);e&&Le.set(e),fe.set(!0)}}),$s=vn("onClick",e=>C(Cs,e)),Rs=vn("offClick",e=>{F(Cs,e)}),vs=Rc("setParams",e=>{Le.set({...Le(),...rs(e)}),$(gt,Le());const t=Et();t.text&&m($c,{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 Ts(){fe.set(!1)}const vc=Object.freeze(Object.defineProperty({__proto__:null,backgroundColor:hs,hasShineEffect:bs,isEnabled:Es,isLoaderVisible:gs,isMounted:fe,isVisible:ws,mount:As,offClick:Rs,onClick:$s,setParams:vs,state:Et,text:ys,textColor:Ss,unmount:Ts},Symbol.toStringTag,{value:"Module"}));function Tn(){throw new _(zo,"CSS variables are already bound")}function Os(e){return sa()(e)}const wt="themeParams",Ps="theme_changed",Tc=H(wt),Ms=ct(wt,_e)("bindCssVars",e=>{Ie()&&Tn(),e||(e=r=>`--tg-theme-${Xt(r)}`);function t(r){Object.entries(W()).forEach(([s,i])=>{i&&r(s,i)})}function n(){t((r,s)=>{Je(e(r),s)})}return n(),W.sub(n),Ie.set(!0),()=>{t(Ze),W.unsub(n),Ie.set(!1)}}),On=Tc("mount",()=>{_e()||(C(Ps,Ds),W.set(N()&&R(wt)||Z().themeParams),_e.set(!0))}),Ds=e=>{const t=Os(e.theme_params);W.set(t),$(wt,t)};function Ns(){F(Ps,Ds),_e.set(!1)}function Bs(e){return h(()=>{const t=e();return x(t)?t:t==="bg_color"?ht():ke()})}const de=l("bg_color"),Pn=Bs(de),pe=l("bottom_bar_bg_color"),yt=h(()=>{const e=pe();return x(e)?e:e==="bottom_bar_bg_color"?Rn()||ke():e==="secondary_bg_color"?ke():ht()}),me=l("bg_color"),Mn=Bs(me),he=l(!1),Ve=l(!1),Is=h(()=>{const e=Pn();return e?An(e):!1}),Dn=h(()=>({backgroundColor:de(),bottomBarColor:pe(),headerColor:me()})),Nn="web_app_set_background_color",Bn="web_app_set_bottom_bar_color",St="web_app_set_header_color",Ue="miniApp",In={any:[Nn,Bn,St]},ks=h(()=>In.any.some(e=>z(e,L()))),Ls=H(Ue),Oc=O(Ue,In),Ct=Y(Ue,he,In),Vs=Ct("bindCssVars",e=>{Ve()&&Tn();const[t,n]=ee();function r(s,i){function a(){Je(s,i()||null)}a(),t(i.sub(a),Ze.bind(null,s))}return e||(e=s=>`--tg-${Xt(s)}`),r(e("bgColor"),Pn),r(e("bottomBarColor"),yt),r(e("headerColor"),Mn),t(()=>{Ve.set(!1)}),Ve.set(!0),n}),Us=Ls("close",e=>{m("web_app_close",{return_back:e})}),js=Oc("mount",()=>{if(!he()){const e=N()&&R(Ue);On(),Ln.ifAvailable(e?e.backgroundColor:"bg_color"),Vn.ifAvailable(e?e.bottomBarColor:"bottom_bar_bg_color"),Un.ifAvailable(e?e.headerColor:"bg_color"),he.set(!0)}}),qs=Ls("ready",()=>{m("web_app_ready")});function kn(){$(Ue,Dn())}const Ln=Ct("setBackgroundColor",e=>{e!==de()&&(m(Nn,{color:e}),de.set(e),kn())},Nn),Vn=Ct("setBottomBarColor",e=>{e!==pe()&&(m(Bn,{color:e}),pe.set(e),kn())},Bn),Un=Ct("setHeaderColor",e=>{e!==me()&&(m(St,x(e)?{color:e}:{color_key:e}),me.set(e),kn())},St,{rgb:[St,"color",x]});function Fs(){he.set(!1)}const Pc=Object.freeze(Object.defineProperty({__proto__:null,backgroundColor:de,backgroundColorRGB:Pn,bindCssVars:Vs,bottomBarColor:pe,bottomBarColorRGB:yt,close:Us,headerColor:me,headerColorRGB:Mn,isCssVarsBound:Ve,isDark:Is,isMounted:he,isSupported:ks,mount:js,ready:qs,setBackgroundColor:Ln,setBottomBarColor:Vn,setHeaderColor:Un,state:Dn,unmount:Fs},Symbol.toStringTag,{value:"Module"}));function Mc(e){const t=e.message.trim(),n=(e.title||"").trim(),r=e.buttons||[];if(n.length>64)throw new _(re,`Invalid title: ${n}`);if(!t||t.length>256)throw new _(re,`Invalid message: ${t}`);if(r.length>3)throw new _(re,`Invalid buttons count: ${r.length}`);return{title:n,message:t,buttons:r.length?r.map((s,i)=>{const a=s.id||"";if(a.length>64)throw new _(re,`Button with index ${i} has invalid id: ${a}`);if(!s.type||s.type==="default"||s.type==="destructive"){const c=s.text.trim();if(!c||c.length>64)throw new _(re,`Button with index ${i} has invalid text: ${c}`);return{type:s.type,text:c,id:a}}return{type:s.type,id:a}}):[{type:"close",id:""}]}}const jn="web_app_open_popup",Dc=O("popup",jn),je=l(!1),Hs=T(jn),Ws=Dc("open",async e=>{if(je())throw new _(tt,"A popup is already opened");je.set(!0);try{const{button_id:t=null}=await v(jn,"popup_closed",{...e,params:Mc(e)});return t}finally{je.set(!1)}}),Nc=Object.freeze(Object.defineProperty({__proto__:null,isOpened:je,isSupported:Hs,open:Ws},Symbol.toStringTag,{value:"Module"})),Bc="web_app_close_scan_qr_popup",qn="web_app_open_scan_qr_popup",Ic="scan_qr_popup_closed",kc="qr_text_received",Gs=O("qrScanner",qn),At=Gs("close",()=>{X.set(!1),m(Bc)}),X=l(!1),zs=T(qn);function Lc(e){return w.withFn(t=>{if(X())throw new _(tt,"The QR Scanner is already opened");X.set(!0),e||(e={});const{onCaptured:n,text:r,capture:s}=e,[,i]=ee(X.sub(()=>{a.resolve()}),C(Ic,()=>{X.set(!1)}),C(kc,c=>{n?n(c.data):(!s||s(c.data))&&(a.resolve(c.data),At())})),a=new Oa({abortSignal:t}).catch(At).finally(i);return(e.postEvent||m)(qn,{text:r}),a},e)}const Ys=Gs("open",Lc),Vc=Object.freeze(Object.defineProperty({__proto__:null,close:At,isOpened:X,isSupported:zs,open:Ys},Symbol.toStringTag,{value:"Module"}));function Q(e){return h(()=>$t()[e])}const qe=l({hasShineEffect:!1,isEnabled:!0,isLoaderVisible:!1,isVisible:!1,position:"left",text:"Cancel"}),$t=h(()=>{const e=qe();return{...e,backgroundColor:e.backgroundColor||yt()||"#000000",textColor:e.textColor||bt()||"#2481cc"}}),be=l(!1),Qs=Q("backgroundColor"),Js=Q("hasShineEffect"),Zs=Q("isEnabled"),Ks=Q("isLoaderVisible"),Xs=Q("isVisible"),xs=Q("position"),ei=Q("text"),ti=Q("textColor"),Rt="web_app_setup_secondary_button",ni="secondary_button_pressed",vt="secondaryButton",Fn=O(vt,Rt),Uc=Y(vt,be,Rt),oi=T(Rt),ri=Fn("mount",()=>{if(!be()){const e=N()&&R(vt);e&&qe.set(e),be.set(!0)}}),si=Fn("onClick",e=>C(ni,e)),ii=Fn("offClick",e=>{F(ni,e)}),ai=Uc("setParams",e=>{qe.set({...qe(),...Object.fromEntries(Object.entries(e).filter(([,n])=>n!==void 0))}),$(vt,qe());const t=$t();t.text&&m(Rt,{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 ci(){be.set(!1)}const jc=Object.freeze(Object.defineProperty({__proto__:null,backgroundColor:Qs,hasShineEffect:Js,isEnabled:Zs,isLoaderVisible:Ks,isMounted:be,isSupported:oi,isVisible:Xs,mount:ri,offClick:ii,onClick:si,position:xs,setParams:ai,state:$t,text:ei,textColor:ti,unmount:ci},Symbol.toStringTag,{value:"Module"})),Tt="web_app_setup_settings_button",ui="settings_button_pressed",Ot="settingsButton",Pt=l(!1),Ee=l(!1),li=T(Tt),Hn=O(Ot,Tt),_i=Y(Ot,Ee,Tt),fi=_i("hide",()=>{Wn(!1)}),di=Hn("mount",()=>{Ee()||(Wn(N()&&R(Ot)||!1),Ee.set(!0))});function Wn(e){e!==Pt()&&(m(Tt,{is_visible:e}),$(Ot,e),Pt.set(e))}const pi=Hn("onClick",e=>C(ui,e)),mi=Hn("offClick",e=>{F(ui,e)}),hi=_i("show",()=>{Wn(!0)});function bi(){Ee.set(!1)}const qc=Object.freeze(Object.defineProperty({__proto__:null,hide:fi,isMounted:Ee,isSupported:li,isVisible:Pt,mount:di,offClick:mi,onClick:pi,show:hi,unmount:bi},Symbol.toStringTag,{value:"Module"})),Mt="web_app_setup_swipe_behavior",Dt="swipeBehavior",ge=l(!1),Ei=T(Mt),Nt=l(!0),Fc=O(Dt,Mt),gi=Y(Dt,ge,Mt),wi=gi("disableVertical",()=>{Gn(!1)}),yi=gi("enableVertical",()=>{Gn(!0)}),Si=Fc("mount",()=>{ge()||(Gn(N()&&R(Dt)||!1,!0),ge.set(!0))});function Gn(e,t){(e!==Nt()||t)&&(m(Mt,{allow_vertical_swipe:e}),$(Dt,e),Nt.set(e))}function Ci(){ge.set(!1)}const Hc=Object.freeze(Object.defineProperty({__proto__:null,disableVertical:wi,enableVertical:yi,isMounted:ge,isSupported:Ei,isVerticalEnabled:Nt,mount:Si,unmount:Ci},Symbol.toStringTag,{value:"Module"})),Wc=Object.freeze(Object.defineProperty({__proto__:null,accentTextColor:ss,backgroundColor:ht,bindCssVars:Ms,bottomBarBgColor:Rn,buttonColor:bt,buttonTextColor:$n,destructiveTextColor:is,headerBackgroundColor:as,hintColor:cs,isCssVarsBound:Ie,isDark:us,isMounted:_e,linkColor:ls,mount:On,secondaryBackgroundColor:ke,sectionBackgroundColor:_s,sectionHeaderTextColor:fs,sectionSeparatorColor:ds,state:W,subtitleTextColor:ps,textColor:ms,unmount:Ns},Symbol.toStringTag,{value:"Module"})),P=l({height:0,width:0,isFullscreen:!1,isExpanded:!1,stableHeight:0}),we=l(!1),Ai=h(()=>!!Fe()),zn=l(void 0),Fe=l(),He=l(!1);function We(e){return h(()=>P()[e])}const $i=We("height"),Ri=We("isExpanded"),vi=h(()=>{const e=P();return e.height===e.stableHeight}),Ti=We("stableHeight"),Oi=We("width"),Yn=We("isFullscreen"),Bt=l(),Pi=h(()=>!!Bt()),Qn=l();function Mi(e){return v("web_app_request_viewport","viewport_changed",e).then(t=>({height:t.height,width:t.width,isExpanded:t.is_expanded,isStable:t.is_state_stable}))}const ye="viewport",Di="web_app_request_fullscreen",Gc="fullscreen_failed",Ni="fullscreen_changed",Bi=H(ye),zc=ct(ye,we),Yc=Y(ye,we,Di),Ii=zc("bindCssVars",e=>{He()&&Tn(),e||(e=r=>`--tg-viewport-${Xt(r)}`);const t=["height","width","stableHeight"];function n(){t.forEach(r=>{Je(e(r),`${P()[r]}px`)})}return n(),P.sub(n),He.set(!0),()=>{t.forEach(Ze),P.unsub(n),He.set(!1)}}),ki=Bi("expand",()=>{m("web_app_expand")}),Li=Bi("mount",ur(ye,e=>{const t=N()&&R(ye);if(t)return t;const n=Z(),r=!!n.fullscreen;if(["macos","tdesktop","unigram","webk","weba","web"].includes(n.platform)){const s=window;return{isExpanded:!0,isFullscreen:r,height:s.innerHeight,width:s.innerWidth,stableHeight:s.innerHeight}}return Mi(e).then(s=>({height:s.height,isExpanded:s.isExpanded,isFullscreen:r,stableHeight:s.isStable?s.height:P().stableHeight,width:s.width}))},()=>{C("viewport_changed",Vi),C(Ni,Ui)},we,P,Fe,zn)),Vi=e=>{Jn({height:e.height,isExpanded:e.is_expanded,stableHeight:e.is_state_stable?e.height:void 0,width:e.width})},Ui=e=>{Jn({isFullscreen:e.is_fullscreen})};function ji(e,t){return Yc(e,cr(n=>v(t,[Ni,Gc],n).then(r=>{if("error"in r){if(r.error==="ALREADY_FULLSCREEN")return!0;throw new _(Zo,"Fullscreen request failed",r.error)}return r.is_fullscreen}).then(r=>{Yn()!==r&&Jn({isFullscreen:r})}),()=>new _("abc"),Bt,Qn))}const qi=ji("requestFullscreen",Di),Fi=ji("exitFullscreen","web_app_exit_fullscreen");function Jn(e){const{height:t,stableHeight:n,width:r}=e;P.set({...P(),...rs({...e,height:t?Zn(t):void 0,width:r?Zn(r):void 0,stableHeight:n?Zn(n):void 0})}),$(ye,P())}function Zn(e){return Math.max(e,0)}function Hi(){const e=Fe();e&&e.cancel(),F("viewport_changed",Vi),F("fullscreen_changed",Ui),we.set(!1)}const Qc=Object.freeze(Object.defineProperty({__proto__:null,bindCssVars:Ii,changeFullscreenError:Qn,changeFullscreenPromise:Bt,exitFullscreen:Fi,expand:ki,height:$i,isChangingFullscreen:Pi,isCssVarsBound:He,isExpanded:Ri,isFullscreen:Yn,isMounted:we,isMounting:Ai,isStable:vi,mount:Li,mountError:zn,mountPromise:Fe,requestFullscreen:qi,stableHeight:Ti,state:P,unmount:Hi,width:Oi},Symbol.toStringTag,{value:"Module"})),Jc=H()("openLink",(e,t)=>{if(typeof e=="string")try{e=new URL(e)}catch(n){throw new _(et,`"${e.toString()}" is invalid URL`,n)}t||(t={}),m("web_app_open_link",{url:e.toString(),try_browser:t.tryBrowser,try_instant_view:t.tryInstantView})}),Wi="web_app_open_tg_link",Gi=H()("openTelegramLink",e=>{const t=e.toString();if(!t.match(/^https:\/\/t.me\/.+/))throw new _(et,`"${t}" is invalid URL`);if(!z(Wi,L())){window.location.href=t;return}e=new URL(e),m(Wi,{path_full:e.pathname+e.search})}),Zc=H()("shareURL",(e,t)=>{Gi("https://t.me/share/url?"+new URLSearchParams({url:e,text:t||""}).toString().replace(/\+/g,"%20"))}),Kn="web_app_request_phone",It=l(!1),zi=V("requestPhoneAccess",e=>{if(It())throw new _(ve,"Phone access request is currently in progress");return It.set(!0),v(Kn,"phone_requested",e).then(t=>t.status).finally(()=>{It.set(!1)})},{isSupported:Kn});function Yi(e){return e||(e={}),oe("getRequestedContact",{},{...e,timeout:e.timeout||5e3}).then(oo({contact:Ge({userId:["user_id",ze()],phoneNumber:["phone_number",q()],firstName:["first_name",q()],lastName:["last_name",q(!0)]})(),authDate:["auth_date",jt()],hash:q()})())}const Kc=V("requestContact",e=>w.withFn(async t=>{const n={abortSignal:t};try{return await Yi(n)}catch{}if(await zi(n)!=="sent")throw new _(Wo,"User denied access");let s=50;for(;!t.aborted;){try{return await Yi(n)}catch{}await Pa(s),s+=50}return null},e),{isSupported:Kn}),Qi="web_app_request_write_access",kt=l(!1),Xc=V("requestWriteAccess",e=>{if(kt())throw new _(ve,"Write access request is currently in progress");return kt.set(!0),v(Qi,"write_access_requested",e).then(t=>t.status).finally(()=>{kt.set(!1)})},{isSupported:Qi}),xc=V("getCurrentTime",e=>oe("getCurrentTime",{},e).then(jt()),{isSupported:"web_app_invoke_custom_method"}),Ji="web_app_read_text_from_clipboard",eu=V("readTextFromClipboard",e=>{const t=qo();return v(Ji,"clipboard_text_received",{...e,params:{req_id:t},capture:Io(t)}).then(({data:n=null})=>n)},{isSupported:Ji}),tu=V("sendData",e=>{const{size:t}=new Blob([e]);if(!t||t>4096)throw new _(Ho,t?"Maximum size of data to send is 4096 bytes":"Attempted to send empty data");m("web_app_data_send",{data:e})}),Zi="web_app_share_to_story",nu=V("shareStory",(e,t)=>{t||(t={}),m(Zi,{text:t.text,media_url:e,widget_link:t.widgetLink})},{isSupported:Zi}),Ki="web_app_switch_inline_query",ou=V("switchInlineQuery",(e,t)=>{m(Ki,{query:e,chat_types:t||[]})},{isSupported:[Ki,{fn:()=>!!Z().botInline,error:"Mini App should be ran in Bot inline mode"}]});function ru(e){try{return{result:e()}}catch(t){return{error:t}}}function su(e){Qa(e),No();const[t,n]=ee(C("reload_iframe",()=>{m("iframe_will_reload"),window.location.reload()}),Bo),{acceptCustomStyles:r=!0}=e||{};if(r){const s=document.createElement("style");s.id="telegram-custom-styles",document.head.appendChild(s),t(C("set_custom_style",i=>{s.innerHTML=i}),()=>{document.head.removeChild(s)})}return m("iframe_ready",{reload_supported:!0}),n}return o.$createRequestId=jo,o.$debug=yo,o.$postEvent=cn,o.$targetOrigin=Oo,o.$version=L,o.CancelablePromise=w,o.ERR_ABORTED=Jt,o.ERR_ACCESS_DENIED=Wo,o.ERR_ALREADY_MOUNTING=Go,o.ERR_ALREADY_OPENED=tt,o.ERR_ALREADY_REQUESTING=ve,o.ERR_CANCELED=Zt,o.ERR_CSS_VARS_ALREADY_BOUND=zo,o.ERR_CUSTOM_METHOD_ERR_RESPONSE=To,o.ERR_DATA_INVALID_SIZE=Ho,o.ERR_FULLSCREEN_FAILED=Zo,o.ERR_INVALID_SLUG=Fo,o.ERR_INVALID_URL=et,o.ERR_INVALID_VALUE=xn,o.ERR_METHOD_PARAMETER_UNSUPPORTED=vo,o.ERR_METHOD_UNSUPPORTED=$o,o.ERR_NOT_AVAILABLE=Yo,o.ERR_NOT_INITIALIZED=Qo,o.ERR_NOT_MOUNTED=Jo,o.ERR_NOT_SUPPORTED=un,o.ERR_PARSE=Vt,o.ERR_POPUP_INVALID_PARAMS=re,o.ERR_RETRIEVE_LP_FAILED=Ro,o.ERR_TIMED_OUT=Kt,o.ERR_UNEXPECTED_TYPE=to,o.ERR_UNEXPECTED_VALUE=eo,o.ERR_UNKNOWN_ENV=on,o.TypedError=_,o.addEventListener=Yt,o.authenticateBiometry=mr,o.backButton=Ja,o.bindMiniAppCssVars=Vs,o.bindThemeParamsCssVars=Ms,o.bindViewportCssVars=Ii,o.biometry=lc,o.biometryMountError=dn,o.biometryState=ae,o.changeFullscreenError=Qn,o.changeFullscreenPromise=Bt,o.classNames=Ye,o.closeMiniApp=Us,o.closeQrScanner=At,o.closingBehavior=fc,o.cloudStorage=pc,o.compareVersions=Lo,o.createPostEvent=Vo,o.defineEventHandlers=No,o.deleteCloudStorageItem=Or,o.deleteCssVar=Ze,o.disableClosingConfirmation=Cr,o.disableVerticalSwipes=wi,o.emitMiniAppsEvent=xe,o.enableClosingConfirmation=Ar,o.enableVerticalSwipes=yi,o.exitFullScreen=Lr,o.exitFullscreen=Fi,o.expandViewport=ki,o.fullScreen=gc,o.getCloudStorageItem=Pr,o.getCloudStorageKeys=Mr,o.getCurrentTime=xc,o.hapticFeedback=wc,o.hapticFeedbackImpactOccurred=Fr,o.hapticFeedbackNotificationOccurred=Hr,o.hapticFeedbackSelectionChanged=Wr,o.hideBackButton=er,o.hideSettingsButton=fi,o.init=su,o.initData=yc,o.initDataAuthDate=wn,o.initDataCanSendAfter=yn,o.initDataCanSendAfterDate=Gr,o.initDataChat=zr,o.initDataChatInstance=Qr,o.initDataChatType=Yr,o.initDataHash=Jr,o.initDataQueryId=Zr,o.initDataRaw=Sn,o.initDataReceiver=Kr,o.initDataStartParam=xr,o.initDataState=mt,o.initDataUser=es,o.invoice=Ac,o.invokeCustomMethod=Uo,o.isAbortError=va,o.isAuthenticatingBiometry=Oe,o.isBackButtonMounted=se,o.isBackButtonSupported=Xo,o.isBackButtonVisible=st,o.isBiometryMounted=Me,o.isBiometryMounting=lr,o.isBiometrySupported=dr,o.isCanceledError=Ta,o.isChangingFullscreen=Pi,o.isClosingBehaviorMounted=ue,o.isClosingConfirmationEnabled=lt,o.isCloudStorageSupported=Tr,o.isColorDark=An,o.isFullScreen=De,o.isFullScreenMounted=le,o.isFullScreenSupported=Br,o.isFullscreen=Yn,o.isHapticFeedbackSupported=qr,o.isIframe=mo,o.isInvoiceOpened=Be,o.isInvoiceSupported=ts,o.isMainButtonEnabled=Es,o.isMainButtonLoaderVisible=gs,o.isMainButtonMounted=fe,o.isMainButtonVisible=ws,o.isMiniAppCssVarsBound=Ve,o.isMiniAppDark=Is,o.isMiniAppMounted=he,o.isMiniAppSupported=ks,o.isPopupOpened=je,o.isPopupSupported=Hs,o.isQrScannerOpened=X,o.isQrScannerSupported=zs,o.isRGB=x,o.isRGBShort=ro,o.isRecord=Wt,o.isRequestingBiometryAccess=Pe,o.isRequestingPhoneAccess=It,o.isRequestingWriteAccess=kt,o.isSSR=ln,o.isSecondaryButtonEnabled=Zs,o.isSecondaryButtonLoaderVisible=Ks,o.isSecondaryButtonMounted=be,o.isSecondaryButtonSupported=oi,o.isSecondaryButtonVisible=Xs,o.isSettingsButtonMounted=Ee,o.isSettingsButtonSupported=li,o.isSettingsButtonVisible=Pt,o.isSwipeBehaviorMounted=ge,o.isSwipeBehaviorSupported=Ei,o.isTMA=sn,o.isThemeParamsCssVarsBound=Ie,o.isThemeParamsDark=us,o.isThemeParamsMounted=_e,o.isTimeoutError=Ra,o.isVerticalSwipesEnabled=Nt,o.isViewportCssVarsBound=He,o.isViewportExpanded=Ri,o.isViewportMounted=we,o.isViewportMounting=Ai,o.isViewportStable=vi,o.mainButton=vc,o.mainButtonBackgroundColor=hs,o.mainButtonHasShineEffect=bs,o.mainButtonState=Et,o.mainButtonText=ys,o.mainButtonTextColor=Ss,o.mergeClassNames=ca,o.miniApp=Pc,o.miniAppBackgroundColor=de,o.miniAppBottomBarColor=pe,o.miniAppBottomBarColorRGB=yt,o.miniAppHeaderColor=me,o.miniAppHeaderColorRGB=Mn,o.miniAppReady=qs,o.miniAppState=Dn,o.mockTelegramEnv=Fa,o.mountBackButton=tr,o.mountBiometry=Er,o.mountClosingBehavior=$r,o.mountFullScreen=Vr,o.mountMainButton=As,o.mountMiniApp=js,o.mountSecondaryButton=ri,o.mountSettingsButton=di,o.mountSwipeBehavior=Si,o.mountThemeParams=On,o.mountViewport=Li,o.off=F,o.offBackButtonClick=or,o.offMainButtonClick=Rs,o.offSecondaryButtonClick=ii,o.offSettingsButtonClick=mi,o.on=C,o.onBackButtonClick=nr,o.onMainButtonClick=$s,o.onSecondaryButtonClick=si,o.onSettingsButtonClick=pi,o.openBiometrySettings=hr,o.openInvoice=os,o.openLink=Jc,o.openPopup=Ws,o.openQrScanner=Ys,o.openTelegramLink=Gi,o.parseInitData=Sc,o.parseThemeParams=Os,o.popup=Nc,o.postEvent=Ke,o.qrScanner=Vc,o.readTextFromClipboard=eu,o.removeEventHandlers=Bo,o.request=Xe,o.requestBiometry=fr,o.requestBiometryAccess=br,o.requestContact=Kc,o.requestFullScreen=kr,o.requestFullscreen=qi,o.requestPhoneAccess=zi,o.requestViewport=Mi,o.requestWriteAccess=Xc,o.restoreInitData=Xr,o.retrieveLaunchParams=Z,o.safeCall=ru,o.secondaryButton=jc,o.secondaryButtonBackgroundColor=Qs,o.secondaryButtonHasShineEffect=Js,o.secondaryButtonPosition=xs,o.secondaryButtonState=$t,o.secondaryButtonText=ei,o.secondaryButtonTextColor=ti,o.sendData=tu,o.serializeLaunchParams=ia,o.serializeThemeParams=Ht,o.setCloudStorageItem=Dr,o.setCssVar=Je,o.setMainButtonParams=vs,o.setMiniAppBackgroundColor=Ln,o.setMiniAppBottomBarColor=Vn,o.setMiniAppHeaderColor=Un,o.setSecondaryButtonParams=ai,o.settingsButton=qc,o.shareStory=nu,o.shareURL=Zc,o.showBackButton=rr,o.showSettingsButton=hi,o.subscribe=Ha,o.supports=z,o.swipeBehavior=Hc,o.switchInlineQuery=ou,o.themeParams=Wc,o.themeParamsAccentTextColor=ss,o.themeParamsBackgroundColor=ht,o.themeParamsBottomBarBgColor=Rn,o.themeParamsButtonColor=bt,o.themeParamsButtonTextColor=$n,o.themeParamsDestructiveTextColor=is,o.themeParamsHeaderBackgroundColor=as,o.themeParamsHintColor=cs,o.themeParamsLinkColor=ls,o.themeParamsSecondaryBackgroundColor=ke,o.themeParamsSectionBackgroundColor=_s,o.themeParamsSectionHeaderTextColor=fs,o.themeParamsSectionSeparatorColor=ds,o.themeParamsState=W,o.themeParamsSubtitleTextColor=ps,o.themeParamsTextColor=ms,o.toRGB=Ft,o.toRecord=Ut,o.unmountBackButton=sr,o.unmountBiometry=wr,o.unmountClosingBehavior=Rr,o.unmountFullScreen=jr,o.unmountMainButton=Ts,o.unmountMiniApp=Fs,o.unmountSecondaryButton=ci,o.unmountSettingsButton=bi,o.unmountSwipeBehavior=Ci,o.unmountThemeParams=Ns,o.unmountViewport=Hi,o.unsubscribe=Wa,o.updateBiometryToken=yr,o.viewport=Qc,o.viewportHeight=$i,o.viewportMountError=zn,o.viewportMountPromise=Fe,o.viewportStableHeight=Ti,o.viewportState=P,o.viewportWidth=Oi,Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}),o}({});
//# sourceMappingURL=index.iife.js.map
{
"name": "@telegram-apps/sdk",
"version": "2.6.2",
"version": "2.7.0",
"description": "TypeScript Source Development Kit for Telegram Mini Apps client application.",

@@ -40,5 +40,6 @@ "author": "Vladislav Kibenko <wolfram.deus@gmail.com>",

"dependencies": {
"@telegram-apps/transformers": "^1.0.1",
"@telegram-apps/bridge": "^1.4.0",
"@telegram-apps/navigation": "^1.0.5",
"@telegram-apps/transformers": "^1.1.0",
"@telegram-apps/toolkit": "^1.0.0",
"@telegram-apps/bridge": "^1.5.0",
"@telegram-apps/navigation": "^1.0.6",
"@telegram-apps/signals": "^1.1.0"

@@ -45,0 +46,0 @@ },

import { isRecord } from '@telegram-apps/transformers';
import type {
UnionRequiredKeys,
UnionOptionalKeys,
} from '@telegram-apps/toolkit';
import { classNames } from './classNames.js';
type UnionStringKeys<U> = U extends U
? { [K in keyof U]-?: U[K] extends string | undefined ? K : never }[keyof U]
: never;
type UnionRequiredKeys<U> = U extends U
? { [K in UnionStringKeys<U>]: ({} extends Pick<U, K> ? never : K) }[UnionStringKeys<U>]
: never;
type UnionOptionalKeys<U> = Exclude<UnionStringKeys<U>, UnionRequiredKeys<U>>;
export type MergeClassNames<Tuple extends any[]> =
// Removes all types from union that will be ignored by the mergeClassNames function.
// Removes all types from union that will be ignored by the mergeClassNames
// function.
Exclude<Tuple[number], number | string | null | undefined | any[] | boolean> extends infer Union

@@ -26,4 +21,4 @@ ?

*
* The function expects to pass an array of objects with values that could be passed to
* the `classNames` function.
* The function expects to pass an array of objects with values that could be
* passed to the `classNames` function.
* @returns An object with keys from all objects with merged values.

@@ -30,0 +25,0 @@ * @see classNames

@@ -14,1 +14,2 @@ export const ERR_POPUP_INVALID_PARAMS = 'ERR_POPUP_INVALID_PARAMS';

export const ERR_NOT_MOUNTED = 'ERR_NOT_MOUNTED';
export const ERR_FULLSCREEN_FAILED = 'ERR_FULLSCREEN_FAILED';

@@ -8,2 +8,3 @@ export { classNames } from '@/classnames/classNames.js';

export * from '@/scopes/components/cloud-storage/exports.js';
export * from '@/scopes/components/full-screen/exports.js';
export * from '@/scopes/components/haptic-feedback/exports.js';

@@ -43,3 +44,4 @@ export * from '@/scopes/components/init-data/exports.js';

ERR_ALREADY_MOUNTING,
ERR_ALREADY_REQUESTING
ERR_ALREADY_REQUESTING,
ERR_FULLSCREEN_FAILED,
} from '@/errors.js';

@@ -104,2 +106,3 @@ export { init, type InitOptions } from '@/init.js';

ExecuteWithPostEvent,
FullScreenErrorStatus,
HeaderColorKey,

@@ -106,0 +109,0 @@ ImpactHapticFeedbackParams,

@@ -24,7 +24,7 @@ import {

state,
mountError,
isMounted,
isRequestingAccess,
isAuthenticating,
isMounting,
mountError,
mountPromise,
} from './signals.js';

@@ -203,17 +203,17 @@ import { requestBiometry } from './requestBiometry.js';

*/
export const mount = wrapBasic(
'mount',
createMountFn<State>(
COMPONENT_NAME,
(options) => {
const s = isPageReload() && getStorageValue<StorageValue>(COMPONENT_NAME);
return s ? s : requestBiometry(options);
},
result => {
on(INFO_RECEIVED_EVENT, onBiometryInfoReceived);
setState(result);
},
{ isMounted, mountError, isMounting },
),
);
export const mount = wrapBasic('mount', createMountFn<State>(
COMPONENT_NAME,
(options) => {
const s = isPageReload() && getStorageValue<StorageValue>(COMPONENT_NAME);
return s ? s : requestBiometry(options);
},
result => {
on(INFO_RECEIVED_EVENT, onBiometryInfoReceived);
setState(result);
},
isMounted,
state,
mountPromise,
mountError,
));

@@ -220,0 +220,0 @@ const onBiometryInfoReceived: EventListener<'biometry_info_received'> = e => {

import { computed, signal } from '@telegram-apps/signals';
import type { CancelablePromise } from '@telegram-apps/toolkit';

@@ -8,3 +9,3 @@ import type { State } from './types.js';

*/
export const state = signal<State | undefined>();
export const state = signal<State>({ available: false});

@@ -21,4 +22,6 @@ /**

//#region Mount.
/**
* True if the component is currently mounted.
* Signal indicating if the component is currently mounted.
*/

@@ -28,12 +31,19 @@ export const isMounted = signal(false);

/**
* True if the component is currently mounting.
* Signal indicating if the component is currently mounting.
*/
export const isMounting = signal<boolean>(false);
export const isMounting = computed(() => !!mountPromise());
/**
* Error occurred while mounting the component.
* Signal containing the error occurred during mount.
*/
export const mountError = signal<Error | undefined>(undefined);
export const mountError = signal<Error | undefined>();
/**
* Signal containing the mount process promise.
*/
export const mountPromise = signal<CancelablePromise<State> | undefined>();
//#endregion
/**
* Signal indicating biometry is available.

@@ -40,0 +50,0 @@ */

@@ -13,2 +13,3 @@ import {

import { createWrapMounted } from '@/scopes/toolkit/createWrapMounted.js';
import { removeUndefined } from '@/utils/removeUndefined.js';

@@ -104,8 +105,3 @@ import { internalState, isMounted, state } from './signals.js';

(updates: Partial<State>): void => {
internalState.set({
...internalState(),
...Object.fromEntries(
Object.entries(updates).filter(([, v]) => v !== undefined),
),
});
internalState.set({ ...internalState(), ...removeUndefined(updates) });
setStorageValue<StorageValue>(COMPONENT_NAME, internalState());

@@ -112,0 +108,0 @@

export {
bindCssVars as bindViewportCssVars,
expand as expandViewport,
exitFullscreen,
height as viewportHeight,

@@ -8,2 +9,4 @@ isExpanded as isViewportExpanded,

isCssVarsBound as isViewportCssVarsBound,
isChangingFullscreen,
isFullscreen,
isMounting as isViewportMounting,

@@ -13,2 +16,6 @@ isMounted as isViewportMounted,

mountError as viewportMountError,
mountPromise as viewportMountPromise,
requestFullscreen,
changeFullscreenPromise,
changeFullscreenError,
state as viewportState,

@@ -15,0 +22,0 @@ stableHeight as viewportStableHeight,

@@ -1,2 +0,25 @@

export * from './signals.js';
export * from './methods.js';
export {
changeFullscreenError,
changeFullscreenPromise,
height,
isMounted,
isStable,
isChangingFullscreen,
isMounting,
isExpanded,
isFullscreen,
isCssVarsBound,
mountPromise,
mountError,
state,
stableHeight,
width,
} from './signals.js';
export {
bindCssVars,
exitFullscreen,
expand,
mount,
requestFullscreen,
unmount,
} from './methods.js';

@@ -6,3 +6,3 @@ import { beforeEach, describe, vi } from 'vitest';

import { mount, expand, bindCssVars } from './methods.js';
import { mount, expand, bindCssVars, exitFullscreen, requestFullscreen } from './methods.js';
import { isMounted } from './signals.js';

@@ -17,10 +17,13 @@

describe.each([
['mount', mount, undefined],
['expand', expand, undefined],
['bindCssVars', bindCssVars, isMounted],
] as const)('%s', (name, fn, isMounted) => {
['mount', mount, undefined, undefined],
['expand', expand, undefined, undefined],
['bindCssVars', bindCssVars, isMounted, undefined],
['exitFullscreen', exitFullscreen, isMounted, '8.0'],
['requestFullscreen', requestFullscreen, isMounted, '8.0'],
] as const)('%s', (name, fn, isMounted, minVersion) => {
testSafety(fn, name, {
component: 'viewport',
minVersion,
isMounted,
});
});

@@ -10,7 +10,7 @@ import {

setCssVar,
type EventListener,
type EventListener, CancelablePromise, AsyncOptions, TypedError,
} from '@telegram-apps/bridge';
import { isPageReload } from '@telegram-apps/navigation';
import { postEvent } from '@/scopes/globals.js';
import { postEvent, request } from '@/scopes/globals.js';
import { createMountFn } from '@/scopes/createMountFn.js';

@@ -20,2 +20,6 @@ import { createWrapMounted } from '@/scopes/toolkit/createWrapMounted.js';

import { throwCssVarsBound } from '@/scopes/toolkit/throwCssVarsBound.js';
import { ERR_FULLSCREEN_FAILED } from '@/errors.js';
import { removeUndefined } from '@/utils/removeUndefined.js';
import { createWrapComplete } from '@/scopes/toolkit/createWrapComplete.js';
import { signalifyAsyncFn } from '@/scopes/signalifyAsyncFn.js';

@@ -28,3 +32,6 @@ import { requestViewport } from './requestViewport.js';

isCssVarsBound,
isMounting,
mountPromise,
changeFullscreenPromise,
changeFullscreenError,
isFullscreen,
} from './signals.js';

@@ -34,12 +41,12 @@ import type { GetCSSVarNameFn } from './types.js';

interface StorageValue {
height: number;
isExpanded: boolean;
stableHeight: number;
width: number;
}
type StorageValue = State;
const COMPONENT_NAME = 'viewport';
const FS_REQUEST_METHOD_NAME = 'web_app_request_fullscreen';
const FS_FAILED_EVENT_NAME = 'fullscreen_failed';
const FS_CHANGED_EVENT_NAME = 'fullscreen_changed';
const wrapBasic = createWrapBasic(COMPONENT_NAME);
const wrapMounted = createWrapMounted(COMPONENT_NAME, isMounted);
const wrapFSComplete = createWrapComplete(COMPONENT_NAME, isMounted, FS_REQUEST_METHOD_NAME);

@@ -49,4 +56,6 @@ /**

*
* By default, created CSS variables names are following the pattern "--tg-theme-{name}", where
* {name} is a theme parameters key name converted from camel case to kebab case.
* By default, created CSS variables names are following the pattern
* "--tg-theme-{name}", where
* {name} is a theme parameters key name converted from camel case to kebab
* case.
*

@@ -60,4 +69,4 @@ * Default variables:

*
* @param getCSSVarName - function, returning complete CSS variable name for the specified
* viewport property.
* @param getCSSVarName - function, returning complete CSS variable name for
* the specified viewport property.
* @returns Function to stop updating variables.

@@ -104,4 +113,5 @@ * @throws {TypedError} ERR_UNKNOWN_ENV

/**
* A method that expands the Mini App to the maximum available height. To find out if the Mini
* App is expanded to the maximum height, refer to the value of the `isExpanded`.
* A method that expands the Mini App to the maximum available height. To find
* out if the Mini App is expanded to the maximum height, refer to the value of
* the `isExpanded`.
* @throws {TypedError} ERR_UNKNOWN_ENV

@@ -129,49 +139,45 @@ * @throws {TypedError} ERR_NOT_INITIALIZED

*/
export const mount = wrapBasic(
'mount',
createMountFn<State>(
COMPONENT_NAME,
options => {
// Try to restore the state using the storage.
const s = isPageReload() && getStorageValue<StorageValue>(COMPONENT_NAME);
if (s) {
return s;
}
export const mount = wrapBasic('mount', createMountFn(
COMPONENT_NAME,
(options) => {
// Try to restore the state using the storage.
const s = isPageReload() && getStorageValue<StorageValue>(COMPONENT_NAME);
if (s) {
return s;
}
// If the platform has a stable viewport, it means we could use the window global object
// properties.
if ([
'macos',
'tdesktop',
'unigram',
'webk',
'weba',
'web',
].includes(retrieveLaunchParams().platform)) {
const w = window;
return {
isExpanded: true,
height: w.innerHeight,
width: w.innerWidth,
stableHeight: w.innerHeight,
};
}
// If the platform has a stable viewport, it means we could use the
// window global object properties.
const lp = retrieveLaunchParams();
const isFullscreen = !!lp.fullscreen;
if (['macos', 'tdesktop', 'unigram', 'webk', 'weba', 'web'].includes(lp.platform)) {
const w = window;
return {
isExpanded: true,
isFullscreen,
height: w.innerHeight,
width: w.innerWidth,
stableHeight: w.innerHeight,
};
}
// We were unable to retrieve data locally. In this case, we are sending
// a request returning the viewport information.
options.timeout ||= 1000;
return requestViewport(options).then(data => ({
height: data.height,
isExpanded: data.isExpanded,
stableHeight: data.isStable ? data.height : state().stableHeight,
width: data.width,
}));
},
result => {
on('viewport_changed', onViewportChanged);
setState(result);
},
{ isMounted, isMounting, mountError },
),
);
// We were unable to retrieve data locally. In this case, we are
// sending a request returning the viewport information.
return requestViewport(options).then(data => ({
height: data.height,
isExpanded: data.isExpanded,
isFullscreen,
stableHeight: data.isStable ? data.height : state().stableHeight,
width: data.width,
}));
},
() => {
on('viewport_changed', onViewportChanged);
on(FS_CHANGED_EVENT_NAME, onFullscreenChanged);
},
isMounted,
state,
mountPromise,
mountError,
));

@@ -182,3 +188,3 @@ const onViewportChanged: EventListener<'viewport_changed'> = (data) => {

isExpanded: data.is_expanded,
stableHeight: data.is_state_stable ? data.height : state().stableHeight,
stableHeight: data.is_state_stable ? data.height : undefined,
width: data.width,

@@ -188,10 +194,89 @@ });

function setState(s: State) {
const onFullscreenChanged: EventListener<'fullscreen_changed'> = (data) => {
setState({ isFullscreen: data.is_fullscreen });
};
function fsChangeGen(
method: string,
requestMethod: 'web_app_exit_fullscreen' | 'web_app_request_fullscreen',
) {
return wrapFSComplete(method, signalifyAsyncFn(
(options?: AsyncOptions): CancelablePromise<void> => {
return request(requestMethod, [FS_CHANGED_EVENT_NAME, FS_FAILED_EVENT_NAME], options)
.then(result => {
if ('error' in result) {
if (result.error === 'ALREADY_FULLSCREEN') {
return true;
}
throw new TypedError(ERR_FULLSCREEN_FAILED, 'Fullscreen request failed', result.error);
}
return result.is_fullscreen;
})
.then(result => {
isFullscreen() !== result && setState({ isFullscreen: result });
});
},
() => new TypedError('abc'),
changeFullscreenPromise,
changeFullscreenError,
));
}
/**
* Requests fullscreen mode for the mini application.
* @since Mini Apps v8.0
* @throws {TypedError} ERR_UNKNOWN_ENV
* @throws {TypedError} ERR_NOT_INITIALIZED
* @throws {TypedError} ERR_NOT_MOUNTED
* @throws {TypedError} ERR_NOT_SUPPORTED
* @throws {TypedError} ERR_FULLSCREEN_FAILED
* @example Using `isAvailable()`
* if (requestFullscreen.isAvailable() && !isChangingFullscreen()) {
* await requestFullscreen();
* }
* @example Using `ifAvailable()`
* if (!isChangingFullscreen()) {
* await requestFullscreen.ifAvailable();
* }
*/
export const requestFullscreen = fsChangeGen(
'requestFullscreen',
FS_REQUEST_METHOD_NAME,
);
/**
* Exits mini application fullscreen mode.
* @since Mini Apps v8.0
* @throws {TypedError} ERR_UNKNOWN_ENV
* @throws {TypedError} ERR_NOT_INITIALIZED
* @throws {TypedError} ERR_NOT_MOUNTED
* @throws {TypedError} ERR_NOT_SUPPORTED
* @throws {TypedError} ERR_FULLSCREEN_FAILED
* @example Using `isAvailable()`
* if (exitFullscreen.isAvailable() && !isChangingFullscreen()) {
* await exitFullscreen();
* }
* @example Using `ifAvailable()`
* if (!isChangingFullscreen()) {
* await exitFullscreen.ifAvailable();
* }
*/
export const exitFullscreen = fsChangeGen(
'exitFullscreen',
'web_app_exit_fullscreen',
);
function setState(s: Partial<State>) {
const { height, stableHeight, width } = s;
state.set({
isExpanded: s.isExpanded,
height: truncate(s.height),
width: truncate(s.width),
stableHeight: truncate(s.stableHeight),
...state(),
...removeUndefined({
...s,
height: height ? truncate(height) : undefined,
width: width ? truncate(width) : undefined,
stableHeight: stableHeight ? truncate(stableHeight) : undefined,
}),
});
setStorageValue<StorageValue>('viewport', state());
setStorageValue<StorageValue>(COMPONENT_NAME, state());
}

@@ -211,4 +296,12 @@

export function unmount(): void {
// Cancel mount promise.
const promise = mountPromise();
promise && promise.cancel();
// Remove event listeners.
off('viewport_changed', onViewportChanged);
off('fullscreen_changed', onFullscreenChanged);
// Drop the mount flag.
isMounted.set(false);
}
import { computed, type Computed, signal } from '@telegram-apps/signals';
import { CancelablePromise } from '@telegram-apps/toolkit';

@@ -13,2 +14,3 @@ import type { State } from './types.js';

width: 0,
isFullscreen: false,
isExpanded: false,

@@ -18,4 +20,6 @@ stableHeight: 0,

//#region Mount.
/**
* True if the component is currently mounted.
* Signal indicating if the component is currently mounted.
*/

@@ -25,16 +29,23 @@ export const isMounted = signal(false);

/**
* True if CSS variables are currently bound.
* Signal indicating if the component is currently mounting.
*/
export const isCssVarsBound = signal(false);
export const isMounting = computed(() => !!mountPromise());
/**
* True if the component is currently mounting.
* Signal containing the error occurred during mount.
*/
export const isMounting = signal<boolean>(false);
export const mountError = signal<Error | undefined>(undefined);
/**
* Error occurred while mounting the component.
* Signal containing the mount process promise.
*/
export const mountError = signal<Error | undefined>(undefined);
export const mountPromise = signal<CancelablePromise<State> | undefined>();
//#endregion
/**
* True if CSS variables are currently bound.
*/
export const isCssVarsBound = signal(false);
/* COMPUTED */

@@ -49,12 +60,12 @@

*
* The application can display just the top part of the Mini App, with its lower part remaining
* outside the screen area. From this position, the user can "pull" the Mini App to its
* maximum height, while the bot can do the same by calling `expand` method. As the position of
* the Mini App changes, the current height value of the visible area will be updated in real
* time.
* The application can display just the top part of the Mini App, with its
* lower part remaining outside the screen area. From this position, the user
* can "pull" the Mini App to its maximum height, while the bot can do the same
* by calling `expand` method. As the position of the Mini App changes, the
* current height value of the visible area will be updated in real time.
*
* Please note that the refresh rate of this value is not sufficient to smoothly follow the
* lower border of the window. It should not be used to pin interface elements to the bottom
* of the visible area. It's more appropriate to use the value of the `stableHeight`
* field for this purpose.
* Please note that the refresh rate of this value is not sufficient to
* smoothly follow the lower border of the window. It should not be used to pin
* interface elements to the bottom of the visible area. It's more appropriate
* to use the value of the `stableHeight` field for this purpose.
*

@@ -66,4 +77,5 @@ * @see stableHeight

/**
* True if the Mini App is expanded to the maximum available height. Otherwise, if
* the Mini App occupies part of the screen and can be expanded to the full height using
* True if the Mini App is expanded to the maximum available height. Otherwise,
* if the Mini App occupies part of the screen and can be expanded to the full
* height using
* `expand` method.

@@ -75,3 +87,4 @@ * @see expand

/**
* True if the current viewport height is stable and is not going to change in the next moment.
* True if the current viewport height is stable and is not going to change in
* the next moment.
*/

@@ -86,10 +99,11 @@ export const isStable = computed(() => {

*
* The application can display just the top part of the Mini App, with its lower part remaining
* outside the screen area. From this position, the user can "pull" the Mini App to its
* maximum height, while the application can do the same by calling `expand` method.
* The application can display just the top part of the Mini App, with its
* lower part remaining outside the screen area. From this position, the user
* can "pull" the Mini App to its maximum height, while the application can do
* the same by calling `expand` method.
*
* Unlike the value of `height`, the value of `stableHeight` does not change as the position
* of the Mini App changes with user gestures or during animations. The value of `stableHeight`
* will be updated after all gestures and animations are completed and the Mini App reaches its
* final size.
* Unlike the value of `height`, the value of `stableHeight` does not change as
* the position of the Mini App changes with user gestures or during
* animations. The value of `stableHeight` will be updated after all gestures
* and animations are completed and the Mini App reaches its final size.
*

@@ -103,2 +117,28 @@ * @see height

*/
export const width = createStateComputed('width');
export const width = createStateComputed('width');
//#region Fullscreen mode.
/**
* Signal indicating if the viewport is currently in fullscreen mode.
*/
export const isFullscreen = createStateComputed('isFullscreen');
/**
* Signal containing fullscreen request or exit promise.
*/
export const changeFullscreenPromise = signal<CancelablePromise<void>>();
/**
* Signal indicating if the fullscreen mode request is currently in progress.
*/
export const isChangingFullscreen = computed(() => {
return !!changeFullscreenPromise();
});
/**
* Signal containing an error received during the last fullscreen mode request.
*/
export const changeFullscreenError = signal<Error | undefined>();
//#endregion
export interface State {
height: number;
isExpanded: boolean;
isFullscreen: boolean;
stableHeight: number;

@@ -5,0 +6,0 @@ width: number;

@@ -9,60 +9,47 @@ import { batch, type Signal } from '@telegram-apps/signals';

import { ERR_ALREADY_MOUNTING } from '@/errors.js';
import { signalifyAsyncFn } from '@/scopes/signalifyAsyncFn.js';
/**
* Creates a mount function for a component.
* @param component - the component name.
* @param mount - function mounting the component.
* @param onMounted - callback which will be called with the mount result.
* @param mountPromise - signal containing mount promise.
* @param isMounted - signal containing mount state.
* @param mountError - signal containing mount error.
* @param component - the component name
* @param mount - function mounting the component
* @param onMounted - function that will be called whenever mount was completed.
* @param isMounted - signal containing the current mount completion state
* @param data - signal containing the current mount state
* @param promise - signal containing the mount promise
* @param error - signal containing the mount error
*/
// #__NO_SIDE_EFFECTS__
export function createMountFn<T = void>(
export function createMountFn<R>(
component: string,
mount: (options: AsyncOptions) => (T | CancelablePromise<T>),
onMounted: (result: T) => void,
{
isMounting,
isMounted,
mountError,
}: {
isMounted: Signal<boolean>,
isMounting: Signal<boolean>,
mountError: Signal<Error | undefined>,
},
): (options?: AsyncOptions) => CancelablePromise<void> {
return mountOptions => {
return CancelablePromise.withFn(async abortSignal => {
if (isMounted()) {
return;
}
if (isMounting()) {
throw new TypedError(
ERR_ALREADY_MOUNTING,
`The ${component} component is already mounting`,
);
}
isMounting.set(true);
mount: (options?: AsyncOptions) => R | CancelablePromise<R>,
onMounted: (result: R) => void,
isMounted: Signal<boolean>,
data: Signal<R>,
promise: Signal<CancelablePromise<R> | undefined>,
error: Signal<Error | undefined>,
): (options?: AsyncOptions) => CancelablePromise<R> {
const noConcurrent = signalifyAsyncFn(
mount,
() => new TypedError(
ERR_ALREADY_MOUNTING,
`The ${component} component is already mounting`,
),
promise,
error,
);
let result: [completed: true, result: T] | [completed: false, err: Error];
try {
result = [true, await mount({ abortSignal })];
} catch (e) {
result = [false, e as Error];
return (options?) => {
return CancelablePromise.resolve().then(async () => {
if (!isMounted()) {
const result = await noConcurrent(options);
batch(() => {
data.set(result);
isMounted.set(true);
onMounted(result);
});
}
batch(() => {
isMounting.set(false);
isMounted.set(true);
if (result[0]) {
onMounted(result[1]);
} else {
const error = result[1];
mountError.set(error);
throw error;
}
});
}, mountOptions);
return data();
});
};
}
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc