@tma.js/sdk-react 2.1.4 → 2.2.1
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/SDKProvider/SDKProvider.types.d.ts +3 -4
- package/dist/dts/createHOCs.d.ts +6 -10
- package/dist/dts/createHooks.d.ts +6 -7
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +725 -667
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
|
@@ -17,7 +17,7 @@ export interface SDKProviderProps extends PropsWithChildren {
|
|
|
17
17
|
/**
|
|
18
18
|
* SDKContext item.
|
|
19
19
|
*/
|
|
20
|
-
export
|
|
20
|
+
export interface SDKContextItem<T> {
|
|
21
21
|
/**
|
|
22
22
|
* This item execution result. The property may be missing in case, execution is async.
|
|
23
23
|
*/
|
|
@@ -26,12 +26,11 @@ export type SDKContextItem<T> = ({
|
|
|
26
26
|
* Function to cleanup item side effects.
|
|
27
27
|
*/
|
|
28
28
|
cleanup?: CleanupFn;
|
|
29
|
-
} | {
|
|
30
29
|
/**
|
|
31
30
|
* An error occurred during execution.
|
|
32
31
|
*/
|
|
33
|
-
error
|
|
34
|
-
}
|
|
32
|
+
error?: unknown;
|
|
33
|
+
}
|
|
35
34
|
export interface SDKContextType {
|
|
36
35
|
/**
|
|
37
36
|
* Uses specified factory with the passed arguments. In case, this factory was called
|
package/dist/dts/createHOCs.d.ts
CHANGED
|
@@ -1,19 +1,15 @@
|
|
|
1
1
|
import { ComponentType } from 'react';
|
|
2
|
-
import {
|
|
3
|
-
import { HookRaw, HookResult } from './createHooks.js';
|
|
2
|
+
import { Hook, HookRaw, HookResult } from './createHooks.js';
|
|
4
3
|
|
|
5
|
-
export interface HOC<
|
|
4
|
+
export interface HOC<H extends HookRaw<any> | HookResult<any>> {
|
|
6
5
|
/**
|
|
7
6
|
* Returns a component which is a HOC, passing some hook result to the wrapped component.
|
|
8
7
|
* @param propKey - key, which will be used to pass a hook result.
|
|
9
|
-
* @param
|
|
8
|
+
* @param ssr - is SSR mode enabled.
|
|
10
9
|
* @param Component - component to wrap.
|
|
11
|
-
*/
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
} & {
|
|
15
|
-
[K in PropKey]?: ReturnType<Hook>;
|
|
16
|
-
}>(propKey: PropKey, optionsKey: OptionsKey, Component: ComponentType<Props>): ComponentType<PartialBy<Props, PropKey | OptionsKey>>;
|
|
10
|
+
*/ <PropKey extends string, SSR extends boolean, Props>(propKey: PropKey, ssr: SSR, Component: ComponentType<Omit<Props, PropKey> & {
|
|
11
|
+
[K in PropKey]: ReturnType<Hook<Exclude<ReturnType<H>, undefined>, SSR>>;
|
|
12
|
+
}>): ComponentType<Omit<Props, PropKey>>;
|
|
17
13
|
}
|
|
18
14
|
export type HOCs<HRaw extends HookRaw<any>, HResult extends HookResult<any>> = [
|
|
19
15
|
HOC<HRaw>,
|
|
@@ -1,15 +1,14 @@
|
|
|
1
|
-
import { CleanupFn, AnyFn } from '@tma.js/sdk';
|
|
1
|
+
import { CleanupFn, AnyFn, If } from '@tma.js/sdk';
|
|
2
2
|
import { SDKContextItem } from './SDKProvider/SDKProvider.types.js';
|
|
3
3
|
|
|
4
|
-
type ExtractResult<T> = T extends [result: infer R, cleanup: CleanupFn] ? ExtractResult<R> : T extends
|
|
4
|
+
type ExtractResult<T> = T extends [result: infer R, cleanup: CleanupFn] ? ExtractResult<R> : T extends PromiseLike<any> ? Awaited<T> | undefined : T;
|
|
5
5
|
type HookFnResult<Fn extends AnyFn> = ExtractResult<ReturnType<Fn>>;
|
|
6
|
-
interface Hook<Result> {
|
|
7
|
-
(ssr?: false): Result;
|
|
8
|
-
(ssr: true): Result | undefined;
|
|
6
|
+
interface CompleteHook<Result> extends Hook<Result, true>, Hook<Result, false> {
|
|
9
7
|
}
|
|
10
|
-
export
|
|
8
|
+
export type Hook<Result, SSR extends boolean> = If<SSR, (ssr: true) => Result | undefined, (ssr?: false) => Result>;
|
|
9
|
+
export interface HookRaw<Factory extends AnyFn> extends CompleteHook<SDKContextItem<HookFnResult<Factory>>> {
|
|
11
10
|
}
|
|
12
|
-
export interface HookResult<Factory extends AnyFn> extends
|
|
11
|
+
export interface HookResult<Factory extends AnyFn> extends CompleteHook<HookFnResult<Factory>> {
|
|
13
12
|
}
|
|
14
13
|
export type Hooks<Factory extends AnyFn> = [
|
|
15
14
|
useRaw: HookRaw<Factory>,
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Ot=require("react/jsx-runtime"),l=require("react");var xs=Object.defineProperty,Ts=(e,t,s)=>t in e?xs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,c=(e,t,s)=>(Ts(e,typeof t!="symbol"?t+"":t,s),s);function qt(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 it(e){const t=Q(),{count:s}=t;t.unsubscribe(e),s&&!t.count&&Us()}function Dt(e){return Q().subscribe(e),()=>it(e)}class ks{constructor(t,s={}){this.scope=t,this.options=s}print(t,...s){const n=new Date,i=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n),{textColor:r,bgColor:a}=this.options,o="font-weight: bold;padding: 0 5px;border-radius:5px";console[t](`%c${i}%c / %c${this.scope}`,`${o};background-color: lightblue;color:black`,"",`${o};${r?`color:${r};`:""}${a?`background-color:${a}`:""}`,...s)}error(...t){this.print("error",...t)}log(...t){this.print("log",...t)}}const rt=new ks("SDK",{bgColor:"forestgreen",textColor:"white"});let st=!1;const kt=({event:e,args:[t]})=>{rt.log("Event received:",t===void 0?{name:e}:{name:e,data:t})};function Mt(e){st!==e&&(st=e,e?Dt(kt):it(kt))}function Is(...e){st&&rt.log(...e)}class ${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(n=>n({event:t,args:s})),(this.listeners.get(t)||[]).forEach(([n,i])=>{n(...s),i&&this.off(t,n)})}on(t,s,n){let i=this.listeners.get(t);return i||this.listeners.set(t,i=[]),i.push([s,n]),this.listenersCount+=1,()=>this.off(t,s)}off(t,s){const n=this.listeners.get(t)||[];for(let i=0;i<n.length;i+=1)if(s===n[i][0]){n.splice(i,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 nt(e,t,s){return window.addEventListener(e,t,s),()=>window.removeEventListener(e,t,s)}class L extends Error{constructor(t,s,n){super(s,{cause:n}),this.type=t,Object.setPrototypeOf(this,L.prototype)}}function b(e,t,s){return new L(e,t,s)}const Nt="ERR_METHOD_UNSUPPORTED",Vt="ERR_METHOD_PARAMETER_UNSUPPORTED",$t="ERR_UNKNOWN_ENV",Lt="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",Ut="ERR_TIMED_OUT",Ht="ERR_UNEXPECTED_TYPE",ot="ERR_PARSE",Wt="ERR_NAVIGATION_LIST_EMPTY",jt="ERR_NAVIGATION_CURSOR_INVALID",As="ERR_NAVIGATION_ITEM_INVALID",Bs="ERR_SSR_INIT",Gt="ERR_INVALID_PATH_BASE";function I(){return b(Ht,"Value has unexpected type")}class K{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 b(ot,`Unable to parse value${this.type?` as ${this.type}`:""}`,s)}}optional(){return this.isOptional=!0,this}}function A(e,t){return()=>new K(e,!1,t)}const P=A(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 I()},"boolean");function Kt(e,t){const s={};for(const n in e){const i=e[n];if(!i)continue;let r,a;if(typeof i=="function"||"parse"in i)r=n,a=typeof i=="function"?i:i.parse.bind(i);else{const{type:o}=i;r=i.from||n,a=typeof o=="function"?o:o.parse.bind(o)}try{const o=a(t(r));o!==void 0&&(s[n]=o)}catch(o){throw b(ot,`Unable to parse field "${n}"`,o)}}return s}function at(e){let t=e;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw I();return t}function d(e,t){return new K(s=>{const n=at(s);return Kt(e,i=>n[i])},!1,t)}const C=A(e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}throw I()},"number");function z(e){return/^#[\da-f]{6}$/i.test(e)}function zt(e){return/^#[\da-f]{3}$/i.test(e)}function ct(e){const t=e.replace(/\s/g,"").toLowerCase();if(z(t))return t;if(zt(t)){let n="#";for(let i=0;i<3;i+=1)n+=t[1+i].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,i)=>{const r=parseInt(i,10).toString(16);return n+(r.length===1?"0":"")+r},"#")}const u=A(e=>{if(typeof e=="string"||typeof e=="number")return e.toString();throw I()},"string"),ht=A(e=>ct(u().parse(e)),"rgb");function Os(e){return d({eventType:u(),eventData:t=>t}).parse(e)}function qs(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function Ds(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function Ms(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((s,n,i)=>{if(n===i.length-1){t[s]=Ds;return}s in t||(t[s]={}),t=t[s]})})}const Ns=d({button_id:e=>e==null?void 0:u().parse(e)}),Vs={clipboard_text_received:d({req_id:u(),data:e=>e===null?e:u().optional().parse(e)}),custom_method_invoked:d({req_id:u(),result:e=>e,error:u().optional()}),invoice_closed:d({slug:u(),status:u()}),phone_requested:d({status:u()}),popup_closed:{parse:e=>Ns.parse(e??{})},qr_text_received:d({data:u().optional()}),theme_changed:d({theme_params:e=>{const t=ht().optional();return Object.entries(at(e)).reduce((s,[n,i])=>(s[n]=t.parse(i),s),{})}}),viewport_changed:d({height:C(),width:e=>e==null?window.innerWidth:C().parse(e),is_state_stable:P(),is_expanded:P()}),write_access_requested:d({status:u()})};function $s(){const e=new $;Ms();let t=[qs,nt("resize",()=>{e.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),nt("message",s=>{if(s.source!==window.parent)return;let n;try{n=Os(s.data)}catch{return}const{eventType:i,eventData:r}=n,a=Vs[i];try{const o=a?a.parse(r):r;e.emit(...o?[i,o]:[i])}catch(o){rt.error(`An error occurred processing the "${i}" event from the Telegram application. Please, file an issue here: https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,n,o)}}),()=>e.clear()];return[e,()=>{t.forEach(s=>s()),t=[]}]}const[Ls,Us]=qt(e=>{const[t,s]=$s(),n=t.off.bind(t);return t.off=(i,r)=>{const{count:a}=t;n(i,r),a&&!t.count&&e()},[t,s]},([,e])=>e());function Q(){return Ls()[0]}function U(e,t){Q().off(e,t)}function y(e,t,s){return Q().on(e,t,s)}function H(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Qt(e,t){const s=e.split("."),n=t.split("."),i=Math.max(s.length,n.length);for(let r=0;r<i;r+=1){const a=parseInt(s[r]||"0",10),o=parseInt(n[r]||"0",10);if(a!==o)return a>o?1:-1}return 0}function R(e,t){return Qt(e,t)<=0}function x(e,t,s){if(typeof s=="string"){if(e==="web_app_open_link"&&t==="try_instant_view")return R("6.4",s);if(e==="web_app_set_header_color"&&t==="color")return R("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 R("6.1",t);case"web_app_open_popup":return R("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 R("6.4",t);case"web_app_switch_inline_query":return R("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return R("6.9",t);case"web_app_setup_settings_button":return R("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 R("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 Hs(e){return"external"in e&&H(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function Ft(e){return"TelegramWebviewProxy"in e&&H(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function ut(){try{return window.self!==window.top}catch{return!0}}let Jt="https://web.telegram.org";function Ws(e){Jt=e}function Yt(){return Jt}function k(e,t,s){let n={},i;t===void 0&&s===void 0?n={}:t!==void 0&&s!==void 0?(n=s,i=t):t!==void 0&&("targetOrigin"in t?n=t:i=t);const{targetOrigin:r=Yt()}=n;if(Is("Posting event:",i?{event:e,data:i}:{event:e}),ut()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:i}),r);return}if(Hs(window)){window.external.notify(JSON.stringify({eventType:e,eventData:i}));return}if(Ft(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(i));return}throw b($t,"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 Zt(e){return(t,s)=>{if(!x(t,e))throw b(Nt,`Method "${t}" is unsupported in Mini Apps version ${e}`);if(H(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&&!x(t,n,e))throw b(Vt,`Parameter "${n}" of "${t}" method is unsupported in Mini Apps version ${e}`)}return k(t,s)}}function pt(e){return({req_id:t})=>t===e}function Xt(e){return b(Ut,`Timeout reached: ${e}ms`)}function lt(e,t){return Promise.race([typeof e=="function"?e():e,new Promise((s,n)=>{setTimeout(()=>{n(Xt(t))},t)})])}async function _(e){let t;const s=new Promise(h=>{t=h}),{method:n,event:i,capture:r,postEvent:a=k,timeout:o}=e,p=(Array.isArray(i)?i:[i]).map(h=>y(h,E=>(!r||r(E))&&t(E)));try{return a(n,e.params),await(o?lt(s,o):s)}finally{p.forEach(h=>h())}}async function T(e,t,s,n={}){const{result:i,error:r}=await _({...n,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:e,params:t,req_id:s},capture:pt(s)});if(r)throw b(Lt,r);return i}function G(...e){return e.map(t=>{if(typeof t=="string")return t;if(H(t))return G(Object.entries(t).map(s=>s[1]&&s[0]));if(Array.isArray(t))return G(...t)}).filter(Boolean).join(" ")}function js(...e){return e.reduce((t,s)=>(H(s)&&Object.entries(s).forEach(([n,i])=>{const r=G(t[n],i);r.length&&(t[n]=r)}),t),{})}function dt(e){const t=ct(e);return Math.sqrt([.299,.587,.114].reduce((s,n,i)=>{const r=parseInt(t.slice(1+i*2,1+(i+1)*2),16);return s+r*r*n},0))<120}class Gs{constructor(t){c(this,"ee",new $),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((n,[i,r])=>this.state[i]===r||r===void 0?n:(this.state[i]=r,this.ee.emit(`change:${i}`,r),!0),!1)&&this.ee.emit("change",this.state)}get(t){return this.state[t]}}class _t{constructor(t){c(this,"state"),c(this,"get"),c(this,"set"),c(this,"clone"),this.state=new Gs(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 te(e,t){return s=>x(t[s],e)}class wt extends _t{constructor(t,s,n){super(t),c(this,"supports"),this.supports=te(s,n)}}class ee extends wt{constructor(t,s,n){super({isVisible:t},s,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"}),c(this,"on",(i,r)=>i==="click"?y("back_button_pressed",r):this.state.on(i,r)),c(this,"off",(i,r)=>i==="click"?U("back_button_pressed",r):this.state.off(i,r)),this.postEvent=n}set isVisible(t){this.set("isVisible",t),this.postEvent("web_app_setup_back_button",{is_visible:t})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const gt=A(e=>e instanceof Date?e:new Date(C().parse(e)*1e3),"Date");function F(e,t){return new K(s=>{if(typeof s!="string"&&!(s instanceof URLSearchParams))throw I();const n=typeof s=="string"?new URLSearchParams(s):s;return Kt(e,i=>{const r=n.get(i);return r===null?void 0:r})},!1,t)}const Ks=d({id:C(),type:u(),title:u(),photoUrl:{type:u().optional(),from:"photo_url"},username:u().optional()},"Chat").optional(),It=d({addedToAttachmentMenu:{type:P().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:P().optional(),from:"allows_write_to_pm"},firstName:{type:u(),from:"first_name"},id:C(),isBot:{type:P().optional(),from:"is_bot"},isPremium:{type:P().optional(),from:"is_premium"},languageCode:{type:u().optional(),from:"language_code"},lastName:{type:u().optional(),from:"last_name"},photoUrl:{type:u().optional(),from:"photo_url"},username:u().optional()},"User").optional();function se(){return F({authDate:{type:gt(),from:"auth_date"},canSendAfter:{type:C().optional(),from:"can_send_after"},chat:Ks,chatInstance:{type:u().optional(),from:"chat_instance"},chatType:{type:u().optional(),from:"chat_type"},hash:u(),queryId:{type:u().optional(),from:"query_id"},receiver:It,startParam:{type:u().optional(),from:"start_param"},user:It},"InitData")}function zs(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}function Qs(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}const ne=A(e=>{const t=ht().optional();return Object.entries(at(e)).reduce((s,[n,i])=>(s[zs(n)]=t.parse(i),s),{})},"ThemeParams");function ft(e){return F({botInline:{type:P().optional(),from:"tgWebAppBotInline"},initData:{type:se().optional(),from:"tgWebAppData"},initDataRaw:{type:u().optional(),from:"tgWebAppData"},platform:{type:u(),from:"tgWebAppPlatform"},showSettings:{type:P().optional(),from:"tgWebAppShowSettings"},startParam:{type:u().optional(),from:"tgWebAppStartParam"},themeParams:{type:ne(),from:"tgWebAppThemeParams"},version:{type:u(),from:"tgWebAppVersion"}}).parse(e)}function ie(e){return ft(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function Fs(){return ie(window.location.href)}function re(){return performance.getEntriesByType("navigation")[0]}function Js(){const e=re();if(!e)throw new Error("Unable to get first navigation entry.");return ie(e.name)}function oe(e){return`tma.js/${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function ae(e,t){sessionStorage.setItem(oe(e),JSON.stringify(t))}function ce(e){const t=sessionStorage.getItem(oe(e));try{return t?JSON.parse(t):void 0}catch{}}function Ys(){return ft(ce("launchParams")||"")}function he(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,s])=>[Qs(t),s])))}function ue(e){const{initDataRaw:t,themeParams:s,platform:n,version:i,showSettings:r,startParam:a,botInline:o}=e,p=new URLSearchParams;return p.set("tgWebAppPlatform",n),p.set("tgWebAppThemeParams",he(s)),p.set("tgWebAppVersion",i),t&&p.set("tgWebAppData",t),a&&p.set("tgWebAppStartParam",a),typeof r=="boolean"&&p.set("tgWebAppShowSettings",r?"1":"0"),typeof o=="boolean"&&p.set("tgWebAppBotInline",o?"1":"0"),p.toString()}function Zs(e){ae("launchParams",ue(e))}function mt(){for(const e of[Fs,Js,Ys])try{const t=e();return Zs(t),t}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}function bt(){const e=re();return!!(e&&e.type==="reload")}function Xs(){let e=0;return()=>(e+=1).toString()}function tn(){let e=!1;const t=[];return[s=>!e&&t.push(s),()=>{e||(e=!0,t.forEach(s=>s()))},e]}const[en]=qt(Xs);function w(e,t){return()=>{const s=mt(),n={...s,postEvent:Zt(s.version),createRequestId:en()};if(typeof e=="function")return e(n);const[i,r,a]=tn(),o=t({...n,state:bt()?ce(e):void 0,addCleanup:i}),p=h=>(a||i(h.on("change",E=>{ae(e,E)})),h);return[o instanceof Promise?o.then(p):p(o),r]}}const pe=w("backButton",({postEvent:e,version:t,state:s={isVisible:!1}})=>new ee(s.isVisible,t,e));class W extends wt{constructor(){super(...arguments),c(this,"on",this.state.on.bind(this.state)),c(this,"off",this.state.off.bind(this.state))}}function le(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 de extends W{constructor({postEvent:t,version:s,...n}){super(n,s,{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=t}get available(){return this.get("available")}get accessGranted(){return this.get("accessGranted")}get accessRequested(){return this.get("accessRequested")}async authenticate({reason:t,...s}){return this.authPromise||(this.authPromise=_({...s,method:"web_app_biometry_request_auth",event:"biometry_auth_requested",postEvent:this.postEvent,params:{reason:(t||"").trim()}}).then(({token:n})=>n).finally(()=>this.authPromise=void 0)),this.authPromise}get deviceId(){return this.get("deviceId")}openSettings(){this.postEvent("web_app_biometry_open_settings")}requestAccess({reason:t,...s}={}){return this.accessPromise||(this.accessPromise=_({...s,postEvent:this.postEvent,method:"web_app_biometry_request_access",event:"biometry_info_received",params:{reason:t||""}}).then(n=>{const i=le(n);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:t,...s}={}){return["removed","updated"].includes((await _({...s,postEvent:this.postEvent,method:"web_app_biometry_update_token",event:"biometry_token_updated",params:{token:t||""}})).status)}}async function _e(e){return le(await _({...e||{},method:"web_app_biometry_get_info",event:"biometry_info_received"}))}const we=w("biometryManager",async({postEvent:e,version:t,state:s})=>new de({...s||await _e({timeout:1e3}),version:t,postEvent:e}));class vt extends _t{constructor(){super(...arguments),c(this,"on",this.state.on.bind(this.state)),c(this,"off",this.state.off.bind(this.state))}}class ge extends vt{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 fe=w("closingBehavior",({postEvent:e,state:t={isConfirmationNeeded:!1}})=>new ge(t.isConfirmationNeeded,e));class yt{constructor(t,s){c(this,"supports"),this.supports=te(t,s)}}function sn(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 I()}class nn extends K{constructor(t,s,n){super(sn,s,n),c(this,"itemParser"),this.itemParser=typeof t=="function"?t:t.parse.bind(t)}parse(t){const s=super.parse(t);return s===void 0?s:s.map(this.itemParser)}of(t){return this.itemParser=typeof t=="function"?t:t.parse.bind(t),this}}function me(e){return new nn(t=>t,!1,e)}function At(e,t){return Object.fromEntries(e.map(s=>[s,t]))}class be extends yt{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 T("deleteStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent})}async getKeys(t={}){return me().of(u()).parse(await T("getStorageKeys",{},this.createRequestId(),{...t,postEvent:this.postEvent}))}async get(t,s={}){const n=Array.isArray(t)?t:[t];if(!n.length)return At(n,"");const i=await T("getStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent}),r=d(At(n,u()),"CloudStorageData").parse(i);return Array.isArray(t)?r:r[t]}async set(t,s,n={}){await T("saveStorageValue",{key:t,value:s},this.createRequestId(),{...n,postEvent:this.postEvent})}}const ve=w(({createRequestId:e,postEvent:t,version:s})=>new be(s,e,t));class ye extends yt{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 Ee=w(({version:e,postEvent:t})=>new ye(e,t));class Re{constructor(t){this.initData=t}get authDate(){return this.initData.authDate}get canSendAfter(){return this.initData.canSendAfter}get canSendAfterDate(){const{canSendAfter:t}=this;return t?new Date(this.authDate.getTime()+t*1e3):void 0}get chat(){return this.initData.chat}get chatType(){return this.initData.chatType}get chatInstance(){return this.initData.chatInstance}get hash(){return this.initData.hash}get queryId(){return this.initData.queryId}get receiver(){return this.initData.receiver}get startParam(){return this.initData.startParam}get user(){return this.initData.user}}const Pe=w(({initData:e})=>e?new Re(e):void 0);function rn(e){return se().parse(e)}class Se extends W{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:i,pathname:r}=new URL(t,window.location.href);if(i!=="t.me")throw new Error(`Incorrect hostname: ${i}`);const a=r.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!a)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');[,,n]=a}this.isOpened=!0;try{return(await _({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 Ce=w(({version:e,postEvent:t})=>new Se(!1,e,t));class xe extends _t{constructor({postEvent:t,...s}){super(s),c(this,"postEvent"),c(this,"on",(n,i)=>n==="click"?y("main_button_pressed",i):this.state.on(n,i)),c(this,"off",(n,i)=>n==="click"?U("main_button_pressed",i):this.state.off(n,i)),this.postEvent=t}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.backgroundColor,text_color:this.textColor})}set isEnabled(t){this.setParams({isEnabled:t})}get isEnabled(){return this.get("isEnabled")}set isLoaderVisible(t){this.setParams({isLoaderVisible:t})}get isLoaderVisible(){return this.get("isLoaderVisible")}set isVisible(t){this.setParams({isVisible:t})}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(t){return this.setParams({text:t})}setTextColor(t){return this.setParams({textColor:t})}setBackgroundColor(t){return this.setParams({backgroundColor:t})}setParams(t){return this.set(t),this.commit(),this}}const Te=w("mainButton",({postEvent:e,themeParams:t,state:s={isVisible:!1,isEnabled:!1,text:"",isLoaderVisible:!1,textColor:t.buttonTextColor||"#ffffff",backgroundColor:t.buttonColor||"#000000"}})=>new xe({...s,postEvent:e}));function on(){return F({contact:d({userId:{type:C(),from:"user_id"},phoneNumber:{type:u(),from:"phone_number"},firstName:{type:u(),from:"first_name"},lastName:{type:u().optional(),from:"last_name"}}),authDate:{type:gt(),from:"auth_date"},hash:u()},"RequestedContact")}function ke(e,t){return s=>{const[n,i]=t[s];return x(n,i,e)}}function an(e){return new Promise(t=>{setTimeout(t,e)})}class Ie extends W{constructor({postEvent:t,createRequestId:s,version:n,botInline:i,...r}){super(r,n,{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=s,this.postEvent=t,this.botInline=i;const a=this.supports.bind(this);this.supports=o=>a(o)?o!=="switchInlineQuery"||i:!1,this.supportsParam=ke(n,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact({timeout:t=1e4}={}){return on().parse(await T("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:t}))}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 dt(this.bgColor)}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:t=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const s=Date.now()+t;let n=50;return lt(async()=>{for(;Date.now()<s;){try{return await this.getRequestedContact()}catch{}await an(n),n+=50}throw Xt(t)},t)}async requestPhoneAccess(t={}){return this.requestPhoneAccessPromise||(this.requestPhoneAccessPromise=_({...t,method:"web_app_request_phone",event:"phone_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestPhoneAccessPromise=void 0)),this.requestPhoneAccessPromise}async requestWriteAccess(t={}){return this.requestWriteAccessPromise||(this.requestWriteAccessPromise=_({...t,method:"web_app_request_write_access",event:"write_access_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestWriteAccessPromise=void 0)),this.requestWriteAccessPromise}sendData(t){const{size:s}=new Blob([t]);if(!s||s>4096)throw new Error(`Passed data has incorrect size: ${s}`);this.postEvent("web_app_data_send",{data:t})}setHeaderColor(t){this.postEvent("web_app_set_header_color",z(t)?{color:t}:{color_key:t}),this.set("headerColor",t)}setBgColor(t){this.postEvent("web_app_set_background_color",{color:t}),this.set("bgColor",t)}switchInlineQuery(t,s=[]){if(!this.supports("switchInlineQuery")&&!this.isBotInline)throw new Error("Method is unsupported because Mini App should be launched in inline mode.");this.postEvent("web_app_switch_inline_query",{query:t,chat_types:s})}}const Ae=w("miniApp",({themeParams:e,botInline:t=!1,state:s={bgColor:e.bgColor||"#ffffff",headerColor:e.headerBgColor||"#000000"},...n})=>new Ie({...n,...s,botInline:t}));function cn(e){const t=e.message.trim(),s=(e.title||"").trim(),n=e.buttons||[];let i;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?i=n.map(r=>{const{id:a=""}=r;if(a.length>64)throw new Error(`Button ID has incorrect size: ${a}`);if(!r.type||r.type==="default"||r.type==="destructive"){const o=r.text.trim();if(!o.length||o.length>64){const p=r.type||"default";throw new Error(`Button text with type "${p}" has incorrect size: ${r.text.length}`)}return{...r,text:o,id:a}}return{...r,id:a}}):i=[{type:"close",id:""}],{title:s,message:t,buttons:i}}class Be extends W{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 _({event:"popup_closed",method:"web_app_open_popup",postEvent:this.postEvent,params:cn(t)});return s}finally{this.isOpened=!1}}}const Oe=w(({postEvent:e,version:t})=>new Be(!1,t,e));class qe extends W{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 _({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 De=w(({version:e,postEvent:t})=>new qe(!1,e,t));class Me extends wt{constructor(t,s,n){super({isVisible:t},s,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"}),c(this,"on",(i,r)=>i==="click"?y("settings_button_pressed",r):this.state.on(i,r)),c(this,"off",(i,r)=>i==="click"?U("settings_button_pressed",r):this.state.off(i,r)),this.postEvent=n}set isVisible(t){this.set("isVisible",t),this.postEvent("web_app_setup_settings_button",{is_visible:t})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const Ne=w("settingsButton",({version:e,postEvent:t,state:s={isVisible:!1}})=>new Me(s.isVisible,e,t));function Et(e){return ne().parse(e)}class Ve extends vt{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||dt(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 y("theme_changed",t=>{this.set(Et(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}const $e=w("themeParams",({themeParams:e,state:t=e,addCleanup:s})=>{const n=new Ve(t);return s(n.listen()),n});function hn(e={}){return _({...e,method:"web_app_request_theme",event:"theme_changed"}).then(Et)}class Le extends yt{constructor(t,s,n){super(t,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),c(this,"supportsParam"),this.version=t,this.createRequestId=s,this.postEvent=n,this.supportsParam=ke(t,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(t,s){const n=new URL(t,window.location.href).toString();if(!x("web_app_open_link",this.version)){window.open(n,"_blank");return}this.postEvent("web_app_open_link",{url:n,...typeof s=="boolean"?{try_instant_view:s}:{}})}openTelegramLink(t){const{hostname:s,pathname:n,search:i}=new URL(t,window.location.href);if(s!=="t.me")throw new Error(`URL has not allowed hostname: ${s}. Only "t.me" is allowed`);if(!x("web_app_open_tg_link",this.version)){window.location.href=t;return}this.postEvent("web_app_open_tg_link",{path_full:n+i})}async readTextFromClipboard(){const t=this.createRequestId(),{data:s=null}=await _({method:"web_app_read_text_from_clipboard",event:"clipboard_text_received",postEvent:this.postEvent,params:{req_id:t},capture:pt(t)});return s}}const Ue=w(({version:e,postEvent:t,createRequestId:s})=>new Le(e,s,t));async function Rt(e={}){const{is_expanded:t,is_state_stable:s,...n}=await _({...e,method:"web_app_request_viewport",event:"viewport_changed"});return{...n,isExpanded:t,isStateStable:s}}function q(e){return e<0?0:e}class He extends vt{constructor({postEvent:t,stableHeight:s,height:n,width:i,isExpanded:r}){super({height:q(n),isExpanded:r,stableHeight:q(s),width:q(i)}),c(this,"postEvent"),this.postEvent=t}async sync(t){const{isStateStable:s,...n}=await Rt(t);this.set({...n,stableHeight:s?n.height:this.get("stableHeight")})}get height(){return this.get("height")}get stableHeight(){return this.get("stableHeight")}listen(){return y("viewport_changed",t=>{const{height:s,width:n,is_expanded:i,is_state_stable:r}=t,a=q(s);this.set({height:a,isExpanded:i,width:q(n),...r?{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}}const We=w("viewport",async({state:e,platform:t,postEvent:s,addCleanup:n})=>{let i=!1,r=0,a=0,o=0;if(e)i=e.isExpanded,r=e.height,a=e.width,o=e.stableHeight;else if(["macos","tdesktop","unigram","webk","weba","web"].includes(t))i=!0,r=window.innerHeight,a=window.innerWidth,o=window.innerHeight;else{const h=await Rt({timeout:1e3,postEvent:s});i=h.isExpanded,r=h.height,a=h.width,o=h.isStateStable?r:0}const p=new He({postEvent:s,height:r,width:a,stableHeight:o,isExpanded:i});return n(p.listen()),p});function S(e,t){document.documentElement.style.setProperty(e,t)}function un(e,t,s){s||(s=o=>`--tg-${o}-color`);const n=s("header"),i=s("bg"),r=()=>{const{headerColor:o}=e;if(z(o))S(n,o);else{const{bgColor:p,secondaryBgColor:h}=t;o==="bg_color"&&p?S(n,p):o==="secondary_bg_color"&&h&&S(n,h)}S(i,e.bgColor)},a=[t.on("change",r),e.on("change",r)];return r(),()=>a.forEach(o=>o())}function pn(e,t){t||(t=n=>`--tg-theme-${n.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`)}`);const s=()=>{Object.entries(e.getState()).forEach(([n,i])=>{i&&S(t(n),i)})};return s(),e.on("change",s)}function ln(e,t){t||(t=h=>`--tg-viewport-${h}`);const[s,n,i]=["height","width","stable-height"].map(h=>t(h)),r=()=>S(s,`${e.height}px`),a=()=>S(n,`${e.width}px`),o=()=>S(i,`${e.stableHeight}px`),p=[e.on("change:height",r),e.on("change:width",a),e.on("change:stableHeight",o)];return r(),a(),o(),()=>p.forEach(h=>h())}function je(e=!0){const t=[y("reload_iframe",()=>{k("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(y("set_custom_style",i=>{n.innerHTML=i}),()=>document.head.removeChild(n))}return k("iframe_ready",{reload_supported:!0}),s}function Ge(){return typeof window>"u"}async function dn(){if(Ft(window))return!0;try{return await _({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function Ke(e){return e instanceof L}function _n(e,t){return Ke(e)&&e.type===t}function Y(e,t){let s,n,i;return typeof e=="string"?s=e:(s=e.pathname===void 0?t:e.pathname,n=e.params,i=e.id),Object.freeze({id:i||(Math.random()*2**14|0).toString(16),pathname:s,params:n})}class ze{constructor(t,s,n=k){if(c(this,"history"),c(this,"ee",new $),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)),this._index=s,this.postEvent=n,t.length===0)throw b(Wt,"History should not be empty.");if(s<0||s>=t.length)throw b(jt,"Index should not be zero and higher or equal than history size.");this.history=t.map(i=>Y(i,""))}attach(){this.attached||(this.attached=!0,this.sync(),y("back_button_pressed",this.back))}get current(){return this.history[this.index]}detach(){this.attached=!1,U("back_button_pressed",this.back)}forward(){this.go(1)}go(t,s){const n=this.index+t,i=Math.min(Math.max(0,n),this.history.length-1);(n===i||s)&&this.replaceAndMove(i,this.history[i])}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,Y(t,this.current.pathname))}replace(t){this.replaceAndMove(this.index,Y(t,this.current.pathname))}replaceAndMove(t,s){const n=t-this.index;if(!n&&this.current===s)return;const i=this.current;if(this.index!==t){const r=this._index;this._index=t,this.attached&&r>0!=t>0&&this.sync()}this.history[t]=s,this.ee.emit("change",{navigator:this,from:i,to:this.current,delta:n})}sync(){this.postEvent("web_app_setup_back_button",{is_visible:!!this.index})}}function Z({params:e,...t}){return{...e||{hash:"",search:""},...t}}function M(e,t){return e.startsWith(t)?e:`${t}${e}`}function N(e){return new URL(typeof e=="string"?e:`${e.pathname||""}${M(e.search||"","?")}${M(e.hash||"","#")}`,"http://a")}function V(e){const t=typeof e=="string"?e.startsWith("/"):!!(e.pathname&&e.pathname.startsWith("/")),s=N(e);return`${t?s.pathname:s.pathname.slice(1)}${s.search}${s.hash}`}function X(e,t,s){let n,i;typeof e=="string"?n=e:(n=V(e),s=e.state,i=e.id);const{pathname:r,search:a,hash:o}=new URL(n,`http://a${M(t,"/")}`);return{id:i,pathname:r,params:{hash:o,search:a,state:s}}}async function D(e){return e===0?!0:Promise.race([new Promise(t=>{const s=nt("popstate",()=>{s(),t(!0)});window.history.go(e)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function wn(){if(window.history.length<=1||(window.history.pushState(null,""),await D(1-window.history.length)))return;let e=await D(-1);for(;e;)e=await D(-1)}function Pt(e){return N(e).pathname}const Bt=0,tt=1,et=2;class St{constructor(t,s,{postEvent:n,hashMode:i="classic",base:r}={}){c(this,"navigator"),c(this,"ee",new $),c(this,"hashMode"),c(this,"base"),c(this,"attached",!1),c(this,"onPopState",({state:a})=>{if(a===null)return this.push(this.parsePath(window.location.href));a===Bt?window.history.forward():a===tt&&this.back(),a===et&&this.forward()}),c(this,"onNavigatorChange",async({to:a,from:o,delta:p})=>{this.attached&&await this.syncHistory(),this.ee.emit("change",{delta:p,from:Z(o),to:Z(a),navigator:this})}),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this.navigator=new ze(t.map(a=>X(a,"/")),s,n),this.navigator.on("change",this.onNavigatorChange),this.hashMode=i,this.base=Pt(r||"")}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(Z)}get path(){return V(this)}get pathname(){return this.navigator.current.pathname}parsePath(t){let s=N(t);return this.hashMode&&(s=N(s.hash.slice(1))),{pathname:s.pathname,search:s.search,hash:s.hash}}push(t,s){const n=X(t,this.path),{state:i=s}=n.params;this.navigator.push({...n,params:{...n.params,state:i}})}replace(t,s){const n=X(t,this.path),{state:i=s}=n.params;this.navigator.replace({...n,params:{...n.params,state:i}})}renderPath(t){const s=(this.base.length===1?"":this.base)+M(V(t),"/");return this.hashMode?M(s.slice(1),this.hashMode==="classic"?"#":"#/"):s}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const{state:t}=this,s=this.renderPath(this);await wn(),this.hasPrev&&this.hasNext?(window.history.replaceState(tt,""),window.history.pushState(t,"",s),window.history.pushState(et,""),await D(-1)):this.hasPrev?(window.history.replaceState(tt,""),window.history.pushState(t,"",s)):this.hasNext?(window.history.replaceState(t,s),window.history.pushState(et,""),await D(-1)):(window.history.replaceState(Bt,""),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 Qe(e){e||(e={});const{href:t,hash:s}=window.location;let n=V(e.hashMode===null?t:s.includes("?")?s.slice(1):`?${s.slice(1)}`);const i=e.base?Pt(e.base):void 0;if(i){if(!n.startsWith(i))throw b(Gt,`Path "${n}" expected to be starting with "${i}"`);n=n.slice(i.length)}return new St([n],0,e)}function gn(e){const t=e.match(/#(.+)/);return t?t[1]:null}function fn(e,t){if(bt()){const s=sessionStorage.getItem(e);if(s)try{const{index:n,history:i}=JSON.parse(s);return new St(i,n,t)}catch(n){console.error("Unable to restore hash navigator state.",n)}}return Qe(t)}function mn(e,t){const s=fn(e,t),n=()=>sessionStorage.setItem(e,JSON.stringify({index:s.index,history:s.history}));return s.on("change",n),n(),s}function g(e,t){function s(n){return(i,r,a)=>o=>{const p=o[r]||[],h={...o,[i]:n(...p)};return Ot.jsx(a,{...h})}}return[s(e),s(t)]}const Fe=l.createContext(void 0);function Je(){const e=l.useContext(Fe);if(!e)throw new Error("useSDK was used outside the SDKProvider.");return e}function f(e){function t(n){const i=Je(),[r,a]=l.useState(n?void 0:()=>{if(Ge())throw new Error("Using hooks on the server side, you must explicitly specify ssr = true option");return i.use(e)});return l.useEffect(()=>{a(i.use(e))},[i]),r}function s(n){const i=t(n);if(i){if("error"in i)throw i.error;return i.result}}return[t,s]}const[Ye,Ze]=f(pe),[bn,vn]=g(Ye,Ze),[Xe,ts]=f(we),[yn,En]=g(Xe,ts),[es,ss]=f(fe),[Rn,Pn]=g(es,ss),[ns,is]=f(ve),[Sn,Cn]=g(ns,is),[rs,os]=f(Ee),[xn,Tn]=g(rs,os),[as,cs]=f(Pe),[kn,In]=g(as,cs),[hs,us]=f(Ce),[An,Bn]=g(hs,us),[ps,ls]=f(Te),[On,qn]=g(ps,ls),[ds,_s]=f(Ae),[Dn,Mn]=g(ds,_s),[ws,gs]=f(Oe),[Nn,Vn]=g(ws,gs),[fs,ms]=f(De),[$n,Ln]=g(fs,ms),[bs,vs]=f(Ne),[Un,Hn]=g(bs,vs),[ys,Es]=f($e),[Wn,jn]=g(ys,Es);function Gn(){return l.useMemo(mt,[])}const[Rs,Ps]=f(Ue),[Kn,zn]=g(Rs,Ps),[Ss,Cs]=f(We),[Qn,Fn]=g(Ss,Cs);function Jn({children:e,acceptCustomStyles:t,debug:s}){const n=l.useRef(!0),[i,r]=l.useState(new Map),a=l.useRef(i),o=l.useCallback(h=>{n.current&&r(E=>(h&&h(E),new Map(E)))},[]),p=l.useMemo(()=>({use(h,...E){const Ct=i.get(h);if(Ct)return Ct;let v,J;try{v=h(...E)}catch(m){J=m}function j(m){return i.set(h,m),m}if(J)return j({error:J});let B;if(Array.isArray(v)&&(B=v[1],v=v[0]),!v)return j({result:v,cleanup:B});function xt(m){if("on"in m){const O=m.on("change",()=>o()),Tt=B;B=()=>{Tt&&Tt(),O()}}return{result:m,cleanup:B}}return v instanceof Promise?(v.then(m=>o(O=>O.set(h,xt(m))),m=>o(O=>O.set(h,{error:m}))),j({})):j(xt(v))}}),[i]);return l.useEffect(()=>(n.current=!0,()=>{n.current=!1}),[]),l.useEffect(()=>{if(ut())return je(t)},[t]),l.useEffect(()=>{Mt(s||!1)},[s]),l.useEffect(()=>{a.current=i},[i]),l.useEffect(()=>()=>{a.current.forEach(h=>{"cleanup"in h&&h.cleanup&&h.cleanup()})},[]),Ot.jsx(Fe.Provider,{value:p,children:e})}exports.BackButton=ee;exports.BasicNavigator=ze;exports.BiometryManager=de;exports.BrowserNavigator=St;exports.ClosingBehavior=ge;exports.CloudStorage=be;exports.ERR_INVALID_PATH_BASE=Gt;exports.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=Lt;exports.ERR_METHOD_PARAMETER_UNSUPPORTED=Vt;exports.ERR_METHOD_UNSUPPORTED=Nt;exports.ERR_NAVIGATION_HISTORY_EMPTY=Wt;exports.ERR_NAVIGATION_INDEX_INVALID=jt;exports.ERR_NAVIGATION_ITEM_INVALID=As;exports.ERR_PARSE=ot;exports.ERR_SSR_INIT=Bs;exports.ERR_TIMED_OUT=Ut;exports.ERR_UNEXPECTED_TYPE=Ht;exports.ERR_UNKNOWN_ENV=$t;exports.EventEmitter=$;exports.HapticFeedback=ye;exports.InitData=Re;exports.Invoice=Se;exports.MainButton=xe;exports.MiniApp=Ie;exports.Popup=Be;exports.QRScanner=qe;exports.SDKError=L;exports.SDKProvider=Jn;exports.SettingsButton=Me;exports.ThemeParams=Ve;exports.Utils=Le;exports.Viewport=He;exports.array=me;exports.bindMiniAppCSSVars=un;exports.bindThemeParamsCSSVars=pn;exports.bindViewportCSSVars=ln;exports.boolean=P;exports.captureSameReq=pt;exports.classNames=G;exports.compareVersions=Qt;exports.createBrowserNavigatorFromLocation=Qe;exports.createPostEvent=Zt;exports.createSafeURL=N;exports.date=gt;exports.getHash=gn;exports.getPathname=Pt;exports.initBackButton=pe;exports.initBiometryManager=we;exports.initClosingBehavior=fe;exports.initCloudStorage=ve;exports.initHapticFeedback=Ee;exports.initInitData=Pe;exports.initInvoice=Ce;exports.initMainButton=Te;exports.initMiniApp=Ae;exports.initNavigator=mn;exports.initPopup=Oe;exports.initQRScanner=De;exports.initSettingsButton=Ne;exports.initThemeParams=$e;exports.initUtils=Ue;exports.initViewport=We;exports.initWeb=je;exports.invokeCustomMethod=T;exports.isColorDark=dt;exports.isIframe=ut;exports.isPageReload=bt;exports.isRGB=z;exports.isRGBShort=zt;exports.isSDKError=Ke;exports.isSDKErrorOfType=_n;exports.isSSR=Ge;exports.isTMA=dn;exports.json=d;exports.mergeClassNames=js;exports.number=C;exports.off=U;exports.on=y;exports.parseInitData=rn;exports.parseLaunchParams=ft;exports.parseThemeParams=Et;exports.postEvent=k;exports.request=_;exports.requestBiometryInfo=_e;exports.requestThemeParams=hn;exports.requestViewport=Rt;exports.retrieveLaunchParams=mt;exports.rgb=ht;exports.searchParams=F;exports.serializeLaunchParams=ue;exports.serializeThemeParams=he;exports.setCSSVar=S;exports.setDebug=Mt;exports.setTargetOrigin=Ws;exports.string=u;exports.subscribe=Dt;exports.supports=x;exports.targetOrigin=Yt;exports.toRGB=ct;exports.unsubscribe=it;exports.urlToPath=V;exports.useBackButton=Ze;exports.useBackButtonRaw=Ye;exports.useBiometryManager=ts;exports.useBiometryManagerRaw=Xe;exports.useClosingBehavior=ss;exports.useClosingBehaviorRaw=es;exports.useCloudStorage=is;exports.useCloudStorageRaw=ns;exports.useHapticFeedback=os;exports.useHapticFeedbackRaw=rs;exports.useInitData=cs;exports.useInitDataRaw=as;exports.useInvoice=us;exports.useInvoiceRaw=hs;exports.useLaunchParams=Gn;exports.useMainButton=ls;exports.useMainButtonRaw=ps;exports.useMiniApp=_s;exports.useMiniAppRaw=ds;exports.usePopup=gs;exports.usePopupRaw=ws;exports.useQRScanner=ms;exports.useQRScannerRaw=fs;exports.useSDK=Je;exports.useSettingsButton=vs;exports.useSettingsButtonRaw=bs;exports.useThemeParams=Es;exports.useThemeParamsRaw=ys;exports.useUtils=Ps;exports.useUtilsRaw=Rs;exports.useViewport=Cs;exports.useViewportRaw=Ss;exports.withBackButton=vn;exports.withBackButtonRaw=bn;exports.withBiometryManager=En;exports.withBiometryManagerRaw=yn;exports.withClosingBehavior=Pn;exports.withClosingBehaviorRaw=Rn;exports.withCloudStorage=Cn;exports.withCloudStorageRaw=Sn;exports.withHapticFeedback=Tn;exports.withHapticFeedbackRaw=xn;exports.withInitData=In;exports.withInitDataRaw=kn;exports.withInvoice=Bn;exports.withInvoiceRaw=An;exports.withMainButton=qn;exports.withMainButtonRaw=On;exports.withMiniApp=Mn;exports.withMiniAppRaw=Dn;exports.withPopup=Vn;exports.withPopupRaw=Nn;exports.withQRScanner=Ln;exports.withQRScannerRaw=$n;exports.withSettingsButton=Hn;exports.withSettingsButtonRaw=Un;exports.withThemeParams=jn;exports.withThemeParamsRaw=Wn;exports.withTimeout=lt;exports.withUtils=zn;exports.withUtilsRaw=Kn;exports.withViewport=Fn;exports.withViewportRaw=Qn;
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const Dt=require("react/jsx-runtime"),l=require("react");var qs=Object.defineProperty,Bs=(e,t,s)=>t in e?qs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,c=(e,t,s)=>(Bs(e,typeof t!="symbol"?t+"":t,s),s);function Mt(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 at(e){const t=F(),{count:s}=t;t.unsubscribe(e),s&&!t.count&&Ws()}function Nt(e){return F().subscribe(e),()=>at(e)}class Os{constructor(t,s={}){this.scope=t,this.options=s}print(t,...s){const n=new Date,i=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n),{textColor:r,bgColor:o}=this.options,a="font-weight: bold;padding: 0 5px;border-radius:5px";console[t](`%c${i}%c / %c${this.scope}`,`${a};background-color: lightblue;color:black`,"",`${a};${r?`color:${r};`:""}${o?`background-color:${o}`:""}`,...s)}error(...t){this.print("error",...t)}log(...t){this.print("log",...t)}}const ct=new Os("SDK",{bgColor:"forestgreen",textColor:"white"});let it=!1;const kt=({name:e,payload:t})=>{ct.log("Event received:",t?{name:e,payload:t}:{name:e})};function Vt(e){it!==e&&(it=e,e?Nt(kt):at(kt))}function Ds(...e){it&&ct.log(...e)}class I{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(n=>n({event:t,args:s})),(this.listeners.get(t)||[]).forEach(([n,i])=>{n(...s),i&&this.off(t,n)})}on(t,s,n){let i=this.listeners.get(t);return i||this.listeners.set(t,i=[]),i.push([s,n]),this.listenersCount+=1,()=>this.off(t,s)}off(t,s){const n=this.listeners.get(t)||[];for(let i=0;i<n.length;i+=1)if(s===n[i][0]){n.splice(i,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 rt(e,t,s){return window.addEventListener(e,t,s),()=>window.removeEventListener(e,t,s)}function $t(...e){let t=!1;const s=[...e];return[n=>!t&&s.push(n),()=>{t||(t=!0,s.forEach(n=>n()))},t]}class L extends Error{constructor(t,s,n){super(s,{cause:n}),this.type=t,Object.setPrototypeOf(this,L.prototype)}}function b(e,t,s){return new L(e,t,s)}const Lt="ERR_METHOD_UNSUPPORTED",Ht="ERR_METHOD_PARAMETER_UNSUPPORTED",Ut="ERR_UNKNOWN_ENV",Wt="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",jt="ERR_TIMED_OUT",Gt="ERR_UNEXPECTED_TYPE",ht="ERR_PARSE",Kt="ERR_NAVIGATION_LIST_EMPTY",zt="ERR_NAVIGATION_CURSOR_INVALID",Ms="ERR_NAVIGATION_ITEM_INVALID",Ns="ERR_SSR_INIT",Ft="ERR_INVALID_PATH_BASE";function k(){return b(Gt,"Value has unexpected type")}class K{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 b(ht,`Unable to parse value${this.type?` as ${this.type}`:""}`,s)}}optional(){return this.isOptional=!0,this}}function q(e,t){return()=>new K(e,!1,t)}const P=q(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 k()},"boolean");function Qt(e,t){const s={};for(const n in e){const i=e[n];if(!i)continue;let r,o;if(typeof i=="function"||"parse"in i)r=n,o=typeof i=="function"?i:i.parse.bind(i);else{const{type:a}=i;r=i.from||n,o=typeof a=="function"?a:a.parse.bind(a)}try{const a=o(t(r));a!==void 0&&(s[n]=a)}catch(a){throw b(ht,`Unable to parse field "${n}"`,a)}}return s}function ut(e){let t=e;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw k();return t}function d(e,t){return new K(s=>{const n=ut(s);return Qt(e,i=>n[i])},!1,t)}const C=q(e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}throw k()},"number");function z(e){return/^#[\da-f]{6}$/i.test(e)}function Jt(e){return/^#[\da-f]{3}$/i.test(e)}function pt(e){const t=e.replace(/\s/g,"").toLowerCase();if(z(t))return t;if(Jt(t)){let n="#";for(let i=0;i<3;i+=1)n+=t[1+i].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,i)=>{const r=parseInt(i,10).toString(16);return n+(r.length===1?"0":"")+r},"#")}const u=q(e=>{if(typeof e=="string"||typeof e=="number")return e.toString();throw k()},"string"),lt=q(e=>pt(u().parse(e)),"rgb");function Yt(e){return d({eventType:u(),eventData:t=>t}).parse(e)}function Vs(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function ot(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function $s(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((s,n,i)=>{if(n===i.length-1){t[s]=ot;return}s in t||(t[s]={}),t=t[s]})})}const Ls={clipboard_text_received:d({req_id:u(),data:e=>e===null?e:u().optional().parse(e)}),custom_method_invoked:d({req_id:u(),result:e=>e,error:u().optional()}),invoice_closed:d({slug:u(),status:u()}),phone_requested:d({status:u()}),popup_closed:{parse(e){return d({button_id:t=>t==null?void 0:u().parse(t)}).parse(e??{})}},qr_text_received:d({data:u().optional()}),theme_changed:d({theme_params:e=>{const t=lt().optional();return Object.entries(ut(e)).reduce((s,[n,i])=>(s[n]=t.parse(i),s),{})}}),viewport_changed:d({height:C(),width:e=>e==null?window.innerWidth:C().parse(e),is_state_stable:P(),is_expanded:P()}),write_access_requested:d({status:u()})};function Hs(){const e=new I,t=new I;t.subscribe(n=>{e.emit("event",{name:n.event,payload:n.args[0]})}),$s();const[,s]=$t(Vs,rt("resize",()=>{t.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),rt("message",n=>{if(n.source!==window.parent)return;let i;try{i=Yt(n.data)}catch{return}const{eventType:r,eventData:o}=i,a=Ls[r];try{const p=a?a.parse(o):o;t.emit(...p?[r,p]:[r])}catch(p){ct.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`,i,p)}}),()=>e.clear(),()=>t.clear());return[{on:t.on.bind(t),off:t.off.bind(t),subscribe(n){return e.on("event",n)},unsubscribe(n){e.off("event",n)},get count(){return t.count+e.count}},s]}const[Us,Ws]=Mt(e=>{const[t,s]=Hs(),n=t.off.bind(t);return t.off=(i,r)=>{const{count:o}=t;n(i,r),o&&!t.count&&e()},[t,s]},([,e])=>e());function F(){return Us()[0]}function H(e,t){F().off(e,t)}function y(e,t,s){return F().on(e,t,s)}function U(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zt(e,t){const s=e.split("."),n=t.split("."),i=Math.max(s.length,n.length);for(let r=0;r<i;r+=1){const o=parseInt(s[r]||"0",10),a=parseInt(n[r]||"0",10);if(o!==a)return o>a?1:-1}return 0}function R(e,t){return Zt(e,t)<=0}function x(e,t,s){if(typeof s=="string"){if(e==="web_app_open_link"&&t==="try_instant_view")return R("6.4",s);if(e==="web_app_set_header_color"&&t==="color")return R("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 R("6.1",t);case"web_app_open_popup":return R("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 R("6.4",t);case"web_app_switch_inline_query":return R("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return R("6.9",t);case"web_app_setup_settings_button":return R("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 R("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 Xt(e){return"external"in e&&U(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function te(e){return"TelegramWebviewProxy"in e&&U(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function Q(){try{return window.self!==window.top}catch{return!0}}let ee="https://web.telegram.org";function js(e){ee=e}function se(){return ee}function A(e,t,s){let n={},i;t===void 0&&s===void 0?n={}:t!==void 0&&s!==void 0?(n=s,i=t):t!==void 0&&("targetOrigin"in t?n=t:i=t);const{targetOrigin:r=se()}=n;if(Ds("Posting event:",i?{event:e,data:i}:{event:e}),Q()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:i}),r);return}if(Xt(window)){window.external.notify(JSON.stringify({eventType:e,eventData:i}));return}if(te(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(i));return}throw b(Ut,"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 ne(e){return(t,s)=>{if(!x(t,e))throw b(Lt,`Method "${t}" is unsupported in Mini Apps version ${e}`);if(U(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&&!x(t,n,e))throw b(Ht,`Parameter "${n}" of "${t}" method is unsupported in Mini Apps version ${e}`)}return A(t,s)}}function dt(e){return({req_id:t})=>t===e}function ie(e){return b(jt,`Timeout reached: ${e}ms`)}function _t(e,t){return Promise.race([typeof e=="function"?e():e,new Promise((s,n)=>{setTimeout(()=>{n(ie(t))},t)})])}async function _(e){let t;const s=new Promise(h=>{t=h}),{method:n,event:i,capture:r,postEvent:o=A,timeout:a}=e,p=(Array.isArray(i)?i:[i]).map(h=>y(h,E=>(!r||r(E))&&t(E)));try{return o(n,e.params),await(a?_t(s,a):s)}finally{p.forEach(h=>h())}}async function T(e,t,s,n={}){const{result:i,error:r}=await _({...n,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:e,params:t,req_id:s},capture:dt(s)});if(r)throw b(Wt,r);return i}function G(...e){return e.map(t=>{if(typeof t=="string")return t;if(U(t))return G(Object.entries(t).map(s=>s[1]&&s[0]));if(Array.isArray(t))return G(...t)}).filter(Boolean).join(" ")}function Gs(...e){return e.reduce((t,s)=>(U(s)&&Object.entries(s).forEach(([n,i])=>{const r=G(t[n],i);r.length&&(t[n]=r)}),t),{})}function wt(e){const t=pt(e);return Math.sqrt([.299,.587,.114].reduce((s,n,i)=>{const r=parseInt(t.slice(1+i*2,1+(i+1)*2),16);return s+r*r*n},0))<120}class Ks{constructor(t){c(this,"ee",new I),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((n,[i,r])=>this.state[i]===r||r===void 0?n:(this.state[i]=r,this.ee.emit(`change:${i}`,r),!0),!1)&&this.ee.emit("change",this.state)}get(t){return this.state[t]}}class gt{constructor(t){c(this,"state"),c(this,"get"),c(this,"set"),c(this,"clone"),this.state=new Ks(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 re(e,t){return s=>x(t[s],e)}class ft extends gt{constructor(t,s,n){super(t),c(this,"supports"),this.supports=re(s,n)}}class oe extends ft{constructor(t,s,n){super({isVisible:t},s,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"}),c(this,"on",(i,r)=>i==="click"?y("back_button_pressed",r):this.state.on(i,r)),c(this,"off",(i,r)=>i==="click"?H("back_button_pressed",r):this.state.off(i,r)),this.postEvent=n}set isVisible(t){this.set("isVisible",t),this.postEvent("web_app_setup_back_button",{is_visible:t})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const mt=q(e=>e instanceof Date?e:new Date(C().parse(e)*1e3),"Date");function J(e,t){return new K(s=>{if(typeof s!="string"&&!(s instanceof URLSearchParams))throw k();const n=typeof s=="string"?new URLSearchParams(s):s;return Qt(e,i=>{const r=n.get(i);return r===null?void 0:r})},!1,t)}const zs=d({id:C(),type:u(),title:u(),photoUrl:{type:u().optional(),from:"photo_url"},username:u().optional()},"Chat").optional(),qt=d({addedToAttachmentMenu:{type:P().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:P().optional(),from:"allows_write_to_pm"},firstName:{type:u(),from:"first_name"},id:C(),isBot:{type:P().optional(),from:"is_bot"},isPremium:{type:P().optional(),from:"is_premium"},languageCode:{type:u().optional(),from:"language_code"},lastName:{type:u().optional(),from:"last_name"},photoUrl:{type:u().optional(),from:"photo_url"},username:u().optional()},"User").optional();function ae(){return J({authDate:{type:mt(),from:"auth_date"},canSendAfter:{type:C().optional(),from:"can_send_after"},chat:zs,chatInstance:{type:u().optional(),from:"chat_instance"},chatType:{type:u().optional(),from:"chat_type"},hash:u(),queryId:{type:u().optional(),from:"query_id"},receiver:qt,startParam:{type:u().optional(),from:"start_param"},user:qt},"InitData")}function Fs(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}function Qs(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}const ce=q(e=>{const t=lt().optional();return Object.entries(ut(e)).reduce((s,[n,i])=>(s[Fs(n)]=t.parse(i),s),{})},"ThemeParams");function Y(e){return J({botInline:{type:P().optional(),from:"tgWebAppBotInline"},initData:{type:ae().optional(),from:"tgWebAppData"},initDataRaw:{type:u().optional(),from:"tgWebAppData"},platform:{type:u(),from:"tgWebAppPlatform"},showSettings:{type:P().optional(),from:"tgWebAppShowSettings"},startParam:{type:u().optional(),from:"tgWebAppStartParam"},themeParams:{type:ce(),from:"tgWebAppThemeParams"},version:{type:u(),from:"tgWebAppVersion"}}).parse(e)}function he(e){return Y(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function Js(){return he(window.location.href)}function ue(){return performance.getEntriesByType("navigation")[0]}function Ys(){const e=ue();if(!e)throw new Error("Unable to get first navigation entry.");return he(e.name)}function pe(e){return`tma.js/${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function le(e,t){sessionStorage.setItem(pe(e),JSON.stringify(t))}function de(e){const t=sessionStorage.getItem(pe(e));try{return t?JSON.parse(t):void 0}catch{}}function Zs(){return Y(de("launchParams")||"")}function bt(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,s])=>[Qs(t),s])))}function _e(e){const{initDataRaw:t,themeParams:s,platform:n,version:i,showSettings:r,startParam:o,botInline:a}=e,p=new URLSearchParams;return p.set("tgWebAppPlatform",n),p.set("tgWebAppThemeParams",bt(s)),p.set("tgWebAppVersion",i),t&&p.set("tgWebAppData",t),o&&p.set("tgWebAppStartParam",o),typeof r=="boolean"&&p.set("tgWebAppShowSettings",r?"1":"0"),typeof a=="boolean"&&p.set("tgWebAppBotInline",a?"1":"0"),p.toString()}function we(e){le("launchParams",_e(e))}function vt(){for(const e of[Js,Ys,Zs])try{const t=e();return we(t),t}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}function yt(){const e=ue();return!!(e&&e.type==="reload")}function Xs(){let e=0;return()=>(e+=1).toString()}const[tn]=Mt(Xs);function w(e,t){return()=>{const s=vt(),n={...s,postEvent:ne(s.version),createRequestId:tn()};if(typeof e=="function")return e(n);const[i,r,o]=$t(),a=t({...n,state:yt()?de(e):void 0,addCleanup:i}),p=h=>(o||i(h.on("change",E=>{le(e,E)})),h);return[a instanceof Promise?a.then(p):p(a),r]}}const ge=w("backButton",({postEvent:e,version:t,state:s={isVisible:!1}})=>new oe(s.isVisible,t,e));class W extends ft{constructor(){super(...arguments),c(this,"on",this.state.on.bind(this.state)),c(this,"off",this.state.off.bind(this.state))}}function fe(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 me extends W{constructor({postEvent:t,version:s,...n}){super(n,s,{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=t}get available(){return this.get("available")}get accessGranted(){return this.get("accessGranted")}get accessRequested(){return this.get("accessRequested")}async authenticate({reason:t,...s}){return this.authPromise||(this.authPromise=_({...s,method:"web_app_biometry_request_auth",event:"biometry_auth_requested",postEvent:this.postEvent,params:{reason:(t||"").trim()}}).then(({token:n})=>n).finally(()=>this.authPromise=void 0)),this.authPromise}get deviceId(){return this.get("deviceId")}openSettings(){this.postEvent("web_app_biometry_open_settings")}requestAccess({reason:t,...s}={}){return this.accessPromise||(this.accessPromise=_({...s,postEvent:this.postEvent,method:"web_app_biometry_request_access",event:"biometry_info_received",params:{reason:t||""}}).then(n=>{const i=fe(n);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:t,...s}={}){return["removed","updated"].includes((await _({...s,postEvent:this.postEvent,method:"web_app_biometry_update_token",event:"biometry_token_updated",params:{token:t||""}})).status)}}async function be(e){return fe(await _({...e||{},method:"web_app_biometry_get_info",event:"biometry_info_received"}))}const ve=w("biometryManager",async({postEvent:e,version:t,state:s})=>new me({...s||x("web_app_biometry_get_info",t)?s||await be({timeout:1e3}):{available:!1,accessGranted:!1,accessRequested:!1,tokenSaved:!1,deviceId:""},version:t,postEvent:e}));class Et extends gt{constructor(){super(...arguments),c(this,"on",this.state.on.bind(this.state)),c(this,"off",this.state.off.bind(this.state))}}class ye extends Et{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 Ee=w("closingBehavior",({postEvent:e,state:t={isConfirmationNeeded:!1}})=>new ye(t.isConfirmationNeeded,e));class Rt{constructor(t,s){c(this,"supports"),this.supports=re(t,s)}}function en(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 k()}class sn extends K{constructor(t,s,n){super(en,s,n),c(this,"itemParser"),this.itemParser=typeof t=="function"?t:t.parse.bind(t)}parse(t){const s=super.parse(t);return s===void 0?s:s.map(this.itemParser)}of(t){return this.itemParser=typeof t=="function"?t:t.parse.bind(t),this}}function Re(e){return new sn(t=>t,!1,e)}function Bt(e,t){return Object.fromEntries(e.map(s=>[s,t]))}class Pe extends Rt{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 T("deleteStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent})}async getKeys(t={}){return Re().of(u()).parse(await T("getStorageKeys",{},this.createRequestId(),{...t,postEvent:this.postEvent}))}async get(t,s={}){const n=Array.isArray(t)?t:[t];if(!n.length)return Bt(n,"");const i=await T("getStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent}),r=d(Bt(n,u()),"CloudStorageData").parse(i);return Array.isArray(t)?r:r[t]}async set(t,s,n={}){await T("saveStorageValue",{key:t,value:s},this.createRequestId(),{...n,postEvent:this.postEvent})}}const Se=w(({createRequestId:e,postEvent:t,version:s})=>new Pe(s,e,t));class Ce extends Rt{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 xe=w(({version:e,postEvent:t})=>new Ce(e,t));class Te{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 Ie=w(({initData:e})=>e?new Te(e):void 0);function nn(e){return ae().parse(e)}class Ae extends W{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:i,pathname:r}=new URL(t,window.location.href);if(i!=="t.me")throw new Error(`Incorrect hostname: ${i}`);const o=r.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 _({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 ke=w(({version:e,postEvent:t})=>new Ae(!1,e,t));class qe extends gt{constructor({postEvent:t,...s}){super(s),c(this,"postEvent"),c(this,"on",(n,i)=>n==="click"?y("main_button_pressed",i):this.state.on(n,i)),c(this,"off",(n,i)=>n==="click"?H("main_button_pressed",i):this.state.off(n,i)),this.postEvent=t}get bgColor(){return this.get("bgColor")}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.bgColor,text_color:this.textColor})}disable(){return this.isEnabled=!1,this}enable(){return this.isEnabled=!0,this}hide(){return this.isVisible=!1,this}hideLoader(){return this.isLoaderVisible=!1,this}set isEnabled(t){this.setParams({isEnabled:t})}get isEnabled(){return this.get("isEnabled")}set isLoaderVisible(t){this.setParams({isLoaderVisible:t})}get isLoaderVisible(){return this.get("isLoaderVisible")}set isVisible(t){this.setParams({isVisible:t})}get isVisible(){return this.get("isVisible")}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(t){return this.setParams({text:t})}setTextColor(t){return this.setParams({textColor:t})}setBgColor(t){return this.setParams({bgColor:t})}setParams(t){return this.set(t),this.commit(),this}get text(){return this.get("text")}get textColor(){return this.get("textColor")}}const Be=w("mainButton",({postEvent:e,themeParams:t,state:s={isVisible:!1,isEnabled:!1,text:"",isLoaderVisible:!1,textColor:t.buttonTextColor||"#ffffff",bgColor:t.buttonColor||"#000000"}})=>new qe({...s,postEvent:e}));function rn(){return J({contact:d({userId:{type:C(),from:"user_id"},phoneNumber:{type:u(),from:"phone_number"},firstName:{type:u(),from:"first_name"},lastName:{type:u().optional(),from:"last_name"}}),authDate:{type:mt(),from:"auth_date"},hash:u()},"RequestedContact")}function Oe(e,t){return s=>{const[n,i]=t[s];return x(n,i,e)}}function on(e){return new Promise(t=>{setTimeout(t,e)})}class De extends W{constructor({postEvent:t,createRequestId:s,version:n,botInline:i,...r}){super(r,n,{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=s,this.postEvent=t,this.botInline=i;const o=this.supports.bind(this);this.supports=a=>o(a)?a!=="switchInlineQuery"||i:!1,this.supportsParam=Oe(n,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact({timeout:t=1e4}={}){return rn().parse(await T("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:t}))}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 wt(this.bgColor)}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:t=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const s=Date.now()+t;let n=50;return _t(async()=>{for(;Date.now()<s;){try{return await this.getRequestedContact()}catch{}await on(n),n+=50}throw ie(t)},t)}async requestPhoneAccess(t={}){return this.requestPhoneAccessPromise||(this.requestPhoneAccessPromise=_({...t,method:"web_app_request_phone",event:"phone_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestPhoneAccessPromise=void 0)),this.requestPhoneAccessPromise}async requestWriteAccess(t={}){return this.requestWriteAccessPromise||(this.requestWriteAccessPromise=_({...t,method:"web_app_request_write_access",event:"write_access_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestWriteAccessPromise=void 0)),this.requestWriteAccessPromise}sendData(t){const{size:s}=new Blob([t]);if(!s||s>4096)throw new Error(`Passed data has incorrect size: ${s}`);this.postEvent("web_app_data_send",{data:t})}setHeaderColor(t){this.postEvent("web_app_set_header_color",z(t)?{color:t}:{color_key:t}),this.set("headerColor",t)}setBgColor(t){this.postEvent("web_app_set_background_color",{color:t}),this.set("bgColor",t)}switchInlineQuery(t,s=[]){if(!this.supports("switchInlineQuery")&&!this.isBotInline)throw new Error("Method is unsupported because Mini App should be launched in inline mode.");this.postEvent("web_app_switch_inline_query",{query:t,chat_types:s})}}const Me=w("miniApp",({themeParams:e,botInline:t=!1,state:s={bgColor:e.bgColor||"#ffffff",headerColor:e.headerBgColor||"#000000"},...n})=>new De({...n,...s,botInline:t}));function an(e){const t=e.message.trim(),s=(e.title||"").trim(),n=e.buttons||[];let i;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?i=n.map(r=>{const{id:o=""}=r;if(o.length>64)throw new Error(`Button ID has incorrect size: ${o}`);if(!r.type||r.type==="default"||r.type==="destructive"){const a=r.text.trim();if(!a.length||a.length>64){const p=r.type||"default";throw new Error(`Button text with type "${p}" has incorrect size: ${r.text.length}`)}return{...r,text:a,id:o}}return{...r,id:o}}):i=[{type:"close",id:""}],{title:s,message:t,buttons:i}}class Ne extends W{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 _({event:"popup_closed",method:"web_app_open_popup",postEvent:this.postEvent,params:an(t)});return s}finally{this.isOpened=!1}}}const Ve=w(({postEvent:e,version:t})=>new Ne(!1,t,e));class $e extends W{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 _({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 Le=w(({version:e,postEvent:t})=>new $e(!1,e,t));class He extends ft{constructor(t,s,n){super({isVisible:t},s,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"}),c(this,"on",(i,r)=>i==="click"?y("settings_button_pressed",r):this.state.on(i,r)),c(this,"off",(i,r)=>i==="click"?H("settings_button_pressed",r):this.state.off(i,r)),this.postEvent=n}set isVisible(t){this.set("isVisible",t),this.postEvent("web_app_setup_settings_button",{is_visible:t})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const Ue=w("settingsButton",({version:e,postEvent:t,state:s={isVisible:!1}})=>new He(s.isVisible,e,t));function Pt(e){return ce().parse(e)}class We extends Et{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||wt(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 y("theme_changed",t=>{this.set(Pt(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}const je=w("themeParams",({themeParams:e,state:t=e,addCleanup:s})=>{const n=new We(t);return s(n.listen()),n});function cn(e={}){return _({...e,method:"web_app_request_theme",event:"theme_changed"}).then(Pt)}class Ge extends Rt{constructor(t,s,n){super(t,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),c(this,"supportsParam"),this.version=t,this.createRequestId=s,this.postEvent=n,this.supportsParam=Oe(t,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(t,s){const n=new URL(t,window.location.href).toString();if(!x("web_app_open_link",this.version)){window.open(n,"_blank");return}this.postEvent("web_app_open_link",{url:n,...typeof s=="boolean"?{try_instant_view:s}:{}})}openTelegramLink(t){const{hostname:s,pathname:n,search:i}=new URL(t,window.location.href);if(s!=="t.me")throw new Error(`URL has not allowed hostname: ${s}. Only "t.me" is allowed`);if(!x("web_app_open_tg_link",this.version)){window.location.href=t;return}this.postEvent("web_app_open_tg_link",{path_full:n+i})}async readTextFromClipboard(){const t=this.createRequestId(),{data:s=null}=await _({method:"web_app_read_text_from_clipboard",event:"clipboard_text_received",postEvent:this.postEvent,params:{req_id:t},capture:dt(t)});return s}}const Ke=w(({version:e,postEvent:t,createRequestId:s})=>new Ge(e,s,t));async function St(e={}){const{is_expanded:t,is_state_stable:s,...n}=await _({...e,method:"web_app_request_viewport",event:"viewport_changed"});return{...n,isExpanded:t,isStateStable:s}}function D(e){return e<0?0:e}class ze extends Et{constructor({postEvent:t,stableHeight:s,height:n,width:i,isExpanded:r}){super({height:D(n),isExpanded:r,stableHeight:D(s),width:D(i)}),c(this,"postEvent"),this.postEvent=t}async sync(t){const{isStateStable:s,...n}=await St(t);this.set({...n,stableHeight:s?n.height:this.get("stableHeight")})}get height(){return this.get("height")}get stableHeight(){return this.get("stableHeight")}listen(){return y("viewport_changed",t=>{const{height:s,width:n,is_expanded:i,is_state_stable:r}=t,o=D(s);this.set({height:o,isExpanded:i,width:D(n),...r?{stableHeight:o}:{}})})}get isExpanded(){return this.get("isExpanded")}get width(){return this.get("width")}expand(){this.postEvent("web_app_expand"),this.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}const Fe=w("viewport",async({state:e,platform:t,postEvent:s,addCleanup:n})=>{let i=!1,r=0,o=0,a=0;if(e)i=e.isExpanded,r=e.height,o=e.width,a=e.stableHeight;else if(["macos","tdesktop","unigram","webk","weba","web"].includes(t))i=!0,r=window.innerHeight,o=window.innerWidth,a=window.innerHeight;else{const h=await St({timeout:1e3,postEvent:s});i=h.isExpanded,r=h.height,o=h.width,a=h.isStateStable?r:0}const p=new ze({postEvent:s,height:r,width:o,stableHeight:a,isExpanded:i});return n(p.listen()),p});function S(e,t){document.documentElement.style.setProperty(e,t)}function hn(e,t,s){s||(s=a=>`--tg-${a}-color`);const n=s("header"),i=s("bg"),r=()=>{const{headerColor:a}=e;if(z(a))S(n,a);else{const{bgColor:p,secondaryBgColor:h}=t;a==="bg_color"&&p?S(n,p):a==="secondary_bg_color"&&h&&S(n,h)}S(i,e.bgColor)},o=[t.on("change",r),e.on("change",r)];return r(),()=>o.forEach(a=>a())}function un(e,t){t||(t=n=>`--tg-theme-${n.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`)}`);const s=()=>{Object.entries(e.getState()).forEach(([n,i])=>{i&&S(t(n),i)})};return s(),e.on("change",s)}function pn(e,t){t||(t=h=>`--tg-viewport-${h}`);const[s,n,i]=["height","width","stable-height"].map(h=>t(h)),r=()=>S(s,`${e.height}px`),o=()=>S(n,`${e.width}px`),a=()=>S(i,`${e.stableHeight}px`),p=[e.on("change:height",r),e.on("change:width",o),e.on("change:stableHeight",a)];return r(),o(),a(),()=>p.forEach(h=>h())}function Qe(e=!0){const t=[y("reload_iframe",()=>{A("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(y("set_custom_style",i=>{n.innerHTML=i}),()=>document.head.removeChild(n))}return A("iframe_ready",{reload_supported:!0}),s}function Je(){return typeof window>"u"}async function ln(){if(te(window))return!0;try{return await _({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function dn(e){const t=typeof e=="string"?Y(e):e;we(t);function s(i){if(typeof i=="string")try{const{eventType:r}=Yt(i);r==="web_app_request_theme"&&ot("theme_changed",{theme_params:JSON.parse(bt(t.themeParams))}),r==="web_app_request_viewport"&&ot("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}catch{}}if(Q()){const i=window.parent.postMessage.bind(window.parent);window.parent.postMessage=r=>{s(r),i(r)};return}if(Xt(window)){const i=window.external.notify.bind(window.external);window.external.notify=r=>{s(r),i(r)};return}const n=window.TelegramWebviewProxy;window.TelegramWebviewProxy={...n||{},postEvent(...i){s(JSON.stringify({eventType:i[0],eventData:i[1]})),n&&n.postEvent(...i)}}}function Ye(e){return e instanceof L}function _n(e,t){return Ye(e)&&e.type===t}function X(e,t){let s,n,i;return typeof e=="string"?s=e:(s=e.pathname===void 0?t:e.pathname,n=e.params,i=e.id),Object.freeze({id:i||(Math.random()*2**14|0).toString(16),pathname:s,params:n})}class Ze{constructor(t,s,n=A){if(c(this,"history"),c(this,"ee",new I),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)),this._index=s,this.postEvent=n,t.length===0)throw b(Kt,"History should not be empty.");if(s<0||s>=t.length)throw b(zt,"Index should not be zero and higher or equal than history size.");this.history=t.map(i=>X(i,""))}attach(){this.attached||(this.attached=!0,this.sync(),y("back_button_pressed",this.back))}get current(){return this.history[this.index]}detach(){this.attached=!1,H("back_button_pressed",this.back)}forward(){this.go(1)}go(t,s){const n=this.index+t,i=Math.min(Math.max(0,n),this.history.length-1);(n===i||s)&&this.replaceAndMove(i,this.history[i])}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,X(t,this.current.pathname))}replace(t){this.replaceAndMove(this.index,X(t,this.current.pathname))}replaceAndMove(t,s){const n=t-this.index;if(!n&&this.current===s)return;const i=this.current;if(this.index!==t){const r=this._index;this._index=t,this.attached&&r>0!=t>0&&this.sync()}this.history[t]=s,this.ee.emit("change",{navigator:this,from:i,to:this.current,delta:n})}sync(){this.postEvent("web_app_setup_back_button",{is_visible:!!this.index})}}function tt({params:e,...t}){return{...e||{hash:"",search:""},...t}}function N(e,t){return e.startsWith(t)?e:`${t}${e}`}function V(e){return new URL(typeof e=="string"?e:`${e.pathname||""}${N(e.search||"","?")}${N(e.hash||"","#")}`,"http://a")}function $(e){const t=typeof e=="string"?e.startsWith("/"):!!(e.pathname&&e.pathname.startsWith("/")),s=V(e);return`${t?s.pathname:s.pathname.slice(1)}${s.search}${s.hash}`}function et(e,t,s){let n,i;typeof e=="string"?n=e:(n=$(e),s=e.state,i=e.id);const{pathname:r,search:o,hash:a}=new URL(n,`http://a${N(t,"/")}`);return{id:i,pathname:r,params:{hash:a,search:o,state:s}}}async function M(e){return e===0?!0:Promise.race([new Promise(t=>{const s=rt("popstate",()=>{s(),t(!0)});window.history.go(e)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function wn(){if(window.history.length<=1||(window.history.pushState(null,""),await M(1-window.history.length)))return;let e=await M(-1);for(;e;)e=await M(-1)}function Ct(e){return V(e).pathname}const Ot=0,st=1,nt=2;class xt{constructor(t,s,{postEvent:n,hashMode:i="classic",base:r}={}){c(this,"navigator"),c(this,"ee",new I),c(this,"hashMode"),c(this,"base"),c(this,"attached",!1),c(this,"onPopState",({state:o})=>{if(o===null)return this.push(this.parsePath(window.location.href));o===Ot?window.history.forward():o===st&&this.back(),o===nt&&this.forward()}),c(this,"onNavigatorChange",async({to:o,from:a,delta:p})=>{this.attached&&await this.syncHistory(),this.ee.emit("change",{delta:p,from:tt(a),to:tt(o),navigator:this})}),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this.navigator=new Ze(t.map(o=>et(o,"/")),s,n),this.navigator.on("change",this.onNavigatorChange),this.hashMode=i,this.base=Ct(r||"")}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(tt)}get path(){return $(this)}get pathname(){return this.navigator.current.pathname}parsePath(t){let s=V(t);return this.hashMode&&(s=V(s.hash.slice(1))),{pathname:s.pathname,search:s.search,hash:s.hash}}push(t,s){const n=et(t,this.path),{state:i=s}=n.params;this.navigator.push({...n,params:{...n.params,state:i}})}replace(t,s){const n=et(t,this.path),{state:i=s}=n.params;this.navigator.replace({...n,params:{...n.params,state:i}})}renderPath(t){const s=(this.base.length===1?"":this.base)+N($(t),"/");return this.hashMode?N(s.slice(1),this.hashMode==="classic"?"#":"#/"):s}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const{state:t}=this,s=this.renderPath(this);await wn(),this.hasPrev&&this.hasNext?(window.history.replaceState(st,""),window.history.pushState(t,"",s),window.history.pushState(nt,""),await M(-1)):this.hasPrev?(window.history.replaceState(st,""),window.history.pushState(t,"",s)):this.hasNext?(window.history.replaceState(t,s),window.history.pushState(nt,""),await M(-1)):(window.history.replaceState(Ot,""),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 Xe(e){e||(e={});const{href:t,hash:s}=window.location;let n=$(e.hashMode===null?t:s.includes("?")?s.slice(1):`?${s.slice(1)}`);const i=e.base?Ct(e.base):void 0;if(i){if(!n.startsWith(i))throw b(Ft,`Path "${n}" expected to be starting with "${i}"`);n=n.slice(i.length)}return new xt([n],0,e)}function gn(e){const t=e.match(/#(.+)/);return t?t[1]:null}function fn(e,t){if(yt()){const s=sessionStorage.getItem(e);if(s)try{const{index:n,history:i}=JSON.parse(s);return new xt(i,n,t)}catch(n){console.error("Unable to restore hash navigator state.",n)}}return Xe(t)}function mn(e,t){const s=fn(e,t),n=()=>sessionStorage.setItem(e,JSON.stringify({index:s.index,history:s.history}));return s.on("change",n),n(),s}function g(e,t){function s(n){return function(r,o,a){return p=>{const h={...p,[r]:n(o)};return Dt.jsx(a,{...h})}}}return[s(e),s(t)]}const ts=l.createContext(void 0);function es(){const e=l.useContext(ts);if(!e)throw new Error("useSDK was used outside the SDKProvider.");return e}function f(e){function t(n){const i=es(),[r,o]=l.useState(n?void 0:()=>{if(Je())throw new Error("Using hooks on the server side, you must explicitly specify ssr = true option");return i.use(e)});return l.useEffect(()=>{o(i.use(e))},[i]),r}function s(n){const i=t(n);if(i){if("error"in i)throw i.error;return i.result}}return[t,s]}const[ss,ns]=f(ge),[bn,vn]=g(ss,ns),[is,rs]=f(ve),[yn,En]=g(is,rs),[os,as]=f(Ee),[Rn,Pn]=g(os,as),[cs,hs]=f(Se),[Sn,Cn]=g(cs,hs),[us,ps]=f(xe),[xn,Tn]=g(us,ps),[ls,ds]=f(Ie),[In,An]=g(ls,ds),[_s,ws]=f(ke),[kn,qn]=g(_s,ws),[gs,fs]=f(Be),[Bn,On]=g(gs,fs),[ms,bs]=f(Me),[Dn,Mn]=g(ms,bs),[vs,ys]=f(Ve),[Nn,Vn]=g(vs,ys),[Es,Rs]=f(Le),[$n,Ln]=g(Es,Rs),[Ps,Ss]=f(Ue),[Hn,Un]=g(Ps,Ss),[Cs,xs]=f(je),[Wn,jn]=g(Cs,xs);function Gn(){return l.useMemo(vt,[])}const[Ts,Is]=f(Ke),[Kn,zn]=g(Ts,Is),[As,ks]=f(Fe),[Fn,Qn]=g(As,ks);function Jn({children:e,acceptCustomStyles:t,debug:s}){const n=l.useRef(!0),[i,r]=l.useState(new Map),o=l.useRef(i),a=l.useCallback(h=>{n.current&&r(E=>(h&&h(E),new Map(E)))},[]),p=l.useMemo(()=>({use(h,...E){const Tt=i.get(h);if(Tt)return Tt;let v,Z;try{v=h(...E)}catch(m){Z=m}function j(m){return i.set(h,m),m}if(Z)return j({error:Z});let B;if(Array.isArray(v)&&(B=v[1],v=v[0]),!v)return j({result:v,cleanup:B});function It(m){if("on"in m){const O=m.on("change",()=>a()),At=B;B=()=>{At&&At(),O()}}return{result:m,cleanup:B}}return v instanceof Promise?(v.then(m=>a(O=>O.set(h,It(m))),m=>a(O=>O.set(h,{error:m}))),j({})):j(It(v))}}),[i]);return l.useEffect(()=>(n.current=!0,()=>{n.current=!1}),[]),l.useEffect(()=>{if(Q())return Qe(t)},[t]),l.useEffect(()=>{Vt(s||!1)},[s]),l.useEffect(()=>{o.current=i},[i]),l.useEffect(()=>()=>{o.current.forEach(h=>{"cleanup"in h&&h.cleanup&&h.cleanup()})},[]),Dt.jsx(ts.Provider,{value:p,children:e})}exports.BackButton=oe;exports.BasicNavigator=Ze;exports.BiometryManager=me;exports.BrowserNavigator=xt;exports.ClosingBehavior=ye;exports.CloudStorage=Pe;exports.ERR_INVALID_PATH_BASE=Ft;exports.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=Wt;exports.ERR_METHOD_PARAMETER_UNSUPPORTED=Ht;exports.ERR_METHOD_UNSUPPORTED=Lt;exports.ERR_NAVIGATION_HISTORY_EMPTY=Kt;exports.ERR_NAVIGATION_INDEX_INVALID=zt;exports.ERR_NAVIGATION_ITEM_INVALID=Ms;exports.ERR_PARSE=ht;exports.ERR_SSR_INIT=Ns;exports.ERR_TIMED_OUT=jt;exports.ERR_UNEXPECTED_TYPE=Gt;exports.ERR_UNKNOWN_ENV=Ut;exports.EventEmitter=I;exports.HapticFeedback=Ce;exports.InitData=Te;exports.Invoice=Ae;exports.MainButton=qe;exports.MiniApp=De;exports.Popup=Ne;exports.QRScanner=$e;exports.SDKError=L;exports.SDKProvider=Jn;exports.SettingsButton=He;exports.ThemeParams=We;exports.Utils=Ge;exports.Viewport=ze;exports.array=Re;exports.bindMiniAppCSSVars=hn;exports.bindThemeParamsCSSVars=un;exports.bindViewportCSSVars=pn;exports.boolean=P;exports.captureSameReq=dt;exports.classNames=G;exports.compareVersions=Zt;exports.createBrowserNavigatorFromLocation=Xe;exports.createPostEvent=ne;exports.createSafeURL=V;exports.date=mt;exports.getHash=gn;exports.getPathname=Ct;exports.initBackButton=ge;exports.initBiometryManager=ve;exports.initClosingBehavior=Ee;exports.initCloudStorage=Se;exports.initHapticFeedback=xe;exports.initInitData=Ie;exports.initInvoice=ke;exports.initMainButton=Be;exports.initMiniApp=Me;exports.initNavigator=mn;exports.initPopup=Ve;exports.initQRScanner=Le;exports.initSettingsButton=Ue;exports.initThemeParams=je;exports.initUtils=Ke;exports.initViewport=Fe;exports.initWeb=Qe;exports.invokeCustomMethod=T;exports.isColorDark=wt;exports.isIframe=Q;exports.isPageReload=yt;exports.isRGB=z;exports.isRGBShort=Jt;exports.isSDKError=Ye;exports.isSDKErrorOfType=_n;exports.isSSR=Je;exports.isTMA=ln;exports.json=d;exports.mergeClassNames=Gs;exports.mockTelegramEnv=dn;exports.number=C;exports.off=H;exports.on=y;exports.parseInitData=nn;exports.parseLaunchParams=Y;exports.parseThemeParams=Pt;exports.postEvent=A;exports.request=_;exports.requestBiometryInfo=be;exports.requestThemeParams=cn;exports.requestViewport=St;exports.retrieveLaunchParams=vt;exports.rgb=lt;exports.searchParams=J;exports.serializeLaunchParams=_e;exports.serializeThemeParams=bt;exports.setCSSVar=S;exports.setDebug=Vt;exports.setTargetOrigin=js;exports.string=u;exports.subscribe=Nt;exports.supports=x;exports.targetOrigin=se;exports.toRGB=pt;exports.unsubscribe=at;exports.urlToPath=$;exports.useBackButton=ns;exports.useBackButtonRaw=ss;exports.useBiometryManager=rs;exports.useBiometryManagerRaw=is;exports.useClosingBehavior=as;exports.useClosingBehaviorRaw=os;exports.useCloudStorage=hs;exports.useCloudStorageRaw=cs;exports.useHapticFeedback=ps;exports.useHapticFeedbackRaw=us;exports.useInitData=ds;exports.useInitDataRaw=ls;exports.useInvoice=ws;exports.useInvoiceRaw=_s;exports.useLaunchParams=Gn;exports.useMainButton=fs;exports.useMainButtonRaw=gs;exports.useMiniApp=bs;exports.useMiniAppRaw=ms;exports.usePopup=ys;exports.usePopupRaw=vs;exports.useQRScanner=Rs;exports.useQRScannerRaw=Es;exports.useSDK=es;exports.useSettingsButton=Ss;exports.useSettingsButtonRaw=Ps;exports.useThemeParams=xs;exports.useThemeParamsRaw=Cs;exports.useUtils=Is;exports.useUtilsRaw=Ts;exports.useViewport=ks;exports.useViewportRaw=As;exports.withBackButton=vn;exports.withBackButtonRaw=bn;exports.withBiometryManager=En;exports.withBiometryManagerRaw=yn;exports.withClosingBehavior=Pn;exports.withClosingBehaviorRaw=Rn;exports.withCloudStorage=Cn;exports.withCloudStorageRaw=Sn;exports.withHapticFeedback=Tn;exports.withHapticFeedbackRaw=xn;exports.withInitData=An;exports.withInitDataRaw=In;exports.withInvoice=qn;exports.withInvoiceRaw=kn;exports.withMainButton=On;exports.withMainButtonRaw=Bn;exports.withMiniApp=Mn;exports.withMiniAppRaw=Dn;exports.withPopup=Vn;exports.withPopupRaw=Nn;exports.withQRScanner=Ln;exports.withQRScannerRaw=$n;exports.withSettingsButton=Un;exports.withSettingsButtonRaw=Hn;exports.withThemeParams=jn;exports.withThemeParamsRaw=Wn;exports.withTimeout=_t;exports.withUtils=zn;exports.withUtilsRaw=Kn;exports.withViewport=Qn;exports.withViewportRaw=Fn;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|