@tma.js/sdk 2.0.0 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dts/errors/errors.d.ts +1 -5
- package/dist/dts/index.d.ts +2 -1
- package/dist/dts/misc/createComponentInitFn/types.d.ts +4 -5
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.iife.js +1 -1
- package/dist/index.iife.js.map +1 -1
- package/dist/index.js +411 -419
- package/dist/index.js.map +1 -1
- package/dist/index.low-level.iife.js +1 -1
- package/dist/index.low-level.iife.js.map +1 -1
- package/package.json +1 -1
|
@@ -42,12 +42,8 @@ export declare const ERR_NAVIGATION_ITEM_INVALID = "ERR_NAVIGATION_ITEM_INVALID"
|
|
|
42
42
|
* SSR component initialization failed.
|
|
43
43
|
*/
|
|
44
44
|
export declare const ERR_SSR_INIT = "ERR_SSR_INIT";
|
|
45
|
-
/**
|
|
46
|
-
* Server side called postEvent.
|
|
47
|
-
*/
|
|
48
|
-
export declare const ERR_SSR_POST_EVENT = "ERR_SSR_POST_EVENT";
|
|
49
45
|
/**
|
|
50
46
|
* Path starts from the invalid base.
|
|
51
47
|
*/
|
|
52
48
|
export declare const ERR_INVALID_PATH_BASE = "ERR_INVALID_PATH_BASE";
|
|
53
|
-
export type ErrorType = typeof ERR_METHOD_UNSUPPORTED | typeof ERR_METHOD_PARAMETER_UNSUPPORTED | typeof ERR_UNKNOWN_ENV | typeof ERR_INVOKE_CUSTOM_METHOD_RESPONSE | typeof ERR_TIMED_OUT | typeof ERR_PARSE | typeof ERR_UNEXPECTED_TYPE | typeof ERR_NAVIGATION_HISTORY_EMPTY | typeof ERR_NAVIGATION_INDEX_INVALID | typeof ERR_NAVIGATION_ITEM_INVALID | typeof ERR_SSR_INIT | typeof
|
|
49
|
+
export type ErrorType = typeof ERR_METHOD_UNSUPPORTED | typeof ERR_METHOD_PARAMETER_UNSUPPORTED | typeof ERR_UNKNOWN_ENV | typeof ERR_INVOKE_CUSTOM_METHOD_RESPONSE | typeof ERR_TIMED_OUT | typeof ERR_PARSE | typeof ERR_UNEXPECTED_TYPE | typeof ERR_NAVIGATION_HISTORY_EMPTY | typeof ERR_NAVIGATION_INDEX_INVALID | typeof ERR_NAVIGATION_ITEM_INVALID | typeof ERR_SSR_INIT | typeof ERR_INVALID_PATH_BASE;
|
package/dist/dts/index.d.ts
CHANGED
|
@@ -93,6 +93,7 @@ export { setDebug } from './debug/debug.js';
|
|
|
93
93
|
*/
|
|
94
94
|
export { initWeb } from './env/initWeb.js';
|
|
95
95
|
export { isIframe } from './env/isIframe.js';
|
|
96
|
+
export { isSSR } from './env/isSSR.js';
|
|
96
97
|
export { isTMA } from './env/isTMA.js';
|
|
97
98
|
/**
|
|
98
99
|
* Errors.
|
|
@@ -117,7 +118,7 @@ export * from './launch-params/types.js';
|
|
|
117
118
|
/**
|
|
118
119
|
* Misc.
|
|
119
120
|
*/
|
|
120
|
-
export type {
|
|
121
|
+
export type { FactoryOptions, FactoryStatic, Factory, FactoryDynamic, InitComponentFn, WithOnChange, } from './misc/createComponentInitFn/types.js';
|
|
121
122
|
/**
|
|
122
123
|
* Navigation.
|
|
123
124
|
*/
|
|
@@ -10,20 +10,19 @@ import { If, IsNever } from '../../types/index.js';
|
|
|
10
10
|
export interface WithOnChange<State> {
|
|
11
11
|
on(event: 'change', listener: (state: State) => void): void;
|
|
12
12
|
}
|
|
13
|
-
type
|
|
13
|
+
type WithState<State> = If<IsNever<State>, {}, {
|
|
14
14
|
state?: State;
|
|
15
15
|
}>;
|
|
16
|
-
export type SSROptions<LP extends LaunchParamName, State> = LaunchParamsWithState<LP, State>;
|
|
17
16
|
/**
|
|
18
17
|
* Options passed to a component factory.
|
|
19
18
|
*/
|
|
20
|
-
export type FactoryOptions<LP extends LaunchParamName, State> =
|
|
19
|
+
export type FactoryOptions<LP extends LaunchParamName, State> = PickLaunchParams<LP> & WithState<State> & {
|
|
21
20
|
postEvent: PostEvent;
|
|
22
21
|
createRequestId: CreateRequestIdFn;
|
|
23
22
|
};
|
|
24
23
|
export interface Factory<LP extends LaunchParamName, R, State> {
|
|
25
24
|
/**
|
|
26
|
-
* Creates new component instance.
|
|
25
|
+
* Creates a new component instance.
|
|
27
26
|
* @param options - factory options.
|
|
28
27
|
*/
|
|
29
28
|
(options: FactoryOptions<LP, State>): R;
|
|
@@ -41,7 +40,7 @@ export interface InitComponentFn<LP extends LaunchParamName, Result, State> {
|
|
|
41
40
|
/**
|
|
42
41
|
* Options, applicable only to SSR mode.
|
|
43
42
|
*/
|
|
44
|
-
ssr?:
|
|
43
|
+
ssr?: Partial<PickLaunchParams<LP>> & WithState<State>;
|
|
45
44
|
}): Result;
|
|
46
45
|
}
|
|
47
46
|
export {};
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var ye=Object.defineProperty;var Ee=(e,t,s)=>t in e?ye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var c=(e,t,s)=>(Ee(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function Rt(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 X(e){const t=H(),{count:s}=t;t.unsubscribe(e),s&&!t.count&&De()}function St(e){return H().subscribe(e),()=>X(e)}class ve{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:o}=this.options,a="font-weight: bold;padding: 0 5px;border-radius:5px";console[t](`%c${r}%c / %c${this.scope}`,`${a};background-color: lightblue;color:black`,"",`${a};${i?`color:${i};`:""}${o?`background-color:${o}`:""}`,...s)}error(...t){this.print("error",...t)}log(...t){this.print("log",...t)}}const O=new ve("SDK",{bgColor:"forestgreen",textColor:"white"});let Q=!1;const mt=({event:e,args:[t]})=>{O.log("Event received:",t===void 0?{name:e}:{name:e,data:t})};function Re(e){Q!==e&&(Q=e,e?St(mt):X(mt))}function Se(...e){Q&&O.log(...e)}class q{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 Y(e,t,s){return window.addEventListener(e,t,s),()=>window.removeEventListener(e,t,s)}class k extends Error{constructor(t,s,n){super(s,{cause:n}),this.type=t,Object.setPrototypeOf(this,k.prototype)}}function d(e,t,s){return new k(e,t,s)}const Pt="ERR_METHOD_UNSUPPORTED",Tt="ERR_METHOD_PARAMETER_UNSUPPORTED",Ct="ERR_UNKNOWN_ENV",At="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",It="ERR_TIMED_OUT",xt="ERR_UNEXPECTED_TYPE",Z="ERR_PARSE",Nt="ERR_NAVIGATION_LIST_EMPTY",qt="ERR_NAVIGATION_CURSOR_INVALID",Pe="ERR_NAVIGATION_ITEM_INVALID",L="ERR_SSR_INIT",kt="ERR_SSR_POST_EVENT",Dt="ERR_INVALID_PATH_BASE";function P(){return d(xt,"Value has unexpected type")}class ${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 d(Z,`Unable to parse value${this.type?` as ${this.type}`:""}`,s)}}optional(){return this.isOptional=!0,this}}function T(e,t){return()=>new $(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 P()},"boolean");function Vt(e,t){const s={};for(const n in e){const r=e[n];if(!r)continue;let i,o;if(typeof r=="function"||"parse"in r)i=n,o=typeof r=="function"?r:r.parse.bind(r);else{const{type:a}=r;i=r.from||n,o=typeof a=="function"?a:a.parse.bind(a)}try{const a=o(t(i));a!==void 0&&(s[n]=a)}catch(a){throw d(Z,`Unable to parse field "${n}"`,a)}}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 P();return t}function u(e,t){return new $(s=>{const n=tt(s);return Vt(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 P()},"number");function U(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(U(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 P()},"string"),st=T(e=>et(h().parse(e)),"rgb");function Te(e){return u({eventType:h(),eventData:t=>t}).parse(e)}function Ce(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function Ae(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function Ie(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((s,n,r)=>{if(n===r.length-1){t[s]=Ae;return}s in t||(t[s]={}),t=t[s]})})}const xe=u({button_id:e=>e==null?void 0:h().parse(e)}),Ne={clipboard_text_received:u({req_id:h(),data:e=>e===null?e:h().optional().parse(e)}),custom_method_invoked:u({req_id:h(),result:e=>e,error:h().optional()}),invoice_closed:u({slug:h(),status:h()}),phone_requested:u({status:h()}),popup_closed:{parse:e=>xe.parse(e??{})},qr_text_received:u({data:h().optional()}),theme_changed:u({theme_params:e=>{const t=st().optional();return Object.entries(tt(e)).reduce((s,[n,r])=>(s[n]=t.parse(r),s),{})}}),viewport_changed:u({height:y(),width:e=>e==null?window.innerWidth:y().parse(e),is_state_stable:w(),is_expanded:w()}),write_access_requested:u({status:h()})};function qe(){const e=new q;Ie();let t=[Ce,Y("resize",()=>{e.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),Y("message",s=>{if(s.source!==window.parent)return;let n;try{n=Te(s.data)}catch{return}const{eventType:r,eventData:i}=n,o=Ne[r];try{const a=o?o.parse(i):i;e.emit(...a?[r,a]:[r])}catch(a){O.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,a)}}),()=>e.clear()];return[e,()=>{t.forEach(s=>s()),t=[]}]}const[ke,De]=Rt(e=>{const[t,s]=qe(),n=t.off.bind(t);return t.off=(r,i)=>{const{count:o}=t;n(r,i),o&&!t.count&&e()},[t,s]},([,e])=>e());function H(){return ke()[0]}function D(e,t){H().off(e,t)}function g(e,t,s){return H().on(e,t,s)}function V(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 o=parseInt(s[i]||"0",10),a=parseInt(n[i]||"0",10);if(o!==a)return o>a?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 Ve(e){return"external"in e&&V(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function Me(e){return"TelegramWebviewProxy"in e&&V(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function Ot(){try{return window.self!==window.top}catch{return!0}}let Lt="https://web.telegram.org";function Be(e){Lt=e}function $t(){return Lt}function R(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=$t()}=n;if(Se("Posting event:",r?{event:e,data:r}:{event:e}),Ot()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:r}),i);return}if(Ve(window)){window.external.notify(JSON.stringify({eventType:e,eventData:r}));return}if(Me(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(r));return}throw d(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 Ut(e){return(t,s)=>{if(!E(t,e))throw d(Pt,`Method "${t}" is unsupported in Mini Apps version ${e}`);if(V(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 d(Tt,`Parameter "${n}" of "${t}" method is unsupported in Mini Apps version ${e}`)}return R(t,s)}}function nt(e){return({req_id:t})=>t===e}function Ht(e){return d(It,`Timeout reached: ${e}ms`)}function rt(e,t){return Promise.race([typeof e=="function"?e():e,new Promise((s,n)=>{setTimeout(()=>{n(Ht(t))},t)})])}async function l(e){let t;const s=new Promise(f=>{t=f}),{method:n,event:r,capture:i,postEvent:o=R,timeout:a}=e,p=(Array.isArray(r)?r:[r]).map(f=>g(f,wt=>(!i||i(wt))&&t(wt)));try{return o(n,e.params),await(a?rt(s,a):s)}finally{p.forEach(f=>f())}}async function v(e,t,s,n={}){const{result:r,error:i}=await l({...n,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:e,params:t,req_id:s},capture:nt(s)});if(i)throw d(At,i);return r}function B(...e){return e.map(t=>{if(typeof t=="string")return t;if(V(t))return B(Object.entries(t).map(s=>s[1]&&s[0]));if(Array.isArray(t))return B(...t)}).filter(Boolean).join(" ")}function Oe(...e){return e.reduce((t,s)=>(V(s)&&Object.entries(s).forEach(([n,r])=>{const i=B(t[n],r);i.length&&(t[n]=i)}),t),{})}function it(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 Le{constructor(t){c(this,"ee",new q);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,o])=>this.state[i]===o||o===void 0?r:(this.state[i]=o,this.ee.emit(`change:${i}`,o),!0),!1)&&this.ee.emit("change",this.state)}get(t){return this.state[t]}}class ot{constructor(t){c(this,"state");c(this,"get");c(this,"set");c(this,"clone");this.state=new Le(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 Wt(e,t){return s=>E(t[s],e)}class at extends ot{constructor(s,n,r){super(s);c(this,"supports");this.supports=Wt(n,r)}}class Gt extends at{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}}function S(){return typeof window>"u"}const ct=T(e=>e instanceof Date?e:new Date(y().parse(e)*1e3),"Date");function W(e,t){return new $(s=>{if(typeof s!="string"&&!(s instanceof URLSearchParams))throw P();const n=typeof s=="string"?new URLSearchParams(s):s;return Vt(e,r=>{const i=n.get(r);return i===null?void 0:i})},!1,t)}const $e=u({id:y(),type:h(),title:h(),photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"Chat").optional(),yt=u({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 jt(){return W({authDate:{type:ct(),from:"auth_date"},canSendAfter:{type:y().optional(),from:"can_send_after"},chat:$e,chatInstance:{type:h().optional(),from:"chat_instance"},chatType:{type:h().optional(),from:"chat_type"},hash:h(),queryId:{type:h().optional(),from:"query_id"},receiver:yt,startParam:{type:h().optional(),from:"start_param"},user:yt},"InitData")}function Ue(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}function He(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[Ue(n)]=t.parse(r),s),{})},"ThemeParams");function ht(e){return W({botInline:{type:w().optional(),from:"tgWebAppBotInline"},initData:{type:jt().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 zt(e){return ht(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function We(){return zt(window.location.href)}function Jt(){return performance.getEntriesByType("navigation")[0]}function Ge(){const e=Jt();if(!e)throw new Error("Unable to get first navigation entry.");return zt(e.name)}function Qt(e){return`tma.js/${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function Yt(e,t){sessionStorage.setItem(Qt(e),JSON.stringify(t))}function Kt(e){const t=sessionStorage.getItem(Qt(e));try{return t?JSON.parse(t):void 0}catch{}}function je(){return ht(Kt("launchParams")||"")}function Xt(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,s])=>[He(t),s])))}function Zt(e){const{initDataRaw:t,themeParams:s,platform:n,version:r,showSettings:i,startParam:o,botInline:a}=e,p=new URLSearchParams;return p.set("tgWebAppPlatform",n),p.set("tgWebAppThemeParams",Xt(s)),p.set("tgWebAppVersion",r),t&&p.set("tgWebAppData",t),o&&p.set("tgWebAppStartParam",o),typeof i=="boolean"&&p.set("tgWebAppShowSettings",i?"1":"0"),typeof a=="boolean"&&p.set("tgWebAppBotInline",a?"1":"0"),p.toString()}function Fe(e){Yt("launchParams",Zt(e))}function te(){for(const e of[We,Ge,je])try{const t=e();return Fe(t),t}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}function pt(){const e=Jt();return!!(e&&e.type==="reload")}function ze(){let e=0;return()=>(e+=1).toString()}const[Je]=Rt(ze);function _(e,t){return({ssr:s}={})=>{let n;if(S()){if(!s)throw d(L,"ssr.options must be specified to initialize component on the server side");n=s}else n=te();const r={...n,postEvent:"version"in n?Ut(n.version):()=>{throw d(kt,"postEvent function is forbidden to be called on the server side.")},createRequestId:Je()};if(S()||typeof e=="function")return typeof e=="function"?e(r):t(r);const i=t({...r,state:pt()?Kt(e):void 0}),o=a=>(a.on("change",p=>{Yt(e,p)}),a);return i instanceof Promise?i.then(o):o(i)}}const Qe=_("backButton",({postEvent:e,version:t,state:s={isVisible:!1}})=>new Gt(s.isVisible,t,e));class M extends at{constructor(){super(...arguments);c(this,"on",this.state.on.bind(this.state));c(this,"off",this.state.off.bind(this.state))}}function ee(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 K 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=l({...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=l({...n,postEvent:this.postEvent,method:"web_app_biometry_request_access",event:"biometry_info_received",params:{reason:s||""}}).then(r=>{const i=ee(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 l({...n,postEvent:this.postEvent,method:"web_app_biometry_update_token",event:"biometry_token_updated",params:{token:s||""}})).status)}}async function se(e){return ee(await l({...e||{},method:"web_app_biometry_get_info",event:"biometry_info_received"}))}const Ye=_("biometryManager",async({postEvent:e,version:t,state:s})=>{if(s)return new K({...s,version:t,postEvent:e});if(S())throw d(L,"BiometryManager cannot be instantiated on the server side without passing the ssr.state object.");return new K({...await se({timeout:1e3}),version:t,postEvent:e})});class ut extends ot{constructor(){super(...arguments);c(this,"on",this.state.on.bind(this.state));c(this,"off",this.state.off.bind(this.state))}}class ne extends ut{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 Ke=_("closingBehavior",({postEvent:e,state:t={isConfirmationNeeded:!1}})=>new ne(t.isConfirmationNeeded,e));class lt{constructor(t,s){c(this,"supports");this.supports=Wt(t,s)}}function Xe(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 P()}class Ze extends ${constructor(s,n,r){super(Xe,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 re(e){return new Ze(t=>t,!1,e)}function Et(e,t){return Object.fromEntries(e.map(s=>[s,t]))}class ie extends lt{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 re().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 Et(n,"");const r=await v("getStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent}),i=u(Et(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 ts=_(({createRequestId:e,postEvent:t,version:s})=>new ie(s,e,t));class oe extends lt{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 es=_(({version:e,postEvent:t})=>new oe(e,t));class ae{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 ss=_(({initData:e})=>e?new ae(e):void 0);function ns(e){return jt().parse(e)}class ce 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 o=i.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!o)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');[,,n]=o}this.isOpened=!0;try{return(await l({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 rs=_(({version:e,postEvent:t})=>new ce(!1,e,t));class he extends ot{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}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 is=_("mainButton",({postEvent:e,themeParams:t,state:s={isVisible:!1,isEnabled:!1,text:"",isLoaderVisible:!1,textColor:t.buttonTextColor||"#ffffff",backgroundColor:t.buttonColor||"#000000"}})=>new he({...s,postEvent:e}));function os(){return W({contact:u({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:ct(),from:"auth_date"},hash:h()},"RequestedContact")}function pe(e,t){return s=>{const[n,r]=t[s];return E(n,r,e)}}function as(e){return new Promise(t=>{setTimeout(t,e)})}class ue extends M{constructor({postEvent:s,createRequestId:n,version:r,botInline:i,...o}){super(o,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 a=this.supports.bind(this);this.supports=p=>a(p)?p!=="switchInlineQuery"||i:!1,this.supportsParam=pe(r,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact({timeout:s=1e4}={}){return os().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 it(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 rt(async()=>{for(;Date.now()<r;){try{return await this.getRequestedContact()}catch{}await as(i),i+=50}throw Ht(s)},s)}async requestPhoneAccess(s={}){return this.requestPhoneAccessPromise||(this.requestPhoneAccessPromise=l({...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=l({...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",U(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 cs=_("miniApp",({themeParams:e,botInline:t=!1,state:s={bgColor:e.bgColor||"#ffffff",headerColor:e.headerBgColor||"#000000"},...n})=>new ue({...n,...s,botInline:t}));function hs(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:o=""}=i;if(o.length>64)throw new Error(`Button ID has incorrect size: ${o}`);if(!i.type||i.type==="default"||i.type==="destructive"){const a=i.text.trim();if(!a.length||a.length>64){const p=i.type||"default";throw new Error(`Button text with type "${p}" has incorrect size: ${i.text.length}`)}return{...i,text:a,id:o}}return{...i,id:o}}):r=[{type:"close",id:""}],{title:s,message:t,buttons:r}}class le 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 l({event:"popup_closed",method:"web_app_open_popup",postEvent:this.postEvent,params:hs(t)});return s}finally{this.isOpened=!1}}}const ps=_(({postEvent:e,version:t})=>new le(!1,t,e));class de 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 l({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 us=_(({version:e,postEvent:t})=>new de(!1,e,t));class _e extends at{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 ls=_("settingsButton",({version:e,postEvent:t,state:s={isVisible:!1}})=>new _e(s.isVisible,e,t));function dt(e){return Ft().parse(e)}class fe extends ut{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||it(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(dt(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}const ds=_("themeParams",({themeParams:e,state:t=e})=>{const s=new fe(t);return S()||s.listen(),s});function _s(e={}){return l({...e,method:"web_app_request_theme",event:"theme_changed"}).then(dt)}class ge extends lt{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=pe(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 l({method:"web_app_read_text_from_clipboard",event:"clipboard_text_received",postEvent:this.postEvent,params:{req_id:s},capture:nt(s)});return n}}const fs=_(({version:e,postEvent:t,createRequestId:s})=>new ge(e,s,t));async function _t(e={}){const{is_expanded:t,is_state_stable:s,...n}=await l({...e,method:"web_app_request_viewport",event:"viewport_changed"});return{...n,isExpanded:t,isStateStable:s}}function C(e){return e<0?0:e}class ft extends ut{constructor({postEvent:s,stableHeight:n,height:r,width:i,isExpanded:o}){super({height:C(r),isExpanded:o,stableHeight:C(n),width:C(i)});c(this,"postEvent");this.postEvent=s}async sync(s){const{isStateStable:n,...r}=await _t(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:o}=s,a=C(n);this.set({height:a,isExpanded:i,width:C(r),...o?{stableHeight:a}:{}})})}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}}async function gs(e,t={}){const{height:s,width:n,isExpanded:r,isStateStable:i}=await _t({...t,postEvent:e});return new ft({postEvent:e,height:s,width:n,isExpanded:r,stableHeight:i?s:0})}function bs({state:e,platform:t,postEvent:s}){let n=!1,r=0,i=0,o=0;return e?(n=e.isExpanded,r=e.height,i=e.width,o=e.stableHeight):["macos","tdesktop","unigram","webk","weba","web"].includes(t)&&(n=!0,r=window.innerHeight,i=window.innerWidth,o=window.innerHeight),new ft({postEvent:s,height:r,width:i,stableHeight:o,isExpanded:n})}const ws=_("viewport",async e=>{if(S()&&!e.state)throw d(L,"Viewport cannot be instantiated on the server side without passing the ssr.state object.");let t=bs(e);return S()||(t.width===0&&await gs(e.postEvent,{timeout:1e3}).then(s=>t=s).catch(s=>O.error("Unable to sync viewport state",s)),t.listen()),t});function m(e,t){document.documentElement.style.setProperty(e,t)}function ms(e,t,s){s||(s=a=>`--tg-${a}-color`);const n=s("header"),r=s("bg"),i=()=>{const{headerColor:a}=e;if(U(a))m(n,a);else{const{bgColor:p,secondaryBgColor:f}=t;a==="bg_color"&&p?m(n,p):a==="secondary_bg_color"&&f&&m(n,f)}m(r,e.bgColor)},o=[t.on("change",i),e.on("change",i)];return i(),()=>o.forEach(a=>a())}function ys(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 Es(e,t){t||(t=f=>`--tg-viewport-${f}`);const[s,n,r]=["height","width","stable-height"].map(f=>t(f)),i=()=>m(s,`${e.height}px`),o=()=>m(n,`${e.width}px`),a=()=>m(r,`${e.stableHeight}px`),p=[e.on("change:height",i),e.on("change:width",o),e.on("change:stableHeight",a)];return i(),o(),a(),()=>p.forEach(f=>f())}function vs(e=!0){const t=[g("reload_iframe",()=>{R("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 R("iframe_ready",{reload_supported:!0}),s}async function Rs(){try{return await l({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function be(e){return e instanceof k}function Ss(e,t){return be(e)&&e.type===t}function G(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 we{constructor(t,s,n=R){c(this,"history");c(this,"ee",new q);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 d(Nt,"History should not be empty.");if(s<0||s>=t.length)throw d(qt,"Index should not be zero and higher or equal than history size.");this.history=t.map(r=>G(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,G(t,this.current.pathname))}replace(t){this.replaceAndMove(this.index,G(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 j({params:e,...t}){return{...e||{hash:"",search:""},...t}}function I(e,t){return e.startsWith(t)?e:`${t}${e}`}function x(e){return new URL(typeof e=="string"?e:`${e.pathname||""}${I(e.search||"","?")}${I(e.hash||"","#")}`,"http://a")}function N(e){const t=typeof e=="string"?e.startsWith("/"):!!(e.pathname&&e.pathname.startsWith("/")),s=x(e);return`${t?s.pathname:s.pathname.slice(1)}${s.search}${s.hash}`}function F(e,t,s){let n,r;typeof e=="string"?n=e:(n=N(e),s=e.state,r=e.id);const{pathname:i,search:o,hash:a}=new URL(n,`http://a${I(t,"/")}`);return{id:r,pathname:i,params:{hash:a,search:o,state:s}}}async function A(e){return e===0?!0:Promise.race([new Promise(t=>{const s=Y("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 A(1-window.history.length)))return;let t=await A(-1);for(;t;)t=await A(-1)}function gt(e){return x(e).pathname}const vt=0,z=1,J=2;class bt{constructor(t,s,{postEvent:n,hashMode:r,base:i}={}){c(this,"navigator");c(this,"ee",new q);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===vt?window.history.forward():t===z&&this.back(),t===J&&this.forward()});c(this,"onNavigatorChange",async({to:t,from:s,delta:n})=>{this.attached&&await this.syncHistory(),this.ee.emit("change",{delta:n,from:j(s),to:j(t),navigator:this})});c(this,"on",this.ee.on.bind(this.ee));c(this,"off",this.ee.off.bind(this.ee));this.navigator=new we(t.map(o=>F(o,"/")),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(j)}get path(){return N(this)}get pathname(){return this.navigator.current.pathname}parsePath(t){let s=x(t);return this.hashMode&&(s=x(s.hash.slice(1))),{pathname:s.pathname,search:s.search,hash:s.hash}}push(t,s){const n=F(t,this.path),{state:r=s}=n.params;this.navigator.push({...n,params:{...n.params,state:r}})}replace(t,s){const n=F(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)+I(N(t),"/");return this.hashMode?I(s.slice(1),this.hashMode==="default"?"#":"#/"):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(J,""),await A(-1)):this.hasPrev?(window.history.replaceState(z,""),window.history.pushState(t,"",s)):this.hasNext?(window.history.replaceState(t,s),window.history.pushState(J,""),await A(-1)):(window.history.replaceState(vt,""),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 me(e){e||(e={});const{href:t,hash:s}=window.location;let n=N(e.hashMode?s.includes("?")?s.slice(1):`?${s.slice(1)}`:t);const r=e.base?gt(e.base):void 0;if(r){if(!n.startsWith(r))throw d(Dt,`Path "${n}" expected to be starting with "${r}"`);n=n.slice(r.length)}return new bt([n],0,e)}function Ts(e){const t=e.match(/#(.+)/);return t?t[1]:null}function Cs(e,t){if(pt()){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 me(t)}function As(e,t){const s=Cs(e,t),n=()=>sessionStorage.setItem(e,JSON.stringify({index:s.index,history:s.history}));return s.on("change",n),n(),s}exports.BackButton=Gt;exports.BasicNavigator=we;exports.BiometryManager=K;exports.BrowserNavigator=bt;exports.ClosingBehavior=ne;exports.CloudStorage=ie;exports.ERR_INVALID_PATH_BASE=Dt;exports.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=At;exports.ERR_METHOD_PARAMETER_UNSUPPORTED=Tt;exports.ERR_METHOD_UNSUPPORTED=Pt;exports.ERR_NAVIGATION_HISTORY_EMPTY=Nt;exports.ERR_NAVIGATION_INDEX_INVALID=qt;exports.ERR_NAVIGATION_ITEM_INVALID=Pe;exports.ERR_PARSE=Z;exports.ERR_SSR_INIT=L;exports.ERR_SSR_POST_EVENT=kt;exports.ERR_TIMED_OUT=It;exports.ERR_UNEXPECTED_TYPE=xt;exports.ERR_UNKNOWN_ENV=Ct;exports.EventEmitter=q;exports.HapticFeedback=oe;exports.InitData=ae;exports.Invoice=ce;exports.MainButton=he;exports.MiniApp=ue;exports.Popup=le;exports.QRScanner=de;exports.SDKError=k;exports.SettingsButton=_e;exports.ThemeParams=fe;exports.Utils=ge;exports.Viewport=ft;exports.array=re;exports.bindMiniAppCSSVars=ms;exports.bindThemeParamsCSSVars=ys;exports.bindViewportCSSVars=Es;exports.boolean=w;exports.captureSameReq=nt;exports.classNames=B;exports.compareVersions=Bt;exports.createBrowserNavigatorFromLocation=me;exports.createPostEvent=Ut;exports.createSafeURL=x;exports.date=ct;exports.getHash=Ts;exports.getPathname=gt;exports.initBackButton=Qe;exports.initBiometryManager=Ye;exports.initClosingBehavior=Ke;exports.initCloudStorage=ts;exports.initHapticFeedback=es;exports.initInitData=ss;exports.initInvoice=rs;exports.initMainButton=is;exports.initMiniApp=cs;exports.initNavigator=As;exports.initPopup=ps;exports.initQRScanner=us;exports.initSettingsButton=ls;exports.initThemeParams=ds;exports.initUtils=fs;exports.initViewport=ws;exports.initWeb=vs;exports.invokeCustomMethod=v;exports.isColorDark=it;exports.isIframe=Ot;exports.isPageReload=pt;exports.isRGB=U;exports.isRGBShort=Mt;exports.isSDKError=be;exports.isSDKErrorOfType=Ss;exports.isTMA=Rs;exports.json=u;exports.mergeClassNames=Oe;exports.number=y;exports.off=D;exports.on=g;exports.parseInitData=ns;exports.parseLaunchParams=ht;exports.parseThemeParams=dt;exports.postEvent=R;exports.request=l;exports.requestBiometryInfo=se;exports.requestThemeParams=_s;exports.requestViewport=_t;exports.retrieveLaunchParams=te;exports.rgb=st;exports.searchParams=W;exports.serializeLaunchParams=Zt;exports.serializeThemeParams=Xt;exports.setCSSVar=m;exports.setDebug=Re;exports.setTargetOrigin=Be;exports.string=h;exports.subscribe=St;exports.supports=E;exports.targetOrigin=$t;exports.toRGB=et;exports.unsubscribe=X;exports.urlToPath=N;exports.withTimeout=rt;
|
|
1
|
+
"use strict";var ye=Object.defineProperty;var Ee=(e,t,s)=>t in e?ye(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s;var c=(e,t,s)=>(Ee(e,typeof t!="symbol"?t+"":t,s),s);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function Pt(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=U(),{count:s}=t;t.unsubscribe(e),s&&!t.count&&De()}function St(e){return U().subscribe(e),()=>K(e)}class ve{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:o}=this.options,a="font-weight: bold;padding: 0 5px;border-radius:5px";console[t](`%c${r}%c / %c${this.scope}`,`${a};background-color: lightblue;color:black`,"",`${a};${i?`color:${i};`:""}${o?`background-color:${o}`:""}`,...s)}error(...t){this.print("error",...t)}log(...t){this.print("log",...t)}}const O=new ve("SDK",{bgColor:"forestgreen",textColor:"white"});let J=!1;const mt=({event:e,args:[t]})=>{O.log("Event received:",t===void 0?{name:e}:{name:e,data:t})};function Pe(e){J!==e&&(J=e,e?St(mt):K(mt))}function Se(...e){J&&O.log(...e)}class q{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)}class k extends Error{constructor(t,s,n){super(s,{cause:n}),this.type=t,Object.setPrototypeOf(this,k.prototype)}}function f(e,t,s){return new k(e,t,s)}const Rt="ERR_METHOD_UNSUPPORTED",Tt="ERR_METHOD_PARAMETER_UNSUPPORTED",Ct="ERR_UNKNOWN_ENV",At="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",It="ERR_TIMED_OUT",xt="ERR_UNEXPECTED_TYPE",X="ERR_PARSE",Nt="ERR_NAVIGATION_LIST_EMPTY",qt="ERR_NAVIGATION_CURSOR_INVALID",Re="ERR_NAVIGATION_ITEM_INVALID",Z="ERR_SSR_INIT",kt="ERR_INVALID_PATH_BASE";function R(){return f(xt,"Value has unexpected type")}class L{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(X,`Unable to parse value${this.type?` as ${this.type}`:""}`,s)}}optional(){return this.isOptional=!0,this}}function T(e,t){return()=>new L(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 Dt(e,t){const s={};for(const n in e){const r=e[n];if(!r)continue;let i,o;if(typeof r=="function"||"parse"in r)i=n,o=typeof r=="function"?r:r.parse.bind(r);else{const{type:a}=r;i=r.from||n,o=typeof a=="function"?a:a.parse.bind(a)}try{const a=o(t(i));a!==void 0&&(s[n]=a)}catch(a){throw f(X,`Unable to parse field "${n}"`,a)}}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 u(e,t){return new L(s=>{const n=tt(s);return Dt(e,r=>n[r])},!1,t)}const E=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 $(e){return/^#[\da-f]{6}$/i.test(e)}function Vt(e){return/^#[\da-f]{3}$/i.test(e)}function et(e){const t=e.replace(/\s/g,"").toLowerCase();if($(t))return t;if(Vt(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 Te(e){return u({eventType:h(),eventData:t=>t}).parse(e)}function Ce(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function Ae(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function Ie(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((s,n,r)=>{if(n===r.length-1){t[s]=Ae;return}s in t||(t[s]={}),t=t[s]})})}const xe=u({button_id:e=>e==null?void 0:h().parse(e)}),Ne={clipboard_text_received:u({req_id:h(),data:e=>e===null?e:h().optional().parse(e)}),custom_method_invoked:u({req_id:h(),result:e=>e,error:h().optional()}),invoice_closed:u({slug:h(),status:h()}),phone_requested:u({status:h()}),popup_closed:{parse:e=>xe.parse(e??{})},qr_text_received:u({data:h().optional()}),theme_changed:u({theme_params:e=>{const t=st().optional();return Object.entries(tt(e)).reduce((s,[n,r])=>(s[n]=t.parse(r),s),{})}}),viewport_changed:u({height:E(),width:e=>e==null?window.innerWidth:E().parse(e),is_state_stable:w(),is_expanded:w()}),write_access_requested:u({status:h()})};function qe(){const e=new q;Ie();let t=[Ce,Q("resize",()=>{e.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),Q("message",s=>{if(s.source!==window.parent)return;let n;try{n=Te(s.data)}catch{return}const{eventType:r,eventData:i}=n,o=Ne[r];try{const a=o?o.parse(i):i;e.emit(...a?[r,a]:[r])}catch(a){O.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,a)}}),()=>e.clear()];return[e,()=>{t.forEach(s=>s()),t=[]}]}const[ke,De]=Pt(e=>{const[t,s]=qe(),n=t.off.bind(t);return t.off=(r,i)=>{const{count:o}=t;n(r,i),o&&!t.count&&e()},[t,s]},([,e])=>e());function U(){return ke()[0]}function D(e,t){U().off(e,t)}function g(e,t,s){return U().on(e,t,s)}function V(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mt(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 o=parseInt(s[i]||"0",10),a=parseInt(n[i]||"0",10);if(o!==a)return o>a?1:-1}return 0}function b(e,t){return Mt(e,t)<=0}function v(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 Ve(e){return"external"in e&&V(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function Bt(e){return"TelegramWebviewProxy"in e&&V(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function Ot(){try{return window.self!==window.top}catch{return!0}}let Lt="https://web.telegram.org";function Me(e){Lt=e}function $t(){return Lt}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=$t()}=n;if(Se("Posting event:",r?{event:e,data:r}:{event:e}),Ot()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:r}),i);return}if(Ve(window)){window.external.notify(JSON.stringify({eventType:e,eventData:r}));return}if(Bt(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 Ut(e){return(t,s)=>{if(!v(t,e))throw f(Rt,`Method "${t}" is unsupported in Mini Apps version ${e}`);if(V(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&&!v(t,n,e))throw f(Tt,`Parameter "${n}" of "${t}" method is unsupported in Mini Apps version ${e}`)}return S(t,s)}}function nt(e){return({req_id:t})=>t===e}function Ht(e){return f(It,`Timeout reached: ${e}ms`)}function rt(e,t){return Promise.race([typeof e=="function"?e():e,new Promise((s,n)=>{setTimeout(()=>{n(Ht(t))},t)})])}async function l(e){let t;const s=new Promise(_=>{t=_}),{method:n,event:r,capture:i,postEvent:o=S,timeout:a}=e,p=(Array.isArray(r)?r:[r]).map(_=>g(_,wt=>(!i||i(wt))&&t(wt)));try{return o(n,e.params),await(a?rt(s,a):s)}finally{p.forEach(_=>_())}}async function P(e,t,s,n={}){const{result:r,error:i}=await l({...n,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:e,params:t,req_id:s},capture:nt(s)});if(i)throw f(At,i);return r}function B(...e){return e.map(t=>{if(typeof t=="string")return t;if(V(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)=>(V(s)&&Object.entries(s).forEach(([n,r])=>{const i=B(t[n],r);i.length&&(t[n]=i)}),t),{})}function it(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 q);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,o])=>this.state[i]===o||o===void 0?r:(this.state[i]=o,this.ee.emit(`change:${i}`,o),!0),!1)&&this.ee.emit("change",this.state)}get(t){return this.state[t]}}class ot{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 Wt(e,t){return s=>v(t[s],e)}class at extends ot{constructor(s,n,r){super(s);c(this,"supports");this.supports=Wt(n,r)}}class Gt extends at{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}}function y(){return typeof window>"u"}const ct=T(e=>e instanceof Date?e:new Date(E().parse(e)*1e3),"Date");function H(e,t){return new L(s=>{if(typeof s!="string"&&!(s instanceof URLSearchParams))throw R();const n=typeof s=="string"?new URLSearchParams(s):s;return Dt(e,r=>{const i=n.get(r);return i===null?void 0:i})},!1,t)}const Le=u({id:E(),type:h(),title:h(),photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"Chat").optional(),yt=u({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:E(),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 jt(){return H({authDate:{type:ct(),from:"auth_date"},canSendAfter:{type:E().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:yt,startParam:{type:h().optional(),from:"start_param"},user:yt},"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 ht(e){return H({botInline:{type:w().optional(),from:"tgWebAppBotInline"},initData:{type:jt().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 zt(e){return ht(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function He(){return zt(window.location.href)}function Jt(){return performance.getEntriesByType("navigation")[0]}function We(){const e=Jt();if(!e)throw new Error("Unable to get first navigation entry.");return zt(e.name)}function Qt(e){return`tma.js/${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function Yt(e,t){sessionStorage.setItem(Qt(e),JSON.stringify(t))}function Kt(e){const t=sessionStorage.getItem(Qt(e));try{return t?JSON.parse(t):void 0}catch{}}function Ge(){return ht(Kt("launchParams")||"")}function Xt(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:o,botInline:a}=e,p=new URLSearchParams;return p.set("tgWebAppPlatform",n),p.set("tgWebAppThemeParams",Xt(s)),p.set("tgWebAppVersion",r),t&&p.set("tgWebAppData",t),o&&p.set("tgWebAppStartParam",o),typeof i=="boolean"&&p.set("tgWebAppShowSettings",i?"1":"0"),typeof a=="boolean"&&p.set("tgWebAppBotInline",a?"1":"0"),p.toString()}function je(e){Yt("launchParams",Zt(e))}function te(){for(const e of[He,We,Ge])try{const t=e();return je(t),t}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}function pt(){const e=Jt();return!!(e&&e.type==="reload")}function Fe(){let e=0;return()=>(e+=1).toString()}const[ze]=Pt(Fe);function d(e,t){return({ssr:s}={})=>{const n=y()?{version:"6.0",themeParams:{},platform:"unknown",...s||{}}:te(),r={...n,postEvent:y()?()=>null:Ut(n.version),createRequestId:ze()};if(y()||typeof e=="function")return typeof e=="function"?e(r):t(r);const i=t({...r,state:pt()?Kt(e):void 0}),o=a=>(a.on("change",p=>{Yt(e,p)}),a);return i instanceof Promise?i.then(o):o(i)}}const Je=d("backButton",({postEvent:e,version:t,state:s={isVisible:!1}})=>new Gt(s.isVisible,t,e));class M extends at{constructor(){super(...arguments);c(this,"on",this.state.on.bind(this.state));c(this,"off",this.state.off.bind(this.state))}}function ee(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 Y 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=l({...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=l({...n,postEvent:this.postEvent,method:"web_app_biometry_request_access",event:"biometry_info_received",params:{reason:s||""}}).then(r=>{const i=ee(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 l({...n,postEvent:this.postEvent,method:"web_app_biometry_update_token",event:"biometry_token_updated",params:{token:s||""}})).status)}}async function se(e){return ee(await l({...e||{},method:"web_app_biometry_get_info",event:"biometry_info_received"}))}const Qe=d("biometryManager",async({postEvent:e,version:t,state:s})=>{if(s)return new Y({...s,version:t,postEvent:e});if(y())throw f(Z,"BiometryManager cannot be instantiated on the server side without passing the ssr.state object.");return new Y({...await se({timeout:1e3}),version:t,postEvent:e})});class ut extends ot{constructor(){super(...arguments);c(this,"on",this.state.on.bind(this.state));c(this,"off",this.state.off.bind(this.state))}}class ne extends ut{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=d("closingBehavior",({postEvent:e,state:t={isConfirmationNeeded:!1}})=>new ne(t.isConfirmationNeeded,e));class lt{constructor(t,s){c(this,"supports");this.supports=Wt(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 R()}class Xe extends L{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 re(e){return new Xe(t=>t,!1,e)}function Et(e,t){return Object.fromEntries(e.map(s=>[s,t]))}class ie extends lt{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 P("deleteStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent})}async getKeys(t={}){return re().of(h()).parse(await P("getStorageKeys",{},this.createRequestId(),{...t,postEvent:this.postEvent}))}async get(t,s={}){const n=Array.isArray(t)?t:[t];if(!n.length)return Et(n,"");const r=await P("getStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent}),i=u(Et(n,h()),"CloudStorageData").parse(r);return Array.isArray(t)?i:i[t]}async set(t,s,n={}){await P("saveStorageValue",{key:t,value:s},this.createRequestId(),{...n,postEvent:this.postEvent})}}const Ze=d(({createRequestId:e,postEvent:t,version:s})=>new ie(s,e,t));class oe extends lt{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=d(({version:e,postEvent:t})=>new oe(e,t));class ae{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=d(({initData:e})=>e?new ae(e):void 0);function ss(e){return jt().parse(e)}class ce 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 o=i.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!o)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');[,,n]=o}this.isOpened=!0;try{return(await l({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=d(({version:e,postEvent:t})=>new ce(!1,e,t));class he extends ot{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}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=d("mainButton",({postEvent:e,themeParams:t,state:s={isVisible:!1,isEnabled:!1,text:"",isLoaderVisible:!1,textColor:t.buttonTextColor||"#ffffff",backgroundColor:t.buttonColor||"#000000"}})=>new he({...s,postEvent:e}));function is(){return H({contact:u({userId:{type:E(),from:"user_id"},phoneNumber:{type:h(),from:"phone_number"},firstName:{type:h(),from:"first_name"},lastName:{type:h().optional(),from:"last_name"}}),authDate:{type:ct(),from:"auth_date"},hash:h()},"RequestedContact")}function pe(e,t){return s=>{const[n,r]=t[s];return v(n,r,e)}}function os(e){return new Promise(t=>{setTimeout(t,e)})}class ue extends M{constructor({postEvent:s,createRequestId:n,version:r,botInline:i,...o}){super(o,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 a=this.supports.bind(this);this.supports=p=>a(p)?p!=="switchInlineQuery"||i:!1,this.supportsParam=pe(r,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact({timeout:s=1e4}={}){return is().parse(await P("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 it(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 rt(async()=>{for(;Date.now()<r;){try{return await this.getRequestedContact()}catch{}await os(i),i+=50}throw Ht(s)},s)}async requestPhoneAccess(s={}){return this.requestPhoneAccessPromise||(this.requestPhoneAccessPromise=l({...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=l({...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",$(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=d("miniApp",({themeParams:e,botInline:t=!1,state:s={bgColor:e.bgColor||"#ffffff",headerColor:e.headerBgColor||"#000000"},...n})=>new ue({...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:o=""}=i;if(o.length>64)throw new Error(`Button ID has incorrect size: ${o}`);if(!i.type||i.type==="default"||i.type==="destructive"){const a=i.text.trim();if(!a.length||a.length>64){const p=i.type||"default";throw new Error(`Button text with type "${p}" has incorrect size: ${i.text.length}`)}return{...i,text:a,id:o}}return{...i,id:o}}):r=[{type:"close",id:""}],{title:s,message:t,buttons:r}}class le 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 l({event:"popup_closed",method:"web_app_open_popup",postEvent:this.postEvent,params:cs(t)});return s}finally{this.isOpened=!1}}}const hs=d(({postEvent:e,version:t})=>new le(!1,t,e));class de 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 l({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=d(({version:e,postEvent:t})=>new de(!1,e,t));class _e extends at{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 us=d("settingsButton",({version:e,postEvent:t,state:s={isVisible:!1}})=>new _e(s.isVisible,e,t));function dt(e){return Ft().parse(e)}class fe extends ut{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||it(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(dt(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}const ls=d("themeParams",({themeParams:e,state:t=e})=>{const s=new fe(t);return y()||s.listen(),s});function ds(e={}){return l({...e,method:"web_app_request_theme",event:"theme_changed"}).then(dt)}class ge extends lt{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=pe(s,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(s,n){const r=new URL(s,window.location.href).toString();if(!v("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(!v("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 l({method:"web_app_read_text_from_clipboard",event:"clipboard_text_received",postEvent:this.postEvent,params:{req_id:s},capture:nt(s)});return n}}const _s=d(({version:e,postEvent:t,createRequestId:s})=>new ge(e,s,t));async function _t(e={}){const{is_expanded:t,is_state_stable:s,...n}=await l({...e,method:"web_app_request_viewport",event:"viewport_changed"});return{...n,isExpanded:t,isStateStable:s}}function C(e){return e<0?0:e}class ft extends ut{constructor({postEvent:s,stableHeight:n,height:r,width:i,isExpanded:o}){super({height:C(r),isExpanded:o,stableHeight:C(n),width:C(i)});c(this,"postEvent");this.postEvent=s}async sync(s){const{isStateStable:n,...r}=await _t(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:o}=s,a=C(n);this.set({height:a,isExpanded:i,width:C(r),...o?{stableHeight:a}:{}})})}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}}async function fs(e,t={}){const{height:s,width:n,isExpanded:r,isStateStable:i}=await _t({...t,postEvent:e});return new ft({postEvent:e,height:s,width:n,isExpanded:r,stableHeight:i?s:0})}function gs({state:e,platform:t,postEvent:s}){let n=!1,r=0,i=0,o=0;return e?(n=e.isExpanded,r=e.height,i=e.width,o=e.stableHeight):["macos","tdesktop","unigram","webk","weba","web"].includes(t)&&(n=!0,r=window.innerHeight,i=window.innerWidth,o=window.innerHeight),new ft({postEvent:s,height:r,width:i,stableHeight:o,isExpanded:n})}const bs=d("viewport",async e=>{if(y()&&!e.state)throw f(Z,"Viewport cannot be instantiated on the server side without passing the ssr.state object.");let t=gs(e);return y()||(t.width===0&&await fs(e.postEvent,{timeout:1e3}).then(s=>t=s).catch(s=>O.error("Unable to sync viewport state",s)),t.listen()),t});function m(e,t){document.documentElement.style.setProperty(e,t)}function ws(e,t,s){s||(s=a=>`--tg-${a}-color`);const n=s("header"),r=s("bg"),i=()=>{const{headerColor:a}=e;if($(a))m(n,a);else{const{bgColor:p,secondaryBgColor:_}=t;a==="bg_color"&&p?m(n,p):a==="secondary_bg_color"&&_&&m(n,_)}m(r,e.bgColor)},o=[t.on("change",i),e.on("change",i)];return i(),()=>o.forEach(a=>a())}function ms(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 ys(e,t){t||(t=_=>`--tg-viewport-${_}`);const[s,n,r]=["height","width","stable-height"].map(_=>t(_)),i=()=>m(s,`${e.height}px`),o=()=>m(n,`${e.width}px`),a=()=>m(r,`${e.stableHeight}px`),p=[e.on("change:height",i),e.on("change:width",o),e.on("change:stableHeight",a)];return i(),o(),a(),()=>p.forEach(_=>_())}function Es(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}async function vs(){if(Bt(window))return!0;try{return await l({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function be(e){return e instanceof k}function Ps(e,t){return be(e)&&e.type===t}function W(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 we{constructor(t,s,n=S){c(this,"history");c(this,"ee",new q);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=>W(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,W(t,this.current.pathname))}replace(t){this.replaceAndMove(this.index,W(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 I(e,t){return e.startsWith(t)?e:`${t}${e}`}function x(e){return new URL(typeof e=="string"?e:`${e.pathname||""}${I(e.search||"","?")}${I(e.hash||"","#")}`,"http://a")}function N(e){const t=typeof e=="string"?e.startsWith("/"):!!(e.pathname&&e.pathname.startsWith("/")),s=x(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:o,hash:a}=new URL(n,`http://a${I(t,"/")}`);return{id:r,pathname:i,params:{hash:a,search:o,state:s}}}async function A(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 Ss(){if(window.history.length<=1||(window.history.pushState(null,""),await A(1-window.history.length)))return;let t=await A(-1);for(;t;)t=await A(-1)}function gt(e){return x(e).pathname}const vt=0,F=1,z=2;class bt{constructor(t,s,{postEvent:n,hashMode:r,base:i}={}){c(this,"navigator");c(this,"ee",new q);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===vt?window.history.forward():t===F&&this.back(),t===z&&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 we(t.map(o=>j(o,"/")),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=x(t);return this.hashMode&&(s=x(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)+I(N(t),"/");return this.hashMode?I(s.slice(1),this.hashMode==="default"?"#":"#/"):s}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const{state:t}=this,s=this.renderPath(this);await Ss(),this.hasPrev&&this.hasNext?(window.history.replaceState(F,""),window.history.pushState(t,"",s),window.history.pushState(z,""),await A(-1)):this.hasPrev?(window.history.replaceState(F,""),window.history.pushState(t,"",s)):this.hasNext?(window.history.replaceState(t,s),window.history.pushState(z,""),await A(-1)):(window.history.replaceState(vt,""),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 me(e){e||(e={});const{href:t,hash:s}=window.location;let n=N(e.hashMode?s.includes("?")?s.slice(1):`?${s.slice(1)}`:t);const r=e.base?gt(e.base):void 0;if(r){if(!n.startsWith(r))throw f(kt,`Path "${n}" expected to be starting with "${r}"`);n=n.slice(r.length)}return new bt([n],0,e)}function Rs(e){const t=e.match(/#(.+)/);return t?t[1]:null}function Ts(e,t){if(pt()){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 me(t)}function Cs(e,t){const s=Ts(e,t),n=()=>sessionStorage.setItem(e,JSON.stringify({index:s.index,history:s.history}));return s.on("change",n),n(),s}exports.BackButton=Gt;exports.BasicNavigator=we;exports.BiometryManager=Y;exports.BrowserNavigator=bt;exports.ClosingBehavior=ne;exports.CloudStorage=ie;exports.ERR_INVALID_PATH_BASE=kt;exports.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=At;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=Re;exports.ERR_PARSE=X;exports.ERR_SSR_INIT=Z;exports.ERR_TIMED_OUT=It;exports.ERR_UNEXPECTED_TYPE=xt;exports.ERR_UNKNOWN_ENV=Ct;exports.EventEmitter=q;exports.HapticFeedback=oe;exports.InitData=ae;exports.Invoice=ce;exports.MainButton=he;exports.MiniApp=ue;exports.Popup=le;exports.QRScanner=de;exports.SDKError=k;exports.SettingsButton=_e;exports.ThemeParams=fe;exports.Utils=ge;exports.Viewport=ft;exports.array=re;exports.bindMiniAppCSSVars=ws;exports.bindThemeParamsCSSVars=ms;exports.bindViewportCSSVars=ys;exports.boolean=w;exports.captureSameReq=nt;exports.classNames=B;exports.compareVersions=Mt;exports.createBrowserNavigatorFromLocation=me;exports.createPostEvent=Ut;exports.createSafeURL=x;exports.date=ct;exports.getHash=Rs;exports.getPathname=gt;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=Cs;exports.initPopup=hs;exports.initQRScanner=ps;exports.initSettingsButton=us;exports.initThemeParams=ls;exports.initUtils=_s;exports.initViewport=bs;exports.initWeb=Es;exports.invokeCustomMethod=P;exports.isColorDark=it;exports.isIframe=Ot;exports.isPageReload=pt;exports.isRGB=$;exports.isRGBShort=Vt;exports.isSDKError=be;exports.isSDKErrorOfType=Ps;exports.isSSR=y;exports.isTMA=vs;exports.json=u;exports.mergeClassNames=Be;exports.number=E;exports.off=D;exports.on=g;exports.parseInitData=ss;exports.parseLaunchParams=ht;exports.parseThemeParams=dt;exports.postEvent=S;exports.request=l;exports.requestBiometryInfo=se;exports.requestThemeParams=ds;exports.requestViewport=_t;exports.retrieveLaunchParams=te;exports.rgb=st;exports.searchParams=H;exports.serializeLaunchParams=Zt;exports.serializeThemeParams=Xt;exports.setCSSVar=m;exports.setDebug=Pe;exports.setTargetOrigin=Me;exports.string=h;exports.subscribe=St;exports.supports=v;exports.targetOrigin=$t;exports.toRGB=et;exports.unsubscribe=K;exports.urlToPath=N;exports.withTimeout=rt;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|