@tma.js/sdk 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,28 +2,30 @@
2
2
 
3
3
  [code-badge]: https://img.shields.io/badge/source-black?logo=github
4
4
 
5
- [code-link]: https://github.com/Telegram-Mini-Apps/tma.js/tree/master/packages/sdk
5
+ [docs-badge]: https://img.shields.io/badge/documentation-blue?logo=gitbook&logoColor=white
6
6
 
7
- [docs-link]: https://docs.telegram-mini-apps.com/packages/typescript/tma-js-sdk/about
7
+ [sdk-code-link]: https://github.com/Telegram-Mini-Apps/tma.js/tree/master/packages/sdk
8
8
 
9
- [docs-badge]: https://img.shields.io/badge/documentation-blue?logo=gitbook&logoColor=white
9
+ [sdk-docs-link]: https://docs.telegram-mini-apps.com/packages/typescript/tma-js-sdk/about
10
10
 
11
- [npm-link]: https://npmjs.com/package/@tma.js/sdk
11
+ [sdk-npm-link]: https://npmjs.com/package/@tma.js/sdk
12
12
 
13
- [npm-badge]: https://img.shields.io/npm/v/@tma.js/sdk?logo=npm
13
+ [sdk-npm-badge]: https://img.shields.io/npm/v/@tma.js/sdk?logo=npm
14
14
 
15
- [size-badge]: https://img.shields.io/bundlephobia/minzip/@tma.js/sdk
15
+ [sdk-size-badge]: https://img.shields.io/bundlephobia/minzip/@tma.js/sdk
16
16
 
17
- [![NPM][npm-badge]][npm-link]
18
- ![Size][size-badge]
19
- [![docs-badge]][docs-link]
20
- [![code-badge]][code-link]
17
+ [![NPM][sdk-npm-badge]][sdk-npm-link]
18
+ ![Size][sdk-size-badge]
19
+ [![docs-badge]][sdk-docs-link]
20
+ [![code-badge]][sdk-code-link]
21
21
 
22
- Made from scratch production-ready TypeScript Telegram Mini Apps
23
- Source Development Kit. It includes all features provided
24
- by other packages extending them with intuitively clear
22
+ Made from scratch TypeScript library for seamless communication with Telegram Mini Apps
25
23
  functionality.
26
24
 
27
- This library is a part of TypeScript packages ecosystem around Telegram Web
28
- Apps. You can learn more about this package in this
29
- [documentation][docs-link].
25
+ The code of this library is designed to simplify the process of developers interacting with Telegram
26
+ Mini Apps. It consists of several individual components, each responsible for a specific aspect of
27
+ the Telegram Mini Apps ecosystem.
28
+
29
+ Before you begin using the SDK, we highly recommend familiarizing yourself with the Telegram Mini
30
+ Apps [documentation](https://docs.telegram-mini-apps.com/platform/about-platform)
31
+ to grasp the fundamental concepts of the platform.
@@ -15,6 +15,7 @@ export { isTMA, isRecord, } from './misc/index.js';
15
15
  export { getHash, HashNavigator, Navigator, type NavigationEntry, type NavigatorConEntry, type NavigatorOptions, type HashNavigatorOptions, type HashNavigatorEventsMap, type HashNavigatorEventListener, type HashNavigatorEventName, } from './navigation/index.js';
16
16
  export { Popup, type PopupEventName, type PopupEventListener, type PopupEvents, type OpenPopupOptions, type OpenPopupOptionsButton, } from './popup/index.js';
17
17
  export { QRScanner, type QRScannerEventListener, type QRScannerEventName, type QRScannerEvents, } from './qr-scanner/index.js';
18
+ export { SettingsButton, type SettingsButtonEventName, type SettingsButtonEventListener, type SettingsButtonEvents, } from './settings-button/index.js';
18
19
  export { supports } from './supports/index.js';
19
20
  export { parseThemeParams, requestThemeParams, serializeThemeParams, themeParamsParser, ThemeParams, type ThemeParamsEventListener, type ThemeParamsEventName, type ThemeParamsEvents, type ThemeParamsKey, type ThemeParamsParsed, } from './theme-params/index.js';
20
21
  export type { RequestId, CreateRequestIdFunc, } from './types/index.js';
@@ -0,0 +1,10 @@
1
+ import { SettingsButton } from '../../settings-button/index.js';
2
+ import type { PostEvent } from '../../bridge/index.js';
3
+ /**
4
+ * Creates SettingsButton instance using last locally saved data also saving each state in
5
+ * the storage.
6
+ * @param isPageReload - was current page reloaded.
7
+ * @param version - platform version.
8
+ * @param postEvent - Bridge postEvent function
9
+ */
10
+ export declare function createSettingsButton(isPageReload: boolean, version: string, postEvent: PostEvent): SettingsButton;
@@ -3,5 +3,6 @@ export * from './createClosingBehavior.js';
3
3
  export * from './createMainButton.js';
4
4
  export * from './createMiniApp.js';
5
5
  export * from './createRequestIdGenerator.js';
6
+ export * from './createSettingsButton.js';
6
7
  export * from './createThemeParams.js';
7
8
  export * from './createViewport.js';
@@ -2,5 +2,6 @@ import type { InitOptions, InitResult } from './types.js';
2
2
  type ComputedInitResult<O> = O extends {
3
3
  async: true;
4
4
  } ? Promise<InitResult> : InitResult;
5
+ export declare function init(): InitResult;
5
6
  export declare function init<O extends InitOptions>(options: O): ComputedInitResult<O>;
6
7
  export {};
@@ -9,6 +9,7 @@ import type { MainButton } from '../main-button/index.js';
9
9
  import type { MiniApp } from '../mini-app/index.js';
10
10
  import type { Popup } from '../popup/index.js';
11
11
  import type { QRScanner } from '../qr-scanner/index.js';
12
+ import type { SettingsButton } from '../settings-button/index.js';
12
13
  import type { ThemeParams } from '../theme-params/index.js';
13
14
  import type { CreateRequestIdFunc } from '../types/index.js';
14
15
  import type { Utils } from '../utils/index.js';
@@ -27,6 +28,7 @@ export interface InitResult {
27
28
  popup: Popup;
28
29
  postEvent: PostEvent;
29
30
  qrScanner: QRScanner;
31
+ settingsButton: SettingsButton;
30
32
  themeParams: ThemeParams;
31
33
  utils: Utils;
32
34
  viewport: Viewport;
@@ -0,0 +1,42 @@
1
+ import { type PostEvent } from '../bridge/index.js';
2
+ import { EventEmitter } from '../event-emitter/index.js';
3
+ import { type SupportsFunc } from '../supports/index.js';
4
+ import type { Version } from '../version/index.js';
5
+ import type { SettingsButtonEvents } from './types.js';
6
+ type Emitter = EventEmitter<SettingsButtonEvents>;
7
+ export declare class SettingsButton {
8
+ private readonly postEvent;
9
+ private readonly ee;
10
+ private readonly state;
11
+ constructor(isVisible: boolean, version: Version, postEvent?: PostEvent);
12
+ private set isVisible(value);
13
+ /**
14
+ * True if SettingsButton is currently visible.
15
+ */
16
+ get isVisible(): boolean;
17
+ /**
18
+ * Hides the SettingsButton.
19
+ */
20
+ hide(): void;
21
+ /**
22
+ * Adds event listener.
23
+ * @param event - event name.
24
+ * @param listener - event listener.
25
+ */
26
+ on: Emitter['on'];
27
+ /**
28
+ * Removes event listener.
29
+ * @param event - event name.
30
+ * @param listener - event listener.
31
+ */
32
+ off: Emitter['off'];
33
+ /**
34
+ * Shows the SettingsButton.
35
+ */
36
+ show(): void;
37
+ /**
38
+ * Checks if specified method is supported by current component.
39
+ */
40
+ supports: SupportsFunc<'show' | 'hide'>;
41
+ }
42
+ export {};
@@ -0,0 +1,2 @@
1
+ export * from './SettingsButton.js';
2
+ export * from './types.js';
@@ -0,0 +1,10 @@
1
+ import type { MiniAppsEventListener } from '../bridge/index.js';
2
+ import type { StateEvents } from '../state/index.js';
3
+ export interface SettingsButtonState {
4
+ isVisible: boolean;
5
+ }
6
+ export interface SettingsButtonEvents extends StateEvents<SettingsButtonState> {
7
+ click: MiniAppsEventListener<'settings_button_pressed'>;
8
+ }
9
+ export type SettingsButtonEventName = keyof SettingsButtonEvents;
10
+ export type SettingsButtonEventListener<E extends SettingsButtonEventName> = SettingsButtonEvents[E];
@@ -18,6 +18,9 @@ interface StorageParams {
18
18
  text: string;
19
19
  textColor: RGB;
20
20
  };
21
+ 'settings-button': {
22
+ isVisible: boolean;
23
+ };
21
24
  viewport: {
22
25
  height: number;
23
26
  isExpanded: boolean;
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Yt=Object.defineProperty;var Xt=(r,t,e)=>t in r?Yt(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var o=(r,t,e)=>(Xt(r,typeof t!="symbol"?t+"":t,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function q(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function yt(){return performance.getEntriesByType("navigation")[0]||null}function te(){const r=yt();return r?r.type==="reload":null}function T(){return new TypeError("Value has unexpected type")}class j extends Error{constructor(e,{cause:n,type:s}={}){super(`Unable to parse value${s?` as ${s}`:""}`,{cause:n});o(this,"type");this.value=e,Object.setPrototypeOf(this,j.prototype),this.type=s}}class F{constructor(t,e,n){this.parser=t,this.isOptional=e,this.type=n}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(e){throw new j(t,{type:this.type,cause:e})}}optional(){return this.isOptional=!0,this}}function ee(r){if(Array.isArray(r))return r;if(typeof r=="string")try{const t=JSON.parse(r);if(Array.isArray(t))return t}catch{}throw T()}class re extends F{constructor(e,n,s){super(ee,n,s);o(this,"itemParser");this.itemParser=typeof e=="function"?e:e.parse.bind(e)}parse(e){const n=super.parse(e);return n===void 0?n:n.map(this.itemParser)}of(e){return this.itemParser=typeof e=="function"?e:e.parse.bind(e),this}}function V(r,t){return()=>new F(r,!1,t)}class G extends Error{constructor(t,{cause:e,type:n}={}){super(`Unable to parse field "${t}"${n?` as ${n}`:""}`,{cause:e}),Object.setPrototypeOf(this,G.prototype)}}function Et(r,t){const e={};for(const n in r){const s=r[n];if(!s)continue;let i,a;if(typeof s=="function"||"parse"in s)i=n,a=typeof s=="function"?s:s.parse.bind(s);else{const{type:l}=s;i=s.from||n,a=typeof l=="function"?l:l.parse.bind(l)}let c;const u=t(i);try{c=a(u)}catch(l){throw l instanceof j?new G(i,{type:l.type,cause:l}):new G(i,{cause:l})}c!==void 0&&(e[n]=c)}return e}function ne(r){return new re(t=>t,!1,r)}const v=V(r=>{if(typeof r=="boolean")return r;const t=String(r);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;throw T()},"boolean"),L=V(r=>{if(typeof r=="number")return r;if(typeof r=="string"){const t=Number(r);if(!Number.isNaN(t))return t}throw T()},"number"),se=L(),ie=V(r=>r instanceof Date?r:new Date(se.parse(r)*1e3),"Date");function X(r){let t=r;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw T();return t}function g(r,t){return new F(e=>{const n=X(e);return Et(r,s=>n[s])},!1,t)}function tt(r){return/^#[\da-f]{6}$/i.test(r)}function Ct(r){return/^#[\da-f]{3}$/i.test(r)}function et(r){const t=r.replace(/\s/g,"").toLowerCase();if(tt(t))return t;if(Ct(t)){let n="#";for(let s=0;s<3;s+=1)n+=t[1+s].repeat(2);return n}const e=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(e===null)throw new Error(`Value "${r}" does not satisfy any of known RGB formats.`);return e.slice(1).reduce((n,s)=>{const i=parseInt(s,10).toString(16);return n+(i.length===1?"0":"")+i},"#")}function rt(r){const t=et(r);return Math.sqrt([.299,.587,.114].reduce((n,s,i)=>{const a=parseInt(t.slice(1+i*2,1+(i+1)*2),16);return n+a*a*s},0))<120}const h=V(r=>{if(typeof r=="string"||typeof r=="number")return r.toString();throw T()},"string"),oe=h(),vt=V(r=>et(oe.parse(r)),"rgb");function Pt(r,t){return new F(e=>{if(typeof e!="string"&&!(e instanceof URLSearchParams))throw T();const n=typeof e=="string"?new URLSearchParams(e):e;return Et(r,s=>{const i=n.get(s);return i===null?void 0:i})},!1,t)}function kt(){return g({id:L(),type:h(),title:h(),photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"Chat")}class St{constructor(t){this.initData=t}get authDate(){return this.initData.authDate}get canSendAfter(){return this.initData.canSendAfter}get canSendAfterDate(){const{canSendAfter:t}=this;return t===void 0?void 0:new Date(this.authDate.getTime()+t*1e3)}get chat(){return this.initData.chat}get chatType(){return this.initData.chatType}get chatInstance(){return this.initData.chatInstance}get hash(){return this.initData.hash}get queryId(){return this.initData.queryId}get receiver(){return this.initData.receiver}get startParam(){return this.initData.startParam}get user(){return this.initData.user}}function Y(){return g({addedToAttachmentMenu:{type:v().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:v().optional(),from:"allows_write_to_pm"},firstName:{type:h(),from:"first_name"},id:L(),isBot:{type:v().optional(),from:"is_bot"},isPremium:{type:v().optional(),from:"is_premium"},languageCode:{type:h().optional(),from:"language_code"},lastName:{type:h().optional(),from:"last_name"},photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"User")}function nt(){return Pt({authDate:{type:ie(),from:"auth_date"},canSendAfter:{type:L().optional(),from:"can_send_after"},chat:kt().optional(),chatInstance:{type:h().optional(),from:"chat_instance"},chatType:{type:h().optional(),from:"chat_type"},hash:h(),queryId:{type:h().optional(),from:"query_id"},receiver:Y().optional(),startParam:{type:h().optional(),from:"start_param"},user:Y().optional()},"InitData")}function ae(r){return nt().parse(r)}function ce(r){return r.replace(/(^|_)bg/,(t,e)=>`${e}background`).replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function he(r){return r.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`).replace(/(^|_)background/,(t,e)=>`${e}bg`)}const ue=vt().optional(),st=V(r=>Object.entries(X(r)).reduce((t,[e,n])=>(t[ce(e)]=ue.parse(n),t),{}),"ThemeParams");function it(r){return st().parse(r)}function pe(r={}){return _("web_app_request_theme","theme_changed",r).then(it)}function xt(r){return JSON.stringify(Object.entries(r).reduce((t,[e,n])=>(n&&(t[he(e)]=n),t),{}))}class w{constructor(){o(this,"listeners",new Map);o(this,"subscribeListeners",[])}addListener(t,e,n){let s=this.listeners.get(t);return s||(s=[],this.listeners.set(t,s)),s.push([e,n]),()=>this.off(t,e)}emit(t,...e){this.subscribeListeners.forEach(s=>s(t,...e));const n=this.listeners.get(t);n&&n.forEach(([s,i],a)=>{s(...e),i&&n.splice(a,1)})}on(t,e){return this.addListener(t,e,!1)}once(t,e){return this.addListener(t,e,!0)}off(t,e){const n=this.listeners.get(t);if(n){for(let s=0;s<n.length;s+=1)if(e===n[s][0]){n.splice(s,1);return}}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let e=0;e<this.subscribeListeners.length;e+=1)if(this.subscribeListeners[e]===t){this.subscribeListeners.splice(e,1);return}}}class b{constructor(t,e){this.state=t,this.ee=e}internalSet(t,e){return this.state[t]===e||e===void 0?!1:(this.state[t]=e,this.ee.emit(`change:${t}`,e),!0)}clone(){return{...this.state}}set(t,e){let n=!1;if(typeof t=="string")n=this.internalSet(t,e);else for(const s in t)this.internalSet(s,t[s])&&(n=!0);n&&this.ee.emit("change")}get(t){return this.state[t]}}class At{constructor(t){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.state=new b(t,this.ee)}get accentTextColor(){return this.get("accentTextColor")}get backgroundColor(){return this.get("backgroundColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}get(t){return this.state.get(t)}getState(){return this.state.clone()}get headerBackgroundColor(){return this.get("headerBackgroundColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.backgroundColor||rt(this.backgroundColor)}get linkColor(){return this.get("linkColor")}get secondaryBackgroundColor(){return this.get("secondaryBackgroundColor")}get sectionBackgroundColor(){return this.get("sectionBackgroundColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}listen(){return m("theme_changed",t=>{this.state.set(it(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}function ot(){return Pt({botInline:{type:v().optional(),from:"tgWebAppBotInline"},initData:{type:nt().optional(),from:"tgWebAppData"},initDataRaw:{type:h().optional(),from:"tgWebAppData"},platform:{type:h(),from:"tgWebAppPlatform"},showSettings:{type:v().optional(),from:"tgWebAppShowSettings"},themeParams:{type:st(),from:"tgWebAppThemeParams"},version:{type:h(),from:"tgWebAppVersion"}},"LaunchParams")}function at(r){return ot().parse(r)}function le(){return at(window.location.hash.slice(1))}function de(){const r=yt();if(!r)throw new Error("Unable to get first navigation entry.");const t=r.name.match(/#(.*)/);if(!t)throw new Error("First navigation entry does not contain hash part.");return at(t[1])}function fe(){try{return de()}catch{}try{return le()}catch{}return null}function qt(r){const{initDataRaw:t,themeParams:e,platform:n,version:s,showSettings:i,botInline:a}=r,c=new URLSearchParams;return t&&c.set("tgWebAppData",t),c.set("tgWebAppPlatform",n),c.set("tgWebAppThemeParams",xt(e)),c.set("tgWebAppVersion",s),typeof i=="boolean"&&c.set("tgWebAppShowSettings",i?"1":"0"),typeof a=="boolean"&&c.set("tgWebAppBotInline",a?"1":"0"),c.toString()}const Lt="telegram-mini-apps-launch-params";function ge(){const r=sessionStorage.getItem(Lt);return r?ot().parse(r):null}function we(r){sessionStorage.setItem(Lt,qt(r))}function _e(){try{return window.self!==window.top}catch{return!0}}function be(){const r=ge(),t=fe(),e=te();if(r){if(t)return{launchParams:t,isPageReload:_e()?e||r.initDataRaw===t.initDataRaw:!0};if(e)return{launchParams:r,isPageReload:e};throw new Error("Unable to retrieve current launch parameters, which must exist.")}if(t)return{launchParams:t,isPageReload:!1};throw new Error("Unable to retrieve any launch parameters.")}const dt="tmajsLaunchData";function ct(){const r=window[dt];if(r)return r;const t=be();return window[dt]=t,we(t.launchParams),t}function me(){try{return ct(),!0}catch{return!1}}function ye(r){return"external"in r&&q(r.external)&&"notify"in r.external&&typeof r.external.notify=="function"}function Ee(r){return"TelegramWebviewProxy"in r&&q(r.TelegramWebviewProxy)&&"postEvent"in r.TelegramWebviewProxy&&typeof r.TelegramWebviewProxy.postEvent=="function"}function ht(){try{return window.self!==window.top}catch{return!0}}class z extends Error{constructor(t,e){super(`Method "${t}" is unsupported in the Mini Apps version ${e}.`),Object.setPrototypeOf(this,z.prototype)}}class J extends Error{constructor(t,e,n){super(`Parameter "${e}" in method "${t}" is unsupported in the Mini Apps version ${n}.`),Object.setPrototypeOf(this,J.prototype)}}class Tt{constructor(t,e){this.prefix=t,this.enabled=e}print(t,...e){if(!this.enabled)return;const n=new Date,s=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n);console[t](`[${s}]`,this.prefix,...e)}disable(){this.enabled=!1}error(...t){this.print("error",...t)}enable(){this.enabled=!0}log(...t){this.print("log",...t)}warn(...t){this.print("warn",...t)}}let Vt="https://web.telegram.org";const A=new Tt("[SDK]",!1);function Ce(r){if(r){A.enable();return}A.disable()}function ve(r){Vt=r}function Pe(){return Vt}const ke=g({eventType:h(),eventData:r=>r});function Se(r,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:r,eventData:t})}))}function xe(){const r=window;"TelegramGameProxy_receiveEvent"in r||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(t=>{let e=r;t.forEach((n,s,i)=>{if(s===i.length-1){e[n]=Se;return}n in e||(e[n]={}),e=e[n]})})}function Ae(r){xe(),window.addEventListener("message",t=>{try{const{eventType:e,eventData:n}=ke.parse(t.data);r(e,n)}catch{}})}function qe(){return g({req_id:h(),data:r=>r===null?r:h().optional().parse(r)})}function Le(){return g({req_id:h(),result:r=>r,error:h().optional()})}function Te(){return g({slug:h(),status:h()})}function Ve(){return g({status:h()})}function $e(){return g({button_id:r=>r==null?void 0:h().parse(r)})}function Ie(){return g({data:h().optional()})}function Re(){return g({theme_params:r=>{const t=vt().optional();return Object.entries(X(r)).reduce((e,[n,s])=>(e[n]=t.parse(s),e),{})}})}function Be(){return g({height:L(),width:r=>r==null?window.innerWidth:L().parse(r),is_state_stable:v(),is_expanded:v()})}function De(){return g({status:h()})}function He(){const r=new w,t=(e,...n)=>{A.log("Emitting processed event:",e,...n),r.emit(e,...n)};return window.addEventListener("resize",()=>{t("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),Ae((e,n)=>{A.log("Received raw event:",e,n);try{switch(e){case"viewport_changed":return t(e,Be().parse(n));case"theme_changed":return t(e,Re().parse(n));case"popup_closed":return n==null?t(e,{}):t(e,$e().parse(n));case"set_custom_style":return t(e,h().parse(n));case"qr_text_received":return t(e,Ie().parse(n));case"clipboard_text_received":return t(e,qe().parse(n));case"invoice_closed":return t(e,Te().parse(n));case"phone_requested":return t("phone_requested",Ve().parse(n));case"custom_method_invoked":return t("custom_method_invoked",Le().parse(n));case"write_access_requested":return t("write_access_requested",De().parse(n));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":case"reload_iframe":return t(e);default:return t(e,n)}}catch(s){A.error("Error processing event:",s)}}),r}const Q="telegram-mini-apps-cached-emitter";function O(){const r=window;return r[Q]===void 0&&(r[Q]=He()),r[Q]}function $(r,t){O().off(r,t)}function m(r,t){return O().on(r,t),()=>$(r,t)}function Ne(r,t){return O().once(r,t),()=>$(r,t)}function $t(r){O().unsubscribe(r)}function Oe(r){return O().subscribe(r),()=>$t(r)}function It(r,t){const e=r.split("."),n=t.split("."),s=Math.max(e.length,n.length);for(let i=0;i<s;i+=1){const a=parseInt(e[i]||"0",10),c=parseInt(n[i]||"0",10);if(a!==c)return a>c?1:-1}return 0}function C(r,t){return It(r,t)<=0}function S(r,t,e){if(typeof e=="string"){if(r==="web_app_open_link"&&t==="try_instant_view")return C("6.4",e);if(r==="web_app_set_header_color"&&t==="color")return C("6.9",e)}switch(r){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 C("6.1",t);case"web_app_open_popup":return C("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 C("6.4",t);case"web_app_switch_inline_query":return C("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return C("6.9",t);case"web_app_setup_settings_button":return C("6.10",t);default:return!0}}function k(r,t){return e=>S(t[e],r)}function Rt(r,t){return e=>{const[n,s]=t[e];return S(n,s,r)}}function f(r,t,e){let n={},s;t===void 0&&e===void 0?n={}:t!==void 0&&e!==void 0?(n=e,s=t):t!==void 0&&("targetOrigin"in t?n=t:s=t);const{targetOrigin:i=Pe()}=n;if(A.log(`Calling method "${r}"`,s),ht()){window.parent.postMessage(JSON.stringify({eventType:r,eventData:s}),i);return}if(ye(window)){window.external.notify(JSON.stringify({eventType:r,eventData:s}));return}if(Ee(window)){window.TelegramWebviewProxy.postEvent(r,JSON.stringify(s));return}throw new Error("Unable to determine current environment and possible way to send event.")}function Bt(r){return(t,e)=>{if(!S(t,r))throw new z(t,r);if(q(e)){let n;if(t==="web_app_open_link"&&"try_instant_view"in e?n="try_instant_view":t==="web_app_set_header_color"&&"color"in e&&(n="color"),n&&!S(t,n,r))throw new J(t,n,r)}return f(t,e)}}class ut extends Error{constructor(t){super(`Async call timeout exceeded. Timeout: ${t}`),Object.setPrototypeOf(this,ut.prototype)}}function ft(r){return new Promise((t,e)=>{setTimeout(e,r,new ut(r))})}function Me(r,t){return typeof r=="function"?(...e)=>Promise.race([r(...e),ft(t)]):Promise.race([r,ft(t)])}function _(r,t,e,n){let s,i,a,c;typeof t=="string"||Array.isArray(t)?(a=Array.isArray(t)?t:[t],s=e):(i=t,a=Array.isArray(e)?e:[e],s=n),q(i)&&typeof i.req_id=="string"&&(c=i.req_id);const{postEvent:u=f,timeout:l}=s||{},p=s&&"capture"in s?s.capture:null,y=new Promise((d,E)=>{const x=a.map(R=>m(R,U=>{typeof c=="string"&&(!q(U)||U.req_id!==c)||typeof p=="function"&&!p(U)||(I(),d(U))})),I=()=>x.forEach(R=>R());try{u(r,i)}catch(R){I(),E(R)}});return typeof l=="number"?Me(y,l):y}class Dt{constructor(t,e,n=f){o(this,"ee",new w);o(this,"state");o(this,"on",(t,e)=>t==="click"?m("back_button_pressed",e):this.ee.on(t,e));o(this,"off",(t,e)=>t==="click"?$("back_button_pressed",e):this.ee.off(t,e));o(this,"supports");this.postEvent=n,this.state=new b({isVisible:t},this.ee),this.supports=k(e,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"})}set isVisible(t){this.state.set("isVisible",t),this.postEvent("web_app_setup_back_button",{is_visible:t})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function gt(r,t){return r+(r.length>0&&t.length>0?` ${t}`:t)}function Ht(...r){return r.reduce((t,e)=>{let n="";return typeof e=="string"?n=e:typeof e=="object"&&e!==null&&(n=Object.entries(e).reduce((s,[i,a])=>a?gt(s,i):s,"")),gt(t,n)},"")}function We(r){return typeof r=="object"&&r!==null&&!Array.isArray(null)}function Ue(...r){return r.reduce((t,e)=>(We(e)&&Object.entries(e).forEach(([n,s])=>{const i=Ht(t[n],s);i.length>0&&(t[n]=i)}),t),{})}class Nt{constructor(t,e=f){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.postEvent=e,this.state=new b({isConfirmationNeeded:t},this.ee)}set isConfirmationNeeded(t){this.state.set("isConfirmationNeeded",t),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:t})}get isConfirmationNeeded(){return this.state.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}const Ge=ne().of(h());function wt(r,t){return r.reduce((e,n)=>(e[n]=t,e),{})}class Ot{constructor(t,e,n=f){o(this,"supports");this.createRequestId=e,this.postEvent=n,this.supports=k(t,{delete:"web_app_invoke_custom_method",get:"web_app_invoke_custom_method",getKeys:"web_app_invoke_custom_method",set:"web_app_invoke_custom_method"})}async invokeCustomMethod(t,e,n={}){const{result:s,error:i}=await _("web_app_invoke_custom_method",{method:t,params:e,req_id:this.createRequestId()},"custom_method_invoked",{...n,postEvent:this.postEvent});if(i)throw new Error(i);return s}async delete(t,e){const n=Array.isArray(t)?t:[t];n.length!==0&&await this.invokeCustomMethod("deleteStorageValues",{keys:n},e)}async getKeys(t){const e=await this.invokeCustomMethod("getStorageKeys",{},t);return Ge.parse(e)}async get(t,e){const n=Array.isArray(t)?t:[t];if(n.length===0)return wt(n,"");const s=g(wt(n,h())),i=await this.invokeCustomMethod("getStorageValues",{keys:n},e).then(a=>s.parse(a));return Array.isArray(t)?i:i[t]}async set(t,e,n){await this.invokeCustomMethod("saveStorageValue",{key:t,value:e},n)}}class Mt{constructor(t,e=f){o(this,"supports");this.postEvent=e,this.supports=k(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"})}impactOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"impact",impact_style:t})}notificationOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"notification",notification_type:t})}selectionChanged(){this.postEvent("web_app_trigger_haptic_feedback",{type:"selection_change"})}}function je(){const r=document.createElement("style");r.id="telegram-custom-styles",document.head.appendChild(r),m("set_custom_style",t=>{r.innerHTML=t})}function Wt(r){return`telegram-mini-apps-${r}`}function M(r,t){sessionStorage.setItem(Wt(r),JSON.stringify(t))}function W(r){const t=sessionStorage.getItem(Wt(r));return t?JSON.parse(t):null}function Fe(r,t,e){const{isVisible:n=!1}=r?W("back-button")||{}:{},s=new Dt(n,t,e);return s.on("change",()=>{M("back-button",{isVisible:s.isVisible})}),s}function ze(r,t){const{isConfirmationNeeded:e=!1}=r?W("closing-behavior")||{}:{},n=new Nt(e,t);return n.on("change",()=>M("closing-behavior",{isConfirmationNeeded:n.isConfirmationNeeded})),n}class Ut{constructor(t){o(this,"ee",new w);o(this,"state");o(this,"postEvent");o(this,"on",(t,e)=>t==="click"?m("main_button_pressed",e):this.ee.on(t,e));o(this,"off",(t,e)=>t==="click"?$("main_button_pressed",e):this.ee.off(t,e));const{postEvent:e=f,text:n,textColor:s,backgroundColor:i,isEnabled:a,isVisible:c,isLoaderVisible:u}=t;this.postEvent=e,this.state=new b({backgroundColor:i,isEnabled:a,isVisible:c,isLoaderVisible:u,text:n,textColor:s},this.ee)}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.backgroundColor,text_color:this.textColor})}set isEnabled(t){this.setParams({isEnabled:t})}get isEnabled(){return this.state.get("isEnabled")}set isLoaderVisible(t){this.setParams({isLoaderVisible:t})}get isLoaderVisible(){return this.state.get("isLoaderVisible")}set isVisible(t){this.setParams({isVisible:t})}get isVisible(){return this.state.get("isVisible")}get backgroundColor(){return this.state.get("backgroundColor")}get text(){return this.state.get("text")}get textColor(){return this.state.get("textColor")}disable(){return this.isEnabled=!1,this}enable(){return this.isEnabled=!0,this}hide(){return this.isVisible=!1,this}hideLoader(){return this.isLoaderVisible=!1,this}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(t){return this.setParams({text:t})}setTextColor(t){return this.setParams({textColor:t})}setBackgroundColor(t){return this.setParams({backgroundColor:t})}setParams(t){return this.state.set(t),this.commit(),this}}function Je(r,t,e,n){const{backgroundColor:s=t,isEnabled:i=!1,isVisible:a=!1,isLoaderVisible:c=!1,textColor:u=e,text:l=""}=r?W("main-button")||{}:{},p=new Ut({backgroundColor:s,isEnabled:i,isLoaderVisible:c,isVisible:a,postEvent:n,text:l,textColor:u}),y=()=>M("main-button",{backgroundColor:p.backgroundColor,isEnabled:p.isEnabled,isLoaderVisible:p.isLoaderVisible,isVisible:p.isVisible,text:p.text,textColor:p.textColor});return p.on("change",y),p}class Gt{constructor(t){o(this,"ee",new w);o(this,"state");o(this,"botInline");o(this,"postEvent");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");o(this,"supportsParam");const{postEvent:e=f,headerColor:n,backgroundColor:s,version:i,botInline:a}=t,c=k(i,{requestPhoneAccess:"web_app_request_phone",requestWriteAccess:"web_app_request_write_access",switchInlineQuery:"web_app_switch_inline_query",setHeaderColor:"web_app_set_header_color",setBackgroundColor:"web_app_set_background_color"});this.postEvent=e,this.botInline=a,this.supports=u=>!(!c(u)||u==="switchInlineQuery"&&!a),this.state=new b({backgroundColor:s,headerColor:n},this.ee),this.supportsParam=Rt(i,{"setHeaderColor.color":["web_app_set_header_color","color"]})}get backgroundColor(){return this.state.get("backgroundColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.state.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return rt(this.backgroundColor)}ready(){this.postEvent("web_app_ready")}requestPhoneAccess(){return _("web_app_request_phone","phone_requested",{postEvent:this.postEvent}).then(t=>t.status)}requestWriteAccess(){return _("web_app_request_write_access","write_access_requested",{postEvent:this.postEvent}).then(t=>t.status)}sendData(t){const{size:e}=new Blob([t]);if(e===0||e>4096)throw new Error(`Passed data has incorrect size: ${e}`);this.postEvent("web_app_data_send",{data:t})}setHeaderColor(t){this.postEvent("web_app_set_header_color",tt(t)?{color:t}:{color_key:t}),this.state.set("headerColor",t)}setBackgroundColor(t){this.postEvent("web_app_set_background_color",{color:t}),this.state.set("backgroundColor",t)}switchInlineQuery(t,e=[]){if(!this.supports("switchInlineQuery")&&!this.isBotInline)throw new Error("Method is unsupported because Mini App should be launched in inline mode.");this.postEvent("web_app_switch_inline_query",{query:t,chat_types:e})}}function Qe(r,t,e,n,s){const{backgroundColor:i=t,headerColor:a="bg_color"}=r?W("mini-app")||{}:{},c=new Gt({headerColor:a,backgroundColor:i,version:e,botInline:n,postEvent:s}),u=()=>M("mini-app",{backgroundColor:c.backgroundColor,headerColor:c.headerColor});return c.on("change",u),c}function Ze(){let r=0;return()=>(r+=1,r.toString())}function Ke(r){const t=new At(r);return t.listen(),t}async function pt(r){const t=await _("web_app_request_viewport","viewport_changed",r);return{height:t.height,width:t.width,isExpanded:t.is_expanded,isStateStable:t.is_state_stable}}function B(r){return r<0?0:r}class N{constructor(t){o(this,"ee",new w);o(this,"state");o(this,"postEvent");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));const{height:e,isExpanded:n,width:s,stableHeight:i,postEvent:a=f}=t;this.postEvent=a,this.state=new b({height:B(e),isExpanded:n,stableHeight:B(i),width:B(s)},this.ee)}sync(t){return pt(t).then(({height:e,isExpanded:n,width:s,isStateStable:i})=>{this.state.set({height:e,width:s,isExpanded:n,stableHeight:i?e:this.state.get("stableHeight")})})}get height(){return this.state.get("height")}get stableHeight(){return this.state.get("stableHeight")}listen(){return m("viewport_changed",t=>{const{height:e,width:n,is_expanded:s,is_state_stable:i}=t,a={height:B(e),isExpanded:s,width:B(n)};i&&(a.stableHeight=a.height),this.state.set(a)})}get isExpanded(){return this.state.get("isExpanded")}get width(){return this.state.get("width")}expand(){this.postEvent("web_app_expand"),this.state.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}function jt(r,t,e){if(r||t==="macos"||t==="web"||t==="weba")return new N({height:window.innerHeight,isExpanded:!0,postEvent:e,stableHeight:window.innerHeight,width:window.innerWidth});const n=W("viewport");return n?new N({...n,postEvent:e}):null}function Ft(r){return r.listen(),r.on("change",()=>M("viewport",{height:r.height,isExpanded:r.isExpanded,stableHeight:r.stableHeight,width:r.width})),r}function Ye(r,t,e){const n=Ft(jt(r,t,e)||new N({width:0,height:0,isExpanded:!1,postEvent:e,stableHeight:0}));return n.sync({postEvent:e,timeout:100}).catch(s=>{console.error("Unable to actualize viewport state",s)}),n}async function Xe(r,t,e){return Ft(jt(r,t,e)||await pt({postEvent:e,timeout:100}).then(({height:n,isStateStable:s,...i})=>new N({...i,height:n,stableHeight:s?n:0})))}function P(r,t){document.documentElement.style.setProperty(r,t)}function tr(r,t){const e=()=>{P("--tg-background-color",r.backgroundColor)},n=()=>{const{backgroundColor:s,secondaryBackgroundColor:i}=t;r.headerColor==="bg_color"?s&&P("--tg-header-color",s):r.headerColor==="secondary_bg_color"?i&&P("--tg-header-color",i):P("--tg-header-color",r.headerColor)};t.on("change",n),r.on("change:backgroundColor",e),r.on("change:headerColor",n),e(),n()}function er(r){const t=()=>{const e=r.getState();Object.entries(e).forEach(([n,s])=>{if(s){const i=n.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);P(`--tg-theme-${i}`,s)}})};r.on("change",t),t()}function _t(r){const t=()=>P("--tg-viewport-height",`${r.height}px`),e=()=>P("--tg-viewport-width",`${r.width}px`),n=()=>P("--tg-viewport-height",`${r.stableHeight}px`);r.on("change:height",t),r.on("change:width",e),r.on("change:stableHeight",n),t(),e(),n()}function rr(r){return typeof r=="object"?r:r?{themeParams:!0,viewport:!0,miniApp:!0}:{}}function bt(r,t,e,n){const s=rr(r);s.miniApp&&tr(t,e),s.themeParams&&er(e),s.viewport&&(n instanceof Promise?n.then(_t):_t(n))}function nr(r){const{hostname:t,pathname:e}=new URL(r,window.location.href);if(t!=="t.me")throw new Error(`Incorrect hostname: ${t}`);const n=e.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(n===null)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');return n[2]}class zt{constructor(t,e=f){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new b({isOpened:!1},this.ee),this.supports=k(t,{open:"web_app_open_invoice"})}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}async open(t,e){if(this.isOpened)throw new Error("Invoice is already opened");const n=e?nr(t):t;this.isOpened=!0;try{return(await _("web_app_open_invoice",{slug:n},"invoice_closed",{postEvent:this.postEvent,capture(i){return n===i.slug}})).status}finally{this.isOpened=!1}}}function sr(r){const t=r.message.trim(),e=(r.title||"").trim(),n=r.buttons||[];let s;if(e.length>64)throw new Error(`Title has incorrect size: ${e.length}`);if(t.length===0||t.length>256)throw new Error(`Message has incorrect size: ${t.length}`);if(n.length>3)throw new Error(`Buttons have incorrect size: ${n.length}`);return n.length===0?s=[{type:"close",id:""}]:s=n.map(i=>{const{id:a=""}=i;if(a.length>64)throw new Error(`Button ID has incorrect size: ${a}`);if(i.type===void 0||i.type==="default"||i.type==="destructive"){const c=i.text.trim();if(c.length===0||c.length>64){const u=i.type||"default";throw new Error(`Button text with type "${u}" has incorrect size: ${i.text.length}`)}return{...i,text:c,id:a}}return{...i,id:a}}),{title:e,message:t,buttons:s}}class Jt{constructor(t,e=f){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new b({isOpened:!1},this.ee),this.supports=k(t,{open:"web_app_open_popup"})}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}open(t){if(this.isOpened)throw new Error("Popup is already opened.");return this.isOpened=!0,_("web_app_open_popup",sr(t),"popup_closed",{postEvent:this.postEvent}).then(({button_id:e=null})=>e).finally(()=>{this.isOpened=!1})}}class Qt{constructor(t,e=f){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new b({isOpened:!1},this.ee),this.supports=k(t,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"})}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}async open(t){if(this.isOpened)throw new Error("QR scanner is already opened.");this.isOpened=!0;try{const e=await _("web_app_open_scan_qr_popup",{text:t},["qr_text_received","scan_qr_popup_closed"],{postEvent:this.postEvent});return typeof e=="object"&&typeof e.data=="string"?e.data:null}finally{this.isOpened=!1}}}class Zt{constructor(t,e,n=f){o(this,"supports");o(this,"supportsParam");this.version=t,this.createRequestId=e,this.postEvent=n,this.supports=k(t,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),this.supportsParam=Rt(t,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(t,e){const n=new URL(t,window.location.href).toString();if(!S("web_app_open_link",this.version)){window.open(n,"_blank");return}this.postEvent("web_app_open_link",{url:n,...typeof e=="boolean"?{try_instant_view:e}:{}})}openTelegramLink(t){const{hostname:e,pathname:n,search:s}=new URL(t,window.location.href);if(e!=="t.me")throw new Error(`URL has not allowed hostname: ${e}. Only "t.me" is allowed`);if(!S("web_app_open_tg_link",this.version)){window.location.href=t;return}this.postEvent("web_app_open_tg_link",{path_full:n+s})}readTextFromClipboard(){return _("web_app_read_text_from_clipboard",{req_id:this.createRequestId()},"clipboard_text_received",{postEvent:this.postEvent}).then(({data:t=null})=>t)}}function ir(r){const{async:t=!1,cssVars:e=!1,acceptCustomStyles:n=!1}=r;try{const{launchParams:{initData:s,initDataRaw:i,version:a,platform:c,themeParams:u,botInline:l=!1},isPageReload:p}=ct(),y=Ze(),d=Bt(a);ht()&&(n&&je(),d("iframe_ready",{reload_supported:!0}),m("reload_iframe",()=>window.location.reload()));const E={backButton:Fe(p,a,d),closingBehavior:ze(p,d),cloudStorage:new Ot(a,y,d),createRequestId:y,hapticFeedback:new Mt(a,d),invoice:new zt(a,d),mainButton:Je(p,u.buttonColor||"#000000",u.buttonTextColor||"#ffffff",d),miniApp:Qe(p,u.backgroundColor||"#ffffff",a,l,d),popup:new Jt(a,d),postEvent:d,qrScanner:new Qt(a,d),themeParams:Ke(u),utils:new Zt(a,y,d),...s?{initData:new St(s),initDataRaw:i}:{}},x=t?Xe(p,c,d):Ye(p,c,d);return x instanceof Promise?x.then(I=>(bt(e,E.miniApp,E.themeParams,I),{...E,viewport:I})):(bt(e,E.miniApp,E.themeParams,x),{...E,viewport:x})}catch(s){if(t)return Promise.reject(s);throw s}}function D(r,t){return r.startsWith(t)?r:`${t}${r}`}function or(r){const t=r.match(/#(.+)/);return t?t[1]:null}async function H(r){return r===0?!0:Promise.race([new Promise(t=>{window.addEventListener("popstate",function e(){window.removeEventListener("popstate",e),t(!0)}),window.history.go(r)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function ar(){if(window.history.length<=1||(window.history.pushState(null,""),await H(1-window.history.length)))return;let t=await H(-1);for(;t;)t=await H(-1)}class Kt{constructor(t,e,{debug:n=!1,loggerPrefix:s="Navigator"}){o(this,"logger");o(this,"entries");if(this.entriesCursor=e,t.length===0)throw new Error("Entries list should not be empty.");if(e>=t.length)throw new Error("Cursor should be less than entries count.");this.entries=t.map(({pathname:i="",search:a,hash:c})=>{if(!i.startsWith("/")&&i.length>0)throw new Error('Pathname should start with "/"');return{pathname:D(i,"/"),search:a?D(a,"?"):"",hash:c?D(c,"#"):""}}),this.logger=new Tt(`[${s}]`,n)}formatEntry(t){let e;if(typeof t=="string")e=t;else{const{pathname:a="",search:c,hash:u}=t;e=a+(c?D(c,"?"):"")+(u?D(u,"#"):"")}const{pathname:n,search:s,hash:i}=new URL(e,`https://localhost${this.path}`);return{pathname:n,search:s,hash:i}}get entry(){return this.entries[this.entriesCursor]}back(){return this.go(-1)}get cursor(){return this.entriesCursor}get canGoBack(){return this.entriesCursor>0}get canGoForward(){return this.entriesCursor!==this.entries.length-1}forward(){return this.go(1)}go(t){this.logger.log(`called go(${t})`);const e=Math.min(this.entries.length-1,Math.max(this.entriesCursor+t,0));if(this.entriesCursor===e)return this.performGo({updated:!1,delta:t});const n=this.entry;this.entriesCursor=e;const s=this.entry;return this.logger.log("State changed",{before:n,after:s}),this.performGo({updated:!0,delta:t,before:n,after:s})}getEntries(){return this.entries.map(t=>({...t}))}get hash(){return this.entry.hash}push(t){this.entriesCursor!==this.entries.length-1&&this.entries.splice(this.entriesCursor+1);const e=this.formatEntry(t),n=this.entry;this.entriesCursor+=1,this.entries[this.entriesCursor]=e;const s=this.entry;return this.logger.log("State changed",{before:n,after:s}),this.performPush({before:n,after:s})}get path(){return`${this.pathname}${this.search}${this.hash}`}get pathname(){return this.entry.pathname}replace(t){const e=this.formatEntry(t);if(this.search===e.search&&this.pathname===e.pathname&&this.hash===e.hash)return this.performReplace({updated:!1,entry:e});const n=this.entry;this.entries[this.entriesCursor]=e;const s=this.entry;return this.logger.log("State changed",{before:n,after:s}),this.performReplace({updated:!0,before:n,after:s})}get search(){return this.entry.search}}const mt=0,Z=1,K=2;class lt extends Kt{constructor(e,n,s={}){super(e,n,{...s,loggerPrefix:"HashNavigator"});o(this,"ee",new w);o(this,"attached",!1);o(this,"onPopState",async({state:e})=>{if(this.logger.log('"popstate" event received. State:',e),e===null)return this.push(window.location.hash.slice(1));if(e===mt){this.logger.log("Void reached. Moving history forward"),window.history.forward();return}if(e===Z)return this.back();if(e===K)return this.forward()});o(this,"back",()=>super.back());o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee))}static fromLocation(e){const{search:n,pathname:s,hash:i}=new URL(window.location.hash.slice(1),window.location.href);return new lt([{search:n,pathname:s,hash:i}],0,e)}async performGo(e){e.updated&&(this.attached&&await this.syncHistory(),this.emitChanged(e.before,e.after))}async performPush({before:e,after:n}){this.attached&&await this.syncHistory(),this.emitChanged(e,n)}async performReplace(e){e.updated&&(this.attached&&window.history.replaceState(null,"",`#${this.path}`),this.emitChanged(e.before,e.after))}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const e=`#${this.path}`;await ar(),f("web_app_setup_back_button",{is_visible:this.canGoBack}),this.canGoBack&&this.canGoForward?(this.logger.log("Setting up history: [<-, *, ->]"),window.history.replaceState(Z,""),window.history.pushState(null,"",e),window.history.pushState(K,""),await H(-1)):this.canGoBack?(this.logger.log("Setting up history: [<-, *]"),window.history.replaceState(Z,""),window.history.pushState(null,"",e)):this.canGoForward?(this.logger.log("Setting up history: [*, ->]"),window.history.replaceState(null,e),window.history.pushState(K,""),await H(-1)):(this.logger.log("Setting up history: [~, *]"),window.history.replaceState(mt,""),window.history.pushState(null,"",e)),window.addEventListener("popstate",this.onPopState)}emitChanged(e,n){this.ee.emit("change",{navigator:this,from:e,to:n})}async attach(){if(!this.attached)return this.logger.log("Attaching",this),this.attached=!0,m("back_button_pressed",this.back),this.syncHistory()}detach(){this.attached&&(this.logger.log("Detaching",this),this.attached=!1,window.removeEventListener("popstate",this.onPopState),$("back_button_pressed",this.back))}}exports.BackButton=Dt;exports.ClosingBehavior=Nt;exports.CloudStorage=Ot;exports.HapticFeedback=Mt;exports.HashNavigator=lt;exports.InitData=St;exports.Invoice=zt;exports.MainButton=Ut;exports.MethodUnsupportedError=z;exports.MiniApp=Gt;exports.Navigator=Kt;exports.ParameterUnsupportedError=J;exports.Popup=Jt;exports.QRScanner=Qt;exports.ThemeParams=At;exports.Utils=Zt;exports.Viewport=N;exports.chatParser=kt;exports.classNames=Ht;exports.compareVersions=It;exports.createPostEvent=Bt;exports.getHash=or;exports.init=ir;exports.initDataParser=nt;exports.isColorDark=rt;exports.isIframe=ht;exports.isRGB=tt;exports.isRGBShort=Ct;exports.isRecord=q;exports.isTMA=me;exports.launchParamsParser=ot;exports.mergeClassNames=Ue;exports.off=$;exports.on=m;exports.once=Ne;exports.parseInitData=ae;exports.parseLaunchParams=at;exports.parseThemeParams=it;exports.postEvent=f;exports.request=_;exports.requestThemeParams=pe;exports.requestViewport=pt;exports.retrieveLaunchData=ct;exports.serializeLaunchParams=qt;exports.serializeThemeParams=xt;exports.setDebug=Ce;exports.setTargetOrigin=ve;exports.subscribe=Oe;exports.supports=S;exports.themeParamsParser=st;exports.toRGB=et;exports.unsubscribe=$t;exports.userParser=Y;
1
+ "use strict";var te=Object.defineProperty;var ee=(r,t,e)=>t in r?te(r,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):r[t]=e;var o=(r,t,e)=>(ee(r,typeof t!="symbol"?t+"":t,e),e);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function q(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function yt(){return performance.getEntriesByType("navigation")[0]||null}function re(){const r=yt();return r?r.type==="reload":null}function T(){return new TypeError("Value has unexpected type")}class j extends Error{constructor(e,{cause:s,type:n}={}){super(`Unable to parse value${n?` as ${n}`:""}`,{cause:s});o(this,"type");this.value=e,Object.setPrototypeOf(this,j.prototype),this.type=n}}class F{constructor(t,e,s){this.parser=t,this.isOptional=e,this.type=s}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(e){throw new j(t,{type:this.type,cause:e})}}optional(){return this.isOptional=!0,this}}function se(r){if(Array.isArray(r))return r;if(typeof r=="string")try{const t=JSON.parse(r);if(Array.isArray(t))return t}catch{}throw T()}class ne extends F{constructor(e,s,n){super(se,s,n);o(this,"itemParser");this.itemParser=typeof e=="function"?e:e.parse.bind(e)}parse(e){const s=super.parse(e);return s===void 0?s:s.map(this.itemParser)}of(e){return this.itemParser=typeof e=="function"?e:e.parse.bind(e),this}}function B(r,t){return()=>new F(r,!1,t)}class G extends Error{constructor(t,{cause:e,type:s}={}){super(`Unable to parse field "${t}"${s?` as ${s}`:""}`,{cause:e}),Object.setPrototypeOf(this,G.prototype)}}function Et(r,t){const e={};for(const s in r){const n=r[s];if(!n)continue;let i,a;if(typeof n=="function"||"parse"in n)i=s,a=typeof n=="function"?n:n.parse.bind(n);else{const{type:d}=n;i=n.from||s,a=typeof d=="function"?d:d.parse.bind(d)}let c;const u=t(i);try{c=a(u)}catch(d){throw d instanceof j?new G(i,{type:d.type,cause:d}):new G(i,{cause:d})}c!==void 0&&(e[s]=c)}return e}function ie(r){return new ne(t=>t,!1,r)}const P=B(r=>{if(typeof r=="boolean")return r;const t=String(r);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;throw T()},"boolean"),L=B(r=>{if(typeof r=="number")return r;if(typeof r=="string"){const t=Number(r);if(!Number.isNaN(t))return t}throw T()},"number"),oe=B(r=>r instanceof Date?r:new Date(L().parse(r)*1e3),"Date");function X(r){let t=r;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw T();return t}function g(r,t){return new F(e=>{const s=X(e);return Et(r,n=>s[n])},!1,t)}function tt(r){return/^#[\da-f]{6}$/i.test(r)}function Ct(r){return/^#[\da-f]{3}$/i.test(r)}function et(r){const t=r.replace(/\s/g,"").toLowerCase();if(tt(t))return t;if(Ct(t)){let s="#";for(let n=0;n<3;n+=1)s+=t[1+n].repeat(2);return s}const e=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(e===null)throw new Error(`Value "${r}" does not satisfy any of known RGB formats.`);return e.slice(1).reduce((s,n)=>{const i=parseInt(n,10).toString(16);return s+(i.length===1?"0":"")+i},"#")}function rt(r){const t=et(r);return Math.sqrt([.299,.587,.114].reduce((s,n,i)=>{const a=parseInt(t.slice(1+i*2,1+(i+1)*2),16);return s+a*a*n},0))<120}const h=B(r=>{if(typeof r=="string"||typeof r=="number")return r.toString();throw T()},"string"),vt=B(r=>et(h().parse(r)),"rgb");function Pt(r,t){return new F(e=>{if(typeof e!="string"&&!(e instanceof URLSearchParams))throw T();const s=typeof e=="string"?new URLSearchParams(e):e;return Et(r,n=>{const i=s.get(n);return i===null?void 0:i})},!1,t)}function kt(){return g({id:L(),type:h(),title:h(),photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"Chat")}class St{constructor(t){this.initData=t}get authDate(){return this.initData.authDate}get canSendAfter(){return this.initData.canSendAfter}get canSendAfterDate(){const{canSendAfter:t}=this;return t===void 0?void 0:new Date(this.authDate.getTime()+t*1e3)}get chat(){return this.initData.chat}get chatType(){return this.initData.chatType}get chatInstance(){return this.initData.chatInstance}get hash(){return this.initData.hash}get queryId(){return this.initData.queryId}get receiver(){return this.initData.receiver}get startParam(){return this.initData.startParam}get user(){return this.initData.user}}function Y(){return g({addedToAttachmentMenu:{type:P().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:P().optional(),from:"allows_write_to_pm"},firstName:{type:h(),from:"first_name"},id:L(),isBot:{type:P().optional(),from:"is_bot"},isPremium:{type:P().optional(),from:"is_premium"},languageCode:{type:h().optional(),from:"language_code"},lastName:{type:h().optional(),from:"last_name"},photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"User")}function st(){return Pt({authDate:{type:oe(),from:"auth_date"},canSendAfter:{type:L().optional(),from:"can_send_after"},chat:kt().optional(),chatInstance:{type:h().optional(),from:"chat_instance"},chatType:{type:h().optional(),from:"chat_type"},hash:h(),queryId:{type:h().optional(),from:"query_id"},receiver:Y().optional(),startParam:{type:h().optional(),from:"start_param"},user:Y().optional()},"InitData")}function ae(r){return st().parse(r)}function ce(r){return r.replace(/(^|_)bg/,(t,e)=>`${e}background`).replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function he(r){return r.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`).replace(/(^|_)background/,(t,e)=>`${e}bg`)}const nt=B(r=>{const t=vt().optional();return Object.entries(X(r)).reduce((e,[s,n])=>(e[ce(s)]=t.parse(n),e),{})},"ThemeParams");function it(r){return nt().parse(r)}function ue(r={}){return w("web_app_request_theme","theme_changed",r).then(it)}function xt(r){return JSON.stringify(Object.entries(r).reduce((t,[e,s])=>(s&&(t[he(e)]=s),t),{}))}class _{constructor(){o(this,"listeners",new Map);o(this,"subscribeListeners",[])}addListener(t,e,s){let n=this.listeners.get(t);return n||(n=[],this.listeners.set(t,n)),n.push([e,s]),()=>this.off(t,e)}emit(t,...e){this.subscribeListeners.forEach(n=>n(t,...e));const s=this.listeners.get(t);s&&s.forEach(([n,i],a)=>{n(...e),i&&s.splice(a,1)})}on(t,e){return this.addListener(t,e,!1)}once(t,e){return this.addListener(t,e,!0)}off(t,e){const s=this.listeners.get(t);if(s){for(let n=0;n<s.length;n+=1)if(e===s[n][0]){s.splice(n,1);return}}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let e=0;e<this.subscribeListeners.length;e+=1)if(this.subscribeListeners[e]===t){this.subscribeListeners.splice(e,1);return}}}class b{constructor(t,e){this.state=t,this.ee=e}internalSet(t,e){return this.state[t]===e||e===void 0?!1:(this.state[t]=e,this.ee.emit(`change:${t}`,e),!0)}clone(){return{...this.state}}set(t,e){let s=!1;if(typeof t=="string")s=this.internalSet(t,e);else for(const n in t)this.internalSet(n,t[n])&&(s=!0);s&&this.ee.emit("change")}get(t){return this.state[t]}}class Vt{constructor(t){o(this,"ee",new _);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.state=new b(t,this.ee)}get accentTextColor(){return this.get("accentTextColor")}get backgroundColor(){return this.get("backgroundColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}get(t){return this.state.get(t)}getState(){return this.state.clone()}get headerBackgroundColor(){return this.get("headerBackgroundColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.backgroundColor||rt(this.backgroundColor)}get linkColor(){return this.get("linkColor")}get secondaryBackgroundColor(){return this.get("secondaryBackgroundColor")}get sectionBackgroundColor(){return this.get("sectionBackgroundColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}listen(){return m("theme_changed",t=>{this.state.set(it(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}function ot(){return Pt({botInline:{type:P().optional(),from:"tgWebAppBotInline"},initData:{type:st().optional(),from:"tgWebAppData"},initDataRaw:{type:h().optional(),from:"tgWebAppData"},platform:{type:h(),from:"tgWebAppPlatform"},showSettings:{type:P().optional(),from:"tgWebAppShowSettings"},themeParams:{type:nt(),from:"tgWebAppThemeParams"},version:{type:h(),from:"tgWebAppVersion"}},"LaunchParams")}function at(r){return ot().parse(r)}function pe(){return at(window.location.hash.slice(1))}function le(){const r=yt();if(!r)throw new Error("Unable to get first navigation entry.");const t=r.name.match(/#(.*)/);if(!t)throw new Error("First navigation entry does not contain hash part.");return at(t[1])}function de(){try{return le()}catch{}try{return pe()}catch{}return null}function At(r){const{initDataRaw:t,themeParams:e,platform:s,version:n,showSettings:i,botInline:a}=r,c=new URLSearchParams;return t&&c.set("tgWebAppData",t),c.set("tgWebAppPlatform",s),c.set("tgWebAppThemeParams",xt(e)),c.set("tgWebAppVersion",n),typeof i=="boolean"&&c.set("tgWebAppShowSettings",i?"1":"0"),typeof a=="boolean"&&c.set("tgWebAppBotInline",a?"1":"0"),c.toString()}const qt="telegram-mini-apps-launch-params";function fe(){const r=sessionStorage.getItem(qt);return r?ot().parse(r):null}function ge(r){sessionStorage.setItem(qt,At(r))}function _e(){try{return window.self!==window.top}catch{return!0}}function we(){const r=fe(),t=de(),e=re();if(r){if(t)return{launchParams:t,isPageReload:_e()?e||r.initDataRaw===t.initDataRaw:!0};if(e)return{launchParams:r,isPageReload:e};throw new Error("Unable to retrieve current launch parameters, which must exist.")}if(t)return{launchParams:t,isPageReload:!1};throw new Error("Unable to retrieve any launch parameters.")}const dt="tmajsLaunchData";function ct(){const r=window[dt];if(r)return r;const t=we();return window[dt]=t,ge(t.launchParams),t}function be(){try{return ct(),!0}catch{return!1}}function me(r){return"external"in r&&q(r.external)&&"notify"in r.external&&typeof r.external.notify=="function"}function ye(r){return"TelegramWebviewProxy"in r&&q(r.TelegramWebviewProxy)&&"postEvent"in r.TelegramWebviewProxy&&typeof r.TelegramWebviewProxy.postEvent=="function"}function ht(){try{return window.self!==window.top}catch{return!0}}class z extends Error{constructor(t,e){super(`Method "${t}" is unsupported in the Mini Apps version ${e}.`),Object.setPrototypeOf(this,z.prototype)}}class J extends Error{constructor(t,e,s){super(`Parameter "${e}" in method "${t}" is unsupported in the Mini Apps version ${s}.`),Object.setPrototypeOf(this,J.prototype)}}class Lt{constructor(t,e){this.prefix=t,this.enabled=e}print(t,...e){if(!this.enabled)return;const s=new Date,n=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(s);console[t](`[${n}]`,this.prefix,...e)}disable(){this.enabled=!1}error(...t){this.print("error",...t)}enable(){this.enabled=!0}log(...t){this.print("log",...t)}warn(...t){this.print("warn",...t)}}let Tt="https://web.telegram.org";const A=new Lt("[SDK]",!1);function Ee(r){if(r){A.enable();return}A.disable()}function Ce(r){Tt=r}function ve(){return Tt}const Pe=g({eventType:h(),eventData:r=>r});function ke(r,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:r,eventData:t})}))}function Se(){const r=window;"TelegramGameProxy_receiveEvent"in r||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(t=>{let e=r;t.forEach((s,n,i)=>{if(n===i.length-1){e[s]=ke;return}s in e||(e[s]={}),e=e[s]})})}function xe(r){Se(),window.addEventListener("message",t=>{try{const{eventType:e,eventData:s}=Pe.parse(t.data);r(e,s)}catch{}})}function Ve(){return g({req_id:h(),data:r=>r===null?r:h().optional().parse(r)})}function Ae(){return g({req_id:h(),result:r=>r,error:h().optional()})}function qe(){return g({slug:h(),status:h()})}function Le(){return g({status:h()})}function Te(){return g({button_id:r=>r==null?void 0:h().parse(r)})}function Be(){return g({data:h().optional()})}function Re(){return g({theme_params:r=>{const t=vt().optional();return Object.entries(X(r)).reduce((e,[s,n])=>(e[s]=t.parse(n),e),{})}})}function $e(){return g({height:L(),width:r=>r==null?window.innerWidth:L().parse(r),is_state_stable:P(),is_expanded:P()})}function Ie(){return g({status:h()})}function De(){const r=new _,t=(e,...s)=>{A.log("Emitting processed event:",e,...s),r.emit(e,...s)};return window.addEventListener("resize",()=>{t("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),xe((e,s)=>{A.log("Received raw event:",e,s);try{switch(e){case"viewport_changed":return t(e,$e().parse(s));case"theme_changed":return t(e,Re().parse(s));case"popup_closed":return s==null?t(e,{}):t(e,Te().parse(s));case"set_custom_style":return t(e,h().parse(s));case"qr_text_received":return t(e,Be().parse(s));case"clipboard_text_received":return t(e,Ve().parse(s));case"invoice_closed":return t(e,qe().parse(s));case"phone_requested":return t("phone_requested",Le().parse(s));case"custom_method_invoked":return t("custom_method_invoked",Ae().parse(s));case"write_access_requested":return t("write_access_requested",Ie().parse(s));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":case"reload_iframe":return t(e);default:return t(e,s)}}catch(n){A.error("Error processing event:",n)}}),r}const Q="telegram-mini-apps-cached-emitter";function W(){const r=window;return r[Q]===void 0&&(r[Q]=De()),r[Q]}function x(r,t){W().off(r,t)}function m(r,t){return W().on(r,t),()=>x(r,t)}function He(r,t){return W().once(r,t),()=>x(r,t)}function Bt(r){W().unsubscribe(r)}function Ne(r){return W().subscribe(r),()=>Bt(r)}function Rt(r,t){const e=r.split("."),s=t.split("."),n=Math.max(e.length,s.length);for(let i=0;i<n;i+=1){const a=parseInt(e[i]||"0",10),c=parseInt(s[i]||"0",10);if(a!==c)return a>c?1:-1}return 0}function v(r,t){return Rt(r,t)<=0}function S(r,t,e){if(typeof e=="string"){if(r==="web_app_open_link"&&t==="try_instant_view")return v("6.4",e);if(r==="web_app_set_header_color"&&t==="color")return v("6.9",e)}switch(r){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 v("6.1",t);case"web_app_open_popup":return v("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 v("6.4",t);case"web_app_switch_inline_query":return v("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return v("6.9",t);case"web_app_setup_settings_button":return v("6.10",t);default:return!0}}function y(r,t){return e=>S(t[e],r)}function $t(r,t){return e=>{const[s,n]=t[e];return S(s,n,r)}}function f(r,t,e){let s={},n;t===void 0&&e===void 0?s={}:t!==void 0&&e!==void 0?(s=e,n=t):t!==void 0&&("targetOrigin"in t?s=t:n=t);const{targetOrigin:i=ve()}=s;if(A.log(`Calling method "${r}"`,n),ht()){window.parent.postMessage(JSON.stringify({eventType:r,eventData:n}),i);return}if(me(window)){window.external.notify(JSON.stringify({eventType:r,eventData:n}));return}if(ye(window)){window.TelegramWebviewProxy.postEvent(r,JSON.stringify(n));return}throw new Error("Unable to determine current environment and possible way to send event.")}function It(r){return(t,e)=>{if(!S(t,r))throw new z(t,r);if(q(e)){let s;if(t==="web_app_open_link"&&"try_instant_view"in e?s="try_instant_view":t==="web_app_set_header_color"&&"color"in e&&(s="color"),s&&!S(t,s,r))throw new J(t,s,r)}return f(t,e)}}class ut extends Error{constructor(t){super(`Async call timeout exceeded. Timeout: ${t}`),Object.setPrototypeOf(this,ut.prototype)}}function ft(r){return new Promise((t,e)=>{setTimeout(e,r,new ut(r))})}function Oe(r,t){return typeof r=="function"?(...e)=>Promise.race([r(...e),ft(t)]):Promise.race([r,ft(t)])}function w(r,t,e,s){let n,i,a,c;typeof t=="string"||Array.isArray(t)?(a=Array.isArray(t)?t:[t],n=e):(i=t,a=Array.isArray(e)?e:[e],n=s),q(i)&&typeof i.req_id=="string"&&(c=i.req_id);const{postEvent:u=f,timeout:d}=n||{},p=n&&"capture"in n?n.capture:null,E=new Promise((l,C)=>{const V=a.map(D=>m(D,U=>{typeof c=="string"&&(!q(U)||U.req_id!==c)||typeof p=="function"&&!p(U)||(I(),l(U))})),I=()=>V.forEach(D=>D());try{u(r,i)}catch(D){I(),C(D)}});return typeof d=="number"?Oe(E,d):E}class Dt{constructor(t,e,s=f){o(this,"ee",new _);o(this,"state");o(this,"on",(t,e)=>t==="click"?m("back_button_pressed",e):this.ee.on(t,e));o(this,"off",(t,e)=>t==="click"?x("back_button_pressed",e):this.ee.off(t,e));o(this,"supports");this.postEvent=s,this.state=new b({isVisible:t},this.ee),this.supports=y(e,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"})}set isVisible(t){this.state.set("isVisible",t),this.postEvent("web_app_setup_back_button",{is_visible:t})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function gt(r,t){return r+(r.length>0&&t.length>0?` ${t}`:t)}function Ht(...r){return r.reduce((t,e)=>{let s="";return typeof e=="string"?s=e:typeof e=="object"&&e!==null&&(s=Object.entries(e).reduce((n,[i,a])=>a?gt(n,i):n,"")),gt(t,s)},"")}function Me(r){return typeof r=="object"&&r!==null&&!Array.isArray(null)}function We(...r){return r.reduce((t,e)=>(Me(e)&&Object.entries(e).forEach(([s,n])=>{const i=Ht(t[s],n);i.length>0&&(t[s]=i)}),t),{})}class Nt{constructor(t,e=f){o(this,"ee",new _);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.postEvent=e,this.state=new b({isConfirmationNeeded:t},this.ee)}set isConfirmationNeeded(t){this.state.set("isConfirmationNeeded",t),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:t})}get isConfirmationNeeded(){return this.state.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}function _t(r,t){return r.reduce((e,s)=>(e[s]=t,e),{})}class Ot{constructor(t,e,s=f){o(this,"supports");this.createRequestId=e,this.postEvent=s,this.supports=y(t,{delete:"web_app_invoke_custom_method",get:"web_app_invoke_custom_method",getKeys:"web_app_invoke_custom_method",set:"web_app_invoke_custom_method"})}async invokeCustomMethod(t,e,s={}){const{result:n,error:i}=await w("web_app_invoke_custom_method",{method:t,params:e,req_id:this.createRequestId()},"custom_method_invoked",{...s,postEvent:this.postEvent});if(i)throw new Error(i);return n}async delete(t,e){const s=Array.isArray(t)?t:[t];s.length!==0&&await this.invokeCustomMethod("deleteStorageValues",{keys:s},e)}async getKeys(t){const e=await this.invokeCustomMethod("getStorageKeys",{},t);return ie().of(h()).parse(e)}async get(t,e){const s=Array.isArray(t)?t:[t];if(s.length===0)return _t(s,"");const n=g(_t(s,h())),i=await this.invokeCustomMethod("getStorageValues",{keys:s},e).then(a=>n.parse(a));return Array.isArray(t)?i:i[t]}async set(t,e,s){await this.invokeCustomMethod("saveStorageValue",{key:t,value:e},s)}}class Mt{constructor(t,e=f){o(this,"supports");this.postEvent=e,this.supports=y(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"})}impactOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"impact",impact_style:t})}notificationOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"notification",notification_type:t})}selectionChanged(){this.postEvent("web_app_trigger_haptic_feedback",{type:"selection_change"})}}function Ue(){const r=document.createElement("style");r.id="telegram-custom-styles",document.head.appendChild(r),m("set_custom_style",t=>{r.innerHTML=t})}function Wt(r){return`telegram-mini-apps-${r}`}function R(r,t){sessionStorage.setItem(Wt(r),JSON.stringify(t))}function $(r){const t=sessionStorage.getItem(Wt(r));return t?JSON.parse(t):null}function Ge(r,t,e){const{isVisible:s=!1}=r?$("back-button")||{}:{},n=new Dt(s,t,e);return n.on("change",()=>{R("back-button",{isVisible:n.isVisible})}),n}function je(r,t){const{isConfirmationNeeded:e=!1}=r?$("closing-behavior")||{}:{},s=new Nt(e,t);return s.on("change",()=>R("closing-behavior",{isConfirmationNeeded:s.isConfirmationNeeded})),s}class Ut{constructor(t){o(this,"ee",new _);o(this,"state");o(this,"postEvent");o(this,"on",(t,e)=>t==="click"?m("main_button_pressed",e):this.ee.on(t,e));o(this,"off",(t,e)=>t==="click"?x("main_button_pressed",e):this.ee.off(t,e));const{postEvent:e=f,text:s,textColor:n,backgroundColor:i,isEnabled:a,isVisible:c,isLoaderVisible:u}=t;this.postEvent=e,this.state=new b({backgroundColor:i,isEnabled:a,isVisible:c,isLoaderVisible:u,text:s,textColor:n},this.ee)}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.backgroundColor,text_color:this.textColor})}set isEnabled(t){this.setParams({isEnabled:t})}get isEnabled(){return this.state.get("isEnabled")}set isLoaderVisible(t){this.setParams({isLoaderVisible:t})}get isLoaderVisible(){return this.state.get("isLoaderVisible")}set isVisible(t){this.setParams({isVisible:t})}get isVisible(){return this.state.get("isVisible")}get backgroundColor(){return this.state.get("backgroundColor")}get text(){return this.state.get("text")}get textColor(){return this.state.get("textColor")}disable(){return this.isEnabled=!1,this}enable(){return this.isEnabled=!0,this}hide(){return this.isVisible=!1,this}hideLoader(){return this.isLoaderVisible=!1,this}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(t){return this.setParams({text:t})}setTextColor(t){return this.setParams({textColor:t})}setBackgroundColor(t){return this.setParams({backgroundColor:t})}setParams(t){return this.state.set(t),this.commit(),this}}function Fe(r,t,e,s){const{backgroundColor:n=t,isEnabled:i=!1,isVisible:a=!1,isLoaderVisible:c=!1,textColor:u=e,text:d=""}=r?$("main-button")||{}:{},p=new Ut({backgroundColor:n,isEnabled:i,isLoaderVisible:c,isVisible:a,postEvent:s,text:d,textColor:u}),E=()=>R("main-button",{backgroundColor:p.backgroundColor,isEnabled:p.isEnabled,isLoaderVisible:p.isLoaderVisible,isVisible:p.isVisible,text:p.text,textColor:p.textColor});return p.on("change",E),p}class Gt{constructor(t){o(this,"ee",new _);o(this,"state");o(this,"botInline");o(this,"postEvent");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");o(this,"supportsParam");const{postEvent:e=f,headerColor:s,backgroundColor:n,version:i,botInline:a}=t,c=y(i,{requestPhoneAccess:"web_app_request_phone",requestWriteAccess:"web_app_request_write_access",switchInlineQuery:"web_app_switch_inline_query",setHeaderColor:"web_app_set_header_color",setBackgroundColor:"web_app_set_background_color"});this.postEvent=e,this.botInline=a,this.supports=u=>!(!c(u)||u==="switchInlineQuery"&&!a),this.state=new b({backgroundColor:n,headerColor:s},this.ee),this.supportsParam=$t(i,{"setHeaderColor.color":["web_app_set_header_color","color"]})}get backgroundColor(){return this.state.get("backgroundColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.state.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return rt(this.backgroundColor)}ready(){this.postEvent("web_app_ready")}requestPhoneAccess(){return w("web_app_request_phone","phone_requested",{postEvent:this.postEvent}).then(t=>t.status)}requestWriteAccess(){return w("web_app_request_write_access","write_access_requested",{postEvent:this.postEvent}).then(t=>t.status)}sendData(t){const{size:e}=new Blob([t]);if(e===0||e>4096)throw new Error(`Passed data has incorrect size: ${e}`);this.postEvent("web_app_data_send",{data:t})}setHeaderColor(t){this.postEvent("web_app_set_header_color",tt(t)?{color:t}:{color_key:t}),this.state.set("headerColor",t)}setBackgroundColor(t){this.postEvent("web_app_set_background_color",{color:t}),this.state.set("backgroundColor",t)}switchInlineQuery(t,e=[]){if(!this.supports("switchInlineQuery")&&!this.isBotInline)throw new Error("Method is unsupported because Mini App should be launched in inline mode.");this.postEvent("web_app_switch_inline_query",{query:t,chat_types:e})}}function ze(r,t,e,s,n){const{backgroundColor:i=t,headerColor:a="bg_color"}=r?$("mini-app")||{}:{},c=new Gt({headerColor:a,backgroundColor:i,version:e,botInline:s,postEvent:n}),u=()=>R("mini-app",{backgroundColor:c.backgroundColor,headerColor:c.headerColor});return c.on("change",u),c}function Je(){let r=0;return()=>(r+=1,r.toString())}class jt{constructor(t,e,s=f){o(this,"ee",new _);o(this,"state");o(this,"on",(t,e)=>t==="click"?m("settings_button_pressed",e):this.ee.on(t,e));o(this,"off",(t,e)=>t==="click"?x("settings_button_pressed",e):this.ee.off(t,e));o(this,"supports");this.postEvent=s,this.state=new b({isVisible:t},this.ee),this.supports=y(e,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"})}set isVisible(t){this.state.set("isVisible",t),this.postEvent("web_app_setup_settings_button",{is_visible:t})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function Qe(r,t,e){const{isVisible:s=!1}=r?$("settings-button")||{}:{},n=new jt(s,t,e);return n.on("change",()=>{R("settings-button",{isVisible:n.isVisible})}),n}function Ze(r){const t=new Vt(r);return t.listen(),t}async function pt(r){const t=await w("web_app_request_viewport","viewport_changed",r);return{height:t.height,width:t.width,isExpanded:t.is_expanded,isStateStable:t.is_state_stable}}function H(r){return r<0?0:r}class M{constructor(t){o(this,"ee",new _);o(this,"state");o(this,"postEvent");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));const{height:e,isExpanded:s,width:n,stableHeight:i,postEvent:a=f}=t;this.postEvent=a,this.state=new b({height:H(e),isExpanded:s,stableHeight:H(i),width:H(n)},this.ee)}sync(t){return pt(t).then(({height:e,isExpanded:s,width:n,isStateStable:i})=>{this.state.set({height:e,width:n,isExpanded:s,stableHeight:i?e:this.state.get("stableHeight")})})}get height(){return this.state.get("height")}get stableHeight(){return this.state.get("stableHeight")}listen(){return m("viewport_changed",t=>{const{height:e,width:s,is_expanded:n,is_state_stable:i}=t,a={height:H(e),isExpanded:n,width:H(s)};i&&(a.stableHeight=a.height),this.state.set(a)})}get isExpanded(){return this.state.get("isExpanded")}get width(){return this.state.get("width")}expand(){this.postEvent("web_app_expand"),this.state.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}function Ft(r){return!["macos","web","weba"].includes(r)}function zt(r,t,e){if(r||!Ft(t))return new M({height:window.innerHeight,isExpanded:!0,postEvent:e,stableHeight:window.innerHeight,width:window.innerWidth});const s=$("viewport");return s?new M({...s,postEvent:e}):null}function Jt(r){return r.listen(),r.on("change",()=>R("viewport",{height:r.height,isExpanded:r.isExpanded,stableHeight:r.stableHeight,width:r.width})),r}function Ke(r,t,e){const s=Jt(zt(r,t,e)||new M({width:0,height:0,isExpanded:!1,postEvent:e,stableHeight:0}));return Ft(t)&&s.sync({postEvent:e,timeout:100}).catch(n=>{console.error("Unable to actualize viewport state",n)}),s}async function Ye(r,t,e){return Jt(zt(r,t,e)||await pt({postEvent:e,timeout:100}).then(({height:s,isStateStable:n,...i})=>new M({...i,height:s,stableHeight:n?s:0})))}function k(r,t){document.documentElement.style.setProperty(r,t)}function Xe(r,t){const e=()=>{k("--tg-background-color",r.backgroundColor)},s=()=>{const{backgroundColor:n,secondaryBackgroundColor:i}=t;r.headerColor==="bg_color"?n&&k("--tg-header-color",n):r.headerColor==="secondary_bg_color"?i&&k("--tg-header-color",i):k("--tg-header-color",r.headerColor)};t.on("change",s),r.on("change:backgroundColor",e),r.on("change:headerColor",s),e(),s()}function tr(r){const t=()=>{const e=r.getState();Object.entries(e).forEach(([s,n])=>{if(n){const i=s.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);k(`--tg-theme-${i}`,n)}})};r.on("change",t),t()}function wt(r){const t=()=>k("--tg-viewport-height",`${r.height}px`),e=()=>k("--tg-viewport-width",`${r.width}px`),s=()=>k("--tg-viewport-height",`${r.stableHeight}px`);r.on("change:height",t),r.on("change:width",e),r.on("change:stableHeight",s),t(),e(),s()}function er(r){return typeof r=="object"?r:r?{themeParams:!0,viewport:!0,miniApp:!0}:{}}function bt(r,t,e,s){const n=er(r);n.miniApp&&Xe(t,e),n.themeParams&&tr(e),n.viewport&&(s instanceof Promise?s.then(wt):wt(s))}function rr(r){const{hostname:t,pathname:e}=new URL(r,window.location.href);if(t!=="t.me")throw new Error(`Incorrect hostname: ${t}`);const s=e.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(s===null)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');return s[2]}class Qt{constructor(t,e=f){o(this,"ee",new _);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new b({isOpened:!1},this.ee),this.supports=y(t,{open:"web_app_open_invoice"})}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}async open(t,e){if(this.isOpened)throw new Error("Invoice is already opened");const s=e?rr(t):t;this.isOpened=!0;try{return(await w("web_app_open_invoice",{slug:s},"invoice_closed",{postEvent:this.postEvent,capture(i){return s===i.slug}})).status}finally{this.isOpened=!1}}}function sr(r){const t=r.message.trim(),e=(r.title||"").trim(),s=r.buttons||[];let n;if(e.length>64)throw new Error(`Title has incorrect size: ${e.length}`);if(t.length===0||t.length>256)throw new Error(`Message has incorrect size: ${t.length}`);if(s.length>3)throw new Error(`Buttons have incorrect size: ${s.length}`);return s.length===0?n=[{type:"close",id:""}]:n=s.map(i=>{const{id:a=""}=i;if(a.length>64)throw new Error(`Button ID has incorrect size: ${a}`);if(i.type===void 0||i.type==="default"||i.type==="destructive"){const c=i.text.trim();if(c.length===0||c.length>64){const u=i.type||"default";throw new Error(`Button text with type "${u}" has incorrect size: ${i.text.length}`)}return{...i,text:c,id:a}}return{...i,id:a}}),{title:e,message:t,buttons:n}}class Zt{constructor(t,e=f){o(this,"ee",new _);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new b({isOpened:!1},this.ee),this.supports=y(t,{open:"web_app_open_popup"})}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}open(t){if(this.isOpened)throw new Error("Popup is already opened.");return this.isOpened=!0,w("web_app_open_popup",sr(t),"popup_closed",{postEvent:this.postEvent}).then(({button_id:e=null})=>e).finally(()=>{this.isOpened=!1})}}class Kt{constructor(t,e=f){o(this,"ee",new _);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new b({isOpened:!1},this.ee),this.supports=y(t,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"})}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}async open(t){if(this.isOpened)throw new Error("QR scanner is already opened.");this.isOpened=!0;try{const e=await w("web_app_open_scan_qr_popup",{text:t},["qr_text_received","scan_qr_popup_closed"],{postEvent:this.postEvent});return typeof e=="object"&&typeof e.data=="string"?e.data:null}finally{this.isOpened=!1}}}class Yt{constructor(t,e,s=f){o(this,"supports");o(this,"supportsParam");this.version=t,this.createRequestId=e,this.postEvent=s,this.supports=y(t,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),this.supportsParam=$t(t,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(t,e){const s=new URL(t,window.location.href).toString();if(!S("web_app_open_link",this.version)){window.open(s,"_blank");return}this.postEvent("web_app_open_link",{url:s,...typeof e=="boolean"?{try_instant_view:e}:{}})}openTelegramLink(t){const{hostname:e,pathname:s,search:n}=new URL(t,window.location.href);if(e!=="t.me")throw new Error(`URL has not allowed hostname: ${e}. Only "t.me" is allowed`);if(!S("web_app_open_tg_link",this.version)){window.location.href=t;return}this.postEvent("web_app_open_tg_link",{path_full:s+n})}readTextFromClipboard(){return w("web_app_read_text_from_clipboard",{req_id:this.createRequestId()},"clipboard_text_received",{postEvent:this.postEvent}).then(({data:t=null})=>t)}}function nr(r={}){const{async:t=!1,cssVars:e=!1,acceptCustomStyles:s=!1}=r;try{const{launchParams:{initData:n,initDataRaw:i,version:a,platform:c,themeParams:u,botInline:d=!1},isPageReload:p}=ct(),E=Je(),l=It(a);ht()&&(s&&Ue(),l("iframe_ready",{reload_supported:!0}),m("reload_iframe",()=>window.location.reload()));const C={backButton:Ge(p,a,l),closingBehavior:je(p,l),cloudStorage:new Ot(a,E,l),createRequestId:E,hapticFeedback:new Mt(a,l),invoice:new Qt(a,l),mainButton:Fe(p,u.buttonColor||"#000000",u.buttonTextColor||"#ffffff",l),miniApp:ze(p,u.backgroundColor||"#ffffff",a,d,l),popup:new Zt(a,l),postEvent:l,qrScanner:new Kt(a,l),settingsButton:Qe(p,a,l),themeParams:Ze(u),utils:new Yt(a,E,l),...n?{initData:new St(n),initDataRaw:i}:{}},V=t?Ye(p,c,l):Ke(p,c,l);return V instanceof Promise?V.then(I=>(bt(e,C.miniApp,C.themeParams,I),{...C,viewport:I})):(bt(e,C.miniApp,C.themeParams,V),{...C,viewport:V})}catch(n){if(t)return Promise.reject(n);throw n}}function N(r,t){return r.startsWith(t)?r:`${t}${r}`}function ir(r){const t=r.match(/#(.+)/);return t?t[1]:null}async function O(r){return r===0?!0:Promise.race([new Promise(t=>{window.addEventListener("popstate",function e(){window.removeEventListener("popstate",e),t(!0)}),window.history.go(r)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function or(){if(window.history.length<=1||(window.history.pushState(null,""),await O(1-window.history.length)))return;let t=await O(-1);for(;t;)t=await O(-1)}class Xt{constructor(t,e,{debug:s=!1,loggerPrefix:n="Navigator"}){o(this,"logger");o(this,"entries");if(this.entriesCursor=e,t.length===0)throw new Error("Entries list should not be empty.");if(e>=t.length)throw new Error("Cursor should be less than entries count.");this.entries=t.map(({pathname:i="",search:a,hash:c})=>{if(!i.startsWith("/")&&i.length>0)throw new Error('Pathname should start with "/"');return{pathname:N(i,"/"),search:a?N(a,"?"):"",hash:c?N(c,"#"):""}}),this.logger=new Lt(`[${n}]`,s)}formatEntry(t){let e;if(typeof t=="string")e=t;else{const{pathname:a="",search:c,hash:u}=t;e=a+(c?N(c,"?"):"")+(u?N(u,"#"):"")}const{pathname:s,search:n,hash:i}=new URL(e,`https://localhost${this.path}`);return{pathname:s,search:n,hash:i}}get entry(){return this.entries[this.entriesCursor]}back(){return this.go(-1)}get cursor(){return this.entriesCursor}get canGoBack(){return this.entriesCursor>0}get canGoForward(){return this.entriesCursor!==this.entries.length-1}forward(){return this.go(1)}go(t){this.logger.log(`called go(${t})`);const e=Math.min(this.entries.length-1,Math.max(this.entriesCursor+t,0));if(this.entriesCursor===e)return this.performGo({updated:!1,delta:t});const s=this.entry;this.entriesCursor=e;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performGo({updated:!0,delta:t,before:s,after:n})}getEntries(){return this.entries.map(t=>({...t}))}get hash(){return this.entry.hash}push(t){this.entriesCursor!==this.entries.length-1&&this.entries.splice(this.entriesCursor+1);const e=this.formatEntry(t),s=this.entry;this.entriesCursor+=1,this.entries[this.entriesCursor]=e;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performPush({before:s,after:n})}get path(){return`${this.pathname}${this.search}${this.hash}`}get pathname(){return this.entry.pathname}replace(t){const e=this.formatEntry(t);if(this.search===e.search&&this.pathname===e.pathname&&this.hash===e.hash)return this.performReplace({updated:!1,entry:e});const s=this.entry;this.entries[this.entriesCursor]=e;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performReplace({updated:!0,before:s,after:n})}get search(){return this.entry.search}}const mt=0,Z=1,K=2;class lt extends Xt{constructor(e,s,n={}){super(e,s,{...n,loggerPrefix:"HashNavigator"});o(this,"ee",new _);o(this,"attached",!1);o(this,"onPopState",async({state:e})=>{if(this.logger.log('"popstate" event received. State:',e),e===null)return this.push(window.location.hash.slice(1));if(e===mt){this.logger.log("Void reached. Moving history forward"),window.history.forward();return}if(e===Z)return this.back();if(e===K)return this.forward()});o(this,"back",()=>super.back());o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee))}static fromLocation(e){const{search:s,pathname:n,hash:i}=new URL(window.location.hash.slice(1),window.location.href);return new lt([{search:s,pathname:n,hash:i}],0,e)}async performGo(e){e.updated&&(this.attached&&await this.syncHistory(),this.emitChanged(e.before,e.after))}async performPush({before:e,after:s}){this.attached&&await this.syncHistory(),this.emitChanged(e,s)}async performReplace(e){e.updated&&(this.attached&&window.history.replaceState(null,"",`#${this.path}`),this.emitChanged(e.before,e.after))}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const e=`#${this.path}`;await or(),f("web_app_setup_back_button",{is_visible:this.canGoBack}),this.canGoBack&&this.canGoForward?(this.logger.log("Setting up history: [<-, *, ->]"),window.history.replaceState(Z,""),window.history.pushState(null,"",e),window.history.pushState(K,""),await O(-1)):this.canGoBack?(this.logger.log("Setting up history: [<-, *]"),window.history.replaceState(Z,""),window.history.pushState(null,"",e)):this.canGoForward?(this.logger.log("Setting up history: [*, ->]"),window.history.replaceState(null,e),window.history.pushState(K,""),await O(-1)):(this.logger.log("Setting up history: [~, *]"),window.history.replaceState(mt,""),window.history.pushState(null,"",e)),window.addEventListener("popstate",this.onPopState)}emitChanged(e,s){this.ee.emit("change",{navigator:this,from:e,to:s})}async attach(){if(!this.attached)return this.logger.log("Attaching",this),this.attached=!0,m("back_button_pressed",this.back),this.syncHistory()}detach(){this.attached&&(this.logger.log("Detaching",this),this.attached=!1,window.removeEventListener("popstate",this.onPopState),x("back_button_pressed",this.back))}}exports.BackButton=Dt;exports.ClosingBehavior=Nt;exports.CloudStorage=Ot;exports.HapticFeedback=Mt;exports.HashNavigator=lt;exports.InitData=St;exports.Invoice=Qt;exports.MainButton=Ut;exports.MethodUnsupportedError=z;exports.MiniApp=Gt;exports.Navigator=Xt;exports.ParameterUnsupportedError=J;exports.Popup=Zt;exports.QRScanner=Kt;exports.SettingsButton=jt;exports.ThemeParams=Vt;exports.Utils=Yt;exports.Viewport=M;exports.chatParser=kt;exports.classNames=Ht;exports.compareVersions=Rt;exports.createPostEvent=It;exports.getHash=ir;exports.init=nr;exports.initDataParser=st;exports.isColorDark=rt;exports.isIframe=ht;exports.isRGB=tt;exports.isRGBShort=Ct;exports.isRecord=q;exports.isTMA=be;exports.launchParamsParser=ot;exports.mergeClassNames=We;exports.off=x;exports.on=m;exports.once=He;exports.parseInitData=ae;exports.parseLaunchParams=at;exports.parseThemeParams=it;exports.postEvent=f;exports.request=w;exports.requestThemeParams=ue;exports.requestViewport=pt;exports.retrieveLaunchData=ct;exports.serializeLaunchParams=At;exports.serializeThemeParams=xt;exports.setDebug=Ee;exports.setTargetOrigin=Ce;exports.subscribe=Ne;exports.supports=S;exports.themeParamsParser=nt;exports.toRGB=et;exports.unsubscribe=Bt;exports.userParser=Y;
2
2
  //# sourceMappingURL=index.cjs.map