@tma.js/sdk-solid 2.1.4 → 2.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("solid-js");var cs=Object.defineProperty,hs=(e,t,s)=>t in e?cs(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,c=(e,t,s)=>(hs(e,typeof t!="symbol"?t+"":t,s),s);function Rt(e,t){let s;const n=()=>{s!==void 0&&t&&t(s),s=void 0};return[()=>s===void 0?s=e(n):s,n]}function et(e){const t=G(),{count:s}=t;t.unsubscribe(e),s&&!t.count&&ys()}function Tt(e){return G().subscribe(e),()=>et(e)}class ps{constructor(t,s={}){this.scope=t,this.options=s}print(t,...s){const n=new Date,r=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n),{textColor:i,bgColor:o}=this.options,a="font-weight: bold;padding: 0 5px;border-radius:5px";console[t](`%c${r}%c / %c${this.scope}`,`${a};background-color: lightblue;color:black`,"",`${a};${i?`color:${i};`:""}${o?`background-color:${o}`:""}`,...s)}error(...t){this.print("error",...t)}log(...t){this.print("log",...t)}}const st=new ps("SDK",{bgColor:"forestgreen",textColor:"white"});let X=!1;const Pt=({name:e,payload:t})=>{st.log("Event received:",t?{name:e,payload:t}:{name:e})};function At(e){X!==e&&(X=e,e?Tt(Pt):et(Pt))}function us(...e){X&&st.log(...e)}class T{constructor(){c(this,"listeners",new Map),c(this,"listenersCount",0),c(this,"subscribeListeners",[])}clear(){this.listeners.clear(),this.subscribeListeners=[]}get count(){return this.listenersCount+this.subscribeListeners.length}emit(t,...s){this.subscribeListeners.forEach(n=>n({event:t,args:s})),(this.listeners.get(t)||[]).forEach(([n,r])=>{n(...s),r&&this.off(t,n)})}on(t,s,n){let r=this.listeners.get(t);return r||this.listeners.set(t,r=[]),r.push([s,n]),this.listenersCount+=1,()=>this.off(t,s)}off(t,s){const n=this.listeners.get(t)||[];for(let r=0;r<n.length;r+=1)if(s===n[r][0]){n.splice(r,1),this.listenersCount-=1;return}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let s=0;s<this.subscribeListeners.length;s+=1)if(this.subscribeListeners[s]===t){this.subscribeListeners.splice(s,1);return}}}function tt(e,t,s){return window.addEventListener(e,t,s),()=>window.removeEventListener(e,t,s)}function It(...e){let t=!1;const s=[...e];return[n=>!t&&s.push(n),()=>{t||(t=!0,s.forEach(n=>n()))},t]}class M extends Error{constructor(t,s,n){super(s,{cause:n}),this.type=t,Object.setPrototypeOf(this,M.prototype)}}function b(e,t,s){return new M(e,t,s)}const kt="ERR_METHOD_UNSUPPORTED",Ot="ERR_METHOD_PARAMETER_UNSUPPORTED",qt="ERR_UNKNOWN_ENV",Dt="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",Nt="ERR_TIMED_OUT",Bt="ERR_UNEXPECTED_TYPE",nt="ERR_PARSE",Mt="ERR_NAVIGATION_LIST_EMPTY",Vt="ERR_NAVIGATION_CURSOR_INVALID",ls="ERR_NAVIGATION_ITEM_INVALID",ds="ERR_SSR_INIT",$t="ERR_INVALID_PATH_BASE";function I(){return b(Bt,"Value has unexpected type")}class W{constructor(t,s,n){this.parser=t,this.isOptional=s,this.type=n}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(s){throw b(nt,`Unable to parse value${this.type?` as ${this.type}`:""}`,s)}}optional(){return this.isOptional=!0,this}}function k(e,t){return()=>new W(e,!1,t)}const E=k(e=>{if(typeof e=="boolean")return e;const t=String(e);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;throw I()},"boolean");function Lt(e,t){const s={};for(const n in e){const r=e[n];if(!r)continue;let i,o;if(typeof r=="function"||"parse"in r)i=n,o=typeof r=="function"?r:r.parse.bind(r);else{const{type:a}=r;i=r.from||n,o=typeof a=="function"?a:a.parse.bind(a)}try{const a=o(t(i));a!==void 0&&(s[n]=a)}catch(a){throw b(nt,`Unable to parse field "${n}"`,a)}}return s}function rt(e){let t=e;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw I();return t}function d(e,t){return new W(s=>{const n=rt(s);return Lt(e,r=>n[r])},!1,t)}const C=k(e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}throw I()},"number");function j(e){return/^#[\da-f]{6}$/i.test(e)}function Ut(e){return/^#[\da-f]{3}$/i.test(e)}function it(e){const t=e.replace(/\s/g,"").toLowerCase();if(j(t))return t;if(Ut(t)){let n="#";for(let r=0;r<3;r+=1)n+=t[1+r].repeat(2);return n}const s=t.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||t.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(!s)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return s.slice(1).reduce((n,r)=>{const i=parseInt(r,10).toString(16);return n+(i.length===1?"0":"")+i},"#")}const h=k(e=>{if(typeof e=="string"||typeof e=="number")return e.toString();throw I()},"string"),ot=k(e=>it(h().parse(e)),"rgb");function _s(e){return d({eventType:h(),eventData:t=>t}).parse(e)}function gs(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function fs(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function ms(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((s,n,r)=>{if(n===r.length-1){t[s]=fs;return}s in t||(t[s]={}),t=t[s]})})}const ws={clipboard_text_received:d({req_id:h(),data:e=>e===null?e:h().optional().parse(e)}),custom_method_invoked:d({req_id:h(),result:e=>e,error:h().optional()}),invoice_closed:d({slug:h(),status:h()}),phone_requested:d({status:h()}),popup_closed:{parse(e){return d({button_id:t=>t==null?void 0:h().parse(t)}).parse(e??{})}},qr_text_received:d({data:h().optional()}),theme_changed:d({theme_params:e=>{const t=ot().optional();return Object.entries(rt(e)).reduce((s,[n,r])=>(s[n]=t.parse(r),s),{})}}),viewport_changed:d({height:C(),width:e=>e==null?window.innerWidth:C().parse(e),is_state_stable:E(),is_expanded:E()}),write_access_requested:d({status:h()})};function bs(){const e=new T,t=new T;t.subscribe(n=>{e.emit("event",{name:n.event,payload:n.args[0]})}),ms();const[,s]=It(gs,tt("resize",()=>{t.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),tt("message",n=>{if(n.source!==window.parent)return;let r;try{r=_s(n.data)}catch{return}const{eventType:i,eventData:o}=r,a=ws[i];try{const p=a?a.parse(o):o;t.emit(...p?[i,p]:[i])}catch(p){st.error(`An error occurred processing the "${i}" event from the Telegram application. Please, file an issue here: https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,r,p)}}),()=>e.clear(),()=>t.clear());return[{on:t.on.bind(t),off:t.off.bind(t),subscribe(n){return e.on("event",n)},unsubscribe(n){e.off("event",n)},get count(){return t.count+e.count}},s]}const[vs,ys]=Rt(e=>{const[t,s]=bs(),n=t.off.bind(t);return t.off=(r,i)=>{const{count:o}=t;n(r,i),o&&!t.count&&e()},[t,s]},([,e])=>e());function G(){return vs()[0]}function V(e,t){G().off(e,t)}function v(e,t,s){return G().on(e,t,s)}function $(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ht(e,t){const s=e.split("."),n=t.split("."),r=Math.max(s.length,n.length);for(let i=0;i<r;i+=1){const o=parseInt(s[i]||"0",10),a=parseInt(n[i]||"0",10);if(o!==a)return o>a?1:-1}return 0}function y(e,t){return Ht(e,t)<=0}function S(e,t,s){if(typeof s=="string"){if(e==="web_app_open_link"&&t==="try_instant_view")return y("6.4",s);if(e==="web_app_set_header_color"&&t==="color")return y("6.9",s)}switch(e){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return y("6.1",t);case"web_app_open_popup":return y("6.2",t);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return y("6.4",t);case"web_app_switch_inline_query":return y("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return y("6.9",t);case"web_app_setup_settings_button":return y("6.10",t);case"web_app_biometry_get_info":case"web_app_biometry_open_settings":case"web_app_biometry_request_access":case"web_app_biometry_request_auth":case"web_app_biometry_update_token":return y("7.2",t);default:return["iframe_ready","iframe_will_reload","web_app_close","web_app_data_send","web_app_expand","web_app_open_link","web_app_ready","web_app_request_theme","web_app_request_viewport","web_app_setup_main_button","web_app_setup_closing_behavior"].includes(e)}}function Es(e){return"external"in e&&$(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function Wt(e){return"TelegramWebviewProxy"in e&&$(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function at(){try{return window.self!==window.top}catch{return!0}}let jt="https://web.telegram.org";function Ps(e){jt=e}function Gt(){return jt}function A(e,t,s){let n={},r;t===void 0&&s===void 0?n={}:t!==void 0&&s!==void 0?(n=s,r=t):t!==void 0&&("targetOrigin"in t?n=t:r=t);const{targetOrigin:i=Gt()}=n;if(us("Posting event:",r?{event:e,data:r}:{event:e}),at()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:r}),i);return}if(Es(window)){window.external.notify(JSON.stringify({eventType:e,eventData:r}));return}if(Wt(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(r));return}throw b(qt,"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 Kt(e){return(t,s)=>{if(!S(t,e))throw b(kt,`Method "${t}" is unsupported in Mini Apps version ${e}`);if($(s)){let n;if(t==="web_app_open_link"&&"try_instant_view"in s?n="try_instant_view":t==="web_app_set_header_color"&&"color"in s&&(n="color"),n&&!S(t,n,e))throw b(Ot,`Parameter "${n}" of "${t}" method is unsupported in Mini Apps version ${e}`)}return A(t,s)}}function ct(e){return({req_id:t})=>t===e}function zt(e){return b(Nt,`Timeout reached: ${e}ms`)}function ht(e,t){return Promise.race([typeof e=="function"?e():e,new Promise((s,n)=>{setTimeout(()=>{n(zt(t))},t)})])}async function _(e){let t;const s=new Promise(u=>{t=u}),{method:n,event:r,capture:i,postEvent:o=A,timeout:a}=e,p=(Array.isArray(r)?r:[r]).map(u=>v(u,l=>(!i||i(l))&&t(l)));try{return o(n,e.params),await(a?ht(s,a):s)}finally{p.forEach(u=>u())}}async function R(e,t,s,n={}){const{result:r,error:i}=await _({...n,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:e,params:t,req_id:s},capture:ct(s)});if(i)throw b(Dt,i);return r}function H(...e){return e.map(t=>{if(typeof t=="string")return t;if($(t))return H(Object.entries(t).map(s=>s[1]&&s[0]));if(Array.isArray(t))return H(...t)}).filter(Boolean).join(" ")}function Cs(...e){return e.reduce((t,s)=>($(s)&&Object.entries(s).forEach(([n,r])=>{const i=H(t[n],r);i.length&&(t[n]=i)}),t),{})}function pt(e){const t=it(e);return Math.sqrt([.299,.587,.114].reduce((s,n,r)=>{const i=parseInt(t.slice(1+r*2,1+(r+1)*2),16);return s+i*i*n},0))<120}class Ss{constructor(t){c(this,"ee",new T),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this.state=t}clone(){return{...this.state}}set(t,s){Object.entries(typeof t=="string"?{[t]:s}:t).reduce((n,[r,i])=>this.state[r]===i||i===void 0?n:(this.state[r]=i,this.ee.emit(`change:${r}`,i),!0),!1)&&this.ee.emit("change",this.state)}get(t){return this.state[t]}}class ut{constructor(t){c(this,"state"),c(this,"get"),c(this,"set"),c(this,"clone"),this.state=new Ss(t),this.set=this.state.set.bind(this.state),this.get=this.state.get.bind(this.state),this.clone=this.state.clone.bind(this.state)}}function Jt(e,t){return s=>S(t[s],e)}class lt extends ut{constructor(t,s,n){super(t),c(this,"supports"),this.supports=Jt(s,n)}}class Ft extends lt{constructor(t,s,n){super({isVisible:t},s,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"}),c(this,"on",(r,i)=>r==="click"?v("back_button_pressed",i):this.state.on(r,i)),c(this,"off",(r,i)=>r==="click"?V("back_button_pressed",i):this.state.off(r,i)),this.postEvent=n}set isVisible(t){this.set("isVisible",t),this.postEvent("web_app_setup_back_button",{is_visible:t})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const dt=k(e=>e instanceof Date?e:new Date(C().parse(e)*1e3),"Date");function K(e,t){return new W(s=>{if(typeof s!="string"&&!(s instanceof URLSearchParams))throw I();const n=typeof s=="string"?new URLSearchParams(s):s;return Lt(e,r=>{const i=n.get(r);return i===null?void 0:i})},!1,t)}const xs=d({id:C(),type:h(),title:h(),photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"Chat").optional(),Ct=d({addedToAttachmentMenu:{type:E().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:E().optional(),from:"allows_write_to_pm"},firstName:{type:h(),from:"first_name"},id:C(),isBot:{type:E().optional(),from:"is_bot"},isPremium:{type:E().optional(),from:"is_premium"},languageCode:{type:h().optional(),from:"language_code"},lastName:{type:h().optional(),from:"last_name"},photoUrl:{type:h().optional(),from:"photo_url"},username:h().optional()},"User").optional();function Qt(){return K({authDate:{type:dt(),from:"auth_date"},canSendAfter:{type:C().optional(),from:"can_send_after"},chat:xs,chatInstance:{type:h().optional(),from:"chat_instance"},chatType:{type:h().optional(),from:"chat_type"},hash:h(),queryId:{type:h().optional(),from:"query_id"},receiver:Ct,startParam:{type:h().optional(),from:"start_param"},user:Ct},"InitData")}function Rs(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}function Ts(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}const Yt=k(e=>{const t=ot().optional();return Object.entries(rt(e)).reduce((s,[n,r])=>(s[Rs(n)]=t.parse(r),s),{})},"ThemeParams");function _t(e){return K({botInline:{type:E().optional(),from:"tgWebAppBotInline"},initData:{type:Qt().optional(),from:"tgWebAppData"},initDataRaw:{type:h().optional(),from:"tgWebAppData"},platform:{type:h(),from:"tgWebAppPlatform"},showSettings:{type:E().optional(),from:"tgWebAppShowSettings"},startParam:{type:h().optional(),from:"tgWebAppStartParam"},themeParams:{type:Yt(),from:"tgWebAppThemeParams"},version:{type:h(),from:"tgWebAppVersion"}}).parse(e)}function Zt(e){return _t(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function As(){return Zt(window.location.href)}function Xt(){return performance.getEntriesByType("navigation")[0]}function Is(){const e=Xt();if(!e)throw new Error("Unable to get first navigation entry.");return Zt(e.name)}function te(e){return`tma.js/${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function ee(e,t){sessionStorage.setItem(te(e),JSON.stringify(t))}function se(e){const t=sessionStorage.getItem(te(e));try{return t?JSON.parse(t):void 0}catch{}}function ks(){return _t(se("launchParams")||"")}function ne(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,s])=>[Ts(t),s])))}function re(e){const{initDataRaw:t,themeParams:s,platform:n,version:r,showSettings:i,startParam:o,botInline:a}=e,p=new URLSearchParams;return p.set("tgWebAppPlatform",n),p.set("tgWebAppThemeParams",ne(s)),p.set("tgWebAppVersion",r),t&&p.set("tgWebAppData",t),o&&p.set("tgWebAppStartParam",o),typeof i=="boolean"&&p.set("tgWebAppShowSettings",i?"1":"0"),typeof a=="boolean"&&p.set("tgWebAppBotInline",a?"1":"0"),p.toString()}function Os(e){ee("launchParams",re(e))}function ie(){for(const e of[As,Is,ks])try{const t=e();return Os(t),t}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}function gt(){const e=Xt();return!!(e&&e.type==="reload")}function qs(){let e=0;return()=>(e+=1).toString()}const[Ds]=Rt(qs);function g(e,t){return()=>{const s=ie(),n={...s,postEvent:Kt(s.version),createRequestId:Ds()};if(typeof e=="function")return e(n);const[r,i,o]=It(),a=t({...n,state:gt()?se(e):void 0,addCleanup:r}),p=u=>(o||r(u.on("change",l=>{ee(e,l)})),u);return[a instanceof Promise?a.then(p):p(a),i]}}const oe=g("backButton",({postEvent:e,version:t,state:s={isVisible:!1}})=>new Ft(s.isVisible,t,e));class L extends lt{constructor(){super(...arguments),c(this,"on",this.state.on.bind(this.state)),c(this,"off",this.state.off.bind(this.state))}}function ae(e){const t=e.available?e:{available:!1,device_id:"",token_saved:!1,access_requested:!1,access_granted:!1,type:""};return{available:!0,type:t.type,deviceId:t.device_id,tokenSaved:t.token_saved,accessRequested:t.access_requested,accessGranted:t.access_granted}}class ce extends L{constructor({postEvent:t,version:s,...n}){super(n,s,{auth:"web_app_biometry_request_auth",openSettings:"web_app_biometry_open_settings",requestAccess:"web_app_biometry_request_access",updateToken:"web_app_biometry_update_token"}),c(this,"postEvent"),c(this,"authPromise"),c(this,"accessPromise"),this.postEvent=t}get available(){return this.get("available")}get accessGranted(){return this.get("accessGranted")}get accessRequested(){return this.get("accessRequested")}async authenticate({reason:t,...s}){return this.authPromise||(this.authPromise=_({...s,method:"web_app_biometry_request_auth",event:"biometry_auth_requested",postEvent:this.postEvent,params:{reason:(t||"").trim()}}).then(({token:n})=>n).finally(()=>this.authPromise=void 0)),this.authPromise}get deviceId(){return this.get("deviceId")}openSettings(){this.postEvent("web_app_biometry_open_settings")}requestAccess({reason:t,...s}={}){return this.accessPromise||(this.accessPromise=_({...s,postEvent:this.postEvent,method:"web_app_biometry_request_access",event:"biometry_info_received",params:{reason:t||""}}).then(n=>{const r=ae(n);return this.set(r),r.accessGranted}).finally(()=>this.accessPromise=void 0)),this.accessPromise}get biometryType(){return this.get("biometryType")}get tokenSaved(){return this.get("tokenSaved")}async updateToken({token:t,...s}={}){return["removed","updated"].includes((await _({...s,postEvent:this.postEvent,method:"web_app_biometry_update_token",event:"biometry_token_updated",params:{token:t||""}})).status)}}async function he(e){return ae(await _({...e||{},method:"web_app_biometry_get_info",event:"biometry_info_received"}))}const pe=g("biometryManager",async({postEvent:e,version:t,state:s})=>new ce({...s||S("web_app_biometry_get_info",t)?s||await he({timeout:1e3}):{available:!1,accessGranted:!1,accessRequested:!1,tokenSaved:!1,deviceId:""},version:t,postEvent:e}));class ft extends ut{constructor(){super(...arguments),c(this,"on",this.state.on.bind(this.state)),c(this,"off",this.state.off.bind(this.state))}}class ue extends ft{constructor(t,s){super({isConfirmationNeeded:t}),this.postEvent=s}set isConfirmationNeeded(t){this.set("isConfirmationNeeded",t),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:t})}get isConfirmationNeeded(){return this.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}const le=g("closingBehavior",({postEvent:e,state:t={isConfirmationNeeded:!1}})=>new ue(t.isConfirmationNeeded,e));class mt{constructor(t,s){c(this,"supports"),this.supports=Jt(t,s)}}function Ns(e){if(Array.isArray(e))return e;if(typeof e=="string")try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}throw I()}class Bs extends W{constructor(t,s,n){super(Ns,s,n),c(this,"itemParser"),this.itemParser=typeof t=="function"?t:t.parse.bind(t)}parse(t){const s=super.parse(t);return s===void 0?s:s.map(this.itemParser)}of(t){return this.itemParser=typeof t=="function"?t:t.parse.bind(t),this}}function de(e){return new Bs(t=>t,!1,e)}function St(e,t){return Object.fromEntries(e.map(s=>[s,t]))}class _e extends mt{constructor(t,s,n){super(t,{delete:"web_app_invoke_custom_method",get:"web_app_invoke_custom_method",getKeys:"web_app_invoke_custom_method",set:"web_app_invoke_custom_method"}),this.createRequestId=s,this.postEvent=n}async delete(t,s={}){const n=Array.isArray(t)?t:[t];n.length&&await R("deleteStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent})}async getKeys(t={}){return de().of(h()).parse(await R("getStorageKeys",{},this.createRequestId(),{...t,postEvent:this.postEvent}))}async get(t,s={}){const n=Array.isArray(t)?t:[t];if(!n.length)return St(n,"");const r=await R("getStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent}),i=d(St(n,h()),"CloudStorageData").parse(r);return Array.isArray(t)?i:i[t]}async set(t,s,n={}){await R("saveStorageValue",{key:t,value:s},this.createRequestId(),{...n,postEvent:this.postEvent})}}const ge=g(({createRequestId:e,postEvent:t,version:s})=>new _e(s,e,t));class fe extends mt{constructor(t,s){super(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"}),this.postEvent=s}impactOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"impact",impact_style:t})}notificationOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"notification",notification_type:t})}selectionChanged(){this.postEvent("web_app_trigger_haptic_feedback",{type:"selection_change"})}}const me=g(({version:e,postEvent:t})=>new fe(e,t));class we{constructor(t){this.initData=t}get authDate(){return this.initData.authDate}get canSendAfter(){return this.initData.canSendAfter}get canSendAfterDate(){const{canSendAfter:t}=this;return t?new Date(this.authDate.getTime()+t*1e3):void 0}get chat(){return this.initData.chat}get chatType(){return this.initData.chatType}get chatInstance(){return this.initData.chatInstance}get hash(){return this.initData.hash}get queryId(){return this.initData.queryId}get receiver(){return this.initData.receiver}get startParam(){return this.initData.startParam}get user(){return this.initData.user}}const be=g(({initData:e})=>e?new we(e):void 0);function Ms(e){return Qt().parse(e)}class ve extends L{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_invoice"}),this.postEvent=n}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t,s){if(this.isOpened)throw new Error("Invoice is already opened");let n;if(!s)n=t;else{const{hostname:r,pathname:i}=new URL(t,window.location.href);if(r!=="t.me")throw new Error(`Incorrect hostname: ${r}`);const o=i.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!o)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');[,,n]=o}this.isOpened=!0;try{return(await _({method:"web_app_open_invoice",event:"invoice_closed",params:{slug:n},postEvent:this.postEvent,capture(r){return n===r.slug}})).status}finally{this.isOpened=!1}}}const ye=g(({version:e,postEvent:t})=>new ve(!1,e,t));class Ee extends ut{constructor({postEvent:t,...s}){super(s),c(this,"postEvent"),c(this,"on",(n,r)=>n==="click"?v("main_button_pressed",r):this.state.on(n,r)),c(this,"off",(n,r)=>n==="click"?V("main_button_pressed",r):this.state.off(n,r)),this.postEvent=t}get bgColor(){return this.get("bgColor")}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.bgColor,text_color:this.textColor})}disable(){return this.isEnabled=!1,this}enable(){return this.isEnabled=!0,this}hide(){return this.isVisible=!1,this}hideLoader(){return this.isLoaderVisible=!1,this}set isEnabled(t){this.setParams({isEnabled:t})}get isEnabled(){return this.get("isEnabled")}set isLoaderVisible(t){this.setParams({isLoaderVisible:t})}get isLoaderVisible(){return this.get("isLoaderVisible")}set isVisible(t){this.setParams({isVisible:t})}get isVisible(){return this.get("isVisible")}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(t){return this.setParams({text:t})}setTextColor(t){return this.setParams({textColor:t})}setBgColor(t){return this.setParams({bgColor:t})}setParams(t){return this.set(t),this.commit(),this}get text(){return this.get("text")}get textColor(){return this.get("textColor")}}const Pe=g("mainButton",({postEvent:e,themeParams:t,state:s={isVisible:!1,isEnabled:!1,text:"",isLoaderVisible:!1,textColor:t.buttonTextColor||"#ffffff",bgColor:t.buttonColor||"#000000"}})=>new Ee({...s,postEvent:e}));function Vs(){return K({contact:d({userId:{type:C(),from:"user_id"},phoneNumber:{type:h(),from:"phone_number"},firstName:{type:h(),from:"first_name"},lastName:{type:h().optional(),from:"last_name"}}),authDate:{type:dt(),from:"auth_date"},hash:h()},"RequestedContact")}function Ce(e,t){return s=>{const[n,r]=t[s];return S(n,r,e)}}function $s(e){return new Promise(t=>{setTimeout(t,e)})}class Se extends L{constructor({postEvent:t,createRequestId:s,version:n,botInline:r,...i}){super(i,n,{requestPhoneAccess:"web_app_request_phone",requestWriteAccess:"web_app_request_write_access",switchInlineQuery:"web_app_switch_inline_query",setHeaderColor:"web_app_set_header_color",setBackgroundColor:"web_app_set_background_color"}),c(this,"botInline"),c(this,"postEvent"),c(this,"createRequestId"),c(this,"requestPhoneAccessPromise"),c(this,"requestWriteAccessPromise"),c(this,"supportsParam"),this.createRequestId=s,this.postEvent=t,this.botInline=r;const o=this.supports.bind(this);this.supports=a=>o(a)?a!=="switchInlineQuery"||r:!1,this.supportsParam=Ce(n,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact({timeout:t=1e4}={}){return Vs().parse(await R("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:t}))}get bgColor(){return this.get("bgColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return pt(this.bgColor)}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:t=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const s=Date.now()+t;let n=50;return ht(async()=>{for(;Date.now()<s;){try{return await this.getRequestedContact()}catch{}await $s(n),n+=50}throw zt(t)},t)}async requestPhoneAccess(t={}){return this.requestPhoneAccessPromise||(this.requestPhoneAccessPromise=_({...t,method:"web_app_request_phone",event:"phone_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestPhoneAccessPromise=void 0)),this.requestPhoneAccessPromise}async requestWriteAccess(t={}){return this.requestWriteAccessPromise||(this.requestWriteAccessPromise=_({...t,method:"web_app_request_write_access",event:"write_access_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestWriteAccessPromise=void 0)),this.requestWriteAccessPromise}sendData(t){const{size:s}=new Blob([t]);if(!s||s>4096)throw new Error(`Passed data has incorrect size: ${s}`);this.postEvent("web_app_data_send",{data:t})}setHeaderColor(t){this.postEvent("web_app_set_header_color",j(t)?{color:t}:{color_key:t}),this.set("headerColor",t)}setBgColor(t){this.postEvent("web_app_set_background_color",{color:t}),this.set("bgColor",t)}switchInlineQuery(t,s=[]){if(!this.supports("switchInlineQuery")&&!this.isBotInline)throw new Error("Method is unsupported because Mini App should be launched in inline mode.");this.postEvent("web_app_switch_inline_query",{query:t,chat_types:s})}}const xe=g("miniApp",({themeParams:e,botInline:t=!1,state:s={bgColor:e.bgColor||"#ffffff",headerColor:e.headerBgColor||"#000000"},...n})=>new Se({...n,...s,botInline:t}));function Ls(e){const t=e.message.trim(),s=(e.title||"").trim(),n=e.buttons||[];let r;if(s.length>64)throw new Error(`Title has incorrect size: ${s.length}`);if(!t.length||t.length>256)throw new Error(`Message has incorrect size: ${t.length}`);if(n.length>3)throw new Error(`Buttons have incorrect size: ${n.length}`);return n.length?r=n.map(i=>{const{id:o=""}=i;if(o.length>64)throw new Error(`Button ID has incorrect size: ${o}`);if(!i.type||i.type==="default"||i.type==="destructive"){const a=i.text.trim();if(!a.length||a.length>64){const p=i.type||"default";throw new Error(`Button text with type "${p}" has incorrect size: ${i.text.length}`)}return{...i,text:a,id:o}}return{...i,id:o}}):r=[{type:"close",id:""}],{title:s,message:t,buttons:r}}class Re extends L{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_popup"}),this.postEvent=n}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("Popup is already opened.");this.isOpened=!0;try{const{button_id:s=null}=await _({event:"popup_closed",method:"web_app_open_popup",postEvent:this.postEvent,params:Ls(t)});return s}finally{this.isOpened=!1}}}const Te=g(({postEvent:e,version:t})=>new Re(!1,t,e));class Ae extends L{constructor(t,s,n){super({isOpened:t},s,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"}),this.postEvent=n}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("QR scanner is already opened.");this.isOpened=!0;try{return(await _({method:"web_app_open_scan_qr_popup",event:["qr_text_received","scan_qr_popup_closed"],postEvent:this.postEvent,params:{text:t}})||{}).data||null}finally{this.isOpened=!1}}}const Ie=g(({version:e,postEvent:t})=>new Ae(!1,e,t));class ke extends lt{constructor(t,s,n){super({isVisible:t},s,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"}),c(this,"on",(r,i)=>r==="click"?v("settings_button_pressed",i):this.state.on(r,i)),c(this,"off",(r,i)=>r==="click"?V("settings_button_pressed",i):this.state.off(r,i)),this.postEvent=n}set isVisible(t){this.set("isVisible",t),this.postEvent("web_app_setup_settings_button",{is_visible:t})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const Oe=g("settingsButton",({version:e,postEvent:t,state:s={isVisible:!1}})=>new ke(s.isVisible,e,t));function wt(e){return Yt().parse(e)}class qe extends ft{get accentTextColor(){return this.get("accentTextColor")}get bgColor(){return this.get("bgColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}getState(){return this.clone()}get headerBgColor(){return this.get("headerBgColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.bgColor||pt(this.bgColor)}get linkColor(){return this.get("linkColor")}get secondaryBgColor(){return this.get("secondaryBgColor")}get sectionBgColor(){return this.get("sectionBgColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}listen(){return v("theme_changed",t=>{this.set(wt(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}const De=g("themeParams",({themeParams:e,state:t=e,addCleanup:s})=>{const n=new qe(t);return s(n.listen()),n});function Us(e={}){return _({...e,method:"web_app_request_theme",event:"theme_changed"}).then(wt)}class Ne extends mt{constructor(t,s,n){super(t,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),c(this,"supportsParam"),this.version=t,this.createRequestId=s,this.postEvent=n,this.supportsParam=Ce(t,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(t,s){const n=new URL(t,window.location.href).toString();if(!S("web_app_open_link",this.version)){window.open(n,"_blank");return}this.postEvent("web_app_open_link",{url:n,...typeof s=="boolean"?{try_instant_view:s}:{}})}openTelegramLink(t){const{hostname:s,pathname:n,search:r}=new URL(t,window.location.href);if(s!=="t.me")throw new Error(`URL has not allowed hostname: ${s}. Only "t.me" is allowed`);if(!S("web_app_open_tg_link",this.version)){window.location.href=t;return}this.postEvent("web_app_open_tg_link",{path_full:n+r})}async readTextFromClipboard(){const t=this.createRequestId(),{data:s=null}=await _({method:"web_app_read_text_from_clipboard",event:"clipboard_text_received",postEvent:this.postEvent,params:{req_id:t},capture:ct(t)});return s}}const Be=g(({version:e,postEvent:t,createRequestId:s})=>new Ne(e,s,t));async function bt(e={}){const{is_expanded:t,is_state_stable:s,...n}=await _({...e,method:"web_app_request_viewport",event:"viewport_changed"});return{...n,isExpanded:t,isStateStable:s}}function O(e){return e<0?0:e}class Me extends ft{constructor({postEvent:t,stableHeight:s,height:n,width:r,isExpanded:i}){super({height:O(n),isExpanded:i,stableHeight:O(s),width:O(r)}),c(this,"postEvent"),this.postEvent=t}async sync(t){const{isStateStable:s,...n}=await bt(t);this.set({...n,stableHeight:s?n.height:this.get("stableHeight")})}get height(){return this.get("height")}get stableHeight(){return this.get("stableHeight")}listen(){return v("viewport_changed",t=>{const{height:s,width:n,is_expanded:r,is_state_stable:i}=t,o=O(s);this.set({height:o,isExpanded:r,width:O(n),...i?{stableHeight:o}:{}})})}get isExpanded(){return this.get("isExpanded")}get width(){return this.get("width")}expand(){this.postEvent("web_app_expand"),this.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}const Ve=g("viewport",async({state:e,platform:t,postEvent:s,addCleanup:n})=>{let r=!1,i=0,o=0,a=0;if(e)r=e.isExpanded,i=e.height,o=e.width,a=e.stableHeight;else if(["macos","tdesktop","unigram","webk","weba","web"].includes(t))r=!0,i=window.innerHeight,o=window.innerWidth,a=window.innerHeight;else{const u=await bt({timeout:1e3,postEvent:s});r=u.isExpanded,i=u.height,o=u.width,a=u.isStateStable?i:0}const p=new Me({postEvent:s,height:i,width:o,stableHeight:a,isExpanded:r});return n(p.listen()),p});function P(e,t){document.documentElement.style.setProperty(e,t)}function Hs(e,t,s){s||(s=a=>`--tg-${a}-color`);const n=s("header"),r=s("bg"),i=()=>{const{headerColor:a}=e;if(j(a))P(n,a);else{const{bgColor:p,secondaryBgColor:u}=t;a==="bg_color"&&p?P(n,p):a==="secondary_bg_color"&&u&&P(n,u)}P(r,e.bgColor)},o=[t.on("change",i),e.on("change",i)];return i(),()=>o.forEach(a=>a())}function Ws(e,t){t||(t=n=>`--tg-theme-${n.replace(/[A-Z]/g,r=>`-${r.toLowerCase()}`)}`);const s=()=>{Object.entries(e.getState()).forEach(([n,r])=>{r&&P(t(n),r)})};return s(),e.on("change",s)}function js(e,t){t||(t=u=>`--tg-viewport-${u}`);const[s,n,r]=["height","width","stable-height"].map(u=>t(u)),i=()=>P(s,`${e.height}px`),o=()=>P(n,`${e.width}px`),a=()=>P(r,`${e.stableHeight}px`),p=[e.on("change:height",i),e.on("change:width",o),e.on("change:stableHeight",a)];return i(),o(),a(),()=>p.forEach(u=>u())}function $e(e=!0){const t=[v("reload_iframe",()=>{A("iframe_will_reload"),window.location.reload()})],s=()=>t.forEach(n=>n());if(e){const n=document.createElement("style");n.id="telegram-custom-styles",document.head.appendChild(n),t.push(v("set_custom_style",r=>{n.innerHTML=r}),()=>document.head.removeChild(n))}return A("iframe_ready",{reload_supported:!0}),s}function Gs(){return typeof window>"u"}async function Ks(){if(Wt(window))return!0;try{return await _({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function Le(e){return e instanceof M}function zs(e,t){return Le(e)&&e.type===t}function J(e,t){let s,n,r;return typeof e=="string"?s=e:(s=e.pathname===void 0?t:e.pathname,n=e.params,r=e.id),Object.freeze({id:r||(Math.random()*2**14|0).toString(16),pathname:s,params:n})}class Ue{constructor(t,s,n=A){if(c(this,"history"),c(this,"ee",new T),c(this,"attached",!1),c(this,"back",()=>this.go(-1)),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this._index=s,this.postEvent=n,t.length===0)throw b(Mt,"History should not be empty.");if(s<0||s>=t.length)throw b(Vt,"Index should not be zero and higher or equal than history size.");this.history=t.map(r=>J(r,""))}attach(){this.attached||(this.attached=!0,this.sync(),v("back_button_pressed",this.back))}get current(){return this.history[this.index]}detach(){this.attached=!1,V("back_button_pressed",this.back)}forward(){this.go(1)}go(t,s){const n=this.index+t,r=Math.min(Math.max(0,n),this.history.length-1);(n===r||s)&&this.replaceAndMove(r,this.history[r])}goTo(t,s){this.go(t-this.index,s)}get hasPrev(){return this.index>0}get hasNext(){return this.index!==this.history.length-1}get index(){return this._index}push(t){this.hasNext&&this.history.splice(this.index+1),this.replaceAndMove(this.index+1,J(t,this.current.pathname))}replace(t){this.replaceAndMove(this.index,J(t,this.current.pathname))}replaceAndMove(t,s){const n=t-this.index;if(!n&&this.current===s)return;const r=this.current;if(this.index!==t){const i=this._index;this._index=t,this.attached&&i>0!=t>0&&this.sync()}this.history[t]=s,this.ee.emit("change",{navigator:this,from:r,to:this.current,delta:n})}sync(){this.postEvent("web_app_setup_back_button",{is_visible:!!this.index})}}function F({params:e,...t}){return{...e||{hash:"",search:""},...t}}function D(e,t){return e.startsWith(t)?e:`${t}${e}`}function N(e){return new URL(typeof e=="string"?e:`${e.pathname||""}${D(e.search||"","?")}${D(e.hash||"","#")}`,"http://a")}function B(e){const t=typeof e=="string"?e.startsWith("/"):!!(e.pathname&&e.pathname.startsWith("/")),s=N(e);return`${t?s.pathname:s.pathname.slice(1)}${s.search}${s.hash}`}function Q(e,t,s){let n,r;typeof e=="string"?n=e:(n=B(e),s=e.state,r=e.id);const{pathname:i,search:o,hash:a}=new URL(n,`http://a${D(t,"/")}`);return{id:r,pathname:i,params:{hash:a,search:o,state:s}}}async function q(e){return e===0?!0:Promise.race([new Promise(t=>{const s=tt("popstate",()=>{s(),t(!0)});window.history.go(e)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function Js(){if(window.history.length<=1||(window.history.pushState(null,""),await q(1-window.history.length)))return;let e=await q(-1);for(;e;)e=await q(-1)}function vt(e){return N(e).pathname}const xt=0,Y=1,Z=2;class yt{constructor(t,s,{postEvent:n,hashMode:r="classic",base:i}={}){c(this,"navigator"),c(this,"ee",new T),c(this,"hashMode"),c(this,"base"),c(this,"attached",!1),c(this,"onPopState",({state:o})=>{if(o===null)return this.push(this.parsePath(window.location.href));o===xt?window.history.forward():o===Y&&this.back(),o===Z&&this.forward()}),c(this,"onNavigatorChange",async({to:o,from:a,delta:p})=>{this.attached&&await this.syncHistory(),this.ee.emit("change",{delta:p,from:F(a),to:F(o),navigator:this})}),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this.navigator=new Ue(t.map(o=>Q(o,"/")),s,n),this.navigator.on("change",this.onNavigatorChange),this.hashMode=r,this.base=vt(i||"")}async attach(){this.attached||(this.attached=!0,this.navigator.attach(),window.addEventListener("popstate",this.onPopState),await this.syncHistory())}back(){this.navigator.back()}detach(){this.attached=!1,this.navigator.detach(),window.removeEventListener("popstate",this.onPopState)}forward(){return this.navigator.forward()}get index(){return this.navigator.index}get id(){return this.navigator.current.id}go(t,s){return this.navigator.go(t,s)}goTo(t,s){this.navigator.goTo(t,s)}get hash(){return(this.navigator.current.params||{}).hash||""}get hasPrev(){return this.navigator.hasPrev}get hasNext(){return this.navigator.hasNext}get history(){return this.navigator.history.map(F)}get path(){return B(this)}get pathname(){return this.navigator.current.pathname}parsePath(t){let s=N(t);return this.hashMode&&(s=N(s.hash.slice(1))),{pathname:s.pathname,search:s.search,hash:s.hash}}push(t,s){const n=Q(t,this.path),{state:r=s}=n.params;this.navigator.push({...n,params:{...n.params,state:r}})}replace(t,s){const n=Q(t,this.path),{state:r=s}=n.params;this.navigator.replace({...n,params:{...n.params,state:r}})}renderPath(t){const s=(this.base.length===1?"":this.base)+D(B(t),"/");return this.hashMode?D(s.slice(1),this.hashMode==="classic"?"#":"#/"):s}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const{state:t}=this,s=this.renderPath(this);await Js(),this.hasPrev&&this.hasNext?(window.history.replaceState(Y,""),window.history.pushState(t,"",s),window.history.pushState(Z,""),await q(-1)):this.hasPrev?(window.history.replaceState(Y,""),window.history.pushState(t,"",s)):this.hasNext?(window.history.replaceState(t,s),window.history.pushState(Z,""),await q(-1)):(window.history.replaceState(xt,""),window.history.pushState(t,"",s)),window.addEventListener("popstate",this.onPopState)}get search(){return(this.navigator.current.params||{}).search||""}get state(){return(this.navigator.current.params||{}).state}}function He(e){e||(e={});const{href:t,hash:s}=window.location;let n=B(e.hashMode===null?t:s.includes("?")?s.slice(1):`?${s.slice(1)}`);const r=e.base?vt(e.base):void 0;if(r){if(!n.startsWith(r))throw b($t,`Path "${n}" expected to be starting with "${r}"`);n=n.slice(r.length)}return new yt([n],0,e)}function Fs(e){const t=e.match(/#(.+)/);return t?t[1]:null}function Qs(e,t){if(gt()){const s=sessionStorage.getItem(e);if(s)try{const{index:n,history:r}=JSON.parse(s);return new yt(r,n,t)}catch(n){console.error("Unable to restore hash navigator state.",n)}}return He(t)}function Ys(e,t){const s=Qs(e,t),n=()=>sessionStorage.setItem(e,JSON.stringify({index:s.index,history:s.history}));return s.on("change",n),n(),s}function f(e){return(t,s,...n)=>r=>w.createComponent(s,w.mergeProps(()=>w.mergeProps({[t]:e(...n)},r)))}const We=w.createContext();function je(){const e=w.useContext(We);if(!e)throw new Error("useSDK was used outside of SDKProvider.");return e}function m(e){return(...t)=>{const s=je()(e,...t),n=()=>s.signal();return Object.defineProperty(n,"error",()=>s.error),n}}const Ge=m(oe),Zs=f(Ge),Ke=m(pe),Xs=f(Ke),ze=m(le),tn=f(ze),Je=m(ge),en=f(Je),Fe=m(me),sn=f(Fe),Qe=m(be),nn=f(Qe),Ye=m(ye),rn=f(Ye),Ze=m(Pe),on=f(Ze),Xe=m(xe),an=f(Xe),ts=m(Te),cn=f(ts),es=m(Ie),hn=f(es),ss=m(Oe),pn=f(ss),ns=m(De),un=f(ns),rs=m(Be),ln=f(rs),is=m(Ve),dn=f(is),_n=e=>{const t=new Map,s=(n,...r)=>{if(t.has(n))return t.get(n);function i(l){return t.set(n,l),l}let o;try{o=n(...r)}catch(l){return i({error:l,signal:()=>{throw l}})}let a;Array.isArray(o)&&([o,a]=o);const[p]=w.createResource(()=>o),u=w.createMemo(()=>{if(p.state!=="ready")return;const l=p();if(!l||!("on"in l))return l;const os=w.from(U=>(U(l),l.on("change",()=>U(l)))),as=Object.getPrototypeOf(l),z={};return new Proxy(l,{get(U,x){if(!(x in z)){const Et=Reflect.getOwnPropertyDescriptor(as,x);z[x]=Et&&"get"in Et?w.createMemo(()=>os()[x]):()=>Reflect.get(U,x)}return z[x]()}})});return i({signal(){if(p.error)throw p.error;return u()},get error(){return p.error},cleanup:a})};return w.createEffect(()=>{At(e.debug||!1)}),w.createEffect(()=>{at()&&w.onCleanup($e(e.acceptCustomStyles))}),w.onCleanup(()=>{t.forEach(n=>n.cleanup&&n.cleanup())}),w.createComponent(We.Provider,{value:s,get children(){return e.children}})};exports.BackButton=Ft;exports.BasicNavigator=Ue;exports.BiometryManager=ce;exports.BrowserNavigator=yt;exports.ClosingBehavior=ue;exports.CloudStorage=_e;exports.ERR_INVALID_PATH_BASE=$t;exports.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=Dt;exports.ERR_METHOD_PARAMETER_UNSUPPORTED=Ot;exports.ERR_METHOD_UNSUPPORTED=kt;exports.ERR_NAVIGATION_HISTORY_EMPTY=Mt;exports.ERR_NAVIGATION_INDEX_INVALID=Vt;exports.ERR_NAVIGATION_ITEM_INVALID=ls;exports.ERR_PARSE=nt;exports.ERR_SSR_INIT=ds;exports.ERR_TIMED_OUT=Nt;exports.ERR_UNEXPECTED_TYPE=Bt;exports.ERR_UNKNOWN_ENV=qt;exports.EventEmitter=T;exports.HapticFeedback=fe;exports.InitData=we;exports.Invoice=ve;exports.MainButton=Ee;exports.MiniApp=Se;exports.Popup=Re;exports.QRScanner=Ae;exports.SDKError=M;exports.SDKProvider=_n;exports.SettingsButton=ke;exports.ThemeParams=qe;exports.Utils=Ne;exports.Viewport=Me;exports.array=de;exports.bindMiniAppCSSVars=Hs;exports.bindThemeParamsCSSVars=Ws;exports.bindViewportCSSVars=js;exports.boolean=E;exports.captureSameReq=ct;exports.classNames=H;exports.compareVersions=Ht;exports.createBrowserNavigatorFromLocation=He;exports.createPostEvent=Kt;exports.createSafeURL=N;exports.date=dt;exports.getHash=Fs;exports.getPathname=vt;exports.initBackButton=oe;exports.initBiometryManager=pe;exports.initClosingBehavior=le;exports.initCloudStorage=ge;exports.initHapticFeedback=me;exports.initInitData=be;exports.initInvoice=ye;exports.initMainButton=Pe;exports.initMiniApp=xe;exports.initNavigator=Ys;exports.initPopup=Te;exports.initQRScanner=Ie;exports.initSettingsButton=Oe;exports.initThemeParams=De;exports.initUtils=Be;exports.initViewport=Ve;exports.initWeb=$e;exports.invokeCustomMethod=R;exports.isColorDark=pt;exports.isIframe=at;exports.isPageReload=gt;exports.isRGB=j;exports.isRGBShort=Ut;exports.isSDKError=Le;exports.isSDKErrorOfType=zs;exports.isSSR=Gs;exports.isTMA=Ks;exports.json=d;exports.mergeClassNames=Cs;exports.number=C;exports.off=V;exports.on=v;exports.parseInitData=Ms;exports.parseLaunchParams=_t;exports.parseThemeParams=wt;exports.postEvent=A;exports.request=_;exports.requestBiometryInfo=he;exports.requestThemeParams=Us;exports.requestViewport=bt;exports.retrieveLaunchParams=ie;exports.rgb=ot;exports.searchParams=K;exports.serializeLaunchParams=re;exports.serializeThemeParams=ne;exports.setCSSVar=P;exports.setDebug=At;exports.setTargetOrigin=Ps;exports.string=h;exports.subscribe=Tt;exports.supports=S;exports.targetOrigin=Gt;exports.toRGB=it;exports.unsubscribe=et;exports.urlToPath=B;exports.useBackButton=Ge;exports.useBiometryManager=Ke;exports.useClosingBehavior=ze;exports.useCloudStorage=Je;exports.useHapticFeedback=Fe;exports.useInitData=Qe;exports.useInvoice=Ye;exports.useMainButton=Ze;exports.useMiniApp=Xe;exports.usePopup=ts;exports.useQRScanner=es;exports.useSDK=je;exports.useSettingsButton=ss;exports.useThemeParams=ns;exports.useUtils=rs;exports.useViewport=is;exports.withBackButton=Zs;exports.withBiometryManager=Xs;exports.withClosingBehavior=tn;exports.withCloudStorage=en;exports.withHapticFeedback=sn;exports.withInitData=nn;exports.withInvoice=rn;exports.withMainButton=on;exports.withMiniApp=an;exports.withPopup=cn;exports.withQRScanner=hn;exports.withSettingsButton=pn;exports.withThemeParams=un;exports.withTimeout=ht;exports.withUtils=ln;exports.withViewport=dn;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const m=require("solid-js");var ds=Object.defineProperty,ls=(e,t,s)=>t in e?ds(e,t,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[t]=s,c=(e,t,s)=>(ls(e,typeof t!="symbol"?t+"":t,s),s);function It(e,t){let s;const n=()=>{s!==void 0&&t&&t(s),s=void 0};return[()=>s===void 0?s=e(n):s,n]}function rt(e){const t=G(),{count:s}=t;t.unsubscribe(e),s&&!t.count&&Ps()}function kt(e){return G().subscribe(e),()=>rt(e)}class _s{constructor(t,s={}){this.scope=t,this.options=s}print(t,...s){const n=new Date,r=Intl.DateTimeFormat("en-GB",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZone:"UTC"}).format(n),{textColor:i,bgColor:o}=this.options,a="font-weight: bold;padding: 0 5px;border-radius:5px";console[t](`%c${r}%c / %c${this.scope}`,`${a};background-color: lightblue;color:black`,"",`${a};${i?`color:${i};`:""}${o?`background-color:${o}`:""}`,...s)}error(...t){this.print("error",...t)}log(...t){this.print("log",...t)}}const it=new _s("SDK",{bgColor:"forestgreen",textColor:"white"});let et=!1;const Ct=({name:e,payload:t})=>{it.log("Event received:",t?{name:e,payload:t}:{name:e})};function qt(e){et!==e&&(et=e,e?kt(Ct):rt(Ct))}function gs(...e){et&&it.log(...e)}class R{constructor(){c(this,"listeners",new Map),c(this,"listenersCount",0),c(this,"subscribeListeners",[])}clear(){this.listeners.clear(),this.subscribeListeners=[]}get count(){return this.listenersCount+this.subscribeListeners.length}emit(t,...s){this.subscribeListeners.forEach(n=>n({event:t,args:s})),(this.listeners.get(t)||[]).forEach(([n,r])=>{n(...s),r&&this.off(t,n)})}on(t,s,n){let r=this.listeners.get(t);return r||this.listeners.set(t,r=[]),r.push([s,n]),this.listenersCount+=1,()=>this.off(t,s)}off(t,s){const n=this.listeners.get(t)||[];for(let r=0;r<n.length;r+=1)if(s===n[r][0]){n.splice(r,1),this.listenersCount-=1;return}}subscribe(t){return this.subscribeListeners.push(t),()=>this.unsubscribe(t)}unsubscribe(t){for(let s=0;s<this.subscribeListeners.length;s+=1)if(this.subscribeListeners[s]===t){this.subscribeListeners.splice(s,1);return}}}function st(e,t,s){return window.addEventListener(e,t,s),()=>window.removeEventListener(e,t,s)}function ot(...e){let t=!1;const s=[...e];return[n=>!t&&s.push(n),()=>{t||(t=!0,s.forEach(n=>n()))},t]}class M extends Error{constructor(t,s,n){super(s,{cause:n}),this.type=t,Object.setPrototypeOf(this,M.prototype)}}function b(e,t,s){return new M(e,t,s)}const Ot="ERR_METHOD_UNSUPPORTED",Dt="ERR_METHOD_PARAMETER_UNSUPPORTED",Nt="ERR_UNKNOWN_ENV",Bt="ERR_INVOKE_CUSTOM_METHOD_RESPONSE",Mt="ERR_TIMED_OUT",Vt="ERR_UNEXPECTED_TYPE",at="ERR_PARSE",$t="ERR_NAVIGATION_LIST_EMPTY",Lt="ERR_NAVIGATION_CURSOR_INVALID",ws="ERR_NAVIGATION_ITEM_INVALID",fs="ERR_SSR_INIT",Ht="ERR_INVALID_PATH_BASE";function I(){return b(Vt,"Value has unexpected type")}class W{constructor(t,s,n){this.parser=t,this.isOptional=s,this.type=n}parse(t){if(!(this.isOptional&&t===void 0))try{return this.parser(t)}catch(s){throw b(at,`Unable to parse value${this.type?` as ${this.type}`:""}`,s)}}optional(){return this.isOptional=!0,this}}function k(e,t){return()=>new W(e,!1,t)}const E=k(e=>{if(typeof e=="boolean")return e;const t=String(e);if(t==="1"||t==="true")return!0;if(t==="0"||t==="false")return!1;throw I()},"boolean");function Ut(e,t){const s={};for(const n in e){const r=e[n];if(!r)continue;let i,o;if(typeof r=="function"||"parse"in r)i=n,o=typeof r=="function"?r:r.parse.bind(r);else{const{type:a}=r;i=r.from||n,o=typeof a=="function"?a:a.parse.bind(a)}try{const a=o(t(i));a!==void 0&&(s[n]=a)}catch(a){throw b(at,`Unable to parse field "${n}"`,a)}}return s}function ct(e){let t=e;if(typeof t=="string"&&(t=JSON.parse(t)),typeof t!="object"||t===null||Array.isArray(t))throw I();return t}function l(e,t){return new W(s=>{const n=ct(s);return Ut(e,r=>n[r])},!1,t)}const x=k(e=>{if(typeof e=="number")return e;if(typeof e=="string"){const t=Number(e);if(!Number.isNaN(t))return t}throw I()},"number");function j(e){return/^#[\da-f]{6}$/i.test(e)}function Wt(e){return/^#[\da-f]{3}$/i.test(e)}function ht(e){const t=e.replace(/\s/g,"").toLowerCase();if(j(t))return t;if(Wt(t)){let n="#";for(let r=0;r<3;r+=1)n+=t[1+r].repeat(2);return n}const s=t.match(/^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$/)||t.match(/^rgba\((\d{1,3}),(\d{1,3}),(\d{1,3}),\d{1,3}\)$/);if(!s)throw new Error(`Value "${e}" does not satisfy any of known RGB formats.`);return s.slice(1).reduce((n,r)=>{const i=parseInt(r,10).toString(16);return n+(i.length===1?"0":"")+i},"#")}const p=k(e=>{if(typeof e=="string"||typeof e=="number")return e.toString();throw I()},"string"),pt=k(e=>ht(p().parse(e)),"rgb");function jt(e){return l({eventType:p(),eventData:t=>t}).parse(e)}function ms(){["TelegramGameProxy_receiveEvent","TelegramGameProxy","Telegram"].forEach(e=>{delete window[e]})}function nt(e,t){window.dispatchEvent(new MessageEvent("message",{data:JSON.stringify({eventType:e,eventData:t}),source:window.parent}))}function bs(){[["TelegramGameProxy_receiveEvent"],["TelegramGameProxy","receiveEvent"],["Telegram","WebView","receiveEvent"]].forEach(e=>{let t=window;e.forEach((s,n,r)=>{if(n===r.length-1){t[s]=nt;return}s in t||(t[s]={}),t=t[s]})})}const vs={clipboard_text_received:l({req_id:p(),data:e=>e===null?e:p().optional().parse(e)}),custom_method_invoked:l({req_id:p(),result:e=>e,error:p().optional()}),invoice_closed:l({slug:p(),status:p()}),phone_requested:l({status:p()}),popup_closed:{parse(e){return l({button_id:t=>t==null?void 0:p().parse(t)}).parse(e??{})}},qr_text_received:l({data:p().optional()}),theme_changed:l({theme_params:e=>{const t=pt().optional();return Object.entries(ct(e)).reduce((s,[n,r])=>(s[n]=t.parse(r),s),{})}}),viewport_changed:l({height:x(),width:e=>e==null?window.innerWidth:x().parse(e),is_state_stable:E(),is_expanded:E()}),write_access_requested:l({status:p()})};function ys(){const e=new R,t=new R;t.subscribe(n=>{e.emit("event",{name:n.event,payload:n.args[0]})}),bs();const[,s]=ot(ms,st("resize",()=>{t.emit("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}),st("message",n=>{if(n.source!==window.parent)return;let r;try{r=jt(n.data)}catch{return}const{eventType:i,eventData:o}=r,a=vs[i];try{const h=a?a.parse(o):o;t.emit(...h?[i,h]:[i])}catch(h){it.error(`An error occurred processing the "${i}" event from the Telegram application. Please, file an issue here: https://github.com/Telegram-Mini-Apps/tma.js/issues/new/choose`,r,h)}}),()=>e.clear(),()=>t.clear());return[{on:t.on.bind(t),off:t.off.bind(t),subscribe(n){return e.on("event",n)},unsubscribe(n){e.off("event",n)},get count(){return t.count+e.count}},s]}const[Es,Ps]=It(e=>{const[t,s]=ys(),n=t.off.bind(t);return t.off=(r,i)=>{const{count:o}=t;n(r,i),o&&!t.count&&e()},[t,s]},([,e])=>e());function G(){return Es()[0]}function V(e,t){G().off(e,t)}function v(e,t,s){return G().on(e,t,s)}function $(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gt(e,t){const s=e.split("."),n=t.split("."),r=Math.max(s.length,n.length);for(let i=0;i<r;i+=1){const o=parseInt(s[i]||"0",10),a=parseInt(n[i]||"0",10);if(o!==a)return o>a?1:-1}return 0}function y(e,t){return Gt(e,t)<=0}function S(e,t,s){if(typeof s=="string"){if(e==="web_app_open_link"&&t==="try_instant_view")return y("6.4",s);if(e==="web_app_set_header_color"&&t==="color")return y("6.9",s)}switch(e){case"web_app_open_tg_link":case"web_app_open_invoice":case"web_app_setup_back_button":case"web_app_set_background_color":case"web_app_set_header_color":case"web_app_trigger_haptic_feedback":return y("6.1",t);case"web_app_open_popup":return y("6.2",t);case"web_app_close_scan_qr_popup":case"web_app_open_scan_qr_popup":case"web_app_read_text_from_clipboard":return y("6.4",t);case"web_app_switch_inline_query":return y("6.7",t);case"web_app_invoke_custom_method":case"web_app_request_write_access":case"web_app_request_phone":return y("6.9",t);case"web_app_setup_settings_button":return y("6.10",t);case"web_app_biometry_get_info":case"web_app_biometry_open_settings":case"web_app_biometry_request_access":case"web_app_biometry_request_auth":case"web_app_biometry_update_token":return y("7.2",t);default:return["iframe_ready","iframe_will_reload","web_app_close","web_app_data_send","web_app_expand","web_app_open_link","web_app_ready","web_app_request_theme","web_app_request_viewport","web_app_setup_main_button","web_app_setup_closing_behavior"].includes(e)}}function Kt(e){return"external"in e&&$(e.external)&&"notify"in e.external&&typeof e.external.notify=="function"}function zt(e){return"TelegramWebviewProxy"in e&&$(e.TelegramWebviewProxy)&&"postEvent"in e.TelegramWebviewProxy&&typeof e.TelegramWebviewProxy.postEvent=="function"}function K(){try{return window.self!==window.top}catch{return!0}}let Jt="https://web.telegram.org";function xs(e){Jt=e}function Ft(){return Jt}function A(e,t,s){let n={},r;t===void 0&&s===void 0?n={}:t!==void 0&&s!==void 0?(n=s,r=t):t!==void 0&&("targetOrigin"in t?n=t:r=t);const{targetOrigin:i=Ft()}=n;if(gs("Posting event:",r?{event:e,data:r}:{event:e}),K()){window.parent.postMessage(JSON.stringify({eventType:e,eventData:r}),i);return}if(Kt(window)){window.external.notify(JSON.stringify({eventType:e,eventData:r}));return}if(zt(window)){window.TelegramWebviewProxy.postEvent(e,JSON.stringify(r));return}throw b(Nt,"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 Qt(e){return(t,s)=>{if(!S(t,e))throw b(Ot,`Method "${t}" is unsupported in Mini Apps version ${e}`);if($(s)){let n;if(t==="web_app_open_link"&&"try_instant_view"in s?n="try_instant_view":t==="web_app_set_header_color"&&"color"in s&&(n="color"),n&&!S(t,n,e))throw b(Dt,`Parameter "${n}" of "${t}" method is unsupported in Mini Apps version ${e}`)}return A(t,s)}}function ut(e){return({req_id:t})=>t===e}function Yt(e){return b(Mt,`Timeout reached: ${e}ms`)}function dt(e,t){return Promise.race([typeof e=="function"?e():e,new Promise((s,n)=>{setTimeout(()=>{n(Yt(t))},t)})])}async function _(e){let t;const s=new Promise(a=>{t=a}),{event:n,capture:r,timeout:i}=e,[,o]=ot(...(Array.isArray(n)?n:[n]).map(a=>v(a,h=>(!r||r(h))&&t(h))));try{return(e.postEvent||A)(e.method,e.params),await(i?dt(s,i):s)}finally{o()}}async function T(e,t,s,n={}){const{result:r,error:i}=await _({...n,method:"web_app_invoke_custom_method",event:"custom_method_invoked",params:{method:e,params:t,req_id:s},capture:ut(s)});if(i)throw b(Bt,i);return r}function U(...e){return e.map(t=>{if(typeof t=="string")return t;if($(t))return U(Object.entries(t).map(s=>s[1]&&s[0]));if(Array.isArray(t))return U(...t)}).filter(Boolean).join(" ")}function Ss(...e){return e.reduce((t,s)=>($(s)&&Object.entries(s).forEach(([n,r])=>{const i=U(t[n],r);i.length&&(t[n]=i)}),t),{})}function lt(e){const t=ht(e);return Math.sqrt([.299,.587,.114].reduce((s,n,r)=>{const i=parseInt(t.slice(1+r*2,1+(r+1)*2),16);return s+i*i*n},0))<120}class Cs{constructor(t){c(this,"ee",new R),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this.state=t}clone(){return{...this.state}}set(t,s){Object.entries(typeof t=="string"?{[t]:s}:t).reduce((n,[r,i])=>this.state[r]===i||i===void 0?n:(this.state[r]=i,this.ee.emit(`change:${r}`,i),!0),!1)&&this.ee.emit("change",this.state)}get(t){return this.state[t]}}class _t{constructor(t){c(this,"state"),c(this,"get"),c(this,"set"),c(this,"clone"),this.state=new Cs(t),this.set=this.state.set.bind(this.state),this.get=this.state.get.bind(this.state),this.clone=this.state.clone.bind(this.state)}}function Zt(e,t){return s=>S(t[s],e)}class gt extends _t{constructor(t,s,n){super(t),c(this,"supports"),this.supports=Zt(s,n)}}class Xt extends gt{constructor(t,s,n){super({isVisible:t},s,{show:"web_app_setup_back_button",hide:"web_app_setup_back_button"}),c(this,"on",(r,i)=>r==="click"?v("back_button_pressed",i):this.state.on(r,i)),c(this,"off",(r,i)=>r==="click"?V("back_button_pressed",i):this.state.off(r,i)),this.postEvent=n}set isVisible(t){this.set("isVisible",t),this.postEvent("web_app_setup_back_button",{is_visible:t})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const wt=k(e=>e instanceof Date?e:new Date(x().parse(e)*1e3),"Date");function z(e,t){return new W(s=>{if(typeof s!="string"&&!(s instanceof URLSearchParams))throw I();const n=typeof s=="string"?new URLSearchParams(s):s;return Ut(e,r=>{const i=n.get(r);return i===null?void 0:i})},!1,t)}const Ts=l({id:x(),type:p(),title:p(),photoUrl:{type:p().optional(),from:"photo_url"},username:p().optional()},"Chat").optional(),Tt=l({addedToAttachmentMenu:{type:E().optional(),from:"added_to_attachment_menu"},allowsWriteToPm:{type:E().optional(),from:"allows_write_to_pm"},firstName:{type:p(),from:"first_name"},id:x(),isBot:{type:E().optional(),from:"is_bot"},isPremium:{type:E().optional(),from:"is_premium"},languageCode:{type:p().optional(),from:"language_code"},lastName:{type:p().optional(),from:"last_name"},photoUrl:{type:p().optional(),from:"photo_url"},username:p().optional()},"User").optional();function te(){return z({authDate:{type:wt(),from:"auth_date"},canSendAfter:{type:x().optional(),from:"can_send_after"},chat:Ts,chatInstance:{type:p().optional(),from:"chat_instance"},chatType:{type:p().optional(),from:"chat_type"},hash:p(),queryId:{type:p().optional(),from:"query_id"},receiver:Tt,startParam:{type:p().optional(),from:"start_param"},user:Tt},"InitData")}function Rs(e){return e.replace(/_[a-z]/g,t=>t[1].toUpperCase())}function As(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}const ee=k(e=>{const t=pt().optional();return Object.entries(ct(e)).reduce((s,[n,r])=>(s[Rs(n)]=t.parse(r),s),{})},"ThemeParams");function J(e){return z({botInline:{type:E().optional(),from:"tgWebAppBotInline"},initData:{type:te().optional(),from:"tgWebAppData"},initDataRaw:{type:p().optional(),from:"tgWebAppData"},platform:{type:p(),from:"tgWebAppPlatform"},showSettings:{type:E().optional(),from:"tgWebAppShowSettings"},startParam:{type:p().optional(),from:"tgWebAppStartParam"},themeParams:{type:ee(),from:"tgWebAppThemeParams"},version:{type:p(),from:"tgWebAppVersion"}}).parse(e)}function se(e){return J(e.replace(/^[^?#]*[?#]/,"").replace(/[?#]/g,"&"))}function Is(){return se(window.location.href)}function ne(){return performance.getEntriesByType("navigation")[0]}function ks(){const e=ne();if(!e)throw new Error("Unable to get first navigation entry.");return se(e.name)}function re(e){return`tma.js/${e.replace(/[A-Z]/g,t=>`-${t.toLowerCase()}`)}`}function ie(e,t){sessionStorage.setItem(re(e),JSON.stringify(t))}function oe(e){const t=sessionStorage.getItem(re(e));try{return t?JSON.parse(t):void 0}catch{}}function qs(){return J(oe("launchParams")||"")}function ft(e){return JSON.stringify(Object.fromEntries(Object.entries(e).map(([t,s])=>[As(t),s])))}function ae(e){const{initDataRaw:t,themeParams:s,platform:n,version:r,showSettings:i,startParam:o,botInline:a}=e,h=new URLSearchParams;return h.set("tgWebAppPlatform",n),h.set("tgWebAppThemeParams",ft(s)),h.set("tgWebAppVersion",r),t&&h.set("tgWebAppData",t),o&&h.set("tgWebAppStartParam",o),typeof i=="boolean"&&h.set("tgWebAppShowSettings",i?"1":"0"),typeof a=="boolean"&&h.set("tgWebAppBotInline",a?"1":"0"),h.toString()}function ce(e){ie("launchParams",ae(e))}function he(){for(const e of[Is,ks,qs])try{const t=e();return ce(t),t}catch{}throw new Error("Unable to retrieve launch parameters from any known source.")}function mt(){const e=ne();return!!(e&&e.type==="reload")}function Os(){let e=0;return()=>(e+=1).toString()}const[Ds]=It(Os);function g(e,t){return()=>{const s=he(),n={...s,postEvent:Qt(s.version),createRequestId:Ds()};if(typeof e=="function")return e(n);const[r,i,o]=ot(),a=t({...n,state:mt()?oe(e):void 0,addCleanup:r}),h=u=>(o||r(u.on("change",d=>{ie(e,d)})),u);return[a instanceof Promise?a.then(h):h(a),i]}}const pe=g("backButton",({postEvent:e,version:t,state:s={isVisible:!1}})=>new Xt(s.isVisible,t,e));class L extends gt{constructor(){super(...arguments),c(this,"on",this.state.on.bind(this.state)),c(this,"off",this.state.off.bind(this.state))}}function ue(e){const t=e.available?e:{available:!1,device_id:"",token_saved:!1,access_requested:!1,access_granted:!1,type:""};return{available:!0,type:t.type,deviceId:t.device_id,tokenSaved:t.token_saved,accessRequested:t.access_requested,accessGranted:t.access_granted}}class de extends L{constructor({postEvent:t,version:s,...n}){super(n,s,{auth:"web_app_biometry_request_auth",openSettings:"web_app_biometry_open_settings",requestAccess:"web_app_biometry_request_access",updateToken:"web_app_biometry_update_token"}),c(this,"postEvent"),c(this,"authPromise"),c(this,"accessPromise"),this.postEvent=t}get available(){return this.get("available")}get accessGranted(){return this.get("accessGranted")}get accessRequested(){return this.get("accessRequested")}async authenticate({reason:t,...s}){return this.authPromise||(this.authPromise=_({...s,method:"web_app_biometry_request_auth",event:"biometry_auth_requested",postEvent:this.postEvent,params:{reason:(t||"").trim()}}).then(({token:n})=>n).finally(()=>this.authPromise=void 0)),this.authPromise}get deviceId(){return this.get("deviceId")}openSettings(){this.postEvent("web_app_biometry_open_settings")}requestAccess({reason:t,...s}={}){return this.accessPromise||(this.accessPromise=_({...s,postEvent:this.postEvent,method:"web_app_biometry_request_access",event:"biometry_info_received",params:{reason:t||""}}).then(n=>{const r=ue(n);return this.set(r),r.accessGranted}).finally(()=>this.accessPromise=void 0)),this.accessPromise}get biometryType(){return this.get("biometryType")}get tokenSaved(){return this.get("tokenSaved")}async updateToken({token:t,...s}={}){return["removed","updated"].includes((await _({...s,postEvent:this.postEvent,method:"web_app_biometry_update_token",event:"biometry_token_updated",params:{token:t||""}})).status)}}async function le(e){return ue(await _({...e||{},method:"web_app_biometry_get_info",event:"biometry_info_received"}))}const _e=g("biometryManager",async({postEvent:e,version:t,state:s})=>new de({...s||S("web_app_biometry_get_info",t)?s||await le({timeout:1e3}):{available:!1,accessGranted:!1,accessRequested:!1,tokenSaved:!1,deviceId:""},version:t,postEvent:e}));class bt extends _t{constructor(){super(...arguments),c(this,"on",this.state.on.bind(this.state)),c(this,"off",this.state.off.bind(this.state))}}class ge extends bt{constructor(t,s){super({isConfirmationNeeded:t}),this.postEvent=s}set isConfirmationNeeded(t){this.set("isConfirmationNeeded",t),this.postEvent("web_app_setup_closing_behavior",{need_confirmation:t})}get isConfirmationNeeded(){return this.get("isConfirmationNeeded")}disableConfirmation(){this.isConfirmationNeeded=!1}enableConfirmation(){this.isConfirmationNeeded=!0}}const we=g("closingBehavior",({postEvent:e,state:t={isConfirmationNeeded:!1}})=>new ge(t.isConfirmationNeeded,e));class vt{constructor(t,s){c(this,"supports"),this.supports=Zt(t,s)}}function Ns(e){if(Array.isArray(e))return e;if(typeof e=="string")try{const t=JSON.parse(e);if(Array.isArray(t))return t}catch{}throw I()}class Bs extends W{constructor(t,s,n){super(Ns,s,n),c(this,"itemParser"),this.itemParser=typeof t=="function"?t:t.parse.bind(t)}parse(t){const s=super.parse(t);return s===void 0?s:s.map(this.itemParser)}of(t){return this.itemParser=typeof t=="function"?t:t.parse.bind(t),this}}function fe(e){return new Bs(t=>t,!1,e)}function Rt(e,t){return Object.fromEntries(e.map(s=>[s,t]))}class me extends vt{constructor(t,s,n){super(t,{delete:"web_app_invoke_custom_method",get:"web_app_invoke_custom_method",getKeys:"web_app_invoke_custom_method",set:"web_app_invoke_custom_method"}),this.createRequestId=s,this.postEvent=n}async delete(t,s={}){const n=Array.isArray(t)?t:[t];n.length&&await T("deleteStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent})}async getKeys(t={}){return fe().of(p()).parse(await T("getStorageKeys",{},this.createRequestId(),{...t,postEvent:this.postEvent}))}async get(t,s={}){const n=Array.isArray(t)?t:[t];if(!n.length)return Rt(n,"");const r=await T("getStorageValues",{keys:n},this.createRequestId(),{...s,postEvent:this.postEvent}),i=l(Rt(n,p()),"CloudStorageData").parse(r);return Array.isArray(t)?i:i[t]}async set(t,s,n={}){await T("saveStorageValue",{key:t,value:s},this.createRequestId(),{...n,postEvent:this.postEvent})}}const be=g(({createRequestId:e,postEvent:t,version:s})=>new me(s,e,t));class ve extends vt{constructor(t,s){super(t,{impactOccurred:"web_app_trigger_haptic_feedback",notificationOccurred:"web_app_trigger_haptic_feedback",selectionChanged:"web_app_trigger_haptic_feedback"}),this.postEvent=s}impactOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"impact",impact_style:t})}notificationOccurred(t){this.postEvent("web_app_trigger_haptic_feedback",{type:"notification",notification_type:t})}selectionChanged(){this.postEvent("web_app_trigger_haptic_feedback",{type:"selection_change"})}}const ye=g(({version:e,postEvent:t})=>new ve(e,t));class Ee{constructor(t){this.initData=t}get authDate(){return this.initData.authDate}get canSendAfter(){return this.initData.canSendAfter}get canSendAfterDate(){const{canSendAfter:t}=this;return t?new Date(this.authDate.getTime()+t*1e3):void 0}get chat(){return this.initData.chat}get chatType(){return this.initData.chatType}get chatInstance(){return this.initData.chatInstance}get hash(){return this.initData.hash}get queryId(){return this.initData.queryId}get receiver(){return this.initData.receiver}get startParam(){return this.initData.startParam}get user(){return this.initData.user}}const Pe=g(({initData:e})=>e?new Ee(e):void 0);function Ms(e){return te().parse(e)}class xe extends L{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_invoice"}),this.postEvent=n}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t,s){if(this.isOpened)throw new Error("Invoice is already opened");let n;if(!s)n=t;else{const{hostname:r,pathname:i}=new URL(t,window.location.href);if(r!=="t.me")throw new Error(`Incorrect hostname: ${r}`);const o=i.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/);if(!o)throw new Error('Link pathname has incorrect format. Expected to receive "/invoice/{slug}" or "/${slug}"');[,,n]=o}this.isOpened=!0;try{return(await _({method:"web_app_open_invoice",event:"invoice_closed",params:{slug:n},postEvent:this.postEvent,capture(r){return n===r.slug}})).status}finally{this.isOpened=!1}}}const Se=g(({version:e,postEvent:t})=>new xe(!1,e,t));class Ce extends _t{constructor({postEvent:t,...s}){super(s),c(this,"postEvent"),c(this,"on",(n,r)=>n==="click"?v("main_button_pressed",r):this.state.on(n,r)),c(this,"off",(n,r)=>n==="click"?V("main_button_pressed",r):this.state.off(n,r)),this.postEvent=t}get bgColor(){return this.get("bgColor")}commit(){this.text!==""&&this.postEvent("web_app_setup_main_button",{is_visible:this.isVisible,is_active:this.isEnabled,is_progress_visible:this.isLoaderVisible,text:this.text,color:this.bgColor,text_color:this.textColor})}disable(){return this.isEnabled=!1,this}enable(){return this.isEnabled=!0,this}hide(){return this.isVisible=!1,this}hideLoader(){return this.isLoaderVisible=!1,this}set isEnabled(t){this.setParams({isEnabled:t})}get isEnabled(){return this.get("isEnabled")}set isLoaderVisible(t){this.setParams({isLoaderVisible:t})}get isLoaderVisible(){return this.get("isLoaderVisible")}set isVisible(t){this.setParams({isVisible:t})}get isVisible(){return this.get("isVisible")}show(){return this.isVisible=!0,this}showLoader(){return this.isLoaderVisible=!0,this}setText(t){return this.setParams({text:t})}setTextColor(t){return this.setParams({textColor:t})}setBgColor(t){return this.setParams({bgColor:t})}setParams(t){return this.set(t),this.commit(),this}get text(){return this.get("text")}get textColor(){return this.get("textColor")}}const Te=g("mainButton",({postEvent:e,themeParams:t,state:s={isVisible:!1,isEnabled:!1,text:"",isLoaderVisible:!1,textColor:t.buttonTextColor||"#ffffff",bgColor:t.buttonColor||"#000000"}})=>new Ce({...s,postEvent:e}));function Vs(){return z({contact:l({userId:{type:x(),from:"user_id"},phoneNumber:{type:p(),from:"phone_number"},firstName:{type:p(),from:"first_name"},lastName:{type:p().optional(),from:"last_name"}}),authDate:{type:wt(),from:"auth_date"},hash:p()},"RequestedContact")}function Re(e,t){return s=>{const[n,r]=t[s];return S(n,r,e)}}function $s(e){return new Promise(t=>{setTimeout(t,e)})}class Ae extends L{constructor({postEvent:t,createRequestId:s,version:n,botInline:r,...i}){super(i,n,{requestPhoneAccess:"web_app_request_phone",requestWriteAccess:"web_app_request_write_access",switchInlineQuery:"web_app_switch_inline_query",setHeaderColor:"web_app_set_header_color",setBackgroundColor:"web_app_set_background_color"}),c(this,"botInline"),c(this,"postEvent"),c(this,"createRequestId"),c(this,"requestPhoneAccessPromise"),c(this,"requestWriteAccessPromise"),c(this,"supportsParam"),this.createRequestId=s,this.postEvent=t,this.botInline=r;const o=this.supports.bind(this);this.supports=a=>o(a)?a!=="switchInlineQuery"||r:!1,this.supportsParam=Re(n,{"setHeaderColor.color":["web_app_set_header_color","color"]})}async getRequestedContact({timeout:t=1e4}={}){return Vs().parse(await T("getRequestedContact",{},this.createRequestId(),{postEvent:this.postEvent,timeout:t}))}get bgColor(){return this.get("bgColor")}close(){this.postEvent("web_app_close")}get headerColor(){return this.get("headerColor")}get isBotInline(){return this.botInline}get isDark(){return lt(this.bgColor)}ready(){this.postEvent("web_app_ready")}async requestContact({timeout:t=5e3}={}){try{return await this.getRequestedContact()}catch{}if(await this.requestPhoneAccess()!=="sent")throw new Error("Access denied.");const s=Date.now()+t;let n=50;return dt(async()=>{for(;Date.now()<s;){try{return await this.getRequestedContact()}catch{}await $s(n),n+=50}throw Yt(t)},t)}async requestPhoneAccess(t={}){return this.requestPhoneAccessPromise||(this.requestPhoneAccessPromise=_({...t,method:"web_app_request_phone",event:"phone_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestPhoneAccessPromise=void 0)),this.requestPhoneAccessPromise}async requestWriteAccess(t={}){return this.requestWriteAccessPromise||(this.requestWriteAccessPromise=_({...t,method:"web_app_request_write_access",event:"write_access_requested",postEvent:this.postEvent}).then(({status:s})=>s).finally(()=>this.requestWriteAccessPromise=void 0)),this.requestWriteAccessPromise}sendData(t){const{size:s}=new Blob([t]);if(!s||s>4096)throw new Error(`Passed data has incorrect size: ${s}`);this.postEvent("web_app_data_send",{data:t})}setHeaderColor(t){this.postEvent("web_app_set_header_color",j(t)?{color:t}:{color_key:t}),this.set("headerColor",t)}setBgColor(t){this.postEvent("web_app_set_background_color",{color:t}),this.set("bgColor",t)}switchInlineQuery(t,s=[]){if(!this.supports("switchInlineQuery")&&!this.isBotInline)throw new Error("Method is unsupported because Mini App should be launched in inline mode.");this.postEvent("web_app_switch_inline_query",{query:t,chat_types:s})}}const Ie=g("miniApp",({themeParams:e,botInline:t=!1,state:s={bgColor:e.bgColor||"#ffffff",headerColor:e.headerBgColor||"#000000"},...n})=>new Ae({...n,...s,botInline:t}));function Ls(e){const t=e.message.trim(),s=(e.title||"").trim(),n=e.buttons||[];let r;if(s.length>64)throw new Error(`Title has incorrect size: ${s.length}`);if(!t.length||t.length>256)throw new Error(`Message has incorrect size: ${t.length}`);if(n.length>3)throw new Error(`Buttons have incorrect size: ${n.length}`);return n.length?r=n.map(i=>{const{id:o=""}=i;if(o.length>64)throw new Error(`Button ID has incorrect size: ${o}`);if(!i.type||i.type==="default"||i.type==="destructive"){const a=i.text.trim();if(!a.length||a.length>64){const h=i.type||"default";throw new Error(`Button text with type "${h}" has incorrect size: ${i.text.length}`)}return{...i,text:a,id:o}}return{...i,id:o}}):r=[{type:"close",id:""}],{title:s,message:t,buttons:r}}class ke extends L{constructor(t,s,n){super({isOpened:t},s,{open:"web_app_open_popup"}),this.postEvent=n}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("Popup is already opened.");this.isOpened=!0;try{const{button_id:s=null}=await _({event:"popup_closed",method:"web_app_open_popup",postEvent:this.postEvent,params:Ls(t)});return s}finally{this.isOpened=!1}}}const qe=g(({postEvent:e,version:t})=>new ke(!1,t,e));class Oe extends L{constructor(t,s,n){super({isOpened:t},s,{close:"web_app_close_scan_qr_popup",open:"web_app_open_scan_qr_popup"}),this.postEvent=n}close(){this.postEvent("web_app_close_scan_qr_popup"),this.isOpened=!1}set isOpened(t){this.set("isOpened",t)}get isOpened(){return this.get("isOpened")}async open(t){if(this.isOpened)throw new Error("QR scanner is already opened.");const{text:s,capture:n}=(typeof t=="string"?{text:t}:t)||{};this.isOpened=!0;try{const r=(await _({method:"web_app_open_scan_qr_popup",event:["qr_text_received","scan_qr_popup_closed"],postEvent:this.postEvent,params:{text:s},capture(i){return i.event==="scan_qr_popup_closed"||!n||n(i.payload)}})||{}).data||null;return r&&this.close(),r}catch(r){throw this.isOpened=!1,r}}}const De=g(({version:e,postEvent:t})=>new Oe(!1,e,t));class Ne extends gt{constructor(t,s,n){super({isVisible:t},s,{show:"web_app_setup_settings_button",hide:"web_app_setup_settings_button"}),c(this,"on",(r,i)=>r==="click"?v("settings_button_pressed",i):this.state.on(r,i)),c(this,"off",(r,i)=>r==="click"?V("settings_button_pressed",i):this.state.off(r,i)),this.postEvent=n}set isVisible(t){this.set("isVisible",t),this.postEvent("web_app_setup_settings_button",{is_visible:t})}get isVisible(){return this.get("isVisible")}hide(){this.isVisible=!1}show(){this.isVisible=!0}}const Be=g("settingsButton",({version:e,postEvent:t,state:s={isVisible:!1}})=>new Ne(s.isVisible,e,t));function yt(e){return ee().parse(e)}class Me extends bt{get accentTextColor(){return this.get("accentTextColor")}get bgColor(){return this.get("bgColor")}get buttonColor(){return this.get("buttonColor")}get buttonTextColor(){return this.get("buttonTextColor")}get destructiveTextColor(){return this.get("destructiveTextColor")}getState(){return this.clone()}get headerBgColor(){return this.get("headerBgColor")}get hintColor(){return this.get("hintColor")}get isDark(){return!this.bgColor||lt(this.bgColor)}get linkColor(){return this.get("linkColor")}get secondaryBgColor(){return this.get("secondaryBgColor")}get sectionBgColor(){return this.get("sectionBgColor")}get sectionHeaderTextColor(){return this.get("sectionHeaderTextColor")}listen(){return v("theme_changed",t=>{this.set(yt(t.theme_params))})}get subtitleTextColor(){return this.get("subtitleTextColor")}get textColor(){return this.get("textColor")}}const Ve=g("themeParams",({themeParams:e,state:t=e,addCleanup:s})=>{const n=new Me(t);return s(n.listen()),n});function Hs(e={}){return _({...e,method:"web_app_request_theme",event:"theme_changed"}).then(yt)}class $e extends vt{constructor(t,s,n){super(t,{readTextFromClipboard:"web_app_read_text_from_clipboard"}),c(this,"supportsParam"),this.version=t,this.createRequestId=s,this.postEvent=n,this.supportsParam=Re(t,{"openLink.tryInstantView":["web_app_open_link","try_instant_view"]})}openLink(t,s){const n=new URL(t,window.location.href).toString();if(!S("web_app_open_link",this.version)){window.open(n,"_blank");return}this.postEvent("web_app_open_link",{url:n,...typeof s=="boolean"?{try_instant_view:s}:{}})}openTelegramLink(t){const{hostname:s,pathname:n,search:r}=new URL(t,window.location.href);if(s!=="t.me")throw new Error(`URL has not allowed hostname: ${s}. Only "t.me" is allowed`);if(!S("web_app_open_tg_link",this.version)){window.location.href=t;return}this.postEvent("web_app_open_tg_link",{path_full:n+r})}async readTextFromClipboard(){const t=this.createRequestId(),{data:s=null}=await _({method:"web_app_read_text_from_clipboard",event:"clipboard_text_received",postEvent:this.postEvent,params:{req_id:t},capture:ut(t)});return s}}const Le=g(({version:e,postEvent:t,createRequestId:s})=>new $e(e,s,t));async function Et(e={}){const{is_expanded:t,is_state_stable:s,...n}=await _({...e,method:"web_app_request_viewport",event:"viewport_changed"});return{...n,isExpanded:t,isStateStable:s}}function q(e){return e<0?0:e}class He extends bt{constructor({postEvent:t,stableHeight:s,height:n,width:r,isExpanded:i}){super({height:q(n),isExpanded:i,stableHeight:q(s),width:q(r)}),c(this,"postEvent"),this.postEvent=t}async sync(t){const{isStateStable:s,...n}=await Et(t);this.set({...n,stableHeight:s?n.height:this.get("stableHeight")})}get height(){return this.get("height")}get stableHeight(){return this.get("stableHeight")}listen(){return v("viewport_changed",t=>{const{height:s,width:n,is_expanded:r,is_state_stable:i}=t,o=q(s);this.set({height:o,isExpanded:r,width:q(n),...i?{stableHeight:o}:{}})})}get isExpanded(){return this.get("isExpanded")}get width(){return this.get("width")}expand(){this.postEvent("web_app_expand"),this.set("isExpanded",!0)}get isStable(){return this.stableHeight===this.height}}const Ue=g("viewport",async({state:e,platform:t,postEvent:s,addCleanup:n})=>{let r=!1,i=0,o=0,a=0;if(e)r=e.isExpanded,i=e.height,o=e.width,a=e.stableHeight;else if(["macos","tdesktop","unigram","webk","weba","web"].includes(t))r=!0,i=window.innerHeight,o=window.innerWidth,a=window.innerHeight;else{const u=await Et({timeout:1e3,postEvent:s});r=u.isExpanded,i=u.height,o=u.width,a=u.isStateStable?i:0}const h=new He({postEvent:s,height:i,width:o,stableHeight:a,isExpanded:r});return n(h.listen()),h});function P(e,t){document.documentElement.style.setProperty(e,t)}function Us(e,t,s){s||(s=a=>`--tg-${a}-color`);const n=s("header"),r=s("bg"),i=()=>{const{headerColor:a}=e;if(j(a))P(n,a);else{const{bgColor:h,secondaryBgColor:u}=t;a==="bg_color"&&h?P(n,h):a==="secondary_bg_color"&&u&&P(n,u)}P(r,e.bgColor)},o=[t.on("change",i),e.on("change",i)];return i(),()=>o.forEach(a=>a())}function Ws(e,t){t||(t=n=>`--tg-theme-${n.replace(/[A-Z]/g,r=>`-${r.toLowerCase()}`)}`);const s=()=>{Object.entries(e.getState()).forEach(([n,r])=>{r&&P(t(n),r)})};return s(),e.on("change",s)}function js(e,t){t||(t=u=>`--tg-viewport-${u}`);const[s,n,r]=["height","width","stable-height"].map(u=>t(u)),i=()=>P(s,`${e.height}px`),o=()=>P(n,`${e.width}px`),a=()=>P(r,`${e.stableHeight}px`),h=[e.on("change:height",i),e.on("change:width",o),e.on("change:stableHeight",a)];return i(),o(),a(),()=>h.forEach(u=>u())}function We(e=!0){const t=[v("reload_iframe",()=>{A("iframe_will_reload"),window.location.reload()})],s=()=>t.forEach(n=>n());if(e){const n=document.createElement("style");n.id="telegram-custom-styles",document.head.appendChild(n),t.push(v("set_custom_style",r=>{n.innerHTML=r}),()=>document.head.removeChild(n))}return A("iframe_ready",{reload_supported:!0}),s}function Gs(){return typeof window>"u"}async function Ks(){if(zt(window))return!0;try{return await _({method:"web_app_request_theme",event:"theme_changed",timeout:100}),!0}catch{return!1}}function zs(e){const t=typeof e=="string"?J(e):e;ce(t);function s(r){if(typeof r=="string")try{const{eventType:i}=jt(r);i==="web_app_request_theme"&&nt("theme_changed",{theme_params:JSON.parse(ft(t.themeParams))}),i==="web_app_request_viewport"&&nt("viewport_changed",{width:window.innerWidth,height:window.innerHeight,is_state_stable:!0,is_expanded:!0})}catch{}}if(K()){const r=window.parent.postMessage.bind(window.parent);window.parent.postMessage=i=>{s(i),r(i)};return}if(Kt(window)){const r=window.external.notify.bind(window.external);window.external.notify=i=>{s(i),r(i)};return}const n=window.TelegramWebviewProxy;window.TelegramWebviewProxy={...n||{},postEvent(...r){s(JSON.stringify({eventType:r[0],eventData:r[1]})),n&&n.postEvent(...r)}}}function je(e){return e instanceof M}function Js(e,t){return je(e)&&e.type===t}function Q(e,t){let s,n,r;return typeof e=="string"?s=e:(s=e.pathname===void 0?t:e.pathname,n=e.params,r=e.id),Object.freeze({id:r||(Math.random()*2**14|0).toString(16),pathname:s,params:n})}class Ge{constructor(t,s,n=A){if(c(this,"history"),c(this,"ee",new R),c(this,"attached",!1),c(this,"back",()=>this.go(-1)),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this._index=s,this.postEvent=n,t.length===0)throw b($t,"History should not be empty.");if(s<0||s>=t.length)throw b(Lt,"Index should not be zero and higher or equal than history size.");this.history=t.map(r=>Q(r,""))}attach(){this.attached||(this.attached=!0,this.sync(),v("back_button_pressed",this.back))}get current(){return this.history[this.index]}detach(){this.attached=!1,V("back_button_pressed",this.back)}forward(){this.go(1)}go(t,s){const n=this.index+t,r=Math.min(Math.max(0,n),this.history.length-1);(n===r||s)&&this.replaceAndMove(r,this.history[r])}goTo(t,s){this.go(t-this.index,s)}get hasPrev(){return this.index>0}get hasNext(){return this.index!==this.history.length-1}get index(){return this._index}push(t){this.hasNext&&this.history.splice(this.index+1),this.replaceAndMove(this.index+1,Q(t,this.current.pathname))}replace(t){this.replaceAndMove(this.index,Q(t,this.current.pathname))}replaceAndMove(t,s){const n=t-this.index;if(!n&&this.current===s)return;const r=this.current;if(this.index!==t){const i=this._index;this._index=t,this.attached&&i>0!=t>0&&this.sync()}this.history[t]=s,this.ee.emit("change",{navigator:this,from:r,to:this.current,delta:n})}sync(){this.postEvent("web_app_setup_back_button",{is_visible:!!this.index})}}function Y({params:e,...t}){return{...e||{hash:"",search:""},...t}}function D(e,t){return e.startsWith(t)?e:`${t}${e}`}function N(e){return new URL(typeof e=="string"?e:`${e.pathname||""}${D(e.search||"","?")}${D(e.hash||"","#")}`,"http://a")}function B(e){const t=typeof e=="string"?e.startsWith("/"):!!(e.pathname&&e.pathname.startsWith("/")),s=N(e);return`${t?s.pathname:s.pathname.slice(1)}${s.search}${s.hash}`}function Z(e,t,s){let n,r;typeof e=="string"?n=e:(n=B(e),s=e.state,r=e.id);const{pathname:i,search:o,hash:a}=new URL(n,`http://a${D(t,"/")}`);return{id:r,pathname:i,params:{hash:a,search:o,state:s}}}async function O(e){return e===0?!0:Promise.race([new Promise(t=>{const s=st("popstate",()=>{s(),t(!0)});window.history.go(e)}),new Promise(t=>{setTimeout(t,50,!1)})])}async function Fs(){if(window.history.length<=1||(window.history.pushState(null,""),await O(1-window.history.length)))return;let e=await O(-1);for(;e;)e=await O(-1)}function Pt(e){return N(e).pathname}const At=0,X=1,tt=2;class xt{constructor(t,s,{postEvent:n,hashMode:r="classic",base:i}={}){c(this,"navigator"),c(this,"ee",new R),c(this,"hashMode"),c(this,"base"),c(this,"attached",!1),c(this,"onPopState",({state:o})=>{if(o===null)return this.push(this.parsePath(window.location.href));o===At?window.history.forward():o===X&&this.back(),o===tt&&this.forward()}),c(this,"onNavigatorChange",async({to:o,from:a,delta:h})=>{this.attached&&await this.syncHistory(),this.ee.emit("change",{delta:h,from:Y(a),to:Y(o),navigator:this})}),c(this,"on",this.ee.on.bind(this.ee)),c(this,"off",this.ee.off.bind(this.ee)),this.navigator=new Ge(t.map(o=>Z(o,"/")),s,n),this.navigator.on("change",this.onNavigatorChange),this.hashMode=r,this.base=Pt(i||"")}async attach(){this.attached||(this.attached=!0,this.navigator.attach(),window.addEventListener("popstate",this.onPopState),await this.syncHistory())}back(){this.navigator.back()}detach(){this.attached=!1,this.navigator.detach(),window.removeEventListener("popstate",this.onPopState)}forward(){return this.navigator.forward()}get index(){return this.navigator.index}get id(){return this.navigator.current.id}go(t,s){return this.navigator.go(t,s)}goTo(t,s){this.navigator.goTo(t,s)}get hash(){return(this.navigator.current.params||{}).hash||""}get hasPrev(){return this.navigator.hasPrev}get hasNext(){return this.navigator.hasNext}get history(){return this.navigator.history.map(Y)}get path(){return B(this)}get pathname(){return this.navigator.current.pathname}parsePath(t){let s=N(t);return this.hashMode&&(s=N(s.hash.slice(1))),{pathname:s.pathname,search:s.search,hash:s.hash}}push(t,s){const n=Z(t,this.path),{state:r=s}=n.params;this.navigator.push({...n,params:{...n.params,state:r}})}replace(t,s){const n=Z(t,this.path),{state:r=s}=n.params;this.navigator.replace({...n,params:{...n.params,state:r}})}renderPath(t){const s=(this.base.length===1?"":this.base)+D(B(t),"/");return this.hashMode?D(s.slice(1),this.hashMode==="classic"?"#":"#/"):s}async syncHistory(){window.removeEventListener("popstate",this.onPopState);const{state:t}=this,s=this.renderPath(this);await Fs(),this.hasPrev&&this.hasNext?(window.history.replaceState(X,""),window.history.pushState(t,"",s),window.history.pushState(tt,""),await O(-1)):this.hasPrev?(window.history.replaceState(X,""),window.history.pushState(t,"",s)):this.hasNext?(window.history.replaceState(t,s),window.history.pushState(tt,""),await O(-1)):(window.history.replaceState(At,""),window.history.pushState(t,"",s)),window.addEventListener("popstate",this.onPopState)}get search(){return(this.navigator.current.params||{}).search||""}get state(){return(this.navigator.current.params||{}).state}}function Ke(e){e||(e={});const{href:t,hash:s}=window.location;let n=B(e.hashMode===null?t:s.includes("?")?s.slice(1):`?${s.slice(1)}`);const r=e.base?Pt(e.base):void 0;if(r){if(!n.startsWith(r))throw b(Ht,`Path "${n}" expected to be starting with "${r}"`);n=n.slice(r.length)}return new xt([n],0,e)}function Qs(e){const t=e.match(/#(.+)/);return t?t[1]:null}function Ys(e,t){if(mt()){const s=sessionStorage.getItem(e);if(s)try{const{index:n,history:r}=JSON.parse(s);return new xt(r,n,t)}catch(n){console.error("Unable to restore hash navigator state.",n)}}return Ke(t)}function Zs(e,t){const s=Ys(e,t),n=()=>sessionStorage.setItem(e,JSON.stringify({index:s.index,history:s.history}));return s.on("change",n),n(),s}function w(e){return(t,s,...n)=>r=>m.createComponent(s,m.mergeProps(()=>m.mergeProps({[t]:e(...n)},r)))}const ze=m.createContext();function Je(){const e=m.useContext(ze);if(!e)throw new Error("useSDK was used outside of SDKProvider.");return e}function f(e){return(...t)=>{const s=Je()(e,...t),n=()=>s.signal();return Object.defineProperty(n,"error",()=>s.error),n}}const Fe=f(pe),Xs=w(Fe),Qe=f(_e),tn=w(Qe),Ye=f(we),en=w(Ye),Ze=f(be),sn=w(Ze),Xe=f(ye),nn=w(Xe),ts=f(Pe),rn=w(ts),es=f(Se),on=w(es),ss=f(Te),an=w(ss),ns=f(Ie),cn=w(ns),rs=f(qe),hn=w(rs),is=f(De),pn=w(is),os=f(Be),un=w(os),as=f(Ve),dn=w(as),cs=f(Le),ln=w(cs),hs=f(Ue),_n=w(hs),gn=e=>{const t=new Map,s=(n,...r)=>{if(t.has(n))return t.get(n);function i(d){return t.set(n,d),d}let o;try{o=n(...r)}catch(d){return i({error:d,signal:()=>{throw d}})}let a;Array.isArray(o)&&([o,a]=o);const[h]=m.createResource(()=>o),u=m.createMemo(()=>{if(h.state!=="ready")return;const d=h();if(!d||!("on"in d))return d;const ps=m.from(H=>(H(d),d.on("change",()=>H(d)))),us=Object.getPrototypeOf(d),F={};return new Proxy(d,{get(H,C){if(!(C in F)){const St=Reflect.getOwnPropertyDescriptor(us,C);F[C]=St&&"get"in St?m.createMemo(()=>ps()[C]):()=>Reflect.get(H,C)}return F[C]()}})});return i({signal(){if(h.error)throw h.error;return u()},get error(){return h.error},cleanup:a})};return m.createEffect(()=>{qt(e.debug||!1)}),m.createEffect(()=>{K()&&m.onCleanup(We(e.acceptCustomStyles))}),m.onCleanup(()=>{t.forEach(n=>n.cleanup&&n.cleanup())}),m.createComponent(ze.Provider,{value:s,get children(){return e.children}})};exports.BackButton=Xt;exports.BasicNavigator=Ge;exports.BiometryManager=de;exports.BrowserNavigator=xt;exports.ClosingBehavior=ge;exports.CloudStorage=me;exports.ERR_INVALID_PATH_BASE=Ht;exports.ERR_INVOKE_CUSTOM_METHOD_RESPONSE=Bt;exports.ERR_METHOD_PARAMETER_UNSUPPORTED=Dt;exports.ERR_METHOD_UNSUPPORTED=Ot;exports.ERR_NAVIGATION_HISTORY_EMPTY=$t;exports.ERR_NAVIGATION_INDEX_INVALID=Lt;exports.ERR_NAVIGATION_ITEM_INVALID=ws;exports.ERR_PARSE=at;exports.ERR_SSR_INIT=fs;exports.ERR_TIMED_OUT=Mt;exports.ERR_UNEXPECTED_TYPE=Vt;exports.ERR_UNKNOWN_ENV=Nt;exports.EventEmitter=R;exports.HapticFeedback=ve;exports.InitData=Ee;exports.Invoice=xe;exports.MainButton=Ce;exports.MiniApp=Ae;exports.Popup=ke;exports.QRScanner=Oe;exports.SDKError=M;exports.SDKProvider=gn;exports.SettingsButton=Ne;exports.ThemeParams=Me;exports.Utils=$e;exports.Viewport=He;exports.array=fe;exports.bindMiniAppCSSVars=Us;exports.bindThemeParamsCSSVars=Ws;exports.bindViewportCSSVars=js;exports.boolean=E;exports.captureSameReq=ut;exports.classNames=U;exports.compareVersions=Gt;exports.createBrowserNavigatorFromLocation=Ke;exports.createPostEvent=Qt;exports.createSafeURL=N;exports.date=wt;exports.getHash=Qs;exports.getPathname=Pt;exports.initBackButton=pe;exports.initBiometryManager=_e;exports.initClosingBehavior=we;exports.initCloudStorage=be;exports.initHapticFeedback=ye;exports.initInitData=Pe;exports.initInvoice=Se;exports.initMainButton=Te;exports.initMiniApp=Ie;exports.initNavigator=Zs;exports.initPopup=qe;exports.initQRScanner=De;exports.initSettingsButton=Be;exports.initThemeParams=Ve;exports.initUtils=Le;exports.initViewport=Ue;exports.initWeb=We;exports.invokeCustomMethod=T;exports.isColorDark=lt;exports.isIframe=K;exports.isPageReload=mt;exports.isRGB=j;exports.isRGBShort=Wt;exports.isSDKError=je;exports.isSDKErrorOfType=Js;exports.isSSR=Gs;exports.isTMA=Ks;exports.json=l;exports.mergeClassNames=Ss;exports.mockTelegramEnv=zs;exports.number=x;exports.off=V;exports.on=v;exports.parseInitData=Ms;exports.parseLaunchParams=J;exports.parseThemeParams=yt;exports.postEvent=A;exports.request=_;exports.requestBiometryInfo=le;exports.requestThemeParams=Hs;exports.requestViewport=Et;exports.retrieveLaunchParams=he;exports.rgb=pt;exports.searchParams=z;exports.serializeLaunchParams=ae;exports.serializeThemeParams=ft;exports.setCSSVar=P;exports.setDebug=qt;exports.setTargetOrigin=xs;exports.string=p;exports.subscribe=kt;exports.supports=S;exports.targetOrigin=Ft;exports.toRGB=ht;exports.unsubscribe=rt;exports.urlToPath=B;exports.useBackButton=Fe;exports.useBiometryManager=Qe;exports.useClosingBehavior=Ye;exports.useCloudStorage=Ze;exports.useHapticFeedback=Xe;exports.useInitData=ts;exports.useInvoice=es;exports.useMainButton=ss;exports.useMiniApp=ns;exports.usePopup=rs;exports.useQRScanner=is;exports.useSDK=Je;exports.useSettingsButton=os;exports.useThemeParams=as;exports.useUtils=cs;exports.useViewport=hs;exports.withBackButton=Xs;exports.withBiometryManager=tn;exports.withClosingBehavior=en;exports.withCloudStorage=sn;exports.withHapticFeedback=nn;exports.withInitData=rn;exports.withInvoice=on;exports.withMainButton=an;exports.withMiniApp=cn;exports.withPopup=hn;exports.withQRScanner=pn;exports.withSettingsButton=un;exports.withThemeParams=dn;exports.withTimeout=dt;exports.withUtils=ln;exports.withViewport=_n;
2
2
  //# sourceMappingURL=index.cjs.map