@tma.js/sdk 2.6.1 → 2.7.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,4 @@
1
- var Xe=Object.defineProperty;var ze=(i,l,m)=>l in i?Xe(i,l,{enumerable:!0,configurable:!0,writable:!0,value:m}):i[l]=m;var P=(i,l,m)=>ze(i,typeof l!="symbol"?l+"":l,m);this.tmajs=this.tmajs||{};this.tmajs.sdk=function(i){"use strict";function l(t,e){let n;const r=()=>{n!==void 0&&e&&e(n),n=void 0};return[()=>n===void 0?n=t(r):n,r]}function m(t){const e=R(),{count:n}=e;e.unsubscribe(t),n&&!e.count&&ye()}function U(t){return R().subscribe(t),()=>m(t)}class re{constructor(e,n={}){this.scope=e,this.options=n}print(e,...n){const r=new Date,o=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(r),{textColor:s,bgColor:u}=this.options,c="font-weight: bold;padding: 0 5px;border-radius:5px";console[e](`%c${o}%c / %c${this.scope}`,`${c};background-color: lightblue;color:black`,"",`${c};${s?`color:${s};`:""}${u?`background-color:${u}`:""}`,...n)}error(...e){this.print("error",...e)}log(...e){this.print("log",...e)}}const A=new re("SDK",{bgColor:"forestgreen",textColor:"white"});let S=!1;const L=({name:t,payload:e})=>{A.log("Event received:",e?{name:t,payload:e}:{name:t})};function oe(t){S!==t&&(S=t,t?U(L):m(L))}function ie(...t){S&&A.log(...t)}class W{constructor(){P(this,"listeners",new Map);P(this,"listenersCount",0);P(this,"subscribeListeners",[])}clear(){this.listeners.clear(),this.subscribeListeners=[]}get count(){return this.listenersCount+this.subscribeListeners.length}emit(e,...n){this.subscribeListeners.forEach(o=>o({event:e,args:n})),(this.listeners.get(e)||[]).forEach(([o,s])=>{o(...n),s&&this.off(e,o)})}on(e,n,r){let o=this.listeners.get(e);return o||this.listeners.set(e,o=[]),o.push([n,r]),this.listenersCount+=1,()=>this.off(e,n)}off(e,n){const r=this.listeners.get(e)||[];for(let o=0;o<r.length;o+=1)if(n===r[o][0]){r.splice(o,1),this.listenersCount-=1;return}}subscribe(e){return this.subscribeListeners.push(e),()=>this.unsubscribe(e)}unsubscribe(e){for(let n=0;n<this.subscribeListeners.length;n+=1)if(this.subscribeListeners[n]===e){this.subscribeListeners.splice(n,1);return}}}function C(t,e,n){return window.addEventListener(t,e,n),()=>window.removeEventListener(t,e,n)}function $(...t){let e=!1;const n=[...t];return[r=>!e&&n.push(r),()=>{e||(e=!0,n.forEach(r=>r()))},e]}class E extends Error{constructor(e,n,r){super(n,{cause:r}),this.type=e,Object.setPrototypeOf(this,E.prototype)}}function d(t,e,n){return new E(t,e,n)}const V="ERR_METHOD_UNSUPPORTED",k="ERR_METHOD_PARAMETER_UNSUPPORTED",q="ERR_UNKNOWN_ENV",G="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",H="ERR_TIMED_OUT",j="ERR_UNEXPECTED_TYPE",N="ERR_PARSE",se="ERR_NAVIGATION_LIST_EMPTY",ae="ERR_NAVIGATION_CURSOR_INVALID",ce="ERR_NAVIGATION_ITEM_INVALID",ue="ERR_SSR_INIT",pe="ERR_INVALID_PATH_BASE";function w(){return d(j,"Value has unexpected type")}class v{constructor(e,n,r){this.parser=e,this.isOptional=n,this.type=r}parse(e){if(!(this.isOptional&&e===void 0))try{return this.parser(e)}catch(n){throw d(N,`Unable to parse value${this.type?` as ${this.type}`:""}`,n)}}optional(){return this.isOptional=!0,this}}function h(t,e){return()=>new v(t,!1,e)}const b=h(t=>{if(typeof t=="boolean")return t;const e=String(t);if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw w()},"boolean");function B(t,e){const n={};for(const r in t){const o=t[r];if(!o)continue;let s,u;if(typeof o=="function"||"parse"in o)s=r,u=typeof o=="function"?o:o.parse.bind(o);else{const{type:c}=o;s=o.from||r,u=typeof c=="function"?c:c.parse.bind(c)}try{const c=u(e(s));c!==void 0&&(n[r]=c)}catch(c){throw d(N,`Unable to parse field "${r}"`,c)}}return n}function I(t){let e=t;if(typeof e=="string"&&(e=JSON.parse(e)),typeof e!="object"||e===null||Array.isArray(e))throw w();return e}function _(t,e){return new v(n=>{const r=I(n);return B(t,o=>r[o])},!1,e)}const g=h(t=>{if(typeof t=="number")return t;if(typeof t=="string"){const e=Number(t);if(!Number.isNaN(e))return e}throw w()},"number");function _e(t){return/^#[\da-f]{6}$/i.test(t)}function fe(t){return/^#[\da-f]{3}$/i.test(t)}function le(t){const e=t.replace(/\s/g,"").toLowerCase();if(_e(e))return e;if(fe(e)){let r="#";for(let o=0;o<3;o+=1)r+=e[1+o].repeat(2);return r}const n=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(!n)throw new Error(`Value "${t}" does not satisfy any of known RGB formats.`);return n.slice(1).reduce((r,o)=>{const s=parseInt(o,10).toString(16);return r+(s.length===1?"0":"")+s},"#")}const a=h(t=>{if(typeof t=="string"||typeof t=="number")return t.toString();throw w()},"string"),K=h(t=>le(a().parse(t)),"rgb");function me(t){return _({eventType:a(),eventData:e=>e}).parse(t)}function de(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(t=>{delete window[t]})}function be(t,e){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:t,eventData:e}),source:window.parent}))}function he(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(t=>{let e=window;t.forEach((n,r,o)=>{if(r===o.length-1){e[n]=be;return}n in e||(e[n]={}),e=e[n]})})}const ge={clipboard_text_received:_({req_id:a(),data:t=>t===null?t:a().optional().parse(t)}),custom_method_invoked:_({req_id:a(),result:t=>t,error:a().optional()}),invoice_closed:_({slug:a(),status:a()}),phone_requested:_({status:a()}),popup_closed:{parse(t){return _({button_id:e=>e==null?void 0:a().parse(e)}).parse(t??{})}},qr_text_received:_({data:a().optional()}),theme_changed:_({theme_params:t=>{const e=K().optional();return Object.entries(I(t)).reduce((n,[r,o])=>(n[r]=e.parse(o),n),{})}}),viewport_changed:_({height:g(),width:t=>t==null?window.innerWidth:g().parse(t),is_state_stable:b(),is_expanded:b()}),write_access_requested:_({status:a()})};function Ee(){const t=new W,e=new W;e.subscribe(r=>{t.emit("event",{name:r.event,payload:r.args[0]})}),he();const[,n]=$(de,C("resize",()=>{e.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),C("message",r=>{if(r.source!==window.parent)return;let o;try{o=me(r.data)}catch{return}const{eventType:s,eventData:u}=o,c=ge[s];try{const p=c?c.parse(u):u;e.emit(...p?[s,p]:[s])}catch(p){A.error(`An error occurred processing the "${s}" event from the Telegram application. Please, file an issue here: https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,o,p)}}),()=>t.clear(),()=>e.clear());return[{on:e.on.bind(e),off:e.off.bind(e),subscribe(r){return t.on("event",r)},unsubscribe(r){t.off("event",r)},get count(){return e.count+t.count}},n]}const[we,ye]=l(t=>{const[e,n]=Ee(),r=e.off.bind(e);return e.off=(o,s)=>{const{count:u}=e;r(o,s),u&&!e.count&&t()},[e,n]},([,t])=>t());function R(){return we()[0]}function Re(t,e){R().off(t,e)}function T(t,e,n){return R().on(t,e,n)}function D(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Te(t,e){const n=t.split("."),r=e.split("."),o=Math.max(n.length,r.length);for(let s=0;s<o;s+=1){const u=parseInt(n[s]||"0",10),c=parseInt(r[s]||"0",10);if(u!==c)return u>c?1:-1}return 0}function f(t,e){return Te(t,e)<=0}function O(t,e,n){if(typeof n=="string"){if(t==="web_app_open_link"){if(e==="try_instant_view")return f("6.4",n);if(e==="try_browser")return f("7.6",n)}if(t==="web_app_set_header_color"&&e==="color")return f("6.9",n);if(t==="web_app_close"&&e==="return_back")return f("7.6",n)}switch(t){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 f("6.1",e);case"web_app_open_popup":return f("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 f("6.4",e);case"web_app_switch_inline_query":return f("6.7",e);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return f("6.9",e);case"web_app_setup_settings_button":return f("6.10",e);case"web_app_biometry_get_info":case"web_app_biometry_open_settings":case"web_app_biometry_request_access":case"web_app_biometry_request_auth":case"web_app_biometry_update_token":return f("7.2",e);default:return["iframe_ready","iframe_will_reload","web_app_close","web_app_data_send","web_app_expand","web_app_open_link","web_app_ready","web_app_request_theme","web_app_request_viewport","web_app_setup_main_button","web_app_setup_closing_behavior"].includes(t)}}function Pe(t){return"external"in t&&D(t.external)&&"notify"in t.external&&typeof t.external.notify=="function"}function Y(t){return"TelegramWebviewProxy"in t&&D(t.TelegramWebviewProxy)&&"postEvent"in t.TelegramWebviewProxy&&typeof t.TelegramWebviewProxy.postEvent=="function"}function J(){try{return window.self!==window.top}catch{return!0}}let F="https://web.telegram.org";function Ae(t){F=t}function X(){return F}function y(t,e,n){let r={},o;e===void 0&&n===void 0?r={}:e!==void 0&&n!==void 0?(r=n,o=e):e!==void 0&&("targetOrigin"in e?r=e:o=e);const{targetOrigin:s=X()}=r;if(ie("Posting event:",o?{event:t,data:o}:{event:t}),J()){window.parent.postMessage(JSON.stringify({eventType:t,eventData:o}),s);return}if(Pe(window)){window.external.notify(JSON.stringify({eventType:t,eventData:o}));return}if(Y(window)){window.TelegramWebviewProxy.postEvent(t,JSON.stringify(o));return}throw d(q,"Unable to determine current environment and possible way to send event. You are probably trying to use Mini Apps method outside of Telegram application environment.")}function Se(t){return(e,n)=>{if(!O(e,t))throw d(V,`Method "${e}" is unsupported in Mini Apps version ${t}`);if(D(n)){let r;if(e==="web_app_open_link"&&"try_instant_view"in n?r="try_instant_view":e==="web_app_set_header_color"&&"color"in n&&(r="color"),r&&!O(e,r,t))throw d(k,`Parameter "${r}" of "${e}" method is unsupported in Mini Apps version ${t}`)}return y(e,n)}}function z(t){return({req_id:e})=>e===t}function Ne(t){return d(H,`Timeout reached: ${t}ms`)}function ve(t,e){return Promise.race([typeof t=="function"?t():t,new Promise((n,r)=>{setTimeout(()=>{r(Ne(e))},e)})])}async function M(t){let e;const n=new Promise(c=>{e=c}),{event:r,capture:o,timeout:s}=t,[,u]=$(...(Array.isArray(r)?r:[r]).map(c=>T(c,p=>(!o||o(p))&&e(p))));try{return(t.postEvent||y)(t.method,t.params),await(s?ve(n,s):n)}finally{u()}}async function Ie(t,e,n,r={}){const{result:o,error:s}=await M({...r,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:t,params:e,req_id:n},capture:z(n)});if(s)throw d(G,s);return o}async function De(){if(Y(window))return!0;try{return await M({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function Z(t){return t instanceof E}function Oe(t,e){return Z(t)&&t.type===e}function Me(t=!0){const e=[T("reload_iframe",()=>{y("iframe_will_reload"),window.location.reload()})],n=()=>e.forEach(r=>r());if(t){const r=document.createElement("style");r.id="telegram-custom-styles",document.head.appendChild(r),e.push(T("set_custom_style",o=>{r.innerHTML=o}),()=>document.head.removeChild(r))}return y("iframe_ready",{reload_supported:!0}),n}const Ue=h(t=>t instanceof Date?t:new Date(g().parse(t)*1e3),"Date");function Q(t,e){return new v(n=>{if(typeof n!="string"&&!(n instanceof URLSearchParams))throw w();const r=typeof n=="string"?new URLSearchParams(n):n;return B(t,o=>{const s=r.get(o);return s===null?void 0:s})},!1,e)}const Le=_({id:g(),type:a(),title:a(),photoUrl:{type:a().optional(),from:"photo_url"},username:a().optional()},"Chat").optional(),x=_({addedToAttachmentMenu:{type:b().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:b().optional(),from:"allows_write_to_pm"},firstName:{type:a(),from:"first_name"},id:g(),isBot:{type:b().optional(),from:"is_bot"},isPremium:{type:b().optional(),from:"is_premium"},languageCode:{type:a().optional(),from:"language_code"},lastName:{type:a().optional(),from:"last_name"},photoUrl:{type:a().optional(),from:"photo_url"},username:a().optional()},"User").optional();function We(){return Q({authDate:{type:Ue(),from:"auth_date"},canSendAfter:{type:g().optional(),from:"can_send_after"},chat:Le,chatInstance:{type:a().optional(),from:"chat_instance"},chatType:{type:a().optional(),from:"chat_type"},hash:a(),queryId:{type:a().optional(),from:"query_id"},receiver:x,startParam:{type:a().optional(),from:"start_param"},user:x},"InitData")}function Ce(t){return t.replace(/_[a-z]/g,e=>e[1].toUpperCase())}function $e(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}const Ve=h(t=>{const e=K().optional();return Object.entries(I(t)).reduce((n,[r,o])=>(n[Ce(r)]=e.parse(o),n),{})},"ThemeParams");function ee(t){return Q({botInline:{type:b().optional(),from:"tgWebAppBotInline"},initData:{type:We().optional(),from:"tgWebAppData"},initDataRaw:{type:a().optional(),from:"tgWebAppData"},platform:{type:a(),from:"tgWebAppPlatform"},showSettings:{type:b().optional(),from:"tgWebAppShowSettings"},startParam:{type:a().optional(),from:"tgWebAppStartParam"},themeParams:{type:Ve(),from:"tgWebAppThemeParams"},version:{type:a(),from:"tgWebAppVersion"}}).parse(t)}function te(t){return ee(t.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function ke(){return te(window.location.href)}function qe(){return performance.getEntriesByType("navigation")[0]}function Ge(){const t=qe();if(!t)throw new Error("Unable to get first navigation entry.");return te(t.name)}function ne(t){return`tma.js/${t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`}function He(t,e){sessionStorage.setItem(ne(t),JSON.stringify(e))}function je(t){const e=sessionStorage.getItem(ne(t));try{return e?JSON.parse(e):void 0}catch{}}function Be(){return ee(je("launchParams")||"")}function Ke(t){return JSON.stringify(Object.fromEntries(Object.entries(t).map(([e,n])=>[$e(e),n])))}function Ye(t){const{initDataRaw:e,themeParams:n,platform:r,version:o,showSettings:s,startParam:u,botInline:c}=t,p=new URLSearchParams;return p.set("tgWebAppPlatform",r),p.set("tgWebAppThemeParams",Ke(n)),p.set("tgWebAppVersion",o),e&&p.set("tgWebAppData",e),u&&p.set("tgWebAppStartParam",u),typeof s=="boolean"&&p.set("tgWebAppShowSettings",s?"1":"0"),typeof c=="boolean"&&p.set("tgWebAppBotInline",c?"1":"0"),p.toString()}function Je(t){He("launchParams",Ye(t))}function Fe(){for(const t of[ke,Ge,Be])try{const e=t();return Je(e),e}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}return i.ERR_INVALID_PATH_BASE=pe,i.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=G,i.ERR_METHOD_PARAMETER_UNSUPPORTED=k,i.ERR_METHOD_UNSUPPORTED=V,i.ERR_NAVIGATION_HISTORY_EMPTY=se,i.ERR_NAVIGATION_INDEX_INVALID=ae,i.ERR_NAVIGATION_ITEM_INVALID=ce,i.ERR_PARSE=N,i.ERR_SSR_INIT=ue,i.ERR_TIMED_OUT=H,i.ERR_UNEXPECTED_TYPE=j,i.ERR_UNKNOWN_ENV=q,i.SDKError=E,i.captureSameReq=z,i.createPostEvent=Se,i.initWeb=Me,i.invokeCustomMethod=Ie,i.isIframe=J,i.isSDKError=Z,i.isSDKErrorOfType=Oe,i.isTMA=De,i.off=Re,i.on=T,i.postEvent=y,i.request=M,i.retrieveLaunchParams=Fe,i.setDebug=oe,i.setTargetOrigin=Ae,i.subscribe=U,i.supports=O,i.targetOrigin=X,i.unsubscribe=m,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}),i}({});
1
+ var Xe=Object.defineProperty;var ze=(i,f,l)=>f in i?Xe(i,f,{enumerable:!0,configurable:!0,writable:!0,value:l}):i[f]=l;var A=(i,f,l)=>ze(i,typeof f!="symbol"?f+"":f,l);this.tmajs=this.tmajs||{};this.tmajs.sdk=function(i){"use strict";function f(t,e){let r;const n=()=>{r!==void 0&&e&&e(r),r=void 0};return[()=>r===void 0?r=t(n):r,n]}function l(t){const e=R(),{count:r}=e;e.unsubscribe(t),r&&!e.count&&de()}function M(t){return R().subscribe(t),()=>l(t)}class re{constructor(e,r={}){this.scope=e,this.options=r}print(e,...r){const n=new Date,o=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n),{textColor:s,bgColor:u}=this.options,a="font-weight: bold;padding: 0 5px;border-radius:5px";console[e](`%c${o}%c / %c${this.scope}`,`${a};background-color: lightblue;color:black`,"",`${a};${s?`color:${s};`:""}${u?`background-color:${u}`:""}`,...r)}error(...e){this.print("error",...e)}log(...e){this.print("log",...e)}}const P=new re("SDK",{bgColor:"forestgreen",textColor:"white"});let I=!1;const U=({name:t,payload:e})=>{P.log("Event received:",e?{name:t,payload:e}:{name:t})};function ne(t){I!==t&&(I=t,t?M(U):l(U))}function oe(...t){I&&P.log(...t)}class L{constructor(){A(this,"listeners",new Map);A(this,"listenersCount",0);A(this,"subscribeListeners",[])}clear(){this.listeners.clear(),this.subscribeListeners=[]}get count(){return this.listenersCount+this.subscribeListeners.length}emit(e,...r){this.subscribeListeners.forEach(o=>o({event:e,args:r})),(this.listeners.get(e)||[]).forEach(([o,s])=>{o(...r),s&&this.off(e,o)})}on(e,r,n){let o=this.listeners.get(e);return o||this.listeners.set(e,o=[]),o.push([r,n]),this.listenersCount+=1,()=>this.off(e,r)}off(e,r){const n=this.listeners.get(e)||[];for(let o=0;o<n.length;o+=1)if(r===n[o][0]){n.splice(o,1),this.listenersCount-=1;return}}subscribe(e){return this.subscribeListeners.push(e),()=>this.unsubscribe(e)}unsubscribe(e){for(let r=0;r<this.subscribeListeners.length;r+=1)if(this.subscribeListeners[r]===e){this.subscribeListeners.splice(r,1);return}}}function W(t,e,r){return window.addEventListener(t,e,r),()=>window.removeEventListener(t,e,r)}function C(...t){let e=!1;const r=t.flat(1);return[n=>!e&&r.push(n),()=>{e||(e=!0,r.forEach(n=>n()))},e]}class E extends Error{constructor(e,r,n){super(r,{cause:n}),this.type=e,Object.setPrototypeOf(this,E.prototype)}}function m(t,e,r){return new E(t,e,r)}const V="ERR_METHOD_UNSUPPORTED",$="ERR_METHOD_PARAMETER_UNSUPPORTED",G="ERR_UNKNOWN_ENV",k="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",q="ERR_TIMED_OUT",H="ERR_UNEXPECTED_TYPE",N="ERR_PARSE",ie="ERR_NAVIGATION_LIST_EMPTY",se="ERR_NAVIGATION_CURSOR_INVALID",ae="ERR_NAVIGATION_ITEM_INVALID",ce="ERR_SSR_INIT",ue="ERR_INVALID_PATH_BASE";function w(){return m(H,"Value has unexpected type")}class S{constructor(e,r,n){this.parser=e,this.isOptional=r,this.type=n}parse(e){if(!(this.isOptional&&e===void 0))try{return this.parser(e)}catch(r){throw m(N,`Unable to parse value${this.type?` as ${this.type}`:""}`,r)}}optional(){return this.isOptional=!0,this}}function d(t,e){return()=>new S(t,!1,e)}const b=d(t=>{if(typeof t=="boolean")return t;const e=String(t);if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1;throw w()},"boolean");function j(t,e){const r={};for(const n in t){const o=t[n];if(!o)continue;let s,u;if(typeof o=="function"||"parse"in o)s=n,u=typeof o=="function"?o:o.parse.bind(o);else{const{type:a}=o;s=o.from||n,u=typeof a=="function"?a:a.parse.bind(a)}try{const a=u(e(s));a!==void 0&&(r[n]=a)}catch(a){throw m(N,`Unable to parse field "${n}"`,a)}}return r}function B(t){let e=t;if(typeof e=="string"&&(e=JSON.parse(e)),typeof e!="object"||e===null||Array.isArray(e))throw w();return e}function h(t,e){return new S(r=>{const n=B(r);return j(t,o=>n[o])},!1,e)}const g=d(t=>{if(typeof t=="number")return t;if(typeof t=="string"){const e=Number(t);if(!Number.isNaN(e))return e}throw w()},"number"),c=d(t=>{if(typeof t=="string"||typeof t=="number")return t.toString();throw w()},"string");function pe(t){return h({eventType:c(),eventData:e=>e}).parse(t)}function _e(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(t=>{delete window[t]})}function fe(t,e){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:t,eventData:e}),source:window.parent}))}function le(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(t=>{let e=window;t.forEach((r,n,o)=>{if(n===o.length-1){e[r]=fe;return}r in e||(e[r]={}),e=e[r]})})}const me={clipboard_text_received:h({req_id:c(),data:t=>t===null?t:c().optional().parse(t)}),custom_method_invoked:h({req_id:c(),result:t=>t,error:c().optional()}),popup_closed:{parse(t){return h({button_id:e=>e==null?void 0:c().parse(e)}).parse(t??{})}},viewport_changed:h({height:g(),width:t=>t==null?window.innerWidth:g().parse(t),is_state_stable:b(),is_expanded:b()})};function be(){const t=new L,e=new L;e.subscribe(n=>{t.emit("event",{name:n.event,payload:n.args[0]})}),le();const[,r]=C(_e,W("resize",()=>{e.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),W("message",n=>{if(n.source!==window.parent)return;let o;try{o=pe(n.data)}catch{return}const{eventType:s,eventData:u}=o,a=me[s];try{const p=a?a.parse(u):u;e.emit(...p?[s,p]:[s])}catch(p){P.error(`An error occurred processing the "${s}" event from the Telegram application.
2
+ Please, file an issue here:
3
+ https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,o,p)}}),()=>t.clear(),()=>e.clear());return[{on:e.on.bind(e),off:e.off.bind(e),subscribe(n){return t.on("event",n)},unsubscribe(n){t.off("event",n)},get count(){return e.count+t.count}},r]}const[he,de]=f(t=>{const[e,r]=be(),n=e.off.bind(e);return e.off=(o,s)=>{const{count:u}=e;n(o,s),u&&!e.count&&t()},[e,r]},([,t])=>t());function R(){return he()[0]}function ge(t,e){R().off(t,e)}function T(t,e,r){return R().on(t,e,r)}function v(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ee(t,e){const r=t.split("."),n=e.split("."),o=Math.max(r.length,n.length);for(let s=0;s<o;s+=1){const u=parseInt(r[s]||"0",10),a=parseInt(n[s]||"0",10);if(u!==a)return u>a?1:-1}return 0}function _(t,e){return Ee(t,e)<=0}function D(t,e,r){if(typeof r=="string"){if(t==="web_app_open_link"){if(e==="try_instant_view")return _("6.4",r);if(e==="try_browser")return _("7.6",r)}if(t==="web_app_set_header_color"&&e==="color")return _("6.9",r);if(t==="web_app_close"&&e==="return_back")return _("7.6",r)}switch(t){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 _("6.1",e);case"web_app_open_popup":return _("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 _("6.4",e);case"web_app_switch_inline_query":return _("6.7",e);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return _("6.9",e);case"web_app_setup_settings_button":return _("6.10",e);case"web_app_biometry_get_info":case"web_app_biometry_open_settings":case"web_app_biometry_request_access":case"web_app_biometry_request_auth":case"web_app_biometry_update_token":return _("7.2",e);default:return["iframe_ready","iframe_will_reload","web_app_close","web_app_data_send","web_app_expand","web_app_open_link","web_app_ready","web_app_request_theme","web_app_request_viewport","web_app_setup_main_button","web_app_setup_closing_behavior"].includes(t)}}function we(t){return"external"in t&&v(t.external)&&"notify"in t.external&&typeof t.external.notify=="function"}function K(t){return"TelegramWebviewProxy"in t&&v(t.TelegramWebviewProxy)&&"postEvent"in t.TelegramWebviewProxy&&typeof t.TelegramWebviewProxy.postEvent=="function"}function Y(){try{return window.self!==window.top}catch{return!0}}let J="https://web.telegram.org";function ye(t){J=t}function F(){return J}function y(t,e,r){let n={},o;if(!e&&!r?n={}:e&&r?(n=r,o=e):e&&("targetOrigin"in e?n=e:o=e),oe("Posting event:",o?{event:t,data:o}:{event:t}),Y())return window.parent.postMessage(JSON.stringify({eventType:t,eventData:o}),n.targetOrigin||F());if(we(window)){window.external.notify(JSON.stringify({eventType:t,eventData:o}));return}if(K(window)){window.TelegramWebviewProxy.postEvent(t,JSON.stringify(o));return}throw m(G,"Unable to determine current environment and possible way to send event. You are probably trying to use Mini Apps method outside the Telegram application environment.")}function Re(t){return(e,r)=>{if(!D(e,t))throw m(V,`Method "${e}" is unsupported in Mini Apps version ${t}`);if(v(r)&&e==="web_app_set_header_color"&&"color"in r&&!D(e,"color",t))throw m($,`Parameter "color" of "${e}" method is unsupported in Mini Apps version ${t}`);return y(e,r)}}function X(t){return({req_id:e})=>e===t}function Te(t){return m(q,`Timeout reached: ${t}ms`)}function Ae(t,e){return Promise.race([typeof t=="function"?t():t,new Promise((r,n)=>{setTimeout(()=>{n(Te(e))},e)})])}async function O(t){let e;const r=new Promise(a=>e=a),{event:n,capture:o,timeout:s}=t,[,u]=C((Array.isArray(n)?n:[n]).map(a=>T(a,p=>{(!o||(Array.isArray(n)?o({event:a,payload:p}):o(p)))&&e(p)})));try{return(t.postEvent||y)(t.method,t.params),await(s?Ae(r,s):r)}finally{u()}}async function Pe(t,e,r,n={}){const{result:o,error:s}=await O({...n,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:t,params:e,req_id:r},capture:X(r)});if(s)throw m(k,s);return o}async function Ie(){if(K(window))return!0;try{return await O({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function z(t){return t instanceof E}function Ne(t,e){return z(t)&&t.type===e}function Se(t=!0){const e=[T("reload_iframe",()=>{y("iframe_will_reload"),window.location.reload()})],r=()=>e.forEach(n=>n());if(t){const n=document.createElement("style");n.id="telegram-custom-styles",document.head.appendChild(n),e.push(T("set_custom_style",o=>{n.innerHTML=o}),()=>document.head.removeChild(n))}return y("iframe_ready",{reload_supported:!0}),r}const ve=d(t=>t instanceof Date?t:new Date(g().parse(t)*1e3),"Date");function Z(t,e){return new S(r=>{if(typeof r!="string"&&!(r instanceof URLSearchParams))throw w();const n=typeof r=="string"?new URLSearchParams(r):r;return j(t,o=>{const s=n.get(o);return s===null?void 0:s})},!1,e)}const De=h({id:g(),type:c(),title:c(),photoUrl:{type:c().optional(),from:"photo_url"},username:c().optional()},"Chat").optional(),Q=h({addedToAttachmentMenu:{type:b().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:b().optional(),from:"allows_write_to_pm"},firstName:{type:c(),from:"first_name"},id:g(),isBot:{type:b().optional(),from:"is_bot"},isPremium:{type:b().optional(),from:"is_premium"},languageCode:{type:c().optional(),from:"language_code"},lastName:{type:c().optional(),from:"last_name"},photoUrl:{type:c().optional(),from:"photo_url"},username:c().optional()},"User").optional();function Oe(){return Z({authDate:{type:ve(),from:"auth_date"},canSendAfter:{type:g().optional(),from:"can_send_after"},chat:De,chatInstance:{type:c().optional(),from:"chat_instance"},chatType:{type:c().optional(),from:"chat_type"},hash:c(),queryId:{type:c().optional(),from:"query_id"},receiver:Q,startParam:{type:c().optional(),from:"start_param"},user:Q},"InitData")}function Me(t){return/^#[\da-f]{6}$/i.test(t)}function Ue(t){return/^#[\da-f]{3}$/i.test(t)}function Le(t){const e=t.replace(/\s/g,"").toLowerCase();if(Me(e))return e;if(Ue(e)){let n="#";for(let o=0;o<3;o+=1)n+=e[1+o].repeat(2);return n}const r=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(!r)throw new Error(`Value "${t}" does not satisfy any of known RGB formats.`);return r.slice(1).reduce((n,o)=>{const s=parseInt(o,10).toString(16);return n+(s.length===1?"0":"")+s},"#")}const We=d(t=>Le(c().parse(t)),"rgb");function Ce(t){return t.replace(/_[a-z]/g,e=>e[1].toUpperCase())}function Ve(t){return t.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`)}const $e=d(t=>{const e=We().optional();return Object.entries(B(t)).reduce((r,[n,o])=>(r[Ce(n)]=e.parse(o),r),{})},"ThemeParams");function x(t){return Z({botInline:{type:b().optional(),from:"tgWebAppBotInline"},initData:{type:Oe().optional(),from:"tgWebAppData"},initDataRaw:{type:c().optional(),from:"tgWebAppData"},platform:{type:c(),from:"tgWebAppPlatform"},showSettings:{type:b().optional(),from:"tgWebAppShowSettings"},startParam:{type:c().optional(),from:"tgWebAppStartParam"},themeParams:{type:$e(),from:"tgWebAppThemeParams"},version:{type:c(),from:"tgWebAppVersion"}}).parse(t)}function ee(t){return x(t.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function Ge(){return ee(window.location.href)}function ke(){return performance.getEntriesByType("navigation")[0]}function qe(){const t=ke();if(!t)throw new Error("Unable to get first navigation entry.");return ee(t.name)}function te(t){return`tma.js/${t.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}`}function He(t,e){sessionStorage.setItem(te(t),JSON.stringify(e))}function je(t){const e=sessionStorage.getItem(te(t));try{return e?JSON.parse(e):void 0}catch{}}function Be(){return x(je("launchParams")||"")}function Ke(t){return JSON.stringify(Object.fromEntries(Object.entries(t).map(([e,r])=>[Ve(e),r])))}function Ye(t){const{initDataRaw:e,themeParams:r,platform:n,version:o,showSettings:s,startParam:u,botInline:a}=t,p=new URLSearchParams;return p.set("tgWebAppPlatform",n),p.set("tgWebAppThemeParams",Ke(r)),p.set("tgWebAppVersion",o),e&&p.set("tgWebAppData",e),u&&p.set("tgWebAppStartParam",u),typeof s=="boolean"&&p.set("tgWebAppShowSettings",s?"1":"0"),typeof a=="boolean"&&p.set("tgWebAppBotInline",a?"1":"0"),p.toString()}function Je(t){He("launchParams",Ye(t))}function Fe(){for(const t of[Ge,qe,Be])try{const e=t();return Je(e),e}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}return i.ERR_INVALID_PATH_BASE=ue,i.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=k,i.ERR_METHOD_PARAMETER_UNSUPPORTED=$,i.ERR_METHOD_UNSUPPORTED=V,i.ERR_NAVIGATION_HISTORY_EMPTY=ie,i.ERR_NAVIGATION_INDEX_INVALID=se,i.ERR_NAVIGATION_ITEM_INVALID=ae,i.ERR_PARSE=N,i.ERR_SSR_INIT=ce,i.ERR_TIMED_OUT=q,i.ERR_UNEXPECTED_TYPE=H,i.ERR_UNKNOWN_ENV=G,i.SDKError=E,i.captureSameReq=X,i.createPostEvent=Re,i.initWeb=Se,i.invokeCustomMethod=Pe,i.isIframe=Y,i.isSDKError=z,i.isSDKErrorOfType=Ne,i.isTMA=Ie,i.off=ge,i.on=T,i.postEvent=y,i.request=O,i.retrieveLaunchParams=Fe,i.setDebug=ne,i.setTargetOrigin=ye,i.subscribe=M,i.supports=D,i.targetOrigin=F,i.unsubscribe=l,Object.defineProperty(i,Symbol.toStringTag,{value:"Module"}),i}({});
2
4
  //# sourceMappingURL=index.low-level.iife.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.low-level.iife.js","sources":["../src/misc/createSingleton.ts","../src/bridge/events/listening/unsubscribe.ts","../src/bridge/events/listening/subscribe.ts","../src/logger/Logger.ts","../src/debug/debug.ts","../src/events/event-emitter/EventEmitter.ts","../src/events/onWindow.ts","../src/misc/createCleanup.ts","../src/errors/SDKError.ts","../src/errors/createError.ts","../src/errors/errors.ts","../src/parsing/createTypeError.ts","../src/parsing/ValueParser/ValueParser.ts","../src/parsing/createValueParserGenerator.ts","../src/parsing/parsers/boolean.ts","../src/parsing/parseBySchema.ts","../src/parsing/toRecord.ts","../src/parsing/parsers/json.ts","../src/parsing/parsers/number.ts","../src/colors/isRGB.ts","../src/colors/isRGBShort.ts","../src/colors/toRGB.ts","../src/parsing/parsers/string.ts","../src/parsing/parsers/rgb.ts","../src/bridge/parseMessage.ts","../src/bridge/events/event-handlers/cleanupEventHandlers.ts","../src/bridge/events/event-handlers/emitMiniAppsEvent.ts","../src/bridge/events/event-handlers/defineEventHandlers.ts","../src/bridge/events/event-emitter/createMiniAppsEventEmitter.ts","../src/bridge/events/event-emitter/singleton.ts","../src/bridge/events/listening/off.ts","../src/bridge/events/listening/on.ts","../src/misc/isRecord.ts","../src/version/compareVersions.ts","../src/supports/supports.ts","../src/env/hasExternalNotify.ts","../src/env/hasWebviewProxy.ts","../src/env/isIframe.ts","../src/bridge/target-origin.ts","../src/bridge/methods/postEvent.ts","../src/bridge/methods/createPostEvent.ts","../src/bridge/utils/captureSameReq.ts","../src/timeout/createTimeoutError.ts","../src/timeout/withTimeout.ts","../src/bridge/utils/request.ts","../src/bridge/utils/invokeCustomMethod.ts","../src/env/isTMA.ts","../src/errors/isSDKError.ts","../src/errors/isSDKErrorOfType.ts","../src/env/initWeb.ts","../src/parsing/parsers/date.ts","../src/parsing/parsers/searchParams.ts","../src/components/InitData/parsers/chat.ts","../src/components/InitData/parsers/user.ts","../src/components/InitData/parsers/initData.ts","../src/components/ThemeParams/keys.ts","../src/components/ThemeParams/parsing/themeParams.ts","../src/launch-params/parseLaunchParams.ts","../src/launch-params/retrieveFromUrl.ts","../src/launch-params/retrieveFromLocation.ts","../src/navigation/getFirstNavigationEntry.ts","../src/launch-params/retrieveFromPerformance.ts","../src/storage/storage.ts","../src/launch-params/retrieveFromStorage.ts","../src/components/ThemeParams/parsing/serializeThemeParams.ts","../src/launch-params/serializeLaunchParams.ts","../src/launch-params/saveToStorage.ts","../src/launch-params/retrieveLaunchParams.ts"],"sourcesContent":["/**\n * Creates resettable singleton. We mostly need it for test purposes.\n * @param create - function which creates singleton entity.\n * @param onReset - function which will be called in case, singleton was reset.\n */\nexport function createSingleton<T>(\n create: (reset: () => void) => T,\n onReset?: (entity: T) => void,\n): [\n /**\n * Returns singleton entity.\n */\n get: () => T,\n /**\n * Resets last stored entity.\n */\n reset: () => void,\n] {\n let cached: T | undefined;\n const reset = () => {\n cached !== undefined && onReset && onReset(cached);\n cached = undefined;\n };\n\n return [() => (cached === undefined ? cached = create(reset) : cached), reset];\n}\n","import { miniAppsEventEmitter, resetMiniAppsEventEmitter } from '../event-emitter/singleton.js';\nimport type { MiniAppsSubscribeListener } from '../types.js';\n\n/**\n * Removes global event listener.\n * @param listener - event listener.\n */\nexport function unsubscribe(listener: MiniAppsSubscribeListener): void {\n const ee = miniAppsEventEmitter();\n const { count } = ee;\n ee.unsubscribe(listener);\n\n // If event emitter now has no listeners, we can make a cleanup.\n if (count && !ee.count) {\n resetMiniAppsEventEmitter();\n }\n}\n","import type { RemoveEventListenerFn } from '@/events/types.js';\n\nimport { miniAppsEventEmitter } from '../event-emitter/singleton.js';\nimport { unsubscribe } from '../listening/unsubscribe.js';\nimport type { MiniAppsSubscribeListener } from '../types.js';\n\n/**\n * Subscribes to all events sent from the native Telegram application.\n * @param listener - event listener to bind.\n * @returns Function to remove bound event listener.\n */\nexport function subscribe(listener: MiniAppsSubscribeListener): RemoveEventListenerFn {\n miniAppsEventEmitter().subscribe(listener);\n return () => unsubscribe(listener);\n}\n","/**\n * Message log level.\n */\nexport type LogLevel = 'log' | 'error';\n\nexport interface LoggerOptions {\n bgColor?: string;\n textColor?: string;\n}\n\nexport class Logger implements Pick<Console, 'log' | 'error'> {\n constructor(\n private readonly scope: string,\n private readonly options: LoggerOptions = {},\n ) {\n }\n\n /**\n * Prints message into a console in case, logger is currently enabled.\n * @param level - log level.\n * @param args - arguments.\n */\n private print(level: LogLevel, ...args: any[]): void {\n const now = new Date();\n const date = Intl\n .DateTimeFormat('en-GB', {\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n fractionalSecondDigits: 3,\n timeZone: 'UTC',\n })\n .format(now);\n\n const { textColor, bgColor } = this.options;\n const commonCss = 'font-weight: bold;padding: 0 5px;border-radius:5px';\n\n console[level](\n `%c${date}%c / %c${this.scope}`,\n `${commonCss};background-color: lightblue;color:black`,\n '',\n `${commonCss};${textColor ? `color:${textColor};` : ''}${bgColor ? `background-color:${bgColor}` : ''}`,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n ...args,\n );\n }\n\n /**\n * Prints error message into a console.\n * @param args\n */\n error(...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n this.print('error', ...args);\n }\n\n /**\n * Prints log message into a console.\n * @param args\n */\n log(...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n this.print('log', ...args);\n }\n}\n","import { subscribe } from '@/bridge/events/listening/subscribe.js';\nimport { unsubscribe } from '@/bridge/events/listening/unsubscribe.js';\nimport { Logger } from '@/logger/Logger.js';\nimport type { MiniAppsSubscribeListener } from '@/bridge/events/types.js';\n\nexport const logger = new Logger('SDK', {\n bgColor: 'forestgreen',\n textColor: 'white',\n});\n\nlet debugEnabled = false;\n\nconst onEvent: MiniAppsSubscribeListener = ({ name, payload }) => {\n logger.log('Event received:', payload ? { name, payload } : { name });\n};\n\n/**\n * Sets new debug mode. Enabling debug mode leads to printing additional messages in the console,\n * related to the processes inside the package.\n * @param enable - should debug be enabled.\n */\nexport function setDebug(enable: boolean): void {\n if (debugEnabled !== enable) {\n debugEnabled = enable;\n enable ? subscribe(onEvent) : unsubscribe(onEvent);\n }\n}\n\n/**\n * Logs info message into the console.\n * @param args - additional arguments.\n */\nexport function log(...args: any[]): void {\n if (debugEnabled) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n logger.log(...args);\n }\n}\n","import type { RemoveEventListenerFn } from '../types.js';\nimport type {\n EmptyEventName,\n EventListener,\n EventName,\n EventParams,\n NonEmptyEventName,\n SubscribeListener,\n} from './types.js';\n\nexport class EventEmitter<Schema> {\n private readonly listeners: Map<\n string,\n [listener: EventListener<any>, once?: boolean][]\n > = new Map();\n\n private listenersCount = 0;\n\n private subscribeListeners: SubscribeListener<Schema>[] = [];\n\n /**\n * Removes all event listeners.\n */\n clear() {\n this.listeners.clear();\n this.subscribeListeners = [];\n }\n\n /**\n * Returns count of bound listeners.\n */\n get count(): number {\n return this.listenersCount + this.subscribeListeners.length;\n }\n\n /**\n * Emits known event which has no parameters.\n * @param event - event name.\n */\n emit<E extends EmptyEventName<Schema>>(event: E): void;\n\n /**\n * Emits known event which has parameters.\n * @param event - event name.\n * @param args - list of event listener arguments.\n */\n emit<E extends NonEmptyEventName<Schema>>(event: E, ...args: EventParams<Schema[E]>): void;\n\n emit(event: EventName<Schema>, ...args: any[]): void {\n this.subscribeListeners.forEach((l) => l({\n event,\n args: args as EventParams<Schema[EventName<Schema>]>,\n }));\n\n const listeners = this.listeners.get(event) || [];\n\n listeners.forEach(([listener, once]) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n listener(...args);\n if (once) {\n this.off(event, listener);\n }\n });\n }\n\n /**\n * Adds new event listener.\n * @param event - event name.\n * @param listener - event listener.\n * @param once - should listener be called only once.\n * @returns Function to remove bound event listener.\n */\n on<E extends EventName<Schema>>(\n event: E,\n listener: EventListener<Schema[E]>,\n once?: boolean,\n ): RemoveEventListenerFn {\n let listeners = this.listeners.get(event);\n if (!listeners) {\n this.listeners.set(event, listeners = []);\n }\n\n listeners.push([listener, once]);\n this.listenersCount += 1;\n\n return () => this.off(event, listener);\n }\n\n /**\n * Removes event listener. In case, specified listener was bound several times, it removes\n * only a single one.\n * @param event - event name.\n * @param listener - event listener.\n */\n off<E extends EventName<Schema>>(event: E, listener: EventListener<Schema[E]>): void {\n const listeners = this.listeners.get(event) || [];\n for (let i = 0; i < listeners.length; i += 1) {\n if (listener === listeners[i][0]) {\n listeners.splice(i, 1);\n this.listenersCount -= 1;\n return;\n }\n }\n }\n\n /**\n * Adds a new event listener for all events.\n * @param listener - event listener.\n * @returns Function to remove event listener.\n */\n subscribe(listener: SubscribeListener<Schema>): RemoveEventListenerFn {\n this.subscribeListeners.push(listener);\n return () => this.unsubscribe(listener);\n }\n\n /**\n * Removes global event listener. In case, specified listener was bound several times, it removes\n * only a single one.\n * @param listener - event listener.\n */\n unsubscribe(listener: SubscribeListener<Schema>): void {\n for (let i = 0; i < this.subscribeListeners.length; i += 1) {\n if (this.subscribeListeners[i] === listener) {\n this.subscribeListeners.splice(i, 1);\n return;\n }\n }\n }\n}\n","import type { RemoveEventListenerFn } from './types.js';\n\n/**\n * Adds new event listener using window.addEventListener.\n * @param type - event name.\n * @param listener - event listener.\n * @param options - listening options.\n * @returns Function to remove event listener.\n */\nexport function onWindow<K extends keyof WindowEventMap>(\n type: K,\n listener: (this: Window, ev: WindowEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions,\n): RemoveEventListenerFn {\n window.addEventListener(type, listener, options);\n return () => window.removeEventListener(type, listener, options);\n}\n","import { CleanupFn } from '@/types/index.js';\n\n/**\n * Returns a tuple, containing function to add cleanup, call cleanup, and flag showing whether\n * cleanup was called. Cleanup will not be performed in case, it was done before.\n */\nexport function createCleanup(...fns: CleanupFn[]): [\n add: (fn: CleanupFn) => void,\n call: () => void,\n cleanedUp: boolean,\n] {\n let called = false;\n const cache: CleanupFn[] = [...fns];\n\n return [\n (fn) => !called && cache.push(fn),\n () => {\n if (!called) {\n called = true;\n cache.forEach(clean => clean());\n }\n },\n called,\n ];\n}","import type { ErrorType } from './errors.js';\n\n/**\n * Error used across the SDK.\n */\nexport class SDKError extends Error {\n constructor(public readonly type: ErrorType, message?: string, cause?: unknown) {\n super(message, { cause });\n Object.setPrototypeOf(this, SDKError.prototype);\n }\n}\n","import { SDKError } from './SDKError.js';\nimport type { ErrorType } from './errors.js';\n\n/**\n * Creates new error using specified type and message.\n * @param type - error code.\n * @param message - error message.\n * @param cause - original error.\n */\nexport function createError(type: ErrorType, message: string, cause?: unknown): SDKError {\n return new SDKError(type, message, cause);\n}\n","/**\n * Specified Mini Apps method is unsupported.\n */\nexport const ERR_METHOD_UNSUPPORTED = 'ERR_METHOD_UNSUPPORTED';\n\n/**\n * Specified Mini Apps method parameter is unsupported.\n */\nexport const ERR_METHOD_PARAMETER_UNSUPPORTED = 'ERR_METHOD_PARAMETER_UNSUPPORTED';\n\n/**\n * Current environment is not Telegram application.\n */\nexport const ERR_UNKNOWN_ENV = 'ERR_UNKNOWN_ENV';\n\n/**\n * Telegram application returned and error while invoking custom method.\n */\nexport const ERR_INVOKE_CUSTOM_METHOD_RESPONSE = 'ERR_INVOKE_CUSTOM_METHOD_RESPONSE';\n\n/**\n * Timeout reached.\n */\nexport const ERR_TIMED_OUT = 'ERR_TIMED_OUT';\n\n/**\n * Value has unexpected type.\n */\nexport const ERR_UNEXPECTED_TYPE = 'ERR_UNEXPECTED_TYPE';\n\n/**\n * Something went wrong during value parsing.\n */\nexport const ERR_PARSE = 'ERR_PARSE';\n\n/**\n * Navigation entries list is empty.\n */\nexport const ERR_NAVIGATION_HISTORY_EMPTY = 'ERR_NAVIGATION_LIST_EMPTY';\n\n/**\n * Navigation entries cursor is invalid.\n */\nexport const ERR_NAVIGATION_INDEX_INVALID = 'ERR_NAVIGATION_CURSOR_INVALID';\n\n/**\n * Navigation entries item is invalid.\n */\nexport const ERR_NAVIGATION_ITEM_INVALID = 'ERR_NAVIGATION_ITEM_INVALID';\n\n/**\n * SSR component initialization failed.\n */\nexport const ERR_SSR_INIT = 'ERR_SSR_INIT';\n\n/**\n * Path starts from the invalid base.\n */\nexport const ERR_INVALID_PATH_BASE = 'ERR_INVALID_PATH_BASE';\n\nexport type ErrorType =\n | typeof ERR_METHOD_UNSUPPORTED\n | typeof ERR_METHOD_PARAMETER_UNSUPPORTED\n | typeof ERR_UNKNOWN_ENV\n | typeof ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n | typeof ERR_TIMED_OUT\n | typeof ERR_PARSE\n | typeof ERR_UNEXPECTED_TYPE\n | typeof ERR_NAVIGATION_HISTORY_EMPTY\n | typeof ERR_NAVIGATION_INDEX_INVALID\n | typeof ERR_NAVIGATION_ITEM_INVALID\n | typeof ERR_SSR_INIT\n | typeof ERR_INVALID_PATH_BASE;\n","import { createError } from '@/errors/createError.js';\nimport { ERR_UNEXPECTED_TYPE } from '@/errors/errors.js';\nimport type { SDKError } from '@/errors/SDKError.js';\n\n/**\n * Creates instance of TypeError stating, that value has unexpected type.\n */\nexport function createTypeError(): SDKError {\n return createError(ERR_UNEXPECTED_TYPE, 'Value has unexpected type');\n}\n","import { createError } from '@/errors/createError.js';\nimport { ERR_PARSE } from '@/errors/errors.js';\n\nimport type { Parser } from '../types.js';\nimport type { ValueParserOptionalResult, ValueParserParseResult } from './types.js';\n\nexport class ValueParser<ResultType, IsOptional extends boolean> {\n constructor(\n protected parser: Parser<ResultType>,\n protected isOptional: IsOptional,\n protected type?: string,\n ) {\n }\n\n /**\n * Attempts to parse passed value\n * @param value - value to parse.\n * @throws {SDKError} ERR_PARSE\n * @see ERR_PARSE\n */\n parse(value: unknown): ValueParserParseResult<ResultType, IsOptional> {\n // In case, parsing result is specified as optional, and passed value is considered as empty,\n // we can return undefined. Otherwise, pass to parser.\n if (this.isOptional && value === undefined) {\n return undefined as ValueParserParseResult<ResultType, IsOptional>;\n }\n\n try {\n return this.parser(value) as ValueParserParseResult<ResultType, IsOptional>;\n } catch (cause) {\n throw createError(\n ERR_PARSE,\n `Unable to parse value${this.type ? ` as ${this.type}` : ''}`,\n cause,\n );\n }\n }\n\n optional(): ValueParserOptionalResult<this, ResultType> {\n this.isOptional = true as IsOptional;\n return this as ValueParserOptionalResult<this, ResultType>;\n }\n}\n","import { ValueParser } from './ValueParser/ValueParser.js';\nimport type { Parser } from './types.js';\n\nexport type ValueParserGenerator<T> = () => ValueParser<T, false>;\n\n/**\n * Creates function which generates new scalar value parser based on the specified one.\n * @param parser - parser to use as basic.\n * @param type - type name.\n */\nexport function createValueParserGenerator<T>(\n parser: Parser<T>,\n type?: string,\n): ValueParserGenerator<T> {\n return () => new ValueParser(parser, false, type);\n}\n","import { createTypeError } from '../createTypeError.js';\nimport { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as boolean.\n */\nexport const boolean: ValueParserGenerator<boolean> = createValueParserGenerator((value) => {\n if (typeof value === 'boolean') {\n return value;\n }\n const asString = String(value);\n\n if (asString === '1' || asString === 'true') {\n return true;\n }\n\n if (asString === '0' || asString === 'false') {\n return false;\n }\n\n throw createTypeError();\n}, 'boolean');\n","import { createError } from '@/errors/createError.js';\nimport { ERR_PARSE } from '@/errors/errors.js';\n\nimport type { Parser, Schema } from './types.js';\n\n/**\n * Parses external value by specified schema. Functions iterates over each schema field\n * and uses getField function to get its value from the external source.\n * @param schema - object schema.\n * @param getField - function which gets external value by its field name.\n */\nexport function parseBySchema<T>(\n schema: Schema<T>,\n getField: (field: string) => unknown,\n): T {\n const result = {} as T;\n\n for (const field in schema) {\n const definition = schema[field];\n if (!definition) {\n continue;\n }\n\n let from: string;\n let parser: Parser<any>;\n\n // In case, definition has \"type\" property, then SchemaFieldDetailed was passed.\n if (typeof definition === 'function' || 'parse' in definition) {\n // Otherwise we are working with either parser function or instance.\n from = field;\n parser = typeof definition === 'function' ? definition : definition.parse.bind(definition);\n } else {\n const { type: definitionType } = definition;\n\n from = definition.from || field;\n parser = typeof definitionType === 'function'\n ? definitionType\n : definitionType.parse.bind(definitionType);\n }\n\n try {\n const parsedValue = parser(getField(from));\n if (parsedValue !== undefined) {\n (result as any)[field] = parsedValue;\n }\n } catch (error) {\n throw createError(ERR_PARSE, `Unable to parse field \"${field}\"`, error);\n }\n }\n\n return result;\n}\n","import { createTypeError } from './createTypeError.js';\n\n/**\n * Converts value to record.\n * @param value - value to convert.\n * @throws {Error} Value passed as a string does not represent JSON object.\n * @throws {Error} Value is not convertable.\n */\nexport function toRecord(value: unknown): Record<string, unknown> {\n let formattedValue: any = value;\n\n // Convert value to JSON in case, it is string. We expect value to be JSON string.\n if (typeof formattedValue === 'string') {\n formattedValue = JSON.parse(formattedValue);\n }\n\n // We expect json to be usual object.\n if (\n typeof formattedValue !== 'object'\n || formattedValue === null\n || Array.isArray(formattedValue)\n ) {\n throw createTypeError();\n }\n\n return formattedValue as Record<string, unknown>;\n}\n","import { parseBySchema } from '../parseBySchema.js';\nimport { toRecord } from '../toRecord.js';\nimport { ValueParser } from '../ValueParser/ValueParser.js';\nimport type { Schema } from '../types.js';\n\n/**\n * Creates new Json parser according to passed schema.\n * @param schema - object schema.\n * @param type - parser type name.\n */\nexport function json<T>(schema: Schema<T>, type?: string): ValueParser<T, false> {\n return new ValueParser((value) => {\n const record = toRecord(value);\n return parseBySchema(schema, (field) => record[field]);\n }, false, type);\n}\n","import { createTypeError } from '../createTypeError.js';\nimport { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as number.\n */\nexport const number: ValueParserGenerator<number> = createValueParserGenerator((value) => {\n if (typeof value === 'number') {\n return value;\n }\n\n if (typeof value === 'string') {\n const num = Number(value);\n\n if (!Number.isNaN(num)) {\n return num;\n }\n }\n\n throw createTypeError();\n}, 'number');\n","import type { RGB } from './types.js';\n\n/**\n * Returns true in case, passed value has #RRGGBB format.\n * @param value - value to check.\n */\nexport function isRGB(value: string): value is RGB {\n return /^#[\\da-f]{6}$/i.test(value);\n}\n","import type { RGBShort } from './types.js';\n\n/**\n * Returns true in case, passed value has #RGB format.\n * @param value - value to check.\n */\nexport function isRGBShort(value: string): value is RGBShort {\n return /^#[\\da-f]{3}$/i.test(value);\n}\n","import { isRGB } from './isRGB.js';\nimport { isRGBShort } from './isRGBShort.js';\nimport type { RGB } from './types.js';\n\n/**\n * Converts passed value to #RRGGBB format. Accepts following color formats:\n * - `#RGB`\n * - `#RRGGBB`\n * - `rgb(1,2,3)`\n * - `rgba(1,2,3,4)`\n * @param value - value to convert.\n * @throws {Error} Passed value does not satisfy any of known RGB formats.\n */\nexport function toRGB(value: string): RGB {\n // Remove all spaces.\n const clean = value.replace(/\\s/g, '').toLowerCase();\n\n // Value already has required format.\n if (isRGB(clean)) {\n return clean;\n }\n\n // Convert from #RGB.\n if (isRGBShort(clean)) {\n let color: RGB = '#';\n for (let i = 0; i < 3; i += 1) {\n color += clean[1 + i].repeat(2);\n }\n return color;\n }\n\n // Example valid values: rgb(0,3,10) rgba(32,114,8,0)\n const match = clean.match(/^rgb\\((\\d{1,3}),(\\d{1,3}),(\\d{1,3})\\)$/)\n || clean.match(/^rgba\\((\\d{1,3}),(\\d{1,3}),(\\d{1,3}),\\d{1,3}\\)$/);\n\n // In case, this didn't work as well, we can't extract RGB color from passed\n // text.\n if (!match) {\n throw new Error(`Value \"${value}\" does not satisfy any of known RGB formats.`);\n }\n\n // Otherwise, take R, G and B components, convert to hex and create #RRGGBB\n // string.\n return match.slice(1).reduce((acc, component) => {\n const formatted = parseInt(component, 10).toString(16);\n return acc + (formatted.length === 1 ? '0' : '') + formatted;\n }, '#') as RGB;\n}\n","import { createTypeError } from '../createTypeError.js';\nimport { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as string.\n */\nexport const string: ValueParserGenerator<string> = createValueParserGenerator((value) => {\n if (typeof value === 'string' || typeof value === 'number') {\n return value.toString();\n }\n throw createTypeError();\n}, 'string');\n","import { toRGB } from '@/colors/toRGB.js';\nimport type { RGB } from '@/colors/types.js';\n\nimport { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport { string } from './string.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as RGB color.\n */\nexport const rgb: ValueParserGenerator<RGB> = createValueParserGenerator((value) => toRGB(string().parse(value)), 'rgb');\n","import { json } from '@/parsing/parsers/json.js';\nimport { string } from '@/parsing/parsers/string.js';\n\n/**\n * Message format used in communication between client and Telegram applications.\n */\nexport interface MiniAppsMessage {\n /**\n * Event name.\n */\n eventType: string;\n /**\n * Event parameters.\n */\n eventData?: unknown;\n}\n\n/**\n * Parses value as a message between client and Telegram applications.\n * @param value - value to parse.\n */\nexport function parseMessage(value: unknown): MiniAppsMessage {\n return json({\n eventType: string(),\n eventData: (v) => v,\n }).parse(value);\n}\n","/**\n * Removes global event handlers, used by the package.\n */\nexport function cleanupEventHandlers(): void {\n ['TelegramGameProxy_receiveEvent', 'TelegramGameProxy', 'Telegram'].forEach((prop) => {\n delete window[prop as keyof Window];\n });\n}\n","/**\n * Emits event sent from Telegram native application like it was sent in\n * default web environment between 2 iframes. It dispatches new MessageEvent\n * and expects it to be handled via `window.addEventListener('message', ...)`\n * as developer would do it to handle messages sent from the parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nexport function emitMiniAppsEvent(eventType: string, eventData: unknown): void {\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType, eventData }),\n // We specify window.parent to imitate the case, the parent iframe sent us this event.\n source: window.parent,\n }));\n}\n","import { emitMiniAppsEvent } from './emitMiniAppsEvent.js';\n\n/**\n * Defines special handlers by known paths, which are recognized by\n * Telegram as ports to receive events. This function also sets special\n * function in global window object to prevent duplicate declaration.\n */\nexport function defineEventHandlers() {\n // Iterate over each path, where \"receiveEvent\" function should be\n // defined. This function is called by external environment in case,\n // it wants to emit some event.\n [\n ['TelegramGameProxy_receiveEvent'], // Windows Phone.\n ['TelegramGameProxy', 'receiveEvent'], // Desktop.\n ['Telegram', 'WebView', 'receiveEvent'], // Android and iOS.\n ].forEach((path) => {\n // Path starts from the \"window\" object.\n let pointer = window as any;\n\n path.forEach((item, idx, arr) => {\n // We are on the last iteration, where function property name is passed.\n if (idx === arr.length - 1) {\n pointer[item] = emitMiniAppsEvent;\n return;\n }\n\n if (!(item in pointer)) {\n pointer[item] = {};\n }\n pointer = pointer[item];\n });\n });\n}\n","import { logger } from '@/debug/debug.js';\nimport { EventEmitter } from '@/events/event-emitter/EventEmitter.js';\nimport { onWindow } from '@/events/onWindow.js';\nimport { createCleanup } from '@/misc/createCleanup.js';\nimport { boolean } from '@/parsing/parsers/boolean.js';\nimport { json } from '@/parsing/parsers/json.js';\nimport { number } from '@/parsing/parsers/number.js';\nimport { rgb } from '@/parsing/parsers/rgb.js';\nimport { string } from '@/parsing/parsers/string.js';\nimport { toRecord } from '@/parsing/toRecord.js';\nimport type { RGB } from '@/colors/types.js';\n\nimport { type MiniAppsMessage, parseMessage } from '../../parseMessage.js';\nimport { cleanupEventHandlers } from '../event-handlers/cleanupEventHandlers.js';\nimport { defineEventHandlers } from '../event-handlers/defineEventHandlers.js';\nimport type {\n MiniAppsEventName,\n MiniAppsEventPayload,\n MiniAppsEventEmitter,\n MiniAppsEvents,\n} from '../types.js';\n\n/**\n * Parsers for each Mini Apps event.\n *\n * This map should be cleaned\n */\nconst parsers: {\n [E in MiniAppsEventName]?: {\n parse(value: unknown): MiniAppsEventPayload<E>;\n }\n} = {\n clipboard_text_received: json({\n req_id: string(),\n data: (value) => (value === null ? value : string().optional().parse(value)),\n }),\n custom_method_invoked: json({\n req_id: string(),\n result: (value) => value,\n error: string().optional(),\n }),\n invoice_closed: json({ slug: string(), status: string() }),\n phone_requested: json({ status: string() }),\n popup_closed: {\n parse(value) {\n return json({\n button_id: (value) => (\n value === null || value === undefined\n ? undefined\n : string().parse(value)\n ),\n }).parse(value ?? {});\n },\n },\n qr_text_received: json({ data: string().optional() }),\n theme_changed: json({\n theme_params: (value) => {\n const parser = rgb().optional();\n\n return Object\n .entries(toRecord(value))\n .reduce<Partial<Record<string, RGB>>>((acc, [k, v]) => {\n acc[k] = parser.parse(v);\n return acc;\n }, {});\n },\n }),\n viewport_changed: json({\n height: number(),\n width: (value) => (\n value === null || value === undefined\n ? window.innerWidth\n : number().parse(value)\n ),\n is_state_stable: boolean(),\n is_expanded: boolean(),\n }),\n write_access_requested: json({ status: string() }),\n};\n\n/**\n * Creates new event emitter, which handles events from the Telegram application.\n */\nexport function createMiniAppsEventEmitter(): [\n /**\n * Created event emitter.\n */\n emitter: MiniAppsEventEmitter,\n /**\n * Function to dispose created emitter.\n */\n dispose: () => void,\n] {\n // We use this event emitter for better developer experience, using the subscribe method.\n const subEmitter = new EventEmitter<{ event: any[] }>();\n\n // Event emitter processing all the incoming events.\n const mainEmitter = new EventEmitter<MiniAppsEvents>();\n\n mainEmitter.subscribe(event => {\n subEmitter.emit('event', { name: event.event, payload: event.args[0] });\n });\n\n // Define event handles, which will proxy native method calls to their web version.\n defineEventHandlers();\n\n // List of cleanup functions, which should be called on dispose.\n const [, cleanup] = createCleanup(\n // Don't forget to remove created handlers.\n cleanupEventHandlers,\n // Add \"resize\" event listener to make sure, we always have fresh viewport information.\n // Desktop version of Telegram is sometimes not sending the viewport_changed\n // event. For example, when the MainButton is shown. That's why we should\n // add our own listener to make sure, viewport information is always fresh.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/10\n onWindow('resize', () => {\n mainEmitter.emit('viewport_changed', {\n width: window.innerWidth,\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n });\n }),\n // Add listener, which handles events sent from the Telegram web application and also events\n // generated by the local emitEvent function.\n onWindow('message', (event) => {\n // Ignore non-parent window messages.\n if (event.source !== window.parent) {\n return;\n }\n\n // Parse incoming event data.\n let message: MiniAppsMessage;\n try {\n message = parseMessage(event.data);\n } catch {\n // We ignore incorrect messages as they could be generated by any other code.\n return;\n }\n\n const { eventType, eventData } = message;\n const parser = parsers[eventType as keyof typeof parsers];\n\n try {\n const data = parser ? parser.parse(eventData) : eventData;\n mainEmitter.emit(...(data ? [eventType, data] : [eventType]) as [any, any]);\n } catch (cause) {\n logger.error(\n `An error occurred processing the \"${eventType}\" event from the Telegram application. Please, file an issue here: https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,\n message,\n cause,\n );\n }\n }),\n // Clear emitters.\n () => subEmitter.clear(),\n () => mainEmitter.clear(),\n );\n\n return [{\n on: mainEmitter.on.bind(mainEmitter),\n off: mainEmitter.off.bind(mainEmitter),\n subscribe(listener) {\n return subEmitter.on('event', listener);\n },\n unsubscribe(listener) {\n subEmitter.off('event', listener);\n },\n get count() {\n return mainEmitter.count + subEmitter.count;\n },\n }, cleanup];\n}\n","import { createSingleton } from '@/misc/createSingleton.js';\n\nimport { createMiniAppsEventEmitter } from './createMiniAppsEventEmitter.js';\nimport type { MiniAppsEventEmitter } from '../types.js';\n\nconst [get, resetMiniAppsEventEmitter] = createSingleton(\n (reset) => {\n const [emitter, cleanup] = createMiniAppsEventEmitter();\n\n // Rewire \"off\" method and make it reset singleton if no event listeners left.\n const off = emitter.off.bind(emitter);\n emitter.off = (event, listener) => {\n const { count } = emitter;\n off(event, listener);\n\n // If event emitter now has no listeners, we can perform a reset.\n if (count && !emitter.count) {\n reset();\n }\n };\n\n return [emitter, cleanup] as const;\n },\n ([, cleanup]) => cleanup(),\n);\n\n/**\n * Returns Mini Apps event emitter singleton.\n */\nexport function miniAppsEventEmitter(): MiniAppsEventEmitter {\n return get()[0];\n}\n\nexport { resetMiniAppsEventEmitter };\n","import { miniAppsEventEmitter } from '../event-emitter/singleton.js';\nimport type { MiniAppsEventListener, MiniAppsEventName } from '../types.js';\n\n/**\n * Removes listener from specified event.\n * @param event - event to listen.\n * @param listener - event listener to remove.\n */\nexport function off<E extends MiniAppsEventName>(\n event: E,\n listener: MiniAppsEventListener<E>,\n): void {\n miniAppsEventEmitter().off(event, listener);\n}\n","import type { RemoveEventListenerFn } from '@/events/types.js';\n\nimport { miniAppsEventEmitter } from '../event-emitter/singleton.js';\nimport type { MiniAppsEventListener, MiniAppsEventName } from '../types.js';\n\n/**\n * Adds new listener to the specified event. Returns handler\n * which allows to stop listening to event.\n * @param event - event name.\n * @param listener - event listener.\n * @param once - should listener be called only once.\n * @returns Function to remove bound event listener.\n */\nexport function on<E extends MiniAppsEventName>(\n event: E,\n listener: MiniAppsEventListener<E>,\n once?: boolean,\n): RemoveEventListenerFn {\n return miniAppsEventEmitter().on(event, listener, once);\n}\n","/**\n * States that passed value is Record and not Array.\n * @param value - value to check.\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","import type { Version } from './types.js';\n\n/**\n * Returns 1 in case, version \"a\" is greater than \"b\".\n * Returns 0 in case, version \"a\" equal to \"b\".\n * Returns -1 in case, version \"a\" is lower than \"b\".\n * @param a - first version.\n * @param b - second version.\n */\nexport function compareVersions(a: Version, b: Version): number {\n // Split both of the version by dot.\n const aParts = a.split('.');\n const bParts = b.split('.');\n\n // Compute maximum length.\n const len = Math.max(aParts.length, bParts.length);\n\n // Iterate over each part of version and compare them. In case, part is\n // missing, assume its value is equal to 0.\n for (let i = 0; i < len; i += 1) {\n const aVal = parseInt(aParts[i] || '0', 10);\n const bVal = parseInt(bParts[i] || '0', 10);\n\n if (aVal === bVal) {\n continue;\n }\n return aVal > bVal ? 1 : -1;\n }\n return 0;\n}\n","import { compareVersions } from '@/version/compareVersions.js';\nimport type {\n MiniAppsMethodName,\n MiniAppsMethodVersionedParams,\n MiniAppsMethodWithVersionedParams,\n} from '@/bridge/methods/types/methods.js';\nimport type { Version } from '@/version/types.js';\n\n/**\n * Returns true if \"a\" version is less than or equal to \"b\" version.\n * @param a\n * @param b\n */\nfunction versionLessOrEqual(a: Version, b: Version): boolean {\n return compareVersions(a, b) <= 0;\n}\n\n/**\n * Returns true in case, passed parameter in specified method is supported.\n * @param method - method name\n * @param param - method parameter\n * @param inVersion - platform version.\n */\nexport function supports<M extends MiniAppsMethodWithVersionedParams>(\n method: M,\n param: MiniAppsMethodVersionedParams<M>,\n inVersion: Version,\n): boolean;\n\n/**\n * Returns true in case, specified method is supported in passed version.\n * @param method - method name.\n * @param inVersion - platform version.\n */\nexport function supports(method: MiniAppsMethodName, inVersion: Version): boolean;\n\nexport function supports(\n method: MiniAppsMethodName,\n paramOrVersion: Version | string,\n inVersion?: string,\n): boolean {\n // Method name, parameter, target version.\n if (typeof inVersion === 'string') {\n if (method === 'web_app_open_link') {\n if (paramOrVersion === 'try_instant_view') {\n return versionLessOrEqual('6.4', inVersion);\n }\n if (paramOrVersion === 'try_browser') {\n return versionLessOrEqual('7.6', inVersion);\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if (paramOrVersion === 'color') {\n return versionLessOrEqual('6.9', inVersion);\n }\n }\n\n if (method === 'web_app_close' && paramOrVersion === 'return_back') {\n return versionLessOrEqual('7.6', inVersion);\n }\n }\n\n switch (method) {\n case 'web_app_open_tg_link':\n case 'web_app_open_invoice':\n case 'web_app_setup_back_button':\n case 'web_app_set_background_color':\n case 'web_app_set_header_color':\n case 'web_app_trigger_haptic_feedback':\n return versionLessOrEqual('6.1', paramOrVersion);\n case 'web_app_open_popup':\n return versionLessOrEqual('6.2', paramOrVersion);\n case 'web_app_close_scan_qr_popup':\n case 'web_app_open_scan_qr_popup':\n case 'web_app_read_text_from_clipboard':\n return versionLessOrEqual('6.4', paramOrVersion);\n case 'web_app_switch_inline_query':\n return versionLessOrEqual('6.7', paramOrVersion);\n case 'web_app_invoke_custom_method':\n case 'web_app_request_write_access':\n case 'web_app_request_phone':\n return versionLessOrEqual('6.9', paramOrVersion);\n case 'web_app_setup_settings_button':\n return versionLessOrEqual('6.10', paramOrVersion);\n case 'web_app_biometry_get_info':\n case 'web_app_biometry_open_settings':\n case 'web_app_biometry_request_access':\n case 'web_app_biometry_request_auth':\n case 'web_app_biometry_update_token':\n return versionLessOrEqual('7.2', paramOrVersion);\n default:\n return [\n 'iframe_ready',\n 'iframe_will_reload',\n 'web_app_close',\n 'web_app_data_send',\n 'web_app_expand',\n 'web_app_open_link',\n 'web_app_ready',\n 'web_app_request_theme',\n 'web_app_request_viewport',\n 'web_app_setup_main_button',\n 'web_app_setup_closing_behavior',\n ].includes(method);\n }\n}\n","import { isRecord } from '@/misc/isRecord.js';\n\n/**\n * Returns true in case, passed value contains path `external.notify` property and `notify` is a\n * function.\n * @param value - value to check.\n */\nexport function hasExternalNotify<T extends object>(value: T): value is (\n T & {\n external: {\n notify: (...args: any) => any;\n };\n}) {\n return 'external' in value\n && isRecord(value.external)\n && 'notify' in value.external\n && typeof value.external.notify === 'function';\n}\n","import { isRecord } from '@/misc/isRecord.js';\n\n/**\n * Returns true in case, passed value contains path `TelegramWebviewProxy.postEvent` property and\n * `postEvent` is a function.\n * @param value - value to check.\n */\nexport function hasWebviewProxy<T extends {}>(value: T): value is (\n T & {\n TelegramWebviewProxy: {\n postEvent: (...args: any) => any;\n }\n}) {\n return 'TelegramWebviewProxy' in value\n && isRecord(value.TelegramWebviewProxy)\n && 'postEvent' in value.TelegramWebviewProxy\n && typeof value.TelegramWebviewProxy.postEvent === 'function';\n}\n","/**\n * @see https://stackoverflow.com/a/326076\n * @returns True, if current environment is iframe.\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch {\n return true;\n }\n}\n","let currentTargetOrigin = 'https://web.telegram.org';\n\n/**\n * Sets new global targetOrigin, used by `postEvent` method.\n * Default value is \"https://web.telegram.org\". You don't need to\n * use this method until you know what you are doing.\n *\n * This method could be used for test purposes.\n * @param value - new target origin.\n */\nexport function setTargetOrigin(value: string): void {\n currentTargetOrigin = value;\n}\n\n/**\n * Returns current global target origin.\n */\nexport function targetOrigin(): string {\n return currentTargetOrigin;\n}\n","import { log } from '@/debug/debug.js';\nimport { hasExternalNotify } from '@/env/hasExternalNotify.js';\nimport { hasWebviewProxy } from '@/env/hasWebviewProxy.js';\nimport { isIframe } from '@/env/isIframe.js';\nimport { createError } from '@/errors/createError.js';\nimport { ERR_UNKNOWN_ENV } from '@/errors/errors.js';\n\nimport { targetOrigin as targetOriginFn } from '../target-origin.js';\nimport type {\n MiniAppsMethodName,\n MiniAppsMethodParams,\n MiniAppsMethodWithOptionalParams,\n MiniAppsMethodWithoutParams,\n MiniAppsMethodWithRequiredParams,\n} from './types/methods.js';\n\ninterface PostEventOptions {\n /**\n * Origin used while posting message. This option is only used in case, current environment\n * is browser (Web version of Telegram) and could be used for test purposes.\n * @default 'https://web.telegram.org'\n */\n targetOrigin?: string;\n}\n\nexport type PostEvent = typeof postEvent;\n\n/**\n * Calls Mini Apps method with optional parameters.\n * @param method - method name.\n * @param params - method parameters.\n * @param options - posting options.\n * @throws {SDKError} ERR_UNKNOWN_ENV\n * @see ERR_UNKNOWN_ENV\n */\nexport function postEvent<Method extends MiniAppsMethodWithOptionalParams>(\n method: Method,\n params?: MiniAppsMethodParams<Method>,\n options?: PostEventOptions,\n): void;\n\n/**\n * Calls Mini Apps method without parameters.\n * @param method - method name.\n * @param options - posting options.\n * @throws {SDKError} ERR_UNKNOWN_ENV\n * @see ERR_UNKNOWN_ENV\n */\nexport function postEvent(method: MiniAppsMethodWithoutParams, options?: PostEventOptions): void;\n\n/**\n * Calls Mini Apps method with parameters.\n * @param method - method name.\n * @param params - method parameters.\n * @param options - posting options.\n * @throws {SDKError} ERR_UNKNOWN_ENV\n * @see ERR_UNKNOWN_ENV\n */\nexport function postEvent<Method extends MiniAppsMethodWithRequiredParams>(\n method: Method,\n params: MiniAppsMethodParams<Method>,\n options?: PostEventOptions,\n): void;\n\nexport function postEvent(\n eventType: MiniAppsMethodName,\n paramsOrOptions?: MiniAppsMethodParams<MiniAppsMethodName> | PostEventOptions,\n options?: PostEventOptions,\n): void {\n let postOptions: PostEventOptions = {};\n let eventData: any;\n\n if (paramsOrOptions === undefined && options === undefined) {\n // Parameters and options were not passed.\n postOptions = {};\n } else if (paramsOrOptions !== undefined && options !== undefined) {\n // Both parameters and options passed.\n postOptions = options;\n eventData = paramsOrOptions;\n } else if (paramsOrOptions !== undefined) {\n // Only parameters were passed.\n if ('targetOrigin' in paramsOrOptions) {\n postOptions = paramsOrOptions;\n } else {\n eventData = paramsOrOptions;\n }\n }\n const { targetOrigin = targetOriginFn() } = postOptions;\n\n log('Posting event:', eventData\n ? { event: eventType, data: eventData }\n : { event: eventType });\n\n // Telegram Web.\n if (isIframe()) {\n window.parent.postMessage(JSON.stringify({ eventType, eventData }), targetOrigin);\n return;\n }\n\n // Telegram for Windows Phone or Android.\n if (hasExternalNotify(window)) {\n window.external.notify(JSON.stringify({ eventType, eventData }));\n return;\n }\n\n // Telegram for iOS and macOS.\n if (hasWebviewProxy(window)) {\n window.TelegramWebviewProxy.postEvent(eventType, JSON.stringify(eventData));\n return;\n }\n\n // Otherwise current environment is unknown, and we are not able to send event.\n throw createError(\n ERR_UNKNOWN_ENV,\n 'Unable to determine current environment and possible way to send event. You are probably trying to use Mini Apps method outside of Telegram application environment.',\n );\n}\n","import { createError } from '@/errors/createError.js';\nimport { ERR_METHOD_PARAMETER_UNSUPPORTED, ERR_METHOD_UNSUPPORTED } from '@/errors/errors.js';\nimport { isRecord } from '@/misc/isRecord.js';\nimport { supports } from '@/supports/supports.js';\nimport type { Version } from '@/version/types.js';\n\nimport { type PostEvent, postEvent } from './postEvent.js';\n\n/**\n * Creates function which checks if specified method and parameters are supported. In case,\n * method or parameters are unsupported, an error will be thrown.\n * @param version - Telegram Mini Apps version.\n * @throws {SDKError} ERR_METHOD_UNSUPPORTED\n * @throws {SDKError} ERR_METHOD_PARAMETER_UNSUPPORTED\n * @see ERR_METHOD_UNSUPPORTED\n * @see ERR_METHOD_PARAMETER_UNSUPPORTED\n */\nexport function createPostEvent(version: Version): PostEvent {\n return (method: any, params: any) => {\n // Firstly, check if method itself is supported.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n if (!supports(method, version)) {\n throw createError(ERR_METHOD_UNSUPPORTED, `Method \"${method}\" is unsupported in Mini Apps version ${version}`);\n }\n\n // Method could use parameters, which are supported only in specific versions of Telegram\n // Mini Apps.\n if (isRecord(params)) {\n let validateParam: string | undefined;\n\n if (method === 'web_app_open_link' && 'try_instant_view' in params) {\n validateParam = 'try_instant_view';\n } else if (method === 'web_app_set_header_color' && 'color' in params) {\n validateParam = 'color';\n }\n\n if (validateParam && !supports(method, validateParam, version)) {\n throw createError(\n ERR_METHOD_PARAMETER_UNSUPPORTED,\n `Parameter \"${validateParam}\" of \"${method}\" method is unsupported in Mini Apps version ${version}`,\n );\n }\n }\n\n return postEvent(method, params);\n };\n}\n","type CaptureSameReqFn = (payload: { req_id: string }) => boolean;\n\n/**\n * Returns a function which can be used in `request` function `capture` property to capture\n * the event with the same request identifier.\n * @param reqId - request identifier.\n */\nexport function captureSameReq(reqId: string): CaptureSameReqFn {\n return ({ req_id }) => req_id === reqId;\n}\n","import { createError } from '@/errors/createError.js';\nimport { ERR_TIMED_OUT } from '@/errors/errors.js';\nimport type { SDKError } from '@/errors/SDKError.js';\n\n/**\n * Creates new timeout error.\n * @param timeout - timeout in ms.\n */\nexport function createTimeoutError(timeout: number): SDKError {\n return createError(ERR_TIMED_OUT, `Timeout reached: ${timeout}ms`);\n}\n","import { createTimeoutError } from '@/timeout/createTimeoutError.js';\n\n/**\n * Runs passed function or promise with specified deadline presented via timeout argument.\n * @param funcOrPromise - function to execute or pending promise.\n * @param timeout - completion timeout.\n */\nexport function withTimeout<T>(\n funcOrPromise: Promise<T> | (() => Promise<T>),\n timeout: number,\n): Promise<T> {\n return Promise.race([\n typeof funcOrPromise === 'function' ? funcOrPromise() : funcOrPromise,\n new Promise<never>((_, rej) => {\n setTimeout(() => {\n rej(createTimeoutError(timeout));\n }, timeout);\n }),\n ]);\n}\n","import { withTimeout } from '@/timeout/withTimeout.js';\nimport type { ExecuteWithOptions, If, IsNever } from '@/types/index.js';\n\nimport { on } from '../events/listening/on.js';\nimport { postEvent as defaultPostEvent } from '../methods/postEvent.js';\nimport type { MiniAppsEventName, MiniAppsEventPayload } from '../events/types.js';\nimport type { MiniAppsMethodName, MiniAppsMethodParams } from '../methods/types/index.js';\nimport { createCleanup } from '@/misc/createCleanup.js';\n\n/**\n * `request` method `capture` option.\n * @see request\n */\nexport type RequestCapture<T extends MiniAppsEventName | MiniAppsEventName[]> =\n T extends (infer U extends MiniAppsEventName)[]\n ? If<\n IsNever<MiniAppsEventPayload<U>>,\n () => boolean,\n (payload: {\n [K in U]: If<\n IsNever<MiniAppsEventPayload<K>>,\n { event: K; },\n { event: K; payload: MiniAppsEventPayload<K> }\n >\n }[U]) => boolean\n >\n : T extends MiniAppsEventName\n ? If<\n IsNever<MiniAppsEventPayload<T>>,\n () => boolean,\n (payload: MiniAppsEventPayload<T>) => boolean\n >\n : never;\n\n/**\n * `request` method options.\n * @see request\n */\nexport type RequestOptions<\n Method extends MiniAppsMethodName,\n Event extends MiniAppsEventName | MiniAppsEventName[]\n> = {\n /**\n * Mini Apps method name.\n */\n method: Method;\n /**\n * Tracked Mini Apps events.\n */\n event: Event;\n /**\n * Should return true in case, this event should be captured. If not specified,\n * request will be captured automatically.\n */\n capture?: RequestCapture<Event>;\n }\n & ExecuteWithOptions\n & If<IsNever<MiniAppsMethodParams<Method>>, {}, {\n /**\n * List of method parameters.\n */\n params: MiniAppsMethodParams<Method>\n}>;\n\nexport type RequestResult<Event extends MiniAppsEventName | MiniAppsEventName[]> =\n Event extends (infer T extends MiniAppsEventName)[]\n ? MiniAppsEventPayload<T>\n : Event extends MiniAppsEventName\n ? MiniAppsEventPayload<Event>\n : never;\n\n/**\n * Calls specified Mini Apps method and captures one of the specified events. Returns promise\n * which will be resolved in case, specified event was captured.\n * @param options - method options.\n */\nexport async function request<\n Method extends MiniAppsMethodName,\n Event extends MiniAppsEventName | MiniAppsEventName[]\n>(\n options: RequestOptions<Method, Event>,\n): Promise<RequestResult<Event>> {\n let resolve: (payload: RequestResult<Event>) => void;\n const promise = new Promise<RequestResult<Event>>((res) => {\n resolve = res;\n });\n\n const { event, capture, timeout } = options;\n const [, cleanup] = createCleanup(\n ...(Array.isArray(event) ? event : [event]).map(\n (ev) => on(ev, (payload: any) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n return (!capture || capture(payload)) && resolve(payload);\n }),\n )\n );\n\n try {\n (options.postEvent || defaultPostEvent)(options.method as any, (options as any).params);\n return await (timeout ? withTimeout(promise, timeout) : promise);\n } finally {\n // After promise execution was completed, don't forget to remove all the listeners.\n cleanup();\n }\n}\n","import { createError } from '@/errors/createError.js';\nimport { ERR_INVOKE_CUSTOM_METHOD_RESPONSE } from '@/errors/errors.js';\nimport type { ExecuteWithOptions } from '@/types/index.js';\n\nimport { captureSameReq } from './captureSameReq.js';\nimport { request } from './request.js';\nimport type { CustomMethodName, CustomMethodParams } from '../methods/types/custom-methods.js';\n\n/**\n * Invokes known custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param requestId - request identifier.\n * @param options - additional options.\n * @throws {SDKError} ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n * @see ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n */\nexport async function invokeCustomMethod<M extends CustomMethodName>(\n method: M,\n params: CustomMethodParams<M>,\n requestId: string,\n options?: ExecuteWithOptions,\n): Promise<unknown>;\n\n/**\n * Invokes unknown custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param requestId - request identifier.\n * @param options - additional options.\n * @throws {SDKError} ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n * @see ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n */\nexport function invokeCustomMethod(\n method: string,\n params: object,\n requestId: string,\n options?: ExecuteWithOptions,\n): Promise<unknown>;\n\nexport async function invokeCustomMethod(\n method: string,\n params: object,\n requestId: string,\n options: ExecuteWithOptions = {},\n): Promise<unknown> {\n const {\n result,\n error,\n } = await request({\n ...options,\n method: 'web_app_invoke_custom_method',\n event: 'custom_method_invoked',\n params: {\n method,\n params,\n req_id: requestId,\n },\n capture: captureSameReq(requestId),\n });\n\n if (error) {\n throw createError(ERR_INVOKE_CUSTOM_METHOD_RESPONSE, error);\n }\n\n return result;\n}\n","import { request } from '@/bridge/utils/request.js';\nimport { hasWebviewProxy } from '@/env/hasWebviewProxy.js';\n\n/**\n * Returns true in case, current environment is Telegram Mini Apps.\n */\nexport async function isTMA(): Promise<boolean> {\n if (hasWebviewProxy(window)) {\n return true;\n }\n try {\n await request({ method: 'web_app_request_theme', event: 'theme_changed', timeout: 100 });\n return true;\n } catch {\n return false;\n }\n}\n","import { SDKError } from './SDKError.js';\n\n/**\n * @returns True, if passed value is an instance of SDKError.\n * @param value - value to check.\n */\nexport function isSDKError(value: unknown): value is SDKError {\n return value instanceof SDKError;\n}\n","import { isSDKError } from './isSDKError.js';\nimport type { ErrorType } from './errors.js';\n\n/**\n * Returns true if passed value is an SDK error of specified type.\n * @param value - value to check.\n * @param type - error type.\n */\nexport function isSDKErrorOfType(value: unknown, type: ErrorType): boolean {\n return isSDKError(value) && value.type === type;\n}\n","import { on } from '@/bridge/events/listening/on.js';\nimport { postEvent } from '@/bridge/methods/postEvent.js';\n\ninterface CleanupFn {\n (): void;\n}\n\n/**\n * Performs initialization process in the web version of Telegram.\n * @returns Function, which performs cleanup removing all created elements and listeners.\n * @param acceptCustomStyles - true if SDK should accept styles sent from the Telegram web\n * application. This option is only used in web versions of Telegram. Default: false.\n */\nexport function initWeb(acceptCustomStyles = true): CleanupFn {\n const listeners: CleanupFn[] = [\n on('reload_iframe', () => {\n postEvent('iframe_will_reload');\n window.location.reload();\n }),\n ];\n const cleanup: CleanupFn = () => listeners.forEach((l) => l());\n\n if (acceptCustomStyles) {\n const style = document.createElement('style');\n style.id = 'telegram-custom-styles';\n document.head.appendChild(style);\n\n listeners.push(\n on('set_custom_style', (html) => {\n // It is safe to use innerHTML here as long as style tag has a special behavior related\n // to the specified content. In case, any script will be passed here, it will not be\n // executed.\n style.innerHTML = html;\n }),\n () => document.head.removeChild(style),\n );\n }\n\n // Notify Telegram, iframe is ready. This will result in sending style tag html from native\n // application which is used in catchCustomStyles function. We should call this method also\n // to start receiving \"reload_iframe\" events from the Telegram application.\n postEvent('iframe_ready', { reload_supported: true });\n\n return cleanup;\n}\n","import { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport { number } from './number.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as Date.\n */\nexport const date: ValueParserGenerator<Date> = createValueParserGenerator((value) => (\n value instanceof Date\n ? value\n : new Date(number().parse(value) * 1000)\n), 'Date');\n","import { createTypeError } from '../createTypeError.js';\nimport { parseBySchema } from '../parseBySchema.js';\nimport { ValueParser } from '../ValueParser/ValueParser.js';\nimport type { Schema } from '../types.js';\n\n/**\n * Creates new search params parser according to passed schema.\n * @param schema - object schema.\n * @param type - parser type name.\n */\nexport function searchParams<T>(schema: Schema<T>, type?: string): ValueParser<T, false> {\n return new ValueParser((value) => {\n if (typeof value !== 'string' && !(value instanceof URLSearchParams)) {\n throw createTypeError();\n }\n\n const params = typeof value === 'string' ? new URLSearchParams(value) : value;\n\n return parseBySchema(schema, (field) => {\n const paramValue = params.get(field);\n return paramValue === null ? undefined : paramValue;\n });\n }, false, type);\n}\n","import { json } from '@/parsing/parsers/json.js';\nimport { number } from '@/parsing/parsers/number.js';\nimport { string } from '@/parsing/parsers/string.js';\n\nimport type { Chat } from '../types.js';\n\nexport const chat = json<Chat>({\n id: number(),\n type: string(),\n title: string(),\n photoUrl: {\n type: string().optional(),\n from: 'photo_url',\n },\n username: string().optional(),\n}, 'Chat')\n .optional();\n","import { boolean } from '@/parsing/parsers/boolean.js';\nimport { json } from '@/parsing/parsers/json.js';\nimport { number } from '@/parsing/parsers/number.js';\nimport { string } from '@/parsing/parsers/string.js';\n\nimport type { User } from '../types.js';\n\nexport const user = json<User>({\n addedToAttachmentMenu: {\n type: boolean().optional(),\n from: 'added_to_attachment_menu',\n },\n allowsWriteToPm: {\n type: boolean().optional(),\n from: 'allows_write_to_pm',\n },\n firstName: {\n type: string(),\n from: 'first_name',\n },\n id: number(),\n isBot: {\n type: boolean().optional(),\n from: 'is_bot',\n },\n isPremium: {\n type: boolean().optional(),\n from: 'is_premium',\n },\n languageCode: {\n type: string().optional(),\n from: 'language_code',\n },\n lastName: {\n type: string().optional(),\n from: 'last_name',\n },\n photoUrl: {\n type: string().optional(),\n from: 'photo_url',\n },\n username: string().optional(),\n}, 'User')\n .optional();\n","import { date } from '@/parsing/parsers/date.js';\nimport { number } from '@/parsing/parsers/number.js';\nimport { searchParams } from '@/parsing/parsers/searchParams.js';\nimport { string } from '@/parsing/parsers/string.js';\nimport type { ValueParser } from '@/parsing/ValueParser/ValueParser.js';\n\nimport { chat } from './chat.js';\nimport { user } from './user.js';\nimport type { InitDataParsed } from '../types.js';\n\n/**\n * Returns parser used to parse init data, presented as search params.\n */\nexport function initData(): ValueParser<InitDataParsed, false> {\n return searchParams<InitDataParsed>({\n authDate: {\n type: date(),\n from: 'auth_date',\n },\n canSendAfter: {\n type: number().optional(),\n from: 'can_send_after',\n },\n chat,\n chatInstance: {\n type: string().optional(),\n from: 'chat_instance',\n },\n chatType: {\n type: string().optional(),\n from: 'chat_type',\n },\n hash: string(),\n queryId: {\n type: string().optional(),\n from: 'query_id',\n },\n receiver: user,\n startParam: {\n type: string().optional(),\n from: 'start_param',\n },\n user,\n }, 'InitData');\n}\n","/**\n * Converts a palette key from the Telegram application to the representation used by the package.\n * @param key - palette key.\n */\nexport function keyToLocal(key: string): string {\n return key.replace(/_[a-z]/g, (match) => match[1].toUpperCase());\n}\n\n/**\n * Converts palette key from the local representation to the representation sent from the\n * Telegram application.\n * @param key - palette key.\n */\nexport function keyToExternal(key: string): string {\n return key.replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`);\n}\n","import { createValueParserGenerator, type ValueParserGenerator } from '@/parsing/createValueParserGenerator.js';\nimport { rgb } from '@/parsing/parsers/rgb.js';\nimport { toRecord } from '@/parsing/toRecord.js';\n\nimport { keyToLocal } from '../keys.js';\nimport type { ThemeParamsParsed } from '../types.js';\n\nexport const themeParams: ValueParserGenerator<ThemeParamsParsed> = createValueParserGenerator(\n (value) => {\n const rgbOptional = rgb().optional();\n\n return Object\n .entries(toRecord(value))\n .reduce<ThemeParamsParsed>((acc, [k, v]) => {\n acc[keyToLocal(k)] = rgbOptional.parse(v);\n return acc;\n }, {});\n },\n 'ThemeParams',\n);\n","import { initData } from '@/components/InitData/parsers/initData.js';\nimport { themeParams } from '@/components/ThemeParams/parsing/themeParams.js';\nimport { boolean } from '@/parsing/parsers/boolean.js';\nimport { searchParams } from '@/parsing/parsers/searchParams.js';\nimport { string } from '@/parsing/parsers/string.js';\n\nimport type { LaunchParams } from './types.js';\n\n/**\n * Parses value as launch parameters.\n * @param value - value to parse.\n */\nexport function parseLaunchParams(value: unknown): LaunchParams {\n return searchParams({\n botInline: {\n type: boolean().optional(),\n from: 'tgWebAppBotInline',\n },\n initData: {\n type: initData().optional(),\n from: 'tgWebAppData',\n },\n initDataRaw: {\n type: string().optional(),\n from: 'tgWebAppData',\n },\n platform: {\n type: string(),\n from: 'tgWebAppPlatform',\n },\n showSettings: {\n type: boolean().optional(),\n from: 'tgWebAppShowSettings',\n },\n startParam: {\n type: string().optional(),\n from: 'tgWebAppStartParam',\n },\n themeParams: {\n type: themeParams(),\n from: 'tgWebAppThemeParams',\n },\n version: {\n type: string(),\n from: 'tgWebAppVersion',\n },\n }).parse(value);\n}\n","import { parseLaunchParams } from './parseLaunchParams.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * @param urlString - URL to extract launch parameters from.\n * @returns Launch parameters from the specified URL.\n * @throws Error if function was unable to extract launch parameters from the passed URL.\n */\nexport function retrieveFromUrl(urlString: string): LaunchParams {\n return parseLaunchParams(\n urlString\n // Replace everything before this first hashtag or question sign.\n .replace(/^[^?#]*[?#]/, '')\n // Replace all hashtags and question signs to make it look like some search params.\n .replace(/[?#]/g, '&'),\n );\n}\n","import { retrieveFromUrl } from './retrieveFromUrl.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * @returns Launch parameters from the current window location hash.\n * @throws Error if function was unable to extract launch parameters from the window location hash.\n */\nexport function retrieveFromLocation(): LaunchParams {\n return retrieveFromUrl(window.location.href);\n}\n","/**\n * Returns the first navigation entry from window.performance.\n * @returns First navigation entry or null, in case performance functionality is not supported\n * or navigation entry was not found.\n */\nexport function getFirstNavigationEntry(): PerformanceNavigationTiming | undefined {\n return performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined;\n}\n","import { getFirstNavigationEntry } from '@/navigation/getFirstNavigationEntry.js';\n\nimport { retrieveFromUrl } from './retrieveFromUrl.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * @returns Launch parameters based on the first navigation entry.\n * @throws Error if function was unable to extract launch parameters from the navigation entry.\n */\nexport function retrieveFromPerformance(): LaunchParams {\n const navigationEntry = getFirstNavigationEntry();\n if (!navigationEntry) {\n throw new Error('Unable to get first navigation entry.');\n }\n\n return retrieveFromUrl(navigationEntry.name);\n}\n","import type { BackButtonState } from '@/components/BackButton/types.js';\nimport type { BiometryManagerState } from '@/components/BiometryManager/types.js';\nimport type { ClosingBehaviorState } from '@/components/ClosingBehavior/types.js';\nimport type { MainButtonState } from '@/components/MainButton/types.js';\nimport type { MiniAppState } from '@/components/MiniApp/types.js';\nimport type { SettingsButtonState } from '@/components/SettingsButton/types.js';\nimport type { ThemeParamsParsed } from '@/components/ThemeParams/types.js';\nimport type { ViewportState } from '@/components/Viewport/types.js';\n\n/**\n * Describes storage keys and according values.\n */\nexport interface StorageParams {\n backButton: BackButtonState;\n biometryManager: BiometryManagerState;\n closingBehavior: ClosingBehaviorState;\n launchParams: string;\n mainButton: MainButtonState;\n miniApp: MiniAppState;\n settingsButton: SettingsButtonState;\n themeParams: ThemeParamsParsed;\n viewport: ViewportState;\n}\n\n/**\n * Key which could be used to store data in the storage.\n */\nexport type StorageKey = keyof StorageParams;\n\n/**\n * Type specific to the specified storage key.\n */\nexport type StorageValue<K extends StorageKey> = StorageParams[K];\n\n/**\n * Converts passed storage key to the formatted state.\n * @param key - storage key.\n */\nfunction formatKey(key: StorageKey): string {\n return `tma.js/${key.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`)}`;\n}\n\n/**\n * Saves value in the storage.\n * @param key - storage key.\n * @param value - storage value.\n */\nexport function setStorageValue<K extends StorageKey>(key: K, value: StorageValue<K>): void {\n sessionStorage.setItem(formatKey(key), JSON.stringify(value));\n}\n\n/**\n * Extracts value from the storage.\n * @param key - storage key.\n */\nexport function getStorageValue<K extends StorageKey>(key: K): StorageValue<K> | undefined {\n const value = sessionStorage.getItem(formatKey(key));\n try {\n return value ? JSON.parse(value) as StorageValue<K> : undefined;\n } catch { /* empty */ }\n}\n","import { parseLaunchParams } from '@/launch-params/parseLaunchParams.js';\nimport { getStorageValue } from '@/storage/storage.js';\nimport type { LaunchParams } from '@/launch-params/types.js';\n\n/**\n * @returns Launch parameters stored in the session storage.\n * @throws Error if function was unable to extract launch parameters from the window location hash.\n */\nexport function retrieveFromStorage(): LaunchParams {\n return parseLaunchParams(getStorageValue('launchParams') || '');\n}\n","import { keyToExternal } from '../keys.js';\nimport type { ThemeParamsParsed } from '../types.js';\n\n/**\n * Serializes theme parameters to representation sent from the Telegram application.\n */\nexport function serializeThemeParams(themeParams: ThemeParamsParsed): string {\n return JSON.stringify(\n Object.fromEntries(\n Object\n .entries(themeParams)\n .map(([key, value]) => [keyToExternal(key), value]),\n ),\n );\n}\n","import { serializeThemeParams } from '@/components/ThemeParams/parsing/serializeThemeParams.js';\n\nimport type { LaunchParams } from './types.js';\n\n/**\n * Converts launch parameters to its initial representation.\n * @param value - launch parameters.\n */\nexport function serializeLaunchParams(value: LaunchParams): string {\n const {\n initDataRaw,\n themeParams,\n platform,\n version,\n showSettings,\n startParam,\n botInline,\n } = value;\n\n const params = new URLSearchParams();\n\n params.set('tgWebAppPlatform', platform);\n params.set('tgWebAppThemeParams', serializeThemeParams(themeParams));\n params.set('tgWebAppVersion', version);\n\n if (initDataRaw) {\n params.set('tgWebAppData', initDataRaw);\n }\n\n if (startParam) {\n params.set('tgWebAppStartParam', startParam);\n }\n\n if (typeof showSettings === 'boolean') {\n params.set('tgWebAppShowSettings', showSettings ? '1' : '0');\n }\n\n if (typeof botInline === 'boolean') {\n params.set('tgWebAppBotInline', botInline ? '1' : '0');\n }\n\n return params.toString();\n}\n","import { setStorageValue } from '@/storage/storage.js';\n\nimport { serializeLaunchParams } from './serializeLaunchParams.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * Saves specified launch parameters in the session storage.\n * @param value - launch params to save.\n */\nexport function saveToStorage(value: LaunchParams): void {\n setStorageValue('launchParams', serializeLaunchParams(value));\n}\n","import { retrieveFromLocation } from './retrieveFromLocation.js';\nimport { retrieveFromPerformance } from './retrieveFromPerformance.js';\nimport { retrieveFromStorage } from './retrieveFromStorage.js';\nimport { saveToStorage } from './saveToStorage.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * @returns Launch parameters from any known source.\n * @throws Error if extraction was unsuccessful.\n */\nexport function retrieveLaunchParams(): LaunchParams {\n const errors: unknown[] = [];\n\n for (const retrieve of [\n // Try to retrieve launch parameters from the current location. This method can return\n // nothing in case, location was changed and then page was reloaded.\n retrieveFromLocation,\n // Then, try using the lower level API - window.performance.\n retrieveFromPerformance,\n // Finally, try to extract launch parameters from the session storage.\n retrieveFromStorage,\n ]) {\n try {\n const lp = retrieve();\n saveToStorage(lp);\n return lp;\n } catch (e) {\n errors.push(e);\n }\n }\n\n throw new Error('Unable to retrieve launch parameters from any known source.');\n}\n"],"names":["createSingleton","create","onReset","cached","reset","unsubscribe","listener","ee","miniAppsEventEmitter","count","resetMiniAppsEventEmitter","subscribe","Logger","scope","options","level","args","now","date","textColor","bgColor","commonCss","logger","debugEnabled","onEvent","name","payload","setDebug","enable","log","EventEmitter","__publicField","event","l","once","listeners","i","onWindow","type","createCleanup","fns","called","cache","fn","clean","SDKError","message","cause","createError","ERR_METHOD_UNSUPPORTED","ERR_METHOD_PARAMETER_UNSUPPORTED","ERR_UNKNOWN_ENV","ERR_INVOKE_CUSTOM_METHOD_RESPONSE","ERR_TIMED_OUT","ERR_UNEXPECTED_TYPE","ERR_PARSE","ERR_NAVIGATION_HISTORY_EMPTY","ERR_NAVIGATION_INDEX_INVALID","ERR_NAVIGATION_ITEM_INVALID","ERR_SSR_INIT","ERR_INVALID_PATH_BASE","createTypeError","ValueParser","parser","isOptional","value","createValueParserGenerator","boolean","asString","parseBySchema","schema","getField","result","field","definition","from","definitionType","parsedValue","error","toRecord","formattedValue","json","record","number","num","isRGB","isRGBShort","toRGB","color","match","acc","component","formatted","string","rgb","parseMessage","v","cleanupEventHandlers","prop","emitMiniAppsEvent","eventType","eventData","defineEventHandlers","path","pointer","item","idx","arr","parsers","k","createMiniAppsEventEmitter","subEmitter","mainEmitter","cleanup","data","get","emitter","off","on","isRecord","compareVersions","a","b","aParts","bParts","len","aVal","bVal","versionLessOrEqual","supports","method","paramOrVersion","inVersion","hasExternalNotify","hasWebviewProxy","isIframe","currentTargetOrigin","setTargetOrigin","targetOrigin","postEvent","paramsOrOptions","postOptions","targetOriginFn","createPostEvent","version","params","validateParam","captureSameReq","reqId","req_id","createTimeoutError","timeout","withTimeout","funcOrPromise","_","rej","request","resolve","promise","res","capture","ev","defaultPostEvent","invokeCustomMethod","requestId","isTMA","isSDKError","isSDKErrorOfType","initWeb","acceptCustomStyles","style","html","searchParams","paramValue","chat","user","initData","keyToLocal","key","keyToExternal","themeParams","rgbOptional","parseLaunchParams","retrieveFromUrl","urlString","retrieveFromLocation","getFirstNavigationEntry","retrieveFromPerformance","navigationEntry","formatKey","m","setStorageValue","getStorageValue","retrieveFromStorage","serializeThemeParams","serializeLaunchParams","initDataRaw","platform","showSettings","startParam","botInline","saveToStorage","retrieveLaunchParams","retrieve","lp"],"mappings":"0OAKgB,SAAAA,EACdC,EACAC,EAUA,CACI,IAAAC,EACJ,MAAMC,EAAQ,IAAM,CACPD,IAAA,QAAaD,GAAWA,EAAQC,CAAM,EACxCA,EAAA,MAAA,EAGJ,MAAA,CAAC,IAAOA,IAAW,OAAYA,EAASF,EAAOG,CAAK,EAAID,EAASC,CAAK,CAC/E,CClBO,SAASC,EAAYC,EAA2C,CACrE,MAAMC,EAAKC,IACL,CAAE,MAAAC,CAAU,EAAAF,EAClBA,EAAG,YAAYD,CAAQ,EAGnBG,GAAS,CAACF,EAAG,OACWG,IAE9B,CCLO,SAASC,EAAUL,EAA4D,CAC/D,OAAAE,EAAA,EAAE,UAAUF,CAAQ,EAClC,IAAMD,EAAYC,CAAQ,CACnC,CCJO,MAAMM,EAAiD,CAC5D,YACmBC,EACAC,EAAyB,GAC1C,CAFiB,KAAA,MAAAD,EACA,KAAA,QAAAC,CAEnB,CAOQ,MAAMC,KAAoBC,EAAmB,CAC7C,MAAAC,MAAU,KACVC,EAAO,KACV,eAAe,QAAS,CACv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DO,SAASyI,IAAqC,CAGnD,UAAWC,IAAY,CAGrBlB,GAEAE,GAEAM,EAAA,EAEI,GAAA,CACF,MAAMW,EAAKD,IACX,OAAAF,GAAcG,CAAE,EACTA,OACG,CAEZ,CAGI,MAAA,IAAI,MAAM,6DAA6D,CAC/E"}
1
+ {"version":3,"file":"index.low-level.iife.js","sources":["../src/misc/createSingleton.ts","../src/bridge/events/listening/unsubscribe.ts","../src/bridge/events/listening/subscribe.ts","../src/logger/Logger.ts","../src/debug/debug.ts","../src/events/event-emitter/EventEmitter.ts","../src/events/onWindow.ts","../src/misc/createCleanup.ts","../src/errors/SDKError.ts","../src/errors/createError.ts","../src/errors/errors.ts","../src/parsing/createTypeError.ts","../src/parsing/ValueParser/ValueParser.ts","../src/parsing/createValueParserGenerator.ts","../src/parsing/parsers/boolean.ts","../src/parsing/parseBySchema.ts","../src/parsing/toRecord.ts","../src/parsing/parsers/json.ts","../src/parsing/parsers/number.ts","../src/parsing/parsers/string.ts","../src/bridge/parseMessage.ts","../src/bridge/events/event-handlers/cleanupEventHandlers.ts","../src/bridge/events/event-handlers/emitMiniAppsEvent.ts","../src/bridge/events/event-handlers/defineEventHandlers.ts","../src/bridge/events/event-emitter/createMiniAppsEventEmitter.ts","../src/bridge/events/event-emitter/singleton.ts","../src/bridge/events/listening/off.ts","../src/bridge/events/listening/on.ts","../src/misc/isRecord.ts","../src/version/compareVersions.ts","../src/supports/supports.ts","../src/env/hasExternalNotify.ts","../src/env/hasWebviewProxy.ts","../src/env/isIframe.ts","../src/bridge/target-origin.ts","../src/bridge/methods/postEvent.ts","../src/bridge/methods/createPostEvent.ts","../src/bridge/captureSameReq.ts","../src/timeout/createTimeoutError.ts","../src/timeout/withTimeout.ts","../src/bridge/request.ts","../src/bridge/invokeCustomMethod.ts","../src/env/isTMA.ts","../src/errors/isSDKError.ts","../src/errors/isSDKErrorOfType.ts","../src/env/initWeb.ts","../src/parsing/parsers/date.ts","../src/parsing/parsers/searchParams.ts","../src/components/InitData/parsers/chat.ts","../src/components/InitData/parsers/user.ts","../src/components/InitData/parsers/initData.ts","../src/colors/isRGB.ts","../src/colors/isRGBShort.ts","../src/colors/toRGB.ts","../src/parsing/parsers/rgb.ts","../src/components/ThemeParams/keys.ts","../src/components/ThemeParams/parsing/themeParams.ts","../src/launch-params/parseLaunchParams.ts","../src/launch-params/retrieveFromUrl.ts","../src/launch-params/retrieveFromLocation.ts","../src/navigation/getFirstNavigationEntry.ts","../src/launch-params/retrieveFromPerformance.ts","../src/storage/storage.ts","../src/launch-params/retrieveFromStorage.ts","../src/components/ThemeParams/parsing/serializeThemeParams.ts","../src/launch-params/serializeLaunchParams.ts","../src/launch-params/saveToStorage.ts","../src/launch-params/retrieveLaunchParams.ts"],"sourcesContent":["/**\n * Creates resettable singleton. We mostly need it for test purposes.\n * @param create - function which creates singleton entity.\n * @param onReset - function which will be called in case, singleton was reset.\n */\nexport function createSingleton<T>(\n create: (reset: () => void) => T,\n onReset?: (entity: T) => void,\n): [\n /**\n * Returns singleton entity.\n */\n get: () => T,\n /**\n * Resets last stored entity.\n */\n reset: () => void,\n] {\n let cached: T | undefined;\n const reset = () => {\n cached !== undefined && onReset && onReset(cached);\n cached = undefined;\n };\n\n return [() => (cached === undefined ? cached = create(reset) : cached), reset];\n}\n","import { miniAppsEventEmitter, resetMiniAppsEventEmitter } from '../event-emitter/singleton.js';\nimport type { MiniAppsSubscribeListener } from '../types.js';\n\n/**\n * Removes global event listener.\n * @param listener - event listener.\n */\nexport function unsubscribe(listener: MiniAppsSubscribeListener): void {\n const ee = miniAppsEventEmitter();\n const { count } = ee;\n ee.unsubscribe(listener);\n\n // If event emitter now has no listeners, we can make a cleanup.\n if (count && !ee.count) {\n resetMiniAppsEventEmitter();\n }\n}\n","import type { RemoveEventListenerFn } from '@/events/types.js';\n\nimport { miniAppsEventEmitter } from '../event-emitter/singleton.js';\nimport { unsubscribe } from '../listening/unsubscribe.js';\nimport type { MiniAppsSubscribeListener } from '../types.js';\n\n/**\n * Subscribes to all events sent from the native Telegram application.\n * @param listener - event listener to bind.\n * @returns Function to remove bound event listener.\n */\nexport function subscribe(listener: MiniAppsSubscribeListener): RemoveEventListenerFn {\n miniAppsEventEmitter().subscribe(listener);\n return () => unsubscribe(listener);\n}\n","/**\n * Message log level.\n */\nexport type LogLevel = 'log' | 'error';\n\nexport interface LoggerOptions {\n bgColor?: string;\n textColor?: string;\n}\n\nexport class Logger implements Pick<Console, 'log' | 'error'> {\n constructor(\n private readonly scope: string,\n private readonly options: LoggerOptions = {},\n ) {\n }\n\n /**\n * Prints message into a console in case, logger is currently enabled.\n * @param level - log level.\n * @param args - arguments.\n */\n private print(level: LogLevel, ...args: any[]): void {\n const now = new Date();\n const date = Intl\n .DateTimeFormat('en-GB', {\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit',\n fractionalSecondDigits: 3,\n timeZone: 'UTC',\n })\n .format(now);\n\n const { textColor, bgColor } = this.options;\n const commonCss = 'font-weight: bold;padding: 0 5px;border-radius:5px';\n\n console[level](\n `%c${date}%c / %c${this.scope}`,\n `${commonCss};background-color: lightblue;color:black`,\n '',\n `${commonCss};${textColor ? `color:${textColor};` : ''}${bgColor ? `background-color:${bgColor}` : ''}`,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n ...args,\n );\n }\n\n /**\n * Prints error message into a console.\n * @param args\n */\n error(...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n this.print('error', ...args);\n }\n\n /**\n * Prints log message into a console.\n * @param args\n */\n log(...args: any[]): void {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n this.print('log', ...args);\n }\n}\n","import { subscribe } from '@/bridge/events/listening/subscribe.js';\nimport { unsubscribe } from '@/bridge/events/listening/unsubscribe.js';\nimport { Logger } from '@/logger/Logger.js';\nimport type { MiniAppsSubscribeListener } from '@/bridge/events/types.js';\n\nexport const logger = new Logger('SDK', {\n bgColor: 'forestgreen',\n textColor: 'white',\n});\n\nlet debugEnabled = false;\n\nconst onEvent: MiniAppsSubscribeListener = ({ name, payload }) => {\n logger.log('Event received:', payload ? { name, payload } : { name });\n};\n\n/**\n * Sets new debug mode. Enabling debug mode leads to printing additional messages in the console,\n * related to the processes inside the package.\n * @param enable - should debug be enabled.\n */\nexport function setDebug(enable: boolean): void {\n if (debugEnabled !== enable) {\n debugEnabled = enable;\n enable ? subscribe(onEvent) : unsubscribe(onEvent);\n }\n}\n\n/**\n * Logs info message into the console.\n * @param args - additional arguments.\n */\nexport function log(...args: any[]): void {\n if (debugEnabled) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n logger.log(...args);\n }\n}\n","import type { RemoveEventListenerFn } from '../types.js';\nimport type {\n EmptyEventName,\n EventListener,\n EventName,\n EventParams,\n NonEmptyEventName,\n SubscribeListener,\n} from './types.js';\n\nexport class EventEmitter<Schema> {\n private readonly listeners: Map<\n string,\n [listener: EventListener<any>, once?: boolean][]\n > = new Map();\n\n private listenersCount = 0;\n\n private subscribeListeners: SubscribeListener<Schema>[] = [];\n\n /**\n * Removes all event listeners.\n */\n clear() {\n this.listeners.clear();\n this.subscribeListeners = [];\n }\n\n /**\n * Returns count of bound listeners.\n */\n get count(): number {\n return this.listenersCount + this.subscribeListeners.length;\n }\n\n /**\n * Emits known event which has no parameters.\n * @param event - event name.\n */\n emit<E extends EmptyEventName<Schema>>(event: E): void;\n\n /**\n * Emits known event which has parameters.\n * @param event - event name.\n * @param args - list of event listener arguments.\n */\n emit<E extends NonEmptyEventName<Schema>>(event: E, ...args: EventParams<Schema[E]>): void;\n\n emit(event: EventName<Schema>, ...args: any[]): void {\n this.subscribeListeners.forEach((l) => l({\n event,\n args: args as EventParams<Schema[EventName<Schema>]>,\n }));\n\n const listeners = this.listeners.get(event) || [];\n\n listeners.forEach(([listener, once]) => {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n listener(...args);\n if (once) {\n this.off(event, listener);\n }\n });\n }\n\n /**\n * Adds new event listener.\n * @param event - event name.\n * @param listener - event listener.\n * @param once - should listener be called only once.\n * @returns Function to remove bound event listener.\n */\n on<E extends EventName<Schema>>(\n event: E,\n listener: EventListener<Schema[E]>,\n once?: boolean,\n ): RemoveEventListenerFn {\n let listeners = this.listeners.get(event);\n if (!listeners) {\n this.listeners.set(event, listeners = []);\n }\n\n listeners.push([listener, once]);\n this.listenersCount += 1;\n\n return () => this.off(event, listener);\n }\n\n /**\n * Removes event listener. In case, specified listener was bound several times, it removes\n * only a single one.\n * @param event - event name.\n * @param listener - event listener.\n */\n off<E extends EventName<Schema>>(event: E, listener: EventListener<Schema[E]>): void {\n const listeners = this.listeners.get(event) || [];\n for (let i = 0; i < listeners.length; i += 1) {\n if (listener === listeners[i][0]) {\n listeners.splice(i, 1);\n this.listenersCount -= 1;\n return;\n }\n }\n }\n\n /**\n * Adds a new event listener for all events.\n * @param listener - event listener.\n * @returns Function to remove event listener.\n */\n subscribe(listener: SubscribeListener<Schema>): RemoveEventListenerFn {\n this.subscribeListeners.push(listener);\n return () => this.unsubscribe(listener);\n }\n\n /**\n * Removes global event listener. In case, specified listener was bound several times, it removes\n * only a single one.\n * @param listener - event listener.\n */\n unsubscribe(listener: SubscribeListener<Schema>): void {\n for (let i = 0; i < this.subscribeListeners.length; i += 1) {\n if (this.subscribeListeners[i] === listener) {\n this.subscribeListeners.splice(i, 1);\n return;\n }\n }\n }\n}\n","import type { RemoveEventListenerFn } from './types.js';\n\n/**\n * Adds new event listener using window.addEventListener.\n * @param type - event name.\n * @param listener - event listener.\n * @param options - listening options.\n * @returns Function to remove event listener.\n */\nexport function onWindow<K extends keyof WindowEventMap>(\n type: K,\n listener: (this: Window, ev: WindowEventMap[K]) => any,\n options?: boolean | AddEventListenerOptions,\n): RemoveEventListenerFn {\n window.addEventListener(type, listener, options);\n return () => window.removeEventListener(type, listener, options);\n}\n","import { CleanupFn } from '@/types/index.js';\n\n/**\n * Returns a tuple, containing function to add cleanup, call cleanup, and flag showing whether\n * cleanup was called. Cleanup will not be performed in case, it was done before.\n */\nexport function createCleanup(...fns: (CleanupFn | CleanupFn[])[]): [\n add: (fn: CleanupFn) => void,\n cleanup: () => void,\n cleanedUp: boolean,\n] {\n let cleanedUp = false;\n const cache = fns.flat(1);\n\n return [\n (fn) => !cleanedUp && cache.push(fn),\n () => {\n if (!cleanedUp) {\n cleanedUp = true;\n cache.forEach(clean => clean());\n }\n },\n cleanedUp,\n ];\n}","import type { ErrorType } from './errors.js';\n\n/**\n * Error used across the SDK.\n */\nexport class SDKError extends Error {\n constructor(public readonly type: ErrorType, message?: string, cause?: unknown) {\n super(message, { cause });\n Object.setPrototypeOf(this, SDKError.prototype);\n }\n}\n","import { SDKError } from './SDKError.js';\nimport type { ErrorType } from './errors.js';\n\n/**\n * Creates new error using specified type and message.\n * @param type - error code.\n * @param message - error message.\n * @param cause - original error.\n */\nexport function createError(type: ErrorType, message: string, cause?: unknown): SDKError {\n return new SDKError(type, message, cause);\n}\n","/**\n * Specified Mini Apps method is unsupported.\n */\nexport const ERR_METHOD_UNSUPPORTED = 'ERR_METHOD_UNSUPPORTED';\n\n/**\n * Specified Mini Apps method parameter is unsupported.\n */\nexport const ERR_METHOD_PARAMETER_UNSUPPORTED = 'ERR_METHOD_PARAMETER_UNSUPPORTED';\n\n/**\n * Current environment is not Telegram application.\n */\nexport const ERR_UNKNOWN_ENV = 'ERR_UNKNOWN_ENV';\n\n/**\n * Telegram application returned and error while invoking custom method.\n */\nexport const ERR_INVOKE_CUSTOM_METHOD_RESPONSE = 'ERR_INVOKE_CUSTOM_METHOD_RESPONSE';\n\n/**\n * Timeout reached.\n */\nexport const ERR_TIMED_OUT = 'ERR_TIMED_OUT';\n\n/**\n * Value has unexpected type.\n */\nexport const ERR_UNEXPECTED_TYPE = 'ERR_UNEXPECTED_TYPE';\n\n/**\n * Something went wrong during value parsing.\n */\nexport const ERR_PARSE = 'ERR_PARSE';\n\n/**\n * Navigation entries list is empty.\n */\nexport const ERR_NAVIGATION_HISTORY_EMPTY = 'ERR_NAVIGATION_LIST_EMPTY';\n\n/**\n * Navigation entries cursor is invalid.\n */\nexport const ERR_NAVIGATION_INDEX_INVALID = 'ERR_NAVIGATION_CURSOR_INVALID';\n\n/**\n * Navigation entries item is invalid.\n */\nexport const ERR_NAVIGATION_ITEM_INVALID = 'ERR_NAVIGATION_ITEM_INVALID';\n\n/**\n * SSR component initialization failed.\n */\nexport const ERR_SSR_INIT = 'ERR_SSR_INIT';\n\n/**\n * Path starts from the invalid base.\n */\nexport const ERR_INVALID_PATH_BASE = 'ERR_INVALID_PATH_BASE';\n\nexport type ErrorType =\n | typeof ERR_METHOD_UNSUPPORTED\n | typeof ERR_METHOD_PARAMETER_UNSUPPORTED\n | typeof ERR_UNKNOWN_ENV\n | typeof ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n | typeof ERR_TIMED_OUT\n | typeof ERR_PARSE\n | typeof ERR_UNEXPECTED_TYPE\n | typeof ERR_NAVIGATION_HISTORY_EMPTY\n | typeof ERR_NAVIGATION_INDEX_INVALID\n | typeof ERR_NAVIGATION_ITEM_INVALID\n | typeof ERR_SSR_INIT\n | typeof ERR_INVALID_PATH_BASE;\n","import { createError } from '@/errors/createError.js';\nimport { ERR_UNEXPECTED_TYPE } from '@/errors/errors.js';\nimport type { SDKError } from '@/errors/SDKError.js';\n\n/**\n * Creates instance of TypeError stating, that value has unexpected type.\n */\nexport function createTypeError(): SDKError {\n return createError(ERR_UNEXPECTED_TYPE, 'Value has unexpected type');\n}\n","import { createError } from '@/errors/createError.js';\nimport { ERR_PARSE } from '@/errors/errors.js';\n\nimport type { Parser } from '../types.js';\nimport type { ValueParserOptionalResult, ValueParserParseResult } from './types.js';\n\nexport class ValueParser<ResultType, IsOptional extends boolean> {\n constructor(\n protected parser: Parser<ResultType>,\n protected isOptional: IsOptional,\n protected type?: string,\n ) {\n }\n\n /**\n * Attempts to parse passed value\n * @param value - value to parse.\n * @throws {SDKError} ERR_PARSE\n * @see ERR_PARSE\n */\n parse(value: unknown): ValueParserParseResult<ResultType, IsOptional> {\n // In case, parsing result is specified as optional, and passed value is considered as empty,\n // we can return undefined. Otherwise, pass to parser.\n if (this.isOptional && value === undefined) {\n return undefined as ValueParserParseResult<ResultType, IsOptional>;\n }\n\n try {\n return this.parser(value) as ValueParserParseResult<ResultType, IsOptional>;\n } catch (cause) {\n throw createError(\n ERR_PARSE,\n `Unable to parse value${this.type ? ` as ${this.type}` : ''}`,\n cause,\n );\n }\n }\n\n optional(): ValueParserOptionalResult<this, ResultType> {\n this.isOptional = true as IsOptional;\n return this as ValueParserOptionalResult<this, ResultType>;\n }\n}\n","import { ValueParser } from './ValueParser/ValueParser.js';\nimport type { Parser } from './types.js';\n\nexport type ValueParserGenerator<T> = () => ValueParser<T, false>;\n\n/**\n * Creates function which generates new scalar value parser based on the specified one.\n * @param parser - parser to use as basic.\n * @param type - type name.\n */\nexport function createValueParserGenerator<T>(\n parser: Parser<T>,\n type?: string,\n): ValueParserGenerator<T> {\n return () => new ValueParser(parser, false, type);\n}\n","import { createTypeError } from '../createTypeError.js';\nimport { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as boolean.\n */\nexport const boolean: ValueParserGenerator<boolean> = createValueParserGenerator((value) => {\n if (typeof value === 'boolean') {\n return value;\n }\n const asString = String(value);\n\n if (asString === '1' || asString === 'true') {\n return true;\n }\n\n if (asString === '0' || asString === 'false') {\n return false;\n }\n\n throw createTypeError();\n}, 'boolean');\n","import { createError } from '@/errors/createError.js';\nimport { ERR_PARSE } from '@/errors/errors.js';\n\nimport type { Parser, Schema } from './types.js';\n\n/**\n * Parses external value by specified schema. Functions iterates over each schema field\n * and uses getField function to get its value from the external source.\n * @param schema - object schema.\n * @param getField - function which gets external value by its field name.\n */\nexport function parseBySchema<T>(\n schema: Schema<T>,\n getField: (field: string) => unknown,\n): T {\n const result = {} as T;\n\n for (const field in schema) {\n const definition = schema[field];\n if (!definition) {\n continue;\n }\n\n let from: string;\n let parser: Parser<any>;\n\n // In case, definition has \"type\" property, then SchemaFieldDetailed was passed.\n if (typeof definition === 'function' || 'parse' in definition) {\n // Otherwise we are working with either parser function or instance.\n from = field;\n parser = typeof definition === 'function' ? definition : definition.parse.bind(definition);\n } else {\n const { type: definitionType } = definition;\n\n from = definition.from || field;\n parser = typeof definitionType === 'function'\n ? definitionType\n : definitionType.parse.bind(definitionType);\n }\n\n try {\n const parsedValue = parser(getField(from));\n if (parsedValue !== undefined) {\n (result as any)[field] = parsedValue;\n }\n } catch (error) {\n throw createError(ERR_PARSE, `Unable to parse field \"${field}\"`, error);\n }\n }\n\n return result;\n}\n","import { createTypeError } from './createTypeError.js';\n\n/**\n * Converts value to record.\n * @param value - value to convert.\n * @throws {Error} Value passed as a string does not represent JSON object.\n * @throws {Error} Value is not convertable.\n */\nexport function toRecord(value: unknown): Record<string, unknown> {\n let formattedValue: any = value;\n\n // Convert value to JSON in case, it is string. We expect value to be JSON string.\n if (typeof formattedValue === 'string') {\n formattedValue = JSON.parse(formattedValue);\n }\n\n // We expect json to be usual object.\n if (\n typeof formattedValue !== 'object'\n || formattedValue === null\n || Array.isArray(formattedValue)\n ) {\n throw createTypeError();\n }\n\n return formattedValue as Record<string, unknown>;\n}\n","import { parseBySchema } from '../parseBySchema.js';\nimport { toRecord } from '../toRecord.js';\nimport { ValueParser } from '../ValueParser/ValueParser.js';\nimport type { Schema } from '../types.js';\n\n/**\n * Creates new Json parser according to passed schema.\n * @param schema - object schema.\n * @param type - parser type name.\n */\nexport function json<T>(schema: Schema<T>, type?: string): ValueParser<T, false> {\n return new ValueParser((value) => {\n const record = toRecord(value);\n return parseBySchema(schema, (field) => record[field]);\n }, false, type);\n}\n","import { createTypeError } from '../createTypeError.js';\nimport { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as number.\n */\nexport const number: ValueParserGenerator<number> = createValueParserGenerator((value) => {\n if (typeof value === 'number') {\n return value;\n }\n\n if (typeof value === 'string') {\n const num = Number(value);\n\n if (!Number.isNaN(num)) {\n return num;\n }\n }\n\n throw createTypeError();\n}, 'number');\n","import { createTypeError } from '../createTypeError.js';\nimport { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as string.\n */\nexport const string: ValueParserGenerator<string> = createValueParserGenerator((value) => {\n if (typeof value === 'string' || typeof value === 'number') {\n return value.toString();\n }\n throw createTypeError();\n}, 'string');\n","import { json } from '@/parsing/parsers/json.js';\nimport { string } from '@/parsing/parsers/string.js';\n\n/**\n * Message format used in communication between client and Telegram applications.\n */\nexport interface MiniAppsMessage {\n /**\n * Event name.\n */\n eventType: string;\n /**\n * Event parameters.\n */\n eventData?: unknown;\n}\n\n/**\n * Parses value as a message between client and Telegram applications.\n * @param value - value to parse.\n */\nexport function parseMessage(value: unknown): MiniAppsMessage {\n return json({\n eventType: string(),\n eventData: (v) => v,\n }).parse(value);\n}\n","/**\n * Removes global event handlers, used by the package.\n */\nexport function cleanupEventHandlers(): void {\n ['TelegramGameProxy_receiveEvent', 'TelegramGameProxy', 'Telegram'].forEach((prop) => {\n delete window[prop as keyof Window];\n });\n}\n","/**\n * Emits event sent from Telegram native application like it was sent in\n * default web environment between 2 iframes. It dispatches new MessageEvent\n * and expects it to be handled via `window.addEventListener('message', ...)`\n * as developer would do it to handle messages sent from the parent iframe.\n * @param eventType - event name.\n * @param eventData - event payload.\n */\nexport function emitMiniAppsEvent(eventType: string, eventData: unknown): void {\n window.dispatchEvent(new MessageEvent('message', {\n data: JSON.stringify({ eventType, eventData }),\n // We specify window.parent to imitate the case, the parent iframe sent us this event.\n source: window.parent,\n }));\n}\n","import { emitMiniAppsEvent } from './emitMiniAppsEvent.js';\n\n/**\n * Defines special handlers by known paths, which are recognized by\n * Telegram as ports to receive events. This function also sets special\n * function in global window object to prevent duplicate declaration.\n */\nexport function defineEventHandlers() {\n // Iterate over each path, where \"receiveEvent\" function should be\n // defined. This function is called by external environment in case,\n // it wants to emit some event.\n [\n ['TelegramGameProxy_receiveEvent'], // Windows Phone.\n ['TelegramGameProxy', 'receiveEvent'], // Desktop.\n ['Telegram', 'WebView', 'receiveEvent'], // Android and iOS.\n ].forEach((path) => {\n // Path starts from the \"window\" object.\n let pointer = window as any;\n\n path.forEach((item, idx, arr) => {\n // We are on the last iteration, where function property name is passed.\n if (idx === arr.length - 1) {\n pointer[item] = emitMiniAppsEvent;\n return;\n }\n\n if (!(item in pointer)) {\n pointer[item] = {};\n }\n pointer = pointer[item];\n });\n });\n}\n","import { logger } from '@/debug/debug.js';\nimport { EventEmitter } from '@/events/event-emitter/EventEmitter.js';\nimport { onWindow } from '@/events/onWindow.js';\nimport { createCleanup } from '@/misc/createCleanup.js';\nimport { boolean } from '@/parsing/parsers/boolean.js';\nimport { json } from '@/parsing/parsers/json.js';\nimport { number } from '@/parsing/parsers/number.js';\nimport { string } from '@/parsing/parsers/string.js';\n\nimport { type MiniAppsMessage, parseMessage } from '../../parseMessage.js';\nimport { cleanupEventHandlers } from '../event-handlers/cleanupEventHandlers.js';\nimport { defineEventHandlers } from '../event-handlers/defineEventHandlers.js';\nimport type {\n MiniAppsEventName,\n MiniAppsEventPayload,\n MiniAppsEventEmitter,\n MiniAppsEvents,\n} from '../types.js';\n\n/**\n * Parsers for problematic Mini Apps events.\n */\nconst parsers: {\n [E in MiniAppsEventName]?: {\n parse(value: unknown): MiniAppsEventPayload<E>;\n }\n} = {\n clipboard_text_received: json({\n req_id: string(),\n data: (value) => (value === null ? value : string().optional().parse(value)),\n }),\n custom_method_invoked: json({\n req_id: string(),\n result: (value) => value,\n error: string().optional(),\n }),\n popup_closed: {\n parse(value) {\n return json({\n button_id: (value) => (\n value === null || value === undefined\n ? undefined\n : string().parse(value)\n ),\n }).parse(value ?? {});\n },\n },\n viewport_changed: json({\n height: number(),\n width: (value) => (\n value === null || value === undefined\n ? window.innerWidth\n : number().parse(value)\n ),\n is_state_stable: boolean(),\n is_expanded: boolean(),\n }),\n};\n\n/**\n * Creates new event emitter, which handles events from the Telegram application.\n */\nexport function createMiniAppsEventEmitter(): [\n /**\n * Created event emitter.\n */\n emitter: MiniAppsEventEmitter,\n /**\n * Function to dispose created emitter.\n */\n dispose: () => void,\n] {\n // We use this event emitter for better developer experience, using the subscribe method.\n const subEmitter = new EventEmitter<{ event: any[] }>();\n\n // Event emitter processing all the incoming events.\n const mainEmitter = new EventEmitter<MiniAppsEvents>();\n\n mainEmitter.subscribe(event => {\n subEmitter.emit('event', { name: event.event, payload: event.args[0] });\n });\n\n // Define event handles, which will proxy native method calls to their web version.\n defineEventHandlers();\n\n // List of cleanup functions, which should be called on dispose.\n const [, cleanup] = createCleanup(\n // Don't forget to remove created handlers.\n cleanupEventHandlers,\n // Add \"resize\" event listener to make sure, we always have fresh viewport information.\n // Desktop version of Telegram is sometimes not sending the viewport_changed\n // event. For example, when the MainButton is shown. That's why we should\n // add our own listener to make sure, viewport information is always fresh.\n // Issue: https://github.com/Telegram-Mini-Apps/tma.js/issues/10\n onWindow('resize', () => {\n mainEmitter.emit('viewport_changed', {\n width: window.innerWidth,\n height: window.innerHeight,\n is_state_stable: true,\n is_expanded: true,\n });\n }),\n // Add listener, which handles events sent from the Telegram web application and also events\n // generated by the local emitEvent function.\n onWindow('message', (event) => {\n // Ignore non-parent window messages.\n if (event.source !== window.parent) {\n return;\n }\n\n // Parse incoming event data.\n let message: MiniAppsMessage;\n try {\n message = parseMessage(event.data);\n } catch {\n // We ignore incorrect messages as they could be generated by any other code.\n return;\n }\n\n const { eventType, eventData } = message;\n const parser = parsers[eventType as keyof typeof parsers];\n\n try {\n const data = parser ? parser.parse(eventData) : eventData;\n mainEmitter.emit(...(data ? [eventType, data] : [eventType]) as [any, any]);\n } catch (cause) {\n logger.error(\n `An error occurred processing the \"${eventType}\" event from the Telegram application.\\nPlease, file an issue here:\\nhttps://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,\n message,\n cause,\n );\n }\n }),\n // Clear emitters.\n () => subEmitter.clear(),\n () => mainEmitter.clear(),\n );\n\n return [{\n on: mainEmitter.on.bind(mainEmitter),\n off: mainEmitter.off.bind(mainEmitter),\n subscribe(listener) {\n return subEmitter.on('event', listener);\n },\n unsubscribe(listener) {\n subEmitter.off('event', listener);\n },\n get count() {\n return mainEmitter.count + subEmitter.count;\n },\n }, cleanup];\n}\n","import { createSingleton } from '@/misc/createSingleton.js';\n\nimport { createMiniAppsEventEmitter } from './createMiniAppsEventEmitter.js';\nimport type { MiniAppsEventEmitter } from '../types.js';\n\nconst [get, resetMiniAppsEventEmitter] = createSingleton(\n (reset) => {\n const [emitter, cleanup] = createMiniAppsEventEmitter();\n\n // Rewire \"off\" method and make it reset singleton if no event listeners left.\n const off = emitter.off.bind(emitter);\n emitter.off = (event, listener) => {\n const { count } = emitter;\n off(event, listener);\n\n // If event emitter now has no listeners, we can perform a reset.\n if (count && !emitter.count) {\n reset();\n }\n };\n\n return [emitter, cleanup] as const;\n },\n ([, cleanup]) => cleanup(),\n);\n\n/**\n * Returns Mini Apps event emitter singleton.\n */\nexport function miniAppsEventEmitter(): MiniAppsEventEmitter {\n return get()[0];\n}\n\nexport { resetMiniAppsEventEmitter };\n","import { miniAppsEventEmitter } from '../event-emitter/singleton.js';\nimport type { MiniAppsEventListener, MiniAppsEventName } from '../types.js';\n\n/**\n * Removes listener from specified event.\n * @param event - event to listen.\n * @param listener - event listener to remove.\n */\nexport function off<E extends MiniAppsEventName>(\n event: E,\n listener: MiniAppsEventListener<E>,\n): void {\n miniAppsEventEmitter().off(event, listener);\n}\n","import type { RemoveEventListenerFn } from '@/events/types.js';\n\nimport { miniAppsEventEmitter } from '../event-emitter/singleton.js';\nimport type { MiniAppsEventListener, MiniAppsEventName } from '../types.js';\n\n/**\n * Adds new listener to the specified event. Returns handler\n * which allows to stop listening to event.\n * @param event - event name.\n * @param listener - event listener.\n * @param once - should listener be called only once.\n * @returns Function to remove bound event listener.\n */\nexport function on<E extends MiniAppsEventName>(\n event: E,\n listener: MiniAppsEventListener<E>,\n once?: boolean,\n): RemoveEventListenerFn {\n return miniAppsEventEmitter().on(event, listener, once);\n}\n","/**\n * States that passed value is Record and not Array.\n * @param value - value to check.\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n","import type { Version } from './types.js';\n\n/**\n * Returns 1 in case, version \"a\" is greater than \"b\".\n * Returns 0 in case, version \"a\" equal to \"b\".\n * Returns -1 in case, version \"a\" is lower than \"b\".\n * @param a - first version.\n * @param b - second version.\n */\nexport function compareVersions(a: Version, b: Version): number {\n // Split both of the version by dot.\n const aParts = a.split('.');\n const bParts = b.split('.');\n\n // Compute maximum length.\n const len = Math.max(aParts.length, bParts.length);\n\n // Iterate over each part of version and compare them. In case, part is\n // missing, assume its value is equal to 0.\n for (let i = 0; i < len; i += 1) {\n const aVal = parseInt(aParts[i] || '0', 10);\n const bVal = parseInt(bParts[i] || '0', 10);\n\n if (aVal === bVal) {\n continue;\n }\n return aVal > bVal ? 1 : -1;\n }\n return 0;\n}\n","import { compareVersions } from '@/version/compareVersions.js';\nimport type {\n MiniAppsMethodName,\n MiniAppsMethodVersionedParams,\n MiniAppsMethodWithVersionedParams,\n} from '@/bridge/methods/types/methods.js';\nimport type { Version } from '@/version/types.js';\n\n/**\n * Returns true if \"a\" version is less than or equal to \"b\" version.\n * @param a\n * @param b\n */\nfunction versionLessOrEqual(a: Version, b: Version): boolean {\n return compareVersions(a, b) <= 0;\n}\n\n/**\n * Returns true in case, passed parameter in specified method is supported.\n * @param method - method name\n * @param param - method parameter\n * @param inVersion - platform version.\n */\nexport function supports<M extends MiniAppsMethodWithVersionedParams>(\n method: M,\n param: MiniAppsMethodVersionedParams<M>,\n inVersion: Version,\n): boolean;\n\n/**\n * Returns true in case, specified method is supported in passed version.\n * @param method - method name.\n * @param inVersion - platform version.\n */\nexport function supports(method: MiniAppsMethodName, inVersion: Version): boolean;\n\nexport function supports(\n method: MiniAppsMethodName,\n paramOrVersion: Version | string,\n inVersion?: string,\n): boolean {\n // Method name, parameter, target version.\n if (typeof inVersion === 'string') {\n if (method === 'web_app_open_link') {\n if (paramOrVersion === 'try_instant_view') {\n return versionLessOrEqual('6.4', inVersion);\n }\n if (paramOrVersion === 'try_browser') {\n return versionLessOrEqual('7.6', inVersion);\n }\n }\n\n if (method === 'web_app_set_header_color') {\n if (paramOrVersion === 'color') {\n return versionLessOrEqual('6.9', inVersion);\n }\n }\n\n if (method === 'web_app_close' && paramOrVersion === 'return_back') {\n return versionLessOrEqual('7.6', inVersion);\n }\n }\n\n switch (method) {\n case 'web_app_open_tg_link':\n case 'web_app_open_invoice':\n case 'web_app_setup_back_button':\n case 'web_app_set_background_color':\n case 'web_app_set_header_color':\n case 'web_app_trigger_haptic_feedback':\n return versionLessOrEqual('6.1', paramOrVersion);\n case 'web_app_open_popup':\n return versionLessOrEqual('6.2', paramOrVersion);\n case 'web_app_close_scan_qr_popup':\n case 'web_app_open_scan_qr_popup':\n case 'web_app_read_text_from_clipboard':\n return versionLessOrEqual('6.4', paramOrVersion);\n case 'web_app_switch_inline_query':\n return versionLessOrEqual('6.7', paramOrVersion);\n case 'web_app_invoke_custom_method':\n case 'web_app_request_write_access':\n case 'web_app_request_phone':\n return versionLessOrEqual('6.9', paramOrVersion);\n case 'web_app_setup_settings_button':\n return versionLessOrEqual('6.10', paramOrVersion);\n case 'web_app_biometry_get_info':\n case 'web_app_biometry_open_settings':\n case 'web_app_biometry_request_access':\n case 'web_app_biometry_request_auth':\n case 'web_app_biometry_update_token':\n return versionLessOrEqual('7.2', paramOrVersion);\n default:\n return [\n 'iframe_ready',\n 'iframe_will_reload',\n 'web_app_close',\n 'web_app_data_send',\n 'web_app_expand',\n 'web_app_open_link',\n 'web_app_ready',\n 'web_app_request_theme',\n 'web_app_request_viewport',\n 'web_app_setup_main_button',\n 'web_app_setup_closing_behavior',\n ].includes(method);\n }\n}\n","import { isRecord } from '@/misc/isRecord.js';\n\n/**\n * Returns true in case, passed value contains path `external.notify` property and `notify` is a\n * function.\n * @param value - value to check.\n */\nexport function hasExternalNotify<T extends object>(value: T): value is (\n T & {\n external: {\n notify: (...args: any) => any;\n };\n}) {\n return 'external' in value\n && isRecord(value.external)\n && 'notify' in value.external\n && typeof value.external.notify === 'function';\n}\n","import { isRecord } from '@/misc/isRecord.js';\n\n/**\n * Returns true in case, passed value contains path `TelegramWebviewProxy.postEvent` property and\n * `postEvent` is a function.\n * @param value - value to check.\n */\nexport function hasWebviewProxy<T extends {}>(value: T): value is (\n T & {\n TelegramWebviewProxy: {\n postEvent: (...args: unknown[]) => unknown;\n }\n}) {\n return 'TelegramWebviewProxy' in value\n && isRecord(value.TelegramWebviewProxy)\n && 'postEvent' in value.TelegramWebviewProxy\n && typeof value.TelegramWebviewProxy.postEvent === 'function';\n}\n","/**\n * @see https://stackoverflow.com/a/326076\n * @returns True, if current environment is iframe.\n */\nexport function isIframe(): boolean {\n try {\n return window.self !== window.top;\n } catch {\n return true;\n }\n}\n","const INITIAL_TARGET_ORIGIN = 'https://web.telegram.org'\n\nlet currentTargetOrigin = INITIAL_TARGET_ORIGIN;\n\n/**\n * Sets a new global targetOrigin, used by the `postEvent` method.\n * The default value is \"https://web.telegram.org\".\n * You don't need to use this method until you know what you are doing.\n *\n * This method could be used for test purposes.\n * @param value - new target origin.\n * @see postEvent\n */\nexport function setTargetOrigin(value: string): void {\n currentTargetOrigin = value;\n}\n\n/**\n * Sets the initial target origin.\n */\nexport function resetTargetOrigin(): void {\n setTargetOrigin(INITIAL_TARGET_ORIGIN);\n}\n\n/**\n * Returns current global target origin.\n */\nexport function targetOrigin(): string {\n return currentTargetOrigin;\n}\n","import { log } from '@/debug/debug.js';\nimport { hasExternalNotify } from '@/env/hasExternalNotify.js';\nimport { hasWebviewProxy } from '@/env/hasWebviewProxy.js';\nimport { isIframe } from '@/env/isIframe.js';\nimport { createError } from '@/errors/createError.js';\nimport { ERR_UNKNOWN_ENV } from '@/errors/errors.js';\n\nimport { targetOrigin as targetOriginFn } from '../target-origin.js';\nimport type {\n MiniAppsMethodName,\n MiniAppsMethodParams,\n MiniAppsMethodWithOptionalParams,\n MiniAppsMethodWithoutParams,\n MiniAppsMethodWithRequiredParams,\n} from './types/methods.js';\n\ninterface PostEventOptions {\n /**\n * Origin used while posting a message.\n *\n * This option is only used if the current environment is browser (Web version of Telegram)\n * and could be used for test purposes.\n * @default 'https://web.telegram.org'\n */\n targetOrigin?: string;\n}\n\nexport type PostEvent = typeof postEvent;\n\n/**\n * Calls Mini Apps method with optional parameters.\n * @param method - method name.\n * @param params - method parameters.\n * @param options - posting options.\n * @throws {SDKError} ERR_UNKNOWN_ENV\n * @see ERR_UNKNOWN_ENV\n */\nexport function postEvent<Method extends MiniAppsMethodWithOptionalParams>(\n method: Method,\n params?: MiniAppsMethodParams<Method>,\n options?: PostEventOptions,\n): void;\n\n/**\n * Calls Mini Apps method without parameters.\n * @param method - method name.\n * @param options - posting options.\n * @throws {SDKError} ERR_UNKNOWN_ENV\n * @see ERR_UNKNOWN_ENV\n */\nexport function postEvent(\n method: MiniAppsMethodWithoutParams | MiniAppsMethodWithOptionalParams,\n options?: PostEventOptions,\n): void;\n\n/**\n * Calls Mini Apps method with parameters.\n * @param method - method name.\n * @param params - method parameters.\n * @param options - posting options.\n * @throws {SDKError} ERR_UNKNOWN_ENV\n * @see ERR_UNKNOWN_ENV\n */\nexport function postEvent<Method extends MiniAppsMethodWithRequiredParams>(\n method: Method,\n params: MiniAppsMethodParams<Method>,\n options?: PostEventOptions,\n): void;\n\nexport function postEvent(\n eventType: MiniAppsMethodName,\n paramsOrOptions?: MiniAppsMethodParams<MiniAppsMethodName> | PostEventOptions,\n options?: PostEventOptions,\n): void {\n let postOptions: PostEventOptions = {};\n let eventData: any;\n\n if (!paramsOrOptions && !options) {\n // Parameters and options were not passed.\n postOptions = {};\n } else if (paramsOrOptions && options) {\n // Both parameters and options passed.\n postOptions = options;\n eventData = paramsOrOptions;\n } else if (paramsOrOptions) {\n // Only parameters were passed.\n if ('targetOrigin' in paramsOrOptions) {\n postOptions = paramsOrOptions;\n } else {\n eventData = paramsOrOptions;\n }\n }\n\n log('Posting event:', eventData\n ? { event: eventType, data: eventData }\n : { event: eventType });\n\n // Telegram Web.\n if (isIframe()) {\n return window.parent.postMessage(\n JSON.stringify({ eventType, eventData }),\n postOptions.targetOrigin || targetOriginFn(),\n );\n }\n\n // Telegram for Windows Phone or Android.\n if (hasExternalNotify(window)) {\n window.external.notify(JSON.stringify({ eventType, eventData }));\n return;\n }\n\n // Telegram for iOS and macOS.\n if (hasWebviewProxy(window)) {\n window.TelegramWebviewProxy.postEvent(eventType, JSON.stringify(eventData));\n return;\n }\n\n // Otherwise current environment is unknown, and we are not able to send event.\n throw createError(\n ERR_UNKNOWN_ENV,\n 'Unable to determine current environment and possible way to send event. You are probably trying to use Mini Apps method outside the Telegram application environment.',\n );\n}\n","import { createError } from '@/errors/createError.js';\nimport { ERR_METHOD_PARAMETER_UNSUPPORTED, ERR_METHOD_UNSUPPORTED } from '@/errors/errors.js';\nimport { isRecord } from '@/misc/isRecord.js';\nimport { supports } from '@/supports/supports.js';\nimport type { Version } from '@/version/types.js';\n\nimport { type PostEvent, postEvent } from './postEvent.js';\n\n/**\n * Creates a function which checks if specified method and parameters are supported.\n *\n * If method or parameters are unsupported, an error will be thrown.\n * @param version - Telegram Mini Apps version.\n * @throws {SDKError} ERR_METHOD_UNSUPPORTED\n * @throws {SDKError} ERR_METHOD_PARAMETER_UNSUPPORTED\n * @see ERR_METHOD_UNSUPPORTED\n * @see ERR_METHOD_PARAMETER_UNSUPPORTED\n */\nexport function createPostEvent(version: Version): PostEvent {\n return (method: any, params: any) => {\n // Firstly, check if a method is supported.\n // eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n if (!supports(method, version)) {\n throw createError(ERR_METHOD_UNSUPPORTED, `Method \"${method}\" is unsupported in Mini Apps version ${version}`);\n }\n\n // Method could use parameters, which are supported only in specific\n // versions of Mini Apps.\n // We are validating only those parameters, which are not backward compatible.\n if (\n isRecord(params)\n && method === 'web_app_set_header_color'\n && 'color' in params\n && !supports(method, 'color', version)\n ) {\n throw createError(\n ERR_METHOD_PARAMETER_UNSUPPORTED,\n `Parameter \"color\" of \"${method}\" method is unsupported in Mini Apps version ${version}`,\n );\n }\n\n return postEvent(method, params);\n };\n}\n","type CaptureSameReqFn = (payload: { req_id: string }) => boolean;\n\n/**\n * Returns a function which can be used in `request` function `capture` property to capture\n * the event with the same request identifier.\n * @param reqId - request identifier.\n */\nexport function captureSameReq(reqId: string): CaptureSameReqFn {\n return ({ req_id }) => req_id === reqId;\n}\n","import { createError } from '@/errors/createError.js';\nimport { ERR_TIMED_OUT } from '@/errors/errors.js';\nimport type { SDKError } from '@/errors/SDKError.js';\n\n/**\n * Creates new timeout error.\n * @param timeout - timeout in ms.\n */\nexport function createTimeoutError(timeout: number): SDKError {\n return createError(ERR_TIMED_OUT, `Timeout reached: ${timeout}ms`);\n}\n","import { createTimeoutError } from '@/timeout/createTimeoutError.js';\n\n/**\n * Runs passed function or promise with specified deadline presented via timeout argument.\n * @param funcOrPromise - function to execute or pending promise.\n * @param timeout - completion timeout.\n */\nexport function withTimeout<T>(\n funcOrPromise: Promise<T> | (() => Promise<T>),\n timeout: number,\n): Promise<T> {\n return Promise.race([\n typeof funcOrPromise === 'function' ? funcOrPromise() : funcOrPromise,\n new Promise<never>((_, rej) => {\n setTimeout(() => {\n rej(createTimeoutError(timeout));\n }, timeout);\n }),\n ]);\n}\n","import { withTimeout } from '@/timeout/withTimeout.js';\nimport type { ExecuteWithOptions, If, IsNever } from '@/types/index.js';\n\nimport { on } from './events/listening/on.js';\nimport { postEvent as defaultPostEvent } from './methods/postEvent.js';\nimport type { MiniAppsEventName, MiniAppsEventPayload } from './events/types.js';\nimport type { MiniAppsMethodName, MiniAppsMethodParams } from './methods/types/index.js';\nimport { createCleanup } from '@/misc/createCleanup.js';\n\n/**\n * Returns all possible payloads for the specified events array.\n */\nexport type RequestEventsPayloads<E extends MiniAppsEventName[]> =\n E extends (infer U extends MiniAppsEventName)[]\n ? MiniAppsEventPayload<U>\n : never;\n\nexport type RequestCaptureEventsFn<E extends MiniAppsEventName[]> =\n E extends (infer U extends MiniAppsEventName)[]\n ? (payload: {\n [K in U]: If<\n IsNever<MiniAppsEventPayload<K>>,\n { event: K },\n { event: K; payload: MiniAppsEventPayload<K> }\n >\n }[U]) => boolean\n : never;\n\nexport type RequestCaptureEventFn<E extends MiniAppsEventName> = If<\n IsNever<MiniAppsEventPayload<E>>,\n () => boolean,\n (payload: MiniAppsEventPayload<E>) => boolean\n>;\n\n/**\n * `request` method options.\n * @see request\n */\nexport type RequestOptions<M extends MiniAppsMethodName, E, C> = {\n /**\n * Mini Apps method name.\n */\n method: M;\n /**\n * Tracked Mini Apps events.\n */\n event: E;\n /**\n * Should return true if this event should be captured.\n * A request will be captured if this property is omitted.\n */\n capture?: C;\n }\n & ExecuteWithOptions\n & If<IsNever<MiniAppsMethodParams<M>>, {}, {\n /**\n * List of method parameters.\n */\n params: MiniAppsMethodParams<M>\n}>;\n\ntype AnyRequestResult =\n | MiniAppsEventPayload<MiniAppsEventName>\n | RequestEventsPayloads<MiniAppsEventName[]>;\n\n/**\n * Calls specified Mini Apps method and captures specified event.\n * @param options - method options.\n * @returns Promise which will be resolved with data of the captured event.\n */\nexport async function request<M extends MiniAppsMethodName, E extends MiniAppsEventName>(\n options: RequestOptions<M, E, RequestCaptureEventFn<E>>,\n): Promise<MiniAppsEventPayload<E>>;\n\n/**\n * Calls specified Mini Apps method and captures one of the specified events.\n * @param options - method options.\n * @returns Promise which will be resolved with data of the first captured event.\n */\nexport async function request<M extends MiniAppsMethodName, E extends MiniAppsEventName[]>(\n options: RequestOptions<M, E, RequestCaptureEventsFn<E>>,\n): Promise<RequestEventsPayloads<E>>;\n\nexport async function request<M extends MiniAppsMethodName>(\n options:\n | RequestOptions<M, MiniAppsEventName, RequestCaptureEventFn<MiniAppsEventName>>\n | RequestOptions<M, MiniAppsEventName[], RequestCaptureEventsFn<MiniAppsEventName[]>>,\n): Promise<AnyRequestResult> {\n let resolve: (payload: AnyRequestResult) => void;\n const promise = new Promise<AnyRequestResult>(res => resolve = res);\n\n const { event, capture, timeout } = options;\n const [, cleanup] = createCleanup(\n // We need to iterate over all tracked events, and create their event listeners.\n (Array.isArray(event) ? event : [event]).map((ev) => {\n // Each event listener waits for the event to occur.\n // Then, if the capture function was passed, we should check if the event should be captured.\n // If the function is omitted, we instantly capture the event.\n return on(ev, (payload) => {\n if (!capture || (\n Array.isArray(event)\n ? (capture as RequestCaptureEventsFn<MiniAppsEventName[]>)({\n event: ev,\n payload: payload as any,\n })\n : (capture as RequestCaptureEventFn<MiniAppsEventName>)(payload)\n )) {\n resolve(payload);\n }\n });\n }),\n );\n\n try {\n (options.postEvent || defaultPostEvent)(options.method as any, (options as any).params);\n return await (timeout ? withTimeout(promise, timeout) : promise);\n } finally {\n // After promise execution was completed, don't forget to remove all the listeners.\n cleanup();\n }\n}\n","import { createError } from '@/errors/createError.js';\nimport { ERR_INVOKE_CUSTOM_METHOD_RESPONSE } from '@/errors/errors.js';\nimport type { ExecuteWithOptions } from '@/types/index.js';\n\nimport { captureSameReq } from './captureSameReq.js';\nimport { request } from './request.js';\nimport type { CustomMethodName, CustomMethodParams } from './methods/types/custom-methods.js';\n\n/**\n * Invokes known custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param requestId - request identifier.\n * @param options - additional options.\n * @throws {SDKError} ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n * @see ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n */\nexport async function invokeCustomMethod<M extends CustomMethodName>(\n method: M,\n params: CustomMethodParams<M>,\n requestId: string,\n options?: ExecuteWithOptions,\n): Promise<unknown>;\n\n/**\n * Invokes unknown custom method. Returns method execution result.\n * @param method - method name.\n * @param params - method parameters.\n * @param requestId - request identifier.\n * @param options - additional options.\n * @throws {SDKError} ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n * @see ERR_INVOKE_CUSTOM_METHOD_RESPONSE\n */\nexport function invokeCustomMethod(\n method: string,\n params: object,\n requestId: string,\n options?: ExecuteWithOptions,\n): Promise<unknown>;\n\nexport async function invokeCustomMethod(\n method: string,\n params: object,\n requestId: string,\n options: ExecuteWithOptions = {},\n): Promise<unknown> {\n const {\n result,\n error,\n } = await request({\n ...options,\n method: 'web_app_invoke_custom_method',\n event: 'custom_method_invoked',\n params: {\n method,\n params,\n req_id: requestId,\n },\n capture: captureSameReq(requestId),\n });\n\n if (error) {\n throw createError(ERR_INVOKE_CUSTOM_METHOD_RESPONSE, error);\n }\n\n return result;\n}\n","import { request } from '@/bridge/request.js';\nimport { hasWebviewProxy } from '@/env/hasWebviewProxy.js';\n\n/**\n * Returns true in case, current environment is Telegram Mini Apps.\n */\nexport async function isTMA(): Promise<boolean> {\n if (hasWebviewProxy(window)) {\n return true;\n }\n try {\n await request({ method: 'web_app_request_theme', event: 'theme_changed', timeout: 100 });\n return true;\n } catch {\n return false;\n }\n}\n","import { SDKError } from './SDKError.js';\n\n/**\n * @returns True, if passed value is an instance of SDKError.\n * @param value - value to check.\n */\nexport function isSDKError(value: unknown): value is SDKError {\n return value instanceof SDKError;\n}\n","import { isSDKError } from './isSDKError.js';\nimport type { ErrorType } from './errors.js';\n\n/**\n * Returns true if passed value is an SDK error of specified type.\n * @param value - value to check.\n * @param type - error type.\n */\nexport function isSDKErrorOfType(value: unknown, type: ErrorType): boolean {\n return isSDKError(value) && value.type === type;\n}\n","import { on } from '@/bridge/events/listening/on.js';\nimport { postEvent } from '@/bridge/methods/postEvent.js';\n\ninterface CleanupFn {\n (): void;\n}\n\n/**\n * Performs initialization process in the web version of Telegram.\n * @returns Function, which performs cleanup removing all created elements and listeners.\n * @param acceptCustomStyles - true if SDK should accept styles sent from the Telegram web\n * application. This option is only used in web versions of Telegram. Default: false.\n */\nexport function initWeb(acceptCustomStyles = true): CleanupFn {\n const listeners: CleanupFn[] = [\n on('reload_iframe', () => {\n postEvent('iframe_will_reload');\n window.location.reload();\n }),\n ];\n const cleanup: CleanupFn = () => listeners.forEach((l) => l());\n\n if (acceptCustomStyles) {\n const style = document.createElement('style');\n style.id = 'telegram-custom-styles';\n document.head.appendChild(style);\n\n listeners.push(\n on('set_custom_style', (html) => {\n // It is safe to use innerHTML here as long as style tag has a special behavior related\n // to the specified content. In case, any script will be passed here, it will not be\n // executed.\n style.innerHTML = html;\n }),\n () => document.head.removeChild(style),\n );\n }\n\n // Notify Telegram, iframe is ready. This will result in sending style tag html from native\n // application which is used in catchCustomStyles function. We should call this method also\n // to start receiving \"reload_iframe\" events from the Telegram application.\n postEvent('iframe_ready', { reload_supported: true });\n\n return cleanup;\n}\n","import { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport { number } from './number.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as Date.\n */\nexport const date: ValueParserGenerator<Date> = createValueParserGenerator((value) => (\n value instanceof Date\n ? value\n : new Date(number().parse(value) * 1000)\n), 'Date');\n","import { createTypeError } from '../createTypeError.js';\nimport { parseBySchema } from '../parseBySchema.js';\nimport { ValueParser } from '../ValueParser/ValueParser.js';\nimport type { Schema } from '../types.js';\n\n/**\n * Creates new search params parser according to passed schema.\n * @param schema - object schema.\n * @param type - parser type name.\n */\nexport function searchParams<T>(schema: Schema<T>, type?: string): ValueParser<T, false> {\n return new ValueParser((value) => {\n if (typeof value !== 'string' && !(value instanceof URLSearchParams)) {\n throw createTypeError();\n }\n\n const params = typeof value === 'string' ? new URLSearchParams(value) : value;\n\n return parseBySchema(schema, (field) => {\n const paramValue = params.get(field);\n return paramValue === null ? undefined : paramValue;\n });\n }, false, type);\n}\n","import { json } from '@/parsing/parsers/json.js';\nimport { number } from '@/parsing/parsers/number.js';\nimport { string } from '@/parsing/parsers/string.js';\n\nimport type { Chat } from '../types.js';\n\nexport const chat = json<Chat>({\n id: number(),\n type: string(),\n title: string(),\n photoUrl: {\n type: string().optional(),\n from: 'photo_url',\n },\n username: string().optional(),\n}, 'Chat')\n .optional();\n","import { boolean } from '@/parsing/parsers/boolean.js';\nimport { json } from '@/parsing/parsers/json.js';\nimport { number } from '@/parsing/parsers/number.js';\nimport { string } from '@/parsing/parsers/string.js';\n\nimport type { User } from '../types.js';\n\nexport const user = json<User>({\n addedToAttachmentMenu: {\n type: boolean().optional(),\n from: 'added_to_attachment_menu',\n },\n allowsWriteToPm: {\n type: boolean().optional(),\n from: 'allows_write_to_pm',\n },\n firstName: {\n type: string(),\n from: 'first_name',\n },\n id: number(),\n isBot: {\n type: boolean().optional(),\n from: 'is_bot',\n },\n isPremium: {\n type: boolean().optional(),\n from: 'is_premium',\n },\n languageCode: {\n type: string().optional(),\n from: 'language_code',\n },\n lastName: {\n type: string().optional(),\n from: 'last_name',\n },\n photoUrl: {\n type: string().optional(),\n from: 'photo_url',\n },\n username: string().optional(),\n}, 'User')\n .optional();\n","import { date } from '@/parsing/parsers/date.js';\nimport { number } from '@/parsing/parsers/number.js';\nimport { searchParams } from '@/parsing/parsers/searchParams.js';\nimport { string } from '@/parsing/parsers/string.js';\nimport type { ValueParser } from '@/parsing/ValueParser/ValueParser.js';\n\nimport { chat } from './chat.js';\nimport { user } from './user.js';\nimport type { InitDataParsed } from '../types.js';\n\n/**\n * Returns parser used to parse init data, presented as search params.\n */\nexport function initData(): ValueParser<InitDataParsed, false> {\n return searchParams<InitDataParsed>({\n authDate: {\n type: date(),\n from: 'auth_date',\n },\n canSendAfter: {\n type: number().optional(),\n from: 'can_send_after',\n },\n chat,\n chatInstance: {\n type: string().optional(),\n from: 'chat_instance',\n },\n chatType: {\n type: string().optional(),\n from: 'chat_type',\n },\n hash: string(),\n queryId: {\n type: string().optional(),\n from: 'query_id',\n },\n receiver: user,\n startParam: {\n type: string().optional(),\n from: 'start_param',\n },\n user,\n }, 'InitData');\n}\n","import type { RGB } from './types.js';\n\n/**\n * Returns true in case, passed value has #RRGGBB format.\n * @param value - value to check.\n */\nexport function isRGB(value: string): value is RGB {\n return /^#[\\da-f]{6}$/i.test(value);\n}\n","import type { RGBShort } from './types.js';\n\n/**\n * Returns true in case, passed value has #RGB format.\n * @param value - value to check.\n */\nexport function isRGBShort(value: string): value is RGBShort {\n return /^#[\\da-f]{3}$/i.test(value);\n}\n","import { isRGB } from './isRGB.js';\nimport { isRGBShort } from './isRGBShort.js';\nimport type { RGB } from './types.js';\n\n/**\n * Converts passed value to #RRGGBB format. Accepts following color formats:\n * - `#RGB`\n * - `#RRGGBB`\n * - `rgb(1,2,3)`\n * - `rgba(1,2,3,4)`\n * @param value - value to convert.\n * @throws {Error} Passed value does not satisfy any of known RGB formats.\n */\nexport function toRGB(value: string): RGB {\n // Remove all spaces.\n const clean = value.replace(/\\s/g, '').toLowerCase();\n\n // Value already has required format.\n if (isRGB(clean)) {\n return clean;\n }\n\n // Convert from #RGB.\n if (isRGBShort(clean)) {\n let color: RGB = '#';\n for (let i = 0; i < 3; i += 1) {\n color += clean[1 + i].repeat(2);\n }\n return color;\n }\n\n // Example valid values: rgb(0,3,10) rgba(32,114,8,0)\n const match = clean.match(/^rgb\\((\\d{1,3}),(\\d{1,3}),(\\d{1,3})\\)$/)\n || clean.match(/^rgba\\((\\d{1,3}),(\\d{1,3}),(\\d{1,3}),\\d{1,3}\\)$/);\n\n // In case, this didn't work as well, we can't extract RGB color from passed\n // text.\n if (!match) {\n throw new Error(`Value \"${value}\" does not satisfy any of known RGB formats.`);\n }\n\n // Otherwise, take R, G and B components, convert to hex and create #RRGGBB\n // string.\n return match.slice(1).reduce((acc, component) => {\n const formatted = parseInt(component, 10).toString(16);\n return acc + (formatted.length === 1 ? '0' : '') + formatted;\n }, '#') as RGB;\n}\n","import { toRGB } from '@/colors/toRGB.js';\nimport type { RGB } from '@/colors/types.js';\n\nimport { createValueParserGenerator } from '../createValueParserGenerator.js';\nimport { string } from './string.js';\nimport type { ValueParserGenerator } from '../createValueParserGenerator.js';\n\n/**\n * Returns parser to parse value as RGB color.\n */\nexport const rgb: ValueParserGenerator<RGB> = createValueParserGenerator((value) => toRGB(string().parse(value)), 'rgb');\n","/**\n * Converts a palette key from the Telegram application to the representation used by the package.\n * @param key - palette key.\n */\nexport function keyToLocal(key: string): string {\n return key.replace(/_[a-z]/g, (match) => match[1].toUpperCase());\n}\n\n/**\n * Converts palette key from the local representation to the representation sent from the\n * Telegram application.\n * @param key - palette key.\n */\nexport function keyToExternal(key: string): string {\n return key.replace(/[A-Z]/g, (match) => `_${match.toLowerCase()}`);\n}\n","import { createValueParserGenerator, type ValueParserGenerator } from '@/parsing/createValueParserGenerator.js';\nimport { rgb } from '@/parsing/parsers/rgb.js';\nimport { toRecord } from '@/parsing/toRecord.js';\n\nimport { keyToLocal } from '../keys.js';\nimport type { ThemeParamsParsed } from '../types.js';\n\nexport const themeParams: ValueParserGenerator<ThemeParamsParsed> = createValueParserGenerator(\n (value) => {\n const rgbOptional = rgb().optional();\n\n return Object\n .entries(toRecord(value))\n .reduce<ThemeParamsParsed>((acc, [k, v]) => {\n acc[keyToLocal(k)] = rgbOptional.parse(v);\n return acc;\n }, {});\n },\n 'ThemeParams',\n);\n","import { initData } from '@/components/InitData/parsers/initData.js';\nimport { themeParams } from '@/components/ThemeParams/parsing/themeParams.js';\nimport { boolean } from '@/parsing/parsers/boolean.js';\nimport { searchParams } from '@/parsing/parsers/searchParams.js';\nimport { string } from '@/parsing/parsers/string.js';\n\nimport type { LaunchParams } from './types.js';\n\n/**\n * Parses value as launch parameters.\n * @param value - value to parse.\n */\nexport function parseLaunchParams(value: unknown): LaunchParams {\n return searchParams({\n botInline: {\n type: boolean().optional(),\n from: 'tgWebAppBotInline',\n },\n initData: {\n type: initData().optional(),\n from: 'tgWebAppData',\n },\n initDataRaw: {\n type: string().optional(),\n from: 'tgWebAppData',\n },\n platform: {\n type: string(),\n from: 'tgWebAppPlatform',\n },\n showSettings: {\n type: boolean().optional(),\n from: 'tgWebAppShowSettings',\n },\n startParam: {\n type: string().optional(),\n from: 'tgWebAppStartParam',\n },\n themeParams: {\n type: themeParams(),\n from: 'tgWebAppThemeParams',\n },\n version: {\n type: string(),\n from: 'tgWebAppVersion',\n },\n }).parse(value);\n}\n","import { parseLaunchParams } from './parseLaunchParams.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * @param urlString - URL to extract launch parameters from.\n * @returns Launch parameters from the specified URL.\n * @throws Error if function was unable to extract launch parameters from the passed URL.\n */\nexport function retrieveFromUrl(urlString: string): LaunchParams {\n return parseLaunchParams(\n urlString\n // Replace everything before this first hashtag or question sign.\n .replace(/^[^?#]*[?#]/, '')\n // Replace all hashtags and question signs to make it look like some search params.\n .replace(/[?#]/g, '&'),\n );\n}\n","import { retrieveFromUrl } from './retrieveFromUrl.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * @returns Launch parameters from the current window location hash.\n * @throws Error if function was unable to extract launch parameters from the window location hash.\n */\nexport function retrieveFromLocation(): LaunchParams {\n return retrieveFromUrl(window.location.href);\n}\n","/**\n * Returns the first navigation entry from window.performance.\n * @returns First navigation entry or null, in case performance functionality is not supported\n * or navigation entry was not found.\n */\nexport function getFirstNavigationEntry(): PerformanceNavigationTiming | undefined {\n return performance.getEntriesByType('navigation')[0] as PerformanceNavigationTiming | undefined;\n}\n","import { getFirstNavigationEntry } from '@/navigation/getFirstNavigationEntry.js';\n\nimport { retrieveFromUrl } from './retrieveFromUrl.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * @returns Launch parameters based on the first navigation entry.\n * @throws Error if function was unable to extract launch parameters from the navigation entry.\n */\nexport function retrieveFromPerformance(): LaunchParams {\n const navigationEntry = getFirstNavigationEntry();\n if (!navigationEntry) {\n throw new Error('Unable to get first navigation entry.');\n }\n\n return retrieveFromUrl(navigationEntry.name);\n}\n","import type { BackButtonState } from '@/components/BackButton/types.js';\nimport type { BiometryManagerState } from '@/components/BiometryManager/types.js';\nimport type { ClosingBehaviorState } from '@/components/ClosingBehavior/types.js';\nimport type { MainButtonState } from '@/components/MainButton/types.js';\nimport type { MiniAppState } from '@/components/MiniApp/types.js';\nimport type { SettingsButtonState } from '@/components/SettingsButton/types.js';\nimport type { ThemeParamsParsed } from '@/components/ThemeParams/types.js';\nimport type { ViewportState } from '@/components/Viewport/types.js';\n\n/**\n * Describes storage keys and according values.\n */\nexport interface StorageParams {\n backButton: BackButtonState;\n biometryManager: BiometryManagerState;\n closingBehavior: ClosingBehaviorState;\n launchParams: string;\n mainButton: MainButtonState;\n miniApp: MiniAppState;\n settingsButton: SettingsButtonState;\n themeParams: ThemeParamsParsed;\n viewport: ViewportState;\n}\n\n/**\n * Key which could be used to store data in the storage.\n */\nexport type StorageKey = keyof StorageParams;\n\n/**\n * Type specific to the specified storage key.\n */\nexport type StorageValue<K extends StorageKey> = StorageParams[K];\n\n/**\n * Converts passed storage key to the formatted state.\n * @param key - storage key.\n */\nfunction formatKey(key: StorageKey): string {\n return `tma.js/${key.replace(/[A-Z]/g, (m) => `-${m.toLowerCase()}`)}`;\n}\n\n/**\n * Saves value in the storage.\n * @param key - storage key.\n * @param value - storage value.\n */\nexport function setStorageValue<K extends StorageKey>(key: K, value: StorageValue<K>): void {\n sessionStorage.setItem(formatKey(key), JSON.stringify(value));\n}\n\n/**\n * Extracts value from the storage.\n * @param key - storage key.\n */\nexport function getStorageValue<K extends StorageKey>(key: K): StorageValue<K> | undefined {\n const value = sessionStorage.getItem(formatKey(key));\n try {\n return value ? JSON.parse(value) as StorageValue<K> : undefined;\n } catch { /* empty */ }\n}\n","import { parseLaunchParams } from '@/launch-params/parseLaunchParams.js';\nimport { getStorageValue } from '@/storage/storage.js';\nimport type { LaunchParams } from '@/launch-params/types.js';\n\n/**\n * @returns Launch parameters stored in the session storage.\n * @throws Error if function was unable to extract launch parameters from the window location hash.\n */\nexport function retrieveFromStorage(): LaunchParams {\n return parseLaunchParams(getStorageValue('launchParams') || '');\n}\n","import { keyToExternal } from '../keys.js';\nimport type { ThemeParamsParsed } from '../types.js';\n\n/**\n * Serializes theme parameters to representation sent from the Telegram application.\n */\nexport function serializeThemeParams(themeParams: ThemeParamsParsed): string {\n return JSON.stringify(\n Object.fromEntries(\n Object\n .entries(themeParams)\n .map(([key, value]) => [keyToExternal(key), value]),\n ),\n );\n}\n","import { serializeThemeParams } from '@/components/ThemeParams/parsing/serializeThemeParams.js';\n\nimport type { LaunchParams } from './types.js';\n\n/**\n * Converts launch parameters to its initial representation.\n * @param value - launch parameters.\n */\nexport function serializeLaunchParams(value: LaunchParams): string {\n const {\n initDataRaw,\n themeParams,\n platform,\n version,\n showSettings,\n startParam,\n botInline,\n } = value;\n\n const params = new URLSearchParams();\n\n params.set('tgWebAppPlatform', platform);\n params.set('tgWebAppThemeParams', serializeThemeParams(themeParams));\n params.set('tgWebAppVersion', version);\n\n if (initDataRaw) {\n params.set('tgWebAppData', initDataRaw);\n }\n\n if (startParam) {\n params.set('tgWebAppStartParam', startParam);\n }\n\n if (typeof showSettings === 'boolean') {\n params.set('tgWebAppShowSettings', showSettings ? '1' : '0');\n }\n\n if (typeof botInline === 'boolean') {\n params.set('tgWebAppBotInline', botInline ? '1' : '0');\n }\n\n return params.toString();\n}\n","import { setStorageValue } from '@/storage/storage.js';\n\nimport { serializeLaunchParams } from './serializeLaunchParams.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * Saves specified launch parameters in the session storage.\n * @param value - launch params to save.\n */\nexport function saveToStorage(value: LaunchParams): void {\n setStorageValue('launchParams', serializeLaunchParams(value));\n}\n","import { retrieveFromLocation } from './retrieveFromLocation.js';\nimport { retrieveFromPerformance } from './retrieveFromPerformance.js';\nimport { retrieveFromStorage } from './retrieveFromStorage.js';\nimport { saveToStorage } from './saveToStorage.js';\nimport type { LaunchParams } from './types.js';\n\n/**\n * @returns Launch parameters from any known source.\n * @throws Error if extraction was unsuccessful.\n */\nexport function retrieveLaunchParams(): LaunchParams {\n const errors: unknown[] = [];\n\n for (const retrieve of [\n // Try to retrieve launch parameters from the current location. This method can return\n // nothing in case, location was changed and then page was reloaded.\n retrieveFromLocation,\n // Then, try using the lower level API - window.performance.\n retrieveFromPerformance,\n // Finally, try to extract launch parameters from the session storage.\n retrieveFromStorage,\n ]) {\n try {\n const lp = retrieve();\n saveToStorage(lp);\n return lp;\n } catch (e) {\n errors.push(e);\n }\n }\n\n throw new Error('Unable to retrieve launch parameters from any known source.');\n}\n"],"names":["createSingleton","create","onReset","cached","reset","unsubscribe","listener","ee","miniAppsEventEmitter","count","resetMiniAppsEventEmitter","subscribe","Logger","scope","options","level","args","now","date","textColor","bgColor","commonCss","logger","debugEnabled","onEvent","name","payload","setDebug","enable","log","EventEmitter","__publicField","event","l","once","listeners","i","onWindow","type","createCleanup","fns","cleanedUp","cache","fn","clean","SDKError","message","cause","createError","ERR_METHOD_UNSUPPORTED","ERR_METHOD_PARAMETER_UNSUPPORTED","ERR_UNKNOWN_ENV","ERR_INVOKE_CUSTOM_METHOD_RESPONSE","ERR_TIMED_OUT","ERR_UNEXPECTED_TYPE","ERR_PARSE","ERR_NAVIGATION_HISTORY_EMPTY","ERR_NAVIGATION_INDEX_INVALID","ERR_NAVIGATION_ITEM_INVALID","ERR_SSR_INIT","ERR_INVALID_PATH_BASE","createTypeError","ValueParser","parser","isOptional","value","createValueParserGenerator","boolean","asString","parseBySchema","schema","getField","result","field","definition","from","definitionType","parsedValue","error","toRecord","formattedValue","json","record","number","num","string","parseMessage","v","cleanupEventHandlers","prop","emitMiniAppsEvent","eventType","eventData","defineEventHandlers","path","pointer","item","idx","arr","parsers","createMiniAppsEventEmitter","subEmitter","mainEmitter","cleanup","data","get","emitter","off","on","isRecord","compareVersions","a","b","aParts","bParts","len","aVal","bVal","versionLessOrEqual","supports","method","paramOrVersion","inVersion","hasExternalNotify","hasWebviewProxy","isIframe","currentTargetOrigin","setTargetOrigin","targetOrigin","postEvent","paramsOrOptions","postOptions","targetOriginFn","createPostEvent","version","params","captureSameReq","reqId","req_id","createTimeoutError","timeout","withTimeout","funcOrPromise","_","rej","request","resolve","promise","res","capture","ev","defaultPostEvent","invokeCustomMethod","requestId","isTMA","isSDKError","isSDKErrorOfType","initWeb","acceptCustomStyles","style","html","searchParams","paramValue","chat","user","initData","isRGB","isRGBShort","toRGB","color","match","acc","component","formatted","rgb","keyToLocal","key","keyToExternal","themeParams","rgbOptional","k","parseLaunchParams","retrieveFromUrl","urlString","retrieveFromLocation","getFirstNavigationEntry","retrieveFromPerformance","navigationEntry","formatKey","m","setStorageValue","getStorageValue","retrieveFromStorage","serializeThemeParams","serializeLaunchParams","initDataRaw","platform","showSettings","startParam","botInline","saveToStorage","retrieveLaunchParams","retrieve","lp"],"mappings":"0OAKgB,SAAAA,EACdC,EACAC,EAUA,CACI,IAAAC,EACJ,MAAMC,EAAQ,IAAM,CACPD,IAAA,QAAaD,GAAWA,EAAQC,CAAM,EACxCA,EAAA,MAAA,EAGJ,MAAA,CAAC,IAAOA,IAAW,OAAYA,EAASF,EAAOG,CAAK,EAAID,EAASC,CAAK,CAC/E,CClBO,SAASC,EAAYC,EAA2C,CACrE,MAAMC,EAAKC,IACL,CAAE,MAAAC,CAAU,EAAAF,EAClBA,EAAG,YAAYD,CAAQ,EAGnBG,GAAS,CAACF,EAAG,OACWG,IAE9B,CCLO,SAASC,EAAUL,EAA4D,CAC/D,OAAAE,EAAA,EAAE,UAAUF,CAAQ,EAClC,IAAMD,EAAYC,CAAQ,CACnC,CCJO,MAAMM,EAAiD,CAC5D,YACmBC,EACAC,EAAyB,GAC1C,CAFiB,KAAA,MAAAD,EACA,KAAA,QAAAC,CAEnB,CAOQ,MAAMC,KAAoBC,EAAmB,CAC7C,MAAAC,MAAU,KACVC,EAAO,KACV,eAAe,QAAS,CACvB,KAAM,UACN,OAAQ,UACR,OAAQ,UACR,uBAAwB,EACxB,SAAU,KAAA,CACX,EACA,OAAOD,CAAG,EAEP,CAAE,UAAAE,EAAW,QAAAC,GAAY,KAAK,QAC9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,EACA,aAAA+D,EACA,WAAAC,EACA,UAAAC,CACE,EAAAtI,EAEEsE,EAAS,IAAI,gBAEZ,OAAAA,EAAA,IAAI,mBAAoB6D,CAAQ,EACvC7D,EAAO,IAAI,sBAAuB0D,GAAqBf,CAAW,CAAC,EAC5D3C,EAAA,IAAI,kBAAmBD,CAAO,EAEjC6D,GACK5D,EAAA,IAAI,eAAgB4D,CAAW,EAGpCG,GACK/D,EAAA,IAAI,qBAAsB+D,CAAU,EAGzC,OAAOD,GAAiB,WAC1B9D,EAAO,IAAI,uBAAwB8D,EAAe,IAAM,GAAG,EAGzD,OAAOE,GAAc,WACvBhE,EAAO,IAAI,oBAAqBgE,EAAY,IAAM,GAAG,EAGhDhE,EAAO,UAChB,CCjCO,SAASiE,GAAcvI,EAA2B,CACvC6H,GAAA,eAAgBI,GAAsBjI,CAAK,CAAC,CAC9D,CCDO,SAASwI,IAAqC,CAGnD,UAAWC,IAAY,CAGrBlB,GAEAE,GAEAM,EAAA,EAEI,GAAA,CACF,MAAMW,EAAKD,IACX,OAAAF,GAAcG,CAAE,EACTA,OACG,CAEZ,CAGI,MAAA,IAAI,MAAM,6DAA6D,CAC/E"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tma.js/sdk",
3
- "version": "2.6.1",
3
+ "version": "2.7.0",
4
4
  "description": "TypeScript Source Development Kit for Telegram Mini Apps client application.",
5
5
  "author": "Vladislav Kibenko <wolfram.deus@gmail.com>",
6
6
  "homepage": "https://github.com/Telegram-Mini-Apps/tma.js#readme",