gramstax 0.3.11 → 0.3.13
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 +11 -11
- package/dist/src/index.d.cts +74 -72
- package/dist/src/index.d.ts +74 -72
- package/dist/src/index.js +10 -10
- package/package.json +1 -1
package/dist/src/index.cjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
"use strict";var ht=Object.create;var V=Object.defineProperty;var mt=Object.getOwnPropertyDescriptor;var gt=Object.getOwnPropertyNames;var yt=Object.getPrototypeOf,bt=Object.prototype.hasOwnProperty;var h=(m,t)=>V(m,"name",{value:t,configurable:!0});var ft=(m,t)=>{for(var e in t)V(m,e,{get:t[e],enumerable:!0})},X=(m,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of gt(t))!bt.call(m,s)&&s!==e&&V(m,s,{get:()=>t[s],enumerable:!(i=mt(t,s))||i.enumerable});return m};var Y=(m,t,e)=>(e=m!=null?ht(yt(m)):{},X(t||!m||!m.__esModule?V(e,"default",{value:m,enumerable:!0}):e,m)),Ct=m=>X(V({},"__esModule",{value:!0}),m);var wt={};ft(wt,{CacheExternal:()=>D,ComponentKeyboard:()=>Q,Ctx:()=>A,DataKeyboard:()=>J,Gramstax:()=>j,LoggingUtils:()=>K,TemplateEngine:()=>k,TemplateManager:()=>O,WorkerThreadExport:()=>q,WorkerThreadGatewayClient:()=>N,WorkerThreadGatewayServer:()=>B,WorkerThreadInit:()=>U,WorkerThreadLaunch:()=>$,WorkerThreadPool:()=>G,log:()=>Pt});module.exports=Ct(wt);var St=h(()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,"getImportMetaUrl"),f=St();var Z=require("logging-pretty");var K=class extends Z.LoggingPretty{static{h(this,"LoggingUtils")}constructor(t){super(t)}errorMake(t,e,i){this.error(`[${e?.name||e}:${i}] ${String(t)}`)}},Pt=new K;var tt=require("keyv"),et=Y(require("@keyv/redis"),1);var D=class extends tt.Keyv{constructor(e="memory",i,s,o){let a;e.startsWith("redis")&&(a=new et.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 st=require("timers/promises"),_=require("grammy");var A=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||this.temp?.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,st.setTimeout)(1200)}}catch(r){if(n)throw r}}async reply(t,e,i,s){let o=this.templateManager.getMessage(this.data.name,i,this.userLanguage,e);return await this.ct.reply(o,{parse_mode:"HTML",reply_markup:t,...s})}async replyMedia(t,e,i,s,o){let a=this.templateManager.getMedia(this.data.name,s,this.userLanguage,i),n={parse_mode:"HTML",reply_markup:e,...o};if(t=="photo")return await this.ct.replyWithPhoto(a.src,{caption:a.caption,...n});if(t=="video")return await this.ct.replyWithVideo(a.src,{caption:a.caption,...n});if(t=="audio")return await this.ct.replyWithAudio(a.src,{caption:a.caption,...n});if(t=="document")return await this.ct.replyWithDocument(a.src,{caption:a.caption,...n});if(t=="animation")return await this.ct.replyWithAnimation(a.src,{caption:a.caption,...n});if(t=="voice")return await this.ct.replyWithVoice(a.src,n);if(t=="video_note")return await this.ct.replyWithVideoNote(a.src,n);if(t=="sticker")return await this.ct.replyWithSticker(a.src,n);if(t=="location")return await this.ct.replyWithLocation(parseInt(a.latitude),parseInt(a.longitude),n);if(t=="contact")return await this.ct.replyWithContact(a.phone,a.first_name,{vcard:a.vcard,...n})}async replyPhoto(t,e,i,s){return this.replyMedia("photo",t,e,i,s)}async replyVideo(t,e,i,s){return this.replyMedia("video",t,e,i,s)}async replyAudio(t,e,i,s){return this.replyMedia("audio",t,e,i,s)}async replyDocument(t,e,i,s){return this.replyMedia("document",t,e,i,s)}async replyAnimation(t,e,i,s){return this.replyMedia("animation",t,e,i,s)}async replyVoice(t,e,i,s){return this.replyMedia("voice",t,e,i,s)}async replyVideoNote(t,e,i,s){return this.replyMedia("video_note",t,e,i,s)}async replySticker(t,e,i,s){return this.replyMedia("sticker",t,e,i,s)}async replyLocation(t,e,i,s){return this.replyMedia("location",t,e,i,s)}async replyContact(t,e,i,s){return this.replyMedia("contact",t,e,i,s)}async replyAction(t){return await this.ct.replyWithChatAction(t)}async edit(t,e,i,s,o=!0){try{let a=this.templateManager.getMessage(this.data.name,i,this.userLanguage,e);return await this.ct.editMessageText(a,{parse_mode:"HTML",reply_markup:t,...s})}catch(a){if(o)await this.reply(t,e,i,s);else throw a}}async editMedia(t,e,i,s,o,a,n=!0){try{let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,s,this.userLanguage,i);return t=="voice"?(await this.delete(),await this.replyVoice(e,i,s,o)):t=="video_note"?(await this.delete(),await this.replyVoice(e,i,s,o)):t=="sticker"?(await this.delete(),await this.replySticker(e,i,s,o)):t=="location"?(await this.delete(),await this.replyLocation(e,i,s,o)):t=="contact"?(await this.delete(),await this.replyContact(e,i,s,o)):await this.ct.editMessageMedia({media:r,caption:c,type:t,parse_mode:"HTML",...o},{reply_markup:e,...a})}catch(r){if(n===!0)await this.reply(e,i,s,a);else throw r}}async editPhoto(t,e,i,s,o){return await this.editMedia("photo",t,e,i,s,o)}async editVideo(t,e,i,s,o){return await this.editMedia("video",t,e,i,s,o)}async editAudio(t,e,i,s,o){return await this.editMedia("audio",t,e,i,s,o)}async editDocument(t,e,i,s,o){return await this.editMedia("document",t,e,i,s,o)}async editAnimation(t,e,i,s,o){return await this.editMedia("animation",t,e,i,s,o)}async editVoice(t,e,i,s){return await this.editMedia("voice",t,e,i,s)}async editVideoNote(t,e,i,s){return await this.editMedia("video_note",t,e,i,s)}async editSticker(t,e,i,s){return await this.editMedia("sticker",t,e,i,s)}async editLocation(t,e,i,s){return await this.editMedia("location",t,e,i,s)}async editContact(t,e,i,s){return await this.editMedia("contact",t,e,i,s)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(t){try{return await this.ct.answerCallbackQuery(t)}catch{return null}}async sessionSet(t,e,i){try{let s={method:t,params:e,...i},o=await this.cacheSession.set(`${this.userId}`,s);return o&&(this.session=s),o}catch{return null}}async sessionGet(){try{let t=await this.cacheSession.get(`${this.userId}`);return t&&(this.session=t),t||null}catch{return null}}async sessionClear(){try{let t=await this.cacheSession.delete(`${this.userId}`);return t&&(this.session={}),t}catch{return null}}static buildData(t){let i=typeof t=="function"?{callbackData:t}:t||{},s=i.callbackData;return{name:"",text:i.text,textCommand:i.textCommand,_positionPayloadText:i.text?i.text.split(this.prototype.seperatorTag("space")).length:void 0,callbackData:s?function(...a){let n=s(...a);return`${this.name}${n==""||n===void 0?"":`:${n}`}`}:function(){return this?.name}}}inlineKeyboard(t,e){let i=this.data.name;if(e?.cache===!0){let n=`${i}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(n);if(!r){let c=new _.InlineKeyboard,l=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"inline",e?.data),d=t(c,l);return this.cacheKeyboard.set(n,d),d}return r}let s=new _.InlineKeyboard,o=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"inline",e?.data);return t(s,o)}bottomKeyboard(t,e){let i=this.data.name;if(e?.cache===!0){let n=`${i}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(n);if(!r){let c=new _.Keyboard,l=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"bottom",e?.data),d=t(c,l);return d.resized(!0),this.cacheKeyboard.set(n,d),d}return r}let s=new _.Keyboard,o=this.templateManager.getKeyboard(i,e?.baseId,this.userLanguage,"bottom",e?.data),a=t(s,o);return a.resized(),a}seperatorTag(t="space"){return t=="space"?" ":":"}payloads(t="",e,i=1){let s=this.seperatorTag(e);return t?t.split(s).slice(i):[]}intent(t="",e,i=1){let s=this.seperatorTag(e);if(!t)return"";let o=t.split(s);return i==1?o[0]:o.slice(0,i).join(s)}validateSessionCallback(t,e){return(t??this.session.method)===this.methodSessionCallback(e)}validateSessionCallbackPayload(t,e){return(t??this.session.method)===this.methodSessionCallbackPayload(e)}validateSessionText(t,e){return(t??this.session.method)===this.methodSessionText(e)}validateSessionTextPayload(t,e){return(t??this.session.method)===this.methodSessionTextPayload(e)}validateSessionTextCommand(t,e){return(t??this.session.method)===this.methodSessionTextCommand(e)}validateSessionTextCommandPayload(t,e){return(t??this.session.method)===this.methodSessionTextCommandPayload(e)}validateSessionTextFree(t,e){return(t??this.session.method)===this.methodSessionTextFree(e)}validateSessionPhotoCaption(t,e){return(t??this.session.method)===this.methodSessionPhotoCaption(e)}validateSessionPhotoCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionPayload(e)}validateSessionPhotoCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionCommand(e)}validateSessionPhotoCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionCommandPayload(e)}validateSessionPhotoFree(t,e){return(t??this.session.method)===this.methodSessionPhotoFree(e)}validateSessionVideoCaption(t,e){return(t??this.session.method)===this.methodSessionVideoCaption(e)}validateSessionVideoCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionPayload(e)}validateSessionVideoCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionCommand(e)}validateSessionVideoCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionCommandPayload(e)}validateSessionVideoFree(t,e){return(t??this.session.method)===this.methodSessionVideoFree(e)}validateSessionAudioCaption(t,e){return(t??this.session.method)===this.methodSessionAudioCaption(e)}validateSessionAudioCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionPayload(e)}validateSessionAudioCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionCommand(e)}validateSessionAudioCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionCommandPayload(e)}validateSessionAudioFree(t,e){return(t??this.session.method)===this.methodSessionAudioFree(e)}validateSessionDocumentCaption(t,e){return(t??this.session.method)===this.methodSessionDocumentCaption(e)}validateSessionDocumentCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionPayload(e)}validateSessionDocumentCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionCommand(e)}validateSessionDocumentCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionCommandPayload(e)}validateSessionDocumentFree(t,e){return(t??this.session.method)===this.methodSessionDocumentFree(e)}validateSessionAnimationCaption(t,e){return(t??this.session.method)===this.methodSessionAnimationCaption(e)}validateSessionAnimationCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionPayload(e)}validateSessionAnimationCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionCommand(e)}validateSessionAnimationCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionCommandPayload(e)}validateSessionAnimationFree(t,e){return(t??this.session.method)===this.methodSessionAnimationFree(e)}validateSessionVoiceCaption(t,e){return(t??this.session.method)===this.methodSessionVoiceCaption(e)}validateSessionVoiceCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionPayload(e)}validateSessionVoiceCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionCommand(e)}validateSessionVoiceCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionCommandPayload(e)}validateSessionVoiceFree(t,e){return(t??this.session.method)===this.methodSessionVoiceFree(e)}validateSessionVideoNoteCaption(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaption(e)}validateSessionVideoNoteCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionPayload(e)}validateSessionVideoNoteCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionCommand(e)}validateSessionVideoNoteCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVideoNoteCaptionCommandPayload(e)}validateSessionVideoNoteFree(t,e){return(t??this.session.method)===this.methodSessionVideoNoteFree(e)}validateSessionStickerFree(t,e){return(t??this.session.method)===this.methodSessionStickerFree(e)}validateSessionLocationFree(t,e){return(t??this.session.method)===this.methodSessionLocationFree(e)}validateSessionContactFree(t,e){return(t??this.session.method)===this.methodSessionContactFree(e)}sessionCallback(t,e){return this.sessionSet(this.methodSessionCallback(e),t)}sessionCallbackPayload(t,e){return this.sessionSet(this.methodSessionCallbackPayload(e),t)}sessionText(t,e){return this.sessionSet(this.methodSessionText(e),t)}sessionTextPayload(t,e){return this.sessionSet(this.methodSessionTextPayload(e),t)}sessionTextCommand(t,e){return this.sessionSet(this.methodSessionTextCommand(e),t)}sessionTextCommandPayload(t,e){return this.sessionSet(this.methodSessionTextCommandPayload(e),t)}sessionTextFree(t,e){return this.sessionSet(this.methodSessionTextFree(e),t)}sessionPhotoCaption(t,e){return this.sessionSet(this.methodSessionPhotoCaption(e),t)}sessionPhotoCaptionPayload(t,e){return this.sessionSet(this.methodSessionPhotoCaptionPayload(e),t)}sessionPhotoCaptionCommand(t,e){return this.sessionSet(this.methodSessionPhotoCaptionCommand(e),t)}sessionPhotoCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionPhotoCaptionCommandPayload(e),t)}sessionPhotoFree(t,e){return this.sessionSet(this.methodSessionPhotoFree(e),t)}sessionVideoCaption(t,e){return this.sessionSet(this.methodSessionVideoCaption(e),t)}sessionVideoCaptionPayload(t,e){return this.sessionSet(this.methodSessionVideoCaptionPayload(e),t)}sessionVideoCaptionCommand(t,e){return this.sessionSet(this.methodSessionVideoCaptionCommand(e),t)}sessionVideoCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVideoCaptionCommandPayload(e),t)}sessionVideoFree(t,e){return this.sessionSet(this.methodSessionVideoFree(e),t)}sessionAudioCaption(t,e){return this.sessionSet(this.methodSessionAudioCaption(e),t)}sessionAudioCaptionPayload(t,e){return this.sessionSet(this.methodSessionAudioCaptionPayload(e),t)}sessionAudioCaptionCommand(t,e){return this.sessionSet(this.methodSessionAudioCaptionCommand(e),t)}sessionAudioCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionAudioCaptionCommandPayload(e),t)}sessionAudioFree(t,e){return this.sessionSet(this.methodSessionAudioFree(e),t)}sessionDocumentCaption(t,e){return this.sessionSet(this.methodSessionDocumentCaption(e),t)}sessionDocumentCaptionPayload(t,e){return this.sessionSet(this.methodSessionDocumentCaptionPayload(e),t)}sessionDocumentCaptionCommand(t,e){return this.sessionSet(this.methodSessionDocumentCaptionCommand(e),t)}sessionDocumentCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionDocumentCaptionCommandPayload(e),t)}sessionDocumentFree(t,e){return this.sessionSet(this.methodSessionDocumentFree(e),t)}sessionAnimationCaption(t,e){return this.sessionSet(this.methodSessionAnimationCaption(e),t)}sessionAnimationCaptionPayload(t,e){return this.sessionSet(this.methodSessionAnimationCaptionPayload(e),t)}sessionAnimationCaptionCommand(t,e){return this.sessionSet(this.methodSessionAnimationCaptionCommand(e),t)}sessionAnimationCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionAnimationCaptionCommandPayload(e),t)}sessionAnimationFree(t,e){return this.sessionSet(this.methodSessionAnimationFree(e),t)}sessionVoiceCaption(t,e){return this.sessionSet(this.methodSessionVoiceCaption(e),t)}sessionVoiceCaptionPayload(t,e){return this.sessionSet(this.methodSessionVoiceCaptionPayload(e),t)}sessionVoiceCaptionCommand(t,e){return this.sessionSet(this.methodSessionVoiceCaptionCommand(e),t)}sessionVoiceCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVoiceCaptionCommandPayload(e),t)}sessionVoiceFree(t,e){return this.sessionSet(this.methodSessionVoiceFree(e),t)}sessionVideoNoteCaption(t,e){return this.sessionSet(this.methodSessionVideoNoteCaption(e),t)}sessionVideoNoteCaptionPayload(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionPayload(e),t)}sessionVideoNoteCaptionCommand(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionCommand(e),t)}sessionVideoNoteCaptionCommandPayload(t,e){return this.sessionSet(this.methodSessionVideoNoteCaptionCommandPayload(e),t)}sessionVideoNoteFree(t,e){return this.sessionSet(this.methodSessionVideoNoteFree(e),t)}sessionStickerFree(t,e){return this.sessionSet(this.methodSessionStickerFree(e),t)}sessionLocationFree(t,e){return this.sessionSet(this.methodSessionLocationFree(e),t)}sessionContactFree(t,e){return this.sessionSet(this.methodSessionContactFree(e),t)}sessionToCallback(t,e){return this.sessionCallback({...this.session.params,...t},e)}sessionToCallbackPayload(t,e){return this.sessionCallbackPayload({...this.session.params,...t},e)}sessionToText(t,e){return this.sessionText({...this.session.params,...t},e)}sessionToTextPayload(t,e){return this.sessionTextPayload({...this.session.params,...t},e)}sessionToTextCommand(t,e){return this.sessionTextCommand({...this.session.params,...t},e)}sessionToTextCommandPayload(t,e){return this.sessionTextCommandPayload({...this.session.params,...t},e)}sessionToTextFree(t,e){return this.sessionTextFree({...this.session.params,...t},e)}sessionToPhotoCaption(t,e){return this.sessionPhotoCaption({...this.session.params,...t},e)}sessionToPhotoCaptionPayload(t,e){return this.sessionPhotoCaptionPayload({...this.session.params,...t},e)}sessionToPhotoCaptionCommand(t,e){return this.sessionPhotoCaptionCommand({...this.session.params,...t},e)}sessionToPhotoCaptionCommandPayload(t,e){return this.sessionPhotoCaptionCommandPayload({...this.session.params,...t},e)}sessionToPhotoFree(t,e){return this.sessionPhotoFree({...this.session.params,...t},e)}sessionToVideoCaption(t,e){return this.sessionVideoCaption({...this.session.params,...t},e)}sessionToVideoCaptionPayload(t,e){return this.sessionVideoCaptionPayload({...this.session.params,...t},e)}sessionToVideoCaptionCommand(t,e){return this.sessionVideoCaptionCommand({...this.session.params,...t},e)}sessionToVideoCaptionCommandPayload(t,e){return this.sessionVideoCaptionCommandPayload({...this.session.params,...t},e)}sessionToVideoFree(t,e){return this.sessionVideoFree({...this.session.params,...t},e)}sessionToAudioCaption(t,e){return this.sessionAudioCaption({...this.session.params,...t},e)}sessionToAudioCaptionPayload(t,e){return this.sessionAudioCaptionPayload({...this.session.params,...t},e)}sessionToAudioCaptionCommand(t,e){return this.sessionAudioCaptionCommand({...this.session.params,...t},e)}sessionToAudioCaptionCommandPayload(t,e){return this.sessionAudioCaptionCommandPayload({...this.session.params,...t},e)}sessionToAudioFree(t,e){return this.sessionAudioFree({...this.session.params,...t},e)}sessionToDocumentCaption(t,e){return this.sessionDocumentCaption({...this.session.params,...t},e)}sessionToDocumentCaptionPayload(t,e){return this.sessionDocumentCaptionPayload({...this.session.params,...t},e)}sessionToDocumentCaptionCommand(t,e){return this.sessionDocumentCaptionCommand({...this.session.params,...t},e)}sessionToDocumentCaptionCommandPayload(t,e){return this.sessionDocumentCaptionCommandPayload({...this.session.params,...t},e)}sessionToDocumentFree(t,e){return this.sessionDocumentFree({...this.session.params,...t},e)}sessionToAnimationCaption(t,e){return this.sessionAnimationCaption({...this.session.params,...t},e)}sessionToAnimationCaptionPayload(t,e){return this.sessionAnimationCaptionPayload({...this.session.params,...t},e)}sessionToAnimationCaptionCommand(t,e){return this.sessionAnimationCaptionCommand({...this.session.params,...t},e)}sessionToAnimationCaptionCommandPayload(t,e){return this.sessionAnimationCaptionCommandPayload({...this.session.params,...t},e)}sessionToAnimationFree(t,e){return this.sessionAnimationFree({...this.session.params,...t},e)}sessionToVoiceCaption(t,e){return this.sessionVoiceCaption({...this.session.params,...t},e)}sessionToVoiceCaptionPayload(t,e){return this.sessionVoiceCaptionPayload({...this.session.params,...t},e)}sessionToVoiceCaptionCommand(t,e){return this.sessionVoiceCaptionCommand({...this.session.params,...t},e)}sessionToVoiceCaptionCommandPayload(t,e){return this.sessionVoiceCaptionCommandPayload({...this.session.params,...t},e)}sessionToVoiceFree(t,e){return this.sessionVoiceFree({...this.session.params,...t},e)}sessionToVideoNoteCaption(t,e){return this.sessionVideoNoteCaption({...this.session.params,...t},e)}sessionToVideoNoteCaptionPayload(t,e){return this.sessionVideoNoteCaptionPayload({...this.session.params,...t},e)}sessionToVideoNoteCaptionCommand(t,e){return this.sessionVideoNoteCaptionCommand({...this.session.params,...t},e)}sessionToVideoNoteCaptionCommandPayload(t,e){return this.sessionVideoNoteCaptionCommandPayload({...this.session.params,...t},e)}sessionToVideoNoteFree(t,e){return this.sessionVideoNoteFree({...this.session.params,...t},e)}sessionToStickerFree(t,e){return this.sessionStickerFree({...this.session.params,...t},e)}sessionToLocationFree(t,e){return this.sessionLocationFree({...this.session.params,...t},e)}sessionToContactFree(t,e){return this.sessionContactFree({...this.session.params,...t},e)}methodSession(t,e){return`${t}-${e||this.data.name}`}methodSessionCallback(t){return this.methodSession("1",t)}methodSessionCallbackPayload(t){return this.methodSession("2",t)}methodSessionText(t){return this.methodSession("3",t)}methodSessionTextPayload(t){return this.methodSession("4",t)}methodSessionTextCommand(t){return this.methodSession("5",t)}methodSessionTextCommandPayload(t){return this.methodSession("6",t)}methodSessionTextFree(t){return this.methodSession("7",t)}methodSessionPhotoCaption(t){return this.methodSession("8",t)}methodSessionPhotoCaptionPayload(t){return this.methodSession("9",t)}methodSessionPhotoCaptionCommand(t){return this.methodSession("10",t)}methodSessionPhotoCaptionCommandPayload(t){return this.methodSession("11",t)}methodSessionPhotoFree(t){return this.methodSession("12",t)}methodSessionVideoCaption(t){return this.methodSession("13",t)}methodSessionVideoCaptionPayload(t){return this.methodSession("14",t)}methodSessionVideoCaptionCommand(t){return this.methodSession("15",t)}methodSessionVideoCaptionCommandPayload(t){return this.methodSession("16",t)}methodSessionVideoFree(t){return this.methodSession("17",t)}methodSessionAudioCaption(t){return this.methodSession("18",t)}methodSessionAudioCaptionPayload(t){return this.methodSession("19",t)}methodSessionAudioCaptionCommand(t){return this.methodSession("20",t)}methodSessionAudioCaptionCommandPayload(t){return this.methodSession("21",t)}methodSessionAudioFree(t){return this.methodSession("22",t)}methodSessionDocumentCaption(t){return this.methodSession("23",t)}methodSessionDocumentCaptionPayload(t){return this.methodSession("24",t)}methodSessionDocumentCaptionCommand(t){return this.methodSession("25",t)}methodSessionDocumentCaptionCommandPayload(t){return this.methodSession("26",t)}methodSessionDocumentFree(t){return this.methodSession("27",t)}methodSessionAnimationCaption(t){return this.methodSession("28",t)}methodSessionAnimationCaptionPayload(t){return this.methodSession("29",t)}methodSessionAnimationCaptionCommand(t){return this.methodSession("30",t)}methodSessionAnimationCaptionCommandPayload(t){return this.methodSession("31",t)}methodSessionAnimationFree(t){return this.methodSession("32",t)}methodSessionVoiceCaption(t){return this.methodSession("33",t)}methodSessionVoiceCaptionPayload(t){return this.methodSession("34",t)}methodSessionVoiceCaptionCommand(t){return this.methodSession("35",t)}methodSessionVoiceCaptionCommandPayload(t){return this.methodSession("36",t)}methodSessionVoiceFree(t){return this.methodSession("37",t)}methodSessionVideoNoteCaption(t){return this.methodSession("38",t)}methodSessionVideoNoteCaptionPayload(t){return this.methodSession("39",t)}methodSessionVideoNoteCaptionCommand(t){return this.methodSession("40",t)}methodSessionVideoNoteCaptionCommandPayload(t){return this.methodSession("41",t)}methodSessionVideoNoteFree(t){return this.methodSession("42",t)}methodSessionStickerFree(t){return this.methodSession("43",t)}methodSessionLocationFree(t){return this.methodSession("44",t)}methodSessionContactFree(t){return this.methodSession("45",t)}};var w=require("path"),ot=require("fs"),at=require("url");var E=require("path"),F=require("fs"),it=require("module");var P=class{static{h(this,"PageManager")}static _getFile(t,e,i=0){let o=Object.values(t)[i];if(o===void 0)throw new Error(`File ${e} must have export (not default) class page`);return o}static getFilePath(){return(0,E.join)(process.cwd(),"src","pages")}static getFileSync(t,e=0){t||(t=this.getFilePath());let s=(0,it.createRequire)(t)(t);return this._getFile(s,t,e)}static async getFile(t,e=0){t||(t=this.getFilePath());let i=await import(`${t}?t=${Date.now()}`);return this._getFile(i,t,e)}static getFileManySync(t,e=0){if(t||(t=this.getFilePath()),!(0,F.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,F.readdirSync)(t).map(s=>{let o=(0,E.join)(t,s);return{path:o,page:this.getFileSync(o,e)}})}static clearCacheRequire(t){if(t||(t=this.getFilePath()),!(0,F.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,F.readdirSync)(t).forEach(i=>{let s=(0,E.join)(t,i);delete require.cache[require.resolve(s)]}),!0}};var rt=require("logging-pretty");var C=require("path"),y=require("fs"),nt=require("chokidar");var k=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,g]of Object.entries(l))p[u]=g(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(g=>g.replace(/\\,/g,",").trim()).map(g=>this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(g))))));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 g of n.matchAll(u)){let b=g[2];if(o){let S=/lang="([^"]*)"/i,x=b?.match(S);if(((x?x[1]:void 0)||"default")!==o)continue}l.push({start:g.index,content:g[0],innerContent:g[3]??""})}}l.sort((p,u)=>p.start-u.start);let d=h(p=>{let u=p.split(`
|
|
2
|
-
`);if(
|
|
3
|
-
`).trim()},"processResult");return
|
|
4
|
-
`):
|
|
5
|
-
`)}return
|
|
6
|
-
`).map((u
|
|
7
|
-
`);n=n.replace(`__IMPORT_${r}__`,p)}return n}};var O=class{static{h(this,"TemplateManager")}_map=new Map;_engine=k;_watcher=[];_pageManager=P;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(t){let{path:e,enableWatch:i=!1}=t;this._path=e,this._isWatchEnabled=i,this._validatePath(),this._initializeWatcher(t.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let t=0;t<this._path.length;t++){let e=this._path[t];if(!(0,y.existsSync)(e))throw new Error(`Template base path is not exists: ${e}`);if(!(0,y.statSync)(e).isDirectory())throw new Error(`Template base path is not a directory: ${e}`)}return!0}catch(t){throw new Error(`Failed to validate Template base path: ${String(t)}`)}}_initializeWatcher(t){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let e=0;e<this._path.length;e++){let i=this._path[e],s=(0,nt.watch)(i,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...t});this._watcher[e]=s,s.on("change",this._handleFileChange.bind(this)),s.on("add",this._handleFileAdd.bind(this)),s.on("unlink",this._handleFileDelete.bind(this)),s.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(t){let e=(0,C.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileAdd(t){let e=(0,C.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileDelete(t){let e=(0,C.basename)(t),i=this._getKey(e);this._map.has(i)&&this._map.delete(i)}_handleWatchError(t){}_loadAllFiles(){let t=new Map,e=[];for(let s=0;s<this._path.length;s++){let o=this._path[s],n=(0,y.readdirSync)(o,"utf8").filter(r=>this._isValidFile(r));for(let r of n){let c=(0,C.join)(o,r),l=this._getExtension(r),d=this._getKey(r);if(l===".html")t.set(d,(0,y.readFileSync)(c,"utf8"));else if(l===".ts"||l===".js"){let p=P.getFileSync(c);p?.template!==void 0&&(t.set(d,p.template),e.push(p))}}}let i=new Map;for(let[s,o]of t.entries())this._compile(s,o,void 0,i,t);t.clear(),i.clear();for(let s of e)s.template=void 0}_loadFile(t){for(let e=0;e<this._path.length;e++){let i=this._path[e],s=(0,C.join)(i,t),o=this._getExtension(t),a=this._getKey(t);if(o==".html"){let n=(0,y.readFileSync)(s,"utf8");this._compile(a,n)}else if(o==".ts"||o==".js"){let n=P.getFileSync(s);n?.template!==void 0&&(this._compile(a,n.template),n.template=void 0)}else throw new Error(`File ${t} is not support`)}}_getExtension(t){return(0,C.extname)(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let i=(0,C.extname)(t).toLowerCase();if(i){let n=(0,C.join)(e,t);if((0,y.existsSync)(n)&&(0,y.statSync)(n).isFile()){if(i===".html")return(0,y.readFileSync)(n,"utf8");if(i===".ts"||i===".js")try{return P.getFileSync(n)?.template??null}catch{return null}}continue}let s=(0,C.join)(e,`${t}.ts`),o=(0,C.join)(e,`${t}.js`);if((0,y.existsSync)(s)&&(0,y.statSync)(s).isFile())try{return P.getFileSync(s)?.template??null}catch{}else if((0,y.existsSync)(o)&&(0,y.statSync)(o).isFile())try{return P.getFileSync(s)?.template??null}catch{}let a=(0,C.join)(e,`${t}.html`);if((0,y.existsSync)(a)&&(0,y.statSync)(a).isFile())return(0,y.readFileSync)(a,"utf8")}return null}_isValidFile(t){return this._supportedExtensions.has(this._getExtension(t))}_getKey(t){return t.replace(/\.[^/.]+$/,"")}_compile(t,e,i,s,o){let a=this._map.get(t),n=a||{},r=!1,c=k.processImportBlocks(e,d=>o&&o.has(d)?o.get(d):this._readTemplateFile(d),0,s),l=k._processBaseBlocks(c);(i===void 0||i?.media===!1||a?.media===void 0)&&(n.media=k.compileMedia(c,l),r=!0),(i===void 0||i?.message===!1||a?.message===void 0)&&(n.message=k.compileMessages(c,l),r=!0),(i===void 0||i?.keyboard===!1||a?.keyboard===void 0)&&(n.keyboard=k.compileKeyboards(c,l),r=!0),(i===void 0||i?.description===!1||a?.description===void 0)&&(n.description=k.compileDescription(c,l),r=!0),r&&this._map.set(t,n)}getMedia(t,e="default",i="default",s){let a=this._map.get(t)?.media?.[e],n=a?.[i]||a?.default;try{if(!n)throw new Error("Media function not found, please check your template");return n(s)}catch{return{}}}getMessage(t,e="default",i="default",s){try{let a=this._map.get(t)?.message?.[e],n=a?.[i]||a?.default;if(!n)throw"";return n(s)}catch{return""}}getDescription(t,e="default",i="default",s="default",o){try{let n=this._map.get(t)?.description?.[e]?.[s],r=n?.[i]||n?.default;if(!r)throw"";return r(o)}catch{return""}}getDescriptionLanguage(t,e="default",i="default"){try{let o=this._map.get(t)?.description?.[e]?.[i];return o?Object.keys(o):[]}catch{return[]}}getDescriptionScopes(t,e="default"){try{let s=this._map.get(t)?.description?.[e];return s?Object.keys(s):[]}catch{return[]}}getKeyboard(t,e="default",i="default",s="inline",o){try{let n=this._map.get(t)?.keyboard?.[e],r=n?.[i]?.[s]||n?.default?.[s];if(!r)throw[];return r(o)}catch{return[]}}async write(t,e){if(this._getExtension(t)!=".html")return null;for(let i=0;i<this._path.length;i++){let s=(0,C.join)(this._path[i],t);if((0,y.existsSync)(s))return(0,y.writeFileSync)(s,e,"utf8"),this._loadFile(t),!0}return null}has(t){return this._map.has(t)}async destroy(){if(this._watcher)for(let t of this._watcher)await t.close();this._map.clear()}};var W=require("grammy");var kt=(0,at.fileURLToPath)(f),vt=(0,w.dirname)(kt),Tt=JSON.parse((0,ot.readFileSync)((0,w.join)(vt,"../../package.json"),"utf-8")).version,j=class{static{h(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;log;bot;handlerBotUpdate;constructor(t){if(!t?.token||t?.token?.length==0)throw new Error("Token is not valid or empty");if(this.log=t.log===!0?new rt.LoggingPretty:t.log?t.log:void 0,this.log?.info?.(`Gramstax v${Tt}`),this.cacheSession=t.cacheSession||new D("memory","session"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new O({path:[(0,w.join)(process.cwd(),"src","pages")]}),this.bot=this.createBot(t.token),this.bot.catch(this.onCatch),this.registerOnCallbackQueryData(),this.registerOnMessageText(),this.registerOnMessagePhoto(),this.registerOnMessageVideo(),this.registerOnMessageAudio(),this.registerOnMessageDocument(),this.registerOnMessageAnimation(),this.registerOnMessageVoice(),this.registerOnMessageVideoNote(),this.registerOnMessageSticker(),this.registerOnMessageLocation(),this.registerOnMessageContact(),this.handlerBotUpdate=this.bot.handleUpdate,this.pages=this.pageLoads(),process.once("SIGINT",()=>this.bot.stop()),process.once("SIGTERM",()=>this.bot.stop()),this.hookBeforeStart(),t.deploy.startsWith("polling"))this.runPolling();else if(t.deploy.startsWith("webhook:"))this.runWebhook(t.deploy.split("webhook:")[1]);else if(t.deploy.startsWith("serverless:"))this.runServerless(t.deploy.split("serverless:")[1]);else if(!t.deploy.startsWith("test"))throw new Error("Params deploy is not valid, expected: polling, webhook:<public-url>, serverless:<your-adapter>")}onCatch(t){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 W.Bot(t)}createCtx(t){return new A({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,W.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,W.webhookCallback)(this.bot,t);let e=await this.bot.api.getMe();await this.onStart(e,"serverless",t)}pageBuildData(t,e){t?.data===void 0&&(t.data=t.buildData()),t.data.name=(0,w.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(g=>g.charAt(0).toUpperCase()+g.slice(1),"upFirst"),p=h(g=>g.replace(o,"").replace(a,"").replace(n,"").replace(r,""),"getPureRouteName"),u=h((g,b)=>s[`methodSession${d(g)}`]?.(b),"methodSession");e.all[i]=t;for(let g=0;g<e.lenListRouteStaticSession;g++){let b=e.listRouteStaticSession[g];if(typeof s[b]!="function")continue;let S=e.routeStatic[b],x=e.routeStaticIntent[b],I=e.routeStaticSession[b],T={name:i,routeName:b},H=S||x;if(H!==void 0){let dt=b.includes(a),pt=b.includes("callback"),ut=b.startsWith("text"),M;if(dt){let z=t.data.textCommand||t.data.name;M=z?`/${z}`:void 0}else pt?M=t.data.name:ut?M=t.data.text||t.data.name:M=t.data.name;M&&(H[M]=T)}I!==void 0&&(I[u(b,i)]=T),b.toLowerCase().endsWith("free")&&l[p(b)].push(T)}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,g)=>u.command.localeCompare(g.command))),p=JSON.stringify(n.sort((u,g)=>u.command.localeCompare(g.command)));d!==p&&(await this.bot.api.setMyCommands(n,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${s},${c?` lang: ${c},`:""} total (${n.length})`))}catch(l){this.log?.error?.(`Failed to sync descriptions for scope: ${s},${c?` lang: ${c},`:""} error: ${String(l)}`)}}}pageLoads(){this.log?.info?.("Load pages..");let t=["callback","text","textCommand","photoCaption","photoCaptionCommand","videoCaption","videoCaptionCommand","audioCaption","audioCaptionCommand","documentCaption","documentCaptionCommand","animationCaption","animationCaptionCommand","voiceCaption","voiceCaptionCommand","videoNoteCaption","videoNoteCaptionCommand"],e=["callbackPayload","textPayload","textCommandPayload","photoCaptionPayload","photoCaptionCommandPayload","videoCaptionPayload","videoCaptionCommandPayload","audioCaptionPayload","audioCaptionCommandPayload","documentCaptionPayload","documentCaptionCommandPayload","animationCaptionPayload","animationCaptionCommandPayload","voiceCaptionPayload","voiceCaptionCommandPayload","videoNoteCaptionPayload","videoNoteCaptionCommandPayload"],i=[...t,...e,"textFree","photoFree","videoFree","audioFree","documentFree","animationFree","voiceFree","videoNoteFree","stickerFree","locationFree","contactFree"],s=h((n,r)=>Object.fromEntries(n.map(c=>[c,r()])),"makeObject"),o=h(()=>[],"initDynamicSpesific"),a={all:{},routeDynamic:[],routeDynamicSpesific:{text:o(),photo:o(),video:o(),audio:o(),document:o(),animation:o(),voice:o(),videoNote:o(),sticker:o(),location:o(),contact:o()},routeStatic:s(t,()=>({})),routeStaticIntent:s(e,()=>({})),routeStaticSession:s(i,()=>({})),listRouteStatic:t,listRouteStaticIntent:e,listRouteStaticSession:i,lenListRouteStatic:t.length,lenListRouteStaticIntent:e.length,lenListRouteStaticSession:i.length};return P.getFileManySync(void 0).forEach(({path:n,page:r})=>{this.pageBuildData(r,n),this.pageSorts(r,a),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(a.all).length})`),a}async pageRoutes(t,e){let i,s;if(i===void 0){let a=t.callbackData,n=t.msgText,r=t.msgCaption,c=this.pages.routeStatic;for(let l=0;l<this.pages.lenListRouteStatic;l++){let d=this.pages.listRouteStatic[l];if(d.startsWith(e)&&(s=c[d][a||n||r]),s)break}s!==void 0&&(i=this.pages.all[s.name])}if(i===void 0){let a=await t.sessionGet();if(a){let n=a.method,r=this.pages.routeStaticSession;for(let c=0;c<this.pages.lenListRouteStaticSession;c++){let l=this.pages.listRouteStaticSession[c];if(l.startsWith(e)&&(s=r[l][n]),s)break}s!==void 0&&(i=this.pages.all[s.name])}}if(i===void 0){let a=this.pages.routeStaticIntent,n=e==="callback",r=n?t.callbackData:t.msgText||t.msgCaption;if(r)for(let c=0;c<this.pages.lenListRouteStaticIntent;c++){let l=this.pages.listRouteStaticIntent[c];if(l.startsWith(e)){let d=a[l];s=d[t.intent(r,n?"colon":"space",1)],!s&&!n&&(s=d[t.intent(r,"space",2)])}if(s)break}s!==void 0&&(i=this.pages.all[s.name])}if(i!==void 0&&s!==void 0)return i.prototype[s.routeName]?await new i(t)[s.routeName]?.():void 0;let o=this.pages.routeDynamicSpesific[e]||[];for(let a=0;a<o.length;a++){let n=o[a];if(n===void 0)continue;let r=this.pages.all[n.name];if(r===void 0||!r.prototype[n.routeName])continue;let l=await new r(t)[n.routeName]?.();if(l!==null)return l}for(let a=0;a<this.pages.routeDynamic.length;a++){let n=this.pages.routeDynamic[a];if(n===void 0)continue;let r=this.pages.all[n];if(r===void 0||!r.prototype.free)continue;let l=await new r(t).free?.();if(l!==null)return l}return null}async hookBeforeRoute(t,e){return!!(t||e)}async hookErrorPage(t,e,i,s){}async hookErrorInputNotFoundPage(t){}async onMessage(t,e){let i=this.createCtx(t);try{if(await this.hookBeforeRoute(i,e)===!1)return;await this.pageRoutes(i,e)===null&&await this.hookErrorInputNotFoundPage(i)}catch(s){await this.hookErrorPage(i,e,s,!1)}}async onCallbackQueryData(t){let e=this.createCtx(t);try{if(await e.callbackQueryAnswer(),await this.hookBeforeRoute(e,"onCallbackQueryData")===!1)return;await this.pageRoutes(e,"callback")}catch(i){await this.hookErrorPage(e,"onCallbackQueryData",i,!0)}}async onMessageText(t){await this.onMessage(t,"text")}async onMessagePhoto(t){await this.onMessage(t,"photo")}async onMessageVideo(t){await this.onMessage(t,"video")}async onMessageAudio(t){await this.onMessage(t,"audio")}async onMessageDocument(t){await this.onMessage(t,"document")}async onMessageAnimation(t){await this.onMessage(t,"animation")}async onMessageVoice(t){await this.onMessage(t,"voice")}async onMessageVideoNote(t){await this.onMessage(t,"videoNote")}async onMessageSticker(t){await this.onMessage(t,"sticker")}async onMessageLocation(t){await this.onMessage(t,"location")}async onMessageContact(t){await this.onMessage(t,"contact")}registerOnCallbackQueryData(){this.bot.on("callback_query:data",this.onCallbackQueryData.bind(this))}registerOnMessageText(){this.bot.on("message:text",this.onMessageText.bind(this))}registerOnMessagePhoto(){this.bot.on("message:photo",this.onMessagePhoto.bind(this))}registerOnMessageVideo(){this.bot.on("message:video",this.onMessageVideo.bind(this))}registerOnMessageAudio(){this.bot.on("message:audio",this.onMessageAudio.bind(this))}registerOnMessageDocument(){this.bot.on("message:document",this.onMessageDocument.bind(this))}registerOnMessageAnimation(){this.bot.on("message:animation",this.onMessageAnimation.bind(this))}registerOnMessageVoice(){this.bot.on("message:voice",this.onMessageVoice.bind(this))}registerOnMessageVideoNote(){this.bot.on("message:video_note",this.onMessageVideoNote.bind(this))}registerOnMessageSticker(){this.bot.on("message:sticker",this.onMessageSticker.bind(this))}registerOnMessageLocation(){this.bot.on("message:location",this.onMessageLocation.bind(this))}registerOnMessageContact(){this.bot.on("message:contact",this.onMessageContact.bind(this))}};var L=require("worker_threads");var v=class{constructor(t,e){this.send=t;this.register=e}static{h(this,"WorkerThreadRpc")}map=new Map;async make(t){let e=this.map,i=this.send,{id:s,method:o,params:a,result:n,error:r}=t;if(o!==void 0)try{let c=this.register[o];if(typeof c!="function")throw new Error(`Method ${o} not found or not function`);let l=await c.apply(this.register,a);i({id:s,result:l})}catch(c){i({id:s,error:c instanceof Error?{message:c.message,stack:c.stack,name:c.name}:c})}else if(n!==void 0){let c=e.get(s);c&&(c.resolve(n),e.delete(s))}else if(r!==void 0){let c=e.get(s);c&&(c.reject(r),e.delete(s))}}makeId(){return Math.random()}makeRequest(t,e,i=!0,s){let o=this.makeId(),a={id:o,method:t,params:e,...s};return i?new Promise((n,r)=>{this.map.set(o,{resolve:n,reject:r}),this.send(a)}):this.send(a)}};var $=class{constructor(t,e){this.path=t;this.argv=e;this.init(),this.rpc=new v(this.send.bind(this),this)}static{h(this,"WorkerThreadLaunch")}pid=process.pid;thread={};threadId={};rpc={};_readyResolve;_readyPromise=new Promise(t=>this._readyResolve=t);static isMainThread=L.isMainThread;ready(){return this._readyPromise}mtdReady(){this._readyResolve?.()}init(){this.thread=new L.Worker(this.path,{argv:this.argv.length==0&&this.argv[0]===void 0?void 0:this.argv}),this.threadId=this.thread.threadId,this.thread.on("message",t=>this.handleOnMessage(t))}async handleOnMessage(t){this.rpc.make(t)}kill(){this.thread.terminate()}send(t){this.thread.postMessage(t)}async request(t,e,i=!0,s){return this.rpc.makeRequest(t,e,i,s)}};var q=class m{static{h(this,"WorkerThreadExport")}static gateway(t){let e=new Proxy({},{get(s,o){if(!(typeof o!="string"||o==="then"))return async(a,...n)=>{let r=a.gatewayClients.get(t);return r||(r=await a.createGatewayClient(t)),r.request(o,n)}}}),i=h(function(s){return new Proxy({},{get(o,a){if(!(typeof a!="string"||a==="then"))return async(...n)=>{let r=s.gatewayClients.get(t);return r||(r=await s.createGatewayClient(t)),r.request(a,n)}}})},"ctor");return Object.setPrototypeOf(i,e),i}static init(t){let{WTInit:e,WTLaunch:i=$,path:s,wrap:o}=t,a=`for-${s}`;if(process.argv[2]===a)return new e,{gateway:h(d=>m.gateway(d),"gateway")};let n,r=new Proxy({},{get(d,p){if(p!=="then")return p==="sendRequest"||p==="request"||p==="kill"||p==="send"?(...u)=>{if(!n)throw new Error(`Thread at ${s} not launched yet.`);return n[p](...u)}:(...u)=>{if(!n)throw new Error(`Thread at ${s} not launched yet.`);return n.request(p,u)}}}),l={...o?o(r):{},launchWorker:h(async(d=[])=>(n=new i(s,[a,...d]),await n.ready(),n),"launchWorker"),gateway:h(d=>m.gateway(d),"gateway")};return new Proxy(l,{get(d,p){if(p!=="then")return p==="gateway"?d.gateway:p==="launchWorker"?d.launchWorker:p in d?d[p]:typeof p=="string"?(...u)=>{if(!n)throw new Error(`Thread at ${s} not launched yet.`);return n.request(p,u)}:d[p]}})}};var G=class{static{h(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(t){this.addMany(t)}add(t){this.thread.set(t.threadId,t),this.threadCount+=1}addMany(t){t.forEach(e=>this.add(e))}getInstance(t){return this.thread.get(t)}kill(t){let e=this.thread.get(t);return e?.kill(),this.thread.delete(t),this.threadCount-=1,e?.threadId}killAll(){this.thread.values().forEach(({threadId:t})=>this.kill(t))}async broadcastRequest(t,e){return await Promise.all(Object.values(this.thread).map(i=>i.request(t,e,!0)))}async request(t,e,i,s=!0,o){return await this.thread.get(t)?.request(e,i,s,o)}};var R=require("worker_threads");var ct=require("net-ipc");var B=class{static{h(this,"WorkerThreadGatewayServer")}server=new ct.Server;rpc=new Map;methods={};constructor(){this.server.on("connect",t=>{let e=new v(i=>t.send(i),this.methods);this.rpc.set(t.id,e)}),this.server.on("disconnect",t=>{this.rpc.delete(t.id)}),this.server.on("message",(t,e)=>{let i=this.rpc.get(e.id);i&&i.make(t)}),this.server.on("error",t=>{console.error(t)})}async start(t,e={}){this.methods=e,this.server.options.path=t;let i=new Promise(s=>{this.server.once("ready",()=>s(this))});return await this.server.start(),i}};var lt=require("net-ipc");var N=class{static{h(this,"WorkerThreadGatewayClient")}client=new lt.Client;rpc;constructor(){this.rpc=new v(t=>this.client.send(t),{}),this.client.on("message",t=>{this.rpc.make(t)})}async connect(t){this.client.options.path=t;let e=new Promise(i=>{this.client.once("ready",()=>i(this))});return await this.client.connect(),e}async request(t,e,i=!0,s){return this.rpc.makeRequest(t,e,i,s)}};var U=class{static{h(this,"WorkerThreadInit")}argv=process.argv;id=R.threadId;pid=process.pid;rpc={};parentPort=R.parentPort;gatewayServer;gatewayClients=new Map;gatewayClientLatest;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=R.isMainThread;constructor(){this.init(),this.rpc=new v(this.send.bind(this),this),this.send({method:"mtdReady"})}init(){this.parentPort?.on("message",t=>this.handleOnMessage(t))}handleOnMessage(t){this.rpc.make(t)}send(t){this.parentPort?.postMessage(t)}request(t,e,i=!0,s){return this.rpc.makeRequest(t,e,i,s)}async createGatewayServer(t,e={}){return this.gatewayServer=new B,await this.gatewayServer.start(t,e),!0}async createGatewayClient(t){let e=new N;return await e.connect(t),this.gatewayClients.set(t,e),this.gatewayClientLatest=e,e}};var Q=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(
|
|
9
|
-
`}return Object.keys(t).map(
|
|
10
|
-
<keyboard type="${e.type}" lang="${
|
|
11
|
-
`}).join(" ")}static _build(t,e,
|
|
1
|
+
"use strict";var pt=Object.create;var V=Object.defineProperty;var gt=Object.getOwnPropertyDescriptor;var ut=Object.getOwnPropertyNames;var yt=Object.getPrototypeOf,ft=Object.prototype.hasOwnProperty;var p=(g,t)=>V(g,"name",{value:t,configurable:!0});var Ct=(g,t)=>{for(var e in t)V(g,e,{get:t[e],enumerable:!0})},X=(g,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ut(t))!ft.call(g,n)&&n!==e&&V(g,n,{get:()=>t[n],enumerable:!(s=gt(t,n))||s.enumerable});return g};var Y=(g,t,e)=>(e=g!=null?pt(yt(g)):{},X(t||!g||!g.__esModule?V(e,"default",{value:g,enumerable:!0}):e,g)),St=g=>X(V({},"__esModule",{value:!0}),g);var vt={};Ct(vt,{CacheExternal:()=>D,ComponentKeyboard:()=>q,Ctx:()=>A,DataKeyboard:()=>G,Gramstax:()=>j,LoggingUtils:()=>K,TemplateEngine:()=>k,TemplateManager:()=>O,WorkerThreadExport:()=>U,WorkerThreadGatewayClient:()=>B,WorkerThreadGatewayServer:()=>N,WorkerThreadInit:()=>Q,WorkerThreadLaunch:()=>W,WorkerThreadPool:()=>J,WorkerThreadRpc:()=>w,log:()=>bt});module.exports=St(vt);var Pt=p(()=>typeof document>"u"?new URL(`file:${__filename}`).href:document.currentScript&&document.currentScript.tagName.toUpperCase()==="SCRIPT"?document.currentScript.src:new URL("main.js",document.baseURI).href,"getImportMetaUrl"),C=Pt();var Z=require("logging-pretty");var K=class extends Z.LoggingPretty{static{p(this,"LoggingUtils")}constructor(t){super(t)}errorMake(t,e,s){this.error(`[${e?`${e}:${s}`:s}] ${String(t)}`)}},bt=new K;var tt=require("keyv"),et=Y(require("@keyv/redis"),1);var D=class extends tt.Keyv{constructor(e="memory",s,n,o){let a;e.startsWith("redis")&&(a=new et.default(e)),e==="memory"&&(a=new Map),o?.forceStore&&(a=o.forceStore);super({store:a,namespace:s,ttl:n});this.url=e}static{p(this,"CacheExternal")}};var st=require("timers/promises"),_=require("grammy");var A=class{static{p(this,"Ctx")}static template;static data;data=this.constructor.data;get userIsPremium(){return this.ct.from?.is_premium??!1}get userIsBot(){return this.ct.from?.is_bot??!1}get userId(){return this.ct.from?.id}get userName(){return this.ct.from?.username}get userFullName(){return`${this.ct.from?.first_name} ${this.ct.from?.last_name||""}`}get userFirstName(){return this.ct.from?.first_name}get userLastName(){return this.ct.from?.last_name}get userLanguage(){return this.ct.from?.language_code}set userLanguage(t){this.ct.from.language_code=t}get msgText(){return this.ct.message?.text}get msgTextPayloads(){return this.getPayloads(this.msgText,"space",this.data?._positionPayloadText||this.temp?.data?._positionPayloadText)}get msgTextPayload(){return this.msgTextPayloads[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionPayloads(){return this.getPayloads(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.getPayloads(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,n,o,a,i=!1){try{this.temp.isAnswer=!0;let r=30,c=e.map(h=>this.templateManager.getMessage(this.data.name,o,h,n));for(let h=0;h<t.length;h++){let d=t[h],l=c[h];await this.ct.api.sendMessage(d,l,{parse_mode:"HTML",reply_markup:s,...a}),h+1==r&&await(0,st.setTimeout)(1200)}}catch(r){if(i)throw r}}async reply(t,e,s,n){this.temp.isAnswer=!0;let o=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.reply(o,{parse_mode:"HTML",reply_markup:t,...n})}async replyMedia(t,e,s,n,o){this.temp.isAnswer=!0;let a=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s),i={parse_mode:"HTML",reply_markup:e,...o};if(t=="photo")return await this.ct.replyWithPhoto(a.src,{caption:a.caption,...i});if(t=="video")return await this.ct.replyWithVideo(a.src,{caption:a.caption,...i});if(t=="audio")return await this.ct.replyWithAudio(a.src,{caption:a.caption,...i});if(t=="document")return await this.ct.replyWithDocument(a.src,{caption:a.caption,...i});if(t=="animation")return await this.ct.replyWithAnimation(a.src,{caption:a.caption,...i});if(t=="voice")return await this.ct.replyWithVoice(a.src,i);if(t=="video_note")return await this.ct.replyWithVideoNote(a.src,i);if(t=="sticker")return await this.ct.replyWithSticker(a.src,i);if(t=="location")return await this.ct.replyWithLocation(parseInt(a.latitude),parseInt(a.longitude),i);if(t=="contact")return await this.ct.replyWithContact(a.phone,a.first_name,{vcard:a.vcard,...i})}async replyPhoto(t,e,s,n){return this.replyMedia("photo",t,e,s,n)}async replyVideo(t,e,s,n){return this.replyMedia("video",t,e,s,n)}async replyAudio(t,e,s,n){return this.replyMedia("audio",t,e,s,n)}async replyDocument(t,e,s,n){return this.replyMedia("document",t,e,s,n)}async replyAnimation(t,e,s,n){return this.replyMedia("animation",t,e,s,n)}async replyVoice(t,e,s,n){return this.replyMedia("voice",t,e,s,n)}async replyVideoNote(t,e,s,n){return this.replyMedia("video_note",t,e,s,n)}async replySticker(t,e,s,n){return this.replyMedia("sticker",t,e,s,n)}async replyLocation(t,e,s,n){return this.replyMedia("location",t,e,s,n)}async replyContact(t,e,s,n){return this.replyMedia("contact",t,e,s,n)}async replyAction(t){return await this.ct.replyWithChatAction(t)}async edit(t,e,s,n,o=!0){try{this.temp.isAnswer=!0;let a=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.editMessageText(a,{parse_mode:"HTML",reply_markup:t,...n})}catch(a){if(o)await this.reply(t,e,s,n);else throw a}}async editMedia(t,e,s,n,o,a,i=!0){try{this.temp.isAnswer=!0;let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s);return t=="voice"?(await this.delete(),await this.replyVoice(e,s,n,o)):t=="video_note"?(await this.delete(),await this.replyVoice(e,s,n,o)):t=="sticker"?(await this.delete(),await this.replySticker(e,s,n,o)):t=="location"?(await this.delete(),await this.replyLocation(e,s,n,o)):t=="contact"?(await this.delete(),await this.replyContact(e,s,n,o)):await this.ct.editMessageMedia({media:r,caption:c,type:t,parse_mode:"HTML",...o},{reply_markup:e,...a})}catch(r){if(i===!0)await this.reply(e,s,n,a);else throw r}}async editPhoto(t,e,s,n,o){return await this.editMedia("photo",t,e,s,n,o)}async editVideo(t,e,s,n,o){return await this.editMedia("video",t,e,s,n,o)}async editAudio(t,e,s,n,o){return await this.editMedia("audio",t,e,s,n,o)}async editDocument(t,e,s,n,o){return await this.editMedia("document",t,e,s,n,o)}async editAnimation(t,e,s,n,o){return await this.editMedia("animation",t,e,s,n,o)}async editVoice(t,e,s,n){return await this.editMedia("voice",t,e,s,n)}async editVideoNote(t,e,s,n){return await this.editMedia("video_note",t,e,s,n)}async editSticker(t,e,s,n){return await this.editMedia("sticker",t,e,s,n)}async editLocation(t,e,s,n){return await this.editMedia("location",t,e,s,n)}async editContact(t,e,s,n){return await this.editMedia("contact",t,e,s,n)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(t){try{return this.temp.isAnswer=!0,await this.ct.answerCallbackQuery(t)}catch{return null}}async sessionSet(t,e,s){try{let n={method:t,params:e,...s},o=await this.cacheSession.set(`${this.userId}`,n);return o&&(this.session=n),o}catch{return null}}async sessionGet(){try{let t=await this.cacheSession.get(`${this.userId}`);return t&&(this.session=t),t||null}catch{return null}}async sessionClear(){try{let t=await this.cacheSession.delete(`${this.userId}`);return t&&(this.session={}),t}catch{return null}}static buildData(t){let s=typeof t=="function"?{callbackData:t}:t||{},n=s.callbackData;return{name:"",text:s.text,textCommand:s.textCommand,_positionPayloadText:s.text?s.text.split(this.prototype.getSeperatorTag("space")).length:void 0,callbackData:n?function(...a){let i=n(...a);return`${this.name}${i==""||i===void 0?"":`:${i}`}`}:function(){return this?.name}}}inlineKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let i=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(i);if(!r){let c=new _.InlineKeyboard,h=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data),d=t(c,h);return this.cacheKeyboard.set(i,d),d}return r}let n=new _.InlineKeyboard,o=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data);return t(n,o)}bottomKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let i=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(i);if(!r){let c=new _.Keyboard,h=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),d=t(c,h);return d.resized(!0),this.cacheKeyboard.set(i,d),d}return r}let n=new _.Keyboard,o=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),a=t(n,o);return a.resized(),a}getSeperatorTag(t="space"){return t=="space"?" ":":"}havePayloads(t="",e){return t.includes(this.getSeperatorTag(e))}getPayloads(t="",e,s=1){if(!t)return[];let n=this.getSeperatorTag(e);return t.split(n).slice(s)}getIntent(t="",e,s=1){if(!t)return"";let n=this.getSeperatorTag(e),o=t.split(n);return s==1?o[0]:o.slice(0,s).join(n)}validateSessionCallback(t,e){return(t??this.session.method)===this.methodSessionCallback(e)}validateSessionCallbackPayload(t,e){return(t??this.session.method)===this.methodSessionCallbackPayload(e)}validateSessionText(t,e){return(t??this.session.method)===this.methodSessionText(e)}validateSessionTextPayload(t,e){return(t??this.session.method)===this.methodSessionTextPayload(e)}validateSessionTextCommand(t,e){return(t??this.session.method)===this.methodSessionTextCommand(e)}validateSessionTextCommandPayload(t,e){return(t??this.session.method)===this.methodSessionTextCommandPayload(e)}validateSessionTextFree(t,e){return(t??this.session.method)===this.methodSessionTextFree(e)}validateSessionPhotoCaption(t,e){return(t??this.session.method)===this.methodSessionPhotoCaption(e)}validateSessionPhotoCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionPayload(e)}validateSessionPhotoCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionCommand(e)}validateSessionPhotoCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionCommandPayload(e)}validateSessionPhotoFree(t,e){return(t??this.session.method)===this.methodSessionPhotoFree(e)}validateSessionVideoCaption(t,e){return(t??this.session.method)===this.methodSessionVideoCaption(e)}validateSessionVideoCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionPayload(e)}validateSessionVideoCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionCommand(e)}validateSessionVideoCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionCommandPayload(e)}validateSessionVideoFree(t,e){return(t??this.session.method)===this.methodSessionVideoFree(e)}validateSessionAudioCaption(t,e){return(t??this.session.method)===this.methodSessionAudioCaption(e)}validateSessionAudioCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionPayload(e)}validateSessionAudioCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionCommand(e)}validateSessionAudioCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionCommandPayload(e)}validateSessionAudioFree(t,e){return(t??this.session.method)===this.methodSessionAudioFree(e)}validateSessionDocumentCaption(t,e){return(t??this.session.method)===this.methodSessionDocumentCaption(e)}validateSessionDocumentCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionPayload(e)}validateSessionDocumentCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionCommand(e)}validateSessionDocumentCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionCommandPayload(e)}validateSessionDocumentFree(t,e){return(t??this.session.method)===this.methodSessionDocumentFree(e)}validateSessionAnimationCaption(t,e){return(t??this.session.method)===this.methodSessionAnimationCaption(e)}validateSessionAnimationCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionPayload(e)}validateSessionAnimationCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionCommand(e)}validateSessionAnimationCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionCommandPayload(e)}validateSessionAnimationFree(t,e){return(t??this.session.method)===this.methodSessionAnimationFree(e)}validateSessionVoiceCaption(t,e){return(t??this.session.method)===this.methodSessionVoiceCaption(e)}validateSessionVoiceCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionPayload(e)}validateSessionVoiceCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionCommand(e)}validateSessionVoiceCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionCommandPayload(e)}validateSessionVoiceFree(t,e){return(t??this.session.method)===this.methodSessionVoiceFree(e)}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 v=require("path"),ot=require("fs"),at=require("url");var E=require("path"),F=require("fs"),nt=require("module");var b=class{static{p(this,"PageManager")}static _getFile(t,e,s=0){let o=Object.values(t)[s];if(o===void 0)throw new Error(`File ${e} must have export (not default) class page`);return o}static getFilePath(){return(0,E.join)(process.cwd(),"src","pages")}static getFileSync(t,e=0){t||(t=this.getFilePath());let n=(0,nt.createRequire)(t)(t);return this._getFile(n,t,e)}static async getFile(t,e=0){t||(t=this.getFilePath());let s=await import(`${t}?t=${Date.now()}`);return this._getFile(s,t,e)}static getFileManySync(t,e=0){if(t||(t=this.getFilePath()),!(0,F.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,F.readdirSync)(t).map(n=>{let o=(0,E.join)(t,n);return{path:o,page:this.getFileSync(o,e)}})}static clearCacheRequire(t){if(t||(t=this.getFilePath()),!(0,F.existsSync)(t))throw new Error(`Directory ${t} is not found, please make it manually`);return(0,F.readdirSync)(t).forEach(s=>{let n=(0,E.join)(t,s);delete require.cache[require.resolve(n)]}),!0}};var rt=require("logging-pretty");var S=require("path"),y=require("fs"),it=require("chokidar");var k=class{static{p(this,"TemplateEngine")}static _escape(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processVariables(t){return t.replace(/\{\{(\w+)\}\}/g,(e,s)=>`\${(data && data["${s}"]) ?? ""}`)}static _processBaseBlocks(t){let e=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,s={};for(let n of t.matchAll(e)){let o=n[2]??"default",i=(n[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[o]=i}return s}static _processScriptBlocks(t){return t.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(e,s)=>{let n=s.trim();return n?`\${(() => { if (!data) return ''; try { with(data) { ${n} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(t){return t.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(t){return t.replace(/<div>([\s\S]*?)<\/div>/gi,(e,s)=>s.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(t){let e=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return t.replace(e,(s,n,o)=>{if(!n)return"";let a="",i=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=i.exec(o))!==null;){let d=(c[1]||"").split(",").map(m=>m.trim()),l=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(m=>{a+=`case "${m}": `}),a+=`return \`${l}\`; `}let h=r.exec(o);if(h){let d=(h[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");a+=`default: return \`${d}\`; `}else a+="default: return ''; ";return`\${(() => { switch((data && data["${n}"])) { ${a} } })()}`})}static _processExec(t){return t.replace(/{~\s*([\s\S]*?)\s*~}/g,(e,s)=>`\${(() => { try { return ${s} } catch(e) { try { with(data || {}) { return ${s} } } catch(ee) { return '' } } })()}`)}static _processMapBlocks(t){let e=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return t.replace(e,(s,n,o)=>{let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let l of n.matchAll(i))a[l[1]]=l[2];let r=a.src;if(!r)return"";let c=a.join??"\\n",h=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");h=h.replace(/\{\{([\w.]+)\}\}/g,(l,m)=>m==="e"||m.startsWith("e.")?`\${${m}}`:m==="i"?"${i}":l);let d=c.replace(/"/g,'\\"');return`\${(data && data["${r}"] || []).map((e, i) => \`${h}\`).join("${d}")}`})}static _processMediaBlocks(t){let e=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let n of t.matchAll(e)){let o=n[1],a=n[2],i={},r=/(\w+)="([^"]*)"/g;if(o)for(let m of o.matchAll(r))i[m[1]]=m[2];let c=i.lang||"default",h=i.type,d=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),l={type:h};i.src&&(l.src=i.src),d&&h!=="video_note"&&h!=="sticker"&&(l.caption=d),h==="location"&&(i.latitude&&(l.latitude=i.latitude),i.longitude&&(l.longitude=i.longitude),d&&(l.caption=d)),h==="contact"&&(i.phone&&(l.phone=i.phone),i.first_name&&(l.first_name=i.first_name),i.last_name&&(l.last_name=i.last_name),i.vcard&&(l.vcard=i.vcard),d&&(l.caption=d)),s[c]=l}return s}static _processMessageBlocks(t){let e=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,n,o]of t.matchAll(e)){let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let h of n.matchAll(i))a[h[1]]=h[2];let r=a.lang||"default",c=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=c}return s}static _processDescriptionBlocks(t){let e=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,n,o]of t.matchAll(e)){let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(i))a[d[1]]=d[2];let r=a.lang||"default",c=a.scope||"default",h=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][c]=h}return s}static _processKeyboardBlocks(t){let e=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,n,o]of t.matchAll(e)){let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(i))a[d[1]]=d[2];let r=a.lang||"default",c=a.type==="bottom"?"bottom":"inline",h=o.trim();s[r]||(s[r]={}),s[r][c]=h}return s}static _compileToFunction(t,e){let s;e?s=t.map(a=>`\`${a}\``).join(","):s=`\`${t}\``;let n=s;if(n=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(n))),e){let o=`return [${n}]`;return new Function("data",o)}else{let o=`return ${n}`;return new Function("data",o)}}static compileMedia(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processMediaBlocks(a);n[o]={};for(let[r,c]of Object.entries(i)){let h={};for(let[d,l]of Object.entries(c)){if(d==="type"||typeof l!="string")continue;let m=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(l)))));h[d]=this._compileToFunction(m,!1)}n[o][r]=d=>{let l={...c};for(let[m,u]of Object.entries(h))l[m]=u(d);return l}}}return n}static compileMessages(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processMessageBlocks(a);n[o]={};for(let[r,c]of Object.entries(i)){let h=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));n[o][r]=this._compileToFunction(h,!1)}}return n}static compileDescription(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processDescriptionBlocks(a);n[o]={};for(let[r,c]of Object.entries(i))for(let[h,d]of Object.entries(c)){n[o][h]||(n[o][h]={});let l=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));n[o][h][r]=this._compileToFunction(l,!1)}}return n}static compileKeyboards(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processKeyboardBlocks(a);n[o]={};for(let[r,c]of Object.entries(i)){n[o][r]={};for(let[h,d]of Object.entries(c)){let m=d.split(/(?<!\\),\s*/).map(u=>u.replace(/\\,/g,",").trim()).map(u=>this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(u))))));n[o][r][h]=this._compileToFunction(m,!0)}}}return n}static _extractBlock(t,e,s="default",n="all",o){let a=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,i=t,r=!1;for(let c of t.matchAll(a))if((c[2]??"default")===s){i=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(t);if(!(s==="default"&&!c))return""}if(e){if(e==="all")return i;let c=Array.isArray(e)?e:[e],h=[];for(let l of c){let m=new RegExp(`([ \\t]*)<${l}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${l}>`,"gi");for(let u of i.matchAll(m)){let f=u[2];if(o){let P=/lang="([^"]*)"/i,x=f?.match(P);if(((x?x[1]:void 0)||"default")!==o)continue}h.push({start:u.index,content:u[0],innerContent:u[3]??""})}}h.sort((l,m)=>l.start-m.start);let d=p(l=>{let m=l.split(`
|
|
2
|
+
`);if(m.length<=1)return l.trim();let u=m.filter(P=>P.trim().length>0);if(u.length===0)return"";let f=u.reduce((P,x)=>{let I=x.match(/^([ \t]*)/),T=I?I[1].length:0;return T<P?T:P},1/0);return m.map(P=>P.length>=f?P.slice(f):P.trimStart()).join(`
|
|
3
|
+
`).trim()},"processResult");return n==="all"?h.map(m=>d(m.content)).join(`
|
|
4
|
+
`):h.map(m=>d(m.innerContent)).join(`
|
|
5
|
+
`)}return i}static _processImportBlocks(t){let e=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,s=[];return{processed:t.replace(e,(o,a,i)=>{let r={},c=/(\w+)="([^"]*)"/g;if(i)for(let m of i.matchAll(c))r[m[1]]=m[2];let h=r.src;if(!h)return"";let d;r.block&&(r.block==="all"?d="all":r.block.includes(",")?d=r.block.split(",").map(m=>m.trim()).filter(m=>m):d=r.block);let l={src:h,blocks:d,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:a||""};return s.push(l),`${a}__IMPORT_${s.length-1}__`}),imports:s}}static processImportBlocks(t,e,s=0,n){if(s>10)return"";let{processed:o,imports:a}=this._processImportBlocks(t),i=o;for(let r=0;r<a.length;r++){let c=a[r],h=`${c.src}|${c.base}|${c.lang||""}|${c.section}|${Array.isArray(c.blocks)?c.blocks.join(","):c.blocks||""}`,d;if(n&&n.has(h))d=n.get(h);else{let m=e(c.src);d=m?this._extractBlock(m,c.blocks,c.base,c.section,c.lang):"",d&&d.includes("<import")&&(d=this.processImportBlocks(d,e,s+1,n)),n&&n.set(h,d)}let l=d.split(`
|
|
6
|
+
`).map((m,u)=>u===0?m:c.indent+m).join(`
|
|
7
|
+
`);i=i.replace(`__IMPORT_${r}__`,l)}return i}};var O=class{static{p(this,"TemplateManager")}_map=new Map;_engine=k;_watcher=[];_pageManager=b;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(t){let{path:e,enableWatch:s=!1}=t;this._path=e,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(t.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let t=0;t<this._path.length;t++){let e=this._path[t];if(!(0,y.existsSync)(e))throw new Error(`Template base path is not exists: ${e}`);if(!(0,y.statSync)(e).isDirectory())throw new Error(`Template base path is not a directory: ${e}`)}return!0}catch(t){throw new Error(`Failed to validate Template base path: ${String(t)}`)}}_initializeWatcher(t){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let e=0;e<this._path.length;e++){let s=this._path[e],n=(0,it.watch)(s,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...t});this._watcher[e]=n,n.on("change",this._handleFileChange.bind(this)),n.on("add",this._handleFileAdd.bind(this)),n.on("unlink",this._handleFileDelete.bind(this)),n.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(t){let e=(0,S.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileAdd(t){let e=(0,S.basename)(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileDelete(t){let e=(0,S.basename)(t),s=this._getKey(e);this._map.has(s)&&this._map.delete(s)}_handleWatchError(t){}_loadAllFiles(){let t=new Map,e=[];for(let n=0;n<this._path.length;n++){let o=this._path[n],i=(0,y.readdirSync)(o,"utf8").filter(r=>this._isValidFile(r));for(let r of i){let c=(0,S.join)(o,r),h=this._getExtension(r),d=this._getKey(r);if(h===".html")t.set(d,(0,y.readFileSync)(c,"utf8"));else if(h===".ts"||h===".js"){let l=b.getFileSync(c);l?.template!==void 0&&(t.set(d,l.template),e.push(l))}}}let s=new Map;for(let[n,o]of t.entries())this._compile(n,o,void 0,s,t);t.clear(),s.clear();for(let n of e)n.template=void 0}_loadFile(t){for(let e=0;e<this._path.length;e++){let s=this._path[e],n=(0,S.join)(s,t),o=this._getExtension(t),a=this._getKey(t);if(o==".html"){let i=(0,y.readFileSync)(n,"utf8");this._compile(a,i)}else if(o==".ts"||o==".js"){let i=b.getFileSync(n);i?.template!==void 0&&(this._compile(a,i.template),i.template=void 0)}else throw new Error(`File ${t} is not support`)}}_getExtension(t){return(0,S.extname)(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let s=(0,S.extname)(t).toLowerCase();if(s){let i=(0,S.join)(e,t);if((0,y.existsSync)(i)&&(0,y.statSync)(i).isFile()){if(s===".html")return(0,y.readFileSync)(i,"utf8");if(s===".ts"||s===".js")try{return b.getFileSync(i)?.template??null}catch{return null}}continue}let n=(0,S.join)(e,`${t}.ts`),o=(0,S.join)(e,`${t}.js`);if((0,y.existsSync)(n)&&(0,y.statSync)(n).isFile())try{return b.getFileSync(n)?.template??null}catch{}else if((0,y.existsSync)(o)&&(0,y.statSync)(o).isFile())try{return b.getFileSync(n)?.template??null}catch{}let a=(0,S.join)(e,`${t}.html`);if((0,y.existsSync)(a)&&(0,y.statSync)(a).isFile())return(0,y.readFileSync)(a,"utf8")}return null}_isValidFile(t){return this._supportedExtensions.has(this._getExtension(t))}_getKey(t){return t.replace(/\.[^/.]+$/,"")}_compile(t,e,s,n,o){let a=this._map.get(t),i=a||{},r=!1,c=k.processImportBlocks(e,d=>o&&o.has(d)?o.get(d):this._readTemplateFile(d),0,n),h=k._processBaseBlocks(c);(s===void 0||s?.media===!1||a?.media===void 0)&&(i.media=k.compileMedia(c,h),r=!0),(s===void 0||s?.message===!1||a?.message===void 0)&&(i.message=k.compileMessages(c,h),r=!0),(s===void 0||s?.keyboard===!1||a?.keyboard===void 0)&&(i.keyboard=k.compileKeyboards(c,h),r=!0),(s===void 0||s?.description===!1||a?.description===void 0)&&(i.description=k.compileDescription(c,h),r=!0),r&&this._map.set(t,i)}getMedia(t,e="default",s="default",n){let a=this._map.get(t)?.media?.[e],i=a?.[s]||a?.default;try{if(!i)throw new Error("Media function not found, please check your template");return i(n)}catch{return{}}}getMessage(t,e="default",s="default",n){try{let a=this._map.get(t)?.message?.[e],i=a?.[s]||a?.default;if(!i)throw"";return i(n)}catch{return""}}getDescription(t,e="default",s="default",n="default",o){try{let i=this._map.get(t)?.description?.[e]?.[n],r=i?.[s]||i?.default;if(!r)throw"";return r(o)}catch{return""}}getDescriptionLanguage(t,e="default",s="default"){try{let o=this._map.get(t)?.description?.[e]?.[s];return o?Object.keys(o):[]}catch{return[]}}getDescriptionScopes(t,e="default"){try{let n=this._map.get(t)?.description?.[e];return n?Object.keys(n):[]}catch{return[]}}getKeyboard(t,e="default",s="default",n="inline",o){try{let i=this._map.get(t)?.keyboard?.[e],r=i?.[s]?.[n]||i?.default?.[n];if(!r)throw[];return r(o)}catch{return[]}}async write(t,e){if(this._getExtension(t)!=".html")return null;for(let s=0;s<this._path.length;s++){let n=(0,S.join)(this._path[s],t);if((0,y.existsSync)(n))return(0,y.writeFileSync)(n,e,"utf8"),this._loadFile(t),!0}return null}has(t){return this._map.has(t)}async destroy(){if(this._watcher)for(let t of this._watcher)await t.close();this._map.clear()}};var $=require("grammy");var kt=(0,at.fileURLToPath)(C),wt=(0,v.dirname)(kt),Tt=JSON.parse((0,ot.readFileSync)((0,v.join)(wt,"../../package.json"),"utf-8")).version,j=class{static{p(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 rt.LoggingPretty:t.log?t.log:void 0,this.log?.info?.(`Gramstax v${Tt}`),this.cacheSession=t.cacheSession||new D("memory","session"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new O({path:[(0,v.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:n}=t;this.log?.success?.(`Telegram bot polling started: ${n} ${e=="webhook"||e=="serverless"?`(${s})`:""}`),this.hookAfterStart()}createBot(t){return new $.Bot(t)}createCtx(t){return new A({ct:t,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{isAnswer:!1,session:{},data:{}}})}runPolling(){this.bot.start({onStart:p(t=>{this.onStart(t,"polling",null)},"onStart")})}async runWebhook(t){let{serve:e}=await import("bun"),s=(0,$.webhookCallback)(this.bot,"bun");this.handlerBotUpdate=s;let n=new URL(t).pathname;e({fetch(i){let{pathname:r}=new URL(i.url);if(i.method=="POST"&&r==n)return s(i);if(i.method=="GET"&&r=="/"){let c=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:c}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}}),(await this.bot.api.getWebhookInfo()).url!=t&&await this.bot.api.setWebhook(t);let a=await this.bot.api.getMe();await this.onStart(a,"webhook",t)}async runServerless(t){this.handlerBotUpdate=(0,$.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,v.parse)(e).name}pageSorts(t,e){let s=t.data.name,n=t.prototype,o="Payload",a="Command",i="Caption",r="Free",c=e.routeDynamic,h=e.routeDynamicSpesific,d=p(u=>u.charAt(0).toUpperCase()+u.slice(1),"upFirst"),l=p(u=>u.replace(o,"").replace(a,"").replace(i,"").replace(r,""),"getPureRouteName"),m=p((u,f)=>n[`methodSession${d(u)}`]?.(f),"methodSession");e.all[s]=t;for(let u=0;u<e.lenListRouteStaticSession;u++){let f=e.listRouteStaticSession[u];if(typeof n[f]!="function")continue;let P=e.routeStatic[f],x=e.routeStaticIntent[f],I=e.routeStaticSession[f],T={name:s,routeName:f},H=P||x;if(H!==void 0){let ht=f.includes(a),lt=f.includes("callback"),mt=f.startsWith("text"),M;if(ht){let z=t.data.textCommand||t.data.name;M=z?`/${z}`:void 0}else lt?M=t.data.name:mt?M=t.data.text||t.data.name:M=t.data.name;M&&(H[M]=T)}I!==void 0&&(I[m(f,s)]=T),f.toLowerCase().endsWith("free")&&h[l(f)].push(T)}n.free&&c.push(s)}async executeSyncBlocksDescription(t){let e=new Map,s=t.routeStatic.textCommand;for(let[,n]of Object.entries(s)){let o=n.name,a=this.templateManager.getDescriptionScopes(o);for(let i of a){e.has(i)||e.set(i,new Set);let r=this.templateManager.getDescriptionLanguage(o,"default",i);for(let c of r)e.get(i).add(c)}}for(let[n,o]of e)for(let a of o){let i=[];for(let[,h]of Object.entries(s)){let d=h.name,l=this.templateManager.getDescription(d,"default",a,n);l&&i.push({command:d,description:l})}if(i.length===0)continue;let r={type:n},c=a==="default"?void 0:a;try{let h=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(h.map(m=>({command:m.command,description:m.description})).sort((m,u)=>m.command.localeCompare(u.command))),l=JSON.stringify(i.sort((m,u)=>m.command.localeCompare(u.command)));d!==l&&(await this.bot.api.setMyCommands(i,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${n},${c?` lang: ${c},`:""} total (${i.length})`))}catch(h){this.log?.error?.(`Failed to sync descriptions for scope: ${n},${c?` lang: ${c},`:""} error: ${String(h)}`)}}}pageLoads(){this.log?.info?.("Load pages..");let t=["callback","text","textCommand","photoCaption","photoCaptionCommand","videoCaption","videoCaptionCommand","audioCaption","audioCaptionCommand","documentCaption","documentCaptionCommand","animationCaption","animationCaptionCommand","voiceCaption","voiceCaptionCommand","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"],n=p((i,r)=>Object.fromEntries(i.map(c=>[c,r()])),"makeObject"),o=p(()=>[],"initDynamicSpesific"),a={all:{},routeDynamic:[],routeDynamicSpesific:{text:o(),photo:o(),video:o(),audio:o(),document:o(),animation:o(),voice:o(),videoNote:o(),sticker:o(),location:o(),contact:o()},routeStatic:n(t,()=>({})),routeStaticIntent:n(e,()=>({})),routeStaticSession:n(s,()=>({})),listRouteStatic:t,listRouteStaticIntent:e,listRouteStaticSession:s,lenListRouteStatic:t.length,lenListRouteStaticIntent:e.length,lenListRouteStaticSession:s.length};return b.getFileManySync(void 0).forEach(({path:i,page:r})=>{this.pageBuildData(r,i),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,n;if(s===void 0){let a=t.callbackData,i=t.msgText,r=t.msgCaption,c=this.pages.routeStatic;for(let h=0;h<this.pages.lenListRouteStatic;h++){let d=this.pages.listRouteStatic[h];if(d.startsWith(e)&&(n=c[d][a||i||r]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s===void 0){let a=await t.sessionGet();if(a){let i=a.method,r=this.pages.routeStaticSession;for(let c=0;c<this.pages.lenListRouteStaticSession;c++){let h=this.pages.listRouteStaticSession[c];if(h.startsWith(e)&&(n=r[h][i]),n)break}n!==void 0&&(s=this.pages.all[n.name])}}if(s===void 0){let a=this.pages.routeStaticIntent,i=e==="callback",r=i?"colon":"space",c=i?t.callbackData:t.msgText||t.msgCaption,h=t.havePayloads(c,r);if(c&&h)for(let d=0;d<this.pages.lenListRouteStaticIntent;d++){let l=this.pages.listRouteStaticIntent[d];if(!l.startsWith(e))continue;let m=a[l];if(n=m[t.getIntent(c,r,1)],!n&&!i&&(n=m[t.getIntent(c,"space",2)]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s!==void 0&&n!==void 0)return s.prototype[n.routeName]?await new s(t)[n.routeName]?.():void 0;let o=this.pages.routeDynamicSpesific[e]||[];for(let a=0;a<o.length;a++){let i=o[a];if(i===void 0)continue;let r=this.pages.all[i.name];r!==void 0&&typeof r.prototype[i.routeName]=="function"&&await new r(t)[i.routeName]()}for(let a=0;a<this.pages.routeDynamic.length;a++){let i=this.pages.routeDynamic[a];if(i===void 0)continue;let r=this.pages.all[i];r!==void 0&&typeof r.prototype.free=="function"&&await new r(t).free()}if(t.temp.isAnswer===!1)return null}async hookBeforeRoute(t,e){return!!(t||e)}async hookErrorPage(t,e,s,n){}async hookErrorInputNotFoundPage(t){}async onMessage(t,e){let s=this.createCtx(t);try{if(await this.hookBeforeRoute(s,e)===!1)return;await this.pageRoutes(s,e)===null&&await this.hookErrorInputNotFoundPage(s)}catch(n){await this.hookErrorPage(s,e,n,!1)}}async onCallbackQueryData(t){let e=this.createCtx(t);try{if(await 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 q=class{static{p(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(s):s}</keyboard>
|
|
9
|
+
`}return Object.keys(t).map(s=>{let n=t[s];return`
|
|
10
|
+
<keyboard type="${e.type}" lang="${s}">${e.reverse?this.data._reverse(n):n}</keyboard>
|
|
11
|
+
`}).join(" ")}static _build(t,e,s){if(!this.data)throw new Error("Data not found");let n=this.data[t];if(!n)throw new Error(`Function ${t} not found`);return this._process(n.call(this.data,e),{type:s,lang:e})}};var G=class{static{p(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 n=s[t||""];return e?this._reverse(n):n}return e?this._reverseObj(s):s}};var L=require("worker_threads");var w=class{constructor(t,e){this.send=t;this.register=e}static{p(this,"WorkerThreadRpc")}map=new Map;async make(t){let e=this.map,s=this.send,{id:n,method:o,params:a,result:i,error:r}=t;if(o!==void 0)try{let c=this.register[o];if(typeof c!="function")throw new Error(`Method ${o} not found or not function`);let h=await c.apply(this.register,a);s({id:n,result:h})}catch(c){s({id:n,error:c instanceof Error?{message:c.message,stack:c.stack,name:c.name}:c})}else if(i!==void 0){let c=e.get(n);c&&(c.resolve(i),e.delete(n))}else if(r!==void 0){let c=e.get(n);c&&(c.reject(r),e.delete(n))}}makeId(){return Math.random()}makeRequest(t,e,s=!0,n){let o=this.makeId(),a={id:o,method:t,params:e,...n};return s?new Promise((i,r)=>{this.map.set(o,{resolve:i,reject:r}),this.send(a)}):this.send(a)}};var W=class{constructor(t,e){this.path=t;this.argv=e;this.init(),this.rpc=new w(this.send.bind(this),this)}static{p(this,"WorkerThreadLaunch")}static isMainThread=L.isMainThread;_readyResolve;_readyPromise=new Promise(t=>this._readyResolve=t);pid=process.pid;thread={};threadId={};rpc={};ready(){return this._readyPromise}mtdReady(){this._readyResolve?.()}init(){this.thread=new L.Worker(this.path,{argv:this.argv.length==0&&this.argv[0]===void 0?void 0:this.argv}),this.threadId=this.thread.threadId,this.thread.on("message",t=>this.handleOnMessage(t))}async handleOnMessage(t){this.rpc.make(t)}kill(){this.thread.terminate()}send(t){this.thread.postMessage(t)}async request(t,e,s=!0,n){return this.rpc.makeRequest(t,e,s,n)}};var U=class g{static{p(this,"WorkerThreadExport")}static gateway(t){let e=new Proxy({},{get(n,o){if(!(typeof o!="string"||o==="then"))return async(a,...i)=>{let r=a.gatewayClients.get(t);return r||(r=await a.createGatewayClient(t)),r.request(o,i)}}}),s=p(function(n){return new Proxy({},{get(o,a){if(!(typeof a!="string"||a==="then"))return async(...i)=>{let r=n.gatewayClients.get(t);return r||(r=await n.createGatewayClient(t)),r.request(a,i)}}})},"ctor");return Object.setPrototypeOf(s,e),s}static init(t){let{WTInit:e,WTLaunch:s=W,path:n,wrap:o}=t,a=`for-${n}`;if(process.argv[2]===a)return new e,{gateway:p(d=>g.gateway(d),"gateway")};let i,r=new Proxy({},{get(d,l){if(l!=="then")return l==="sendRequest"||l==="request"||l==="kill"||l==="send"?(...m)=>{if(!i)throw new Error(`Thread at ${n} not launched yet.`);return i[l](...m)}:(...m)=>{if(!i)throw new Error(`Thread at ${n} not launched yet.`);return i.request(l,m)}}}),h={...o?o(r):{},launchWorker:p(async(d=[])=>(i=new s(n,[a,...d]),await i.ready(),i),"launchWorker"),gateway:p(d=>g.gateway(d),"gateway")};return new Proxy(h,{get(d,l){if(l!=="then")return l==="gateway"?d.gateway:l==="launchWorker"?d.launchWorker:l in d?d[l]:typeof l=="string"?(...m)=>{if(!i)throw new Error(`Thread at ${n} not launched yet.`);return i.request(l,m)}:d[l]}})}};var ct=require("net-ipc");var B=class{static{p(this,"WorkerThreadGatewayClient")}client=new ct.Client;rpc;constructor(){this.rpc=new w(t=>this.client.send(t),{}),this.client.on("message",t=>{this.rpc.make(t)})}async connect(t){this.client.options.path=t;let e=new Promise(s=>{this.client.once("ready",()=>s(this))});return await this.client.connect(),e}async request(t,e,s=!0,n){return this.rpc.makeRequest(t,e,s,n)}};var dt=require("net-ipc");var N=class{static{p(this,"WorkerThreadGatewayServer")}server=new dt.Server;rpc=new Map;methods={};constructor(){this.server.on("connect",t=>{let e=new w(s=>t.send(s),this.methods);this.rpc.set(t.id,e)}),this.server.on("disconnect",t=>{this.rpc.delete(t.id)}),this.server.on("message",(t,e)=>{let s=this.rpc.get(e.id);s&&s.make(t)}),this.server.on("error",t=>{console.error(t)})}async start(t,e={}){this.methods=e,this.server.options.path=t;let s=new Promise(n=>{this.server.once("ready",()=>n(this))});return await this.server.start(),s}};var R=require("worker_threads");var Q=class{static{p(this,"WorkerThreadInit")}argv=process.argv;id=R.threadId;pid=process.pid;rpc={};parentPort=R.parentPort;gatewayServer;gatewayClients=new Map;gatewayClientLatest;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=R.isMainThread;constructor(){this.init(),this.rpc=new w(this.send.bind(this),this),this.send({method:"mtdReady"})}init(){this.parentPort?.on("message",t=>this.handleOnMessage(t))}handleOnMessage(t){this.rpc.make(t)}send(t){this.parentPort?.postMessage(t)}request(t,e,s=!0,n){return this.rpc.makeRequest(t,e,s,n)}async createGatewayServer(t,e={}){return this.gatewayServer=new N,await this.gatewayServer.start(t,e),!0}async createGatewayClient(t){let e=new B;return await e.connect(t),this.gatewayClients.set(t,e),this.gatewayClientLatest=e,e}};var J=class{static{p(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(t){this.addMany(t)}add(t){this.thread.set(t.threadId,t),this.threadCount+=1}addMany(t){t.forEach(e=>this.add(e))}getInstance(t){return this.thread.get(t)}kill(t){let e=this.thread.get(t);return e?.kill(),this.thread.delete(t),this.threadCount-=1,e?.threadId}killAll(){this.thread.values().forEach(({threadId:t})=>this.kill(t))}async broadcastRequest(t,e){return await Promise.all(Object.values(this.thread).map(s=>s.request(t,e,!0)))}async request(t,e,s,n=!0,o){return await this.thread.get(t)?.request(e,s,n,o)}};0&&(module.exports={CacheExternal,ComponentKeyboard,Ctx,DataKeyboard,Gramstax,LoggingUtils,TemplateEngine,TemplateManager,WorkerThreadExport,WorkerThreadGatewayClient,WorkerThreadGatewayServer,WorkerThreadInit,WorkerThreadLaunch,WorkerThreadPool,WorkerThreadRpc,log});
|
package/dist/src/index.d.cts
CHANGED
|
@@ -11,7 +11,7 @@ import { Server, Client } from 'net-ipc';
|
|
|
11
11
|
|
|
12
12
|
declare class LoggingUtils extends LoggingPretty {
|
|
13
13
|
constructor(options?: ConstructorParameters<typeof LoggingPretty>[0]);
|
|
14
|
-
errorMake(error: any,
|
|
14
|
+
errorMake(error: any, constructorName?: any, funcName?: string): void;
|
|
15
15
|
}
|
|
16
16
|
declare const log: LoggingUtils;
|
|
17
17
|
|
|
@@ -252,6 +252,7 @@ type IPageData<T extends any[] = any[]> = {
|
|
|
252
252
|
_positionPayloadText: number;
|
|
253
253
|
};
|
|
254
254
|
type ITemp = {
|
|
255
|
+
isAnswer: boolean;
|
|
255
256
|
session: {
|
|
256
257
|
method?: string;
|
|
257
258
|
params?: any;
|
|
@@ -359,57 +360,58 @@ declare class Ctx {
|
|
|
359
360
|
data?: IData;
|
|
360
361
|
cache?: boolean;
|
|
361
362
|
}): IBottomKb;
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
363
|
+
getSeperatorTag(mtd?: `space` | `colon`): " " | ":";
|
|
364
|
+
havePayloads(str: string | undefined, mtd: Parameters<typeof this.getSeperatorTag>[0]): boolean;
|
|
365
|
+
getPayloads(str: string | undefined, mtd: Parameters<typeof this.getSeperatorTag>[0], positionStart?: number): string[];
|
|
366
|
+
getIntent(str: string | undefined, mtd: Parameters<typeof this.getSeperatorTag>[0], positionEnd?: number): string;
|
|
367
|
+
to?(...args: any): Promise<any>;
|
|
368
|
+
core?(...args: any): Promise<any>;
|
|
369
|
+
callback?(): Promise<void | null>;
|
|
370
|
+
callbackPayload?(): Promise<void | null>;
|
|
371
|
+
text?(): Promise<void | null>;
|
|
372
|
+
textPayload?(): Promise<void | null>;
|
|
373
|
+
textCommand?(): Promise<void | null>;
|
|
374
|
+
textCommandPayload?(): Promise<void | null>;
|
|
375
|
+
textFree?(): Promise<void | null>;
|
|
376
|
+
photoCaption?(): Promise<void | null>;
|
|
377
|
+
photoCaptionPayload?(): Promise<void | null>;
|
|
378
|
+
photoCaptionCommand?(): Promise<void | null>;
|
|
379
|
+
photoCaptionCommandPayload?(): Promise<void | null>;
|
|
380
|
+
photoFree?(): Promise<void | null>;
|
|
381
|
+
videoCaption?(): Promise<void | null>;
|
|
382
|
+
videoCaptionPayload?(): Promise<void | null>;
|
|
383
|
+
videoCaptionCommand?(): Promise<void | null>;
|
|
384
|
+
videoCaptionCommandPayload?(): Promise<void | null>;
|
|
385
|
+
videoFree?(): Promise<void | null>;
|
|
386
|
+
audioCaption?(): Promise<void | null>;
|
|
387
|
+
audioCaptionPayload?(): Promise<void | null>;
|
|
388
|
+
audioCaptionCommand?(): Promise<void | null>;
|
|
389
|
+
audioCaptionCommandPayload?(): Promise<void | null>;
|
|
390
|
+
audioFree?(): Promise<void | null>;
|
|
391
|
+
documentCaption?(): Promise<void | null>;
|
|
392
|
+
documentCaptionPayload?(): Promise<void | null>;
|
|
393
|
+
documentCaptionCommand?(): Promise<void | null>;
|
|
394
|
+
documentCaptionCommandPayload?(): Promise<void | null>;
|
|
395
|
+
documentFree?(): Promise<void | null>;
|
|
396
|
+
animationCaption?(): Promise<void | null>;
|
|
397
|
+
animationCaptionPayload?(): Promise<void | null>;
|
|
398
|
+
animationCaptionCommand?(): Promise<void | null>;
|
|
399
|
+
animationCaptionCommandPayload?(): Promise<void | null>;
|
|
400
|
+
animationFree?(): Promise<void | null>;
|
|
401
|
+
voiceCaption?(): Promise<void | null>;
|
|
402
|
+
voiceCaptionPayload?(): Promise<void | null>;
|
|
403
|
+
voiceCaptionCommand?(): Promise<void | null>;
|
|
404
|
+
voiceCaptionCommandPayload?(): Promise<void | null>;
|
|
405
|
+
voiceFree?(): Promise<void | null>;
|
|
406
|
+
videoNoteCaption?(): Promise<void | null>;
|
|
407
|
+
videoNoteCaptionPayload?(): Promise<void | null>;
|
|
408
|
+
videoNoteCaptionCommand?(): Promise<void | null>;
|
|
409
|
+
videoNoteCaptionCommandPayload?(): Promise<void | null>;
|
|
410
|
+
videoNoteFree?(): Promise<void | null>;
|
|
411
|
+
stickerFree?(): Promise<void | null>;
|
|
412
|
+
locationFree?(): Promise<void | null>;
|
|
413
|
+
contactFree?(): Promise<void | null>;
|
|
414
|
+
free?(): Promise<void | null>;
|
|
413
415
|
validateSessionCallback(method?: string, name?: string): boolean;
|
|
414
416
|
validateSessionCallbackPayload(method?: string, name?: string): boolean;
|
|
415
417
|
validateSessionText(method?: string, name?: string): boolean;
|
|
@@ -1031,6 +1033,22 @@ declare class Gramstax<ICtx extends Ctx = Ctx> {
|
|
|
1031
1033
|
registerOnMessageContact(): void;
|
|
1032
1034
|
}
|
|
1033
1035
|
|
|
1036
|
+
declare class DataKeyboard {
|
|
1037
|
+
static _reverse(input: string): string;
|
|
1038
|
+
static _reverseObj(input: any): any;
|
|
1039
|
+
static _build(lang: string | undefined, reverse: boolean | undefined, obj: any): string;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
declare class ComponentKeyboard {
|
|
1043
|
+
static data: typeof DataKeyboard;
|
|
1044
|
+
static _process(obj: any, params: {
|
|
1045
|
+
type?: string;
|
|
1046
|
+
lang?: string;
|
|
1047
|
+
reverse?: boolean;
|
|
1048
|
+
}): string;
|
|
1049
|
+
static _build(key: string, lang?: string, type?: string): string;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1034
1052
|
type IMapRpc = Map<any, {
|
|
1035
1053
|
reject: (error: any) => any;
|
|
1036
1054
|
resolve: (result: any) => any;
|
|
@@ -1048,13 +1066,13 @@ declare class WorkerThreadRpc {
|
|
|
1048
1066
|
declare class WorkerThreadLaunch {
|
|
1049
1067
|
path: string;
|
|
1050
1068
|
argv: any[];
|
|
1069
|
+
static isMainThread: boolean;
|
|
1070
|
+
private _readyResolve?;
|
|
1071
|
+
private _readyPromise;
|
|
1051
1072
|
pid: number;
|
|
1052
1073
|
thread: Worker;
|
|
1053
1074
|
threadId: number;
|
|
1054
1075
|
rpc: WorkerThreadRpc;
|
|
1055
|
-
private _readyResolve?;
|
|
1056
|
-
private _readyPromise;
|
|
1057
|
-
static isMainThread: boolean;
|
|
1058
1076
|
constructor(path: string, argv: any[]);
|
|
1059
1077
|
ready(): Promise<void>;
|
|
1060
1078
|
mtdReady(): void;
|
|
@@ -1138,20 +1156,4 @@ declare class WorkerThreadPool {
|
|
|
1138
1156
|
request(threadId: number, method: string, params: any, _wait?: boolean, _others?: any): Promise<any>;
|
|
1139
1157
|
}
|
|
1140
1158
|
|
|
1141
|
-
|
|
1142
|
-
static _reverse(input: string): string;
|
|
1143
|
-
static _reverseObj(input: any): any;
|
|
1144
|
-
static _build(lang: string | undefined, reverse: boolean | undefined, obj: any): string;
|
|
1145
|
-
}
|
|
1146
|
-
|
|
1147
|
-
declare class ComponentKeyboard {
|
|
1148
|
-
static data: typeof DataKeyboard;
|
|
1149
|
-
static _process(obj: any, params: {
|
|
1150
|
-
type?: string;
|
|
1151
|
-
lang?: string;
|
|
1152
|
-
reverse?: boolean;
|
|
1153
|
-
}): string;
|
|
1154
|
-
static _build(key: string, lang?: string, type?: string): string;
|
|
1155
|
-
}
|
|
1156
|
-
|
|
1157
|
-
export { CacheExternal, ComponentKeyboard, Ctx, DataKeyboard, Gramstax, type IMediaBlock, LoggingUtils, TemplateEngine, TemplateManager, type WorkerThreadAsyncMethods, WorkerThreadExport, type WorkerThreadExportOpt, WorkerThreadGatewayClient, type WorkerThreadGatewayProxy, WorkerThreadGatewayServer, WorkerThreadInit, WorkerThreadLaunch, WorkerThreadPool, log };
|
|
1159
|
+
export { CacheExternal, ComponentKeyboard, Ctx, DataKeyboard, Gramstax, type IMapRpc, type IMediaBlock, LoggingUtils, TemplateEngine, TemplateManager, type WorkerThreadAsyncMethods, WorkerThreadExport, type WorkerThreadExportOpt, WorkerThreadGatewayClient, type WorkerThreadGatewayProxy, WorkerThreadGatewayServer, WorkerThreadInit, WorkerThreadLaunch, WorkerThreadPool, WorkerThreadRpc, log };
|
package/dist/src/index.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ import { Server, Client } from 'net-ipc';
|
|
|
11
11
|
|
|
12
12
|
declare class LoggingUtils extends LoggingPretty {
|
|
13
13
|
constructor(options?: ConstructorParameters<typeof LoggingPretty>[0]);
|
|
14
|
-
errorMake(error: any,
|
|
14
|
+
errorMake(error: any, constructorName?: any, funcName?: string): void;
|
|
15
15
|
}
|
|
16
16
|
declare const log: LoggingUtils;
|
|
17
17
|
|
|
@@ -252,6 +252,7 @@ type IPageData<T extends any[] = any[]> = {
|
|
|
252
252
|
_positionPayloadText: number;
|
|
253
253
|
};
|
|
254
254
|
type ITemp = {
|
|
255
|
+
isAnswer: boolean;
|
|
255
256
|
session: {
|
|
256
257
|
method?: string;
|
|
257
258
|
params?: any;
|
|
@@ -359,57 +360,58 @@ declare class Ctx {
|
|
|
359
360
|
data?: IData;
|
|
360
361
|
cache?: boolean;
|
|
361
362
|
}): IBottomKb;
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
363
|
+
getSeperatorTag(mtd?: `space` | `colon`): " " | ":";
|
|
364
|
+
havePayloads(str: string | undefined, mtd: Parameters<typeof this.getSeperatorTag>[0]): boolean;
|
|
365
|
+
getPayloads(str: string | undefined, mtd: Parameters<typeof this.getSeperatorTag>[0], positionStart?: number): string[];
|
|
366
|
+
getIntent(str: string | undefined, mtd: Parameters<typeof this.getSeperatorTag>[0], positionEnd?: number): string;
|
|
367
|
+
to?(...args: any): Promise<any>;
|
|
368
|
+
core?(...args: any): Promise<any>;
|
|
369
|
+
callback?(): Promise<void | null>;
|
|
370
|
+
callbackPayload?(): Promise<void | null>;
|
|
371
|
+
text?(): Promise<void | null>;
|
|
372
|
+
textPayload?(): Promise<void | null>;
|
|
373
|
+
textCommand?(): Promise<void | null>;
|
|
374
|
+
textCommandPayload?(): Promise<void | null>;
|
|
375
|
+
textFree?(): Promise<void | null>;
|
|
376
|
+
photoCaption?(): Promise<void | null>;
|
|
377
|
+
photoCaptionPayload?(): Promise<void | null>;
|
|
378
|
+
photoCaptionCommand?(): Promise<void | null>;
|
|
379
|
+
photoCaptionCommandPayload?(): Promise<void | null>;
|
|
380
|
+
photoFree?(): Promise<void | null>;
|
|
381
|
+
videoCaption?(): Promise<void | null>;
|
|
382
|
+
videoCaptionPayload?(): Promise<void | null>;
|
|
383
|
+
videoCaptionCommand?(): Promise<void | null>;
|
|
384
|
+
videoCaptionCommandPayload?(): Promise<void | null>;
|
|
385
|
+
videoFree?(): Promise<void | null>;
|
|
386
|
+
audioCaption?(): Promise<void | null>;
|
|
387
|
+
audioCaptionPayload?(): Promise<void | null>;
|
|
388
|
+
audioCaptionCommand?(): Promise<void | null>;
|
|
389
|
+
audioCaptionCommandPayload?(): Promise<void | null>;
|
|
390
|
+
audioFree?(): Promise<void | null>;
|
|
391
|
+
documentCaption?(): Promise<void | null>;
|
|
392
|
+
documentCaptionPayload?(): Promise<void | null>;
|
|
393
|
+
documentCaptionCommand?(): Promise<void | null>;
|
|
394
|
+
documentCaptionCommandPayload?(): Promise<void | null>;
|
|
395
|
+
documentFree?(): Promise<void | null>;
|
|
396
|
+
animationCaption?(): Promise<void | null>;
|
|
397
|
+
animationCaptionPayload?(): Promise<void | null>;
|
|
398
|
+
animationCaptionCommand?(): Promise<void | null>;
|
|
399
|
+
animationCaptionCommandPayload?(): Promise<void | null>;
|
|
400
|
+
animationFree?(): Promise<void | null>;
|
|
401
|
+
voiceCaption?(): Promise<void | null>;
|
|
402
|
+
voiceCaptionPayload?(): Promise<void | null>;
|
|
403
|
+
voiceCaptionCommand?(): Promise<void | null>;
|
|
404
|
+
voiceCaptionCommandPayload?(): Promise<void | null>;
|
|
405
|
+
voiceFree?(): Promise<void | null>;
|
|
406
|
+
videoNoteCaption?(): Promise<void | null>;
|
|
407
|
+
videoNoteCaptionPayload?(): Promise<void | null>;
|
|
408
|
+
videoNoteCaptionCommand?(): Promise<void | null>;
|
|
409
|
+
videoNoteCaptionCommandPayload?(): Promise<void | null>;
|
|
410
|
+
videoNoteFree?(): Promise<void | null>;
|
|
411
|
+
stickerFree?(): Promise<void | null>;
|
|
412
|
+
locationFree?(): Promise<void | null>;
|
|
413
|
+
contactFree?(): Promise<void | null>;
|
|
414
|
+
free?(): Promise<void | null>;
|
|
413
415
|
validateSessionCallback(method?: string, name?: string): boolean;
|
|
414
416
|
validateSessionCallbackPayload(method?: string, name?: string): boolean;
|
|
415
417
|
validateSessionText(method?: string, name?: string): boolean;
|
|
@@ -1031,6 +1033,22 @@ declare class Gramstax<ICtx extends Ctx = Ctx> {
|
|
|
1031
1033
|
registerOnMessageContact(): void;
|
|
1032
1034
|
}
|
|
1033
1035
|
|
|
1036
|
+
declare class DataKeyboard {
|
|
1037
|
+
static _reverse(input: string): string;
|
|
1038
|
+
static _reverseObj(input: any): any;
|
|
1039
|
+
static _build(lang: string | undefined, reverse: boolean | undefined, obj: any): string;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
declare class ComponentKeyboard {
|
|
1043
|
+
static data: typeof DataKeyboard;
|
|
1044
|
+
static _process(obj: any, params: {
|
|
1045
|
+
type?: string;
|
|
1046
|
+
lang?: string;
|
|
1047
|
+
reverse?: boolean;
|
|
1048
|
+
}): string;
|
|
1049
|
+
static _build(key: string, lang?: string, type?: string): string;
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1034
1052
|
type IMapRpc = Map<any, {
|
|
1035
1053
|
reject: (error: any) => any;
|
|
1036
1054
|
resolve: (result: any) => any;
|
|
@@ -1048,13 +1066,13 @@ declare class WorkerThreadRpc {
|
|
|
1048
1066
|
declare class WorkerThreadLaunch {
|
|
1049
1067
|
path: string;
|
|
1050
1068
|
argv: any[];
|
|
1069
|
+
static isMainThread: boolean;
|
|
1070
|
+
private _readyResolve?;
|
|
1071
|
+
private _readyPromise;
|
|
1051
1072
|
pid: number;
|
|
1052
1073
|
thread: Worker;
|
|
1053
1074
|
threadId: number;
|
|
1054
1075
|
rpc: WorkerThreadRpc;
|
|
1055
|
-
private _readyResolve?;
|
|
1056
|
-
private _readyPromise;
|
|
1057
|
-
static isMainThread: boolean;
|
|
1058
1076
|
constructor(path: string, argv: any[]);
|
|
1059
1077
|
ready(): Promise<void>;
|
|
1060
1078
|
mtdReady(): void;
|
|
@@ -1138,20 +1156,4 @@ declare class WorkerThreadPool {
|
|
|
1138
1156
|
request(threadId: number, method: string, params: any, _wait?: boolean, _others?: any): Promise<any>;
|
|
1139
1157
|
}
|
|
1140
1158
|
|
|
1141
|
-
|
|
1142
|
-
static _reverse(input: string): string;
|
|
1143
|
-
static _reverseObj(input: any): any;
|
|
1144
|
-
static _build(lang: string | undefined, reverse: boolean | undefined, obj: any): string;
|
|
1145
|
-
}
|
|
1146
|
-
|
|
1147
|
-
declare class ComponentKeyboard {
|
|
1148
|
-
static data: typeof DataKeyboard;
|
|
1149
|
-
static _process(obj: any, params: {
|
|
1150
|
-
type?: string;
|
|
1151
|
-
lang?: string;
|
|
1152
|
-
reverse?: boolean;
|
|
1153
|
-
}): string;
|
|
1154
|
-
static _build(key: string, lang?: string, type?: string): string;
|
|
1155
|
-
}
|
|
1156
|
-
|
|
1157
|
-
export { CacheExternal, ComponentKeyboard, Ctx, DataKeyboard, Gramstax, type IMediaBlock, LoggingUtils, TemplateEngine, TemplateManager, type WorkerThreadAsyncMethods, WorkerThreadExport, type WorkerThreadExportOpt, WorkerThreadGatewayClient, type WorkerThreadGatewayProxy, WorkerThreadGatewayServer, WorkerThreadInit, WorkerThreadLaunch, WorkerThreadPool, log };
|
|
1159
|
+
export { CacheExternal, ComponentKeyboard, Ctx, DataKeyboard, Gramstax, type IMapRpc, type IMediaBlock, LoggingUtils, TemplateEngine, TemplateManager, type WorkerThreadAsyncMethods, WorkerThreadExport, type WorkerThreadExportOpt, WorkerThreadGatewayClient, type WorkerThreadGatewayProxy, WorkerThreadGatewayServer, WorkerThreadInit, WorkerThreadLaunch, WorkerThreadPool, WorkerThreadRpc, log };
|
package/dist/src/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
var ot=Object.defineProperty;var h=(g,t)=>ot(g,"name",{value:t,configurable:!0}),$=(g=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(g,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):g)(function(g){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+g+'" is not supported')});import{LoggingPretty as at}from"logging-pretty";var B=class extends at{static{h(this,"LoggingUtils")}constructor(t){super(t)}errorMake(t,e,s){this.error(`[${e?.name||e}:${s}] ${String(t)}`)}},Vt=new B;import{Keyv as rt}from"keyv";import ct from"@keyv/redis";var F=class extends rt{constructor(e="memory",s,i,o){let a;e.startsWith("redis")&&(a=new ct(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 lt}from"timers/promises";import{InlineKeyboard as j,Keyboard as q}from"grammy";var R=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||this.temp?.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 lt(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 j,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 j,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 q,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 q,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 z,parse as mt,dirname as gt}from"path";import{readFileSync as yt}from"fs";import{fileURLToPath as bt}from"url";import{join as N}from"path";import{existsSync as G,readdirSync as Q}from"fs";import{createRequire as dt}from"module";var S=class{static{h(this,"PageManager")}static _getFile(t,e,s=0){let o=Object.values(t)[s];if(o===void 0)throw new Error(`File ${e} must have export (not default) class page`);return o}static getFilePath(){return N(process.cwd(),"src","pages")}static getFileSync(t,e=0){t||(t=this.getFilePath());let i=dt(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()),!G(t))throw new Error(`Directory ${t} is not found, please make it manually`);return Q(t).map(i=>{let o=N(t,i);return{path:o,page:this.getFileSync(o,e)}})}static clearCacheRequire(t){if(t||(t=this.getFilePath()),!G(t))throw new Error(`Directory ${t} is not found, please make it manually`);return Q(t).forEach(s=>{let i=N(t,s);delete $.cache[$.resolve(i)]}),!0}};import{LoggingPretty as ft}from"logging-pretty";import{basename as K,join as T,extname as J}from"path";import{readdirSync as pt,readFileSync as V,existsSync as M,statSync as _,writeFileSync as ut}from"fs";import{watch as ht}from"chokidar";var P=class{static{h(this,"TemplateEngine")}static _escape(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processVariables(t){return t.replace(/\{\{(\w+)\}\}/g,(e,s)=>`\${(data && data["${s}"]) ?? ""}`)}static _processBaseBlocks(t){let e=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,s={};for(let i of t.matchAll(e)){let o=i[2]??"default",n=(i[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[o]=n}return s}static _processScriptBlocks(t){return t.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(e,s)=>{let i=s.trim();return i?`\${(() => { if (!data) return ''; try { with(data) { ${i} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(t){return t.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(t){return t.replace(/<div>([\s\S]*?)<\/div>/gi,(e,s)=>s.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(t){let e=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return t.replace(e,(s,i,o)=>{if(!i)return"";let a="",n=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=n.exec(o))!==null;){let d=(c[1]||"").split(",").map(u=>u.trim()),p=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(u=>{a+=`case "${u}": `}),a+=`return \`${p}\`; `}let l=r.exec(o);if(l){let d=(l[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");a+=`default: return \`${d}\`; `}else a+="default: return ''; ";return`\${(() => { switch((data && data["${i}"])) { ${a} } })()}`})}static _processExec(t){return t.replace(/{~\s*([\s\S]*?)\s*~}/g,(e,s)=>`\${(() => { try { return ${s} } catch(e) { try { with(data || {}) { return ${s} } } catch(ee) { return '' } } })()}`)}static _processMapBlocks(t){let e=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return t.replace(e,(s,i,o)=>{let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let p of i.matchAll(n))a[p[1]]=p[2];let r=a.src;if(!r)return"";let c=a.join??"\\n",l=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");l=l.replace(/\{\{([\w.]+)\}\}/g,(p,u)=>u==="e"||u.startsWith("e.")?`\${${u}}`:u==="i"?"${i}":p);let d=c.replace(/"/g,'\\"');return`\${(data && data["${r}"] || []).map((e, i) => \`${l}\`).join("${d}")}`})}static _processMediaBlocks(t){let e=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let i of t.matchAll(e)){let o=i[1],a=i[2],n={},r=/(\w+)="([^"]*)"/g;if(o)for(let u of o.matchAll(r))n[u[1]]=u[2];let c=n.lang||"default",l=n.type,d=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),p={type:l};n.src&&(p.src=n.src),d&&l!=="video_note"&&l!=="sticker"&&(p.caption=d),l==="location"&&(n.latitude&&(p.latitude=n.latitude),n.longitude&&(p.longitude=n.longitude),d&&(p.caption=d)),l==="contact"&&(n.phone&&(p.phone=n.phone),n.first_name&&(p.first_name=n.first_name),n.last_name&&(p.last_name=n.last_name),n.vcard&&(p.vcard=n.vcard),d&&(p.caption=d)),s[c]=p}return s}static _processMessageBlocks(t){let e=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,i,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let l of i.matchAll(n))a[l[1]]=l[2];let r=a.lang||"default",c=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=c}return s}static _processDescriptionBlocks(t){let e=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,i,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let d of i.matchAll(n))a[d[1]]=d[2];let r=a.lang||"default",c=a.scope||"default",l=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][c]=l}return s}static _processKeyboardBlocks(t){let e=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,i,o]of t.matchAll(e)){let a={},n=/(\w+)="([^"]*)"/g;if(i)for(let d of i.matchAll(n))a[d[1]]=d[2];let r=a.lang||"default",c=a.type==="bottom"?"bottom":"inline",l=o.trim();s[r]||(s[r]={}),s[r][c]=l}return s}static _compileToFunction(t,e){let s;e?s=t.map(a=>`\`${a}\``).join(","):s=`\`${t}\``;let i=s;if(i=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(i))),e){let o=`return [${i}]`;return new Function("data",o)}else{let o=`return ${i}`;return new Function("data",o)}}static compileMedia(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processMediaBlocks(a);i[o]={};for(let[r,c]of Object.entries(n)){let l={};for(let[d,p]of Object.entries(c)){if(d==="type"||typeof p!="string")continue;let u=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(p)))));l[d]=this._compileToFunction(u,!1)}i[o][r]=d=>{let p={...c};for(let[u,m]of Object.entries(l))p[u]=m(d);return p}}}return i}static compileMessages(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processMessageBlocks(a);i[o]={};for(let[r,c]of Object.entries(n)){let l=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));i[o][r]=this._compileToFunction(l,!1)}}return i}static compileDescription(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processDescriptionBlocks(a);i[o]={};for(let[r,c]of Object.entries(n))for(let[l,d]of Object.entries(c)){i[o][l]||(i[o][l]={});let p=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));i[o][l][r]=this._compileToFunction(p,!1)}}return i}static compileKeyboards(t,e){let s=e||this._processBaseBlocks(t),i={};for(let[o,a]of Object.entries(s)){let n=this._processKeyboardBlocks(a);i[o]={};for(let[r,c]of Object.entries(n)){i[o][r]={};for(let[l,d]of Object.entries(c)){let u=d.split(/(?<!\\),\s*/).map(m=>m.replace(/\\,/g,",").trim()).map(m=>this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(m))))));i[o][r][l]=this._compileToFunction(u,!0)}}}return i}static _extractBlock(t,e,s="default",i="all",o){let a=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,n=t,r=!1;for(let c of t.matchAll(a))if((c[2]??"default")===s){n=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(t);if(!(s==="default"&&!c))return""}if(e){if(e==="all")return n;let c=Array.isArray(e)?e:[e],l=[];for(let p of c){let u=new RegExp(`([ \\t]*)<${p}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${p}>`,"gi");for(let m of n.matchAll(u)){let y=m[2];if(o){let C=/lang="([^"]*)"/i,w=y?.match(C);if(((w?w[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(
|
|
3
|
-
`).trim()},"processResult");return
|
|
4
|
-
`):
|
|
5
|
-
`)}return
|
|
6
|
-
`).map((
|
|
7
|
-
`);n=n.replace(`__IMPORT_${r}__`,p)}return n}};var D=class{static{h(this,"TemplateManager")}_map=new Map;_engine=P;_watcher=[];_pageManager=S;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(t){let{path:e,enableWatch:s=!1}=t;this._path=e,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(t.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let t=0;t<this._path.length;t++){let e=this._path[t];if(!M(e))throw new Error(`Template base path is not exists: ${e}`);if(!_(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=ht(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=K(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileAdd(t){let e=K(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileDelete(t){let e=K(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=pt(o,"utf8").filter(r=>this._isValidFile(r));for(let r of n){let c=T(o,r),l=this._getExtension(r),d=this._getKey(r);if(l===".html")t.set(d,V(c,"utf8"));else if(l===".ts"||l===".js"){let p=S.getFileSync(c);p?.template!==void 0&&(t.set(d,p.template),e.push(p))}}}let s=new Map;for(let[i,o]of t.entries())this._compile(i,o,void 0,s,t);t.clear(),s.clear();for(let i of e)i.template=void 0}_loadFile(t){for(let e=0;e<this._path.length;e++){let s=this._path[e],i=T(s,t),o=this._getExtension(t),a=this._getKey(t);if(o==".html"){let n=V(i,"utf8");this._compile(a,n)}else if(o==".ts"||o==".js"){let n=S.getFileSync(i);n?.template!==void 0&&(this._compile(a,n.template),n.template=void 0)}else throw new Error(`File ${t} is not support`)}}_getExtension(t){return J(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let s=J(t).toLowerCase();if(s){let n=T(e,t);if(M(n)&&_(n).isFile()){if(s===".html")return V(n,"utf8");if(s===".ts"||s===".js")try{return S.getFileSync(n)?.template??null}catch{return null}}continue}let i=T(e,`${t}.ts`),o=T(e,`${t}.js`);if(M(i)&&_(i).isFile())try{return S.getFileSync(i)?.template??null}catch{}else if(M(o)&&_(o).isFile())try{return S.getFileSync(i)?.template??null}catch{}let a=T(e,`${t}.html`);if(M(a)&&_(a).isFile())return V(a,"utf8")}return null}_isValidFile(t){return this._supportedExtensions.has(this._getExtension(t))}_getKey(t){return t.replace(/\.[^/.]+$/,"")}_compile(t,e,s,i,o){let a=this._map.get(t),n=a||{},r=!1,c=P.processImportBlocks(e,d=>o&&o.has(d)?o.get(d):this._readTemplateFile(d),0,i),l=P._processBaseBlocks(c);(s===void 0||s?.media===!1||a?.media===void 0)&&(n.media=P.compileMedia(c,l),r=!0),(s===void 0||s?.message===!1||a?.message===void 0)&&(n.message=P.compileMessages(c,l),r=!0),(s===void 0||s?.keyboard===!1||a?.keyboard===void 0)&&(n.keyboard=P.compileKeyboards(c,l),r=!0),(s===void 0||s?.description===!1||a?.description===void 0)&&(n.description=P.compileDescription(c,l),r=!0),r&&this._map.set(t,n)}getMedia(t,e="default",s="default",i){let a=this._map.get(t)?.media?.[e],n=a?.[s]||a?.default;try{if(!n)throw new Error("Media function not found, please check your template");return n(i)}catch{return{}}}getMessage(t,e="default",s="default",i){try{let a=this._map.get(t)?.message?.[e],n=a?.[s]||a?.default;if(!n)throw"";return n(i)}catch{return""}}getDescription(t,e="default",s="default",i="default",o){try{let n=this._map.get(t)?.description?.[e]?.[i],r=n?.[s]||n?.default;if(!r)throw"";return r(o)}catch{return""}}getDescriptionLanguage(t,e="default",s="default"){try{let o=this._map.get(t)?.description?.[e]?.[s];return o?Object.keys(o):[]}catch{return[]}}getDescriptionScopes(t,e="default"){try{let i=this._map.get(t)?.description?.[e];return i?Object.keys(i):[]}catch{return[]}}getKeyboard(t,e="default",s="default",i="inline",o){try{let n=this._map.get(t)?.keyboard?.[e],r=n?.[s]?.[i]||n?.default?.[i];if(!r)throw[];return r(o)}catch{return[]}}async write(t,e){if(this._getExtension(t)!=".html")return null;for(let s=0;s<this._path.length;s++){let i=T(this._path[s],t);if(M(i))return ut(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 Ct,webhookCallback as U}from"grammy";var St=bt(import.meta.url),Pt=gt(St),kt=JSON.parse(yt(z(Pt,"../../package.json"),"utf-8")).version,H=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 ft:t.log?t.log:void 0,this.log?.info?.(`Gramstax v${kt}`),this.cacheSession=t.cacheSession||new F("memory","session"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new D({path:[z(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 Ct(t)}createCtx(t){return new R({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=U(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=U(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=mt(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],w=e.routeStaticIntent[y],x=e.routeStaticSession[y],v={name:s,routeName:y},E=C||w;if(E!==void 0){let st=y.includes(a),it=y.includes("callback"),nt=y.startsWith("text"),I;if(st){let L=t.data.textCommand||t.data.name;I=L?`/${L}`:void 0}else it?I=t.data.name:nt?I=t.data.text||t.data.name:I=t.data.name;I&&(E[I]=v)}x!==void 0&&(x[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 S.getFileManySync(void 0).forEach(({path:n,page:r})=>{this.pageBuildData(r,n),this.pageSorts(r,a),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(a.all).length})`),a}async pageRoutes(t,e){let s,i;if(s===void 0){let a=t.callbackData,n=t.msgText,r=t.msgCaption,c=this.pages.routeStatic;for(let l=0;l<this.pages.lenListRouteStatic;l++){let d=this.pages.listRouteStatic[l];if(d.startsWith(e)&&(i=c[d][a||n||r]),i)break}i!==void 0&&(s=this.pages.all[i.name])}if(s===void 0){let a=await t.sessionGet();if(a){let n=a.method,r=this.pages.routeStaticSession;for(let c=0;c<this.pages.lenListRouteStaticSession;c++){let l=this.pages.listRouteStaticSession[c];if(l.startsWith(e)&&(i=r[l][n]),i)break}i!==void 0&&(s=this.pages.all[i.name])}}if(s===void 0){let a=this.pages.routeStaticIntent,n=e==="callback",r=n?t.callbackData:t.msgText||t.msgCaption;if(r)for(let c=0;c<this.pages.lenListRouteStaticIntent;c++){let l=this.pages.listRouteStaticIntent[c];if(l.startsWith(e)){let d=a[l];i=d[t.intent(r,n?"colon":"space",1)],!i&&!n&&(i=d[t.intent(r,"space",2)])}if(i)break}i!==void 0&&(s=this.pages.all[i.name])}if(s!==void 0&&i!==void 0)return s.prototype[i.routeName]?await new s(t)[i.routeName]?.():void 0;let o=this.pages.routeDynamicSpesific[e]||[];for(let a=0;a<o.length;a++){let n=o[a];if(n===void 0)continue;let r=this.pages.all[n.name];if(r===void 0||!r.prototype[n.routeName])continue;let l=await new r(t)[n.routeName]?.();if(l!==null)return l}for(let a=0;a<this.pages.routeDynamic.length;a++){let n=this.pages.routeDynamic[a];if(n===void 0)continue;let r=this.pages.all[n];if(r===void 0||!r.prototype.free)continue;let l=await new r(t).free?.();if(l!==null)return l}return null}async hookBeforeRoute(t,e){return!!(t||e)}async hookErrorPage(t,e,s,i){}async hookErrorInputNotFoundPage(t){}async onMessage(t,e){let s=this.createCtx(t);try{if(await this.hookBeforeRoute(s,e)===!1)return;await this.pageRoutes(s,e)===null&&await this.hookErrorInputNotFoundPage(s)}catch(i){await this.hookErrorPage(s,e,i,!1)}}async onCallbackQueryData(t){let e=this.createCtx(t);try{if(await e.callbackQueryAnswer(),await this.hookBeforeRoute(e,"onCallbackQueryData")===!1)return;await this.pageRoutes(e,"callback")}catch(s){await this.hookErrorPage(e,"onCallbackQueryData",s,!0)}}async onMessageText(t){await this.onMessage(t,"text")}async onMessagePhoto(t){await this.onMessage(t,"photo")}async onMessageVideo(t){await this.onMessage(t,"video")}async onMessageAudio(t){await this.onMessage(t,"audio")}async onMessageDocument(t){await this.onMessage(t,"document")}async onMessageAnimation(t){await this.onMessage(t,"animation")}async onMessageVoice(t){await this.onMessage(t,"voice")}async onMessageVideoNote(t){await this.onMessage(t,"videoNote")}async onMessageSticker(t){await this.onMessage(t,"sticker")}async onMessageLocation(t){await this.onMessage(t,"location")}async onMessageContact(t){await this.onMessage(t,"contact")}registerOnCallbackQueryData(){this.bot.on("callback_query:data",this.onCallbackQueryData.bind(this))}registerOnMessageText(){this.bot.on("message:text",this.onMessageText.bind(this))}registerOnMessagePhoto(){this.bot.on("message:photo",this.onMessagePhoto.bind(this))}registerOnMessageVideo(){this.bot.on("message:video",this.onMessageVideo.bind(this))}registerOnMessageAudio(){this.bot.on("message:audio",this.onMessageAudio.bind(this))}registerOnMessageDocument(){this.bot.on("message:document",this.onMessageDocument.bind(this))}registerOnMessageAnimation(){this.bot.on("message:animation",this.onMessageAnimation.bind(this))}registerOnMessageVoice(){this.bot.on("message:voice",this.onMessageVoice.bind(this))}registerOnMessageVideoNote(){this.bot.on("message:video_note",this.onMessageVideoNote.bind(this))}registerOnMessageSticker(){this.bot.on("message:sticker",this.onMessageSticker.bind(this))}registerOnMessageLocation(){this.bot.on("message:location",this.onMessageLocation.bind(this))}registerOnMessageContact(){this.bot.on("message:contact",this.onMessageContact.bind(this))}};import{isMainThread as vt,Worker as Tt}from"worker_threads";var k=class{constructor(t,e){this.send=t;this.register=e}static{h(this,"WorkerThreadRpc")}map=new Map;async make(t){let e=this.map,s=this.send,{id:i,method:o,params:a,result:n,error:r}=t;if(o!==void 0)try{let c=this.register[o];if(typeof c!="function")throw new Error(`Method ${o} not found or not function`);let l=await c.apply(this.register,a);s({id:i,result:l})}catch(c){s({id:i,error:c instanceof Error?{message:c.message,stack:c.stack,name:c.name}:c})}else if(n!==void 0){let c=e.get(i);c&&(c.resolve(n),e.delete(i))}else if(r!==void 0){let c=e.get(i);c&&(c.reject(r),e.delete(i))}}makeId(){return Math.random()}makeRequest(t,e,s=!0,i){let o=this.makeId(),a={id:o,method:t,params:e,...i};return s?new Promise((n,r)=>{this.map.set(o,{resolve:n,reject:r}),this.send(a)}):this.send(a)}};var A=class{constructor(t,e){this.path=t;this.argv=e;this.init(),this.rpc=new k(this.send.bind(this),this)}static{h(this,"WorkerThreadLaunch")}pid=process.pid;thread={};threadId={};rpc={};_readyResolve;_readyPromise=new Promise(t=>this._readyResolve=t);static isMainThread=vt;ready(){return this._readyPromise}mtdReady(){this._readyResolve?.()}init(){this.thread=new Tt(this.path,{argv:this.argv.length==0&&this.argv[0]===void 0?void 0:this.argv}),this.threadId=this.thread.threadId,this.thread.on("message",t=>this.handleOnMessage(t))}async handleOnMessage(t){this.rpc.make(t)}kill(){this.thread.terminate()}send(t){this.thread.postMessage(t)}async request(t,e,s=!0,i){return this.rpc.makeRequest(t,e,s,i)}};var X=class g{static{h(this,"WorkerThreadExport")}static gateway(t){let e=new Proxy({},{get(i,o){if(!(typeof o!="string"||o==="then"))return async(a,...n)=>{let r=a.gatewayClients.get(t);return r||(r=await a.createGatewayClient(t)),r.request(o,n)}}}),s=h(function(i){return new Proxy({},{get(o,a){if(!(typeof a!="string"||a==="then"))return async(...n)=>{let r=i.gatewayClients.get(t);return r||(r=await i.createGatewayClient(t)),r.request(a,n)}}})},"ctor");return Object.setPrototypeOf(s,e),s}static init(t){let{WTInit:e,WTLaunch:s=A,path:i,wrap:o}=t,a=`for-${i}`;if(process.argv[2]===a)return new e,{gateway:h(d=>g.gateway(d),"gateway")};let n,r=new Proxy({},{get(d,p){if(p!=="then")return p==="sendRequest"||p==="request"||p==="kill"||p==="send"?(...u)=>{if(!n)throw new Error(`Thread at ${i} not launched yet.`);return n[p](...u)}:(...u)=>{if(!n)throw new Error(`Thread at ${i} not launched yet.`);return n.request(p,u)}}}),l={...o?o(r):{},launchWorker:h(async(d=[])=>(n=new s(i,[a,...d]),await n.ready(),n),"launchWorker"),gateway:h(d=>g.gateway(d),"gateway")};return new Proxy(l,{get(d,p){if(p!=="then")return p==="gateway"?d.gateway:p==="launchWorker"?d.launchWorker:p in d?d[p]:typeof p=="string"?(...u)=>{if(!n)throw new Error(`Thread at ${i} not launched yet.`);return n.request(p,u)}:d[p]}})}};var Y=class{static{h(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(t){this.addMany(t)}add(t){this.thread.set(t.threadId,t),this.threadCount+=1}addMany(t){t.forEach(e=>this.add(e))}getInstance(t){return this.thread.get(t)}kill(t){let e=this.thread.get(t);return e?.kill(),this.thread.delete(t),this.threadCount-=1,e?.threadId}killAll(){this.thread.values().forEach(({threadId:t})=>this.kill(t))}async broadcastRequest(t,e){return await Promise.all(Object.values(this.thread).map(s=>s.request(t,e,!0)))}async request(t,e,s,i=!0,o){return await this.thread.get(t)?.request(e,s,i,o)}};import{parentPort as It,threadId as Mt,isMainThread as _t}from"worker_threads";import{Server as wt}from"net-ipc";var O=class{static{h(this,"WorkerThreadGatewayServer")}server=new wt;rpc=new Map;methods={};constructor(){this.server.on("connect",t=>{let e=new k(s=>t.send(s),this.methods);this.rpc.set(t.id,e)}),this.server.on("disconnect",t=>{this.rpc.delete(t.id)}),this.server.on("message",(t,e)=>{let s=this.rpc.get(e.id);s&&s.make(t)}),this.server.on("error",t=>{console.error(t)})}async start(t,e={}){this.methods=e,this.server.options.path=t;let s=new Promise(i=>{this.server.once("ready",()=>i(this))});return await this.server.start(),s}};import{Client as xt}from"net-ipc";var W=class{static{h(this,"WorkerThreadGatewayClient")}client=new xt;rpc;constructor(){this.rpc=new k(t=>this.client.send(t),{}),this.client.on("message",t=>{this.rpc.make(t)})}async connect(t){this.client.options.path=t;let e=new Promise(s=>{this.client.once("ready",()=>s(this))});return await this.client.connect(),e}async request(t,e,s=!0,i){return this.rpc.makeRequest(t,e,s,i)}};var Z=class{static{h(this,"WorkerThreadInit")}argv=process.argv;id=Mt;pid=process.pid;rpc={};parentPort=It;gatewayServer;gatewayClients=new Map;gatewayClientLatest;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=_t;constructor(){this.init(),this.rpc=new k(this.send.bind(this),this),this.send({method:"mtdReady"})}init(){this.parentPort?.on("message",t=>this.handleOnMessage(t))}handleOnMessage(t){this.rpc.make(t)}send(t){this.parentPort?.postMessage(t)}request(t,e,s=!0,i){return this.rpc.makeRequest(t,e,s,i)}async createGatewayServer(t,e={}){return this.gatewayServer=new O,await this.gatewayServer.start(t,e),!0}async createGatewayClient(t){let e=new W;return await e.connect(t),this.gatewayClients.set(t,e),this.gatewayClientLatest=e,e}};var tt=class{static{h(this,"ComponentKeyboard")}static data;static _process(t,e){if(e.type||(e.type="inline"),e.lang){let s=t[e.lang];return`
|
|
1
|
+
var ot=Object.defineProperty;var p=(u,t)=>ot(u,"name",{value:t,configurable:!0}),$=(u=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(u,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):u)(function(u){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+u+'" is not supported')});import{LoggingPretty as at}from"logging-pretty";var B=class extends at{static{p(this,"LoggingUtils")}constructor(t){super(t)}errorMake(t,e,s){this.error(`[${e?`${e}:${s}`:s}] ${String(t)}`)}},Vt=new B;import{Keyv as rt}from"keyv";import ct from"@keyv/redis";var F=class extends rt{constructor(e="memory",s,n,o){let a;e.startsWith("redis")&&(a=new ct(e)),e==="memory"&&(a=new Map),o?.forceStore&&(a=o.forceStore);super({store:a,namespace:s,ttl:n});this.url=e}static{p(this,"CacheExternal")}};import{setTimeout as dt}from"timers/promises";import{InlineKeyboard as j,Keyboard as q}from"grammy";var R=class{static{p(this,"Ctx")}static template;static data;data=this.constructor.data;get userIsPremium(){return this.ct.from?.is_premium??!1}get userIsBot(){return this.ct.from?.is_bot??!1}get userId(){return this.ct.from?.id}get userName(){return this.ct.from?.username}get userFullName(){return`${this.ct.from?.first_name} ${this.ct.from?.last_name||""}`}get userFirstName(){return this.ct.from?.first_name}get userLastName(){return this.ct.from?.last_name}get userLanguage(){return this.ct.from?.language_code}set userLanguage(t){this.ct.from.language_code=t}get msgText(){return this.ct.message?.text}get msgTextPayloads(){return this.getPayloads(this.msgText,"space",this.data?._positionPayloadText||this.temp?.data?._positionPayloadText)}get msgTextPayload(){return this.msgTextPayloads[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionPayloads(){return this.getPayloads(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.getPayloads(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,n,o,a,i=!1){try{this.temp.isAnswer=!0;let r=30,c=e.map(h=>this.templateManager.getMessage(this.data.name,o,h,n));for(let h=0;h<t.length;h++){let d=t[h],l=c[h];await this.ct.api.sendMessage(d,l,{parse_mode:"HTML",reply_markup:s,...a}),h+1==r&&await dt(1200)}}catch(r){if(i)throw r}}async reply(t,e,s,n){this.temp.isAnswer=!0;let o=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.reply(o,{parse_mode:"HTML",reply_markup:t,...n})}async replyMedia(t,e,s,n,o){this.temp.isAnswer=!0;let a=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s),i={parse_mode:"HTML",reply_markup:e,...o};if(t=="photo")return await this.ct.replyWithPhoto(a.src,{caption:a.caption,...i});if(t=="video")return await this.ct.replyWithVideo(a.src,{caption:a.caption,...i});if(t=="audio")return await this.ct.replyWithAudio(a.src,{caption:a.caption,...i});if(t=="document")return await this.ct.replyWithDocument(a.src,{caption:a.caption,...i});if(t=="animation")return await this.ct.replyWithAnimation(a.src,{caption:a.caption,...i});if(t=="voice")return await this.ct.replyWithVoice(a.src,i);if(t=="video_note")return await this.ct.replyWithVideoNote(a.src,i);if(t=="sticker")return await this.ct.replyWithSticker(a.src,i);if(t=="location")return await this.ct.replyWithLocation(parseInt(a.latitude),parseInt(a.longitude),i);if(t=="contact")return await this.ct.replyWithContact(a.phone,a.first_name,{vcard:a.vcard,...i})}async replyPhoto(t,e,s,n){return this.replyMedia("photo",t,e,s,n)}async replyVideo(t,e,s,n){return this.replyMedia("video",t,e,s,n)}async replyAudio(t,e,s,n){return this.replyMedia("audio",t,e,s,n)}async replyDocument(t,e,s,n){return this.replyMedia("document",t,e,s,n)}async replyAnimation(t,e,s,n){return this.replyMedia("animation",t,e,s,n)}async replyVoice(t,e,s,n){return this.replyMedia("voice",t,e,s,n)}async replyVideoNote(t,e,s,n){return this.replyMedia("video_note",t,e,s,n)}async replySticker(t,e,s,n){return this.replyMedia("sticker",t,e,s,n)}async replyLocation(t,e,s,n){return this.replyMedia("location",t,e,s,n)}async replyContact(t,e,s,n){return this.replyMedia("contact",t,e,s,n)}async replyAction(t){return await this.ct.replyWithChatAction(t)}async edit(t,e,s,n,o=!0){try{this.temp.isAnswer=!0;let a=this.templateManager.getMessage(this.data.name,s,this.userLanguage,e);return await this.ct.editMessageText(a,{parse_mode:"HTML",reply_markup:t,...n})}catch(a){if(o)await this.reply(t,e,s,n);else throw a}}async editMedia(t,e,s,n,o,a,i=!0){try{this.temp.isAnswer=!0;let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s);return t=="voice"?(await this.delete(),await this.replyVoice(e,s,n,o)):t=="video_note"?(await this.delete(),await this.replyVoice(e,s,n,o)):t=="sticker"?(await this.delete(),await this.replySticker(e,s,n,o)):t=="location"?(await this.delete(),await this.replyLocation(e,s,n,o)):t=="contact"?(await this.delete(),await this.replyContact(e,s,n,o)):await this.ct.editMessageMedia({media:r,caption:c,type:t,parse_mode:"HTML",...o},{reply_markup:e,...a})}catch(r){if(i===!0)await this.reply(e,s,n,a);else throw r}}async editPhoto(t,e,s,n,o){return await this.editMedia("photo",t,e,s,n,o)}async editVideo(t,e,s,n,o){return await this.editMedia("video",t,e,s,n,o)}async editAudio(t,e,s,n,o){return await this.editMedia("audio",t,e,s,n,o)}async editDocument(t,e,s,n,o){return await this.editMedia("document",t,e,s,n,o)}async editAnimation(t,e,s,n,o){return await this.editMedia("animation",t,e,s,n,o)}async editVoice(t,e,s,n){return await this.editMedia("voice",t,e,s,n)}async editVideoNote(t,e,s,n){return await this.editMedia("video_note",t,e,s,n)}async editSticker(t,e,s,n){return await this.editMedia("sticker",t,e,s,n)}async editLocation(t,e,s,n){return await this.editMedia("location",t,e,s,n)}async editContact(t,e,s,n){return await this.editMedia("contact",t,e,s,n)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(t){try{return this.temp.isAnswer=!0,await this.ct.answerCallbackQuery(t)}catch{return null}}async sessionSet(t,e,s){try{let n={method:t,params:e,...s},o=await this.cacheSession.set(`${this.userId}`,n);return o&&(this.session=n),o}catch{return null}}async sessionGet(){try{let t=await this.cacheSession.get(`${this.userId}`);return t&&(this.session=t),t||null}catch{return null}}async sessionClear(){try{let t=await this.cacheSession.delete(`${this.userId}`);return t&&(this.session={}),t}catch{return null}}static buildData(t){let s=typeof t=="function"?{callbackData:t}:t||{},n=s.callbackData;return{name:"",text:s.text,textCommand:s.textCommand,_positionPayloadText:s.text?s.text.split(this.prototype.getSeperatorTag("space")).length:void 0,callbackData:n?function(...a){let i=n(...a);return`${this.name}${i==""||i===void 0?"":`:${i}`}`}:function(){return this?.name}}}inlineKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let i=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(i);if(!r){let c=new j,h=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data),d=t(c,h);return this.cacheKeyboard.set(i,d),d}return r}let n=new j,o=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"inline",e?.data);return t(n,o)}bottomKeyboard(t,e){let s=this.data.name;if(e?.cache===!0){let i=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(i);if(!r){let c=new q,h=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),d=t(c,h);return d.resized(!0),this.cacheKeyboard.set(i,d),d}return r}let n=new q,o=this.templateManager.getKeyboard(s,e?.baseId,this.userLanguage,"bottom",e?.data),a=t(n,o);return a.resized(),a}getSeperatorTag(t="space"){return t=="space"?" ":":"}havePayloads(t="",e){return t.includes(this.getSeperatorTag(e))}getPayloads(t="",e,s=1){if(!t)return[];let n=this.getSeperatorTag(e);return t.split(n).slice(s)}getIntent(t="",e,s=1){if(!t)return"";let n=this.getSeperatorTag(e),o=t.split(n);return s==1?o[0]:o.slice(0,s).join(n)}validateSessionCallback(t,e){return(t??this.session.method)===this.methodSessionCallback(e)}validateSessionCallbackPayload(t,e){return(t??this.session.method)===this.methodSessionCallbackPayload(e)}validateSessionText(t,e){return(t??this.session.method)===this.methodSessionText(e)}validateSessionTextPayload(t,e){return(t??this.session.method)===this.methodSessionTextPayload(e)}validateSessionTextCommand(t,e){return(t??this.session.method)===this.methodSessionTextCommand(e)}validateSessionTextCommandPayload(t,e){return(t??this.session.method)===this.methodSessionTextCommandPayload(e)}validateSessionTextFree(t,e){return(t??this.session.method)===this.methodSessionTextFree(e)}validateSessionPhotoCaption(t,e){return(t??this.session.method)===this.methodSessionPhotoCaption(e)}validateSessionPhotoCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionPayload(e)}validateSessionPhotoCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionCommand(e)}validateSessionPhotoCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionPhotoCaptionCommandPayload(e)}validateSessionPhotoFree(t,e){return(t??this.session.method)===this.methodSessionPhotoFree(e)}validateSessionVideoCaption(t,e){return(t??this.session.method)===this.methodSessionVideoCaption(e)}validateSessionVideoCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionPayload(e)}validateSessionVideoCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionCommand(e)}validateSessionVideoCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVideoCaptionCommandPayload(e)}validateSessionVideoFree(t,e){return(t??this.session.method)===this.methodSessionVideoFree(e)}validateSessionAudioCaption(t,e){return(t??this.session.method)===this.methodSessionAudioCaption(e)}validateSessionAudioCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionPayload(e)}validateSessionAudioCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionCommand(e)}validateSessionAudioCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionAudioCaptionCommandPayload(e)}validateSessionAudioFree(t,e){return(t??this.session.method)===this.methodSessionAudioFree(e)}validateSessionDocumentCaption(t,e){return(t??this.session.method)===this.methodSessionDocumentCaption(e)}validateSessionDocumentCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionPayload(e)}validateSessionDocumentCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionCommand(e)}validateSessionDocumentCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionDocumentCaptionCommandPayload(e)}validateSessionDocumentFree(t,e){return(t??this.session.method)===this.methodSessionDocumentFree(e)}validateSessionAnimationCaption(t,e){return(t??this.session.method)===this.methodSessionAnimationCaption(e)}validateSessionAnimationCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionPayload(e)}validateSessionAnimationCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionCommand(e)}validateSessionAnimationCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionAnimationCaptionCommandPayload(e)}validateSessionAnimationFree(t,e){return(t??this.session.method)===this.methodSessionAnimationFree(e)}validateSessionVoiceCaption(t,e){return(t??this.session.method)===this.methodSessionVoiceCaption(e)}validateSessionVoiceCaptionPayload(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionPayload(e)}validateSessionVoiceCaptionCommand(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionCommand(e)}validateSessionVoiceCaptionCommandPayload(t,e){return(t??this.session.method)===this.methodSessionVoiceCaptionCommandPayload(e)}validateSessionVoiceFree(t,e){return(t??this.session.method)===this.methodSessionVoiceFree(e)}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 z,parse as gt,dirname as ut}from"path";import{readFileSync as yt}from"fs";import{fileURLToPath as ft}from"url";import{join as K}from"path";import{existsSync as G,readdirSync as Q}from"fs";import{createRequire as ht}from"module";var P=class{static{p(this,"PageManager")}static _getFile(t,e,s=0){let o=Object.values(t)[s];if(o===void 0)throw new Error(`File ${e} must have export (not default) class page`);return o}static getFilePath(){return K(process.cwd(),"src","pages")}static getFileSync(t,e=0){t||(t=this.getFilePath());let n=ht(t)(t);return this._getFile(n,t,e)}static async getFile(t,e=0){t||(t=this.getFilePath());let s=await import(`${t}?t=${Date.now()}`);return this._getFile(s,t,e)}static getFileManySync(t,e=0){if(t||(t=this.getFilePath()),!G(t))throw new Error(`Directory ${t} is not found, please make it manually`);return Q(t).map(n=>{let o=K(t,n);return{path:o,page:this.getFileSync(o,e)}})}static clearCacheRequire(t){if(t||(t=this.getFilePath()),!G(t))throw new Error(`Directory ${t} is not found, please make it manually`);return Q(t).forEach(s=>{let n=K(t,s);delete $.cache[$.resolve(n)]}),!0}};import{LoggingPretty as Ct}from"logging-pretty";import{basename as N,join as T,extname as J}from"path";import{readdirSync as lt,readFileSync as V,existsSync as M,statSync as _,writeFileSync as mt}from"fs";import{watch as pt}from"chokidar";var b=class{static{p(this,"TemplateEngine")}static _escape(t){return t.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processVariables(t){return t.replace(/\{\{(\w+)\}\}/g,(e,s)=>`\${(data && data["${s}"]) ?? ""}`)}static _processBaseBlocks(t){let e=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,s={};for(let n of t.matchAll(e)){let o=n[2]??"default",i=(n[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[o]=i}return s}static _processScriptBlocks(t){return t.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(e,s)=>{let n=s.trim();return n?`\${(() => { if (!data) return ''; try { with(data) { ${n} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(t){return t.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(t){return t.replace(/<div>([\s\S]*?)<\/div>/gi,(e,s)=>s.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(t){let e=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return t.replace(e,(s,n,o)=>{if(!n)return"";let a="",i=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=i.exec(o))!==null;){let d=(c[1]||"").split(",").map(m=>m.trim()),l=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(m=>{a+=`case "${m}": `}),a+=`return \`${l}\`; `}let h=r.exec(o);if(h){let d=(h[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");a+=`default: return \`${d}\`; `}else a+="default: return ''; ";return`\${(() => { switch((data && data["${n}"])) { ${a} } })()}`})}static _processExec(t){return t.replace(/{~\s*([\s\S]*?)\s*~}/g,(e,s)=>`\${(() => { try { return ${s} } catch(e) { try { with(data || {}) { return ${s} } } catch(ee) { return '' } } })()}`)}static _processMapBlocks(t){let e=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return t.replace(e,(s,n,o)=>{let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let l of n.matchAll(i))a[l[1]]=l[2];let r=a.src;if(!r)return"";let c=a.join??"\\n",h=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");h=h.replace(/\{\{([\w.]+)\}\}/g,(l,m)=>m==="e"||m.startsWith("e.")?`\${${m}}`:m==="i"?"${i}":l);let d=c.replace(/"/g,'\\"');return`\${(data && data["${r}"] || []).map((e, i) => \`${h}\`).join("${d}")}`})}static _processMediaBlocks(t){let e=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let n of t.matchAll(e)){let o=n[1],a=n[2],i={},r=/(\w+)="([^"]*)"/g;if(o)for(let m of o.matchAll(r))i[m[1]]=m[2];let c=i.lang||"default",h=i.type,d=a.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),l={type:h};i.src&&(l.src=i.src),d&&h!=="video_note"&&h!=="sticker"&&(l.caption=d),h==="location"&&(i.latitude&&(l.latitude=i.latitude),i.longitude&&(l.longitude=i.longitude),d&&(l.caption=d)),h==="contact"&&(i.phone&&(l.phone=i.phone),i.first_name&&(l.first_name=i.first_name),i.last_name&&(l.last_name=i.last_name),i.vcard&&(l.vcard=i.vcard),d&&(l.caption=d)),s[c]=l}return s}static _processMessageBlocks(t){let e=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,n,o]of t.matchAll(e)){let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let h of n.matchAll(i))a[h[1]]=h[2];let r=a.lang||"default",c=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=c}return s}static _processDescriptionBlocks(t){let e=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,n,o]of t.matchAll(e)){let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(i))a[d[1]]=d[2];let r=a.lang||"default",c=a.scope||"default",h=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][c]=h}return s}static _processKeyboardBlocks(t){let e=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,n,o]of t.matchAll(e)){let a={},i=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(i))a[d[1]]=d[2];let r=a.lang||"default",c=a.type==="bottom"?"bottom":"inline",h=o.trim();s[r]||(s[r]={}),s[r][c]=h}return s}static _compileToFunction(t,e){let s;e?s=t.map(a=>`\`${a}\``).join(","):s=`\`${t}\``;let n=s;if(n=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(n))),e){let o=`return [${n}]`;return new Function("data",o)}else{let o=`return ${n}`;return new Function("data",o)}}static compileMedia(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processMediaBlocks(a);n[o]={};for(let[r,c]of Object.entries(i)){let h={};for(let[d,l]of Object.entries(c)){if(d==="type"||typeof l!="string")continue;let m=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(l)))));h[d]=this._compileToFunction(m,!1)}n[o][r]=d=>{let l={...c};for(let[m,g]of Object.entries(h))l[m]=g(d);return l}}}return n}static compileMessages(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processMessageBlocks(a);n[o]={};for(let[r,c]of Object.entries(i)){let h=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));n[o][r]=this._compileToFunction(h,!1)}}return n}static compileDescription(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processDescriptionBlocks(a);n[o]={};for(let[r,c]of Object.entries(i))for(let[h,d]of Object.entries(c)){n[o][h]||(n[o][h]={});let l=this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));n[o][h][r]=this._compileToFunction(l,!1)}}return n}static compileKeyboards(t,e){let s=e||this._processBaseBlocks(t),n={};for(let[o,a]of Object.entries(s)){let i=this._processKeyboardBlocks(a);n[o]={};for(let[r,c]of Object.entries(i)){n[o][r]={};for(let[h,d]of Object.entries(c)){let m=d.split(/(?<!\\),\s*/).map(g=>g.replace(/\\,/g,",").trim()).map(g=>this._processVariables(this._processExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(g))))));n[o][r][h]=this._compileToFunction(m,!0)}}}return n}static _extractBlock(t,e,s="default",n="all",o){let a=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,i=t,r=!1;for(let c of t.matchAll(a))if((c[2]??"default")===s){i=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(t);if(!(s==="default"&&!c))return""}if(e){if(e==="all")return i;let c=Array.isArray(e)?e:[e],h=[];for(let l of c){let m=new RegExp(`([ \\t]*)<${l}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${l}>`,"gi");for(let g of i.matchAll(m)){let y=g[2];if(o){let S=/lang="([^"]*)"/i,w=y?.match(S);if(((w?w[1]:void 0)||"default")!==o)continue}h.push({start:g.index,content:g[0],innerContent:g[3]??""})}}h.sort((l,m)=>l.start-m.start);let d=p(l=>{let m=l.split(`
|
|
2
|
+
`);if(m.length<=1)return l.trim();let g=m.filter(S=>S.trim().length>0);if(g.length===0)return"";let y=g.reduce((S,w)=>{let x=w.match(/^([ \t]*)/),v=x?x[1].length:0;return v<S?v:S},1/0);return m.map(S=>S.length>=y?S.slice(y):S.trimStart()).join(`
|
|
3
|
+
`).trim()},"processResult");return n==="all"?h.map(m=>d(m.content)).join(`
|
|
4
|
+
`):h.map(m=>d(m.innerContent)).join(`
|
|
5
|
+
`)}return i}static _processImportBlocks(t){let e=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,s=[];return{processed:t.replace(e,(o,a,i)=>{let r={},c=/(\w+)="([^"]*)"/g;if(i)for(let m of i.matchAll(c))r[m[1]]=m[2];let h=r.src;if(!h)return"";let d;r.block&&(r.block==="all"?d="all":r.block.includes(",")?d=r.block.split(",").map(m=>m.trim()).filter(m=>m):d=r.block);let l={src:h,blocks:d,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:a||""};return s.push(l),`${a}__IMPORT_${s.length-1}__`}),imports:s}}static processImportBlocks(t,e,s=0,n){if(s>10)return"";let{processed:o,imports:a}=this._processImportBlocks(t),i=o;for(let r=0;r<a.length;r++){let c=a[r],h=`${c.src}|${c.base}|${c.lang||""}|${c.section}|${Array.isArray(c.blocks)?c.blocks.join(","):c.blocks||""}`,d;if(n&&n.has(h))d=n.get(h);else{let m=e(c.src);d=m?this._extractBlock(m,c.blocks,c.base,c.section,c.lang):"",d&&d.includes("<import")&&(d=this.processImportBlocks(d,e,s+1,n)),n&&n.set(h,d)}let l=d.split(`
|
|
6
|
+
`).map((m,g)=>g===0?m:c.indent+m).join(`
|
|
7
|
+
`);i=i.replace(`__IMPORT_${r}__`,l)}return i}};var D=class{static{p(this,"TemplateManager")}_map=new Map;_engine=b;_watcher=[];_pageManager=P;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(t){let{path:e,enableWatch:s=!1}=t;this._path=e,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(t.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let t=0;t<this._path.length;t++){let e=this._path[t];if(!M(e))throw new Error(`Template base path is not exists: ${e}`);if(!_(e).isDirectory())throw new Error(`Template base path is not a directory: ${e}`)}return!0}catch(t){throw new Error(`Failed to validate Template base path: ${String(t)}`)}}_initializeWatcher(t){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let e=0;e<this._path.length;e++){let s=this._path[e],n=pt(s,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...t});this._watcher[e]=n,n.on("change",this._handleFileChange.bind(this)),n.on("add",this._handleFileAdd.bind(this)),n.on("unlink",this._handleFileDelete.bind(this)),n.on("error",this._handleWatchError.bind(this))}}}_handleFileChange(t){let e=N(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileAdd(t){let e=N(t);this._isValidFile(e)&&this._loadFile(e)}_handleFileDelete(t){let e=N(t),s=this._getKey(e);this._map.has(s)&&this._map.delete(s)}_handleWatchError(t){}_loadAllFiles(){let t=new Map,e=[];for(let n=0;n<this._path.length;n++){let o=this._path[n],i=lt(o,"utf8").filter(r=>this._isValidFile(r));for(let r of i){let c=T(o,r),h=this._getExtension(r),d=this._getKey(r);if(h===".html")t.set(d,V(c,"utf8"));else if(h===".ts"||h===".js"){let l=P.getFileSync(c);l?.template!==void 0&&(t.set(d,l.template),e.push(l))}}}let s=new Map;for(let[n,o]of t.entries())this._compile(n,o,void 0,s,t);t.clear(),s.clear();for(let n of e)n.template=void 0}_loadFile(t){for(let e=0;e<this._path.length;e++){let s=this._path[e],n=T(s,t),o=this._getExtension(t),a=this._getKey(t);if(o==".html"){let i=V(n,"utf8");this._compile(a,i)}else if(o==".ts"||o==".js"){let i=P.getFileSync(n);i?.template!==void 0&&(this._compile(a,i.template),i.template=void 0)}else throw new Error(`File ${t} is not support`)}}_getExtension(t){return J(t).toLowerCase()}_readTemplateFile(t){for(let e of this._path){let s=J(t).toLowerCase();if(s){let i=T(e,t);if(M(i)&&_(i).isFile()){if(s===".html")return V(i,"utf8");if(s===".ts"||s===".js")try{return P.getFileSync(i)?.template??null}catch{return null}}continue}let n=T(e,`${t}.ts`),o=T(e,`${t}.js`);if(M(n)&&_(n).isFile())try{return P.getFileSync(n)?.template??null}catch{}else if(M(o)&&_(o).isFile())try{return P.getFileSync(n)?.template??null}catch{}let a=T(e,`${t}.html`);if(M(a)&&_(a).isFile())return V(a,"utf8")}return null}_isValidFile(t){return this._supportedExtensions.has(this._getExtension(t))}_getKey(t){return t.replace(/\.[^/.]+$/,"")}_compile(t,e,s,n,o){let a=this._map.get(t),i=a||{},r=!1,c=b.processImportBlocks(e,d=>o&&o.has(d)?o.get(d):this._readTemplateFile(d),0,n),h=b._processBaseBlocks(c);(s===void 0||s?.media===!1||a?.media===void 0)&&(i.media=b.compileMedia(c,h),r=!0),(s===void 0||s?.message===!1||a?.message===void 0)&&(i.message=b.compileMessages(c,h),r=!0),(s===void 0||s?.keyboard===!1||a?.keyboard===void 0)&&(i.keyboard=b.compileKeyboards(c,h),r=!0),(s===void 0||s?.description===!1||a?.description===void 0)&&(i.description=b.compileDescription(c,h),r=!0),r&&this._map.set(t,i)}getMedia(t,e="default",s="default",n){let a=this._map.get(t)?.media?.[e],i=a?.[s]||a?.default;try{if(!i)throw new Error("Media function not found, please check your template");return i(n)}catch{return{}}}getMessage(t,e="default",s="default",n){try{let a=this._map.get(t)?.message?.[e],i=a?.[s]||a?.default;if(!i)throw"";return i(n)}catch{return""}}getDescription(t,e="default",s="default",n="default",o){try{let i=this._map.get(t)?.description?.[e]?.[n],r=i?.[s]||i?.default;if(!r)throw"";return r(o)}catch{return""}}getDescriptionLanguage(t,e="default",s="default"){try{let o=this._map.get(t)?.description?.[e]?.[s];return o?Object.keys(o):[]}catch{return[]}}getDescriptionScopes(t,e="default"){try{let n=this._map.get(t)?.description?.[e];return n?Object.keys(n):[]}catch{return[]}}getKeyboard(t,e="default",s="default",n="inline",o){try{let i=this._map.get(t)?.keyboard?.[e],r=i?.[s]?.[n]||i?.default?.[n];if(!r)throw[];return r(o)}catch{return[]}}async write(t,e){if(this._getExtension(t)!=".html")return null;for(let s=0;s<this._path.length;s++){let n=T(this._path[s],t);if(M(n))return mt(n,e,"utf8"),this._loadFile(t),!0}return null}has(t){return this._map.has(t)}async destroy(){if(this._watcher)for(let t of this._watcher)await t.close();this._map.clear()}};import{Bot as St,webhookCallback as U}from"grammy";var Pt=ft(import.meta.url),bt=ut(Pt),kt=JSON.parse(yt(z(bt,"../../package.json"),"utf-8")).version,H=class{static{p(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 Ct:t.log?t.log:void 0,this.log?.info?.(`Gramstax v${kt}`),this.cacheSession=t.cacheSession||new F("memory","session"),this.cacheKeyboard=t.cacheKeyboard||new Map,this.templateManager=t.templateManager||new D({path:[z(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:n}=t;this.log?.success?.(`Telegram bot polling started: ${n} ${e=="webhook"||e=="serverless"?`(${s})`:""}`),this.hookAfterStart()}createBot(t){return new St(t)}createCtx(t){return new R({ct:t,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{isAnswer:!1,session:{},data:{}}})}runPolling(){this.bot.start({onStart:p(t=>{this.onStart(t,"polling",null)},"onStart")})}async runWebhook(t){let{serve:e}=await import("bun"),s=U(this.bot,"bun");this.handlerBotUpdate=s;let n=new URL(t).pathname;e({fetch(i){let{pathname:r}=new URL(i.url);if(i.method=="POST"&&r==n)return s(i);if(i.method=="GET"&&r=="/"){let c=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:c}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}}),(await this.bot.api.getWebhookInfo()).url!=t&&await this.bot.api.setWebhook(t);let a=await this.bot.api.getMe();await this.onStart(a,"webhook",t)}async runServerless(t){this.handlerBotUpdate=U(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=gt(e).name}pageSorts(t,e){let s=t.data.name,n=t.prototype,o="Payload",a="Command",i="Caption",r="Free",c=e.routeDynamic,h=e.routeDynamicSpesific,d=p(g=>g.charAt(0).toUpperCase()+g.slice(1),"upFirst"),l=p(g=>g.replace(o,"").replace(a,"").replace(i,"").replace(r,""),"getPureRouteName"),m=p((g,y)=>n[`methodSession${d(g)}`]?.(y),"methodSession");e.all[s]=t;for(let g=0;g<e.lenListRouteStaticSession;g++){let y=e.listRouteStaticSession[g];if(typeof n[y]!="function")continue;let S=e.routeStatic[y],w=e.routeStaticIntent[y],x=e.routeStaticSession[y],v={name:s,routeName:y},E=S||w;if(E!==void 0){let st=y.includes(a),nt=y.includes("callback"),it=y.startsWith("text"),I;if(st){let L=t.data.textCommand||t.data.name;I=L?`/${L}`:void 0}else nt?I=t.data.name:it?I=t.data.text||t.data.name:I=t.data.name;I&&(E[I]=v)}x!==void 0&&(x[m(y,s)]=v),y.toLowerCase().endsWith("free")&&h[l(y)].push(v)}n.free&&c.push(s)}async executeSyncBlocksDescription(t){let e=new Map,s=t.routeStatic.textCommand;for(let[,n]of Object.entries(s)){let o=n.name,a=this.templateManager.getDescriptionScopes(o);for(let i of a){e.has(i)||e.set(i,new Set);let r=this.templateManager.getDescriptionLanguage(o,"default",i);for(let c of r)e.get(i).add(c)}}for(let[n,o]of e)for(let a of o){let i=[];for(let[,h]of Object.entries(s)){let d=h.name,l=this.templateManager.getDescription(d,"default",a,n);l&&i.push({command:d,description:l})}if(i.length===0)continue;let r={type:n},c=a==="default"?void 0:a;try{let h=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(h.map(m=>({command:m.command,description:m.description})).sort((m,g)=>m.command.localeCompare(g.command))),l=JSON.stringify(i.sort((m,g)=>m.command.localeCompare(g.command)));d!==l&&(await this.bot.api.setMyCommands(i,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${n},${c?` lang: ${c},`:""} total (${i.length})`))}catch(h){this.log?.error?.(`Failed to sync descriptions for scope: ${n},${c?` lang: ${c},`:""} error: ${String(h)}`)}}}pageLoads(){this.log?.info?.("Load pages..");let t=["callback","text","textCommand","photoCaption","photoCaptionCommand","videoCaption","videoCaptionCommand","audioCaption","audioCaptionCommand","documentCaption","documentCaptionCommand","animationCaption","animationCaptionCommand","voiceCaption","voiceCaptionCommand","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"],n=p((i,r)=>Object.fromEntries(i.map(c=>[c,r()])),"makeObject"),o=p(()=>[],"initDynamicSpesific"),a={all:{},routeDynamic:[],routeDynamicSpesific:{text:o(),photo:o(),video:o(),audio:o(),document:o(),animation:o(),voice:o(),videoNote:o(),sticker:o(),location:o(),contact:o()},routeStatic:n(t,()=>({})),routeStaticIntent:n(e,()=>({})),routeStaticSession:n(s,()=>({})),listRouteStatic:t,listRouteStaticIntent:e,listRouteStaticSession:s,lenListRouteStatic:t.length,lenListRouteStaticIntent:e.length,lenListRouteStaticSession:s.length};return P.getFileManySync(void 0).forEach(({path:i,page:r})=>{this.pageBuildData(r,i),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,n;if(s===void 0){let a=t.callbackData,i=t.msgText,r=t.msgCaption,c=this.pages.routeStatic;for(let h=0;h<this.pages.lenListRouteStatic;h++){let d=this.pages.listRouteStatic[h];if(d.startsWith(e)&&(n=c[d][a||i||r]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s===void 0){let a=await t.sessionGet();if(a){let i=a.method,r=this.pages.routeStaticSession;for(let c=0;c<this.pages.lenListRouteStaticSession;c++){let h=this.pages.listRouteStaticSession[c];if(h.startsWith(e)&&(n=r[h][i]),n)break}n!==void 0&&(s=this.pages.all[n.name])}}if(s===void 0){let a=this.pages.routeStaticIntent,i=e==="callback",r=i?"colon":"space",c=i?t.callbackData:t.msgText||t.msgCaption,h=t.havePayloads(c,r);if(c&&h)for(let d=0;d<this.pages.lenListRouteStaticIntent;d++){let l=this.pages.listRouteStaticIntent[d];if(!l.startsWith(e))continue;let m=a[l];if(n=m[t.getIntent(c,r,1)],!n&&!i&&(n=m[t.getIntent(c,"space",2)]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s!==void 0&&n!==void 0)return s.prototype[n.routeName]?await new s(t)[n.routeName]?.():void 0;let o=this.pages.routeDynamicSpesific[e]||[];for(let a=0;a<o.length;a++){let i=o[a];if(i===void 0)continue;let r=this.pages.all[i.name];r!==void 0&&typeof r.prototype[i.routeName]=="function"&&await new r(t)[i.routeName]()}for(let a=0;a<this.pages.routeDynamic.length;a++){let i=this.pages.routeDynamic[a];if(i===void 0)continue;let r=this.pages.all[i];r!==void 0&&typeof r.prototype.free=="function"&&await new r(t).free()}if(t.temp.isAnswer===!1)return null}async hookBeforeRoute(t,e){return!!(t||e)}async hookErrorPage(t,e,s,n){}async hookErrorInputNotFoundPage(t){}async onMessage(t,e){let s=this.createCtx(t);try{if(await this.hookBeforeRoute(s,e)===!1)return;await this.pageRoutes(s,e)===null&&await this.hookErrorInputNotFoundPage(s)}catch(n){await this.hookErrorPage(s,e,n,!1)}}async onCallbackQueryData(t){let e=this.createCtx(t);try{if(await 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 X=class{static{p(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
|
-
`}return Object.keys(t).map(s=>{let
|
|
10
|
-
<keyboard type="${e.type}" lang="${s}">${e.reverse?this.data._reverse(
|
|
11
|
-
`}).join(" ")}static _build(t,e,s){if(!this.data)throw new Error("Data not found");let
|
|
9
|
+
`}return Object.keys(t).map(s=>{let n=t[s];return`
|
|
10
|
+
<keyboard type="${e.type}" lang="${s}">${e.reverse?this.data._reverse(n):n}</keyboard>
|
|
11
|
+
`}).join(" ")}static _build(t,e,s){if(!this.data)throw new Error("Data not found");let n=this.data[t];if(!n)throw new Error(`Function ${t} not found`);return this._process(n.call(this.data,e),{type:s,lang:e})}};var Y=class{static{p(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 n=s[t||""];return e?this._reverse(n):n}return e?this._reverseObj(s):s}};import{isMainThread as vt,Worker as Tt}from"worker_threads";var k=class{constructor(t,e){this.send=t;this.register=e}static{p(this,"WorkerThreadRpc")}map=new Map;async make(t){let e=this.map,s=this.send,{id:n,method:o,params:a,result:i,error:r}=t;if(o!==void 0)try{let c=this.register[o];if(typeof c!="function")throw new Error(`Method ${o} not found or not function`);let h=await c.apply(this.register,a);s({id:n,result:h})}catch(c){s({id:n,error:c instanceof Error?{message:c.message,stack:c.stack,name:c.name}:c})}else if(i!==void 0){let c=e.get(n);c&&(c.resolve(i),e.delete(n))}else if(r!==void 0){let c=e.get(n);c&&(c.reject(r),e.delete(n))}}makeId(){return Math.random()}makeRequest(t,e,s=!0,n){let o=this.makeId(),a={id:o,method:t,params:e,...n};return s?new Promise((i,r)=>{this.map.set(o,{resolve:i,reject:r}),this.send(a)}):this.send(a)}};var A=class{constructor(t,e){this.path=t;this.argv=e;this.init(),this.rpc=new k(this.send.bind(this),this)}static{p(this,"WorkerThreadLaunch")}static isMainThread=vt;_readyResolve;_readyPromise=new Promise(t=>this._readyResolve=t);pid=process.pid;thread={};threadId={};rpc={};ready(){return this._readyPromise}mtdReady(){this._readyResolve?.()}init(){this.thread=new Tt(this.path,{argv:this.argv.length==0&&this.argv[0]===void 0?void 0:this.argv}),this.threadId=this.thread.threadId,this.thread.on("message",t=>this.handleOnMessage(t))}async handleOnMessage(t){this.rpc.make(t)}kill(){this.thread.terminate()}send(t){this.thread.postMessage(t)}async request(t,e,s=!0,n){return this.rpc.makeRequest(t,e,s,n)}};var Z=class u{static{p(this,"WorkerThreadExport")}static gateway(t){let e=new Proxy({},{get(n,o){if(!(typeof o!="string"||o==="then"))return async(a,...i)=>{let r=a.gatewayClients.get(t);return r||(r=await a.createGatewayClient(t)),r.request(o,i)}}}),s=p(function(n){return new Proxy({},{get(o,a){if(!(typeof a!="string"||a==="then"))return async(...i)=>{let r=n.gatewayClients.get(t);return r||(r=await n.createGatewayClient(t)),r.request(a,i)}}})},"ctor");return Object.setPrototypeOf(s,e),s}static init(t){let{WTInit:e,WTLaunch:s=A,path:n,wrap:o}=t,a=`for-${n}`;if(process.argv[2]===a)return new e,{gateway:p(d=>u.gateway(d),"gateway")};let i,r=new Proxy({},{get(d,l){if(l!=="then")return l==="sendRequest"||l==="request"||l==="kill"||l==="send"?(...m)=>{if(!i)throw new Error(`Thread at ${n} not launched yet.`);return i[l](...m)}:(...m)=>{if(!i)throw new Error(`Thread at ${n} not launched yet.`);return i.request(l,m)}}}),h={...o?o(r):{},launchWorker:p(async(d=[])=>(i=new s(n,[a,...d]),await i.ready(),i),"launchWorker"),gateway:p(d=>u.gateway(d),"gateway")};return new Proxy(h,{get(d,l){if(l!=="then")return l==="gateway"?d.gateway:l==="launchWorker"?d.launchWorker:l in d?d[l]:typeof l=="string"?(...m)=>{if(!i)throw new Error(`Thread at ${n} not launched yet.`);return i.request(l,m)}:d[l]}})}};import{Client as wt}from"net-ipc";var O=class{static{p(this,"WorkerThreadGatewayClient")}client=new wt;rpc;constructor(){this.rpc=new k(t=>this.client.send(t),{}),this.client.on("message",t=>{this.rpc.make(t)})}async connect(t){this.client.options.path=t;let e=new Promise(s=>{this.client.once("ready",()=>s(this))});return await this.client.connect(),e}async request(t,e,s=!0,n){return this.rpc.makeRequest(t,e,s,n)}};import{Server as xt}from"net-ipc";var W=class{static{p(this,"WorkerThreadGatewayServer")}server=new xt;rpc=new Map;methods={};constructor(){this.server.on("connect",t=>{let e=new k(s=>t.send(s),this.methods);this.rpc.set(t.id,e)}),this.server.on("disconnect",t=>{this.rpc.delete(t.id)}),this.server.on("message",(t,e)=>{let s=this.rpc.get(e.id);s&&s.make(t)}),this.server.on("error",t=>{console.error(t)})}async start(t,e={}){this.methods=e,this.server.options.path=t;let s=new Promise(n=>{this.server.once("ready",()=>n(this))});return await this.server.start(),s}};import{parentPort as It,threadId as Mt,isMainThread as _t}from"worker_threads";var tt=class{static{p(this,"WorkerThreadInit")}argv=process.argv;id=Mt;pid=process.pid;rpc={};parentPort=It;gatewayServer;gatewayClients=new Map;gatewayClientLatest;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=_t;constructor(){this.init(),this.rpc=new k(this.send.bind(this),this),this.send({method:"mtdReady"})}init(){this.parentPort?.on("message",t=>this.handleOnMessage(t))}handleOnMessage(t){this.rpc.make(t)}send(t){this.parentPort?.postMessage(t)}request(t,e,s=!0,n){return this.rpc.makeRequest(t,e,s,n)}async createGatewayServer(t,e={}){return this.gatewayServer=new W,await this.gatewayServer.start(t,e),!0}async createGatewayClient(t){let e=new O;return await e.connect(t),this.gatewayClients.set(t,e),this.gatewayClientLatest=e,e}};var et=class{static{p(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(t){this.addMany(t)}add(t){this.thread.set(t.threadId,t),this.threadCount+=1}addMany(t){t.forEach(e=>this.add(e))}getInstance(t){return this.thread.get(t)}kill(t){let e=this.thread.get(t);return e?.kill(),this.thread.delete(t),this.threadCount-=1,e?.threadId}killAll(){this.thread.values().forEach(({threadId:t})=>this.kill(t))}async broadcastRequest(t,e){return await Promise.all(Object.values(this.thread).map(s=>s.request(t,e,!0)))}async request(t,e,s,n=!0,o){return await this.thread.get(t)?.request(e,s,n,o)}};export{F as CacheExternal,X as ComponentKeyboard,R as Ctx,Y as DataKeyboard,H as Gramstax,B as LoggingUtils,b as TemplateEngine,D as TemplateManager,Z as WorkerThreadExport,O as WorkerThreadGatewayClient,W as WorkerThreadGatewayServer,tt as WorkerThreadInit,A as WorkerThreadLaunch,et as WorkerThreadPool,k as WorkerThreadRpc,Vt as log};
|