gramstax 0.5.21 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
- "use strict";var gt=Object.create;var O=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var yt=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var p=(g,t)=>O(g,"name",{value:t,configurable:!0});var St=(g,t)=>{for(var e in t)O(g,e,{get:t[e],enumerable:!0})},tt=(g,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of yt(t))!Ct.call(g,n)&&n!==e&&O(g,n,{get:()=>t[n],enumerable:!(s=ut(t,n))||s.enumerable});return g};var et=(g,t,e)=>(e=g!=null?gt(ft(g)):{},tt(t||!g||!g.__esModule?O(e,"default",{value:g,enumerable:!0}):e,g)),bt=g=>tt(O({},"__esModule",{value:!0}),g);var wt={};St(wt,{BlockKeyboard:()=>Q,CacheExternal:()=>D,Ctx:()=>V,Gramstax:()=>J,LabelKeyboard:()=>H,LoggingUtil:()=>E,TemplateEngine:()=>k,TemplateManager:()=>B,WorkerThreadExport:()=>z,WorkerThreadGatewayClient:()=>K,WorkerThreadGatewayServer:()=>L,WorkerThreadInit:()=>X,WorkerThreadLaunch:()=>$,WorkerThreadPool:()=>Y,WorkerThreadRpc:()=>T,log:()=>q});module.exports=bt(wt);var Pt=p(()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,"getImportMetaUrl"),S=Pt();var st=require("logging-pretty");var E=class extends st.LoggingPretty{static{p(this,"LoggingUtil")}constructor(t){super(t)}errorMake(t,e,s){this.error(`[${e?`${e}:${s}`:s}] ${this._formatErrorObj(t)}`)}_formatErrorObj(t){return JSON.stringify(t instanceof Error?{message:t.message,stack:t.stack,name:t.name}:t,null,2)}},q=new E;var nt=require("keyv"),it=et(require("@keyv/redis"),1);var D=class extends nt.Keyv{constructor(e="memory",s,n,o){let a;e.startsWith("redis")&&(a=new it.default(e)),e==="memory"&&(a=new Map),o?.forceStore&&(a=o.forceStore);super({store:a,namespace:n,ttl:s});this.url=e}static{p(this,"CacheExternal")}refreshLruCache(e){let s=this.store,n=this.opts.namespace?this.opts.namespace?.length+1:null,o=s.keys().toArray();for(let a=0;a<o.length;a++){let i=o[a];if(a==e)return;this.get(n?i.slice(n):i)}}};var U=require("timers/promises"),R=require("grammy");var V=class{static{p(this,"Ctx")}static template;static data;data=this.constructor.data;get userIsPremium(){return this.ct.from?.is_premium??!1}get userIsBot(){return this.ct.from?.is_bot??!1}get userId(){return this.ct.from?.id}get userName(){return this.ct.from?.username}get userFullName(){return`${this.ct.from?.first_name} ${this.ct.from?.last_name||""}`}get userFirstName(){return this.ct.from?.first_name}get userLastName(){return this.ct.from?.last_name}get userLanguage(){return this.ct.from?.language_code}set userLanguage(t){this.ct.from.language_code=t}get msgText(){return this.ct.message?.text}get msgTextPayloads(){return this.getPayloads(this.msgText,"space",this.data?._positionPayloadText||this.temp?.data?._positionPayloadText)}get msgTextPayload(){return this.msgTextPayloads[0]}get msgTextCommandPayloads(){return this.getPayloads(this.msgText,"space")}get msgTextCommandPayload(){return this.msgTextCommandPayloads[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionPayloads(){return this.getPayloads(this.msgCaption,"space")}get msgCaptionPayload(){return this.msgCaptionPayloads[0]}get msgCaptionCommandPayloads(){return this.getPayloads(this.msgCaption,"space")}get msgCaptionCommandPayload(){return this.msgCaptionCommandPayloads[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get msgDocument(){return this.ct.message?.document}get msgAnimation(){return this.ct.message?.animation}get msgVoice(){return this.ct.message?.voice}get msgVideoNote(){return this.ct.message?.video_note}get msgSticker(){return this.ct.message?.sticker}get msgLocation(){return this.ct.message?.location}get msgContact(){return this.ct.message?.contact}get msgWebAppData(){return this.ct.message?.web_app_data}get msgGift(){return this.ct.message?.gift}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataPayloads(){return this.getPayloads(this.callbackData,"colon")}get callbackDataPayload(){return this.callbackDataPayloads?.[0]}get session(){return this.temp.session}set session(t){this.temp.session=t}ct;cacheSession;cacheKeyboard;templateManager;temp;constructor(t){this.ct=t.ct,this.cacheSession=t.cacheSession,this.cacheKeyboard=t.cacheKeyboard,this.templateManager=t.templateManager,this.temp=t.temp}async broadcast(t,e,s,n,o,a,i=!1){try{this.temp.isAnswer=!0;let r=30,c=e.map(l=>this.templateManager.getMessage(this.data.name,o,l,n));for(let l=0;l<t.length;l++){let h=t[l],d=c[l];await this.ct.api.sendMessage(h,d,{parse_mode:"HTML",reply_markup:s,...a}),l+1==r&&await(0,U.setTimeout)(1200)}}catch(r){if(i)throw r}}async broadcastMedia(t,e,s,n,o,a,i=!1){try{this.temp.isAnswer=!0;let r=30,c=e.map(l=>this.templateManager.getMedia(this.data.name,o,l,n));for(let l=0;l<t.length;l++){let h=t[l],d=c[l];if(!d)continue;let m={parse_mode:"HTML",reply_markup:s,...a};d.type=="photo"&&await this.ct.api.sendPhoto(h,d.src,{caption:d.caption,...m}),d.type=="video"&&await this.ct.api.sendVideo(h,d.src,{caption:d.caption,...m}),d.type=="audio"&&await this.ct.api.sendAudio(h,d.src,{caption:d.caption,...m}),d.type=="document"&&await this.ct.api.sendDocument(h,d.src,{caption:d.caption,...m}),d.type=="animation"&&await this.ct.api.sendAnimation(h,d.src,{caption:d.caption,...m}),d.type=="voice"&&await this.ct.api.sendVoice(h,d.src,m),d.type=="video_note"&&await this.ct.api.sendVideoNote(h,d.src,m),d.type=="sticker"&&await this.ct.api.sendSticker(h,d.src,m),d.type=="location"&&await this.ct.api.sendLocation(h,parseInt(d.latitude),parseInt(d.longitude),m),d.type=="contact"&&await this.ct.api.sendContact(h,d.phone,d.first_name,{vcard:d.vcard,...m}),l+1==r&&await(0,U.setTimeout)(1200)}}catch(r){if(i)throw r}}async reply(t,e,s,n){this.temp.isAnswer=!0;let o=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.reply(o,{parse_mode:"HTML",reply_markup:t,...n})}async replyMedia(t,e,s,n,o){this.temp.isAnswer=!0;let a=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s),i={parse_mode:"HTML",reply_markup:e,...o};if(t=="photo")return await this.ct.replyWithPhoto(a.src,{caption:a.caption,...i});if(t=="video")return await this.ct.replyWithVideo(a.src,{caption:a.caption,...i});if(t=="audio")return await this.ct.replyWithAudio(a.src,{caption:a.caption,...i});if(t=="document")return await this.ct.replyWithDocument(a.src,{caption:a.caption,...i});if(t=="animation")return await this.ct.replyWithAnimation(a.src,{caption:a.caption,...i});if(t=="voice")return await this.ct.replyWithVoice(a.src,i);if(t=="video_note")return await this.ct.replyWithVideoNote(a.src,i);if(t=="sticker")return await this.ct.replyWithSticker(a.src,i);if(t=="location")return await this.ct.replyWithLocation(parseInt(a.latitude),parseInt(a.longitude),i);if(t=="contact")return await this.ct.replyWithContact(a.phone,a.first_name,{vcard:a.vcard,...i})}async replyPhoto(t,e,s,n){return this.replyMedia("photo",t,e,s,n)}async replyVideo(t,e,s,n){return this.replyMedia("video",t,e,s,n)}async replyAudio(t,e,s,n){return this.replyMedia("audio",t,e,s,n)}async replyDocument(t,e,s,n){return this.replyMedia("document",t,e,s,n)}async replyAnimation(t,e,s,n){return this.replyMedia("animation",t,e,s,n)}async replyVoice(t,e,s,n){return this.replyMedia("voice",t,e,s,n)}async replyVideoNote(t,e,s,n){return this.replyMedia("video_note",t,e,s,n)}async replySticker(t,e,s,n){return this.replyMedia("sticker",t,e,s,n)}async replyLocation(t,e,s,n){return this.replyMedia("location",t,e,s,n)}async replyContact(t,e,s,n){return this.replyMedia("contact",t,e,s,n)}async replyAction(t){return await this.ct.replyWithChatAction(t)}async edit(t,e,s,n,o=!0){try{this.temp.isAnswer=!0;let a=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.editMessageText(a,{parse_mode:"HTML",reply_markup:t,...n})}catch(a){if(o)await this.reply(t,e,s,n);else throw a}}async editMedia(t,e,s,n,o,a,i=!0){try{this.temp.isAnswer=!0;let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s);return t=="voice"?(await this.delete(),await this.replyVoice(e,s,n,o)):t=="video_note"?(await this.delete(),await this.replyVoice(e,s,n,o)):t=="sticker"?(await this.delete(),await this.replySticker(e,s,n,o)):t=="location"?(await this.delete(),await this.replyLocation(e,s,n,o)):t=="contact"?(await this.delete(),await this.replyContact(e,s,n,o)):await this.ct.editMessageMedia({media:r,caption:c,type:t,parse_mode:"HTML",...o},{reply_markup:e,...a})}catch(r){if(i===!0)await this.reply(e,s,n,a);else throw r}}async editPhoto(t,e,s,n,o){return await this.editMedia("photo",t,e,s,n,o)}async editVideo(t,e,s,n,o){return await this.editMedia("video",t,e,s,n,o)}async editAudio(t,e,s,n,o){return await this.editMedia("audio",t,e,s,n,o)}async editDocument(t,e,s,n,o){return await this.editMedia("document",t,e,s,n,o)}async editAnimation(t,e,s,n,o){return await this.editMedia("animation",t,e,s,n,o)}async editVoice(t,e,s,n){return await this.editMedia("voice",t,e,s,n)}async editVideoNote(t,e,s,n){return await this.editMedia("video_note",t,e,s,n)}async editSticker(t,e,s,n){return await this.editMedia("sticker",t,e,s,n)}async editLocation(t,e,s,n){return await this.editMedia("location",t,e,s,n)}async editContact(t,e,s,n){return await this.editMedia("contact",t,e,s,n)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(t){try{return this.temp.isAnswer=!0,await this.ct.answerCallbackQuery(t)}catch{return null}}async sessionSet(t,e,s){try{let n={method:t,params:e,...s},o=await this.cacheSession.set(`${this.userId}`,n);return o&&(this.session=n),o}catch{return null}}async sessionGet(){try{let t=await this.cacheSession.get(`${this.userId}`);return t&&(this.session=t),t||null}catch{return null}}async sessionClear(){try{let t=await this.cacheSession.delete(`${this.userId}`);return t&&(this.session={}),t}catch{return null}}static buildData(t){let s=typeof t=="function"?{callback:t}:t||{},n=s.callback,o=this.prototype.addPayloads.bind(this.prototype),a=s.name||"";return{name:a,intentText:s.intentText||a,intentTextCommand:s.intentTextCommand||a,intentCallback:a,callback:n?function(...r){return o(this.intentCallback,"colon",n(...r))}:function(){return this?.intentCallback},_positionPayloadText:s.intentText?s.intentText.split(this.prototype.getSeperatorTag("space")).length:void 0}}keyboardCols(t,e,s,n){let[o,a]=s.split("-"),i=parseInt(o),r=a?parseInt(a):null,c=e.length,l=t;for(let h=0;h<c;h++){let d=e[h];if(n(d,h),r===null)(h+1)%i===0&&h<c-1&&l.row();else{let m=c-(h+1);(m===r||m>r&&(h+1)%i===0)&&l.row()}}return t}bottomKeyboardT(t="1",e,s){return this.bottomKeyboard((n,o)=>this.keyboardCols(n,o,t,a=>n.text(a)),{baseId:e??void 0,data:s})}inlineKeyboardT(t,e="1",s,n){return this.inlineKeyboard((o,a)=>this.keyboardCols(o,a,e,(i,r)=>{let c=t[r],l=typeof c=="string"?c:c.data.callback();o.text(i,l)}),{baseId:s??void 0,data:n})}inlineKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let i=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(i);if(!r){let c=new R.InlineKeyboard,l=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data),h=t(c,l);return this.cacheKeyboard.set(i,h),h}return r}let n=new R.InlineKeyboard,o=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data);return t(n,o)}bottomKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let i=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(i);if(!r){let c=new R.Keyboard,l=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),h=t(c,l);return h.resized(!0),this.cacheKeyboard.set(i,h),h}return r}let n=new R.Keyboard,o=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),a=t(n,o);return a.resized(),a}getSeperatorTag(t="space"){return t=="space"?" ":":"}havePayloads(t="",e){return t.includes(this.getSeperatorTag(e))}addPayloads(t="",e,s){let n=this.getSeperatorTag(e),o="";for(let a=0;a<s.length;a++){let i=s[a];i!=null&&i!==""&&(o+=n+i)}return t+o}getPayloads(t="",e,s=1){if(!t)return[];let n=this.getSeperatorTag(e);return t.split(n).slice(s)}getIntent(t="",e,s=1){if(!t)return"";let n=this.getSeperatorTag(e),o=t.split(n);return s==1?o[0]:o.slice(0,s).join(n)}validateSessionCallback(t,e){return(t??this.session.method)===this.methodSessionCallback(e)}validateSessionCallbackPayload(t,e){return(t??this.session.method)===this.methodSessionCallbackPayload(e)}validateSessionText(t,e){return(t??this.session.method)===this.methodSessionText(e)}validateSessionTextPayload(t,e){return(t??this.session.method)===this.methodSessionTextPayload(e)}validateSessionTextCommand(t,e){return(t??this.session.method)===this.methodSessionTextCommand(e)}validateSessionTextCommandPayload(t,e){return(t??this.session.method)===this.methodSessionTextCommandPayload(e)}validateSessionTextFree(t,e){return(t??this.session.method)===this.methodSessionTextFree(e)}validateSessionPhotoCaption(t,e){return(t??this.session.method)===this.methodSessionPhotoCaption(e)}validateSessionPhotoCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionPayload(e)}validateSessionPhotoCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionCommand(e)}validateSessionPhotoCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionCommandPayload(e)}validateSessionPhotoFree(t,e){return(t??this.session.method)===this.methodSessionPhotoFree(e)}validateSessionVideoCaption(t,e){return(t??this.session.method)===this.methodSessionVideoCaption(e)}validateSessionVideoCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionPayload(e)}validateSessionVideoCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionCommand(e)}validateSessionVideoCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionCommandPayload(e)}validateSessionVideoFree(t,e){return(t??this.session.method)===this.methodSessionVideoFree(e)}validateSessionAudioCaption(t,e){return(t??this.session.method)===this.methodSessionAudioCaption(e)}validateSessionAudioCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionPayload(e)}validateSessionAudioCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionCommand(e)}validateSessionAudioCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionCommandPayload(e)}validateSessionAudioFree(t,e){return(t??this.session.method)===this.methodSessionAudioFree(e)}validateSessionDocumentCaption(t,e){return(t??this.session.method)===this.methodSessionDocumentCaption(e)}validateSessionDocumentCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionPayload(e)}validateSessionDocumentCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionCommand(e)}validateSessionDocumentCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionCommandPayload(e)}validateSessionDocumentFree(t,e){return(t??this.session.method)===this.methodSessionDocumentFree(e)}validateSessionAnimationCaption(t,e){return(t??this.session.method)===this.methodSessionAnimationCaption(e)}validateSessionAnimationCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionPayload(e)}validateSessionAnimationCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionCommand(e)}validateSessionAnimationCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionCommandPayload(e)}validateSessionAnimationFree(t,e){return(t??this.session.method)===this.methodSessionAnimationFree(e)}validateSessionVoiceCaption(t,e){return(t??this.session.method)===this.methodSessionVoiceCaption(e)}validateSessionVoiceCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionPayload(e)}validateSessionVoiceCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionCommand(e)}validateSessionVoiceCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionCommandPayload(e)}validateSessionVoiceFree(t,e){return(t??this.session.method)===this.methodSessionVoiceFree(e)}validateSessionVideoNoteFree(t,e){return(t??this.session.method)===this.methodSessionVideoNoteFree(e)}validateSessionStickerFree(t,e){return(t??this.session.method)===this.methodSessionStickerFree(e)}validateSessionLocationFree(t,e){return(t??this.session.method)===this.methodSessionLocationFree(e)}validateSessionContactFree(t,e){return(t??this.session.method)===this.methodSessionContactFree(e)}sessionCallback(t,e){return this.sessionSet(this.methodSessionCallback(e),t)}sessionCallbackPayload(t,e){return this.sessionSet(this.methodSessionCallbackPayload(e),t)}sessionText(t,e){return this.sessionSet(this.methodSessionText(e),t)}sessionTextPayload(t,e){return this.sessionSet(this.methodSessionTextPayload(e),t)}sessionTextCommand(t,e){return this.sessionSet(this.methodSessionTextCommand(e),t)}sessionTextCommandPayload(t,e){return this.sessionSet(this.methodSessionTextCommandPayload(e),t)}sessionTextFree(t,e){return this.sessionSet(this.methodSessionTextFree(e),t)}sessionPhotoCaption(t,e){return this.sessionSet(this.methodSessionPhotoCaption(e),t)}sessionPhotoCaptionPayload(t,e){return this.sessionSet(this.methodSessionPhotoCaptionPayload(e),t)}sessionPhotoCaptionCommand(t,e){return this.sessionSet(this.methodSessionPhotoCaptionCommand(e),t)}sessionPhotoCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionPhotoCaptionCommandPayload(e),t)}sessionPhotoFree(t,e){return this.sessionSet(this.methodSessionPhotoFree(e),t)}sessionVideoCaption(t,e){return this.sessionSet(this.methodSessionVideoCaption(e),t)}sessionVideoCaptionPayload(t,e){return this.sessionSet(this.methodSessionVideoCaptionPayload(e),t)}sessionVideoCaptionCommand(t,e){return this.sessionSet(this.methodSessionVideoCaptionCommand(e),t)}sessionVideoCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVideoCaptionCommandPayload(e),t)}sessionVideoFree(t,e){return this.sessionSet(this.methodSessionVideoFree(e),t)}sessionAudioCaption(t,e){return this.sessionSet(this.methodSessionAudioCaption(e),t)}sessionAudioCaptionPayload(t,e){return this.sessionSet(this.methodSessionAudioCaptionPayload(e),t)}sessionAudioCaptionCommand(t,e){return this.sessionSet(this.methodSessionAudioCaptionCommand(e),t)}sessionAudioCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionAudioCaptionCommandPayload(e),t)}sessionAudioFree(t,e){return this.sessionSet(this.methodSessionAudioFree(e),t)}sessionDocumentCaption(t,e){return this.sessionSet(this.methodSessionDocumentCaption(e),t)}sessionDocumentCaptionPayload(t,e){return this.sessionSet(this.methodSessionDocumentCaptionPayload(e),t)}sessionDocumentCaptionCommand(t,e){return this.sessionSet(this.methodSessionDocumentCaptionCommand(e),t)}sessionDocumentCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionDocumentCaptionCommandPayload(e),t)}sessionDocumentFree(t,e){return this.sessionSet(this.methodSessionDocumentFree(e),t)}sessionAnimationCaption(t,e){return this.sessionSet(this.methodSessionAnimationCaption(e),t)}sessionAnimationCaptionPayload(t,e){return this.sessionSet(this.methodSessionAnimationCaptionPayload(e),t)}sessionAnimationCaptionCommand(t,e){return this.sessionSet(this.methodSessionAnimationCaptionCommand(e),t)}sessionAnimationCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionAnimationCaptionCommandPayload(e),t)}sessionAnimationFree(t,e){return this.sessionSet(this.methodSessionAnimationFree(e),t)}sessionVoiceCaption(t,e){return this.sessionSet(this.methodSessionVoiceCaption(e),t)}sessionVoiceCaptionPayload(t,e){return this.sessionSet(this.methodSessionVoiceCaptionPayload(e),t)}sessionVoiceCaptionCommand(t,e){return this.sessionSet(this.methodSessionVoiceCaptionCommand(e),t)}sessionVoiceCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVoiceCaptionCommandPayload(e),t)}sessionVoiceFree(t,e){return this.sessionSet(this.methodSessionVoiceFree(e),t)}sessionVideoNoteFree(t,e){return this.sessionSet(this.methodSessionVideoNoteFree(e),t)}sessionStickerFree(t,e){return this.sessionSet(this.methodSessionStickerFree(e),t)}sessionLocationFree(t,e){return this.sessionSet(this.methodSessionLocationFree(e),t)}sessionContactFree(t,e){return this.sessionSet(this.methodSessionContactFree(e),t)}sessionToCallback(t,e){return this.sessionCallback({...this.session.params,...t},e)}sessionToCallbackPayload(t,e){return this.sessionCallbackPayload({...this.session.params,...t},e)}sessionToText(t,e){return this.sessionText({...this.session.params,...t},e)}sessionToTextPayload(t,e){return this.sessionTextPayload({...this.session.params,...t},e)}sessionToTextCommand(t,e){return this.sessionTextCommand({...this.session.params,...t},e)}sessionToTextCommandPayload(t,e){return this.sessionTextCommandPayload({...this.session.params,...t},e)}sessionToTextFree(t,e){return this.sessionTextFree({...this.session.params,...t},e)}sessionToPhotoCaption(t,e){return this.sessionPhotoCaption({...this.session.params,...t},e)}sessionToPhotoCaptionPayload(t,e){return this.sessionPhotoCaptionPayload({...this.session.params,...t},e)}sessionToPhotoCaptionCommand(t,e){return this.sessionPhotoCaptionCommand({...this.session.params,...t},e)}sessionToPhotoCaptionCommandPayload(t,e){return this.sessionPhotoCaptionCommandPayload({...this.session.params,...t},e)}sessionToPhotoFree(t,e){return this.sessionPhotoFree({...this.session.params,...t},e)}sessionToVideoCaption(t,e){return this.sessionVideoCaption({...this.session.params,...t},e)}sessionToVideoCaptionPayload(t,e){return this.sessionVideoCaptionPayload({...this.session.params,...t},e)}sessionToVideoCaptionCommand(t,e){return this.sessionVideoCaptionCommand({...this.session.params,...t},e)}sessionToVideoCaptionCommandPayload(t,e){return this.sessionVideoCaptionCommandPayload({...this.session.params,...t},e)}sessionToVideoFree(t,e){return this.sessionVideoFree({...this.session.params,...t},e)}sessionToAudioCaption(t,e){return this.sessionAudioCaption({...this.session.params,...t},e)}sessionToAudioCaptionPayload(t,e){return this.sessionAudioCaptionPayload({...this.session.params,...t},e)}sessionToAudioCaptionCommand(t,e){return this.sessionAudioCaptionCommand({...this.session.params,...t},e)}sessionToAudioCaptionCommandPayload(t,e){return this.sessionAudioCaptionCommandPayload({...this.session.params,...t},e)}sessionToAudioFree(t,e){return this.sessionAudioFree({...this.session.params,...t},e)}sessionToDocumentCaption(t,e){return this.sessionDocumentCaption({...this.session.params,...t},e)}sessionToDocumentCaptionPayload(t,e){return this.sessionDocumentCaptionPayload({...this.session.params,...t},e)}sessionToDocumentCaptionCommand(t,e){return this.sessionDocumentCaptionCommand({...this.session.params,...t},e)}sessionToDocumentCaptionCommandPayload(t,e){return this.sessionDocumentCaptionCommandPayload({...this.session.params,...t},e)}sessionToDocumentFree(t,e){return this.sessionDocumentFree({...this.session.params,...t},e)}sessionToAnimationCaption(t,e){return this.sessionAnimationCaption({...this.session.params,...t},e)}sessionToAnimationCaptionPayload(t,e){return this.sessionAnimationCaptionPayload({...this.session.params,...t},e)}sessionToAnimationCaptionCommand(t,e){return this.sessionAnimationCaptionCommand({...this.session.params,...t},e)}sessionToAnimationCaptionCommandPayload(t,e){return this.sessionAnimationCaptionCommandPayload({...this.session.params,...t},e)}sessionToAnimationFree(t,e){return this.sessionAnimationFree({...this.session.params,...t},e)}sessionToVoiceCaption(t,e){return this.sessionVoiceCaption({...this.session.params,...t},e)}sessionToVoiceCaptionPayload(t,e){return this.sessionVoiceCaptionPayload({...this.session.params,...t},e)}sessionToVoiceCaptionCommand(t,e){return this.sessionVoiceCaptionCommand({...this.session.params,...t},e)}sessionToVoiceCaptionCommandPayload(t,e){return this.sessionVoiceCaptionCommandPayload({...this.session.params,...t},e)}sessionToVoiceFree(t,e){return this.sessionVoiceFree({...this.session.params,...t},e)}sessionToVideoNoteFree(t,e){return this.sessionVideoNoteFree({...this.session.params,...t},e)}sessionToStickerFree(t,e){return this.sessionStickerFree({...this.session.params,...t},e)}sessionToLocationFree(t,e){return this.sessionLocationFree({...this.session.params,...t},e)}sessionToContactFree(t,e){return this.sessionContactFree({...this.session.params,...t},e)}methodSession(t,e){return`${t}-${e||this.data.name}`}methodSessionCallback(t){return this.methodSession("1",t)}methodSessionCallbackPayload(t){return this.methodSession("2",t)}methodSessionText(t){return this.methodSession("3",t)}methodSessionTextPayload(t){return this.methodSession("4",t)}methodSessionTextCommand(t){return this.methodSession("5",t)}methodSessionTextCommandPayload(t){return this.methodSession("6",t)}methodSessionTextFree(t){return this.methodSession("7",t)}methodSessionPhotoCaption(t){return this.methodSession("8",t)}methodSessionPhotoCaptionPayload(t){return this.methodSession("9",t)}methodSessionPhotoCaptionCommand(t){return this.methodSession("10",t)}methodSessionPhotoCaptionCommandPayload(t){return this.methodSession("11",t)}methodSessionPhotoFree(t){return this.methodSession("12",t)}methodSessionVideoCaption(t){return this.methodSession("13",t)}methodSessionVideoCaptionPayload(t){return this.methodSession("14",t)}methodSessionVideoCaptionCommand(t){return this.methodSession("15",t)}methodSessionVideoCaptionCommandPayload(t){return this.methodSession("16",t)}methodSessionVideoFree(t){return this.methodSession("17",t)}methodSessionAudioCaption(t){return this.methodSession("18",t)}methodSessionAudioCaptionPayload(t){return this.methodSession("19",t)}methodSessionAudioCaptionCommand(t){return this.methodSession("20",t)}methodSessionAudioCaptionCommandPayload(t){return this.methodSession("21",t)}methodSessionAudioFree(t){return this.methodSession("22",t)}methodSessionDocumentCaption(t){return this.methodSession("23",t)}methodSessionDocumentCaptionPayload(t){return this.methodSession("24",t)}methodSessionDocumentCaptionCommand(t){return this.methodSession("25",t)}methodSessionDocumentCaptionCommandPayload(t){return this.methodSession("26",t)}methodSessionDocumentFree(t){return this.methodSession("27",t)}methodSessionAnimationCaption(t){return this.methodSession("28",t)}methodSessionAnimationCaptionPayload(t){return this.methodSession("29",t)}methodSessionAnimationCaptionCommand(t){return this.methodSession("30",t)}methodSessionAnimationCaptionCommandPayload(t){return this.methodSession("31",t)}methodSessionAnimationFree(t){return this.methodSession("32",t)}methodSessionVoiceCaption(t){return this.methodSession("33",t)}methodSessionVoiceCaptionPayload(t){return this.methodSession("34",t)}methodSessionVoiceCaptionCommand(t){return this.methodSession("35",t)}methodSessionVoiceCaptionCommandPayload(t){return this.methodSession("36",t)}methodSessionVoiceFree(t){return this.methodSession("37",t)}methodSessionVideoNoteFree(t){return this.methodSession("38",t)}methodSessionStickerFree(t){return this.methodSession("39",t)}methodSessionLocationFree(t){return this.methodSession("40",t)}methodSessionContactFree(t){return this.methodSession("41",t)}};var j=require("path"),F=require("fs"),ot=require("module");var P=class{static{p(this,"PageManager")}static _getFile(t,e,s=0){let o=Object.values(t)[s];if(o===void 0)throw new Error(`File ${e} must have export (not default) class page`);return o}static getFilePath(){return(0,j.join)(process.cwd(),"src","pages")}static getFileSync(t,e=0){t||(t=this.getFilePath());let n=(0,ot.createRequire)(t)(t);return this._getFile(n,t,e)}static async getFile(t,e=0){t||(t=this.getFilePath());let s=await import(`${t}?t=${Date.now()}`);return this._getFile(s,t,e)}static getFileManySync(t,e=0){if(t||(t=this.getFilePath()),!(0,F.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,F.readdirSync)(t).map(n=>{let o=(0,j.join)(t,n);return{path:o,page:this.getFileSync(o,e)}})}static clearCacheRequire(t){if(t||(t=this.getFilePath()),!(0,F.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,F.readdirSync)(t).forEach(s=>{let n=(0,j.join)(t,s);delete require.cache[require.resolve(n)]}),!0}};var rt=require("fs"),ct=require("url"),M=require("path");var b=require("path"),f=require("fs"),at=require("chokidar");var k=class{static{p(this,"TemplateEngine")}static _escape(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processVariables(t){return t.replace(/\{\{(\w+)\}\}/g,(e,s)=>`\${(data && data["${s}"]) ?? ""}`)}static _processBaseBlocks(t){let e=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,s={};for(let n of t.matchAll(e)){let o=n[2]??"default",i=(n[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[o]=i}return s}static _processScriptBlocks(t){return t.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(e,s)=>{let n=s.trim();return n?`\${(() => { if (!data) return ''; try { with(data) { ${n} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(t){return t.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(t){return t.replace(/<div>([\s\S]*?)<\/div>/gi,(e,s)=>s.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(t){let e=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return t.replace(e,(s,n,o)=>{if(!n)return"";let a="",i=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=i.exec(o))!==null;){let h=(c[1]||"").split(",").map(m=>m.trim()),d=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");h.forEach(m=>{a+=`case "${m}": `}),a+=`return \`${d}\`; `}let l=r.exec(o);if(l){let h=(l[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();a+=`default: return \`${h}\`; `}else a+="default: return ''; ";return`\${(() => { switch((data && data["${n}"])) { ${a} } })()}`})}static _processExec(t){return t.replace(/{~\s*([\s\S]*?)\s*~}/g,(e,s)=>`\${(() => { try { return ${s} } catch(e) { try { with(data || {}) { return ${s} } } catch(ee) { return '' } } })()}`)}static _processMapBlocks(t){let e=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return t.replace(e,(s,n,o)=>{let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(i))a[d[1]]=d[2];let r=a.src;if(!r)return"";let c=a.join??"\\n",l=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");l=l.replace(/\{\{([\w.]+)\}\}/g,(d,m)=>m==="e"||m.startsWith("e.")?`\${${m}}`:m==="i"?"${i}":d);let h=c.replace(/"/g,'\\"');return`\${(data && data["${r}"] || []).map((e, i) => \`${l}\`).join("${h}")}`})}static _processMediaBlocks(t){let e=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let n of t.matchAll(e)){let o=n[1],a=n[2],i={},r=/(\w+)="([^"]*)"/g;if(o)for(let m of o.matchAll(r))i[m[1]]=m[2];let c=i.lang||"default",l=i.type,h=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),d={type:l};i.src&&(d.src=i.src),h&&l!=="video_note"&&l!=="sticker"&&(d.caption=h),l==="location"&&(i.latitude&&(d.latitude=i.latitude),i.longitude&&(d.longitude=i.longitude),h&&(d.caption=h)),l==="contact"&&(i.phone&&(d.phone=i.phone),i.first_name&&(d.first_name=i.first_name),i.last_name&&(d.last_name=i.last_name),i.vcard&&(d.vcard=i.vcard),h&&(d.caption=h)),s[c]=d}return s}static _processMessageBlocks(t){let e=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,n,o]of t.matchAll(e)){let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let l of n.matchAll(i))a[l[1]]=l[2];let r=a.lang||"default",c=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=c}return s}static _processDescriptionBlocks(t){let e=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,n,o]of t.matchAll(e)){let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let h of n.matchAll(i))a[h[1]]=h[2];let r=a.lang||"default",c=a.scope||"default",l=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][c]=l}return s}static _processKeyboardBlocks(t){let e=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,n,o]of t.matchAll(e)){let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let h of n.matchAll(i))a[h[1]]=h[2];let r=a.lang||"default",c=a.type==="bottom"?"bottom":"inline",l=o.trim();s[r]||(s[r]={}),s[r][c]=l}return s}static _compileToFunction(t,e){let s;e?s=t.map(a=>`\`${a}\``).join(","):s=`\`${t}\``;let n=s;if(n=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(n))),e){let o=`return [${n}]`;return new Function("data",o)}else{let o=`return ${n}`;return new Function("data",o)}}static compileMedia(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processMediaBlocks(a);n[o]={};for(let[r,c]of Object.entries(i)){let l={};for(let[h,d]of Object.entries(c)){if(h==="type"||typeof d!="string")continue;let m=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));l[h]=this._compileToFunction(m,!1)}n[o][r]=h=>{let d={...c};for(let[m,y]of Object.entries(l))d[m]=y(h);return d}}}return n}static compileMessages(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processMessageBlocks(a);n[o]={};for(let[r,c]of Object.entries(i)){let l=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));n[o][r]=this._compileToFunction(l,!1)}}return n}static compileDescription(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processDescriptionBlocks(a);n[o]={};for(let[r,c]of Object.entries(i))for(let[l,h]of Object.entries(c)){n[o][l]||(n[o][l]={});let d=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(h)))));n[o][l][r]=this._compileToFunction(d,!1)}}return n}static compileKeyboards(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processKeyboardBlocks(a);n[o]={};for(let[r,c]of Object.entries(i)){n[o][r]={};for(let[l,h]of Object.entries(c)){let m=h.split(/(?<!\\),\s*/).map(y=>y.replace(/\\,/g,",").trim()).map(y=>this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(y))))));n[o][r][l]=this._compileToFunction(m,!0)}}}return n}static _extractBlock(t,e,s="default",n="all",o){let a=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,i=t,r=!1;for(let c of t.matchAll(a))if((c[2]??"default")===s){i=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(t);if(!(s==="default"&&!c))return""}if(e){if(e==="all")return i;let c=Array.isArray(e)?e:[e],l=[];for(let d of c){let m=new RegExp(`([ \\t]*)<${d}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${d}>`,"gi");for(let y of i.matchAll(m)){let C=y[2];if(o){let u=/lang="([^"]*)"/i,w=C?.match(u);if(((w?w[1]:void 0)||"default")!==o)continue}l.push({start:y.index,content:y[0],innerContent:y[3]??""})}}l.sort((d,m)=>d.start-m.start);let h=p(d=>{let m=d.split(`
2
- `);if(m.length<=1)return d.trim();let y=m.filter(u=>u.trim().length>0);if(y.length===0)return"";let C=y.reduce((u,w)=>{let I=w.match(/^([ \t]*)/),x=I?I[1].length:0;return x<u?x:u},1/0);return m.map(u=>u.length>=C?u.slice(C):u.trimStart()).join(`
3
- `).trim()},"processResult");return n==="all"?l.map(m=>h(m.content)).join(`
4
- `):l.map(m=>h(m.innerContent)).join(`
5
- `)}return i}static _processImportBlocks(t){let e=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,s=[];return{processed:t.replace(e,(o,a,i)=>{let r={},c=/(\w+)="([^"]*)"/g;if(i)for(let m of i.matchAll(c))r[m[1]]=m[2];let l=r.src;if(!l)return"";let h;r.block&&(r.block==="all"?h="all":r.block.includes(",")?h=r.block.split(",").map(m=>m.trim()).filter(m=>m):h=r.block);let d={src:l,blocks:h,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:a||""};return s.push(d),`${a}__IMPORT_${s.length-1}__`}),imports:s}}static processImportBlocks(t,e,s=0,n){if(s>10)return"";let{processed:o,imports:a}=this._processImportBlocks(t),i=o;for(let r=0;r<a.length;r++){let c=a[r],l=`${c.src}|${c.base}|${c.lang||""}|${c.section}|${Array.isArray(c.blocks)?c.blocks.join(","):c.blocks||""}`,h;if(n&&n.has(l))h=n.get(l);else{let m=e(c.src);h=m?this._extractBlock(m,c.blocks,c.base,c.section,c.lang):"",h&&h.includes("<import")&&(h=this.processImportBlocks(h,e,s+1,n)),n&&n.set(l,h)}let d=h.split(`
1
+ "use strict";var gt=Object.create;var D=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var yt=Object.getOwnPropertyNames;var ft=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var p=(g,t)=>D(g,"name",{value:t,configurable:!0});var Tt=(g,t)=>{for(var e in t)D(g,e,{get:t[e],enumerable:!0})},tt=(g,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of yt(t))!Ct.call(g,n)&&n!==e&&D(g,n,{get:()=>t[n],enumerable:!(s=ut(t,n))||s.enumerable});return g};var et=(g,t,e)=>(e=g!=null?gt(ft(g)):{},tt(t||!g||!g.__esModule?D(e,"default",{value:g,enumerable:!0}):e,g)),St=g=>tt(D({},"__esModule",{value:!0}),g);var It={};Tt(It,{BlockKeyboard:()=>Q,CacheExternal:()=>A,Ctx:()=>B,Gramstax:()=>J,LabelKeyboard:()=>H,LoggingUtil:()=>L,TemplateEngine:()=>P,TemplateManager:()=>V,WorkerThreadExport:()=>z,WorkerThreadGatewayClient:()=>$,WorkerThreadGatewayServer:()=>E,WorkerThreadInit:()=>X,WorkerThreadLaunch:()=>W,WorkerThreadPool:()=>Y,WorkerThreadRpc:()=>k,log:()=>q});module.exports=St(It);var bt=p(()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,"getImportMetaUrl"),C=bt();var st=require("logging-pretty");var L=class extends st.LoggingPretty{static{p(this,"LoggingUtil")}constructor(t){super(t)}errorMake(t,e,s){this.error(`[${e?`${e}:${s}`:s}] ${this._formatErrorObj(t)}`)}_formatErrorObj(t){return JSON.stringify(t instanceof Error?{message:t.message,stack:t.stack,name:t.name}:t,null,2)}},q=new L;var nt=require("keyv"),it=et(require("@keyv/redis"),1);var A=class extends nt.Keyv{constructor(e="memory",s,n,o){let a;e.startsWith("redis")&&(a=new it.default(e)),e==="memory"&&(a=new Map),o?.forceStore&&(a=o.forceStore);super({store:a,namespace:n,ttl:s});this.url=e}static{p(this,"CacheExternal")}refreshLruCache(e){let s=this.store,n=this.opts.namespace?this.opts.namespace?.length+1:null,o=s.keys().toArray();for(let a=0;a<o.length;a++){let i=o[a];if(a==e)return;this.get(n?i.slice(n):i)}}};var U=require("timers/promises"),v=require("grammy");var B=class{static{p(this,"Ctx")}static template;static data;data=this.constructor.data;get userIsPremium(){return this.ct.from?.is_premium??!1}get userIsBot(){return this.ct.from?.is_bot??!1}get userId(){return this.ct.from?.id}get userName(){return this.ct.from?.username}get userFullName(){return`${this.ct.from?.first_name} ${this.ct.from?.last_name||""}`}get userFirstName(){return this.ct.from?.first_name}get userLastName(){return this.ct.from?.last_name}get userLanguage(){return this.ct.from?.language_code}set userLanguage(t){this.ct.from.language_code=t}get msgText(){return this.ct.message?.text}get msgTextPayloads(){return this.getPayloads(this.msgText,"space",this.data?._positionPayloadText||this.temp?.data?._positionPayloadText)}get msgTextPayload(){return this.msgTextPayloads[0]}get msgTextCommandPayloads(){return this.getPayloads(this.msgText,"space")}get msgTextCommandPayload(){return this.msgTextCommandPayloads[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionPayloads(){return this.getPayloads(this.msgCaption,"space")}get msgCaptionPayload(){return this.msgCaptionPayloads[0]}get msgCaptionCommandPayloads(){return this.getPayloads(this.msgCaption,"space")}get msgCaptionCommandPayload(){return this.msgCaptionCommandPayloads[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get msgDocument(){return this.ct.message?.document}get msgAnimation(){return this.ct.message?.animation}get msgVoice(){return this.ct.message?.voice}get msgVideoNote(){return this.ct.message?.video_note}get msgSticker(){return this.ct.message?.sticker}get msgLocation(){return this.ct.message?.location}get msgContact(){return this.ct.message?.contact}get msgWebAppData(){return this.ct.message?.web_app_data}get msgGift(){return this.ct.message?.gift}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataPayloads(){return this.getPayloads(this.callbackData,"colon")}get callbackDataPayload(){return this.callbackDataPayloads?.[0]}get session(){return this.temp.session}set session(t){this.temp.session=t}ct;cacheSession;cacheKeyboard;templateManager;temp;constructor(t){this.ct=t.ct,this.cacheSession=t.cacheSession,this.cacheKeyboard=t.cacheKeyboard,this.templateManager=t.templateManager,this.temp=t.temp}async broadcast(t,e,s,n,o,a,i=!1){try{this.temp.isAnswer=!0;let r=30,c=e.map(h=>this.templateManager.getMessage(this.data.name,o,h,n));for(let h=0;h<t.length;h++){let l=t[h],d=c[h];await this.ct.api.sendMessage(l,d,{parse_mode:"HTML",reply_markup:s,...a}),h+1==r&&await(0,U.setTimeout)(1200)}}catch(r){if(i)throw r}}async broadcastMedia(t,e,s,n,o,a,i=!1){try{this.temp.isAnswer=!0;let r=30,c=e.map(h=>this.templateManager.getMedia(this.data.name,o,h,n));for(let h=0;h<t.length;h++){let l=t[h],d=c[h];if(!d)continue;let m={parse_mode:"HTML",reply_markup:s,...a};d.type=="photo"&&await this.ct.api.sendPhoto(l,d.src,{caption:d.caption,...m}),d.type=="video"&&await this.ct.api.sendVideo(l,d.src,{caption:d.caption,...m}),d.type=="audio"&&await this.ct.api.sendAudio(l,d.src,{caption:d.caption,...m}),d.type=="document"&&await this.ct.api.sendDocument(l,d.src,{caption:d.caption,...m}),d.type=="animation"&&await this.ct.api.sendAnimation(l,d.src,{caption:d.caption,...m}),d.type=="voice"&&await this.ct.api.sendVoice(l,d.src,m),d.type=="video_note"&&await this.ct.api.sendVideoNote(l,d.src,m),d.type=="sticker"&&await this.ct.api.sendSticker(l,d.src,m),d.type=="location"&&await this.ct.api.sendLocation(l,parseInt(d.latitude),parseInt(d.longitude),m),d.type=="contact"&&await this.ct.api.sendContact(l,d.phone,d.first_name,{vcard:d.vcard,...m}),h+1==r&&await(0,U.setTimeout)(1200)}}catch(r){if(i)throw r}}async reply(t,e,s,n){this.temp.isAnswer=!0;let o=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.reply(o,{parse_mode:"HTML",reply_markup:t,...n})}async replyMedia(t,e,s,n,o){this.temp.isAnswer=!0;let a=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s),i={parse_mode:"HTML",reply_markup:e,...o};if(t=="photo")return await this.ct.replyWithPhoto(a.src,{caption:a.caption,...i});if(t=="video")return await this.ct.replyWithVideo(a.src,{caption:a.caption,...i});if(t=="audio")return await this.ct.replyWithAudio(a.src,{caption:a.caption,...i});if(t=="document")return await this.ct.replyWithDocument(a.src,{caption:a.caption,...i});if(t=="animation")return await this.ct.replyWithAnimation(a.src,{caption:a.caption,...i});if(t=="voice")return await this.ct.replyWithVoice(a.src,i);if(t=="video_note")return await this.ct.replyWithVideoNote(a.src,i);if(t=="sticker")return await this.ct.replyWithSticker(a.src,i);if(t=="location")return await this.ct.replyWithLocation(parseInt(a.latitude),parseInt(a.longitude),i);if(t=="contact")return await this.ct.replyWithContact(a.phone,a.first_name,{vcard:a.vcard,...i})}async replyPhoto(t,e,s,n){return this.replyMedia("photo",t,e,s,n)}async replyVideo(t,e,s,n){return this.replyMedia("video",t,e,s,n)}async replyAudio(t,e,s,n){return this.replyMedia("audio",t,e,s,n)}async replyDocument(t,e,s,n){return this.replyMedia("document",t,e,s,n)}async replyAnimation(t,e,s,n){return this.replyMedia("animation",t,e,s,n)}async replyVoice(t,e,s,n){return this.replyMedia("voice",t,e,s,n)}async replyVideoNote(t,e,s,n){return this.replyMedia("video_note",t,e,s,n)}async replySticker(t,e,s,n){return this.replyMedia("sticker",t,e,s,n)}async replyLocation(t,e,s,n){return this.replyMedia("location",t,e,s,n)}async replyContact(t,e,s,n){return this.replyMedia("contact",t,e,s,n)}async replyAction(t){return await this.ct.replyWithChatAction(t)}async edit(t,e,s,n,o=!0){try{this.temp.isAnswer=!0;let a=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.editMessageText(a,{parse_mode:"HTML",reply_markup:t,...n})}catch(a){if(o)await this.reply(t,e,s,n);else throw a}}async editMedia(t,e,s,n,o,a,i=!0){try{this.temp.isAnswer=!0;let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s);return t=="voice"?(await this.delete(),await this.replyVoice(e,s,n,o)):t=="video_note"?(await this.delete(),await this.replyVoice(e,s,n,o)):t=="sticker"?(await this.delete(),await this.replySticker(e,s,n,o)):t=="location"?(await this.delete(),await this.replyLocation(e,s,n,o)):t=="contact"?(await this.delete(),await this.replyContact(e,s,n,o)):await this.ct.editMessageMedia({media:r,caption:c,type:t,parse_mode:"HTML",...o},{reply_markup:e,...a})}catch(r){if(i===!0)await this.reply(e,s,n,a);else throw r}}async editPhoto(t,e,s,n,o){return await this.editMedia("photo",t,e,s,n,o)}async editVideo(t,e,s,n,o){return await this.editMedia("video",t,e,s,n,o)}async editAudio(t,e,s,n,o){return await this.editMedia("audio",t,e,s,n,o)}async editDocument(t,e,s,n,o){return await this.editMedia("document",t,e,s,n,o)}async editAnimation(t,e,s,n,o){return await this.editMedia("animation",t,e,s,n,o)}async editVoice(t,e,s,n){return await this.editMedia("voice",t,e,s,n)}async editVideoNote(t,e,s,n){return await this.editMedia("video_note",t,e,s,n)}async editSticker(t,e,s,n){return await this.editMedia("sticker",t,e,s,n)}async editLocation(t,e,s,n){return await this.editMedia("location",t,e,s,n)}async editContact(t,e,s,n){return await this.editMedia("contact",t,e,s,n)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(t){try{return this.temp.isAnswer=!0,await this.ct.answerCallbackQuery(t)}catch{return null}}async sessionSet(t,e,s){try{let n={method:t,params:e,...s},o=await this.cacheSession.set(`${this.userId}`,n);return o&&(this.session=n),o}catch{return null}}async sessionGet(){try{let t=await this.cacheSession.get(`${this.userId}`);return t&&(this.session=t),t||null}catch{return null}}async sessionClear(){try{let t=await this.cacheSession.delete(`${this.userId}`);return t&&(this.session={}),t}catch{return null}}static buildData(t){let s=typeof t=="function"?{callback:t}:t||{},n=s.callback,o=this.prototype.addPayloads.bind(this.prototype),a=s.name||"";return{name:a,intentText:s.intentText||a,intentTextCommand:s.intentTextCommand||a,intentCallback:a,callback:n?function(...r){return o(this.intentCallback,"colon",n(...r))}:function(){return this?.intentCallback},_positionPayloadText:s.intentText?s.intentText.split(this.prototype.getSeperatorTag("space")).length:void 0}}keyboardCols(t,e,s,n){let[o,a]=s.split("-"),i=parseInt(o),r=a?parseInt(a):null,c=e.length,h=t;for(let l=0;l<c;l++){let d=e[l];if(n(d,l),r===null)(l+1)%i===0&&l<c-1&&h.row();else{let m=c-(l+1);(m===r||m>r&&(l+1)%i===0)&&h.row()}}return t}bottomKeyboardT(t="1",e,s){return this.bottomKeyboard((n,o)=>this.keyboardCols(n,o,t,a=>n.text(a)),{baseId:e??void 0,data:s})}inlineKeyboardT(t,e="1",s,n){return this.inlineKeyboard((o,a)=>this.keyboardCols(o,a,e,(i,r)=>{let c=t[r],h=typeof c=="string"?c:c.data.callback();o.text(i,h)}),{baseId:s??void 0,data:n})}inlineKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let i=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(i);if(!r){let c=new v.InlineKeyboard,h=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data),l=t(c,h);return this.cacheKeyboard.set(i,l),l}return r}let n=new v.InlineKeyboard,o=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data);return t(n,o)}bottomKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let i=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(i);if(!r){let c=new v.Keyboard,h=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),l=t(c,h);return l.resized(!0),this.cacheKeyboard.set(i,l),l}return r}let n=new v.Keyboard,o=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),a=t(n,o);return a.resized(),a}getSeperatorTag(t="space"){return t=="space"?" ":":"}havePayloads(t="",e){return t.includes(this.getSeperatorTag(e))}addPayloads(t="",e,s){let n=this.getSeperatorTag(e),o="";for(let a=0;a<s.length;a++){let i=s[a];i!=null&&i!==""&&(o+=n+i)}return t+o}getPayloads(t="",e,s=1){if(!t)return[];let n=this.getSeperatorTag(e);return t.split(n).slice(s)}getIntent(t="",e,s=1){if(!t)return"";let n=this.getSeperatorTag(e),o=t.split(n);return s==1?o[0]:o.slice(0,s).join(n)}isSessionCallback(t,e){return(t??this.session.method)===this.methodSessionCallback(e)}isSessionCallbackPayload(t,e){return(t??this.session.method)===this.methodSessionCallbackPayload(e)}isSessionText(t,e){return(t??this.session.method)===this.methodSessionText(e)}isSessionTextPayload(t,e){return(t??this.session.method)===this.methodSessionTextPayload(e)}isSessionTextCommand(t,e){return(t??this.session.method)===this.methodSessionTextCommand(e)}isSessionTextCommandPayload(t,e){return(t??this.session.method)===this.methodSessionTextCommandPayload(e)}isSessionTextFree(t,e){return(t??this.session.method)===this.methodSessionTextFree(e)}isSessionPhotoCaption(t,e){return(t??this.session.method)===this.methodSessionPhotoCaption(e)}isSessionPhotoCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionPayload(e)}isSessionPhotoCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionCommand(e)}isSessionPhotoCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionCommandPayload(e)}isSessionPhotoFree(t,e){return(t??this.session.method)===this.methodSessionPhotoFree(e)}isSessionVideoCaption(t,e){return(t??this.session.method)===this.methodSessionVideoCaption(e)}isSessionVideoCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionPayload(e)}isSessionVideoCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionCommand(e)}isSessionVideoCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionCommandPayload(e)}isSessionVideoFree(t,e){return(t??this.session.method)===this.methodSessionVideoFree(e)}isSessionAudioCaption(t,e){return(t??this.session.method)===this.methodSessionAudioCaption(e)}isSessionAudioCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionPayload(e)}isSessionAudioCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionCommand(e)}isSessionAudioCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionCommandPayload(e)}isSessionAudioFree(t,e){return(t??this.session.method)===this.methodSessionAudioFree(e)}isSessionDocumentCaption(t,e){return(t??this.session.method)===this.methodSessionDocumentCaption(e)}isSessionDocumentCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionPayload(e)}isSessionDocumentCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionCommand(e)}isSessionDocumentCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionCommandPayload(e)}isSessionDocumentFree(t,e){return(t??this.session.method)===this.methodSessionDocumentFree(e)}isSessionAnimationCaption(t,e){return(t??this.session.method)===this.methodSessionAnimationCaption(e)}isSessionAnimationCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionPayload(e)}isSessionAnimationCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionCommand(e)}isSessionAnimationCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionCommandPayload(e)}isSessionAnimationFree(t,e){return(t??this.session.method)===this.methodSessionAnimationFree(e)}isSessionVoiceCaption(t,e){return(t??this.session.method)===this.methodSessionVoiceCaption(e)}isSessionVoiceCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionPayload(e)}isSessionVoiceCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionCommand(e)}isSessionVoiceCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionCommandPayload(e)}isSessionVoiceFree(t,e){return(t??this.session.method)===this.methodSessionVoiceFree(e)}isSessionVideoNoteFree(t,e){return(t??this.session.method)===this.methodSessionVideoNoteFree(e)}isSessionStickerFree(t,e){return(t??this.session.method)===this.methodSessionStickerFree(e)}isSessionLocationFree(t,e){return(t??this.session.method)===this.methodSessionLocationFree(e)}isSessionContactFree(t,e){return(t??this.session.method)===this.methodSessionContactFree(e)}sessionCallback(t,e){return this.sessionSet(this.methodSessionCallback(e),t)}sessionCallbackPayload(t,e){return this.sessionSet(this.methodSessionCallbackPayload(e),t)}sessionText(t,e){return this.sessionSet(this.methodSessionText(e),t)}sessionTextPayload(t,e){return this.sessionSet(this.methodSessionTextPayload(e),t)}sessionTextCommand(t,e){return this.sessionSet(this.methodSessionTextCommand(e),t)}sessionTextCommandPayload(t,e){return this.sessionSet(this.methodSessionTextCommandPayload(e),t)}sessionTextFree(t,e){return this.sessionSet(this.methodSessionTextFree(e),t)}sessionPhotoCaption(t,e){return this.sessionSet(this.methodSessionPhotoCaption(e),t)}sessionPhotoCaptionPayload(t,e){return this.sessionSet(this.methodSessionPhotoCaptionPayload(e),t)}sessionPhotoCaptionCommand(t,e){return this.sessionSet(this.methodSessionPhotoCaptionCommand(e),t)}sessionPhotoCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionPhotoCaptionCommandPayload(e),t)}sessionPhotoFree(t,e){return this.sessionSet(this.methodSessionPhotoFree(e),t)}sessionVideoCaption(t,e){return this.sessionSet(this.methodSessionVideoCaption(e),t)}sessionVideoCaptionPayload(t,e){return this.sessionSet(this.methodSessionVideoCaptionPayload(e),t)}sessionVideoCaptionCommand(t,e){return this.sessionSet(this.methodSessionVideoCaptionCommand(e),t)}sessionVideoCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVideoCaptionCommandPayload(e),t)}sessionVideoFree(t,e){return this.sessionSet(this.methodSessionVideoFree(e),t)}sessionAudioCaption(t,e){return this.sessionSet(this.methodSessionAudioCaption(e),t)}sessionAudioCaptionPayload(t,e){return this.sessionSet(this.methodSessionAudioCaptionPayload(e),t)}sessionAudioCaptionCommand(t,e){return this.sessionSet(this.methodSessionAudioCaptionCommand(e),t)}sessionAudioCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionAudioCaptionCommandPayload(e),t)}sessionAudioFree(t,e){return this.sessionSet(this.methodSessionAudioFree(e),t)}sessionDocumentCaption(t,e){return this.sessionSet(this.methodSessionDocumentCaption(e),t)}sessionDocumentCaptionPayload(t,e){return this.sessionSet(this.methodSessionDocumentCaptionPayload(e),t)}sessionDocumentCaptionCommand(t,e){return this.sessionSet(this.methodSessionDocumentCaptionCommand(e),t)}sessionDocumentCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionDocumentCaptionCommandPayload(e),t)}sessionDocumentFree(t,e){return this.sessionSet(this.methodSessionDocumentFree(e),t)}sessionAnimationCaption(t,e){return this.sessionSet(this.methodSessionAnimationCaption(e),t)}sessionAnimationCaptionPayload(t,e){return this.sessionSet(this.methodSessionAnimationCaptionPayload(e),t)}sessionAnimationCaptionCommand(t,e){return this.sessionSet(this.methodSessionAnimationCaptionCommand(e),t)}sessionAnimationCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionAnimationCaptionCommandPayload(e),t)}sessionAnimationFree(t,e){return this.sessionSet(this.methodSessionAnimationFree(e),t)}sessionVoiceCaption(t,e){return this.sessionSet(this.methodSessionVoiceCaption(e),t)}sessionVoiceCaptionPayload(t,e){return this.sessionSet(this.methodSessionVoiceCaptionPayload(e),t)}sessionVoiceCaptionCommand(t,e){return this.sessionSet(this.methodSessionVoiceCaptionCommand(e),t)}sessionVoiceCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVoiceCaptionCommandPayload(e),t)}sessionVoiceFree(t,e){return this.sessionSet(this.methodSessionVoiceFree(e),t)}sessionVideoNoteFree(t,e){return this.sessionSet(this.methodSessionVideoNoteFree(e),t)}sessionStickerFree(t,e){return this.sessionSet(this.methodSessionStickerFree(e),t)}sessionLocationFree(t,e){return this.sessionSet(this.methodSessionLocationFree(e),t)}sessionContactFree(t,e){return this.sessionSet(this.methodSessionContactFree(e),t)}methodSession(t,e){return`${t}-${e||this.data.name}`}methodSessionCallback(t){return this.methodSession("1",t)}methodSessionCallbackPayload(t){return this.methodSession("2",t)}methodSessionText(t){return this.methodSession("3",t)}methodSessionTextPayload(t){return this.methodSession("4",t)}methodSessionTextCommand(t){return this.methodSession("5",t)}methodSessionTextCommandPayload(t){return this.methodSession("6",t)}methodSessionTextFree(t){return this.methodSession("7",t)}methodSessionPhotoCaption(t){return this.methodSession("8",t)}methodSessionPhotoCaptionPayload(t){return this.methodSession("9",t)}methodSessionPhotoCaptionCommand(t){return this.methodSession("10",t)}methodSessionPhotoCaptionCommandPayload(t){return this.methodSession("11",t)}methodSessionPhotoFree(t){return this.methodSession("12",t)}methodSessionVideoCaption(t){return this.methodSession("13",t)}methodSessionVideoCaptionPayload(t){return this.methodSession("14",t)}methodSessionVideoCaptionCommand(t){return this.methodSession("15",t)}methodSessionVideoCaptionCommandPayload(t){return this.methodSession("16",t)}methodSessionVideoFree(t){return this.methodSession("17",t)}methodSessionAudioCaption(t){return this.methodSession("18",t)}methodSessionAudioCaptionPayload(t){return this.methodSession("19",t)}methodSessionAudioCaptionCommand(t){return this.methodSession("20",t)}methodSessionAudioCaptionCommandPayload(t){return this.methodSession("21",t)}methodSessionAudioFree(t){return this.methodSession("22",t)}methodSessionDocumentCaption(t){return this.methodSession("23",t)}methodSessionDocumentCaptionPayload(t){return this.methodSession("24",t)}methodSessionDocumentCaptionCommand(t){return this.methodSession("25",t)}methodSessionDocumentCaptionCommandPayload(t){return this.methodSession("26",t)}methodSessionDocumentFree(t){return this.methodSession("27",t)}methodSessionAnimationCaption(t){return this.methodSession("28",t)}methodSessionAnimationCaptionPayload(t){return this.methodSession("29",t)}methodSessionAnimationCaptionCommand(t){return this.methodSession("30",t)}methodSessionAnimationCaptionCommandPayload(t){return this.methodSession("31",t)}methodSessionAnimationFree(t){return this.methodSession("32",t)}methodSessionVoiceCaption(t){return this.methodSession("33",t)}methodSessionVoiceCaptionPayload(t){return this.methodSession("34",t)}methodSessionVoiceCaptionCommand(t){return this.methodSession("35",t)}methodSessionVoiceCaptionCommandPayload(t){return this.methodSession("36",t)}methodSessionVoiceFree(t){return this.methodSession("37",t)}methodSessionVideoNoteFree(t){return this.methodSession("38",t)}methodSessionStickerFree(t){return this.methodSession("39",t)}methodSessionLocationFree(t){return this.methodSession("40",t)}methodSessionContactFree(t){return this.methodSession("41",t)}};var j=require("path"),O=require("fs"),ot=require("module");var b=class{static{p(this,"PageManager")}static _getFile(t,e,s=0){let o=Object.values(t)[s];if(o===void 0)throw new Error(`File ${e} must have export (not default) class page`);return o}static getFilePath(){return(0,j.join)(process.cwd(),"src","pages")}static getFileSync(t,e=0){t||(t=this.getFilePath());let n=(0,ot.createRequire)(t)(t);return this._getFile(n,t,e)}static async getFile(t,e=0){t||(t=this.getFilePath());let s=await import(`${t}?t=${Date.now()}`);return this._getFile(s,t,e)}static getFileManySync(t,e=0){if(t||(t=this.getFilePath()),!(0,O.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,O.readdirSync)(t).map(n=>{let o=(0,j.join)(t,n);return{path:o,page:this.getFileSync(o,e)}})}static clearCacheRequire(t){if(t||(t=this.getFilePath()),!(0,O.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,O.readdirSync)(t).forEach(s=>{let n=(0,j.join)(t,s);delete require.cache[require.resolve(n)]}),!0}};var rt=require("fs"),ct=require("url"),w=require("path");var S=require("path"),f=require("fs"),at=require("chokidar");var P=class{static{p(this,"TemplateEngine")}static _escape(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processScopeVariables(t){return t.replace(/\{\{(\w+)\}\}/g,(e,s)=>`\${(data && data["${s}"]) ?? ""}`)}static _processScopeExec(t){return t.replace(/{~\s*([\s\S]*?)\s*~}/g,(e,s)=>`\${(() => { try { return ${s} } catch(e) { try { with(data || {}) { return ${s} } } catch(ee) { return '' } } })()}`)}static _processBaseBlocks(t){let e=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,s={};for(let n of t.matchAll(e)){let o=n[2]??"default",i=(n[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[o]=i}return s}static _processScriptBlocks(t){return t.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(e,s)=>{let n=s.trim();return n?`\${(() => { if (!data) return ''; try { with(data) { ${n} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(t){return t.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(t){return t.replace(/<div>([\s\S]*?)<\/div>/gi,(e,s)=>s.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(t){let e=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return t.replace(e,(s,n,o)=>{if(!n)return"";let a="",i=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=i.exec(o))!==null;){let l=(c[1]||"").split(",").map(m=>m.trim()),d=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");l.forEach(m=>{a+=`case "${m}": `}),a+=`return \`${d}\`; `}let h=r.exec(o);if(h){let l=(h[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();a+=`default: return \`${l}\`; `}else a+="default: return ''; ";return`\${(() => { switch((data && data["${n}"])) { ${a} } })()}`})}static _processMapBlocks(t){let e=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return t.replace(e,(s,n,o)=>{let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(i))a[d[1]]=d[2];let r=a.src;if(!r)return"";let c=a.join??"\\n",h=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");h=h.replace(/\{\{([\w.]+)\}\}/g,(d,m)=>m==="e"||m.startsWith("e.")?`\${${m}}`:m==="i"?"${i}":d);let l=c.replace(/"/g,'\\"');return`\${(data && data["${r}"] || []).map((e, i) => \`${h}\`).join("${l}")}`})}static _processMediaBlocks(t){let e=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let n of t.matchAll(e)){let o=n[1],a=n[2],i={},r=/(\w+)="([^"]*)"/g;if(o)for(let m of o.matchAll(r))i[m[1]]=m[2];let c=i.lang||"default",h=i.type,l=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),d={type:h};i.src&&(d.src=i.src),l&&h!=="video_note"&&h!=="sticker"&&(d.caption=l),h==="location"&&(i.latitude&&(d.latitude=i.latitude),i.longitude&&(d.longitude=i.longitude),l&&(d.caption=l)),h==="contact"&&(i.phone&&(d.phone=i.phone),i.first_name&&(d.first_name=i.first_name),i.last_name&&(d.last_name=i.last_name),i.vcard&&(d.vcard=i.vcard),l&&(d.caption=l)),s[c]=d}return s}static _processMessageBlocks(t){let e=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,n,o]of t.matchAll(e)){let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let h of n.matchAll(i))a[h[1]]=h[2];let r=a.lang||"default",c=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=c}return s}static _processDescriptionBlocks(t){let e=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,n,o]of t.matchAll(e)){let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let l of n.matchAll(i))a[l[1]]=l[2];let r=a.lang||"default",c=a.scope||"default",h=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][c]=h}return s}static _processKeyboardBlocks(t){let e=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,n,o]of t.matchAll(e)){let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let l of n.matchAll(i))a[l[1]]=l[2];let r=a.lang||"default",c=a.type==="bottom"?"bottom":"inline",h=o.trim();s[r]||(s[r]={}),s[r][c]=h}return s}static _compileToFunction(t,e){let s;e?s=t.map(a=>`\`${a}\``).join(","):s=`\`${t}\``;let n=s;if(n=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(n))),e){let o=`return [${n}]`;return new Function("data",o)}else{let o=`return ${n}`;return new Function("data",o)}}static compileBlockMedia(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processMediaBlocks(a);n[o]={};for(let[r,c]of Object.entries(i)){let h={};for(let[l,d]of Object.entries(c)){if(l==="type"||typeof d!="string")continue;let m=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));h[l]=this._compileToFunction(m,!1)}n[o][r]=l=>{let d={...c};for(let[m,y]of Object.entries(h))d[m]=y(l);return d}}}return n}static compileBlockMessage(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processMessageBlocks(a);n[o]={};for(let[r,c]of Object.entries(i)){let h=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));n[o][r]=this._compileToFunction(h,!1)}}return n}static compileBlockDescription(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processDescriptionBlocks(a);n[o]={};for(let[r,c]of Object.entries(i))for(let[h,l]of Object.entries(c)){n[o][h]||(n[o][h]={});let d=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(l)))));n[o][h][r]=this._compileToFunction(d,!1)}}return n}static compileBlockKeyboards(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processKeyboardBlocks(a);n[o]={};for(let[r,c]of Object.entries(i)){n[o][r]={};for(let[h,l]of Object.entries(c)){let m=l.split(/(?<!\\),\s*/).map(y=>y.replace(/\\,/g,",").trim()).map(y=>this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(y))))));n[o][r][h]=this._compileToFunction(m,!0)}}}return n}static _extractBlock(t,e,s="default",n="all",o){let a=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,i=t,r=!1;for(let c of t.matchAll(a))if((c[2]??"default")===s){i=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(t);if(!(s==="default"&&!c))return""}if(e){if(e==="all")return i;let c=Array.isArray(e)?e:[e],h=[];for(let d of c){let m=new RegExp(`([ \\t]*)<${d}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${d}>`,"gi");for(let y of i.matchAll(m)){let T=y[2];if(o){let u=/lang="([^"]*)"/i,I=T?.match(u);if(((I?I[1]:void 0)||"default")!==o)continue}h.push({start:y.index,content:y[0],innerContent:y[3]??""})}}h.sort((d,m)=>d.start-m.start);let l=p(d=>{let m=d.split(`
2
+ `);if(m.length<=1)return d.trim();let y=m.filter(u=>u.trim().length>0);if(y.length===0)return"";let T=y.reduce((u,I)=>{let x=I.match(/^([ \t]*)/),_=x?x[1].length:0;return _<u?_:u},1/0);return m.map(u=>u.length>=T?u.slice(T):u.trimStart()).join(`
3
+ `).trim()},"processResult");return n==="all"?h.map(m=>l(m.content)).join(`
4
+ `):h.map(m=>l(m.innerContent)).join(`
5
+ `)}return i}static _processImportBlocks(t){let e=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,s=[];return{processed:t.replace(e,(o,a,i)=>{let r={},c=/(\w+)="([^"]*)"/g;if(i)for(let m of i.matchAll(c))r[m[1]]=m[2];let h=r.src;if(!h)return"";let l;r.block&&(r.block==="all"?l="all":r.block.includes(",")?l=r.block.split(",").map(m=>m.trim()).filter(m=>m):l=r.block);let d={src:h,blocks:l,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:a||""};return s.push(d),`${a}__IMPORT_${s.length-1}__`}),imports:s}}static processImportBlocks(t,e,s=0,n){if(s>10)return"";let{processed:o,imports:a}=this._processImportBlocks(t),i=o;for(let r=0;r<a.length;r++){let c=a[r],h=`${c.src}|${c.base}|${c.lang||""}|${c.section}|${Array.isArray(c.blocks)?c.blocks.join(","):c.blocks||""}`,l;if(n&&n.has(h))l=n.get(h);else{let m=e(c.src);l=m?this._extractBlock(m,c.blocks,c.base,c.section,c.lang):"",l&&l.includes("<import")&&(l=this.processImportBlocks(l,e,s+1,n)),n&&n.set(h,l)}let d=l.split(`
6
6
  `).map((m,y)=>y===0?m:c.indent+m).join(`
7
- `);i=i.replace(`__IMPORT_${r}__`,d)}return i}};var B=class{static{p(this,"TemplateManager")}_map=new Map;_engine=k;_watcher=[];_pageManager=P;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(t){let{path:e,enableWatch:s=!1}=t;this._path=e,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(t.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let t=0;t<this._path.length;t++){let e=this._path[t];if(!(0,f.existsSync)(e))throw new Error(`Template base path is not exists: ${e}`);if(!(0,f.statSync)(e).isDirectory())throw new Error(`Template base path is not a directory: ${e}`)}return!0}catch(t){throw new Error(`Failed to validate Template base path: ${String(t)}`)}}_initializeWatcher(t){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let e=0;e<this._path.length;e++){let s=this._path[e],n=(0,at.watch)(s,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...t});this._watcher[e]=n,n.on("change",this._handleFileChange.bind(this)),n.on("add",this._handleFileAdd.bind(this)),n.on("unlink",this._handleFileDelete.bind(this)),n.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(t){let e=(0,b.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileAdd(t){let e=(0,b.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileDelete(t){let e=(0,b.basename)(t),s=this._getKey(e);this._map.has(s)&&this._map.delete(s)}_handleWatchError(t){}_loadAllFiles(){let t=new Map,e=[];for(let n=0;n<this._path.length;n++){let o=this._path[n],i=(0,f.readdirSync)(o,"utf8").filter(r=>this._isValidFile(r));for(let r of i){let c=(0,b.join)(o,r),l=this._getExtension(r),h=this._getKey(r);if(l===".html")t.set(h,(0,f.readFileSync)(c,"utf8"));else if(l===".ts"||l===".js"){let d=P.getFileSync(c);d?.template!==void 0&&(t.set(h,d.template),e.push(d))}}}let s=new Map;for(let[n,o]of t.entries())this._compile(n,o,void 0,s,t);t.clear(),s.clear();for(let n of e)n.template=void 0}_loadFile(t){for(let e=0;e<this._path.length;e++){let s=this._path[e],n=(0,b.join)(s,t),o=this._getExtension(t),a=this._getKey(t);if(o==".html"){let i=(0,f.readFileSync)(n,"utf8");this._compile(a,i)}else if(o==".ts"||o==".js"){let i=P.getFileSync(n);i?.template!==void 0&&(this._compile(a,i.template),i.template=void 0)}else throw new Error(`File ${t} is not support`)}}_getExtension(t){return(0,b.extname)(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let s=(0,b.extname)(t).toLowerCase();if(s){let i=(0,b.join)(e,t);if((0,f.existsSync)(i)&&(0,f.statSync)(i).isFile()){if(s===".html")return(0,f.readFileSync)(i,"utf8");if(s===".ts"||s===".js")try{return P.getFileSync(i)?.template??null}catch{return null}}continue}let n=(0,b.join)(e,`${t}.ts`),o=(0,b.join)(e,`${t}.js`);if((0,f.existsSync)(n)&&(0,f.statSync)(n).isFile())try{return P.getFileSync(n)?.template??null}catch{}else if((0,f.existsSync)(o)&&(0,f.statSync)(o).isFile())try{return P.getFileSync(n)?.template??null}catch{}let a=(0,b.join)(e,`${t}.html`);if((0,f.existsSync)(a)&&(0,f.statSync)(a).isFile())return(0,f.readFileSync)(a,"utf8")}return null}_isValidFile(t){return this._supportedExtensions.has(this._getExtension(t))}_getKey(t){return t.replace(/\.[^/.]+$/,"")}_compile(t,e,s,n,o){let a=this._map.get(t),i=a||{},r=!1,c=k.processImportBlocks(e,h=>o&&o.has(h)?o.get(h):this._readTemplateFile(h),0,n),l=k._processBaseBlocks(c);(s===void 0||s?.media===!1||a?.media===void 0)&&(i.media=k.compileMedia(c,l),r=!0),(s===void 0||s?.message===!1||a?.message===void 0)&&(i.message=k.compileMessages(c,l),r=!0),(s===void 0||s?.keyboard===!1||a?.keyboard===void 0)&&(i.keyboard=k.compileKeyboards(c,l),r=!0),(s===void 0||s?.description===!1||a?.description===void 0)&&(i.description=k.compileDescription(c,l),r=!0),r&&this._map.set(t,i)}getMedia(t,e="default",s="default",n){let a=this._map.get(t)?.media?.[e],i=a?.[s]||a?.default;try{if(!i)throw new Error("Media function not found, please check your template");return i(n)}catch{return{}}}getMessage(t,e="default",s="default",n){try{let a=this._map.get(t)?.message?.[e],i=a?.[s]||a?.default;if(!i)throw"";return i(n)}catch{return""}}getDescription(t,e="default",s="default",n="default",o){try{let i=this._map.get(t)?.description?.[e]?.[n],r=i?.[s]||i?.default;if(!r)throw"";return r(o)}catch{return""}}getDescriptionLanguage(t,e="default",s="default"){try{let o=this._map.get(t)?.description?.[e]?.[s];return o?Object.keys(o):[]}catch{return[]}}getDescriptionScopes(t,e="default"){try{let n=this._map.get(t)?.description?.[e];return n?Object.keys(n):[]}catch{return[]}}getKeyboard(t,e="default",s="default",n="inline",o){try{let i=this._map.get(t)?.keyboard?.[e],r=i?.[s]?.[n]||i?.default?.[n];if(!r)throw[];return r(o)}catch{return[]}}async write(t,e){if(this._getExtension(t)!=".html")return null;for(let s=0;s<this._path.length;s++){let n=(0,b.join)(this._path[s],t);if((0,f.existsSync)(n))return(0,f.writeFileSync)(n,e,"utf8"),this._loadFile(t),!0}return null}has(t){return this._map.has(t)}async destroy(){if(this._watcher)for(let t of this._watcher)await t.close();this._map.clear()}};var W=require("grammy");var kt=(0,M.dirname)((()=>{try{return __filename}catch{return(0,ct.fileURLToPath)(S)}})()),Tt=JSON.parse((0,rt.readFileSync)((0,M.join)(kt,"../../package.json"),"utf-8")).version,J=class{static{p(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;optionsPage={shortCallbackData:!1};log;bot;handlerBotUpdate;constructor(t){if(!t?.token||t?.token?.length==0)throw new Error("Token is not valid or empty");if(typeof t.optionsPage?.shortCallbackData=="boolean"&&(this.optionsPage.shortCallbackData=t.optionsPage.shortCallbackData),this.log=t.log===!0?q:t.log?t.log:void 0,this.log?.info?.(`Gramstax v${Tt}`),this.cacheSession=t.cacheSession||new D("memory"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new B({path:[(0,M.join)(process.cwd(),"src","pages")]}),this.bot=this.createBot(t.token),this.bot.catch(this.onCatch),this.registerOnCallbackQueryData(),this.registerOnMessageText(),this.registerOnMessagePhoto(),this.registerOnMessageVideo(),this.registerOnMessageAudio(),this.registerOnMessageDocument(),this.registerOnMessageAnimation(),this.registerOnMessageVoice(),this.registerOnMessageVideoNote(),this.registerOnMessageSticker(),this.registerOnMessageLocation(),this.registerOnMessageContact(),this.handlerBotUpdate=this.bot.handleUpdate,this.pages=this.pageLoads(),process.once("SIGINT",()=>this.bot.stop()),process.once("SIGTERM",()=>this.bot.stop()),this.hookBeforeStart(),t.deploy.startsWith("polling"))this.runPolling();else if(t.deploy.startsWith("webhook:"))this.runWebhook(t.deploy.split("webhook:")[1]);else if(t.deploy.startsWith("serverless:"))this.runServerless(t.deploy.split("serverless:")[1]);else if(!t.deploy.startsWith("test"))throw new Error("Params deploy is not valid, expected: polling, webhook:<public-url>, serverless:<your-adapter>")}onCatch(t){if(this.log?.errorMake)this.log?.errorMake(t,"Bot","catch");else{let e=JSON.stringify(t,null,2);this.log?.error?.(`[Bot.catch]: ${e}`)}}hookBeforeStart(){}hookAfterStart(){}async onStart(t,e,s){await this.executeSyncBlocksDescription(this.pages);let{username:n}=t;this.log?.success?.(`Telegram bot polling started: ${n} ${e=="webhook"||e=="serverless"?`(${s})`:""}`),this.hookAfterStart()}createBot(t){return new W.Bot(t)}createCtx(t){return new V({ct:t,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{isAnswer:!1,session:{},data:{}}})}runPolling(){this.bot.start({onStart:p(t=>{this.onStart(t,"polling",null)},"onStart")})}async runWebhook(t){let{serve:e}=await import("bun"),s=(0,W.webhookCallback)(this.bot,"bun");this.handlerBotUpdate=s;let n=new URL(t).pathname;e({fetch(i){let{pathname:r}=new URL(i.url);if(i.method=="POST"&&r==n)return s(i);if(i.method=="GET"&&r=="/"){let c=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:c}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}}),(await this.bot.api.getWebhookInfo()).url!=t&&await this.bot.api.setWebhook(t);let a=await this.bot.api.getMe();await this.onStart(a,"webhook",t)}async runServerless(t){this.handlerBotUpdate=(0,W.webhookCallback)(this.bot,t);let e=await this.bot.api.getMe();await this.onStart(e,"serverless",t)}pageBuildData(t,e){t?.data===void 0&&(t.data=t.buildData());let{name:s}=(0,M.parse)(e);t.data.name||(t.data.name=s),t.data.intentText||(t.data.intentText=t.data.name),t.data.intentTextCommand||(t.data.intentTextCommand=t.data.name),t.data.intentCallback||(t.data.intentCallback=t.data.name)}pageSorts(t,e,s){let n=t.data.name,o=t.prototype,a="Payload",i="Command",r="Caption",c="Free",l=e.routeDynamic,h=e.routeDynamicSpesific,d=p(C=>C.charAt(0).toUpperCase()+C.slice(1),"upFirst"),m=p(C=>C.replace(a,"").replace(i,"").replace(r,"").replace(c,""),"getPureRouteName"),y=p((C,u)=>o[`methodSession${d(C)}`]?.(u),"methodSession");e.all[n]=t;for(let C=0;C<e.lenListRouteStaticSession;C++){let u=e.listRouteStaticSession[C];if(typeof o[u]!="function")continue;let w=e.routeStatic[u],I=e.routeStaticIntent[u],x=e.routeStaticSession[u],G={name:n,routeName:u},Z=w||I;if(Z!==void 0){let lt=u.includes(i),mt=u.includes("callback"),pt=u.startsWith("text"),v;if(lt){let _=t.data.intentTextCommand;v=_?`/${_}`:void 0}else if(mt){let _=t.data.intentCallback;this.optionsPage.shortCallbackData===!0&&(_=String(s),t.data.intentCallback=_),v=_}else pt?v=t.data.intentText:v=t.data.name;v&&(Z[v]=G)}x!==void 0&&(x[y(u,n)]=G),u.toLowerCase().endsWith("free")&&h[m(u)].push(G)}o.free&&l.push(n)}async executeSyncBlocksDescription(t){let e=new Map,s=t.routeStatic.textCommand;for(let[,n]of Object.entries(s)){let o=n.name,a=this.templateManager.getDescriptionScopes(o);for(let i of a){e.has(i)||e.set(i,new Set);let r=this.templateManager.getDescriptionLanguage(o,"default",i);for(let c of r)e.get(i).add(c)}}for(let[n,o]of e)for(let a of o){let i=[];for(let[,l]of Object.entries(s)){let h=l.name,d=this.templateManager.getDescription(h,"default",a,n);d&&i.push({command:h,description:d})}if(i.length===0)continue;let r={type:n},c=a==="default"?void 0:a;try{let l=await this.bot.api.getMyCommands({scope:r,language_code:c}),h=JSON.stringify(l.map(m=>({command:m.command,description:m.description})).sort((m,y)=>m.command.localeCompare(y.command))),d=JSON.stringify(i.sort((m,y)=>m.command.localeCompare(y.command)));h!==d&&(await this.bot.api.setMyCommands(i,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${n},${c?` lang: ${c},`:""} total (${i.length})`))}catch(l){this.log?.error?.(`Failed to sync descriptions for scope: ${n},${c?` lang: ${c},`:""} error: ${String(l)}`)}}}pageLoads(){this.log?.info?.("Load pages..");let t=["callback","text","textCommand","photoCaption","photoCaptionCommand","videoCaption","videoCaptionCommand","audioCaption","audioCaptionCommand","documentCaption","documentCaptionCommand","animationCaption","animationCaptionCommand","voiceCaption","voiceCaptionCommand"],e=["callbackPayload","textPayload","textCommandPayload","photoCaptionPayload","photoCaptionCommandPayload","videoCaptionPayload","videoCaptionCommandPayload","audioCaptionPayload","audioCaptionCommandPayload","documentCaptionPayload","documentCaptionCommandPayload","animationCaptionPayload","animationCaptionCommandPayload","voiceCaptionPayload","voiceCaptionCommandPayload"],s=[...t,...e,"textFree","photoFree","videoFree","audioFree","documentFree","animationFree","voiceFree","videoNoteFree","stickerFree","locationFree","contactFree"],n=p((i,r)=>Object.fromEntries(i.map(c=>[c,r()])),"makeObject"),o=p(()=>[],"initDynamicSpesific"),a={all:{},routeDynamic:[],routeDynamicSpesific:{text:o(),photo:o(),video:o(),audio:o(),document:o(),animation:o(),voice:o(),videoNote:o(),sticker:o(),location:o(),contact:o()},routeStatic:n(t,()=>({})),routeStaticIntent:n(e,()=>({})),routeStaticSession:n(s,()=>({})),listRouteStatic:t,listRouteStaticIntent:e,listRouteStaticSession:s,lenListRouteStatic:t.length,lenListRouteStaticIntent:e.length,lenListRouteStaticSession:s.length};return P.getFileManySync(void 0).forEach(({path:i,page:r},c)=>{this.pageBuildData(r,i),this.pageSorts(r,a,c),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(a.all).length})`),a}async pageRoutes(t,e){let s,n;if(s===void 0){let a=await t.sessionGet();if(a){let i=a.method,r=this.pages.routeStaticSession,c=t.callbackData,l=t.msgText,h=t.msgCaption,d=c||l||h,m=e==="callback",y=m?"colon":"space",C=d&&t.havePayloads(d,y)?t.getIntent(d,y,1):void 0,u=!m&&d?t.getIntent(d,"space",2):void 0;for(let w=0;w<this.pages.lenListRouteStaticSession;w++){let I=this.pages.listRouteStaticSession[w];if(I.startsWith(e)){if(d){if(this.pages.routeStatic[I]?.[d])continue;let x=this.pages.routeStaticIntent[I];if(x&&(C&&x[C]||u&&x[u]))continue}n=r[I][i]}if(n)break}n!==void 0&&(s=this.pages.all[n.name])}}if(s===void 0){let a=t.callbackData,i=t.msgText,r=t.msgCaption,c=this.pages.routeStatic;for(let l=0;l<this.pages.lenListRouteStatic;l++){let h=this.pages.listRouteStatic[l];if(h.startsWith(e)&&(n=c[h][a||i||r]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s===void 0){let a=this.pages.routeStaticIntent,i=e==="callback",r=i?"colon":"space",c=i?t.callbackData:t.msgText||t.msgCaption,l=t.havePayloads(c,r);if(c&&l)for(let h=0;h<this.pages.lenListRouteStaticIntent;h++){let d=this.pages.listRouteStaticIntent[h];if(!d.startsWith(e))continue;let m=a[d];if(n=m[t.getIntent(c,r,1)],!n&&!i&&(n=m[t.getIntent(c,"space",2)]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s!==void 0&&n!==void 0){if(!s.prototype[n.routeName])return;let i=await new s(t)[n.routeName]?.();return t.temp.isAnswer===!0?i:null}let o=this.pages.routeDynamicSpesific[e]||[];for(let a=0;a<o.length;a++){let i=o[a];if(i===void 0)continue;let r=this.pages.all[i.name];r!==void 0&&typeof r.prototype[i.routeName]=="function"&&await new r(t)[i.routeName]()}for(let a=0;a<this.pages.routeDynamic.length;a++){let i=this.pages.routeDynamic[a];if(i===void 0)continue;let r=this.pages.all[i];r!==void 0&&typeof r.prototype.free=="function"&&await new r(t).free()}if(t.temp.isAnswer===!1)return null}async hookBeforeRoute(t,e){return!!(t||e)}async hookErrorPage(t,e,s,n){}async hookErrorInputNotFoundPage(t){}async onMessage(t,e){let s=this.createCtx(t);try{if(await this.hookBeforeRoute(s,e)===!1)return;await this.pageRoutes(s,e)===null&&await this.hookErrorInputNotFoundPage(s)}catch(n){await this.hookErrorPage(s,e,n,!1)}}async onCallbackQueryData(t){let e=this.createCtx(t);try{if(await this.hookBeforeRoute(e,"onCallbackQueryData")===!1)return;await this.pageRoutes(e,"callback")}catch(s){await this.hookErrorPage(e,"onCallbackQueryData",s,!0)}}async onMessageText(t){await this.onMessage(t,"text")}async onMessagePhoto(t){await this.onMessage(t,"photo")}async onMessageVideo(t){await this.onMessage(t,"video")}async onMessageAudio(t){await this.onMessage(t,"audio")}async onMessageDocument(t){await this.onMessage(t,"document")}async onMessageAnimation(t){await this.onMessage(t,"animation")}async onMessageVoice(t){await this.onMessage(t,"voice")}async onMessageVideoNote(t){await this.onMessage(t,"videoNote")}async onMessageSticker(t){await this.onMessage(t,"sticker")}async onMessageLocation(t){await this.onMessage(t,"location")}async onMessageContact(t){await this.onMessage(t,"contact")}registerOnCallbackQueryData(){this.bot.on("callback_query:data",this.onCallbackQueryData.bind(this))}registerOnMessageText(){this.bot.on("message:text",this.onMessageText.bind(this))}registerOnMessagePhoto(){this.bot.on("message:photo",this.onMessagePhoto.bind(this))}registerOnMessageVideo(){this.bot.on("message:video",this.onMessageVideo.bind(this))}registerOnMessageAudio(){this.bot.on("message:audio",this.onMessageAudio.bind(this))}registerOnMessageDocument(){this.bot.on("message:document",this.onMessageDocument.bind(this))}registerOnMessageAnimation(){this.bot.on("message:animation",this.onMessageAnimation.bind(this))}registerOnMessageVoice(){this.bot.on("message:voice",this.onMessageVoice.bind(this))}registerOnMessageVideoNote(){this.bot.on("message:video_note",this.onMessageVideoNote.bind(this))}registerOnMessageSticker(){this.bot.on("message:sticker",this.onMessageSticker.bind(this))}registerOnMessageLocation(){this.bot.on("message:location",this.onMessageLocation.bind(this))}registerOnMessageContact(){this.bot.on("message:contact",this.onMessageContact.bind(this))}};var Q=class{static{p(this,"BlockKeyboard")}static label;static _build(t,e,s,n){if(!this.label)throw new Error("Label not found, make sure set this.label from class extends LabelKeyboard");s||(s="inline");let o=this.label[t];if(!o)throw new Error(`Object value ${t} not found`);let a=p((i,r)=>`<keyboard type="${s}" lang="${r}">${n?this.label._reverse(i):i}</keyboard>`,"pro");return e?a(o[e],e):Object.keys(o).map(i=>a(o[i],i)).join(" ")}};var H=class{static{p(this,"LabelKeyboard")}static _reverse(t){return t.split(/(?<!\\), */).reverse().join(", ")}static _reverseObj(t){return Object.keys(t).reduce((e,s)=>(e[s]=this._reverse(t[s]),e),{})}};var N=require("worker_threads");var T=class{constructor(t,e){this.send=t;this.register=e}static{p(this,"WorkerThreadRpc")}map=new Map;async make(t){let e=this.map,s=this.send,{id:n,method:o,params:a,result:i,error:r}=t;if(o!==void 0)try{let c=this.register[o];if(typeof c!="function")throw new Error(`Method ${o} not found or not function`);let l=await c.apply(this.register,a);s({id:n,result:l})}catch(c){s({id:n,error:c instanceof Error?{message:c.message,stack:c.stack,name:c.name}:c})}else if(i!==void 0){let c=e.get(n);c&&(c.resolve(i),e.delete(n))}else if(r!==void 0){let c=e.get(n);c&&(c.reject(r),e.delete(n))}}makeId(){return Math.random()}makeRequest(t,e,s=!0,n){let o=this.makeId(),a={id:o,method:t,params:e,...n};return s?new Promise((i,r)=>{this.map.set(o,{resolve:i,reject:r}),this.send(a)}):this.send(a)}};var $=class{constructor(t,e,s){this.path=t;this.argv=e;this.register=s;this.init(),s||(s=this),this.rpc=new T(this.send.bind(this),s)}static{p(this,"WorkerThreadLaunch")}static isMainThread=N.isMainThread;_readyResolve;_readyPromise=new Promise(t=>this._readyResolve=t);pid=process.pid;thread={};threadId={};rpc={};ready(){return this._readyPromise}mtdReady(){this._readyResolve?.()}init(){this.thread=new N.Worker(this.path,{argv:this.argv.length==0&&this.argv[0]===void 0?void 0:this.argv}),this.threadId=this.thread.threadId,this.thread.on("message",t=>this.handleOnMessage(t)),this.thread.on("exit",()=>this.kill()),process.once("SIGINT",()=>this.kill()),process.once("SIGTERM",()=>this.kill())}async handleOnMessage(t){this.rpc.make(t)}kill(){this.thread.terminate()}send(t){this.thread.postMessage(t)}async request(t,e,s=!0,n){return this.rpc.makeRequest(t,e,s,n)}};var z=class g{static{p(this,"WorkerThreadExport")}static launchGatewayClient(t){let e=new Proxy({},{get(n,o){if(!(typeof o!="string"||o==="then"))return async(a,...i)=>{let r=a.gatewayClients.get(t);return r||(r=await a.createGatewayClient(t)),r.request(o,i)}}}),s=p(function(n){return new Proxy({},{get(o,a){if(!(typeof a!="string"||a==="then"))return async(...i)=>{let r=n.gatewayClients.get(t);return r||(r=await n.createGatewayClient(t)),r.request(a,i)}}})},"ctor");return Object.setPrototypeOf(s,e),s}static init(t){let{WTInit:e,WTLaunch:s=$,path:n,wrap:o}=t,a=`for-${n}`;if(process.argv[2]===a)return new e,{launchGatewayClient:p(h=>g.launchGatewayClient(h||e.gatewayServerPath),"launchGatewayClient")};let i,r=new Proxy({},{get(h,d){if(d!=="then")return d==="sendRequest"||d==="request"||d==="kill"||d==="send"?(...m)=>{if(!i)throw new Error(`Thread at ${n} not launched yet.`);return i[d](...m)}:(...m)=>{if(!i)throw new Error(`Thread at ${n} not launched yet.`);return i.request(d,m)}}}),l={...o?o(r):{},launchWorker:p(async(h=[])=>(i=new s(n,[a,...h]),await i.ready(),i),"launchWorker"),launchGatewayClient:p(h=>g.launchGatewayClient(h||e.gatewayServerPath),"launchGatewayClient")};return new Proxy(l,{get(h,d){if(d!=="then")return d==="launchGatewayClient"?h.launchGatewayClient:d==="launchWorker"?h.launchWorker:d in h?h[d]:typeof d=="string"?(...m)=>{if(!i)throw new Error(`Thread at ${n} not launched yet.`);return i.request(d,m)}:h[d]}})}};var dt=require("net-ipc");var K=class{static{p(this,"WorkerThreadGatewayClient")}client=new dt.Client;rpc;constructor(){this.rpc=new T(t=>this.client.send(t),{}),this.client.on("message",t=>{this.rpc.make(t)})}async connect(t){this.client.options.path=t;let e=new Promise(s=>{this.client.once("ready",()=>s(this))});return await this.client.connect(),e}async request(t,e,s=!0,n){return this.rpc.makeRequest(t,e,s,n)}};var ht=require("net-ipc");var L=class{static{p(this,"WorkerThreadGatewayServer")}server=new ht.Server;rpc=new Map;register={};constructor(){this.server.on("connect",t=>{let e=new T(s=>t.send(s),this.register);this.rpc.set(t.id,e)}),this.server.on("disconnect",t=>{this.rpc.delete(t.id)}),this.server.on("message",(t,e)=>{let s=this.rpc.get(e.id);s&&s.make(t)}),this.server.on("error",t=>{console.error(t)})}async start(t,e={}){this.register=e,this.server.options.path=t;let s=new Promise(n=>{this.server.once("ready",()=>n(this))});return await this.server.start(),s}};var A=require("worker_threads");var X=class{static{p(this,"WorkerThreadInit")}argv=process.argv;id=A.threadId;pid=process.pid;rpc={};parentPort=A.parentPort;gatewayServer;gatewayClients=new Map;gatewayClientLatest;static gatewayServerPath;gatewayServerPath=this.constructor.gatewayServerPath;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=A.isMainThread;constructor(){this.init(),this.rpc=new T(this.send.bind(this),this),this.send({method:"mtdReady"})}init(){this.parentPort?.on("message",t=>this.handleOnMessage(t))}handleOnMessage(t){this.rpc.make(t)}send(t){this.parentPort?.postMessage(t)}request(t,e,s=!0,n){return this.rpc.makeRequest(t,e,s,n)}async createGatewayServer(t,e){return t||(t=this),e||(e=this.constructor.gatewayServerPath),this.gatewayServer=new L,await this.gatewayServer.start(e,t),this.constructor.gatewayServerPath=e,!0}async createGatewayClient(t){let e=new K;return await e.connect(t),this.gatewayClients.set(t,e),this.gatewayClientLatest=e,e}};var Y=class{static{p(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(t){this.addMany(t)}add(t){this.thread.set(t.threadId,t),this.threadCount+=1}addMany(t){t.forEach(e=>this.add(e))}getInstance(t){return this.thread.get(t)}kill(t){let e=this.thread.get(t);return e?.kill(),this.thread.delete(t),this.threadCount-=1,e?.threadId}killAll(){this.thread.values().forEach(({threadId:t})=>this.kill(t))}async broadcastRequest(t,e){return await Promise.all(Object.values(this.thread).map(s=>s.request(t,e,!0)))}async request(t,e,s,n=!0,o){return await this.thread.get(t)?.request(e,s,n,o)}};0&&(module.exports={BlockKeyboard,CacheExternal,Ctx,Gramstax,LabelKeyboard,LoggingUtil,TemplateEngine,TemplateManager,WorkerThreadExport,WorkerThreadGatewayClient,WorkerThreadGatewayServer,WorkerThreadInit,WorkerThreadLaunch,WorkerThreadPool,WorkerThreadRpc,log});
7
+ `);i=i.replace(`__IMPORT_${r}__`,d)}return i}};var V=class{static{p(this,"TemplateManager")}_map=new Map;_engine=P;_watcher=[];_pageManager=b;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(t){let{path:e,enableWatch:s=!1}=t;this._path=e,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(t.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let t=0;t<this._path.length;t++){let e=this._path[t];if(!(0,f.existsSync)(e))throw new Error(`Template base path is not exists: ${e}`);if(!(0,f.statSync)(e).isDirectory())throw new Error(`Template base path is not a directory: ${e}`)}return!0}catch(t){throw new Error(`Failed to validate Template base path: ${String(t)}`)}}_initializeWatcher(t){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let e=0;e<this._path.length;e++){let s=this._path[e],n=(0,at.watch)(s,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...t});this._watcher[e]=n,n.on("change",this._handleFileChange.bind(this)),n.on("add",this._handleFileAdd.bind(this)),n.on("unlink",this._handleFileDelete.bind(this)),n.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(t){let e=(0,S.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileAdd(t){let e=(0,S.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileDelete(t){let e=(0,S.basename)(t),s=this._getKey(e);this._map.has(s)&&this._map.delete(s)}_handleWatchError(t){}_loadAllFiles(){let t=new Map,e=[];for(let n=0;n<this._path.length;n++){let o=this._path[n],i=(0,f.readdirSync)(o,"utf8").filter(r=>this._isValidFile(r));for(let r of i){let c=(0,S.join)(o,r),h=this._getExtension(r),l=this._getKey(r);if(h===".html")t.set(l,(0,f.readFileSync)(c,"utf8"));else if(h===".ts"||h===".js"){let d=b.getFileSync(c);d?.template!==void 0&&(t.set(l,d.template),e.push(d))}}}let s=new Map;for(let[n,o]of t.entries())this._compile(n,o,void 0,s,t);t.clear(),s.clear();for(let n of e)n.template=void 0}_loadFile(t){for(let e=0;e<this._path.length;e++){let s=this._path[e],n=(0,S.join)(s,t),o=this._getExtension(t),a=this._getKey(t);if(o==".html"){let i=(0,f.readFileSync)(n,"utf8");this._compile(a,i)}else if(o==".ts"||o==".js"){let i=b.getFileSync(n);i?.template!==void 0&&(this._compile(a,i.template),i.template=void 0)}else throw new Error(`File ${t} is not support`)}}_getExtension(t){return(0,S.extname)(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let s=(0,S.extname)(t).toLowerCase();if(s){let i=(0,S.join)(e,t);if((0,f.existsSync)(i)&&(0,f.statSync)(i).isFile()){if(s===".html")return(0,f.readFileSync)(i,"utf8");if(s===".ts"||s===".js")try{return b.getFileSync(i)?.template??null}catch{return null}}continue}let n=(0,S.join)(e,`${t}.ts`),o=(0,S.join)(e,`${t}.js`);if((0,f.existsSync)(n)&&(0,f.statSync)(n).isFile())try{return b.getFileSync(n)?.template??null}catch{}else if((0,f.existsSync)(o)&&(0,f.statSync)(o).isFile())try{return b.getFileSync(n)?.template??null}catch{}let a=(0,S.join)(e,`${t}.html`);if((0,f.existsSync)(a)&&(0,f.statSync)(a).isFile())return(0,f.readFileSync)(a,"utf8")}return null}_isValidFile(t){return this._supportedExtensions.has(this._getExtension(t))}_getKey(t){return t.replace(/\.[^/.]+$/,"")}_compile(t,e,s,n,o){let a=this._map.get(t),i=a||{},r=!1,c=P.processImportBlocks(e,l=>o&&o.has(l)?o.get(l):this._readTemplateFile(l),0,n),h=P._processBaseBlocks(c);(s===void 0||s?.media===!1||a?.media===void 0)&&(i.media=P.compileBlockMedia(c,h),r=!0),(s===void 0||s?.message===!1||a?.message===void 0)&&(i.message=P.compileBlockMessage(c,h),r=!0),(s===void 0||s?.keyboard===!1||a?.keyboard===void 0)&&(i.keyboard=P.compileBlockKeyboards(c,h),r=!0),(s===void 0||s?.description===!1||a?.description===void 0)&&(i.description=P.compileBlockDescription(c,h),r=!0),r&&this._map.set(t,i)}getMedia(t,e="default",s="default",n){let a=this._map.get(t)?.media?.[e],i=a?.[s]||a?.default;try{if(!i)throw new Error("Media function not found, please check your template");return i(n)}catch{return{}}}getMessage(t,e="default",s="default",n){try{let a=this._map.get(t)?.message?.[e],i=a?.[s]||a?.default;if(!i)throw"";return i(n)}catch{return""}}getDescription(t,e="default",s="default",n="default",o){try{let i=this._map.get(t)?.description?.[e]?.[n],r=i?.[s]||i?.default;if(!r)throw"";return r(o)}catch{return""}}getDescriptionLanguage(t,e="default",s="default"){try{let o=this._map.get(t)?.description?.[e]?.[s];return o?Object.keys(o):[]}catch{return[]}}getDescriptionScopes(t,e="default"){try{let n=this._map.get(t)?.description?.[e];return n?Object.keys(n):[]}catch{return[]}}getKeyboard(t,e="default",s="default",n="inline",o){try{let i=this._map.get(t)?.keyboard?.[e],r=i?.[s]?.[n]||i?.default?.[n];if(!r)throw[];return r(o)}catch{return[]}}async write(t,e){if(this._getExtension(t)!=".html")return null;for(let s=0;s<this._path.length;s++){let n=(0,S.join)(this._path[s],t);if((0,f.existsSync)(n))return(0,f.writeFileSync)(n,e,"utf8"),this._loadFile(t),!0}return null}has(t){return this._map.has(t)}async destroy(){if(this._watcher)for(let t of this._watcher)await t.close();this._map.clear()}};var K=require("grammy");var Pt=(0,w.dirname)((()=>{try{return __filename}catch{return(0,ct.fileURLToPath)(C)}})()),kt=JSON.parse((0,rt.readFileSync)((0,w.join)(Pt,"../../package.json"),"utf-8")).version,J=class{static{p(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;optionsPage={shortCallbackData:!1};log;bot;handlerBotUpdate;constructor(t){if(!t?.token||t?.token?.length==0)throw new Error("Token is not valid or empty");if(typeof t.optionsPage?.shortCallbackData=="boolean"&&(this.optionsPage.shortCallbackData=t.optionsPage.shortCallbackData),this.log=t.log===!0?q:t.log?t.log:void 0,this.log?.info?.(`Gramstax v${kt}`),this.cacheSession=t.cacheSession||new A("memory"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new V({path:[(0,w.join)(process.cwd(),"src","pages")]}),this.bot=this.createBot(t.token),this.bot.catch(this._onCatch),this._registerOnCallbackQueryData(),this._registerOnMessageText(),this._registerOnMessagePhoto(),this._registerOnMessageVideo(),this._registerOnMessageAudio(),this._registerOnMessageDocument(),this._registerOnMessageAnimation(),this._registerOnMessageVoice(),this._registerOnMessageVideoNote(),this._registerOnMessageSticker(),this._registerOnMessageLocation(),this._registerOnMessageContact(),this.handlerBotUpdate=this.bot.handleUpdate,this.pages=this._pageLoads(),process.once("SIGINT",()=>this.bot.stop()),process.once("SIGTERM",()=>this.bot.stop()),this.hookBeforeStart(),t.deploy.startsWith("polling"))this._runPolling();else if(t.deploy.startsWith("webhook:"))this._runWebhook(t.deploy.split("webhook:")[1]);else if(t.deploy.startsWith("serverless:"))this._runServerless(t.deploy.split("serverless:")[1]);else if(!t.deploy.startsWith("test"))throw new Error("Params deploy is not valid, expected: polling, webhook:<public-url>, serverless:<your-adapter>")}_onCatch(t){if(this.log?.errorMake)this.log?.errorMake(t,"Bot","catch");else{let e=JSON.stringify(t,null,2);this.log?.error?.(`[Bot.catch]: ${e}`)}}hookBeforeStart(){}hookAfterStart(){}async _onStart(t,e,s){await this.executeSyncBlocksDescription(this.pages);let{username:n}=t;this.log?.success?.(`Telegram bot polling started: ${n} ${e=="webhook"||e=="serverless"?`(${s})`:""}`),this.hookAfterStart()}createBot(t){return new K.Bot(t)}createCtx(t){return new B({ct:t,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{isAnswer:!1,session:{},data:{}}})}_runPolling(){this.bot.start({onStart:p(t=>{this._onStart(t,"polling",null)},"onStart")})}async _runWebhook(t){let{serve:e}=await import("bun"),s=(0,K.webhookCallback)(this.bot,"bun");this.handlerBotUpdate=s;let n=new URL(t).pathname;e({fetch(i){let{pathname:r}=new URL(i.url);if(i.method=="POST"&&r==n)return s(i);if(i.method=="GET"&&r=="/"){let c=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:c}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}}),(await this.bot.api.getWebhookInfo()).url!=t&&await this.bot.api.setWebhook(t);let a=await this.bot.api.getMe();await this._onStart(a,"webhook",t)}async _runServerless(t){this.handlerBotUpdate=(0,K.webhookCallback)(this.bot,t);let e=await this.bot.api.getMe();await this._onStart(e,"serverless",t)}_pageBuildData(t,e){t?.data===void 0&&(t.data=t.buildData());let{name:s}=(0,w.parse)(e);t.data.name||(t.data.name=s),t.data.intentText||(t.data.intentText=t.data.name),t.data.intentTextCommand||(t.data.intentTextCommand=t.data.name),t.data.intentCallback||(t.data.intentCallback=t.data.name)}_pageSorts(t,e,s){let n=t.data.name,o=t.prototype,a="Payload",i="Command",r="Caption",c="Free",h=e.routeDynamic,l=e.routeDynamicSpesific,d=p(T=>T.charAt(0).toUpperCase()+T.slice(1),"upFirst"),m=p(T=>T.replace(a,"").replace(i,"").replace(r,"").replace(c,""),"getPureRouteName"),y=p((T,u)=>o[`methodSession${d(T)}`]?.(u),"methodSession");e.all[n]=t;for(let T=0;T<e.lenListRouteStaticSession;T++){let u=e.listRouteStaticSession[T];if(typeof o[u]!="function")continue;let I=e.routeStatic[u],x=e.routeStaticIntent[u],_=e.routeStaticSession[u],G={name:n,routeName:u},Z=I||x;if(Z!==void 0){let ht=u.includes(i),mt=u.includes("callback"),pt=u.startsWith("text"),M;if(ht){let R=t.data.intentTextCommand;M=R?`/${R}`:void 0}else if(mt){let R=t.data.intentCallback;this.optionsPage.shortCallbackData===!0&&(R=String(s),t.data.intentCallback=R),M=R}else pt?M=t.data.intentText:M=t.data.name;M&&(Z[M]=G)}_!==void 0&&(_[y(u,n)]=G),u.toLowerCase().endsWith("free")&&l[m(u)].push(G)}o.free&&h.push(n)}async executeSyncBlocksDescription(t){let e=new Map,s=t.routeStatic.textCommand;for(let[,n]of Object.entries(s)){let o=n.name,a=this.templateManager.getDescriptionScopes(o);for(let i of a){e.has(i)||e.set(i,new Set);let r=this.templateManager.getDescriptionLanguage(o,"default",i);for(let c of r)e.get(i).add(c)}}for(let[n,o]of e)for(let a of o){let i=[];for(let[,h]of Object.entries(s)){let l=h.name,d=this.templateManager.getDescription(l,"default",a,n);d&&i.push({command:l,description:d})}if(i.length===0)continue;let r={type:n},c=a==="default"?void 0:a;try{let h=await this.bot.api.getMyCommands({scope:r,language_code:c}),l=JSON.stringify(h.map(m=>({command:m.command,description:m.description})).sort((m,y)=>m.command.localeCompare(y.command))),d=JSON.stringify(i.sort((m,y)=>m.command.localeCompare(y.command)));l!==d&&(await this.bot.api.setMyCommands(i,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${n},${c?` lang: ${c},`:""} total (${i.length})`))}catch(h){this.log?.error?.(`Failed to sync descriptions for scope: ${n},${c?` lang: ${c},`:""} error: ${String(h)}`)}}}_pageLoads(){this.log?.info?.("Load pages..");let t=["callback","text","textCommand","photoCaption","photoCaptionCommand","videoCaption","videoCaptionCommand","audioCaption","audioCaptionCommand","documentCaption","documentCaptionCommand","animationCaption","animationCaptionCommand","voiceCaption","voiceCaptionCommand"],e=["callbackPayload","textPayload","textCommandPayload","photoCaptionPayload","photoCaptionCommandPayload","videoCaptionPayload","videoCaptionCommandPayload","audioCaptionPayload","audioCaptionCommandPayload","documentCaptionPayload","documentCaptionCommandPayload","animationCaptionPayload","animationCaptionCommandPayload","voiceCaptionPayload","voiceCaptionCommandPayload"],s=[...t,...e,"textFree","photoFree","videoFree","audioFree","documentFree","animationFree","voiceFree","videoNoteFree","stickerFree","locationFree","contactFree"],n=p((i,r)=>Object.fromEntries(i.map(c=>[c,r()])),"makeObject"),o=p(()=>[],"initDynamicSpesific"),a={all:{},routeDynamic:[],routeDynamicSpesific:{text:o(),photo:o(),video:o(),audio:o(),document:o(),animation:o(),voice:o(),videoNote:o(),sticker:o(),location:o(),contact:o()},routeStatic:n(t,()=>({})),routeStaticIntent:n(e,()=>({})),routeStaticSession:n(s,()=>({})),listRouteStatic:t,listRouteStaticIntent:e,listRouteStaticSession:s,lenListRouteStatic:t.length,lenListRouteStaticIntent:e.length,lenListRouteStaticSession:s.length};return b.getFileManySync(void 0).forEach(({path:i,page:r},c)=>{this._pageBuildData(r,i),this._pageSorts(r,a,c),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(a.all).length})`),a}async _pageRoutes(t,e){let s,n;if(s===void 0){let a=await t.sessionGet();if(a){let i=a.method,r=this.pages.routeStaticSession,c=t.callbackData,h=t.msgText,l=t.msgCaption,d=c||h||l,m=e==="callback",y=m?"colon":"space",T=d&&t.havePayloads(d,y)?t.getIntent(d,y,1):void 0,u=!m&&d?t.getIntent(d,"space",2):void 0;for(let I=0;I<this.pages.lenListRouteStaticSession;I++){let x=this.pages.listRouteStaticSession[I];if(x.startsWith(e)){if(d){if(this.pages.routeStatic[x]?.[d])continue;let _=this.pages.routeStaticIntent[x];if(_&&(T&&_[T]||u&&_[u]))continue}n=r[x][i]}if(n)break}n!==void 0&&(s=this.pages.all[n.name])}}if(s===void 0){let a=t.callbackData,i=t.msgText,r=t.msgCaption,c=this.pages.routeStatic;for(let h=0;h<this.pages.lenListRouteStatic;h++){let l=this.pages.listRouteStatic[h];if(l.startsWith(e)&&(n=c[l][a||i||r]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s===void 0){let a=this.pages.routeStaticIntent,i=e==="callback",r=i?"colon":"space",c=i?t.callbackData:t.msgText||t.msgCaption,h=t.havePayloads(c,r);if(c&&h)for(let l=0;l<this.pages.lenListRouteStaticIntent;l++){let d=this.pages.listRouteStaticIntent[l];if(!d.startsWith(e))continue;let m=a[d];if(n=m[t.getIntent(c,r,1)],!n&&!i&&(n=m[t.getIntent(c,"space",2)]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s!==void 0&&n!==void 0){if(!s.prototype[n.routeName])return;let i=await new s(t)[n.routeName]?.();return t.temp.isAnswer===!0?i:null}let o=this.pages.routeDynamicSpesific[e]||[];for(let a=0;a<o.length;a++){let i=o[a];if(i===void 0)continue;let r=this.pages.all[i.name];r!==void 0&&typeof r.prototype[i.routeName]=="function"&&await new r(t)[i.routeName]()}for(let a=0;a<this.pages.routeDynamic.length;a++){let i=this.pages.routeDynamic[a];if(i===void 0)continue;let r=this.pages.all[i];r!==void 0&&typeof r.prototype.free=="function"&&await new r(t).free()}if(t.temp.isAnswer===!1)return null}async hookBeforeRoute(t,e){return!!(t||e)}async hookErrorPage(t,e,s,n){}async hookErrorInputNotFoundPage(t){}async _onMessage(t,e){let s=this.createCtx(t);try{if(await this.hookBeforeRoute(s,e)===!1)return;await this._pageRoutes(s,e)===null&&await this.hookErrorInputNotFoundPage(s)}catch(n){await this.hookErrorPage(s,e,n,!1)}}async _onCallbackQueryData(t){let e=this.createCtx(t);try{if(await this.hookBeforeRoute(e,"onCallbackQueryData")===!1)return;await this._pageRoutes(e,"callback")}catch(s){await this.hookErrorPage(e,"onCallbackQueryData",s,!0)}}async _onMessageText(t){await this._onMessage(t,"text")}async _onMessagePhoto(t){await this._onMessage(t,"photo")}async _onMessageVideo(t){await this._onMessage(t,"video")}async _onMessageAudio(t){await this._onMessage(t,"audio")}async _onMessageDocument(t){await this._onMessage(t,"document")}async _onMessageAnimation(t){await this._onMessage(t,"animation")}async _onMessageVoice(t){await this._onMessage(t,"voice")}async _onMessageVideoNote(t){await this._onMessage(t,"videoNote")}async _onMessageSticker(t){await this._onMessage(t,"sticker")}async _onMessageLocation(t){await this._onMessage(t,"location")}async _onMessageContact(t){await this._onMessage(t,"contact")}_registerOnCallbackQueryData(){this.bot.on("callback_query:data",this._onCallbackQueryData.bind(this))}_registerOnMessageText(){this.bot.on("message:text",this._onMessageText.bind(this))}_registerOnMessagePhoto(){this.bot.on("message:photo",this._onMessagePhoto.bind(this))}_registerOnMessageVideo(){this.bot.on("message:video",this._onMessageVideo.bind(this))}_registerOnMessageAudio(){this.bot.on("message:audio",this._onMessageAudio.bind(this))}_registerOnMessageDocument(){this.bot.on("message:document",this._onMessageDocument.bind(this))}_registerOnMessageAnimation(){this.bot.on("message:animation",this._onMessageAnimation.bind(this))}_registerOnMessageVoice(){this.bot.on("message:voice",this._onMessageVoice.bind(this))}_registerOnMessageVideoNote(){this.bot.on("message:video_note",this._onMessageVideoNote.bind(this))}_registerOnMessageSticker(){this.bot.on("message:sticker",this._onMessageSticker.bind(this))}_registerOnMessageLocation(){this.bot.on("message:location",this._onMessageLocation.bind(this))}_registerOnMessageContact(){this.bot.on("message:contact",this._onMessageContact.bind(this))}};var Q=class{static{p(this,"BlockKeyboard")}static label;static _build(t,e,s,n){if(!this.label)throw new Error("Label not found, make sure set this.label from class extends LabelKeyboard");s||(s="inline");let o=this.label[t];if(!o)throw new Error(`Object value ${t} not found`);let a=p((i,r)=>`<keyboard type="${s}" lang="${r}">${n?this.label._reverse(i):i}</keyboard>`,"pro");return e?a(o[e],e):Object.keys(o).map(i=>a(o[i],i)).join(" ")}};var H=class{static{p(this,"LabelKeyboard")}static _reverse(t){return t.split(/(?<!\\), */).reverse().join(", ")}static _reverseObj(t){return Object.keys(t).reduce((e,s)=>(e[s]=this._reverse(t[s]),e),{})}};var N=require("worker_threads");var k=class{constructor(t,e){this.send=t;this.register=e}static{p(this,"WorkerThreadRpc")}map=new Map;async make(t){let e=this.map,s=this.send,{id:n,method:o,params:a,result:i,error:r}=t;if(o!==void 0)try{let c=this.register[o];if(typeof c!="function")throw new Error(`Method ${o} not found or not function`);let h=await c.apply(this.register,a);s({id:n,result:h})}catch(c){s({id:n,error:c instanceof Error?{message:c.message,stack:c.stack,name:c.name}:c})}else if(i!==void 0){let c=e.get(n);c&&(c.resolve(i),e.delete(n))}else if(r!==void 0){let c=e.get(n);c&&(c.reject(r),e.delete(n))}}makeId(){return Math.random()}makeRequest(t,e,s=!0,n){let o=this.makeId(),a={id:o,method:t,params:e,...n};return s?new Promise((i,r)=>{this.map.set(o,{resolve:i,reject:r}),this.send(a)}):this.send(a)}};var W=class{constructor(t,e,s){this.path=t;this.argv=e;this.register=s;this.init(),s||(s=this),this.rpc=new k(this.send.bind(this),s)}static{p(this,"WorkerThreadLaunch")}static isMainThread=N.isMainThread;_readyResolve;_readyPromise=new Promise(t=>this._readyResolve=t);pid=process.pid;thread={};threadId={};rpc={};ready(){return this._readyPromise}mtdReady(){this._readyResolve?.()}init(){this.thread=new N.Worker(this.path,{argv:this.argv.length==0&&this.argv[0]===void 0?void 0:this.argv}),this.threadId=this.thread.threadId,this.thread.on("message",t=>this.handleOnMessage(t)),this.thread.on("exit",()=>this.kill()),process.once("SIGINT",()=>this.kill()),process.once("SIGTERM",()=>this.kill())}async handleOnMessage(t){this.rpc.make(t)}kill(){this.thread.terminate()}send(t){this.thread.postMessage(t)}async request(t,e,s=!0,n){return this.rpc.makeRequest(t,e,s,n)}};var z=class g{static{p(this,"WorkerThreadExport")}static launchGatewayClient(t){let e=new Proxy({},{get(n,o){if(!(typeof o!="string"||o==="then"))return async(a,...i)=>{let r=a.gatewayClients.get(t);return r||(r=await a.createGatewayClient(t)),r.request(o,i)}}}),s=p(function(n){return new Proxy({},{get(o,a){if(!(typeof a!="string"||a==="then"))return async(...i)=>{let r=n.gatewayClients.get(t);return r||(r=await n.createGatewayClient(t)),r.request(a,i)}}})},"ctor");return Object.setPrototypeOf(s,e),s}static init(t){let{WTInit:e,WTLaunch:s=W,path:n,wrap:o}=t,a=`for-${n}`;if(process.argv[2]===a)return new e,{launchGatewayClient:p(l=>g.launchGatewayClient(l||e.gatewayServerPath),"launchGatewayClient")};let i,r=new Proxy({},{get(l,d){if(d!=="then")return d==="sendRequest"||d==="request"||d==="kill"||d==="send"?(...m)=>{if(!i)throw new Error(`Thread at ${n} not launched yet.`);return i[d](...m)}:(...m)=>{if(!i)throw new Error(`Thread at ${n} not launched yet.`);return i.request(d,m)}}}),h={...o?o(r):{},launchWorker:p(async(l=[])=>(i=new s(n,[a,...l]),await i.ready(),i),"launchWorker"),launchGatewayClient:p(l=>g.launchGatewayClient(l||e.gatewayServerPath),"launchGatewayClient")};return new Proxy(h,{get(l,d){if(d!=="then")return d==="launchGatewayClient"?l.launchGatewayClient:d==="launchWorker"?l.launchWorker:d in l?l[d]:typeof d=="string"?(...m)=>{if(!i)throw new Error(`Thread at ${n} not launched yet.`);return i.request(d,m)}:l[d]}})}};var dt=require("net-ipc");var $=class{static{p(this,"WorkerThreadGatewayClient")}client=new dt.Client;rpc;constructor(){this.rpc=new k(t=>this.client.send(t),{}),this.client.on("message",t=>{this.rpc.make(t)})}async connect(t){this.client.options.path=t;let e=new Promise(s=>{this.client.once("ready",()=>s(this))});return await this.client.connect(),e}async request(t,e,s=!0,n){return this.rpc.makeRequest(t,e,s,n)}};var lt=require("net-ipc");var E=class{static{p(this,"WorkerThreadGatewayServer")}server=new lt.Server;rpc=new Map;register={};constructor(){this.server.on("connect",t=>{let e=new k(s=>t.send(s),this.register);this.rpc.set(t.id,e)}),this.server.on("disconnect",t=>{this.rpc.delete(t.id)}),this.server.on("message",(t,e)=>{let s=this.rpc.get(e.id);s&&s.make(t)}),this.server.on("error",t=>{console.error(t)})}async start(t,e={}){this.register=e,this.server.options.path=t;let s=new Promise(n=>{this.server.once("ready",()=>n(this))});return await this.server.start(),s}};var F=require("worker_threads");var X=class{static{p(this,"WorkerThreadInit")}argv=process.argv;id=F.threadId;pid=process.pid;rpc={};parentPort=F.parentPort;gatewayServer;gatewayClients=new Map;gatewayClientLatest;static gatewayServerPath;gatewayServerPath=this.constructor.gatewayServerPath;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=F.isMainThread;constructor(){this.init(),this.rpc=new k(this.send.bind(this),this),this.send({method:"mtdReady"})}init(){this.parentPort?.on("message",t=>this.handleOnMessage(t))}handleOnMessage(t){this.rpc.make(t)}send(t){this.parentPort?.postMessage(t)}request(t,e,s=!0,n){return this.rpc.makeRequest(t,e,s,n)}async createGatewayServer(t,e){return t||(t=this),e||(e=this.constructor.gatewayServerPath),this.gatewayServer=new E,await this.gatewayServer.start(e,t),this.constructor.gatewayServerPath=e,!0}async createGatewayClient(t){let e=new $;return await e.connect(t),this.gatewayClients.set(t,e),this.gatewayClientLatest=e,e}};var Y=class{static{p(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(t){this.addMany(t)}add(t){this.thread.set(t.threadId,t),this.threadCount+=1}addMany(t){t.forEach(e=>this.add(e))}getInstance(t){return this.thread.get(t)}kill(t){let e=this.thread.get(t);return e?.kill(),this.thread.delete(t),this.threadCount-=1,e?.threadId}killAll(){this.thread.values().forEach(({threadId:t})=>this.kill(t))}async broadcastRequest(t,e){return await Promise.all(Object.values(this.thread).map(s=>s.request(t,e,!0)))}async request(t,e,s,n=!0,o){return await this.thread.get(t)?.request(e,s,n,o)}};0&&(module.exports={BlockKeyboard,CacheExternal,Ctx,Gramstax,LabelKeyboard,LoggingUtil,TemplateEngine,TemplateManager,WorkerThreadExport,WorkerThreadGatewayClient,WorkerThreadGatewayServer,WorkerThreadInit,WorkerThreadLaunch,WorkerThreadPool,WorkerThreadRpc,log});