hm-tracking-sdk 0.1.5 → 0.1.8

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.
@@ -8,7 +8,7 @@
8
8
  `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(f){return f instanceof this?f:new this(f)}static concat(f,...d){const m=new this(f);return d.forEach(v=>m.set(v)),m}static accessor(f){const m=(this[$internals]=this[$internals]={accessors:{}}).accessors,v=this.prototype;function g(w){const _=normalizeHeader(w);m[_]||(buildAccessors(v,w),m[_]=!0)}return utils$5.isArray(f)?f.forEach(g):g(f),this}};AxiosHeaders$1.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),utils$5.reduceDescriptors(AxiosHeaders$1.prototype,({value:r},f)=>{let d=f[0].toUpperCase()+f.slice(1);return{get:()=>r,set(m){this[d]=m}}}),utils$5.freezeMethods(AxiosHeaders$1);function transformData(r,f){const d=this||defaults,m=f||d,v=AxiosHeaders$1.from(m.headers);let g=m.data;return utils$5.forEach(r,function(_){g=_.call(d,g,v.normalize(),f?f.status:void 0)}),v.normalize(),g}function isCancel$1(r){return!!(r&&r.__CANCEL__)}function CanceledError$1(r,f,d){AxiosError$1.call(this,r??"canceled",AxiosError$1.ERR_CANCELED,f,d),this.name="CanceledError"}utils$5.inherits(CanceledError$1,AxiosError$1,{__CANCEL__:!0});function settle(r,f,d){const m=d.config.validateStatus;!d.status||!m||m(d.status)?r(d):f(new AxiosError$1("Request failed with status code "+d.status,[AxiosError$1.ERR_BAD_REQUEST,AxiosError$1.ERR_BAD_RESPONSE][Math.floor(d.status/100)-4],d.config,d.request,d))}function parseProtocol(r){const f=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return f&&f[1]||""}function speedometer(r,f){r=r||10;const d=new Array(r),m=new Array(r);let v=0,g=0,w;return f=f!==void 0?f:1e3,function(S){const x=Date.now(),b=m[g];w||(w=x),d[v]=S,m[v]=x;let C=g,E=0;for(;C!==v;)E+=d[C++],C=C%r;if(v=(v+1)%r,v===g&&(g=(g+1)%r),x-w<f)return;const M=b&&x-b;return M?Math.round(E*1e3/M):void 0}}function throttle(r,f){let d=0,m=1e3/f,v,g;const w=(x,b=Date.now())=>{d=b,v=null,g&&(clearTimeout(g),g=null),r(...x)};return[(...x)=>{const b=Date.now(),C=b-d;C>=m?w(x,b):(v=x,g||(g=setTimeout(()=>{g=null,w(v)},m-C)))},()=>v&&w(v)]}const progressEventReducer=(r,f,d=3)=>{let m=0;const v=speedometer(50,250);return throttle(g=>{const w=g.loaded,_=g.lengthComputable?g.total:void 0,S=w-m,x=v(S),b=w<=_;m=w;const C={loaded:w,total:_,progress:_?w/_:void 0,bytes:S,rate:x||void 0,estimated:x&&_&&b?(_-w)/x:void 0,event:g,lengthComputable:_!=null,[f?"download":"upload"]:!0};r(C)},d)},progressEventDecorator=(r,f)=>{const d=r!=null;return[m=>f[0]({lengthComputable:d,total:r,loaded:m}),f[1]]},asyncDecorator=r=>(...f)=>utils$5.asap(()=>r(...f)),isURLSameOrigin=platform$1.hasStandardBrowserEnv?((r,f)=>d=>(d=new URL(d,platform$1.origin),r.protocol===d.protocol&&r.host===d.host&&(f||r.port===d.port)))(new URL(platform$1.origin),platform$1.navigator&&/(msie|trident)/i.test(platform$1.navigator.userAgent)):()=>!0,cookies=platform$1.hasStandardBrowserEnv?{write(r,f,d,m,v,g){const w=[r+"="+encodeURIComponent(f)];utils$5.isNumber(d)&&w.push("expires="+new Date(d).toGMTString()),utils$5.isString(m)&&w.push("path="+m),utils$5.isString(v)&&w.push("domain="+v),g===!0&&w.push("secure"),document.cookie=w.join("; ")},read(r){const f=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return f?decodeURIComponent(f[3]):null},remove(r){this.write(r,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function isAbsoluteURL(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function combineURLs(r,f){return f?r.replace(/\/?\/$/,"")+"/"+f.replace(/^\/+/,""):r}function buildFullPath(r,f,d){let m=!isAbsoluteURL(f);return r&&(m||d==!1)?combineURLs(r,f):f}const headersToObject=r=>r instanceof AxiosHeaders$1?{...r}:r;function mergeConfig$1(r,f){f=f||{};const d={};function m(x,b,C,E){return utils$5.isPlainObject(x)&&utils$5.isPlainObject(b)?utils$5.merge.call({caseless:E},x,b):utils$5.isPlainObject(b)?utils$5.merge({},b):utils$5.isArray(b)?b.slice():b}function v(x,b,C,E){if(utils$5.isUndefined(b)){if(!utils$5.isUndefined(x))return m(void 0,x,C,E)}else return m(x,b,C,E)}function g(x,b){if(!utils$5.isUndefined(b))return m(void 0,b)}function w(x,b){if(utils$5.isUndefined(b)){if(!utils$5.isUndefined(x))return m(void 0,x)}else return m(void 0,b)}function _(x,b,C){if(C in f)return m(x,b);if(C in r)return m(void 0,x)}const S={url:g,method:g,data:g,baseURL:w,transformRequest:w,transformResponse:w,paramsSerializer:w,timeout:w,timeoutMessage:w,withCredentials:w,withXSRFToken:w,adapter:w,responseType:w,xsrfCookieName:w,xsrfHeaderName:w,onUploadProgress:w,onDownloadProgress:w,decompress:w,maxContentLength:w,maxBodyLength:w,beforeRedirect:w,transport:w,httpAgent:w,httpsAgent:w,cancelToken:w,socketPath:w,responseEncoding:w,validateStatus:_,headers:(x,b,C)=>v(headersToObject(x),headersToObject(b),C,!0)};return utils$5.forEach(Object.keys({...r,...f}),function(b){const C=S[b]||v,E=C(r[b],f[b],b);utils$5.isUndefined(E)&&C!==_||(d[b]=E)}),d}const resolveConfig=r=>{const f=mergeConfig$1({},r);let{data:d,withXSRFToken:m,xsrfHeaderName:v,xsrfCookieName:g,headers:w,auth:_}=f;f.headers=w=AxiosHeaders$1.from(w),f.url=buildURL(buildFullPath(f.baseURL,f.url,f.allowAbsoluteUrls),r.params,r.paramsSerializer),_&&w.set("Authorization","Basic "+btoa((_.username||"")+":"+(_.password?unescape(encodeURIComponent(_.password)):"")));let S;if(utils$5.isFormData(d)){if(platform$1.hasStandardBrowserEnv||platform$1.hasStandardBrowserWebWorkerEnv)w.setContentType(void 0);else if((S=w.getContentType())!==!1){const[x,...b]=S?S.split(";").map(C=>C.trim()).filter(Boolean):[];w.setContentType([x||"multipart/form-data",...b].join("; "))}}if(platform$1.hasStandardBrowserEnv&&(m&&utils$5.isFunction(m)&&(m=m(f)),m||m!==!1&&isURLSameOrigin(f.url))){const x=v&&g&&cookies.read(g);x&&w.set(v,x)}return f},isXHRAdapterSupported=typeof XMLHttpRequest<"u",xhrAdapter=isXHRAdapterSupported&&function(r){return new Promise(function(d,m){const v=resolveConfig(r);let g=v.data;const w=AxiosHeaders$1.from(v.headers).normalize();let{responseType:_,onUploadProgress:S,onDownloadProgress:x}=v,b,C,E,M,A;function T(){M&&M(),A&&A(),v.cancelToken&&v.cancelToken.unsubscribe(b),v.signal&&v.signal.removeEventListener("abort",b)}let L=new XMLHttpRequest;L.open(v.method.toUpperCase(),v.url,!0),L.timeout=v.timeout;function O(){if(!L)return;const H=AxiosHeaders$1.from("getAllResponseHeaders"in L&&L.getAllResponseHeaders()),X={data:!_||_==="text"||_==="json"?L.responseText:L.response,status:L.status,statusText:L.statusText,headers:H,config:r,request:L};settle(function(se){d(se),T()},function(se){m(se),T()},X),L=null}"onloadend"in L?L.onloadend=O:L.onreadystatechange=function(){!L||L.readyState!==4||L.status===0&&!(L.responseURL&&L.responseURL.indexOf("file:")===0)||setTimeout(O)},L.onabort=function(){L&&(m(new AxiosError$1("Request aborted",AxiosError$1.ECONNABORTED,r,L)),L=null)},L.onerror=function(){m(new AxiosError$1("Network Error",AxiosError$1.ERR_NETWORK,r,L)),L=null},L.ontimeout=function(){let V=v.timeout?"timeout of "+v.timeout+"ms exceeded":"timeout exceeded";const X=v.transitional||transitionalDefaults;v.timeoutErrorMessage&&(V=v.timeoutErrorMessage),m(new AxiosError$1(V,X.clarifyTimeoutError?AxiosError$1.ETIMEDOUT:AxiosError$1.ECONNABORTED,r,L)),L=null},g===void 0&&w.setContentType(null),"setRequestHeader"in L&&utils$5.forEach(w.toJSON(),function(V,X){L.setRequestHeader(X,V)}),utils$5.isUndefined(v.withCredentials)||(L.withCredentials=!!v.withCredentials),_&&_!=="json"&&(L.responseType=v.responseType),x&&([E,A]=progressEventReducer(x,!0),L.addEventListener("progress",E)),S&&L.upload&&([C,M]=progressEventReducer(S),L.upload.addEventListener("progress",C),L.upload.addEventListener("loadend",M)),(v.cancelToken||v.signal)&&(b=H=>{L&&(m(!H||H.type?new CanceledError$1(null,r,L):H),L.abort(),L=null)},v.cancelToken&&v.cancelToken.subscribe(b),v.signal&&(v.signal.aborted?b():v.signal.addEventListener("abort",b)));const N=parseProtocol(v.url);if(N&&platform$1.protocols.indexOf(N)===-1){m(new AxiosError$1("Unsupported protocol "+N+":",AxiosError$1.ERR_BAD_REQUEST,r));return}L.send(g||null)})},composeSignals=(r,f)=>{const{length:d}=r=r?r.filter(Boolean):[];if(f||d){let m=new AbortController,v;const g=function(x){if(!v){v=!0,_();const b=x instanceof Error?x:this.reason;m.abort(b instanceof AxiosError$1?b:new CanceledError$1(b instanceof Error?b.message:b))}};let w=f&&setTimeout(()=>{w=null,g(new AxiosError$1(`timeout ${f} of ms exceeded`,AxiosError$1.ETIMEDOUT))},f);const _=()=>{r&&(w&&clearTimeout(w),w=null,r.forEach(x=>{x.unsubscribe?x.unsubscribe(g):x.removeEventListener("abort",g)}),r=null)};r.forEach(x=>x.addEventListener("abort",g));const{signal:S}=m;return S.unsubscribe=()=>utils$5.asap(_),S}},streamChunk=function*(r,f){let d=r.byteLength;if(d<f){yield r;return}let m=0,v;for(;m<d;)v=m+f,yield r.slice(m,v),m=v},readBytes=async function*(r,f){for await(const d of readStream(r))yield*streamChunk(d,f)},readStream=async function*(r){if(r[Symbol.asyncIterator]){yield*r;return}const f=r.getReader();try{for(;;){const{done:d,value:m}=await f.read();if(d)break;yield m}}finally{await f.cancel()}},trackStream=(r,f,d,m)=>{const v=readBytes(r,f);let g=0,w,_=S=>{w||(w=!0,m&&m(S))};return new ReadableStream({async pull(S){try{const{done:x,value:b}=await v.next();if(x){_(),S.close();return}let C=b.byteLength;if(d){let E=g+=C;d(E)}S.enqueue(new Uint8Array(b))}catch(x){throw _(x),x}},cancel(S){return _(S),v.return()}},{highWaterMark:2})},isFetchSupported=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",isReadableStreamSupported=isFetchSupported&&typeof ReadableStream=="function",encodeText=isFetchSupported&&(typeof TextEncoder=="function"?(r=>f=>r.encode(f))(new TextEncoder):async r=>new Uint8Array(await new Response(r).arrayBuffer())),test=(r,...f)=>{try{return!!r(...f)}catch{return!1}},supportsRequestStream=isReadableStreamSupported&&test(()=>{let r=!1;const f=new Request(platform$1.origin,{body:new ReadableStream,method:"POST",get duplex(){return r=!0,"half"}}).headers.has("Content-Type");return r&&!f}),DEFAULT_CHUNK_SIZE=64*1024,supportsResponseStream=isReadableStreamSupported&&test(()=>utils$5.isReadableStream(new Response("").body)),resolvers={stream:supportsResponseStream&&(r=>r.body)};isFetchSupported&&(r=>{["text","arrayBuffer","blob","formData","stream"].forEach(f=>{!resolvers[f]&&(resolvers[f]=utils$5.isFunction(r[f])?d=>d[f]():(d,m)=>{throw new AxiosError$1(`Response type '${f}' is not supported`,AxiosError$1.ERR_NOT_SUPPORT,m)})})})(new Response);const getBodyLength=async r=>{if(r==null)return 0;if(utils$5.isBlob(r))return r.size;if(utils$5.isSpecCompliantForm(r))return(await new Request(platform$1.origin,{method:"POST",body:r}).arrayBuffer()).byteLength;if(utils$5.isArrayBufferView(r)||utils$5.isArrayBuffer(r))return r.byteLength;if(utils$5.isURLSearchParams(r)&&(r=r+""),utils$5.isString(r))return(await encodeText(r)).byteLength},resolveBodyLength=async(r,f)=>{const d=utils$5.toFiniteNumber(r.getContentLength());return d??getBodyLength(f)},fetchAdapter=isFetchSupported&&(async r=>{let{url:f,method:d,data:m,signal:v,cancelToken:g,timeout:w,onDownloadProgress:_,onUploadProgress:S,responseType:x,headers:b,withCredentials:C="same-origin",fetchOptions:E}=resolveConfig(r);x=x?(x+"").toLowerCase():"text";let M=composeSignals([v,g&&g.toAbortSignal()],w),A;const T=M&&M.unsubscribe&&(()=>{M.unsubscribe()});let L;try{if(S&&supportsRequestStream&&d!=="get"&&d!=="head"&&(L=await resolveBodyLength(b,m))!==0){let X=new Request(f,{method:"POST",body:m,duplex:"half"}),oe;if(utils$5.isFormData(m)&&(oe=X.headers.get("content-type"))&&b.setContentType(oe),X.body){const[se,de]=progressEventDecorator(L,progressEventReducer(asyncDecorator(S)));m=trackStream(X.body,DEFAULT_CHUNK_SIZE,se,de)}}utils$5.isString(C)||(C=C?"include":"omit");const O="credentials"in Request.prototype;A=new Request(f,{...E,signal:M,method:d.toUpperCase(),headers:b.normalize().toJSON(),body:m,duplex:"half",credentials:O?C:void 0});let N=await fetch(A,E);const H=supportsResponseStream&&(x==="stream"||x==="response");if(supportsResponseStream&&(_||H&&T)){const X={};["status","statusText","headers"].forEach(he=>{X[he]=N[he]});const oe=utils$5.toFiniteNumber(N.headers.get("content-length")),[se,de]=_&&progressEventDecorator(oe,progressEventReducer(asyncDecorator(_),!0))||[];N=new Response(trackStream(N.body,DEFAULT_CHUNK_SIZE,se,()=>{de&&de(),T&&T()}),X)}x=x||"text";let V=await resolvers[utils$5.findKey(resolvers,x)||"text"](N,r);return!H&&T&&T(),await new Promise((X,oe)=>{settle(X,oe,{data:V,headers:AxiosHeaders$1.from(N.headers),status:N.status,statusText:N.statusText,config:r,request:A})})}catch(O){throw T&&T(),O&&O.name==="TypeError"&&/Load failed|fetch/i.test(O.message)?Object.assign(new AxiosError$1("Network Error",AxiosError$1.ERR_NETWORK,r,A),{cause:O.cause||O}):AxiosError$1.from(O,O&&O.code,r,A)}}),knownAdapters={http:httpAdapter,xhr:xhrAdapter,fetch:fetchAdapter};utils$5.forEach(knownAdapters,(r,f)=>{if(r){try{Object.defineProperty(r,"name",{value:f})}catch{}Object.defineProperty(r,"adapterName",{value:f})}});const renderReason=r=>`- ${r}`,isResolvedHandle=r=>utils$5.isFunction(r)||r===null||r===!1,adapters={getAdapter:r=>{r=utils$5.isArray(r)?r:[r];const{length:f}=r;let d,m;const v={};for(let g=0;g<f;g++){d=r[g];let w;if(m=d,!isResolvedHandle(d)&&(m=knownAdapters[(w=String(d)).toLowerCase()],m===void 0))throw new AxiosError$1(`Unknown adapter '${w}'`);if(m)break;v[w||"#"+g]=m}if(!m){const g=Object.entries(v).map(([_,S])=>`adapter ${_} `+(S===!1?"is not supported by the environment":"is not available in the build"));let w=f?g.length>1?`since :
9
9
  `+g.map(renderReason).join(`
10
10
  `):" "+renderReason(g[0]):"as no adapter specified";throw new AxiosError$1("There is no suitable adapter to dispatch the request "+w,"ERR_NOT_SUPPORT")}return m},adapters:knownAdapters};function throwIfCancellationRequested(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new CanceledError$1(null,r)}function dispatchRequest(r){return throwIfCancellationRequested(r),r.headers=AxiosHeaders$1.from(r.headers),r.data=transformData.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),adapters.getAdapter(r.adapter||defaults.adapter)(r).then(function(m){return throwIfCancellationRequested(r),m.data=transformData.call(r,r.transformResponse,m),m.headers=AxiosHeaders$1.from(m.headers),m},function(m){return isCancel$1(m)||(throwIfCancellationRequested(r),m&&m.response&&(m.response.data=transformData.call(r,r.transformResponse,m.response),m.response.headers=AxiosHeaders$1.from(m.response.headers))),Promise.reject(m)})}const VERSION$1="1.11.0",validators$1={};["object","boolean","number","function","string","symbol"].forEach((r,f)=>{validators$1[r]=function(m){return typeof m===r||"a"+(f<1?"n ":" ")+r}});const deprecatedWarnings={};validators$1.transitional=function(f,d,m){function v(g,w){return"[Axios v"+VERSION$1+"] Transitional option '"+g+"'"+w+(m?". "+m:"")}return(g,w,_)=>{if(f===!1)throw new AxiosError$1(v(w," has been removed"+(d?" in "+d:"")),AxiosError$1.ERR_DEPRECATED);return d&&!deprecatedWarnings[w]&&(deprecatedWarnings[w]=!0),f?f(g,w,_):!0}},validators$1.spelling=function(f){return(d,m)=>!0};function assertOptions(r,f,d){if(typeof r!="object")throw new AxiosError$1("options must be an object",AxiosError$1.ERR_BAD_OPTION_VALUE);const m=Object.keys(r);let v=m.length;for(;v-- >0;){const g=m[v],w=f[g];if(w){const _=r[g],S=_===void 0||w(_,g,r);if(S!==!0)throw new AxiosError$1("option "+g+" must be "+S,AxiosError$1.ERR_BAD_OPTION_VALUE);continue}if(d!==!0)throw new AxiosError$1("Unknown option "+g,AxiosError$1.ERR_BAD_OPTION)}}const validator={assertOptions,validators:validators$1},validators=validator.validators;let Axios$1=class{constructor(f){this.defaults=f||{},this.interceptors={request:new InterceptorManager,response:new InterceptorManager}}async request(f,d){try{return await this._request(f,d)}catch(m){if(m instanceof Error){let v={};Error.captureStackTrace?Error.captureStackTrace(v):v=new Error;const g=v.stack?v.stack.replace(/^.+\n/,""):"";try{m.stack?g&&!String(m.stack).endsWith(g.replace(/^.+\n.+\n/,""))&&(m.stack+=`
11
- `+g):m.stack=g}catch{}}throw m}}_request(f,d){typeof f=="string"?(d=d||{},d.url=f):d=f||{},d=mergeConfig$1(this.defaults,d);const{transitional:m,paramsSerializer:v,headers:g}=d;m!==void 0&&validator.assertOptions(m,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1),v!=null&&(utils$5.isFunction(v)?d.paramsSerializer={serialize:v}:validator.assertOptions(v,{encode:validators.function,serialize:validators.function},!0)),d.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?d.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:d.allowAbsoluteUrls=!0),validator.assertOptions(d,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),d.method=(d.method||this.defaults.method||"get").toLowerCase();let w=g&&utils$5.merge(g.common,g[d.method]);g&&utils$5.forEach(["delete","get","head","post","put","patch","common"],A=>{delete g[A]}),d.headers=AxiosHeaders$1.concat(w,g);const _=[];let S=!0;this.interceptors.request.forEach(function(T){typeof T.runWhen=="function"&&T.runWhen(d)===!1||(S=S&&T.synchronous,_.unshift(T.fulfilled,T.rejected))});const x=[];this.interceptors.response.forEach(function(T){x.push(T.fulfilled,T.rejected)});let b,C=0,E;if(!S){const A=[dispatchRequest.bind(this),void 0];for(A.unshift(..._),A.push(...x),E=A.length,b=Promise.resolve(d);C<E;)b=b.then(A[C++],A[C++]);return b}E=_.length;let M=d;for(C=0;C<E;){const A=_[C++],T=_[C++];try{M=A(M)}catch(L){T.call(this,L);break}}try{b=dispatchRequest.call(this,M)}catch(A){return Promise.reject(A)}for(C=0,E=x.length;C<E;)b=b.then(x[C++],x[C++]);return b}getUri(f){f=mergeConfig$1(this.defaults,f);const d=buildFullPath(f.baseURL,f.url,f.allowAbsoluteUrls);return buildURL(d,f.params,f.paramsSerializer)}};utils$5.forEach(["delete","get","head","options"],function(f){Axios$1.prototype[f]=function(d,m){return this.request(mergeConfig$1(m||{},{method:f,url:d,data:(m||{}).data}))}}),utils$5.forEach(["post","put","patch"],function(f){function d(m){return function(g,w,_){return this.request(mergeConfig$1(_||{},{method:f,headers:m?{"Content-Type":"multipart/form-data"}:{},url:g,data:w}))}}Axios$1.prototype[f]=d(),Axios$1.prototype[f+"Form"]=d(!0)});let CancelToken$1=class Gt{constructor(f){if(typeof f!="function")throw new TypeError("executor must be a function.");let d;this.promise=new Promise(function(g){d=g});const m=this;this.promise.then(v=>{if(!m._listeners)return;let g=m._listeners.length;for(;g-- >0;)m._listeners[g](v);m._listeners=null}),this.promise.then=v=>{let g;const w=new Promise(_=>{m.subscribe(_),g=_}).then(v);return w.cancel=function(){m.unsubscribe(g)},w},f(function(g,w,_){m.reason||(m.reason=new CanceledError$1(g,w,_),d(m.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(f){if(this.reason){f(this.reason);return}this._listeners?this._listeners.push(f):this._listeners=[f]}unsubscribe(f){if(!this._listeners)return;const d=this._listeners.indexOf(f);d!==-1&&this._listeners.splice(d,1)}toAbortSignal(){const f=new AbortController,d=m=>{f.abort(m)};return this.subscribe(d),f.signal.unsubscribe=()=>this.unsubscribe(d),f.signal}static source(){let f;return{token:new Gt(function(v){f=v}),cancel:f}}};function spread$2(r){return function(d){return r.apply(null,d)}}function isAxiosError$1(r){return utils$5.isObject(r)&&r.isAxiosError===!0}const HttpStatusCode$1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(HttpStatusCode$1).forEach(([r,f])=>{HttpStatusCode$1[f]=r});function createInstance(r){const f=new Axios$1(r),d=bind(Axios$1.prototype.request,f);return utils$5.extend(d,Axios$1.prototype,f,{allOwnKeys:!0}),utils$5.extend(d,f,null,{allOwnKeys:!0}),d.create=function(v){return createInstance(mergeConfig$1(r,v))},d}const axios=createInstance(defaults);axios.Axios=Axios$1,axios.CanceledError=CanceledError$1,axios.CancelToken=CancelToken$1,axios.isCancel=isCancel$1,axios.VERSION=VERSION$1,axios.toFormData=toFormData$1,axios.AxiosError=AxiosError$1,axios.Cancel=axios.CanceledError,axios.all=function(f){return Promise.all(f)},axios.spread=spread$2,axios.isAxiosError=isAxiosError$1,axios.mergeConfig=mergeConfig$1,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=r=>formDataToJSON(utils$5.isHTMLForm(r)?new FormData(r):r),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;const{Axios,AxiosError,CanceledError,isCancel,CancelToken,VERSION,all,Cancel,isAxiosError,spread:spread$1,toFormData,AxiosHeaders,HttpStatusCode,formToJSON,getAdapter,mergeConfig}=axios,TEST_BASE_URL="https://miniapptest-spinfi.xy1212.com";class HttpClient{constructor(f){this.options=f;const d=f.baseURL;this.instance=axios.create({baseURL:d,timeout:3e4}),this.instance.interceptors.request.use(m=>{const v=this.options.getToken();if(v){m.headers=m.headers||{};const g=`Bearer ${v}`;m.headers.Authorization=g}return m}),this.instance.interceptors.response.use(m=>m,m=>(m.response&&m.response.status===401&&this.options.onAuthError&&this.options.onAuthError(),Promise.reject(m)))}request(f){return this.instance.request(f)}get(f,d){return this.instance.get(f,d)}post(f,d,m){return this.instance.post(f,d,m)}}class NamespacedStorage{constructor(f="tg_tracking_sdk"){this.prefix=f}k(f){return`${this.prefix}:${f}`}set(f,d){try{localStorage.setItem(this.k(f),JSON.stringify(d))}catch{}}get(f){try{const d=localStorage.getItem(this.k(f));return d?JSON.parse(d):null}catch{return null}}remove(f){try{localStorage.removeItem(this.k(f))}catch{}}}class APIService{constructor(f){this.http=f}auth(f){return this.http.post("/api/user/auth",f).then(d=>d.data)}getAdPositionConfig(f){return this.http.post("/api/ad/adPositionDisplayAd",{adPositionName:f}).then(d=>d.data)}createAd(f){return this.http.post("/api/v2/ad/create",f).then(d=>d.data)}adMonitor(f){return this.http.get("/api/v2/ad/monitor",{params:f}).then(d=>d.data)}bindWalletReq(f){return this.http.post("/api/user/bindWallet",f).then(d=>d.data)}merchantPayModeList(){return this.http.get("/api/v2/merchant/pay/modeList").then(f=>f.data)}merchantPayCreate(f){return this.http.post("/api/v2/merchant/pay/create",f).then(d=>d.data)}merchantPayFinish(f){return this.http.post("/api/v2/merchant/pay/finish",f).then(d=>d.data)}merchantPayQueryResult(f){return this.http.post("/api/v2/merchant/pay/queryResult",f).then(d=>d.data)}merchantPayNotify(f){return this.http.post("/api/v2/merchant/pay/notify",f).then(d=>d.data)}}class HmAdManager{constructor(f={}){this.options=f,this.initialized=!1}async init(){this.initialized||(this.options.autoInjectScript!==!1&&this.sdkZone&&this.sdkFunc&&await this.ensureScriptInjected(),this.initialized=!0)}async setSpace(f){if(!f)return;const d=String(f),m=`show_${f}`,v=this.sdkZone!==d||this.sdkFunc!==m;this.sdkZone=d,this.sdkFunc=m,this.options.autoInjectScript!==!1&&await this.ensureScriptInjected(v)}findExistingScript(){return typeof document>"u"?null:document.querySelector("script[src*='//libtl.com/sdk.js']")}async ensureScriptInjected(f=!1){var g;if(typeof document>"u")return;const d=this.findExistingScript(),m=this.sdkZone||"",v=this.sdkFunc||"";if(d){const w=d.getAttribute("data-zone")||"",_=d.getAttribute("data-sdk")||"";if(w===m&&_===v&&!f)return;(g=d.parentElement)==null||g.removeChild(d)}!m||!v||await this.injectScript(m,v)}injectScript(f,d){return new Promise((m,v)=>{if(typeof document>"u")return m();const g=document.createElement("script");g.src="//libtl.com/sdk.js",g.setAttribute("data-zone",f),g.setAttribute("data-sdk",d),g.async=!0,g.onload=()=>m(),g.onerror=()=>v(new Error("Hm 脚本加载失败")),document.head.appendChild(g)})}async callSDK(f){if(!this.sdkFunc)throw new Error("Hm 未设置 spaceId");const d=window[this.sdkFunc];if(typeof d!="function")throw new Error("Hm SDK 未正确加载");await d(f)}async show(){try{await this.callSDK()}catch(f){throw f}}async showPopup(){try{await this.callSDK("pop")}catch(f){throw f}}async showInApp(f){try{await this.callSDK({type:"inApp",inAppSettings:f})}catch(d){throw d}}}class AdMonitor{constructor(f){this.getMonitor=f}extractParamsFromUrl(f){if(!f)return null;try{return{param:new URL(f).searchParams.get("param")||""}}catch{return null}}async send(f,d){if(!f)return;const m=Array.isArray(f)?f:[f];if(m.length===0)return;const v=m[0],g=this.extractParamsFromUrl(v);let w;if(g&&this.getMonitor)try{const _=Math.floor(Date.now()/1e3).toString(),S=CryptoJS.MD5(d+_).toString(),x={param:g.param,request_code:S,timestamp:_};w=await this.getMonitor(x)}catch{}return await Promise.allSettled(m.slice(1).map(_=>{try{return fetch(_,{method:"GET"})}catch{return Promise.resolve()}})),w}}var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var dist$1={},sdk={},telegramWebApps={},hasRequiredTelegramWebApps;function requireTelegramWebApps(){return hasRequiredTelegramWebApps||(hasRequiredTelegramWebApps=1,(function(){var r={},f="";try{f=location.hash.toString()}catch{}var d=S(f),m=O("initParams");if(m)for(var v in m)typeof d[v]>"u"&&(d[v]=m[v]);L("initParams",d);var g=!1,w;try{if(g=window.parent!=null&&window!=window.parent,g){window.addEventListener("message",function(N){if(N.source===window.parent){try{var H=JSON.parse(N.data)}catch{return}if(!(!H||!H.eventType))if(H.eventType=="set_custom_style")N.origin==="https://web.telegram.org"&&(w.innerHTML=H.eventData);else if(H.eventType=="reload_iframe"){try{window.parent.postMessage(JSON.stringify({eventType:"iframe_will_reload"}),"*")}catch{}location.reload()}else E(H.eventType,H.eventData)}}),w=document.createElement("style"),document.head.appendChild(w);try{window.parent.postMessage(JSON.stringify({eventType:"iframe_ready",eventData:{reload_supported:!0}}),"*")}catch{}}}catch{}function _(N){try{return N=N.replace(/\+/g,"%20"),decodeURIComponent(N)}catch{return N}}function S(N){N=N.replace(/^#/,"");var H={};if(!N.length)return H;if(N.indexOf("=")<0&&N.indexOf("?")<0)return H._path=_(N),H;var V=N.indexOf("?");if(V>=0){var X=N.substr(0,V);H._path=_(X),N=N.substr(V+1)}var oe=x(N);for(var se in oe)H[se]=oe[se];return H}function x(N){var H={};if(!N.length)return H;var V=N.split("&"),X,oe,se,de;for(X=0;X<V.length;X++)oe=V[X].split("="),se=_(oe[0]),de=oe[1]==null?null:_(oe[1]),H[se]=de;return H}function b(N,H){var V=N.indexOf("#");if(V<0)return N+"#"+H;var X=N.substr(V+1);return X.indexOf("=")>=0||X.indexOf("?")>=0?N+"&"+H:X.length>0?N+"?"+H:N+H}function C(N,H,V){if(H||(H=function(){}),V===void 0&&(V=""),window.TelegramWebviewProxy!==void 0)TelegramWebviewProxy.postEvent(N,JSON.stringify(V)),H();else if(window.external&&"notify"in window.external)window.external.notify(JSON.stringify({eventType:N,eventData:V})),H();else if(g)try{var X="https://web.telegram.org";X="*",window.parent.postMessage(JSON.stringify({eventType:N,eventData:V}),X),H()}catch(oe){H(oe)}else H({notAvailable:!0})}function E(N,H){M(N,function(V){V(N,H)})}function M(N,H){var V=r[N];if(!(V===void 0||!V.length))for(var X=0;X<V.length;X++)try{H(V[X])}catch{}}function A(N,H){r[N]===void 0&&(r[N]=[]);var V=r[N].indexOf(H);V===-1&&r[N].push(H)}function T(N,H){if(r[N]!==void 0){var V=r[N].indexOf(H);V!==-1&&r[N].splice(V,1)}}function L(N,H){try{return window.sessionStorage.setItem("__telegram__"+N,JSON.stringify(H)),!0}catch{}return!1}function O(N){try{return JSON.parse(window.sessionStorage.getItem("__telegram__"+N))}catch{}return null}window.Telegram||(window.Telegram={}),window.Telegram.WebView={initParams:d,isIframe:g,onEvent:A,offEvent:T,postEvent:C,receiveEvent:E,callEventCallbacks:M},window.Telegram.Utils={urlSafeDecode:_,urlParseQueryString:x,urlParseHashParams:S,urlAppendHashParams:b,sessionStorageSet:L,sessionStorageGet:O},window.TelegramGameProxy_receiveEvent=E,window.TelegramGameProxy={receiveEvent:E}})(),(function(){var r=window.Telegram.Utils,f=window.Telegram.WebView,d=f.initParams,m=f.isIframe,v={},g="",w={},_={},S="light",x="6.0",b="unknown";if(d.tgWebAppData&&d.tgWebAppData.length){g=d.tgWebAppData,w=r.urlParseQueryString(g);for(var C in w){var E=w[C];try{(E.substr(0,1)=="{"&&E.substr(-1)=="}"||E.substr(0,1)=="["&&E.substr(-1)=="]")&&(w[C]=JSON.parse(E))}catch{}}}if(d.tgWebAppThemeParams&&d.tgWebAppThemeParams.length){var M=d.tgWebAppThemeParams;try{var A=JSON.parse(M);A&&he(A)}catch{}}var A=r.sessionStorageGet("themeParams");A&&he(A),d.tgWebAppVersion&&(x=d.tgWebAppVersion),d.tgWebAppPlatform&&(b=d.tgWebAppPlatform);function T(fe,U){U.theme_params&&(he(U.theme_params),window.Telegram.WebApp.MainButton.setParams({}),window.Telegram.WebApp.SecondaryButton.setParams({}),me(),ae(),Oe(),X("themeChanged"))}var L=window.innerHeight;function O(fe,U){U.height&&(window.removeEventListener("resize",N),B(U))}function N(fe){L!=window.innerHeight&&(L=window.innerHeight,X("viewportChanged",{isStateStable:!0}))}function H(fe){if(!(fe.metaKey||fe.ctrlKey)){for(var U=fe.target;U.tagName!="A"&&U.parentNode;)U=U.parentNode;U.tagName=="A"&&U.target!="_blank"&&(U.protocol=="http:"||U.protocol=="https:")&&U.hostname=="t.me"&&(v.openTgLink(U.href),fe.preventDefault())}}function V(fe){return fe.toString().replace(/^\s+|\s+$/g,"")}function X(fe){var U=Array.prototype.slice.call(arguments);fe=U.shift(),f.callEventCallbacks("webview:"+fe,function(G){G.apply(v,U)})}function oe(fe,U){f.onEvent("webview:"+fe,U)}function se(fe,U){f.offEvent("webview:"+fe,U)}function de(fe,U){var G=document.documentElement;G&&G.style&&G.style.setProperty&&G.style.setProperty("--tg-"+fe,U)}function he(fe){fe.bg_color=="#1c1c1d"&&fe.bg_color==fe.secondary_bg_color&&(fe.secondary_bg_color="#2c2c2e");var U;for(var G in fe)(U=Ue(fe[G]))&&(_[G]=U,G=="bg_color"&&(S=De(U)?"dark":"light",de("color-scheme",S)),G="theme-"+G.split("_").join("-"),de(G,U));r.sessionStorageSet("themeParams",_)}var we={};function te(fe){for(var U=100;--U;){for(var G="",re="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",K=re.length,ue=0;ue<fe;ue++)G+=re[Math.floor(Math.random()*K)];if(!we[G])return we[G]={},G}throw Error("WebAppCallbackIdGenerateFailed")}var k=!1,q=!1,y=!0;function B(fe){typeof fe<"u"&&(y=!!fe.is_expanded,k=fe.height,fe.is_state_stable&&(q=fe.height),X("viewportChanged",{isStateStable:!!fe.is_state_stable}));var U,G;k!==!1?U=k-ut+"px":U=ut?"calc(100vh - "+ut+"px)":"100vh",q!==!1?G=q-ut+"px":G=ut?"calc(100vh - "+ut+"px)":"100vh",de("viewport-height",U),de("viewport-stable-height",G)}var $=!1;function I(fe){je("6.2")&&($=!!fe,f.postEvent("web_app_setup_closing_behavior",!1,{need_confirmation:$}))}var F=!0;function j(fe){je("7.7")&&(F=!!fe,f.postEvent("web_app_setup_swipe_behavior",!1,{allow_vertical_swipe:F}))}var D="bg_color",W=null;function R(){return D=="secondary_bg_color"?_.secondary_bg_color:D=="bg_color"?_.bg_color:W}function z(fe){if(je("6.1")){je("6.9")||(_.bg_color&&_.bg_color==fe?fe="bg_color":_.secondary_bg_color&&_.secondary_bg_color==fe&&(fe="secondary_bg_color"));var U=null,G=null;if(fe=="bg_color"||fe=="secondary_bg_color")G=fe;else if(je("6.9")&&(U=Ue(fe),!U))throw Error("WebAppHeaderColorInvalid");if(!je("6.9")&&G!="bg_color"&&G!="secondary_bg_color")throw Error("WebAppHeaderColorKeyInvalid");D=G,W=U,me()}}var ye=null,Ce=null;function me(){(ye!=D||Ce!=W)&&(ye=D,Ce=W,Ce?f.postEvent("web_app_set_header_color",!1,{color:W}):f.postEvent("web_app_set_header_color",!1,{color_key:D}))}var ie="bg_color";function ee(){return ie=="secondary_bg_color"?_.secondary_bg_color:ie=="bg_color"?_.bg_color:ie}function pe(fe){if(je("6.1")){var U;if(fe=="bg_color"||fe=="secondary_bg_color")U=fe;else if(U=Ue(fe),!U)throw Error("WebAppBackgroundColorInvalid");ie=U,ae()}}var be=null;function ae(){var fe=ee();be!=fe&&(be=fe,f.postEvent("web_app_set_background_color",!1,{color:fe}))}var ne="bottom_bar_bg_color";function Se(){return ne=="bottom_bar_bg_color"?_.bottom_bar_bg_color||_.secondary_bg_color||"#ffffff":ne=="secondary_bg_color"?_.secondary_bg_color:ne=="bg_color"?_.bg_color:ne}function qe(fe){if(je("7.10")){var U;if(fe=="bg_color"||fe=="secondary_bg_color"||fe=="bottom_bar_bg_color")U=fe;else if(U=Ue(fe),!U)throw Error("WebAppBottomBarColorInvalid");ne=U,Oe(),window.Telegram.WebApp.SecondaryButton.setParams({})}}var Ie=null;function Oe(){var fe=Se();Ie!=fe&&(Ie=fe,f.postEvent("web_app_set_bottom_bar_color",!1,{color:fe})),d.tgWebAppDebug&&bt()}function Ue(fe){fe+="";var U;if(U=/^\s*#([0-9a-f]{6})\s*$/i.exec(fe))return"#"+U[1].toLowerCase();if(U=/^\s*#([0-9a-f])([0-9a-f])([0-9a-f])\s*$/i.exec(fe))return("#"+U[1]+U[1]+U[2]+U[2]+U[3]+U[3]).toLowerCase();if(U=/^\s*rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+\.{0,1}\d*))?\)\s*$/.exec(fe)){var G=parseInt(U[1]),re=parseInt(U[2]),K=parseInt(U[3]);return G=(G<16?"0":"")+G.toString(16),re=(re<16?"0":"")+re.toString(16),K=(K<16?"0":"")+K.toString(16),"#"+G+re+K}return!1}function De(fe){fe=fe.replace(/[\s#]/g,""),fe.length==3&&(fe=fe[0]+fe[0]+fe[1]+fe[1]+fe[2]+fe[2]);var U=parseInt(fe.substr(0,2),16),G=parseInt(fe.substr(2,2),16),re=parseInt(fe.substr(4,2),16),K=Math.sqrt(.299*(U*U)+.587*(G*G)+.114*(re*re));return K<120}function $e(fe,U){typeof fe!="string"&&(fe=""),typeof U!="string"&&(U=""),fe=fe.replace(/^\s+|\s+$/g,"").split("."),U=U.replace(/^\s+|\s+$/g,"").split(".");var G=Math.max(fe.length,U.length),re,K,ue;for(re=0;re<G;re++)if(K=parseInt(fe[re])||0,ue=parseInt(U[re])||0,K!=ue)return K>ue?1:-1;return 0}function je(fe){return $e(x,fe)>=0}function Ye(fe){if(window.Blob)try{return new Blob([fe]).size}catch{}for(var U=fe.length,G=fe.length-1;G>=0;G--){var re=fe.charCodeAt(G);re>127&&re<=2047?U++:re>2047&&re<=65535&&(U+=2),re>=56320&&re<=57343&&G--}return U}var st=(function(){var fe=!1,U={};Object.defineProperty(U,"isVisible",{set:function(Pe){Te({is_visible:Pe})},get:function(){return fe},enumerable:!0});var G=null;f.onEvent("back_button_pressed",re);function re(){X("backButtonClicked")}function K(){return{is_visible:fe}}function ue(Pe){return typeof Pe>"u"&&(Pe=K()),JSON.stringify(Pe)}function Ae(){return!!je("6.1")}function xe(){var Pe=K(),Fe=ue(Pe);G!==Fe&&(G=Fe,f.postEvent("web_app_setup_back_button",!1,Pe))}function Te(Pe){return Ae()&&(typeof Pe.is_visible<"u"&&(fe=!!Pe.is_visible),xe()),U}return U.onClick=function(Pe){return Ae()&&oe("backButtonClicked",Pe),U},U.offClick=function(Pe){return Ae()&&se("backButtonClicked",Pe),U},U.show=function(){return Te({is_visible:!0})},U.hide=function(){return Te({is_visible:!1})},U})(),Je=null,Ge={},ut=0;if(d.tgWebAppDebug){Je=document.createElement("tg-bottom-bar");var gt={display:"flex",gap:"7px",font:"600 14px/18px sans-serif",width:"100%",background:Se(),position:"fixed",left:"0",right:"0",bottom:"0",margin:"0",padding:"7px",textAlign:"center",boxSizing:"border-box",zIndex:"10000"};for(var rt in gt)Je.style[rt]=gt[rt];document.addEventListener("DOMContentLoaded",function fe(U){document.removeEventListener("DOMContentLoaded",fe),document.body.appendChild(Je)});var wt=document.createElement("style");wt.innerHTML='tg-bottom-button.shine { position: relative; overflow: hidden; } tg-bottom-button.shine:before { content:""; position: absolute; top: 0; width: 100%; height: 100%; background: linear-gradient(120deg, transparent, rgba(255, 255, 255, .2), transparent); animation: tg-bottom-button-shine 5s ease-in-out infinite; } @-webkit-keyframes tg-bottom-button-shine { 0% {left: -100%;} 12%,100% {left: 100%}} @keyframes tg-bottom-button-shine { 0% {left: -100%;} 12%,100% {left: 100%}}',Je.appendChild(wt)}function bt(){var fe=Ge.main._bottomButton,U=Ge.secondary._bottomButton;fe.isVisible||U.isVisible?(Je.style.display="flex",ut=58,fe.isVisible&&U.isVisible&&(U.position=="top"?(Je.style.flexDirection="column-reverse",ut+=51):U.position=="bottom"?(Je.style.flexDirection="column",ut+=51):U.position=="left"?Je.style.flexDirection="row-reverse":U.position=="right"&&(Je.style.flexDirection="row"))):(Je.style.display="none",ut=0),Je.style.background=Se(),document.documentElement&&(document.documentElement.style.boxSizing="border-box",document.documentElement.style.paddingBottom=ut+"px"),B()}var le=function(fe){var U=fe=="main";if(U)var G="web_app_setup_main_button",re="main_button_pressed",K="mainButtonClicked",ue="Continue",Ae=function(){return _.button_color||"#2481cc"},xe=function(){return _.button_text_color||"#ffffff"};else var G="web_app_setup_secondary_button",re="secondary_button_pressed",K="secondaryButtonClicked",ue="Cancel",Ae=function(){return Se()},xe=function(){return _.button_color||"#2481cc"};var Te=!1,Pe=!0,Fe=!1,Ne=!1,At=fe,ot=ue,yt=!1,vt=!1,xt="left",Ve={};Object.defineProperty(Ve,"type",{get:function(){return At},enumerable:!0}),Object.defineProperty(Ve,"text",{set:function(Be){Ve.setParams({text:Be})},get:function(){return ot},enumerable:!0}),Object.defineProperty(Ve,"color",{set:function(Be){Ve.setParams({color:Be})},get:function(){return yt||Ae()},enumerable:!0}),Object.defineProperty(Ve,"textColor",{set:function(Be){Ve.setParams({text_color:Be})},get:function(){return vt||xe()},enumerable:!0}),Object.defineProperty(Ve,"isVisible",{set:function(Be){Ve.setParams({is_visible:Be})},get:function(){return Te},enumerable:!0}),Object.defineProperty(Ve,"isProgressVisible",{get:function(){return Ne},enumerable:!0}),Object.defineProperty(Ve,"isActive",{set:function(Be){Ve.setParams({is_active:Be})},get:function(){return Pe},enumerable:!0}),Object.defineProperty(Ve,"hasShineEffect",{set:function(Be){Ve.setParams({has_shine_effect:Be})},get:function(){return Fe},enumerable:!0}),U||Object.defineProperty(Ve,"position",{set:function(Be){Ve.setParams({position:Be})},get:function(){return xt},enumerable:!0});var ft=null;f.onEvent(re,pt);var et=null;if(d.tgWebAppDebug){et=document.createElement("tg-bottom-button");var ht={display:"none",width:"100%",height:"44px",borderRadius:"0",background:"no-repeat right center",padding:"13px 15px",textAlign:"center",boxSizing:"border-box"};for(var it in ht)et.style[it]=ht[it];Je.appendChild(et),et.addEventListener("click",pt,!1),et._bottomButton=Ve,Ge[fe]=et}function pt(){Pe&&X(K)}function at(){var Be=Ve.color,Ke=Ve.textColor;if(Te){var We={is_visible:!0,is_active:Pe,is_progress_visible:Ne,text:ot,color:Be,text_color:Ke,has_shine_effect:Fe&&Pe&&!Ne};U||(We.position=xt)}else var We={is_visible:!1};return We}function ct(Be){return typeof Be>"u"&&(Be=at()),JSON.stringify(Be)}function dt(){var Be=at(),Ke=ct(Be);ft!==Ke&&(ft=Ke,f.postEvent(G,!1,Be),d.tgWebAppDebug&&nt(Be))}function nt(Be){Be.is_visible?(et.style.display="block",et.style.opacity=Be.is_active?"1":"0.8",et.style.cursor=Be.is_active?"pointer":"auto",et.disabled=!Be.is_active,et.innerText=Be.text,et.className=Be.has_shine_effect?"shine":"",et.style.backgroundImage=Be.is_progress_visible?"url('data:image/svg+xml,"+encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewport="0 0 48 48" width="48px" height="48px"><circle cx="50%" cy="50%" stroke="'+Be.text_color+'" stroke-width="2.25" stroke-linecap="round" fill="none" stroke-dashoffset="106" r="9" stroke-dasharray="56.52" rotate="-90"><animate attributeName="stroke-dashoffset" attributeType="XML" dur="360s" from="0" to="12500" repeatCount="indefinite"></animate><animateTransform attributeName="transform" attributeType="XML" type="rotate" dur="1s" from="-90 24 24" to="630 24 24" repeatCount="indefinite"></animateTransform></circle></svg>')+"')":"none",et.style.backgroundColor=Be.color,et.style.color=Be.text_color):et.style.display="none",bt()}function Le(Be){if(typeof Be.text<"u"){var Ke=V(Be.text);if(!Ke.length||Ke.length>64)throw Error("WebAppBottomButtonParamInvalid");ot=Ke}if(typeof Be.color<"u")if(Be.color===!1||Be.color===null)yt=!1;else{var We=Ue(Be.color);if(!We)throw Error("WebAppBottomButtonParamInvalid");yt=We}if(typeof Be.text_color<"u")if(Be.text_color===!1||Be.text_color===null)vt=!1;else{var ze=Ue(Be.text_color);if(!ze)throw Error("WebAppBottomButtonParamInvalid");vt=ze}if(typeof Be.is_visible<"u"){if(Be.is_visible&&!Ve.text.length)throw Error("WebAppBottomButtonParamInvalid");Te=!!Be.is_visible}if(typeof Be.has_shine_effect<"u"&&(Fe=!!Be.has_shine_effect),!U&&typeof Be.position<"u"){if(Be.position!="left"&&Be.position!="right"&&Be.position!="top"&&Be.position!="bottom")throw Error("WebAppBottomButtonParamInvalid");xt=Be.position}return typeof Be.is_active<"u"&&(Pe=!!Be.is_active),dt(),Ve}return Ve.setText=function(Be){return Ve.setParams({text:Be})},Ve.onClick=function(Be){return oe(K,Be),Ve},Ve.offClick=function(Be){return se(K,Be),Ve},Ve.show=function(){return Ve.setParams({is_visible:!0})},Ve.hide=function(){return Ve.setParams({is_visible:!1})},Ve.enable=function(){return Ve.setParams({is_active:!0})},Ve.disable=function(){return Ve.setParams({is_active:!1})},Ve.showProgress=function(Be){return Pe=!!Be,Ne=!0,dt(),Ve},Ve.hideProgress=function(){return Ve.isActive||(Pe=!0),Ne=!1,dt(),Ve},Ve.setParams=Le,Ve},Z=le("main"),J=le("secondary"),ge=(function(){var fe=!1,U={};Object.defineProperty(U,"isVisible",{set:function(Pe){Te({is_visible:Pe})},get:function(){return fe},enumerable:!0});var G=null;f.onEvent("settings_button_pressed",re);function re(){X("settingsButtonClicked")}function K(){return{is_visible:fe}}function ue(Pe){return typeof Pe>"u"&&(Pe=K()),JSON.stringify(Pe)}function Ae(){return!!je("6.10")}function xe(){var Pe=K(),Fe=ue(Pe);G!==Fe&&(G=Fe,f.postEvent("web_app_setup_settings_button",!1,Pe))}function Te(Pe){return Ae()&&(typeof Pe.is_visible<"u"&&(fe=!!Pe.is_visible),xe()),U}return U.onClick=function(Pe){return Ae()&&oe("settingsButtonClicked",Pe),U},U.offClick=function(Pe){return Ae()&&se("settingsButtonClicked",Pe),U},U.show=function(){return Te({is_visible:!0})},U.hide=function(){return Te({is_visible:!1})},U})(),Ee=(function(){var fe={};function U(G){if(!je("6.1"))return fe;if(G.type=="impact"){if(G.impact_style!="light"&&G.impact_style!="medium"&&G.impact_style!="heavy"&&G.impact_style!="rigid"&&G.impact_style!="soft")throw Error("WebAppHapticImpactStyleInvalid")}else if(G.type=="notification"){if(G.notification_type!="error"&&G.notification_type!="success"&&G.notification_type!="warning")throw Error("WebAppHapticNotificationTypeInvalid")}else if(G.type!="selection_change")throw Error("WebAppHapticFeedbackTypeInvalid");return f.postEvent("web_app_trigger_haptic_feedback",!1,G),fe}return fe.impactOccurred=function(G){return U({type:"impact",impact_style:G})},fe.notificationOccurred=function(G){return U({type:"notification",notification_type:G})},fe.selectionChanged=function(){return U({type:"selection_change"})},fe})(),Re=(function(){var fe={};function U(G,re,K){if(!je("6.9"))throw Error("WebAppMethodUnsupported");return ve(G,re,K),fe}return fe.setItem=function(G,re,K){return U("saveStorageValue",{key:G,value:re},K)},fe.getItem=function(G,re){return fe.getItems([G],re?function(K,ue){K?re(K):re(null,ue[G])}:null)},fe.getItems=function(G,re){return U("getStorageValues",{keys:G},re)},fe.removeItem=function(G,re){return fe.removeItems([G],re)},fe.removeItems=function(G,re){return U("deleteStorageValues",{keys:G},re)},fe.getKeys=function(G){return U("getStorageKeys",{},G)},fe})(),ke=(function(){var fe=!1,U=!1,G="unknown",re=!1,K=!1,ue=!1,Ae="",xe={};Object.defineProperty(xe,"isInited",{get:function(){return fe},enumerable:!0}),Object.defineProperty(xe,"isBiometricAvailable",{get:function(){return fe&&U},enumerable:!0}),Object.defineProperty(xe,"biometricType",{get:function(){return G||"unknown"},enumerable:!0}),Object.defineProperty(xe,"isAccessRequested",{get:function(){return re},enumerable:!0}),Object.defineProperty(xe,"isAccessGranted",{get:function(){return re&&K},enumerable:!0}),Object.defineProperty(xe,"isBiometricTokenSaved",{get:function(){return ue},enumerable:!0}),Object.defineProperty(xe,"deviceId",{get:function(){return Ae||""},enumerable:!0});var Te={callbacks:[]},Pe=!1,Fe=!1,Ne=!1;f.onEvent("biometry_info_received",At),f.onEvent("biometry_auth_requested",ot),f.onEvent("biometry_token_updated",yt);function At(Ve,ft){if(fe=!0,ft.available?(U=!0,G=ft.type||"unknown",ft.access_requested?(re=!0,K=!!ft.access_granted,ue=!!ft.token_saved):(re=!1,K=!1,ue=!1)):(U=!1,G="unknown",re=!1,K=!1,ue=!1),Ae=ft.device_id||"",Te.callbacks.length>0)for(var et=0;et<Te.callbacks.length;et++){var ht=Te.callbacks[et];ht()}if(Pe){var it=Pe;Pe=!1,it.callback&&it.callback(K)}X("biometricManagerUpdated")}function ot(Ve,ft){var et=ft.status=="authorized",ht=ft.token||"";if(Fe){var it=Fe;Fe=!1,it.callback&&it.callback(et,et?ht:null)}X("biometricAuthRequested",et?{isAuthenticated:!0,biometricToken:ht}:{isAuthenticated:!1})}function yt(Ve,ft){var et=!1;if(U&&re&&(ft.status=="updated"?(ue=!0,et=!0):ft.status=="removed"&&(ue=!1,et=!0)),Ne){var ht=Ne;Ne=!1,ht.callback&&ht.callback(et)}X("biometricTokenUpdated",{isUpdated:et})}function vt(){return!!je("7.2")}function xt(){if(!fe)throw Error("WebAppBiometricManagerNotInited");return!0}return xe.init=function(Ve){return!vt()||fe||(Ve&&Te.callbacks.push(Ve),f.postEvent("web_app_biometry_get_info",!1)),xe},xe.requestAccess=function(Ve,ft){if(!vt())return xe;if(xt(),!U)throw Error("WebAppBiometricManagerBiometricsNotAvailable");if(Pe)throw Error("WebAppBiometricManagerAccessRequested");var et={};if(typeof Ve.reason<"u"){var ht=V(Ve.reason);if(ht.length>128)throw Error("WebAppBiometricRequestAccessParamInvalid");ht.length>0&&(et.reason=ht)}return Pe={callback:ft},f.postEvent("web_app_biometry_request_access",!1,et),xe},xe.authenticate=function(Ve,ft){if(!vt())return xe;if(xt(),!U)throw Error("WebAppBiometricManagerBiometricsNotAvailable");if(!K)throw Error("WebAppBiometricManagerBiometricAccessNotGranted");if(Fe)throw Error("WebAppBiometricManagerAuthenticationRequested");var et={};if(typeof Ve.reason<"u"){var ht=V(Ve.reason);if(ht.length>128)throw Error("WebAppBiometricRequestAccessParamInvalid");ht.length>0&&(et.reason=ht)}return Fe={callback:ft},f.postEvent("web_app_biometry_request_auth",!1,et),xe},xe.updateBiometricToken=function(Ve,ft){if(!vt())return xe;if(Ve=Ve||"",Ve.length>1024)throw Error("WebAppBiometricManagerTokenInvalid");if(xt(),!U)throw Error("WebAppBiometricManagerBiometricsNotAvailable");if(!K)throw Error("WebAppBiometricManagerBiometricAccessNotGranted");if(Ne)throw Error("WebAppBiometricManagerTokenUpdateRequested");return Ne={callback:ft},f.postEvent("web_app_biometry_update_token",!1,{token:Ve}),xe},xe.openSettings=function(){if(!vt())return xe;if(xt(),!U)throw Error("WebAppBiometricManagerBiometricsNotAvailable");if(!re)throw Error("WebAppBiometricManagerBiometricsAccessNotRequested");return K||f.postEvent("web_app_biometry_open_settings",!1),xe},xe})(),Xe={};function He(fe,U){if(U.slug&&Xe[U.slug]){var G=Xe[U.slug];delete Xe[U.slug],G.callback&&G.callback(U.status),X("invoiceClosed",{url:G.url,status:U.status})}}var Ze=!1;function _t(fe,U){if(Ze){var G=Ze;Ze=!1;var re=null;typeof U.button_id<"u"&&(re=U.button_id),G.callback&&G.callback(re),X("popupClosed",{button_id:re})}}var tt=!1;function mt(fe,U){if(tt){var G=tt,re=null;typeof U.data<"u"&&(re=U.data),G.callback&&G.callback(re)&&(tt=!1,f.postEvent("web_app_close_scan_qr_popup",!1)),X("qrTextReceived",{data:re})}}function Tt(fe,U){tt=!1,X("scanQrPopupClosed")}function St(fe,U){if(U.req_id&&we[U.req_id]){var G=we[U.req_id];delete we[U.req_id];var re=null;typeof U.data<"u"&&(re=U.data),G.callback&&G.callback(re),X("clipboardTextReceived",{data:re})}}var lt=!1;function Mt(fe,U){if(lt){var G=lt;lt=!1,G.callback&&G.callback(U.status=="allowed"),X("writeAccessRequested",{status:U.status})}}function Ct(fe,U){var G,re,K=0,ue=function(){ve("getRequestedContact",{},function(xe,Te){Te&&Te.length?(clearTimeout(re),fe(Te)):(K+=50,G=setTimeout(ue,K))})},Ae=function(){clearTimeout(G),fe("")};re=setTimeout(Ae,U),ue()}var ce=!1;function Y(fe,U){if(ce){var G=ce;ce=!1;var re=U.status=="sent",K={status:U.status};re?Ct(function(ue){if(ue&&ue.length){K.response=ue,K.responseUnsafe=r.urlParseQueryString(ue);for(var Ae in K.responseUnsafe){var xe=K.responseUnsafe[Ae];try{(xe.substr(0,1)=="{"&&xe.substr(-1)=="}"||xe.substr(0,1)=="["&&xe.substr(-1)=="]")&&(K.responseUnsafe[Ae]=JSON.parse(xe))}catch{}}}G.callback&&G.callback(re,K),X("contactRequested",K)},3e3):(G.callback&&G.callback(re,K),X("contactRequested",K))}}function Q(fe,U){if(U.req_id&&we[U.req_id]){var G=we[U.req_id];delete we[U.req_id];var re=null,K=null;typeof U.result<"u"&&(re=U.result),typeof U.error<"u"&&(K=U.error),G.callback&&G.callback(K,re)}}function ve(fe,U,G){if(!je("6.9"))throw Error("WebAppMethodUnsupported");var re=te(16),K={req_id:re,method:fe,params:U||{}};we[re]={callback:G},f.postEvent("web_app_invoke_custom_method",!1,K)}window.Telegram||(window.Telegram={}),Object.defineProperty(v,"initData",{get:function(){return g},enumerable:!0}),Object.defineProperty(v,"initDataUnsafe",{get:function(){return w},enumerable:!0}),Object.defineProperty(v,"version",{get:function(){return x},enumerable:!0}),Object.defineProperty(v,"platform",{get:function(){return b},enumerable:!0}),Object.defineProperty(v,"colorScheme",{get:function(){return S},enumerable:!0}),Object.defineProperty(v,"themeParams",{get:function(){return _},enumerable:!0}),Object.defineProperty(v,"isExpanded",{get:function(){return y},enumerable:!0}),Object.defineProperty(v,"viewportHeight",{get:function(){return(k===!1?window.innerHeight:k)-ut},enumerable:!0}),Object.defineProperty(v,"viewportStableHeight",{get:function(){return(q===!1?window.innerHeight:q)-ut},enumerable:!0}),Object.defineProperty(v,"isClosingConfirmationEnabled",{set:function(fe){I(fe)},get:function(){return $},enumerable:!0}),Object.defineProperty(v,"isVerticalSwipesEnabled",{set:function(fe){j(fe)},get:function(){return F},enumerable:!0}),Object.defineProperty(v,"headerColor",{set:function(fe){z(fe)},get:function(){return R()},enumerable:!0}),Object.defineProperty(v,"backgroundColor",{set:function(fe){pe(fe)},get:function(){return ee()},enumerable:!0}),Object.defineProperty(v,"bottomBarColor",{set:function(fe){qe(fe)},get:function(){return Se()},enumerable:!0}),Object.defineProperty(v,"BackButton",{value:st,enumerable:!0}),Object.defineProperty(v,"MainButton",{value:Z,enumerable:!0}),Object.defineProperty(v,"SecondaryButton",{value:J,enumerable:!0}),Object.defineProperty(v,"SettingsButton",{value:ge,enumerable:!0}),Object.defineProperty(v,"HapticFeedback",{value:Ee,enumerable:!0}),Object.defineProperty(v,"CloudStorage",{value:Re,enumerable:!0}),Object.defineProperty(v,"BiometricManager",{value:ke,enumerable:!0}),v.setHeaderColor=function(fe){v.headerColor=fe},v.setBackgroundColor=function(fe){v.backgroundColor=fe},v.setBottomBarColor=function(fe){v.bottomBarColor=fe},v.enableClosingConfirmation=function(){v.isClosingConfirmationEnabled=!0},v.disableClosingConfirmation=function(){v.isClosingConfirmationEnabled=!1},v.enableVerticalSwipes=function(){v.isVerticalSwipesEnabled=!0},v.disableVerticalSwipes=function(){v.isVerticalSwipesEnabled=!1},v.isVersionAtLeast=function(fe){return je(fe)},v.onEvent=function(fe,U){oe(fe,U)},v.offEvent=function(fe,U){se(fe,U)},v.sendData=function(fe){if(!fe||!fe.length||Ye(fe)>4096)throw Error("WebAppDataInvalid");f.postEvent("web_app_data_send",!1,{data:fe})},v.switchInlineQuery=function(fe,U){if(!je("6.6"))throw Error("WebAppMethodUnsupported");if(!d.tgWebAppBotInline)throw Error("WebAppInlineModeDisabled");if(fe=fe||"",fe.length>256)throw Error("WebAppInlineQueryInvalid");var G=[];if(U){if(!Array.isArray(U))throw Error("WebAppInlineChooseChatTypesInvalid");for(var re={users:1,bots:1,groups:1,channels:1},K=0;K<U.length;K++){var ue=U[K];if(!re[ue])throw Error("WebAppInlineChooseChatTypeInvalid");re[ue]!=2&&(re[ue]=2,G.push(ue))}}f.postEvent("web_app_switch_inline_query",!1,{query:fe,chat_types:G})},v.openLink=function(re,U){var G=document.createElement("A");if(G.href=re,G.protocol!="http:"&&G.protocol!="https:")throw Error("WebAppTgUrlInvalid");var re=G.href;if(U=U||{},je("6.1")){var K={url:re};je("6.4")&&U.try_instant_view&&(K.try_instant_view=!0),je("7.6")&&U.try_browser&&(K.try_browser=U.try_browser),f.postEvent("web_app_open_link",!1,K)}else window.open(re,"_blank")},v.openTelegramLink=function(fe){var U=document.createElement("A");if(U.href=fe,U.protocol!="http:"&&U.protocol!="https:"||U.hostname!="t.me")throw Error("WebAppTgUrlInvalid");var G=U.pathname+U.search;m||je("6.1")?f.postEvent("web_app_open_tg_link",!1,{path_full:G}):location.href="https://t.me"+G},v.openInvoice=function(fe,U){var G=document.createElement("A"),re,K;if(G.href=fe,G.protocol!="http:"&&G.protocol!="https:"||G.hostname!="t.me"||!(re=G.pathname.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/))||!(K=re[2]))throw Error("WebAppInvoiceUrlInvalid");if(!je("6.1"))throw Error("WebAppMethodUnsupported");if(Xe[K])throw Error("WebAppInvoiceOpened");Xe[K]={url:fe,callback:U},f.postEvent("web_app_open_invoice",!1,{slug:K})},v.showPopup=function(fe,U){if(!je("6.2"))throw Error("WebAppMethodUnsupported");if(Ze)throw Error("WebAppPopupOpened");var G="",re="",K=[],ue={};if(typeof fe.title<"u"){if(G=V(fe.title),G.length>64)throw Error("WebAppPopupParamInvalid");G.length>0&&(ue.title=G)}if(typeof fe.message<"u"&&(re=V(fe.message)),!re.length||re.length>256)throw Error("WebAppPopupParamInvalid");if(ue.message=re,typeof fe.buttons<"u"){if(!Array.isArray(fe.buttons))throw Error("WebAppPopupParamInvalid");for(var Ae=0;Ae<fe.buttons.length;Ae++){var xe=fe.buttons[Ae],Te={},Pe="";if(typeof xe.id<"u"&&(Pe=xe.id.toString(),Pe.length>64))throw Error("WebAppPopupParamInvalid");Te.id=Pe;var Fe=xe.type;if(typeof Fe>"u"&&(Fe="default"),Te.type=Fe,!(Fe=="ok"||Fe=="close"||Fe=="cancel"))if(Fe=="default"||Fe=="destructive"){var Ne="";if(typeof xe.text<"u"&&(Ne=V(xe.text)),!Ne.length||Ne.length>64)throw Error("WebAppPopupParamInvalid");Te.text=Ne}else throw Error("WebAppPopupParamInvalid");K.push(Te)}}else K.push({id:"",type:"close"});if(K.length<1||K.length>3)throw Error("WebAppPopupParamInvalid");ue.buttons=K,Ze={callback:U},f.postEvent("web_app_open_popup",!1,ue)},v.showAlert=function(fe,U){v.showPopup({message:fe},U?function(){U()}:null)},v.showConfirm=function(fe,U){v.showPopup({message:fe,buttons:[{type:"ok",id:"ok"},{type:"cancel"}]},U?function(G){U(G=="ok")}:null)},v.showScanQrPopup=function(fe,U){if(!je("6.4"))throw Error("WebAppMethodUnsupported");if(tt)throw Error("WebAppScanQrPopupOpened");var G="",re={};if(typeof fe.text<"u"){if(G=V(fe.text),G.length>64)throw Error("WebAppScanQrPopupParamInvalid");G.length>0&&(re.text=G)}tt={callback:U},f.postEvent("web_app_open_scan_qr_popup",!1,re)},v.closeScanQrPopup=function(){if(!je("6.4"))throw Error("WebAppMethodUnsupported");tt=!1,f.postEvent("web_app_close_scan_qr_popup",!1)},v.readTextFromClipboard=function(fe){if(!je("6.4"))throw Error("WebAppMethodUnsupported");var U=te(16),G={req_id:U};we[U]={callback:fe},f.postEvent("web_app_read_text_from_clipboard",!1,G)},v.requestWriteAccess=function(fe){if(!je("6.9"))throw Error("WebAppMethodUnsupported");if(lt)throw Error("WebAppWriteAccessRequested");lt={callback:fe},f.postEvent("web_app_request_write_access")},v.requestContact=function(fe){if(!je("6.9"))throw Error("WebAppMethodUnsupported");if(ce)throw Error("WebAppContactRequested");ce={callback:fe},f.postEvent("web_app_request_phone")},v.shareToStory=function(fe,U){if(U=U||{},!je("7.8"))throw Error("WebAppMethodUnsupported");var G=document.createElement("A");if(G.href=fe,G.protocol!="http:"&&G.protocol!="https:")throw Error("WebAppMediaUrlInvalid");var re={};if(re.media_url=G.href,typeof U.text<"u"){var K=V(U.text);if(K.length>2048)throw Error("WebAppShareToStoryParamInvalid");K.length>0&&(re.text=K)}if(typeof U.widget_link<"u"){if(U.widget_link=U.widget_link||{},G.href=U.widget_link.url,G.protocol!="http:"&&G.protocol!="https:")throw Error("WebAppShareToStoryParamInvalid");var ue={url:G.href};if(typeof U.widget_link.name<"u"){var Ae=V(U.widget_link.name);if(Ae.length>48)throw Error("WebAppShareToStoryParamInvalid");Ae.length>0&&(ue.name=Ae)}re.widget_link=ue}f.postEvent("web_app_share_to_story",!1,re)},v.invokeCustomMethod=function(fe,U,G){ve(fe,U,G)},v.ready=function(){f.postEvent("web_app_ready")},v.expand=function(){f.postEvent("web_app_expand")},v.close=function(fe){fe=fe||{};var U={};je("7.6")&&fe.return_back&&(U.return_back=!0),f.postEvent("web_app_close",!1,U)},window.Telegram.WebApp=v,me(),ae(),Oe(),B(),d.tgWebAppShowSettings&&ge.show(),window.addEventListener("resize",N),m&&document.addEventListener("click",H),f.onEvent("theme_changed",T),f.onEvent("viewport_changed",O),f.onEvent("invoice_closed",He),f.onEvent("popup_closed",_t),f.onEvent("qr_text_received",mt),f.onEvent("scan_qr_popup_closed",Tt),f.onEvent("clipboard_text_received",St),f.onEvent("write_access_requested",Mt),f.onEvent("phone_requested",Y),f.onEvent("custom_method_invoked",Q),f.postEvent("web_app_request_theme"),f.postEvent("web_app_request_viewport")})()),telegramWebApps}var hasRequiredSdk;function requireSdk(){if(hasRequiredSdk)return sdk;hasRequiredSdk=1,Object.defineProperty(sdk,"__esModule",{value:!0}),sdk.WebApp=void 0,requireTelegramWebApps();var r=window;return sdk.WebApp=r.Telegram.WebApp,sdk}var hasRequiredDist$1;function requireDist$1(){if(hasRequiredDist$1)return dist$1;hasRequiredDist$1=1,Object.defineProperty(dist$1,"__esModule",{value:!0});var r=requireSdk();return dist$1.default=r.WebApp,dist$1}var distExports=requireDist$1();const WebApp=getDefaultExportFromCjs(distExports);function retrieveLaunchParams(){if(!WebApp.initData||WebApp.initData==="")throw new Error("未能提取启动参数,不在 Telegram 环境中");return WebApp.initData}function isTelegramEnv(){try{return typeof window<"u"&&window.Telegram&&window.Telegram.WebApp?(retrieveLaunchParams(),!0):!1}catch{return!1}}function getTelegramUserUnsafe(){try{if(!WebApp||!WebApp.initDataUnsafe)return null;const r=WebApp.initDataUnsafe;return!r.user||!r.user.id?null:{user:{id:r.user.id,firstName:r.user.first_name||"",lastName:r.user.last_name||"",username:r.user.username,languageCode:r.user.language_code,isPremium:r.user.is_premium||!1,allowsWriteToPm:r.user.allows_write_to_pm||!1},authDate:new Date().toISOString(),hash:r.hash||"",startParam:r.start_param,chatType:r.chat_type,chatInstance:r.chat_instance}}catch{return null}}function readCookie(r){if(typeof document>"u")return null;const f=document.cookie.match(new RegExp("(?:^|; )"+r.replace(/([.$?*|{}()\[\]\\/+^])/g,"\\$1")+"=([^;]*)"));return f?decodeURIComponent(f[1]):null}function writeCookie(r,f,d=365*2){if(typeof document>"u")return;const m=new Date;m.setTime(m.getTime()+d*24*60*60*1e3);const v="; expires="+m.toUTCString();document.cookie=`${encodeURIComponent(r)}=${encodeURIComponent(f)}${v}; path=/`}function generateNumericId(){const r=Math.floor(Math.random()*1e9),f=Date.now()%1e9;return Number(String(f).padStart(9,"0")+String(r).padStart(9,"0"))}function getAnonymousBrowserUser(r="tg_tracking_uid"){let f=readCookie(r);if(!f){const v=generateNumericId();f=String(v),writeCookie(r,f)}const d=Number(f.replace(/\D/g,"").slice(0,15))||generateNumericId(),m=typeof navigator<"u"&&(navigator.language||navigator.userLanguage)||"en";return{user:{id:d,firstName:"Guest",lastName:"",username:`guest_${f.slice(-6)}`,languageCode:m.toLowerCase(),isPremium:!1,allowsWriteToPm:!1},authDate:new Date().toISOString(),hash:"anonymous_cookie_user",startParam:"browser_guest",chatType:"sender",chatInstance:""}}function getDefaultMockUser(){return{user:{id:2077220643,firstName:"Mock",lastName:"User",username:"mock_user_demo",languageCode:"zh-hans",isPremium:!0,allowsWriteToPm:!0},authDate:new Date().toISOString(),hash:"mock_hash_for_demo_purpose",startParam:"demo_start_param",chatType:"sender",chatInstance:"-245769840322609948"}}var naclUtil$1={exports:{}},naclUtil=naclUtil$1.exports,hasRequiredNaclUtil;function requireNaclUtil(){return hasRequiredNaclUtil||(hasRequiredNaclUtil=1,(function(r){(function(f,d){r.exports?r.exports=d():(f.nacl||(f.nacl={}),f.nacl.util=d())})(naclUtil,function(){var f={};function d(m){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(m))throw new TypeError("invalid encoding")}return f.decodeUTF8=function(m){if(typeof m!="string")throw new TypeError("expected string");var v,g=unescape(encodeURIComponent(m)),w=new Uint8Array(g.length);for(v=0;v<g.length;v++)w[v]=g.charCodeAt(v);return w},f.encodeUTF8=function(m){var v,g=[];for(v=0;v<m.length;v++)g.push(String.fromCharCode(m[v]));return decodeURIComponent(escape(g.join("")))},typeof atob>"u"?typeof Buffer.from<"u"?(f.encodeBase64=function(m){return Buffer.from(m).toString("base64")},f.decodeBase64=function(m){return d(m),new Uint8Array(Array.prototype.slice.call(Buffer.from(m,"base64"),0))}):(f.encodeBase64=function(m){return new Buffer(m).toString("base64")},f.decodeBase64=function(m){return d(m),new Uint8Array(Array.prototype.slice.call(new Buffer(m,"base64"),0))}):(f.encodeBase64=function(m){var v,g=[],w=m.length;for(v=0;v<w;v++)g.push(String.fromCharCode(m[v]));return btoa(g.join(""))},f.decodeBase64=function(m){d(m);var v,g=atob(m),w=new Uint8Array(g.length);for(v=0;v<g.length;v++)w[v]=g.charCodeAt(v);return w}),f})})(naclUtil$1)),naclUtil$1.exports}var naclUtilExports=requireNaclUtil();const nacl=getDefaultExportFromCjs(naclUtilExports);function commonjsRequire(r){throw new Error('Could not dynamically require "'+r+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var naclFast={exports:{}},cryptoBrowserify={},browser$b={exports:{}},safeBuffer$1={exports:{}},dist={},hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,(function(r){Object.defineProperties(r,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var f={},d={};d.byteLength=b,d.toByteArray=E,d.fromByteArray=T;for(var m=[],v=[],g=typeof Uint8Array<"u"?Uint8Array:Array,w="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_=0,S=w.length;_<S;++_)m[_]=w[_],v[w.charCodeAt(_)]=_;v[45]=62,v[95]=63;function x(N){var H=N.length;if(H%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var V=N.indexOf("=");V===-1&&(V=H);var X=V===H?0:4-V%4;return[V,X]}function b(N){var H=x(N),V=H[0],X=H[1];return(V+X)*3/4-X}function C(N,H,V){return(H+V)*3/4-V}function E(N){var H,V=x(N),X=V[0],oe=V[1],se=new g(C(N,X,oe)),de=0,he=oe>0?X-4:X,we;for(we=0;we<he;we+=4)H=v[N.charCodeAt(we)]<<18|v[N.charCodeAt(we+1)]<<12|v[N.charCodeAt(we+2)]<<6|v[N.charCodeAt(we+3)],se[de++]=H>>16&255,se[de++]=H>>8&255,se[de++]=H&255;return oe===2&&(H=v[N.charCodeAt(we)]<<2|v[N.charCodeAt(we+1)]>>4,se[de++]=H&255),oe===1&&(H=v[N.charCodeAt(we)]<<10|v[N.charCodeAt(we+1)]<<4|v[N.charCodeAt(we+2)]>>2,se[de++]=H>>8&255,se[de++]=H&255),se}function M(N){return m[N>>18&63]+m[N>>12&63]+m[N>>6&63]+m[N&63]}function A(N,H,V){for(var X,oe=[],se=H;se<V;se+=3)X=(N[se]<<16&16711680)+(N[se+1]<<8&65280)+(N[se+2]&255),oe.push(M(X));return oe.join("")}function T(N){for(var H,V=N.length,X=V%3,oe=[],se=16383,de=0,he=V-X;de<he;de+=se)oe.push(A(N,de,de+se>he?he:de+se));return X===1?(H=N[V-1],oe.push(m[H>>2]+m[H<<4&63]+"==")):X===2&&(H=(N[V-2]<<8)+N[V-1],oe.push(m[H>>10]+m[H>>4&63]+m[H<<2&63]+"=")),oe.join("")}var L={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */L.read=function(N,H,V,X,oe){var se,de,he=oe*8-X-1,we=(1<<he)-1,te=we>>1,k=-7,q=V?oe-1:0,y=V?-1:1,B=N[H+q];for(q+=y,se=B&(1<<-k)-1,B>>=-k,k+=he;k>0;se=se*256+N[H+q],q+=y,k-=8);for(de=se&(1<<-k)-1,se>>=-k,k+=X;k>0;de=de*256+N[H+q],q+=y,k-=8);if(se===0)se=1-te;else{if(se===we)return de?NaN:(B?-1:1)*(1/0);de=de+Math.pow(2,X),se=se-te}return(B?-1:1)*de*Math.pow(2,se-X)},L.write=function(N,H,V,X,oe,se){var de,he,we,te=se*8-oe-1,k=(1<<te)-1,q=k>>1,y=oe===23?Math.pow(2,-24)-Math.pow(2,-77):0,B=X?0:se-1,$=X?1:-1,I=H<0||H===0&&1/H<0?1:0;for(H=Math.abs(H),isNaN(H)||H===1/0?(he=isNaN(H)?1:0,de=k):(de=Math.floor(Math.log(H)/Math.LN2),H*(we=Math.pow(2,-de))<1&&(de--,we*=2),de+q>=1?H+=y/we:H+=y*Math.pow(2,1-q),H*we>=2&&(de++,we/=2),de+q>=k?(he=0,de=k):de+q>=1?(he=(H*we-1)*Math.pow(2,oe),de=de+q):(he=H*Math.pow(2,q-1)*Math.pow(2,oe),de=0));oe>=8;N[V+B]=he&255,B+=$,he/=256,oe-=8);for(de=de<<oe|he,te+=oe;te>0;N[V+B]=de&255,B+=$,de/=256,te-=8);N[V+B-$]|=I*128};/*!
11
+ `+g):m.stack=g}catch{}}throw m}}_request(f,d){typeof f=="string"?(d=d||{},d.url=f):d=f||{},d=mergeConfig$1(this.defaults,d);const{transitional:m,paramsSerializer:v,headers:g}=d;m!==void 0&&validator.assertOptions(m,{silentJSONParsing:validators.transitional(validators.boolean),forcedJSONParsing:validators.transitional(validators.boolean),clarifyTimeoutError:validators.transitional(validators.boolean)},!1),v!=null&&(utils$5.isFunction(v)?d.paramsSerializer={serialize:v}:validator.assertOptions(v,{encode:validators.function,serialize:validators.function},!0)),d.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?d.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:d.allowAbsoluteUrls=!0),validator.assertOptions(d,{baseUrl:validators.spelling("baseURL"),withXsrfToken:validators.spelling("withXSRFToken")},!0),d.method=(d.method||this.defaults.method||"get").toLowerCase();let w=g&&utils$5.merge(g.common,g[d.method]);g&&utils$5.forEach(["delete","get","head","post","put","patch","common"],A=>{delete g[A]}),d.headers=AxiosHeaders$1.concat(w,g);const _=[];let S=!0;this.interceptors.request.forEach(function(T){typeof T.runWhen=="function"&&T.runWhen(d)===!1||(S=S&&T.synchronous,_.unshift(T.fulfilled,T.rejected))});const x=[];this.interceptors.response.forEach(function(T){x.push(T.fulfilled,T.rejected)});let b,C=0,E;if(!S){const A=[dispatchRequest.bind(this),void 0];for(A.unshift(..._),A.push(...x),E=A.length,b=Promise.resolve(d);C<E;)b=b.then(A[C++],A[C++]);return b}E=_.length;let M=d;for(C=0;C<E;){const A=_[C++],T=_[C++];try{M=A(M)}catch(L){T.call(this,L);break}}try{b=dispatchRequest.call(this,M)}catch(A){return Promise.reject(A)}for(C=0,E=x.length;C<E;)b=b.then(x[C++],x[C++]);return b}getUri(f){f=mergeConfig$1(this.defaults,f);const d=buildFullPath(f.baseURL,f.url,f.allowAbsoluteUrls);return buildURL(d,f.params,f.paramsSerializer)}};utils$5.forEach(["delete","get","head","options"],function(f){Axios$1.prototype[f]=function(d,m){return this.request(mergeConfig$1(m||{},{method:f,url:d,data:(m||{}).data}))}}),utils$5.forEach(["post","put","patch"],function(f){function d(m){return function(g,w,_){return this.request(mergeConfig$1(_||{},{method:f,headers:m?{"Content-Type":"multipart/form-data"}:{},url:g,data:w}))}}Axios$1.prototype[f]=d(),Axios$1.prototype[f+"Form"]=d(!0)});let CancelToken$1=class Gt{constructor(f){if(typeof f!="function")throw new TypeError("executor must be a function.");let d;this.promise=new Promise(function(g){d=g});const m=this;this.promise.then(v=>{if(!m._listeners)return;let g=m._listeners.length;for(;g-- >0;)m._listeners[g](v);m._listeners=null}),this.promise.then=v=>{let g;const w=new Promise(_=>{m.subscribe(_),g=_}).then(v);return w.cancel=function(){m.unsubscribe(g)},w},f(function(g,w,_){m.reason||(m.reason=new CanceledError$1(g,w,_),d(m.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(f){if(this.reason){f(this.reason);return}this._listeners?this._listeners.push(f):this._listeners=[f]}unsubscribe(f){if(!this._listeners)return;const d=this._listeners.indexOf(f);d!==-1&&this._listeners.splice(d,1)}toAbortSignal(){const f=new AbortController,d=m=>{f.abort(m)};return this.subscribe(d),f.signal.unsubscribe=()=>this.unsubscribe(d),f.signal}static source(){let f;return{token:new Gt(function(v){f=v}),cancel:f}}};function spread$2(r){return function(d){return r.apply(null,d)}}function isAxiosError$1(r){return utils$5.isObject(r)&&r.isAxiosError===!0}const HttpStatusCode$1={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(HttpStatusCode$1).forEach(([r,f])=>{HttpStatusCode$1[f]=r});function createInstance(r){const f=new Axios$1(r),d=bind(Axios$1.prototype.request,f);return utils$5.extend(d,Axios$1.prototype,f,{allOwnKeys:!0}),utils$5.extend(d,f,null,{allOwnKeys:!0}),d.create=function(v){return createInstance(mergeConfig$1(r,v))},d}const axios=createInstance(defaults);axios.Axios=Axios$1,axios.CanceledError=CanceledError$1,axios.CancelToken=CancelToken$1,axios.isCancel=isCancel$1,axios.VERSION=VERSION$1,axios.toFormData=toFormData$1,axios.AxiosError=AxiosError$1,axios.Cancel=axios.CanceledError,axios.all=function(f){return Promise.all(f)},axios.spread=spread$2,axios.isAxiosError=isAxiosError$1,axios.mergeConfig=mergeConfig$1,axios.AxiosHeaders=AxiosHeaders$1,axios.formToJSON=r=>formDataToJSON(utils$5.isHTMLForm(r)?new FormData(r):r),axios.getAdapter=adapters.getAdapter,axios.HttpStatusCode=HttpStatusCode$1,axios.default=axios;const{Axios,AxiosError,CanceledError,isCancel,CancelToken,VERSION,all,Cancel,isAxiosError,spread:spread$1,toFormData,AxiosHeaders,HttpStatusCode,formToJSON,getAdapter,mergeConfig}=axios,TEST_BASE_URL="https://miniapptest-spinfi.xy1212.com";class HttpClient{constructor(f){this.options=f;const d=f.baseURL;this.instance=axios.create({baseURL:d,timeout:3e4}),this.instance.interceptors.request.use(m=>{const v=this.options.getToken();if(v){m.headers=m.headers||{};const w=`Bearer ${v}`;m.headers.Authorization=w}const g=this.options.getAppId?this.options.getAppId():null;return g&&(m.headers=m.headers||{},m.headers["hm-app-id"]=String(g)),m}),this.instance.interceptors.response.use(m=>m,m=>(m.response&&m.response.status===401&&this.options.onAuthError&&this.options.onAuthError(),Promise.reject(m)))}request(f){return this.instance.request(f)}get(f,d){return this.instance.get(f,d)}post(f,d,m){return this.instance.post(f,d,m)}}class NamespacedStorage{constructor(f="tg_tracking_sdk"){this.prefix=f}k(f){return`${this.prefix}:${f}`}set(f,d){try{localStorage.setItem(this.k(f),JSON.stringify(d))}catch{}}get(f){try{const d=localStorage.getItem(this.k(f));return d?JSON.parse(d):null}catch{return null}}remove(f){try{localStorage.removeItem(this.k(f))}catch{}}}class APIService{constructor(f){this.http=f}auth(f){return this.http.post("/api/user/auth",f).then(d=>d.data)}getAdPositionConfig(f){return this.http.post("/api/ad/adPositionDisplayAd",{adPositionName:f}).then(d=>d.data)}createAd(f){return this.http.post("/api/v2/ad/create",f).then(d=>d.data)}adMonitor(f){return this.http.get("/api/v2/ad/monitor",{params:f}).then(d=>d.data)}bindWalletReq(f){return this.http.post("/api/user/bindWallet",f).then(d=>d.data)}merchantPayModeList(){return this.http.get("/api/v2/merchant/pay/modeList").then(f=>f.data)}merchantPayCreate(f){return this.http.post("/api/v2/merchant/pay/create",f).then(d=>d.data)}merchantPayFinish(f){return this.http.post("/api/v2/merchant/pay/finish",f).then(d=>d.data)}merchantPayQueryResult(f){return this.http.post("/api/v2/merchant/pay/queryResult",f).then(d=>d.data)}merchantPayNotify(f){return this.http.post("/api/v2/merchant/pay/notify",f).then(d=>d.data)}}class HmAdManager{constructor(f={}){this.options=f,this.initialized=!1}async init(){this.initialized||(this.options.autoInjectScript!==!1&&this.sdkZone&&this.sdkFunc&&await this.ensureScriptInjected(),this.initialized=!0)}async setSpace(f){if(!f)return;const d=String(f),m=`show_${f}`,v=this.sdkZone!==d||this.sdkFunc!==m;this.sdkZone=d,this.sdkFunc=m,this.options.autoInjectScript!==!1&&await this.ensureScriptInjected(v)}findExistingScript(){return typeof document>"u"?null:document.querySelector("script[src*='//libtl.com/sdk.js']")}async ensureScriptInjected(f=!1){var g;if(typeof document>"u")return;const d=this.findExistingScript(),m=this.sdkZone||"",v=this.sdkFunc||"";if(d){const w=d.getAttribute("data-zone")||"",_=d.getAttribute("data-sdk")||"";if(w===m&&_===v&&!f)return;(g=d.parentElement)==null||g.removeChild(d)}!m||!v||await this.injectScript(m,v)}injectScript(f,d){return new Promise((m,v)=>{if(typeof document>"u")return m();const g=document.createElement("script");g.src="//libtl.com/sdk.js",g.setAttribute("data-zone",f),g.setAttribute("data-sdk",d),g.async=!0,g.onload=()=>m(),g.onerror=()=>v(new Error("Hm 脚本加载失败")),document.head.appendChild(g)})}async callSDK(f){if(!this.sdkFunc)throw new Error("Hm 未设置 spaceId");const d=window[this.sdkFunc];if(typeof d!="function")throw new Error("Hm SDK 未正确加载");await d(f)}async show(){try{await this.callSDK()}catch(f){throw f}}async showPopup(){try{await this.callSDK("pop")}catch(f){throw f}}async showInApp(f){try{await this.callSDK({type:"inApp",inAppSettings:f})}catch(d){throw d}}}class AdMonitor{constructor(f){this.getMonitor=f}extractParamsFromUrl(f){if(!f)return null;try{return{param:new URL(f).searchParams.get("param")||""}}catch{return null}}async send(f,d){if(!f)return;const m=Array.isArray(f)?f:[f];if(m.length===0)return;const v=m[0],g=this.extractParamsFromUrl(v);let w;if(g&&this.getMonitor)try{const _=Math.floor(Date.now()/1e3).toString(),S=CryptoJS.MD5(d+_).toString(),x={param:g.param,request_code:S,timestamp:_};w=await this.getMonitor(x)}catch{}return await Promise.allSettled(m.slice(1).map(_=>{try{return fetch(_,{method:"GET"})}catch{return Promise.resolve()}})),w}}var commonjsGlobal=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function getDefaultExportFromCjs(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var dist$1={},sdk={},telegramWebApps={},hasRequiredTelegramWebApps;function requireTelegramWebApps(){return hasRequiredTelegramWebApps||(hasRequiredTelegramWebApps=1,(function(){var r={},f="";try{f=location.hash.toString()}catch{}var d=S(f),m=O("initParams");if(m)for(var v in m)typeof d[v]>"u"&&(d[v]=m[v]);L("initParams",d);var g=!1,w;try{if(g=window.parent!=null&&window!=window.parent,g){window.addEventListener("message",function(N){if(N.source===window.parent){try{var H=JSON.parse(N.data)}catch{return}if(!(!H||!H.eventType))if(H.eventType=="set_custom_style")N.origin==="https://web.telegram.org"&&(w.innerHTML=H.eventData);else if(H.eventType=="reload_iframe"){try{window.parent.postMessage(JSON.stringify({eventType:"iframe_will_reload"}),"*")}catch{}location.reload()}else E(H.eventType,H.eventData)}}),w=document.createElement("style"),document.head.appendChild(w);try{window.parent.postMessage(JSON.stringify({eventType:"iframe_ready",eventData:{reload_supported:!0}}),"*")}catch{}}}catch{}function _(N){try{return N=N.replace(/\+/g,"%20"),decodeURIComponent(N)}catch{return N}}function S(N){N=N.replace(/^#/,"");var H={};if(!N.length)return H;if(N.indexOf("=")<0&&N.indexOf("?")<0)return H._path=_(N),H;var V=N.indexOf("?");if(V>=0){var X=N.substr(0,V);H._path=_(X),N=N.substr(V+1)}var oe=x(N);for(var se in oe)H[se]=oe[se];return H}function x(N){var H={};if(!N.length)return H;var V=N.split("&"),X,oe,se,de;for(X=0;X<V.length;X++)oe=V[X].split("="),se=_(oe[0]),de=oe[1]==null?null:_(oe[1]),H[se]=de;return H}function b(N,H){var V=N.indexOf("#");if(V<0)return N+"#"+H;var X=N.substr(V+1);return X.indexOf("=")>=0||X.indexOf("?")>=0?N+"&"+H:X.length>0?N+"?"+H:N+H}function C(N,H,V){if(H||(H=function(){}),V===void 0&&(V=""),window.TelegramWebviewProxy!==void 0)TelegramWebviewProxy.postEvent(N,JSON.stringify(V)),H();else if(window.external&&"notify"in window.external)window.external.notify(JSON.stringify({eventType:N,eventData:V})),H();else if(g)try{var X="https://web.telegram.org";X="*",window.parent.postMessage(JSON.stringify({eventType:N,eventData:V}),X),H()}catch(oe){H(oe)}else H({notAvailable:!0})}function E(N,H){M(N,function(V){V(N,H)})}function M(N,H){var V=r[N];if(!(V===void 0||!V.length))for(var X=0;X<V.length;X++)try{H(V[X])}catch{}}function A(N,H){r[N]===void 0&&(r[N]=[]);var V=r[N].indexOf(H);V===-1&&r[N].push(H)}function T(N,H){if(r[N]!==void 0){var V=r[N].indexOf(H);V!==-1&&r[N].splice(V,1)}}function L(N,H){try{return window.sessionStorage.setItem("__telegram__"+N,JSON.stringify(H)),!0}catch{}return!1}function O(N){try{return JSON.parse(window.sessionStorage.getItem("__telegram__"+N))}catch{}return null}window.Telegram||(window.Telegram={}),window.Telegram.WebView={initParams:d,isIframe:g,onEvent:A,offEvent:T,postEvent:C,receiveEvent:E,callEventCallbacks:M},window.Telegram.Utils={urlSafeDecode:_,urlParseQueryString:x,urlParseHashParams:S,urlAppendHashParams:b,sessionStorageSet:L,sessionStorageGet:O},window.TelegramGameProxy_receiveEvent=E,window.TelegramGameProxy={receiveEvent:E}})(),(function(){var r=window.Telegram.Utils,f=window.Telegram.WebView,d=f.initParams,m=f.isIframe,v={},g="",w={},_={},S="light",x="6.0",b="unknown";if(d.tgWebAppData&&d.tgWebAppData.length){g=d.tgWebAppData,w=r.urlParseQueryString(g);for(var C in w){var E=w[C];try{(E.substr(0,1)=="{"&&E.substr(-1)=="}"||E.substr(0,1)=="["&&E.substr(-1)=="]")&&(w[C]=JSON.parse(E))}catch{}}}if(d.tgWebAppThemeParams&&d.tgWebAppThemeParams.length){var M=d.tgWebAppThemeParams;try{var A=JSON.parse(M);A&&he(A)}catch{}}var A=r.sessionStorageGet("themeParams");A&&he(A),d.tgWebAppVersion&&(x=d.tgWebAppVersion),d.tgWebAppPlatform&&(b=d.tgWebAppPlatform);function T(fe,U){U.theme_params&&(he(U.theme_params),window.Telegram.WebApp.MainButton.setParams({}),window.Telegram.WebApp.SecondaryButton.setParams({}),me(),ae(),Oe(),X("themeChanged"))}var L=window.innerHeight;function O(fe,U){U.height&&(window.removeEventListener("resize",N),B(U))}function N(fe){L!=window.innerHeight&&(L=window.innerHeight,X("viewportChanged",{isStateStable:!0}))}function H(fe){if(!(fe.metaKey||fe.ctrlKey)){for(var U=fe.target;U.tagName!="A"&&U.parentNode;)U=U.parentNode;U.tagName=="A"&&U.target!="_blank"&&(U.protocol=="http:"||U.protocol=="https:")&&U.hostname=="t.me"&&(v.openTgLink(U.href),fe.preventDefault())}}function V(fe){return fe.toString().replace(/^\s+|\s+$/g,"")}function X(fe){var U=Array.prototype.slice.call(arguments);fe=U.shift(),f.callEventCallbacks("webview:"+fe,function(G){G.apply(v,U)})}function oe(fe,U){f.onEvent("webview:"+fe,U)}function se(fe,U){f.offEvent("webview:"+fe,U)}function de(fe,U){var G=document.documentElement;G&&G.style&&G.style.setProperty&&G.style.setProperty("--tg-"+fe,U)}function he(fe){fe.bg_color=="#1c1c1d"&&fe.bg_color==fe.secondary_bg_color&&(fe.secondary_bg_color="#2c2c2e");var U;for(var G in fe)(U=Ue(fe[G]))&&(_[G]=U,G=="bg_color"&&(S=De(U)?"dark":"light",de("color-scheme",S)),G="theme-"+G.split("_").join("-"),de(G,U));r.sessionStorageSet("themeParams",_)}var we={};function te(fe){for(var U=100;--U;){for(var G="",re="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",K=re.length,ue=0;ue<fe;ue++)G+=re[Math.floor(Math.random()*K)];if(!we[G])return we[G]={},G}throw Error("WebAppCallbackIdGenerateFailed")}var k=!1,q=!1,y=!0;function B(fe){typeof fe<"u"&&(y=!!fe.is_expanded,k=fe.height,fe.is_state_stable&&(q=fe.height),X("viewportChanged",{isStateStable:!!fe.is_state_stable}));var U,G;k!==!1?U=k-ut+"px":U=ut?"calc(100vh - "+ut+"px)":"100vh",q!==!1?G=q-ut+"px":G=ut?"calc(100vh - "+ut+"px)":"100vh",de("viewport-height",U),de("viewport-stable-height",G)}var $=!1;function I(fe){je("6.2")&&($=!!fe,f.postEvent("web_app_setup_closing_behavior",!1,{need_confirmation:$}))}var F=!0;function j(fe){je("7.7")&&(F=!!fe,f.postEvent("web_app_setup_swipe_behavior",!1,{allow_vertical_swipe:F}))}var D="bg_color",W=null;function R(){return D=="secondary_bg_color"?_.secondary_bg_color:D=="bg_color"?_.bg_color:W}function z(fe){if(je("6.1")){je("6.9")||(_.bg_color&&_.bg_color==fe?fe="bg_color":_.secondary_bg_color&&_.secondary_bg_color==fe&&(fe="secondary_bg_color"));var U=null,G=null;if(fe=="bg_color"||fe=="secondary_bg_color")G=fe;else if(je("6.9")&&(U=Ue(fe),!U))throw Error("WebAppHeaderColorInvalid");if(!je("6.9")&&G!="bg_color"&&G!="secondary_bg_color")throw Error("WebAppHeaderColorKeyInvalid");D=G,W=U,me()}}var ye=null,Ce=null;function me(){(ye!=D||Ce!=W)&&(ye=D,Ce=W,Ce?f.postEvent("web_app_set_header_color",!1,{color:W}):f.postEvent("web_app_set_header_color",!1,{color_key:D}))}var ie="bg_color";function ee(){return ie=="secondary_bg_color"?_.secondary_bg_color:ie=="bg_color"?_.bg_color:ie}function pe(fe){if(je("6.1")){var U;if(fe=="bg_color"||fe=="secondary_bg_color")U=fe;else if(U=Ue(fe),!U)throw Error("WebAppBackgroundColorInvalid");ie=U,ae()}}var be=null;function ae(){var fe=ee();be!=fe&&(be=fe,f.postEvent("web_app_set_background_color",!1,{color:fe}))}var ne="bottom_bar_bg_color";function Se(){return ne=="bottom_bar_bg_color"?_.bottom_bar_bg_color||_.secondary_bg_color||"#ffffff":ne=="secondary_bg_color"?_.secondary_bg_color:ne=="bg_color"?_.bg_color:ne}function qe(fe){if(je("7.10")){var U;if(fe=="bg_color"||fe=="secondary_bg_color"||fe=="bottom_bar_bg_color")U=fe;else if(U=Ue(fe),!U)throw Error("WebAppBottomBarColorInvalid");ne=U,Oe(),window.Telegram.WebApp.SecondaryButton.setParams({})}}var Ie=null;function Oe(){var fe=Se();Ie!=fe&&(Ie=fe,f.postEvent("web_app_set_bottom_bar_color",!1,{color:fe})),d.tgWebAppDebug&&bt()}function Ue(fe){fe+="";var U;if(U=/^\s*#([0-9a-f]{6})\s*$/i.exec(fe))return"#"+U[1].toLowerCase();if(U=/^\s*#([0-9a-f])([0-9a-f])([0-9a-f])\s*$/i.exec(fe))return("#"+U[1]+U[1]+U[2]+U[2]+U[3]+U[3]).toLowerCase();if(U=/^\s*rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+\.{0,1}\d*))?\)\s*$/.exec(fe)){var G=parseInt(U[1]),re=parseInt(U[2]),K=parseInt(U[3]);return G=(G<16?"0":"")+G.toString(16),re=(re<16?"0":"")+re.toString(16),K=(K<16?"0":"")+K.toString(16),"#"+G+re+K}return!1}function De(fe){fe=fe.replace(/[\s#]/g,""),fe.length==3&&(fe=fe[0]+fe[0]+fe[1]+fe[1]+fe[2]+fe[2]);var U=parseInt(fe.substr(0,2),16),G=parseInt(fe.substr(2,2),16),re=parseInt(fe.substr(4,2),16),K=Math.sqrt(.299*(U*U)+.587*(G*G)+.114*(re*re));return K<120}function $e(fe,U){typeof fe!="string"&&(fe=""),typeof U!="string"&&(U=""),fe=fe.replace(/^\s+|\s+$/g,"").split("."),U=U.replace(/^\s+|\s+$/g,"").split(".");var G=Math.max(fe.length,U.length),re,K,ue;for(re=0;re<G;re++)if(K=parseInt(fe[re])||0,ue=parseInt(U[re])||0,K!=ue)return K>ue?1:-1;return 0}function je(fe){return $e(x,fe)>=0}function Ye(fe){if(window.Blob)try{return new Blob([fe]).size}catch{}for(var U=fe.length,G=fe.length-1;G>=0;G--){var re=fe.charCodeAt(G);re>127&&re<=2047?U++:re>2047&&re<=65535&&(U+=2),re>=56320&&re<=57343&&G--}return U}var st=(function(){var fe=!1,U={};Object.defineProperty(U,"isVisible",{set:function(Pe){Te({is_visible:Pe})},get:function(){return fe},enumerable:!0});var G=null;f.onEvent("back_button_pressed",re);function re(){X("backButtonClicked")}function K(){return{is_visible:fe}}function ue(Pe){return typeof Pe>"u"&&(Pe=K()),JSON.stringify(Pe)}function Ae(){return!!je("6.1")}function xe(){var Pe=K(),Fe=ue(Pe);G!==Fe&&(G=Fe,f.postEvent("web_app_setup_back_button",!1,Pe))}function Te(Pe){return Ae()&&(typeof Pe.is_visible<"u"&&(fe=!!Pe.is_visible),xe()),U}return U.onClick=function(Pe){return Ae()&&oe("backButtonClicked",Pe),U},U.offClick=function(Pe){return Ae()&&se("backButtonClicked",Pe),U},U.show=function(){return Te({is_visible:!0})},U.hide=function(){return Te({is_visible:!1})},U})(),Je=null,Ge={},ut=0;if(d.tgWebAppDebug){Je=document.createElement("tg-bottom-bar");var gt={display:"flex",gap:"7px",font:"600 14px/18px sans-serif",width:"100%",background:Se(),position:"fixed",left:"0",right:"0",bottom:"0",margin:"0",padding:"7px",textAlign:"center",boxSizing:"border-box",zIndex:"10000"};for(var rt in gt)Je.style[rt]=gt[rt];document.addEventListener("DOMContentLoaded",function fe(U){document.removeEventListener("DOMContentLoaded",fe),document.body.appendChild(Je)});var wt=document.createElement("style");wt.innerHTML='tg-bottom-button.shine { position: relative; overflow: hidden; } tg-bottom-button.shine:before { content:""; position: absolute; top: 0; width: 100%; height: 100%; background: linear-gradient(120deg, transparent, rgba(255, 255, 255, .2), transparent); animation: tg-bottom-button-shine 5s ease-in-out infinite; } @-webkit-keyframes tg-bottom-button-shine { 0% {left: -100%;} 12%,100% {left: 100%}} @keyframes tg-bottom-button-shine { 0% {left: -100%;} 12%,100% {left: 100%}}',Je.appendChild(wt)}function bt(){var fe=Ge.main._bottomButton,U=Ge.secondary._bottomButton;fe.isVisible||U.isVisible?(Je.style.display="flex",ut=58,fe.isVisible&&U.isVisible&&(U.position=="top"?(Je.style.flexDirection="column-reverse",ut+=51):U.position=="bottom"?(Je.style.flexDirection="column",ut+=51):U.position=="left"?Je.style.flexDirection="row-reverse":U.position=="right"&&(Je.style.flexDirection="row"))):(Je.style.display="none",ut=0),Je.style.background=Se(),document.documentElement&&(document.documentElement.style.boxSizing="border-box",document.documentElement.style.paddingBottom=ut+"px"),B()}var le=function(fe){var U=fe=="main";if(U)var G="web_app_setup_main_button",re="main_button_pressed",K="mainButtonClicked",ue="Continue",Ae=function(){return _.button_color||"#2481cc"},xe=function(){return _.button_text_color||"#ffffff"};else var G="web_app_setup_secondary_button",re="secondary_button_pressed",K="secondaryButtonClicked",ue="Cancel",Ae=function(){return Se()},xe=function(){return _.button_color||"#2481cc"};var Te=!1,Pe=!0,Fe=!1,Ne=!1,At=fe,ot=ue,yt=!1,vt=!1,xt="left",Ve={};Object.defineProperty(Ve,"type",{get:function(){return At},enumerable:!0}),Object.defineProperty(Ve,"text",{set:function(Be){Ve.setParams({text:Be})},get:function(){return ot},enumerable:!0}),Object.defineProperty(Ve,"color",{set:function(Be){Ve.setParams({color:Be})},get:function(){return yt||Ae()},enumerable:!0}),Object.defineProperty(Ve,"textColor",{set:function(Be){Ve.setParams({text_color:Be})},get:function(){return vt||xe()},enumerable:!0}),Object.defineProperty(Ve,"isVisible",{set:function(Be){Ve.setParams({is_visible:Be})},get:function(){return Te},enumerable:!0}),Object.defineProperty(Ve,"isProgressVisible",{get:function(){return Ne},enumerable:!0}),Object.defineProperty(Ve,"isActive",{set:function(Be){Ve.setParams({is_active:Be})},get:function(){return Pe},enumerable:!0}),Object.defineProperty(Ve,"hasShineEffect",{set:function(Be){Ve.setParams({has_shine_effect:Be})},get:function(){return Fe},enumerable:!0}),U||Object.defineProperty(Ve,"position",{set:function(Be){Ve.setParams({position:Be})},get:function(){return xt},enumerable:!0});var ft=null;f.onEvent(re,pt);var et=null;if(d.tgWebAppDebug){et=document.createElement("tg-bottom-button");var ht={display:"none",width:"100%",height:"44px",borderRadius:"0",background:"no-repeat right center",padding:"13px 15px",textAlign:"center",boxSizing:"border-box"};for(var it in ht)et.style[it]=ht[it];Je.appendChild(et),et.addEventListener("click",pt,!1),et._bottomButton=Ve,Ge[fe]=et}function pt(){Pe&&X(K)}function at(){var Be=Ve.color,Ke=Ve.textColor;if(Te){var We={is_visible:!0,is_active:Pe,is_progress_visible:Ne,text:ot,color:Be,text_color:Ke,has_shine_effect:Fe&&Pe&&!Ne};U||(We.position=xt)}else var We={is_visible:!1};return We}function ct(Be){return typeof Be>"u"&&(Be=at()),JSON.stringify(Be)}function dt(){var Be=at(),Ke=ct(Be);ft!==Ke&&(ft=Ke,f.postEvent(G,!1,Be),d.tgWebAppDebug&&nt(Be))}function nt(Be){Be.is_visible?(et.style.display="block",et.style.opacity=Be.is_active?"1":"0.8",et.style.cursor=Be.is_active?"pointer":"auto",et.disabled=!Be.is_active,et.innerText=Be.text,et.className=Be.has_shine_effect?"shine":"",et.style.backgroundImage=Be.is_progress_visible?"url('data:image/svg+xml,"+encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewport="0 0 48 48" width="48px" height="48px"><circle cx="50%" cy="50%" stroke="'+Be.text_color+'" stroke-width="2.25" stroke-linecap="round" fill="none" stroke-dashoffset="106" r="9" stroke-dasharray="56.52" rotate="-90"><animate attributeName="stroke-dashoffset" attributeType="XML" dur="360s" from="0" to="12500" repeatCount="indefinite"></animate><animateTransform attributeName="transform" attributeType="XML" type="rotate" dur="1s" from="-90 24 24" to="630 24 24" repeatCount="indefinite"></animateTransform></circle></svg>')+"')":"none",et.style.backgroundColor=Be.color,et.style.color=Be.text_color):et.style.display="none",bt()}function Le(Be){if(typeof Be.text<"u"){var Ke=V(Be.text);if(!Ke.length||Ke.length>64)throw Error("WebAppBottomButtonParamInvalid");ot=Ke}if(typeof Be.color<"u")if(Be.color===!1||Be.color===null)yt=!1;else{var We=Ue(Be.color);if(!We)throw Error("WebAppBottomButtonParamInvalid");yt=We}if(typeof Be.text_color<"u")if(Be.text_color===!1||Be.text_color===null)vt=!1;else{var ze=Ue(Be.text_color);if(!ze)throw Error("WebAppBottomButtonParamInvalid");vt=ze}if(typeof Be.is_visible<"u"){if(Be.is_visible&&!Ve.text.length)throw Error("WebAppBottomButtonParamInvalid");Te=!!Be.is_visible}if(typeof Be.has_shine_effect<"u"&&(Fe=!!Be.has_shine_effect),!U&&typeof Be.position<"u"){if(Be.position!="left"&&Be.position!="right"&&Be.position!="top"&&Be.position!="bottom")throw Error("WebAppBottomButtonParamInvalid");xt=Be.position}return typeof Be.is_active<"u"&&(Pe=!!Be.is_active),dt(),Ve}return Ve.setText=function(Be){return Ve.setParams({text:Be})},Ve.onClick=function(Be){return oe(K,Be),Ve},Ve.offClick=function(Be){return se(K,Be),Ve},Ve.show=function(){return Ve.setParams({is_visible:!0})},Ve.hide=function(){return Ve.setParams({is_visible:!1})},Ve.enable=function(){return Ve.setParams({is_active:!0})},Ve.disable=function(){return Ve.setParams({is_active:!1})},Ve.showProgress=function(Be){return Pe=!!Be,Ne=!0,dt(),Ve},Ve.hideProgress=function(){return Ve.isActive||(Pe=!0),Ne=!1,dt(),Ve},Ve.setParams=Le,Ve},Z=le("main"),J=le("secondary"),ge=(function(){var fe=!1,U={};Object.defineProperty(U,"isVisible",{set:function(Pe){Te({is_visible:Pe})},get:function(){return fe},enumerable:!0});var G=null;f.onEvent("settings_button_pressed",re);function re(){X("settingsButtonClicked")}function K(){return{is_visible:fe}}function ue(Pe){return typeof Pe>"u"&&(Pe=K()),JSON.stringify(Pe)}function Ae(){return!!je("6.10")}function xe(){var Pe=K(),Fe=ue(Pe);G!==Fe&&(G=Fe,f.postEvent("web_app_setup_settings_button",!1,Pe))}function Te(Pe){return Ae()&&(typeof Pe.is_visible<"u"&&(fe=!!Pe.is_visible),xe()),U}return U.onClick=function(Pe){return Ae()&&oe("settingsButtonClicked",Pe),U},U.offClick=function(Pe){return Ae()&&se("settingsButtonClicked",Pe),U},U.show=function(){return Te({is_visible:!0})},U.hide=function(){return Te({is_visible:!1})},U})(),Ee=(function(){var fe={};function U(G){if(!je("6.1"))return fe;if(G.type=="impact"){if(G.impact_style!="light"&&G.impact_style!="medium"&&G.impact_style!="heavy"&&G.impact_style!="rigid"&&G.impact_style!="soft")throw Error("WebAppHapticImpactStyleInvalid")}else if(G.type=="notification"){if(G.notification_type!="error"&&G.notification_type!="success"&&G.notification_type!="warning")throw Error("WebAppHapticNotificationTypeInvalid")}else if(G.type!="selection_change")throw Error("WebAppHapticFeedbackTypeInvalid");return f.postEvent("web_app_trigger_haptic_feedback",!1,G),fe}return fe.impactOccurred=function(G){return U({type:"impact",impact_style:G})},fe.notificationOccurred=function(G){return U({type:"notification",notification_type:G})},fe.selectionChanged=function(){return U({type:"selection_change"})},fe})(),Re=(function(){var fe={};function U(G,re,K){if(!je("6.9"))throw Error("WebAppMethodUnsupported");return ve(G,re,K),fe}return fe.setItem=function(G,re,K){return U("saveStorageValue",{key:G,value:re},K)},fe.getItem=function(G,re){return fe.getItems([G],re?function(K,ue){K?re(K):re(null,ue[G])}:null)},fe.getItems=function(G,re){return U("getStorageValues",{keys:G},re)},fe.removeItem=function(G,re){return fe.removeItems([G],re)},fe.removeItems=function(G,re){return U("deleteStorageValues",{keys:G},re)},fe.getKeys=function(G){return U("getStorageKeys",{},G)},fe})(),ke=(function(){var fe=!1,U=!1,G="unknown",re=!1,K=!1,ue=!1,Ae="",xe={};Object.defineProperty(xe,"isInited",{get:function(){return fe},enumerable:!0}),Object.defineProperty(xe,"isBiometricAvailable",{get:function(){return fe&&U},enumerable:!0}),Object.defineProperty(xe,"biometricType",{get:function(){return G||"unknown"},enumerable:!0}),Object.defineProperty(xe,"isAccessRequested",{get:function(){return re},enumerable:!0}),Object.defineProperty(xe,"isAccessGranted",{get:function(){return re&&K},enumerable:!0}),Object.defineProperty(xe,"isBiometricTokenSaved",{get:function(){return ue},enumerable:!0}),Object.defineProperty(xe,"deviceId",{get:function(){return Ae||""},enumerable:!0});var Te={callbacks:[]},Pe=!1,Fe=!1,Ne=!1;f.onEvent("biometry_info_received",At),f.onEvent("biometry_auth_requested",ot),f.onEvent("biometry_token_updated",yt);function At(Ve,ft){if(fe=!0,ft.available?(U=!0,G=ft.type||"unknown",ft.access_requested?(re=!0,K=!!ft.access_granted,ue=!!ft.token_saved):(re=!1,K=!1,ue=!1)):(U=!1,G="unknown",re=!1,K=!1,ue=!1),Ae=ft.device_id||"",Te.callbacks.length>0)for(var et=0;et<Te.callbacks.length;et++){var ht=Te.callbacks[et];ht()}if(Pe){var it=Pe;Pe=!1,it.callback&&it.callback(K)}X("biometricManagerUpdated")}function ot(Ve,ft){var et=ft.status=="authorized",ht=ft.token||"";if(Fe){var it=Fe;Fe=!1,it.callback&&it.callback(et,et?ht:null)}X("biometricAuthRequested",et?{isAuthenticated:!0,biometricToken:ht}:{isAuthenticated:!1})}function yt(Ve,ft){var et=!1;if(U&&re&&(ft.status=="updated"?(ue=!0,et=!0):ft.status=="removed"&&(ue=!1,et=!0)),Ne){var ht=Ne;Ne=!1,ht.callback&&ht.callback(et)}X("biometricTokenUpdated",{isUpdated:et})}function vt(){return!!je("7.2")}function xt(){if(!fe)throw Error("WebAppBiometricManagerNotInited");return!0}return xe.init=function(Ve){return!vt()||fe||(Ve&&Te.callbacks.push(Ve),f.postEvent("web_app_biometry_get_info",!1)),xe},xe.requestAccess=function(Ve,ft){if(!vt())return xe;if(xt(),!U)throw Error("WebAppBiometricManagerBiometricsNotAvailable");if(Pe)throw Error("WebAppBiometricManagerAccessRequested");var et={};if(typeof Ve.reason<"u"){var ht=V(Ve.reason);if(ht.length>128)throw Error("WebAppBiometricRequestAccessParamInvalid");ht.length>0&&(et.reason=ht)}return Pe={callback:ft},f.postEvent("web_app_biometry_request_access",!1,et),xe},xe.authenticate=function(Ve,ft){if(!vt())return xe;if(xt(),!U)throw Error("WebAppBiometricManagerBiometricsNotAvailable");if(!K)throw Error("WebAppBiometricManagerBiometricAccessNotGranted");if(Fe)throw Error("WebAppBiometricManagerAuthenticationRequested");var et={};if(typeof Ve.reason<"u"){var ht=V(Ve.reason);if(ht.length>128)throw Error("WebAppBiometricRequestAccessParamInvalid");ht.length>0&&(et.reason=ht)}return Fe={callback:ft},f.postEvent("web_app_biometry_request_auth",!1,et),xe},xe.updateBiometricToken=function(Ve,ft){if(!vt())return xe;if(Ve=Ve||"",Ve.length>1024)throw Error("WebAppBiometricManagerTokenInvalid");if(xt(),!U)throw Error("WebAppBiometricManagerBiometricsNotAvailable");if(!K)throw Error("WebAppBiometricManagerBiometricAccessNotGranted");if(Ne)throw Error("WebAppBiometricManagerTokenUpdateRequested");return Ne={callback:ft},f.postEvent("web_app_biometry_update_token",!1,{token:Ve}),xe},xe.openSettings=function(){if(!vt())return xe;if(xt(),!U)throw Error("WebAppBiometricManagerBiometricsNotAvailable");if(!re)throw Error("WebAppBiometricManagerBiometricsAccessNotRequested");return K||f.postEvent("web_app_biometry_open_settings",!1),xe},xe})(),Xe={};function He(fe,U){if(U.slug&&Xe[U.slug]){var G=Xe[U.slug];delete Xe[U.slug],G.callback&&G.callback(U.status),X("invoiceClosed",{url:G.url,status:U.status})}}var Ze=!1;function _t(fe,U){if(Ze){var G=Ze;Ze=!1;var re=null;typeof U.button_id<"u"&&(re=U.button_id),G.callback&&G.callback(re),X("popupClosed",{button_id:re})}}var tt=!1;function mt(fe,U){if(tt){var G=tt,re=null;typeof U.data<"u"&&(re=U.data),G.callback&&G.callback(re)&&(tt=!1,f.postEvent("web_app_close_scan_qr_popup",!1)),X("qrTextReceived",{data:re})}}function Tt(fe,U){tt=!1,X("scanQrPopupClosed")}function St(fe,U){if(U.req_id&&we[U.req_id]){var G=we[U.req_id];delete we[U.req_id];var re=null;typeof U.data<"u"&&(re=U.data),G.callback&&G.callback(re),X("clipboardTextReceived",{data:re})}}var lt=!1;function Mt(fe,U){if(lt){var G=lt;lt=!1,G.callback&&G.callback(U.status=="allowed"),X("writeAccessRequested",{status:U.status})}}function Ct(fe,U){var G,re,K=0,ue=function(){ve("getRequestedContact",{},function(xe,Te){Te&&Te.length?(clearTimeout(re),fe(Te)):(K+=50,G=setTimeout(ue,K))})},Ae=function(){clearTimeout(G),fe("")};re=setTimeout(Ae,U),ue()}var ce=!1;function Y(fe,U){if(ce){var G=ce;ce=!1;var re=U.status=="sent",K={status:U.status};re?Ct(function(ue){if(ue&&ue.length){K.response=ue,K.responseUnsafe=r.urlParseQueryString(ue);for(var Ae in K.responseUnsafe){var xe=K.responseUnsafe[Ae];try{(xe.substr(0,1)=="{"&&xe.substr(-1)=="}"||xe.substr(0,1)=="["&&xe.substr(-1)=="]")&&(K.responseUnsafe[Ae]=JSON.parse(xe))}catch{}}}G.callback&&G.callback(re,K),X("contactRequested",K)},3e3):(G.callback&&G.callback(re,K),X("contactRequested",K))}}function Q(fe,U){if(U.req_id&&we[U.req_id]){var G=we[U.req_id];delete we[U.req_id];var re=null,K=null;typeof U.result<"u"&&(re=U.result),typeof U.error<"u"&&(K=U.error),G.callback&&G.callback(K,re)}}function ve(fe,U,G){if(!je("6.9"))throw Error("WebAppMethodUnsupported");var re=te(16),K={req_id:re,method:fe,params:U||{}};we[re]={callback:G},f.postEvent("web_app_invoke_custom_method",!1,K)}window.Telegram||(window.Telegram={}),Object.defineProperty(v,"initData",{get:function(){return g},enumerable:!0}),Object.defineProperty(v,"initDataUnsafe",{get:function(){return w},enumerable:!0}),Object.defineProperty(v,"version",{get:function(){return x},enumerable:!0}),Object.defineProperty(v,"platform",{get:function(){return b},enumerable:!0}),Object.defineProperty(v,"colorScheme",{get:function(){return S},enumerable:!0}),Object.defineProperty(v,"themeParams",{get:function(){return _},enumerable:!0}),Object.defineProperty(v,"isExpanded",{get:function(){return y},enumerable:!0}),Object.defineProperty(v,"viewportHeight",{get:function(){return(k===!1?window.innerHeight:k)-ut},enumerable:!0}),Object.defineProperty(v,"viewportStableHeight",{get:function(){return(q===!1?window.innerHeight:q)-ut},enumerable:!0}),Object.defineProperty(v,"isClosingConfirmationEnabled",{set:function(fe){I(fe)},get:function(){return $},enumerable:!0}),Object.defineProperty(v,"isVerticalSwipesEnabled",{set:function(fe){j(fe)},get:function(){return F},enumerable:!0}),Object.defineProperty(v,"headerColor",{set:function(fe){z(fe)},get:function(){return R()},enumerable:!0}),Object.defineProperty(v,"backgroundColor",{set:function(fe){pe(fe)},get:function(){return ee()},enumerable:!0}),Object.defineProperty(v,"bottomBarColor",{set:function(fe){qe(fe)},get:function(){return Se()},enumerable:!0}),Object.defineProperty(v,"BackButton",{value:st,enumerable:!0}),Object.defineProperty(v,"MainButton",{value:Z,enumerable:!0}),Object.defineProperty(v,"SecondaryButton",{value:J,enumerable:!0}),Object.defineProperty(v,"SettingsButton",{value:ge,enumerable:!0}),Object.defineProperty(v,"HapticFeedback",{value:Ee,enumerable:!0}),Object.defineProperty(v,"CloudStorage",{value:Re,enumerable:!0}),Object.defineProperty(v,"BiometricManager",{value:ke,enumerable:!0}),v.setHeaderColor=function(fe){v.headerColor=fe},v.setBackgroundColor=function(fe){v.backgroundColor=fe},v.setBottomBarColor=function(fe){v.bottomBarColor=fe},v.enableClosingConfirmation=function(){v.isClosingConfirmationEnabled=!0},v.disableClosingConfirmation=function(){v.isClosingConfirmationEnabled=!1},v.enableVerticalSwipes=function(){v.isVerticalSwipesEnabled=!0},v.disableVerticalSwipes=function(){v.isVerticalSwipesEnabled=!1},v.isVersionAtLeast=function(fe){return je(fe)},v.onEvent=function(fe,U){oe(fe,U)},v.offEvent=function(fe,U){se(fe,U)},v.sendData=function(fe){if(!fe||!fe.length||Ye(fe)>4096)throw Error("WebAppDataInvalid");f.postEvent("web_app_data_send",!1,{data:fe})},v.switchInlineQuery=function(fe,U){if(!je("6.6"))throw Error("WebAppMethodUnsupported");if(!d.tgWebAppBotInline)throw Error("WebAppInlineModeDisabled");if(fe=fe||"",fe.length>256)throw Error("WebAppInlineQueryInvalid");var G=[];if(U){if(!Array.isArray(U))throw Error("WebAppInlineChooseChatTypesInvalid");for(var re={users:1,bots:1,groups:1,channels:1},K=0;K<U.length;K++){var ue=U[K];if(!re[ue])throw Error("WebAppInlineChooseChatTypeInvalid");re[ue]!=2&&(re[ue]=2,G.push(ue))}}f.postEvent("web_app_switch_inline_query",!1,{query:fe,chat_types:G})},v.openLink=function(re,U){var G=document.createElement("A");if(G.href=re,G.protocol!="http:"&&G.protocol!="https:")throw Error("WebAppTgUrlInvalid");var re=G.href;if(U=U||{},je("6.1")){var K={url:re};je("6.4")&&U.try_instant_view&&(K.try_instant_view=!0),je("7.6")&&U.try_browser&&(K.try_browser=U.try_browser),f.postEvent("web_app_open_link",!1,K)}else window.open(re,"_blank")},v.openTelegramLink=function(fe){var U=document.createElement("A");if(U.href=fe,U.protocol!="http:"&&U.protocol!="https:"||U.hostname!="t.me")throw Error("WebAppTgUrlInvalid");var G=U.pathname+U.search;m||je("6.1")?f.postEvent("web_app_open_tg_link",!1,{path_full:G}):location.href="https://t.me"+G},v.openInvoice=function(fe,U){var G=document.createElement("A"),re,K;if(G.href=fe,G.protocol!="http:"&&G.protocol!="https:"||G.hostname!="t.me"||!(re=G.pathname.match(/^\/(\$|invoice\/)([A-Za-z0-9\-_=]+)$/))||!(K=re[2]))throw Error("WebAppInvoiceUrlInvalid");if(!je("6.1"))throw Error("WebAppMethodUnsupported");if(Xe[K])throw Error("WebAppInvoiceOpened");Xe[K]={url:fe,callback:U},f.postEvent("web_app_open_invoice",!1,{slug:K})},v.showPopup=function(fe,U){if(!je("6.2"))throw Error("WebAppMethodUnsupported");if(Ze)throw Error("WebAppPopupOpened");var G="",re="",K=[],ue={};if(typeof fe.title<"u"){if(G=V(fe.title),G.length>64)throw Error("WebAppPopupParamInvalid");G.length>0&&(ue.title=G)}if(typeof fe.message<"u"&&(re=V(fe.message)),!re.length||re.length>256)throw Error("WebAppPopupParamInvalid");if(ue.message=re,typeof fe.buttons<"u"){if(!Array.isArray(fe.buttons))throw Error("WebAppPopupParamInvalid");for(var Ae=0;Ae<fe.buttons.length;Ae++){var xe=fe.buttons[Ae],Te={},Pe="";if(typeof xe.id<"u"&&(Pe=xe.id.toString(),Pe.length>64))throw Error("WebAppPopupParamInvalid");Te.id=Pe;var Fe=xe.type;if(typeof Fe>"u"&&(Fe="default"),Te.type=Fe,!(Fe=="ok"||Fe=="close"||Fe=="cancel"))if(Fe=="default"||Fe=="destructive"){var Ne="";if(typeof xe.text<"u"&&(Ne=V(xe.text)),!Ne.length||Ne.length>64)throw Error("WebAppPopupParamInvalid");Te.text=Ne}else throw Error("WebAppPopupParamInvalid");K.push(Te)}}else K.push({id:"",type:"close"});if(K.length<1||K.length>3)throw Error("WebAppPopupParamInvalid");ue.buttons=K,Ze={callback:U},f.postEvent("web_app_open_popup",!1,ue)},v.showAlert=function(fe,U){v.showPopup({message:fe},U?function(){U()}:null)},v.showConfirm=function(fe,U){v.showPopup({message:fe,buttons:[{type:"ok",id:"ok"},{type:"cancel"}]},U?function(G){U(G=="ok")}:null)},v.showScanQrPopup=function(fe,U){if(!je("6.4"))throw Error("WebAppMethodUnsupported");if(tt)throw Error("WebAppScanQrPopupOpened");var G="",re={};if(typeof fe.text<"u"){if(G=V(fe.text),G.length>64)throw Error("WebAppScanQrPopupParamInvalid");G.length>0&&(re.text=G)}tt={callback:U},f.postEvent("web_app_open_scan_qr_popup",!1,re)},v.closeScanQrPopup=function(){if(!je("6.4"))throw Error("WebAppMethodUnsupported");tt=!1,f.postEvent("web_app_close_scan_qr_popup",!1)},v.readTextFromClipboard=function(fe){if(!je("6.4"))throw Error("WebAppMethodUnsupported");var U=te(16),G={req_id:U};we[U]={callback:fe},f.postEvent("web_app_read_text_from_clipboard",!1,G)},v.requestWriteAccess=function(fe){if(!je("6.9"))throw Error("WebAppMethodUnsupported");if(lt)throw Error("WebAppWriteAccessRequested");lt={callback:fe},f.postEvent("web_app_request_write_access")},v.requestContact=function(fe){if(!je("6.9"))throw Error("WebAppMethodUnsupported");if(ce)throw Error("WebAppContactRequested");ce={callback:fe},f.postEvent("web_app_request_phone")},v.shareToStory=function(fe,U){if(U=U||{},!je("7.8"))throw Error("WebAppMethodUnsupported");var G=document.createElement("A");if(G.href=fe,G.protocol!="http:"&&G.protocol!="https:")throw Error("WebAppMediaUrlInvalid");var re={};if(re.media_url=G.href,typeof U.text<"u"){var K=V(U.text);if(K.length>2048)throw Error("WebAppShareToStoryParamInvalid");K.length>0&&(re.text=K)}if(typeof U.widget_link<"u"){if(U.widget_link=U.widget_link||{},G.href=U.widget_link.url,G.protocol!="http:"&&G.protocol!="https:")throw Error("WebAppShareToStoryParamInvalid");var ue={url:G.href};if(typeof U.widget_link.name<"u"){var Ae=V(U.widget_link.name);if(Ae.length>48)throw Error("WebAppShareToStoryParamInvalid");Ae.length>0&&(ue.name=Ae)}re.widget_link=ue}f.postEvent("web_app_share_to_story",!1,re)},v.invokeCustomMethod=function(fe,U,G){ve(fe,U,G)},v.ready=function(){f.postEvent("web_app_ready")},v.expand=function(){f.postEvent("web_app_expand")},v.close=function(fe){fe=fe||{};var U={};je("7.6")&&fe.return_back&&(U.return_back=!0),f.postEvent("web_app_close",!1,U)},window.Telegram.WebApp=v,me(),ae(),Oe(),B(),d.tgWebAppShowSettings&&ge.show(),window.addEventListener("resize",N),m&&document.addEventListener("click",H),f.onEvent("theme_changed",T),f.onEvent("viewport_changed",O),f.onEvent("invoice_closed",He),f.onEvent("popup_closed",_t),f.onEvent("qr_text_received",mt),f.onEvent("scan_qr_popup_closed",Tt),f.onEvent("clipboard_text_received",St),f.onEvent("write_access_requested",Mt),f.onEvent("phone_requested",Y),f.onEvent("custom_method_invoked",Q),f.postEvent("web_app_request_theme"),f.postEvent("web_app_request_viewport")})()),telegramWebApps}var hasRequiredSdk;function requireSdk(){if(hasRequiredSdk)return sdk;hasRequiredSdk=1,Object.defineProperty(sdk,"__esModule",{value:!0}),sdk.WebApp=void 0,requireTelegramWebApps();var r=window;return sdk.WebApp=r.Telegram.WebApp,sdk}var hasRequiredDist$1;function requireDist$1(){if(hasRequiredDist$1)return dist$1;hasRequiredDist$1=1,Object.defineProperty(dist$1,"__esModule",{value:!0});var r=requireSdk();return dist$1.default=r.WebApp,dist$1}var distExports=requireDist$1();const WebApp=getDefaultExportFromCjs(distExports);function retrieveLaunchParams(){if(!WebApp.initData||WebApp.initData==="")throw new Error("未能提取启动参数,不在 Telegram 环境中");return WebApp.initData}function isTelegramEnv(){try{return typeof window<"u"&&window.Telegram&&window.Telegram.WebApp?(retrieveLaunchParams(),!0):!1}catch{return!1}}function getTelegramUserUnsafe(){try{if(!WebApp||!WebApp.initDataUnsafe)return null;const r=WebApp.initDataUnsafe;return!r.user||!r.user.id?null:{user:{id:r.user.id,firstName:r.user.first_name||"",lastName:r.user.last_name||"",username:r.user.username,languageCode:r.user.language_code,isPremium:r.user.is_premium||!1,allowsWriteToPm:r.user.allows_write_to_pm||!1},authDate:new Date().toISOString(),hash:r.hash||"",startParam:r.start_param,chatType:r.chat_type,chatInstance:r.chat_instance}}catch{return null}}function readCookie(r){if(typeof document>"u")return null;const f=document.cookie.match(new RegExp("(?:^|; )"+r.replace(/([.$?*|{}()\[\]\\/+^])/g,"\\$1")+"=([^;]*)"));return f?decodeURIComponent(f[1]):null}function writeCookie(r,f,d=365*2){if(typeof document>"u")return;const m=new Date;m.setTime(m.getTime()+d*24*60*60*1e3);const v="; expires="+m.toUTCString();document.cookie=`${encodeURIComponent(r)}=${encodeURIComponent(f)}${v}; path=/`}function generateNumericId(){const r=Math.floor(Math.random()*1e9),f=Date.now()%1e9;return Number(String(f).padStart(9,"0")+String(r).padStart(9,"0"))}function getAnonymousBrowserUser(r="tg_tracking_uid"){let f=readCookie(r);if(!f){const v=generateNumericId();f=String(v),writeCookie(r,f)}const d=Number(f.replace(/\D/g,"").slice(0,15))||generateNumericId(),m=typeof navigator<"u"&&(navigator.language||navigator.userLanguage)||"en";return{user:{id:d,firstName:"Guest",lastName:"",username:`guest_${f.slice(-6)}`,languageCode:m.toLowerCase(),isPremium:!1,allowsWriteToPm:!1},authDate:new Date().toISOString(),hash:"anonymous_cookie_user",startParam:"browser_guest",chatType:"sender",chatInstance:""}}function getDefaultMockUser(){return{user:{id:2077220643,firstName:"Mock",lastName:"User",username:"mock_user_demo",languageCode:"zh-hans",isPremium:!0,allowsWriteToPm:!0},authDate:new Date().toISOString(),hash:"mock_hash_for_demo_purpose",startParam:"demo_start_param",chatType:"sender",chatInstance:"-245769840322609948"}}var naclUtil$1={exports:{}},naclUtil=naclUtil$1.exports,hasRequiredNaclUtil;function requireNaclUtil(){return hasRequiredNaclUtil||(hasRequiredNaclUtil=1,(function(r){(function(f,d){r.exports?r.exports=d():(f.nacl||(f.nacl={}),f.nacl.util=d())})(naclUtil,function(){var f={};function d(m){if(!/^(?:[A-Za-z0-9+\/]{2}[A-Za-z0-9+\/]{2})*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)?$/.test(m))throw new TypeError("invalid encoding")}return f.decodeUTF8=function(m){if(typeof m!="string")throw new TypeError("expected string");var v,g=unescape(encodeURIComponent(m)),w=new Uint8Array(g.length);for(v=0;v<g.length;v++)w[v]=g.charCodeAt(v);return w},f.encodeUTF8=function(m){var v,g=[];for(v=0;v<m.length;v++)g.push(String.fromCharCode(m[v]));return decodeURIComponent(escape(g.join("")))},typeof atob>"u"?typeof Buffer.from<"u"?(f.encodeBase64=function(m){return Buffer.from(m).toString("base64")},f.decodeBase64=function(m){return d(m),new Uint8Array(Array.prototype.slice.call(Buffer.from(m,"base64"),0))}):(f.encodeBase64=function(m){return new Buffer(m).toString("base64")},f.decodeBase64=function(m){return d(m),new Uint8Array(Array.prototype.slice.call(new Buffer(m,"base64"),0))}):(f.encodeBase64=function(m){var v,g=[],w=m.length;for(v=0;v<w;v++)g.push(String.fromCharCode(m[v]));return btoa(g.join(""))},f.decodeBase64=function(m){d(m);var v,g=atob(m),w=new Uint8Array(g.length);for(v=0;v<g.length;v++)w[v]=g.charCodeAt(v);return w}),f})})(naclUtil$1)),naclUtil$1.exports}var naclUtilExports=requireNaclUtil();const nacl=getDefaultExportFromCjs(naclUtilExports);function commonjsRequire(r){throw new Error('Could not dynamically require "'+r+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var naclFast={exports:{}},cryptoBrowserify={},browser$b={exports:{}},safeBuffer$1={exports:{}},dist={},hasRequiredDist;function requireDist(){return hasRequiredDist||(hasRequiredDist=1,(function(r){Object.defineProperties(r,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var f={},d={};d.byteLength=b,d.toByteArray=E,d.fromByteArray=T;for(var m=[],v=[],g=typeof Uint8Array<"u"?Uint8Array:Array,w="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",_=0,S=w.length;_<S;++_)m[_]=w[_],v[w.charCodeAt(_)]=_;v[45]=62,v[95]=63;function x(N){var H=N.length;if(H%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var V=N.indexOf("=");V===-1&&(V=H);var X=V===H?0:4-V%4;return[V,X]}function b(N){var H=x(N),V=H[0],X=H[1];return(V+X)*3/4-X}function C(N,H,V){return(H+V)*3/4-V}function E(N){var H,V=x(N),X=V[0],oe=V[1],se=new g(C(N,X,oe)),de=0,he=oe>0?X-4:X,we;for(we=0;we<he;we+=4)H=v[N.charCodeAt(we)]<<18|v[N.charCodeAt(we+1)]<<12|v[N.charCodeAt(we+2)]<<6|v[N.charCodeAt(we+3)],se[de++]=H>>16&255,se[de++]=H>>8&255,se[de++]=H&255;return oe===2&&(H=v[N.charCodeAt(we)]<<2|v[N.charCodeAt(we+1)]>>4,se[de++]=H&255),oe===1&&(H=v[N.charCodeAt(we)]<<10|v[N.charCodeAt(we+1)]<<4|v[N.charCodeAt(we+2)]>>2,se[de++]=H>>8&255,se[de++]=H&255),se}function M(N){return m[N>>18&63]+m[N>>12&63]+m[N>>6&63]+m[N&63]}function A(N,H,V){for(var X,oe=[],se=H;se<V;se+=3)X=(N[se]<<16&16711680)+(N[se+1]<<8&65280)+(N[se+2]&255),oe.push(M(X));return oe.join("")}function T(N){for(var H,V=N.length,X=V%3,oe=[],se=16383,de=0,he=V-X;de<he;de+=se)oe.push(A(N,de,de+se>he?he:de+se));return X===1?(H=N[V-1],oe.push(m[H>>2]+m[H<<4&63]+"==")):X===2&&(H=(N[V-2]<<8)+N[V-1],oe.push(m[H>>10]+m[H>>4&63]+m[H<<2&63]+"=")),oe.join("")}var L={};/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */L.read=function(N,H,V,X,oe){var se,de,he=oe*8-X-1,we=(1<<he)-1,te=we>>1,k=-7,q=V?oe-1:0,y=V?-1:1,B=N[H+q];for(q+=y,se=B&(1<<-k)-1,B>>=-k,k+=he;k>0;se=se*256+N[H+q],q+=y,k-=8);for(de=se&(1<<-k)-1,se>>=-k,k+=X;k>0;de=de*256+N[H+q],q+=y,k-=8);if(se===0)se=1-te;else{if(se===we)return de?NaN:(B?-1:1)*(1/0);de=de+Math.pow(2,X),se=se-te}return(B?-1:1)*de*Math.pow(2,se-X)},L.write=function(N,H,V,X,oe,se){var de,he,we,te=se*8-oe-1,k=(1<<te)-1,q=k>>1,y=oe===23?Math.pow(2,-24)-Math.pow(2,-77):0,B=X?0:se-1,$=X?1:-1,I=H<0||H===0&&1/H<0?1:0;for(H=Math.abs(H),isNaN(H)||H===1/0?(he=isNaN(H)?1:0,de=k):(de=Math.floor(Math.log(H)/Math.LN2),H*(we=Math.pow(2,-de))<1&&(de--,we*=2),de+q>=1?H+=y/we:H+=y*Math.pow(2,1-q),H*we>=2&&(de++,we/=2),de+q>=k?(he=0,de=k):de+q>=1?(he=(H*we-1)*Math.pow(2,oe),de=de+q):(he=H*Math.pow(2,q-1)*Math.pow(2,oe),de=0));oe>=8;N[V+B]=he&255,B+=$,he/=256,oe-=8);for(de=de<<oe|he,te+=oe;te>0;N[V+B]=de&255,B+=$,de/=256,te-=8);N[V+B-$]|=I*128};/*!
12
12
  * The buffer module from node.js, for the browser.
13
13
  *
14
14
  * @author Feross Aboukhadijeh <https://feross.org>
@@ -1242,4 +1242,4 @@ https://github.com/browserify/crypto-browserify`)},cryptoBrowserify.constants={D
1242
1242
  width: 16px;
1243
1243
  `,ButtonStyled=styled(Button)`
1244
1244
  margin-top: 32px;
1245
- `,ActionModal=r=>{const f=useDataAttributes(r),d=useContext(TonConnectUiContext),[m,v]=createSignal(!0),[g,w]=createSignal(!1),[_,S]=createSignal(!1),[x,b]=createSignal(!1);createEffect(()=>{const A=action();w(!!A&&("sent"in A&&A.sent||A.name==="transaction-sent")),S(!!A&&("signed"in A&&A.signed||A.name==="data-signed")),b(!!A&&(A.name==="transaction-canceled"||A.name==="sign-data-canceled"))});let C;d!=null&&d.wallet&&"universalLink"in d.wallet&&(d.wallet.openMethod==="universal-link"||isTelegramUrl(d.wallet.universalLink)&&isInTMA())&&(C=d.wallet.universalLink);let E;d!=null&&d.wallet&&"deepLink"in d.wallet&&(d.wallet.openMethod==="custom-deeplink"||isTelegramUrl(d.wallet.deepLink)&&isInTMA())&&(E=d.wallet.deepLink);const M=()=>{const A=action(),T="returnStrategy"in A?A.returnStrategy:appState.returnStrategy,L=!m();v(!1),isTelegramUrl(C)?redirectToTelegram(C,{returnStrategy:T,twaReturnUrl:"twaReturnUrl"in A?A.twaReturnUrl:appState.twaReturnUrl,forceRedirect:L}):redirectToWallet(C,E,{returnStrategy:T,forceRedirect:L},()=>{})};return createComponent(ActionModalStyled,mergeProps(f,{get children(){return[createMemo(()=>r.icon),createComponent(H1Styled,{get translationKey(){return r.headerTranslationKey},get translationValues(){return r.headerTranslationValues}}),createComponent(TextStyled,{get translationKey(){return r.textTranslationKey},get translationValues(){return r.textTranslationValues}}),createComponent(Show,{get when(){return!g()&&!_()&&!x()&&(r.showButton==="open-wallet"&&C||r.showButton!=="open-wallet")},get children(){return createComponent(LoaderButtonStyled,{disabled:!0,"data-tc-connect-button-loading":"true",get children(){return createComponent(LoaderIconStyled,{})}})}}),createComponent(Show,{get when(){return g()||_()},get children(){return[createComponent(Show,{get when(){return r.showButton!=="open-wallet"},get children(){return createComponent(ButtonStyled,{onClick:()=>r.onClose(),get children(){return createComponent(Translation,{translationKey:"common.close",children:"Close"})}})}}),createComponent(Show,{get when(){return r.showButton==="open-wallet"&&C},get children(){return createComponent(ButtonStyled,{onClick:M,get children(){return createComponent(Translation,{translationKey:"common.openWallet",children:"Open wallet"})}})}})]}})]}}))},ConfirmTransactionModal=r=>{const f=useContext(TonConnectUiContext),[d]=useI18n(),m=()=>f.wallet&&"name"in f.wallet?f.wallet.name:d("common.yourWallet",{},"Your wallet");return createComponent(ActionModal,{headerTranslationKey:"actionModal.confirmTransaction.header",get headerTranslationValues(){return{name:m()}},textTranslationKey:"actionModal.confirmTransaction.text",get icon(){return createComponent(LoaderIcon,{size:"m"})},onClose:()=>r.onClose(),showButton:"open-wallet","data-tc-confirm-modal":"true"})},TransactionCanceledModal=r=>createComponent(ActionModal,{headerTranslationKey:"actionModal.transactionCanceled.header",textTranslationKey:"actionModal.transactionCanceled.text",get icon(){return createComponent(ErrorIcon,{size:"m"})},onClose:()=>r.onClose(),"data-tc-transaction-canceled-modal":"true"}),TransactionSentModal=r=>createComponent(ActionModal,{headerTranslationKey:"actionModal.transactionSent.header",textTranslationKey:"actionModal.transactionSent.text",get icon(){return createComponent(SuccessIcon,{size:"m"})},showButton:"open-wallet",onClose:()=>r.onClose(),"data-tc-transaction-sent-modal":"true"}),ConfirmSignDataModal=r=>{const f=useContext(TonConnectUiContext),[d]=useI18n(),m=()=>f.wallet&&"name"in f.wallet?f.wallet.name:d("common.yourWallet",{},"Your wallet");return createComponent(ActionModal,{headerTranslationKey:"actionModal.signData.header",get headerTranslationValues(){return{name:m()}},textTranslationKey:"actionModal.signData.text",get icon(){return createComponent(LoaderIcon,{size:"m"})},onClose:()=>r.onClose(),showButton:"open-wallet","data-tc-sign-data-confirm-modal":"true"})},SignDataCanceledModal=r=>createComponent(ActionModal,{headerTranslationKey:"actionModal.signDataCanceled.header",get icon(){return createComponent(ErrorIcon,{size:"m"})},onClose:()=>r.onClose(),"data-tc-sign-data-canceled-modal":"true"}),DataSignedModal=r=>createComponent(ActionModal,{headerTranslationKey:"actionModal.dataSigned.header",get icon(){return createComponent(SuccessIcon,{size:"m"})},onClose:()=>r.onClose(),"data-tc-data-signed-modal":"true"}),ActionsModal=()=>createComponent(Modal,{get opened(){var r;return createMemo(()=>action()!==null)()&&((r=action())==null?void 0:r.openModal)===!0},get enableAndroidBackHandler(){return appState.enableAndroidBackHandler},onClose:()=>setAction(null),showFooter:!1,"data-tc-actions-modal-container":"true",get children(){return createComponent(Switch,{get children(){return[createComponent(Match,{get when(){return action().name==="transaction-sent"},get children(){return createComponent(TransactionSentModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="transaction-canceled"},get children(){return createComponent(TransactionCanceledModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="confirm-transaction"},get children(){return createComponent(ConfirmTransactionModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="data-signed"},get children(){return createComponent(DataSignedModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="sign-data-canceled"},get children(){return createComponent(SignDataCanceledModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="confirm-sign-data"},get children(){return createComponent(ConfirmSignDataModal,{onClose:()=>setAction(null)})}})]}})}}),SingleWalletModal=()=>{const{locale:r}=useI18n()[1];createEffect(()=>r(appState.language)),createEffect(()=>{getSingleWalletModalIsOpened()&&updateIsMobile()});const f=useContext(ConnectorContext),d=useContext(TonConnectUiContext),[m,v]=createSignal(!1),g=()=>{var x;return((x=appState.connectRequestParameters)==null?void 0:x.state)==="loading"},w=createMemo(()=>{var x;if(!g())return(x=appState.connectRequestParameters)==null?void 0:x.value}),_=x=>{d.closeSingleWalletModal(x)},S=f.onStatusChange(x=>{x&&_("wallet-selected")});return onCleanup(S),onCleanup(()=>{v(!1)}),createComponent(StyledModal,{get opened(){return getSingleWalletModalIsOpened()},get enableAndroidBackHandler(){return appState.enableAndroidBackHandler},onClose:()=>_("action-cancelled"),onClickQuestion:()=>v(x=>!x),showFooter:!0,"data-tc-wallets-modal-container":"true",get children(){return[createComponent(Show,{get when(){return m()},get children(){return createComponent(InfoModal,{onBackClick:()=>v(!1)})}}),createComponent(Show,{get when(){return!m()},get children(){return[createComponent(Show,{get when(){return g()},get children(){return[createComponent(H1Styled$a,{translationKey:"walletModal.loading",children:"Wallets list is loading"}),createComponent(LoaderContainerStyled,{get children(){return createComponent(LoaderIcon,{size:"m"})}})]}}),createComponent(Show,{get when(){return!g()},get children(){return createComponent(Dynamic,{get component(){return isMobile()?MobileConnectionModal:DesktopConnectionModal},get wallet(){return getSingleWalletModalWalletInfo()},get additionalRequest(){return w()},onBackClick:()=>{},backDisabled:!0})}})]}})]}})},App=r=>{const f=createI18nContext(i18nDictionary,appState.language);return defineStylesRoot(),fixMobileSafariActiveTransition(),createComponent(I18nContext.Provider,{value:f,get children(){return createComponent(TonConnectUiContext.Provider,{get value(){return r.tonConnectUI},get children(){return createComponent(ConnectorContext.Provider,{get value(){return appState.connector},get children(){return[createComponent(GlobalStyles,{}),createComponent(ThemeProvider,{theme:themeState,get children(){return[createComponent(Show,{get when(){return appState.buttonRootId},get children(){return createComponent(Portal,{get mount(){return document.getElementById(appState.buttonRootId)},get children(){return createComponent(AccountButton,{})}})}}),createComponent(Dynamic,{component:globalStylesTag,get children(){return[createComponent(WalletsModal,{}),createComponent(SingleWalletModal,{}),createComponent(ActionsModal,{})]}})]}})]}})}})}})},widgetController={openWalletsModal:()=>void setTimeout(()=>setWalletsModalState({status:"opened",closeReason:null})),closeWalletsModal:r=>void setTimeout(()=>setWalletsModalState({status:"closed",closeReason:r})),openSingleWalletModal:r=>{setTimeout(()=>setSingleWalletModalState({status:"opened",closeReason:null,walletInfo:r}))},closeSingleWalletModal:r=>void setTimeout(()=>setSingleWalletModalState({status:"closed",closeReason:r})),openWalletNotSupportFeatureModal:r=>void setTimeout(()=>setWalletsModalState({status:"opened",closeReason:null,type:"wallet-not-support-feature",requiredFeature:r.requiredFeature})),setAction:r=>void setTimeout(()=>setAction(r)),clearAction:()=>void setTimeout(()=>setAction(null)),getSelectedWalletInfo:()=>lastSelectedWalletInfo(),removeSelectedWalletInfo:()=>setLastSelectedWalletInfo(null),renderApp:(r,f)=>render(()=>createComponent(App,{tonConnectUI:f}),document.getElementById(r))};class WalletsModalManager{constructor(f){__publicField(this,"connector"),__publicField(this,"setConnectRequestParametersCallback"),__publicField(this,"consumers",[]),__publicField(this,"tracker"),__publicField(this,"state",walletsModalState()),this.connector=f.connector,this.tracker=f.tracker,this.setConnectRequestParametersCallback=f.setConnectRequestParametersCallback,createEffect(()=>{const d=walletsModalState();this.state=d,this.consumers.forEach(m=>m(d))})}open(){return __async(this,null,function*(){this.tracker.trackConnectionStarted();const d=(yield this.connector.getWallets()).find(isWalletInfoCurrentlyEmbedded);return d?this.connectEmbeddedWallet(d):this.openWalletsModal()})}close(f="action-cancelled"){f==="action-cancelled"&&this.tracker.trackConnectionError("Connection was cancelled"),widgetController.closeWalletsModal(f)}onStateChange(f){return this.consumers.push(f),()=>{this.consumers=this.consumers.filter(d=>d!==f)}}connectEmbeddedWallet(f){const d=v=>{setLastSelectedWalletInfo(f),this.connector.connect({jsBridgeKey:f.jsBridgeKey},v)},m=appState.connectRequestParameters;(m==null?void 0:m.state)==="loading"?this.setConnectRequestParametersCallback(d):d(m==null?void 0:m.value)}openWalletsModal(){return __async(this,null,function*(){return isInTMA()&&sendExpand(),widgetController.openWalletsModal(),new Promise(f=>{const d=this.onStateChange(m=>{const{status:v}=m;v==="opened"&&(d(),f())})})})}}class TransactionModalManager{constructor(f){__publicField(this,"connector"),__publicField(this,"consumers",[]),this.connector=f.connector,createEffect(()=>{const d=action();this.consumers.forEach(m=>m(d))})}onStateChange(f){return this.consumers.push(f),()=>{this.consumers=this.consumers.filter(d=>d!==f)}}}class SingleWalletModalManager{constructor(f){__publicField(this,"connector"),__publicField(this,"setConnectRequestParametersCallback"),__publicField(this,"consumers",[]),__publicField(this,"tracker"),__publicField(this,"state",singleWalletModalState()),this.connector=f.connector,this.tracker=f.tracker,this.setConnectRequestParametersCallback=f.setConnectRequestParametersCallback,createEffect(()=>{const d=singleWalletModalState();this.state=d,this.consumers.forEach(m=>m(d))})}open(f){return __async(this,null,function*(){this.tracker.trackConnectionStarted();const d=yield this.connector.getWallets(),m=applyWalletsListConfiguration(d,appState.walletsListConfiguration),v=m.find(isWalletInfoCurrentlyEmbedded);if(!!v)return this.connectEmbeddedWallet(v);const _=m.filter(isWalletInfoRemote).find(b=>eqWalletName(b,f));if(!!_)return this.openSingleWalletModal(_);const x=`Trying to open modal window with unknown wallet "${f}".`;throw this.tracker.trackConnectionError(x),new TonConnectUIError(x)})}close(f="action-cancelled"){f==="action-cancelled"&&this.tracker.trackConnectionError("Connection was cancelled"),widgetController.closeSingleWalletModal("action-cancelled")}onStateChange(f){return this.consumers.push(f),()=>{this.consumers=this.consumers.filter(d=>d!==f)}}connectEmbeddedWallet(f){const d=v=>{setLastSelectedWalletInfo(f),this.connector.connect({jsBridgeKey:f.jsBridgeKey},v)},m=appState.connectRequestParameters;(m==null?void 0:m.state)==="loading"?this.setConnectRequestParametersCallback(d):d(m==null?void 0:m.value)}openSingleWalletModal(f){return __async(this,null,function*(){return isInTMA()&&sendExpand(),widgetController.openSingleWalletModal(f),new Promise(d=>{const m=this.onStateChange(v=>{const{status:g}=v;g==="opened"&&(m(),d())})})})}}class TonConnectUITracker{constructor(f){__publicField(this,"eventPrefix","ton-connect-ui-"),__publicField(this,"tonConnectUiVersion"),__publicField(this,"tonConnectSdkVersion",null),__publicField(this,"eventDispatcher");var d;this.eventDispatcher=(d=f==null?void 0:f.eventDispatcher)!=null?d:new BrowserEventDispatcher,this.tonConnectUiVersion=f.tonConnectUiVersion,this.init().catch()}get version(){return createVersionInfo({ton_connect_sdk_lib:this.tonConnectSdkVersion,ton_connect_ui_lib:this.tonConnectUiVersion})}init(){return __async(this,null,function*(){try{yield this.setRequestVersionHandler(),this.tonConnectSdkVersion=yield this.requestTonConnectSdkVersion()}catch{}})}setRequestVersionHandler(){return __async(this,null,function*(){yield this.eventDispatcher.addEventListener("ton-connect-ui-request-version",()=>__async(this,null,function*(){yield this.eventDispatcher.dispatchEvent("ton-connect-ui-response-version",createResponseVersionEvent(this.tonConnectUiVersion))}))})}requestTonConnectSdkVersion(){return __async(this,null,function*(){return new Promise((f,d)=>__async(this,null,function*(){try{yield this.eventDispatcher.addEventListener("ton-connect-response-version",m=>{f(m.detail.version)},{once:!0}),yield this.eventDispatcher.dispatchEvent("ton-connect-request-version",createRequestVersionEvent())}catch(m){d(m)}}))})}dispatchUserActionEvent(f){var d;try{(d=this.eventDispatcher)==null||d.dispatchEvent(`${this.eventPrefix}${f.type}`,f).catch()}catch{}}trackConnectionStarted(...f){try{const d=createConnectionStartedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackConnectionCompleted(...f){try{const d=createConnectionCompletedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackConnectionError(...f){try{const d=createConnectionErrorEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringStarted(...f){try{const d=createConnectionRestoringStartedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringCompleted(...f){try{const d=createConnectionRestoringCompletedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringError(...f){try{const d=createConnectionRestoringErrorEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackDisconnection(...f){try{const d=createDisconnectionEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSentForSignature(...f){try{const d=createTransactionSentForSignatureEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSigned(...f){try{const d=createTransactionSignedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSigningFailed(...f){try{const d=createTransactionSigningFailedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackDataSentForSignature(...f){try{const d=createDataSentForSignatureEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackDataSigned(...f){try{const d=createDataSignedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackDataSigningFailed(...f){try{const d=createDataSigningFailedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}}const tonConnectUiVersion="2.2.0";class TonConnectUI{constructor(f){if(__publicField(this,"walletInfoStorage",new WalletInfoStorage),__publicField(this,"preferredWalletStorage",new PreferredWalletStorage),__publicField(this,"tracker"),__publicField(this,"walletInfo",null),__publicField(this,"systemThemeChangeUnsubscribe",null),__publicField(this,"actionsConfiguration"),__publicField(this,"walletsList"),__publicField(this,"_walletsRequiredFeatures"),__publicField(this,"_walletsPreferredFeatures"),__publicField(this,"connectRequestParametersCallback"),__publicField(this,"connector"),__publicField(this,"modal"),__publicField(this,"singleWalletModal"),__publicField(this,"transactionModal"),__publicField(this,"connectionRestored",Promise.resolve(!1)),f&&"connector"in f&&f.connector)this.connector=f.connector;else if(f&&"manifestUrl"in f&&f.manifestUrl)this.connector=new TonConnect({manifestUrl:f.manifestUrl,eventDispatcher:f.eventDispatcher,walletsRequiredFeatures:f.walletsRequiredFeatures});else throw new TonConnectUIError("You have to specify a `manifestUrl` or a `connector` in the options.");this.tracker=new TonConnectUITracker({eventDispatcher:f==null?void 0:f.eventDispatcher,tonConnectUiVersion}),this.modal=new WalletsModalManager({connector:this.connector,tracker:this.tracker,setConnectRequestParametersCallback:v=>{this.connectRequestParametersCallback=v}}),this.singleWalletModal=new SingleWalletModalManager({connector:this.connector,tracker:this.tracker,setConnectRequestParametersCallback:v=>{this.connectRequestParametersCallback=v}}),this.transactionModal=new TransactionModalManager({connector:this.connector}),this._walletsRequiredFeatures=f.walletsRequiredFeatures,this._walletsPreferredFeatures=f.walletsPreferredFeatures,this.walletsList=this.getWallets(),this.walletsList.then(v=>preloadImages(uniq(v.map(g=>g.imageUrl))));const d=this.normalizeWidgetRoot(f==null?void 0:f.widgetRootId);this.subscribeToWalletChange(),(f==null?void 0:f.restoreConnection)!==!1&&(this.connectionRestored=createMacrotaskAsync(()=>__async(this,null,function*(){return this.tracker.trackConnectionRestoringStarted(),yield this.connector.restoreConnection(),this.connector.connected?this.tracker.trackConnectionRestoringCompleted(this.wallet):(this.tracker.trackConnectionRestoringError("Connection was not restored"),this.walletInfoStorage.removeWalletInfo()),this.connector.connected}))),this.uiOptions=mergeOptions(f,{uiPreferences:{theme:"SYSTEM"}});const m=this.preferredWalletStorage.getPreferredWalletAppName();setAppState({connector:this.connector,preferredWalletAppName:m}),widgetController.renderApp(d,this)}static getWallets(){return TonConnect.getWallets()}get walletsRequiredFeatures(){return this._walletsRequiredFeatures}get walletsPreferredFeatures(){return this._walletsPreferredFeatures}get connected(){return this.connector.connected}get account(){return this.connector.account}get wallet(){return this.connector.wallet?__spreadValues(__spreadValues({},this.connector.wallet),this.walletInfo):null}set uiOptions(f){var d,m,v,g,w;this.checkButtonRootExist(f.buttonRootId),this.actionsConfiguration=f.actionsConfiguration,"walletsRequiredFeatures"in f&&(this._walletsRequiredFeatures=f.walletsRequiredFeatures),"walletsPreferredFeatures"in f&&(this._walletsPreferredFeatures=f.walletsPreferredFeatures),(d=f.uiPreferences)!=null&&d.theme?((m=f.uiPreferences)==null?void 0:m.theme)!=="SYSTEM"?((v=this.systemThemeChangeUnsubscribe)==null||v.call(this),setTheme(f.uiPreferences.theme,f.uiPreferences.colorsSet)):(setTheme(getSystemTheme(),f.uiPreferences.colorsSet),this.systemThemeChangeUnsubscribe||(this.systemThemeChangeUnsubscribe=subscribeToThemeChange(setTheme))):(g=f.uiPreferences)!=null&&g.colorsSet&&setColors(f.uiPreferences.colorsSet),(w=f.uiPreferences)!=null&&w.borderRadius&&setBorderRadius(f.uiPreferences.borderRadius),setAppState(_=>{var S,x;const b=mergeOptions(__spreadValues(__spreadValues(__spreadValues(__spreadValues({},f.language&&{language:f.language}),!!((S=f.actionsConfiguration)!=null&&S.returnStrategy)&&{returnStrategy:f.actionsConfiguration.returnStrategy}),!!((x=f.actionsConfiguration)!=null&&x.twaReturnUrl)&&{twaReturnUrl:f.actionsConfiguration.twaReturnUrl}),!!f.walletsListConfiguration&&{walletsListConfiguration:f.walletsListConfiguration}),unwrap(_));return f.buttonRootId!==void 0&&(b.buttonRootId=f.buttonRootId),f.enableAndroidBackHandler!==void 0&&(b.enableAndroidBackHandler=f.enableAndroidBackHandler),b})}setConnectRequestParameters(f){var d;setAppState({connectRequestParameters:f}),((f==null?void 0:f.state)==="ready"||!f)&&((d=this.connectRequestParametersCallback)==null||d.call(this,f==null?void 0:f.value))}getWallets(){return __async(this,null,function*(){return this.connector.getWallets()})}onStatusChange(f,d){return this.connector.onStatusChange(m=>__async(this,null,function*(){if(m){const v=yield this.getSelectedWalletInfo(m);f(__spreadValues(__spreadValues({},m),v||this.walletInfoStorage.getWalletInfo()))}else f(m)}),d)}openModal(){return __async(this,null,function*(){return this.modal.open()})}closeModal(f){this.modal.close(f)}onModalStateChange(f){return this.modal.onStateChange(f)}get modalState(){return this.modal.state}openSingleWalletModal(f){return __async(this,null,function*(){return this.singleWalletModal.open(f)})}closeSingleWalletModal(f){this.singleWalletModal.close(f)}onSingleWalletModalStateChange(f){return this.singleWalletModal.onStateChange(f)}get singleWalletModalState(){return this.singleWalletModal.state}connectWallet(){return __async(this,null,function*(){const d=(yield this.getWallets()).find(isWalletInfoCurrentlyEmbedded);return d?yield this.connectEmbeddedWallet(d):yield this.connectExternalWallet()})}disconnect(){return this.tracker.trackDisconnection(this.wallet,"dapp"),widgetController.clearAction(),widgetController.removeSelectedWalletInfo(),this.walletInfoStorage.removeWalletInfo(),this.connector.disconnect()}sendTransaction(f,d){return __async(this,null,function*(){if(this.tracker.trackTransactionSentForSignature(this.wallet,f),!this.connected)throw this.tracker.trackTransactionSigningFailed(this.wallet,f,"Wallet was not connected"),new TonConnectUIError("Connect wallet to send a transaction.");isInTMA()&&sendExpand();const{notifications:m,modals:v,returnStrategy:g,twaReturnUrl:w}=this.getModalsAndNotificationsConfiguration(d);widgetController.setAction({name:"confirm-transaction",showNotification:m.includes("before"),openModal:v.includes("before"),sent:!1});const _=new AbortController,S=()=>{_.signal.aborted||(widgetController.setAction({name:"confirm-transaction",showNotification:m.includes("before"),openModal:v.includes("before"),sent:!0}),this.redirectAfterRequestSent({returnStrategy:g,twaReturnUrl:w}))},x=this.onTransactionModalStateChange(b=>{b!=null&&b.openModal||(x(),b||_.abort())});try{const b=yield this.waitForSendTransaction({transaction:f,signal:_.signal},S);return this.tracker.trackTransactionSigned(this.wallet,f,b),widgetController.setAction({name:"transaction-sent",showNotification:m.includes("success"),openModal:v.includes("success")}),b}catch(b){throw b instanceof WalletNotSupportFeatureError?(widgetController.clearAction(),widgetController.openWalletNotSupportFeatureModal(b.cause),b):(widgetController.setAction({name:"transaction-canceled",showNotification:m.includes("error"),openModal:v.includes("error")}),b instanceof TonConnectError?b:new TonConnectUIError("Unhandled error:"+b))}finally{x()}})}signData(f){return __async(this,null,function*(){if(this.tracker.trackDataSentForSignature(this.wallet,f),!this.connected)throw this.tracker.trackDataSigningFailed(this.wallet,f,"Wallet was not connected"),new TonConnectUIError("Connect wallet to send a transaction.");isInTMA()&&sendExpand();const{notifications:d,modals:m,returnStrategy:v,twaReturnUrl:g}=this.getModalsAndNotificationsConfiguration();widgetController.setAction({name:"confirm-sign-data",showNotification:d.includes("before"),openModal:m.includes("before"),signed:!1});const w=new AbortController,_=()=>{w.signal.aborted||(widgetController.setAction({name:"confirm-sign-data",showNotification:d.includes("before"),openModal:m.includes("before"),signed:!0}),this.redirectAfterRequestSent({returnStrategy:v,twaReturnUrl:g}))},S=this.onTransactionModalStateChange(x=>{x!=null&&x.openModal||(S(),x||w.abort())});try{const x=yield this.waitForSignData({data:f,signal:new AbortController().signal},_);return this.tracker.trackDataSigned(this.wallet,f,x),widgetController.setAction({name:"data-signed",showNotification:d.includes("success"),openModal:m.includes("success")}),x}catch(x){throw x instanceof WalletNotSupportFeatureError?(widgetController.clearAction(),widgetController.openWalletNotSupportFeatureModal(x.cause),x):(widgetController.setAction({name:"sign-data-canceled",showNotification:d.includes("error"),openModal:m.includes("error")}),x instanceof TonConnectError?x:new TonConnectUIError("Unhandled error:"+x))}finally{S()}})}redirectAfterRequestSent({returnStrategy:f,twaReturnUrl:d}){this.walletInfo&&"universalLink"in this.walletInfo&&(this.walletInfo.openMethod==="universal-link"||this.walletInfo.openMethod==="custom-deeplink")&&(isTelegramUrl(this.walletInfo.universalLink)?redirectToTelegram(this.walletInfo.universalLink,{returnStrategy:f,twaReturnUrl:d||appState.twaReturnUrl,forceRedirect:!1}):redirectToWallet(this.walletInfo.universalLink,this.walletInfo.deepLink,{returnStrategy:f,forceRedirect:!1},()=>{}))}connectEmbeddedWallet(f){return __async(this,null,function*(){const d=v=>{setLastSelectedWalletInfo(f),this.connector.connect({jsBridgeKey:f.jsBridgeKey},v)},m=appState.connectRequestParameters;return(m==null?void 0:m.state)==="loading"?this.connectRequestParametersCallback=d:d(m==null?void 0:m.value),yield this.waitForWalletConnection({ignoreErrors:!1})})}connectExternalWallet(){return __async(this,null,function*(){const f=new AbortController;widgetController.openWalletsModal();const d=this.onModalStateChange(m=>{const{status:v,closeReason:g}=m;v!=="opened"&&(d(),g==="action-cancelled"&&f.abort())});return yield this.waitForWalletConnection({ignoreErrors:!0,signal:f.signal})})}waitForWalletConnection(f){return __async(this,null,function*(){return new Promise((d,m)=>{this.tracker.trackConnectionStarted();const{ignoreErrors:v=!1,signal:g=null}=f;if(g&&g.aborted)return this.tracker.trackConnectionError("Connection was cancelled"),m(new TonConnectUIError("Wallet was not connected"));const w=x=>__async(this,null,function*(){if(x)this.tracker.trackConnectionCompleted(x),S(),d(x);else{if(this.tracker.trackConnectionError("Connection was cancelled"),v)return;S(),m(new TonConnectUIError("Wallet was not connected"))}}),_=x=>{this.tracker.trackConnectionError(x.message),!v&&(S(),m(x))},S=this.onStatusChange(x=>w(x),x=>_(x));g&&g.addEventListener("abort",()=>{S(),m(new TonConnectUIError("Wallet was not connected"))},{once:!0})})})}waitForSendTransaction(f,d){return __async(this,null,function*(){return new Promise((m,v)=>{const{transaction:g,signal:w}=f;if(w.aborted)return this.tracker.trackTransactionSigningFailed(this.wallet,g,"Transaction was cancelled"),v(new TonConnectUIError("Transaction was not sent"));const _=b=>__async(this,null,function*(){m(b)}),S=b=>{v(b)},x=()=>{this.tracker.trackTransactionSigningFailed(this.wallet,g,"Transaction was cancelled"),v(new TonConnectUIError("Transaction was not sent"))};w.addEventListener("abort",x,{once:!0}),this.connector.sendTransaction(g,{onRequestSent:d,signal:w}).then(b=>(w.removeEventListener("abort",x),_(b))).catch(b=>(w.removeEventListener("abort",x),S(b)))})})}waitForSignData(f,d){return __async(this,null,function*(){return new Promise((m,v)=>{const{data:g,signal:w}=f;if(w.aborted)return this.tracker.trackDataSigningFailed(this.wallet,g,"SignData was cancelled"),v(new TonConnectUIError("SignData was not sent"));const _=b=>__async(this,null,function*(){m(b)}),S=b=>{v(b)},x=()=>{this.tracker.trackDataSigningFailed(this.wallet,g,"SignData was cancelled"),v(new TonConnectUIError("SignData was not sent"))};w.addEventListener("abort",x,{once:!0}),this.connector.signData(g,{onRequestSent:d,signal:w}).then(b=>_(b)).catch(b=>S(b))})})}onTransactionModalStateChange(f){return this.transactionModal.onStateChange(f)}subscribeToWalletChange(){this.connector.onStatusChange(f=>__async(this,null,function*(){var d;f?(yield this.updateWalletInfo(f),this.setPreferredWalletAppName(((d=this.walletInfo)==null?void 0:d.appName)||f.device.appName)):this.walletInfoStorage.removeWalletInfo()}))}setPreferredWalletAppName(f){this.preferredWalletStorage.setPreferredWalletAppName(f),setAppState({preferredWalletAppName:f})}getSelectedWalletInfo(f){return __async(this,null,function*(){let d=widgetController.getSelectedWalletInfo();if(!d)return null;let m;if("name"in d)m=d;else{const g=applyWalletsListConfiguration(yield this.walletsList,appState.walletsListConfiguration).find(w=>eqWalletName(w,f.device.appName));if(!g)throw new TonConnectUIError(`Cannot find WalletInfo for the '${f.device.appName}' wallet`);m=__spreadValues(__spreadValues({},g),d)}return m})}updateWalletInfo(f){return __async(this,null,function*(){const d=yield this.getSelectedWalletInfo(f);if(d){this.walletInfo=d,this.walletInfoStorage.setWalletInfo(d);return}const m=this.walletInfoStorage.getWalletInfo();if(m){this.walletInfo=m;return}this.walletInfo=(yield this.walletsList).find(v=>eqWalletName(v,f.device.appName))||null})}normalizeWidgetRoot(f){if(!f||!document.getElementById(f)){f="tc-widget-root";const d=document.createElement("div");d.id=f,document.body.appendChild(d)}return f}checkButtonRootExist(f){if(f!=null&&!document.getElementById(f))throw new TonConnectUIError(`${f} element not found in the document.`)}getModalsAndNotificationsConfiguration(f){var d,m,v,g,w,_;const S=["before","success","error"];let x=S;(d=this.actionsConfiguration)!=null&&d.notifications&&((m=this.actionsConfiguration)==null?void 0:m.notifications)!=="all"&&(x=this.actionsConfiguration.notifications),f!=null&&f.notifications&&(f.notifications==="all"?x=S:x=f.notifications);let b=["before"];(v=this.actionsConfiguration)!=null&&v.modals&&(this.actionsConfiguration.modals==="all"?b=S:b=this.actionsConfiguration.modals),f!=null&&f.modals&&(f.modals==="all"?b=S:b=f.modals);const C=(f==null?void 0:f.returnStrategy)||((g=this.actionsConfiguration)==null?void 0:g.returnStrategy)||"back",E=(f==null?void 0:f.twaReturnUrl)||((w=this.actionsConfiguration)==null?void 0:w.twaReturnUrl);let M=(f==null?void 0:f.skipRedirectToWallet)||((_=this.actionsConfiguration)==null?void 0:_.skipRedirectToWallet)||"ios";return isInTMA()&&(M="never"),{notifications:x,modals:b,returnStrategy:C,twaReturnUrl:E,skipRedirectToWallet:M}}}const DEFAULT_MANIFEST_URL="https://miniapp.spinfi.me/tonconnect-manifest.json";let tonConnectUIInstance=null;class DefaultTonWalletProvider{constructor(f){if(this.bindWalletCallback=f,!tonConnectUIInstance)try{tonConnectUIInstance=new TonConnectUI({manifestUrl:DEFAULT_MANIFEST_URL})}catch{throw new Error("创建TonConnectUI实例失败")}this.ui=tonConnectUIInstance}isConnected(){var f;try{return!!((f=this.ui)!=null&&f.connected)}catch{return!1}}async reportWalletAddress(){const f=this.getUserFriendlyAddress();if(f&&this.bindWalletCallback)try{await this.bindWalletCallback(f)}catch{}}async connect(){if(this.isConnected())return await this.reportWalletAddress(),!0;try{return await new Promise((f,d)=>{this.ui.openModal();const m=this.ui.onStatusChange(()=>{this.isConnected()&&(m(),f())});setTimeout(()=>{this.isConnected()||(m(),d(new Error("连接钱包超时")))},3e5)}),await this.reportWalletAddress(),this.isConnected()}catch{return!1}}getUserFriendlyAddress(){var m,v,g;const f=this.ui,d=((v=(m=f==null?void 0:f.wallet)==null?void 0:m.account)==null?void 0:v.address)||((g=f==null?void 0:f.account)==null?void 0:g.address)||null;return d?toUserFriendlyAddress(d):null}async sendTonTransaction(f){if(!this.isConnected()&&!await this.connect())throw new Error("钱包未连接");const d=await this.ui.sendTransaction(f),m=d==null?void 0:d.boc;let v;if(m)try{v=m.substring(0,16)}catch{}return{transferHash:v,boc:m,raw:d}}async sendUsdtTransaction(f){if(!this.isConnected()&&!await this.connect())throw new Error("钱包未连接");const d=await this.ui.sendTransaction(f),m=d==null?void 0:d.boc;let v;if(m)try{v=m.substring(0,16)}catch{}return{transferHash:v,boc:m,raw:d}}async disconnect(){try{const f=this.ui;if(f!=null&&f.disconnect)await f.disconnect();else if(f!=null&&f.onStatusChange){const d=f.onStatusChange(()=>{});d&&d()}return!this.isConnected()}catch{return!1}}}class HmTrackingSDK{constructor(f){this.options=f,this.token=null,this.user=null;const d=this.options||{};this.storage=new NamespacedStorage(d.storageKeyPrefix||"hm_tracking_sdk"),this.token=this.storage.get("token");const m=d.baseURL||TEST_BASE_URL;this.http=new HttpClient({getToken:()=>this.token,onAuthError:()=>this.clearAuth(),baseURL:m}),this.api=new APIService(this.http),this.hmAdManager=new HmAdManager({autoInjectScript:!0}),this.adMonitor=new AdMonitor(v=>this.api.adMonitor(v)),this.tonWallet=new DefaultTonWalletProvider(this.bindWallet.bind(this))}async init(){const f=isTelegramEnv();try{const d=this.options||{},m=f?getTelegramUserUnsafe():null;if(m?this.user=m:d.customUser?this.user=d.customUser:typeof window<"u"?this.user=getAnonymousBrowserUser():this.user=getDefaultMockUser(),!this.user)throw new Error("未获取到用户信息:请在非 Telegram 环境提供 customUser");this.clearAuth(),await this.auth();try{await this.hmAdManager.init()}catch{}}catch(d){throw d}}async auth(){var f;try{const d=await this.api.auth(this.user);if(d.code!==1)throw new Error(d.msg||"鉴权失败");const m=(f=d.data)==null?void 0:f.token;if(!m)throw new Error("鉴权未返回 token");this.token=m,this.storage.set("token",m)}catch(d){throw d}}clearAuth(){this.token=null,this.storage.remove("token")}ensureTelegramEnvOrThrow(){if(!isTelegramEnv())throw new Error("支付相关功能仅支持在 Telegram 环境内使用")}async getAdPositionConfig(f){const d=await this.api.getAdPositionConfig(String(f));if(d.code!==1)throw new Error(d.msg||"获取广告位配置失败");return d.data||[]}async createAd(f){const d=await this.api.createAd(f);if(d.code!==1)throw new Error(d.msg||"创建广告失败");const m=d.data;return m!=null&&m.spaceId&&await this.hmAdManager.setSpace(String(m.spaceId)),m}async showHmAdByPosition(f,d){const m=await this.getAdPositionConfig(f);if(!m||m.length===0)throw new Error("未找到广告位配置");const v=m[0],g=await this.createAd({adId:v.adId,adPositionId:v.adPositionId}),w={start:g.start,show:g.show,error:g.error,close:g.close,reward:g.reward};await this.showHmAdWithMonitor(w,g.adShowId,d)}async showHmAdWithMonitor(f,d,m){const v=d||"";await this.adMonitor.send(f.start,v),await this.adMonitor.send(f.show,v);try{await this.hmAdManager.show(),await this.adMonitor.send(f.close,v);const g=await this.adMonitor.send(f.reward,v);m!=null&&m.onSuccess&&await m.onSuccess(g)}catch(g){throw await this.adMonitor.send(f.error,v),m!=null&&m.onError&&await m.onError(g),g}}async showHmPopupAd(f,d,m){const v=d||"";await this.adMonitor.send(f.start,v),await this.adMonitor.send(f.show,v);try{await this.hmAdManager.showPopup(),await this.adMonitor.send(f.close,v);const g=await this.adMonitor.send(f.reward,v);m!=null&&m.onSuccess&&await m.onSuccess(g)}catch(g){throw await this.adMonitor.send(f.error,v),m!=null&&m.onError&&await m.onError(g),g}}async showHmInAppAd(f,d,m,v){const g=m||"";await this.adMonitor.send(f.start,g),await this.adMonitor.send(f.show,g);try{await this.hmAdManager.showInApp(d),await this.adMonitor.send(f.close,g);const w=await this.adMonitor.send(f.reward,g);v!=null&&v.onSuccess&&await v.onSuccess(w)}catch(w){throw await this.adMonitor.send(f.error,g),v!=null&&v.onError&&await v.onError(w),w}}async bindWallet(f){try{if((await this.api.bindWalletReq({wallet:f,forceBind:!0})).code!==1)return}catch(d){throw d}}async disconnectWallet(){try{return this.tonWallet?(await this.tonWallet.disconnect(),!this.tonWallet.isConnected()):!0}catch{return!1}}async connectWallet(){return this.tonWallet?await this.tonWallet.connect():!1}isWalletConnected(){var f;return!!((f=this.tonWallet)!=null&&f.isConnected())}async ensureWalletConnected(){return this.ensureTelegramEnvOrThrow(),this.tonWallet?await this.tonWallet.connect():!1}async getSupportedPayModes(){const f=await this.api.merchantPayModeList();if(f.code!==1)throw new Error(f.msg||"获取支付方式失败");const d=f.data;return Array.isArray(d)?{payModeList:d}:{payModeList:Array.isArray(d==null?void 0:d.payModeList)?d.payModeList:[]}}async merchantPayQueryResult(f){const d=await this.api.merchantPayQueryResult(f);if(d.code!==1)throw new Error(d.msg||"查询支付结果失败");return d.data}async finishPayment(f,d,m=""){const v={orderSn:f,status:d,transferHash:m},g=await this.api.merchantPayFinish(v);if(g.code!==1)throw new Error(g.msg||"支付完成回调失败");return g.data}async payByMerchant(f){var _,S,x;this.ensureTelegramEnvOrThrow();const d=(_=f.currencyName)==null?void 0:_.toUpperCase(),m=await this.api.merchantPayCreate(f);if(m.code!==1)throw new Error(m.msg||"创建支付订单失败");const v=m.data;if(d==="STARS"&&v.payUrl)try{return await new Promise((C,E)=>{WebApp.openInvoice(v.payUrl,M=>{M==="paid"?C():E(new Error(`星币支付未完成: ${M||"未知状态"}`))})}),await this.finishPayment(v.orderSn,"success")}catch{return await this.finishPayment(v.orderSn,"failed")}if(!this.tonWallet||!this.tonWallet.isConnected())throw new Error("请先连接钱包");if(!((x=(S=v.transferData)==null?void 0:S.messages)==null?void 0:x[0]))throw new Error("订单未返回链上消息");let w;try{if(d==="TON")w=await this.tonWallet.sendTonTransaction(v.transferData);else if(d==="USDT")w=await this.tonWallet.sendUsdtTransaction(v.transferData);else throw new Error("暂不支持的币种");const b=w==null?void 0:w.transferHash;return await this.finishPayment(v.orderSn,"success",b||"")}catch{return await this.finishPayment(v.orderSn,"failed")}}}var AdPositionName=(r=>(r.GameRewardedAdPosition="game_rewarded_ad_position",r.TaskRewardedAdPosition="task_rewarded_ad_position",r.TaskListAdPosition="task_list_ad_position",r))(AdPositionName||{});globalThis.Buffer=Buffer$1,globalThis.process=process$1,globalThis.global=globalThis,exports.AdPositionName=AdPositionName,exports.HmTrackingSDK=HmTrackingSDK,exports.getAnonymousBrowserUser=getAnonymousBrowserUser,exports.getDefaultMockUser=getDefaultMockUser,exports.getTelegramUserUnsafe=getTelegramUserUnsafe,exports.isTelegramEnv=isTelegramEnv,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})}));
1245
+ `,ActionModal=r=>{const f=useDataAttributes(r),d=useContext(TonConnectUiContext),[m,v]=createSignal(!0),[g,w]=createSignal(!1),[_,S]=createSignal(!1),[x,b]=createSignal(!1);createEffect(()=>{const A=action();w(!!A&&("sent"in A&&A.sent||A.name==="transaction-sent")),S(!!A&&("signed"in A&&A.signed||A.name==="data-signed")),b(!!A&&(A.name==="transaction-canceled"||A.name==="sign-data-canceled"))});let C;d!=null&&d.wallet&&"universalLink"in d.wallet&&(d.wallet.openMethod==="universal-link"||isTelegramUrl(d.wallet.universalLink)&&isInTMA())&&(C=d.wallet.universalLink);let E;d!=null&&d.wallet&&"deepLink"in d.wallet&&(d.wallet.openMethod==="custom-deeplink"||isTelegramUrl(d.wallet.deepLink)&&isInTMA())&&(E=d.wallet.deepLink);const M=()=>{const A=action(),T="returnStrategy"in A?A.returnStrategy:appState.returnStrategy,L=!m();v(!1),isTelegramUrl(C)?redirectToTelegram(C,{returnStrategy:T,twaReturnUrl:"twaReturnUrl"in A?A.twaReturnUrl:appState.twaReturnUrl,forceRedirect:L}):redirectToWallet(C,E,{returnStrategy:T,forceRedirect:L},()=>{})};return createComponent(ActionModalStyled,mergeProps(f,{get children(){return[createMemo(()=>r.icon),createComponent(H1Styled,{get translationKey(){return r.headerTranslationKey},get translationValues(){return r.headerTranslationValues}}),createComponent(TextStyled,{get translationKey(){return r.textTranslationKey},get translationValues(){return r.textTranslationValues}}),createComponent(Show,{get when(){return!g()&&!_()&&!x()&&(r.showButton==="open-wallet"&&C||r.showButton!=="open-wallet")},get children(){return createComponent(LoaderButtonStyled,{disabled:!0,"data-tc-connect-button-loading":"true",get children(){return createComponent(LoaderIconStyled,{})}})}}),createComponent(Show,{get when(){return g()||_()},get children(){return[createComponent(Show,{get when(){return r.showButton!=="open-wallet"},get children(){return createComponent(ButtonStyled,{onClick:()=>r.onClose(),get children(){return createComponent(Translation,{translationKey:"common.close",children:"Close"})}})}}),createComponent(Show,{get when(){return r.showButton==="open-wallet"&&C},get children(){return createComponent(ButtonStyled,{onClick:M,get children(){return createComponent(Translation,{translationKey:"common.openWallet",children:"Open wallet"})}})}})]}})]}}))},ConfirmTransactionModal=r=>{const f=useContext(TonConnectUiContext),[d]=useI18n(),m=()=>f.wallet&&"name"in f.wallet?f.wallet.name:d("common.yourWallet",{},"Your wallet");return createComponent(ActionModal,{headerTranslationKey:"actionModal.confirmTransaction.header",get headerTranslationValues(){return{name:m()}},textTranslationKey:"actionModal.confirmTransaction.text",get icon(){return createComponent(LoaderIcon,{size:"m"})},onClose:()=>r.onClose(),showButton:"open-wallet","data-tc-confirm-modal":"true"})},TransactionCanceledModal=r=>createComponent(ActionModal,{headerTranslationKey:"actionModal.transactionCanceled.header",textTranslationKey:"actionModal.transactionCanceled.text",get icon(){return createComponent(ErrorIcon,{size:"m"})},onClose:()=>r.onClose(),"data-tc-transaction-canceled-modal":"true"}),TransactionSentModal=r=>createComponent(ActionModal,{headerTranslationKey:"actionModal.transactionSent.header",textTranslationKey:"actionModal.transactionSent.text",get icon(){return createComponent(SuccessIcon,{size:"m"})},showButton:"open-wallet",onClose:()=>r.onClose(),"data-tc-transaction-sent-modal":"true"}),ConfirmSignDataModal=r=>{const f=useContext(TonConnectUiContext),[d]=useI18n(),m=()=>f.wallet&&"name"in f.wallet?f.wallet.name:d("common.yourWallet",{},"Your wallet");return createComponent(ActionModal,{headerTranslationKey:"actionModal.signData.header",get headerTranslationValues(){return{name:m()}},textTranslationKey:"actionModal.signData.text",get icon(){return createComponent(LoaderIcon,{size:"m"})},onClose:()=>r.onClose(),showButton:"open-wallet","data-tc-sign-data-confirm-modal":"true"})},SignDataCanceledModal=r=>createComponent(ActionModal,{headerTranslationKey:"actionModal.signDataCanceled.header",get icon(){return createComponent(ErrorIcon,{size:"m"})},onClose:()=>r.onClose(),"data-tc-sign-data-canceled-modal":"true"}),DataSignedModal=r=>createComponent(ActionModal,{headerTranslationKey:"actionModal.dataSigned.header",get icon(){return createComponent(SuccessIcon,{size:"m"})},onClose:()=>r.onClose(),"data-tc-data-signed-modal":"true"}),ActionsModal=()=>createComponent(Modal,{get opened(){var r;return createMemo(()=>action()!==null)()&&((r=action())==null?void 0:r.openModal)===!0},get enableAndroidBackHandler(){return appState.enableAndroidBackHandler},onClose:()=>setAction(null),showFooter:!1,"data-tc-actions-modal-container":"true",get children(){return createComponent(Switch,{get children(){return[createComponent(Match,{get when(){return action().name==="transaction-sent"},get children(){return createComponent(TransactionSentModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="transaction-canceled"},get children(){return createComponent(TransactionCanceledModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="confirm-transaction"},get children(){return createComponent(ConfirmTransactionModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="data-signed"},get children(){return createComponent(DataSignedModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="sign-data-canceled"},get children(){return createComponent(SignDataCanceledModal,{onClose:()=>setAction(null)})}}),createComponent(Match,{get when(){return action().name==="confirm-sign-data"},get children(){return createComponent(ConfirmSignDataModal,{onClose:()=>setAction(null)})}})]}})}}),SingleWalletModal=()=>{const{locale:r}=useI18n()[1];createEffect(()=>r(appState.language)),createEffect(()=>{getSingleWalletModalIsOpened()&&updateIsMobile()});const f=useContext(ConnectorContext),d=useContext(TonConnectUiContext),[m,v]=createSignal(!1),g=()=>{var x;return((x=appState.connectRequestParameters)==null?void 0:x.state)==="loading"},w=createMemo(()=>{var x;if(!g())return(x=appState.connectRequestParameters)==null?void 0:x.value}),_=x=>{d.closeSingleWalletModal(x)},S=f.onStatusChange(x=>{x&&_("wallet-selected")});return onCleanup(S),onCleanup(()=>{v(!1)}),createComponent(StyledModal,{get opened(){return getSingleWalletModalIsOpened()},get enableAndroidBackHandler(){return appState.enableAndroidBackHandler},onClose:()=>_("action-cancelled"),onClickQuestion:()=>v(x=>!x),showFooter:!0,"data-tc-wallets-modal-container":"true",get children(){return[createComponent(Show,{get when(){return m()},get children(){return createComponent(InfoModal,{onBackClick:()=>v(!1)})}}),createComponent(Show,{get when(){return!m()},get children(){return[createComponent(Show,{get when(){return g()},get children(){return[createComponent(H1Styled$a,{translationKey:"walletModal.loading",children:"Wallets list is loading"}),createComponent(LoaderContainerStyled,{get children(){return createComponent(LoaderIcon,{size:"m"})}})]}}),createComponent(Show,{get when(){return!g()},get children(){return createComponent(Dynamic,{get component(){return isMobile()?MobileConnectionModal:DesktopConnectionModal},get wallet(){return getSingleWalletModalWalletInfo()},get additionalRequest(){return w()},onBackClick:()=>{},backDisabled:!0})}})]}})]}})},App=r=>{const f=createI18nContext(i18nDictionary,appState.language);return defineStylesRoot(),fixMobileSafariActiveTransition(),createComponent(I18nContext.Provider,{value:f,get children(){return createComponent(TonConnectUiContext.Provider,{get value(){return r.tonConnectUI},get children(){return createComponent(ConnectorContext.Provider,{get value(){return appState.connector},get children(){return[createComponent(GlobalStyles,{}),createComponent(ThemeProvider,{theme:themeState,get children(){return[createComponent(Show,{get when(){return appState.buttonRootId},get children(){return createComponent(Portal,{get mount(){return document.getElementById(appState.buttonRootId)},get children(){return createComponent(AccountButton,{})}})}}),createComponent(Dynamic,{component:globalStylesTag,get children(){return[createComponent(WalletsModal,{}),createComponent(SingleWalletModal,{}),createComponent(ActionsModal,{})]}})]}})]}})}})}})},widgetController={openWalletsModal:()=>void setTimeout(()=>setWalletsModalState({status:"opened",closeReason:null})),closeWalletsModal:r=>void setTimeout(()=>setWalletsModalState({status:"closed",closeReason:r})),openSingleWalletModal:r=>{setTimeout(()=>setSingleWalletModalState({status:"opened",closeReason:null,walletInfo:r}))},closeSingleWalletModal:r=>void setTimeout(()=>setSingleWalletModalState({status:"closed",closeReason:r})),openWalletNotSupportFeatureModal:r=>void setTimeout(()=>setWalletsModalState({status:"opened",closeReason:null,type:"wallet-not-support-feature",requiredFeature:r.requiredFeature})),setAction:r=>void setTimeout(()=>setAction(r)),clearAction:()=>void setTimeout(()=>setAction(null)),getSelectedWalletInfo:()=>lastSelectedWalletInfo(),removeSelectedWalletInfo:()=>setLastSelectedWalletInfo(null),renderApp:(r,f)=>render(()=>createComponent(App,{tonConnectUI:f}),document.getElementById(r))};class WalletsModalManager{constructor(f){__publicField(this,"connector"),__publicField(this,"setConnectRequestParametersCallback"),__publicField(this,"consumers",[]),__publicField(this,"tracker"),__publicField(this,"state",walletsModalState()),this.connector=f.connector,this.tracker=f.tracker,this.setConnectRequestParametersCallback=f.setConnectRequestParametersCallback,createEffect(()=>{const d=walletsModalState();this.state=d,this.consumers.forEach(m=>m(d))})}open(){return __async(this,null,function*(){this.tracker.trackConnectionStarted();const d=(yield this.connector.getWallets()).find(isWalletInfoCurrentlyEmbedded);return d?this.connectEmbeddedWallet(d):this.openWalletsModal()})}close(f="action-cancelled"){f==="action-cancelled"&&this.tracker.trackConnectionError("Connection was cancelled"),widgetController.closeWalletsModal(f)}onStateChange(f){return this.consumers.push(f),()=>{this.consumers=this.consumers.filter(d=>d!==f)}}connectEmbeddedWallet(f){const d=v=>{setLastSelectedWalletInfo(f),this.connector.connect({jsBridgeKey:f.jsBridgeKey},v)},m=appState.connectRequestParameters;(m==null?void 0:m.state)==="loading"?this.setConnectRequestParametersCallback(d):d(m==null?void 0:m.value)}openWalletsModal(){return __async(this,null,function*(){return isInTMA()&&sendExpand(),widgetController.openWalletsModal(),new Promise(f=>{const d=this.onStateChange(m=>{const{status:v}=m;v==="opened"&&(d(),f())})})})}}class TransactionModalManager{constructor(f){__publicField(this,"connector"),__publicField(this,"consumers",[]),this.connector=f.connector,createEffect(()=>{const d=action();this.consumers.forEach(m=>m(d))})}onStateChange(f){return this.consumers.push(f),()=>{this.consumers=this.consumers.filter(d=>d!==f)}}}class SingleWalletModalManager{constructor(f){__publicField(this,"connector"),__publicField(this,"setConnectRequestParametersCallback"),__publicField(this,"consumers",[]),__publicField(this,"tracker"),__publicField(this,"state",singleWalletModalState()),this.connector=f.connector,this.tracker=f.tracker,this.setConnectRequestParametersCallback=f.setConnectRequestParametersCallback,createEffect(()=>{const d=singleWalletModalState();this.state=d,this.consumers.forEach(m=>m(d))})}open(f){return __async(this,null,function*(){this.tracker.trackConnectionStarted();const d=yield this.connector.getWallets(),m=applyWalletsListConfiguration(d,appState.walletsListConfiguration),v=m.find(isWalletInfoCurrentlyEmbedded);if(!!v)return this.connectEmbeddedWallet(v);const _=m.filter(isWalletInfoRemote).find(b=>eqWalletName(b,f));if(!!_)return this.openSingleWalletModal(_);const x=`Trying to open modal window with unknown wallet "${f}".`;throw this.tracker.trackConnectionError(x),new TonConnectUIError(x)})}close(f="action-cancelled"){f==="action-cancelled"&&this.tracker.trackConnectionError("Connection was cancelled"),widgetController.closeSingleWalletModal("action-cancelled")}onStateChange(f){return this.consumers.push(f),()=>{this.consumers=this.consumers.filter(d=>d!==f)}}connectEmbeddedWallet(f){const d=v=>{setLastSelectedWalletInfo(f),this.connector.connect({jsBridgeKey:f.jsBridgeKey},v)},m=appState.connectRequestParameters;(m==null?void 0:m.state)==="loading"?this.setConnectRequestParametersCallback(d):d(m==null?void 0:m.value)}openSingleWalletModal(f){return __async(this,null,function*(){return isInTMA()&&sendExpand(),widgetController.openSingleWalletModal(f),new Promise(d=>{const m=this.onStateChange(v=>{const{status:g}=v;g==="opened"&&(m(),d())})})})}}class TonConnectUITracker{constructor(f){__publicField(this,"eventPrefix","ton-connect-ui-"),__publicField(this,"tonConnectUiVersion"),__publicField(this,"tonConnectSdkVersion",null),__publicField(this,"eventDispatcher");var d;this.eventDispatcher=(d=f==null?void 0:f.eventDispatcher)!=null?d:new BrowserEventDispatcher,this.tonConnectUiVersion=f.tonConnectUiVersion,this.init().catch()}get version(){return createVersionInfo({ton_connect_sdk_lib:this.tonConnectSdkVersion,ton_connect_ui_lib:this.tonConnectUiVersion})}init(){return __async(this,null,function*(){try{yield this.setRequestVersionHandler(),this.tonConnectSdkVersion=yield this.requestTonConnectSdkVersion()}catch{}})}setRequestVersionHandler(){return __async(this,null,function*(){yield this.eventDispatcher.addEventListener("ton-connect-ui-request-version",()=>__async(this,null,function*(){yield this.eventDispatcher.dispatchEvent("ton-connect-ui-response-version",createResponseVersionEvent(this.tonConnectUiVersion))}))})}requestTonConnectSdkVersion(){return __async(this,null,function*(){return new Promise((f,d)=>__async(this,null,function*(){try{yield this.eventDispatcher.addEventListener("ton-connect-response-version",m=>{f(m.detail.version)},{once:!0}),yield this.eventDispatcher.dispatchEvent("ton-connect-request-version",createRequestVersionEvent())}catch(m){d(m)}}))})}dispatchUserActionEvent(f){var d;try{(d=this.eventDispatcher)==null||d.dispatchEvent(`${this.eventPrefix}${f.type}`,f).catch()}catch{}}trackConnectionStarted(...f){try{const d=createConnectionStartedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackConnectionCompleted(...f){try{const d=createConnectionCompletedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackConnectionError(...f){try{const d=createConnectionErrorEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringStarted(...f){try{const d=createConnectionRestoringStartedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringCompleted(...f){try{const d=createConnectionRestoringCompletedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackConnectionRestoringError(...f){try{const d=createConnectionRestoringErrorEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackDisconnection(...f){try{const d=createDisconnectionEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSentForSignature(...f){try{const d=createTransactionSentForSignatureEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSigned(...f){try{const d=createTransactionSignedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackTransactionSigningFailed(...f){try{const d=createTransactionSigningFailedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackDataSentForSignature(...f){try{const d=createDataSentForSignatureEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackDataSigned(...f){try{const d=createDataSignedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}trackDataSigningFailed(...f){try{const d=createDataSigningFailedEvent(this.version,...f);this.dispatchUserActionEvent(d)}catch{}}}const tonConnectUiVersion="2.2.0";class TonConnectUI{constructor(f){if(__publicField(this,"walletInfoStorage",new WalletInfoStorage),__publicField(this,"preferredWalletStorage",new PreferredWalletStorage),__publicField(this,"tracker"),__publicField(this,"walletInfo",null),__publicField(this,"systemThemeChangeUnsubscribe",null),__publicField(this,"actionsConfiguration"),__publicField(this,"walletsList"),__publicField(this,"_walletsRequiredFeatures"),__publicField(this,"_walletsPreferredFeatures"),__publicField(this,"connectRequestParametersCallback"),__publicField(this,"connector"),__publicField(this,"modal"),__publicField(this,"singleWalletModal"),__publicField(this,"transactionModal"),__publicField(this,"connectionRestored",Promise.resolve(!1)),f&&"connector"in f&&f.connector)this.connector=f.connector;else if(f&&"manifestUrl"in f&&f.manifestUrl)this.connector=new TonConnect({manifestUrl:f.manifestUrl,eventDispatcher:f.eventDispatcher,walletsRequiredFeatures:f.walletsRequiredFeatures});else throw new TonConnectUIError("You have to specify a `manifestUrl` or a `connector` in the options.");this.tracker=new TonConnectUITracker({eventDispatcher:f==null?void 0:f.eventDispatcher,tonConnectUiVersion}),this.modal=new WalletsModalManager({connector:this.connector,tracker:this.tracker,setConnectRequestParametersCallback:v=>{this.connectRequestParametersCallback=v}}),this.singleWalletModal=new SingleWalletModalManager({connector:this.connector,tracker:this.tracker,setConnectRequestParametersCallback:v=>{this.connectRequestParametersCallback=v}}),this.transactionModal=new TransactionModalManager({connector:this.connector}),this._walletsRequiredFeatures=f.walletsRequiredFeatures,this._walletsPreferredFeatures=f.walletsPreferredFeatures,this.walletsList=this.getWallets(),this.walletsList.then(v=>preloadImages(uniq(v.map(g=>g.imageUrl))));const d=this.normalizeWidgetRoot(f==null?void 0:f.widgetRootId);this.subscribeToWalletChange(),(f==null?void 0:f.restoreConnection)!==!1&&(this.connectionRestored=createMacrotaskAsync(()=>__async(this,null,function*(){return this.tracker.trackConnectionRestoringStarted(),yield this.connector.restoreConnection(),this.connector.connected?this.tracker.trackConnectionRestoringCompleted(this.wallet):(this.tracker.trackConnectionRestoringError("Connection was not restored"),this.walletInfoStorage.removeWalletInfo()),this.connector.connected}))),this.uiOptions=mergeOptions(f,{uiPreferences:{theme:"SYSTEM"}});const m=this.preferredWalletStorage.getPreferredWalletAppName();setAppState({connector:this.connector,preferredWalletAppName:m}),widgetController.renderApp(d,this)}static getWallets(){return TonConnect.getWallets()}get walletsRequiredFeatures(){return this._walletsRequiredFeatures}get walletsPreferredFeatures(){return this._walletsPreferredFeatures}get connected(){return this.connector.connected}get account(){return this.connector.account}get wallet(){return this.connector.wallet?__spreadValues(__spreadValues({},this.connector.wallet),this.walletInfo):null}set uiOptions(f){var d,m,v,g,w;this.checkButtonRootExist(f.buttonRootId),this.actionsConfiguration=f.actionsConfiguration,"walletsRequiredFeatures"in f&&(this._walletsRequiredFeatures=f.walletsRequiredFeatures),"walletsPreferredFeatures"in f&&(this._walletsPreferredFeatures=f.walletsPreferredFeatures),(d=f.uiPreferences)!=null&&d.theme?((m=f.uiPreferences)==null?void 0:m.theme)!=="SYSTEM"?((v=this.systemThemeChangeUnsubscribe)==null||v.call(this),setTheme(f.uiPreferences.theme,f.uiPreferences.colorsSet)):(setTheme(getSystemTheme(),f.uiPreferences.colorsSet),this.systemThemeChangeUnsubscribe||(this.systemThemeChangeUnsubscribe=subscribeToThemeChange(setTheme))):(g=f.uiPreferences)!=null&&g.colorsSet&&setColors(f.uiPreferences.colorsSet),(w=f.uiPreferences)!=null&&w.borderRadius&&setBorderRadius(f.uiPreferences.borderRadius),setAppState(_=>{var S,x;const b=mergeOptions(__spreadValues(__spreadValues(__spreadValues(__spreadValues({},f.language&&{language:f.language}),!!((S=f.actionsConfiguration)!=null&&S.returnStrategy)&&{returnStrategy:f.actionsConfiguration.returnStrategy}),!!((x=f.actionsConfiguration)!=null&&x.twaReturnUrl)&&{twaReturnUrl:f.actionsConfiguration.twaReturnUrl}),!!f.walletsListConfiguration&&{walletsListConfiguration:f.walletsListConfiguration}),unwrap(_));return f.buttonRootId!==void 0&&(b.buttonRootId=f.buttonRootId),f.enableAndroidBackHandler!==void 0&&(b.enableAndroidBackHandler=f.enableAndroidBackHandler),b})}setConnectRequestParameters(f){var d;setAppState({connectRequestParameters:f}),((f==null?void 0:f.state)==="ready"||!f)&&((d=this.connectRequestParametersCallback)==null||d.call(this,f==null?void 0:f.value))}getWallets(){return __async(this,null,function*(){return this.connector.getWallets()})}onStatusChange(f,d){return this.connector.onStatusChange(m=>__async(this,null,function*(){if(m){const v=yield this.getSelectedWalletInfo(m);f(__spreadValues(__spreadValues({},m),v||this.walletInfoStorage.getWalletInfo()))}else f(m)}),d)}openModal(){return __async(this,null,function*(){return this.modal.open()})}closeModal(f){this.modal.close(f)}onModalStateChange(f){return this.modal.onStateChange(f)}get modalState(){return this.modal.state}openSingleWalletModal(f){return __async(this,null,function*(){return this.singleWalletModal.open(f)})}closeSingleWalletModal(f){this.singleWalletModal.close(f)}onSingleWalletModalStateChange(f){return this.singleWalletModal.onStateChange(f)}get singleWalletModalState(){return this.singleWalletModal.state}connectWallet(){return __async(this,null,function*(){const d=(yield this.getWallets()).find(isWalletInfoCurrentlyEmbedded);return d?yield this.connectEmbeddedWallet(d):yield this.connectExternalWallet()})}disconnect(){return this.tracker.trackDisconnection(this.wallet,"dapp"),widgetController.clearAction(),widgetController.removeSelectedWalletInfo(),this.walletInfoStorage.removeWalletInfo(),this.connector.disconnect()}sendTransaction(f,d){return __async(this,null,function*(){if(this.tracker.trackTransactionSentForSignature(this.wallet,f),!this.connected)throw this.tracker.trackTransactionSigningFailed(this.wallet,f,"Wallet was not connected"),new TonConnectUIError("Connect wallet to send a transaction.");isInTMA()&&sendExpand();const{notifications:m,modals:v,returnStrategy:g,twaReturnUrl:w}=this.getModalsAndNotificationsConfiguration(d);widgetController.setAction({name:"confirm-transaction",showNotification:m.includes("before"),openModal:v.includes("before"),sent:!1});const _=new AbortController,S=()=>{_.signal.aborted||(widgetController.setAction({name:"confirm-transaction",showNotification:m.includes("before"),openModal:v.includes("before"),sent:!0}),this.redirectAfterRequestSent({returnStrategy:g,twaReturnUrl:w}))},x=this.onTransactionModalStateChange(b=>{b!=null&&b.openModal||(x(),b||_.abort())});try{const b=yield this.waitForSendTransaction({transaction:f,signal:_.signal},S);return this.tracker.trackTransactionSigned(this.wallet,f,b),widgetController.setAction({name:"transaction-sent",showNotification:m.includes("success"),openModal:v.includes("success")}),b}catch(b){throw b instanceof WalletNotSupportFeatureError?(widgetController.clearAction(),widgetController.openWalletNotSupportFeatureModal(b.cause),b):(widgetController.setAction({name:"transaction-canceled",showNotification:m.includes("error"),openModal:v.includes("error")}),b instanceof TonConnectError?b:new TonConnectUIError("Unhandled error:"+b))}finally{x()}})}signData(f){return __async(this,null,function*(){if(this.tracker.trackDataSentForSignature(this.wallet,f),!this.connected)throw this.tracker.trackDataSigningFailed(this.wallet,f,"Wallet was not connected"),new TonConnectUIError("Connect wallet to send a transaction.");isInTMA()&&sendExpand();const{notifications:d,modals:m,returnStrategy:v,twaReturnUrl:g}=this.getModalsAndNotificationsConfiguration();widgetController.setAction({name:"confirm-sign-data",showNotification:d.includes("before"),openModal:m.includes("before"),signed:!1});const w=new AbortController,_=()=>{w.signal.aborted||(widgetController.setAction({name:"confirm-sign-data",showNotification:d.includes("before"),openModal:m.includes("before"),signed:!0}),this.redirectAfterRequestSent({returnStrategy:v,twaReturnUrl:g}))},S=this.onTransactionModalStateChange(x=>{x!=null&&x.openModal||(S(),x||w.abort())});try{const x=yield this.waitForSignData({data:f,signal:new AbortController().signal},_);return this.tracker.trackDataSigned(this.wallet,f,x),widgetController.setAction({name:"data-signed",showNotification:d.includes("success"),openModal:m.includes("success")}),x}catch(x){throw x instanceof WalletNotSupportFeatureError?(widgetController.clearAction(),widgetController.openWalletNotSupportFeatureModal(x.cause),x):(widgetController.setAction({name:"sign-data-canceled",showNotification:d.includes("error"),openModal:m.includes("error")}),x instanceof TonConnectError?x:new TonConnectUIError("Unhandled error:"+x))}finally{S()}})}redirectAfterRequestSent({returnStrategy:f,twaReturnUrl:d}){this.walletInfo&&"universalLink"in this.walletInfo&&(this.walletInfo.openMethod==="universal-link"||this.walletInfo.openMethod==="custom-deeplink")&&(isTelegramUrl(this.walletInfo.universalLink)?redirectToTelegram(this.walletInfo.universalLink,{returnStrategy:f,twaReturnUrl:d||appState.twaReturnUrl,forceRedirect:!1}):redirectToWallet(this.walletInfo.universalLink,this.walletInfo.deepLink,{returnStrategy:f,forceRedirect:!1},()=>{}))}connectEmbeddedWallet(f){return __async(this,null,function*(){const d=v=>{setLastSelectedWalletInfo(f),this.connector.connect({jsBridgeKey:f.jsBridgeKey},v)},m=appState.connectRequestParameters;return(m==null?void 0:m.state)==="loading"?this.connectRequestParametersCallback=d:d(m==null?void 0:m.value),yield this.waitForWalletConnection({ignoreErrors:!1})})}connectExternalWallet(){return __async(this,null,function*(){const f=new AbortController;widgetController.openWalletsModal();const d=this.onModalStateChange(m=>{const{status:v,closeReason:g}=m;v!=="opened"&&(d(),g==="action-cancelled"&&f.abort())});return yield this.waitForWalletConnection({ignoreErrors:!0,signal:f.signal})})}waitForWalletConnection(f){return __async(this,null,function*(){return new Promise((d,m)=>{this.tracker.trackConnectionStarted();const{ignoreErrors:v=!1,signal:g=null}=f;if(g&&g.aborted)return this.tracker.trackConnectionError("Connection was cancelled"),m(new TonConnectUIError("Wallet was not connected"));const w=x=>__async(this,null,function*(){if(x)this.tracker.trackConnectionCompleted(x),S(),d(x);else{if(this.tracker.trackConnectionError("Connection was cancelled"),v)return;S(),m(new TonConnectUIError("Wallet was not connected"))}}),_=x=>{this.tracker.trackConnectionError(x.message),!v&&(S(),m(x))},S=this.onStatusChange(x=>w(x),x=>_(x));g&&g.addEventListener("abort",()=>{S(),m(new TonConnectUIError("Wallet was not connected"))},{once:!0})})})}waitForSendTransaction(f,d){return __async(this,null,function*(){return new Promise((m,v)=>{const{transaction:g,signal:w}=f;if(w.aborted)return this.tracker.trackTransactionSigningFailed(this.wallet,g,"Transaction was cancelled"),v(new TonConnectUIError("Transaction was not sent"));const _=b=>__async(this,null,function*(){m(b)}),S=b=>{v(b)},x=()=>{this.tracker.trackTransactionSigningFailed(this.wallet,g,"Transaction was cancelled"),v(new TonConnectUIError("Transaction was not sent"))};w.addEventListener("abort",x,{once:!0}),this.connector.sendTransaction(g,{onRequestSent:d,signal:w}).then(b=>(w.removeEventListener("abort",x),_(b))).catch(b=>(w.removeEventListener("abort",x),S(b)))})})}waitForSignData(f,d){return __async(this,null,function*(){return new Promise((m,v)=>{const{data:g,signal:w}=f;if(w.aborted)return this.tracker.trackDataSigningFailed(this.wallet,g,"SignData was cancelled"),v(new TonConnectUIError("SignData was not sent"));const _=b=>__async(this,null,function*(){m(b)}),S=b=>{v(b)},x=()=>{this.tracker.trackDataSigningFailed(this.wallet,g,"SignData was cancelled"),v(new TonConnectUIError("SignData was not sent"))};w.addEventListener("abort",x,{once:!0}),this.connector.signData(g,{onRequestSent:d,signal:w}).then(b=>_(b)).catch(b=>S(b))})})}onTransactionModalStateChange(f){return this.transactionModal.onStateChange(f)}subscribeToWalletChange(){this.connector.onStatusChange(f=>__async(this,null,function*(){var d;f?(yield this.updateWalletInfo(f),this.setPreferredWalletAppName(((d=this.walletInfo)==null?void 0:d.appName)||f.device.appName)):this.walletInfoStorage.removeWalletInfo()}))}setPreferredWalletAppName(f){this.preferredWalletStorage.setPreferredWalletAppName(f),setAppState({preferredWalletAppName:f})}getSelectedWalletInfo(f){return __async(this,null,function*(){let d=widgetController.getSelectedWalletInfo();if(!d)return null;let m;if("name"in d)m=d;else{const g=applyWalletsListConfiguration(yield this.walletsList,appState.walletsListConfiguration).find(w=>eqWalletName(w,f.device.appName));if(!g)throw new TonConnectUIError(`Cannot find WalletInfo for the '${f.device.appName}' wallet`);m=__spreadValues(__spreadValues({},g),d)}return m})}updateWalletInfo(f){return __async(this,null,function*(){const d=yield this.getSelectedWalletInfo(f);if(d){this.walletInfo=d,this.walletInfoStorage.setWalletInfo(d);return}const m=this.walletInfoStorage.getWalletInfo();if(m){this.walletInfo=m;return}this.walletInfo=(yield this.walletsList).find(v=>eqWalletName(v,f.device.appName))||null})}normalizeWidgetRoot(f){if(!f||!document.getElementById(f)){f="tc-widget-root";const d=document.createElement("div");d.id=f,document.body.appendChild(d)}return f}checkButtonRootExist(f){if(f!=null&&!document.getElementById(f))throw new TonConnectUIError(`${f} element not found in the document.`)}getModalsAndNotificationsConfiguration(f){var d,m,v,g,w,_;const S=["before","success","error"];let x=S;(d=this.actionsConfiguration)!=null&&d.notifications&&((m=this.actionsConfiguration)==null?void 0:m.notifications)!=="all"&&(x=this.actionsConfiguration.notifications),f!=null&&f.notifications&&(f.notifications==="all"?x=S:x=f.notifications);let b=["before"];(v=this.actionsConfiguration)!=null&&v.modals&&(this.actionsConfiguration.modals==="all"?b=S:b=this.actionsConfiguration.modals),f!=null&&f.modals&&(f.modals==="all"?b=S:b=f.modals);const C=(f==null?void 0:f.returnStrategy)||((g=this.actionsConfiguration)==null?void 0:g.returnStrategy)||"back",E=(f==null?void 0:f.twaReturnUrl)||((w=this.actionsConfiguration)==null?void 0:w.twaReturnUrl);let M=(f==null?void 0:f.skipRedirectToWallet)||((_=this.actionsConfiguration)==null?void 0:_.skipRedirectToWallet)||"ios";return isInTMA()&&(M="never"),{notifications:x,modals:b,returnStrategy:C,twaReturnUrl:E,skipRedirectToWallet:M}}}const DEFAULT_MANIFEST_URL="https://miniapp.spinfi.me/tonconnect-manifest.json";let tonConnectUIInstance=null,currentManifestUrl=null;class DefaultTonWalletProvider{constructor(f,d){this.bindWalletCallback=d;const m=f||DEFAULT_MANIFEST_URL;if(!tonConnectUIInstance||currentManifestUrl!==m)try{tonConnectUIInstance=new TonConnectUI({manifestUrl:m}),currentManifestUrl=m}catch{throw new Error("创建TonConnectUI实例失败")}this.ui=tonConnectUIInstance}isConnected(){var f;try{return!!((f=this.ui)!=null&&f.connected)}catch{return!1}}async reportWalletAddress(){const f=this.getUserFriendlyAddress();if(f&&this.bindWalletCallback)try{await this.bindWalletCallback(f)}catch{}}async connect(){if(this.isConnected())return await this.reportWalletAddress(),!0;try{return await new Promise((f,d)=>{this.ui.openModal();const m=this.ui.onStatusChange(()=>{this.isConnected()&&(m(),f())});setTimeout(()=>{this.isConnected()||(m(),d(new Error("连接钱包超时")))},3e5)}),await this.reportWalletAddress(),this.isConnected()}catch{return!1}}getUserFriendlyAddress(){var m,v,g;const f=this.ui,d=((v=(m=f==null?void 0:f.wallet)==null?void 0:m.account)==null?void 0:v.address)||((g=f==null?void 0:f.account)==null?void 0:g.address)||null;return d?toUserFriendlyAddress(d):null}async sendTonTransaction(f){if(!this.isConnected()&&!await this.connect())throw new Error("钱包未连接");const d=await this.ui.sendTransaction(f),m=d==null?void 0:d.boc;let v;if(m)try{v=m.substring(0,16)}catch{}return{transferHash:v,boc:m,raw:d}}async sendUsdtTransaction(f){if(!this.isConnected()&&!await this.connect())throw new Error("钱包未连接");const d=await this.ui.sendTransaction(f),m=d==null?void 0:d.boc;let v;if(m)try{v=m.substring(0,16)}catch{}return{transferHash:v,boc:m,raw:d}}async disconnect(){try{const f=this.ui;if(f!=null&&f.disconnect)await f.disconnect();else if(f!=null&&f.onStatusChange){const d=f.onStatusChange(()=>{});d&&d()}return!this.isConnected()}catch{return!1}}}class HmTrackingSDK{constructor(f){this.options=f,this.token=null,this.user=null;const d=this.options||{};this.storage=new NamespacedStorage(d.storageKeyPrefix||"hm_tracking_sdk"),this.token=this.storage.get("token");const m=d.baseURL||TEST_BASE_URL;this.http=new HttpClient({getToken:()=>this.token,onAuthError:()=>this.clearAuth(),baseURL:m,getAppId:()=>this.options&&this.options.appId||null}),this.api=new APIService(this.http),this.hmAdManager=new HmAdManager({autoInjectScript:!0}),this.adMonitor=new AdMonitor(v=>this.api.adMonitor(v)),this.tonWallet=new DefaultTonWalletProvider(d.tonConnectManifestUrl,this.bindWallet.bind(this))}async init(){const f=isTelegramEnv();try{const d=this.options||{},m=f?getTelegramUserUnsafe():null;if(m?this.user=m:d.customUser?this.user=d.customUser:typeof window<"u"?this.user=getAnonymousBrowserUser():this.user=getDefaultMockUser(),!this.user)throw new Error("未获取到用户信息:请在非 Telegram 环境提供 customUser");this.clearAuth(),await this.auth();try{await this.hmAdManager.init()}catch{}}catch(d){throw d}}async auth(){var f,d;try{const m={...this.user},v=(f=this.options)==null?void 0:f.notifyUrl;v&&(m.notifyUrl=v);const g=await this.api.auth(m);if(g.code!==1)throw new Error(g.msg||"鉴权失败");const w=(d=g.data)==null?void 0:d.token;if(!w)throw new Error("鉴权未返回 token");this.token=w,this.storage.set("token",w)}catch(m){throw m}}clearAuth(){this.token=null,this.storage.remove("token")}ensureTelegramEnvOrThrow(){if(!isTelegramEnv())throw new Error("支付相关功能仅支持在 Telegram 环境内使用")}async getAdPositionConfig(f){const d=await this.api.getAdPositionConfig(String(f));if(d.code!==1)throw new Error(d.msg||"获取广告位配置失败");return d.data||[]}async createAd(f){const d=await this.api.createAd(f);if(d.code!==1)throw new Error(d.msg||"创建广告失败");const m=d.data;return m!=null&&m.spaceId&&await this.hmAdManager.setSpace(String(m.spaceId)),m}async showHmAdByPosition(f,d){const m=await this.getAdPositionConfig(f);if(!m||m.length===0)throw new Error("未找到广告位配置");const v=m[0],g=await this.createAd({adId:v.adId,adPositionId:v.adPositionId}),w={start:g.start,show:g.show,error:g.error,close:g.close,reward:g.reward};await this.showHmAdWithMonitor(w,g.adShowId,d)}async showHmAdWithMonitor(f,d,m){const v=d||"";await this.adMonitor.send(f.start,v),await this.adMonitor.send(f.show,v);try{await this.hmAdManager.show(),await this.adMonitor.send(f.close,v);const g=await this.adMonitor.send(f.reward,v);m!=null&&m.onSuccess&&await m.onSuccess(g)}catch(g){throw await this.adMonitor.send(f.error,v),m!=null&&m.onError&&await m.onError(g),g}}async showHmPopupAd(f,d,m){const v=d||"";await this.adMonitor.send(f.start,v),await this.adMonitor.send(f.show,v);try{await this.hmAdManager.showPopup(),await this.adMonitor.send(f.close,v);const g=await this.adMonitor.send(f.reward,v);m!=null&&m.onSuccess&&await m.onSuccess(g)}catch(g){throw await this.adMonitor.send(f.error,v),m!=null&&m.onError&&await m.onError(g),g}}async showHmInAppAd(f,d,m,v){const g=m||"";await this.adMonitor.send(f.start,g),await this.adMonitor.send(f.show,g);try{await this.hmAdManager.showInApp(d),await this.adMonitor.send(f.close,g);const w=await this.adMonitor.send(f.reward,g);v!=null&&v.onSuccess&&await v.onSuccess(w)}catch(w){throw await this.adMonitor.send(f.error,g),v!=null&&v.onError&&await v.onError(w),w}}async bindWallet(f){try{if((await this.api.bindWalletReq({wallet:f,forceBind:!0})).code!==1)return}catch(d){throw d}}async disconnectWallet(){try{return this.tonWallet?(await this.tonWallet.disconnect(),!this.tonWallet.isConnected()):!0}catch{return!1}}async connectWallet(){return this.tonWallet?await this.tonWallet.connect():!1}isWalletConnected(){var f;return!!((f=this.tonWallet)!=null&&f.isConnected())}async ensureWalletConnected(){return this.ensureTelegramEnvOrThrow(),this.tonWallet?await this.tonWallet.connect():!1}async getSupportedPayModes(){const f=await this.api.merchantPayModeList();if(f.code!==1)throw new Error(f.msg||"获取支付方式失败");const d=f.data;return Array.isArray(d)?{payModeList:d}:{payModeList:Array.isArray(d==null?void 0:d.payModeList)?d.payModeList:[]}}async merchantPayQueryResult(f){const d=await this.api.merchantPayQueryResult(f);if(d.code!==1)throw new Error(d.msg||"查询支付结果失败");return d.data}async finishPayment(f,d,m=""){const v={orderSn:f,status:d,transferHash:m},g=await this.api.merchantPayFinish(v);if(g.code!==1)throw new Error(g.msg||"支付完成回调失败");return g.data}async payByMerchant(f){var _,S,x;this.ensureTelegramEnvOrThrow();const d=(_=f.currencyName)==null?void 0:_.toUpperCase(),m=await this.api.merchantPayCreate(f);if(m.code!==1)throw new Error(m.msg||"创建支付订单失败");const v=m.data;if(d==="STARS"&&v.payUrl)try{return await new Promise((C,E)=>{WebApp.openInvoice(v.payUrl,M=>{M==="paid"?C():E(new Error(`星币支付未完成: ${M||"未知状态"}`))})}),await this.finishPayment(v.orderSn,"success")}catch{return await this.finishPayment(v.orderSn,"failed")}if(!this.tonWallet||!this.tonWallet.isConnected())throw new Error("请先连接钱包");if(!((x=(S=v.transferData)==null?void 0:S.messages)==null?void 0:x[0]))throw new Error("订单未返回链上消息");let w;try{if(d==="TON")w=await this.tonWallet.sendTonTransaction(v.transferData);else if(d==="USDT")w=await this.tonWallet.sendUsdtTransaction(v.transferData);else throw new Error("暂不支持的币种");const b=w==null?void 0:w.transferHash;return await this.finishPayment(v.orderSn,"success",b||"")}catch{return await this.finishPayment(v.orderSn,"failed")}}}var AdPositionName=(r=>(r.GameRewardedAdPosition="game_rewarded_ad_position",r.TaskRewardedAdPosition="task_rewarded_ad_position",r.TaskListAdPosition="task_list_ad_position",r))(AdPositionName||{});globalThis.Buffer=Buffer$1,globalThis.process=process$1,globalThis.global=globalThis,exports.AdPositionName=AdPositionName,exports.HmTrackingSDK=HmTrackingSDK,exports.getAnonymousBrowserUser=getAnonymousBrowserUser,exports.getDefaultMockUser=getDefaultMockUser,exports.getTelegramUserUnsafe=getTelegramUserUnsafe,exports.isTelegramEnv=isTelegramEnv,Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"})}));
@@ -27,11 +27,12 @@ export class HmTrackingSDK {
27
27
  getToken: () => this.token,
28
28
  onAuthError: () => this.clearAuth(),
29
29
  baseURL,
30
+ getAppId: () => (this.options && this.options.appId) || null,
30
31
  });
31
32
  this.api = new APIService(this.http);
32
33
  this.hmAdManager = new HmAdManager({ autoInjectScript: true });
33
34
  this.adMonitor = new AdMonitor((params) => this.api.adMonitor(params));
34
- this.tonWallet = new DefaultTonWalletProvider(this.bindWallet.bind(this));
35
+ this.tonWallet = new DefaultTonWalletProvider(opts.tonConnectManifestUrl, this.bindWallet.bind(this));
35
36
  }
36
37
  async init() {
37
38
  const inTelegram = isTelegramEnv();
@@ -78,7 +79,13 @@ export class HmTrackingSDK {
78
79
  */
79
80
  async auth() {
80
81
  try {
81
- const res = await this.api.auth(this.user);
82
+ const payload = {
83
+ ...this.user,
84
+ };
85
+ const notifyUrl = this.options?.notifyUrl;
86
+ if (notifyUrl)
87
+ payload["notifyUrl"] = notifyUrl;
88
+ const res = await this.api.auth(payload);
82
89
  if (res.code !== 1)
83
90
  throw new Error(res.msg || "鉴权失败");
84
91
  const token = res.data?.token;