@tma.js/sdk 1.3.0 → 1.4.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/index.d.ts +1 -0
- package/dist/dts/launch-params/index.d.ts +1 -0
- package/dist/dts/launch-params/retrieveFromUrl.d.ts +6 -0
- package/dist/dts/launch-params/types.d.ts +12 -8
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.iife.js +1 -1
- package/dist/index.iife.js.map +1 -1
- package/dist/index.mjs +253 -238
- package/dist/index.mjs.map +1 -1
- package/package.json +2 -2
- package/src/__tests__/globals.ts +39 -0
- package/src/back-button/__tests__/BackButton.ts +129 -0
- package/src/bridge/__tests__/request.ts +236 -0
- package/src/bridge/env/__tests__/hasExternalNotify.ts +15 -0
- package/src/bridge/env/__tests__/hasWebviewProxy.ts +15 -0
- package/src/bridge/env/__tests__/isIframe.ts +30 -0
- package/src/bridge/events/__tests__/createEmitter.ts +143 -0
- package/src/bridge/events/__tests__/off.ts +34 -0
- package/src/bridge/events/__tests__/on.ts +49 -0
- package/src/bridge/events/__tests__/onTelegramEvent.ts +51 -0
- package/src/bridge/events/__tests__/once.ts +64 -0
- package/src/bridge/events/__tests__/singletonEmitter.ts +22 -0
- package/src/bridge/events/__tests__/subscribe.ts +49 -0
- package/src/bridge/events/__tests__/unsubscribe.ts +34 -0
- package/src/bridge/events/parsers/__tests__/clipboardTextReceived.ts +21 -0
- package/src/bridge/events/parsers/__tests__/invoiceClosed.ts +12 -0
- package/src/bridge/events/parsers/__tests__/popupClosed.ts +10 -0
- package/src/bridge/events/parsers/__tests__/qrTextReceived.ts +9 -0
- package/src/bridge/events/parsers/__tests__/theme-changed.ts +42 -0
- package/src/bridge/events/parsers/__tests__/viewportChanged.ts +49 -0
- package/src/bridge/methods/__tests__/createPostEvent.ts +37 -0
- package/src/bridge/methods/__tests__/postEvent.ts +137 -0
- package/src/classnames/__tests__/classNames.ts +20 -0
- package/src/classnames/__tests__/mergeClassNames.ts +21 -0
- package/src/closing-behavior/__tests__/ClosingBehavior.ts +86 -0
- package/src/colors/__tests__/isColorDark.ts +12 -0
- package/src/colors/__tests__/isRGB.ts +13 -0
- package/src/colors/__tests__/isRGBShort.ts +13 -0
- package/src/colors/__tests__/toRGB.ts +23 -0
- package/src/event-emitter/__tests__/EventEmitter.ts +145 -0
- package/src/haptic-feedback/__tests__/HapticFeedback.ts +68 -0
- package/src/index.ts +12 -0
- package/src/init/creators/__tests__/createViewport.ts +96 -0
- package/src/init-data/__tests__/InitData.ts +98 -0
- package/src/init-data/__tests__/chatParser.ts +102 -0
- package/src/init-data/__tests__/initDataParser.ts +136 -0
- package/src/init-data/__tests__/parseInitData.ts +136 -0
- package/src/init-data/__tests__/userParser.ts +96 -0
- package/src/launch-params/__tests__/retrieveFromUrl.ts +19 -0
- package/src/launch-params/index.ts +1 -0
- package/src/launch-params/launchParamsParser.ts +4 -0
- package/src/launch-params/retrieveFromLocation.ts +2 -2
- package/src/launch-params/retrieveFromPerformance.ts +2 -7
- package/src/launch-params/retrieveFromUrl.ts +19 -0
- package/src/launch-params/types.ts +13 -8
- package/src/logger/__tests__/Logger.ts +107 -0
- package/src/main-button/__tests__/MainButton.ts +346 -0
- package/src/mini-app/__tests__/MiniApp.ts +140 -0
- package/src/misc/__tests__/isRecord.ts +21 -0
- package/src/navigation/HashNavigator/__tests__/HashNavigator.ts +144 -0
- package/src/navigation/HashNavigator/__tests__/drop.ts +42 -0
- package/src/navigation/HashNavigator/__tests__/go.ts +9 -0
- package/src/parsing/__tests__/ArrayValueParser.ts +18 -0
- package/src/parsing/__tests__/toRecord.ts +10 -0
- package/src/parsing/parsers/__tests__/array.ts +39 -0
- package/src/parsing/parsers/__tests__/boolean.ts +31 -0
- package/src/parsing/parsers/__tests__/date.ts +25 -0
- package/src/parsing/parsers/__tests__/json.ts +80 -0
- package/src/parsing/parsers/__tests__/number.ts +23 -0
- package/src/parsing/parsers/__tests__/rgb.ts +22 -0
- package/src/parsing/parsers/__tests__/searchParams.ts +105 -0
- package/src/parsing/parsers/__tests__/string.ts +25 -0
- package/src/popup/__tests__/Popup.ts +130 -0
- package/src/popup/__tests__/preparePopupParams.ts +85 -0
- package/src/supports/__tests__/supports.ts +123 -0
- package/src/theme-params/__tests__/keys.ts +19 -0
- package/src/theme-params/__tests__/parseThemeParams.ts +29 -0
- package/src/theme-params/__tests__/serializeThemeParams.ts +29 -0
- package/src/theme-params/__tests__/themeParamsParser.ts +29 -0
- package/src/timeout/__tests__/isTimeoutError.ts +9 -0
- package/src/timeout/__tests__/withTimeout.ts +28 -0
- package/src/version/__tests__/compareVersions.ts +19 -0
- package/src/viewport/__tests__/isStableViewportPlatform.ts +15 -0
- package/src/viewport/__tests__/utils.ts +12 -0
package/dist/dts/index.d.ts
CHANGED
|
@@ -13,6 +13,7 @@ export { MainButton, type MainButtonParams, type MainButtonProps, type MainButto
|
|
|
13
13
|
export { MiniApp, type MiniAppHeaderColor, type MiniAppEventName, type MiniAppEventListener, type MiniAppEvents, type MiniAppProps, } from './mini-app/index.js';
|
|
14
14
|
export { isTMA, isRecord } from './misc/index.js';
|
|
15
15
|
export { getHash, HashNavigator, Navigator, type NavigationEntry, type NavigatorConEntry, type NavigatorOptions, type HashNavigatorOptions, type HashNavigatorEventsMap, type HashNavigatorEventListener, type HashNavigatorEventName, } from './navigation/index.js';
|
|
16
|
+
export { boolean, searchParams, string, rgb, array, date, json, number, ParseError, ParseSchemaFieldError, } from './parsing/index.js';
|
|
16
17
|
export { Popup, type PopupEventName, type PopupEventListener, type PopupEvents, type OpenPopupOptions, type OpenPopupOptionsButton, } from './popup/index.js';
|
|
17
18
|
export { QRScanner, type QRScannerEventListener, type QRScannerEventName, type QRScannerEvents, } from './qr-scanner/index.js';
|
|
18
19
|
export { SettingsButton, type SettingsButtonEventName, type SettingsButtonEventListener, type SettingsButtonEvents, } from './settings-button/index.js';
|
|
@@ -6,6 +6,7 @@ export * from './parseLaunchParams.js';
|
|
|
6
6
|
export * from './retrieveCurrent.js';
|
|
7
7
|
export * from './retrieveFromLocation.js';
|
|
8
8
|
export * from './retrieveFromPerformance.js';
|
|
9
|
+
export * from './retrieveFromUrl.js';
|
|
9
10
|
export * from './retrieveLaunchData.js';
|
|
10
11
|
export * from './serializeLaunchParams.js';
|
|
11
12
|
export * from './storage.js';
|
|
@@ -7,9 +7,9 @@ import type { Platform } from '../types/index.js';
|
|
|
7
7
|
*/
|
|
8
8
|
export interface LaunchParams {
|
|
9
9
|
/**
|
|
10
|
-
*
|
|
10
|
+
* True if Mini App is currently launched in inline mode.
|
|
11
11
|
*/
|
|
12
|
-
|
|
12
|
+
botInline?: boolean;
|
|
13
13
|
/**
|
|
14
14
|
* Current launch init data. Can be missing in case, application was launched via
|
|
15
15
|
* KeyboardButton.
|
|
@@ -24,17 +24,21 @@ export interface LaunchParams {
|
|
|
24
24
|
*/
|
|
25
25
|
platform: Platform;
|
|
26
26
|
/**
|
|
27
|
-
*
|
|
27
|
+
* True if application is required to show the Settings Button.
|
|
28
28
|
*/
|
|
29
|
-
|
|
29
|
+
showSettings?: boolean;
|
|
30
30
|
/**
|
|
31
|
-
*
|
|
31
|
+
* Start parameter passed in the application link.
|
|
32
32
|
*/
|
|
33
|
-
|
|
33
|
+
startParam?: string;
|
|
34
34
|
/**
|
|
35
|
-
*
|
|
35
|
+
* Mini App palette settings.
|
|
36
36
|
*/
|
|
37
|
-
|
|
37
|
+
themeParams: ThemeParamsParsed;
|
|
38
|
+
/**
|
|
39
|
+
* Current Mini Apps version.
|
|
40
|
+
*/
|
|
41
|
+
version: string;
|
|
38
42
|
}
|
|
39
43
|
export interface LaunchData {
|
|
40
44
|
/**
|
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var tt=Object.defineProperty;var rt=(r,e,t)=>e in r?tt(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var o=(r,e,t)=>(rt(r,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function L(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Ce(){return performance.getEntriesByType("navigation")[0]||null}function st(){const r=Ce();return r?r.type==="reload":null}function B(){return new TypeError("Value has unexpected type")}class z extends Error{constructor(t,{cause:s,type:n}={}){super(`Unable to parse value${n?` as ${n}`:""}`,{cause:s});o(this,"type");this.value=t,Object.setPrototypeOf(this,z.prototype),this.type=n}}class J{constructor(e,t,s){this.parser=e,this.isOptional=t,this.type=s}parse(e){if(!(this.isOptional&&e===void 0))try{return this.parser(e)}catch(t){throw new z(e,{type:this.type,cause:t})}}optional(){return this.isOptional=!0,this}}function nt(r){if(Array.isArray(r))return r;if(typeof r=="string")try{const e=JSON.parse(r);if(Array.isArray(e))return e}catch{}throw B()}class it extends J{constructor(t,s,n){super(nt,s,n);o(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 $(r,e){return()=>new J(r,!1,e)}class F extends Error{constructor(e,{cause:t,type:s}={}){super(`Unable to parse field "${e}"${s?` as ${s}`:""}`,{cause:t}),Object.setPrototypeOf(this,F.prototype)}}function ve(r,e){const t={};for(const s in r){const n=r[s];if(!n)continue;let i,a;if(typeof n=="function"||"parse"in n)i=s,a=typeof n=="function"?n:n.parse.bind(n);else{const{type:h}=n;i=n.from||s,a=typeof h=="function"?h:h.parse.bind(h)}let c;const p=e(i);try{c=a(p)}catch(h){throw h instanceof z?new F(i,{type:h.type,cause:h}):new F(i,{cause:h})}c!==void 0&&(t[s]=c)}return t}function ot(r){return new it(e=>e,!1,r)}const S=$(r=>{if(typeof r=="boolean")return r;const e=String(r);if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw B()},"boolean"),q=$(r=>{if(typeof r=="number")return r;if(typeof r=="string"){const e=Number(r);if(!Number.isNaN(e))return e}throw B()},"number"),Pe=$(r=>r instanceof Date?r:new Date(q().parse(r)*1e3),"Date");function te(r){let e=r;if(typeof e=="string"&&(e=JSON.parse(e)),typeof e!="object"||e===null||Array.isArray(e))throw B();return e}function f(r,e){return new J(t=>{const s=te(t);return ve(r,n=>s[n])},!1,e)}function re(r){return/^#[\da-f]{6}$/i.test(r)}function Se(r){return/^#[\da-f]{3}$/i.test(r)}function se(r){const e=r.replace(/\s/g,"").toLowerCase();if(re(e))return e;if(Se(e)){let s="#";for(let n=0;n<3;n+=1)s+=e[1+n].repeat(2);return s}const t=e.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||e.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(t===null)throw new Error(`Value "${r}" does not satisfy any of known RGB formats.`);return t.slice(1).reduce((s,n)=>{const i=parseInt(n,10).toString(16);return s+(i.length===1?"0":"")+i},"#")}function ne(r){const e=se(r);return Math.sqrt([.299,.587,.114].reduce((s,n,i)=>{const a=parseInt(e.slice(1+i*2,1+(i+1)*2),16);return s+a*a*n},0))<120}const u=$(r=>{if(typeof r=="string"||typeof r=="number")return r.toString();throw B()},"string"),ke=$(r=>se(u().parse(r)),"rgb");function ie(r,e){return new J(t=>{if(typeof t!="string"&&!(t instanceof URLSearchParams))throw B();const s=typeof t=="string"?new URLSearchParams(t):t;return ve(r,n=>{const i=s.get(n);return i===null?void 0:i})},!1,e)}function xe(){return f({id:q(),type:u(),title:u(),photoUrl:{type:u().optional(),from:"photo_url"},username:u().optional()},"Chat")}class qe{constructor(e){this.initData=e}get authDate(){return this.initData.authDate}get canSendAfter(){return this.initData.canSendAfter}get canSendAfterDate(){const{canSendAfter:e}=this;return e===void 0?void 0:new Date(this.authDate.getTime()+e*1e3)}get chat(){return this.initData.chat}get chatType(){return this.initData.chatType}get chatInstance(){return this.initData.chatInstance}get hash(){return this.initData.hash}get queryId(){return this.initData.queryId}get receiver(){return this.initData.receiver}get startParam(){return this.initData.startParam}get user(){return this.initData.user}}function ee(){return f({addedToAttachmentMenu:{type:S().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:S().optional(),from:"allows_write_to_pm"},firstName:{type:u(),from:"first_name"},id:q(),isBot:{type:S().optional(),from:"is_bot"},isPremium:{type:S().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")}function oe(){return ie({authDate:{type:Pe(),from:"auth_date"},canSendAfter:{type:q().optional(),from:"can_send_after"},chat:xe().optional(),chatInstance:{type:u().optional(),from:"chat_instance"},chatType:{type:u().optional(),from:"chat_type"},hash:u(),queryId:{type:u().optional(),from:"query_id"},receiver:ee().optional(),startParam:{type:u().optional(),from:"start_param"},user:ee().optional()},"InitData")}function at(r){return oe().parse(r)}function ct(r){return r.replace(/(^|_)bg/,(e,t)=>`${t}background`).replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}function ut(r){return r.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`).replace(/(^|_)background/,(e,t)=>`${t}bg`)}const ae=$(r=>{const e=ke().optional();return Object.entries(te(r)).reduce((t,[s,n])=>(t[ct(s)]=e.parse(n),t),{})},"ThemeParams");function ce(r){return ae().parse(r)}function ht(r={}){return b("web_app_request_theme","theme_changed",r).then(ce)}function Ae(r){return JSON.stringify(Object.entries(r).reduce((e,[t,s])=>(s&&(e[ut(t)]=s),e),{}))}class w{constructor(){o(this,"listeners",new Map);o(this,"subscribeListeners",[])}addListener(e,t,s){let n=this.listeners.get(e);return n||(n=[],this.listeners.set(e,n)),n.push([t,s]),()=>this.off(e,t)}emit(e,...t){this.subscribeListeners.forEach(n=>n(e,...t));const s=this.listeners.get(e);s&&s.forEach(([n,i],a)=>{n(...t),i&&s.splice(a,1)})}on(e,t){return this.addListener(e,t,!1)}once(e,t){return this.addListener(e,t,!0)}off(e,t){const s=this.listeners.get(e);if(s){for(let n=0;n<s.length;n+=1)if(t===s[n][0]){s.splice(n,1);return}}}subscribe(e){return this.subscribeListeners.push(e),()=>this.unsubscribe(e)}unsubscribe(e){for(let t=0;t<this.subscribeListeners.length;t+=1)if(this.subscribeListeners[t]===e){this.subscribeListeners.splice(t,1);return}}}class m{constructor(e,t){this.state=e,this.ee=t}internalSet(e,t){return this.state[e]===t||t===void 0?!1:(this.state[e]=t,this.ee.emit(`change:${e}`,t),!0)}clone(){return{...this.state}}set(e,t){let s=!1;if(typeof e=="string")s=this.internalSet(e,t);else for(const n in e)this.internalSet(n,e[n])&&(s=!0);s&&this.ee.emit("change")}get(e){return this.state[e]}}class Re{constructor(e){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.state=new m(e,this.ee)}get accentTextColor(){return this.get("accentTextColor")}get backgroundColor(){return this.get("backgroundColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}get(e){return this.state.get(e)}getState(){return this.state.clone()}get headerBackgroundColor(){return this.get("headerBackgroundColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.backgroundColor||ne(this.backgroundColor)}get linkColor(){return this.get("linkColor")}get secondaryBackgroundColor(){return this.get("secondaryBackgroundColor")}get sectionBackgroundColor(){return this.get("sectionBackgroundColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}listen(){return y("theme_changed",e=>{this.state.set(ce(e.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}function ue(){return ie({botInline:{type:S().optional(),from:"tgWebAppBotInline"},initData:{type:oe().optional(),from:"tgWebAppData"},initDataRaw:{type:u().optional(),from:"tgWebAppData"},platform:{type:u(),from:"tgWebAppPlatform"},showSettings:{type:S().optional(),from:"tgWebAppShowSettings"},themeParams:{type:ae(),from:"tgWebAppThemeParams"},version:{type:u(),from:"tgWebAppVersion"}},"LaunchParams")}function he(r){return ue().parse(r)}function pt(){return he(window.location.hash.slice(1))}function lt(){const r=Ce();if(!r)throw new Error("Unable to get first navigation entry.");const e=r.name.match(/#(.*)/);if(!e)throw new Error("First navigation entry does not contain hash part.");return he(e[1])}function dt(){try{return lt()}catch{}try{return pt()}catch{}return null}function Ve(r){const{initDataRaw:e,themeParams:t,platform:s,version:n,showSettings:i,botInline:a}=r,c=new URLSearchParams;return e&&c.set("tgWebAppData",e),c.set("tgWebAppPlatform",s),c.set("tgWebAppThemeParams",Ae(t)),c.set("tgWebAppVersion",n),typeof i=="boolean"&&c.set("tgWebAppShowSettings",i?"1":"0"),typeof a=="boolean"&&c.set("tgWebAppBotInline",a?"1":"0"),c.toString()}const Te="telegram-mini-apps-launch-params";function ft(){const r=sessionStorage.getItem(Te);return r?ue().parse(r):null}function gt(r){sessionStorage.setItem(Te,Ve(r))}function wt(){try{return window.self!==window.top}catch{return!0}}function _t(){const r=ft(),e=dt(),t=st();if(r){if(e)return{launchParams:e,isPageReload:wt()?t||r.initDataRaw===e.initDataRaw:!0};if(t)return{launchParams:r,isPageReload:t};throw new Error("Unable to retrieve current launch parameters, which must exist.")}if(e)return{launchParams:e,isPageReload:!1};throw new Error("Unable to retrieve any launch parameters.")}const we="tmajsLaunchData";function pe(){const r=window[we];if(r)return r;const e=_t();return window[we]=e,gt(e.launchParams),e}function bt(){try{return pe(),!0}catch{return!1}}function mt(r){return"external"in r&&L(r.external)&&"notify"in r.external&&typeof r.external.notify=="function"}function yt(r){return"TelegramWebviewProxy"in r&&L(r.TelegramWebviewProxy)&&"postEvent"in r.TelegramWebviewProxy&&typeof r.TelegramWebviewProxy.postEvent=="function"}function le(){try{return window.self!==window.top}catch{return!0}}class Q extends Error{constructor(e,t){super(`Method "${e}" is unsupported in the Mini Apps version ${t}.`),Object.setPrototypeOf(this,Q.prototype)}}class Z extends Error{constructor(e,t,s){super(`Parameter "${t}" in method "${e}" is unsupported in the Mini Apps version ${s}.`),Object.setPrototypeOf(this,Z.prototype)}}class Ie{constructor(e,t){this.prefix=e,this.enabled=t}print(e,...t){if(!this.enabled)return;const s=new Date,n=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(s);console[e](`[${n}]`,this.prefix,...t)}disable(){this.enabled=!1}error(...e){this.print("error",...e)}enable(){this.enabled=!0}log(...e){this.print("log",...e)}warn(...e){this.print("warn",...e)}}let Le="https://web.telegram.org";const I=new Ie("[SDK]",!1);function Et(r){if(r){I.enable();return}I.disable()}function Ct(r){Le=r}function vt(){return Le}const Pt=f({eventType:u(),eventData:r=>r});function St(r,e){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:r,eventData:e})}))}function kt(){const r=window;"TelegramGameProxy_receiveEvent"in r||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=r;e.forEach((s,n,i)=>{if(n===i.length-1){t[s]=St;return}s in t||(t[s]={}),t=t[s]})})}function xt(r){kt(),window.addEventListener("message",e=>{try{const{eventType:t,eventData:s}=Pt.parse(e.data);r(t,s)}catch{}})}function qt(){return f({req_id:u(),data:r=>r===null?r:u().optional().parse(r)})}function At(){return f({req_id:u(),result:r=>r,error:u().optional()})}function Rt(){return f({slug:u(),status:u()})}function Vt(){return f({status:u()})}function Tt(){return f({button_id:r=>r==null?void 0:u().parse(r)})}function It(){return f({data:u().optional()})}function Lt(){return f({theme_params:r=>{const e=ke().optional();return Object.entries(te(r)).reduce((t,[s,n])=>(t[s]=e.parse(n),t),{})}})}function Bt(){return f({height:q(),width:r=>r==null?window.innerWidth:q().parse(r),is_state_stable:S(),is_expanded:S()})}function $t(){return f({status:u()})}function Dt(){const r=new w,e=(t,...s)=>{I.log("Emitting processed event:",t,...s),r.emit(t,...s)};return window.addEventListener("resize",()=>{e("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),xt((t,s)=>{I.log("Received raw event:",t,s);try{switch(t){case"viewport_changed":return e(t,Bt().parse(s));case"theme_changed":return e(t,Lt().parse(s));case"popup_closed":return s==null?e(t,{}):e(t,Tt().parse(s));case"set_custom_style":return e(t,u().parse(s));case"qr_text_received":return e(t,It().parse(s));case"clipboard_text_received":return e(t,qt().parse(s));case"invoice_closed":return e(t,Rt().parse(s));case"phone_requested":return e("phone_requested",Vt().parse(s));case"custom_method_invoked":return e("custom_method_invoked",At().parse(s));case"write_access_requested":return e("write_access_requested",$t().parse(s));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":case"reload_iframe":return e(t);default:return e(t,s)}}catch(n){I.error("Error processing event:",n)}}),r}const K="telegram-mini-apps-cached-emitter";function M(){const r=window;return r[K]===void 0&&(r[K]=Dt()),r[K]}function R(r,e){M().off(r,e)}function y(r,e){return M().on(r,e),()=>R(r,e)}function Nt(r,e){return M().once(r,e),()=>R(r,e)}function Be(r){M().unsubscribe(r)}function Ht(r){return M().subscribe(r),()=>Be(r)}function $e(r,e){const t=r.split("."),s=e.split("."),n=Math.max(t.length,s.length);for(let i=0;i<n;i+=1){const a=parseInt(t[i]||"0",10),c=parseInt(s[i]||"0",10);if(a!==c)return a>c?1:-1}return 0}function P(r,e){return $e(r,e)<=0}function A(r,e,t){if(typeof t=="string"){if(r==="web_app_open_link"&&e==="try_instant_view")return P("6.4",t);if(r==="web_app_set_header_color"&&e==="color")return P("6.9",t)}switch(r){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return P("6.1",e);case"web_app_open_popup":return P("6.2",e);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return P("6.4",e);case"web_app_switch_inline_query":return P("6.7",e);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return P("6.9",e);case"web_app_setup_settings_button":return P("6.10",e);default:return!0}}function E(r,e){return t=>A(e[t],r)}function De(r,e){return t=>{const[s,n]=e[t];return A(s,n,r)}}function d(r,e,t){let s={},n;e===void 0&&t===void 0?s={}:e!==void 0&&t!==void 0?(s=t,n=e):e!==void 0&&("targetOrigin"in e?s=e:n=e);const{targetOrigin:i=vt()}=s;if(I.log(`Calling method "${r}"`,n),le()){window.parent.postMessage(JSON.stringify({eventType:r,eventData:n}),i);return}if(mt(window)){window.external.notify(JSON.stringify({eventType:r,eventData:n}));return}if(yt(window)){window.TelegramWebviewProxy.postEvent(r,JSON.stringify(n));return}throw new Error("Unable to determine current environment and possible way to send event.")}function Ne(r){return(e,t)=>{if(!A(e,r))throw new Q(e,r);if(L(t)){let s;if(e==="web_app_open_link"&&"try_instant_view"in t?s="try_instant_view":e==="web_app_set_header_color"&&"color"in t&&(s="color"),s&&!A(e,s,r))throw new Z(e,s,r)}return d(e,t)}}class U extends Error{constructor(e){super(`Async call timeout exceeded. Timeout: ${e}`),Object.setPrototypeOf(this,U.prototype)}}function Ot(r){return r instanceof U}function Wt(r){return new Promise(e=>{setTimeout(e,r)})}function Mt(r){return new Promise((e,t)=>{setTimeout(t,r,new U(r))})}function de(r,e){return Promise.race([r(),Mt(e)])}function b(r,e,t,s){let n,i,a,c;typeof e=="string"||Array.isArray(e)?(a=Array.isArray(e)?e:[e],n=t):(i=e,a=Array.isArray(t)?t:[t],n=s),L(i)&&typeof i.req_id=="string"&&(c=i.req_id);const{postEvent:p=d,timeout:h}=n||{},g=n&&"capture"in n?n.capture:null,_=()=>new Promise((V,l)=>{const C=a.map(v=>y(v,G=>{c&&(!L(G)||G.req_id!==c)||typeof g=="function"&&!g(G)||(x(),V(G))})),x=()=>C.forEach(v=>v());try{p(r,i)}catch(v){x(),l(v)}});return typeof h=="number"?de(_,h):_()}async function T(r,e,t,s={}){const{result:n,error:i}=await b("web_app_invoke_custom_method",{method:r,params:e,req_id:t},"custom_method_invoked",s);if(i)throw new Error(i);return n}class He{constructor(e,t,s=d){o(this,"ee",new w);o(this,"state");o(this,"on",(e,t)=>e==="click"?y("back_button_pressed",t):this.ee.on(e,t));o(this,"off",(e,t)=>e==="click"?R("back_button_pressed",t):this.ee.off(e,t));o(this,"supports");this.postEvent=s,this.state=new m({isVisible:e},this.ee),this.supports=E(t,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"})}set isVisible(e){this.state.set("isVisible",e),this.postEvent("web_app_setup_back_button",{is_visible:e})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function _e(r,e){return r+(r.length>0&&e.length>0?` ${e}`:e)}function Oe(...r){return r.reduce((e,t)=>{let s="";return typeof t=="string"?s=t:typeof t=="object"&&t!==null&&(s=Object.entries(t).reduce((n,[i,a])=>a?_e(n,i):n,"")),_e(e,s)},"")}function Ut(r){return typeof r=="object"&&r!==null&&!Array.isArray(null)}function Gt(...r){return r.reduce((e,t)=>(Ut(t)&&Object.entries(t).forEach(([s,n])=>{const i=Oe(e[s],n);i.length>0&&(e[s]=i)}),e),{})}class We{constructor(e,t=d){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.postEvent=t,this.state=new m({isConfirmationNeeded:e},this.ee)}set isConfirmationNeeded(e){this.state.set("isConfirmationNeeded",e),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:e})}get isConfirmationNeeded(){return this.state.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}function be(r,e){return r.reduce((t,s)=>(t[s]=e,t),{})}class Me{constructor(e,t,s=d){o(this,"supports");this.createRequestId=t,this.postEvent=s,this.supports=E(e,{delete:"web_app_invoke_custom_method",get:"web_app_invoke_custom_method",getKeys:"web_app_invoke_custom_method",set:"web_app_invoke_custom_method"})}async delete(e,t={}){const s=Array.isArray(e)?e:[e];s.length!==0&&await T("deleteStorageValues",{keys:s},this.createRequestId(),{...t,postEvent:this.postEvent})}async getKeys(e={}){const t=await T("getStorageKeys",{},this.createRequestId(),{...e,postEvent:this.postEvent});return ot().of(u()).parse(t)}async get(e,t={}){const s=Array.isArray(e)?e:[e];if(s.length===0)return be(s,"");const n=f(be(s,u())),i=await T("getStorageValues",{keys:s},this.createRequestId(),{...t,postEvent:this.postEvent}).then(a=>n.parse(a));return Array.isArray(e)?i:i[e]}async set(e,t,s={}){await T("saveStorageValue",{key:e,value:t},this.createRequestId(),{...s,postEvent:this.postEvent})}}class Ue{constructor(e,t=d){o(this,"supports");this.postEvent=t,this.supports=E(e,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"})}impactOccurred(e){this.postEvent("web_app_trigger_haptic_feedback",{type:"impact",impact_style:e})}notificationOccurred(e){this.postEvent("web_app_trigger_haptic_feedback",{type:"notification",notification_type:e})}selectionChanged(){this.postEvent("web_app_trigger_haptic_feedback",{type:"selection_change"})}}function jt(){const r=document.createElement("style");r.id="telegram-custom-styles",document.head.appendChild(r),y("set_custom_style",e=>{r.innerHTML=e})}function Ge(r){return`telegram-mini-apps-${r}`}function D(r,e){sessionStorage.setItem(Ge(r),JSON.stringify(e))}function N(r){const e=sessionStorage.getItem(Ge(r));return e?JSON.parse(e):null}function Ft(r,e,t){const{isVisible:s=!1}=r?N("back-button")||{}:{},n=new He(s,e,t);return n.on("change",()=>{D("back-button",{isVisible:n.isVisible})}),n}function zt(r,e){const{isConfirmationNeeded:t=!1}=r?N("closing-behavior")||{}:{},s=new We(t,e);return s.on("change",()=>D("closing-behavior",{isConfirmationNeeded:s.isConfirmationNeeded})),s}class je{constructor(e){o(this,"ee",new w);o(this,"state");o(this,"postEvent");o(this,"on",(e,t)=>e==="click"?y("main_button_pressed",t):this.ee.on(e,t));o(this,"off",(e,t)=>e==="click"?R("main_button_pressed",t):this.ee.off(e,t));const{postEvent:t=d,text:s,textColor:n,backgroundColor:i,isEnabled:a,isVisible:c,isLoaderVisible:p}=e;this.postEvent=t,this.state=new m({backgroundColor:i,isEnabled:a,isVisible:c,isLoaderVisible:p,text:s,textColor:n},this.ee)}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.backgroundColor,text_color:this.textColor})}set isEnabled(e){this.setParams({isEnabled:e})}get isEnabled(){return this.state.get("isEnabled")}set isLoaderVisible(e){this.setParams({isLoaderVisible:e})}get isLoaderVisible(){return this.state.get("isLoaderVisible")}set isVisible(e){this.setParams({isVisible:e})}get isVisible(){return this.state.get("isVisible")}get backgroundColor(){return this.state.get("backgroundColor")}get text(){return this.state.get("text")}get textColor(){return this.state.get("textColor")}disable(){return this.isEnabled=!1,this}enable(){return this.isEnabled=!0,this}hide(){return this.isVisible=!1,this}hideLoader(){return this.isLoaderVisible=!1,this}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(e){return this.setParams({text:e})}setTextColor(e){return this.setParams({textColor:e})}setBackgroundColor(e){return this.setParams({backgroundColor:e})}setParams(e){return this.state.set(e),this.commit(),this}}function Jt(r,e,t,s){const{backgroundColor:n=e,isEnabled:i=!1,isVisible:a=!1,isLoaderVisible:c=!1,textColor:p=t,text:h=""}=r?N("main-button")||{}:{},g=new je({backgroundColor:n,isEnabled:i,isLoaderVisible:c,isVisible:a,postEvent:s,text:h,textColor:p}),_=()=>D("main-button",{backgroundColor:g.backgroundColor,isEnabled:g.isEnabled,isLoaderVisible:g.isLoaderVisible,isVisible:g.isVisible,text:g.text,textColor:g.textColor});return g.on("change",_),g}const Qt=ie({contact:f({userId:{type:q(),from:"user_id"},phoneNumber:{type:u(),from:"phone_number"},firstName:{type:u(),from:"first_name"},lastName:{type:u().optional(),from:"last_name"}}),authDate:{type:Pe(),from:"auth_date"},hash:u()});class Fe{constructor(e){o(this,"ee",new w);o(this,"state");o(this,"botInline");o(this,"postEvent");o(this,"createRequestId");o(this,"requestingPhoneAccess",!1);o(this,"requestingWriteAccess",!1);o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");o(this,"supportsParam");const{postEvent:t=d,headerColor:s,backgroundColor:n,version:i,botInline:a,createRequestId:c}=e,p=E(i,{requestPhoneAccess:"web_app_request_phone",requestWriteAccess:"web_app_request_write_access",switchInlineQuery:"web_app_switch_inline_query",setHeaderColor:"web_app_set_header_color",setBackgroundColor:"web_app_set_background_color"});this.postEvent=t,this.botInline=a,this.createRequestId=c,this.supports=h=>!(!p(h)||h==="switchInlineQuery"&&!a),this.state=new m({backgroundColor:n,headerColor:s},this.ee),this.supportsParam=De(i,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact(){return T("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:1e4}).then(e=>Qt.parse(e))}get backgroundColor(){return this.state.get("backgroundColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.state.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return ne(this.backgroundColor)}get isRequestingPhoneAccess(){return this.requestingPhoneAccess}get isRequestingWriteAccess(){return this.requestingWriteAccess}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:e=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const s=Date.now()+e;let n=50;return de(async()=>{for(;Date.now()<s;){try{return await this.getRequestedContact()}catch{}await Wt(n),n+=50}throw new Error("Unable to retrieve requested contact.")},e)}requestPhoneAccess(e={}){if(this.requestingPhoneAccess)throw new Error("Phone access is already being requested.");return this.requestingPhoneAccess=!0,b("web_app_request_phone","phone_requested",{...e,postEvent:this.postEvent}).then(t=>t.status).finally(()=>{this.requestingPhoneAccess=!1})}requestWriteAccess(e={}){if(this.requestingWriteAccess)throw new Error("Write access is already being requested.");return this.requestingWriteAccess=!0,b("web_app_request_write_access","write_access_requested",{...e,postEvent:this.postEvent}).then(t=>t.status).finally(()=>{this.requestingWriteAccess=!1})}sendData(e){const{size:t}=new Blob([e]);if(t===0||t>4096)throw new Error(`Passed data has incorrect size: ${t}`);this.postEvent("web_app_data_send",{data:e})}setHeaderColor(e){this.postEvent("web_app_set_header_color",re(e)?{color:e}:{color_key:e}),this.state.set("headerColor",e)}setBackgroundColor(e){this.postEvent("web_app_set_background_color",{color:e}),this.state.set("backgroundColor",e)}switchInlineQuery(e,t=[]){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:e,chat_types:t})}}function Zt(r,e,t,s,n,i){const{backgroundColor:a=e,headerColor:c="bg_color"}=r?N("mini-app")||{}:{},p=new Fe({headerColor:c,backgroundColor:a,version:t,botInline:s,createRequestId:n,postEvent:i}),h=()=>D("mini-app",{backgroundColor:p.backgroundColor,headerColor:p.headerColor});return p.on("change",h),p}function Kt(){let r=0;return()=>(r+=1,r.toString())}class ze{constructor(e,t,s=d){o(this,"ee",new w);o(this,"state");o(this,"on",(e,t)=>e==="click"?y("settings_button_pressed",t):this.ee.on(e,t));o(this,"off",(e,t)=>e==="click"?R("settings_button_pressed",t):this.ee.off(e,t));o(this,"supports");this.postEvent=s,this.state=new m({isVisible:e},this.ee),this.supports=E(t,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"})}set isVisible(e){this.state.set("isVisible",e),this.postEvent("web_app_setup_settings_button",{is_visible:e})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function Yt(r,e,t){const{isVisible:s=!1}=r?N("settings-button")||{}:{},n=new ze(s,e,t);return n.on("change",()=>{D("settings-button",{isVisible:n.isVisible})}),n}function Xt(r){const e=new Re(r);return e.listen(),e}function Je(r){return["macos","tdesktop","unigram","web","weba"].includes(r)}async function fe(r){const e=await b("web_app_request_viewport","viewport_changed",r);return{height:e.height,width:e.width,isExpanded:e.is_expanded,isStateStable:e.is_state_stable}}function H(r){return r<0?0:r}class Qe{constructor(e){o(this,"ee",new w);o(this,"state");o(this,"postEvent");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));const{height:t,isExpanded:s,width:n,stableHeight:i,postEvent:a=d}=e;this.postEvent=a,this.state=new m({height:H(t),isExpanded:s,stableHeight:H(i),width:H(n)},this.ee)}sync(e){return fe(e).then(({height:t,isExpanded:s,width:n,isStateStable:i})=>{this.state.set({height:t,width:n,isExpanded:s,stableHeight:i?t:this.state.get("stableHeight")})})}get height(){return this.state.get("height")}get stableHeight(){return this.state.get("stableHeight")}listen(){return y("viewport_changed",e=>{const{height:t,width:s,is_expanded:n,is_state_stable:i}=e,a={height:H(t),isExpanded:n,width:H(s)};i&&(a.stableHeight=a.height),this.state.set(a)})}get isExpanded(){return this.state.get("isExpanded")}get width(){return this.state.get("width")}expand(){this.postEvent("web_app_expand"),this.state.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}function j(r){const e=new Qe(r);return e.on("change",()=>D("viewport",{height:e.height,isExpanded:e.isExpanded,stableHeight:e.stableHeight,width:e.width})),e.listen(),e}function er(r,e,t,s){const n=r?N("viewport"):null;if(n)return j({...n,postEvent:t});if(Je(e))return j({height:window.innerHeight,isExpanded:!0,postEvent:t,stableHeight:window.innerHeight,width:window.innerWidth});if(s)return fe({postEvent:t,timeout:5e3}).then(({height:a,isStateStable:c,...p})=>j({...p,height:a,stableHeight:c?a:0}));const i=j({width:0,height:0,isExpanded:!1,postEvent:t,stableHeight:0});return i.sync({postEvent:t,timeout:5e3}).catch(a=>{console.error("Unable to actualize viewport state",a)}),i}function k(r,e){document.documentElement.style.setProperty(r,e)}function tr(r,e){const t=()=>{k("--tg-background-color",r.backgroundColor)},s=()=>{const{backgroundColor:n,secondaryBackgroundColor:i}=e;r.headerColor==="bg_color"?n&&k("--tg-header-color",n):r.headerColor==="secondary_bg_color"?i&&k("--tg-header-color",i):k("--tg-header-color",r.headerColor)};e.on("change",s),r.on("change:backgroundColor",t),r.on("change:headerColor",s),t(),s()}function rr(r){const e=()=>{const t=r.getState();Object.entries(t).forEach(([s,n])=>{if(n){const i=s.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);k(`--tg-theme-${i}`,n)}})};r.on("change",e),e()}function me(r){const e=()=>k("--tg-viewport-height",`${r.height}px`),t=()=>k("--tg-viewport-width",`${r.width}px`),s=()=>k("--tg-viewport-height",`${r.stableHeight}px`);r.on("change:height",e),r.on("change:width",t),r.on("change:stableHeight",s),e(),t(),s()}function sr(r){return typeof r=="object"?r:r?{themeParams:!0,viewport:!0,miniApp:!0}:{}}function ye(r,e,t,s){const n=sr(r);n.miniApp&&tr(e,t),n.themeParams&&rr(t),n.viewport&&(s instanceof Promise?s.then(me):me(s))}function nr(r){const{hostname:e,pathname:t}=new URL(r,window.location.href);if(e!=="t.me")throw new Error(`Incorrect hostname: ${e}`);const s=t.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(s===null)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');return s[2]}class Ze{constructor(e,t=d){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=t,this.state=new m({isOpened:!1},this.ee),this.supports=E(e,{open:"web_app_open_invoice"})}set isOpened(e){this.state.set("isOpened",e)}get isOpened(){return this.state.get("isOpened")}async open(e,t){if(this.isOpened)throw new Error("Invoice is already opened");const s=t?nr(e):e;this.isOpened=!0;try{return(await b("web_app_open_invoice",{slug:s},"invoice_closed",{postEvent:this.postEvent,capture(i){return s===i.slug}})).status}finally{this.isOpened=!1}}}function ir(r){const e=r.message.trim(),t=(r.title||"").trim(),s=r.buttons||[];let n;if(t.length>64)throw new Error(`Title has incorrect size: ${t.length}`);if(e.length===0||e.length>256)throw new Error(`Message has incorrect size: ${e.length}`);if(s.length>3)throw new Error(`Buttons have incorrect size: ${s.length}`);return s.length===0?n=[{type:"close",id:""}]:n=s.map(i=>{const{id:a=""}=i;if(a.length>64)throw new Error(`Button ID has incorrect size: ${a}`);if(i.type===void 0||i.type==="default"||i.type==="destructive"){const c=i.text.trim();if(c.length===0||c.length>64){const p=i.type||"default";throw new Error(`Button text with type "${p}" has incorrect size: ${i.text.length}`)}return{...i,text:c,id:a}}return{...i,id:a}}),{title:t,message:e,buttons:n}}class Ke{constructor(e,t=d){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=t,this.state=new m({isOpened:!1},this.ee),this.supports=E(e,{open:"web_app_open_popup"})}set isOpened(e){this.state.set("isOpened",e)}get isOpened(){return this.state.get("isOpened")}open(e){if(this.isOpened)throw new Error("Popup is already opened.");return this.isOpened=!0,b("web_app_open_popup",ir(e),"popup_closed",{postEvent:this.postEvent}).then(({button_id:t=null})=>t).finally(()=>{this.isOpened=!1})}}class Ye{constructor(e,t=d){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=t,this.state=new m({isOpened:!1},this.ee),this.supports=E(e,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"})}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(e){this.state.set("isOpened",e)}get isOpened(){return this.state.get("isOpened")}async open(e){if(this.isOpened)throw new Error("QR scanner is already opened.");this.isOpened=!0;try{const t=await b("web_app_open_scan_qr_popup",{text:e},["qr_text_received","scan_qr_popup_closed"],{postEvent:this.postEvent});return typeof t=="object"&&typeof t.data=="string"?t.data:null}finally{this.isOpened=!1}}}class Xe{constructor(e,t,s=d){o(this,"supports");o(this,"supportsParam");this.version=e,this.createRequestId=t,this.postEvent=s,this.supports=E(e,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),this.supportsParam=De(e,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(e,t){const s=new URL(e,window.location.href).toString();if(!A("web_app_open_link",this.version)){window.open(s,"_blank");return}this.postEvent("web_app_open_link",{url:s,...typeof t=="boolean"?{try_instant_view:t}:{}})}openTelegramLink(e){const{hostname:t,pathname:s,search:n}=new URL(e,window.location.href);if(t!=="t.me")throw new Error(`URL has not allowed hostname: ${t}. Only "t.me" is allowed`);if(!A("web_app_open_tg_link",this.version)){window.location.href=e;return}this.postEvent("web_app_open_tg_link",{path_full:s+n})}readTextFromClipboard(){return b("web_app_read_text_from_clipboard",{req_id:this.createRequestId()},"clipboard_text_received",{postEvent:this.postEvent}).then(({data:e=null})=>e)}}function or(r={}){const{async:e=!1,complete:t=e,cssVars:s=!1,acceptCustomStyles:n=!1}=r;try{const{launchParams:{initData:i,initDataRaw:a,version:c,platform:p,themeParams:h,botInline:g=!1},isPageReload:_}=pe(),V=Kt(),l=Ne(c);le()&&(n&&jt(),l("iframe_ready",{reload_supported:!0}),y("reload_iframe",()=>window.location.reload()));const C={backButton:Ft(_,c,l),closingBehavior:zt(_,l),cloudStorage:new Me(c,V,l),createRequestId:V,hapticFeedback:new Ue(c,l),invoice:new Ze(c,l),mainButton:Jt(_,h.buttonColor||"#000000",h.buttonTextColor||"#ffffff",l),miniApp:Zt(_,h.backgroundColor||"#ffffff",c,g,V,l),popup:new Ke(c,l),postEvent:l,qrScanner:new Ye(c,l),settingsButton:Yt(_,c,l),themeParams:Xt(h),utils:new Xe(c,V,l),...i?{initData:new qe(i),initDataRaw:a}:{}},x=er(_,p,l,t);return x instanceof Promise||t?Promise.resolve(x).then(v=>(ye(s,C.miniApp,C.themeParams,v),{...C,viewport:v})):(ye(s,C.miniApp,C.themeParams,x),{...C,viewport:x})}catch(i){if(t)return Promise.reject(i);throw i}}function O(r,e){return r.startsWith(e)?r:`${e}${r}`}function ar(r){const e=r.match(/#(.+)/);return e?e[1]:null}async function W(r){return r===0?!0:Promise.race([new Promise(e=>{window.addEventListener("popstate",function t(){window.removeEventListener("popstate",t),e(!0)}),window.history.go(r)}),new Promise(e=>{setTimeout(e,50,!1)})])}async function cr(){if(window.history.length<=1||(window.history.pushState(null,""),await W(1-window.history.length)))return;let e=await W(-1);for(;e;)e=await W(-1)}class et{constructor(e,t,{debug:s=!1,loggerPrefix:n="Navigator"}){o(this,"logger");o(this,"entries");if(this.entriesCursor=t,e.length===0)throw new Error("Entries list should not be empty.");if(t>=e.length)throw new Error("Cursor should be less than entries count.");this.entries=e.map(({pathname:i="",search:a,hash:c})=>{if(!i.startsWith("/")&&i.length>0)throw new Error('Pathname should start with "/"');return{pathname:O(i,"/"),search:a?O(a,"?"):"",hash:c?O(c,"#"):""}}),this.logger=new Ie(`[${n}]`,s)}formatEntry(e){let t;if(typeof e=="string")t=e;else{const{pathname:a="",search:c,hash:p}=e;t=a+(c?O(c,"?"):"")+(p?O(p,"#"):"")}const{pathname:s,search:n,hash:i}=new URL(t,`https://localhost${this.path}`);return{pathname:s,search:n,hash:i}}get entry(){return this.entries[this.entriesCursor]}back(){return this.go(-1)}get cursor(){return this.entriesCursor}get canGoBack(){return this.entriesCursor>0}get canGoForward(){return this.entriesCursor!==this.entries.length-1}forward(){return this.go(1)}go(e){this.logger.log(`called go(${e})`);const t=Math.min(this.entries.length-1,Math.max(this.entriesCursor+e,0));if(this.entriesCursor===t)return this.performGo({updated:!1,delta:e});const s=this.entry;this.entriesCursor=t;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performGo({updated:!0,delta:e,before:s,after:n})}getEntries(){return this.entries.map(e=>({...e}))}get hash(){return this.entry.hash}push(e){this.entriesCursor!==this.entries.length-1&&this.entries.splice(this.entriesCursor+1);const t=this.formatEntry(e),s=this.entry;this.entriesCursor+=1,this.entries[this.entriesCursor]=t;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performPush({before:s,after:n})}get path(){return`${this.pathname}${this.search}${this.hash}`}get pathname(){return this.entry.pathname}replace(e){const t=this.formatEntry(e);if(this.search===t.search&&this.pathname===t.pathname&&this.hash===t.hash)return this.performReplace({updated:!1,entry:t});const s=this.entry;this.entries[this.entriesCursor]=t;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performReplace({updated:!0,before:s,after:n})}get search(){return this.entry.search}}const Ee=0,Y=1,X=2;class ge extends et{constructor(t,s,n={}){super(t,s,{...n,loggerPrefix:"HashNavigator"});o(this,"ee",new w);o(this,"attached",!1);o(this,"onPopState",async({state:t})=>{if(this.logger.log('"popstate" event received. State:',t),t===null)return this.push(window.location.hash.slice(1));if(t===Ee){this.logger.log("Void reached. Moving history forward"),window.history.forward();return}if(t===Y)return this.back();if(t===X)return this.forward()});o(this,"back",()=>super.back());o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee))}static fromLocation(t){const{search:s,pathname:n,hash:i}=new URL(window.location.hash.slice(1),window.location.href);return new ge([{search:s,pathname:n,hash:i}],0,t)}async performGo(t){t.updated&&(this.attached&&await this.syncHistory(),this.emitChanged(t.before,t.after))}async performPush({before:t,after:s}){this.attached&&await this.syncHistory(),this.emitChanged(t,s)}async performReplace(t){t.updated&&(this.attached&&window.history.replaceState(null,"",`#${this.path}`),this.emitChanged(t.before,t.after))}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const t=`#${this.path}`;await cr(),d("web_app_setup_back_button",{is_visible:this.canGoBack}),this.canGoBack&&this.canGoForward?(this.logger.log("Setting up history: [<-, *, ->]"),window.history.replaceState(Y,""),window.history.pushState(null,"",t),window.history.pushState(X,""),await W(-1)):this.canGoBack?(this.logger.log("Setting up history: [<-, *]"),window.history.replaceState(Y,""),window.history.pushState(null,"",t)):this.canGoForward?(this.logger.log("Setting up history: [*, ->]"),window.history.replaceState(null,t),window.history.pushState(X,""),await W(-1)):(this.logger.log("Setting up history: [~, *]"),window.history.replaceState(Ee,""),window.history.pushState(null,"",t)),window.addEventListener("popstate",this.onPopState)}emitChanged(t,s){this.ee.emit("change",{navigator:this,from:t,to:s})}async attach(){if(!this.attached)return this.logger.log("Attaching",this),this.attached=!0,y("back_button_pressed",this.back),this.syncHistory()}detach(){this.attached&&(this.logger.log("Detaching",this),this.attached=!1,window.removeEventListener("popstate",this.onPopState),R("back_button_pressed",this.back))}}exports.BackButton=He;exports.ClosingBehavior=We;exports.CloudStorage=Me;exports.HapticFeedback=Ue;exports.HashNavigator=ge;exports.InitData=qe;exports.Invoice=Ze;exports.MainButton=je;exports.MethodUnsupportedError=Q;exports.MiniApp=Fe;exports.Navigator=et;exports.ParameterUnsupportedError=Z;exports.Popup=Ke;exports.QRScanner=Ye;exports.SettingsButton=ze;exports.ThemeParams=Re;exports.TimeoutError=U;exports.Utils=Xe;exports.Viewport=Qe;exports.chatParser=xe;exports.classNames=Oe;exports.compareVersions=$e;exports.createPostEvent=Ne;exports.getHash=ar;exports.init=or;exports.initDataParser=oe;exports.invokeCustomMethod=T;exports.isColorDark=ne;exports.isIframe=le;exports.isRGB=re;exports.isRGBShort=Se;exports.isRecord=L;exports.isStableViewportPlatform=Je;exports.isTMA=bt;exports.isTimeoutError=Ot;exports.launchParamsParser=ue;exports.mergeClassNames=Gt;exports.off=R;exports.on=y;exports.once=Nt;exports.parseInitData=at;exports.parseLaunchParams=he;exports.parseThemeParams=ce;exports.postEvent=d;exports.request=b;exports.requestThemeParams=ht;exports.requestViewport=fe;exports.retrieveLaunchData=pe;exports.serializeLaunchParams=Ve;exports.serializeThemeParams=Ae;exports.setDebug=Et;exports.setTargetOrigin=Ct;exports.subscribe=Ht;exports.supports=A;exports.themeParamsParser=ae;exports.toRGB=se;exports.unsubscribe=Be;exports.userParser=ee;exports.withTimeout=de;
|
|
1
|
+
"use strict";var st=Object.defineProperty;var nt=(r,e,t)=>e in r?st(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var o=(r,e,t)=>(nt(r,typeof e!="symbol"?e+"":e,t),t);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});function L(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function ve(){return performance.getEntriesByType("navigation")[0]||null}function it(){const r=ve();return r?r.type==="reload":null}function B(){return new TypeError("Value has unexpected type")}class U extends Error{constructor(t,{cause:s,type:n}={}){super(`Unable to parse value${n?` as ${n}`:""}`,{cause:s});o(this,"type");this.value=t,Object.setPrototypeOf(this,U.prototype),this.type=n}}class J{constructor(e,t,s){this.parser=e,this.isOptional=t,this.type=s}parse(e){if(!(this.isOptional&&e===void 0))try{return this.parser(e)}catch(t){throw new U(e,{type:this.type,cause:t})}}optional(){return this.isOptional=!0,this}}function ot(r){if(Array.isArray(r))return r;if(typeof r=="string")try{const e=JSON.parse(r);if(Array.isArray(e))return e}catch{}throw B()}class at extends J{constructor(t,s,n){super(ot,s,n);o(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 $(r,e){return()=>new J(r,!1,e)}class M extends Error{constructor(e,{cause:t,type:s}={}){super(`Unable to parse field "${e}"${s?` as ${s}`:""}`,{cause:t}),Object.setPrototypeOf(this,M.prototype)}}function Pe(r,e){const t={};for(const s in r){const n=r[s];if(!n)continue;let i,a;if(typeof n=="function"||"parse"in n)i=s,a=typeof n=="function"?n:n.parse.bind(n);else{const{type:h}=n;i=n.from||s,a=typeof h=="function"?h:h.parse.bind(h)}let c;const p=e(i);try{c=a(p)}catch(h){throw h instanceof U?new M(i,{type:h.type,cause:h}):new M(i,{cause:h})}c!==void 0&&(t[s]=c)}return t}function Se(r){return new at(e=>e,!1,r)}const E=$(r=>{if(typeof r=="boolean")return r;const e=String(r);if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw B()},"boolean"),x=$(r=>{if(typeof r=="number")return r;if(typeof r=="string"){const e=Number(r);if(!Number.isNaN(e))return e}throw B()},"number"),re=$(r=>r instanceof Date?r:new Date(x().parse(r)*1e3),"Date");function se(r){let e=r;if(typeof e=="string"&&(e=JSON.parse(e)),typeof e!="object"||e===null||Array.isArray(e))throw B();return e}function f(r,e){return new J(t=>{const s=se(t);return Pe(r,n=>s[n])},!1,e)}function ne(r){return/^#[\da-f]{6}$/i.test(r)}function ke(r){return/^#[\da-f]{3}$/i.test(r)}function ie(r){const e=r.replace(/\s/g,"").toLowerCase();if(ne(e))return e;if(ke(e)){let s="#";for(let n=0;n<3;n+=1)s+=e[1+n].repeat(2);return s}const t=e.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||e.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(t===null)throw new Error(`Value "${r}" does not satisfy any of known RGB formats.`);return t.slice(1).reduce((s,n)=>{const i=parseInt(n,10).toString(16);return s+(i.length===1?"0":"")+i},"#")}function oe(r){const e=ie(r);return Math.sqrt([.299,.587,.114].reduce((s,n,i)=>{const a=parseInt(e.slice(1+i*2,1+(i+1)*2),16);return s+a*a*n},0))<120}const u=$(r=>{if(typeof r=="string"||typeof r=="number")return r.toString();throw B()},"string"),ae=$(r=>ie(u().parse(r)),"rgb");function Q(r,e){return new J(t=>{if(typeof t!="string"&&!(t instanceof URLSearchParams))throw B();const s=typeof t=="string"?new URLSearchParams(t):t;return Pe(r,n=>{const i=s.get(n);return i===null?void 0:i})},!1,e)}function xe(){return f({id:x(),type:u(),title:u(),photoUrl:{type:u().optional(),from:"photo_url"},username:u().optional()},"Chat")}class qe{constructor(e){this.initData=e}get authDate(){return this.initData.authDate}get canSendAfter(){return this.initData.canSendAfter}get canSendAfterDate(){const{canSendAfter:e}=this;return e===void 0?void 0:new Date(this.authDate.getTime()+e*1e3)}get chat(){return this.initData.chat}get chatType(){return this.initData.chatType}get chatInstance(){return this.initData.chatInstance}get hash(){return this.initData.hash}get queryId(){return this.initData.queryId}get receiver(){return this.initData.receiver}get startParam(){return this.initData.startParam}get user(){return this.initData.user}}function te(){return f({addedToAttachmentMenu:{type:E().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:E().optional(),from:"allows_write_to_pm"},firstName:{type:u(),from:"first_name"},id:x(),isBot:{type:E().optional(),from:"is_bot"},isPremium:{type:E().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")}function ce(){return Q({authDate:{type:re(),from:"auth_date"},canSendAfter:{type:x().optional(),from:"can_send_after"},chat:xe().optional(),chatInstance:{type:u().optional(),from:"chat_instance"},chatType:{type:u().optional(),from:"chat_type"},hash:u(),queryId:{type:u().optional(),from:"query_id"},receiver:te().optional(),startParam:{type:u().optional(),from:"start_param"},user:te().optional()},"InitData")}function ct(r){return ce().parse(r)}function ut(r){return r.replace(/(^|_)bg/,(e,t)=>`${t}background`).replace(/_([a-z])/g,(e,t)=>t.toUpperCase())}function ht(r){return r.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`).replace(/(^|_)background/,(e,t)=>`${t}bg`)}const ue=$(r=>{const e=ae().optional();return Object.entries(se(r)).reduce((t,[s,n])=>(t[ut(s)]=e.parse(n),t),{})},"ThemeParams");function he(r){return ue().parse(r)}function pt(r={}){return b("web_app_request_theme","theme_changed",r).then(he)}function Ae(r){return JSON.stringify(Object.entries(r).reduce((e,[t,s])=>(s&&(e[ht(t)]=s),e),{}))}class w{constructor(){o(this,"listeners",new Map);o(this,"subscribeListeners",[])}addListener(e,t,s){let n=this.listeners.get(e);return n||(n=[],this.listeners.set(e,n)),n.push([t,s]),()=>this.off(e,t)}emit(e,...t){this.subscribeListeners.forEach(n=>n(e,...t));const s=this.listeners.get(e);s&&s.forEach(([n,i],a)=>{n(...t),i&&s.splice(a,1)})}on(e,t){return this.addListener(e,t,!1)}once(e,t){return this.addListener(e,t,!0)}off(e,t){const s=this.listeners.get(e);if(s){for(let n=0;n<s.length;n+=1)if(t===s[n][0]){s.splice(n,1);return}}}subscribe(e){return this.subscribeListeners.push(e),()=>this.unsubscribe(e)}unsubscribe(e){for(let t=0;t<this.subscribeListeners.length;t+=1)if(this.subscribeListeners[t]===e){this.subscribeListeners.splice(t,1);return}}}class m{constructor(e,t){this.state=e,this.ee=t}internalSet(e,t){return this.state[e]===t||t===void 0?!1:(this.state[e]=t,this.ee.emit(`change:${e}`,t),!0)}clone(){return{...this.state}}set(e,t){let s=!1;if(typeof e=="string")s=this.internalSet(e,t);else for(const n in e)this.internalSet(n,e[n])&&(s=!0);s&&this.ee.emit("change")}get(e){return this.state[e]}}class Re{constructor(e){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.state=new m(e,this.ee)}get accentTextColor(){return this.get("accentTextColor")}get backgroundColor(){return this.get("backgroundColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}get(e){return this.state.get(e)}getState(){return this.state.clone()}get headerBackgroundColor(){return this.get("headerBackgroundColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.backgroundColor||oe(this.backgroundColor)}get linkColor(){return this.get("linkColor")}get secondaryBackgroundColor(){return this.get("secondaryBackgroundColor")}get sectionBackgroundColor(){return this.get("sectionBackgroundColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}listen(){return y("theme_changed",e=>{this.state.set(he(e.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}function pe(){return Q({botInline:{type:E().optional(),from:"tgWebAppBotInline"},initData:{type:ce().optional(),from:"tgWebAppData"},initDataRaw:{type:u().optional(),from:"tgWebAppData"},platform:{type:u(),from:"tgWebAppPlatform"},showSettings:{type:E().optional(),from:"tgWebAppShowSettings"},startParam:{type:u().optional(),from:"tgWebAppStartParam"},themeParams:{type:ue(),from:"tgWebAppThemeParams"},version:{type:u(),from:"tgWebAppVersion"}},"LaunchParams")}function Ve(r){return pe().parse(r)}function Te(r){const e=r.includes("?")?r.replace("#","&").slice(r.indexOf("?")+1):r.slice(r.indexOf("#")+1);return Ve(e)}function lt(){return Te(window.location.href)}function dt(){const r=ve();if(!r)throw new Error("Unable to get first navigation entry.");return Te(r.name)}function ft(){try{return dt()}catch{}try{return lt()}catch{}return null}function Ie(r){const{initDataRaw:e,themeParams:t,platform:s,version:n,showSettings:i,botInline:a}=r,c=new URLSearchParams;return e&&c.set("tgWebAppData",e),c.set("tgWebAppPlatform",s),c.set("tgWebAppThemeParams",Ae(t)),c.set("tgWebAppVersion",n),typeof i=="boolean"&&c.set("tgWebAppShowSettings",i?"1":"0"),typeof a=="boolean"&&c.set("tgWebAppBotInline",a?"1":"0"),c.toString()}const Le="telegram-mini-apps-launch-params";function gt(){const r=sessionStorage.getItem(Le);return r?pe().parse(r):null}function wt(r){sessionStorage.setItem(Le,Ie(r))}function _t(){try{return window.self!==window.top}catch{return!0}}function bt(){const r=gt(),e=ft(),t=it();if(r){if(e)return{launchParams:e,isPageReload:_t()?t||r.initDataRaw===e.initDataRaw:!0};if(t)return{launchParams:r,isPageReload:t};throw new Error("Unable to retrieve current launch parameters, which must exist.")}if(e)return{launchParams:e,isPageReload:!1};throw new Error("Unable to retrieve any launch parameters.")}const _e="tmajsLaunchData";function le(){const r=window[_e];if(r)return r;const e=bt();return window[_e]=e,wt(e.launchParams),e}function mt(){try{return le(),!0}catch{return!1}}function yt(r){return"external"in r&&L(r.external)&&"notify"in r.external&&typeof r.external.notify=="function"}function Et(r){return"TelegramWebviewProxy"in r&&L(r.TelegramWebviewProxy)&&"postEvent"in r.TelegramWebviewProxy&&typeof r.TelegramWebviewProxy.postEvent=="function"}function de(){try{return window.self!==window.top}catch{return!0}}class Z extends Error{constructor(e,t){super(`Method "${e}" is unsupported in the Mini Apps version ${t}.`),Object.setPrototypeOf(this,Z.prototype)}}class K extends Error{constructor(e,t,s){super(`Parameter "${t}" in method "${e}" is unsupported in the Mini Apps version ${s}.`),Object.setPrototypeOf(this,K.prototype)}}class Be{constructor(e,t){this.prefix=e,this.enabled=t}print(e,...t){if(!this.enabled)return;const s=new Date,n=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(s);console[e](`[${n}]`,this.prefix,...t)}disable(){this.enabled=!1}error(...e){this.print("error",...e)}enable(){this.enabled=!0}log(...e){this.print("log",...e)}warn(...e){this.print("warn",...e)}}let $e="https://web.telegram.org";const I=new Be("[SDK]",!1);function Ct(r){if(r){I.enable();return}I.disable()}function vt(r){$e=r}function Pt(){return $e}const St=f({eventType:u(),eventData:r=>r});function kt(r,e){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:r,eventData:e})}))}function xt(){const r=window;"TelegramGameProxy_receiveEvent"in r||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=r;e.forEach((s,n,i)=>{if(n===i.length-1){t[s]=kt;return}s in t||(t[s]={}),t=t[s]})})}function qt(r){xt(),window.addEventListener("message",e=>{try{const{eventType:t,eventData:s}=St.parse(e.data);r(t,s)}catch{}})}function At(){return f({req_id:u(),data:r=>r===null?r:u().optional().parse(r)})}function Rt(){return f({req_id:u(),result:r=>r,error:u().optional()})}function Vt(){return f({slug:u(),status:u()})}function Tt(){return f({status:u()})}function It(){return f({button_id:r=>r==null?void 0:u().parse(r)})}function Lt(){return f({data:u().optional()})}function Bt(){return f({theme_params:r=>{const e=ae().optional();return Object.entries(se(r)).reduce((t,[s,n])=>(t[s]=e.parse(n),t),{})}})}function $t(){return f({height:x(),width:r=>r==null?window.innerWidth:x().parse(r),is_state_stable:E(),is_expanded:E()})}function Dt(){return f({status:u()})}function Nt(){const r=new w,e=(t,...s)=>{I.log("Emitting processed event:",t,...s),r.emit(t,...s)};return window.addEventListener("resize",()=>{e("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),qt((t,s)=>{I.log("Received raw event:",t,s);try{switch(t){case"viewport_changed":return e(t,$t().parse(s));case"theme_changed":return e(t,Bt().parse(s));case"popup_closed":return s==null?e(t,{}):e(t,It().parse(s));case"set_custom_style":return e(t,u().parse(s));case"qr_text_received":return e(t,Lt().parse(s));case"clipboard_text_received":return e(t,At().parse(s));case"invoice_closed":return e(t,Vt().parse(s));case"phone_requested":return e("phone_requested",Tt().parse(s));case"custom_method_invoked":return e("custom_method_invoked",Rt().parse(s));case"write_access_requested":return e("write_access_requested",Dt().parse(s));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":case"reload_iframe":return e(t);default:return e(t,s)}}catch(n){I.error("Error processing event:",n)}}),r}const Y="telegram-mini-apps-cached-emitter";function j(){const r=window;return r[Y]===void 0&&(r[Y]=Nt()),r[Y]}function R(r,e){j().off(r,e)}function y(r,e){return j().on(r,e),()=>R(r,e)}function Ot(r,e){return j().once(r,e),()=>R(r,e)}function De(r){j().unsubscribe(r)}function Wt(r){return j().subscribe(r),()=>De(r)}function Ne(r,e){const t=r.split("."),s=e.split("."),n=Math.max(t.length,s.length);for(let i=0;i<n;i+=1){const a=parseInt(t[i]||"0",10),c=parseInt(s[i]||"0",10);if(a!==c)return a>c?1:-1}return 0}function S(r,e){return Ne(r,e)<=0}function A(r,e,t){if(typeof t=="string"){if(r==="web_app_open_link"&&e==="try_instant_view")return S("6.4",t);if(r==="web_app_set_header_color"&&e==="color")return S("6.9",t)}switch(r){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return S("6.1",e);case"web_app_open_popup":return S("6.2",e);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return S("6.4",e);case"web_app_switch_inline_query":return S("6.7",e);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return S("6.9",e);case"web_app_setup_settings_button":return S("6.10",e);default:return!0}}function C(r,e){return t=>A(e[t],r)}function Oe(r,e){return t=>{const[s,n]=e[t];return A(s,n,r)}}function d(r,e,t){let s={},n;e===void 0&&t===void 0?s={}:e!==void 0&&t!==void 0?(s=t,n=e):e!==void 0&&("targetOrigin"in e?s=e:n=e);const{targetOrigin:i=Pt()}=s;if(I.log(`Calling method "${r}"`,n),de()){window.parent.postMessage(JSON.stringify({eventType:r,eventData:n}),i);return}if(yt(window)){window.external.notify(JSON.stringify({eventType:r,eventData:n}));return}if(Et(window)){window.TelegramWebviewProxy.postEvent(r,JSON.stringify(n));return}throw new Error("Unable to determine current environment and possible way to send event.")}function We(r){return(e,t)=>{if(!A(e,r))throw new Z(e,r);if(L(t)){let s;if(e==="web_app_open_link"&&"try_instant_view"in t?s="try_instant_view":e==="web_app_set_header_color"&&"color"in t&&(s="color"),s&&!A(e,s,r))throw new K(e,s,r)}return d(e,t)}}class G extends Error{constructor(e){super(`Async call timeout exceeded. Timeout: ${e}`),Object.setPrototypeOf(this,G.prototype)}}function Ht(r){return r instanceof G}function Mt(r){return new Promise(e=>{setTimeout(e,r)})}function Ut(r){return new Promise((e,t)=>{setTimeout(t,r,new G(r))})}function fe(r,e){return Promise.race([r(),Ut(e)])}function b(r,e,t,s){let n,i,a,c;typeof e=="string"||Array.isArray(e)?(a=Array.isArray(e)?e:[e],n=t):(i=e,a=Array.isArray(t)?t:[t],n=s),L(i)&&typeof i.req_id=="string"&&(c=i.req_id);const{postEvent:p=d,timeout:h}=n||{},g=n&&"capture"in n?n.capture:null,_=()=>new Promise((V,l)=>{const v=a.map(P=>y(P,F=>{c&&(!L(F)||F.req_id!==c)||typeof g=="function"&&!g(F)||(q(),V(F))})),q=()=>v.forEach(P=>P());try{p(r,i)}catch(P){q(),l(P)}});return typeof h=="number"?fe(_,h):_()}async function T(r,e,t,s={}){const{result:n,error:i}=await b("web_app_invoke_custom_method",{method:r,params:e,req_id:t},"custom_method_invoked",s);if(i)throw new Error(i);return n}class He{constructor(e,t,s=d){o(this,"ee",new w);o(this,"state");o(this,"on",(e,t)=>e==="click"?y("back_button_pressed",t):this.ee.on(e,t));o(this,"off",(e,t)=>e==="click"?R("back_button_pressed",t):this.ee.off(e,t));o(this,"supports");this.postEvent=s,this.state=new m({isVisible:e},this.ee),this.supports=C(t,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"})}set isVisible(e){this.state.set("isVisible",e),this.postEvent("web_app_setup_back_button",{is_visible:e})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function be(r,e){return r+(r.length>0&&e.length>0?` ${e}`:e)}function Me(...r){return r.reduce((e,t)=>{let s="";return typeof t=="string"?s=t:typeof t=="object"&&t!==null&&(s=Object.entries(t).reduce((n,[i,a])=>a?be(n,i):n,"")),be(e,s)},"")}function jt(r){return typeof r=="object"&&r!==null&&!Array.isArray(null)}function Gt(...r){return r.reduce((e,t)=>(jt(t)&&Object.entries(t).forEach(([s,n])=>{const i=Me(e[s],n);i.length>0&&(e[s]=i)}),e),{})}class Ue{constructor(e,t=d){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.postEvent=t,this.state=new m({isConfirmationNeeded:e},this.ee)}set isConfirmationNeeded(e){this.state.set("isConfirmationNeeded",e),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:e})}get isConfirmationNeeded(){return this.state.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}function me(r,e){return r.reduce((t,s)=>(t[s]=e,t),{})}class je{constructor(e,t,s=d){o(this,"supports");this.createRequestId=t,this.postEvent=s,this.supports=C(e,{delete:"web_app_invoke_custom_method",get:"web_app_invoke_custom_method",getKeys:"web_app_invoke_custom_method",set:"web_app_invoke_custom_method"})}async delete(e,t={}){const s=Array.isArray(e)?e:[e];s.length!==0&&await T("deleteStorageValues",{keys:s},this.createRequestId(),{...t,postEvent:this.postEvent})}async getKeys(e={}){const t=await T("getStorageKeys",{},this.createRequestId(),{...e,postEvent:this.postEvent});return Se().of(u()).parse(t)}async get(e,t={}){const s=Array.isArray(e)?e:[e];if(s.length===0)return me(s,"");const n=f(me(s,u())),i=await T("getStorageValues",{keys:s},this.createRequestId(),{...t,postEvent:this.postEvent}).then(a=>n.parse(a));return Array.isArray(e)?i:i[e]}async set(e,t,s={}){await T("saveStorageValue",{key:e,value:t},this.createRequestId(),{...s,postEvent:this.postEvent})}}class Ge{constructor(e,t=d){o(this,"supports");this.postEvent=t,this.supports=C(e,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"})}impactOccurred(e){this.postEvent("web_app_trigger_haptic_feedback",{type:"impact",impact_style:e})}notificationOccurred(e){this.postEvent("web_app_trigger_haptic_feedback",{type:"notification",notification_type:e})}selectionChanged(){this.postEvent("web_app_trigger_haptic_feedback",{type:"selection_change"})}}function Ft(){const r=document.createElement("style");r.id="telegram-custom-styles",document.head.appendChild(r),y("set_custom_style",e=>{r.innerHTML=e})}function Fe(r){return`telegram-mini-apps-${r}`}function D(r,e){sessionStorage.setItem(Fe(r),JSON.stringify(e))}function N(r){const e=sessionStorage.getItem(Fe(r));return e?JSON.parse(e):null}function zt(r,e,t){const{isVisible:s=!1}=r?N("back-button")||{}:{},n=new He(s,e,t);return n.on("change",()=>{D("back-button",{isVisible:n.isVisible})}),n}function Jt(r,e){const{isConfirmationNeeded:t=!1}=r?N("closing-behavior")||{}:{},s=new Ue(t,e);return s.on("change",()=>D("closing-behavior",{isConfirmationNeeded:s.isConfirmationNeeded})),s}class ze{constructor(e){o(this,"ee",new w);o(this,"state");o(this,"postEvent");o(this,"on",(e,t)=>e==="click"?y("main_button_pressed",t):this.ee.on(e,t));o(this,"off",(e,t)=>e==="click"?R("main_button_pressed",t):this.ee.off(e,t));const{postEvent:t=d,text:s,textColor:n,backgroundColor:i,isEnabled:a,isVisible:c,isLoaderVisible:p}=e;this.postEvent=t,this.state=new m({backgroundColor:i,isEnabled:a,isVisible:c,isLoaderVisible:p,text:s,textColor:n},this.ee)}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.backgroundColor,text_color:this.textColor})}set isEnabled(e){this.setParams({isEnabled:e})}get isEnabled(){return this.state.get("isEnabled")}set isLoaderVisible(e){this.setParams({isLoaderVisible:e})}get isLoaderVisible(){return this.state.get("isLoaderVisible")}set isVisible(e){this.setParams({isVisible:e})}get isVisible(){return this.state.get("isVisible")}get backgroundColor(){return this.state.get("backgroundColor")}get text(){return this.state.get("text")}get textColor(){return this.state.get("textColor")}disable(){return this.isEnabled=!1,this}enable(){return this.isEnabled=!0,this}hide(){return this.isVisible=!1,this}hideLoader(){return this.isLoaderVisible=!1,this}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(e){return this.setParams({text:e})}setTextColor(e){return this.setParams({textColor:e})}setBackgroundColor(e){return this.setParams({backgroundColor:e})}setParams(e){return this.state.set(e),this.commit(),this}}function Qt(r,e,t,s){const{backgroundColor:n=e,isEnabled:i=!1,isVisible:a=!1,isLoaderVisible:c=!1,textColor:p=t,text:h=""}=r?N("main-button")||{}:{},g=new ze({backgroundColor:n,isEnabled:i,isLoaderVisible:c,isVisible:a,postEvent:s,text:h,textColor:p}),_=()=>D("main-button",{backgroundColor:g.backgroundColor,isEnabled:g.isEnabled,isLoaderVisible:g.isLoaderVisible,isVisible:g.isVisible,text:g.text,textColor:g.textColor});return g.on("change",_),g}const Zt=Q({contact:f({userId:{type:x(),from:"user_id"},phoneNumber:{type:u(),from:"phone_number"},firstName:{type:u(),from:"first_name"},lastName:{type:u().optional(),from:"last_name"}}),authDate:{type:re(),from:"auth_date"},hash:u()});class Je{constructor(e){o(this,"ee",new w);o(this,"state");o(this,"botInline");o(this,"postEvent");o(this,"createRequestId");o(this,"requestingPhoneAccess",!1);o(this,"requestingWriteAccess",!1);o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");o(this,"supportsParam");const{postEvent:t=d,headerColor:s,backgroundColor:n,version:i,botInline:a,createRequestId:c}=e,p=C(i,{requestPhoneAccess:"web_app_request_phone",requestWriteAccess:"web_app_request_write_access",switchInlineQuery:"web_app_switch_inline_query",setHeaderColor:"web_app_set_header_color",setBackgroundColor:"web_app_set_background_color"});this.postEvent=t,this.botInline=a,this.createRequestId=c,this.supports=h=>!(!p(h)||h==="switchInlineQuery"&&!a),this.state=new m({backgroundColor:n,headerColor:s},this.ee),this.supportsParam=Oe(i,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact(){return T("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:1e4}).then(e=>Zt.parse(e))}get backgroundColor(){return this.state.get("backgroundColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.state.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return oe(this.backgroundColor)}get isRequestingPhoneAccess(){return this.requestingPhoneAccess}get isRequestingWriteAccess(){return this.requestingWriteAccess}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:e=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const s=Date.now()+e;let n=50;return fe(async()=>{for(;Date.now()<s;){try{return await this.getRequestedContact()}catch{}await Mt(n),n+=50}throw new Error("Unable to retrieve requested contact.")},e)}requestPhoneAccess(e={}){if(this.requestingPhoneAccess)throw new Error("Phone access is already being requested.");return this.requestingPhoneAccess=!0,b("web_app_request_phone","phone_requested",{...e,postEvent:this.postEvent}).then(t=>t.status).finally(()=>{this.requestingPhoneAccess=!1})}requestWriteAccess(e={}){if(this.requestingWriteAccess)throw new Error("Write access is already being requested.");return this.requestingWriteAccess=!0,b("web_app_request_write_access","write_access_requested",{...e,postEvent:this.postEvent}).then(t=>t.status).finally(()=>{this.requestingWriteAccess=!1})}sendData(e){const{size:t}=new Blob([e]);if(t===0||t>4096)throw new Error(`Passed data has incorrect size: ${t}`);this.postEvent("web_app_data_send",{data:e})}setHeaderColor(e){this.postEvent("web_app_set_header_color",ne(e)?{color:e}:{color_key:e}),this.state.set("headerColor",e)}setBackgroundColor(e){this.postEvent("web_app_set_background_color",{color:e}),this.state.set("backgroundColor",e)}switchInlineQuery(e,t=[]){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:e,chat_types:t})}}function Kt(r,e,t,s,n,i){const{backgroundColor:a=e,headerColor:c="bg_color"}=r?N("mini-app")||{}:{},p=new Je({headerColor:c,backgroundColor:a,version:t,botInline:s,createRequestId:n,postEvent:i}),h=()=>D("mini-app",{backgroundColor:p.backgroundColor,headerColor:p.headerColor});return p.on("change",h),p}function Yt(){let r=0;return()=>(r+=1,r.toString())}class Qe{constructor(e,t,s=d){o(this,"ee",new w);o(this,"state");o(this,"on",(e,t)=>e==="click"?y("settings_button_pressed",t):this.ee.on(e,t));o(this,"off",(e,t)=>e==="click"?R("settings_button_pressed",t):this.ee.off(e,t));o(this,"supports");this.postEvent=s,this.state=new m({isVisible:e},this.ee),this.supports=C(t,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"})}set isVisible(e){this.state.set("isVisible",e),this.postEvent("web_app_setup_settings_button",{is_visible:e})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function Xt(r,e,t){const{isVisible:s=!1}=r?N("settings-button")||{}:{},n=new Qe(s,e,t);return n.on("change",()=>{D("settings-button",{isVisible:n.isVisible})}),n}function er(r){const e=new Re(r);return e.listen(),e}function Ze(r){return["macos","tdesktop","unigram","web","weba"].includes(r)}async function ge(r){const e=await b("web_app_request_viewport","viewport_changed",r);return{height:e.height,width:e.width,isExpanded:e.is_expanded,isStateStable:e.is_state_stable}}function O(r){return r<0?0:r}class Ke{constructor(e){o(this,"ee",new w);o(this,"state");o(this,"postEvent");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));const{height:t,isExpanded:s,width:n,stableHeight:i,postEvent:a=d}=e;this.postEvent=a,this.state=new m({height:O(t),isExpanded:s,stableHeight:O(i),width:O(n)},this.ee)}sync(e){return ge(e).then(({height:t,isExpanded:s,width:n,isStateStable:i})=>{this.state.set({height:t,width:n,isExpanded:s,stableHeight:i?t:this.state.get("stableHeight")})})}get height(){return this.state.get("height")}get stableHeight(){return this.state.get("stableHeight")}listen(){return y("viewport_changed",e=>{const{height:t,width:s,is_expanded:n,is_state_stable:i}=e,a={height:O(t),isExpanded:n,width:O(s)};i&&(a.stableHeight=a.height),this.state.set(a)})}get isExpanded(){return this.state.get("isExpanded")}get width(){return this.state.get("width")}expand(){this.postEvent("web_app_expand"),this.state.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}function z(r){const e=new Ke(r);return e.on("change",()=>D("viewport",{height:e.height,isExpanded:e.isExpanded,stableHeight:e.stableHeight,width:e.width})),e.listen(),e}function tr(r,e,t,s){const n=r?N("viewport"):null;if(n)return z({...n,postEvent:t});if(Ze(e))return z({height:window.innerHeight,isExpanded:!0,postEvent:t,stableHeight:window.innerHeight,width:window.innerWidth});if(s)return ge({postEvent:t,timeout:5e3}).then(({height:a,isStateStable:c,...p})=>z({...p,height:a,stableHeight:c?a:0}));const i=z({width:0,height:0,isExpanded:!1,postEvent:t,stableHeight:0});return i.sync({postEvent:t,timeout:5e3}).catch(a=>{console.error("Unable to actualize viewport state",a)}),i}function k(r,e){document.documentElement.style.setProperty(r,e)}function rr(r,e){const t=()=>{k("--tg-background-color",r.backgroundColor)},s=()=>{const{backgroundColor:n,secondaryBackgroundColor:i}=e;r.headerColor==="bg_color"?n&&k("--tg-header-color",n):r.headerColor==="secondary_bg_color"?i&&k("--tg-header-color",i):k("--tg-header-color",r.headerColor)};e.on("change",s),r.on("change:backgroundColor",t),r.on("change:headerColor",s),t(),s()}function sr(r){const e=()=>{const t=r.getState();Object.entries(t).forEach(([s,n])=>{if(n){const i=s.replace(/[A-Z]/g,a=>`-${a.toLowerCase()}`);k(`--tg-theme-${i}`,n)}})};r.on("change",e),e()}function ye(r){const e=()=>k("--tg-viewport-height",`${r.height}px`),t=()=>k("--tg-viewport-width",`${r.width}px`),s=()=>k("--tg-viewport-height",`${r.stableHeight}px`);r.on("change:height",e),r.on("change:width",t),r.on("change:stableHeight",s),e(),t(),s()}function nr(r){return typeof r=="object"?r:r?{themeParams:!0,viewport:!0,miniApp:!0}:{}}function Ee(r,e,t,s){const n=nr(r);n.miniApp&&rr(e,t),n.themeParams&&sr(t),n.viewport&&(s instanceof Promise?s.then(ye):ye(s))}function ir(r){const{hostname:e,pathname:t}=new URL(r,window.location.href);if(e!=="t.me")throw new Error(`Incorrect hostname: ${e}`);const s=t.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(s===null)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');return s[2]}class Ye{constructor(e,t=d){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=t,this.state=new m({isOpened:!1},this.ee),this.supports=C(e,{open:"web_app_open_invoice"})}set isOpened(e){this.state.set("isOpened",e)}get isOpened(){return this.state.get("isOpened")}async open(e,t){if(this.isOpened)throw new Error("Invoice is already opened");const s=t?ir(e):e;this.isOpened=!0;try{return(await b("web_app_open_invoice",{slug:s},"invoice_closed",{postEvent:this.postEvent,capture(i){return s===i.slug}})).status}finally{this.isOpened=!1}}}function or(r){const e=r.message.trim(),t=(r.title||"").trim(),s=r.buttons||[];let n;if(t.length>64)throw new Error(`Title has incorrect size: ${t.length}`);if(e.length===0||e.length>256)throw new Error(`Message has incorrect size: ${e.length}`);if(s.length>3)throw new Error(`Buttons have incorrect size: ${s.length}`);return s.length===0?n=[{type:"close",id:""}]:n=s.map(i=>{const{id:a=""}=i;if(a.length>64)throw new Error(`Button ID has incorrect size: ${a}`);if(i.type===void 0||i.type==="default"||i.type==="destructive"){const c=i.text.trim();if(c.length===0||c.length>64){const p=i.type||"default";throw new Error(`Button text with type "${p}" has incorrect size: ${i.text.length}`)}return{...i,text:c,id:a}}return{...i,id:a}}),{title:t,message:e,buttons:n}}class Xe{constructor(e,t=d){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=t,this.state=new m({isOpened:!1},this.ee),this.supports=C(e,{open:"web_app_open_popup"})}set isOpened(e){this.state.set("isOpened",e)}get isOpened(){return this.state.get("isOpened")}open(e){if(this.isOpened)throw new Error("Popup is already opened.");return this.isOpened=!0,b("web_app_open_popup",or(e),"popup_closed",{postEvent:this.postEvent}).then(({button_id:t=null})=>t).finally(()=>{this.isOpened=!1})}}class et{constructor(e,t=d){o(this,"ee",new w);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=t,this.state=new m({isOpened:!1},this.ee),this.supports=C(e,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"})}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(e){this.state.set("isOpened",e)}get isOpened(){return this.state.get("isOpened")}async open(e){if(this.isOpened)throw new Error("QR scanner is already opened.");this.isOpened=!0;try{const t=await b("web_app_open_scan_qr_popup",{text:e},["qr_text_received","scan_qr_popup_closed"],{postEvent:this.postEvent});return typeof t=="object"&&typeof t.data=="string"?t.data:null}finally{this.isOpened=!1}}}class tt{constructor(e,t,s=d){o(this,"supports");o(this,"supportsParam");this.version=e,this.createRequestId=t,this.postEvent=s,this.supports=C(e,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),this.supportsParam=Oe(e,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(e,t){const s=new URL(e,window.location.href).toString();if(!A("web_app_open_link",this.version)){window.open(s,"_blank");return}this.postEvent("web_app_open_link",{url:s,...typeof t=="boolean"?{try_instant_view:t}:{}})}openTelegramLink(e){const{hostname:t,pathname:s,search:n}=new URL(e,window.location.href);if(t!=="t.me")throw new Error(`URL has not allowed hostname: ${t}. Only "t.me" is allowed`);if(!A("web_app_open_tg_link",this.version)){window.location.href=e;return}this.postEvent("web_app_open_tg_link",{path_full:s+n})}readTextFromClipboard(){return b("web_app_read_text_from_clipboard",{req_id:this.createRequestId()},"clipboard_text_received",{postEvent:this.postEvent}).then(({data:e=null})=>e)}}function ar(r={}){const{async:e=!1,complete:t=e,cssVars:s=!1,acceptCustomStyles:n=!1}=r;try{const{launchParams:{initData:i,initDataRaw:a,version:c,platform:p,themeParams:h,botInline:g=!1},isPageReload:_}=le(),V=Yt(),l=We(c);de()&&(n&&Ft(),l("iframe_ready",{reload_supported:!0}),y("reload_iframe",()=>window.location.reload()));const v={backButton:zt(_,c,l),closingBehavior:Jt(_,l),cloudStorage:new je(c,V,l),createRequestId:V,hapticFeedback:new Ge(c,l),invoice:new Ye(c,l),mainButton:Qt(_,h.buttonColor||"#000000",h.buttonTextColor||"#ffffff",l),miniApp:Kt(_,h.backgroundColor||"#ffffff",c,g,V,l),popup:new Xe(c,l),postEvent:l,qrScanner:new et(c,l),settingsButton:Xt(_,c,l),themeParams:er(h),utils:new tt(c,V,l),...i?{initData:new qe(i),initDataRaw:a}:{}},q=tr(_,p,l,t);return q instanceof Promise||t?Promise.resolve(q).then(P=>(Ee(s,v.miniApp,v.themeParams,P),{...v,viewport:P})):(Ee(s,v.miniApp,v.themeParams,q),{...v,viewport:q})}catch(i){if(t)return Promise.reject(i);throw i}}function W(r,e){return r.startsWith(e)?r:`${e}${r}`}function cr(r){const e=r.match(/#(.+)/);return e?e[1]:null}async function H(r){return r===0?!0:Promise.race([new Promise(e=>{window.addEventListener("popstate",function t(){window.removeEventListener("popstate",t),e(!0)}),window.history.go(r)}),new Promise(e=>{setTimeout(e,50,!1)})])}async function ur(){if(window.history.length<=1||(window.history.pushState(null,""),await H(1-window.history.length)))return;let e=await H(-1);for(;e;)e=await H(-1)}class rt{constructor(e,t,{debug:s=!1,loggerPrefix:n="Navigator"}){o(this,"logger");o(this,"entries");if(this.entriesCursor=t,e.length===0)throw new Error("Entries list should not be empty.");if(t>=e.length)throw new Error("Cursor should be less than entries count.");this.entries=e.map(({pathname:i="",search:a,hash:c})=>{if(!i.startsWith("/")&&i.length>0)throw new Error('Pathname should start with "/"');return{pathname:W(i,"/"),search:a?W(a,"?"):"",hash:c?W(c,"#"):""}}),this.logger=new Be(`[${n}]`,s)}formatEntry(e){let t;if(typeof e=="string")t=e;else{const{pathname:a="",search:c,hash:p}=e;t=a+(c?W(c,"?"):"")+(p?W(p,"#"):"")}const{pathname:s,search:n,hash:i}=new URL(t,`https://localhost${this.path}`);return{pathname:s,search:n,hash:i}}get entry(){return this.entries[this.entriesCursor]}back(){return this.go(-1)}get cursor(){return this.entriesCursor}get canGoBack(){return this.entriesCursor>0}get canGoForward(){return this.entriesCursor!==this.entries.length-1}forward(){return this.go(1)}go(e){this.logger.log(`called go(${e})`);const t=Math.min(this.entries.length-1,Math.max(this.entriesCursor+e,0));if(this.entriesCursor===t)return this.performGo({updated:!1,delta:e});const s=this.entry;this.entriesCursor=t;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performGo({updated:!0,delta:e,before:s,after:n})}getEntries(){return this.entries.map(e=>({...e}))}get hash(){return this.entry.hash}push(e){this.entriesCursor!==this.entries.length-1&&this.entries.splice(this.entriesCursor+1);const t=this.formatEntry(e),s=this.entry;this.entriesCursor+=1,this.entries[this.entriesCursor]=t;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performPush({before:s,after:n})}get path(){return`${this.pathname}${this.search}${this.hash}`}get pathname(){return this.entry.pathname}replace(e){const t=this.formatEntry(e);if(this.search===t.search&&this.pathname===t.pathname&&this.hash===t.hash)return this.performReplace({updated:!1,entry:t});const s=this.entry;this.entries[this.entriesCursor]=t;const n=this.entry;return this.logger.log("State changed",{before:s,after:n}),this.performReplace({updated:!0,before:s,after:n})}get search(){return this.entry.search}}const Ce=0,X=1,ee=2;class we extends rt{constructor(t,s,n={}){super(t,s,{...n,loggerPrefix:"HashNavigator"});o(this,"ee",new w);o(this,"attached",!1);o(this,"onPopState",async({state:t})=>{if(this.logger.log('"popstate" event received. State:',t),t===null)return this.push(window.location.hash.slice(1));if(t===Ce){this.logger.log("Void reached. Moving history forward"),window.history.forward();return}if(t===X)return this.back();if(t===ee)return this.forward()});o(this,"back",()=>super.back());o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee))}static fromLocation(t){const{search:s,pathname:n,hash:i}=new URL(window.location.hash.slice(1),window.location.href);return new we([{search:s,pathname:n,hash:i}],0,t)}async performGo(t){t.updated&&(this.attached&&await this.syncHistory(),this.emitChanged(t.before,t.after))}async performPush({before:t,after:s}){this.attached&&await this.syncHistory(),this.emitChanged(t,s)}async performReplace(t){t.updated&&(this.attached&&window.history.replaceState(null,"",`#${this.path}`),this.emitChanged(t.before,t.after))}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const t=`#${this.path}`;await ur(),d("web_app_setup_back_button",{is_visible:this.canGoBack}),this.canGoBack&&this.canGoForward?(this.logger.log("Setting up history: [<-, *, ->]"),window.history.replaceState(X,""),window.history.pushState(null,"",t),window.history.pushState(ee,""),await H(-1)):this.canGoBack?(this.logger.log("Setting up history: [<-, *]"),window.history.replaceState(X,""),window.history.pushState(null,"",t)):this.canGoForward?(this.logger.log("Setting up history: [*, ->]"),window.history.replaceState(null,t),window.history.pushState(ee,""),await H(-1)):(this.logger.log("Setting up history: [~, *]"),window.history.replaceState(Ce,""),window.history.pushState(null,"",t)),window.addEventListener("popstate",this.onPopState)}emitChanged(t,s){this.ee.emit("change",{navigator:this,from:t,to:s})}async attach(){if(!this.attached)return this.logger.log("Attaching",this),this.attached=!0,y("back_button_pressed",this.back),this.syncHistory()}detach(){this.attached&&(this.logger.log("Detaching",this),this.attached=!1,window.removeEventListener("popstate",this.onPopState),R("back_button_pressed",this.back))}}exports.BackButton=He;exports.ClosingBehavior=Ue;exports.CloudStorage=je;exports.HapticFeedback=Ge;exports.HashNavigator=we;exports.InitData=qe;exports.Invoice=Ye;exports.MainButton=ze;exports.MethodUnsupportedError=Z;exports.MiniApp=Je;exports.Navigator=rt;exports.ParameterUnsupportedError=K;exports.ParseError=U;exports.ParseSchemaFieldError=M;exports.Popup=Xe;exports.QRScanner=et;exports.SettingsButton=Qe;exports.ThemeParams=Re;exports.TimeoutError=G;exports.Utils=tt;exports.Viewport=Ke;exports.array=Se;exports.boolean=E;exports.chatParser=xe;exports.classNames=Me;exports.compareVersions=Ne;exports.createPostEvent=We;exports.date=re;exports.getHash=cr;exports.init=ar;exports.initDataParser=ce;exports.invokeCustomMethod=T;exports.isColorDark=oe;exports.isIframe=de;exports.isRGB=ne;exports.isRGBShort=ke;exports.isRecord=L;exports.isStableViewportPlatform=Ze;exports.isTMA=mt;exports.isTimeoutError=Ht;exports.json=f;exports.launchParamsParser=pe;exports.mergeClassNames=Gt;exports.number=x;exports.off=R;exports.on=y;exports.once=Ot;exports.parseInitData=ct;exports.parseLaunchParams=Ve;exports.parseThemeParams=he;exports.postEvent=d;exports.request=b;exports.requestThemeParams=pt;exports.requestViewport=ge;exports.retrieveLaunchData=le;exports.rgb=ae;exports.searchParams=Q;exports.serializeLaunchParams=Ie;exports.serializeThemeParams=Ae;exports.setDebug=Ct;exports.setTargetOrigin=vt;exports.string=u;exports.subscribe=Wt;exports.supports=A;exports.themeParamsParser=ue;exports.toRGB=ie;exports.unsubscribe=De;exports.userParser=te;exports.withTimeout=fe;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|