gramstax 0.3.0 → 0.3.2
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 +8 -8
- package/dist/src/index.d.cts +46 -23
- package/dist/src/index.d.ts +46 -23
- package/dist/src/index.js +8 -8
- package/package.json +1 -1
package/dist/src/index.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
"use strict";var et=Object.create;var T=Object.defineProperty;var st=Object.getOwnPropertyDescriptor;var it=Object.getOwnPropertyNames;var nt=Object.getPrototypeOf,ot=Object.prototype.hasOwnProperty;var h=(g,t)=>T(g,"name",{value:t,configurable:!0});var at=(g,t)=>{for(var e in t)T(g,e,{get:t[e],enumerable:!0})},j=(g,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of it(t))!ot.call(g,i)&&i!==e&&T(g,i,{get:()=>t[i],enumerable:!(s=st(t,i))||s.enumerable});return g};var Q=(g,t,e)=>(e=g!=null?et(nt(g)):{},j(t||!g||!g.__esModule?T(e,"default",{value:g,enumerable:!0}):e,g)),rt=g=>j(T({},"__esModule",{value:!0}),g);var lt={};at(lt,{CacheExternal:()=>w,ComponentKeyboard:()=>K,Ctx:()=>I,DataKeyboard:()=>L,Gramstax:()=>$,LoggingUtils:()=>R,TemplateEngine:()=>S,TemplateManager:()=>_,ThreadExport:()=>B,ThreadMain:()=>V,ThreadMainPool:()=>N,ThreadSub:()=>E,log:()=>ct});module.exports=rt(lt);var q=Q(require("logging-pretty"),1);var R=class extends q.default{static{h(this,"LoggingUtils")}constructor(t){super(t)}errorMake(t,e,s){this.error(`[${e?.name||e}:${s}] ${String(t)}`)}},ct=new R;var J=require("keyv"),U=Q(require("@keyv/redis"),1);var w=class extends J.Keyv{constructor(e="memory",s,i,a){let n;e.startsWith("redis")&&(n=new U.default(e)),e==="memory"&&(n=new Map),a?.forceStore&&(n=a.forceStore);super({store:n,namespace:s,ttl:i});this.url=e}static{h(this,"CacheExternal")}};var G=require("timers/promises"),M=require("grammy");var I=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 msgTextIntent(){return this.msgText&&this.msgText.indexOf(" ")!=-1?this.msgText.split(" ")[0]:""}get msgTextPayloads(){return this.msgText&&this.msgText.indexOf(" ")!=-1?this.msgText.split(" ").slice(1):[]}get msgTextPayload(){return this.msgTextPayloads[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionIntent(){return this.msgCaption&&this.msgCaption.indexOf(" ")!=-1?this.msgCaption.split(" ")[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 callbackDataIntent(){return this.callbackData&&this.callbackData.indexOf(":")!=-1?this.callbackData.split(":")[0]:""}get callbackDataPayloads(){return this.callbackData&&this.callbackData.indexOf(":")!=-1?this.callbackData.split(":").slice(1):[]}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,a,n,o=!1){try{let l=e.map(c=>this.templateManager.getMessage(this.data.name,a,c,i));for(let c=0;c<t.length;c++){let d=t[c],p=l[c];await this.ct.api.sendMessage(d,p,{parse_mode:"HTML",reply_markup:s,...n}),c+1==30&&await(0,G.setTimeout)(1200)}}catch(r){if(o)throw r}}async reply(t,e,s,i){let a=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.reply(a,{parse_mode:"HTML",reply_markup:t,...i})}async replyMedia(t,e,s,i,a){let n=this.templateManager.getMedia(this.data.name,i,this.userLanguage,s),o={parse_mode:"HTML",reply_markup:e,...a};if(t=="photo")return await this.ct.replyWithPhoto(n.src,{caption:n.caption,...o});if(t=="video")return await this.ct.replyWithVideo(n.src,{caption:n.caption,...o});if(t=="audio")return await this.ct.replyWithAudio(n.src,{caption:n.caption,...o});if(t=="document")return await this.ct.replyWithDocument(n.src,{caption:n.caption,...o});if(t=="animation")return await this.ct.replyWithAnimation(n.src,{caption:n.caption,...o});if(t=="voice")return await this.ct.replyWithVoice(n.src,o);if(t=="video_note")return await this.ct.replyWithVideoNote(n.src,o);if(t=="sticker")return await this.ct.replyWithSticker(n.src,o);if(t=="location")return await this.ct.replyWithLocation(parseInt(n.latitude),parseInt(n.longitude),o);if(t=="contact")return await this.ct.replyWithContact(n.phone,n.first_name,{vcard:n.vcard,...o})}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,a=!0){try{let n=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.editMessageText(n,{parse_mode:"HTML",reply_markup:t,...i})}catch(n){if(a)await this.reply(t,e,s,i);else throw n}}async editMedia(t,e,s,i,a,n,o=!0){try{let{src:r,caption:l}=this.templateManager.getMedia(this.data.name,i,this.userLanguage,s);return t=="voice"?(await this.delete(),await this.replyVoice(e,s,i,a)):t=="video_note"?(await this.delete(),await this.replyVoice(e,s,i,a)):t=="sticker"?(await this.delete(),await this.replySticker(e,s,i,a)):t=="location"?(await this.delete(),await this.replyLocation(e,s,i,a)):t=="contact"?(await this.delete(),await this.replyContact(e,s,i,a)):await this.ct.editMessageMedia({media:r,caption:l,type:t,parse_mode:"HTML",...a},{reply_markup:e,...n})}catch(r){if(o===!0)await this.reply(e,s,i,n);else throw r}}async editPhoto(t,e,s,i,a){return await this.editMedia("photo",t,e,s,i,a)}async editVideo(t,e,s,i,a){return await this.editMedia("video",t,e,s,i,a)}async editAudio(t,e,s,i,a){return await this.editMedia("audio",t,e,s,i,a)}async editDocument(t,e,s,i,a){return await this.editMedia("document",t,e,s,i,a)}async editAnimation(t,e,s,i,a){return await this.editMedia("animation",t,e,s,i,a)}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},a=await this.cacheSession.set(`${this.userId}`,i);return a&&(this.session=i),a}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){return{name:"",callbackData:t?function(...e){let s=t(...e);return`${this.name}${s==""||s===void 0?"":`:${s}`}`}:function(){return this?.name}}}inlineKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let o=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(o);if(!r){let l=new M.InlineKeyboard,c=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data),d=t(l,c);return this.cacheKeyboard.set(o,d),d}return r}let i=new M.InlineKeyboard,a=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data);return t(i,a)}bottomKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let o=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(o);if(!r){let l=new M.Keyboard,c=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),d=t(l,c);return d.resized(!0),this.cacheKeyboard.set(o,d),d}return r}let i=new M.Keyboard,a=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),n=t(i,a);return n.resized(),n}validateSessionCallback(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionCallback(e)}validateSessionCallbackPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionCallbackPayload(e)}validateSessionText(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionText(e)}validateSessionTextPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionTextPayload(e)}validateSessionTextCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionTextCommand(e)}validateSessionTextCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionTextCommandPayload(e)}validateSessionTextFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionTextFree(e)}validateSessionPhotoCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionPhotoCaption(e)}validateSessionPhotoCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionPhotoCaptionPayload(e)}validateSessionPhotoCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionPhotoCaptionCommand(e)}validateSessionPhotoCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionPhotoCaptionCommandPayload(e)}validateSessionPhotoFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionPhotoFree(e)}validateSessionVideoCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoCaption(e)}validateSessionVideoCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoCaptionPayload(e)}validateSessionVideoCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoCaptionCommand(e)}validateSessionVideoCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoCaptionCommandPayload(e)}validateSessionVideoFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoFree(e)}validateSessionAudioCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAudioCaption(e)}validateSessionAudioCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAudioCaptionPayload(e)}validateSessionAudioCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAudioCaptionCommand(e)}validateSessionAudioCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAudioCaptionCommandPayload(e)}validateSessionAudioFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAudioFree(e)}validateSessionDocumentCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionDocumentCaption(e)}validateSessionDocumentCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionDocumentCaptionPayload(e)}validateSessionDocumentCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionDocumentCaptionCommand(e)}validateSessionDocumentCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionDocumentCaptionCommandPayload(e)}validateSessionDocumentFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionDocumentFree(e)}validateSessionAnimationCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAnimationCaption(e)}validateSessionAnimationCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAnimationCaptionPayload(e)}validateSessionAnimationCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAnimationCaptionCommand(e)}validateSessionAnimationCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAnimationCaptionCommandPayload(e)}validateSessionAnimationFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAnimationFree(e)}validateSessionVoiceCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVoiceCaption(e)}validateSessionVoiceCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVoiceCaptionPayload(e)}validateSessionVoiceCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVoiceCaptionCommand(e)}validateSessionVoiceCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVoiceCaptionCommandPayload(e)}validateSessionVoiceFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVoiceFree(e)}validateSessionVideoNoteCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoNoteCaption(e)}validateSessionVideoNoteCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoNoteCaptionPayload(e)}validateSessionVideoNoteCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoNoteCaptionCommand(e)}validateSessionVideoNoteCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoNoteCaptionCommandPayload(e)}validateSessionVideoNoteFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoNoteFree(e)}validateSessionStickerFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionStickerFree(e)}validateSessionLocationFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionLocationFree(e)}validateSessionContactFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===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)}intent(t,e=!0){t||(t=e?this.data.callbackData():this.data.name);let s=e?":":" ";return t.indexOf(s)!=-1?t.split(s)[0]:t}methodSession(t,e){return`${t}-${e||this.data.name}`}methodSessionCallback(t){return this.methodSession("1",t)}methodSessionCallbackPayload(t){return this.methodSession("2",t)}methodSessionText(t){return this.methodSession("3",t)}methodSessionTextPayload(t){return this.methodSession("4",t)}methodSessionTextCommand(t){return this.methodSession("5",t)}methodSessionTextCommandPayload(t){return this.methodSession("6",t)}methodSessionTextFree(t){return this.methodSession("7",t)}methodSessionPhotoCaption(t){return this.methodSession("8",t)}methodSessionPhotoCaptionPayload(t){return this.methodSession("9",t)}methodSessionPhotoCaptionCommand(t){return this.methodSession("10",t)}methodSessionPhotoCaptionCommandPayload(t){return this.methodSession("11",t)}methodSessionPhotoFree(t){return this.methodSession("12",t)}methodSessionVideoCaption(t){return this.methodSession("13",t)}methodSessionVideoCaptionPayload(t){return this.methodSession("14",t)}methodSessionVideoCaptionCommand(t){return this.methodSession("15",t)}methodSessionVideoCaptionCommandPayload(t){return this.methodSession("16",t)}methodSessionVideoFree(t){return this.methodSession("17",t)}methodSessionAudioCaption(t){return this.methodSession("18",t)}methodSessionAudioCaptionPayload(t){return this.methodSession("19",t)}methodSessionAudioCaptionCommand(t){return this.methodSession("20",t)}methodSessionAudioCaptionCommandPayload(t){return this.methodSession("21",t)}methodSessionAudioFree(t){return this.methodSession("22",t)}methodSessionDocumentCaption(t){return this.methodSession("23",t)}methodSessionDocumentCaptionPayload(t){return this.methodSession("24",t)}methodSessionDocumentCaptionCommand(t){return this.methodSession("25",t)}methodSessionDocumentCaptionCommandPayload(t){return this.methodSession("26",t)}methodSessionDocumentFree(t){return this.methodSession("27",t)}methodSessionAnimationCaption(t){return this.methodSession("28",t)}methodSessionAnimationCaptionPayload(t){return this.methodSession("29",t)}methodSessionAnimationCaptionCommand(t){return this.methodSession("30",t)}methodSessionAnimationCaptionCommandPayload(t){return this.methodSession("31",t)}methodSessionAnimationFree(t){return this.methodSession("32",t)}methodSessionVoiceCaption(t){return this.methodSession("33",t)}methodSessionVoiceCaptionPayload(t){return this.methodSession("34",t)}methodSessionVoiceCaptionCommand(t){return this.methodSession("35",t)}methodSessionVoiceCaptionCommandPayload(t){return this.methodSession("36",t)}methodSessionVoiceFree(t){return this.methodSession("37",t)}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 z=require("bun"),O=require("path");var A=require("path"),D=require("fs");var P=class{static{h(this,"PageManager")}static _getFile(t,e,s=!0,i=0){let n=Object.values(t)[i];if(n===void 0)throw new Error(`File ${e} must have export (not default) class page`);return s===!0&&(n.template=void 0),n}static getFilePath(){return(0,A.join)(process.cwd(),"src","pages")}static getFileSync(t,e=!0,s=0){t||(t=this.getFilePath());let i=require(t);return this._getFile(i,t,e,s)}static async getFile(t,e=!0,s=0){t||(t=this.getFilePath());let i=await import(`${t}?t=${Date.now()}`);return this._getFile(i,t,e,s)}static getFileManySync(t,e=!0,s=0){if(t||(t=this.getFilePath()),!(0,D.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,D.readdirSync)(t).map(a=>{let n=(0,A.join)(t,a);return{path:n,page:this.getFileSync(n,e,s)}})}};var X=require("logging-pretty");var f=require("path"),y=require("fs"),H=require("chokidar");var S=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 a=i[2]??"default",o=(i[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[a]=o}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,a)=>{if(!i)return"";let n="",o=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,l;for(;(l=o.exec(a))!==null;){let d=(l[1]||"").split(",").map(u=>u.trim()),p=(l[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(u=>{n+=`case "${u}": `}),n+=`return \`${p}\`; `}let c=r.exec(a);if(c){let d=(c[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");n+=`default: return \`${d}\`; `}else n+="default: return ''; ";return`\${(() => { switch((data && data["${i}"])) { ${n} } })()}`})}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,a)=>{let n={},o=/(\w+)="([^"]*)"/g;if(i)for(let p of i.matchAll(o))n[p[1]]=p[2];let r=n.src;if(!r)return"";let l=n.join??"\\n",c=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");c=c.replace(/\{\{([\w.]+)\}\}/g,(p,u)=>u==="e"||u.startsWith("e.")?`\${${u}}`:u==="i"?"${i}":p);let d=l.replace(/"/g,'\\"');return`\${(data && data["${r}"] || []).map((e, i) => \`${c}\`).join("${d}")}`})}static _processMediaBlocks(t){let e=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let i of t.matchAll(e)){let a=i[1],n=i[2],o={},r=/(\w+)="([^"]*)"/g;if(a)for(let u of a.matchAll(r))o[u[1]]=u[2];let l=o.lang||"default",c=o.type,d=n.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),p={type:c};o.src&&(p.src=o.src),d&&c!=="video_note"&&c!=="sticker"&&(p.caption=d),c==="location"&&(o.latitude&&(p.latitude=o.latitude),o.longitude&&(p.longitude=o.longitude),d&&(p.caption=d)),c==="contact"&&(o.phone&&(p.phone=o.phone),o.first_name&&(p.first_name=o.first_name),o.last_name&&(p.last_name=o.last_name),o.vcard&&(p.vcard=o.vcard),d&&(p.caption=d)),s[l]=p}return s}static _processMessageBlocks(t){let e=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,i,a]of t.matchAll(e)){let n={},o=/(\w+)="([^"]*)"/g;if(i)for(let c of i.matchAll(o))n[c[1]]=c[2];let r=n.lang||"default",l=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=l}return s}static _processDescriptionBlocks(t){let e=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,i,a]of t.matchAll(e)){let n={},o=/(\w+)="([^"]*)"/g;if(i)for(let d of i.matchAll(o))n[d[1]]=d[2];let r=n.lang||"default",l=n.scope||"default",c=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][l]=c}return s}static _processKeyboardBlocks(t){let e=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,i,a]of t.matchAll(e)){let n={},o=/(\w+)="([^"]*)"/g;if(i)for(let d of i.matchAll(o))n[d[1]]=d[2];let r=n.lang||"default",l=n.type==="bottom"?"bottom":"inline",c=a.trim();s[r]||(s[r]={}),s[r][l]=c}return s}static _compileToFunction(t,e){let s;e?s=t.map(n=>`\`${n}\``).join(","):s=`\`${t}\``;let i=s;if(i=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(i))),e){let a=`return [${i}]`;return new Function("data",a)}else{let a=`return ${i}`;return new Function("data",a)}}static compileMedia(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[a,n]of Object.entries(s)){let o=this._processMediaBlocks(n);i[a]={};for(let[r,l]of Object.entries(o)){let c={};for(let[d,p]of Object.entries(l)){if(d==="type"||typeof p!="string")continue;let u=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(p)))));c[d]=this._compileToFunction(u,!1)}i[a][r]=d=>{let p={...l};for(let[u,m]of Object.entries(c))p[u]=m(d);return p}}}return i}static compileMessages(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[a,n]of Object.entries(s)){let o=this._processMessageBlocks(n);i[a]={};for(let[r,l]of Object.entries(o)){let c=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(l)))));i[a][r]=this._compileToFunction(c,!1)}}return i}static compileDescription(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[a,n]of Object.entries(s)){let o=this._processDescriptionBlocks(n);i[a]={};for(let[r,l]of Object.entries(o))for(let[c,d]of Object.entries(l)){i[a][c]||(i[a][c]={});let p=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));i[a][c][r]=this._compileToFunction(p,!1)}}return i}static compileKeyboards(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[a,n]of Object.entries(s)){let o=this._processKeyboardBlocks(n);i[a]={};for(let[r,l]of Object.entries(o)){i[a][r]={};for(let[c,d]of Object.entries(l)){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[a][r][c]=this._compileToFunction(u,!0)}}}return i}static _extractBlock(t,e,s="default",i="all",a){let n=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,o=t,r=!1;for(let l of t.matchAll(n))if((l[2]??"default")===s){o=l[3]??"",r=!0;break}if(!r){let l=/<base\b/.test(t);if(!(s==="default"&&!l))return""}if(e){if(e==="all")return o;let l=Array.isArray(e)?e:[e],c=[];for(let p of l){let u=new RegExp(`([ \\t]*)<${p}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${p}>`,"gi");for(let m of o.matchAll(u)){let b=m[2];if(a){let C=/lang="([^"]*)"/i,k=b?.match(C);if(((k?k[1]:void 0)||"default")!==a)continue}c.push({start:m.index,content:m[0],innerContent:m[3]??""})}}c.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(C=>C.trim().length>0);if(m.length===0)return"";let
|
|
3
|
-
`).trim()},"processResult");return i==="all"?
|
|
4
|
-
`):
|
|
5
|
-
`)}return
|
|
6
|
-
`).map((u,m)=>m===0?u:
|
|
7
|
-
`);o=o.replace(`__IMPORT_${r}__`,p)}return o}};var _=class{static{h(this,"TemplateManager")}_map=new Map;_engine=S;_watcher=[];_supportedExtensions=new Set([".html",".ts"]);_path;_isWatchEnabled;constructor(t){let{path:e,enableWatch:s=!1}=t;this._path=e,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(t.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let t=0;t<this._path.length;t++){let e=this._path[t];if(!(0,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 s=this._path[e],i=(0,H.watch)(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=(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),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 a=this._path[i],o=(0,y.readdirSync)(a,"utf8").filter(r=>this._isValidFile(r));for(let r of o){let l=(0,f.join)(a,r),c=this._getExtension(r),d=this._getKey(r);if(c===".html")t.set(d,(0,y.readFileSync)(l,"utf8"));else if(c===".ts"){let p=P.getFileSync(l,!1);p?.template!==void 0&&(t.set(d,p.template),e.push(p))}}}let s=new Map;for(let[i,a]of t.entries())this._compile(i,a,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=(0,f.join)(s,t),a=this._getExtension(t),n=this._getKey(t);if(a==".html"){let o=(0,y.readFileSync)(i,"utf8");this._compile(n,o)}else if(a==".ts"){let o=P.getFileSync(i,!1);o?.template!==void 0&&(this._compile(n,o.template),o.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 s=(0,f.extname)(t).toLowerCase();if(s){let n=(0,f.join)(e,t);if((0,y.existsSync)(n)&&(0,y.statSync)(n).isFile()){if(s===".html")return(0,y.readFileSync)(n,"utf8");if(s===".ts")try{return P.getFileSync(n,!1)?.template??null}catch{return null}}continue}let i=(0,f.join)(e,`${t}.ts`);if((0,y.existsSync)(i)&&(0,y.statSync)(i).isFile())try{return P.getFileSync(i,!1)?.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,s,i,a){let n=this._map.get(t),o=n||{},r=!1,l=S.processImportBlocks(e,d=>a&&a.has(d)?a.get(d):this._readTemplateFile(d),0,i),c=S._processBaseBlocks(l);(s===void 0||s?.media===!1||n?.media===void 0)&&(o.media=S.compileMedia(l,c),r=!0),(s===void 0||s?.message===!1||n?.message===void 0)&&(o.message=S.compileMessages(l,c),r=!0),(s===void 0||s?.keyboard===!1||n?.keyboard===void 0)&&(o.keyboard=S.compileKeyboards(l,c),r=!0),(s===void 0||s?.description===!1||n?.description===void 0)&&(o.description=S.compileDescription(l,c),r=!0),r&&this._map.set(t,o)}getMedia(t,e="default",s="default",i){let n=this._map.get(t)?.media?.[e],o=n?.[s]||n?.default;try{if(!o)throw new Error("Media function not found, please check your template");return o(i)}catch{return{}}}getMessage(t,e="default",s="default",i){try{let n=this._map.get(t)?.message?.[e],o=n?.[s]||n?.default;if(!o)throw"";return o(i)}catch{return""}}getDescription(t,e="default",s="default",i="default",a){try{let o=this._map.get(t)?.description?.[e]?.[i],r=o?.[s]||o?.default;if(!r)throw"";return r(a)}catch{return""}}getDescriptionLanguage(t,e="default",s="default"){try{let a=this._map.get(t)?.description?.[e]?.[s];return a?Object.keys(a):[]}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",a){try{let o=this._map.get(t)?.keyboard?.[e],r=o?.[s]?.[i]||o?.default?.[i];if(!r)throw[];return r(a)}catch{return[]}}async write(t,e){if(this._getExtension(t)!=".html")return null;for(let s=0;s<this._path.length;s++){let i=(0,f.join)(this._path[s],t);if((0,y.existsSync)(i))return(0,y.writeFileSync)(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()}};var F=require("grammy");var $=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 X.LoggingPretty:t.log?t.log:void 0,this.cacheSession=t.cacheSession||new w("memory","session"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new _({path:[(0,O.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()),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)}`)}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})`:""}`)}createBot(t){return new F.Bot(t)}createCtx(t){return new I({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 e=(0,F.webhookCallback)(this.bot,"bun");this.handlerBotUpdate=e;let s=new URL(t).pathname;(0,z.serve)({fetch(n){let{pathname:o}=new URL(n.url);if(n.method=="POST"&&o==s)return e(n);if(n.method=="GET"&&o=="/"){let r=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:r}),{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,F.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,O.parse)(e).name}pageSorts(t,e){let s=t.data.name,i=t.prototype,a="Payload",n="Command",o="Caption",r="Free",l=e.routeDynamic,c=e.routeDynamicSpesific,d=h(m=>m.charAt(0).toUpperCase()+m.slice(1),"upFirst"),p=h(m=>m.replace(a,"").replace(n,"").replace(o,"").replace(r,""),"getPureRouteName"),u=h((m,b)=>i[`methodSession${d(m)}`]?.(b),"methodSession");e.all[s]=t;for(let m=0;m<e.lenListRouteStaticSession;m++){let b=e.listRouteStaticSession[m],C=e.routeStatic[b],k=e.routeStaticIntent[b],x=e.routeStaticSession[b],v={name:s,routeName:b},W=C||k;if(W!==void 0){let tt=b.includes(n)?`/${s}`:s;W[i.intent(tt,b.startsWith("callback"))]=v}x!==void 0&&(x[u(b,s)]=v),b.toLowerCase().endsWith("free")&&c[p(b)].push(v)}i.free&&l.push(s)}async executeSyncBlocksDescription(t){let e=new Map,s=t.routeStatic.textCommand;for(let[,i]of Object.entries(s)){let a=i.name,n=this.templateManager.getDescriptionScopes(a);for(let o of n){e.has(o)||e.set(o,new Set);let r=this.templateManager.getDescriptionLanguage(a,"default",o);for(let l of r)e.get(o).add(l)}}for(let[i,a]of e)for(let n of a){let o=[];for(let[,c]of Object.entries(s)){let d=c.name,p=this.templateManager.getDescription(d,"default",n,i);p&&o.push({command:d,description:p})}if(o.length===0)continue;let r={type:i},l=n==="default"?void 0:n;try{let c=await this.bot.api.getMyCommands({scope:r,language_code:l}),d=JSON.stringify(c.map(u=>({command:u.command,description:u.description})).sort((u,m)=>u.command.localeCompare(m.command))),p=JSON.stringify(o.sort((u,m)=>u.command.localeCompare(m.command)));d!==p&&(await this.bot.api.setMyCommands(o,{scope:r,language_code:l}),this.log?.info?.(`Synced descriptions for scope: ${i},${l?` lang: ${l},`:""} total (${o.length})`))}catch(c){this.log?.error?.(`Failed to sync descriptions for scope: ${i},${l?` lang: ${l},`:""} error: ${String(c)}`)}}}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((o,r)=>Object.fromEntries(o.map(l=>[l,r()])),"makeObject"),a=h(()=>[],"initDynamicSpesific"),n={all:{},routeDynamic:[],routeDynamicSpesific:{text:a(),photo:a(),video:a(),audio:a(),document:a(),animation:a(),voice:a(),videoNote:a(),sticker:a(),location:a(),contact:a()},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 P.getFileManySync(void 0,!0).forEach(({path:o,page:r})=>{this.pageBuildData(r,o),this.pageSorts(r,n)}),this.log?.info?.(`Finish load pages with total (${Object.keys(n.all).length})`),n}async pageRoutes(t,e){let s,i;if(s===void 0){let n=t.callbackData,o=t.msgText,r=t.msgCaption,l=this.pages.routeStatic;for(let c=0;c<this.pages.lenListRouteStatic;c++){let d=this.pages.listRouteStatic[c];if(d.startsWith(e)&&(i=l[d][n||o||r]),i)break}i!==void 0&&(s=this.pages.all[i.name])}if(s===void 0){let n=await t.sessionGet();if(n){let o=n.method,r=this.pages.routeStaticSession;for(let l=0;l<this.pages.lenListRouteStaticSession;l++){let c=this.pages.listRouteStaticSession[l];if(c.startsWith(e)&&(i=r[c][o]),i)break}i!==void 0&&(s=this.pages.all[i.name])}}if(s===void 0){let n=t.callbackDataIntent,o=t.msgTextIntent,r=t.msgCaptionIntent,l=this.pages.routeStaticIntent;for(let c=0;c<this.pages.lenListRouteStaticIntent;c++){let d=this.pages.listRouteStaticIntent[c];if(d.startsWith(e)&&(i=l[d][n||o||r]),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 a=this.pages.routeDynamicSpesific[e]||[];for(let n=0;n<a.length;n++){let o=a[n];if(o===void 0)continue;let r=this.pages.all[o.name];if(r===void 0||!r.prototype[o.routeName])continue;let c=await new r(t)[o.routeName]?.();if(c!==null)return c}for(let n=0;n<this.pages.routeDynamic.length;n++){let o=this.pages.routeDynamic[n];if(o===void 0)continue;let r=this.pages.all[o];if(r===void 0||!r.prototype.free)continue;let c=await new r(t).free?.();if(c!==null)return c}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))}};var Y=require("bun");var V=class g{constructor(t,e){this.path=t;this.argv=e;if(!Y.isMainThread)throw new Error("Is not main thread");this.sub=new Worker(t,{argv:e}),this.id=this.sub.threadId,this.sub.onmessage=async({data:s})=>{let{id:i,method:a,params:n,result:o}=s;if(a!==void 0){let r=this[a];if(typeof r!="function")throw new Error(`Method ${a} not found`);let l=await r.apply(this,n);this.send({id:i,result:l})}else if(o!==void 0){let r=this.map.get(i);r&&(r?.(o),this.map.delete(i))}}}static{h(this,"ThreadMain")}map=new Map;sub;id;createId(){return Math.random()}send(t){this.sub.postMessage(t)}async sendRequest(t,e,s=!0){let i=this.createId();return s?new Promise(a=>{this.map.set(i,a),this.send({id:i,method:t,params:e})}):this.send({id:i,method:t,params:e})}kill(){this.sub.terminate()}async clone(t){return await new Promise(e=>{setInterval(()=>{this.id&&e(this.id)},100)}),new g(this.path,t)}};var B=class{static{h(this,"ThreadExport")}static init(t){let{CSub:e,CMain:s=V,path:i,wrap:a}=t,n=`for-${i}`;if(process.argv[2]===n)return new e,{};let o,r=new Proxy({},{get(d,p){return p==="sendRequest"?(u,m,b=!0)=>{if(!o)throw new Error(`Thread at ${i} not launched yet.`);return o.sendRequest(u,m,b)}:(...u)=>{if(!o)throw new Error(`Thread at ${i} not launched yet.`);return o.sendRequest(p,u)}}});return{...a?a(r):{},launch:h((d=[])=>(o=new s(i,[n,...d]),o),"launch")}}};var N=class{static{h(this,"ThreadMainPool")}thread={};threadCount=0;constructor(t){t.forEach(async e=>{let s=await e;this.thread[s.id]=s,this.threadCount+=1})}add(t){this.thread[t.id]=t,this.threadCount+=1}getInstance(t){return this.thread[t]}killAll(){return Object.values(this.thread).map(({id:t})=>this.kill(t))}kill(t){let e=this.thread[t];return e?.kill(),delete this.thread[t],this.threadCount-=1,e?.id}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)}};var Z=require("bun");var E=class{static{h(this,"ThreadSub")}map=new Map;argv=process.argv;id=process.pid;threadIsMain=Z.isMainThread;constructor(){if(this.threadIsMain)throw new Error("Is not sub thread");self.onmessage=async({data:t})=>{let{id:e,method:s,params:i,result:a}=t;if(s!==void 0)try{let n=this[s];if(typeof n!="function")throw new Error(`Method ${s} not found`);let o=await n.apply(this,i);this.send({id:e,result:o})}catch(n){this.send({id:e,error:n})}else if(a!==void 0){let n=this.map.get(e);n&&(n?.(a),this.map.delete(e))}}}createId(){return Math.random()}send(t){self.postMessage(t)}async sendRequest(t,e,s=!0){let i=this.createId();return s?new Promise(a=>{this.map.set(i,a),this.send({id:i,method:t,params:e})}):this.send({id:i,method:t,params:e})}kill(){self.terminate()}};var K=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`
|
|
1
|
+
"use strict";var nt=Object.create;var _=Object.defineProperty;var ot=Object.getOwnPropertyDescriptor;var at=Object.getOwnPropertyNames;var rt=Object.getPrototypeOf,ct=Object.prototype.hasOwnProperty;var h=(g,t)=>_(g,"name",{value:t,configurable:!0});var lt=(g,t)=>{for(var e in t)_(g,e,{get:t[e],enumerable:!0})},G=(g,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of at(t))!ct.call(g,i)&&i!==e&&_(g,i,{get:()=>t[i],enumerable:!(s=ot(t,i))||s.enumerable});return g};var E=(g,t,e)=>(e=g!=null?nt(rt(g)):{},G(t||!g||!g.__esModule?_(e,"default",{value:g,enumerable:!0}):e,g)),dt=g=>G(_({},"__esModule",{value:!0}),g);var ut={};lt(ut,{CacheExternal:()=>F,ComponentKeyboard:()=>q,Ctx:()=>V,DataKeyboard:()=>Q,Gramstax:()=>K,LoggingUtils:()=>A,TemplateEngine:()=>S,TemplateManager:()=>R,ThreadExport:()=>L,ThreadMain:()=>O,ThreadMainPool:()=>W,ThreadSub:()=>j,log:()=>pt});module.exports=dt(ut);var H=E(require("logging-pretty"),1);var A=class extends H.default{static{h(this,"LoggingUtils")}constructor(t){super(t)}errorMake(t,e,s){this.error(`[${e?.name||e}:${s}] ${String(t)}`)}},pt=new A;var z=require("keyv"),X=E(require("@keyv/redis"),1);var F=class extends z.Keyv{constructor(e="memory",s,i,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:s,ttl:i});this.url=e}static{h(this,"CacheExternal")}};var Y=require("timers/promises"),w=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,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(0,Y.setTimeout)(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 w.InlineKeyboard,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 w.InlineKeyboard,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 w.Keyboard,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 w.Keyboard,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)}};var B=require("path");var $=require("path"),I=require("fs");var P=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(0,$.join)(process.cwd(),"src","pages")}static getFileSync(t,e=0){t||(t=this.getFilePath());let s=require(t);return this._getFile(s,t,e)}static async getFile(t,e=0){t||(t=this.getFilePath());let s=await import(`${t}?t=${Date.now()}`);return this._getFile(s,t,e)}static getFileManySync(t,e=0){if(t||(t=this.getFilePath()),!(0,I.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,I.readdirSync)(t).map(i=>{let o=(0,$.join)(t,i);return{path:o,page:this.getFileSync(o,e)}})}static clearCacheRequire(t){if(t||(t=this.getFilePath()),!(0,I.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,I.readdirSync)(t).forEach(s=>{let i=(0,$.join)(t,s);delete require.cache[require.resolve(i)]}),!0}};var tt=require("logging-pretty");var f=require("path"),b=require("fs"),Z=require("chokidar");var S=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 y=m[2];if(o){let C=/lang="([^"]*)"/i,x=y?.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(C=>C.trim().length>0);if(m.length===0)return"";let y=m.reduce((C,x)=>{let T=x.match(/^([ \t]*)/),v=T?T[1].length:0;return v<C?v:C},1/0);return u.map(C=>C.length>=y?C.slice(y):C.trimStart()).join(`
|
|
3
|
+
`).trim()},"processResult");return i==="all"?l.map(u=>d(u.content)).join(`
|
|
4
|
+
`):l.map(u=>d(u.innerContent)).join(`
|
|
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
|
+
`).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=S;_watcher=[];_pageManager=P;_supportedExtensions=new Set([".html",".ts"]);_path;_isWatchEnabled;constructor(t){let{path:e,enableWatch:s=!1}=t;this._path=e,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(t.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let t=0;t<this._path.length;t++){let e=this._path[t];if(!(0,b.existsSync)(e))throw new Error(`Template base path is not exists: ${e}`);if(!(0,b.statSync)(e).isDirectory())throw new Error(`Template base path is not a directory: ${e}`)}return!0}catch(t){throw new Error(`Failed to validate Template base path: ${String(t)}`)}}_initializeWatcher(t){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let e=0;e<this._path.length;e++){let s=this._path[e],i=(0,Z.watch)(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=(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),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=(0,b.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,b.readFileSync)(c,"utf8"));else if(l===".ts"){let p=P.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=(0,f.join)(s,t),o=this._getExtension(t),a=this._getKey(t);if(o==".html"){let n=(0,b.readFileSync)(i,"utf8");this._compile(a,n)}else if(o==".ts"){let n=P.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(0,f.extname)(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let s=(0,f.extname)(t).toLowerCase();if(s){let a=(0,f.join)(e,t);if((0,b.existsSync)(a)&&(0,b.statSync)(a).isFile()){if(s===".html")return(0,b.readFileSync)(a,"utf8");if(s===".ts")try{return P.getFileSync(a)?.template??null}catch{return null}}continue}let i=(0,f.join)(e,`${t}.ts`);if((0,b.existsSync)(i)&&(0,b.statSync)(i).isFile())try{return P.getFileSync(i)?.template??null}catch{}let o=(0,f.join)(e,`${t}.html`);if((0,b.existsSync)(o)&&(0,b.statSync)(o).isFile())return(0,b.readFileSync)(o,"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=S.processImportBlocks(e,d=>o&&o.has(d)?o.get(d):this._readTemplateFile(d),0,i),l=S._processBaseBlocks(c);(s===void 0||s?.media===!1||a?.media===void 0)&&(n.media=S.compileMedia(c,l),r=!0),(s===void 0||s?.message===!1||a?.message===void 0)&&(n.message=S.compileMessages(c,l),r=!0),(s===void 0||s?.keyboard===!1||a?.keyboard===void 0)&&(n.keyboard=S.compileKeyboards(c,l),r=!0),(s===void 0||s?.description===!1||a?.description===void 0)&&(n.description=S.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=(0,f.join)(this._path[s],t);if((0,b.existsSync)(i))return(0,b.writeFileSync)(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()}};var D=require("grammy");var 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 tt.LoggingPretty:t.log?t.log:void 0,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,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 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"),s=(0,D.webhookCallback)(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=(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 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,y)=>i[`methodSession${d(m)}`]?.(y),"methodSession");e.all[s]=t;for(let m=0;m<e.lenListRouteStaticSession;m++){let y=e.listRouteStaticSession[m];if(typeof i[y]!="function")continue;let C=e.routeStatic[y],x=e.routeStaticIntent[y],T=e.routeStaticSession[y],v={name:s,routeName:y},J=C||x;if(J!==void 0){let et=y.includes(a),st=y.includes("callback"),it=y.startsWith("text"),M;if(et){let U=t.data.textCommand||t.data.name;M=U?`/${U}`:void 0}else st?M=t.data.name:it?M=t.data.text||t.data.name:M=t.data.name;M&&(J[M]=v)}T!==void 0&&(T[u(y,s)]=v),y.toLowerCase().endsWith("free")&&l[p(y)].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 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 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))}};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 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 L=class{static{h(this,"ThreadExport")}static init(t){let{CSub:e,CMain:s=O,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,y=!0)=>{if(!n)throw new Error(`Thread at ${i} not launched yet.`);return n.sendRequest(u,m,y)}:(...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 W=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)}};var k=require("worker_threads");var j=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: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){k.parentPort.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 q=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 Q=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}};0&&(module.exports={CacheExternal,ComponentKeyboard,Ctx,DataKeyboard,Gramstax,LoggingUtils,TemplateEngine,TemplateManager,ThreadExport,ThreadMain,ThreadMainPool,ThreadSub,log});
|
package/dist/src/index.d.cts
CHANGED
|
@@ -5,6 +5,7 @@ import { Context, Keyboard, InlineKeyboard, Bot, BotError } from 'grammy';
|
|
|
5
5
|
import * as _grammyjs_types from '@grammyjs/types';
|
|
6
6
|
import { FSWatcher } from 'chokidar';
|
|
7
7
|
import { UserFromGetMe } from 'grammy/types';
|
|
8
|
+
import { Worker } from 'node:worker_threads';
|
|
8
9
|
|
|
9
10
|
declare class LoggingUtils extends LoggingPretty {
|
|
10
11
|
constructor(options?: ConstructorParameters<typeof LoggingPretty>[0]);
|
|
@@ -20,6 +21,18 @@ declare class CacheExternal extends Keyv {
|
|
|
20
21
|
constructor(url?: string, namespace?: string, ttl?: number, more?: IMore);
|
|
21
22
|
}
|
|
22
23
|
|
|
24
|
+
declare class PageManager {
|
|
25
|
+
static _getFile(mod: Record<any, any>, path: string, positionModule?: number): typeof Ctx;
|
|
26
|
+
static getFilePath(): string;
|
|
27
|
+
static getFileSync(path?: string, positionModule?: number): typeof Ctx;
|
|
28
|
+
static getFile(path?: string, positionModule?: number): Promise<typeof Ctx>;
|
|
29
|
+
static getFileManySync(path?: string, positionModule?: number): {
|
|
30
|
+
path: string;
|
|
31
|
+
page: typeof Ctx;
|
|
32
|
+
}[];
|
|
33
|
+
static clearCacheRequire(path?: string): boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
23
36
|
type IMediaBlock = {
|
|
24
37
|
type: `photo` | `video` | `audio` | `document` | `animation` | `voice` | `video_note` | `sticker` | `location` | `contact`;
|
|
25
38
|
src?: string;
|
|
@@ -122,6 +135,7 @@ declare class TemplateManager {
|
|
|
122
135
|
_map: Map<string, ICompiledTemplate>;
|
|
123
136
|
_engine: typeof TemplateEngine;
|
|
124
137
|
_watcher: FSWatcher[];
|
|
138
|
+
_pageManager: typeof PageManager;
|
|
125
139
|
_supportedExtensions: Set<string>;
|
|
126
140
|
readonly _path: ITemplateOptions[`path`];
|
|
127
141
|
readonly _isWatchEnabled: ITemplateOptions[`enableWatch`];
|
|
@@ -228,22 +242,25 @@ type IOptEditMedia2 = Parameters<Context[`editMessageMedia`]>[1]
|
|
|
228
242
|
type ITypeReplyAction = Parameters<Context[`replyWithChatAction`]>[0]
|
|
229
243
|
type IData = Record<string, any>
|
|
230
244
|
|
|
231
|
-
type IPageData = {
|
|
245
|
+
type IPageData<T extends any[] = any[]> = {
|
|
232
246
|
name: string;
|
|
233
|
-
callbackData: (...args:
|
|
247
|
+
callbackData: (...args: T) => string;
|
|
248
|
+
text: string;
|
|
249
|
+
textCommand: string;
|
|
250
|
+
_positionPayloadText: number;
|
|
234
251
|
};
|
|
235
252
|
type ITemp = {
|
|
236
253
|
session: {
|
|
237
254
|
method?: string;
|
|
238
255
|
params?: any;
|
|
239
256
|
};
|
|
240
|
-
data: Partial<IPageData
|
|
257
|
+
data: Partial<IPageData<any>>;
|
|
241
258
|
[key: string]: any;
|
|
242
259
|
};
|
|
243
260
|
declare class Ctx {
|
|
244
261
|
static template?: string;
|
|
245
|
-
static data: IPageData
|
|
246
|
-
data: IPageData
|
|
262
|
+
static data: IPageData<any>;
|
|
263
|
+
data: IPageData<any>;
|
|
247
264
|
get userIsPremium(): boolean;
|
|
248
265
|
get userIsBot(): boolean;
|
|
249
266
|
get userId(): number;
|
|
@@ -254,16 +271,15 @@ declare class Ctx {
|
|
|
254
271
|
get userLanguage(): string;
|
|
255
272
|
set userLanguage(v: string);
|
|
256
273
|
get msgText(): string;
|
|
257
|
-
get msgTextIntent(): string;
|
|
258
274
|
get msgTextPayloads(): string[];
|
|
259
275
|
get msgTextPayload(): string;
|
|
260
276
|
get msgCaption(): string;
|
|
261
|
-
get
|
|
277
|
+
get msgCaptionPayloads(): string[];
|
|
278
|
+
get msgCaptionPayload(): string;
|
|
262
279
|
get msgPhoto(): _grammyjs_types.PhotoSize[] | undefined;
|
|
263
280
|
get msgVideo(): _grammyjs_types.Video | undefined;
|
|
264
281
|
get msgAudio(): _grammyjs_types.Audio | undefined;
|
|
265
282
|
get callbackData(): string;
|
|
266
|
-
get callbackDataIntent(): string;
|
|
267
283
|
get callbackDataPayloads(): string[];
|
|
268
284
|
get callbackDataPayload(): string;
|
|
269
285
|
get callbackDataParts(): string[];
|
|
@@ -320,14 +336,17 @@ declare class Ctx {
|
|
|
320
336
|
[moreRoot: string]: any;
|
|
321
337
|
} | null>;
|
|
322
338
|
sessionClear(): Promise<boolean | null>;
|
|
323
|
-
static buildData<C extends (
|
|
324
|
-
|
|
325
|
-
callbackData:
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
339
|
+
static buildData<C extends (...args: any[]) => any>(callback: C): IPageData<Parameters<C>>;
|
|
340
|
+
static buildData<C extends (...args: any[]) => any>(options: {
|
|
341
|
+
callbackData: C;
|
|
342
|
+
text?: string;
|
|
343
|
+
textCommand?: string;
|
|
344
|
+
}): IPageData<Parameters<C>>;
|
|
345
|
+
static buildData(options: {
|
|
346
|
+
text?: string;
|
|
347
|
+
textCommand?: string;
|
|
348
|
+
}): IPageData<[]>;
|
|
349
|
+
static buildData(): IPageData<[]>;
|
|
331
350
|
inlineKeyboard(callback: (kb: IInlineKb, arr: string[]) => IInlineKb, params?: {
|
|
332
351
|
baseId?: string;
|
|
333
352
|
data?: IData;
|
|
@@ -338,6 +357,9 @@ declare class Ctx {
|
|
|
338
357
|
data?: IData;
|
|
339
358
|
cache?: boolean;
|
|
340
359
|
}): IBottomKb;
|
|
360
|
+
seperatorTag(mtd?: `space` | `colon`): " " | ":";
|
|
361
|
+
payloads(str: string | undefined, mtd: Parameters<typeof this.seperatorTag>[0], positionStart?: number): string[];
|
|
362
|
+
intent(str: string | undefined, mtd: Parameters<typeof this.seperatorTag>[0], positionEnd?: number): string;
|
|
341
363
|
transition?(...args: any): Promise<void>;
|
|
342
364
|
internal?(...args: any): Promise<void>;
|
|
343
365
|
callback?(): Promise<void>;
|
|
@@ -521,7 +543,6 @@ declare class Ctx {
|
|
|
521
543
|
sessionToStickerFree(paramsAdd?: any, name?: string): Promise<boolean | null>;
|
|
522
544
|
sessionToLocationFree(paramsAdd?: any, name?: string): Promise<boolean | null>;
|
|
523
545
|
sessionToContactFree(paramsAdd?: any, name?: string): Promise<boolean | null>;
|
|
524
|
-
intent(str?: string, isCallbackData?: boolean): string;
|
|
525
546
|
methodSession(prefix: string, name: string | undefined): string;
|
|
526
547
|
methodSessionCallback(name?: string): string;
|
|
527
548
|
methodSessionCallbackPayload(name?: string): string;
|
|
@@ -588,6 +609,8 @@ declare class Gramstax<ICtx extends Ctx = Ctx> {
|
|
|
588
609
|
templateManager?: TemplateManager;
|
|
589
610
|
});
|
|
590
611
|
onCatch(error: BotError<Context>): void;
|
|
612
|
+
hookBeforeStart(): void;
|
|
613
|
+
hookAfterStart(): void;
|
|
591
614
|
onStart(botInfo: UserFromGetMe, method: `polling` | `webhook` | `serverless`, data: string | null): Promise<void>;
|
|
592
615
|
createBot(token: string): Bot<Context, grammy.Api<grammy.RawApi>>;
|
|
593
616
|
createCtx(ct: Context): ICtx;
|
|
@@ -1011,25 +1034,25 @@ declare class ThreadMain {
|
|
|
1011
1034
|
argv?: any[] | undefined;
|
|
1012
1035
|
map: Map<number, (value: any) => any>;
|
|
1013
1036
|
sub: Worker;
|
|
1014
|
-
|
|
1037
|
+
pid: number;
|
|
1038
|
+
subId: number;
|
|
1015
1039
|
constructor(path: string, argv?: any[] | undefined);
|
|
1016
1040
|
createId(): number;
|
|
1017
1041
|
send(payload: any): void;
|
|
1018
1042
|
sendRequest(method: string, params: any, wait?: boolean): Promise<any>;
|
|
1019
1043
|
kill(): void;
|
|
1020
|
-
clone(argv?: any[]): Promise<ThreadMain>;
|
|
1021
1044
|
}
|
|
1022
1045
|
|
|
1023
1046
|
declare class ThreadSub {
|
|
1024
1047
|
map: Map<number, (value: any) => any>;
|
|
1025
1048
|
argv: string[];
|
|
1026
1049
|
id: number;
|
|
1050
|
+
pid: number;
|
|
1027
1051
|
threadIsMain: boolean;
|
|
1028
1052
|
constructor();
|
|
1029
1053
|
createId(): number;
|
|
1030
1054
|
send(payload: any): void;
|
|
1031
1055
|
sendRequest(method: string, params: any, wait?: boolean): Promise<unknown>;
|
|
1032
|
-
kill(): void;
|
|
1033
1056
|
}
|
|
1034
1057
|
|
|
1035
1058
|
type ThreadExportOptions<TSub extends ThreadSub, TMain extends ThreadMain, TWrap> = {
|
|
@@ -1049,11 +1072,11 @@ declare class ThreadMainPool {
|
|
|
1049
1072
|
threadCount: number;
|
|
1050
1073
|
constructor(instance: (Promise<ThreadMain> | ThreadMain)[]);
|
|
1051
1074
|
add(instance: ThreadMain): void;
|
|
1052
|
-
getInstance(
|
|
1075
|
+
getInstance(subId: number): ThreadMain | undefined;
|
|
1053
1076
|
killAll(): (number | undefined)[];
|
|
1054
|
-
kill(
|
|
1077
|
+
kill(subId: number): number | undefined;
|
|
1055
1078
|
broadcastRequest(method: string, params: any): Promise<any[]>;
|
|
1056
|
-
sendRequest(
|
|
1079
|
+
sendRequest(subId: number, method: string, params: any, wait?: boolean): Promise<any>;
|
|
1057
1080
|
}
|
|
1058
1081
|
|
|
1059
1082
|
declare class DataKeyboard {
|
package/dist/src/index.d.ts
CHANGED
|
@@ -5,6 +5,7 @@ import { Context, Keyboard, InlineKeyboard, Bot, BotError } from 'grammy';
|
|
|
5
5
|
import * as _grammyjs_types from '@grammyjs/types';
|
|
6
6
|
import { FSWatcher } from 'chokidar';
|
|
7
7
|
import { UserFromGetMe } from 'grammy/types';
|
|
8
|
+
import { Worker } from 'node:worker_threads';
|
|
8
9
|
|
|
9
10
|
declare class LoggingUtils extends LoggingPretty {
|
|
10
11
|
constructor(options?: ConstructorParameters<typeof LoggingPretty>[0]);
|
|
@@ -20,6 +21,18 @@ declare class CacheExternal extends Keyv {
|
|
|
20
21
|
constructor(url?: string, namespace?: string, ttl?: number, more?: IMore);
|
|
21
22
|
}
|
|
22
23
|
|
|
24
|
+
declare class PageManager {
|
|
25
|
+
static _getFile(mod: Record<any, any>, path: string, positionModule?: number): typeof Ctx;
|
|
26
|
+
static getFilePath(): string;
|
|
27
|
+
static getFileSync(path?: string, positionModule?: number): typeof Ctx;
|
|
28
|
+
static getFile(path?: string, positionModule?: number): Promise<typeof Ctx>;
|
|
29
|
+
static getFileManySync(path?: string, positionModule?: number): {
|
|
30
|
+
path: string;
|
|
31
|
+
page: typeof Ctx;
|
|
32
|
+
}[];
|
|
33
|
+
static clearCacheRequire(path?: string): boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
23
36
|
type IMediaBlock = {
|
|
24
37
|
type: `photo` | `video` | `audio` | `document` | `animation` | `voice` | `video_note` | `sticker` | `location` | `contact`;
|
|
25
38
|
src?: string;
|
|
@@ -122,6 +135,7 @@ declare class TemplateManager {
|
|
|
122
135
|
_map: Map<string, ICompiledTemplate>;
|
|
123
136
|
_engine: typeof TemplateEngine;
|
|
124
137
|
_watcher: FSWatcher[];
|
|
138
|
+
_pageManager: typeof PageManager;
|
|
125
139
|
_supportedExtensions: Set<string>;
|
|
126
140
|
readonly _path: ITemplateOptions[`path`];
|
|
127
141
|
readonly _isWatchEnabled: ITemplateOptions[`enableWatch`];
|
|
@@ -228,22 +242,25 @@ type IOptEditMedia2 = Parameters<Context[`editMessageMedia`]>[1]
|
|
|
228
242
|
type ITypeReplyAction = Parameters<Context[`replyWithChatAction`]>[0]
|
|
229
243
|
type IData = Record<string, any>
|
|
230
244
|
|
|
231
|
-
type IPageData = {
|
|
245
|
+
type IPageData<T extends any[] = any[]> = {
|
|
232
246
|
name: string;
|
|
233
|
-
callbackData: (...args:
|
|
247
|
+
callbackData: (...args: T) => string;
|
|
248
|
+
text: string;
|
|
249
|
+
textCommand: string;
|
|
250
|
+
_positionPayloadText: number;
|
|
234
251
|
};
|
|
235
252
|
type ITemp = {
|
|
236
253
|
session: {
|
|
237
254
|
method?: string;
|
|
238
255
|
params?: any;
|
|
239
256
|
};
|
|
240
|
-
data: Partial<IPageData
|
|
257
|
+
data: Partial<IPageData<any>>;
|
|
241
258
|
[key: string]: any;
|
|
242
259
|
};
|
|
243
260
|
declare class Ctx {
|
|
244
261
|
static template?: string;
|
|
245
|
-
static data: IPageData
|
|
246
|
-
data: IPageData
|
|
262
|
+
static data: IPageData<any>;
|
|
263
|
+
data: IPageData<any>;
|
|
247
264
|
get userIsPremium(): boolean;
|
|
248
265
|
get userIsBot(): boolean;
|
|
249
266
|
get userId(): number;
|
|
@@ -254,16 +271,15 @@ declare class Ctx {
|
|
|
254
271
|
get userLanguage(): string;
|
|
255
272
|
set userLanguage(v: string);
|
|
256
273
|
get msgText(): string;
|
|
257
|
-
get msgTextIntent(): string;
|
|
258
274
|
get msgTextPayloads(): string[];
|
|
259
275
|
get msgTextPayload(): string;
|
|
260
276
|
get msgCaption(): string;
|
|
261
|
-
get
|
|
277
|
+
get msgCaptionPayloads(): string[];
|
|
278
|
+
get msgCaptionPayload(): string;
|
|
262
279
|
get msgPhoto(): _grammyjs_types.PhotoSize[] | undefined;
|
|
263
280
|
get msgVideo(): _grammyjs_types.Video | undefined;
|
|
264
281
|
get msgAudio(): _grammyjs_types.Audio | undefined;
|
|
265
282
|
get callbackData(): string;
|
|
266
|
-
get callbackDataIntent(): string;
|
|
267
283
|
get callbackDataPayloads(): string[];
|
|
268
284
|
get callbackDataPayload(): string;
|
|
269
285
|
get callbackDataParts(): string[];
|
|
@@ -320,14 +336,17 @@ declare class Ctx {
|
|
|
320
336
|
[moreRoot: string]: any;
|
|
321
337
|
} | null>;
|
|
322
338
|
sessionClear(): Promise<boolean | null>;
|
|
323
|
-
static buildData<C extends (
|
|
324
|
-
|
|
325
|
-
callbackData:
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
339
|
+
static buildData<C extends (...args: any[]) => any>(callback: C): IPageData<Parameters<C>>;
|
|
340
|
+
static buildData<C extends (...args: any[]) => any>(options: {
|
|
341
|
+
callbackData: C;
|
|
342
|
+
text?: string;
|
|
343
|
+
textCommand?: string;
|
|
344
|
+
}): IPageData<Parameters<C>>;
|
|
345
|
+
static buildData(options: {
|
|
346
|
+
text?: string;
|
|
347
|
+
textCommand?: string;
|
|
348
|
+
}): IPageData<[]>;
|
|
349
|
+
static buildData(): IPageData<[]>;
|
|
331
350
|
inlineKeyboard(callback: (kb: IInlineKb, arr: string[]) => IInlineKb, params?: {
|
|
332
351
|
baseId?: string;
|
|
333
352
|
data?: IData;
|
|
@@ -338,6 +357,9 @@ declare class Ctx {
|
|
|
338
357
|
data?: IData;
|
|
339
358
|
cache?: boolean;
|
|
340
359
|
}): IBottomKb;
|
|
360
|
+
seperatorTag(mtd?: `space` | `colon`): " " | ":";
|
|
361
|
+
payloads(str: string | undefined, mtd: Parameters<typeof this.seperatorTag>[0], positionStart?: number): string[];
|
|
362
|
+
intent(str: string | undefined, mtd: Parameters<typeof this.seperatorTag>[0], positionEnd?: number): string;
|
|
341
363
|
transition?(...args: any): Promise<void>;
|
|
342
364
|
internal?(...args: any): Promise<void>;
|
|
343
365
|
callback?(): Promise<void>;
|
|
@@ -521,7 +543,6 @@ declare class Ctx {
|
|
|
521
543
|
sessionToStickerFree(paramsAdd?: any, name?: string): Promise<boolean | null>;
|
|
522
544
|
sessionToLocationFree(paramsAdd?: any, name?: string): Promise<boolean | null>;
|
|
523
545
|
sessionToContactFree(paramsAdd?: any, name?: string): Promise<boolean | null>;
|
|
524
|
-
intent(str?: string, isCallbackData?: boolean): string;
|
|
525
546
|
methodSession(prefix: string, name: string | undefined): string;
|
|
526
547
|
methodSessionCallback(name?: string): string;
|
|
527
548
|
methodSessionCallbackPayload(name?: string): string;
|
|
@@ -588,6 +609,8 @@ declare class Gramstax<ICtx extends Ctx = Ctx> {
|
|
|
588
609
|
templateManager?: TemplateManager;
|
|
589
610
|
});
|
|
590
611
|
onCatch(error: BotError<Context>): void;
|
|
612
|
+
hookBeforeStart(): void;
|
|
613
|
+
hookAfterStart(): void;
|
|
591
614
|
onStart(botInfo: UserFromGetMe, method: `polling` | `webhook` | `serverless`, data: string | null): Promise<void>;
|
|
592
615
|
createBot(token: string): Bot<Context, grammy.Api<grammy.RawApi>>;
|
|
593
616
|
createCtx(ct: Context): ICtx;
|
|
@@ -1011,25 +1034,25 @@ declare class ThreadMain {
|
|
|
1011
1034
|
argv?: any[] | undefined;
|
|
1012
1035
|
map: Map<number, (value: any) => any>;
|
|
1013
1036
|
sub: Worker;
|
|
1014
|
-
|
|
1037
|
+
pid: number;
|
|
1038
|
+
subId: number;
|
|
1015
1039
|
constructor(path: string, argv?: any[] | undefined);
|
|
1016
1040
|
createId(): number;
|
|
1017
1041
|
send(payload: any): void;
|
|
1018
1042
|
sendRequest(method: string, params: any, wait?: boolean): Promise<any>;
|
|
1019
1043
|
kill(): void;
|
|
1020
|
-
clone(argv?: any[]): Promise<ThreadMain>;
|
|
1021
1044
|
}
|
|
1022
1045
|
|
|
1023
1046
|
declare class ThreadSub {
|
|
1024
1047
|
map: Map<number, (value: any) => any>;
|
|
1025
1048
|
argv: string[];
|
|
1026
1049
|
id: number;
|
|
1050
|
+
pid: number;
|
|
1027
1051
|
threadIsMain: boolean;
|
|
1028
1052
|
constructor();
|
|
1029
1053
|
createId(): number;
|
|
1030
1054
|
send(payload: any): void;
|
|
1031
1055
|
sendRequest(method: string, params: any, wait?: boolean): Promise<unknown>;
|
|
1032
|
-
kill(): void;
|
|
1033
1056
|
}
|
|
1034
1057
|
|
|
1035
1058
|
type ThreadExportOptions<TSub extends ThreadSub, TMain extends ThreadMain, TWrap> = {
|
|
@@ -1049,11 +1072,11 @@ declare class ThreadMainPool {
|
|
|
1049
1072
|
threadCount: number;
|
|
1050
1073
|
constructor(instance: (Promise<ThreadMain> | ThreadMain)[]);
|
|
1051
1074
|
add(instance: ThreadMain): void;
|
|
1052
|
-
getInstance(
|
|
1075
|
+
getInstance(subId: number): ThreadMain | undefined;
|
|
1053
1076
|
killAll(): (number | undefined)[];
|
|
1054
|
-
kill(
|
|
1077
|
+
kill(subId: number): number | undefined;
|
|
1055
1078
|
broadcastRequest(method: string, params: any): Promise<any[]>;
|
|
1056
|
-
sendRequest(
|
|
1079
|
+
sendRequest(subId: number, method: string, params: any, wait?: boolean): Promise<any>;
|
|
1057
1080
|
}
|
|
1058
1081
|
|
|
1059
1082
|
declare class DataKeyboard {
|
package/dist/src/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var U=Object.defineProperty;var h=(g,t)=>U(g,"name",{value:t,configurable:!0}),O=(g=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(g,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):g)(function(g){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+g+'" is not supported')});import G from"logging-pretty";var V=class extends G{static{h(this,"LoggingUtils")}constructor(t){super(t)}errorMake(t,e,s){this.error(`[${e?.name||e}:${s}] ${String(t)}`)}},ht=new V;import{Keyv as H}from"keyv";import z from"@keyv/redis";var M=class extends H{constructor(e="memory",s,i,a){let n;e.startsWith("redis")&&(n=new z(e)),e==="memory"&&(n=new Map),a?.forceStore&&(n=a.forceStore);super({store:n,namespace:s,ttl:i});this.url=e}static{h(this,"CacheExternal")}};import{setTimeout as X}from"timers/promises";import{InlineKeyboard as A,Keyboard as $}from"grammy";var T=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 msgTextIntent(){return this.msgText&&this.msgText.indexOf(" ")!=-1?this.msgText.split(" ")[0]:""}get msgTextPayloads(){return this.msgText&&this.msgText.indexOf(" ")!=-1?this.msgText.split(" ").slice(1):[]}get msgTextPayload(){return this.msgTextPayloads[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionIntent(){return this.msgCaption&&this.msgCaption.indexOf(" ")!=-1?this.msgCaption.split(" ")[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 callbackDataIntent(){return this.callbackData&&this.callbackData.indexOf(":")!=-1?this.callbackData.split(":")[0]:""}get callbackDataPayloads(){return this.callbackData&&this.callbackData.indexOf(":")!=-1?this.callbackData.split(":").slice(1):[]}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,a,n,o=!1){try{let l=e.map(c=>this.templateManager.getMessage(this.data.name,a,c,i));for(let c=0;c<t.length;c++){let d=t[c],p=l[c];await this.ct.api.sendMessage(d,p,{parse_mode:"HTML",reply_markup:s,...n}),c+1==30&&await X(1200)}}catch(r){if(o)throw r}}async reply(t,e,s,i){let a=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.reply(a,{parse_mode:"HTML",reply_markup:t,...i})}async replyMedia(t,e,s,i,a){let n=this.templateManager.getMedia(this.data.name,i,this.userLanguage,s),o={parse_mode:"HTML",reply_markup:e,...a};if(t=="photo")return await this.ct.replyWithPhoto(n.src,{caption:n.caption,...o});if(t=="video")return await this.ct.replyWithVideo(n.src,{caption:n.caption,...o});if(t=="audio")return await this.ct.replyWithAudio(n.src,{caption:n.caption,...o});if(t=="document")return await this.ct.replyWithDocument(n.src,{caption:n.caption,...o});if(t=="animation")return await this.ct.replyWithAnimation(n.src,{caption:n.caption,...o});if(t=="voice")return await this.ct.replyWithVoice(n.src,o);if(t=="video_note")return await this.ct.replyWithVideoNote(n.src,o);if(t=="sticker")return await this.ct.replyWithSticker(n.src,o);if(t=="location")return await this.ct.replyWithLocation(parseInt(n.latitude),parseInt(n.longitude),o);if(t=="contact")return await this.ct.replyWithContact(n.phone,n.first_name,{vcard:n.vcard,...o})}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,a=!0){try{let n=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.editMessageText(n,{parse_mode:"HTML",reply_markup:t,...i})}catch(n){if(a)await this.reply(t,e,s,i);else throw n}}async editMedia(t,e,s,i,a,n,o=!0){try{let{src:r,caption:l}=this.templateManager.getMedia(this.data.name,i,this.userLanguage,s);return t=="voice"?(await this.delete(),await this.replyVoice(e,s,i,a)):t=="video_note"?(await this.delete(),await this.replyVoice(e,s,i,a)):t=="sticker"?(await this.delete(),await this.replySticker(e,s,i,a)):t=="location"?(await this.delete(),await this.replyLocation(e,s,i,a)):t=="contact"?(await this.delete(),await this.replyContact(e,s,i,a)):await this.ct.editMessageMedia({media:r,caption:l,type:t,parse_mode:"HTML",...a},{reply_markup:e,...n})}catch(r){if(o===!0)await this.reply(e,s,i,n);else throw r}}async editPhoto(t,e,s,i,a){return await this.editMedia("photo",t,e,s,i,a)}async editVideo(t,e,s,i,a){return await this.editMedia("video",t,e,s,i,a)}async editAudio(t,e,s,i,a){return await this.editMedia("audio",t,e,s,i,a)}async editDocument(t,e,s,i,a){return await this.editMedia("document",t,e,s,i,a)}async editAnimation(t,e,s,i,a){return await this.editMedia("animation",t,e,s,i,a)}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},a=await this.cacheSession.set(`${this.userId}`,i);return a&&(this.session=i),a}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){return{name:"",callbackData:t?function(...e){let s=t(...e);return`${this.name}${s==""||s===void 0?"":`:${s}`}`}:function(){return this?.name}}}inlineKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let o=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(o);if(!r){let l=new A,c=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data),d=t(l,c);return this.cacheKeyboard.set(o,d),d}return r}let i=new A,a=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data);return t(i,a)}bottomKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let o=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(o);if(!r){let l=new $,c=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),d=t(l,c);return d.resized(!0),this.cacheKeyboard.set(o,d),d}return r}let i=new $,a=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),n=t(i,a);return n.resized(),n}validateSessionCallback(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionCallback(e)}validateSessionCallbackPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionCallbackPayload(e)}validateSessionText(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionText(e)}validateSessionTextPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionTextPayload(e)}validateSessionTextCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionTextCommand(e)}validateSessionTextCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionTextCommandPayload(e)}validateSessionTextFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionTextFree(e)}validateSessionPhotoCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionPhotoCaption(e)}validateSessionPhotoCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionPhotoCaptionPayload(e)}validateSessionPhotoCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionPhotoCaptionCommand(e)}validateSessionPhotoCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionPhotoCaptionCommandPayload(e)}validateSessionPhotoFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionPhotoFree(e)}validateSessionVideoCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoCaption(e)}validateSessionVideoCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoCaptionPayload(e)}validateSessionVideoCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoCaptionCommand(e)}validateSessionVideoCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoCaptionCommandPayload(e)}validateSessionVideoFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoFree(e)}validateSessionAudioCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAudioCaption(e)}validateSessionAudioCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAudioCaptionPayload(e)}validateSessionAudioCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAudioCaptionCommand(e)}validateSessionAudioCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAudioCaptionCommandPayload(e)}validateSessionAudioFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAudioFree(e)}validateSessionDocumentCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionDocumentCaption(e)}validateSessionDocumentCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionDocumentCaptionPayload(e)}validateSessionDocumentCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionDocumentCaptionCommand(e)}validateSessionDocumentCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionDocumentCaptionCommandPayload(e)}validateSessionDocumentFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionDocumentFree(e)}validateSessionAnimationCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAnimationCaption(e)}validateSessionAnimationCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAnimationCaptionPayload(e)}validateSessionAnimationCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAnimationCaptionCommand(e)}validateSessionAnimationCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAnimationCaptionCommandPayload(e)}validateSessionAnimationFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionAnimationFree(e)}validateSessionVoiceCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVoiceCaption(e)}validateSessionVoiceCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVoiceCaptionPayload(e)}validateSessionVoiceCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVoiceCaptionCommand(e)}validateSessionVoiceCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVoiceCaptionCommandPayload(e)}validateSessionVoiceFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVoiceFree(e)}validateSessionVideoNoteCaption(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoNoteCaption(e)}validateSessionVideoNoteCaptionPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoNoteCaptionPayload(e)}validateSessionVideoNoteCaptionCommand(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoNoteCaptionCommand(e)}validateSessionVideoNoteCaptionCommandPayload(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoNoteCaptionCommandPayload(e)}validateSessionVideoNoteFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionVideoNoteFree(e)}validateSessionStickerFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionStickerFree(e)}validateSessionLocationFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===this.methodSessionLocationFree(e)}validateSessionContactFree(t,e){return t===void 0&&(t=this.session.method),t===void 0?!1:t===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)}intent(t,e=!0){t||(t=e?this.data.callbackData():this.data.name);let s=e?":":" ";return t.indexOf(s)!=-1?t.split(s)[0]:t}methodSession(t,e){return`${t}-${e||this.data.name}`}methodSessionCallback(t){return this.methodSession("1",t)}methodSessionCallbackPayload(t){return this.methodSession("2",t)}methodSessionText(t){return this.methodSession("3",t)}methodSessionTextPayload(t){return this.methodSession("4",t)}methodSessionTextCommand(t){return this.methodSession("5",t)}methodSessionTextCommandPayload(t){return this.methodSession("6",t)}methodSessionTextFree(t){return this.methodSession("7",t)}methodSessionPhotoCaption(t){return this.methodSession("8",t)}methodSessionPhotoCaptionPayload(t){return this.methodSession("9",t)}methodSessionPhotoCaptionCommand(t){return this.methodSession("10",t)}methodSessionPhotoCaptionCommandPayload(t){return this.methodSession("11",t)}methodSessionPhotoFree(t){return this.methodSession("12",t)}methodSessionVideoCaption(t){return this.methodSession("13",t)}methodSessionVideoCaptionPayload(t){return this.methodSession("14",t)}methodSessionVideoCaptionCommand(t){return this.methodSession("15",t)}methodSessionVideoCaptionCommandPayload(t){return this.methodSession("16",t)}methodSessionVideoFree(t){return this.methodSession("17",t)}methodSessionAudioCaption(t){return this.methodSession("18",t)}methodSessionAudioCaptionPayload(t){return this.methodSession("19",t)}methodSessionAudioCaptionCommand(t){return this.methodSession("20",t)}methodSessionAudioCaptionCommandPayload(t){return this.methodSession("21",t)}methodSessionAudioFree(t){return this.methodSession("22",t)}methodSessionDocumentCaption(t){return this.methodSession("23",t)}methodSessionDocumentCaptionPayload(t){return this.methodSession("24",t)}methodSessionDocumentCaptionCommand(t){return this.methodSession("25",t)}methodSessionDocumentCaptionCommandPayload(t){return this.methodSession("26",t)}methodSessionDocumentFree(t){return this.methodSession("27",t)}methodSessionAnimationCaption(t){return this.methodSession("28",t)}methodSessionAnimationCaptionPayload(t){return this.methodSession("29",t)}methodSessionAnimationCaptionCommand(t){return this.methodSession("30",t)}methodSessionAnimationCaptionCommandPayload(t){return this.methodSession("31",t)}methodSessionAnimationFree(t){return this.methodSession("32",t)}methodSessionVoiceCaption(t){return this.methodSession("33",t)}methodSessionVoiceCaptionPayload(t){return this.methodSession("34",t)}methodSessionVoiceCaptionCommand(t){return this.methodSession("35",t)}methodSessionVoiceCaptionCommandPayload(t){return this.methodSession("36",t)}methodSessionVoiceFree(t){return this.methodSession("37",t)}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{serve as it}from"bun";import{join as nt,parse as ot}from"path";import{join as B}from"path";import{existsSync as Y,readdirSync as Z}from"fs";var C=class{static{h(this,"PageManager")}static _getFile(t,e,s=!0,i=0){let n=Object.values(t)[i];if(n===void 0)throw new Error(`File ${e} must have export (not default) class page`);return s===!0&&(n.template=void 0),n}static getFilePath(){return B(process.cwd(),"src","pages")}static getFileSync(t,e=!0,s=0){t||(t=this.getFilePath());let i=O(t);return this._getFile(i,t,e,s)}static async getFile(t,e=!0,s=0){t||(t=this.getFilePath());let i=await import(`${t}?t=${Date.now()}`);return this._getFile(i,t,e,s)}static getFileManySync(t,e=!0,s=0){if(t||(t=this.getFilePath()),!Y(t))throw new Error(`Directory ${t} is not found, please make it manually`);return Z(t).map(a=>{let n=B(t,a);return{path:n,page:this.getFileSync(n,e,s)}})}};import{LoggingPretty as at}from"logging-pretty";import{basename as R,join as k,extname as N}from"path";import{readdirSync as tt,readFileSync as w,existsSync as x,statSync as I,writeFileSync as et}from"fs";import{watch as st}from"chokidar";var f=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 a=i[2]??"default",o=(i[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[a]=o}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,a)=>{if(!i)return"";let n="",o=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,l;for(;(l=o.exec(a))!==null;){let d=(l[1]||"").split(",").map(u=>u.trim()),p=(l[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(u=>{n+=`case "${u}": `}),n+=`return \`${p}\`; `}let c=r.exec(a);if(c){let d=(c[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");n+=`default: return \`${d}\`; `}else n+="default: return ''; ";return`\${(() => { switch((data && data["${i}"])) { ${n} } })()}`})}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,a)=>{let n={},o=/(\w+)="([^"]*)"/g;if(i)for(let p of i.matchAll(o))n[p[1]]=p[2];let r=n.src;if(!r)return"";let l=n.join??"\\n",c=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");c=c.replace(/\{\{([\w.]+)\}\}/g,(p,u)=>u==="e"||u.startsWith("e.")?`\${${u}}`:u==="i"?"${i}":p);let d=l.replace(/"/g,'\\"');return`\${(data && data["${r}"] || []).map((e, i) => \`${c}\`).join("${d}")}`})}static _processMediaBlocks(t){let e=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let i of t.matchAll(e)){let a=i[1],n=i[2],o={},r=/(\w+)="([^"]*)"/g;if(a)for(let u of a.matchAll(r))o[u[1]]=u[2];let l=o.lang||"default",c=o.type,d=n.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),p={type:c};o.src&&(p.src=o.src),d&&c!=="video_note"&&c!=="sticker"&&(p.caption=d),c==="location"&&(o.latitude&&(p.latitude=o.latitude),o.longitude&&(p.longitude=o.longitude),d&&(p.caption=d)),c==="contact"&&(o.phone&&(p.phone=o.phone),o.first_name&&(p.first_name=o.first_name),o.last_name&&(p.last_name=o.last_name),o.vcard&&(p.vcard=o.vcard),d&&(p.caption=d)),s[l]=p}return s}static _processMessageBlocks(t){let e=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,i,a]of t.matchAll(e)){let n={},o=/(\w+)="([^"]*)"/g;if(i)for(let c of i.matchAll(o))n[c[1]]=c[2];let r=n.lang||"default",l=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=l}return s}static _processDescriptionBlocks(t){let e=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,i,a]of t.matchAll(e)){let n={},o=/(\w+)="([^"]*)"/g;if(i)for(let d of i.matchAll(o))n[d[1]]=d[2];let r=n.lang||"default",l=n.scope||"default",c=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][l]=c}return s}static _processKeyboardBlocks(t){let e=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,i,a]of t.matchAll(e)){let n={},o=/(\w+)="([^"]*)"/g;if(i)for(let d of i.matchAll(o))n[d[1]]=d[2];let r=n.lang||"default",l=n.type==="bottom"?"bottom":"inline",c=a.trim();s[r]||(s[r]={}),s[r][l]=c}return s}static _compileToFunction(t,e){let s;e?s=t.map(n=>`\`${n}\``).join(","):s=`\`${t}\``;let i=s;if(i=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(i))),e){let a=`return [${i}]`;return new Function("data",a)}else{let a=`return ${i}`;return new Function("data",a)}}static compileMedia(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[a,n]of Object.entries(s)){let o=this._processMediaBlocks(n);i[a]={};for(let[r,l]of Object.entries(o)){let c={};for(let[d,p]of Object.entries(l)){if(d==="type"||typeof p!="string")continue;let u=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(p)))));c[d]=this._compileToFunction(u,!1)}i[a][r]=d=>{let p={...l};for(let[u,m]of Object.entries(c))p[u]=m(d);return p}}}return i}static compileMessages(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[a,n]of Object.entries(s)){let o=this._processMessageBlocks(n);i[a]={};for(let[r,l]of Object.entries(o)){let c=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(l)))));i[a][r]=this._compileToFunction(c,!1)}}return i}static compileDescription(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[a,n]of Object.entries(s)){let o=this._processDescriptionBlocks(n);i[a]={};for(let[r,l]of Object.entries(o))for(let[c,d]of Object.entries(l)){i[a][c]||(i[a][c]={});let p=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));i[a][c][r]=this._compileToFunction(p,!1)}}return i}static compileKeyboards(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[a,n]of Object.entries(s)){let o=this._processKeyboardBlocks(n);i[a]={};for(let[r,l]of Object.entries(o)){i[a][r]={};for(let[c,d]of Object.entries(l)){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[a][r][c]=this._compileToFunction(u,!0)}}}return i}static _extractBlock(t,e,s="default",i="all",a){let n=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,o=t,r=!1;for(let l of t.matchAll(n))if((l[2]??"default")===s){o=l[3]??"",r=!0;break}if(!r){let l=/<base\b/.test(t);if(!(s==="default"&&!l))return""}if(e){if(e==="all")return o;let l=Array.isArray(e)?e:[e],c=[];for(let p of l){let u=new RegExp(`([ \\t]*)<${p}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${p}>`,"gi");for(let m of o.matchAll(u)){let y=m[2];if(a){let b=/lang="([^"]*)"/i,P=y?.match(b);if(((P?P[1]:void 0)||"default")!==a)continue}c.push({start:m.index,content:m[0],innerContent:m[3]??""})}}c.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
|
|
3
|
-
`).trim()},"processResult");return i==="all"?
|
|
4
|
-
`):
|
|
5
|
-
`)}return
|
|
6
|
-
`).map((u,m)=>m===0?u:
|
|
7
|
-
`);o=o.replace(`__IMPORT_${r}__`,p)}return o}};var _=class{static{h(this,"TemplateManager")}_map=new Map;_engine=f;_watcher=[];_supportedExtensions=new Set([".html",".ts"]);_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(!x(e))throw new Error(`Template base path is not exists: ${e}`);if(!I(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=st(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=R(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileAdd(t){let e=R(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileDelete(t){let e=R(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 a=this._path[i],o=tt(a,"utf8").filter(r=>this._isValidFile(r));for(let r of o){let l=k(a,r),c=this._getExtension(r),d=this._getKey(r);if(c===".html")t.set(d,w(l,"utf8"));else if(c===".ts"){let p=C.getFileSync(l,!1);p?.template!==void 0&&(t.set(d,p.template),e.push(p))}}}let s=new Map;for(let[i,a]of t.entries())this._compile(i,a,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),a=this._getExtension(t),n=this._getKey(t);if(a==".html"){let o=w(i,"utf8");this._compile(n,o)}else if(a==".ts"){let o=C.getFileSync(i,!1);o?.template!==void 0&&(this._compile(n,o.template),o.template=void 0)}else throw new Error(`File ${t} is not support`)}}_getExtension(t){return N(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let s=N(t).toLowerCase();if(s){let n=k(e,t);if(x(n)&&I(n).isFile()){if(s===".html")return w(n,"utf8");if(s===".ts")try{return C.getFileSync(n,!1)?.template??null}catch{return null}}continue}let i=k(e,`${t}.ts`);if(x(i)&&I(i).isFile())try{return C.getFileSync(i,!1)?.template??null}catch{}let a=k(e,`${t}.html`);if(x(a)&&I(a).isFile())return w(a,"utf8")}return null}_isValidFile(t){return this._supportedExtensions.has(this._getExtension(t))}_getKey(t){return t.replace(/\.[^/.]+$/,"")}_compile(t,e,s,i,a){let n=this._map.get(t),o=n||{},r=!1,l=f.processImportBlocks(e,d=>a&&a.has(d)?a.get(d):this._readTemplateFile(d),0,i),c=f._processBaseBlocks(l);(s===void 0||s?.media===!1||n?.media===void 0)&&(o.media=f.compileMedia(l,c),r=!0),(s===void 0||s?.message===!1||n?.message===void 0)&&(o.message=f.compileMessages(l,c),r=!0),(s===void 0||s?.keyboard===!1||n?.keyboard===void 0)&&(o.keyboard=f.compileKeyboards(l,c),r=!0),(s===void 0||s?.description===!1||n?.description===void 0)&&(o.description=f.compileDescription(l,c),r=!0),r&&this._map.set(t,o)}getMedia(t,e="default",s="default",i){let n=this._map.get(t)?.media?.[e],o=n?.[s]||n?.default;try{if(!o)throw new Error("Media function not found, please check your template");return o(i)}catch{return{}}}getMessage(t,e="default",s="default",i){try{let n=this._map.get(t)?.message?.[e],o=n?.[s]||n?.default;if(!o)throw"";return o(i)}catch{return""}}getDescription(t,e="default",s="default",i="default",a){try{let o=this._map.get(t)?.description?.[e]?.[i],r=o?.[s]||o?.default;if(!r)throw"";return r(a)}catch{return""}}getDescriptionLanguage(t,e="default",s="default"){try{let a=this._map.get(t)?.description?.[e]?.[s];return a?Object.keys(a):[]}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",a){try{let o=this._map.get(t)?.keyboard?.[e],r=o?.[s]?.[i]||o?.default?.[i];if(!r)throw[];return r(a)}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(x(i))return et(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 rt,webhookCallback as E}from"grammy";var 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 at:t.log?t.log:void 0,this.cacheSession=t.cacheSession||new M("memory","session"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new _({path:[nt(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()),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)}`)}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})`:""}`)}createBot(t){return new rt(t)}createCtx(t){return new T({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 e=E(this.bot,"bun");this.handlerBotUpdate=e;let s=new URL(t).pathname;it({fetch(n){let{pathname:o}=new URL(n.url);if(n.method=="POST"&&o==s)return e(n);if(n.method=="GET"&&o=="/"){let r=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:r}),{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=E(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=ot(e).name}pageSorts(t,e){let s=t.data.name,i=t.prototype,a="Payload",n="Command",o="Caption",r="Free",l=e.routeDynamic,c=e.routeDynamicSpesific,d=h(m=>m.charAt(0).toUpperCase()+m.slice(1),"upFirst"),p=h(m=>m.replace(a,"").replace(n,"").replace(o,"").replace(r,""),"getPureRouteName"),u=h((m,y)=>i[`methodSession${d(m)}`]?.(y),"methodSession");e.all[s]=t;for(let m=0;m<e.lenListRouteStaticSession;m++){let y=e.listRouteStaticSession[m],b=e.routeStatic[y],P=e.routeStaticIntent[y],v=e.routeStaticSession[y],S={name:s,routeName:y},D=b||P;if(D!==void 0){let J=y.includes(n)?`/${s}`:s;D[i.intent(J,y.startsWith("callback"))]=S}v!==void 0&&(v[u(y,s)]=S),y.toLowerCase().endsWith("free")&&c[p(y)].push(S)}i.free&&l.push(s)}async executeSyncBlocksDescription(t){let e=new Map,s=t.routeStatic.textCommand;for(let[,i]of Object.entries(s)){let a=i.name,n=this.templateManager.getDescriptionScopes(a);for(let o of n){e.has(o)||e.set(o,new Set);let r=this.templateManager.getDescriptionLanguage(a,"default",o);for(let l of r)e.get(o).add(l)}}for(let[i,a]of e)for(let n of a){let o=[];for(let[,c]of Object.entries(s)){let d=c.name,p=this.templateManager.getDescription(d,"default",n,i);p&&o.push({command:d,description:p})}if(o.length===0)continue;let r={type:i},l=n==="default"?void 0:n;try{let c=await this.bot.api.getMyCommands({scope:r,language_code:l}),d=JSON.stringify(c.map(u=>({command:u.command,description:u.description})).sort((u,m)=>u.command.localeCompare(m.command))),p=JSON.stringify(o.sort((u,m)=>u.command.localeCompare(m.command)));d!==p&&(await this.bot.api.setMyCommands(o,{scope:r,language_code:l}),this.log?.info?.(`Synced descriptions for scope: ${i},${l?` lang: ${l},`:""} total (${o.length})`))}catch(c){this.log?.error?.(`Failed to sync descriptions for scope: ${i},${l?` lang: ${l},`:""} error: ${String(c)}`)}}}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((o,r)=>Object.fromEntries(o.map(l=>[l,r()])),"makeObject"),a=h(()=>[],"initDynamicSpesific"),n={all:{},routeDynamic:[],routeDynamicSpesific:{text:a(),photo:a(),video:a(),audio:a(),document:a(),animation:a(),voice:a(),videoNote:a(),sticker:a(),location:a(),contact:a()},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 C.getFileManySync(void 0,!0).forEach(({path:o,page:r})=>{this.pageBuildData(r,o),this.pageSorts(r,n)}),this.log?.info?.(`Finish load pages with total (${Object.keys(n.all).length})`),n}async pageRoutes(t,e){let s,i;if(s===void 0){let n=t.callbackData,o=t.msgText,r=t.msgCaption,l=this.pages.routeStatic;for(let c=0;c<this.pages.lenListRouteStatic;c++){let d=this.pages.listRouteStatic[c];if(d.startsWith(e)&&(i=l[d][n||o||r]),i)break}i!==void 0&&(s=this.pages.all[i.name])}if(s===void 0){let n=await t.sessionGet();if(n){let o=n.method,r=this.pages.routeStaticSession;for(let l=0;l<this.pages.lenListRouteStaticSession;l++){let c=this.pages.listRouteStaticSession[l];if(c.startsWith(e)&&(i=r[c][o]),i)break}i!==void 0&&(s=this.pages.all[i.name])}}if(s===void 0){let n=t.callbackDataIntent,o=t.msgTextIntent,r=t.msgCaptionIntent,l=this.pages.routeStaticIntent;for(let c=0;c<this.pages.lenListRouteStaticIntent;c++){let d=this.pages.listRouteStaticIntent[c];if(d.startsWith(e)&&(i=l[d][n||o||r]),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 a=this.pages.routeDynamicSpesific[e]||[];for(let n=0;n<a.length;n++){let o=a[n];if(o===void 0)continue;let r=this.pages.all[o.name];if(r===void 0||!r.prototype[o.routeName])continue;let c=await new r(t)[o.routeName]?.();if(c!==null)return c}for(let n=0;n<this.pages.routeDynamic.length;n++){let o=this.pages.routeDynamic[n];if(o===void 0)continue;let r=this.pages.all[o];if(r===void 0||!r.prototype.free)continue;let c=await new r(t).free?.();if(c!==null)return c}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{isMainThread as ct}from"bun";var F=class g{constructor(t,e){this.path=t;this.argv=e;if(!ct)throw new Error("Is not main thread");this.sub=new Worker(t,{argv:e}),this.id=this.sub.threadId,this.sub.onmessage=async({data:s})=>{let{id:i,method:a,params:n,result:o}=s;if(a!==void 0){let r=this[a];if(typeof r!="function")throw new Error(`Method ${a} not found`);let l=await r.apply(this,n);this.send({id:i,result:l})}else if(o!==void 0){let r=this.map.get(i);r&&(r?.(o),this.map.delete(i))}}}static{h(this,"ThreadMain")}map=new Map;sub;id;createId(){return Math.random()}send(t){this.sub.postMessage(t)}async sendRequest(t,e,s=!0){let i=this.createId();return s?new Promise(a=>{this.map.set(i,a),this.send({id:i,method:t,params:e})}):this.send({id:i,method:t,params:e})}kill(){this.sub.terminate()}async clone(t){return await new Promise(e=>{setInterval(()=>{this.id&&e(this.id)},100)}),new g(this.path,t)}};var L=class{static{h(this,"ThreadExport")}static init(t){let{CSub:e,CMain:s=F,path:i,wrap:a}=t,n=`for-${i}`;if(process.argv[2]===n)return new e,{};let o,r=new Proxy({},{get(d,p){return p==="sendRequest"?(u,m,y=!0)=>{if(!o)throw new Error(`Thread at ${i} not launched yet.`);return o.sendRequest(u,m,y)}:(...u)=>{if(!o)throw new Error(`Thread at ${i} not launched yet.`);return o.sendRequest(p,u)}}});return{...a?a(r):{},launch:h((d=[])=>(o=new s(i,[n,...d]),o),"launch")}}};var W=class{static{h(this,"ThreadMainPool")}thread={};threadCount=0;constructor(t){t.forEach(async e=>{let s=await e;this.thread[s.id]=s,this.threadCount+=1})}add(t){this.thread[t.id]=t,this.threadCount+=1}getInstance(t){return this.thread[t]}killAll(){return Object.values(this.thread).map(({id:t})=>this.kill(t))}kill(t){let e=this.thread[t];return e?.kill(),delete this.thread[t],this.threadCount-=1,e?.id}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{isMainThread as lt}from"bun";var j=class{static{h(this,"ThreadSub")}map=new Map;argv=process.argv;id=process.pid;threadIsMain=lt;constructor(){if(this.threadIsMain)throw new Error("Is not sub thread");self.onmessage=async({data:t})=>{let{id:e,method:s,params:i,result:a}=t;if(s!==void 0)try{let n=this[s];if(typeof n!="function")throw new Error(`Method ${s} not found`);let o=await n.apply(this,i);this.send({id:e,result:o})}catch(n){this.send({id:e,error:n})}else if(a!==void 0){let n=this.map.get(e);n&&(n?.(a),this.map.delete(e))}}}createId(){return Math.random()}send(t){self.postMessage(t)}async sendRequest(t,e,s=!0){let i=this.createId();return s?new Promise(a=>{this.map.set(i,a),this.send({id:i,method:t,params:e})}):this.send({id:i,method:t,params:e})}kill(){self.terminate()}};var Q=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`
|
|
1
|
+
var tt=Object.defineProperty;var h=(y,t)=>tt(y,"name",{value:t,configurable:!0}),M=(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 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)}`)}},ft=new D;import{Keyv as st}from"keyv";import it from"@keyv/redis";var w=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 I=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 ct,parse as lt}from"path";import{join as O}from"path";import{existsSync as K,readdirSync as L}from"fs";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 s=M(t);return this._getFile(s,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 M.cache[M.resolve(i)]}),!0}};import{LoggingPretty as dt}from"logging-pretty";import{basename as A,join as x,extname as W}from"path";import{readdirSync as ot,readFileSync as _,existsSync as T,statSync as F,writeFileSync as at}from"fs";import{watch as rt}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,P=g?.match(b);if(((P?P[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,P)=>{let v=P.match(/^([ \t]*)/),S=v?v[1].length:0;return S<b?S:b},1/0);return u.map(b=>b.length>=g?b.slice(g):b.trimStart()).join(`
|
|
3
|
+
`).trim()},"processResult");return i==="all"?l.map(u=>d(u.content)).join(`
|
|
4
|
+
`):l.map(u=>d(u.innerContent)).join(`
|
|
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
|
+
`).map((u,m)=>m===0?u:c.indent+u).join(`
|
|
7
|
+
`);n=n.replace(`__IMPORT_${r}__`,p)}return n}};var V=class{static{h(this,"TemplateManager")}_map=new Map;_engine=C;_watcher=[];_pageManager=f;_supportedExtensions=new Set([".html",".ts"]);_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(!F(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=rt(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=ot(o,"utf8").filter(r=>this._isValidFile(r));for(let r of n){let c=x(o,r),l=this._getExtension(r),d=this._getKey(r);if(l===".html")t.set(d,_(c,"utf8"));else if(l===".ts"){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=x(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"){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 a=x(e,t);if(T(a)&&F(a).isFile()){if(s===".html")return _(a,"utf8");if(s===".ts")try{return f.getFileSync(a)?.template??null}catch{return null}}continue}let i=x(e,`${t}.ts`);if(T(i)&&F(i).isFile())try{return f.getFileSync(i)?.template??null}catch{}let o=x(e,`${t}.html`);if(T(o)&&F(o).isFile())return _(o,"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=x(this._path[s],t);if(T(i))return at(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 pt,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 dt:t.log?t.log:void 0,this.cacheSession=t.cacheSession||new w("memory","session"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new V({path:[ct(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 pt(t)}createCtx(t){return new I({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=lt(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],P=e.routeStaticIntent[g],v=e.routeStaticSession[g],S={name:s,routeName:g},$=b||P;if($!==void 0){let X=g.includes(a),Y=g.includes("callback"),Z=g.startsWith("text"),k;if(X){let B=t.data.textCommand||t.data.name;k=B?`/${B}`:void 0}else Y?k=t.data.name:Z?k=t.data.text||t.data.name:k=t.data.name;k&&($[k]=S)}v!==void 0&&(v[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 ut,isMainThread as ht}from"worker_threads";var R=class{constructor(t,e){this.path=t;this.argv=e;if(!ht)throw new Error("Is not main thread");this.sub=new ut(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=R,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 J=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 U,threadId as mt,isMainThread as gt}from"worker_threads";var G=class{static{h(this,"ThreadSub")}map=new Map;argv=process.argv;id=mt;pid=process.pid;threadIsMain=gt;constructor(){if(this.threadIsMain)throw new Error("Is not sub thread");U.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){U.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`
|
|
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{w as CacheExternal,H as ComponentKeyboard,I as Ctx,z as DataKeyboard,q as Gramstax,D as LoggingUtils,C as TemplateEngine,V as TemplateManager,Q as ThreadExport,R as ThreadMain,J as ThreadMainPool,G as ThreadSub,ft as log};
|