gramstax 0.3.7 → 0.3.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/src/index.cjs +3 -3
- package/dist/src/index.js +4 -4
- package/package.json +1 -1
package/dist/src/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var ot=Object.create;var _=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var rt=Object.getOwnPropertyNames;var ct=Object.getPrototypeOf,lt=Object.prototype.hasOwnProperty;var h=(g,t)=>_(g,"name",{value:t,configurable:!0});var dt=(g,t)=>{for(var e in t)_(g,e,{get:t[e],enumerable:!0})},J=(g,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of rt(t))!lt.call(g,s)&&s!==e&&_(g,s,{get:()=>t[s],enumerable:!(i=at(t,s))||i.enumerable});return g};var U=(g,t,e)=>(e=g!=null?ot(ct(g)):{},J(t||!g||!g.__esModule?_(e,"default",{value:g,enumerable:!0}):e,g)),pt=g=>J(_({},"__esModule",{value:!0}),g);var ht={};dt(ht,{CacheExternal:()=>F,ComponentKeyboard:()=>j,Ctx:()=>V,DataKeyboard:()=>q,Gramstax:()=>E,LoggingUtils:()=>A,TemplateEngine:()=>P,TemplateManager:()=>R,ThreadExport:()=>K,ThreadMain:()=>O,ThreadMainPool:()=>L,ThreadSub:()=>W,log:()=>ut});module.exports=pt(ht);var H=require("logging-pretty");var A=class extends H.LoggingPretty{static{h(this,"LoggingUtils")}constructor(t){super(t)}errorMake(t,e,i){this.error(`[${e?.name||e}:${i}] ${String(t)}`)}},ut=new A;var z=require("keyv"),X=U(require("@keyv/redis"),1);var F=class extends z.Keyv{constructor(e="memory",i,s,o){let a;e.startsWith("redis")&&(a=new X.default(e)),e==="memory"&&(a=new Map),o?.forceStore&&(a=o.forceStore);super({store:a,namespace:i,ttl:s});this.url=e}static{h(this,"CacheExternal")}};var Y=require("timers/promises"),I=require("grammy");var V=class{static{h(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.payloads(this.msgText,"space",this.data._positionPayloadText)}get msgTextPayload(){return this.msgTextPayloads[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionPayloads(){return this.payloads(this.msgCaption,"space")}get msgCaptionPayload(){return this.msgCaptionPayloads[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataPayloads(){return this.payloads(this.callbackData,"colon")}get callbackDataPayload(){return this.callbackDataPayloads?.[0]}get callbackDataParts(){return this.callbackDataPayload&&this.callbackDataPayload.indexOf("+")!=-1?this.callbackDataPayload.split("+"):[]}set session(t){this.temp.session=t}get session(){return this.temp.session}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,i,s,o,a,n=!1){try{let c=e.map(l=>this.templateManager.getMessage(this.data.name,o,l,s));for(let l=0;l<t.length;l++){let d=t[l],p=c[l];await this.ct.api.sendMessage(d,p,{parse_mode:"HTML",reply_markup:i,...a}),l+1==30&&await(0,Y.setTimeout)(1200)}}catch(r){if(n)throw r}}async reply(t,e,i,s){let o=this.templateManager.getMessage(this.data.name,i,this.userLanguage,e);return await this.ct.reply(o,{parse_mode:"HTML",reply_markup:t,...s})}async replyMedia(t,e,i,s,o){let a=this.templateManager.getMedia(this.data.name,s,this.userLanguage,i),n={parse_mode:"HTML",reply_markup:e,...o};if(t=="photo")return await this.ct.replyWithPhoto(a.src,{caption:a.caption,...n});if(t=="video")return await this.ct.replyWithVideo(a.src,{caption:a.caption,...n});if(t=="audio")return await this.ct.replyWithAudio(a.src,{caption:a.caption,...n});if(t=="document")return await this.ct.replyWithDocument(a.src,{caption:a.caption,...n});if(t=="animation")return await this.ct.replyWithAnimation(a.src,{caption:a.caption,...n});if(t=="voice")return await this.ct.replyWithVoice(a.src,n);if(t=="video_note")return await this.ct.replyWithVideoNote(a.src,n);if(t=="sticker")return await this.ct.replyWithSticker(a.src,n);if(t=="location")return await this.ct.replyWithLocation(parseInt(a.latitude),parseInt(a.longitude),n);if(t=="contact")return await this.ct.replyWithContact(a.phone,a.first_name,{vcard:a.vcard,...n})}async replyPhoto(t,e,i,s){return this.replyMedia("photo",t,e,i,s)}async replyVideo(t,e,i,s){return this.replyMedia("video",t,e,i,s)}async replyAudio(t,e,i,s){return this.replyMedia("audio",t,e,i,s)}async replyDocument(t,e,i,s){return this.replyMedia("document",t,e,i,s)}async replyAnimation(t,e,i,s){return this.replyMedia("animation",t,e,i,s)}async replyVoice(t,e,i,s){return this.replyMedia("voice",t,e,i,s)}async replyVideoNote(t,e,i,s){return this.replyMedia("video_note",t,e,i,s)}async replySticker(t,e,i,s){return this.replyMedia("sticker",t,e,i,s)}async replyLocation(t,e,i,s){return this.replyMedia("location",t,e,i,s)}async replyContact(t,e,i,s){return this.replyMedia("contact",t,e,i,s)}async replyAction(t){return await this.ct.replyWithChatAction(t)}async edit(t,e,i,s,o=!0){try{let a=this.templateManager.getMessage(this.data.name,i,this.userLanguage,e);return await this.ct.editMessageText(a,{parse_mode:"HTML",reply_markup:t,...s})}catch(a){if(o)await this.reply(t,e,i,s);else throw a}}async editMedia(t,e,i,s,o,a,n=!0){try{let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,s,this.userLanguage,i);return t=="voice"?(await this.delete(),await this.replyVoice(e,i,s,o)):t=="video_note"?(await this.delete(),await this.replyVoice(e,i,s,o)):t=="sticker"?(await this.delete(),await this.replySticker(e,i,s,o)):t=="location"?(await this.delete(),await this.replyLocation(e,i,s,o)):t=="contact"?(await this.delete(),await this.replyContact(e,i,s,o)):await this.ct.editMessageMedia({media:r,caption:c,type:t,parse_mode:"HTML",...o},{reply_markup:e,...a})}catch(r){if(n===!0)await this.reply(e,i,s,a);else throw r}}async editPhoto(t,e,i,s,o){return await this.editMedia("photo",t,e,i,s,o)}async editVideo(t,e,i,s,o){return await this.editMedia("video",t,e,i,s,o)}async editAudio(t,e,i,s,o){return await this.editMedia("audio",t,e,i,s,o)}async editDocument(t,e,i,s,o){return await this.editMedia("document",t,e,i,s,o)}async editAnimation(t,e,i,s,o){return await this.editMedia("animation",t,e,i,s,o)}async editVoice(t,e,i,s){return await this.editMedia("voice",t,e,i,s)}async editVideoNote(t,e,i,s){return await this.editMedia("video_note",t,e,i,s)}async editSticker(t,e,i,s){return await this.editMedia("sticker",t,e,i,s)}async editLocation(t,e,i,s){return await this.editMedia("location",t,e,i,s)}async editContact(t,e,i,s){return await this.editMedia("contact",t,e,i,s)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(t){try{return await this.ct.answerCallbackQuery(t)}catch{return null}}async sessionSet(t,e,i){try{let s={method:t,params:e,...i},o=await this.cacheSession.set(`${this.userId}`,s);return o&&(this.session=s),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 i=typeof t=="function"?{callbackData:t}:t||{},s=i.callbackData;return{name:"",text:i.text,textCommand:i.textCommand,_positionPayloadText:i.text?i.text.split(this.prototype.seperatorTag("space")).length:void 0,callbackData:s?function(...a){let n=s(...a);return`${this.name}${n==""||n===void 0?"":`:${n}`}`}:function(){return this?.name}}}inlineKeyboard(t,e){let i=this.data.name;if(e?.cache===!0){let n=`${i}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(n);if(!r){let c=new I.InlineKeyboard,l=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"inline",e?.data),d=t(c,l);return this.cacheKeyboard.set(n,d),d}return r}let s=new I.InlineKeyboard,o=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"inline",e?.data);return t(s,o)}bottomKeyboard(t,e){let i=this.data.name;if(e?.cache===!0){let n=`${i}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(n);if(!r){let c=new I.Keyboard,l=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"bottom",e?.data),d=t(c,l);return d.resized(!0),this.cacheKeyboard.set(n,d),d}return r}let s=new I.Keyboard,o=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"bottom",e?.data),a=t(s,o);return a.resized(),a}seperatorTag(t="space"){return t=="space"?" ":":"}payloads(t="",e,i=1){let s=this.seperatorTag(e);return t?t.split(s).slice(i):[]}intent(t="",e,i=1){let s=this.seperatorTag(e);if(!t)return"";let o=t.split(s);return i==1?o[0]:o.slice(0,i).join(s)}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)}validateSessionVideoNoteCaption(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaption(e)}validateSessionVideoNoteCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionPayload(e)}validateSessionVideoNoteCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionCommand(e)}validateSessionVideoNoteCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionCommandPayload(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)}sessionVideoNoteCaption(t,e){return this.sessionSet(this.methodSessionVideoNoteCaption(e),t)}sessionVideoNoteCaptionPayload(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionPayload(e),t)}sessionVideoNoteCaptionCommand(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionCommand(e),t)}sessionVideoNoteCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionCommandPayload(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)}sessionToVideoNoteCaption(t,e){return this.sessionVideoNoteCaption({...this.session.params,...t},e)}sessionToVideoNoteCaptionPayload(t,e){return this.sessionVideoNoteCaptionPayload({...this.session.params,...t},e)}sessionToVideoNoteCaptionCommand(t,e){return this.sessionVideoNoteCaptionCommand({...this.session.params,...t},e)}sessionToVideoNoteCaptionCommandPayload(t,e){return this.sessionVideoNoteCaptionCommandPayload({...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)}methodSessionVideoNoteCaption(t){return this.methodSession("38",t)}methodSessionVideoNoteCaptionPayload(t){return this.methodSession("39",t)}methodSessionVideoNoteCaptionCommand(t){return this.methodSession("40",t)}methodSessionVideoNoteCaptionCommandPayload(t){return this.methodSession("41",t)}methodSessionVideoNoteFree(t){return this.methodSession("42",t)}methodSessionStickerFree(t){return this.methodSession("43",t)}methodSessionLocationFree(t){return this.methodSession("44",t)}methodSessionContactFree(t){return this.methodSession("45",t)}};var B=require("path");var $=require("path"),w=require("fs"),Z=require("module");var S=class{static{h(this,"PageManager")}static _getFile(t,e,i=0){let o=Object.values(t)[i];if(o===void 0)throw new Error(`File ${e} must have export (not default) class page`);return o}static getFilePath(){return(0,$.join)(process.cwd(),"src","pages")}static getFileSync(t,e=0){t||(t=this.getFilePath());let s=(0,Z.createRequire)(t)(t);return this._getFile(s,t,e)}static async getFile(t,e=0){t||(t=this.getFilePath());let i=await import(`${t}?t=${Date.now()}`);return this._getFile(i,t,e)}static getFileManySync(t,e=0){if(t||(t=this.getFilePath()),!(0,w.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,w.readdirSync)(t).map(s=>{let o=(0,$.join)(t,s);return{path:o,page:this.getFileSync(o,e)}})}static clearCacheRequire(t){if(t||(t=this.getFilePath()),!(0,w.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,w.readdirSync)(t).forEach(i=>{let s=(0,$.join)(t,i);delete require.cache[require.resolve(s)]}),!0}};var et=require("logging-pretty");var f=require("path"),y=require("fs"),tt=require("chokidar");var P=class{static{h(this,"TemplateEngine")}static _escape(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processVariables(t){return t.replace(/\{\{(\w+)\}\}/g,(e,i)=>`\${(data && data["${i}"]) ?? ""}`)}static _processBaseBlocks(t){let e=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,i={};for(let s of t.matchAll(e)){let o=s[2]??"default",n=(s[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();i[o]=n}return i}static _processScriptBlocks(t){return t.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(e,i)=>{let s=i.trim();return s?`\${(() => { if (!data) return ''; try { with(data) { ${s} } } 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,i)=>i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(t){let e=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return t.replace(e,(i,s,o)=>{if(!s)return"";let a="",n=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=n.exec(o))!==null;){let d=(c[1]||"").split(",").map(u=>u.trim()),p=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(u=>{a+=`case "${u}": `}),a+=`return \`${p}\`; `}let l=r.exec(o);if(l){let d=(l[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");a+=`default: return \`${d}\`; `}else a+="default: return ''; ";return`\${(() => { switch((data && data["${s}"])) { ${a} } })()}`})}static _processExec(t){return t.replace(/{~\s*([\s\S]*?)\s*~}/g,(e,i)=>`\${(() => { try { return ${i} } catch(e) { try { with(data || {}) { return ${i} } } catch(ee) { return '' } } })()}`)}static _processMapBlocks(t){let e=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return t.replace(e,(i,s,o)=>{let a={},n=/(\w+)="([^"]*)"/g;if(s)for(let p of s.matchAll(n))a[p[1]]=p[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,(p,u)=>u==="e"||u.startsWith("e.")?`\${${u}}`:u==="i"?"${i}":p);let d=c.replace(/"/g,'\\"');return`\${(data && data["${r}"] || []).map((e, i) => \`${l}\`).join("${d}")}`})}static _processMediaBlocks(t){let e=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,i={};for(let s of t.matchAll(e)){let o=s[1],a=s[2],n={},r=/(\w+)="([^"]*)"/g;if(o)for(let u of o.matchAll(r))n[u[1]]=u[2];let c=n.lang||"default",l=n.type,d=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),p={type:l};n.src&&(p.src=n.src),d&&l!=="video_note"&&l!=="sticker"&&(p.caption=d),l==="location"&&(n.latitude&&(p.latitude=n.latitude),n.longitude&&(p.longitude=n.longitude),d&&(p.caption=d)),l==="contact"&&(n.phone&&(p.phone=n.phone),n.first_name&&(p.first_name=n.first_name),n.last_name&&(p.last_name=n.last_name),n.vcard&&(p.vcard=n.vcard),d&&(p.caption=d)),i[c]=p}return i}static _processMessageBlocks(t){let e=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,i={};for(let[,s,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(s)for(let l of s.matchAll(n))a[l[1]]=l[2];let r=a.lang||"default",c=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();i[r]=c}return i}static _processDescriptionBlocks(t){let e=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,i={};for(let[,s,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(s)for(let d of s.matchAll(n))a[d[1]]=d[2];let r=a.lang||"default",c=a.scope||"default",l=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();i[r]||(i[r]={}),i[r][c]=l}return i}static _processKeyboardBlocks(t){let e=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,i={};for(let[,s,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(s)for(let d of s.matchAll(n))a[d[1]]=d[2];let r=a.lang||"default",c=a.type==="bottom"?"bottom":"inline",l=o.trim();i[r]||(i[r]={}),i[r][c]=l}return i}static _compileToFunction(t,e){let i;e?i=t.map(a=>`\`${a}\``).join(","):i=`\`${t}\``;let s=i;if(s=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(s))),e){let o=`return [${s}]`;return new Function("data",o)}else{let o=`return ${s}`;return new Function("data",o)}}static compileMedia(t,e){let i=e||this._processBaseBlocks(t),s={};for(let[o,a]of Object.entries(i)){let n=this._processMediaBlocks(a);s[o]={};for(let[r,c]of Object.entries(n)){let l={};for(let[d,p]of Object.entries(c)){if(d==="type"||typeof p!="string")continue;let u=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(p)))));l[d]=this._compileToFunction(u,!1)}s[o][r]=d=>{let p={...c};for(let[u,m]of Object.entries(l))p[u]=m(d);return p}}}return s}static compileMessages(t,e){let i=e||this._processBaseBlocks(t),s={};for(let[o,a]of Object.entries(i)){let n=this._processMessageBlocks(a);s[o]={};for(let[r,c]of Object.entries(n)){let l=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));s[o][r]=this._compileToFunction(l,!1)}}return s}static compileDescription(t,e){let i=e||this._processBaseBlocks(t),s={};for(let[o,a]of Object.entries(i)){let n=this._processDescriptionBlocks(a);s[o]={};for(let[r,c]of Object.entries(n))for(let[l,d]of Object.entries(c)){s[o][l]||(s[o][l]={});let p=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));s[o][l][r]=this._compileToFunction(p,!1)}}return s}static compileKeyboards(t,e){let i=e||this._processBaseBlocks(t),s={};for(let[o,a]of Object.entries(i)){let n=this._processKeyboardBlocks(a);s[o]={};for(let[r,c]of Object.entries(n)){s[o][r]={};for(let[l,d]of Object.entries(c)){let u=d.split(/(?<!\\),\s*/).map(m=>m.replace(/\\,/g,",").trim()).map(m=>this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(m))))));s[o][r][l]=this._compileToFunction(u,!0)}}}return s}static _extractBlock(t,e,i="default",s="all",o){let a=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,n=t,r=!1;for(let c of t.matchAll(a))if((c[2]??"default")===i){n=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(t);if(!(i==="default"&&!c))return""}if(e){if(e==="all")return n;let c=Array.isArray(e)?e:[e],l=[];for(let p of c){let u=new RegExp(`([ \\t]*)<${p}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${p}>`,"gi");for(let m of n.matchAll(u)){let b=m[2];if(o){let C=/lang="([^"]*)"/i,x=b?.match(C);if(((x?x[1]:void 0)||"default")!==o)continue}l.push({start:m.index,content:m[0],innerContent:m[3]??""})}}l.sort((p,u)=>p.start-u.start);let d=h(p=>{let u=p.split(`
|
|
2
|
-
`);if(u.length<=1)return p.trim();let m=u.filter(
|
|
1
|
+
"use strict";var ct=Object.create;var R=Object.defineProperty;var lt=Object.getOwnPropertyDescriptor;var dt=Object.getOwnPropertyNames;var pt=Object.getPrototypeOf,ut=Object.prototype.hasOwnProperty;var h=(g,t)=>R(g,"name",{value:t,configurable:!0});var ht=(g,t)=>{for(var e in t)R(g,e,{get:t[e],enumerable:!0})},G=(g,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dt(t))!ut.call(g,s)&&s!==e&&R(g,s,{get:()=>t[s],enumerable:!(i=lt(t,s))||i.enumerable});return g};var H=(g,t,e)=>(e=g!=null?ct(pt(g)):{},G(t||!g||!g.__esModule?R(e,"default",{value:g,enumerable:!0}):e,g)),mt=g=>G(R({},"__esModule",{value:!0}),g);var St={};ht(St,{CacheExternal:()=>V,ComponentKeyboard:()=>U,Ctx:()=>D,DataKeyboard:()=>q,Gramstax:()=>K,LoggingUtils:()=>B,TemplateEngine:()=>v,TemplateManager:()=>O,ThreadExport:()=>L,ThreadMain:()=>$,ThreadMainPool:()=>j,ThreadSub:()=>W,log:()=>yt});module.exports=mt(St);var gt=h(()=>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"),f=gt();var z=require("logging-pretty");var B=class extends z.LoggingPretty{static{h(this,"LoggingUtils")}constructor(t){super(t)}errorMake(t,e,i){this.error(`[${e?.name||e}:${i}] ${String(t)}`)}},yt=new B;var X=require("keyv"),Y=H(require("@keyv/redis"),1);var V=class extends X.Keyv{constructor(e="memory",i,s,o){let a;e.startsWith("redis")&&(a=new Y.default(e)),e==="memory"&&(a=new Map),o?.forceStore&&(a=o.forceStore);super({store:a,namespace:i,ttl:s});this.url=e}static{h(this,"CacheExternal")}};var Z=require("timers/promises"),_=require("grammy");var D=class{static{h(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.payloads(this.msgText,"space",this.data._positionPayloadText)}get msgTextPayload(){return this.msgTextPayloads[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionPayloads(){return this.payloads(this.msgCaption,"space")}get msgCaptionPayload(){return this.msgCaptionPayloads[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataPayloads(){return this.payloads(this.callbackData,"colon")}get callbackDataPayload(){return this.callbackDataPayloads?.[0]}get callbackDataParts(){return this.callbackDataPayload&&this.callbackDataPayload.indexOf("+")!=-1?this.callbackDataPayload.split("+"):[]}set session(t){this.temp.session=t}get session(){return this.temp.session}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,i,s,o,a,n=!1){try{let c=e.map(l=>this.templateManager.getMessage(this.data.name,o,l,s));for(let l=0;l<t.length;l++){let d=t[l],p=c[l];await this.ct.api.sendMessage(d,p,{parse_mode:"HTML",reply_markup:i,...a}),l+1==30&&await(0,Z.setTimeout)(1200)}}catch(r){if(n)throw r}}async reply(t,e,i,s){let o=this.templateManager.getMessage(this.data.name,i,this.userLanguage,e);return await this.ct.reply(o,{parse_mode:"HTML",reply_markup:t,...s})}async replyMedia(t,e,i,s,o){let a=this.templateManager.getMedia(this.data.name,s,this.userLanguage,i),n={parse_mode:"HTML",reply_markup:e,...o};if(t=="photo")return await this.ct.replyWithPhoto(a.src,{caption:a.caption,...n});if(t=="video")return await this.ct.replyWithVideo(a.src,{caption:a.caption,...n});if(t=="audio")return await this.ct.replyWithAudio(a.src,{caption:a.caption,...n});if(t=="document")return await this.ct.replyWithDocument(a.src,{caption:a.caption,...n});if(t=="animation")return await this.ct.replyWithAnimation(a.src,{caption:a.caption,...n});if(t=="voice")return await this.ct.replyWithVoice(a.src,n);if(t=="video_note")return await this.ct.replyWithVideoNote(a.src,n);if(t=="sticker")return await this.ct.replyWithSticker(a.src,n);if(t=="location")return await this.ct.replyWithLocation(parseInt(a.latitude),parseInt(a.longitude),n);if(t=="contact")return await this.ct.replyWithContact(a.phone,a.first_name,{vcard:a.vcard,...n})}async replyPhoto(t,e,i,s){return this.replyMedia("photo",t,e,i,s)}async replyVideo(t,e,i,s){return this.replyMedia("video",t,e,i,s)}async replyAudio(t,e,i,s){return this.replyMedia("audio",t,e,i,s)}async replyDocument(t,e,i,s){return this.replyMedia("document",t,e,i,s)}async replyAnimation(t,e,i,s){return this.replyMedia("animation",t,e,i,s)}async replyVoice(t,e,i,s){return this.replyMedia("voice",t,e,i,s)}async replyVideoNote(t,e,i,s){return this.replyMedia("video_note",t,e,i,s)}async replySticker(t,e,i,s){return this.replyMedia("sticker",t,e,i,s)}async replyLocation(t,e,i,s){return this.replyMedia("location",t,e,i,s)}async replyContact(t,e,i,s){return this.replyMedia("contact",t,e,i,s)}async replyAction(t){return await this.ct.replyWithChatAction(t)}async edit(t,e,i,s,o=!0){try{let a=this.templateManager.getMessage(this.data.name,i,this.userLanguage,e);return await this.ct.editMessageText(a,{parse_mode:"HTML",reply_markup:t,...s})}catch(a){if(o)await this.reply(t,e,i,s);else throw a}}async editMedia(t,e,i,s,o,a,n=!0){try{let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,s,this.userLanguage,i);return t=="voice"?(await this.delete(),await this.replyVoice(e,i,s,o)):t=="video_note"?(await this.delete(),await this.replyVoice(e,i,s,o)):t=="sticker"?(await this.delete(),await this.replySticker(e,i,s,o)):t=="location"?(await this.delete(),await this.replyLocation(e,i,s,o)):t=="contact"?(await this.delete(),await this.replyContact(e,i,s,o)):await this.ct.editMessageMedia({media:r,caption:c,type:t,parse_mode:"HTML",...o},{reply_markup:e,...a})}catch(r){if(n===!0)await this.reply(e,i,s,a);else throw r}}async editPhoto(t,e,i,s,o){return await this.editMedia("photo",t,e,i,s,o)}async editVideo(t,e,i,s,o){return await this.editMedia("video",t,e,i,s,o)}async editAudio(t,e,i,s,o){return await this.editMedia("audio",t,e,i,s,o)}async editDocument(t,e,i,s,o){return await this.editMedia("document",t,e,i,s,o)}async editAnimation(t,e,i,s,o){return await this.editMedia("animation",t,e,i,s,o)}async editVoice(t,e,i,s){return await this.editMedia("voice",t,e,i,s)}async editVideoNote(t,e,i,s){return await this.editMedia("video_note",t,e,i,s)}async editSticker(t,e,i,s){return await this.editMedia("sticker",t,e,i,s)}async editLocation(t,e,i,s){return await this.editMedia("location",t,e,i,s)}async editContact(t,e,i,s){return await this.editMedia("contact",t,e,i,s)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(t){try{return await this.ct.answerCallbackQuery(t)}catch{return null}}async sessionSet(t,e,i){try{let s={method:t,params:e,...i},o=await this.cacheSession.set(`${this.userId}`,s);return o&&(this.session=s),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 i=typeof t=="function"?{callbackData:t}:t||{},s=i.callbackData;return{name:"",text:i.text,textCommand:i.textCommand,_positionPayloadText:i.text?i.text.split(this.prototype.seperatorTag("space")).length:void 0,callbackData:s?function(...a){let n=s(...a);return`${this.name}${n==""||n===void 0?"":`:${n}`}`}:function(){return this?.name}}}inlineKeyboard(t,e){let i=this.data.name;if(e?.cache===!0){let n=`${i}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(n);if(!r){let c=new _.InlineKeyboard,l=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"inline",e?.data),d=t(c,l);return this.cacheKeyboard.set(n,d),d}return r}let s=new _.InlineKeyboard,o=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"inline",e?.data);return t(s,o)}bottomKeyboard(t,e){let i=this.data.name;if(e?.cache===!0){let n=`${i}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(n);if(!r){let c=new _.Keyboard,l=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"bottom",e?.data),d=t(c,l);return d.resized(!0),this.cacheKeyboard.set(n,d),d}return r}let s=new _.Keyboard,o=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"bottom",e?.data),a=t(s,o);return a.resized(),a}seperatorTag(t="space"){return t=="space"?" ":":"}payloads(t="",e,i=1){let s=this.seperatorTag(e);return t?t.split(s).slice(i):[]}intent(t="",e,i=1){let s=this.seperatorTag(e);if(!t)return"";let o=t.split(s);return i==1?o[0]:o.slice(0,i).join(s)}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)}validateSessionVideoNoteCaption(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaption(e)}validateSessionVideoNoteCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionPayload(e)}validateSessionVideoNoteCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionCommand(e)}validateSessionVideoNoteCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionCommandPayload(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)}sessionVideoNoteCaption(t,e){return this.sessionSet(this.methodSessionVideoNoteCaption(e),t)}sessionVideoNoteCaptionPayload(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionPayload(e),t)}sessionVideoNoteCaptionCommand(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionCommand(e),t)}sessionVideoNoteCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionCommandPayload(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)}sessionToVideoNoteCaption(t,e){return this.sessionVideoNoteCaption({...this.session.params,...t},e)}sessionToVideoNoteCaptionPayload(t,e){return this.sessionVideoNoteCaptionPayload({...this.session.params,...t},e)}sessionToVideoNoteCaptionCommand(t,e){return this.sessionVideoNoteCaptionCommand({...this.session.params,...t},e)}sessionToVideoNoteCaptionCommandPayload(t,e){return this.sessionVideoNoteCaptionCommandPayload({...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)}methodSessionVideoNoteCaption(t){return this.methodSession("38",t)}methodSessionVideoNoteCaptionPayload(t){return this.methodSession("39",t)}methodSessionVideoNoteCaptionCommand(t){return this.methodSession("40",t)}methodSessionVideoNoteCaptionCommandPayload(t){return this.methodSession("41",t)}methodSessionVideoNoteFree(t){return this.methodSession("42",t)}methodSessionStickerFree(t){return this.methodSession("43",t)}methodSessionLocationFree(t){return this.methodSession("44",t)}methodSessionContactFree(t){return this.methodSession("45",t)}};var x=require("path"),st=require("fs"),it=require("url");var N=require("path"),F=require("fs"),tt=require("module");var P=class{static{h(this,"PageManager")}static _getFile(t,e,i=0){let o=Object.values(t)[i];if(o===void 0)throw new Error(`File ${e} must have export (not default) class page`);return o}static getFilePath(){return(0,N.join)(process.cwd(),"src","pages")}static getFileSync(t,e=0){t||(t=this.getFilePath());let s=(0,tt.createRequire)(t)(t);return this._getFile(s,t,e)}static async getFile(t,e=0){t||(t=this.getFilePath());let i=await import(`${t}?t=${Date.now()}`);return this._getFile(i,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(s=>{let o=(0,N.join)(t,s);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(i=>{let s=(0,N.join)(t,i);delete require.cache[require.resolve(s)]}),!0}};var nt=require("logging-pretty");var C=require("path"),y=require("fs"),et=require("chokidar");var v=class{static{h(this,"TemplateEngine")}static _escape(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processVariables(t){return t.replace(/\{\{(\w+)\}\}/g,(e,i)=>`\${(data && data["${i}"]) ?? ""}`)}static _processBaseBlocks(t){let e=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,i={};for(let s of t.matchAll(e)){let o=s[2]??"default",n=(s[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();i[o]=n}return i}static _processScriptBlocks(t){return t.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(e,i)=>{let s=i.trim();return s?`\${(() => { if (!data) return ''; try { with(data) { ${s} } } 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,i)=>i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(t){let e=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return t.replace(e,(i,s,o)=>{if(!s)return"";let a="",n=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=n.exec(o))!==null;){let d=(c[1]||"").split(",").map(u=>u.trim()),p=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(u=>{a+=`case "${u}": `}),a+=`return \`${p}\`; `}let l=r.exec(o);if(l){let d=(l[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");a+=`default: return \`${d}\`; `}else a+="default: return ''; ";return`\${(() => { switch((data && data["${s}"])) { ${a} } })()}`})}static _processExec(t){return t.replace(/{~\s*([\s\S]*?)\s*~}/g,(e,i)=>`\${(() => { try { return ${i} } catch(e) { try { with(data || {}) { return ${i} } } catch(ee) { return '' } } })()}`)}static _processMapBlocks(t){let e=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return t.replace(e,(i,s,o)=>{let a={},n=/(\w+)="([^"]*)"/g;if(s)for(let p of s.matchAll(n))a[p[1]]=p[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,(p,u)=>u==="e"||u.startsWith("e.")?`\${${u}}`:u==="i"?"${i}":p);let d=c.replace(/"/g,'\\"');return`\${(data && data["${r}"] || []).map((e, i) => \`${l}\`).join("${d}")}`})}static _processMediaBlocks(t){let e=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,i={};for(let s of t.matchAll(e)){let o=s[1],a=s[2],n={},r=/(\w+)="([^"]*)"/g;if(o)for(let u of o.matchAll(r))n[u[1]]=u[2];let c=n.lang||"default",l=n.type,d=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),p={type:l};n.src&&(p.src=n.src),d&&l!=="video_note"&&l!=="sticker"&&(p.caption=d),l==="location"&&(n.latitude&&(p.latitude=n.latitude),n.longitude&&(p.longitude=n.longitude),d&&(p.caption=d)),l==="contact"&&(n.phone&&(p.phone=n.phone),n.first_name&&(p.first_name=n.first_name),n.last_name&&(p.last_name=n.last_name),n.vcard&&(p.vcard=n.vcard),d&&(p.caption=d)),i[c]=p}return i}static _processMessageBlocks(t){let e=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,i={};for(let[,s,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(s)for(let l of s.matchAll(n))a[l[1]]=l[2];let r=a.lang||"default",c=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();i[r]=c}return i}static _processDescriptionBlocks(t){let e=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,i={};for(let[,s,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(s)for(let d of s.matchAll(n))a[d[1]]=d[2];let r=a.lang||"default",c=a.scope||"default",l=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();i[r]||(i[r]={}),i[r][c]=l}return i}static _processKeyboardBlocks(t){let e=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,i={};for(let[,s,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(s)for(let d of s.matchAll(n))a[d[1]]=d[2];let r=a.lang||"default",c=a.type==="bottom"?"bottom":"inline",l=o.trim();i[r]||(i[r]={}),i[r][c]=l}return i}static _compileToFunction(t,e){let i;e?i=t.map(a=>`\`${a}\``).join(","):i=`\`${t}\``;let s=i;if(s=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(s))),e){let o=`return [${s}]`;return new Function("data",o)}else{let o=`return ${s}`;return new Function("data",o)}}static compileMedia(t,e){let i=e||this._processBaseBlocks(t),s={};for(let[o,a]of Object.entries(i)){let n=this._processMediaBlocks(a);s[o]={};for(let[r,c]of Object.entries(n)){let l={};for(let[d,p]of Object.entries(c)){if(d==="type"||typeof p!="string")continue;let u=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(p)))));l[d]=this._compileToFunction(u,!1)}s[o][r]=d=>{let p={...c};for(let[u,m]of Object.entries(l))p[u]=m(d);return p}}}return s}static compileMessages(t,e){let i=e||this._processBaseBlocks(t),s={};for(let[o,a]of Object.entries(i)){let n=this._processMessageBlocks(a);s[o]={};for(let[r,c]of Object.entries(n)){let l=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));s[o][r]=this._compileToFunction(l,!1)}}return s}static compileDescription(t,e){let i=e||this._processBaseBlocks(t),s={};for(let[o,a]of Object.entries(i)){let n=this._processDescriptionBlocks(a);s[o]={};for(let[r,c]of Object.entries(n))for(let[l,d]of Object.entries(c)){s[o][l]||(s[o][l]={});let p=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));s[o][l][r]=this._compileToFunction(p,!1)}}return s}static compileKeyboards(t,e){let i=e||this._processBaseBlocks(t),s={};for(let[o,a]of Object.entries(i)){let n=this._processKeyboardBlocks(a);s[o]={};for(let[r,c]of Object.entries(n)){s[o][r]={};for(let[l,d]of Object.entries(c)){let u=d.split(/(?<!\\),\s*/).map(m=>m.replace(/\\,/g,",").trim()).map(m=>this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(m))))));s[o][r][l]=this._compileToFunction(u,!0)}}}return s}static _extractBlock(t,e,i="default",s="all",o){let a=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,n=t,r=!1;for(let c of t.matchAll(a))if((c[2]??"default")===i){n=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(t);if(!(i==="default"&&!c))return""}if(e){if(e==="all")return n;let c=Array.isArray(e)?e:[e],l=[];for(let p of c){let u=new RegExp(`([ \\t]*)<${p}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${p}>`,"gi");for(let m of n.matchAll(u)){let b=m[2];if(o){let S=/lang="([^"]*)"/i,I=b?.match(S);if(((I?I[1]:void 0)||"default")!==o)continue}l.push({start:m.index,content:m[0],innerContent:m[3]??""})}}l.sort((p,u)=>p.start-u.start);let d=h(p=>{let u=p.split(`
|
|
2
|
+
`);if(u.length<=1)return p.trim();let m=u.filter(S=>S.trim().length>0);if(m.length===0)return"";let b=m.reduce((S,I)=>{let M=I.match(/^([ \t]*)/),k=M?M[1].length:0;return k<S?k:S},1/0);return u.map(S=>S.length>=b?S.slice(b):S.trimStart()).join(`
|
|
3
3
|
`).trim()},"processResult");return s==="all"?l.map(u=>d(u.content)).join(`
|
|
4
4
|
`):l.map(u=>d(u.innerContent)).join(`
|
|
5
5
|
`)}return n}static _processImportBlocks(t){let e=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,i=[];return{processed:t.replace(e,(o,a,n)=>{let r={},c=/(\w+)="([^"]*)"/g;if(n)for(let u of n.matchAll(c))r[u[1]]=u[2];let l=r.src;if(!l)return"";let d;r.block&&(r.block==="all"?d="all":r.block.includes(",")?d=r.block.split(",").map(u=>u.trim()).filter(u=>u):d=r.block);let p={src:l,blocks:d,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:a||""};return i.push(p),`${a}__IMPORT_${i.length-1}__`}),imports:i}}static processImportBlocks(t,e,i=0,s){if(i>10)return"";let{processed:o,imports:a}=this._processImportBlocks(t),n=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||""}`,d;if(s&&s.has(l))d=s.get(l);else{let u=e(c.src);d=u?this._extractBlock(u,c.blocks,c.base,c.section,c.lang):"",d&&d.includes("<import")&&(d=this.processImportBlocks(d,e,i+1,s)),s&&s.set(l,d)}let p=d.split(`
|
|
6
6
|
`).map((u,m)=>m===0?u:c.indent+u).join(`
|
|
7
|
-
`);n=n.replace(`__IMPORT_${r}__`,p)}return n}};var R=class{static{h(this,"TemplateManager")}_map=new Map;_engine=P;_watcher=[];_pageManager=S;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(t){let{path:e,enableWatch:i=!1}=t;this._path=e,this._isWatchEnabled=i,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,y.existsSync)(e))throw new Error(`Template base path is not exists: ${e}`);if(!(0,y.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 i=this._path[e],s=(0,tt.watch)(i,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...t});this._watcher[e]=s,s.on("change",this._handleFileChange.bind(this)),s.on("add",this._handleFileAdd.bind(this)),s.on("unlink",this._handleFileDelete.bind(this)),s.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(t){let e=(0,f.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileAdd(t){let e=(0,f.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileDelete(t){let e=(0,f.basename)(t),i=this._getKey(e);this._map.has(i)&&this._map.delete(i)}_handleWatchError(t){}_loadAllFiles(){let t=new Map,e=[];for(let s=0;s<this._path.length;s++){let o=this._path[s],n=(0,y.readdirSync)(o,"utf8").filter(r=>this._isValidFile(r));for(let r of n){let c=(0,f.join)(o,r),l=this._getExtension(r),d=this._getKey(r);if(l===".html")t.set(d,(0,y.readFileSync)(c,"utf8"));else if(l===".ts"||l===".js"){let p=S.getFileSync(c);p?.template!==void 0&&(t.set(d,p.template),e.push(p))}}}let i=new Map;for(let[s,o]of t.entries())this._compile(s,o,void 0,i,t);t.clear(),i.clear();for(let s of e)s.template=void 0}_loadFile(t){for(let e=0;e<this._path.length;e++){let i=this._path[e],s=(0,f.join)(i,t),o=this._getExtension(t),a=this._getKey(t);if(o==".html"){let n=(0,y.readFileSync)(s,"utf8");this._compile(a,n)}else if(o==".ts"||o==".js"){let n=S.getFileSync(s);n?.template!==void 0&&(this._compile(a,n.template),n.template=void 0)}else throw new Error(`File ${t} is not support`)}}_getExtension(t){return(0,f.extname)(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let i=(0,f.extname)(t).toLowerCase();if(i){let n=(0,f.join)(e,t);if((0,y.existsSync)(n)&&(0,y.statSync)(n).isFile()){if(i===".html")return(0,y.readFileSync)(n,"utf8");if(i===".ts"||i===".js")try{return S.getFileSync(n)?.template??null}catch{return null}}continue}let s=(0,f.join)(e,`${t}.ts`),o=(0,f.join)(e,`${t}.js`);if((0,y.existsSync)(s)&&(0,y.statSync)(s).isFile())try{return S.getFileSync(s)?.template??null}catch{}else if((0,y.existsSync)(o)&&(0,y.statSync)(o).isFile())try{return S.getFileSync(s)?.template??null}catch{}let a=(0,f.join)(e,`${t}.html`);if((0,y.existsSync)(a)&&(0,y.statSync)(a).isFile())return(0,y.readFileSync)(a,"utf8")}return null}_isValidFile(t){return this._supportedExtensions.has(this._getExtension(t))}_getKey(t){return t.replace(/\.[^/.]+$/,"")}_compile(t,e,i,s,o){let a=this._map.get(t),n=a||{},r=!1,c=P.processImportBlocks(e,d=>o&&o.has(d)?o.get(d):this._readTemplateFile(d),0,s),l=P._processBaseBlocks(c);(i===void 0||i?.media===!1||a?.media===void 0)&&(n.media=P.compileMedia(c,l),r=!0),(i===void 0||i?.message===!1||a?.message===void 0)&&(n.message=P.compileMessages(c,l),r=!0),(i===void 0||i?.keyboard===!1||a?.keyboard===void 0)&&(n.keyboard=P.compileKeyboards(c,l),r=!0),(i===void 0||i?.description===!1||a?.description===void 0)&&(n.description=P.compileDescription(c,l),r=!0),r&&this._map.set(t,n)}getMedia(t,e="default",i="default",s){let a=this._map.get(t)?.media?.[e],n=a?.[i]||a?.default;try{if(!n)throw new Error("Media function not found, please check your template");return n(s)}catch{return{}}}getMessage(t,e="default",i="default",s){try{let a=this._map.get(t)?.message?.[e],n=a?.[i]||a?.default;if(!n)throw"";return n(s)}catch{return""}}getDescription(t,e="default",i="default",s="default",o){try{let n=this._map.get(t)?.description?.[e]?.[s],r=n?.[i]||n?.default;if(!r)throw"";return r(o)}catch{return""}}getDescriptionLanguage(t,e="default",i="default"){try{let o=this._map.get(t)?.description?.[e]?.[i];return o?Object.keys(o):[]}catch{return[]}}getDescriptionScopes(t,e="default"){try{let s=this._map.get(t)?.description?.[e];return s?Object.keys(s):[]}catch{return[]}}getKeyboard(t,e="default",i="default",s="inline",o){try{let n=this._map.get(t)?.keyboard?.[e],r=n?.[i]?.[s]||n?.default?.[s];if(!r)throw[];return r(o)}catch{return[]}}async write(t,e){if(this._getExtension(t)!=".html")return null;for(let i=0;i<this._path.length;i++){let s=(0,f.join)(this._path[i],t);if((0,y.existsSync)(s))return(0,y.writeFileSync)(s,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 D=require("grammy");var E=class{static{h(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;log;bot;handlerBotUpdate;constructor(t){if(!t?.token||t?.token?.length==0)throw new Error("Token is not valid or empty");if(this.log=t.log===!0?new et.LoggingPretty:t.log?t.log:void 0,this.log?.info?.("Gramstax v0.3.6"),this.cacheSession=t.cacheSession||new F("memory","session"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new R({path:[(0,B.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){this.log?.error?.(`[Bot.catch]: ${JSON.stringify(t,null,2)}`)}hookBeforeStart(){}hookAfterStart(){}async onStart(t,e,i){await this.executeSyncBlocksDescription(this.pages);let{username:s}=t;this.log?.success?.(`Telegram bot polling started: ${s} ${e=="webhook"||e=="serverless"?`(${i})`:""}`),this.hookAfterStart()}createBot(t){return new D.Bot(t)}createCtx(t){return new V({ct:t,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{session:{},data:{}}})}runPolling(){this.bot.start({onStart:h(t=>{this.onStart(t,"polling",null)},"onStart")})}async runWebhook(t){let{serve:e}=await import("bun"),i=(0,D.webhookCallback)(this.bot,"bun");this.handlerBotUpdate=i;let s=new URL(t).pathname;e({fetch(n){let{pathname:r}=new URL(n.url);if(n.method=="POST"&&r==s)return i(n);if(n.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,D.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()),t.data.name=(0,B.parse)(e).name}pageSorts(t,e){let i=t.data.name,s=t.prototype,o="Payload",a="Command",n="Caption",r="Free",c=e.routeDynamic,l=e.routeDynamicSpesific,d=h(m=>m.charAt(0).toUpperCase()+m.slice(1),"upFirst"),p=h(m=>m.replace(o,"").replace(a,"").replace(n,"").replace(r,""),"getPureRouteName"),u=h((m,b)=>s[`methodSession${d(m)}`]?.(b),"methodSession");e.all[i]=t;for(let m=0;m<e.lenListRouteStaticSession;m++){let b=e.listRouteStaticSession[m];if(typeof s[b]!="function")continue;let C=e.routeStatic[b],x=e.routeStaticIntent[b],T=e.routeStaticSession[b],v={name:i,routeName:b},Q=C||x;if(Q!==void 0){let st=b.includes(a),it=b.includes("callback"),nt=b.startsWith("text"),M;if(st){let G=t.data.textCommand||t.data.name;M=G?`/${G}`:void 0}else it?M=t.data.name:nt?M=t.data.text||t.data.name:M=t.data.name;M&&(Q[M]=v)}T!==void 0&&(T[u(b,i)]=v),b.toLowerCase().endsWith("free")&&l[p(b)].push(v)}s.free&&c.push(i)}async executeSyncBlocksDescription(t){let e=new Map,i=t.routeStatic.textCommand;for(let[,s]of Object.entries(i)){let o=s.name,a=this.templateManager.getDescriptionScopes(o);for(let n of a){e.has(n)||e.set(n,new Set);let r=this.templateManager.getDescriptionLanguage(o,"default",n);for(let c of r)e.get(n).add(c)}}for(let[s,o]of e)for(let a of o){let n=[];for(let[,l]of Object.entries(i)){let d=l.name,p=this.templateManager.getDescription(d,"default",a,s);p&&n.push({command:d,description:p})}if(n.length===0)continue;let r={type:s},c=a==="default"?void 0:a;try{let l=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(l.map(u=>({command:u.command,description:u.description})).sort((u,m)=>u.command.localeCompare(m.command))),p=JSON.stringify(n.sort((u,m)=>u.command.localeCompare(m.command)));d!==p&&(await this.bot.api.setMyCommands(n,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${s},${c?` lang: ${c},`:""} total (${n.length})`))}catch(l){this.log?.error?.(`Failed to sync descriptions for scope: ${s},${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","videoNoteCaption","videoNoteCaptionCommand"],e=["callbackPayload","textPayload","textCommandPayload","photoCaptionPayload","photoCaptionCommandPayload","videoCaptionPayload","videoCaptionCommandPayload","audioCaptionPayload","audioCaptionCommandPayload","documentCaptionPayload","documentCaptionCommandPayload","animationCaptionPayload","animationCaptionCommandPayload","voiceCaptionPayload","voiceCaptionCommandPayload","videoNoteCaptionPayload","videoNoteCaptionCommandPayload"],i=[...t,...e,"textFree","photoFree","videoFree","audioFree","documentFree","animationFree","voiceFree","videoNoteFree","stickerFree","locationFree","contactFree"],s=h((n,r)=>Object.fromEntries(n.map(c=>[c,r()])),"makeObject"),o=h(()=>[],"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:s(t,()=>({})),routeStaticIntent:s(e,()=>({})),routeStaticSession:s(i,()=>({})),listRouteStatic:t,listRouteStaticIntent:e,listRouteStaticSession:i,lenListRouteStatic:t.length,lenListRouteStaticIntent:e.length,lenListRouteStaticSession:i.length};return S.getFileManySync(void 0).forEach(({path:n,page:r})=>{this.pageBuildData(r,n),this.pageSorts(r,a),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(a.all).length})`),a}async pageRoutes(t,e){let i,s;if(i===void 0){let a=t.callbackData,n=t.msgText,r=t.msgCaption,c=this.pages.routeStatic;for(let l=0;l<this.pages.lenListRouteStatic;l++){let d=this.pages.listRouteStatic[l];if(d.startsWith(e)&&(s=c[d][a||n||r]),s)break}s!==void 0&&(i=this.pages.all[s.name])}if(i===void 0){let a=await t.sessionGet();if(a){let n=a.method,r=this.pages.routeStaticSession;for(let c=0;c<this.pages.lenListRouteStaticSession;c++){let l=this.pages.listRouteStaticSession[c];if(l.startsWith(e)&&(s=r[l][n]),s)break}s!==void 0&&(i=this.pages.all[s.name])}}if(i===void 0){let a=this.pages.routeStaticIntent,n=e==="callback",r=n?t.callbackData:t.msgText||t.msgCaption;if(r)for(let c=0;c<this.pages.lenListRouteStaticIntent;c++){let l=this.pages.listRouteStaticIntent[c];if(l.startsWith(e)){let d=a[l];s=d[t.intent(r,n?"colon":"space",1)],!s&&!n&&(s=d[t.intent(r,"space",2)])}if(s)break}s!==void 0&&(i=this.pages.all[s.name])}if(i!==void 0&&s!==void 0)return i.prototype[s.routeName]?await new i(t)[s.routeName]?.():void 0;let o=this.pages.routeDynamicSpesific[e]||[];for(let a=0;a<o.length;a++){let n=o[a];if(n===void 0)continue;let r=this.pages.all[n.name];if(r===void 0||!r.prototype[n.routeName])continue;let l=await new r(t)[n.routeName]?.();if(l!==null)return l}for(let a=0;a<this.pages.routeDynamic.length;a++){let n=this.pages.routeDynamic[a];if(n===void 0)continue;let r=this.pages.all[n];if(r===void 0||!r.prototype.free)continue;let l=await new r(t).free?.();if(l!==null)return l}return null}async hookBeforeRoute(t,e){return!!(t||e)}async hookErrorPage(t,e,i,s){}async hookErrorInputNotFoundPage(t){}async onMessage(t,e){let i=this.createCtx(t);try{if(await this.hookBeforeRoute(i,e)===!1)return;await this.pageRoutes(i,e)===null&&await this.hookErrorInputNotFoundPage(i)}catch(s){await this.hookErrorPage(i,e,s,!1)}}async onCallbackQueryData(t){let e=this.createCtx(t);try{if(await e.callbackQueryAnswer(),await this.hookBeforeRoute(e,"onCallbackQueryData")===!1)return;await this.pageRoutes(e,"callback")}catch(i){await this.hookErrorPage(e,"onCallbackQueryData",i,!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 N=require("worker_threads");var O=class{constructor(t,e){this.path=t;this.argv=e;if(!N.isMainThread)throw new Error("Is not main thread");this.sub=new N.Worker(t,{argv:e}),this.subId=this.sub.threadId,this.sub.on("message",async i=>{let{id:s,method:o,params:a,result:n}=i;if(o!==void 0){let r=this[o];if(typeof r!="function")throw new Error(`Method ${o} not found`);let c=await r.apply(this,a);this.send({id:s,result:c})}else if(n!==void 0){let r=this.map.get(s);r&&(r?.(n),this.map.delete(s))}})}static{h(this,"ThreadMain")}map=new Map;sub;pid=process.pid;subId;createId(){return Math.random()}send(t){this.sub.postMessage(t)}async sendRequest(t,e,i=!0){let s=this.createId();return i?new Promise(o=>{this.map.set(s,o),this.send({id:s,method:t,params:e})}):this.send({id:s,method:t,params:e})}kill(){this.sub.terminate()}};var K=class{static{h(this,"ThreadExport")}static init(t){let{CSub:e,CMain:i=O,path:s,wrap:o}=t,a=`for-${s}`;if(process.argv[2]===a)return new e,{};let n,r=new Proxy({},{get(d,p){return p==="sendRequest"?(u,m,b=!0)=>{if(!n)throw new Error(`Thread at ${s} not launched yet.`);return n.sendRequest(u,m,b)}:(...u)=>{if(!n)throw new Error(`Thread at ${s} not launched yet.`);return n.sendRequest(p,u)}}});return{...o?o(r):{},launch:h((d=[])=>(n=new i(s,[a,...d]),n),"launch")}}};var L=class{static{h(this,"ThreadMainPool")}thread={};threadCount=0;constructor(t){t.forEach(async e=>{let i=await e;this.thread[i.subId]=i,this.threadCount+=1})}add(t){this.thread[t.subId]=t,this.threadCount+=1}getInstance(t){return this.thread[t]}killAll(){return Object.values(this.thread).map(({subId:t})=>this.kill(t))}kill(t){let e=this.thread[t];return e?.kill(),delete this.thread[t],this.threadCount-=1,e?.subId}async broadcastRequest(t,e){return await Promise.all(Object.values(this.thread).map(i=>i.sendRequest(t,e,!0)))}async sendRequest(t,e,i,s=!0){return await this.thread[t]?.sendRequest(e,i,s)}};var k=require("worker_threads");var W=class{static{h(this,"ThreadSub")}map=new Map;argv=process.argv;id=k.threadId;pid=process.pid;threadIsMain=k.isMainThread;constructor(){if(this.threadIsMain)throw new Error("Is not sub thread");k.parentPort.on("message",async t=>{let{id:e,method:i,params:s,result:o}=t;if(i!==void 0)try{let a=this[i];if(typeof a!="function")throw new Error(`Method ${i} not found`);let n=await a.apply(this,s);this.send({id:e,result:n})}catch(a){this.send({id:e,error:a})}else if(o!==void 0){let a=this.map.get(e);a&&(a?.(o),this.map.delete(e))}})}createId(){return Math.random()}send(t){k.parentPort.postMessage(t)}async sendRequest(t,e,i=!0){let s=this.createId();return i?new Promise(o=>{this.map.set(s,o),this.send({id:s,method:t,params:e})}):this.send({id:s,method:t,params:e})}};var j=class{static{h(this,"ComponentKeyboard")}static data;static _process(t,e){if(e.type||(e.type="inline"),e.lang){let i=t[e.lang];return`
|
|
7
|
+
`);n=n.replace(`__IMPORT_${r}__`,p)}return n}};var O=class{static{h(this,"TemplateManager")}_map=new Map;_engine=v;_watcher=[];_pageManager=P;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(t){let{path:e,enableWatch:i=!1}=t;this._path=e,this._isWatchEnabled=i,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,y.existsSync)(e))throw new Error(`Template base path is not exists: ${e}`);if(!(0,y.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 i=this._path[e],s=(0,et.watch)(i,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...t});this._watcher[e]=s,s.on("change",this._handleFileChange.bind(this)),s.on("add",this._handleFileAdd.bind(this)),s.on("unlink",this._handleFileDelete.bind(this)),s.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(t){let e=(0,C.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileAdd(t){let e=(0,C.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileDelete(t){let e=(0,C.basename)(t),i=this._getKey(e);this._map.has(i)&&this._map.delete(i)}_handleWatchError(t){}_loadAllFiles(){let t=new Map,e=[];for(let s=0;s<this._path.length;s++){let o=this._path[s],n=(0,y.readdirSync)(o,"utf8").filter(r=>this._isValidFile(r));for(let r of n){let c=(0,C.join)(o,r),l=this._getExtension(r),d=this._getKey(r);if(l===".html")t.set(d,(0,y.readFileSync)(c,"utf8"));else if(l===".ts"||l===".js"){let p=P.getFileSync(c);p?.template!==void 0&&(t.set(d,p.template),e.push(p))}}}let i=new Map;for(let[s,o]of t.entries())this._compile(s,o,void 0,i,t);t.clear(),i.clear();for(let s of e)s.template=void 0}_loadFile(t){for(let e=0;e<this._path.length;e++){let i=this._path[e],s=(0,C.join)(i,t),o=this._getExtension(t),a=this._getKey(t);if(o==".html"){let n=(0,y.readFileSync)(s,"utf8");this._compile(a,n)}else if(o==".ts"||o==".js"){let n=P.getFileSync(s);n?.template!==void 0&&(this._compile(a,n.template),n.template=void 0)}else throw new Error(`File ${t} is not support`)}}_getExtension(t){return(0,C.extname)(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let i=(0,C.extname)(t).toLowerCase();if(i){let n=(0,C.join)(e,t);if((0,y.existsSync)(n)&&(0,y.statSync)(n).isFile()){if(i===".html")return(0,y.readFileSync)(n,"utf8");if(i===".ts"||i===".js")try{return P.getFileSync(n)?.template??null}catch{return null}}continue}let s=(0,C.join)(e,`${t}.ts`),o=(0,C.join)(e,`${t}.js`);if((0,y.existsSync)(s)&&(0,y.statSync)(s).isFile())try{return P.getFileSync(s)?.template??null}catch{}else if((0,y.existsSync)(o)&&(0,y.statSync)(o).isFile())try{return P.getFileSync(s)?.template??null}catch{}let a=(0,C.join)(e,`${t}.html`);if((0,y.existsSync)(a)&&(0,y.statSync)(a).isFile())return(0,y.readFileSync)(a,"utf8")}return null}_isValidFile(t){return this._supportedExtensions.has(this._getExtension(t))}_getKey(t){return t.replace(/\.[^/.]+$/,"")}_compile(t,e,i,s,o){let a=this._map.get(t),n=a||{},r=!1,c=v.processImportBlocks(e,d=>o&&o.has(d)?o.get(d):this._readTemplateFile(d),0,s),l=v._processBaseBlocks(c);(i===void 0||i?.media===!1||a?.media===void 0)&&(n.media=v.compileMedia(c,l),r=!0),(i===void 0||i?.message===!1||a?.message===void 0)&&(n.message=v.compileMessages(c,l),r=!0),(i===void 0||i?.keyboard===!1||a?.keyboard===void 0)&&(n.keyboard=v.compileKeyboards(c,l),r=!0),(i===void 0||i?.description===!1||a?.description===void 0)&&(n.description=v.compileDescription(c,l),r=!0),r&&this._map.set(t,n)}getMedia(t,e="default",i="default",s){let a=this._map.get(t)?.media?.[e],n=a?.[i]||a?.default;try{if(!n)throw new Error("Media function not found, please check your template");return n(s)}catch{return{}}}getMessage(t,e="default",i="default",s){try{let a=this._map.get(t)?.message?.[e],n=a?.[i]||a?.default;if(!n)throw"";return n(s)}catch{return""}}getDescription(t,e="default",i="default",s="default",o){try{let n=this._map.get(t)?.description?.[e]?.[s],r=n?.[i]||n?.default;if(!r)throw"";return r(o)}catch{return""}}getDescriptionLanguage(t,e="default",i="default"){try{let o=this._map.get(t)?.description?.[e]?.[i];return o?Object.keys(o):[]}catch{return[]}}getDescriptionScopes(t,e="default"){try{let s=this._map.get(t)?.description?.[e];return s?Object.keys(s):[]}catch{return[]}}getKeyboard(t,e="default",i="default",s="inline",o){try{let n=this._map.get(t)?.keyboard?.[e],r=n?.[i]?.[s]||n?.default?.[s];if(!r)throw[];return r(o)}catch{return[]}}async write(t,e){if(this._getExtension(t)!=".html")return null;for(let i=0;i<this._path.length;i++){let s=(0,C.join)(this._path[i],t);if((0,y.existsSync)(s))return(0,y.writeFileSync)(s,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 A=require("grammy");var bt=(0,it.fileURLToPath)(f),ft=(0,x.dirname)(bt),Ct=JSON.parse((0,st.readFileSync)((0,x.join)(ft,"../../package.json"),"utf-8")).version,K=class{static{h(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;log;bot;handlerBotUpdate;constructor(t){if(!t?.token||t?.token?.length==0)throw new Error("Token is not valid or empty");if(this.log=t.log===!0?new nt.LoggingPretty:t.log?t.log:void 0,this.log?.info?.(`Gramstax v${Ct}`),this.cacheSession=t.cacheSession||new V("memory","session"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new O({path:[(0,x.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){this.log?.error?.(`[Bot.catch]: ${JSON.stringify(t,null,2)}`)}hookBeforeStart(){}hookAfterStart(){}async onStart(t,e,i){await this.executeSyncBlocksDescription(this.pages);let{username:s}=t;this.log?.success?.(`Telegram bot polling started: ${s} ${e=="webhook"||e=="serverless"?`(${i})`:""}`),this.hookAfterStart()}createBot(t){return new A.Bot(t)}createCtx(t){return new D({ct:t,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{session:{},data:{}}})}runPolling(){this.bot.start({onStart:h(t=>{this.onStart(t,"polling",null)},"onStart")})}async runWebhook(t){let{serve:e}=await import("bun"),i=(0,A.webhookCallback)(this.bot,"bun");this.handlerBotUpdate=i;let s=new URL(t).pathname;e({fetch(n){let{pathname:r}=new URL(n.url);if(n.method=="POST"&&r==s)return i(n);if(n.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,A.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()),t.data.name=(0,x.parse)(e).name}pageSorts(t,e){let i=t.data.name,s=t.prototype,o="Payload",a="Command",n="Caption",r="Free",c=e.routeDynamic,l=e.routeDynamicSpesific,d=h(m=>m.charAt(0).toUpperCase()+m.slice(1),"upFirst"),p=h(m=>m.replace(o,"").replace(a,"").replace(n,"").replace(r,""),"getPureRouteName"),u=h((m,b)=>s[`methodSession${d(m)}`]?.(b),"methodSession");e.all[i]=t;for(let m=0;m<e.lenListRouteStaticSession;m++){let b=e.listRouteStaticSession[m];if(typeof s[b]!="function")continue;let S=e.routeStatic[b],I=e.routeStaticIntent[b],M=e.routeStaticSession[b],k={name:i,routeName:b},Q=S||I;if(Q!==void 0){let ot=b.includes(a),at=b.includes("callback"),rt=b.startsWith("text"),w;if(ot){let J=t.data.textCommand||t.data.name;w=J?`/${J}`:void 0}else at?w=t.data.name:rt?w=t.data.text||t.data.name:w=t.data.name;w&&(Q[w]=k)}M!==void 0&&(M[u(b,i)]=k),b.toLowerCase().endsWith("free")&&l[p(b)].push(k)}s.free&&c.push(i)}async executeSyncBlocksDescription(t){let e=new Map,i=t.routeStatic.textCommand;for(let[,s]of Object.entries(i)){let o=s.name,a=this.templateManager.getDescriptionScopes(o);for(let n of a){e.has(n)||e.set(n,new Set);let r=this.templateManager.getDescriptionLanguage(o,"default",n);for(let c of r)e.get(n).add(c)}}for(let[s,o]of e)for(let a of o){let n=[];for(let[,l]of Object.entries(i)){let d=l.name,p=this.templateManager.getDescription(d,"default",a,s);p&&n.push({command:d,description:p})}if(n.length===0)continue;let r={type:s},c=a==="default"?void 0:a;try{let l=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(l.map(u=>({command:u.command,description:u.description})).sort((u,m)=>u.command.localeCompare(m.command))),p=JSON.stringify(n.sort((u,m)=>u.command.localeCompare(m.command)));d!==p&&(await this.bot.api.setMyCommands(n,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${s},${c?` lang: ${c},`:""} total (${n.length})`))}catch(l){this.log?.error?.(`Failed to sync descriptions for scope: ${s},${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","videoNoteCaption","videoNoteCaptionCommand"],e=["callbackPayload","textPayload","textCommandPayload","photoCaptionPayload","photoCaptionCommandPayload","videoCaptionPayload","videoCaptionCommandPayload","audioCaptionPayload","audioCaptionCommandPayload","documentCaptionPayload","documentCaptionCommandPayload","animationCaptionPayload","animationCaptionCommandPayload","voiceCaptionPayload","voiceCaptionCommandPayload","videoNoteCaptionPayload","videoNoteCaptionCommandPayload"],i=[...t,...e,"textFree","photoFree","videoFree","audioFree","documentFree","animationFree","voiceFree","videoNoteFree","stickerFree","locationFree","contactFree"],s=h((n,r)=>Object.fromEntries(n.map(c=>[c,r()])),"makeObject"),o=h(()=>[],"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:s(t,()=>({})),routeStaticIntent:s(e,()=>({})),routeStaticSession:s(i,()=>({})),listRouteStatic:t,listRouteStaticIntent:e,listRouteStaticSession:i,lenListRouteStatic:t.length,lenListRouteStaticIntent:e.length,lenListRouteStaticSession:i.length};return P.getFileManySync(void 0).forEach(({path:n,page:r})=>{this.pageBuildData(r,n),this.pageSorts(r,a),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(a.all).length})`),a}async pageRoutes(t,e){let i,s;if(i===void 0){let a=t.callbackData,n=t.msgText,r=t.msgCaption,c=this.pages.routeStatic;for(let l=0;l<this.pages.lenListRouteStatic;l++){let d=this.pages.listRouteStatic[l];if(d.startsWith(e)&&(s=c[d][a||n||r]),s)break}s!==void 0&&(i=this.pages.all[s.name])}if(i===void 0){let a=await t.sessionGet();if(a){let n=a.method,r=this.pages.routeStaticSession;for(let c=0;c<this.pages.lenListRouteStaticSession;c++){let l=this.pages.listRouteStaticSession[c];if(l.startsWith(e)&&(s=r[l][n]),s)break}s!==void 0&&(i=this.pages.all[s.name])}}if(i===void 0){let a=this.pages.routeStaticIntent,n=e==="callback",r=n?t.callbackData:t.msgText||t.msgCaption;if(r)for(let c=0;c<this.pages.lenListRouteStaticIntent;c++){let l=this.pages.listRouteStaticIntent[c];if(l.startsWith(e)){let d=a[l];s=d[t.intent(r,n?"colon":"space",1)],!s&&!n&&(s=d[t.intent(r,"space",2)])}if(s)break}s!==void 0&&(i=this.pages.all[s.name])}if(i!==void 0&&s!==void 0)return i.prototype[s.routeName]?await new i(t)[s.routeName]?.():void 0;let o=this.pages.routeDynamicSpesific[e]||[];for(let a=0;a<o.length;a++){let n=o[a];if(n===void 0)continue;let r=this.pages.all[n.name];if(r===void 0||!r.prototype[n.routeName])continue;let l=await new r(t)[n.routeName]?.();if(l!==null)return l}for(let a=0;a<this.pages.routeDynamic.length;a++){let n=this.pages.routeDynamic[a];if(n===void 0)continue;let r=this.pages.all[n];if(r===void 0||!r.prototype.free)continue;let l=await new r(t).free?.();if(l!==null)return l}return null}async hookBeforeRoute(t,e){return!!(t||e)}async hookErrorPage(t,e,i,s){}async hookErrorInputNotFoundPage(t){}async onMessage(t,e){let i=this.createCtx(t);try{if(await this.hookBeforeRoute(i,e)===!1)return;await this.pageRoutes(i,e)===null&&await this.hookErrorInputNotFoundPage(i)}catch(s){await this.hookErrorPage(i,e,s,!1)}}async onCallbackQueryData(t){let e=this.createCtx(t);try{if(await e.callbackQueryAnswer(),await this.hookBeforeRoute(e,"onCallbackQueryData")===!1)return;await this.pageRoutes(e,"callback")}catch(i){await this.hookErrorPage(e,"onCallbackQueryData",i,!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 E=require("worker_threads");var $=class{constructor(t,e){this.path=t;this.argv=e;if(!E.isMainThread)throw new Error("Is not main thread");this.sub=new E.Worker(t,{argv:e}),this.subId=this.sub.threadId,this.sub.on("message",async i=>{let{id:s,method:o,params:a,result:n}=i;if(o!==void 0){let r=this[o];if(typeof r!="function")throw new Error(`Method ${o} not found`);let c=await r.apply(this,a);this.send({id:s,result:c})}else if(n!==void 0){let r=this.map.get(s);r&&(r?.(n),this.map.delete(s))}})}static{h(this,"ThreadMain")}map=new Map;sub;pid=process.pid;subId;createId(){return Math.random()}send(t){this.sub.postMessage(t)}async sendRequest(t,e,i=!0){let s=this.createId();return i?new Promise(o=>{this.map.set(s,o),this.send({id:s,method:t,params:e})}):this.send({id:s,method:t,params:e})}kill(){this.sub.terminate()}};var L=class{static{h(this,"ThreadExport")}static init(t){let{CSub:e,CMain:i=$,path:s,wrap:o}=t,a=`for-${s}`;if(process.argv[2]===a)return new e,{};let n,r=new Proxy({},{get(d,p){return p==="sendRequest"?(u,m,b=!0)=>{if(!n)throw new Error(`Thread at ${s} not launched yet.`);return n.sendRequest(u,m,b)}:(...u)=>{if(!n)throw new Error(`Thread at ${s} not launched yet.`);return n.sendRequest(p,u)}}});return{...o?o(r):{},launch:h((d=[])=>(n=new i(s,[a,...d]),n),"launch")}}};var j=class{static{h(this,"ThreadMainPool")}thread={};threadCount=0;constructor(t){t.forEach(async e=>{let i=await e;this.thread[i.subId]=i,this.threadCount+=1})}add(t){this.thread[t.subId]=t,this.threadCount+=1}getInstance(t){return this.thread[t]}killAll(){return Object.values(this.thread).map(({subId:t})=>this.kill(t))}kill(t){let e=this.thread[t];return e?.kill(),delete this.thread[t],this.threadCount-=1,e?.subId}async broadcastRequest(t,e){return await Promise.all(Object.values(this.thread).map(i=>i.sendRequest(t,e,!0)))}async sendRequest(t,e,i,s=!0){return await this.thread[t]?.sendRequest(e,i,s)}};var T=require("worker_threads");var W=class{static{h(this,"ThreadSub")}map=new Map;argv=process.argv;id=T.threadId;pid=process.pid;threadIsMain=T.isMainThread;constructor(){if(this.threadIsMain)throw new Error("Is not sub thread");T.parentPort.on("message",async t=>{let{id:e,method:i,params:s,result:o}=t;if(i!==void 0)try{let a=this[i];if(typeof a!="function")throw new Error(`Method ${i} not found`);let n=await a.apply(this,s);this.send({id:e,result:n})}catch(a){this.send({id:e,error:a})}else if(o!==void 0){let a=this.map.get(e);a&&(a?.(o),this.map.delete(e))}})}createId(){return Math.random()}send(t){T.parentPort.postMessage(t)}async sendRequest(t,e,i=!0){let s=this.createId();return i?new Promise(o=>{this.map.set(s,o),this.send({id:s,method:t,params:e})}):this.send({id:s,method:t,params:e})}};var U=class{static{h(this,"ComponentKeyboard")}static data;static _process(t,e){if(e.type||(e.type="inline"),e.lang){let i=t[e.lang];return`
|
|
8
8
|
<keyboard type="${e.type}" lang="${e.lang}">${e.reverse?this.data._reverse(i):i}</keyboard>
|
|
9
9
|
`}return Object.keys(t).map(i=>{let s=t[i];return`
|
|
10
10
|
<keyboard type="${e.type}" lang="${i}">${e.reverse?this.data._reverse(s):s}</keyboard>
|
package/dist/src/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var tt=Object.defineProperty;var h=(y,t)=>tt(y,"name",{value:t,configurable:!0}),R=(y=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(y,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):y)(function(y){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+y+'" is not supported')});import{LoggingPretty as et}from"logging-pretty";var D=class extends et{static{h(this,"LoggingUtils")}constructor(t){super(t)}errorMake(t,e,s){this.error(`[${e?.name||e}:${s}] ${String(t)}`)}},Ct=new D;import{Keyv as st}from"keyv";import it from"@keyv/redis";var I=class extends st{constructor(e="memory",s,i,o){let a;e.startsWith("redis")&&(a=new it(e)),e==="memory"&&(a=new Map),o?.forceStore&&(a=o.forceStore);super({store:a,namespace:s,ttl:i});this.url=e}static{h(this,"CacheExternal")}};import{setTimeout as nt}from"timers/promises";import{InlineKeyboard as N,Keyboard as E}from"grammy";var w=class{static{h(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.payloads(this.msgText,"space",this.data._positionPayloadText)}get msgTextPayload(){return this.msgTextPayloads[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionPayloads(){return this.payloads(this.msgCaption,"space")}get msgCaptionPayload(){return this.msgCaptionPayloads[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataPayloads(){return this.payloads(this.callbackData,"colon")}get callbackDataPayload(){return this.callbackDataPayloads?.[0]}get callbackDataParts(){return this.callbackDataPayload&&this.callbackDataPayload.indexOf("+")!=-1?this.callbackDataPayload.split("+"):[]}set session(t){this.temp.session=t}get session(){return this.temp.session}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,i,o,a,n=!1){try{let c=e.map(l=>this.templateManager.getMessage(this.data.name,o,l,i));for(let l=0;l<t.length;l++){let d=t[l],p=c[l];await this.ct.api.sendMessage(d,p,{parse_mode:"HTML",reply_markup:s,...a}),l+1==30&&await nt(1200)}}catch(r){if(n)throw r}}async reply(t,e,s,i){let o=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.reply(o,{parse_mode:"HTML",reply_markup:t,...i})}async replyMedia(t,e,s,i,o){let a=this.templateManager.getMedia(this.data.name,i,this.userLanguage,s),n={parse_mode:"HTML",reply_markup:e,...o};if(t=="photo")return await this.ct.replyWithPhoto(a.src,{caption:a.caption,...n});if(t=="video")return await this.ct.replyWithVideo(a.src,{caption:a.caption,...n});if(t=="audio")return await this.ct.replyWithAudio(a.src,{caption:a.caption,...n});if(t=="document")return await this.ct.replyWithDocument(a.src,{caption:a.caption,...n});if(t=="animation")return await this.ct.replyWithAnimation(a.src,{caption:a.caption,...n});if(t=="voice")return await this.ct.replyWithVoice(a.src,n);if(t=="video_note")return await this.ct.replyWithVideoNote(a.src,n);if(t=="sticker")return await this.ct.replyWithSticker(a.src,n);if(t=="location")return await this.ct.replyWithLocation(parseInt(a.latitude),parseInt(a.longitude),n);if(t=="contact")return await this.ct.replyWithContact(a.phone,a.first_name,{vcard:a.vcard,...n})}async replyPhoto(t,e,s,i){return this.replyMedia("photo",t,e,s,i)}async replyVideo(t,e,s,i){return this.replyMedia("video",t,e,s,i)}async replyAudio(t,e,s,i){return this.replyMedia("audio",t,e,s,i)}async replyDocument(t,e,s,i){return this.replyMedia("document",t,e,s,i)}async replyAnimation(t,e,s,i){return this.replyMedia("animation",t,e,s,i)}async replyVoice(t,e,s,i){return this.replyMedia("voice",t,e,s,i)}async replyVideoNote(t,e,s,i){return this.replyMedia("video_note",t,e,s,i)}async replySticker(t,e,s,i){return this.replyMedia("sticker",t,e,s,i)}async replyLocation(t,e,s,i){return this.replyMedia("location",t,e,s,i)}async replyContact(t,e,s,i){return this.replyMedia("contact",t,e,s,i)}async replyAction(t){return await this.ct.replyWithChatAction(t)}async edit(t,e,s,i,o=!0){try{let a=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.editMessageText(a,{parse_mode:"HTML",reply_markup:t,...i})}catch(a){if(o)await this.reply(t,e,s,i);else throw a}}async editMedia(t,e,s,i,o,a,n=!0){try{let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,i,this.userLanguage,s);return t=="voice"?(await this.delete(),await this.replyVoice(e,s,i,o)):t=="video_note"?(await this.delete(),await this.replyVoice(e,s,i,o)):t=="sticker"?(await this.delete(),await this.replySticker(e,s,i,o)):t=="location"?(await this.delete(),await this.replyLocation(e,s,i,o)):t=="contact"?(await this.delete(),await this.replyContact(e,s,i,o)):await this.ct.editMessageMedia({media:r,caption:c,type:t,parse_mode:"HTML",...o},{reply_markup:e,...a})}catch(r){if(n===!0)await this.reply(e,s,i,a);else throw r}}async editPhoto(t,e,s,i,o){return await this.editMedia("photo",t,e,s,i,o)}async editVideo(t,e,s,i,o){return await this.editMedia("video",t,e,s,i,o)}async editAudio(t,e,s,i,o){return await this.editMedia("audio",t,e,s,i,o)}async editDocument(t,e,s,i,o){return await this.editMedia("document",t,e,s,i,o)}async editAnimation(t,e,s,i,o){return await this.editMedia("animation",t,e,s,i,o)}async editVoice(t,e,s,i){return await this.editMedia("voice",t,e,s,i)}async editVideoNote(t,e,s,i){return await this.editMedia("video_note",t,e,s,i)}async editSticker(t,e,s,i){return await this.editMedia("sticker",t,e,s,i)}async editLocation(t,e,s,i){return await this.editMedia("location",t,e,s,i)}async editContact(t,e,s,i){return await this.editMedia("contact",t,e,s,i)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(t){try{return await this.ct.answerCallbackQuery(t)}catch{return null}}async sessionSet(t,e,s){try{let i={method:t,params:e,...s},o=await this.cacheSession.set(`${this.userId}`,i);return o&&(this.session=i),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"?{callbackData:t}:t||{},i=s.callbackData;return{name:"",text:s.text,textCommand:s.textCommand,_positionPayloadText:s.text?s.text.split(this.prototype.seperatorTag("space")).length:void 0,callbackData:i?function(...a){let n=i(...a);return`${this.name}${n==""||n===void 0?"":`:${n}`}`}:function(){return this?.name}}}inlineKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let n=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(n);if(!r){let c=new N,l=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data),d=t(c,l);return this.cacheKeyboard.set(n,d),d}return r}let i=new N,o=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data);return t(i,o)}bottomKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let n=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(n);if(!r){let c=new E,l=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),d=t(c,l);return d.resized(!0),this.cacheKeyboard.set(n,d),d}return r}let i=new E,o=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),a=t(i,o);return a.resized(),a}seperatorTag(t="space"){return t=="space"?" ":":"}payloads(t="",e,s=1){let i=this.seperatorTag(e);return t?t.split(i).slice(s):[]}intent(t="",e,s=1){let i=this.seperatorTag(e);if(!t)return"";let o=t.split(i);return s==1?o[0]:o.slice(0,s).join(i)}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)}validateSessionVideoNoteCaption(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaption(e)}validateSessionVideoNoteCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionPayload(e)}validateSessionVideoNoteCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionCommand(e)}validateSessionVideoNoteCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionCommandPayload(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)}sessionVideoNoteCaption(t,e){return this.sessionSet(this.methodSessionVideoNoteCaption(e),t)}sessionVideoNoteCaptionPayload(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionPayload(e),t)}sessionVideoNoteCaptionCommand(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionCommand(e),t)}sessionVideoNoteCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionCommandPayload(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)}sessionToVideoNoteCaption(t,e){return this.sessionVideoNoteCaption({...this.session.params,...t},e)}sessionToVideoNoteCaptionPayload(t,e){return this.sessionVideoNoteCaptionPayload({...this.session.params,...t},e)}sessionToVideoNoteCaptionCommand(t,e){return this.sessionVideoNoteCaptionCommand({...this.session.params,...t},e)}sessionToVideoNoteCaptionCommandPayload(t,e){return this.sessionVideoNoteCaptionCommandPayload({...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)}methodSessionVideoNoteCaption(t){return this.methodSession("38",t)}methodSessionVideoNoteCaptionPayload(t){return this.methodSession("39",t)}methodSessionVideoNoteCaptionCommand(t){return this.methodSession("40",t)}methodSessionVideoNoteCaptionCommandPayload(t){return this.methodSession("41",t)}methodSessionVideoNoteFree(t){return this.methodSession("42",t)}methodSessionStickerFree(t){return this.methodSession("43",t)}methodSessionLocationFree(t){return this.methodSession("44",t)}methodSessionContactFree(t){return this.methodSession("45",t)}};import{join as lt,parse as dt}from"path";import{join as O}from"path";import{existsSync as K,readdirSync as L}from"fs";import{createRequire as ot}from"module";var f=class{static{h(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 O(process.cwd(),"src","pages")}static getFileSync(t,e=0){t||(t=this.getFilePath());let i=ot(t)(t);return this._getFile(i,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()),!K(t))throw new Error(`Directory ${t} is not found, please make it manually`);return L(t).map(i=>{let o=O(t,i);return{path:o,page:this.getFileSync(o,e)}})}static clearCacheRequire(t){if(t||(t=this.getFilePath()),!K(t))throw new Error(`Directory ${t} is not found, please make it manually`);return L(t).forEach(s=>{let i=O(t,s);delete R.cache[R.resolve(i)]}),!0}};import{LoggingPretty as pt}from"logging-pretty";import{basename as A,join as P,extname as W}from"path";import{readdirSync as at,readFileSync as _,existsSync as T,statSync as M,writeFileSync as rt}from"fs";import{watch as ct}from"chokidar";var C=class{static{h(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 i of t.matchAll(e)){let o=i[2]??"default",n=(i[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[o]=n}return s}static _processScriptBlocks(t){return t.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(e,s)=>{let i=s.trim();return i?`\${(() => { if (!data) return ''; try { with(data) { ${i} } } 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,i,o)=>{if(!i)return"";let a="",n=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=n.exec(o))!==null;){let d=(c[1]||"").split(",").map(u=>u.trim()),p=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(u=>{a+=`case "${u}": `}),a+=`return \`${p}\`; `}let l=r.exec(o);if(l){let d=(l[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");a+=`default: return \`${d}\`; `}else a+="default: return ''; ";return`\${(() => { switch((data && data["${i}"])) { ${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,i,o)=>{let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let p of i.matchAll(n))a[p[1]]=p[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,(p,u)=>u==="e"||u.startsWith("e.")?`\${${u}}`:u==="i"?"${i}":p);let d=c.replace(/"/g,'\\"');return`\${(data && data["${r}"] || []).map((e, i) => \`${l}\`).join("${d}")}`})}static _processMediaBlocks(t){let e=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let i of t.matchAll(e)){let o=i[1],a=i[2],n={},r=/(\w+)="([^"]*)"/g;if(o)for(let u of o.matchAll(r))n[u[1]]=u[2];let c=n.lang||"default",l=n.type,d=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),p={type:l};n.src&&(p.src=n.src),d&&l!=="video_note"&&l!=="sticker"&&(p.caption=d),l==="location"&&(n.latitude&&(p.latitude=n.latitude),n.longitude&&(p.longitude=n.longitude),d&&(p.caption=d)),l==="contact"&&(n.phone&&(p.phone=n.phone),n.first_name&&(p.first_name=n.first_name),n.last_name&&(p.last_name=n.last_name),n.vcard&&(p.vcard=n.vcard),d&&(p.caption=d)),s[c]=p}return s}static _processMessageBlocks(t){let e=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,i,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let l of i.matchAll(n))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[,i,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let d of i.matchAll(n))a[d[1]]=d[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[,i,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let d of i.matchAll(n))a[d[1]]=d[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 i=s;if(i=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(i))),e){let o=`return [${i}]`;return new Function("data",o)}else{let o=`return ${i}`;return new Function("data",o)}}static compileMedia(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processMediaBlocks(a);i[o]={};for(let[r,c]of Object.entries(n)){let l={};for(let[d,p]of Object.entries(c)){if(d==="type"||typeof p!="string")continue;let u=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(p)))));l[d]=this._compileToFunction(u,!1)}i[o][r]=d=>{let p={...c};for(let[u,m]of Object.entries(l))p[u]=m(d);return p}}}return i}static compileMessages(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processMessageBlocks(a);i[o]={};for(let[r,c]of Object.entries(n)){let l=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));i[o][r]=this._compileToFunction(l,!1)}}return i}static compileDescription(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processDescriptionBlocks(a);i[o]={};for(let[r,c]of Object.entries(n))for(let[l,d]of Object.entries(c)){i[o][l]||(i[o][l]={});let p=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));i[o][l][r]=this._compileToFunction(p,!1)}}return i}static compileKeyboards(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processKeyboardBlocks(a);i[o]={};for(let[r,c]of Object.entries(n)){i[o][r]={};for(let[l,d]of Object.entries(c)){let u=d.split(/(?<!\\),\s*/).map(m=>m.replace(/\\,/g,",").trim()).map(m=>this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(m))))));i[o][r][l]=this._compileToFunction(u,!0)}}}return i}static _extractBlock(t,e,s="default",i="all",o){let a=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,n=t,r=!1;for(let c of t.matchAll(a))if((c[2]??"default")===s){n=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(t);if(!(s==="default"&&!c))return""}if(e){if(e==="all")return n;let c=Array.isArray(e)?e:[e],l=[];for(let p of c){let u=new RegExp(`([ \\t]*)<${p}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${p}>`,"gi");for(let m of n.matchAll(u)){let g=m[2];if(o){let b=/lang="([^"]*)"/i,v=g?.match(b);if(((v?v[1]:void 0)||"default")!==o)continue}l.push({start:m.index,content:m[0],innerContent:m[3]??""})}}l.sort((p,u)=>p.start-u.start);let d=h(p=>{let u=p.split(`
|
|
2
|
-
`);if(u.length<=1)return p.trim();let m=u.filter(b=>b.trim().length>0);if(m.length===0)return"";let g=m.reduce((b,
|
|
1
|
+
var it=Object.defineProperty;var h=(y,t)=>it(y,"name",{value:t,configurable:!0}),O=(y=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(y,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):y)(function(y){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+y+'" is not supported')});import{LoggingPretty as nt}from"logging-pretty";var A=class extends nt{static{h(this,"LoggingUtils")}constructor(t){super(t)}errorMake(t,e,s){this.error(`[${e?.name||e}:${s}] ${String(t)}`)}},It=new A;import{Keyv as ot}from"keyv";import at from"@keyv/redis";var _=class extends ot{constructor(e="memory",s,i,o){let a;e.startsWith("redis")&&(a=new at(e)),e==="memory"&&(a=new Map),o?.forceStore&&(a=o.forceStore);super({store:a,namespace:s,ttl:i});this.url=e}static{h(this,"CacheExternal")}};import{setTimeout as rt}from"timers/promises";import{InlineKeyboard as K,Keyboard as L}from"grammy";var F=class{static{h(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.payloads(this.msgText,"space",this.data._positionPayloadText)}get msgTextPayload(){return this.msgTextPayloads[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionPayloads(){return this.payloads(this.msgCaption,"space")}get msgCaptionPayload(){return this.msgCaptionPayloads[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataPayloads(){return this.payloads(this.callbackData,"colon")}get callbackDataPayload(){return this.callbackDataPayloads?.[0]}get callbackDataParts(){return this.callbackDataPayload&&this.callbackDataPayload.indexOf("+")!=-1?this.callbackDataPayload.split("+"):[]}set session(t){this.temp.session=t}get session(){return this.temp.session}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,i,o,a,n=!1){try{let c=e.map(l=>this.templateManager.getMessage(this.data.name,o,l,i));for(let l=0;l<t.length;l++){let d=t[l],p=c[l];await this.ct.api.sendMessage(d,p,{parse_mode:"HTML",reply_markup:s,...a}),l+1==30&&await rt(1200)}}catch(r){if(n)throw r}}async reply(t,e,s,i){let o=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.reply(o,{parse_mode:"HTML",reply_markup:t,...i})}async replyMedia(t,e,s,i,o){let a=this.templateManager.getMedia(this.data.name,i,this.userLanguage,s),n={parse_mode:"HTML",reply_markup:e,...o};if(t=="photo")return await this.ct.replyWithPhoto(a.src,{caption:a.caption,...n});if(t=="video")return await this.ct.replyWithVideo(a.src,{caption:a.caption,...n});if(t=="audio")return await this.ct.replyWithAudio(a.src,{caption:a.caption,...n});if(t=="document")return await this.ct.replyWithDocument(a.src,{caption:a.caption,...n});if(t=="animation")return await this.ct.replyWithAnimation(a.src,{caption:a.caption,...n});if(t=="voice")return await this.ct.replyWithVoice(a.src,n);if(t=="video_note")return await this.ct.replyWithVideoNote(a.src,n);if(t=="sticker")return await this.ct.replyWithSticker(a.src,n);if(t=="location")return await this.ct.replyWithLocation(parseInt(a.latitude),parseInt(a.longitude),n);if(t=="contact")return await this.ct.replyWithContact(a.phone,a.first_name,{vcard:a.vcard,...n})}async replyPhoto(t,e,s,i){return this.replyMedia("photo",t,e,s,i)}async replyVideo(t,e,s,i){return this.replyMedia("video",t,e,s,i)}async replyAudio(t,e,s,i){return this.replyMedia("audio",t,e,s,i)}async replyDocument(t,e,s,i){return this.replyMedia("document",t,e,s,i)}async replyAnimation(t,e,s,i){return this.replyMedia("animation",t,e,s,i)}async replyVoice(t,e,s,i){return this.replyMedia("voice",t,e,s,i)}async replyVideoNote(t,e,s,i){return this.replyMedia("video_note",t,e,s,i)}async replySticker(t,e,s,i){return this.replyMedia("sticker",t,e,s,i)}async replyLocation(t,e,s,i){return this.replyMedia("location",t,e,s,i)}async replyContact(t,e,s,i){return this.replyMedia("contact",t,e,s,i)}async replyAction(t){return await this.ct.replyWithChatAction(t)}async edit(t,e,s,i,o=!0){try{let a=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.editMessageText(a,{parse_mode:"HTML",reply_markup:t,...i})}catch(a){if(o)await this.reply(t,e,s,i);else throw a}}async editMedia(t,e,s,i,o,a,n=!0){try{let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,i,this.userLanguage,s);return t=="voice"?(await this.delete(),await this.replyVoice(e,s,i,o)):t=="video_note"?(await this.delete(),await this.replyVoice(e,s,i,o)):t=="sticker"?(await this.delete(),await this.replySticker(e,s,i,o)):t=="location"?(await this.delete(),await this.replyLocation(e,s,i,o)):t=="contact"?(await this.delete(),await this.replyContact(e,s,i,o)):await this.ct.editMessageMedia({media:r,caption:c,type:t,parse_mode:"HTML",...o},{reply_markup:e,...a})}catch(r){if(n===!0)await this.reply(e,s,i,a);else throw r}}async editPhoto(t,e,s,i,o){return await this.editMedia("photo",t,e,s,i,o)}async editVideo(t,e,s,i,o){return await this.editMedia("video",t,e,s,i,o)}async editAudio(t,e,s,i,o){return await this.editMedia("audio",t,e,s,i,o)}async editDocument(t,e,s,i,o){return await this.editMedia("document",t,e,s,i,o)}async editAnimation(t,e,s,i,o){return await this.editMedia("animation",t,e,s,i,o)}async editVoice(t,e,s,i){return await this.editMedia("voice",t,e,s,i)}async editVideoNote(t,e,s,i){return await this.editMedia("video_note",t,e,s,i)}async editSticker(t,e,s,i){return await this.editMedia("sticker",t,e,s,i)}async editLocation(t,e,s,i){return await this.editMedia("location",t,e,s,i)}async editContact(t,e,s,i){return await this.editMedia("contact",t,e,s,i)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(t){try{return await this.ct.answerCallbackQuery(t)}catch{return null}}async sessionSet(t,e,s){try{let i={method:t,params:e,...s},o=await this.cacheSession.set(`${this.userId}`,i);return o&&(this.session=i),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"?{callbackData:t}:t||{},i=s.callbackData;return{name:"",text:s.text,textCommand:s.textCommand,_positionPayloadText:s.text?s.text.split(this.prototype.seperatorTag("space")).length:void 0,callbackData:i?function(...a){let n=i(...a);return`${this.name}${n==""||n===void 0?"":`:${n}`}`}:function(){return this?.name}}}inlineKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let n=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(n);if(!r){let c=new K,l=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data),d=t(c,l);return this.cacheKeyboard.set(n,d),d}return r}let i=new K,o=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data);return t(i,o)}bottomKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let n=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(n);if(!r){let c=new L,l=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),d=t(c,l);return d.resized(!0),this.cacheKeyboard.set(n,d),d}return r}let i=new L,o=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),a=t(i,o);return a.resized(),a}seperatorTag(t="space"){return t=="space"?" ":":"}payloads(t="",e,s=1){let i=this.seperatorTag(e);return t?t.split(i).slice(s):[]}intent(t="",e,s=1){let i=this.seperatorTag(e);if(!t)return"";let o=t.split(i);return s==1?o[0]:o.slice(0,s).join(i)}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)}validateSessionVideoNoteCaption(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaption(e)}validateSessionVideoNoteCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionPayload(e)}validateSessionVideoNoteCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionCommand(e)}validateSessionVideoNoteCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionCommandPayload(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)}sessionVideoNoteCaption(t,e){return this.sessionSet(this.methodSessionVideoNoteCaption(e),t)}sessionVideoNoteCaptionPayload(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionPayload(e),t)}sessionVideoNoteCaptionCommand(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionCommand(e),t)}sessionVideoNoteCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionCommandPayload(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)}sessionToVideoNoteCaption(t,e){return this.sessionVideoNoteCaption({...this.session.params,...t},e)}sessionToVideoNoteCaptionPayload(t,e){return this.sessionVideoNoteCaptionPayload({...this.session.params,...t},e)}sessionToVideoNoteCaptionCommand(t,e){return this.sessionVideoNoteCaptionCommand({...this.session.params,...t},e)}sessionToVideoNoteCaptionCommandPayload(t,e){return this.sessionVideoNoteCaptionCommandPayload({...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)}methodSessionVideoNoteCaption(t){return this.methodSession("38",t)}methodSessionVideoNoteCaptionPayload(t){return this.methodSession("39",t)}methodSessionVideoNoteCaptionCommand(t){return this.methodSession("40",t)}methodSessionVideoNoteCaptionCommandPayload(t){return this.methodSession("41",t)}methodSessionVideoNoteFree(t){return this.methodSession("42",t)}methodSessionStickerFree(t){return this.methodSession("43",t)}methodSessionLocationFree(t){return this.methodSession("44",t)}methodSessionContactFree(t){return this.methodSession("45",t)}};import{join as U,parse as ut,dirname as ht}from"path";import{readFileSync as mt}from"fs";import{fileURLToPath as gt}from"url";import{join as $}from"path";import{existsSync as j,readdirSync as W}from"fs";import{createRequire as ct}from"module";var S=class{static{h(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 $(process.cwd(),"src","pages")}static getFileSync(t,e=0){t||(t=this.getFilePath());let i=ct(t)(t);return this._getFile(i,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()),!j(t))throw new Error(`Directory ${t} is not found, please make it manually`);return W(t).map(i=>{let o=$(t,i);return{path:o,page:this.getFileSync(o,e)}})}static clearCacheRequire(t){if(t||(t=this.getFilePath()),!j(t))throw new Error(`Directory ${t} is not found, please make it manually`);return W(t).forEach(s=>{let i=$(t,s);delete O.cache[O.resolve(i)]}),!0}};import{LoggingPretty as yt}from"logging-pretty";import{basename as B,join as k,extname as q}from"path";import{readdirSync as lt,readFileSync as R,existsSync as I,statSync as w,writeFileSync as dt}from"fs";import{watch as pt}from"chokidar";var P=class{static{h(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 i of t.matchAll(e)){let o=i[2]??"default",n=(i[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[o]=n}return s}static _processScriptBlocks(t){return t.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(e,s)=>{let i=s.trim();return i?`\${(() => { if (!data) return ''; try { with(data) { ${i} } } 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,i,o)=>{if(!i)return"";let a="",n=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=n.exec(o))!==null;){let d=(c[1]||"").split(",").map(u=>u.trim()),p=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(u=>{a+=`case "${u}": `}),a+=`return \`${p}\`; `}let l=r.exec(o);if(l){let d=(l[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");a+=`default: return \`${d}\`; `}else a+="default: return ''; ";return`\${(() => { switch((data && data["${i}"])) { ${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,i,o)=>{let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let p of i.matchAll(n))a[p[1]]=p[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,(p,u)=>u==="e"||u.startsWith("e.")?`\${${u}}`:u==="i"?"${i}":p);let d=c.replace(/"/g,'\\"');return`\${(data && data["${r}"] || []).map((e, i) => \`${l}\`).join("${d}")}`})}static _processMediaBlocks(t){let e=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let i of t.matchAll(e)){let o=i[1],a=i[2],n={},r=/(\w+)="([^"]*)"/g;if(o)for(let u of o.matchAll(r))n[u[1]]=u[2];let c=n.lang||"default",l=n.type,d=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),p={type:l};n.src&&(p.src=n.src),d&&l!=="video_note"&&l!=="sticker"&&(p.caption=d),l==="location"&&(n.latitude&&(p.latitude=n.latitude),n.longitude&&(p.longitude=n.longitude),d&&(p.caption=d)),l==="contact"&&(n.phone&&(p.phone=n.phone),n.first_name&&(p.first_name=n.first_name),n.last_name&&(p.last_name=n.last_name),n.vcard&&(p.vcard=n.vcard),d&&(p.caption=d)),s[c]=p}return s}static _processMessageBlocks(t){let e=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,i,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let l of i.matchAll(n))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[,i,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let d of i.matchAll(n))a[d[1]]=d[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[,i,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let d of i.matchAll(n))a[d[1]]=d[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 i=s;if(i=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(i))),e){let o=`return [${i}]`;return new Function("data",o)}else{let o=`return ${i}`;return new Function("data",o)}}static compileMedia(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processMediaBlocks(a);i[o]={};for(let[r,c]of Object.entries(n)){let l={};for(let[d,p]of Object.entries(c)){if(d==="type"||typeof p!="string")continue;let u=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(p)))));l[d]=this._compileToFunction(u,!1)}i[o][r]=d=>{let p={...c};for(let[u,m]of Object.entries(l))p[u]=m(d);return p}}}return i}static compileMessages(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processMessageBlocks(a);i[o]={};for(let[r,c]of Object.entries(n)){let l=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));i[o][r]=this._compileToFunction(l,!1)}}return i}static compileDescription(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processDescriptionBlocks(a);i[o]={};for(let[r,c]of Object.entries(n))for(let[l,d]of Object.entries(c)){i[o][l]||(i[o][l]={});let p=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));i[o][l][r]=this._compileToFunction(p,!1)}}return i}static compileKeyboards(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processKeyboardBlocks(a);i[o]={};for(let[r,c]of Object.entries(n)){i[o][r]={};for(let[l,d]of Object.entries(c)){let u=d.split(/(?<!\\),\s*/).map(m=>m.replace(/\\,/g,",").trim()).map(m=>this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(m))))));i[o][r][l]=this._compileToFunction(u,!0)}}}return i}static _extractBlock(t,e,s="default",i="all",o){let a=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,n=t,r=!1;for(let c of t.matchAll(a))if((c[2]??"default")===s){n=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(t);if(!(s==="default"&&!c))return""}if(e){if(e==="all")return n;let c=Array.isArray(e)?e:[e],l=[];for(let p of c){let u=new RegExp(`([ \\t]*)<${p}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${p}>`,"gi");for(let m of n.matchAll(u)){let g=m[2];if(o){let b=/lang="([^"]*)"/i,x=g?.match(b);if(((x?x[1]:void 0)||"default")!==o)continue}l.push({start:m.index,content:m[0],innerContent:m[3]??""})}}l.sort((p,u)=>p.start-u.start);let d=h(p=>{let u=p.split(`
|
|
2
|
+
`);if(u.length<=1)return p.trim();let m=u.filter(b=>b.trim().length>0);if(m.length===0)return"";let g=m.reduce((b,x)=>{let T=x.match(/^([ \t]*)/),v=T?T[1].length:0;return v<b?v:b},1/0);return u.map(b=>b.length>=g?b.slice(g):b.trimStart()).join(`
|
|
3
3
|
`).trim()},"processResult");return i==="all"?l.map(u=>d(u.content)).join(`
|
|
4
4
|
`):l.map(u=>d(u.innerContent)).join(`
|
|
5
5
|
`)}return n}static _processImportBlocks(t){let e=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,s=[];return{processed:t.replace(e,(o,a,n)=>{let r={},c=/(\w+)="([^"]*)"/g;if(n)for(let u of n.matchAll(c))r[u[1]]=u[2];let l=r.src;if(!l)return"";let d;r.block&&(r.block==="all"?d="all":r.block.includes(",")?d=r.block.split(",").map(u=>u.trim()).filter(u=>u):d=r.block);let p={src:l,blocks:d,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:a||""};return s.push(p),`${a}__IMPORT_${s.length-1}__`}),imports:s}}static processImportBlocks(t,e,s=0,i){if(s>10)return"";let{processed:o,imports:a}=this._processImportBlocks(t),n=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||""}`,d;if(i&&i.has(l))d=i.get(l);else{let u=e(c.src);d=u?this._extractBlock(u,c.blocks,c.base,c.section,c.lang):"",d&&d.includes("<import")&&(d=this.processImportBlocks(d,e,s+1,i)),i&&i.set(l,d)}let p=d.split(`
|
|
6
6
|
`).map((u,m)=>m===0?u:c.indent+u).join(`
|
|
7
|
-
`);n=n.replace(`__IMPORT_${r}__`,p)}return n}};var F=class{static{h(this,"TemplateManager")}_map=new Map;_engine=C;_watcher=[];_pageManager=f;_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(!T(e))throw new Error(`Template base path is not exists: ${e}`);if(!M(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],i=ct(s,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...t});this._watcher[e]=i,i.on("change",this._handleFileChange.bind(this)),i.on("add",this._handleFileAdd.bind(this)),i.on("unlink",this._handleFileDelete.bind(this)),i.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(t){let e=A(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileAdd(t){let e=A(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileDelete(t){let e=A(t),s=this._getKey(e);this._map.has(s)&&this._map.delete(s)}_handleWatchError(t){}_loadAllFiles(){let t=new Map,e=[];for(let i=0;i<this._path.length;i++){let o=this._path[i],n=at(o,"utf8").filter(r=>this._isValidFile(r));for(let r of n){let c=P(o,r),l=this._getExtension(r),d=this._getKey(r);if(l===".html")t.set(d,_(c,"utf8"));else if(l===".ts"||l===".js"){let p=f.getFileSync(c);p?.template!==void 0&&(t.set(d,p.template),e.push(p))}}}let s=new Map;for(let[i,o]of t.entries())this._compile(i,o,void 0,s,t);t.clear(),s.clear();for(let i of e)i.template=void 0}_loadFile(t){for(let e=0;e<this._path.length;e++){let s=this._path[e],i=P(s,t),o=this._getExtension(t),a=this._getKey(t);if(o==".html"){let n=_(i,"utf8");this._compile(a,n)}else if(o==".ts"||o==".js"){let n=f.getFileSync(i);n?.template!==void 0&&(this._compile(a,n.template),n.template=void 0)}else throw new Error(`File ${t} is not support`)}}_getExtension(t){return W(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let s=W(t).toLowerCase();if(s){let n=P(e,t);if(T(n)&&M(n).isFile()){if(s===".html")return _(n,"utf8");if(s===".ts"||s===".js")try{return f.getFileSync(n)?.template??null}catch{return null}}continue}let i=P(e,`${t}.ts`),o=P(e,`${t}.js`);if(T(i)&&M(i).isFile())try{return f.getFileSync(i)?.template??null}catch{}else if(T(o)&&M(o).isFile())try{return f.getFileSync(i)?.template??null}catch{}let a=P(e,`${t}.html`);if(T(a)&&M(a).isFile())return _(a,"utf8")}return null}_isValidFile(t){return this._supportedExtensions.has(this._getExtension(t))}_getKey(t){return t.replace(/\.[^/.]+$/,"")}_compile(t,e,s,i,o){let a=this._map.get(t),n=a||{},r=!1,c=C.processImportBlocks(e,d=>o&&o.has(d)?o.get(d):this._readTemplateFile(d),0,i),l=C._processBaseBlocks(c);(s===void 0||s?.media===!1||a?.media===void 0)&&(n.media=C.compileMedia(c,l),r=!0),(s===void 0||s?.message===!1||a?.message===void 0)&&(n.message=C.compileMessages(c,l),r=!0),(s===void 0||s?.keyboard===!1||a?.keyboard===void 0)&&(n.keyboard=C.compileKeyboards(c,l),r=!0),(s===void 0||s?.description===!1||a?.description===void 0)&&(n.description=C.compileDescription(c,l),r=!0),r&&this._map.set(t,n)}getMedia(t,e="default",s="default",i){let a=this._map.get(t)?.media?.[e],n=a?.[s]||a?.default;try{if(!n)throw new Error("Media function not found, please check your template");return n(i)}catch{return{}}}getMessage(t,e="default",s="default",i){try{let a=this._map.get(t)?.message?.[e],n=a?.[s]||a?.default;if(!n)throw"";return n(i)}catch{return""}}getDescription(t,e="default",s="default",i="default",o){try{let n=this._map.get(t)?.description?.[e]?.[i],r=n?.[s]||n?.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 i=this._map.get(t)?.description?.[e];return i?Object.keys(i):[]}catch{return[]}}getKeyboard(t,e="default",s="default",i="inline",o){try{let n=this._map.get(t)?.keyboard?.[e],r=n?.[s]?.[i]||n?.default?.[i];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 i=P(this._path[s],t);if(T(i))return rt(i,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()}};import{Bot as ut,webhookCallback as j}from"grammy";var q=class{static{h(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;log;bot;handlerBotUpdate;constructor(t){if(!t?.token||t?.token?.length==0)throw new Error("Token is not valid or empty");if(this.log=t.log===!0?new pt:t.log?t.log:void 0,this.log?.info?.("Gramstax v0.3.6"),this.cacheSession=t.cacheSession||new I("memory","session"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new F({path:[lt(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){this.log?.error?.(`[Bot.catch]: ${JSON.stringify(t,null,2)}`)}hookBeforeStart(){}hookAfterStart(){}async onStart(t,e,s){await this.executeSyncBlocksDescription(this.pages);let{username:i}=t;this.log?.success?.(`Telegram bot polling started: ${i} ${e=="webhook"||e=="serverless"?`(${s})`:""}`),this.hookAfterStart()}createBot(t){return new ut(t)}createCtx(t){return new w({ct:t,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{session:{},data:{}}})}runPolling(){this.bot.start({onStart:h(t=>{this.onStart(t,"polling",null)},"onStart")})}async runWebhook(t){let{serve:e}=await import("bun"),s=j(this.bot,"bun");this.handlerBotUpdate=s;let i=new URL(t).pathname;e({fetch(n){let{pathname:r}=new URL(n.url);if(n.method=="POST"&&r==i)return s(n);if(n.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=j(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()),t.data.name=dt(e).name}pageSorts(t,e){let s=t.data.name,i=t.prototype,o="Payload",a="Command",n="Caption",r="Free",c=e.routeDynamic,l=e.routeDynamicSpesific,d=h(m=>m.charAt(0).toUpperCase()+m.slice(1),"upFirst"),p=h(m=>m.replace(o,"").replace(a,"").replace(n,"").replace(r,""),"getPureRouteName"),u=h((m,g)=>i[`methodSession${d(m)}`]?.(g),"methodSession");e.all[s]=t;for(let m=0;m<e.lenListRouteStaticSession;m++){let g=e.listRouteStaticSession[m];if(typeof i[g]!="function")continue;let b=e.routeStatic[g],v=e.routeStaticIntent[g],k=e.routeStaticSession[g],S={name:s,routeName:g},$=b||v;if($!==void 0){let X=g.includes(a),Y=g.includes("callback"),Z=g.startsWith("text"),x;if(X){let B=t.data.textCommand||t.data.name;x=B?`/${B}`:void 0}else Y?x=t.data.name:Z?x=t.data.text||t.data.name:x=t.data.name;x&&($[x]=S)}k!==void 0&&(k[u(g,s)]=S),g.toLowerCase().endsWith("free")&&l[p(g)].push(S)}i.free&&c.push(s)}async executeSyncBlocksDescription(t){let e=new Map,s=t.routeStatic.textCommand;for(let[,i]of Object.entries(s)){let o=i.name,a=this.templateManager.getDescriptionScopes(o);for(let n of a){e.has(n)||e.set(n,new Set);let r=this.templateManager.getDescriptionLanguage(o,"default",n);for(let c of r)e.get(n).add(c)}}for(let[i,o]of e)for(let a of o){let n=[];for(let[,l]of Object.entries(s)){let d=l.name,p=this.templateManager.getDescription(d,"default",a,i);p&&n.push({command:d,description:p})}if(n.length===0)continue;let r={type:i},c=a==="default"?void 0:a;try{let l=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(l.map(u=>({command:u.command,description:u.description})).sort((u,m)=>u.command.localeCompare(m.command))),p=JSON.stringify(n.sort((u,m)=>u.command.localeCompare(m.command)));d!==p&&(await this.bot.api.setMyCommands(n,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${i},${c?` lang: ${c},`:""} total (${n.length})`))}catch(l){this.log?.error?.(`Failed to sync descriptions for scope: ${i},${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","videoNoteCaption","videoNoteCaptionCommand"],e=["callbackPayload","textPayload","textCommandPayload","photoCaptionPayload","photoCaptionCommandPayload","videoCaptionPayload","videoCaptionCommandPayload","audioCaptionPayload","audioCaptionCommandPayload","documentCaptionPayload","documentCaptionCommandPayload","animationCaptionPayload","animationCaptionCommandPayload","voiceCaptionPayload","voiceCaptionCommandPayload","videoNoteCaptionPayload","videoNoteCaptionCommandPayload"],s=[...t,...e,"textFree","photoFree","videoFree","audioFree","documentFree","animationFree","voiceFree","videoNoteFree","stickerFree","locationFree","contactFree"],i=h((n,r)=>Object.fromEntries(n.map(c=>[c,r()])),"makeObject"),o=h(()=>[],"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:i(t,()=>({})),routeStaticIntent:i(e,()=>({})),routeStaticSession:i(s,()=>({})),listRouteStatic:t,listRouteStaticIntent:e,listRouteStaticSession:s,lenListRouteStatic:t.length,lenListRouteStaticIntent:e.length,lenListRouteStaticSession:s.length};return f.getFileManySync(void 0).forEach(({path:n,page:r})=>{this.pageBuildData(r,n),this.pageSorts(r,a),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(a.all).length})`),a}async pageRoutes(t,e){let s,i;if(s===void 0){let a=t.callbackData,n=t.msgText,r=t.msgCaption,c=this.pages.routeStatic;for(let l=0;l<this.pages.lenListRouteStatic;l++){let d=this.pages.listRouteStatic[l];if(d.startsWith(e)&&(i=c[d][a||n||r]),i)break}i!==void 0&&(s=this.pages.all[i.name])}if(s===void 0){let a=await t.sessionGet();if(a){let n=a.method,r=this.pages.routeStaticSession;for(let c=0;c<this.pages.lenListRouteStaticSession;c++){let l=this.pages.listRouteStaticSession[c];if(l.startsWith(e)&&(i=r[l][n]),i)break}i!==void 0&&(s=this.pages.all[i.name])}}if(s===void 0){let a=this.pages.routeStaticIntent,n=e==="callback",r=n?t.callbackData:t.msgText||t.msgCaption;if(r)for(let c=0;c<this.pages.lenListRouteStaticIntent;c++){let l=this.pages.listRouteStaticIntent[c];if(l.startsWith(e)){let d=a[l];i=d[t.intent(r,n?"colon":"space",1)],!i&&!n&&(i=d[t.intent(r,"space",2)])}if(i)break}i!==void 0&&(s=this.pages.all[i.name])}if(s!==void 0&&i!==void 0)return s.prototype[i.routeName]?await new s(t)[i.routeName]?.():void 0;let o=this.pages.routeDynamicSpesific[e]||[];for(let a=0;a<o.length;a++){let n=o[a];if(n===void 0)continue;let r=this.pages.all[n.name];if(r===void 0||!r.prototype[n.routeName])continue;let l=await new r(t)[n.routeName]?.();if(l!==null)return l}for(let a=0;a<this.pages.routeDynamic.length;a++){let n=this.pages.routeDynamic[a];if(n===void 0)continue;let r=this.pages.all[n];if(r===void 0||!r.prototype.free)continue;let l=await new r(t).free?.();if(l!==null)return l}return null}async hookBeforeRoute(t,e){return!!(t||e)}async hookErrorPage(t,e,s,i){}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(i){await this.hookErrorPage(s,e,i,!1)}}async onCallbackQueryData(t){let e=this.createCtx(t);try{if(await e.callbackQueryAnswer(),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))}};import{Worker as ht,isMainThread as mt}from"worker_threads";var V=class{constructor(t,e){this.path=t;this.argv=e;if(!mt)throw new Error("Is not main thread");this.sub=new ht(t,{argv:e}),this.subId=this.sub.threadId,this.sub.on("message",async s=>{let{id:i,method:o,params:a,result:n}=s;if(o!==void 0){let r=this[o];if(typeof r!="function")throw new Error(`Method ${o} not found`);let c=await r.apply(this,a);this.send({id:i,result:c})}else if(n!==void 0){let r=this.map.get(i);r&&(r?.(n),this.map.delete(i))}})}static{h(this,"ThreadMain")}map=new Map;sub;pid=process.pid;subId;createId(){return Math.random()}send(t){this.sub.postMessage(t)}async sendRequest(t,e,s=!0){let i=this.createId();return s?new Promise(o=>{this.map.set(i,o),this.send({id:i,method:t,params:e})}):this.send({id:i,method:t,params:e})}kill(){this.sub.terminate()}};var Q=class{static{h(this,"ThreadExport")}static init(t){let{CSub:e,CMain:s=V,path:i,wrap:o}=t,a=`for-${i}`;if(process.argv[2]===a)return new e,{};let n,r=new Proxy({},{get(d,p){return p==="sendRequest"?(u,m,g=!0)=>{if(!n)throw new Error(`Thread at ${i} not launched yet.`);return n.sendRequest(u,m,g)}:(...u)=>{if(!n)throw new Error(`Thread at ${i} not launched yet.`);return n.sendRequest(p,u)}}});return{...o?o(r):{},launch:h((d=[])=>(n=new s(i,[a,...d]),n),"launch")}}};var G=class{static{h(this,"ThreadMainPool")}thread={};threadCount=0;constructor(t){t.forEach(async e=>{let s=await e;this.thread[s.subId]=s,this.threadCount+=1})}add(t){this.thread[t.subId]=t,this.threadCount+=1}getInstance(t){return this.thread[t]}killAll(){return Object.values(this.thread).map(({subId:t})=>this.kill(t))}kill(t){let e=this.thread[t];return e?.kill(),delete this.thread[t],this.threadCount-=1,e?.subId}async broadcastRequest(t,e){return await Promise.all(Object.values(this.thread).map(s=>s.sendRequest(t,e,!0)))}async sendRequest(t,e,s,i=!0){return await this.thread[t]?.sendRequest(e,s,i)}};import{parentPort as J,threadId as gt,isMainThread as yt}from"worker_threads";var U=class{static{h(this,"ThreadSub")}map=new Map;argv=process.argv;id=gt;pid=process.pid;threadIsMain=yt;constructor(){if(this.threadIsMain)throw new Error("Is not sub thread");J.on("message",async t=>{let{id:e,method:s,params:i,result:o}=t;if(s!==void 0)try{let a=this[s];if(typeof a!="function")throw new Error(`Method ${s} not found`);let n=await a.apply(this,i);this.send({id:e,result:n})}catch(a){this.send({id:e,error:a})}else if(o!==void 0){let a=this.map.get(e);a&&(a?.(o),this.map.delete(e))}})}createId(){return Math.random()}send(t){J.postMessage(t)}async sendRequest(t,e,s=!0){let i=this.createId();return s?new Promise(o=>{this.map.set(i,o),this.send({id:i,method:t,params:e})}):this.send({id:i,method:t,params:e})}};var H=class{static{h(this,"ComponentKeyboard")}static data;static _process(t,e){if(e.type||(e.type="inline"),e.lang){let s=t[e.lang];return`
|
|
7
|
+
`);n=n.replace(`__IMPORT_${r}__`,p)}return n}};var V=class{static{h(this,"TemplateManager")}_map=new Map;_engine=P;_watcher=[];_pageManager=S;_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(!I(e))throw new Error(`Template base path is not exists: ${e}`);if(!w(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],i=pt(s,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...t});this._watcher[e]=i,i.on("change",this._handleFileChange.bind(this)),i.on("add",this._handleFileAdd.bind(this)),i.on("unlink",this._handleFileDelete.bind(this)),i.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(t){let e=B(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileAdd(t){let e=B(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileDelete(t){let e=B(t),s=this._getKey(e);this._map.has(s)&&this._map.delete(s)}_handleWatchError(t){}_loadAllFiles(){let t=new Map,e=[];for(let i=0;i<this._path.length;i++){let o=this._path[i],n=lt(o,"utf8").filter(r=>this._isValidFile(r));for(let r of n){let c=k(o,r),l=this._getExtension(r),d=this._getKey(r);if(l===".html")t.set(d,R(c,"utf8"));else if(l===".ts"||l===".js"){let p=S.getFileSync(c);p?.template!==void 0&&(t.set(d,p.template),e.push(p))}}}let s=new Map;for(let[i,o]of t.entries())this._compile(i,o,void 0,s,t);t.clear(),s.clear();for(let i of e)i.template=void 0}_loadFile(t){for(let e=0;e<this._path.length;e++){let s=this._path[e],i=k(s,t),o=this._getExtension(t),a=this._getKey(t);if(o==".html"){let n=R(i,"utf8");this._compile(a,n)}else if(o==".ts"||o==".js"){let n=S.getFileSync(i);n?.template!==void 0&&(this._compile(a,n.template),n.template=void 0)}else throw new Error(`File ${t} is not support`)}}_getExtension(t){return q(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let s=q(t).toLowerCase();if(s){let n=k(e,t);if(I(n)&&w(n).isFile()){if(s===".html")return R(n,"utf8");if(s===".ts"||s===".js")try{return S.getFileSync(n)?.template??null}catch{return null}}continue}let i=k(e,`${t}.ts`),o=k(e,`${t}.js`);if(I(i)&&w(i).isFile())try{return S.getFileSync(i)?.template??null}catch{}else if(I(o)&&w(o).isFile())try{return S.getFileSync(i)?.template??null}catch{}let a=k(e,`${t}.html`);if(I(a)&&w(a).isFile())return R(a,"utf8")}return null}_isValidFile(t){return this._supportedExtensions.has(this._getExtension(t))}_getKey(t){return t.replace(/\.[^/.]+$/,"")}_compile(t,e,s,i,o){let a=this._map.get(t),n=a||{},r=!1,c=P.processImportBlocks(e,d=>o&&o.has(d)?o.get(d):this._readTemplateFile(d),0,i),l=P._processBaseBlocks(c);(s===void 0||s?.media===!1||a?.media===void 0)&&(n.media=P.compileMedia(c,l),r=!0),(s===void 0||s?.message===!1||a?.message===void 0)&&(n.message=P.compileMessages(c,l),r=!0),(s===void 0||s?.keyboard===!1||a?.keyboard===void 0)&&(n.keyboard=P.compileKeyboards(c,l),r=!0),(s===void 0||s?.description===!1||a?.description===void 0)&&(n.description=P.compileDescription(c,l),r=!0),r&&this._map.set(t,n)}getMedia(t,e="default",s="default",i){let a=this._map.get(t)?.media?.[e],n=a?.[s]||a?.default;try{if(!n)throw new Error("Media function not found, please check your template");return n(i)}catch{return{}}}getMessage(t,e="default",s="default",i){try{let a=this._map.get(t)?.message?.[e],n=a?.[s]||a?.default;if(!n)throw"";return n(i)}catch{return""}}getDescription(t,e="default",s="default",i="default",o){try{let n=this._map.get(t)?.description?.[e]?.[i],r=n?.[s]||n?.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 i=this._map.get(t)?.description?.[e];return i?Object.keys(i):[]}catch{return[]}}getKeyboard(t,e="default",s="default",i="inline",o){try{let n=this._map.get(t)?.keyboard?.[e],r=n?.[s]?.[i]||n?.default?.[i];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 i=k(this._path[s],t);if(I(i))return dt(i,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()}};import{Bot as bt,webhookCallback as Q}from"grammy";var ft=gt(import.meta.url),Ct=ht(ft),St=JSON.parse(mt(U(Ct,"../../package.json"),"utf-8")).version,J=class{static{h(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;log;bot;handlerBotUpdate;constructor(t){if(!t?.token||t?.token?.length==0)throw new Error("Token is not valid or empty");if(this.log=t.log===!0?new yt:t.log?t.log:void 0,this.log?.info?.(`Gramstax v${St}`),this.cacheSession=t.cacheSession||new _("memory","session"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new V({path:[U(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){this.log?.error?.(`[Bot.catch]: ${JSON.stringify(t,null,2)}`)}hookBeforeStart(){}hookAfterStart(){}async onStart(t,e,s){await this.executeSyncBlocksDescription(this.pages);let{username:i}=t;this.log?.success?.(`Telegram bot polling started: ${i} ${e=="webhook"||e=="serverless"?`(${s})`:""}`),this.hookAfterStart()}createBot(t){return new bt(t)}createCtx(t){return new F({ct:t,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{session:{},data:{}}})}runPolling(){this.bot.start({onStart:h(t=>{this.onStart(t,"polling",null)},"onStart")})}async runWebhook(t){let{serve:e}=await import("bun"),s=Q(this.bot,"bun");this.handlerBotUpdate=s;let i=new URL(t).pathname;e({fetch(n){let{pathname:r}=new URL(n.url);if(n.method=="POST"&&r==i)return s(n);if(n.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=Q(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()),t.data.name=ut(e).name}pageSorts(t,e){let s=t.data.name,i=t.prototype,o="Payload",a="Command",n="Caption",r="Free",c=e.routeDynamic,l=e.routeDynamicSpesific,d=h(m=>m.charAt(0).toUpperCase()+m.slice(1),"upFirst"),p=h(m=>m.replace(o,"").replace(a,"").replace(n,"").replace(r,""),"getPureRouteName"),u=h((m,g)=>i[`methodSession${d(m)}`]?.(g),"methodSession");e.all[s]=t;for(let m=0;m<e.lenListRouteStaticSession;m++){let g=e.listRouteStaticSession[m];if(typeof i[g]!="function")continue;let b=e.routeStatic[g],x=e.routeStaticIntent[g],T=e.routeStaticSession[g],v={name:s,routeName:g},N=b||x;if(N!==void 0){let tt=g.includes(a),et=g.includes("callback"),st=g.startsWith("text"),M;if(tt){let E=t.data.textCommand||t.data.name;M=E?`/${E}`:void 0}else et?M=t.data.name:st?M=t.data.text||t.data.name:M=t.data.name;M&&(N[M]=v)}T!==void 0&&(T[u(g,s)]=v),g.toLowerCase().endsWith("free")&&l[p(g)].push(v)}i.free&&c.push(s)}async executeSyncBlocksDescription(t){let e=new Map,s=t.routeStatic.textCommand;for(let[,i]of Object.entries(s)){let o=i.name,a=this.templateManager.getDescriptionScopes(o);for(let n of a){e.has(n)||e.set(n,new Set);let r=this.templateManager.getDescriptionLanguage(o,"default",n);for(let c of r)e.get(n).add(c)}}for(let[i,o]of e)for(let a of o){let n=[];for(let[,l]of Object.entries(s)){let d=l.name,p=this.templateManager.getDescription(d,"default",a,i);p&&n.push({command:d,description:p})}if(n.length===0)continue;let r={type:i},c=a==="default"?void 0:a;try{let l=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(l.map(u=>({command:u.command,description:u.description})).sort((u,m)=>u.command.localeCompare(m.command))),p=JSON.stringify(n.sort((u,m)=>u.command.localeCompare(m.command)));d!==p&&(await this.bot.api.setMyCommands(n,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${i},${c?` lang: ${c},`:""} total (${n.length})`))}catch(l){this.log?.error?.(`Failed to sync descriptions for scope: ${i},${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","videoNoteCaption","videoNoteCaptionCommand"],e=["callbackPayload","textPayload","textCommandPayload","photoCaptionPayload","photoCaptionCommandPayload","videoCaptionPayload","videoCaptionCommandPayload","audioCaptionPayload","audioCaptionCommandPayload","documentCaptionPayload","documentCaptionCommandPayload","animationCaptionPayload","animationCaptionCommandPayload","voiceCaptionPayload","voiceCaptionCommandPayload","videoNoteCaptionPayload","videoNoteCaptionCommandPayload"],s=[...t,...e,"textFree","photoFree","videoFree","audioFree","documentFree","animationFree","voiceFree","videoNoteFree","stickerFree","locationFree","contactFree"],i=h((n,r)=>Object.fromEntries(n.map(c=>[c,r()])),"makeObject"),o=h(()=>[],"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:i(t,()=>({})),routeStaticIntent:i(e,()=>({})),routeStaticSession:i(s,()=>({})),listRouteStatic:t,listRouteStaticIntent:e,listRouteStaticSession:s,lenListRouteStatic:t.length,lenListRouteStaticIntent:e.length,lenListRouteStaticSession:s.length};return S.getFileManySync(void 0).forEach(({path:n,page:r})=>{this.pageBuildData(r,n),this.pageSorts(r,a),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(a.all).length})`),a}async pageRoutes(t,e){let s,i;if(s===void 0){let a=t.callbackData,n=t.msgText,r=t.msgCaption,c=this.pages.routeStatic;for(let l=0;l<this.pages.lenListRouteStatic;l++){let d=this.pages.listRouteStatic[l];if(d.startsWith(e)&&(i=c[d][a||n||r]),i)break}i!==void 0&&(s=this.pages.all[i.name])}if(s===void 0){let a=await t.sessionGet();if(a){let n=a.method,r=this.pages.routeStaticSession;for(let c=0;c<this.pages.lenListRouteStaticSession;c++){let l=this.pages.listRouteStaticSession[c];if(l.startsWith(e)&&(i=r[l][n]),i)break}i!==void 0&&(s=this.pages.all[i.name])}}if(s===void 0){let a=this.pages.routeStaticIntent,n=e==="callback",r=n?t.callbackData:t.msgText||t.msgCaption;if(r)for(let c=0;c<this.pages.lenListRouteStaticIntent;c++){let l=this.pages.listRouteStaticIntent[c];if(l.startsWith(e)){let d=a[l];i=d[t.intent(r,n?"colon":"space",1)],!i&&!n&&(i=d[t.intent(r,"space",2)])}if(i)break}i!==void 0&&(s=this.pages.all[i.name])}if(s!==void 0&&i!==void 0)return s.prototype[i.routeName]?await new s(t)[i.routeName]?.():void 0;let o=this.pages.routeDynamicSpesific[e]||[];for(let a=0;a<o.length;a++){let n=o[a];if(n===void 0)continue;let r=this.pages.all[n.name];if(r===void 0||!r.prototype[n.routeName])continue;let l=await new r(t)[n.routeName]?.();if(l!==null)return l}for(let a=0;a<this.pages.routeDynamic.length;a++){let n=this.pages.routeDynamic[a];if(n===void 0)continue;let r=this.pages.all[n];if(r===void 0||!r.prototype.free)continue;let l=await new r(t).free?.();if(l!==null)return l}return null}async hookBeforeRoute(t,e){return!!(t||e)}async hookErrorPage(t,e,s,i){}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(i){await this.hookErrorPage(s,e,i,!1)}}async onCallbackQueryData(t){let e=this.createCtx(t);try{if(await e.callbackQueryAnswer(),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))}};import{Worker as Pt,isMainThread as vt}from"worker_threads";var D=class{constructor(t,e){this.path=t;this.argv=e;if(!vt)throw new Error("Is not main thread");this.sub=new Pt(t,{argv:e}),this.subId=this.sub.threadId,this.sub.on("message",async s=>{let{id:i,method:o,params:a,result:n}=s;if(o!==void 0){let r=this[o];if(typeof r!="function")throw new Error(`Method ${o} not found`);let c=await r.apply(this,a);this.send({id:i,result:c})}else if(n!==void 0){let r=this.map.get(i);r&&(r?.(n),this.map.delete(i))}})}static{h(this,"ThreadMain")}map=new Map;sub;pid=process.pid;subId;createId(){return Math.random()}send(t){this.sub.postMessage(t)}async sendRequest(t,e,s=!0){let i=this.createId();return s?new Promise(o=>{this.map.set(i,o),this.send({id:i,method:t,params:e})}):this.send({id:i,method:t,params:e})}kill(){this.sub.terminate()}};var G=class{static{h(this,"ThreadExport")}static init(t){let{CSub:e,CMain:s=D,path:i,wrap:o}=t,a=`for-${i}`;if(process.argv[2]===a)return new e,{};let n,r=new Proxy({},{get(d,p){return p==="sendRequest"?(u,m,g=!0)=>{if(!n)throw new Error(`Thread at ${i} not launched yet.`);return n.sendRequest(u,m,g)}:(...u)=>{if(!n)throw new Error(`Thread at ${i} not launched yet.`);return n.sendRequest(p,u)}}});return{...o?o(r):{},launch:h((d=[])=>(n=new s(i,[a,...d]),n),"launch")}}};var H=class{static{h(this,"ThreadMainPool")}thread={};threadCount=0;constructor(t){t.forEach(async e=>{let s=await e;this.thread[s.subId]=s,this.threadCount+=1})}add(t){this.thread[t.subId]=t,this.threadCount+=1}getInstance(t){return this.thread[t]}killAll(){return Object.values(this.thread).map(({subId:t})=>this.kill(t))}kill(t){let e=this.thread[t];return e?.kill(),delete this.thread[t],this.threadCount-=1,e?.subId}async broadcastRequest(t,e){return await Promise.all(Object.values(this.thread).map(s=>s.sendRequest(t,e,!0)))}async sendRequest(t,e,s,i=!0){return await this.thread[t]?.sendRequest(e,s,i)}};import{parentPort as z,threadId as kt,isMainThread as xt}from"worker_threads";var X=class{static{h(this,"ThreadSub")}map=new Map;argv=process.argv;id=kt;pid=process.pid;threadIsMain=xt;constructor(){if(this.threadIsMain)throw new Error("Is not sub thread");z.on("message",async t=>{let{id:e,method:s,params:i,result:o}=t;if(s!==void 0)try{let a=this[s];if(typeof a!="function")throw new Error(`Method ${s} not found`);let n=await a.apply(this,i);this.send({id:e,result:n})}catch(a){this.send({id:e,error:a})}else if(o!==void 0){let a=this.map.get(e);a&&(a?.(o),this.map.delete(e))}})}createId(){return Math.random()}send(t){z.postMessage(t)}async sendRequest(t,e,s=!0){let i=this.createId();return s?new Promise(o=>{this.map.set(i,o),this.send({id:i,method:t,params:e})}):this.send({id:i,method:t,params:e})}};var Y=class{static{h(this,"ComponentKeyboard")}static data;static _process(t,e){if(e.type||(e.type="inline"),e.lang){let s=t[e.lang];return`
|
|
8
8
|
<keyboard type="${e.type}" lang="${e.lang}">${e.reverse?this.data._reverse(s):s}</keyboard>
|
|
9
9
|
`}return Object.keys(t).map(s=>{let i=t[s];return`
|
|
10
10
|
<keyboard type="${e.type}" lang="${s}">${e.reverse?this.data._reverse(i):i}</keyboard>
|
|
11
|
-
`}).join(" ")}static _build(t,e,s){if(!this.data)throw new Error("Data not found");let i=this.data[t];if(!i)throw new Error(`Function ${t} not found`);return this._process(i.call(this.data,e),{type:s,lang:e})}};var
|
|
11
|
+
`}).join(" ")}static _build(t,e,s){if(!this.data)throw new Error("Data not found");let i=this.data[t];if(!i)throw new Error(`Function ${t} not found`);return this._process(i.call(this.data,e),{type:s,lang:e})}};var Z=class{static{h(this,"DataKeyboard")}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),{})}static _build(t,e,s){if(t){let i=s[t||""];return e?this._reverse(i):i}return e?this._reverseObj(s):s}};export{_ as CacheExternal,Y as ComponentKeyboard,F as Ctx,Z as DataKeyboard,J as Gramstax,A as LoggingUtils,P as TemplateEngine,V as TemplateManager,G as ThreadExport,D as ThreadMain,H as ThreadMainPool,X as ThreadSub,It as log};
|