@tma.js/sdk 2.1.0 → 2.3.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.
@@ -1,6 +1,7 @@
1
1
  import { RGB } from '../../colors/types.js';
2
+ import { EventListener } from '../../events/event-emitter/types.js';
3
+ import { RemoveEventListenerFn } from '../../events/types.js';
2
4
  import { EventEmitter } from '../../events/event-emitter/EventEmitter.js';
3
- import { EventListener, SubscribeListener } from '../../events/event-emitter/types.js';
4
5
  import { RequestId } from '../../request-id/types.js';
5
6
 
6
7
  export type InvoiceStatus = 'paid' | 'failed' | 'pending' | 'cancelled' | string;
@@ -286,11 +287,16 @@ export type MiniAppsEventPayload<E extends MiniAppsEventName> = MiniAppsEvents[E
286
287
  * Returns event listener for the specified Mini Apps event.
287
288
  */
288
289
  export type MiniAppsEventListener<E extends MiniAppsEventName> = EventListener<MiniAppsEvents[E]>;
290
+ export interface MiniAppsEventEmitter extends Pick<EventEmitter<MiniAppsEvents>, 'on' | 'off' | 'count'> {
291
+ subscribe(listener: MiniAppsSubscribeListener): RemoveEventListenerFn;
292
+ unsubscribe(listener: MiniAppsSubscribeListener): void;
293
+ }
289
294
  /**
290
295
  * Mini Apps event listener used in `subscribe` and `unsubscribe` functions.
291
296
  */
292
- export type MiniAppsSubscribeListener = SubscribeListener<MiniAppsEvents>;
293
- /**
294
- * Mini Apps event emitter.
295
- */
296
- export type MiniAppsEventEmitter = EventEmitter<MiniAppsEvents>;
297
+ export type MiniAppsSubscribeListener = (payload: {
298
+ [E in MiniAppsEventName]: {
299
+ name: E;
300
+ payload: MiniAppsEventPayload<E>;
301
+ };
302
+ }[MiniAppsEventName]) => void;
@@ -11,37 +11,14 @@ type Emitter = EventEmitter<MainButtonEvents>;
11
11
  export declare class MainButton extends WithStateUtils<MainButtonState> {
12
12
  private readonly postEvent;
13
13
  constructor({ postEvent, ...rest }: MainButtonProps);
14
- /**
15
- * Sends current local state to the Telegram application.
16
- */
17
- private commit;
18
- private set isEnabled(value);
19
- /**
20
- * True if the MainButton is enabled.
21
- */
22
- get isEnabled(): boolean;
23
- private set isLoaderVisible(value);
24
- /**
25
- * True if the MainButton loader is visible.
26
- */
27
- get isLoaderVisible(): boolean;
28
- private set isVisible(value);
29
- /**
30
- * True if the MainButton is visible.
31
- */
32
- get isVisible(): boolean;
33
14
  /**
34
15
  * The MainButton background color.
35
16
  */
36
- get backgroundColor(): RGB;
17
+ get bgColor(): RGB;
37
18
  /**
38
- * The MainButton text.
39
- */
40
- get text(): string;
41
- /**
42
- * The MainButton text color.
19
+ * Sends current local state to the Telegram application.
43
20
  */
44
- get textColor(): RGB;
21
+ private commit;
45
22
  /**
46
23
  * Disables the MainButton.
47
24
  * @see Does not work on Android: https://github.com/Telegram-Mini-Apps/issues/issues/1
@@ -59,6 +36,21 @@ export declare class MainButton extends WithStateUtils<MainButtonState> {
59
36
  * Hides the MainButton loading indicator.
60
37
  */
61
38
  hideLoader(): this;
39
+ private set isEnabled(value);
40
+ /**
41
+ * True if the MainButton is enabled.
42
+ */
43
+ get isEnabled(): boolean;
44
+ private set isLoaderVisible(value);
45
+ /**
46
+ * True if the MainButton loader is visible.
47
+ */
48
+ get isLoaderVisible(): boolean;
49
+ private set isVisible(value);
50
+ /**
51
+ * True if the MainButton is visible.
52
+ */
53
+ get isVisible(): boolean;
62
54
  /**
63
55
  * Adds a new event listener.
64
56
  * @param event - event to listen.
@@ -94,13 +86,21 @@ export declare class MainButton extends WithStateUtils<MainButtonState> {
94
86
  setTextColor(textColor: RGB): this;
95
87
  /**
96
88
  * Updates current Main Button color.
97
- * @param backgroundColor - color to set.
89
+ * @param bgColor - color to set.
98
90
  */
99
- setBackgroundColor(backgroundColor: RGB): this;
91
+ setBgColor(bgColor: RGB): this;
100
92
  /**
101
93
  * Allows setting multiple Main Button parameters.
102
94
  * @param params - Main Button parameters.
103
95
  */
104
96
  setParams(params: Partial<MainButtonParams>): this;
97
+ /**
98
+ * The MainButton text.
99
+ */
100
+ get text(): string;
101
+ /**
102
+ * The MainButton text color.
103
+ */
104
+ get textColor(): RGB;
105
105
  }
106
106
  export {};
@@ -3,7 +3,7 @@ import { StateEvents } from '../../classes/State/types.js';
3
3
  import { RGB } from '../../colors/types.js';
4
4
 
5
5
  export interface MainButtonParams {
6
- backgroundColor: RGB;
6
+ bgColor: RGB;
7
7
  isEnabled: boolean;
8
8
  isLoaderVisible: boolean;
9
9
  isVisible: boolean;
@@ -0,0 +1,7 @@
1
+ import { LaunchParams } from '../launch-params/types.js';
2
+
3
+ /**
4
+ * Mocks a Telegram application environment.
5
+ * @param launchParamsRaw - launch parameters presented as a string or query parameters.
6
+ */
7
+ export declare function mockTelegramEnv(launchParamsRaw: LaunchParams | string): void;
@@ -95,6 +95,7 @@ export { initWeb } from './env/initWeb.js';
95
95
  export { isIframe } from './env/isIframe.js';
96
96
  export { isSSR } from './env/isSSR.js';
97
97
  export { isTMA } from './env/isTMA.js';
98
+ export { mockTelegramEnv } from './env/mockTelegramEnv.js';
98
99
  /**
99
100
  * Errors.
100
101
  */
@@ -4,7 +4,7 @@ import { CleanupFn } from '../types/index.js';
4
4
  * Returns a tuple, containing function to add cleanup, call cleanup, and flag showing whether
5
5
  * cleanup was called. Cleanup will not be performed in case, it was done before.
6
6
  */
7
- export declare function createCleanup(): [
7
+ export declare function createCleanup(...fns: CleanupFn[]): [
8
8
  add: (fn: CleanupFn) => void,
9
9
  call: () => void,
10
10
  cleanedUp: boolean
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var me=Object.defineProperty;var we=(e,t,s)=>t in e?me(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var c=(e,t,s)=>(we(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function wt(e,t){let s;const n=()=>{s!==void 0&&t&&t(s),s=void 0};return[()=>s===void 0?s=e(n):s,n]}function Q(e){const t=$(),{count:s}=t;t.unsubscribe(e),s&&!t.count&&ke()}function yt(e){return $().subscribe(e),()=>Q(e)}class ye{constructor(t,s={}){this.scope=t,this.options=s}print(t,...s){const n=new Date,r=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n),{textColor:i,bgColor:a}=this.options,o="font-weight: bold;padding: 0 5px;border-radius:5px";console[t](`%c${r}%c / %c${this.scope}`,`${o};background-color: lightblue;color:black`,"",`${o};${i?`color:${i};`:""}${a?`background-color:${a}`:""}`,...s)}error(...t){this.print("error",...t)}log(...t){this.print("log",...t)}}const Y=new ye("SDK",{bgColor:"forestgreen",textColor:"white"});let z=!1;const ft=({event:e,args:[t]})=>{Y.log("Event received:",t===void 0?{name:e}:{name:e,data:t})};function Ee(e){z!==e&&(z=e,e?yt(ft):Q(ft))}function ve(...e){z&&Y.log(...e)}class N{constructor(){c(this,"listeners",new Map);c(this,"listenersCount",0);c(this,"subscribeListeners",[])}clear(){this.listeners.clear(),this.subscribeListeners=[]}get count(){return this.listenersCount+this.subscribeListeners.length}emit(t,...s){this.subscribeListeners.forEach(r=>r({event:t,args:s})),(this.listeners.get(t)||[]).forEach(([r,i])=>{r(...s),i&&this.off(t,r)})}on(t,s,n){let r=this.listeners.get(t);return r||this.listeners.set(t,r=[]),r.push([s,n]),this.listenersCount+=1,()=>this.off(t,s)}off(t,s){const n=this.listeners.get(t)||[];for(let r=0;r<n.length;r+=1)if(s===n[r][0]){n.splice(r,1),this.listenersCount-=1;return}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let s=0;s<this.subscribeListeners.length;s+=1)if(this.subscribeListeners[s]===t){this.subscribeListeners.splice(s,1);return}}}function J(e,t,s){return window.addEventListener(e,t,s),()=>window.removeEventListener(e,t,s)}class q extends Error{constructor(t,s,n){super(s,{cause:n}),this.type=t,Object.setPrototypeOf(this,q.prototype)}}function f(e,t,s){return new q(e,t,s)}const Et="ERR_METHOD_UNSUPPORTED",vt="ERR_METHOD_PARAMETER_UNSUPPORTED",Pt="ERR_UNKNOWN_ENV",St="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",Rt="ERR_TIMED_OUT",Tt="ERR_UNEXPECTED_TYPE",K="ERR_PARSE",Ct="ERR_NAVIGATION_LIST_EMPTY",At="ERR_NAVIGATION_CURSOR_INVALID",Pe="ERR_NAVIGATION_ITEM_INVALID",Se="ERR_SSR_INIT",It="ERR_INVALID_PATH_BASE";function S(){return f(Tt,"Value has unexpected type")}class O{constructor(t,s,n){this.parser=t,this.isOptional=s,this.type=n}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(s){throw f(K,`Unable to parse value${this.type?` as ${this.type}`:""}`,s)}}optional(){return this.isOptional=!0,this}}function R(e,t){return()=>new O(e,!1,t)}const m=R(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;throw S()},"boolean");function xt(e,t){const s={};for(const n in e){const r=e[n];if(!r)continue;let i,a;if(typeof r=="function"||"parse"in r)i=n,a=typeof r=="function"?r:r.parse.bind(r);else{const{type:o}=r;i=r.from||n,a=typeof o=="function"?o:o.parse.bind(o)}try{const o=a(t(i));o!==void 0&&(s[n]=o)}catch(o){throw f(K,`Unable to parse field "${n}"`,o)}}return s}function X(e){let t=e;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw S();return t}function l(e,t){return new O(s=>{const n=X(s);return xt(e,r=>n[r])},!1,t)}const y=R(e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}throw S()},"number");function L(e){return/^#[\da-f]{6}$/i.test(e)}function Nt(e){return/^#[\da-f]{3}$/i.test(e)}function Z(e){const t=e.replace(/\s/g,"").toLowerCase();if(L(t))return t;if(Nt(t)){let n="#";for(let r=0;r<3;r+=1)n+=t[1+r].repeat(2);return n}const s=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(!s)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return s.slice(1).reduce((n,r)=>{const i=parseInt(r,10).toString(16);return n+(i.length===1?"0":"")+i},"#")}const h=R(e=>{if(typeof e=="string"||typeof e=="number")return e.toString();throw S()},"string"),tt=R(e=>Z(h().parse(e)),"rgb");function Re(e){return l({eventType:h(),eventData:t=>t}).parse(e)}function Te(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function Ce(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function Ae(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((s,n,r)=>{if(n===r.length-1){t[s]=Ce;return}s in t||(t[s]={}),t=t[s]})})}const Ie=l({button_id:e=>e==null?void 0:h().parse(e)}),xe={clipboard_text_received:l({req_id:h(),data:e=>e===null?e:h().optional().parse(e)}),custom_method_invoked:l({req_id:h(),result:e=>e,error:h().optional()}),invoice_closed:l({slug:h(),status:h()}),phone_requested:l({status:h()}),popup_closed:{parse:e=>Ie.parse(e??{})},qr_text_received:l({data:h().optional()}),theme_changed:l({theme_params:e=>{const t=tt().optional();return Object.entries(X(e)).reduce((s,[n,r])=>(s[n]=t.parse(r),s),{})}}),viewport_changed:l({height:y(),width:e=>e==null?window.innerWidth:y().parse(e),is_state_stable:m(),is_expanded:m()}),write_access_requested:l({status:h()})};function Ne(){const e=new N;Ae();let t=[Te,J("resize",()=>{e.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),J("message",s=>{if(s.source!==window.parent)return;let n;try{n=Re(s.data)}catch{return}const{eventType:r,eventData:i}=n,a=xe[r];try{const o=a?a.parse(i):i;e.emit(...o?[r,o]:[r])}catch(o){Y.error(`An error occurred processing the "${r}" event from the Telegram application. Please, file an issue here: https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,n,o)}}),()=>e.clear()];return[e,()=>{t.forEach(s=>s()),t=[]}]}const[qe,ke]=wt(e=>{const[t,s]=Ne(),n=t.off.bind(t);return t.off=(r,i)=>{const{count:a}=t;n(r,i),a&&!t.count&&e()},[t,s]},([,e])=>e());function $(){return qe()[0]}function k(e,t){$().off(e,t)}function g(e,t,s){return $().on(e,t,s)}function D(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function qt(e,t){const s=e.split("."),n=t.split("."),r=Math.max(s.length,n.length);for(let i=0;i<r;i+=1){const a=parseInt(s[i]||"0",10),o=parseInt(n[i]||"0",10);if(a!==o)return a>o?1:-1}return 0}function b(e,t){return qt(e,t)<=0}function E(e,t,s){if(typeof s=="string"){if(e==="web_app_open_link"&&t==="try_instant_view")return b("6.4",s);if(e==="web_app_set_header_color"&&t==="color")return b("6.9",s)}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 b("6.1",t);case"web_app_open_popup":return b("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 b("6.4",t);case"web_app_switch_inline_query":return b("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return b("6.9",t);case"web_app_setup_settings_button":return b("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 b("7.2",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 De(e){return"external"in e&&D(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function kt(e){return"TelegramWebviewProxy"in e&&D(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function Dt(){try{return window.self!==window.top}catch{return!0}}let Vt="https://web.telegram.org";function Ve(e){Vt=e}function Mt(){return Vt}function P(e,t,s){let n={},r;t===void 0&&s===void 0?n={}:t!==void 0&&s!==void 0?(n=s,r=t):t!==void 0&&("targetOrigin"in t?n=t:r=t);const{targetOrigin:i=Mt()}=n;if(ve("Posting event:",r?{event:e,data:r}:{event:e}),Dt()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:r}),i);return}if(De(window)){window.external.notify(JSON.stringify({eventType:e,eventData:r}));return}if(kt(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(r));return}throw f(Pt,"Unable to determine current environment and possible way to send event. You are probably trying to use Mini Apps method outside of Telegram application environment.")}function Bt(e){return(t,s)=>{if(!E(t,e))throw f(Et,`Method "${t}" is unsupported in Mini Apps version ${e}`);if(D(s)){let n;if(t==="web_app_open_link"&&"try_instant_view"in s?n="try_instant_view":t==="web_app_set_header_color"&&"color"in s&&(n="color"),n&&!E(t,n,e))throw f(vt,`Parameter "${n}" of "${t}" method is unsupported in Mini Apps version ${e}`)}return P(t,s)}}function et(e){return({req_id:t})=>t===e}function Ot(e){return f(Rt,`Timeout reached: ${e}ms`)}function st(e,t){return Promise.race([typeof e=="function"?e():e,new Promise((s,n)=>{setTimeout(()=>{n(Ot(t))},t)})])}async function d(e){let t;const s=new Promise(u=>{t=u}),{method:n,event:r,capture:i,postEvent:a=P,timeout:o}=e,p=(Array.isArray(r)?r:[r]).map(u=>g(u,M=>(!i||i(M))&&t(M)));try{return a(n,e.params),await(o?st(s,o):s)}finally{p.forEach(u=>u())}}async function v(e,t,s,n={}){const{result:r,error:i}=await d({...n,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:e,params:t,req_id:s},capture:et(s)});if(i)throw f(St,i);return r}function B(...e){return e.map(t=>{if(typeof t=="string")return t;if(D(t))return B(Object.entries(t).map(s=>s[1]&&s[0]));if(Array.isArray(t))return B(...t)}).filter(Boolean).join(" ")}function Me(...e){return e.reduce((t,s)=>(D(s)&&Object.entries(s).forEach(([n,r])=>{const i=B(t[n],r);i.length&&(t[n]=i)}),t),{})}function nt(e){const t=Z(e);return Math.sqrt([.299,.587,.114].reduce((s,n,r)=>{const i=parseInt(t.slice(1+r*2,1+(r+1)*2),16);return s+i*i*n},0))<120}class Be{constructor(t){c(this,"ee",new N);c(this,"on",this.ee.on.bind(this.ee));c(this,"off",this.ee.off.bind(this.ee));this.state=t}clone(){return{...this.state}}set(t,s){Object.entries(typeof t=="string"?{[t]:s}:t).reduce((r,[i,a])=>this.state[i]===a||a===void 0?r:(this.state[i]=a,this.ee.emit(`change:${i}`,a),!0),!1)&&this.ee.emit("change",this.state)}get(t){return this.state[t]}}class rt{constructor(t){c(this,"state");c(this,"get");c(this,"set");c(this,"clone");this.state=new Be(t),this.set=this.state.set.bind(this.state),this.get=this.state.get.bind(this.state),this.clone=this.state.clone.bind(this.state)}}function Lt(e,t){return s=>E(t[s],e)}class it extends rt{constructor(s,n,r){super(s);c(this,"supports");this.supports=Lt(n,r)}}class $t extends it{constructor(s,n,r){super({isVisible:s},n,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"});c(this,"on",(s,n)=>s==="click"?g("back_button_pressed",n):this.state.on(s,n));c(this,"off",(s,n)=>s==="click"?k("back_button_pressed",n):this.state.off(s,n));this.postEvent=r}set isVisible(s){this.set("isVisible",s),this.postEvent("web_app_setup_back_button",{is_visible:s})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const ot=R(e=>e instanceof Date?e:new Date(y().parse(e)*1e3),"Date");function U(e,t){return new O(s=>{if(typeof s!="string"&&!(s instanceof URLSearchParams))throw S();const n=typeof s=="string"?new URLSearchParams(s):s;return xt(e,r=>{const i=n.get(r);return i===null?void 0:i})},!1,t)}const Oe=l({id:y(),type:h(),title:h(),photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"Chat").optional(),gt=l({addedToAttachmentMenu:{type:m().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:m().optional(),from:"allows_write_to_pm"},firstName:{type:h(),from:"first_name"},id:y(),isBot:{type:m().optional(),from:"is_bot"},isPremium:{type:m().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").optional();function Ut(){return U({authDate:{type:ot(),from:"auth_date"},canSendAfter:{type:y().optional(),from:"can_send_after"},chat:Oe,chatInstance:{type:h().optional(),from:"chat_instance"},chatType:{type:h().optional(),from:"chat_type"},hash:h(),queryId:{type:h().optional(),from:"query_id"},receiver:gt,startParam:{type:h().optional(),from:"start_param"},user:gt},"InitData")}function Le(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}function $e(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}const Ht=R(e=>{const t=tt().optional();return Object.entries(X(e)).reduce((s,[n,r])=>(s[Le(n)]=t.parse(r),s),{})},"ThemeParams");function at(e){return U({botInline:{type:m().optional(),from:"tgWebAppBotInline"},initData:{type:Ut().optional(),from:"tgWebAppData"},initDataRaw:{type:h().optional(),from:"tgWebAppData"},platform:{type:h(),from:"tgWebAppPlatform"},showSettings:{type:m().optional(),from:"tgWebAppShowSettings"},startParam:{type:h().optional(),from:"tgWebAppStartParam"},themeParams:{type:Ht(),from:"tgWebAppThemeParams"},version:{type:h(),from:"tgWebAppVersion"}}).parse(e)}function Wt(e){return at(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function Ue(){return Wt(window.location.href)}function Gt(){return performance.getEntriesByType("navigation")[0]}function He(){const e=Gt();if(!e)throw new Error("Unable to get first navigation entry.");return Wt(e.name)}function jt(e){return`tma.js/${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function Ft(e,t){sessionStorage.setItem(jt(e),JSON.stringify(t))}function zt(e){const t=sessionStorage.getItem(jt(e));try{return t?JSON.parse(t):void 0}catch{}}function We(){return at(zt("launchParams")||"")}function Jt(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,s])=>[$e(t),s])))}function Qt(e){const{initDataRaw:t,themeParams:s,platform:n,version:r,showSettings:i,startParam:a,botInline:o}=e,p=new URLSearchParams;return p.set("tgWebAppPlatform",n),p.set("tgWebAppThemeParams",Jt(s)),p.set("tgWebAppVersion",r),t&&p.set("tgWebAppData",t),a&&p.set("tgWebAppStartParam",a),typeof i=="boolean"&&p.set("tgWebAppShowSettings",i?"1":"0"),typeof o=="boolean"&&p.set("tgWebAppBotInline",o?"1":"0"),p.toString()}function Ge(e){Ft("launchParams",Qt(e))}function Yt(){for(const e of[Ue,He,We])try{const t=e();return Ge(t),t}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}function ct(){const e=Gt();return!!(e&&e.type==="reload")}function je(){let e=0;return()=>(e+=1).toString()}function Fe(){let e=!1;const t=[];return[s=>!e&&t.push(s),()=>{e||(e=!0,t.forEach(s=>s()))},e]}const[ze]=wt(je);function _(e,t){return()=>{const s=Yt(),n={...s,postEvent:Bt(s.version),createRequestId:ze()};if(typeof e=="function")return e(n);const[r,i,a]=Fe(),o=t({...n,state:ct()?zt(e):void 0,addCleanup:r}),p=u=>(a||r(u.on("change",M=>{Ft(e,M)})),u);return[o instanceof Promise?o.then(p):p(o),i]}}const Je=_("backButton",({postEvent:e,version:t,state:s={isVisible:!1}})=>new $t(s.isVisible,t,e));class V extends it{constructor(){super(...arguments);c(this,"on",this.state.on.bind(this.state));c(this,"off",this.state.off.bind(this.state))}}function Kt(e){const t=e.available?e:{available:!1,device_id:"",token_saved:!1,access_requested:!1,access_granted:!1,type:""};return{available:!0,type:t.type,deviceId:t.device_id,tokenSaved:t.token_saved,accessRequested:t.access_requested,accessGranted:t.access_granted}}class Xt extends V{constructor({postEvent:s,version:n,...r}){super(r,n,{auth:"web_app_biometry_request_auth",openSettings:"web_app_biometry_open_settings",requestAccess:"web_app_biometry_request_access",updateToken:"web_app_biometry_update_token"});c(this,"postEvent");c(this,"authPromise");c(this,"accessPromise");this.postEvent=s}get available(){return this.get("available")}get accessGranted(){return this.get("accessGranted")}get accessRequested(){return this.get("accessRequested")}async authenticate({reason:s,...n}){return this.authPromise||(this.authPromise=d({...n,method:"web_app_biometry_request_auth",event:"biometry_auth_requested",postEvent:this.postEvent,params:{reason:(s||"").trim()}}).then(({token:r})=>r).finally(()=>this.authPromise=void 0)),this.authPromise}get deviceId(){return this.get("deviceId")}openSettings(){this.postEvent("web_app_biometry_open_settings")}requestAccess({reason:s,...n}={}){return this.accessPromise||(this.accessPromise=d({...n,postEvent:this.postEvent,method:"web_app_biometry_request_access",event:"biometry_info_received",params:{reason:s||""}}).then(r=>{const i=Kt(r);return this.set(i),i.accessGranted}).finally(()=>this.accessPromise=void 0)),this.accessPromise}get biometryType(){return this.get("biometryType")}get tokenSaved(){return this.get("tokenSaved")}async updateToken({token:s,...n}={}){return["removed","updated"].includes((await d({...n,postEvent:this.postEvent,method:"web_app_biometry_update_token",event:"biometry_token_updated",params:{token:s||""}})).status)}}async function Zt(e){return Kt(await d({...e||{},method:"web_app_biometry_get_info",event:"biometry_info_received"}))}const Qe=_("biometryManager",async({postEvent:e,version:t,state:s})=>new Xt({...s||await Zt({timeout:1e3}),version:t,postEvent:e}));class ht extends rt{constructor(){super(...arguments);c(this,"on",this.state.on.bind(this.state));c(this,"off",this.state.off.bind(this.state))}}class te extends ht{constructor(t,s){super({isConfirmationNeeded:t}),this.postEvent=s}set isConfirmationNeeded(t){this.set("isConfirmationNeeded",t),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:t})}get isConfirmationNeeded(){return this.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}const Ye=_("closingBehavior",({postEvent:e,state:t={isConfirmationNeeded:!1}})=>new te(t.isConfirmationNeeded,e));class pt{constructor(t,s){c(this,"supports");this.supports=Lt(t,s)}}function Ke(e){if(Array.isArray(e))return e;if(typeof e=="string")try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}throw S()}class Xe extends O{constructor(s,n,r){super(Ke,n,r);c(this,"itemParser");this.itemParser=typeof s=="function"?s:s.parse.bind(s)}parse(s){const n=super.parse(s);return n===void 0?n:n.map(this.itemParser)}of(s){return this.itemParser=typeof s=="function"?s:s.parse.bind(s),this}}function ee(e){return new Xe(t=>t,!1,e)}function bt(e,t){return Object.fromEntries(e.map(s=>[s,t]))}class se extends pt{constructor(t,s,n){super(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"}),this.createRequestId=s,this.postEvent=n}async delete(t,s={}){const n=Array.isArray(t)?t:[t];n.length&&await v("deleteStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent})}async getKeys(t={}){return ee().of(h()).parse(await v("getStorageKeys",{},this.createRequestId(),{...t,postEvent:this.postEvent}))}async get(t,s={}){const n=Array.isArray(t)?t:[t];if(!n.length)return bt(n,"");const r=await v("getStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent}),i=l(bt(n,h()),"CloudStorageData").parse(r);return Array.isArray(t)?i:i[t]}async set(t,s,n={}){await v("saveStorageValue",{key:t,value:s},this.createRequestId(),{...n,postEvent:this.postEvent})}}const Ze=_(({createRequestId:e,postEvent:t,version:s})=>new se(s,e,t));class ne extends pt{constructor(t,s){super(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"}),this.postEvent=s}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"})}}const ts=_(({version:e,postEvent:t})=>new ne(e,t));class re{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?new Date(this.authDate.getTime()+t*1e3):void 0}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}}const es=_(({initData:e})=>e?new re(e):void 0);function ss(e){return Ut().parse(e)}class ie extends V{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_invoice"}),this.postEvent=n}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t,s){if(this.isOpened)throw new Error("Invoice is already opened");let n;if(!s)n=t;else{const{hostname:r,pathname:i}=new URL(t,window.location.href);if(r!=="t.me")throw new Error(`Incorrect hostname: ${r}`);const a=i.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!a)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');[,,n]=a}this.isOpened=!0;try{return(await d({method:"web_app_open_invoice",event:"invoice_closed",params:{slug:n},postEvent:this.postEvent,capture(i){return n===i.slug}})).status}finally{this.isOpened=!1}}}const ns=_(({version:e,postEvent:t})=>new ie(!1,e,t));class oe extends rt{constructor({postEvent:s,...n}){super(n);c(this,"postEvent");c(this,"on",(s,n)=>s==="click"?g("main_button_pressed",n):this.state.on(s,n));c(this,"off",(s,n)=>s==="click"?k("main_button_pressed",n):this.state.off(s,n));this.postEvent=s}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(s){this.setParams({isEnabled:s})}get isEnabled(){return this.get("isEnabled")}set isLoaderVisible(s){this.setParams({isLoaderVisible:s})}get isLoaderVisible(){return this.get("isLoaderVisible")}set isVisible(s){this.setParams({isVisible:s})}get isVisible(){return this.get("isVisible")}get backgroundColor(){return this.get("backgroundColor")}get text(){return this.get("text")}get textColor(){return this.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(s){return this.setParams({text:s})}setTextColor(s){return this.setParams({textColor:s})}setBackgroundColor(s){return this.setParams({backgroundColor:s})}setParams(s){return this.set(s),this.commit(),this}}const rs=_("mainButton",({postEvent:e,themeParams:t,state:s={isVisible:!1,isEnabled:!1,text:"",isLoaderVisible:!1,textColor:t.buttonTextColor||"#ffffff",backgroundColor:t.buttonColor||"#000000"}})=>new oe({...s,postEvent:e}));function is(){return U({contact:l({userId:{type:y(),from:"user_id"},phoneNumber:{type:h(),from:"phone_number"},firstName:{type:h(),from:"first_name"},lastName:{type:h().optional(),from:"last_name"}}),authDate:{type:ot(),from:"auth_date"},hash:h()},"RequestedContact")}function ae(e,t){return s=>{const[n,r]=t[s];return E(n,r,e)}}function os(e){return new Promise(t=>{setTimeout(t,e)})}class ce extends V{constructor({postEvent:s,createRequestId:n,version:r,botInline:i,...a}){super(a,r,{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"});c(this,"botInline");c(this,"postEvent");c(this,"createRequestId");c(this,"requestPhoneAccessPromise");c(this,"requestWriteAccessPromise");c(this,"supportsParam");this.createRequestId=n,this.postEvent=s,this.botInline=i;const o=this.supports.bind(this);this.supports=p=>o(p)?p!=="switchInlineQuery"||i:!1,this.supportsParam=ae(r,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact({timeout:s=1e4}={}){return is().parse(await v("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:s}))}get bgColor(){return this.get("bgColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return nt(this.bgColor)}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:s=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const r=Date.now()+s;let i=50;return st(async()=>{for(;Date.now()<r;){try{return await this.getRequestedContact()}catch{}await os(i),i+=50}throw Ot(s)},s)}async requestPhoneAccess(s={}){return this.requestPhoneAccessPromise||(this.requestPhoneAccessPromise=d({...s,method:"web_app_request_phone",event:"phone_requested",postEvent:this.postEvent}).then(({status:n})=>n).finally(()=>this.requestPhoneAccessPromise=void 0)),this.requestPhoneAccessPromise}async requestWriteAccess(s={}){return this.requestWriteAccessPromise||(this.requestWriteAccessPromise=d({...s,method:"web_app_request_write_access",event:"write_access_requested",postEvent:this.postEvent}).then(({status:n})=>n).finally(()=>this.requestWriteAccessPromise=void 0)),this.requestWriteAccessPromise}sendData(s){const{size:n}=new Blob([s]);if(!n||n>4096)throw new Error(`Passed data has incorrect size: ${n}`);this.postEvent("web_app_data_send",{data:s})}setHeaderColor(s){this.postEvent("web_app_set_header_color",L(s)?{color:s}:{color_key:s}),this.set("headerColor",s)}setBgColor(s){this.postEvent("web_app_set_background_color",{color:s}),this.set("bgColor",s)}switchInlineQuery(s,n=[]){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:s,chat_types:n})}}const as=_("miniApp",({themeParams:e,botInline:t=!1,state:s={bgColor:e.bgColor||"#ffffff",headerColor:e.headerBgColor||"#000000"},...n})=>new ce({...n,...s,botInline:t}));function cs(e){const t=e.message.trim(),s=(e.title||"").trim(),n=e.buttons||[];let r;if(s.length>64)throw new Error(`Title has incorrect size: ${s.length}`);if(!t.length||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?r=n.map(i=>{const{id:a=""}=i;if(a.length>64)throw new Error(`Button ID has incorrect size: ${a}`);if(!i.type||i.type==="default"||i.type==="destructive"){const o=i.text.trim();if(!o.length||o.length>64){const p=i.type||"default";throw new Error(`Button text with type "${p}" has incorrect size: ${i.text.length}`)}return{...i,text:o,id:a}}return{...i,id:a}}):r=[{type:"close",id:""}],{title:s,message:t,buttons:r}}class he extends V{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_popup"}),this.postEvent=n}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("Popup is already opened.");this.isOpened=!0;try{const{button_id:s=null}=await d({event:"popup_closed",method:"web_app_open_popup",postEvent:this.postEvent,params:cs(t)});return s}finally{this.isOpened=!1}}}const hs=_(({postEvent:e,version:t})=>new he(!1,t,e));class pe extends V{constructor(t,s,n){super({isOpened:t},s,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"}),this.postEvent=n}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("QR scanner is already opened.");this.isOpened=!0;try{return(await d({method:"web_app_open_scan_qr_popup",event:["qr_text_received","scan_qr_popup_closed"],postEvent:this.postEvent,params:{text:t}})||{}).data||null}finally{this.isOpened=!1}}}const ps=_(({version:e,postEvent:t})=>new pe(!1,e,t));class ue extends it{constructor(s,n,r){super({isVisible:s},n,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"});c(this,"on",(s,n)=>s==="click"?g("settings_button_pressed",n):this.state.on(s,n));c(this,"off",(s,n)=>s==="click"?k("settings_button_pressed",n):this.state.off(s,n));this.postEvent=r}set isVisible(s){this.set("isVisible",s),this.postEvent("web_app_setup_settings_button",{is_visible:s})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const us=_("settingsButton",({version:e,postEvent:t,state:s={isVisible:!1}})=>new ue(s.isVisible,e,t));function ut(e){return Ht().parse(e)}class le extends ht{get accentTextColor(){return this.get("accentTextColor")}get bgColor(){return this.get("bgColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}getState(){return this.clone()}get headerBgColor(){return this.get("headerBgColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.bgColor||nt(this.bgColor)}get linkColor(){return this.get("linkColor")}get secondaryBgColor(){return this.get("secondaryBgColor")}get sectionBgColor(){return this.get("sectionBgColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}listen(){return g("theme_changed",t=>{this.set(ut(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}const ls=_("themeParams",({themeParams:e,state:t=e,addCleanup:s})=>{const n=new le(t);return s(n.listen()),n});function ds(e={}){return d({...e,method:"web_app_request_theme",event:"theme_changed"}).then(ut)}class de extends pt{constructor(s,n,r){super(s,{readTextFromClipboard:"web_app_read_text_from_clipboard"});c(this,"supportsParam");this.version=s,this.createRequestId=n,this.postEvent=r,this.supportsParam=ae(s,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(s,n){const r=new URL(s,window.location.href).toString();if(!E("web_app_open_link",this.version)){window.open(r,"_blank");return}this.postEvent("web_app_open_link",{url:r,...typeof n=="boolean"?{try_instant_view:n}:{}})}openTelegramLink(s){const{hostname:n,pathname:r,search:i}=new URL(s,window.location.href);if(n!=="t.me")throw new Error(`URL has not allowed hostname: ${n}. Only "t.me" is allowed`);if(!E("web_app_open_tg_link",this.version)){window.location.href=s;return}this.postEvent("web_app_open_tg_link",{path_full:r+i})}async readTextFromClipboard(){const s=this.createRequestId(),{data:n=null}=await d({method:"web_app_read_text_from_clipboard",event:"clipboard_text_received",postEvent:this.postEvent,params:{req_id:s},capture:et(s)});return n}}const _s=_(({version:e,postEvent:t,createRequestId:s})=>new de(e,s,t));async function lt(e={}){const{is_expanded:t,is_state_stable:s,...n}=await d({...e,method:"web_app_request_viewport",event:"viewport_changed"});return{...n,isExpanded:t,isStateStable:s}}function T(e){return e<0?0:e}class _e extends ht{constructor({postEvent:s,stableHeight:n,height:r,width:i,isExpanded:a}){super({height:T(r),isExpanded:a,stableHeight:T(n),width:T(i)});c(this,"postEvent");this.postEvent=s}async sync(s){const{isStateStable:n,...r}=await lt(s);this.set({...r,stableHeight:n?r.height:this.get("stableHeight")})}get height(){return this.get("height")}get stableHeight(){return this.get("stableHeight")}listen(){return g("viewport_changed",s=>{const{height:n,width:r,is_expanded:i,is_state_stable:a}=s,o=T(n);this.set({height:o,isExpanded:i,width:T(r),...a?{stableHeight:o}:{}})})}get isExpanded(){return this.get("isExpanded")}get width(){return this.get("width")}expand(){this.postEvent("web_app_expand"),this.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}const fs=_("viewport",async({state:e,platform:t,postEvent:s,addCleanup:n})=>{let r=!1,i=0,a=0,o=0;if(e)r=e.isExpanded,i=e.height,a=e.width,o=e.stableHeight;else if(["macos","tdesktop","unigram","webk","weba","web"].includes(t))r=!0,i=window.innerHeight,a=window.innerWidth,o=window.innerHeight;else{const u=await lt({timeout:1e3,postEvent:s});r=u.isExpanded,i=u.height,a=u.width,o=u.isStateStable?i:0}const p=new _e({postEvent:s,height:i,width:a,stableHeight:o,isExpanded:r});return n(p.listen()),p});function w(e,t){document.documentElement.style.setProperty(e,t)}function gs(e,t,s){s||(s=o=>`--tg-${o}-color`);const n=s("header"),r=s("bg"),i=()=>{const{headerColor:o}=e;if(L(o))w(n,o);else{const{bgColor:p,secondaryBgColor:u}=t;o==="bg_color"&&p?w(n,p):o==="secondary_bg_color"&&u&&w(n,u)}w(r,e.bgColor)},a=[t.on("change",i),e.on("change",i)];return i(),()=>a.forEach(o=>o())}function bs(e,t){t||(t=n=>`--tg-theme-${n.replace(/[A-Z]/g,r=>`-${r.toLowerCase()}`)}`);const s=()=>{Object.entries(e.getState()).forEach(([n,r])=>{r&&w(t(n),r)})};return s(),e.on("change",s)}function ms(e,t){t||(t=u=>`--tg-viewport-${u}`);const[s,n,r]=["height","width","stable-height"].map(u=>t(u)),i=()=>w(s,`${e.height}px`),a=()=>w(n,`${e.width}px`),o=()=>w(r,`${e.stableHeight}px`),p=[e.on("change:height",i),e.on("change:width",a),e.on("change:stableHeight",o)];return i(),a(),o(),()=>p.forEach(u=>u())}function ws(e=!0){const t=[g("reload_iframe",()=>{P("iframe_will_reload"),window.location.reload()})],s=()=>t.forEach(n=>n());if(e){const n=document.createElement("style");n.id="telegram-custom-styles",document.head.appendChild(n),t.push(g("set_custom_style",r=>{n.innerHTML=r}),()=>document.head.removeChild(n))}return P("iframe_ready",{reload_supported:!0}),s}function ys(){return typeof window>"u"}async function Es(){if(kt(window))return!0;try{return await d({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function fe(e){return e instanceof q}function vs(e,t){return fe(e)&&e.type===t}function H(e,t){let s,n,r;return typeof e=="string"?s=e:(s=e.pathname===void 0?t:e.pathname,n=e.params,r=e.id),Object.freeze({id:r||(Math.random()*2**14|0).toString(16),pathname:s,params:n})}class ge{constructor(t,s,n=P){c(this,"history");c(this,"ee",new N);c(this,"attached",!1);c(this,"back",()=>this.go(-1));c(this,"on",this.ee.on.bind(this.ee));c(this,"off",this.ee.off.bind(this.ee));if(this._index=s,this.postEvent=n,t.length===0)throw f(Ct,"History should not be empty.");if(s<0||s>=t.length)throw f(At,"Index should not be zero and higher or equal than history size.");this.history=t.map(r=>H(r,""))}attach(){this.attached||(this.attached=!0,this.sync(),g("back_button_pressed",this.back))}get current(){return this.history[this.index]}detach(){this.attached=!1,k("back_button_pressed",this.back)}forward(){this.go(1)}go(t,s){const n=this.index+t,r=Math.min(Math.max(0,n),this.history.length-1);(n===r||s)&&this.replaceAndMove(r,this.history[r])}goTo(t,s){this.go(t-this.index,s)}get hasPrev(){return this.index>0}get hasNext(){return this.index!==this.history.length-1}get index(){return this._index}push(t){this.hasNext&&this.history.splice(this.index+1),this.replaceAndMove(this.index+1,H(t,this.current.pathname))}replace(t){this.replaceAndMove(this.index,H(t,this.current.pathname))}replaceAndMove(t,s){const n=t-this.index;if(!n&&this.current===s)return;const r=this.current;if(this.index!==t){const i=this._index;this._index=t,this.attached&&i>0!=t>0&&this.sync()}this.history[t]=s,this.ee.emit("change",{navigator:this,from:r,to:this.current,delta:n})}sync(){this.postEvent("web_app_setup_back_button",{is_visible:!!this.index})}}function W({params:e,...t}){return{...e||{hash:"",search:""},...t}}function A(e,t){return e.startsWith(t)?e:`${t}${e}`}function I(e){return new URL(typeof e=="string"?e:`${e.pathname||""}${A(e.search||"","?")}${A(e.hash||"","#")}`,"http://a")}function x(e){const t=typeof e=="string"?e.startsWith("/"):!!(e.pathname&&e.pathname.startsWith("/")),s=I(e);return`${t?s.pathname:s.pathname.slice(1)}${s.search}${s.hash}`}function G(e,t,s){let n,r;typeof e=="string"?n=e:(n=x(e),s=e.state,r=e.id);const{pathname:i,search:a,hash:o}=new URL(n,`http://a${A(t,"/")}`);return{id:r,pathname:i,params:{hash:o,search:a,state:s}}}async function C(e){return e===0?!0:Promise.race([new Promise(t=>{const s=J("popstate",()=>{s(),t(!0)});window.history.go(e)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function Ps(){if(window.history.length<=1||(window.history.pushState(null,""),await C(1-window.history.length)))return;let t=await C(-1);for(;t;)t=await C(-1)}function dt(e){return I(e).pathname}const mt=0,j=1,F=2;class _t{constructor(t,s,{postEvent:n,hashMode:r="classic",base:i}={}){c(this,"navigator");c(this,"ee",new N);c(this,"hashMode");c(this,"base");c(this,"attached",!1);c(this,"onPopState",({state:t})=>{if(t===null)return this.push(this.parsePath(window.location.href));t===mt?window.history.forward():t===j&&this.back(),t===F&&this.forward()});c(this,"onNavigatorChange",async({to:t,from:s,delta:n})=>{this.attached&&await this.syncHistory(),this.ee.emit("change",{delta:n,from:W(s),to:W(t),navigator:this})});c(this,"on",this.ee.on.bind(this.ee));c(this,"off",this.ee.off.bind(this.ee));this.navigator=new ge(t.map(a=>G(a,"/")),s,n),this.navigator.on("change",this.onNavigatorChange),this.hashMode=r,this.base=dt(i||"")}async attach(){this.attached||(this.attached=!0,this.navigator.attach(),window.addEventListener("popstate",this.onPopState),await this.syncHistory())}back(){this.navigator.back()}detach(){this.attached=!1,this.navigator.detach(),window.removeEventListener("popstate",this.onPopState)}forward(){return this.navigator.forward()}get index(){return this.navigator.index}get id(){return this.navigator.current.id}go(t,s){return this.navigator.go(t,s)}goTo(t,s){this.navigator.goTo(t,s)}get hash(){return(this.navigator.current.params||{}).hash||""}get hasPrev(){return this.navigator.hasPrev}get hasNext(){return this.navigator.hasNext}get history(){return this.navigator.history.map(W)}get path(){return x(this)}get pathname(){return this.navigator.current.pathname}parsePath(t){let s=I(t);return this.hashMode&&(s=I(s.hash.slice(1))),{pathname:s.pathname,search:s.search,hash:s.hash}}push(t,s){const n=G(t,this.path),{state:r=s}=n.params;this.navigator.push({...n,params:{...n.params,state:r}})}replace(t,s){const n=G(t,this.path),{state:r=s}=n.params;this.navigator.replace({...n,params:{...n.params,state:r}})}renderPath(t){const s=(this.base.length===1?"":this.base)+A(x(t),"/");return this.hashMode?A(s.slice(1),this.hashMode==="classic"?"#":"#/"):s}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const{state:t}=this,s=this.renderPath(this);await Ps(),this.hasPrev&&this.hasNext?(window.history.replaceState(j,""),window.history.pushState(t,"",s),window.history.pushState(F,""),await C(-1)):this.hasPrev?(window.history.replaceState(j,""),window.history.pushState(t,"",s)):this.hasNext?(window.history.replaceState(t,s),window.history.pushState(F,""),await C(-1)):(window.history.replaceState(mt,""),window.history.pushState(t,"",s)),window.addEventListener("popstate",this.onPopState)}get search(){return(this.navigator.current.params||{}).search||""}get state(){return(this.navigator.current.params||{}).state}}function be(e){e||(e={});const{href:t,hash:s}=window.location;let n=x(e.hashMode===null?t:s.includes("?")?s.slice(1):`?${s.slice(1)}`);const r=e.base?dt(e.base):void 0;if(r){if(!n.startsWith(r))throw f(It,`Path "${n}" expected to be starting with "${r}"`);n=n.slice(r.length)}return new _t([n],0,e)}function Ss(e){const t=e.match(/#(.+)/);return t?t[1]:null}function Rs(e,t){if(ct()){const s=sessionStorage.getItem(e);if(s)try{const{index:n,history:r}=JSON.parse(s);return new _t(r,n,t)}catch(n){console.error("Unable to restore hash navigator state.",n)}}return be(t)}function Ts(e,t){const s=Rs(e,t),n=()=>sessionStorage.setItem(e,JSON.stringify({index:s.index,history:s.history}));return s.on("change",n),n(),s}exports.BackButton=$t;exports.BasicNavigator=ge;exports.BiometryManager=Xt;exports.BrowserNavigator=_t;exports.ClosingBehavior=te;exports.CloudStorage=se;exports.ERR_INVALID_PATH_BASE=It;exports.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=St;exports.ERR_METHOD_PARAMETER_UNSUPPORTED=vt;exports.ERR_METHOD_UNSUPPORTED=Et;exports.ERR_NAVIGATION_HISTORY_EMPTY=Ct;exports.ERR_NAVIGATION_INDEX_INVALID=At;exports.ERR_NAVIGATION_ITEM_INVALID=Pe;exports.ERR_PARSE=K;exports.ERR_SSR_INIT=Se;exports.ERR_TIMED_OUT=Rt;exports.ERR_UNEXPECTED_TYPE=Tt;exports.ERR_UNKNOWN_ENV=Pt;exports.EventEmitter=N;exports.HapticFeedback=ne;exports.InitData=re;exports.Invoice=ie;exports.MainButton=oe;exports.MiniApp=ce;exports.Popup=he;exports.QRScanner=pe;exports.SDKError=q;exports.SettingsButton=ue;exports.ThemeParams=le;exports.Utils=de;exports.Viewport=_e;exports.array=ee;exports.bindMiniAppCSSVars=gs;exports.bindThemeParamsCSSVars=bs;exports.bindViewportCSSVars=ms;exports.boolean=m;exports.captureSameReq=et;exports.classNames=B;exports.compareVersions=qt;exports.createBrowserNavigatorFromLocation=be;exports.createPostEvent=Bt;exports.createSafeURL=I;exports.date=ot;exports.getHash=Ss;exports.getPathname=dt;exports.initBackButton=Je;exports.initBiometryManager=Qe;exports.initClosingBehavior=Ye;exports.initCloudStorage=Ze;exports.initHapticFeedback=ts;exports.initInitData=es;exports.initInvoice=ns;exports.initMainButton=rs;exports.initMiniApp=as;exports.initNavigator=Ts;exports.initPopup=hs;exports.initQRScanner=ps;exports.initSettingsButton=us;exports.initThemeParams=ls;exports.initUtils=_s;exports.initViewport=fs;exports.initWeb=ws;exports.invokeCustomMethod=v;exports.isColorDark=nt;exports.isIframe=Dt;exports.isPageReload=ct;exports.isRGB=L;exports.isRGBShort=Nt;exports.isSDKError=fe;exports.isSDKErrorOfType=vs;exports.isSSR=ys;exports.isTMA=Es;exports.json=l;exports.mergeClassNames=Me;exports.number=y;exports.off=k;exports.on=g;exports.parseInitData=ss;exports.parseLaunchParams=at;exports.parseThemeParams=ut;exports.postEvent=P;exports.request=d;exports.requestBiometryInfo=Zt;exports.requestThemeParams=ds;exports.requestViewport=lt;exports.retrieveLaunchParams=Yt;exports.rgb=tt;exports.searchParams=U;exports.serializeLaunchParams=Qt;exports.serializeThemeParams=Jt;exports.setCSSVar=w;exports.setDebug=Ee;exports.setTargetOrigin=Ve;exports.string=h;exports.subscribe=yt;exports.supports=E;exports.targetOrigin=Mt;exports.toRGB=Z;exports.unsubscribe=Q;exports.urlToPath=x;exports.withTimeout=st;
1
+ "use strict";var Pe=Object.defineProperty;var Se=(e,t,s)=>t in e?Pe(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var c=(e,t,s)=>(Se(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function vt(e,t){let s;const n=()=>{s!==void 0&&t&&t(s),s=void 0};return[()=>s===void 0?s=e(n):s,n]}function K(e){const t=$(),{count:s}=t;t.unsubscribe(e),s&&!t.count&&Me()}function Pt(e){return $().subscribe(e),()=>K(e)}class Re{constructor(t,s={}){this.scope=t,this.options=s}print(t,...s){const n=new Date,r=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n),{textColor:i,bgColor:a}=this.options,o="font-weight: bold;padding: 0 5px;border-radius:5px";console[t](`%c${r}%c / %c${this.scope}`,`${o};background-color: lightblue;color:black`,"",`${o};${i?`color:${i};`:""}${a?`background-color:${a}`:""}`,...s)}error(...t){this.print("error",...t)}log(...t){this.print("log",...t)}}const X=new Re("SDK",{bgColor:"forestgreen",textColor:"white"});let J=!1;const wt=({name:e,payload:t})=>{X.log("Event received:",t?{name:e,payload:t}:{name:e})};function Te(e){J!==e&&(J=e,e?Pt(wt):K(wt))}function Ce(...e){J&&X.log(...e)}class P{constructor(){c(this,"listeners",new Map);c(this,"listenersCount",0);c(this,"subscribeListeners",[])}clear(){this.listeners.clear(),this.subscribeListeners=[]}get count(){return this.listenersCount+this.subscribeListeners.length}emit(t,...s){this.subscribeListeners.forEach(r=>r({event:t,args:s})),(this.listeners.get(t)||[]).forEach(([r,i])=>{r(...s),i&&this.off(t,r)})}on(t,s,n){let r=this.listeners.get(t);return r||this.listeners.set(t,r=[]),r.push([s,n]),this.listenersCount+=1,()=>this.off(t,s)}off(t,s){const n=this.listeners.get(t)||[];for(let r=0;r<n.length;r+=1)if(s===n[r][0]){n.splice(r,1),this.listenersCount-=1;return}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let s=0;s<this.subscribeListeners.length;s+=1)if(this.subscribeListeners[s]===t){this.subscribeListeners.splice(s,1);return}}}function Q(e,t,s){return window.addEventListener(e,t,s),()=>window.removeEventListener(e,t,s)}function St(...e){let t=!1;const s=[...e];return[n=>!t&&s.push(n),()=>{t||(t=!0,s.forEach(n=>n()))},t]}class q extends Error{constructor(t,s,n){super(s,{cause:n}),this.type=t,Object.setPrototypeOf(this,q.prototype)}}function f(e,t,s){return new q(e,t,s)}const Rt="ERR_METHOD_UNSUPPORTED",Tt="ERR_METHOD_PARAMETER_UNSUPPORTED",Ct="ERR_UNKNOWN_ENV",xt="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",At="ERR_TIMED_OUT",It="ERR_UNEXPECTED_TYPE",Z="ERR_PARSE",Nt="ERR_NAVIGATION_LIST_EMPTY",qt="ERR_NAVIGATION_CURSOR_INVALID",xe="ERR_NAVIGATION_ITEM_INVALID",Ae="ERR_SSR_INIT",Dt="ERR_INVALID_PATH_BASE";function R(){return f(It,"Value has unexpected type")}class O{constructor(t,s,n){this.parser=t,this.isOptional=s,this.type=n}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(s){throw f(Z,`Unable to parse value${this.type?` as ${this.type}`:""}`,s)}}optional(){return this.isOptional=!0,this}}function T(e,t){return()=>new O(e,!1,t)}const w=T(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;throw R()},"boolean");function kt(e,t){const s={};for(const n in e){const r=e[n];if(!r)continue;let i,a;if(typeof r=="function"||"parse"in r)i=n,a=typeof r=="function"?r:r.parse.bind(r);else{const{type:o}=r;i=r.from||n,a=typeof o=="function"?o:o.parse.bind(o)}try{const o=a(t(i));o!==void 0&&(s[n]=o)}catch(o){throw f(Z,`Unable to parse field "${n}"`,o)}}return s}function tt(e){let t=e;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw R();return t}function l(e,t){return new O(s=>{const n=tt(s);return kt(e,r=>n[r])},!1,t)}const y=T(e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}throw R()},"number");function L(e){return/^#[\da-f]{6}$/i.test(e)}function Mt(e){return/^#[\da-f]{3}$/i.test(e)}function et(e){const t=e.replace(/\s/g,"").toLowerCase();if(L(t))return t;if(Mt(t)){let n="#";for(let r=0;r<3;r+=1)n+=t[1+r].repeat(2);return n}const s=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(!s)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return s.slice(1).reduce((n,r)=>{const i=parseInt(r,10).toString(16);return n+(i.length===1?"0":"")+i},"#")}const h=T(e=>{if(typeof e=="string"||typeof e=="number")return e.toString();throw R()},"string"),st=T(e=>et(h().parse(e)),"rgb");function Vt(e){return l({eventType:h(),eventData:t=>t}).parse(e)}function Ie(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function Y(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function Ne(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((s,n,r)=>{if(n===r.length-1){t[s]=Y;return}s in t||(t[s]={}),t=t[s]})})}const qe={clipboard_text_received:l({req_id:h(),data:e=>e===null?e:h().optional().parse(e)}),custom_method_invoked:l({req_id:h(),result:e=>e,error:h().optional()}),invoice_closed:l({slug:h(),status:h()}),phone_requested:l({status:h()}),popup_closed:{parse(e){return l({button_id:t=>t==null?void 0:h().parse(t)}).parse(e??{})}},qr_text_received:l({data:h().optional()}),theme_changed:l({theme_params:e=>{const t=st().optional();return Object.entries(tt(e)).reduce((s,[n,r])=>(s[n]=t.parse(r),s),{})}}),viewport_changed:l({height:y(),width:e=>e==null?window.innerWidth:y().parse(e),is_state_stable:w(),is_expanded:w()}),write_access_requested:l({status:h()})};function De(){const e=new P,t=new P;t.subscribe(n=>{e.emit("event",{name:n.event,payload:n.args[0]})}),Ne();const[,s]=St(Ie,Q("resize",()=>{t.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),Q("message",n=>{if(n.source!==window.parent)return;let r;try{r=Vt(n.data)}catch{return}const{eventType:i,eventData:a}=r,o=qe[i];try{const p=o?o.parse(a):a;t.emit(...p?[i,p]:[i])}catch(p){X.error(`An error occurred processing the "${i}" event from the Telegram application. Please, file an issue here: https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,r,p)}}),()=>e.clear(),()=>t.clear());return[{on:t.on.bind(t),off:t.off.bind(t),subscribe(n){return e.on("event",n)},unsubscribe(n){e.off("event",n)},get count(){return t.count+e.count}},s]}const[ke,Me]=vt(e=>{const[t,s]=De(),n=t.off.bind(t);return t.off=(r,i)=>{const{count:a}=t;n(r,i),a&&!t.count&&e()},[t,s]},([,e])=>e());function $(){return ke()[0]}function D(e,t){$().off(e,t)}function g(e,t,s){return $().on(e,t,s)}function k(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bt(e,t){const s=e.split("."),n=t.split("."),r=Math.max(s.length,n.length);for(let i=0;i<r;i+=1){const a=parseInt(s[i]||"0",10),o=parseInt(n[i]||"0",10);if(a!==o)return a>o?1:-1}return 0}function b(e,t){return Bt(e,t)<=0}function E(e,t,s){if(typeof s=="string"){if(e==="web_app_open_link"&&t==="try_instant_view")return b("6.4",s);if(e==="web_app_set_header_color"&&t==="color")return b("6.9",s)}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 b("6.1",t);case"web_app_open_popup":return b("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 b("6.4",t);case"web_app_switch_inline_query":return b("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return b("6.9",t);case"web_app_setup_settings_button":return b("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 b("7.2",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 Ot(e){return"external"in e&&k(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function Lt(e){return"TelegramWebviewProxy"in e&&k(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function nt(){try{return window.self!==window.top}catch{return!0}}let $t="https://web.telegram.org";function Ve(e){$t=e}function Ut(){return $t}function S(e,t,s){let n={},r;t===void 0&&s===void 0?n={}:t!==void 0&&s!==void 0?(n=s,r=t):t!==void 0&&("targetOrigin"in t?n=t:r=t);const{targetOrigin:i=Ut()}=n;if(Ce("Posting event:",r?{event:e,data:r}:{event:e}),nt()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:r}),i);return}if(Ot(window)){window.external.notify(JSON.stringify({eventType:e,eventData:r}));return}if(Lt(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(r));return}throw f(Ct,"Unable to determine current environment and possible way to send event. You are probably trying to use Mini Apps method outside of Telegram application environment.")}function Wt(e){return(t,s)=>{if(!E(t,e))throw f(Rt,`Method "${t}" is unsupported in Mini Apps version ${e}`);if(k(s)){let n;if(t==="web_app_open_link"&&"try_instant_view"in s?n="try_instant_view":t==="web_app_set_header_color"&&"color"in s&&(n="color"),n&&!E(t,n,e))throw f(Tt,`Parameter "${n}" of "${t}" method is unsupported in Mini Apps version ${e}`)}return S(t,s)}}function rt(e){return({req_id:t})=>t===e}function Ht(e){return f(At,`Timeout reached: ${e}ms`)}function it(e,t){return Promise.race([typeof e=="function"?e():e,new Promise((s,n)=>{setTimeout(()=>{n(Ht(t))},t)})])}async function d(e){let t;const s=new Promise(u=>{t=u}),{method:n,event:r,capture:i,postEvent:a=S,timeout:o}=e,p=(Array.isArray(r)?r:[r]).map(u=>g(u,V=>(!i||i(V))&&t(V)));try{return a(n,e.params),await(o?it(s,o):s)}finally{p.forEach(u=>u())}}async function v(e,t,s,n={}){const{result:r,error:i}=await d({...n,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:e,params:t,req_id:s},capture:rt(s)});if(i)throw f(xt,i);return r}function B(...e){return e.map(t=>{if(typeof t=="string")return t;if(k(t))return B(Object.entries(t).map(s=>s[1]&&s[0]));if(Array.isArray(t))return B(...t)}).filter(Boolean).join(" ")}function Be(...e){return e.reduce((t,s)=>(k(s)&&Object.entries(s).forEach(([n,r])=>{const i=B(t[n],r);i.length&&(t[n]=i)}),t),{})}function ot(e){const t=et(e);return Math.sqrt([.299,.587,.114].reduce((s,n,r)=>{const i=parseInt(t.slice(1+r*2,1+(r+1)*2),16);return s+i*i*n},0))<120}class Oe{constructor(t){c(this,"ee",new P);c(this,"on",this.ee.on.bind(this.ee));c(this,"off",this.ee.off.bind(this.ee));this.state=t}clone(){return{...this.state}}set(t,s){Object.entries(typeof t=="string"?{[t]:s}:t).reduce((r,[i,a])=>this.state[i]===a||a===void 0?r:(this.state[i]=a,this.ee.emit(`change:${i}`,a),!0),!1)&&this.ee.emit("change",this.state)}get(t){return this.state[t]}}class at{constructor(t){c(this,"state");c(this,"get");c(this,"set");c(this,"clone");this.state=new Oe(t),this.set=this.state.set.bind(this.state),this.get=this.state.get.bind(this.state),this.clone=this.state.clone.bind(this.state)}}function Gt(e,t){return s=>E(t[s],e)}class ct extends at{constructor(s,n,r){super(s);c(this,"supports");this.supports=Gt(n,r)}}class jt extends ct{constructor(s,n,r){super({isVisible:s},n,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"});c(this,"on",(s,n)=>s==="click"?g("back_button_pressed",n):this.state.on(s,n));c(this,"off",(s,n)=>s==="click"?D("back_button_pressed",n):this.state.off(s,n));this.postEvent=r}set isVisible(s){this.set("isVisible",s),this.postEvent("web_app_setup_back_button",{is_visible:s})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const ht=T(e=>e instanceof Date?e:new Date(y().parse(e)*1e3),"Date");function U(e,t){return new O(s=>{if(typeof s!="string"&&!(s instanceof URLSearchParams))throw R();const n=typeof s=="string"?new URLSearchParams(s):s;return kt(e,r=>{const i=n.get(r);return i===null?void 0:i})},!1,t)}const Le=l({id:y(),type:h(),title:h(),photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"Chat").optional(),mt=l({addedToAttachmentMenu:{type:w().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:w().optional(),from:"allows_write_to_pm"},firstName:{type:h(),from:"first_name"},id:y(),isBot:{type:w().optional(),from:"is_bot"},isPremium:{type:w().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").optional();function zt(){return U({authDate:{type:ht(),from:"auth_date"},canSendAfter:{type:y().optional(),from:"can_send_after"},chat:Le,chatInstance:{type:h().optional(),from:"chat_instance"},chatType:{type:h().optional(),from:"chat_type"},hash:h(),queryId:{type:h().optional(),from:"query_id"},receiver:mt,startParam:{type:h().optional(),from:"start_param"},user:mt},"InitData")}function $e(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}function Ue(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}const Ft=T(e=>{const t=st().optional();return Object.entries(tt(e)).reduce((s,[n,r])=>(s[$e(n)]=t.parse(r),s),{})},"ThemeParams");function W(e){return U({botInline:{type:w().optional(),from:"tgWebAppBotInline"},initData:{type:zt().optional(),from:"tgWebAppData"},initDataRaw:{type:h().optional(),from:"tgWebAppData"},platform:{type:h(),from:"tgWebAppPlatform"},showSettings:{type:w().optional(),from:"tgWebAppShowSettings"},startParam:{type:h().optional(),from:"tgWebAppStartParam"},themeParams:{type:Ft(),from:"tgWebAppThemeParams"},version:{type:h(),from:"tgWebAppVersion"}}).parse(e)}function Jt(e){return W(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function We(){return Jt(window.location.href)}function Qt(){return performance.getEntriesByType("navigation")[0]}function He(){const e=Qt();if(!e)throw new Error("Unable to get first navigation entry.");return Jt(e.name)}function Yt(e){return`tma.js/${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function Kt(e,t){sessionStorage.setItem(Yt(e),JSON.stringify(t))}function Xt(e){const t=sessionStorage.getItem(Yt(e));try{return t?JSON.parse(t):void 0}catch{}}function Ge(){return W(Xt("launchParams")||"")}function pt(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,s])=>[Ue(t),s])))}function Zt(e){const{initDataRaw:t,themeParams:s,platform:n,version:r,showSettings:i,startParam:a,botInline:o}=e,p=new URLSearchParams;return p.set("tgWebAppPlatform",n),p.set("tgWebAppThemeParams",pt(s)),p.set("tgWebAppVersion",r),t&&p.set("tgWebAppData",t),a&&p.set("tgWebAppStartParam",a),typeof i=="boolean"&&p.set("tgWebAppShowSettings",i?"1":"0"),typeof o=="boolean"&&p.set("tgWebAppBotInline",o?"1":"0"),p.toString()}function te(e){Kt("launchParams",Zt(e))}function ee(){for(const e of[We,He,Ge])try{const t=e();return te(t),t}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}function ut(){const e=Qt();return!!(e&&e.type==="reload")}function je(){let e=0;return()=>(e+=1).toString()}const[ze]=vt(je);function _(e,t){return()=>{const s=ee(),n={...s,postEvent:Wt(s.version),createRequestId:ze()};if(typeof e=="function")return e(n);const[r,i,a]=St(),o=t({...n,state:ut()?Xt(e):void 0,addCleanup:r}),p=u=>(a||r(u.on("change",V=>{Kt(e,V)})),u);return[o instanceof Promise?o.then(p):p(o),i]}}const Fe=_("backButton",({postEvent:e,version:t,state:s={isVisible:!1}})=>new jt(s.isVisible,t,e));class M extends ct{constructor(){super(...arguments);c(this,"on",this.state.on.bind(this.state));c(this,"off",this.state.off.bind(this.state))}}function se(e){const t=e.available?e:{available:!1,device_id:"",token_saved:!1,access_requested:!1,access_granted:!1,type:""};return{available:!0,type:t.type,deviceId:t.device_id,tokenSaved:t.token_saved,accessRequested:t.access_requested,accessGranted:t.access_granted}}class ne extends M{constructor({postEvent:s,version:n,...r}){super(r,n,{auth:"web_app_biometry_request_auth",openSettings:"web_app_biometry_open_settings",requestAccess:"web_app_biometry_request_access",updateToken:"web_app_biometry_update_token"});c(this,"postEvent");c(this,"authPromise");c(this,"accessPromise");this.postEvent=s}get available(){return this.get("available")}get accessGranted(){return this.get("accessGranted")}get accessRequested(){return this.get("accessRequested")}async authenticate({reason:s,...n}){return this.authPromise||(this.authPromise=d({...n,method:"web_app_biometry_request_auth",event:"biometry_auth_requested",postEvent:this.postEvent,params:{reason:(s||"").trim()}}).then(({token:r})=>r).finally(()=>this.authPromise=void 0)),this.authPromise}get deviceId(){return this.get("deviceId")}openSettings(){this.postEvent("web_app_biometry_open_settings")}requestAccess({reason:s,...n}={}){return this.accessPromise||(this.accessPromise=d({...n,postEvent:this.postEvent,method:"web_app_biometry_request_access",event:"biometry_info_received",params:{reason:s||""}}).then(r=>{const i=se(r);return this.set(i),i.accessGranted}).finally(()=>this.accessPromise=void 0)),this.accessPromise}get biometryType(){return this.get("biometryType")}get tokenSaved(){return this.get("tokenSaved")}async updateToken({token:s,...n}={}){return["removed","updated"].includes((await d({...n,postEvent:this.postEvent,method:"web_app_biometry_update_token",event:"biometry_token_updated",params:{token:s||""}})).status)}}async function re(e){return se(await d({...e||{},method:"web_app_biometry_get_info",event:"biometry_info_received"}))}const Je=_("biometryManager",async({postEvent:e,version:t,state:s})=>new ne({...s||E("web_app_biometry_get_info",t)?s||await re({timeout:1e3}):{available:!1,accessGranted:!1,accessRequested:!1,tokenSaved:!1,deviceId:""},version:t,postEvent:e}));class lt extends at{constructor(){super(...arguments);c(this,"on",this.state.on.bind(this.state));c(this,"off",this.state.off.bind(this.state))}}class ie extends lt{constructor(t,s){super({isConfirmationNeeded:t}),this.postEvent=s}set isConfirmationNeeded(t){this.set("isConfirmationNeeded",t),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:t})}get isConfirmationNeeded(){return this.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}const Qe=_("closingBehavior",({postEvent:e,state:t={isConfirmationNeeded:!1}})=>new ie(t.isConfirmationNeeded,e));class dt{constructor(t,s){c(this,"supports");this.supports=Gt(t,s)}}function Ye(e){if(Array.isArray(e))return e;if(typeof e=="string")try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}throw R()}class Ke extends O{constructor(s,n,r){super(Ye,n,r);c(this,"itemParser");this.itemParser=typeof s=="function"?s:s.parse.bind(s)}parse(s){const n=super.parse(s);return n===void 0?n:n.map(this.itemParser)}of(s){return this.itemParser=typeof s=="function"?s:s.parse.bind(s),this}}function oe(e){return new Ke(t=>t,!1,e)}function yt(e,t){return Object.fromEntries(e.map(s=>[s,t]))}class ae extends dt{constructor(t,s,n){super(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"}),this.createRequestId=s,this.postEvent=n}async delete(t,s={}){const n=Array.isArray(t)?t:[t];n.length&&await v("deleteStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent})}async getKeys(t={}){return oe().of(h()).parse(await v("getStorageKeys",{},this.createRequestId(),{...t,postEvent:this.postEvent}))}async get(t,s={}){const n=Array.isArray(t)?t:[t];if(!n.length)return yt(n,"");const r=await v("getStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent}),i=l(yt(n,h()),"CloudStorageData").parse(r);return Array.isArray(t)?i:i[t]}async set(t,s,n={}){await v("saveStorageValue",{key:t,value:s},this.createRequestId(),{...n,postEvent:this.postEvent})}}const Xe=_(({createRequestId:e,postEvent:t,version:s})=>new ae(s,e,t));class ce extends dt{constructor(t,s){super(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"}),this.postEvent=s}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"})}}const Ze=_(({version:e,postEvent:t})=>new ce(e,t));class he{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?new Date(this.authDate.getTime()+t*1e3):void 0}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}}const ts=_(({initData:e})=>e?new he(e):void 0);function es(e){return zt().parse(e)}class pe extends M{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_invoice"}),this.postEvent=n}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t,s){if(this.isOpened)throw new Error("Invoice is already opened");let n;if(!s)n=t;else{const{hostname:r,pathname:i}=new URL(t,window.location.href);if(r!=="t.me")throw new Error(`Incorrect hostname: ${r}`);const a=i.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!a)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');[,,n]=a}this.isOpened=!0;try{return(await d({method:"web_app_open_invoice",event:"invoice_closed",params:{slug:n},postEvent:this.postEvent,capture(i){return n===i.slug}})).status}finally{this.isOpened=!1}}}const ss=_(({version:e,postEvent:t})=>new pe(!1,e,t));class ue extends at{constructor({postEvent:s,...n}){super(n);c(this,"postEvent");c(this,"on",(s,n)=>s==="click"?g("main_button_pressed",n):this.state.on(s,n));c(this,"off",(s,n)=>s==="click"?D("main_button_pressed",n):this.state.off(s,n));this.postEvent=s}get bgColor(){return this.get("bgColor")}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.bgColor,text_color:this.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}set isEnabled(s){this.setParams({isEnabled:s})}get isEnabled(){return this.get("isEnabled")}set isLoaderVisible(s){this.setParams({isLoaderVisible:s})}get isLoaderVisible(){return this.get("isLoaderVisible")}set isVisible(s){this.setParams({isVisible:s})}get isVisible(){return this.get("isVisible")}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(s){return this.setParams({text:s})}setTextColor(s){return this.setParams({textColor:s})}setBgColor(s){return this.setParams({bgColor:s})}setParams(s){return this.set(s),this.commit(),this}get text(){return this.get("text")}get textColor(){return this.get("textColor")}}const ns=_("mainButton",({postEvent:e,themeParams:t,state:s={isVisible:!1,isEnabled:!1,text:"",isLoaderVisible:!1,textColor:t.buttonTextColor||"#ffffff",bgColor:t.buttonColor||"#000000"}})=>new ue({...s,postEvent:e}));function rs(){return U({contact:l({userId:{type:y(),from:"user_id"},phoneNumber:{type:h(),from:"phone_number"},firstName:{type:h(),from:"first_name"},lastName:{type:h().optional(),from:"last_name"}}),authDate:{type:ht(),from:"auth_date"},hash:h()},"RequestedContact")}function le(e,t){return s=>{const[n,r]=t[s];return E(n,r,e)}}function is(e){return new Promise(t=>{setTimeout(t,e)})}class de extends M{constructor({postEvent:s,createRequestId:n,version:r,botInline:i,...a}){super(a,r,{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"});c(this,"botInline");c(this,"postEvent");c(this,"createRequestId");c(this,"requestPhoneAccessPromise");c(this,"requestWriteAccessPromise");c(this,"supportsParam");this.createRequestId=n,this.postEvent=s,this.botInline=i;const o=this.supports.bind(this);this.supports=p=>o(p)?p!=="switchInlineQuery"||i:!1,this.supportsParam=le(r,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact({timeout:s=1e4}={}){return rs().parse(await v("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:s}))}get bgColor(){return this.get("bgColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return ot(this.bgColor)}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:s=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const r=Date.now()+s;let i=50;return it(async()=>{for(;Date.now()<r;){try{return await this.getRequestedContact()}catch{}await is(i),i+=50}throw Ht(s)},s)}async requestPhoneAccess(s={}){return this.requestPhoneAccessPromise||(this.requestPhoneAccessPromise=d({...s,method:"web_app_request_phone",event:"phone_requested",postEvent:this.postEvent}).then(({status:n})=>n).finally(()=>this.requestPhoneAccessPromise=void 0)),this.requestPhoneAccessPromise}async requestWriteAccess(s={}){return this.requestWriteAccessPromise||(this.requestWriteAccessPromise=d({...s,method:"web_app_request_write_access",event:"write_access_requested",postEvent:this.postEvent}).then(({status:n})=>n).finally(()=>this.requestWriteAccessPromise=void 0)),this.requestWriteAccessPromise}sendData(s){const{size:n}=new Blob([s]);if(!n||n>4096)throw new Error(`Passed data has incorrect size: ${n}`);this.postEvent("web_app_data_send",{data:s})}setHeaderColor(s){this.postEvent("web_app_set_header_color",L(s)?{color:s}:{color_key:s}),this.set("headerColor",s)}setBgColor(s){this.postEvent("web_app_set_background_color",{color:s}),this.set("bgColor",s)}switchInlineQuery(s,n=[]){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:s,chat_types:n})}}const os=_("miniApp",({themeParams:e,botInline:t=!1,state:s={bgColor:e.bgColor||"#ffffff",headerColor:e.headerBgColor||"#000000"},...n})=>new de({...n,...s,botInline:t}));function as(e){const t=e.message.trim(),s=(e.title||"").trim(),n=e.buttons||[];let r;if(s.length>64)throw new Error(`Title has incorrect size: ${s.length}`);if(!t.length||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?r=n.map(i=>{const{id:a=""}=i;if(a.length>64)throw new Error(`Button ID has incorrect size: ${a}`);if(!i.type||i.type==="default"||i.type==="destructive"){const o=i.text.trim();if(!o.length||o.length>64){const p=i.type||"default";throw new Error(`Button text with type "${p}" has incorrect size: ${i.text.length}`)}return{...i,text:o,id:a}}return{...i,id:a}}):r=[{type:"close",id:""}],{title:s,message:t,buttons:r}}class _e extends M{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_popup"}),this.postEvent=n}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("Popup is already opened.");this.isOpened=!0;try{const{button_id:s=null}=await d({event:"popup_closed",method:"web_app_open_popup",postEvent:this.postEvent,params:as(t)});return s}finally{this.isOpened=!1}}}const cs=_(({postEvent:e,version:t})=>new _e(!1,t,e));class fe extends M{constructor(t,s,n){super({isOpened:t},s,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"}),this.postEvent=n}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("QR scanner is already opened.");this.isOpened=!0;try{return(await d({method:"web_app_open_scan_qr_popup",event:["qr_text_received","scan_qr_popup_closed"],postEvent:this.postEvent,params:{text:t}})||{}).data||null}finally{this.isOpened=!1}}}const hs=_(({version:e,postEvent:t})=>new fe(!1,e,t));class ge extends ct{constructor(s,n,r){super({isVisible:s},n,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"});c(this,"on",(s,n)=>s==="click"?g("settings_button_pressed",n):this.state.on(s,n));c(this,"off",(s,n)=>s==="click"?D("settings_button_pressed",n):this.state.off(s,n));this.postEvent=r}set isVisible(s){this.set("isVisible",s),this.postEvent("web_app_setup_settings_button",{is_visible:s})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const ps=_("settingsButton",({version:e,postEvent:t,state:s={isVisible:!1}})=>new ge(s.isVisible,e,t));function _t(e){return Ft().parse(e)}class be extends lt{get accentTextColor(){return this.get("accentTextColor")}get bgColor(){return this.get("bgColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}getState(){return this.clone()}get headerBgColor(){return this.get("headerBgColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.bgColor||ot(this.bgColor)}get linkColor(){return this.get("linkColor")}get secondaryBgColor(){return this.get("secondaryBgColor")}get sectionBgColor(){return this.get("sectionBgColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}listen(){return g("theme_changed",t=>{this.set(_t(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}const us=_("themeParams",({themeParams:e,state:t=e,addCleanup:s})=>{const n=new be(t);return s(n.listen()),n});function ls(e={}){return d({...e,method:"web_app_request_theme",event:"theme_changed"}).then(_t)}class we extends dt{constructor(s,n,r){super(s,{readTextFromClipboard:"web_app_read_text_from_clipboard"});c(this,"supportsParam");this.version=s,this.createRequestId=n,this.postEvent=r,this.supportsParam=le(s,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(s,n){const r=new URL(s,window.location.href).toString();if(!E("web_app_open_link",this.version)){window.open(r,"_blank");return}this.postEvent("web_app_open_link",{url:r,...typeof n=="boolean"?{try_instant_view:n}:{}})}openTelegramLink(s){const{hostname:n,pathname:r,search:i}=new URL(s,window.location.href);if(n!=="t.me")throw new Error(`URL has not allowed hostname: ${n}. Only "t.me" is allowed`);if(!E("web_app_open_tg_link",this.version)){window.location.href=s;return}this.postEvent("web_app_open_tg_link",{path_full:r+i})}async readTextFromClipboard(){const s=this.createRequestId(),{data:n=null}=await d({method:"web_app_read_text_from_clipboard",event:"clipboard_text_received",postEvent:this.postEvent,params:{req_id:s},capture:rt(s)});return n}}const ds=_(({version:e,postEvent:t,createRequestId:s})=>new we(e,s,t));async function ft(e={}){const{is_expanded:t,is_state_stable:s,...n}=await d({...e,method:"web_app_request_viewport",event:"viewport_changed"});return{...n,isExpanded:t,isStateStable:s}}function C(e){return e<0?0:e}class me extends lt{constructor({postEvent:s,stableHeight:n,height:r,width:i,isExpanded:a}){super({height:C(r),isExpanded:a,stableHeight:C(n),width:C(i)});c(this,"postEvent");this.postEvent=s}async sync(s){const{isStateStable:n,...r}=await ft(s);this.set({...r,stableHeight:n?r.height:this.get("stableHeight")})}get height(){return this.get("height")}get stableHeight(){return this.get("stableHeight")}listen(){return g("viewport_changed",s=>{const{height:n,width:r,is_expanded:i,is_state_stable:a}=s,o=C(n);this.set({height:o,isExpanded:i,width:C(r),...a?{stableHeight:o}:{}})})}get isExpanded(){return this.get("isExpanded")}get width(){return this.get("width")}expand(){this.postEvent("web_app_expand"),this.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}const _s=_("viewport",async({state:e,platform:t,postEvent:s,addCleanup:n})=>{let r=!1,i=0,a=0,o=0;if(e)r=e.isExpanded,i=e.height,a=e.width,o=e.stableHeight;else if(["macos","tdesktop","unigram","webk","weba","web"].includes(t))r=!0,i=window.innerHeight,a=window.innerWidth,o=window.innerHeight;else{const u=await ft({timeout:1e3,postEvent:s});r=u.isExpanded,i=u.height,a=u.width,o=u.isStateStable?i:0}const p=new me({postEvent:s,height:i,width:a,stableHeight:o,isExpanded:r});return n(p.listen()),p});function m(e,t){document.documentElement.style.setProperty(e,t)}function fs(e,t,s){s||(s=o=>`--tg-${o}-color`);const n=s("header"),r=s("bg"),i=()=>{const{headerColor:o}=e;if(L(o))m(n,o);else{const{bgColor:p,secondaryBgColor:u}=t;o==="bg_color"&&p?m(n,p):o==="secondary_bg_color"&&u&&m(n,u)}m(r,e.bgColor)},a=[t.on("change",i),e.on("change",i)];return i(),()=>a.forEach(o=>o())}function gs(e,t){t||(t=n=>`--tg-theme-${n.replace(/[A-Z]/g,r=>`-${r.toLowerCase()}`)}`);const s=()=>{Object.entries(e.getState()).forEach(([n,r])=>{r&&m(t(n),r)})};return s(),e.on("change",s)}function bs(e,t){t||(t=u=>`--tg-viewport-${u}`);const[s,n,r]=["height","width","stable-height"].map(u=>t(u)),i=()=>m(s,`${e.height}px`),a=()=>m(n,`${e.width}px`),o=()=>m(r,`${e.stableHeight}px`),p=[e.on("change:height",i),e.on("change:width",a),e.on("change:stableHeight",o)];return i(),a(),o(),()=>p.forEach(u=>u())}function ws(e=!0){const t=[g("reload_iframe",()=>{S("iframe_will_reload"),window.location.reload()})],s=()=>t.forEach(n=>n());if(e){const n=document.createElement("style");n.id="telegram-custom-styles",document.head.appendChild(n),t.push(g("set_custom_style",r=>{n.innerHTML=r}),()=>document.head.removeChild(n))}return S("iframe_ready",{reload_supported:!0}),s}function ms(){return typeof window>"u"}async function ys(){if(Lt(window))return!0;try{return await d({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function Es(e){const t=typeof e=="string"?W(e):e;te(t);function s(r){if(typeof r=="string")try{const{eventType:i}=Vt(r);i==="web_app_request_theme"&&Y("theme_changed",{theme_params:JSON.parse(pt(t.themeParams))}),i==="web_app_request_viewport"&&Y("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}catch{}}if(nt()){const r=window.parent.postMessage.bind(window.parent);window.parent.postMessage=i=>{s(i),r(i)};return}if(Ot(window)){const r=window.external.notify.bind(window.external);window.external.notify=i=>{s(i),r(i)};return}const n=window.TelegramWebviewProxy;window.TelegramWebviewProxy={...n||{},postEvent(...r){s(JSON.stringify({eventType:r[0],eventData:r[1]})),n&&n.postEvent(...r)}}}function ye(e){return e instanceof q}function vs(e,t){return ye(e)&&e.type===t}function H(e,t){let s,n,r;return typeof e=="string"?s=e:(s=e.pathname===void 0?t:e.pathname,n=e.params,r=e.id),Object.freeze({id:r||(Math.random()*2**14|0).toString(16),pathname:s,params:n})}class Ee{constructor(t,s,n=S){c(this,"history");c(this,"ee",new P);c(this,"attached",!1);c(this,"back",()=>this.go(-1));c(this,"on",this.ee.on.bind(this.ee));c(this,"off",this.ee.off.bind(this.ee));if(this._index=s,this.postEvent=n,t.length===0)throw f(Nt,"History should not be empty.");if(s<0||s>=t.length)throw f(qt,"Index should not be zero and higher or equal than history size.");this.history=t.map(r=>H(r,""))}attach(){this.attached||(this.attached=!0,this.sync(),g("back_button_pressed",this.back))}get current(){return this.history[this.index]}detach(){this.attached=!1,D("back_button_pressed",this.back)}forward(){this.go(1)}go(t,s){const n=this.index+t,r=Math.min(Math.max(0,n),this.history.length-1);(n===r||s)&&this.replaceAndMove(r,this.history[r])}goTo(t,s){this.go(t-this.index,s)}get hasPrev(){return this.index>0}get hasNext(){return this.index!==this.history.length-1}get index(){return this._index}push(t){this.hasNext&&this.history.splice(this.index+1),this.replaceAndMove(this.index+1,H(t,this.current.pathname))}replace(t){this.replaceAndMove(this.index,H(t,this.current.pathname))}replaceAndMove(t,s){const n=t-this.index;if(!n&&this.current===s)return;const r=this.current;if(this.index!==t){const i=this._index;this._index=t,this.attached&&i>0!=t>0&&this.sync()}this.history[t]=s,this.ee.emit("change",{navigator:this,from:r,to:this.current,delta:n})}sync(){this.postEvent("web_app_setup_back_button",{is_visible:!!this.index})}}function G({params:e,...t}){return{...e||{hash:"",search:""},...t}}function A(e,t){return e.startsWith(t)?e:`${t}${e}`}function I(e){return new URL(typeof e=="string"?e:`${e.pathname||""}${A(e.search||"","?")}${A(e.hash||"","#")}`,"http://a")}function N(e){const t=typeof e=="string"?e.startsWith("/"):!!(e.pathname&&e.pathname.startsWith("/")),s=I(e);return`${t?s.pathname:s.pathname.slice(1)}${s.search}${s.hash}`}function j(e,t,s){let n,r;typeof e=="string"?n=e:(n=N(e),s=e.state,r=e.id);const{pathname:i,search:a,hash:o}=new URL(n,`http://a${A(t,"/")}`);return{id:r,pathname:i,params:{hash:o,search:a,state:s}}}async function x(e){return e===0?!0:Promise.race([new Promise(t=>{const s=Q("popstate",()=>{s(),t(!0)});window.history.go(e)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function Ps(){if(window.history.length<=1||(window.history.pushState(null,""),await x(1-window.history.length)))return;let t=await x(-1);for(;t;)t=await x(-1)}function gt(e){return I(e).pathname}const Et=0,z=1,F=2;class bt{constructor(t,s,{postEvent:n,hashMode:r="classic",base:i}={}){c(this,"navigator");c(this,"ee",new P);c(this,"hashMode");c(this,"base");c(this,"attached",!1);c(this,"onPopState",({state:t})=>{if(t===null)return this.push(this.parsePath(window.location.href));t===Et?window.history.forward():t===z&&this.back(),t===F&&this.forward()});c(this,"onNavigatorChange",async({to:t,from:s,delta:n})=>{this.attached&&await this.syncHistory(),this.ee.emit("change",{delta:n,from:G(s),to:G(t),navigator:this})});c(this,"on",this.ee.on.bind(this.ee));c(this,"off",this.ee.off.bind(this.ee));this.navigator=new Ee(t.map(a=>j(a,"/")),s,n),this.navigator.on("change",this.onNavigatorChange),this.hashMode=r,this.base=gt(i||"")}async attach(){this.attached||(this.attached=!0,this.navigator.attach(),window.addEventListener("popstate",this.onPopState),await this.syncHistory())}back(){this.navigator.back()}detach(){this.attached=!1,this.navigator.detach(),window.removeEventListener("popstate",this.onPopState)}forward(){return this.navigator.forward()}get index(){return this.navigator.index}get id(){return this.navigator.current.id}go(t,s){return this.navigator.go(t,s)}goTo(t,s){this.navigator.goTo(t,s)}get hash(){return(this.navigator.current.params||{}).hash||""}get hasPrev(){return this.navigator.hasPrev}get hasNext(){return this.navigator.hasNext}get history(){return this.navigator.history.map(G)}get path(){return N(this)}get pathname(){return this.navigator.current.pathname}parsePath(t){let s=I(t);return this.hashMode&&(s=I(s.hash.slice(1))),{pathname:s.pathname,search:s.search,hash:s.hash}}push(t,s){const n=j(t,this.path),{state:r=s}=n.params;this.navigator.push({...n,params:{...n.params,state:r}})}replace(t,s){const n=j(t,this.path),{state:r=s}=n.params;this.navigator.replace({...n,params:{...n.params,state:r}})}renderPath(t){const s=(this.base.length===1?"":this.base)+A(N(t),"/");return this.hashMode?A(s.slice(1),this.hashMode==="classic"?"#":"#/"):s}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const{state:t}=this,s=this.renderPath(this);await Ps(),this.hasPrev&&this.hasNext?(window.history.replaceState(z,""),window.history.pushState(t,"",s),window.history.pushState(F,""),await x(-1)):this.hasPrev?(window.history.replaceState(z,""),window.history.pushState(t,"",s)):this.hasNext?(window.history.replaceState(t,s),window.history.pushState(F,""),await x(-1)):(window.history.replaceState(Et,""),window.history.pushState(t,"",s)),window.addEventListener("popstate",this.onPopState)}get search(){return(this.navigator.current.params||{}).search||""}get state(){return(this.navigator.current.params||{}).state}}function ve(e){e||(e={});const{href:t,hash:s}=window.location;let n=N(e.hashMode===null?t:s.includes("?")?s.slice(1):`?${s.slice(1)}`);const r=e.base?gt(e.base):void 0;if(r){if(!n.startsWith(r))throw f(Dt,`Path "${n}" expected to be starting with "${r}"`);n=n.slice(r.length)}return new bt([n],0,e)}function Ss(e){const t=e.match(/#(.+)/);return t?t[1]:null}function Rs(e,t){if(ut()){const s=sessionStorage.getItem(e);if(s)try{const{index:n,history:r}=JSON.parse(s);return new bt(r,n,t)}catch(n){console.error("Unable to restore hash navigator state.",n)}}return ve(t)}function Ts(e,t){const s=Rs(e,t),n=()=>sessionStorage.setItem(e,JSON.stringify({index:s.index,history:s.history}));return s.on("change",n),n(),s}exports.BackButton=jt;exports.BasicNavigator=Ee;exports.BiometryManager=ne;exports.BrowserNavigator=bt;exports.ClosingBehavior=ie;exports.CloudStorage=ae;exports.ERR_INVALID_PATH_BASE=Dt;exports.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=xt;exports.ERR_METHOD_PARAMETER_UNSUPPORTED=Tt;exports.ERR_METHOD_UNSUPPORTED=Rt;exports.ERR_NAVIGATION_HISTORY_EMPTY=Nt;exports.ERR_NAVIGATION_INDEX_INVALID=qt;exports.ERR_NAVIGATION_ITEM_INVALID=xe;exports.ERR_PARSE=Z;exports.ERR_SSR_INIT=Ae;exports.ERR_TIMED_OUT=At;exports.ERR_UNEXPECTED_TYPE=It;exports.ERR_UNKNOWN_ENV=Ct;exports.EventEmitter=P;exports.HapticFeedback=ce;exports.InitData=he;exports.Invoice=pe;exports.MainButton=ue;exports.MiniApp=de;exports.Popup=_e;exports.QRScanner=fe;exports.SDKError=q;exports.SettingsButton=ge;exports.ThemeParams=be;exports.Utils=we;exports.Viewport=me;exports.array=oe;exports.bindMiniAppCSSVars=fs;exports.bindThemeParamsCSSVars=gs;exports.bindViewportCSSVars=bs;exports.boolean=w;exports.captureSameReq=rt;exports.classNames=B;exports.compareVersions=Bt;exports.createBrowserNavigatorFromLocation=ve;exports.createPostEvent=Wt;exports.createSafeURL=I;exports.date=ht;exports.getHash=Ss;exports.getPathname=gt;exports.initBackButton=Fe;exports.initBiometryManager=Je;exports.initClosingBehavior=Qe;exports.initCloudStorage=Xe;exports.initHapticFeedback=Ze;exports.initInitData=ts;exports.initInvoice=ss;exports.initMainButton=ns;exports.initMiniApp=os;exports.initNavigator=Ts;exports.initPopup=cs;exports.initQRScanner=hs;exports.initSettingsButton=ps;exports.initThemeParams=us;exports.initUtils=ds;exports.initViewport=_s;exports.initWeb=ws;exports.invokeCustomMethod=v;exports.isColorDark=ot;exports.isIframe=nt;exports.isPageReload=ut;exports.isRGB=L;exports.isRGBShort=Mt;exports.isSDKError=ye;exports.isSDKErrorOfType=vs;exports.isSSR=ms;exports.isTMA=ys;exports.json=l;exports.mergeClassNames=Be;exports.mockTelegramEnv=Es;exports.number=y;exports.off=D;exports.on=g;exports.parseInitData=es;exports.parseLaunchParams=W;exports.parseThemeParams=_t;exports.postEvent=S;exports.request=d;exports.requestBiometryInfo=re;exports.requestThemeParams=ls;exports.requestViewport=ft;exports.retrieveLaunchParams=ee;exports.rgb=st;exports.searchParams=U;exports.serializeLaunchParams=Zt;exports.serializeThemeParams=pt;exports.setCSSVar=m;exports.setDebug=Te;exports.setTargetOrigin=Ve;exports.string=h;exports.subscribe=Pt;exports.supports=E;exports.targetOrigin=Ut;exports.toRGB=et;exports.unsubscribe=K;exports.urlToPath=N;exports.withTimeout=it;
2
2
  //# sourceMappingURL=index.cjs.map