gramstax 0.3.2 → 0.3.4
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 +9 -9
- package/dist/src/index.d.cts +3 -3
- package/dist/src/index.d.ts +3 -3
- package/dist/src/index.js +4 -4
- package/package.json +1 -1
package/dist/src/index.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
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
|
|
3
|
-
`).trim()},"processResult");return
|
|
1
|
+
"use strict";var at=Object.create;var _=Object.defineProperty;var rt=Object.getOwnPropertyDescriptor;var ct=Object.getOwnPropertyNames;var lt=Object.getPrototypeOf,dt=Object.prototype.hasOwnProperty;var h=(g,t)=>_(g,"name",{value:t,configurable:!0});var pt=(g,t)=>{for(var e in t)_(g,e,{get:t[e],enumerable:!0})},U=(g,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of ct(t))!dt.call(g,s)&&s!==e&&_(g,s,{get:()=>t[s],enumerable:!(i=rt(t,s))||i.enumerable});return g};var G=(g,t,e)=>(e=g!=null?at(lt(g)):{},U(t||!g||!g.__esModule?_(e,"default",{value:g,enumerable:!0}):e,g)),ut=g=>U(_({},"__esModule",{value:!0}),g);var gt={};pt(gt,{CacheExternal:()=>F,ComponentKeyboard:()=>W,Ctx:()=>V,DataKeyboard:()=>q,Gramstax:()=>E,LoggingUtils:()=>A,TemplateEngine:()=>P,TemplateManager:()=>R,ThreadExport:()=>K,ThreadMain:()=>O,ThreadMainPool:()=>L,ThreadSub:()=>j,log:()=>ht});module.exports=ut(gt);var H=require("logging-pretty");var A=class extends H.LoggingPretty{static{h(this,"LoggingUtils")}constructor(t){super(t)}errorMake(t,e,i){this.error(`[${e?.name||e}:${i}] ${String(t)}`)}},ht=new A;var z=require("keyv"),X=G(require("@keyv/redis"),1);var F=class extends z.Keyv{constructor(e="memory",i,s,o){let a;e.startsWith("redis")&&(a=new X.default(e)),e==="memory"&&(a=new Map),o?.forceStore&&(a=o.forceStore);super({store:a,namespace:i,ttl:s});this.url=e}static{h(this,"CacheExternal")}};var Y=require("timers/promises"),M=require("grammy");var V=class{static{h(this,"Ctx")}static template;static data;data=this.constructor.data;get userIsPremium(){return this.ct.from?.is_premium??!1}get userIsBot(){return this.ct.from?.is_bot??!1}get userId(){return this.ct.from?.id}get userName(){return this.ct.from?.username}get userFullName(){return`${this.ct.from?.first_name} ${this.ct.from?.last_name||""}`}get userFirstName(){return this.ct.from?.first_name}get userLastName(){return this.ct.from?.last_name}get userLanguage(){return this.ct.from?.language_code}set userLanguage(t){this.ct.from.language_code=t}get msgText(){return this.ct.message?.text}get msgTextPayloads(){return this.payloads(this.msgText,"space",this.data._positionPayloadText)}get msgTextPayload(){return this.msgTextPayloads[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionPayloads(){return this.payloads(this.msgCaption,"space")}get msgCaptionPayload(){return this.msgCaptionPayloads[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataPayloads(){return this.payloads(this.callbackData,"colon")}get callbackDataPayload(){return this.callbackDataPayloads?.[0]}get callbackDataParts(){return this.callbackDataPayload&&this.callbackDataPayload.indexOf("+")!=-1?this.callbackDataPayload.split("+"):[]}set session(t){this.temp.session=t}get session(){return this.temp.session}ct;cacheSession;cacheKeyboard;templateManager;temp;constructor(t){this.ct=t.ct,this.cacheSession=t.cacheSession,this.cacheKeyboard=t.cacheKeyboard,this.templateManager=t.templateManager,this.temp=t.temp}async broadcast(t,e,i,s,o,a,n=!1){try{let c=e.map(l=>this.templateManager.getMessage(this.data.name,o,l,s));for(let l=0;l<t.length;l++){let d=t[l],p=c[l];await this.ct.api.sendMessage(d,p,{parse_mode:"HTML",reply_markup:i,...a}),l+1==30&&await(0,Y.setTimeout)(1200)}}catch(r){if(n)throw r}}async reply(t,e,i,s){let o=this.templateManager.getMessage(this.data.name,i,this.userLanguage,e);return await this.ct.reply(o,{parse_mode:"HTML",reply_markup:t,...s})}async replyMedia(t,e,i,s,o){let a=this.templateManager.getMedia(this.data.name,s,this.userLanguage,i),n={parse_mode:"HTML",reply_markup:e,...o};if(t=="photo")return await this.ct.replyWithPhoto(a.src,{caption:a.caption,...n});if(t=="video")return await this.ct.replyWithVideo(a.src,{caption:a.caption,...n});if(t=="audio")return await this.ct.replyWithAudio(a.src,{caption:a.caption,...n});if(t=="document")return await this.ct.replyWithDocument(a.src,{caption:a.caption,...n});if(t=="animation")return await this.ct.replyWithAnimation(a.src,{caption:a.caption,...n});if(t=="voice")return await this.ct.replyWithVoice(a.src,n);if(t=="video_note")return await this.ct.replyWithVideoNote(a.src,n);if(t=="sticker")return await this.ct.replyWithSticker(a.src,n);if(t=="location")return await this.ct.replyWithLocation(parseInt(a.latitude),parseInt(a.longitude),n);if(t=="contact")return await this.ct.replyWithContact(a.phone,a.first_name,{vcard:a.vcard,...n})}async replyPhoto(t,e,i,s){return this.replyMedia("photo",t,e,i,s)}async replyVideo(t,e,i,s){return this.replyMedia("video",t,e,i,s)}async replyAudio(t,e,i,s){return this.replyMedia("audio",t,e,i,s)}async replyDocument(t,e,i,s){return this.replyMedia("document",t,e,i,s)}async replyAnimation(t,e,i,s){return this.replyMedia("animation",t,e,i,s)}async replyVoice(t,e,i,s){return this.replyMedia("voice",t,e,i,s)}async replyVideoNote(t,e,i,s){return this.replyMedia("video_note",t,e,i,s)}async replySticker(t,e,i,s){return this.replyMedia("sticker",t,e,i,s)}async replyLocation(t,e,i,s){return this.replyMedia("location",t,e,i,s)}async replyContact(t,e,i,s){return this.replyMedia("contact",t,e,i,s)}async replyAction(t){return await this.ct.replyWithChatAction(t)}async edit(t,e,i,s,o=!0){try{let a=this.templateManager.getMessage(this.data.name,i,this.userLanguage,e);return await this.ct.editMessageText(a,{parse_mode:"HTML",reply_markup:t,...s})}catch(a){if(o)await this.reply(t,e,i,s);else throw a}}async editMedia(t,e,i,s,o,a,n=!0){try{let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,s,this.userLanguage,i);return t=="voice"?(await this.delete(),await this.replyVoice(e,i,s,o)):t=="video_note"?(await this.delete(),await this.replyVoice(e,i,s,o)):t=="sticker"?(await this.delete(),await this.replySticker(e,i,s,o)):t=="location"?(await this.delete(),await this.replyLocation(e,i,s,o)):t=="contact"?(await this.delete(),await this.replyContact(e,i,s,o)):await this.ct.editMessageMedia({media:r,caption:c,type:t,parse_mode:"HTML",...o},{reply_markup:e,...a})}catch(r){if(n===!0)await this.reply(e,i,s,a);else throw r}}async editPhoto(t,e,i,s,o){return await this.editMedia("photo",t,e,i,s,o)}async editVideo(t,e,i,s,o){return await this.editMedia("video",t,e,i,s,o)}async editAudio(t,e,i,s,o){return await this.editMedia("audio",t,e,i,s,o)}async editDocument(t,e,i,s,o){return await this.editMedia("document",t,e,i,s,o)}async editAnimation(t,e,i,s,o){return await this.editMedia("animation",t,e,i,s,o)}async editVoice(t,e,i,s){return await this.editMedia("voice",t,e,i,s)}async editVideoNote(t,e,i,s){return await this.editMedia("video_note",t,e,i,s)}async editSticker(t,e,i,s){return await this.editMedia("sticker",t,e,i,s)}async editLocation(t,e,i,s){return await this.editMedia("location",t,e,i,s)}async editContact(t,e,i,s){return await this.editMedia("contact",t,e,i,s)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(t){try{return await this.ct.answerCallbackQuery(t)}catch{return null}}async sessionSet(t,e,i){try{let s={method:t,params:e,...i},o=await this.cacheSession.set(`${this.userId}`,s);return o&&(this.session=s),o}catch{return null}}async sessionGet(){try{let t=await this.cacheSession.get(`${this.userId}`);return t&&(this.session=t),t||null}catch{return null}}async sessionClear(){try{let t=await this.cacheSession.delete(`${this.userId}`);return t&&(this.session={}),t}catch{return null}}static buildData(t){let i=typeof t=="function"?{callbackData:t}:t||{},s=i.callbackData;return{name:"",text:i.text,textCommand:i.textCommand,_positionPayloadText:i.text?i.text.split(this.prototype.seperatorTag("space")).length:void 0,callbackData:s?function(...a){let n=s(...a);return`${this.name}${n==""||n===void 0?"":`:${n}`}`}:function(){return this?.name}}}inlineKeyboard(t,e){let i=this.data.name;if(e?.cache===!0){let n=`${i}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(n);if(!r){let c=new M.InlineKeyboard,l=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"inline",e?.data),d=t(c,l);return this.cacheKeyboard.set(n,d),d}return r}let s=new M.InlineKeyboard,o=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"inline",e?.data);return t(s,o)}bottomKeyboard(t,e){let i=this.data.name;if(e?.cache===!0){let n=`${i}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(n);if(!r){let c=new M.Keyboard,l=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"bottom",e?.data),d=t(c,l);return d.resized(!0),this.cacheKeyboard.set(n,d),d}return r}let s=new M.Keyboard,o=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"bottom",e?.data),a=t(s,o);return a.resized(),a}seperatorTag(t="space"){return t=="space"?" ":":"}payloads(t="",e,i=1){let s=this.seperatorTag(e);return t?t.split(s).slice(i):[]}intent(t="",e,i=1){let s=this.seperatorTag(e);if(!t)return"";let o=t.split(s);return i==1?o[0]:o.slice(0,i).join(s)}validateSessionCallback(t,e){return(t??this.session.method)===this.methodSessionCallback(e)}validateSessionCallbackPayload(t,e){return(t??this.session.method)===this.methodSessionCallbackPayload(e)}validateSessionText(t,e){return(t??this.session.method)===this.methodSessionText(e)}validateSessionTextPayload(t,e){return(t??this.session.method)===this.methodSessionTextPayload(e)}validateSessionTextCommand(t,e){return(t??this.session.method)===this.methodSessionTextCommand(e)}validateSessionTextCommandPayload(t,e){return(t??this.session.method)===this.methodSessionTextCommandPayload(e)}validateSessionTextFree(t,e){return(t??this.session.method)===this.methodSessionTextFree(e)}validateSessionPhotoCaption(t,e){return(t??this.session.method)===this.methodSessionPhotoCaption(e)}validateSessionPhotoCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionPayload(e)}validateSessionPhotoCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionCommand(e)}validateSessionPhotoCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionCommandPayload(e)}validateSessionPhotoFree(t,e){return(t??this.session.method)===this.methodSessionPhotoFree(e)}validateSessionVideoCaption(t,e){return(t??this.session.method)===this.methodSessionVideoCaption(e)}validateSessionVideoCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionPayload(e)}validateSessionVideoCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionCommand(e)}validateSessionVideoCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionCommandPayload(e)}validateSessionVideoFree(t,e){return(t??this.session.method)===this.methodSessionVideoFree(e)}validateSessionAudioCaption(t,e){return(t??this.session.method)===this.methodSessionAudioCaption(e)}validateSessionAudioCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionPayload(e)}validateSessionAudioCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionCommand(e)}validateSessionAudioCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionCommandPayload(e)}validateSessionAudioFree(t,e){return(t??this.session.method)===this.methodSessionAudioFree(e)}validateSessionDocumentCaption(t,e){return(t??this.session.method)===this.methodSessionDocumentCaption(e)}validateSessionDocumentCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionPayload(e)}validateSessionDocumentCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionCommand(e)}validateSessionDocumentCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionCommandPayload(e)}validateSessionDocumentFree(t,e){return(t??this.session.method)===this.methodSessionDocumentFree(e)}validateSessionAnimationCaption(t,e){return(t??this.session.method)===this.methodSessionAnimationCaption(e)}validateSessionAnimationCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionPayload(e)}validateSessionAnimationCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionCommand(e)}validateSessionAnimationCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionCommandPayload(e)}validateSessionAnimationFree(t,e){return(t??this.session.method)===this.methodSessionAnimationFree(e)}validateSessionVoiceCaption(t,e){return(t??this.session.method)===this.methodSessionVoiceCaption(e)}validateSessionVoiceCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionPayload(e)}validateSessionVoiceCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionCommand(e)}validateSessionVoiceCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionCommandPayload(e)}validateSessionVoiceFree(t,e){return(t??this.session.method)===this.methodSessionVoiceFree(e)}validateSessionVideoNoteCaption(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaption(e)}validateSessionVideoNoteCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionPayload(e)}validateSessionVideoNoteCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionCommand(e)}validateSessionVideoNoteCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionCommandPayload(e)}validateSessionVideoNoteFree(t,e){return(t??this.session.method)===this.methodSessionVideoNoteFree(e)}validateSessionStickerFree(t,e){return(t??this.session.method)===this.methodSessionStickerFree(e)}validateSessionLocationFree(t,e){return(t??this.session.method)===this.methodSessionLocationFree(e)}validateSessionContactFree(t,e){return(t??this.session.method)===this.methodSessionContactFree(e)}sessionCallback(t,e){return this.sessionSet(this.methodSessionCallback(e),t)}sessionCallbackPayload(t,e){return this.sessionSet(this.methodSessionCallbackPayload(e),t)}sessionText(t,e){return this.sessionSet(this.methodSessionText(e),t)}sessionTextPayload(t,e){return this.sessionSet(this.methodSessionTextPayload(e),t)}sessionTextCommand(t,e){return this.sessionSet(this.methodSessionTextCommand(e),t)}sessionTextCommandPayload(t,e){return this.sessionSet(this.methodSessionTextCommandPayload(e),t)}sessionTextFree(t,e){return this.sessionSet(this.methodSessionTextFree(e),t)}sessionPhotoCaption(t,e){return this.sessionSet(this.methodSessionPhotoCaption(e),t)}sessionPhotoCaptionPayload(t,e){return this.sessionSet(this.methodSessionPhotoCaptionPayload(e),t)}sessionPhotoCaptionCommand(t,e){return this.sessionSet(this.methodSessionPhotoCaptionCommand(e),t)}sessionPhotoCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionPhotoCaptionCommandPayload(e),t)}sessionPhotoFree(t,e){return this.sessionSet(this.methodSessionPhotoFree(e),t)}sessionVideoCaption(t,e){return this.sessionSet(this.methodSessionVideoCaption(e),t)}sessionVideoCaptionPayload(t,e){return this.sessionSet(this.methodSessionVideoCaptionPayload(e),t)}sessionVideoCaptionCommand(t,e){return this.sessionSet(this.methodSessionVideoCaptionCommand(e),t)}sessionVideoCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVideoCaptionCommandPayload(e),t)}sessionVideoFree(t,e){return this.sessionSet(this.methodSessionVideoFree(e),t)}sessionAudioCaption(t,e){return this.sessionSet(this.methodSessionAudioCaption(e),t)}sessionAudioCaptionPayload(t,e){return this.sessionSet(this.methodSessionAudioCaptionPayload(e),t)}sessionAudioCaptionCommand(t,e){return this.sessionSet(this.methodSessionAudioCaptionCommand(e),t)}sessionAudioCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionAudioCaptionCommandPayload(e),t)}sessionAudioFree(t,e){return this.sessionSet(this.methodSessionAudioFree(e),t)}sessionDocumentCaption(t,e){return this.sessionSet(this.methodSessionDocumentCaption(e),t)}sessionDocumentCaptionPayload(t,e){return this.sessionSet(this.methodSessionDocumentCaptionPayload(e),t)}sessionDocumentCaptionCommand(t,e){return this.sessionSet(this.methodSessionDocumentCaptionCommand(e),t)}sessionDocumentCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionDocumentCaptionCommandPayload(e),t)}sessionDocumentFree(t,e){return this.sessionSet(this.methodSessionDocumentFree(e),t)}sessionAnimationCaption(t,e){return this.sessionSet(this.methodSessionAnimationCaption(e),t)}sessionAnimationCaptionPayload(t,e){return this.sessionSet(this.methodSessionAnimationCaptionPayload(e),t)}sessionAnimationCaptionCommand(t,e){return this.sessionSet(this.methodSessionAnimationCaptionCommand(e),t)}sessionAnimationCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionAnimationCaptionCommandPayload(e),t)}sessionAnimationFree(t,e){return this.sessionSet(this.methodSessionAnimationFree(e),t)}sessionVoiceCaption(t,e){return this.sessionSet(this.methodSessionVoiceCaption(e),t)}sessionVoiceCaptionPayload(t,e){return this.sessionSet(this.methodSessionVoiceCaptionPayload(e),t)}sessionVoiceCaptionCommand(t,e){return this.sessionSet(this.methodSessionVoiceCaptionCommand(e),t)}sessionVoiceCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVoiceCaptionCommandPayload(e),t)}sessionVoiceFree(t,e){return this.sessionSet(this.methodSessionVoiceFree(e),t)}sessionVideoNoteCaption(t,e){return this.sessionSet(this.methodSessionVideoNoteCaption(e),t)}sessionVideoNoteCaptionPayload(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionPayload(e),t)}sessionVideoNoteCaptionCommand(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionCommand(e),t)}sessionVideoNoteCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionCommandPayload(e),t)}sessionVideoNoteFree(t,e){return this.sessionSet(this.methodSessionVideoNoteFree(e),t)}sessionStickerFree(t,e){return this.sessionSet(this.methodSessionStickerFree(e),t)}sessionLocationFree(t,e){return this.sessionSet(this.methodSessionLocationFree(e),t)}sessionContactFree(t,e){return this.sessionSet(this.methodSessionContactFree(e),t)}sessionToCallback(t,e){return this.sessionCallback({...this.session.params,...t},e)}sessionToCallbackPayload(t,e){return this.sessionCallbackPayload({...this.session.params,...t},e)}sessionToText(t,e){return this.sessionText({...this.session.params,...t},e)}sessionToTextPayload(t,e){return this.sessionTextPayload({...this.session.params,...t},e)}sessionToTextCommand(t,e){return this.sessionTextCommand({...this.session.params,...t},e)}sessionToTextCommandPayload(t,e){return this.sessionTextCommandPayload({...this.session.params,...t},e)}sessionToTextFree(t,e){return this.sessionTextFree({...this.session.params,...t},e)}sessionToPhotoCaption(t,e){return this.sessionPhotoCaption({...this.session.params,...t},e)}sessionToPhotoCaptionPayload(t,e){return this.sessionPhotoCaptionPayload({...this.session.params,...t},e)}sessionToPhotoCaptionCommand(t,e){return this.sessionPhotoCaptionCommand({...this.session.params,...t},e)}sessionToPhotoCaptionCommandPayload(t,e){return this.sessionPhotoCaptionCommandPayload({...this.session.params,...t},e)}sessionToPhotoFree(t,e){return this.sessionPhotoFree({...this.session.params,...t},e)}sessionToVideoCaption(t,e){return this.sessionVideoCaption({...this.session.params,...t},e)}sessionToVideoCaptionPayload(t,e){return this.sessionVideoCaptionPayload({...this.session.params,...t},e)}sessionToVideoCaptionCommand(t,e){return this.sessionVideoCaptionCommand({...this.session.params,...t},e)}sessionToVideoCaptionCommandPayload(t,e){return this.sessionVideoCaptionCommandPayload({...this.session.params,...t},e)}sessionToVideoFree(t,e){return this.sessionVideoFree({...this.session.params,...t},e)}sessionToAudioCaption(t,e){return this.sessionAudioCaption({...this.session.params,...t},e)}sessionToAudioCaptionPayload(t,e){return this.sessionAudioCaptionPayload({...this.session.params,...t},e)}sessionToAudioCaptionCommand(t,e){return this.sessionAudioCaptionCommand({...this.session.params,...t},e)}sessionToAudioCaptionCommandPayload(t,e){return this.sessionAudioCaptionCommandPayload({...this.session.params,...t},e)}sessionToAudioFree(t,e){return this.sessionAudioFree({...this.session.params,...t},e)}sessionToDocumentCaption(t,e){return this.sessionDocumentCaption({...this.session.params,...t},e)}sessionToDocumentCaptionPayload(t,e){return this.sessionDocumentCaptionPayload({...this.session.params,...t},e)}sessionToDocumentCaptionCommand(t,e){return this.sessionDocumentCaptionCommand({...this.session.params,...t},e)}sessionToDocumentCaptionCommandPayload(t,e){return this.sessionDocumentCaptionCommandPayload({...this.session.params,...t},e)}sessionToDocumentFree(t,e){return this.sessionDocumentFree({...this.session.params,...t},e)}sessionToAnimationCaption(t,e){return this.sessionAnimationCaption({...this.session.params,...t},e)}sessionToAnimationCaptionPayload(t,e){return this.sessionAnimationCaptionPayload({...this.session.params,...t},e)}sessionToAnimationCaptionCommand(t,e){return this.sessionAnimationCaptionCommand({...this.session.params,...t},e)}sessionToAnimationCaptionCommandPayload(t,e){return this.sessionAnimationCaptionCommandPayload({...this.session.params,...t},e)}sessionToAnimationFree(t,e){return this.sessionAnimationFree({...this.session.params,...t},e)}sessionToVoiceCaption(t,e){return this.sessionVoiceCaption({...this.session.params,...t},e)}sessionToVoiceCaptionPayload(t,e){return this.sessionVoiceCaptionPayload({...this.session.params,...t},e)}sessionToVoiceCaptionCommand(t,e){return this.sessionVoiceCaptionCommand({...this.session.params,...t},e)}sessionToVoiceCaptionCommandPayload(t,e){return this.sessionVoiceCaptionCommandPayload({...this.session.params,...t},e)}sessionToVoiceFree(t,e){return this.sessionVoiceFree({...this.session.params,...t},e)}sessionToVideoNoteCaption(t,e){return this.sessionVideoNoteCaption({...this.session.params,...t},e)}sessionToVideoNoteCaptionPayload(t,e){return this.sessionVideoNoteCaptionPayload({...this.session.params,...t},e)}sessionToVideoNoteCaptionCommand(t,e){return this.sessionVideoNoteCaptionCommand({...this.session.params,...t},e)}sessionToVideoNoteCaptionCommandPayload(t,e){return this.sessionVideoNoteCaptionCommandPayload({...this.session.params,...t},e)}sessionToVideoNoteFree(t,e){return this.sessionVideoNoteFree({...this.session.params,...t},e)}sessionToStickerFree(t,e){return this.sessionStickerFree({...this.session.params,...t},e)}sessionToLocationFree(t,e){return this.sessionLocationFree({...this.session.params,...t},e)}sessionToContactFree(t,e){return this.sessionContactFree({...this.session.params,...t},e)}methodSession(t,e){return`${t}-${e||this.data.name}`}methodSessionCallback(t){return this.methodSession("1",t)}methodSessionCallbackPayload(t){return this.methodSession("2",t)}methodSessionText(t){return this.methodSession("3",t)}methodSessionTextPayload(t){return this.methodSession("4",t)}methodSessionTextCommand(t){return this.methodSession("5",t)}methodSessionTextCommandPayload(t){return this.methodSession("6",t)}methodSessionTextFree(t){return this.methodSession("7",t)}methodSessionPhotoCaption(t){return this.methodSession("8",t)}methodSessionPhotoCaptionPayload(t){return this.methodSession("9",t)}methodSessionPhotoCaptionCommand(t){return this.methodSession("10",t)}methodSessionPhotoCaptionCommandPayload(t){return this.methodSession("11",t)}methodSessionPhotoFree(t){return this.methodSession("12",t)}methodSessionVideoCaption(t){return this.methodSession("13",t)}methodSessionVideoCaptionPayload(t){return this.methodSession("14",t)}methodSessionVideoCaptionCommand(t){return this.methodSession("15",t)}methodSessionVideoCaptionCommandPayload(t){return this.methodSession("16",t)}methodSessionVideoFree(t){return this.methodSession("17",t)}methodSessionAudioCaption(t){return this.methodSession("18",t)}methodSessionAudioCaptionPayload(t){return this.methodSession("19",t)}methodSessionAudioCaptionCommand(t){return this.methodSession("20",t)}methodSessionAudioCaptionCommandPayload(t){return this.methodSession("21",t)}methodSessionAudioFree(t){return this.methodSession("22",t)}methodSessionDocumentCaption(t){return this.methodSession("23",t)}methodSessionDocumentCaptionPayload(t){return this.methodSession("24",t)}methodSessionDocumentCaptionCommand(t){return this.methodSession("25",t)}methodSessionDocumentCaptionCommandPayload(t){return this.methodSession("26",t)}methodSessionDocumentFree(t){return this.methodSession("27",t)}methodSessionAnimationCaption(t){return this.methodSession("28",t)}methodSessionAnimationCaptionPayload(t){return this.methodSession("29",t)}methodSessionAnimationCaptionCommand(t){return this.methodSession("30",t)}methodSessionAnimationCaptionCommandPayload(t){return this.methodSession("31",t)}methodSessionAnimationFree(t){return this.methodSession("32",t)}methodSessionVoiceCaption(t){return this.methodSession("33",t)}methodSessionVoiceCaptionPayload(t){return this.methodSession("34",t)}methodSessionVoiceCaptionCommand(t){return this.methodSession("35",t)}methodSessionVoiceCaptionCommandPayload(t){return this.methodSession("36",t)}methodSessionVoiceFree(t){return this.methodSession("37",t)}methodSessionVideoNoteCaption(t){return this.methodSession("38",t)}methodSessionVideoNoteCaptionPayload(t){return this.methodSession("39",t)}methodSessionVideoNoteCaptionCommand(t){return this.methodSession("40",t)}methodSessionVideoNoteCaptionCommandPayload(t){return this.methodSession("41",t)}methodSessionVideoNoteFree(t){return this.methodSession("42",t)}methodSessionStickerFree(t){return this.methodSession("43",t)}methodSessionLocationFree(t){return this.methodSession("44",t)}methodSessionContactFree(t){return this.methodSession("45",t)}};var B=require("path");var $=require("path"),I=require("fs"),Z=require("module");var S=class{static{h(this,"PageManager")}static _getFile(t,e,i=0){let o=Object.values(t)[i];if(o===void 0)throw new Error(`File ${e} must have export (not default) class page`);return o}static getFilePath(){return(0,$.join)(process.cwd(),"src","pages")}static getFileSync(t,e=0){t||(t=this.getFilePath());let s=(0,Z.createRequire)(t)(t);return this._getFile(s,t,e)}static async getFile(t,e=0){t||(t=this.getFilePath());let i=await import(`${t}?t=${Date.now()}`);return this._getFile(i,t,e)}static getFileManySync(t,e=0){if(t||(t=this.getFilePath()),!(0,I.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,I.readdirSync)(t).map(s=>{let o=(0,$.join)(t,s);return{path:o,page:this.getFileSync(o,e)}})}static clearCacheRequire(t){if(t||(t=this.getFilePath()),!(0,I.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,I.readdirSync)(t).forEach(i=>{let s=(0,$.join)(t,i);delete require.cache[require.resolve(s)]}),!0}};var st=require("logging-pretty");var f=require("path"),y=require("fs"),tt=require("chokidar");var P=class{static{h(this,"TemplateEngine")}static _escape(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processVariables(t){return t.replace(/\{\{(\w+)\}\}/g,(e,i)=>`\${(data && data["${i}"]) ?? ""}`)}static _processBaseBlocks(t){let e=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,i={};for(let s of t.matchAll(e)){let o=s[2]??"default",n=(s[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();i[o]=n}return i}static _processScriptBlocks(t){return t.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(e,i)=>{let s=i.trim();return s?`\${(() => { if (!data) return ''; try { with(data) { ${s} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(t){return t.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(t){return t.replace(/<div>([\s\S]*?)<\/div>/gi,(e,i)=>i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(t){let e=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return t.replace(e,(i,s,o)=>{if(!s)return"";let a="",n=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=n.exec(o))!==null;){let d=(c[1]||"").split(",").map(u=>u.trim()),p=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(u=>{a+=`case "${u}": `}),a+=`return \`${p}\`; `}let l=r.exec(o);if(l){let d=(l[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");a+=`default: return \`${d}\`; `}else a+="default: return ''; ";return`\${(() => { switch((data && data["${s}"])) { ${a} } })()}`})}static _processExec(t){return t.replace(/{~\s*([\s\S]*?)\s*~}/g,(e,i)=>`\${(() => { try { return ${i} } catch(e) { try { with(data || {}) { return ${i} } } catch(ee) { return '' } } })()}`)}static _processMapBlocks(t){let e=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return t.replace(e,(i,s,o)=>{let a={},n=/(\w+)="([^"]*)"/g;if(s)for(let p of s.matchAll(n))a[p[1]]=p[2];let r=a.src;if(!r)return"";let c=a.join??"\\n",l=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");l=l.replace(/\{\{([\w.]+)\}\}/g,(p,u)=>u==="e"||u.startsWith("e.")?`\${${u}}`:u==="i"?"${i}":p);let d=c.replace(/"/g,'\\"');return`\${(data && data["${r}"] || []).map((e, i) => \`${l}\`).join("${d}")}`})}static _processMediaBlocks(t){let e=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,i={};for(let s of t.matchAll(e)){let o=s[1],a=s[2],n={},r=/(\w+)="([^"]*)"/g;if(o)for(let u of o.matchAll(r))n[u[1]]=u[2];let c=n.lang||"default",l=n.type,d=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),p={type:l};n.src&&(p.src=n.src),d&&l!=="video_note"&&l!=="sticker"&&(p.caption=d),l==="location"&&(n.latitude&&(p.latitude=n.latitude),n.longitude&&(p.longitude=n.longitude),d&&(p.caption=d)),l==="contact"&&(n.phone&&(p.phone=n.phone),n.first_name&&(p.first_name=n.first_name),n.last_name&&(p.last_name=n.last_name),n.vcard&&(p.vcard=n.vcard),d&&(p.caption=d)),i[c]=p}return i}static _processMessageBlocks(t){let e=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,i={};for(let[,s,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(s)for(let l of s.matchAll(n))a[l[1]]=l[2];let r=a.lang||"default",c=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();i[r]=c}return i}static _processDescriptionBlocks(t){let e=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,i={};for(let[,s,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(s)for(let d of s.matchAll(n))a[d[1]]=d[2];let r=a.lang||"default",c=a.scope||"default",l=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();i[r]||(i[r]={}),i[r][c]=l}return i}static _processKeyboardBlocks(t){let e=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,i={};for(let[,s,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(s)for(let d of s.matchAll(n))a[d[1]]=d[2];let r=a.lang||"default",c=a.type==="bottom"?"bottom":"inline",l=o.trim();i[r]||(i[r]={}),i[r][c]=l}return i}static _compileToFunction(t,e){let i;e?i=t.map(a=>`\`${a}\``).join(","):i=`\`${t}\``;let s=i;if(s=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(s))),e){let o=`return [${s}]`;return new Function("data",o)}else{let o=`return ${s}`;return new Function("data",o)}}static compileMedia(t,e){let i=e||this._processBaseBlocks(t),s={};for(let[o,a]of Object.entries(i)){let n=this._processMediaBlocks(a);s[o]={};for(let[r,c]of Object.entries(n)){let l={};for(let[d,p]of Object.entries(c)){if(d==="type"||typeof p!="string")continue;let u=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(p)))));l[d]=this._compileToFunction(u,!1)}s[o][r]=d=>{let p={...c};for(let[u,m]of Object.entries(l))p[u]=m(d);return p}}}return s}static compileMessages(t,e){let i=e||this._processBaseBlocks(t),s={};for(let[o,a]of Object.entries(i)){let n=this._processMessageBlocks(a);s[o]={};for(let[r,c]of Object.entries(n)){let l=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));s[o][r]=this._compileToFunction(l,!1)}}return s}static compileDescription(t,e){let i=e||this._processBaseBlocks(t),s={};for(let[o,a]of Object.entries(i)){let n=this._processDescriptionBlocks(a);s[o]={};for(let[r,c]of Object.entries(n))for(let[l,d]of Object.entries(c)){s[o][l]||(s[o][l]={});let p=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));s[o][l][r]=this._compileToFunction(p,!1)}}return s}static compileKeyboards(t,e){let i=e||this._processBaseBlocks(t),s={};for(let[o,a]of Object.entries(i)){let n=this._processKeyboardBlocks(a);s[o]={};for(let[r,c]of Object.entries(n)){s[o][r]={};for(let[l,d]of Object.entries(c)){let u=d.split(/(?<!\\),\s*/).map(m=>m.replace(/\\,/g,",").trim()).map(m=>this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(m))))));s[o][r][l]=this._compileToFunction(u,!0)}}}return s}static _extractBlock(t,e,i="default",s="all",o){let a=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,n=t,r=!1;for(let c of t.matchAll(a))if((c[2]??"default")===i){n=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(t);if(!(i==="default"&&!c))return""}if(e){if(e==="all")return n;let c=Array.isArray(e)?e:[e],l=[];for(let p of c){let u=new RegExp(`([ \\t]*)<${p}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${p}>`,"gi");for(let m of n.matchAll(u)){let b=m[2];if(o){let C=/lang="([^"]*)"/i,x=b?.match(C);if(((x?x[1]:void 0)||"default")!==o)continue}l.push({start:m.index,content:m[0],innerContent:m[3]??""})}}l.sort((p,u)=>p.start-u.start);let d=h(p=>{let u=p.split(`
|
|
2
|
+
`);if(u.length<=1)return p.trim();let m=u.filter(C=>C.trim().length>0);if(m.length===0)return"";let b=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>=b?C.slice(b):C.trimStart()).join(`
|
|
3
|
+
`).trim()},"processResult");return s==="all"?l.map(u=>d(u.content)).join(`
|
|
4
4
|
`):l.map(u=>d(u.innerContent)).join(`
|
|
5
|
-
`)}return n}static _processImportBlocks(t){let e=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,
|
|
5
|
+
`)}return n}static _processImportBlocks(t){let e=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,i=[];return{processed:t.replace(e,(o,a,n)=>{let r={},c=/(\w+)="([^"]*)"/g;if(n)for(let u of n.matchAll(c))r[u[1]]=u[2];let l=r.src;if(!l)return"";let d;r.block&&(r.block==="all"?d="all":r.block.includes(",")?d=r.block.split(",").map(u=>u.trim()).filter(u=>u):d=r.block);let p={src:l,blocks:d,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:a||""};return i.push(p),`${a}__IMPORT_${i.length-1}__`}),imports:i}}static processImportBlocks(t,e,i=0,s){if(i>10)return"";let{processed:o,imports:a}=this._processImportBlocks(t),n=o;for(let r=0;r<a.length;r++){let c=a[r],l=`${c.src}|${c.base}|${c.lang||""}|${c.section}|${Array.isArray(c.blocks)?c.blocks.join(","):c.blocks||""}`,d;if(s&&s.has(l))d=s.get(l);else{let u=e(c.src);d=u?this._extractBlock(u,c.blocks,c.base,c.section,c.lang):"",d&&d.includes("<import")&&(d=this.processImportBlocks(d,e,i+1,s)),s&&s.set(l,d)}let p=d.split(`
|
|
6
6
|
`).map((u,m)=>m===0?u:c.indent+u).join(`
|
|
7
|
-
`);n=n.replace(`__IMPORT_${r}__`,p)}return n}};var R=class{static{h(this,"TemplateManager")}_map=new Map;_engine=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
|
-
<keyboard type="${e.type}" lang="${e.lang}">${e.reverse?this.data._reverse(
|
|
9
|
-
`}return Object.keys(t).map(
|
|
10
|
-
<keyboard type="${e.type}" lang="${
|
|
11
|
-
`}).join(" ")}static _build(t,e,
|
|
7
|
+
`);n=n.replace(`__IMPORT_${r}__`,p)}return n}};var R=class{static{h(this,"TemplateManager")}_map=new Map;_engine=P;_watcher=[];_pageManager=S;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(t){let{path:e,enableWatch:i=!1}=t;this._path=e,this._isWatchEnabled=i,this._validatePath(),this._initializeWatcher(t.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let t=0;t<this._path.length;t++){let e=this._path[t];if(!(0,y.existsSync)(e))throw new Error(`Template base path is not exists: ${e}`);if(!(0,y.statSync)(e).isDirectory())throw new Error(`Template base path is not a directory: ${e}`)}return!0}catch(t){throw new Error(`Failed to validate Template base path: ${String(t)}`)}}_initializeWatcher(t){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let e=0;e<this._path.length;e++){let i=this._path[e],s=(0,tt.watch)(i,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...t});this._watcher[e]=s,s.on("change",this._handleFileChange.bind(this)),s.on("add",this._handleFileAdd.bind(this)),s.on("unlink",this._handleFileDelete.bind(this)),s.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(t){let e=(0,f.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileAdd(t){let e=(0,f.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileDelete(t){let e=(0,f.basename)(t),i=this._getKey(e);this._map.has(i)&&this._map.delete(i)}_handleWatchError(t){}_loadAllFiles(){let t=new Map,e=[];for(let s=0;s<this._path.length;s++){let o=this._path[s],n=(0,y.readdirSync)(o,"utf8").filter(r=>this._isValidFile(r));for(let r of n){let c=(0,f.join)(o,r),l=this._getExtension(r),d=this._getKey(r);if(l===".html")t.set(d,(0,y.readFileSync)(c,"utf8"));else if(l===".ts"||l===".js"){let p=S.getFileSync(c);p?.template!==void 0&&(t.set(d,p.template),e.push(p))}}}let i=new Map;for(let[s,o]of t.entries())this._compile(s,o,void 0,i,t);t.clear(),i.clear();for(let s of e)s.template=void 0}_loadFile(t){for(let e=0;e<this._path.length;e++){let i=this._path[e],s=(0,f.join)(i,t),o=this._getExtension(t),a=this._getKey(t);if(o==".html"){let n=(0,y.readFileSync)(s,"utf8");this._compile(a,n)}else if(o==".ts"||o==".js"){let n=S.getFileSync(s);n?.template!==void 0&&(this._compile(a,n.template),n.template=void 0)}else throw new Error(`File ${t} is not support`)}}_getExtension(t){return(0,f.extname)(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let i=(0,f.extname)(t).toLowerCase();if(i){let n=(0,f.join)(e,t);if((0,y.existsSync)(n)&&(0,y.statSync)(n).isFile()){if(i===".html")return(0,y.readFileSync)(n,"utf8");if(i===".ts"||i===".js")try{return S.getFileSync(n)?.template??null}catch{return null}}continue}let s=(0,f.join)(e,`${t}.ts`),o=(0,f.join)(e,`${t}.js`);if((0,y.existsSync)(s)&&(0,y.statSync)(s).isFile())try{return S.getFileSync(s)?.template??null}catch{}else if((0,y.existsSync)(o)&&(0,y.statSync)(o).isFile())try{return S.getFileSync(s)?.template??null}catch{}let a=(0,f.join)(e,`${t}.html`);if((0,y.existsSync)(a)&&(0,y.statSync)(a).isFile())return(0,y.readFileSync)(a,"utf8")}return null}_isValidFile(t){return this._supportedExtensions.has(this._getExtension(t))}_getKey(t){return t.replace(/\.[^/.]+$/,"")}_compile(t,e,i,s,o){let a=this._map.get(t),n=a||{},r=!1,c=P.processImportBlocks(e,d=>o&&o.has(d)?o.get(d):this._readTemplateFile(d),0,s),l=P._processBaseBlocks(c);(i===void 0||i?.media===!1||a?.media===void 0)&&(n.media=P.compileMedia(c,l),r=!0),(i===void 0||i?.message===!1||a?.message===void 0)&&(n.message=P.compileMessages(c,l),r=!0),(i===void 0||i?.keyboard===!1||a?.keyboard===void 0)&&(n.keyboard=P.compileKeyboards(c,l),r=!0),(i===void 0||i?.description===!1||a?.description===void 0)&&(n.description=P.compileDescription(c,l),r=!0),r&&this._map.set(t,n)}getMedia(t,e="default",i="default",s){let a=this._map.get(t)?.media?.[e],n=a?.[i]||a?.default;try{if(!n)throw new Error("Media function not found, please check your template");return n(s)}catch{return{}}}getMessage(t,e="default",i="default",s){try{let a=this._map.get(t)?.message?.[e],n=a?.[i]||a?.default;if(!n)throw"";return n(s)}catch{return""}}getDescription(t,e="default",i="default",s="default",o){try{let n=this._map.get(t)?.description?.[e]?.[s],r=n?.[i]||n?.default;if(!r)throw"";return r(o)}catch{return""}}getDescriptionLanguage(t,e="default",i="default"){try{let o=this._map.get(t)?.description?.[e]?.[i];return o?Object.keys(o):[]}catch{return[]}}getDescriptionScopes(t,e="default"){try{let s=this._map.get(t)?.description?.[e];return s?Object.keys(s):[]}catch{return[]}}getKeyboard(t,e="default",i="default",s="inline",o){try{let n=this._map.get(t)?.keyboard?.[e],r=n?.[i]?.[s]||n?.default?.[s];if(!r)throw[];return r(o)}catch{return[]}}async write(t,e){if(this._getExtension(t)!=".html")return null;for(let i=0;i<this._path.length;i++){let s=(0,f.join)(this._path[i],t);if((0,y.existsSync)(s))return(0,y.writeFileSync)(s,e,"utf8"),this._loadFile(t),!0}return null}has(t){return this._map.has(t)}async destroy(){if(this._watcher)for(let t of this._watcher)await t.close();this._map.clear()}};var D=require("grammy");var et="0.3.3";var E=class{static{h(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;log;bot;handlerBotUpdate;constructor(t){if(!t?.token||t?.token?.length==0)throw new Error("Token is not valid or empty");if(this.log=t.log===!0?new st.LoggingPretty:t.log?t.log:void 0,this.log?.info?.(`Gramstax v${et}`),this.cacheSession=t.cacheSession||new F("memory","session"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new R({path:[(0,B.join)(process.cwd(),"src","pages")]}),this.bot=this.createBot(t.token),this.bot.catch(this.onCatch),this.registerOnCallbackQueryData(),this.registerOnMessageText(),this.registerOnMessagePhoto(),this.registerOnMessageVideo(),this.registerOnMessageAudio(),this.registerOnMessageDocument(),this.registerOnMessageAnimation(),this.registerOnMessageVoice(),this.registerOnMessageVideoNote(),this.registerOnMessageSticker(),this.registerOnMessageLocation(),this.registerOnMessageContact(),this.handlerBotUpdate=this.bot.handleUpdate,this.pages=this.pageLoads(),process.once("SIGINT",()=>this.bot.stop()),process.once("SIGTERM",()=>this.bot.stop()),this.hookBeforeStart(),t.deploy.startsWith("polling"))this.runPolling();else if(t.deploy.startsWith("webhook:"))this.runWebhook(t.deploy.split("webhook:")[1]);else if(t.deploy.startsWith("serverless:"))this.runServerless(t.deploy.split("serverless:")[1]);else if(!t.deploy.startsWith("test"))throw new Error("Params deploy is not valid, expected: polling, webhook:<public-url>, serverless:<your-adapter>")}onCatch(t){this.log?.error?.(`[Bot.catch]: ${JSON.stringify(t,null,2)}`)}hookBeforeStart(){}hookAfterStart(){}async onStart(t,e,i){await this.executeSyncBlocksDescription(this.pages);let{username:s}=t;this.log?.success?.(`Telegram bot polling started: ${s} ${e=="webhook"||e=="serverless"?`(${i})`:""}`),this.hookAfterStart()}createBot(t){return new D.Bot(t)}createCtx(t){return new V({ct:t,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{session:{},data:{}}})}runPolling(){this.bot.start({onStart:h(t=>{this.onStart(t,"polling",null)},"onStart")})}async runWebhook(t){let{serve:e}=await import("bun"),i=(0,D.webhookCallback)(this.bot,"bun");this.handlerBotUpdate=i;let s=new URL(t).pathname;e({fetch(n){let{pathname:r}=new URL(n.url);if(n.method=="POST"&&r==s)return i(n);if(n.method=="GET"&&r=="/"){let c=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:c}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}}),(await this.bot.api.getWebhookInfo()).url!=t&&await this.bot.api.setWebhook(t);let a=await this.bot.api.getMe();await this.onStart(a,"webhook",t)}async runServerless(t){this.handlerBotUpdate=(0,D.webhookCallback)(this.bot,t);let e=await this.bot.api.getMe();await this.onStart(e,"serverless",t)}pageBuildData(t,e){t?.data===void 0&&(t.data=t.buildData()),t.data.name=(0,B.parse)(e).name}pageSorts(t,e){let i=t.data.name,s=t.prototype,o="Payload",a="Command",n="Caption",r="Free",c=e.routeDynamic,l=e.routeDynamicSpesific,d=h(m=>m.charAt(0).toUpperCase()+m.slice(1),"upFirst"),p=h(m=>m.replace(o,"").replace(a,"").replace(n,"").replace(r,""),"getPureRouteName"),u=h((m,b)=>s[`methodSession${d(m)}`]?.(b),"methodSession");e.all[i]=t;for(let m=0;m<e.lenListRouteStaticSession;m++){let b=e.listRouteStaticSession[m];if(typeof s[b]!="function")continue;let C=e.routeStatic[b],x=e.routeStaticIntent[b],T=e.routeStaticSession[b],v={name:i,routeName:b},Q=C||x;if(Q!==void 0){let it=b.includes(a),nt=b.includes("callback"),ot=b.startsWith("text"),w;if(it){let J=t.data.textCommand||t.data.name;w=J?`/${J}`:void 0}else nt?w=t.data.name:ot?w=t.data.text||t.data.name:w=t.data.name;w&&(Q[w]=v)}T!==void 0&&(T[u(b,i)]=v),b.toLowerCase().endsWith("free")&&l[p(b)].push(v)}s.free&&c.push(i)}async executeSyncBlocksDescription(t){let e=new Map,i=t.routeStatic.textCommand;for(let[,s]of Object.entries(i)){let o=s.name,a=this.templateManager.getDescriptionScopes(o);for(let n of a){e.has(n)||e.set(n,new Set);let r=this.templateManager.getDescriptionLanguage(o,"default",n);for(let c of r)e.get(n).add(c)}}for(let[s,o]of e)for(let a of o){let n=[];for(let[,l]of Object.entries(i)){let d=l.name,p=this.templateManager.getDescription(d,"default",a,s);p&&n.push({command:d,description:p})}if(n.length===0)continue;let r={type:s},c=a==="default"?void 0:a;try{let l=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(l.map(u=>({command:u.command,description:u.description})).sort((u,m)=>u.command.localeCompare(m.command))),p=JSON.stringify(n.sort((u,m)=>u.command.localeCompare(m.command)));d!==p&&(await this.bot.api.setMyCommands(n,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${s},${c?` lang: ${c},`:""} total (${n.length})`))}catch(l){this.log?.error?.(`Failed to sync descriptions for scope: ${s},${c?` lang: ${c},`:""} error: ${String(l)}`)}}}pageLoads(){this.log?.info?.("Load pages..");let t=["callback","text","textCommand","photoCaption","photoCaptionCommand","videoCaption","videoCaptionCommand","audioCaption","audioCaptionCommand","documentCaption","documentCaptionCommand","animationCaption","animationCaptionCommand","voiceCaption","voiceCaptionCommand","videoNoteCaption","videoNoteCaptionCommand"],e=["callbackPayload","textPayload","textCommandPayload","photoCaptionPayload","photoCaptionCommandPayload","videoCaptionPayload","videoCaptionCommandPayload","audioCaptionPayload","audioCaptionCommandPayload","documentCaptionPayload","documentCaptionCommandPayload","animationCaptionPayload","animationCaptionCommandPayload","voiceCaptionPayload","voiceCaptionCommandPayload","videoNoteCaptionPayload","videoNoteCaptionCommandPayload"],i=[...t,...e,"textFree","photoFree","videoFree","audioFree","documentFree","animationFree","voiceFree","videoNoteFree","stickerFree","locationFree","contactFree"],s=h((n,r)=>Object.fromEntries(n.map(c=>[c,r()])),"makeObject"),o=h(()=>[],"initDynamicSpesific"),a={all:{},routeDynamic:[],routeDynamicSpesific:{text:o(),photo:o(),video:o(),audio:o(),document:o(),animation:o(),voice:o(),videoNote:o(),sticker:o(),location:o(),contact:o()},routeStatic:s(t,()=>({})),routeStaticIntent:s(e,()=>({})),routeStaticSession:s(i,()=>({})),listRouteStatic:t,listRouteStaticIntent:e,listRouteStaticSession:i,lenListRouteStatic:t.length,lenListRouteStaticIntent:e.length,lenListRouteStaticSession:i.length};return S.getFileManySync(void 0).forEach(({path:n,page:r})=>{this.pageBuildData(r,n),this.pageSorts(r,a),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(a.all).length})`),a}async pageRoutes(t,e){let i,s;if(i===void 0){let a=t.callbackData,n=t.msgText,r=t.msgCaption,c=this.pages.routeStatic;for(let l=0;l<this.pages.lenListRouteStatic;l++){let d=this.pages.listRouteStatic[l];if(d.startsWith(e)&&(s=c[d][a||n||r]),s)break}s!==void 0&&(i=this.pages.all[s.name])}if(i===void 0){let a=await t.sessionGet();if(a){let n=a.method,r=this.pages.routeStaticSession;for(let c=0;c<this.pages.lenListRouteStaticSession;c++){let l=this.pages.listRouteStaticSession[c];if(l.startsWith(e)&&(s=r[l][n]),s)break}s!==void 0&&(i=this.pages.all[s.name])}}if(i===void 0){let a=this.pages.routeStaticIntent,n=e==="callback",r=n?t.callbackData:t.msgText||t.msgCaption;if(r)for(let c=0;c<this.pages.lenListRouteStaticIntent;c++){let l=this.pages.listRouteStaticIntent[c];if(l.startsWith(e)){let d=a[l];s=d[t.intent(r,n?"colon":"space",1)],!s&&!n&&(s=d[t.intent(r,"space",2)])}if(s)break}s!==void 0&&(i=this.pages.all[s.name])}if(i!==void 0&&s!==void 0)return i.prototype[s.routeName]?await new i(t)[s.routeName]?.():void 0;let o=this.pages.routeDynamicSpesific[e]||[];for(let a=0;a<o.length;a++){let n=o[a];if(n===void 0)continue;let r=this.pages.all[n.name];if(r===void 0||!r.prototype[n.routeName])continue;let l=await new r(t)[n.routeName]?.();if(l!==null)return l}for(let a=0;a<this.pages.routeDynamic.length;a++){let n=this.pages.routeDynamic[a];if(n===void 0)continue;let r=this.pages.all[n];if(r===void 0||!r.prototype.free)continue;let l=await new r(t).free?.();if(l!==null)return l}return null}async hookBeforeRoute(t,e){return!!(t||e)}async hookErrorPage(t,e,i,s){}async hookErrorInputNotFoundPage(t){}async onMessage(t,e){let i=this.createCtx(t);try{if(await this.hookBeforeRoute(i,e)===!1)return;await this.pageRoutes(i,e)===null&&await this.hookErrorInputNotFoundPage(i)}catch(s){await this.hookErrorPage(i,e,s,!1)}}async onCallbackQueryData(t){let e=this.createCtx(t);try{if(await e.callbackQueryAnswer(),await this.hookBeforeRoute(e,"onCallbackQueryData")===!1)return;await this.pageRoutes(e,"callback")}catch(i){await this.hookErrorPage(e,"onCallbackQueryData",i,!0)}}async onMessageText(t){await this.onMessage(t,"text")}async onMessagePhoto(t){await this.onMessage(t,"photo")}async onMessageVideo(t){await this.onMessage(t,"video")}async onMessageAudio(t){await this.onMessage(t,"audio")}async onMessageDocument(t){await this.onMessage(t,"document")}async onMessageAnimation(t){await this.onMessage(t,"animation")}async onMessageVoice(t){await this.onMessage(t,"voice")}async onMessageVideoNote(t){await this.onMessage(t,"videoNote")}async onMessageSticker(t){await this.onMessage(t,"sticker")}async onMessageLocation(t){await this.onMessage(t,"location")}async onMessageContact(t){await this.onMessage(t,"contact")}registerOnCallbackQueryData(){this.bot.on("callback_query:data",this.onCallbackQueryData.bind(this))}registerOnMessageText(){this.bot.on("message:text",this.onMessageText.bind(this))}registerOnMessagePhoto(){this.bot.on("message:photo",this.onMessagePhoto.bind(this))}registerOnMessageVideo(){this.bot.on("message:video",this.onMessageVideo.bind(this))}registerOnMessageAudio(){this.bot.on("message:audio",this.onMessageAudio.bind(this))}registerOnMessageDocument(){this.bot.on("message:document",this.onMessageDocument.bind(this))}registerOnMessageAnimation(){this.bot.on("message:animation",this.onMessageAnimation.bind(this))}registerOnMessageVoice(){this.bot.on("message:voice",this.onMessageVoice.bind(this))}registerOnMessageVideoNote(){this.bot.on("message:video_note",this.onMessageVideoNote.bind(this))}registerOnMessageSticker(){this.bot.on("message:sticker",this.onMessageSticker.bind(this))}registerOnMessageLocation(){this.bot.on("message:location",this.onMessageLocation.bind(this))}registerOnMessageContact(){this.bot.on("message:contact",this.onMessageContact.bind(this))}};var N=require("worker_threads");var O=class{constructor(t,e){this.path=t;this.argv=e;if(!N.isMainThread)throw new Error("Is not main thread");this.sub=new N.Worker(t,{argv:e}),this.subId=this.sub.threadId,this.sub.on("message",async i=>{let{id:s,method:o,params:a,result:n}=i;if(o!==void 0){let r=this[o];if(typeof r!="function")throw new Error(`Method ${o} not found`);let c=await r.apply(this,a);this.send({id:s,result:c})}else if(n!==void 0){let r=this.map.get(s);r&&(r?.(n),this.map.delete(s))}})}static{h(this,"ThreadMain")}map=new Map;sub;pid=process.pid;subId;createId(){return Math.random()}send(t){this.sub.postMessage(t)}async sendRequest(t,e,i=!0){let s=this.createId();return i?new Promise(o=>{this.map.set(s,o),this.send({id:s,method:t,params:e})}):this.send({id:s,method:t,params:e})}kill(){this.sub.terminate()}};var K=class{static{h(this,"ThreadExport")}static init(t){let{CSub:e,CMain:i=O,path:s,wrap:o}=t,a=`for-${s}`;if(process.argv[2]===a)return new e,{};let n,r=new Proxy({},{get(d,p){return p==="sendRequest"?(u,m,b=!0)=>{if(!n)throw new Error(`Thread at ${s} not launched yet.`);return n.sendRequest(u,m,b)}:(...u)=>{if(!n)throw new Error(`Thread at ${s} not launched yet.`);return n.sendRequest(p,u)}}});return{...o?o(r):{},launch:h((d=[])=>(n=new i(s,[a,...d]),n),"launch")}}};var L=class{static{h(this,"ThreadMainPool")}thread={};threadCount=0;constructor(t){t.forEach(async e=>{let i=await e;this.thread[i.subId]=i,this.threadCount+=1})}add(t){this.thread[t.subId]=t,this.threadCount+=1}getInstance(t){return this.thread[t]}killAll(){return Object.values(this.thread).map(({subId:t})=>this.kill(t))}kill(t){let e=this.thread[t];return e?.kill(),delete this.thread[t],this.threadCount-=1,e?.subId}async broadcastRequest(t,e){return await Promise.all(Object.values(this.thread).map(i=>i.sendRequest(t,e,!0)))}async sendRequest(t,e,i,s=!0){return await this.thread[t]?.sendRequest(e,i,s)}};var k=require("worker_threads");var 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:i,params:s,result:o}=t;if(i!==void 0)try{let a=this[i];if(typeof a!="function")throw new Error(`Method ${i} not found`);let n=await a.apply(this,s);this.send({id:e,result:n})}catch(a){this.send({id:e,error:a})}else if(o!==void 0){let a=this.map.get(e);a&&(a?.(o),this.map.delete(e))}})}createId(){return Math.random()}send(t){k.parentPort.postMessage(t)}async sendRequest(t,e,i=!0){let s=this.createId();return i?new Promise(o=>{this.map.set(s,o),this.send({id:s,method:t,params:e})}):this.send({id:s,method:t,params:e})}};var W=class{static{h(this,"ComponentKeyboard")}static data;static _process(t,e){if(e.type||(e.type="inline"),e.lang){let i=t[e.lang];return`
|
|
8
|
+
<keyboard type="${e.type}" lang="${e.lang}">${e.reverse?this.data._reverse(i):i}</keyboard>
|
|
9
|
+
`}return Object.keys(t).map(i=>{let s=t[i];return`
|
|
10
|
+
<keyboard type="${e.type}" lang="${i}">${e.reverse?this.data._reverse(s):s}</keyboard>
|
|
11
|
+
`}).join(" ")}static _build(t,e,i){if(!this.data)throw new Error("Data not found");let s=this.data[t];if(!s)throw new Error(`Function ${t} not found`);return this._process(s.call(this.data,e),{type:i,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,i)=>(e[i]=this._reverse(t[i]),e),{})}static _build(t,e,i){if(t){let s=i[t||""];return e?this._reverse(s):s}return e?this._reverseObj(i):i}};0&&(module.exports={CacheExternal,ComponentKeyboard,Ctx,DataKeyboard,Gramstax,LoggingUtils,TemplateEngine,TemplateManager,ThreadExport,ThreadMain,ThreadMainPool,ThreadSub,log});
|
package/dist/src/index.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { LoggingPretty } from 'logging-pretty';
|
|
2
2
|
import { Keyv } from 'keyv';
|
|
3
3
|
import * as grammy from 'grammy';
|
|
4
4
|
import { Context, Keyboard, InlineKeyboard, Bot, BotError } from 'grammy';
|
|
@@ -596,13 +596,13 @@ declare class Gramstax<ICtx extends Ctx = Ctx> {
|
|
|
596
596
|
cacheKeyboard: Map<any, any>;
|
|
597
597
|
cacheSession: CacheExternal;
|
|
598
598
|
pages: ReturnType<typeof this.pageLoads>;
|
|
599
|
-
log: LoggingPretty
|
|
599
|
+
log: LoggingPretty | undefined;
|
|
600
600
|
bot: Bot;
|
|
601
601
|
handlerBotUpdate: any;
|
|
602
602
|
constructor(params: {
|
|
603
603
|
token: string;
|
|
604
604
|
deploy: string;
|
|
605
|
-
log?: LoggingPretty
|
|
605
|
+
log?: LoggingPretty | boolean | null;
|
|
606
606
|
cacheData?: CacheExternal;
|
|
607
607
|
cacheSession?: CacheExternal;
|
|
608
608
|
cacheKeyboard?: Map<any, any>;
|
package/dist/src/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { LoggingPretty } from 'logging-pretty';
|
|
2
2
|
import { Keyv } from 'keyv';
|
|
3
3
|
import * as grammy from 'grammy';
|
|
4
4
|
import { Context, Keyboard, InlineKeyboard, Bot, BotError } from 'grammy';
|
|
@@ -596,13 +596,13 @@ declare class Gramstax<ICtx extends Ctx = Ctx> {
|
|
|
596
596
|
cacheKeyboard: Map<any, any>;
|
|
597
597
|
cacheSession: CacheExternal;
|
|
598
598
|
pages: ReturnType<typeof this.pageLoads>;
|
|
599
|
-
log: LoggingPretty
|
|
599
|
+
log: LoggingPretty | undefined;
|
|
600
600
|
bot: Bot;
|
|
601
601
|
handlerBotUpdate: any;
|
|
602
602
|
constructor(params: {
|
|
603
603
|
token: string;
|
|
604
604
|
deploy: string;
|
|
605
|
-
log?: LoggingPretty
|
|
605
|
+
log?: LoggingPretty | boolean | null;
|
|
606
606
|
cacheData?: CacheExternal;
|
|
607
607
|
cacheSession?: CacheExternal;
|
|
608
608
|
cacheKeyboard?: Map<any, any>;
|
package/dist/src/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var tt=Object.defineProperty;var h=(y,t)=>tt(y,"name",{value:t,configurable:!0}),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,
|
|
1
|
+
var et=Object.defineProperty;var h=(y,t)=>et(y,"name",{value:t,configurable:!0}),R=(y=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(y,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):y)(function(y){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+y+'" is not supported')});import{LoggingPretty as st}from"logging-pretty";var D=class extends st{static{h(this,"LoggingUtils")}constructor(t){super(t)}errorMake(t,e,s){this.error(`[${e?.name||e}:${s}] ${String(t)}`)}},Pt=new D;import{Keyv as it}from"keyv";import nt from"@keyv/redis";var M=class extends it{constructor(e="memory",s,i,o){let a;e.startsWith("redis")&&(a=new nt(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 ot}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 ot(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 pt,parse as ut}from"path";import{join as O}from"path";import{existsSync as K,readdirSync as L}from"fs";import{createRequire as at}from"module";var f=class{static{h(this,"PageManager")}static _getFile(t,e,s=0){let o=Object.values(t)[s];if(o===void 0)throw new Error(`File ${e} must have export (not default) class page`);return o}static getFilePath(){return O(process.cwd(),"src","pages")}static getFileSync(t,e=0){t||(t=this.getFilePath());let i=at(t)(t);return this._getFile(i,t,e)}static async getFile(t,e=0){t||(t=this.getFilePath());let s=await import(`${t}?t=${Date.now()}`);return this._getFile(s,t,e)}static getFileManySync(t,e=0){if(t||(t=this.getFilePath()),!K(t))throw new Error(`Directory ${t} is not found, please make it manually`);return L(t).map(i=>{let o=O(t,i);return{path:o,page:this.getFileSync(o,e)}})}static clearCacheRequire(t){if(t||(t=this.getFilePath()),!K(t))throw new Error(`Directory ${t} is not found, please make it manually`);return L(t).forEach(s=>{let i=O(t,s);delete R.cache[R.resolve(i)]}),!0}};import{LoggingPretty as ht}from"logging-pretty";import{basename as A,join as P,extname as j}from"path";import{readdirSync as rt,readFileSync as _,existsSync as T,statSync as w,writeFileSync as ct}from"fs";import{watch as lt}from"chokidar";var C=class{static{h(this,"TemplateEngine")}static _escape(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processVariables(t){return t.replace(/\{\{(\w+)\}\}/g,(e,s)=>`\${(data && data["${s}"]) ?? ""}`)}static _processBaseBlocks(t){let e=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,s={};for(let i of t.matchAll(e)){let o=i[2]??"default",n=(i[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[o]=n}return s}static _processScriptBlocks(t){return t.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(e,s)=>{let i=s.trim();return i?`\${(() => { if (!data) return ''; try { with(data) { ${i} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(t){return t.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(t){return t.replace(/<div>([\s\S]*?)<\/div>/gi,(e,s)=>s.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(t){let e=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return t.replace(e,(s,i,o)=>{if(!i)return"";let a="",n=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=n.exec(o))!==null;){let d=(c[1]||"").split(",").map(u=>u.trim()),p=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(u=>{a+=`case "${u}": `}),a+=`return \`${p}\`; `}let l=r.exec(o);if(l){let d=(l[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");a+=`default: return \`${d}\`; `}else a+="default: return ''; ";return`\${(() => { switch((data && data["${i}"])) { ${a} } })()}`})}static _processExec(t){return t.replace(/{~\s*([\s\S]*?)\s*~}/g,(e,s)=>`\${(() => { try { return ${s} } catch(e) { try { with(data || {}) { return ${s} } } catch(ee) { return '' } } })()}`)}static _processMapBlocks(t){let e=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return t.replace(e,(s,i,o)=>{let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let p of i.matchAll(n))a[p[1]]=p[2];let r=a.src;if(!r)return"";let c=a.join??"\\n",l=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");l=l.replace(/\{\{([\w.]+)\}\}/g,(p,u)=>u==="e"||u.startsWith("e.")?`\${${u}}`:u==="i"?"${i}":p);let d=c.replace(/"/g,'\\"');return`\${(data && data["${r}"] || []).map((e, i) => \`${l}\`).join("${d}")}`})}static _processMediaBlocks(t){let e=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let i of t.matchAll(e)){let o=i[1],a=i[2],n={},r=/(\w+)="([^"]*)"/g;if(o)for(let u of o.matchAll(r))n[u[1]]=u[2];let c=n.lang||"default",l=n.type,d=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),p={type:l};n.src&&(p.src=n.src),d&&l!=="video_note"&&l!=="sticker"&&(p.caption=d),l==="location"&&(n.latitude&&(p.latitude=n.latitude),n.longitude&&(p.longitude=n.longitude),d&&(p.caption=d)),l==="contact"&&(n.phone&&(p.phone=n.phone),n.first_name&&(p.first_name=n.first_name),n.last_name&&(p.last_name=n.last_name),n.vcard&&(p.vcard=n.vcard),d&&(p.caption=d)),s[c]=p}return s}static _processMessageBlocks(t){let e=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,i,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let l of i.matchAll(n))a[l[1]]=l[2];let r=a.lang||"default",c=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=c}return s}static _processDescriptionBlocks(t){let e=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,i,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let d of i.matchAll(n))a[d[1]]=d[2];let r=a.lang||"default",c=a.scope||"default",l=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][c]=l}return s}static _processKeyboardBlocks(t){let e=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,i,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let d of i.matchAll(n))a[d[1]]=d[2];let r=a.lang||"default",c=a.type==="bottom"?"bottom":"inline",l=o.trim();s[r]||(s[r]={}),s[r][c]=l}return s}static _compileToFunction(t,e){let s;e?s=t.map(a=>`\`${a}\``).join(","):s=`\`${t}\``;let i=s;if(i=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(i))),e){let o=`return [${i}]`;return new Function("data",o)}else{let o=`return ${i}`;return new Function("data",o)}}static compileMedia(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processMediaBlocks(a);i[o]={};for(let[r,c]of Object.entries(n)){let l={};for(let[d,p]of Object.entries(c)){if(d==="type"||typeof p!="string")continue;let u=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(p)))));l[d]=this._compileToFunction(u,!1)}i[o][r]=d=>{let p={...c};for(let[u,m]of Object.entries(l))p[u]=m(d);return p}}}return i}static compileMessages(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processMessageBlocks(a);i[o]={};for(let[r,c]of Object.entries(n)){let l=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));i[o][r]=this._compileToFunction(l,!1)}}return i}static compileDescription(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processDescriptionBlocks(a);i[o]={};for(let[r,c]of Object.entries(n))for(let[l,d]of Object.entries(c)){i[o][l]||(i[o][l]={});let p=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));i[o][l][r]=this._compileToFunction(p,!1)}}return i}static compileKeyboards(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processKeyboardBlocks(a);i[o]={};for(let[r,c]of Object.entries(n)){i[o][r]={};for(let[l,d]of Object.entries(c)){let u=d.split(/(?<!\\),\s*/).map(m=>m.replace(/\\,/g,",").trim()).map(m=>this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(m))))));i[o][r][l]=this._compileToFunction(u,!0)}}}return i}static _extractBlock(t,e,s="default",i="all",o){let a=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,n=t,r=!1;for(let c of t.matchAll(a))if((c[2]??"default")===s){n=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(t);if(!(s==="default"&&!c))return""}if(e){if(e==="all")return n;let c=Array.isArray(e)?e:[e],l=[];for(let p of c){let u=new RegExp(`([ \\t]*)<${p}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${p}>`,"gi");for(let m of n.matchAll(u)){let g=m[2];if(o){let b=/lang="([^"]*)"/i,v=g?.match(b);if(((v?v[1]:void 0)||"default")!==o)continue}l.push({start:m.index,content:m[0],innerContent:m[3]??""})}}l.sort((p,u)=>p.start-u.start);let d=h(p=>{let u=p.split(`
|
|
2
|
+
`);if(u.length<=1)return p.trim();let m=u.filter(b=>b.trim().length>0);if(m.length===0)return"";let g=m.reduce((b,v)=>{let k=v.match(/^([ \t]*)/),S=k?k[1].length:0;return S<b?S:b},1/0);return u.map(b=>b.length>=g?b.slice(g):b.trimStart()).join(`
|
|
3
3
|
`).trim()},"processResult");return i==="all"?l.map(u=>d(u.content)).join(`
|
|
4
4
|
`):l.map(u=>d(u.innerContent)).join(`
|
|
5
5
|
`)}return n}static _processImportBlocks(t){let e=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,s=[];return{processed:t.replace(e,(o,a,n)=>{let r={},c=/(\w+)="([^"]*)"/g;if(n)for(let u of n.matchAll(c))r[u[1]]=u[2];let l=r.src;if(!l)return"";let d;r.block&&(r.block==="all"?d="all":r.block.includes(",")?d=r.block.split(",").map(u=>u.trim()).filter(u=>u):d=r.block);let p={src:l,blocks:d,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:a||""};return s.push(p),`${a}__IMPORT_${s.length-1}__`}),imports:s}}static processImportBlocks(t,e,s=0,i){if(s>10)return"";let{processed:o,imports:a}=this._processImportBlocks(t),n=o;for(let r=0;r<a.length;r++){let c=a[r],l=`${c.src}|${c.base}|${c.lang||""}|${c.section}|${Array.isArray(c.blocks)?c.blocks.join(","):c.blocks||""}`,d;if(i&&i.has(l))d=i.get(l);else{let u=e(c.src);d=u?this._extractBlock(u,c.blocks,c.base,c.section,c.lang):"",d&&d.includes("<import")&&(d=this.processImportBlocks(d,e,s+1,i)),i&&i.set(l,d)}let p=d.split(`
|
|
6
6
|
`).map((u,m)=>m===0?u:c.indent+u).join(`
|
|
7
|
-
`);n=n.replace(`__IMPORT_${r}__`,p)}return n}};var 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`
|
|
7
|
+
`);n=n.replace(`__IMPORT_${r}__`,p)}return n}};var F=class{static{h(this,"TemplateManager")}_map=new Map;_engine=C;_watcher=[];_pageManager=f;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(t){let{path:e,enableWatch:s=!1}=t;this._path=e,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(t.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let t=0;t<this._path.length;t++){let e=this._path[t];if(!T(e))throw new Error(`Template base path is not exists: ${e}`);if(!w(e).isDirectory())throw new Error(`Template base path is not a directory: ${e}`)}return!0}catch(t){throw new Error(`Failed to validate Template base path: ${String(t)}`)}}_initializeWatcher(t){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let e=0;e<this._path.length;e++){let s=this._path[e],i=lt(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=rt(o,"utf8").filter(r=>this._isValidFile(r));for(let r of n){let c=P(o,r),l=this._getExtension(r),d=this._getKey(r);if(l===".html")t.set(d,_(c,"utf8"));else if(l===".ts"||l===".js"){let p=f.getFileSync(c);p?.template!==void 0&&(t.set(d,p.template),e.push(p))}}}let s=new Map;for(let[i,o]of t.entries())this._compile(i,o,void 0,s,t);t.clear(),s.clear();for(let i of e)i.template=void 0}_loadFile(t){for(let e=0;e<this._path.length;e++){let s=this._path[e],i=P(s,t),o=this._getExtension(t),a=this._getKey(t);if(o==".html"){let n=_(i,"utf8");this._compile(a,n)}else if(o==".ts"||o==".js"){let n=f.getFileSync(i);n?.template!==void 0&&(this._compile(a,n.template),n.template=void 0)}else throw new Error(`File ${t} is not support`)}}_getExtension(t){return j(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let s=j(t).toLowerCase();if(s){let n=P(e,t);if(T(n)&&w(n).isFile()){if(s===".html")return _(n,"utf8");if(s===".ts"||s===".js")try{return f.getFileSync(n)?.template??null}catch{return null}}continue}let i=P(e,`${t}.ts`),o=P(e,`${t}.js`);if(T(i)&&w(i).isFile())try{return f.getFileSync(i)?.template??null}catch{}else if(T(o)&&w(o).isFile())try{return f.getFileSync(i)?.template??null}catch{}let a=P(e,`${t}.html`);if(T(a)&&w(a).isFile())return _(a,"utf8")}return null}_isValidFile(t){return this._supportedExtensions.has(this._getExtension(t))}_getKey(t){return t.replace(/\.[^/.]+$/,"")}_compile(t,e,s,i,o){let a=this._map.get(t),n=a||{},r=!1,c=C.processImportBlocks(e,d=>o&&o.has(d)?o.get(d):this._readTemplateFile(d),0,i),l=C._processBaseBlocks(c);(s===void 0||s?.media===!1||a?.media===void 0)&&(n.media=C.compileMedia(c,l),r=!0),(s===void 0||s?.message===!1||a?.message===void 0)&&(n.message=C.compileMessages(c,l),r=!0),(s===void 0||s?.keyboard===!1||a?.keyboard===void 0)&&(n.keyboard=C.compileKeyboards(c,l),r=!0),(s===void 0||s?.description===!1||a?.description===void 0)&&(n.description=C.compileDescription(c,l),r=!0),r&&this._map.set(t,n)}getMedia(t,e="default",s="default",i){let a=this._map.get(t)?.media?.[e],n=a?.[s]||a?.default;try{if(!n)throw new Error("Media function not found, please check your template");return n(i)}catch{return{}}}getMessage(t,e="default",s="default",i){try{let a=this._map.get(t)?.message?.[e],n=a?.[s]||a?.default;if(!n)throw"";return n(i)}catch{return""}}getDescription(t,e="default",s="default",i="default",o){try{let n=this._map.get(t)?.description?.[e]?.[i],r=n?.[s]||n?.default;if(!r)throw"";return r(o)}catch{return""}}getDescriptionLanguage(t,e="default",s="default"){try{let o=this._map.get(t)?.description?.[e]?.[s];return o?Object.keys(o):[]}catch{return[]}}getDescriptionScopes(t,e="default"){try{let i=this._map.get(t)?.description?.[e];return i?Object.keys(i):[]}catch{return[]}}getKeyboard(t,e="default",s="default",i="inline",o){try{let n=this._map.get(t)?.keyboard?.[e],r=n?.[s]?.[i]||n?.default?.[i];if(!r)throw[];return r(o)}catch{return[]}}async write(t,e){if(this._getExtension(t)!=".html")return null;for(let s=0;s<this._path.length;s++){let i=P(this._path[s],t);if(T(i))return ct(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 mt,webhookCallback as q}from"grammy";var W="0.3.3";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 ht:t.log?t.log:void 0,this.log?.info?.(`Gramstax v${W}`),this.cacheSession=t.cacheSession||new M("memory","session"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new F({path:[pt(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 mt(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=q(this.bot,"bun");this.handlerBotUpdate=s;let i=new URL(t).pathname;e({fetch(n){let{pathname:r}=new URL(n.url);if(n.method=="POST"&&r==i)return s(n);if(n.method=="GET"&&r=="/"){let c=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:c}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}}),(await this.bot.api.getWebhookInfo()).url!=t&&await this.bot.api.setWebhook(t);let a=await this.bot.api.getMe();await this.onStart(a,"webhook",t)}async runServerless(t){this.handlerBotUpdate=q(this.bot,t);let e=await this.bot.api.getMe();await this.onStart(e,"serverless",t)}pageBuildData(t,e){t?.data===void 0&&(t.data=t.buildData()),t.data.name=ut(e).name}pageSorts(t,e){let s=t.data.name,i=t.prototype,o="Payload",a="Command",n="Caption",r="Free",c=e.routeDynamic,l=e.routeDynamicSpesific,d=h(m=>m.charAt(0).toUpperCase()+m.slice(1),"upFirst"),p=h(m=>m.replace(o,"").replace(a,"").replace(n,"").replace(r,""),"getPureRouteName"),u=h((m,g)=>i[`methodSession${d(m)}`]?.(g),"methodSession");e.all[s]=t;for(let m=0;m<e.lenListRouteStaticSession;m++){let g=e.listRouteStaticSession[m];if(typeof i[g]!="function")continue;let b=e.routeStatic[g],v=e.routeStaticIntent[g],k=e.routeStaticSession[g],S={name:s,routeName:g},$=b||v;if($!==void 0){let Y=g.includes(a),Z=g.includes("callback"),tt=g.startsWith("text"),x;if(Y){let B=t.data.textCommand||t.data.name;x=B?`/${B}`:void 0}else Z?x=t.data.name:tt?x=t.data.text||t.data.name:x=t.data.name;x&&($[x]=S)}k!==void 0&&(k[u(g,s)]=S),g.toLowerCase().endsWith("free")&&l[p(g)].push(S)}i.free&&c.push(s)}async executeSyncBlocksDescription(t){let e=new Map,s=t.routeStatic.textCommand;for(let[,i]of Object.entries(s)){let o=i.name,a=this.templateManager.getDescriptionScopes(o);for(let n of a){e.has(n)||e.set(n,new Set);let r=this.templateManager.getDescriptionLanguage(o,"default",n);for(let c of r)e.get(n).add(c)}}for(let[i,o]of e)for(let a of o){let n=[];for(let[,l]of Object.entries(s)){let d=l.name,p=this.templateManager.getDescription(d,"default",a,i);p&&n.push({command:d,description:p})}if(n.length===0)continue;let r={type:i},c=a==="default"?void 0:a;try{let l=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(l.map(u=>({command:u.command,description:u.description})).sort((u,m)=>u.command.localeCompare(m.command))),p=JSON.stringify(n.sort((u,m)=>u.command.localeCompare(m.command)));d!==p&&(await this.bot.api.setMyCommands(n,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${i},${c?` lang: ${c},`:""} total (${n.length})`))}catch(l){this.log?.error?.(`Failed to sync descriptions for scope: ${i},${c?` lang: ${c},`:""} error: ${String(l)}`)}}}pageLoads(){this.log?.info?.("Load pages..");let t=["callback","text","textCommand","photoCaption","photoCaptionCommand","videoCaption","videoCaptionCommand","audioCaption","audioCaptionCommand","documentCaption","documentCaptionCommand","animationCaption","animationCaptionCommand","voiceCaption","voiceCaptionCommand","videoNoteCaption","videoNoteCaptionCommand"],e=["callbackPayload","textPayload","textCommandPayload","photoCaptionPayload","photoCaptionCommandPayload","videoCaptionPayload","videoCaptionCommandPayload","audioCaptionPayload","audioCaptionCommandPayload","documentCaptionPayload","documentCaptionCommandPayload","animationCaptionPayload","animationCaptionCommandPayload","voiceCaptionPayload","voiceCaptionCommandPayload","videoNoteCaptionPayload","videoNoteCaptionCommandPayload"],s=[...t,...e,"textFree","photoFree","videoFree","audioFree","documentFree","animationFree","voiceFree","videoNoteFree","stickerFree","locationFree","contactFree"],i=h((n,r)=>Object.fromEntries(n.map(c=>[c,r()])),"makeObject"),o=h(()=>[],"initDynamicSpesific"),a={all:{},routeDynamic:[],routeDynamicSpesific:{text:o(),photo:o(),video:o(),audio:o(),document:o(),animation:o(),voice:o(),videoNote:o(),sticker:o(),location:o(),contact:o()},routeStatic:i(t,()=>({})),routeStaticIntent:i(e,()=>({})),routeStaticSession:i(s,()=>({})),listRouteStatic:t,listRouteStaticIntent:e,listRouteStaticSession:s,lenListRouteStatic:t.length,lenListRouteStaticIntent:e.length,lenListRouteStaticSession:s.length};return f.getFileManySync(void 0).forEach(({path:n,page:r})=>{this.pageBuildData(r,n),this.pageSorts(r,a),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(a.all).length})`),a}async pageRoutes(t,e){let s,i;if(s===void 0){let a=t.callbackData,n=t.msgText,r=t.msgCaption,c=this.pages.routeStatic;for(let l=0;l<this.pages.lenListRouteStatic;l++){let d=this.pages.listRouteStatic[l];if(d.startsWith(e)&&(i=c[d][a||n||r]),i)break}i!==void 0&&(s=this.pages.all[i.name])}if(s===void 0){let a=await t.sessionGet();if(a){let n=a.method,r=this.pages.routeStaticSession;for(let c=0;c<this.pages.lenListRouteStaticSession;c++){let l=this.pages.listRouteStaticSession[c];if(l.startsWith(e)&&(i=r[l][n]),i)break}i!==void 0&&(s=this.pages.all[i.name])}}if(s===void 0){let a=this.pages.routeStaticIntent,n=e==="callback",r=n?t.callbackData:t.msgText||t.msgCaption;if(r)for(let c=0;c<this.pages.lenListRouteStaticIntent;c++){let l=this.pages.listRouteStaticIntent[c];if(l.startsWith(e)){let d=a[l];i=d[t.intent(r,n?"colon":"space",1)],!i&&!n&&(i=d[t.intent(r,"space",2)])}if(i)break}i!==void 0&&(s=this.pages.all[i.name])}if(s!==void 0&&i!==void 0)return s.prototype[i.routeName]?await new s(t)[i.routeName]?.():void 0;let o=this.pages.routeDynamicSpesific[e]||[];for(let a=0;a<o.length;a++){let n=o[a];if(n===void 0)continue;let r=this.pages.all[n.name];if(r===void 0||!r.prototype[n.routeName])continue;let l=await new r(t)[n.routeName]?.();if(l!==null)return l}for(let a=0;a<this.pages.routeDynamic.length;a++){let n=this.pages.routeDynamic[a];if(n===void 0)continue;let r=this.pages.all[n];if(r===void 0||!r.prototype.free)continue;let l=await new r(t).free?.();if(l!==null)return l}return null}async hookBeforeRoute(t,e){return!!(t||e)}async hookErrorPage(t,e,s,i){}async hookErrorInputNotFoundPage(t){}async onMessage(t,e){let s=this.createCtx(t);try{if(await this.hookBeforeRoute(s,e)===!1)return;await this.pageRoutes(s,e)===null&&await this.hookErrorInputNotFoundPage(s)}catch(i){await this.hookErrorPage(s,e,i,!1)}}async onCallbackQueryData(t){let e=this.createCtx(t);try{if(await e.callbackQueryAnswer(),await this.hookBeforeRoute(e,"onCallbackQueryData")===!1)return;await this.pageRoutes(e,"callback")}catch(s){await this.hookErrorPage(e,"onCallbackQueryData",s,!0)}}async onMessageText(t){await this.onMessage(t,"text")}async onMessagePhoto(t){await this.onMessage(t,"photo")}async onMessageVideo(t){await this.onMessage(t,"video")}async onMessageAudio(t){await this.onMessage(t,"audio")}async onMessageDocument(t){await this.onMessage(t,"document")}async onMessageAnimation(t){await this.onMessage(t,"animation")}async onMessageVoice(t){await this.onMessage(t,"voice")}async onMessageVideoNote(t){await this.onMessage(t,"videoNote")}async onMessageSticker(t){await this.onMessage(t,"sticker")}async onMessageLocation(t){await this.onMessage(t,"location")}async onMessageContact(t){await this.onMessage(t,"contact")}registerOnCallbackQueryData(){this.bot.on("callback_query:data",this.onCallbackQueryData.bind(this))}registerOnMessageText(){this.bot.on("message:text",this.onMessageText.bind(this))}registerOnMessagePhoto(){this.bot.on("message:photo",this.onMessagePhoto.bind(this))}registerOnMessageVideo(){this.bot.on("message:video",this.onMessageVideo.bind(this))}registerOnMessageAudio(){this.bot.on("message:audio",this.onMessageAudio.bind(this))}registerOnMessageDocument(){this.bot.on("message:document",this.onMessageDocument.bind(this))}registerOnMessageAnimation(){this.bot.on("message:animation",this.onMessageAnimation.bind(this))}registerOnMessageVoice(){this.bot.on("message:voice",this.onMessageVoice.bind(this))}registerOnMessageVideoNote(){this.bot.on("message:video_note",this.onMessageVideoNote.bind(this))}registerOnMessageSticker(){this.bot.on("message:sticker",this.onMessageSticker.bind(this))}registerOnMessageLocation(){this.bot.on("message:location",this.onMessageLocation.bind(this))}registerOnMessageContact(){this.bot.on("message:contact",this.onMessageContact.bind(this))}};import{Worker as gt,isMainThread as yt}from"worker_threads";var V=class{constructor(t,e){this.path=t;this.argv=e;if(!yt)throw new Error("Is not main thread");this.sub=new gt(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 J=class{static{h(this,"ThreadExport")}static init(t){let{CSub:e,CMain:s=V,path:i,wrap:o}=t,a=`for-${i}`;if(process.argv[2]===a)return new e,{};let n,r=new Proxy({},{get(d,p){return p==="sendRequest"?(u,m,g=!0)=>{if(!n)throw new Error(`Thread at ${i} not launched yet.`);return n.sendRequest(u,m,g)}:(...u)=>{if(!n)throw new Error(`Thread at ${i} not launched yet.`);return n.sendRequest(p,u)}}});return{...o?o(r):{},launch:h((d=[])=>(n=new s(i,[a,...d]),n),"launch")}}};var U=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 G,threadId as bt,isMainThread as ft}from"worker_threads";var H=class{static{h(this,"ThreadSub")}map=new Map;argv=process.argv;id=bt;pid=process.pid;threadIsMain=ft;constructor(){if(this.threadIsMain)throw new Error("Is not sub thread");G.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){G.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 z=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 X=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{M as CacheExternal,z as ComponentKeyboard,I as Ctx,X as DataKeyboard,Q as Gramstax,D as LoggingUtils,C as TemplateEngine,F as TemplateManager,J as ThreadExport,V as ThreadMain,U as ThreadMainPool,H as ThreadSub,Pt as log};
|