@tma.js/sdk 1.0.1 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- var ar=Object.defineProperty;var cr=(a,w,C)=>w in a?ar(a,w,{enumerable:!0,configurable:!0,writable:!0,value:C}):a[w]=C;var o=(a,w,C)=>(cr(a,typeof w!="symbol"?w+"":w,C),C);this.tmajs=this.tmajs||{};this.tmajs.sdk=function(a){"use strict";function w(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function C(){return performance.getEntriesByType("navigation")[0]||null}function Xt(){const r=C();return r?r.type==="reload":null}function T(){return new TypeError("Value has unexpected type")}class G extends Error{constructor(e,{cause:n,type:s}={}){super(`Unable to parse value${s?` as ${s}`:""}`,{cause:n});o(this,"type");this.value=e,Object.setPrototypeOf(this,G.prototype),this.type=s}}class F{constructor(t,e,n){this.parser=t,this.isOptional=e,this.type=n}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(e){throw new G(t,{type:this.type,cause:e})}}optional(){return this.isOptional=!0,this}}function te(r){if(Array.isArray(r))return r;if(typeof r=="string")try{const t=JSON.parse(r);if(Array.isArray(t))return t}catch{}throw T()}class ee extends F{constructor(e,n,s){super(te,n,s);o(this,"itemParser");this.itemParser=typeof e=="function"?e:e.parse.bind(e)}parse(e){const n=super.parse(e);return n===void 0?n:n.map(this.itemParser)}of(e){return this.itemParser=typeof e=="function"?e:e.parse.bind(e),this}}function V(r,t){return()=>new F(r,!1,t)}class z extends Error{constructor(t,{cause:e,type:n}={}){super(`Unable to parse field "${t}"${n?` as ${n}`:""}`,{cause:e}),Object.setPrototypeOf(this,z.prototype)}}function gt(r,t){const e={};for(const n in r){const s=r[n];if(!s)continue;let i,c;if(typeof s=="function"||"parse"in s)i=n,c=typeof s=="function"?s:s.parse.bind(s);else{const{type:d}=s;i=s.from||n,c=typeof d=="function"?d:d.parse.bind(d)}let h;const p=t(i);try{h=c(p)}catch(d){throw d instanceof G?new z(i,{type:d.type,cause:d}):new z(i,{cause:d})}h!==void 0&&(e[n]=h)}return e}function re(r){return new ee(t=>t,!1,r)}const v=V(r=>{if(typeof r=="boolean")return r;const t=String(r);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;throw T()},"boolean"),$=V(r=>{if(typeof r=="number")return r;if(typeof r=="string"){const t=Number(r);if(!Number.isNaN(t))return t}throw T()},"number"),ne=$(),se=V(r=>r instanceof Date?r:new Date(ne.parse(r)*1e3),"Date");function K(r){let t=r;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw T();return t}function _(r,t){return new F(e=>{const n=K(e);return gt(r,s=>n[s])},!1,t)}function Y(r){return/^#[\da-f]{6}$/i.test(r)}function wt(r){return/^#[\da-f]{3}$/i.test(r)}function X(r){const t=r.replace(/\s/g,"").toLowerCase();if(Y(t))return t;if(wt(t)){let n="#";for(let s=0;s<3;s+=1)n+=t[1+s].repeat(2);return n}const e=t.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||t.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(e===null)throw new Error(`Value "${r}" does not satisfy any of known RGB formats.`);return e.slice(1).reduce((n,s)=>{const i=parseInt(s,10).toString(16);return n+(i.length===1?"0":"")+i},"#")}function tt(r){const t=X(r);return Math.sqrt([.299,.587,.114].reduce((n,s,i)=>{const c=parseInt(t.slice(1+i*2,1+(i+1)*2),16);return n+c*c*s},0))<120}const u=V(r=>{if(typeof r=="string"||typeof r=="number")return r.toString();throw T()},"string"),ie=u(),_t=V(r=>X(ie.parse(r)),"rgb");function bt(r,t){return new F(e=>{if(typeof e!="string"&&!(e instanceof URLSearchParams))throw T();const n=typeof e=="string"?new URLSearchParams(e):e;return gt(r,s=>{const i=n.get(s);return i===null?void 0:i})},!1,t)}function mt(){return _({id:$(),type:u(),title:u(),photoUrl:{type:u().optional(),from:"photo_url"},username:u().optional()},"Chat")}class yt{constructor(t){this.initData=t}get authDate(){return this.initData.authDate}get canSendAfter(){return this.initData.canSendAfter}get canSendAfterDate(){const{canSendAfter:t}=this;return t===void 0?void 0:new Date(this.authDate.getTime()+t*1e3)}get chat(){return this.initData.chat}get chatType(){return this.initData.chatType}get chatInstance(){return this.initData.chatInstance}get hash(){return this.initData.hash}get queryId(){return this.initData.queryId}get receiver(){return this.initData.receiver}get startParam(){return this.initData.startParam}get user(){return this.initData.user}}function et(){return _({addedToAttachmentMenu:{type:v().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:v().optional(),from:"allows_write_to_pm"},firstName:{type:u(),from:"first_name"},id:$(),isBot:{type:v().optional(),from:"is_bot"},isPremium:{type:v().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 rt(){return bt({authDate:{type:se(),from:"auth_date"},canSendAfter:{type:$().optional(),from:"can_send_after"},chat:mt().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:et().optional(),startParam:{type:u().optional(),from:"start_param"},user:et().optional()},"InitData")}function oe(r){return rt().parse(r)}function ae(r){return r.replace(/(^|_)bg/,(t,e)=>`${e}background`).replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function ce(r){return r.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`).replace(/(^|_)background/,(t,e)=>`${e}bg`)}const he=_t().optional(),nt=V(r=>Object.entries(K(r)).reduce((t,[e,n])=>(t[ae(e)]=he.parse(n),t),{}),"ThemeParams");function st(r){return nt().parse(r)}function ue(r={}){return m("web_app_request_theme","theme_changed",r).then(st)}function Et(r){return JSON.stringify(Object.entries(r).reduce((t,[e,n])=>(n&&(t[ce(e)]=n),t),{}))}class b{constructor(){o(this,"listeners",new Map);o(this,"subscribeListeners",[])}addListener(t,e,n){let s=this.listeners.get(t);return s||(s=[],this.listeners.set(t,s)),s.push([e,n]),()=>this.off(t,e)}emit(t,...e){this.subscribeListeners.forEach(s=>s(t,...e));const n=this.listeners.get(t);n&&n.forEach(([s,i],c)=>{s(...e),i&&n.splice(c,1)})}on(t,e){return this.addListener(t,e,!1)}once(t,e){return this.addListener(t,e,!0)}off(t,e){const n=this.listeners.get(t);if(n){for(let s=0;s<n.length;s+=1)if(e===n[s][0]){n.splice(s,1);return}}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let e=0;e<this.subscribeListeners.length;e+=1)if(this.subscribeListeners[e]===t){this.subscribeListeners.splice(e,1);return}}}class y{constructor(t,e){this.state=t,this.ee=e}internalSet(t,e){return this.state[t]===e||e===void 0?!1:(this.state[t]=e,this.ee.emit(`change:${t}`,e),!0)}clone(){return{...this.state}}set(t,e){let n=!1;if(typeof t=="string")n=this.internalSet(t,e);else for(const s in t)this.internalSet(s,t[s])&&(n=!0);n&&this.ee.emit("change")}get(t){return this.state[t]}}class Ct{constructor(t){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.state=new y(t,this.ee)}get accentTextColor(){return this.get("accentTextColor")}get backgroundColor(){return this.get("backgroundColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}get(t){return this.state.get(t)}getState(){return this.state.clone()}get headerBackgroundColor(){return this.get("headerBackgroundColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.backgroundColor||tt(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 E("theme_changed",t=>{this.state.set(st(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}function it(){return bt({botInline:{type:v().optional(),from:"tgWebAppBotInline"},initData:{type:rt().optional(),from:"tgWebAppData"},initDataRaw:{type:u().optional(),from:"tgWebAppData"},platform:{type:u(),from:"tgWebAppPlatform"},showSettings:{type:v().optional(),from:"tgWebAppShowSettings"},themeParams:{type:nt(),from:"tgWebAppThemeParams"},version:{type:u(),from:"tgWebAppVersion"}},"LaunchParams")}function ot(r){return it().parse(r)}function pe(){return ot(window.location.hash.slice(1))}function le(){const r=C();if(!r)throw new Error("Unable to get first navigation entry.");const t=r.name.match(/#(.*)/);if(!t)throw new Error("First navigation entry does not contain hash part.");return ot(t[1])}function de(){try{return le()}catch{}try{return pe()}catch{}return null}function vt(r){const{initDataRaw:t,themeParams:e,platform:n,version:s,showSettings:i,botInline:c}=r,h=new URLSearchParams;return t&&h.set("tgWebAppData",t),h.set("tgWebAppPlatform",n),h.set("tgWebAppThemeParams",Et(e)),h.set("tgWebAppVersion",s),typeof i=="boolean"&&h.set("tgWebAppShowSettings",i?"1":"0"),typeof c=="boolean"&&h.set("tgWebAppBotInline",c?"1":"0"),h.toString()}const Pt="telegram-mini-apps-launch-params";function fe(){const r=sessionStorage.getItem(Pt);return r?it().parse(r):null}function ge(r){sessionStorage.setItem(Pt,vt(r))}function we(){try{return window.self!==window.top}catch{return!0}}function _e(){const r=fe(),t=de(),e=Xt();if(r){if(t)return{launchParams:t,isPageReload:we()?e||r.initDataRaw===t.initDataRaw:!0};if(e)return{launchParams:r,isPageReload:e};throw new Error("Unable to retrieve current launch parameters, which must exist.")}if(t)return{launchParams:t,isPageReload:!1};throw new Error("Unable to retrieve any launch parameters.")}const kt="tmajsLaunchData";function at(){const r=window[kt];if(r)return r;const t=_e();return window[kt]=t,ge(t.launchParams),t}function be(){try{return at(),!0}catch{return!1}}function me(r){return"external"in r&&w(r.external)&&"notify"in r.external&&typeof r.external.notify=="function"}function ye(r){return"TelegramWebviewProxy"in r&&w(r.TelegramWebviewProxy)&&"postEvent"in r.TelegramWebviewProxy&&typeof r.TelegramWebviewProxy.postEvent=="function"}function ct(){try{return window.self!==window.top}catch{return!0}}class J extends Error{constructor(t,e){super(`Method "${t}" is unsupported in the Mini Apps version ${e}.`),Object.setPrototypeOf(this,J.prototype)}}class Q extends Error{constructor(t,e,n){super(`Parameter "${e}" in method "${t}" is unsupported in the Mini Apps version ${n}.`),Object.setPrototypeOf(this,Q.prototype)}}class St{constructor(t,e){this.prefix=t,this.enabled=e}print(t,...e){if(!this.enabled)return;const n=new Date,s=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n);console[t](`[${s}]`,this.prefix,...e)}disable(){this.enabled=!1}error(...t){this.print("error",...t)}enable(){this.enabled=!0}log(...t){this.print("log",...t)}warn(...t){this.print("warn",...t)}}let At="https://web.telegram.org";const I=new St("[SDK]",!1);function Ee(r){if(r){I.enable();return}I.disable()}function Ce(r){At=r}function ve(){return At}const Pe=_({eventType:u(),eventData:r=>r});function ke(r,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:r,eventData:t})}))}function Se(){const r=window;"TelegramGameProxy_receiveEvent"in r||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(t=>{let e=r;t.forEach((n,s,i)=>{if(s===i.length-1){e[n]=ke;return}n in e||(e[n]={}),e=e[n]})})}function Ae(r){Se(),window.addEventListener("message",t=>{try{const{eventType:e,eventData:n}=Pe.parse(t.data);r(e,n)}catch{}})}function qe(){return _({req_id:u(),data:r=>r===null?r:u().optional().parse(r)})}function Le(){return _({req_id:u(),result:r=>r,error:u().optional()})}function Te(){return _({slug:u(),status:u()})}function Ve(){return _({status:u()})}function $e(){return _({button_id:r=>r==null?void 0:u().parse(r)})}function Ie(){return _({data:u().optional()})}function Re(){return _({theme_params:r=>{const t=_t().optional();return Object.entries(K(r)).reduce((e,[n,s])=>(e[n]=t.parse(s),e),{})}})}function Be(){return _({height:$(),width:r=>r==null?window.innerWidth:$().parse(r),is_state_stable:v(),is_expanded:v()})}function De(){return _({status:u()})}function xe(){const r=new b,t=(e,...n)=>{I.log("Emitting processed event:",e,...n),r.emit(e,...n)};return window.addEventListener("resize",()=>{t("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),Ae((e,n)=>{I.log("Received raw event:",e,n);try{switch(e){case"viewport_changed":return t(e,Be().parse(n));case"theme_changed":return t(e,Re().parse(n));case"popup_closed":return n==null?t(e,{}):t(e,$e().parse(n));case"set_custom_style":return t(e,u().parse(n));case"qr_text_received":return t(e,Ie().parse(n));case"clipboard_text_received":return t(e,qe().parse(n));case"invoice_closed":return t(e,Te().parse(n));case"phone_requested":return t("phone_requested",Ve().parse(n));case"custom_method_invoked":return t("custom_method_invoked",Le().parse(n));case"write_access_requested":return t("write_access_requested",De().parse(n));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":case"reload_iframe":return t(e);default:return t(e,n)}}catch(s){I.error("Error processing event:",s)}}),r}const ht="telegram-mini-apps-cached-emitter";function D(){const r=window;return r[ht]===void 0&&(r[ht]=xe()),r[ht]}function R(r,t){D().off(r,t)}function E(r,t){return D().on(r,t),()=>R(r,t)}function He(r,t){return D().once(r,t),()=>R(r,t)}function qt(r){D().unsubscribe(r)}function Ne(r){return D().subscribe(r),()=>qt(r)}function Lt(r,t){const e=r.split("."),n=t.split("."),s=Math.max(e.length,n.length);for(let i=0;i<s;i+=1){const c=parseInt(e[i]||"0",10),h=parseInt(n[i]||"0",10);if(c!==h)return c>h?1:-1}return 0}function P(r,t){return Lt(r,t)<=0}function L(r,t,e){if(typeof e=="string"){if(r==="web_app_open_link"&&t==="try_instant_view")return P("6.4",e);if(r==="web_app_set_header_color"&&t==="color")return P("6.9",e)}switch(r){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return P("6.1",t);case"web_app_open_popup":return P("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 P("6.4",t);case"web_app_switch_inline_query":return P("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return P("6.9",t);case"web_app_setup_settings_button":return P("6.10",t);default:return!0}}function k(r,t){return e=>L(t[e],r)}function Tt(r,t){return e=>{const[n,s]=t[e];return L(n,s,r)}}function g(r,t,e){let n={},s;t===void 0&&e===void 0?n={}:t!==void 0&&e!==void 0?(n=e,s=t):t!==void 0&&("targetOrigin"in t?n=t:s=t);const{targetOrigin:i=ve()}=n;if(I.log(`Calling method "${r}"`,s),ct()){window.parent.postMessage(JSON.stringify({eventType:r,eventData:s}),i);return}if(me(window)){window.external.notify(JSON.stringify({eventType:r,eventData:s}));return}if(ye(window)){window.TelegramWebviewProxy.postEvent(r,JSON.stringify(s));return}throw new Error("Unable to determine current environment and possible way to send event.")}function Vt(r){return(t,e)=>{if(!L(t,r))throw new J(t,r);if(w(e)){let n;if(t==="web_app_open_link"&&"try_instant_view"in e?n="try_instant_view":t==="web_app_set_header_color"&&"color"in e&&(n="color"),n&&!L(t,n,r))throw new Q(t,n,r)}return g(t,e)}}class ut extends Error{constructor(t){super(`Async call timeout exceeded. Timeout: ${t}`),Object.setPrototypeOf(this,ut.prototype)}}function $t(r){return new Promise((t,e)=>{setTimeout(e,r,new ut(r))})}function Oe(r,t){return typeof r=="function"?(...e)=>Promise.race([r(...e),$t(t)]):Promise.race([r,$t(t)])}function m(r,t,e,n){let s,i,c,h;typeof t=="string"||Array.isArray(t)?(c=Array.isArray(t)?t:[t],s=e):(i=t,c=Array.isArray(e)?e:[e],s=n),w(i)&&typeof i.req_id=="string"&&(h=i.req_id);const{postEvent:p=g,timeout:d}=s||{},l=s&&"capture"in s?s.capture:null,A=new Promise((f,q)=>{const B=c.map(j=>E(j,Z=>{typeof h=="string"&&(!w(Z)||Z.req_id!==h)||typeof l=="function"&&!l(Z)||(U(),f(Z))})),U=()=>B.forEach(j=>j());try{p(r,i)}catch(j){U(),q(j)}});return typeof d=="number"?Oe(A,d):A}class It{constructor(t,e,n=g){o(this,"ee",new b);o(this,"state");o(this,"on",(t,e)=>t==="click"?E("back_button_pressed",e):this.ee.on(t,e));o(this,"off",(t,e)=>t==="click"?R("back_button_pressed",e):this.ee.off(t,e));o(this,"supports");this.postEvent=n,this.state=new y({isVisible:t},this.ee),this.supports=k(e,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"})}set isVisible(t){this.state.set("isVisible",t),this.postEvent("web_app_setup_back_button",{is_visible:t})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function Rt(r,t){return r+(r.length>0&&t.length>0?` ${t}`:t)}function Bt(...r){return r.reduce((t,e)=>{let n="";return typeof e=="string"?n=e:typeof e=="object"&&e!==null&&(n=Object.entries(e).reduce((s,[i,c])=>c?Rt(s,i):s,"")),Rt(t,n)},"")}function Me(r){return typeof r=="object"&&r!==null&&!Array.isArray(null)}function We(...r){return r.reduce((t,e)=>(Me(e)&&Object.entries(e).forEach(([n,s])=>{const i=Bt(t[n],s);i.length>0&&(t[n]=i)}),t),{})}class Dt{constructor(t,e=g){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.postEvent=e,this.state=new y({isConfirmationNeeded:t},this.ee)}set isConfirmationNeeded(t){this.state.set("isConfirmationNeeded",t),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:t})}get isConfirmationNeeded(){return this.state.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}const Ue=re().of(u());function xt(r,t){return r.reduce((e,n)=>(e[n]=t,e),{})}class Ht{constructor(t,e,n=g){o(this,"supports");this.createRequestId=e,this.postEvent=n,this.supports=k(t,{delete:"web_app_invoke_custom_method",get:"web_app_invoke_custom_method",getKeys:"web_app_invoke_custom_method",set:"web_app_invoke_custom_method"})}async invokeCustomMethod(t,e,n={}){const{result:s,error:i}=await m("web_app_invoke_custom_method",{method:t,params:e,req_id:this.createRequestId()},"custom_method_invoked",{...n,postEvent:this.postEvent});if(i)throw new Error(i);return s}async delete(t,e){const n=Array.isArray(t)?t:[t];n.length!==0&&await this.invokeCustomMethod("deleteStorageValues",{keys:n},e)}async getKeys(t){const e=await this.invokeCustomMethod("getStorageKeys",{},t);return Ue.parse(e)}async get(t,e){const n=Array.isArray(t)?t:[t];if(n.length===0)return xt(n,"");const s=_(xt(n,u())),i=await this.invokeCustomMethod("getStorageValues",{keys:n},e).then(c=>s.parse(c));return Array.isArray(t)?i:i[t]}async set(t,e,n){await this.invokeCustomMethod("saveStorageValue",{key:t,value:e},n)}}class Nt{constructor(t,e=g){o(this,"supports");this.postEvent=e,this.supports=k(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"})}impactOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"impact",impact_style:t})}notificationOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"notification",notification_type:t})}selectionChanged(){this.postEvent("web_app_trigger_haptic_feedback",{type:"selection_change"})}}function je(){const r=document.createElement("style");r.id="telegram-custom-styles",document.head.appendChild(r),E("set_custom_style",t=>{r.innerHTML=t})}function Ot(r){return`telegram-mini-apps-${r}`}function x(r,t){sessionStorage.setItem(Ot(r),JSON.stringify(t))}function H(r){const t=sessionStorage.getItem(Ot(r));return t?JSON.parse(t):null}function Ge(r,t,e){const{isVisible:n=!1}=r?H("back-button")||{}:{},s=new It(n,t,e);return s.on("change",()=>{x("back-button",{isVisible:s.isVisible})}),s}function Fe(r,t){const{isConfirmationNeeded:e=!1}=r?H("closing-behavior")||{}:{},n=new Dt(e,t);return n.on("change",()=>x("closing-behavior",{isConfirmationNeeded:n.isConfirmationNeeded})),n}class Mt{constructor(t){o(this,"ee",new b);o(this,"state");o(this,"postEvent");o(this,"on",(t,e)=>t==="click"?E("main_button_pressed",e):this.ee.on(t,e));o(this,"off",(t,e)=>t==="click"?R("main_button_pressed",e):this.ee.off(t,e));const{postEvent:e=g,text:n,textColor:s,backgroundColor:i,isEnabled:c,isVisible:h,isLoaderVisible:p}=t;this.postEvent=e,this.state=new y({backgroundColor:i,isEnabled:c,isVisible:h,isLoaderVisible:p,text:n,textColor:s},this.ee)}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.backgroundColor,text_color:this.textColor})}set isEnabled(t){this.setParams({isEnabled:t})}get isEnabled(){return this.state.get("isEnabled")}set isLoaderVisible(t){this.setParams({isLoaderVisible:t})}get isLoaderVisible(){return this.state.get("isLoaderVisible")}set isVisible(t){this.setParams({isVisible:t})}get isVisible(){return this.state.get("isVisible")}get backgroundColor(){return this.state.get("backgroundColor")}get text(){return this.state.get("text")}get textColor(){return this.state.get("textColor")}disable(){return this.isEnabled=!1,this}enable(){return this.isEnabled=!0,this}hide(){return this.isVisible=!1,this}hideLoader(){return this.isLoaderVisible=!1,this}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(t){return this.setParams({text:t})}setTextColor(t){return this.setParams({textColor:t})}setBackgroundColor(t){return this.setParams({backgroundColor:t})}setParams(t){return this.state.set(t),this.commit(),this}}function ze(r,t,e,n){const{backgroundColor:s=t,isEnabled:i=!1,isVisible:c=!1,isLoaderVisible:h=!1,textColor:p=e,text:d=""}=r?H("main-button")||{}:{},l=new Mt({backgroundColor:s,isEnabled:i,isLoaderVisible:h,isVisible:c,postEvent:n,text:d,textColor:p}),A=()=>x("main-button",{backgroundColor:l.backgroundColor,isEnabled:l.isEnabled,isLoaderVisible:l.isLoaderVisible,isVisible:l.isVisible,text:l.text,textColor:l.textColor});return l.on("change",A),l}class Wt{constructor(t){o(this,"ee",new b);o(this,"state");o(this,"botInline");o(this,"postEvent");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");o(this,"supportsParam");const{postEvent:e=g,headerColor:n,backgroundColor:s,version:i,botInline:c}=t,h=k(i,{requestPhoneAccess:"web_app_request_phone",requestWriteAccess:"web_app_request_write_access",switchInlineQuery:"web_app_switch_inline_query",setHeaderColor:"web_app_set_header_color",setBackgroundColor:"web_app_set_background_color"});this.postEvent=e,this.botInline=c,this.supports=p=>!(!h(p)||p==="switchInlineQuery"&&!c),this.state=new y({backgroundColor:s,headerColor:n},this.ee),this.supportsParam=Tt(i,{"setHeaderColor.color":["web_app_set_header_color","color"]})}get backgroundColor(){return this.state.get("backgroundColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.state.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return tt(this.backgroundColor)}ready(){this.postEvent("web_app_ready")}requestPhoneAccess(){return m("web_app_request_phone","phone_requested",{postEvent:this.postEvent}).then(t=>t.status)}requestWriteAccess(){return m("web_app_request_write_access","write_access_requested",{postEvent:this.postEvent}).then(t=>t.status)}sendData(t){const{size:e}=new Blob([t]);if(e===0||e>4096)throw new Error(`Passed data has incorrect size: ${e}`);this.postEvent("web_app_data_send",{data:t})}setHeaderColor(t){this.postEvent("web_app_set_header_color",Y(t)?{color:t}:{color_key:t}),this.state.set("headerColor",t)}setBackgroundColor(t){this.postEvent("web_app_set_background_color",{color:t}),this.state.set("backgroundColor",t)}switchInlineQuery(t,e=[]){if(!this.supports("switchInlineQuery")&&!this.isBotInline)throw new Error("Method is unsupported because Mini App should be launched in inline mode.");this.postEvent("web_app_switch_inline_query",{query:t,chat_types:e})}}function Je(r,t,e,n,s){const{backgroundColor:i=t,headerColor:c="bg_color"}=r?H("mini-app")||{}:{},h=new Wt({headerColor:c,backgroundColor:i,version:e,botInline:n,postEvent:s}),p=()=>x("mini-app",{backgroundColor:h.backgroundColor,headerColor:h.headerColor});return h.on("change",p),h}function Qe(){let r=0;return()=>(r+=1,r.toString())}function Ze(r){const t=new Ct(r);return t.listen(),t}async function pt(r){const t=await m("web_app_request_viewport","viewport_changed",r);return{height:t.height,width:t.width,isExpanded:t.is_expanded,isStateStable:t.is_state_stable}}function N(r){return r<0?0:r}class O{constructor(t){o(this,"ee",new b);o(this,"state");o(this,"postEvent");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));const{height:e,isExpanded:n,width:s,stableHeight:i,postEvent:c=g}=t;this.postEvent=c,this.state=new y({height:N(e),isExpanded:n,stableHeight:N(i),width:N(s)},this.ee)}sync(t){return pt(t).then(({height:e,isExpanded:n,width:s,isStateStable:i})=>{this.state.set({height:e,width:s,isExpanded:n,stableHeight:i?e:this.state.get("stableHeight")})})}get height(){return this.state.get("height")}get stableHeight(){return this.state.get("stableHeight")}listen(){return E("viewport_changed",t=>{const{height:e,width:n,is_expanded:s,is_state_stable:i}=t,c={height:N(e),isExpanded:s,width:N(n)};i&&(c.stableHeight=c.height),this.state.set(c)})}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 Ut(r,t,e){if(r||t==="macos"||t==="web"||t==="weba")return new O({height:window.innerHeight,isExpanded:!0,postEvent:e,stableHeight:window.innerHeight,width:window.innerWidth});const n=H("viewport");return n?new O({...n,postEvent:e}):null}function jt(r){return r.listen(),r.on("change",()=>x("viewport",{height:r.height,isExpanded:r.isExpanded,stableHeight:r.stableHeight,width:r.width})),r}function Ke(r,t,e){const n=jt(Ut(r,t,e)||new O({width:0,height:0,isExpanded:!1,postEvent:e,stableHeight:0}));return n.sync({postEvent:e,timeout:100}).catch(s=>{console.error("Unable to actualize viewport state",s)}),n}async function Ye(r,t,e){return jt(Ut(r,t,e)||await pt({postEvent:e,timeout:100}).then(({height:n,isStateStable:s,...i})=>new O({...i,height:n,stableHeight:s?n:0})))}function S(r,t){document.documentElement.style.setProperty(r,t)}function Xe(r,t){const e=()=>{S("--tg-background-color",r.backgroundColor)},n=()=>{const{backgroundColor:s,secondaryBackgroundColor:i}=t;r.headerColor==="bg_color"?s&&S("--tg-header-color",s):r.headerColor==="secondary_bg_color"?i&&S("--tg-header-color",i):S("--tg-header-color",r.headerColor)};t.on("change",n),r.on("change:backgroundColor",e),r.on("change:headerColor",n),e(),n()}function tr(r){const t=()=>{const e=r.getState();Object.entries(e).forEach(([n,s])=>{if(s){const i=n.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`);S(`--tg-theme-${i}`,s)}})};r.on("change",t),t()}function Gt(r){const t=()=>S("--tg-viewport-height",`${r.height}px`),e=()=>S("--tg-viewport-width",`${r.width}px`),n=()=>S("--tg-viewport-height",`${r.stableHeight}px`);r.on("change:height",t),r.on("change:width",e),r.on("change:stableHeight",n),t(),e(),n()}function er(r){return typeof r=="object"?r:r?{themeParams:!0,viewport:!0,miniApp:!0}:{}}function Ft(r,t,e,n){const s=er(r);s.miniApp&&Xe(t,e),s.themeParams&&tr(e),s.viewport&&(n instanceof Promise?n.then(Gt):Gt(n))}function rr(r){const{hostname:t,pathname:e}=new URL(r,window.location.href);if(t!=="t.me")throw new Error(`Incorrect hostname: ${t}`);const n=e.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(n===null)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');return n[2]}class zt{constructor(t,e=g){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new y({isOpened:!1},this.ee),this.supports=k(t,{open:"web_app_open_invoice"})}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}async open(t,e){if(this.isOpened)throw new Error("Invoice is already opened");const n=e?rr(t):t;this.isOpened=!0;try{return(await m("web_app_open_invoice",{slug:n},"invoice_closed",{postEvent:this.postEvent,capture(i){return n===i.slug}})).status}finally{this.isOpened=!1}}}function nr(r){const t=r.message.trim(),e=(r.title||"").trim(),n=r.buttons||[];let s;if(e.length>64)throw new Error(`Title has incorrect size: ${e.length}`);if(t.length===0||t.length>256)throw new Error(`Message has incorrect size: ${t.length}`);if(n.length>3)throw new Error(`Buttons have incorrect size: ${n.length}`);return n.length===0?s=[{type:"close",id:""}]:s=n.map(i=>{const{id:c=""}=i;if(c.length>64)throw new Error(`Button ID has incorrect size: ${c}`);if(i.type===void 0||i.type==="default"||i.type==="destructive"){const h=i.text.trim();if(h.length===0||h.length>64){const p=i.type||"default";throw new Error(`Button text with type "${p}" has incorrect size: ${i.text.length}`)}return{...i,text:h,id:c}}return{...i,id:c}}),{title:e,message:t,buttons:s}}class Jt{constructor(t,e=g){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new y({isOpened:!1},this.ee),this.supports=k(t,{open:"web_app_open_popup"})}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}open(t){if(this.isOpened)throw new Error("Popup is already opened.");return this.isOpened=!0,m("web_app_open_popup",nr(t),"popup_closed",{postEvent:this.postEvent}).then(({button_id:e=null})=>e).finally(()=>{this.isOpened=!1})}}class Qt{constructor(t,e=g){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new y({isOpened:!1},this.ee),this.supports=k(t,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"})}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}async open(t){if(this.isOpened)throw new Error("QR scanner is already opened.");this.isOpened=!0;try{const e=await m("web_app_open_scan_qr_popup",{text:t},["qr_text_received","scan_qr_popup_closed"],{postEvent:this.postEvent});return typeof e=="object"&&typeof e.data=="string"?e.data:null}finally{this.isOpened=!1}}}class Zt{constructor(t,e,n=g){o(this,"supports");o(this,"supportsParam");this.version=t,this.createRequestId=e,this.postEvent=n,this.supports=k(t,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),this.supportsParam=Tt(t,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(t,e){const n=new URL(t,window.location.href).toString();if(!L("web_app_open_link",this.version)){window.open(n,"_blank");return}this.postEvent("web_app_open_link",{url:n,...typeof e=="boolean"?{try_instant_view:e}:{}})}openTelegramLink(t){const{hostname:e,pathname:n,search:s}=new URL(t,window.location.href);if(e!=="t.me")throw new Error(`URL has not allowed hostname: ${e}. Only "t.me" is allowed`);if(!L("web_app_open_tg_link",this.version)){window.location.href=t;return}this.postEvent("web_app_open_tg_link",{path_full:n+s})}readTextFromClipboard(){return m("web_app_read_text_from_clipboard",{req_id:this.createRequestId()},"clipboard_text_received",{postEvent:this.postEvent}).then(({data:t=null})=>t)}}function sr(r){const{async:t=!1,cssVars:e=!1,acceptCustomStyles:n=!1}=r;try{const{launchParams:{initData:s,initDataRaw:i,version:c,platform:h,themeParams:p,botInline:d=!1},isPageReload:l}=at(),A=Qe(),f=Vt(c);ct()&&(n&&je(),f("iframe_ready",{reload_supported:!0}),E("reload_iframe",()=>window.location.reload()));const q={backButton:Ge(l,c,f),closingBehavior:Fe(l,f),cloudStorage:new Ht(c,A,f),createRequestId:A,hapticFeedback:new Nt(c,f),invoice:new zt(c,f),mainButton:ze(l,p.buttonColor||"#000000",p.buttonTextColor||"#ffffff",f),miniApp:Je(l,p.backgroundColor||"#ffffff",c,d,f),popup:new Jt(c,f),postEvent:f,qrScanner:new Qt(c,f),themeParams:Ze(p),utils:new Zt(c,A,f),...s?{initData:new yt(s),initDataRaw:i}:{}},B=t?Ye(l,h,f):Ke(l,h,f);return B instanceof Promise?B.then(U=>(Ft(e,q.miniApp,q.themeParams,U),{...q,viewport:U})):(Ft(e,q.miniApp,q.themeParams,B),{...q,viewport:B})}catch(s){if(t)return Promise.reject(s);throw s}}function M(r,t){return r.startsWith(t)?r:`${t}${r}`}function ir(r){const t=r.match(/#(.+)/);return t?t[1]:null}async function W(r){return r===0?!0:Promise.race([new Promise(t=>{window.addEventListener("popstate",function e(){window.removeEventListener("popstate",e),t(!0)}),window.history.go(r)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function or(){if(window.history.length<=1||(window.history.pushState(null,""),await W(1-window.history.length)))return;let t=await W(-1);for(;t;)t=await W(-1)}class Kt{constructor(t,e,{debug:n=!1,loggerPrefix:s="Navigator"}){o(this,"logger");o(this,"entries");if(this.entriesCursor=e,t.length===0)throw new Error("Entries list should not be empty.");if(e>=t.length)throw new Error("Cursor should be less than entries count.");this.entries=t.map(({pathname:i="",search:c,hash:h})=>{if(!i.startsWith("/")&&i.length>0)throw new Error('Pathname should start with "/"');return{pathname:M(i,"/"),search:c?M(c,"?"):"",hash:h?M(h,"#"):""}}),this.logger=new St(`[${s}]`,n)}formatEntry(t){let e;if(typeof t=="string")e=t;else{const{pathname:c="",search:h,hash:p}=t;e=c+(h?M(h,"?"):"")+(p?M(p,"#"):"")}const{pathname:n,search:s,hash:i}=new URL(e,`https://localhost${this.path}`);return{pathname:n,search:s,hash:i}}get entry(){return this.entries[this.entriesCursor]}back(){return this.go(-1)}get cursor(){return this.entriesCursor}get canGoBack(){return this.entriesCursor>0}get canGoForward(){return this.entriesCursor!==this.entries.length-1}forward(){return this.go(1)}go(t){this.logger.log(`called go(${t})`);const e=Math.min(this.entries.length-1,Math.max(this.entriesCursor+t,0));if(this.entriesCursor===e)return this.performGo({updated:!1,delta:t});const n=this.entry;this.entriesCursor=e;const s=this.entry;return this.logger.log("State changed",{before:n,after:s}),this.performGo({updated:!0,delta:t,before:n,after:s})}getEntries(){return this.entries.map(t=>({...t}))}get hash(){return this.entry.hash}push(t){this.entriesCursor!==this.entries.length-1&&this.entries.splice(this.entriesCursor+1);const e=this.formatEntry(t),n=this.entry;this.entriesCursor+=1,this.entries[this.entriesCursor]=e;const s=this.entry;return this.logger.log("State changed",{before:n,after:s}),this.performPush({before:n,after:s})}get path(){return`${this.pathname}${this.search}${this.hash}`}get pathname(){return this.entry.pathname}replace(t){const e=this.formatEntry(t);if(this.search===e.search&&this.pathname===e.pathname&&this.hash===e.hash)return this.performReplace({updated:!1,entry:e});const n=this.entry;this.entries[this.entriesCursor]=e;const s=this.entry;return this.logger.log("State changed",{before:n,after:s}),this.performReplace({updated:!0,before:n,after:s})}get search(){return this.entry.search}}const Yt=0,lt=1,dt=2;class ft extends Kt{constructor(e,n,s={}){super(e,n,{...s,loggerPrefix:"HashNavigator"});o(this,"ee",new b);o(this,"attached",!1);o(this,"onPopState",async({state:e})=>{if(this.logger.log('"popstate" event received. State:',e),e===null)return this.push(window.location.hash.slice(1));if(e===Yt){this.logger.log("Void reached. Moving history forward"),window.history.forward();return}if(e===lt)return this.back();if(e===dt)return this.forward()});o(this,"back",()=>super.back());o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee))}static fromLocation(e){const{search:n,pathname:s,hash:i}=new URL(window.location.hash.slice(1),window.location.href);return new ft([{search:n,pathname:s,hash:i}],0,e)}async performGo(e){e.updated&&(this.attached&&await this.syncHistory(),this.emitChanged(e.before,e.after))}async performPush({before:e,after:n}){this.attached&&await this.syncHistory(),this.emitChanged(e,n)}async performReplace(e){e.updated&&(this.attached&&window.history.replaceState(null,"",`#${this.path}`),this.emitChanged(e.before,e.after))}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const e=`#${this.path}`;await or(),g("web_app_setup_back_button",{is_visible:this.canGoBack}),this.canGoBack&&this.canGoForward?(this.logger.log("Setting up history: [<-, *, ->]"),window.history.replaceState(lt,""),window.history.pushState(null,"",e),window.history.pushState(dt,""),await W(-1)):this.canGoBack?(this.logger.log("Setting up history: [<-, *]"),window.history.replaceState(lt,""),window.history.pushState(null,"",e)):this.canGoForward?(this.logger.log("Setting up history: [*, ->]"),window.history.replaceState(null,e),window.history.pushState(dt,""),await W(-1)):(this.logger.log("Setting up history: [~, *]"),window.history.replaceState(Yt,""),window.history.pushState(null,"",e)),window.addEventListener("popstate",this.onPopState)}emitChanged(e,n){this.ee.emit("change",{navigator:this,from:e,to:n})}async attach(){if(!this.attached)return this.logger.log("Attaching",this),this.attached=!0,E("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))}}return a.BackButton=It,a.ClosingBehavior=Dt,a.CloudStorage=Ht,a.HapticFeedback=Nt,a.HashNavigator=ft,a.InitData=yt,a.Invoice=zt,a.MainButton=Mt,a.MethodUnsupportedError=J,a.MiniApp=Wt,a.Navigator=Kt,a.ParameterUnsupportedError=Q,a.Popup=Jt,a.QRScanner=Qt,a.ThemeParams=Ct,a.Utils=Zt,a.Viewport=O,a.chatParser=mt,a.classNames=Bt,a.compareVersions=Lt,a.createPostEvent=Vt,a.getHash=ir,a.init=sr,a.initDataParser=rt,a.isColorDark=tt,a.isIframe=ct,a.isRGB=Y,a.isRGBShort=wt,a.isRecord=w,a.isTMA=be,a.launchParamsParser=it,a.mergeClassNames=We,a.off=R,a.on=E,a.once=He,a.parseInitData=oe,a.parseLaunchParams=ot,a.parseThemeParams=st,a.postEvent=g,a.request=m,a.requestThemeParams=ue,a.requestViewport=pt,a.retrieveLaunchData=at,a.serializeLaunchParams=vt,a.serializeThemeParams=Et,a.setDebug=Ee,a.setTargetOrigin=Ce,a.subscribe=Ne,a.supports=L,a.themeParamsParser=nt,a.toRGB=X,a.unsubscribe=qt,a.userParser=et,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"}),a}({});
1
+ var or=Object.defineProperty;var ar=(a,_,v)=>_ in a?or(a,_,{enumerable:!0,configurable:!0,writable:!0,value:v}):a[_]=v;var o=(a,_,v)=>(ar(a,typeof _!="symbol"?_+"":_,v),v);this.tmajs=this.tmajs||{};this.tmajs.sdk=function(a){"use strict";function _(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function v(){return performance.getEntriesByType("navigation")[0]||null}function ee(){const r=v();return r?r.type==="reload":null}function T(){return new TypeError("Value has unexpected type")}class G extends Error{constructor(e,{cause:n,type:s}={}){super(`Unable to parse value${s?` as ${s}`:""}`,{cause:n});o(this,"type");this.value=e,Object.setPrototypeOf(this,G.prototype),this.type=s}}class F{constructor(t,e,n){this.parser=t,this.isOptional=e,this.type=n}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(e){throw new G(t,{type:this.type,cause:e})}}optional(){return this.isOptional=!0,this}}function re(r){if(Array.isArray(r))return r;if(typeof r=="string")try{const t=JSON.parse(r);if(Array.isArray(t))return t}catch{}throw T()}class ne extends F{constructor(e,n,s){super(re,n,s);o(this,"itemParser");this.itemParser=typeof e=="function"?e:e.parse.bind(e)}parse(e){const n=super.parse(e);return n===void 0?n:n.map(this.itemParser)}of(e){return this.itemParser=typeof e=="function"?e:e.parse.bind(e),this}}function B(r,t){return()=>new F(r,!1,t)}class z extends Error{constructor(t,{cause:e,type:n}={}){super(`Unable to parse field "${t}"${n?` as ${n}`:""}`,{cause:e}),Object.setPrototypeOf(this,z.prototype)}}function gt(r,t){const e={};for(const n in r){const s=r[n];if(!s)continue;let i,c;if(typeof s=="function"||"parse"in s)i=n,c=typeof s=="function"?s:s.parse.bind(s);else{const{type:g}=s;i=s.from||n,c=typeof g=="function"?g:g.parse.bind(g)}let h;const p=t(i);try{h=c(p)}catch(g){throw g instanceof G?new z(i,{type:g.type,cause:g}):new z(i,{cause:g})}h!==void 0&&(e[n]=h)}return e}function se(r){return new ne(t=>t,!1,r)}const P=B(r=>{if(typeof r=="boolean")return r;const t=String(r);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;throw T()},"boolean"),R=B(r=>{if(typeof r=="number")return r;if(typeof r=="string"){const t=Number(r);if(!Number.isNaN(t))return t}throw T()},"number"),ie=B(r=>r instanceof Date?r:new Date(R().parse(r)*1e3),"Date");function K(r){let t=r;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw T();return t}function w(r,t){return new F(e=>{const n=K(e);return gt(r,s=>n[s])},!1,t)}function Y(r){return/^#[\da-f]{6}$/i.test(r)}function _t(r){return/^#[\da-f]{3}$/i.test(r)}function X(r){const t=r.replace(/\s/g,"").toLowerCase();if(Y(t))return t;if(_t(t)){let n="#";for(let s=0;s<3;s+=1)n+=t[1+s].repeat(2);return n}const e=t.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||t.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(e===null)throw new Error(`Value "${r}" does not satisfy any of known RGB formats.`);return e.slice(1).reduce((n,s)=>{const i=parseInt(s,10).toString(16);return n+(i.length===1?"0":"")+i},"#")}function tt(r){const t=X(r);return Math.sqrt([.299,.587,.114].reduce((n,s,i)=>{const c=parseInt(t.slice(1+i*2,1+(i+1)*2),16);return n+c*c*s},0))<120}const u=B(r=>{if(typeof r=="string"||typeof r=="number")return r.toString();throw T()},"string"),wt=B(r=>X(u().parse(r)),"rgb");function bt(r,t){return new F(e=>{if(typeof e!="string"&&!(e instanceof URLSearchParams))throw T();const n=typeof e=="string"?new URLSearchParams(e):e;return gt(r,s=>{const i=n.get(s);return i===null?void 0:i})},!1,t)}function mt(){return w({id:R(),type:u(),title:u(),photoUrl:{type:u().optional(),from:"photo_url"},username:u().optional()},"Chat")}class yt{constructor(t){this.initData=t}get authDate(){return this.initData.authDate}get canSendAfter(){return this.initData.canSendAfter}get canSendAfterDate(){const{canSendAfter:t}=this;return t===void 0?void 0:new Date(this.authDate.getTime()+t*1e3)}get chat(){return this.initData.chat}get chatType(){return this.initData.chatType}get chatInstance(){return this.initData.chatInstance}get hash(){return this.initData.hash}get queryId(){return this.initData.queryId}get receiver(){return this.initData.receiver}get startParam(){return this.initData.startParam}get user(){return this.initData.user}}function et(){return w({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:R(),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")}function rt(){return bt({authDate:{type:ie(),from:"auth_date"},canSendAfter:{type:R().optional(),from:"can_send_after"},chat:mt().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:et().optional(),startParam:{type:u().optional(),from:"start_param"},user:et().optional()},"InitData")}function oe(r){return rt().parse(r)}function ae(r){return r.replace(/(^|_)bg/,(t,e)=>`${e}background`).replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function ce(r){return r.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`).replace(/(^|_)background/,(t,e)=>`${e}bg`)}const nt=B(r=>{const t=wt().optional();return Object.entries(K(r)).reduce((e,[n,s])=>(e[ae(n)]=t.parse(s),e),{})},"ThemeParams");function st(r){return nt().parse(r)}function he(r={}){return E("web_app_request_theme","theme_changed",r).then(st)}function Et(r){return JSON.stringify(Object.entries(r).reduce((t,[e,n])=>(n&&(t[ce(e)]=n),t),{}))}class b{constructor(){o(this,"listeners",new Map);o(this,"subscribeListeners",[])}addListener(t,e,n){let s=this.listeners.get(t);return s||(s=[],this.listeners.set(t,s)),s.push([e,n]),()=>this.off(t,e)}emit(t,...e){this.subscribeListeners.forEach(s=>s(t,...e));const n=this.listeners.get(t);n&&n.forEach(([s,i],c)=>{s(...e),i&&n.splice(c,1)})}on(t,e){return this.addListener(t,e,!1)}once(t,e){return this.addListener(t,e,!0)}off(t,e){const n=this.listeners.get(t);if(n){for(let s=0;s<n.length;s+=1)if(e===n[s][0]){n.splice(s,1);return}}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let e=0;e<this.subscribeListeners.length;e+=1)if(this.subscribeListeners[e]===t){this.subscribeListeners.splice(e,1);return}}}class m{constructor(t,e){this.state=t,this.ee=e}internalSet(t,e){return this.state[t]===e||e===void 0?!1:(this.state[t]=e,this.ee.emit(`change:${t}`,e),!0)}clone(){return{...this.state}}set(t,e){let n=!1;if(typeof t=="string")n=this.internalSet(t,e);else for(const s in t)this.internalSet(s,t[s])&&(n=!0);n&&this.ee.emit("change")}get(t){return this.state[t]}}class Ct{constructor(t){o(this,"ee",new b);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(t,this.ee)}get accentTextColor(){return this.get("accentTextColor")}get backgroundColor(){return this.get("backgroundColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}get(t){return this.state.get(t)}getState(){return this.state.clone()}get headerBackgroundColor(){return this.get("headerBackgroundColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.backgroundColor||tt(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",t=>{this.state.set(st(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}function it(){return bt({botInline:{type:P().optional(),from:"tgWebAppBotInline"},initData:{type:rt().optional(),from:"tgWebAppData"},initDataRaw:{type:u().optional(),from:"tgWebAppData"},platform:{type:u(),from:"tgWebAppPlatform"},showSettings:{type:P().optional(),from:"tgWebAppShowSettings"},themeParams:{type:nt(),from:"tgWebAppThemeParams"},version:{type:u(),from:"tgWebAppVersion"}},"LaunchParams")}function ot(r){return it().parse(r)}function ue(){return ot(window.location.hash.slice(1))}function pe(){const r=v();if(!r)throw new Error("Unable to get first navigation entry.");const t=r.name.match(/#(.*)/);if(!t)throw new Error("First navigation entry does not contain hash part.");return ot(t[1])}function le(){try{return pe()}catch{}try{return ue()}catch{}return null}function vt(r){const{initDataRaw:t,themeParams:e,platform:n,version:s,showSettings:i,botInline:c}=r,h=new URLSearchParams;return t&&h.set("tgWebAppData",t),h.set("tgWebAppPlatform",n),h.set("tgWebAppThemeParams",Et(e)),h.set("tgWebAppVersion",s),typeof i=="boolean"&&h.set("tgWebAppShowSettings",i?"1":"0"),typeof c=="boolean"&&h.set("tgWebAppBotInline",c?"1":"0"),h.toString()}const Pt="telegram-mini-apps-launch-params";function de(){const r=sessionStorage.getItem(Pt);return r?it().parse(r):null}function fe(r){sessionStorage.setItem(Pt,vt(r))}function ge(){try{return window.self!==window.top}catch{return!0}}function _e(){const r=de(),t=le(),e=ee();if(r){if(t)return{launchParams:t,isPageReload:ge()?e||r.initDataRaw===t.initDataRaw:!0};if(e)return{launchParams:r,isPageReload:e};throw new Error("Unable to retrieve current launch parameters, which must exist.")}if(t)return{launchParams:t,isPageReload:!1};throw new Error("Unable to retrieve any launch parameters.")}const kt="tmajsLaunchData";function at(){const r=window[kt];if(r)return r;const t=_e();return window[kt]=t,fe(t.launchParams),t}function we(){try{return at(),!0}catch{return!1}}function be(r){return"external"in r&&_(r.external)&&"notify"in r.external&&typeof r.external.notify=="function"}function me(r){return"TelegramWebviewProxy"in r&&_(r.TelegramWebviewProxy)&&"postEvent"in r.TelegramWebviewProxy&&typeof r.TelegramWebviewProxy.postEvent=="function"}function ct(){try{return window.self!==window.top}catch{return!0}}class J extends Error{constructor(t,e){super(`Method "${t}" is unsupported in the Mini Apps version ${e}.`),Object.setPrototypeOf(this,J.prototype)}}class Q extends Error{constructor(t,e,n){super(`Parameter "${e}" in method "${t}" is unsupported in the Mini Apps version ${n}.`),Object.setPrototypeOf(this,Q.prototype)}}class St{constructor(t,e){this.prefix=t,this.enabled=e}print(t,...e){if(!this.enabled)return;const n=new Date,s=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n);console[t](`[${s}]`,this.prefix,...e)}disable(){this.enabled=!1}error(...t){this.print("error",...t)}enable(){this.enabled=!0}log(...t){this.print("log",...t)}warn(...t){this.print("warn",...t)}}let Vt="https://web.telegram.org";const $=new St("[SDK]",!1);function ye(r){if(r){$.enable();return}$.disable()}function Ee(r){Vt=r}function Ce(){return Vt}const ve=w({eventType:u(),eventData:r=>r});function Pe(r,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:r,eventData:t})}))}function ke(){const r=window;"TelegramGameProxy_receiveEvent"in r||[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(t=>{let e=r;t.forEach((n,s,i)=>{if(s===i.length-1){e[n]=Pe;return}n in e||(e[n]={}),e=e[n]})})}function Se(r){ke(),window.addEventListener("message",t=>{try{const{eventType:e,eventData:n}=ve.parse(t.data);r(e,n)}catch{}})}function Ve(){return w({req_id:u(),data:r=>r===null?r:u().optional().parse(r)})}function Ae(){return w({req_id:u(),result:r=>r,error:u().optional()})}function qe(){return w({slug:u(),status:u()})}function Le(){return w({status:u()})}function Te(){return w({button_id:r=>r==null?void 0:u().parse(r)})}function Be(){return w({data:u().optional()})}function Re(){return w({theme_params:r=>{const t=wt().optional();return Object.entries(K(r)).reduce((e,[n,s])=>(e[n]=t.parse(s),e),{})}})}function $e(){return w({height:R(),width:r=>r==null?window.innerWidth:R().parse(r),is_state_stable:P(),is_expanded:P()})}function Ie(){return w({status:u()})}function De(){const r=new b,t=(e,...n)=>{$.log("Emitting processed event:",e,...n),r.emit(e,...n)};return window.addEventListener("resize",()=>{t("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),Se((e,n)=>{$.log("Received raw event:",e,n);try{switch(e){case"viewport_changed":return t(e,$e().parse(n));case"theme_changed":return t(e,Re().parse(n));case"popup_closed":return n==null?t(e,{}):t(e,Te().parse(n));case"set_custom_style":return t(e,u().parse(n));case"qr_text_received":return t(e,Be().parse(n));case"clipboard_text_received":return t(e,Ve().parse(n));case"invoice_closed":return t(e,qe().parse(n));case"phone_requested":return t("phone_requested",Le().parse(n));case"custom_method_invoked":return t("custom_method_invoked",Ae().parse(n));case"write_access_requested":return t("write_access_requested",Ie().parse(n));case"main_button_pressed":case"back_button_pressed":case"settings_button_pressed":case"scan_qr_popup_closed":case"reload_iframe":return t(e);default:return t(e,n)}}catch(s){$.error("Error processing event:",s)}}),r}const ht="telegram-mini-apps-cached-emitter";function H(){const r=window;return r[ht]===void 0&&(r[ht]=De()),r[ht]}function q(r,t){H().off(r,t)}function y(r,t){return H().on(r,t),()=>q(r,t)}function xe(r,t){return H().once(r,t),()=>q(r,t)}function At(r){H().unsubscribe(r)}function He(r){return H().subscribe(r),()=>At(r)}function qt(r,t){const e=r.split("."),n=t.split("."),s=Math.max(e.length,n.length);for(let i=0;i<s;i+=1){const c=parseInt(e[i]||"0",10),h=parseInt(n[i]||"0",10);if(c!==h)return c>h?1:-1}return 0}function k(r,t){return qt(r,t)<=0}function L(r,t,e){if(typeof e=="string"){if(r==="web_app_open_link"&&t==="try_instant_view")return k("6.4",e);if(r==="web_app_set_header_color"&&t==="color")return k("6.9",e)}switch(r){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return k("6.1",t);case"web_app_open_popup":return k("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 k("6.4",t);case"web_app_switch_inline_query":return k("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return k("6.9",t);case"web_app_setup_settings_button":return k("6.10",t);default:return!0}}function C(r,t){return e=>L(t[e],r)}function Lt(r,t){return e=>{const[n,s]=t[e];return L(n,s,r)}}function f(r,t,e){let n={},s;t===void 0&&e===void 0?n={}:t!==void 0&&e!==void 0?(n=e,s=t):t!==void 0&&("targetOrigin"in t?n=t:s=t);const{targetOrigin:i=Ce()}=n;if($.log(`Calling method "${r}"`,s),ct()){window.parent.postMessage(JSON.stringify({eventType:r,eventData:s}),i);return}if(be(window)){window.external.notify(JSON.stringify({eventType:r,eventData:s}));return}if(me(window)){window.TelegramWebviewProxy.postEvent(r,JSON.stringify(s));return}throw new Error("Unable to determine current environment and possible way to send event.")}function Tt(r){return(t,e)=>{if(!L(t,r))throw new J(t,r);if(_(e)){let n;if(t==="web_app_open_link"&&"try_instant_view"in e?n="try_instant_view":t==="web_app_set_header_color"&&"color"in e&&(n="color"),n&&!L(t,n,r))throw new Q(t,n,r)}return f(t,e)}}class ut extends Error{constructor(t){super(`Async call timeout exceeded. Timeout: ${t}`),Object.setPrototypeOf(this,ut.prototype)}}function Bt(r){return new Promise((t,e)=>{setTimeout(e,r,new ut(r))})}function Ne(r,t){return typeof r=="function"?(...e)=>Promise.race([r(...e),Bt(t)]):Promise.race([r,Bt(t)])}function E(r,t,e,n){let s,i,c,h;typeof t=="string"||Array.isArray(t)?(c=Array.isArray(t)?t:[t],s=e):(i=t,c=Array.isArray(e)?e:[e],s=n),_(i)&&typeof i.req_id=="string"&&(h=i.req_id);const{postEvent:p=f,timeout:g}=s||{},l=s&&"capture"in s?s.capture:null,V=new Promise((d,A)=>{const x=c.map(j=>y(j,Z=>{typeof h=="string"&&(!_(Z)||Z.req_id!==h)||typeof l=="function"&&!l(Z)||(U(),d(Z))})),U=()=>x.forEach(j=>j());try{p(r,i)}catch(j){U(),A(j)}});return typeof g=="number"?Ne(V,g):V}class Rt{constructor(t,e,n=f){o(this,"ee",new b);o(this,"state");o(this,"on",(t,e)=>t==="click"?y("back_button_pressed",e):this.ee.on(t,e));o(this,"off",(t,e)=>t==="click"?q("back_button_pressed",e):this.ee.off(t,e));o(this,"supports");this.postEvent=n,this.state=new m({isVisible:t},this.ee),this.supports=C(e,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"})}set isVisible(t){this.state.set("isVisible",t),this.postEvent("web_app_setup_back_button",{is_visible:t})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function $t(r,t){return r+(r.length>0&&t.length>0?` ${t}`:t)}function It(...r){return r.reduce((t,e)=>{let n="";return typeof e=="string"?n=e:typeof e=="object"&&e!==null&&(n=Object.entries(e).reduce((s,[i,c])=>c?$t(s,i):s,"")),$t(t,n)},"")}function Oe(r){return typeof r=="object"&&r!==null&&!Array.isArray(null)}function Me(...r){return r.reduce((t,e)=>(Oe(e)&&Object.entries(e).forEach(([n,s])=>{const i=It(t[n],s);i.length>0&&(t[n]=i)}),t),{})}class Dt{constructor(t,e=f){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));this.postEvent=e,this.state=new m({isConfirmationNeeded:t},this.ee)}set isConfirmationNeeded(t){this.state.set("isConfirmationNeeded",t),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:t})}get isConfirmationNeeded(){return this.state.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}function xt(r,t){return r.reduce((e,n)=>(e[n]=t,e),{})}class Ht{constructor(t,e,n=f){o(this,"supports");this.createRequestId=e,this.postEvent=n,this.supports=C(t,{delete:"web_app_invoke_custom_method",get:"web_app_invoke_custom_method",getKeys:"web_app_invoke_custom_method",set:"web_app_invoke_custom_method"})}async invokeCustomMethod(t,e,n={}){const{result:s,error:i}=await E("web_app_invoke_custom_method",{method:t,params:e,req_id:this.createRequestId()},"custom_method_invoked",{...n,postEvent:this.postEvent});if(i)throw new Error(i);return s}async delete(t,e){const n=Array.isArray(t)?t:[t];n.length!==0&&await this.invokeCustomMethod("deleteStorageValues",{keys:n},e)}async getKeys(t){const e=await this.invokeCustomMethod("getStorageKeys",{},t);return se().of(u()).parse(e)}async get(t,e){const n=Array.isArray(t)?t:[t];if(n.length===0)return xt(n,"");const s=w(xt(n,u())),i=await this.invokeCustomMethod("getStorageValues",{keys:n},e).then(c=>s.parse(c));return Array.isArray(t)?i:i[t]}async set(t,e,n){await this.invokeCustomMethod("saveStorageValue",{key:t,value:e},n)}}class Nt{constructor(t,e=f){o(this,"supports");this.postEvent=e,this.supports=C(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"})}impactOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"impact",impact_style:t})}notificationOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"notification",notification_type:t})}selectionChanged(){this.postEvent("web_app_trigger_haptic_feedback",{type:"selection_change"})}}function We(){const r=document.createElement("style");r.id="telegram-custom-styles",document.head.appendChild(r),y("set_custom_style",t=>{r.innerHTML=t})}function Ot(r){return`telegram-mini-apps-${r}`}function I(r,t){sessionStorage.setItem(Ot(r),JSON.stringify(t))}function D(r){const t=sessionStorage.getItem(Ot(r));return t?JSON.parse(t):null}function Ue(r,t,e){const{isVisible:n=!1}=r?D("back-button")||{}:{},s=new Rt(n,t,e);return s.on("change",()=>{I("back-button",{isVisible:s.isVisible})}),s}function je(r,t){const{isConfirmationNeeded:e=!1}=r?D("closing-behavior")||{}:{},n=new Dt(e,t);return n.on("change",()=>I("closing-behavior",{isConfirmationNeeded:n.isConfirmationNeeded})),n}class Mt{constructor(t){o(this,"ee",new b);o(this,"state");o(this,"postEvent");o(this,"on",(t,e)=>t==="click"?y("main_button_pressed",e):this.ee.on(t,e));o(this,"off",(t,e)=>t==="click"?q("main_button_pressed",e):this.ee.off(t,e));const{postEvent:e=f,text:n,textColor:s,backgroundColor:i,isEnabled:c,isVisible:h,isLoaderVisible:p}=t;this.postEvent=e,this.state=new m({backgroundColor:i,isEnabled:c,isVisible:h,isLoaderVisible:p,text:n,textColor:s},this.ee)}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.backgroundColor,text_color:this.textColor})}set isEnabled(t){this.setParams({isEnabled:t})}get isEnabled(){return this.state.get("isEnabled")}set isLoaderVisible(t){this.setParams({isLoaderVisible:t})}get isLoaderVisible(){return this.state.get("isLoaderVisible")}set isVisible(t){this.setParams({isVisible:t})}get isVisible(){return this.state.get("isVisible")}get backgroundColor(){return this.state.get("backgroundColor")}get text(){return this.state.get("text")}get textColor(){return this.state.get("textColor")}disable(){return this.isEnabled=!1,this}enable(){return this.isEnabled=!0,this}hide(){return this.isVisible=!1,this}hideLoader(){return this.isLoaderVisible=!1,this}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(t){return this.setParams({text:t})}setTextColor(t){return this.setParams({textColor:t})}setBackgroundColor(t){return this.setParams({backgroundColor:t})}setParams(t){return this.state.set(t),this.commit(),this}}function Ge(r,t,e,n){const{backgroundColor:s=t,isEnabled:i=!1,isVisible:c=!1,isLoaderVisible:h=!1,textColor:p=e,text:g=""}=r?D("main-button")||{}:{},l=new Mt({backgroundColor:s,isEnabled:i,isLoaderVisible:h,isVisible:c,postEvent:n,text:g,textColor:p}),V=()=>I("main-button",{backgroundColor:l.backgroundColor,isEnabled:l.isEnabled,isLoaderVisible:l.isLoaderVisible,isVisible:l.isVisible,text:l.text,textColor:l.textColor});return l.on("change",V),l}class Wt{constructor(t){o(this,"ee",new b);o(this,"state");o(this,"botInline");o(this,"postEvent");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");o(this,"supportsParam");const{postEvent:e=f,headerColor:n,backgroundColor:s,version:i,botInline:c}=t,h=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=e,this.botInline=c,this.supports=p=>!(!h(p)||p==="switchInlineQuery"&&!c),this.state=new m({backgroundColor:s,headerColor:n},this.ee),this.supportsParam=Lt(i,{"setHeaderColor.color":["web_app_set_header_color","color"]})}get backgroundColor(){return this.state.get("backgroundColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.state.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return tt(this.backgroundColor)}ready(){this.postEvent("web_app_ready")}requestPhoneAccess(){return E("web_app_request_phone","phone_requested",{postEvent:this.postEvent}).then(t=>t.status)}requestWriteAccess(){return E("web_app_request_write_access","write_access_requested",{postEvent:this.postEvent}).then(t=>t.status)}sendData(t){const{size:e}=new Blob([t]);if(e===0||e>4096)throw new Error(`Passed data has incorrect size: ${e}`);this.postEvent("web_app_data_send",{data:t})}setHeaderColor(t){this.postEvent("web_app_set_header_color",Y(t)?{color:t}:{color_key:t}),this.state.set("headerColor",t)}setBackgroundColor(t){this.postEvent("web_app_set_background_color",{color:t}),this.state.set("backgroundColor",t)}switchInlineQuery(t,e=[]){if(!this.supports("switchInlineQuery")&&!this.isBotInline)throw new Error("Method is unsupported because Mini App should be launched in inline mode.");this.postEvent("web_app_switch_inline_query",{query:t,chat_types:e})}}function Fe(r,t,e,n,s){const{backgroundColor:i=t,headerColor:c="bg_color"}=r?D("mini-app")||{}:{},h=new Wt({headerColor:c,backgroundColor:i,version:e,botInline:n,postEvent:s}),p=()=>I("mini-app",{backgroundColor:h.backgroundColor,headerColor:h.headerColor});return h.on("change",p),h}function ze(){let r=0;return()=>(r+=1,r.toString())}class Ut{constructor(t,e,n=f){o(this,"ee",new b);o(this,"state");o(this,"on",(t,e)=>t==="click"?y("settings_button_pressed",e):this.ee.on(t,e));o(this,"off",(t,e)=>t==="click"?q("settings_button_pressed",e):this.ee.off(t,e));o(this,"supports");this.postEvent=n,this.state=new m({isVisible:t},this.ee),this.supports=C(e,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"})}set isVisible(t){this.state.set("isVisible",t),this.postEvent("web_app_setup_settings_button",{is_visible:t})}get isVisible(){return this.state.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}function Je(r,t,e){const{isVisible:n=!1}=r?D("settings-button")||{}:{},s=new Ut(n,t,e);return s.on("change",()=>{I("settings-button",{isVisible:s.isVisible})}),s}function Qe(r){const t=new Ct(r);return t.listen(),t}async function pt(r){const t=await E("web_app_request_viewport","viewport_changed",r);return{height:t.height,width:t.width,isExpanded:t.is_expanded,isStateStable:t.is_state_stable}}function N(r){return r<0?0:r}class O{constructor(t){o(this,"ee",new b);o(this,"state");o(this,"postEvent");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));const{height:e,isExpanded:n,width:s,stableHeight:i,postEvent:c=f}=t;this.postEvent=c,this.state=new m({height:N(e),isExpanded:n,stableHeight:N(i),width:N(s)},this.ee)}sync(t){return pt(t).then(({height:e,isExpanded:n,width:s,isStateStable:i})=>{this.state.set({height:e,width:s,isExpanded:n,stableHeight:i?e:this.state.get("stableHeight")})})}get height(){return this.state.get("height")}get stableHeight(){return this.state.get("stableHeight")}listen(){return y("viewport_changed",t=>{const{height:e,width:n,is_expanded:s,is_state_stable:i}=t,c={height:N(e),isExpanded:s,width:N(n)};i&&(c.stableHeight=c.height),this.state.set(c)})}get isExpanded(){return this.state.get("isExpanded")}get width(){return this.state.get("width")}expand(){this.postEvent("web_app_expand"),this.state.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}function jt(r){return!["macos","web","weba"].includes(r)}function Gt(r,t,e){if(r||!jt(t))return new O({height:window.innerHeight,isExpanded:!0,postEvent:e,stableHeight:window.innerHeight,width:window.innerWidth});const n=D("viewport");return n?new O({...n,postEvent:e}):null}function Ft(r){return r.listen(),r.on("change",()=>I("viewport",{height:r.height,isExpanded:r.isExpanded,stableHeight:r.stableHeight,width:r.width})),r}function Ze(r,t,e){const n=Ft(Gt(r,t,e)||new O({width:0,height:0,isExpanded:!1,postEvent:e,stableHeight:0}));return jt(t)&&n.sync({postEvent:e,timeout:100}).catch(s=>{console.error("Unable to actualize viewport state",s)}),n}async function Ke(r,t,e){return Ft(Gt(r,t,e)||await pt({postEvent:e,timeout:100}).then(({height:n,isStateStable:s,...i})=>new O({...i,height:n,stableHeight:s?n:0})))}function S(r,t){document.documentElement.style.setProperty(r,t)}function Ye(r,t){const e=()=>{S("--tg-background-color",r.backgroundColor)},n=()=>{const{backgroundColor:s,secondaryBackgroundColor:i}=t;r.headerColor==="bg_color"?s&&S("--tg-header-color",s):r.headerColor==="secondary_bg_color"?i&&S("--tg-header-color",i):S("--tg-header-color",r.headerColor)};t.on("change",n),r.on("change:backgroundColor",e),r.on("change:headerColor",n),e(),n()}function Xe(r){const t=()=>{const e=r.getState();Object.entries(e).forEach(([n,s])=>{if(s){const i=n.replace(/[A-Z]/g,c=>`-${c.toLowerCase()}`);S(`--tg-theme-${i}`,s)}})};r.on("change",t),t()}function zt(r){const t=()=>S("--tg-viewport-height",`${r.height}px`),e=()=>S("--tg-viewport-width",`${r.width}px`),n=()=>S("--tg-viewport-height",`${r.stableHeight}px`);r.on("change:height",t),r.on("change:width",e),r.on("change:stableHeight",n),t(),e(),n()}function tr(r){return typeof r=="object"?r:r?{themeParams:!0,viewport:!0,miniApp:!0}:{}}function Jt(r,t,e,n){const s=tr(r);s.miniApp&&Ye(t,e),s.themeParams&&Xe(e),s.viewport&&(n instanceof Promise?n.then(zt):zt(n))}function er(r){const{hostname:t,pathname:e}=new URL(r,window.location.href);if(t!=="t.me")throw new Error(`Incorrect hostname: ${t}`);const n=e.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(n===null)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');return n[2]}class Qt{constructor(t,e=f){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new m({isOpened:!1},this.ee),this.supports=C(t,{open:"web_app_open_invoice"})}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}async open(t,e){if(this.isOpened)throw new Error("Invoice is already opened");const n=e?er(t):t;this.isOpened=!0;try{return(await E("web_app_open_invoice",{slug:n},"invoice_closed",{postEvent:this.postEvent,capture(i){return n===i.slug}})).status}finally{this.isOpened=!1}}}function rr(r){const t=r.message.trim(),e=(r.title||"").trim(),n=r.buttons||[];let s;if(e.length>64)throw new Error(`Title has incorrect size: ${e.length}`);if(t.length===0||t.length>256)throw new Error(`Message has incorrect size: ${t.length}`);if(n.length>3)throw new Error(`Buttons have incorrect size: ${n.length}`);return n.length===0?s=[{type:"close",id:""}]:s=n.map(i=>{const{id:c=""}=i;if(c.length>64)throw new Error(`Button ID has incorrect size: ${c}`);if(i.type===void 0||i.type==="default"||i.type==="destructive"){const h=i.text.trim();if(h.length===0||h.length>64){const p=i.type||"default";throw new Error(`Button text with type "${p}" has incorrect size: ${i.text.length}`)}return{...i,text:h,id:c}}return{...i,id:c}}),{title:e,message:t,buttons:s}}class Zt{constructor(t,e=f){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new m({isOpened:!1},this.ee),this.supports=C(t,{open:"web_app_open_popup"})}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}open(t){if(this.isOpened)throw new Error("Popup is already opened.");return this.isOpened=!0,E("web_app_open_popup",rr(t),"popup_closed",{postEvent:this.postEvent}).then(({button_id:e=null})=>e).finally(()=>{this.isOpened=!1})}}class Kt{constructor(t,e=f){o(this,"ee",new b);o(this,"state");o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee));o(this,"supports");this.postEvent=e,this.state=new m({isOpened:!1},this.ee),this.supports=C(t,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"})}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(t){this.state.set("isOpened",t)}get isOpened(){return this.state.get("isOpened")}async open(t){if(this.isOpened)throw new Error("QR scanner is already opened.");this.isOpened=!0;try{const e=await E("web_app_open_scan_qr_popup",{text:t},["qr_text_received","scan_qr_popup_closed"],{postEvent:this.postEvent});return typeof e=="object"&&typeof e.data=="string"?e.data:null}finally{this.isOpened=!1}}}class Yt{constructor(t,e,n=f){o(this,"supports");o(this,"supportsParam");this.version=t,this.createRequestId=e,this.postEvent=n,this.supports=C(t,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),this.supportsParam=Lt(t,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(t,e){const n=new URL(t,window.location.href).toString();if(!L("web_app_open_link",this.version)){window.open(n,"_blank");return}this.postEvent("web_app_open_link",{url:n,...typeof e=="boolean"?{try_instant_view:e}:{}})}openTelegramLink(t){const{hostname:e,pathname:n,search:s}=new URL(t,window.location.href);if(e!=="t.me")throw new Error(`URL has not allowed hostname: ${e}. Only "t.me" is allowed`);if(!L("web_app_open_tg_link",this.version)){window.location.href=t;return}this.postEvent("web_app_open_tg_link",{path_full:n+s})}readTextFromClipboard(){return E("web_app_read_text_from_clipboard",{req_id:this.createRequestId()},"clipboard_text_received",{postEvent:this.postEvent}).then(({data:t=null})=>t)}}function nr(r={}){const{async:t=!1,cssVars:e=!1,acceptCustomStyles:n=!1}=r;try{const{launchParams:{initData:s,initDataRaw:i,version:c,platform:h,themeParams:p,botInline:g=!1},isPageReload:l}=at(),V=ze(),d=Tt(c);ct()&&(n&&We(),d("iframe_ready",{reload_supported:!0}),y("reload_iframe",()=>window.location.reload()));const A={backButton:Ue(l,c,d),closingBehavior:je(l,d),cloudStorage:new Ht(c,V,d),createRequestId:V,hapticFeedback:new Nt(c,d),invoice:new Qt(c,d),mainButton:Ge(l,p.buttonColor||"#000000",p.buttonTextColor||"#ffffff",d),miniApp:Fe(l,p.backgroundColor||"#ffffff",c,g,d),popup:new Zt(c,d),postEvent:d,qrScanner:new Kt(c,d),settingsButton:Je(l,c,d),themeParams:Qe(p),utils:new Yt(c,V,d),...s?{initData:new yt(s),initDataRaw:i}:{}},x=t?Ke(l,h,d):Ze(l,h,d);return x instanceof Promise?x.then(U=>(Jt(e,A.miniApp,A.themeParams,U),{...A,viewport:U})):(Jt(e,A.miniApp,A.themeParams,x),{...A,viewport:x})}catch(s){if(t)return Promise.reject(s);throw s}}function M(r,t){return r.startsWith(t)?r:`${t}${r}`}function sr(r){const t=r.match(/#(.+)/);return t?t[1]:null}async function W(r){return r===0?!0:Promise.race([new Promise(t=>{window.addEventListener("popstate",function e(){window.removeEventListener("popstate",e),t(!0)}),window.history.go(r)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function ir(){if(window.history.length<=1||(window.history.pushState(null,""),await W(1-window.history.length)))return;let t=await W(-1);for(;t;)t=await W(-1)}class Xt{constructor(t,e,{debug:n=!1,loggerPrefix:s="Navigator"}){o(this,"logger");o(this,"entries");if(this.entriesCursor=e,t.length===0)throw new Error("Entries list should not be empty.");if(e>=t.length)throw new Error("Cursor should be less than entries count.");this.entries=t.map(({pathname:i="",search:c,hash:h})=>{if(!i.startsWith("/")&&i.length>0)throw new Error('Pathname should start with "/"');return{pathname:M(i,"/"),search:c?M(c,"?"):"",hash:h?M(h,"#"):""}}),this.logger=new St(`[${s}]`,n)}formatEntry(t){let e;if(typeof t=="string")e=t;else{const{pathname:c="",search:h,hash:p}=t;e=c+(h?M(h,"?"):"")+(p?M(p,"#"):"")}const{pathname:n,search:s,hash:i}=new URL(e,`https://localhost${this.path}`);return{pathname:n,search:s,hash:i}}get entry(){return this.entries[this.entriesCursor]}back(){return this.go(-1)}get cursor(){return this.entriesCursor}get canGoBack(){return this.entriesCursor>0}get canGoForward(){return this.entriesCursor!==this.entries.length-1}forward(){return this.go(1)}go(t){this.logger.log(`called go(${t})`);const e=Math.min(this.entries.length-1,Math.max(this.entriesCursor+t,0));if(this.entriesCursor===e)return this.performGo({updated:!1,delta:t});const n=this.entry;this.entriesCursor=e;const s=this.entry;return this.logger.log("State changed",{before:n,after:s}),this.performGo({updated:!0,delta:t,before:n,after:s})}getEntries(){return this.entries.map(t=>({...t}))}get hash(){return this.entry.hash}push(t){this.entriesCursor!==this.entries.length-1&&this.entries.splice(this.entriesCursor+1);const e=this.formatEntry(t),n=this.entry;this.entriesCursor+=1,this.entries[this.entriesCursor]=e;const s=this.entry;return this.logger.log("State changed",{before:n,after:s}),this.performPush({before:n,after:s})}get path(){return`${this.pathname}${this.search}${this.hash}`}get pathname(){return this.entry.pathname}replace(t){const e=this.formatEntry(t);if(this.search===e.search&&this.pathname===e.pathname&&this.hash===e.hash)return this.performReplace({updated:!1,entry:e});const n=this.entry;this.entries[this.entriesCursor]=e;const s=this.entry;return this.logger.log("State changed",{before:n,after:s}),this.performReplace({updated:!0,before:n,after:s})}get search(){return this.entry.search}}const te=0,lt=1,dt=2;class ft extends Xt{constructor(e,n,s={}){super(e,n,{...s,loggerPrefix:"HashNavigator"});o(this,"ee",new b);o(this,"attached",!1);o(this,"onPopState",async({state:e})=>{if(this.logger.log('"popstate" event received. State:',e),e===null)return this.push(window.location.hash.slice(1));if(e===te){this.logger.log("Void reached. Moving history forward"),window.history.forward();return}if(e===lt)return this.back();if(e===dt)return this.forward()});o(this,"back",()=>super.back());o(this,"on",this.ee.on.bind(this.ee));o(this,"off",this.ee.off.bind(this.ee))}static fromLocation(e){const{search:n,pathname:s,hash:i}=new URL(window.location.hash.slice(1),window.location.href);return new ft([{search:n,pathname:s,hash:i}],0,e)}async performGo(e){e.updated&&(this.attached&&await this.syncHistory(),this.emitChanged(e.before,e.after))}async performPush({before:e,after:n}){this.attached&&await this.syncHistory(),this.emitChanged(e,n)}async performReplace(e){e.updated&&(this.attached&&window.history.replaceState(null,"",`#${this.path}`),this.emitChanged(e.before,e.after))}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const e=`#${this.path}`;await ir(),f("web_app_setup_back_button",{is_visible:this.canGoBack}),this.canGoBack&&this.canGoForward?(this.logger.log("Setting up history: [<-, *, ->]"),window.history.replaceState(lt,""),window.history.pushState(null,"",e),window.history.pushState(dt,""),await W(-1)):this.canGoBack?(this.logger.log("Setting up history: [<-, *]"),window.history.replaceState(lt,""),window.history.pushState(null,"",e)):this.canGoForward?(this.logger.log("Setting up history: [*, ->]"),window.history.replaceState(null,e),window.history.pushState(dt,""),await W(-1)):(this.logger.log("Setting up history: [~, *]"),window.history.replaceState(te,""),window.history.pushState(null,"",e)),window.addEventListener("popstate",this.onPopState)}emitChanged(e,n){this.ee.emit("change",{navigator:this,from:e,to:n})}async attach(){if(!this.attached)return this.logger.log("Attaching",this),this.attached=!0,y("back_button_pressed",this.back),this.syncHistory()}detach(){this.attached&&(this.logger.log("Detaching",this),this.attached=!1,window.removeEventListener("popstate",this.onPopState),q("back_button_pressed",this.back))}}return a.BackButton=Rt,a.ClosingBehavior=Dt,a.CloudStorage=Ht,a.HapticFeedback=Nt,a.HashNavigator=ft,a.InitData=yt,a.Invoice=Qt,a.MainButton=Mt,a.MethodUnsupportedError=J,a.MiniApp=Wt,a.Navigator=Xt,a.ParameterUnsupportedError=Q,a.Popup=Zt,a.QRScanner=Kt,a.SettingsButton=Ut,a.ThemeParams=Ct,a.Utils=Yt,a.Viewport=O,a.chatParser=mt,a.classNames=It,a.compareVersions=qt,a.createPostEvent=Tt,a.getHash=sr,a.init=nr,a.initDataParser=rt,a.isColorDark=tt,a.isIframe=ct,a.isRGB=Y,a.isRGBShort=_t,a.isRecord=_,a.isTMA=we,a.launchParamsParser=it,a.mergeClassNames=Me,a.off=q,a.on=y,a.once=xe,a.parseInitData=oe,a.parseLaunchParams=ot,a.parseThemeParams=st,a.postEvent=f,a.request=E,a.requestThemeParams=he,a.requestViewport=pt,a.retrieveLaunchData=at,a.serializeLaunchParams=vt,a.serializeThemeParams=Et,a.setDebug=ye,a.setTargetOrigin=Ee,a.subscribe=He,a.supports=L,a.themeParamsParser=nt,a.toRGB=X,a.unsubscribe=At,a.userParser=et,Object.defineProperty(a,Symbol.toStringTag,{value:"Module"}),a}({});
2
2
  //# sourceMappingURL=index.iife.js.map