gramstax 0.8.15 → 0.8.16
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 +7 -7
- package/dist/src/index.d.cts +6 -2
- package/dist/src/index.d.ts +6 -2
- package/dist/src/index.js +7 -7
- package/package.json +1 -1
package/dist/src/index.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var fe=Object.create;var W=Object.defineProperty;var Te=Object.getOwnPropertyDescriptor;var be=Object.getOwnPropertyNames;var Ce=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty;var u=(g,e)=>W(g,"name",{value:e,configurable:!0});var Se=(g,e)=>{for(var t in e)W(g,t,{get:e[t],enumerable:!0})},ie=(g,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of be(e))!ke.call(g,n)&&n!==t&&W(g,n,{get:()=>e[n],enumerable:!(s=Te(e,n))||s.enumerable});return g};var oe=(g,e,t)=>(t=g!=null?fe(Ce(g)):{},ie(e||!g||!g.__esModule?W(t,"default",{value:g,enumerable:!0}):t,g)),we=g=>ie(W({},"__esModule",{value:!0}),g);var Me={};Se(Me,{BlockKeyboard:()=>X,CacheExternal:()=>V,Ctx:()=>K,Gramstax:()=>z,LabelKeyboard:()=>Y,LoggingHelper:()=>Q,MockTelegramServer:()=>se,PageManager:()=>M,TemplateEngine:()=>A,TemplateManager:()=>L,WebhookQueue:()=>E,WorkerThreadExport:()=>Z,WorkerThreadGatewayClient:()=>N,WorkerThreadGatewayServer:()=>j,WorkerThreadInit:()=>ee,WorkerThreadLaunch:()=>U,WorkerThreadPool:()=>te,WorkerThreadRpc:()=>R,log:()=>$});module.exports=we(Me);var _e=u(()=>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=_e();var ae=require("logging-pretty");var Q=class extends ae.LoggingPretty{static{u(this,"LoggingHelper")}timers=new Map;constructor(e){super(e)}errorMake(e,t,s){this.error(`[${t?`${t}:${s}`:s}] ${this._formatErrorObj(e)}`)}_formatErrorObj(e){return JSON.stringify(e instanceof Error?{message:e.message,stack:e.stack,name:e.name}:e,null,2)}time(e){this.timers.set(e,process.hrtime.bigint())}timeEnd(e,t){let s=this.timers.get(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}let n=(Number(process.hrtime.bigint()-s)/1e6).toFixed(3);this.timers.delete(e),t?this.debug(`${t} (took ${n}ms)`):this.debug(`${e} (took ${n}ms)`)}timeCheck(e){let t=this.timers.get(e);if(t!==void 0)return(Number(process.hrtime.bigint()-t)/1e6).toFixed(3)}timeLog(e,t){let s=this.timeCheck(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}t?this.debug(`${t} (${s}ms)`):this.debug(`${e} (${s}ms)`)}timeClear(){this.timers.clear()}timeActive(){return Array.from(this.timers.keys())}},$=new Q;var re=require("keyv"),ce=oe(require("@keyv/redis"),1);var V=class extends re.Keyv{constructor(t="memory",s,n,i){let o;t.startsWith("redis")&&(o=new ce.default(t)),t==="memory"&&(o=new Map),i?.forceStore&&(o=i.forceStore);super({store:o,namespace:n,ttl:s});this.url=t}url;static{u(this,"CacheExternal")}refreshLruCache(t){let s=this.store,n=this.opts.namespace?this.opts.namespace?.length+1:null,i=s.keys().toArray();for(let o=0;o<i.length;o++){let a=i[o];if(o==t)return;this.get(n?a.slice(n):a)}}};var J=require("timers/promises"),P=require("grammy");var K=class{static{u(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(e){this.ct.from.language_code=e}get msgText(){return this.ct.message?.text}get msgTextArgs(){return this.getArgs(this.msgText,"space",this.data?._positionArgText||this.temp?.data?._positionArgText)}get msgTextArg(){return this.msgTextArgs[0]}get msgTextCommandArgs(){return this.getArgs(this.msgText,"space")}get msgTextCommandArg(){return this.msgTextCommandArgs[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionArg(){return this.msgCaptionArgs[0]}get msgCaptionCommandArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionCommandArg(){return this.msgCaptionCommandArgs[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get msgDocument(){return this.ct.message?.document}get msgAnimation(){return this.ct.message?.animation}get msgVoice(){return this.ct.message?.voice}get msgVideoNote(){return this.ct.message?.video_note}get msgSticker(){return this.ct.message?.sticker}get msgLocation(){return this.ct.message?.location}get msgContact(){return this.ct.message?.contact}get msgWebAppData(){return this.ct.message?.web_app_data}get msgGift(){return this.ct.message?.gift}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataArgs(){return this.getArgs(this.callbackData,"colon")}get callbackDataArg(){return this.callbackDataArgs?.[0]}ct;cacheSession;cacheKeyboard;templateManager;temp;constructor(e){this.ct=e.ct,this.cacheSession=e.cacheSession,this.cacheKeyboard=e.cacheKeyboard,this.templateManager=e.templateManager,this.temp=e.temp}async broadcast(e,t,s,n,i,o,a=!1){let r={successCount:0,failedCount:0,totalCount:0};r.totalCount=e.length;try{this.temp.isAnswer=!0;let c=30,h=t.map(d=>this.templateManager.getMessage(this.data.name,i,d,n));for(let d=0;d<e.length;d++){let m=e[d],l=h[d];await this.ct.api.sendMessage(m,l,{parse_mode:"HTML",reply_markup:s,...o}),r.successCount+=1,d+1==c&&await(0,J.setTimeout)(1200)}}catch(c){if(r.failedCount+=1,a)throw{...r,err:c}}return r}async broadcastMedia(e,t,s,n,i,o,a=!1){let r={successCount:0,failedCount:0,totalCount:0};r.totalCount=e.length;try{this.temp.isAnswer=!0;let c=30,h=t.map(d=>this.templateManager.getMedia(this.data.name,i,d,n));for(let d=0;d<e.length;d++){let m=e[d],l=h[d];if(!l)continue;let p={parse_mode:"HTML",reply_markup:s,...o};l.type=="photo"&&await this.ct.api.sendPhoto(m,l.src,{caption:l.caption,...p}),l.type=="video"&&await this.ct.api.sendVideo(m,l.src,{caption:l.caption,...p}),l.type=="audio"&&await this.ct.api.sendAudio(m,l.src,{caption:l.caption,...p}),l.type=="document"&&await this.ct.api.sendDocument(m,l.src,{caption:l.caption,...p}),l.type=="animation"&&await this.ct.api.sendAnimation(m,l.src,{caption:l.caption,...p}),l.type=="voice"&&await this.ct.api.sendVoice(m,l.src,p),l.type=="video_note"&&await this.ct.api.sendVideoNote(m,l.src,p),l.type=="sticker"&&await this.ct.api.sendSticker(m,l.src,p),l.type=="location"&&await this.ct.api.sendLocation(m,parseInt(l.latitude),parseInt(l.longitude),p),l.type=="contact"&&await this.ct.api.sendContact(m,l.phone,l.first_name,{vcard:l.vcard,...p}),r.successCount+=1,d+1==c&&await(0,J.setTimeout)(1200)}}catch(c){if(r.failedCount+=1,a)throw{...r,err:c}}return r}async reply(e,t,s,n){this.temp.isAnswer=!0;let i=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.reply(i,{parse_mode:"HTML",reply_markup:e,...n})}async replyMedia(e,t,s,n,i){this.temp.isAnswer=!0;let o=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s),a={parse_mode:"HTML",reply_markup:t,...i};if(e=="photo")return await this.ct.replyWithPhoto(o.src,{caption:o.caption,...a});if(e=="video")return await this.ct.replyWithVideo(o.src,{caption:o.caption,...a});if(e=="audio")return await this.ct.replyWithAudio(o.src,{caption:o.caption,...a});if(e=="document")return await this.ct.replyWithDocument(o.src,{caption:o.caption,...a});if(e=="animation")return await this.ct.replyWithAnimation(o.src,{caption:o.caption,...a});if(e=="voice")return await this.ct.replyWithVoice(o.src,a);if(e=="video_note")return await this.ct.replyWithVideoNote(o.src,a);if(e=="sticker")return await this.ct.replyWithSticker(o.src,a);if(e=="location")return await this.ct.replyWithLocation(parseInt(o.latitude),parseInt(o.longitude),a);if(e=="contact")return await this.ct.replyWithContact(o.phone,o.first_name,{vcard:o.vcard,...a})}async replyPhoto(e,t,s,n){return this.replyMedia("photo",e,t,s,n)}async replyVideo(e,t,s,n){return this.replyMedia("video",e,t,s,n)}async replyAudio(e,t,s,n){return this.replyMedia("audio",e,t,s,n)}async replyDocument(e,t,s,n){return this.replyMedia("document",e,t,s,n)}async replyAnimation(e,t,s,n){return this.replyMedia("animation",e,t,s,n)}async replyVoice(e,t,s,n){return this.replyMedia("voice",e,t,s,n)}async replyVideoNote(e,t,s,n){return this.replyMedia("video_note",e,t,s,n)}async replySticker(e,t,s,n){return this.replyMedia("sticker",e,t,s,n)}async replyLocation(e,t,s,n){return this.replyMedia("location",e,t,s,n)}async replyContact(e,t,s,n){return this.replyMedia("contact",e,t,s,n)}async replyAction(e){return await this.ct.replyWithChatAction(e)}async edit(e,t,s,n,i=!0){try{this.temp.isAnswer=!0;let o=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.editMessageText(o,{parse_mode:"HTML",reply_markup:e,...n})}catch(o){if(i)await this.reply(e,t,s,n);else throw o}}async editMedia(e,t,s,n,i,o,a=!0){try{this.temp.isAnswer=!0;let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s);return e=="voice"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="video_note"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="sticker"?(await this.delete(),await this.replySticker(t,s,n,i)):e=="location"?(await this.delete(),await this.replyLocation(t,s,n,i)):e=="contact"?(await this.delete(),await this.replyContact(t,s,n,i)):await this.ct.editMessageMedia({media:r,caption:c,type:e,parse_mode:"HTML",...i},{reply_markup:t,...o})}catch(r){if(a===!0)await this.reply(t,s,n,o);else throw r}}async editPhoto(e,t,s,n,i){return await this.editMedia("photo",e,t,s,n,i)}async editVideo(e,t,s,n,i){return await this.editMedia("video",e,t,s,n,i)}async editAudio(e,t,s,n,i){return await this.editMedia("audio",e,t,s,n,i)}async editDocument(e,t,s,n,i){return await this.editMedia("document",e,t,s,n,i)}async editAnimation(e,t,s,n,i){return await this.editMedia("animation",e,t,s,n,i)}async editVoice(e,t,s,n){return await this.editMedia("voice",e,t,s,n)}async editVideoNote(e,t,s,n){return await this.editMedia("video_note",e,t,s,n)}async editSticker(e,t,s,n){return await this.editMedia("sticker",e,t,s,n)}async editLocation(e,t,s,n){return await this.editMedia("location",e,t,s,n)}async editContact(e,t,s,n){return await this.editMedia("contact",e,t,s,n)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(e){try{return this.temp.isAnswer=!0,await this.ct.answerCallbackQuery(e)}catch{return null}}async setSession(e,t,s){try{let n={method:e,params:t,...s},i=await this.cacheSession.set(`${this.userId}`,n);return i&&(this.temp.session=n),i}catch{return null}}async getSession(){try{let e=await this.cacheSession.get(`${this.userId}`);return e&&(this.temp.session=e),e||null}catch{return null}}async clearSession(){try{let e=await this.cacheSession.delete(`${this.userId}`);return e&&(this.temp.session={}),e}catch{return null}}static buildData(e){let s=typeof e=="function"?{callbackData:e}:e||{},n=s.callbackData,i=this.prototype.addArgs.bind(this.prototype),o=s.name||"";return{name:o,intentText:s.intentText||o,intentCommandText:s.intentCommandText||o,intentCallbackData:o,callbackData:n?function(...r){return i(this.intentCallbackData,"colon",n(...r))}:function(){return this?.intentCallbackData},_positionArgText:s.intentText?s.intentText.split(this.prototype.getSeperatorTag("space")).length:void 0}}keyboardCols(e,t,s,n){let[i,o]=s.split("-"),a=parseInt(i),r=o?parseInt(o):null,c=t.length,h=e;for(let d=0;d<c;d++){let m=t[d];if(n(m,d),r===null)(d+1)%a===0&&d<c-1&&h.row();else{let l=c-(d+1);(l===r||l>r&&(d+1)%a===0)&&h.row()}}return e}bottomKeyboardT(e="1",t,s){return this.bottomKeyboard((n,i)=>this.keyboardCols(n,i,e,o=>n.text(o)),{baseId:t??void 0,data:s})}inlineKeyboardT(e,t="1",s,n){return this.inlineKeyboard((i,o)=>this.keyboardCols(i,o,t,(a,r)=>{let c=e[r],h=typeof c=="string"?c:c.data.callbackData();i.text(a,h)}),{baseId:s??void 0,data:n})}inlineKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let a=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(a);if(!r){let c=new P.InlineKeyboard,h=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data),d=e(c,h);return this.cacheKeyboard.set(a,d),d}return r}let n=new P.InlineKeyboard,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data);return e(n,i)}bottomKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let a=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(a);if(!r){let c=new P.Keyboard,h=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),d=e(c,h);return d.resized(!0),this.cacheKeyboard.set(a,d),d}return r}let n=new P.Keyboard,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),o=e(n,i);return o.resized(),o}getSeperatorTag(e="space"){return e=="space"?" ":":"}haveArgs(e="",t){return e.includes(this.getSeperatorTag(t))}addArgs(e="",t,s){let n=this.getSeperatorTag(t),i="";for(let o=0;o<s.length;o++){let a=s[o];a!=null&&a!==""&&(i+=n+a)}return e+i}getArgs(e="",t,s=1){if(!e)return[];let n=this.getSeperatorTag(t);return e.split(n).slice(s)}getIntent(e="",t,s=1){if(!e)return"";let n=this.getSeperatorTag(t),i=e.split(n);return s==1?i[0]:i.slice(0,s).join(n)}isSessionCallbackData(){return this.temp.session.method===this.methodSessionCallbackData()}isSessionArgsCallbackData(){return this.temp.session.method===this.methodSessionArgsCallbackData()}isSessionText(){return this.temp.session.method===this.methodSessionText()}isSessionArgsText(){return this.temp.session.method===this.methodSessionArgsText()}isSessionCommandText(){return this.temp.session.method===this.methodSessionCommandText()}isSessionCommandArgsText(){return this.temp.session.method===this.methodSessionCommandArgsText()}isSessionFreeText(){return this.temp.session.method===this.methodSessionFreeText()}isSessionCaptionPhoto(){return this.temp.session.method===this.methodSessionCaptionPhoto()}isSessionCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCaptionArgsPhoto()}isSessionCommandCaptionPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionPhoto()}isSessionCommandCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionArgsPhoto()}isSessionFreePhoto(){return this.temp.session.method===this.methodSessionFreePhoto()}isSessionCaptionVideo(){return this.temp.session.method===this.methodSessionCaptionVideo()}isSessionCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCaptionArgsVideo()}isSessionCommandCaptionVideo(){return this.temp.session.method===this.methodSessionCommandCaptionVideo()}isSessionCommandCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVideo()}isSessionFreeVideo(){return this.temp.session.method===this.methodSessionFreeVideo()}isSessionCaptionAudio(){return this.temp.session.method===this.methodSessionCaptionAudio()}isSessionCaptionArgsAudio(){return this.temp.session.method===this.methodSessionCaptionArgsAudio()}isSessionCaptionCommandAudio(){return this.temp.session.method===this.methodSessionCaptionCommandAudio()}isSessionCaptionCommandArgsAudio(){return this.temp.session.method===this.methodSessionCaptionCommandArgsAudio()}isSessionFreeAudio(){return this.temp.session.method===this.methodSessionFreeAudio()}isSessionCaptionDocument(){return this.temp.session.method===this.methodSessionCaptionDocument()}isSessionCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCaptionArgsDocument()}isSessionCommandCaptionDocument(){return this.temp.session.method===this.methodSessionCommandCaptionDocument()}isSessionCommandCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCommandCaptionArgsDocument()}isSessionFreeDocument(){return this.temp.session.method===this.methodSessionFreeDocument()}isSessionCaptionAnimation(){return this.temp.session.method===this.methodSessionCaptionAnimation()}isSessionCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCaptionArgsAnimation()}isSessionCommandCaptionAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionAnimation()}isSessionCommandCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionArgsAnimation()}isSessionFreeAnimation(){return this.temp.session.method===this.methodSessionFreeAnimation()}isSessionCaptionVoice(){return this.temp.session.method===this.methodSessionCaptionVoice()}isSessionCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCaptionArgsVoice()}isSessionCommandCaptionVoice(){return this.temp.session.method===this.methodSessionCommandCaptionVoice()}isSessionCommandCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVoice()}isSessionFreeVoice(){return this.temp.session.method===this.methodSessionFreeVoice()}isSessionFreeVideoNote(){return this.temp.session.method===this.methodSessionFreeVideoNote()}isSessionFreeSticker(){return this.temp.session.method===this.methodSessionFreeSticker()}isSessionFreeLocation(){return this.temp.session.method===this.methodSessionFreeLocation()}isSessionFreeContact(){return this.temp.session.method===this.methodSessionFreeContact()}sessionCallbackData(e){return this.setSession(this.methodSessionCallbackData(),e)}sessionArgsCallbackData(e){return this.setSession(this.methodSessionArgsCallbackData(),e)}sessionText(e){return this.setSession(this.methodSessionText(),e)}sessionArgsText(e){return this.setSession(this.methodSessionArgsText(),e)}sessionCommandText(e){return this.setSession(this.methodSessionCommandText(),e)}sessionCommandArgsText(e){return this.setSession(this.methodSessionCommandArgsText(),e)}sessionFreeText(e){return this.setSession(this.methodSessionFreeText(),e)}sessionCaptionPhoto(e){return this.setSession(this.methodSessionCaptionPhoto(),e)}sessionCaptionArgsPhoto(e){return this.setSession(this.methodSessionCaptionArgsPhoto(),e)}sessionCommandCaptionPhoto(e){return this.setSession(this.methodSessionCommandCaptionPhoto(),e)}sessionCommandCaptionArgsPhoto(e){return this.setSession(this.methodSessionCommandCaptionArgsPhoto(),e)}sessionFreePhoto(e){return this.setSession(this.methodSessionFreePhoto(),e)}sessionCaptionVideo(e){return this.setSession(this.methodSessionCaptionVideo(),e)}sessionCaptionArgsVideo(e){return this.setSession(this.methodSessionCaptionArgsVideo(),e)}sessionCommandCaptionVideo(e){return this.setSession(this.methodSessionCommandCaptionVideo(),e)}sessionCommandCaptionArgsVideo(e){return this.setSession(this.methodSessionCommandCaptionArgsVideo(),e)}sessionFreeVideo(e){return this.setSession(this.methodSessionFreeVideo(),e)}sessionCaptionAudio(e){return this.setSession(this.methodSessionCaptionAudio(),e)}sessionCaptionArgsAudio(e){return this.setSession(this.methodSessionCaptionArgsAudio(),e)}sessionCaptionCommandAudio(e){return this.setSession(this.methodSessionCaptionCommandAudio(),e)}sessionCaptionCommandArgsAudio(e){return this.setSession(this.methodSessionCaptionCommandArgsAudio(),e)}sessionFreeAudio(e){return this.setSession(this.methodSessionFreeAudio(),e)}sessionCaptionDocument(e){return this.setSession(this.methodSessionCaptionDocument(),e)}sessionCaptionArgsDocument(e){return this.setSession(this.methodSessionCaptionArgsDocument(),e)}sessionCommandCaptionDocument(e){return this.setSession(this.methodSessionCommandCaptionDocument(),e)}sessionCommandCaptionArgsDocument(e){return this.setSession(this.methodSessionCommandCaptionArgsDocument(),e)}sessionFreeDocument(e){return this.setSession(this.methodSessionFreeDocument(),e)}sessionCaptionAnimation(e){return this.setSession(this.methodSessionCaptionAnimation(),e)}sessionCaptionArgsAnimation(e){return this.setSession(this.methodSessionCaptionArgsAnimation(),e)}sessionCommandCaptionAnimation(e){return this.setSession(this.methodSessionCommandCaptionAnimation(),e)}sessionCommandCaptionArgsAnimation(e){return this.setSession(this.methodSessionCommandCaptionArgsAnimation(),e)}sessionFreeAnimation(e){return this.setSession(this.methodSessionFreeAnimation(),e)}sessionCaptionVoice(e){return this.setSession(this.methodSessionCaptionVoice(),e)}sessionCaptionArgsVoice(e){return this.setSession(this.methodSessionCaptionArgsVoice(),e)}sessionCommandCaptionVoice(e){return this.setSession(this.methodSessionCommandCaptionVoice(),e)}sessionCommandCaptionArgsVoice(e){return this.setSession(this.methodSessionCommandCaptionArgsVoice(),e)}sessionFreeVoice(e){return this.setSession(this.methodSessionFreeVoice(),e)}sessionFreeVideoNote(e){return this.setSession(this.methodSessionFreeVideoNote(),e)}sessionFreeSticker(e){return this.setSession(this.methodSessionFreeSticker(),e)}sessionFreeLocation(e){return this.setSession(this.methodSessionFreeLocation(),e)}sessionFreeContact(e){return this.setSession(this.methodSessionFreeContact(),e)}methodSession(e,t){return`${e}-${t||this.data.name}`}methodSessionCallbackData(e){return this.methodSession("1",e)}methodSessionArgsCallbackData(e){return this.methodSession("2",e)}methodSessionText(e){return this.methodSession("3",e)}methodSessionArgsText(e){return this.methodSession("4",e)}methodSessionCommandText(e){return this.methodSession("5",e)}methodSessionCommandArgsText(e){return this.methodSession("6",e)}methodSessionFreeText(e){return this.methodSession("7",e)}methodSessionCaptionPhoto(e){return this.methodSession("8",e)}methodSessionCaptionArgsPhoto(e){return this.methodSession("9",e)}methodSessionCommandCaptionPhoto(e){return this.methodSession("10",e)}methodSessionCommandCaptionArgsPhoto(e){return this.methodSession("11",e)}methodSessionFreePhoto(e){return this.methodSession("12",e)}methodSessionCaptionVideo(e){return this.methodSession("13",e)}methodSessionCaptionArgsVideo(e){return this.methodSession("14",e)}methodSessionCommandCaptionVideo(e){return this.methodSession("15",e)}methodSessionCommandCaptionArgsVideo(e){return this.methodSession("16",e)}methodSessionFreeVideo(e){return this.methodSession("17",e)}methodSessionCaptionAudio(e){return this.methodSession("18",e)}methodSessionCaptionArgsAudio(e){return this.methodSession("19",e)}methodSessionCaptionCommandAudio(e){return this.methodSession("20",e)}methodSessionCaptionCommandArgsAudio(e){return this.methodSession("21",e)}methodSessionFreeAudio(e){return this.methodSession("22",e)}methodSessionCaptionDocument(e){return this.methodSession("23",e)}methodSessionCaptionArgsDocument(e){return this.methodSession("24",e)}methodSessionCommandCaptionDocument(e){return this.methodSession("25",e)}methodSessionCommandCaptionArgsDocument(e){return this.methodSession("26",e)}methodSessionFreeDocument(e){return this.methodSession("27",e)}methodSessionCaptionAnimation(e){return this.methodSession("28",e)}methodSessionCaptionArgsAnimation(e){return this.methodSession("29",e)}methodSessionCommandCaptionAnimation(e){return this.methodSession("30",e)}methodSessionCommandCaptionArgsAnimation(e){return this.methodSession("31",e)}methodSessionFreeAnimation(e){return this.methodSession("32",e)}methodSessionCaptionVoice(e){return this.methodSession("33",e)}methodSessionCaptionArgsVoice(e){return this.methodSession("34",e)}methodSessionCommandCaptionVoice(e){return this.methodSession("35",e)}methodSessionCommandCaptionArgsVoice(e){return this.methodSession("36",e)}methodSessionFreeVoice(e){return this.methodSession("37",e)}methodSessionFreeVideoNote(e){return this.methodSession("38",e)}methodSessionFreeSticker(e){return this.methodSession("39",e)}methodSessionFreeLocation(e){return this.methodSession("40",e)}methodSessionFreeContact(e){return this.methodSession("41",e)}};var G=require("path"),D=require("fs"),de=require("module");var M=class{static{u(this,"PageManager")}static _getFile(e,t,s=0){let i=Object.values(e)[s];if(i===void 0)throw new Error(`File ${t} must have export (not default) class page`);return i}static getFilePath(){return(0,G.join)(process.cwd(),"src","pages")}static getFileSync(e,t=0){e||(e=this.getFilePath());let n=(0,de.createRequire)(e)(e);return this._getFile(n,e,t)}static async getFile(e,t=0){e||(e=this.getFilePath());let s=await import(`${e}?t=${Date.now()}`);return this._getFile(s,e,t)}static getFileManySync(e,t=0){if(e||(e=this.getFilePath()),!(0,D.existsSync)(e))throw new Error(`Directory ${e} is not found, please make it manually`);return(0,D.readdirSync)(e).map(n=>{let i=(0,G.join)(e,n);return{path:i,page:this.getFileSync(i,t)}})}static clearCacheRequire(e){if(e||(e=this.getFilePath()),!(0,D.existsSync)(e))throw new Error(`Directory ${e} is not found, please make it manually`);return(0,D.readdirSync)(e).forEach(s=>{let n=(0,G.join)(e,s);delete require.cache[require.resolve(n)]}),!0}};var le=require("fs"),me=require("url"),v=require("path");var w=require("path"),T=require("fs"),he=require("chokidar");var A=class g{static{u(this,"TemplateEngine")}static ALLOWED_BLOCKS=["<base>","<message>","<keyboard>","<media>","<description>","<script>","<switch>","<case>","<default>","<map>","<div>","<import/>","<space/>","<b>","<i>","<u>","<s>","<code>","<pre>","<a>","<blockquote>","<blockquote expandable>"];static ALLOWED_SCOPE=["{{}}","{~~}"];static _escape(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processScopeVariables(e){return e.replace(/\{\{(\w+)\}\}/g,(t,s)=>`\${(data && data["${s}"]) ?? ""}`)}static _processScopeExec(e){return e.replace(/{~\s*([\s\S]*?)\s*~}/g,(t,s)=>`\${(() => { try { return ${s} } catch(e) { try { with(data || {}) { return ${s} } } catch(ee) { return '' } } })()}`)}static _processBaseBlocks(e){let t=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,s={};for(let n of e.matchAll(t)){let i=n[2]??"default",a=(n[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[i]=a}return s}static _processScriptBlocks(e){return e.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(t,s)=>{let n=s.trim();return n?`\${(() => { if (!data) return ''; try { with(data) { ${n} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(e){return e.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(e){return e.replace(/<div>([\s\S]*?)<\/div>/gi,(t,s)=>s.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(e){let t=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return e.replace(t,(s,n,i)=>{if(!n)return"";let o="",a=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=a.exec(i))!==null;){let d=(c[1]||"").split(",").map(l=>l.trim()),m=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(l=>{o+=`case "${l}": `}),o+=`return \`${m}\`; `}let h=r.exec(i);if(h){let d=(h[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();o+=`default: return \`${d}\`; `}else o+="default: return ''; ";return`\${(() => { switch((data && data["${n}"])) { ${o} } })()}`})}static _processMapBlocks(e){let t=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return e.replace(t,(s,n,i)=>{let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let m of n.matchAll(a))o[m[1]]=m[2];let r=o.src;if(!r)return"";let c=o.join??"\\n",h=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");h=h.replace(/\{\{([\w.]+)\}\}/g,(m,l)=>l==="e"||l.startsWith("e.")?`\${${l}}`:l==="i"?"${i}":m);let d=c.replace(/"/g,'\\"');return`\${(() => { const __arr = (data && data["${r}"]) || []; let __out = ""; for (let i = 0; i < __arr.length; i++) { const e = __arr[i]; if (i > 0) { __out += "${d}" } __out += \`${h}\`; } return __out; })()}`})}static _processMediaBlocks(e){let t=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let n of e.matchAll(t)){let i=n[1],o=n[2],a={},r=/(\w+)="([^"]*)"/g;if(i)for(let l of i.matchAll(r))a[l[1]]=l[2];let c=a.lang||"default",h=a.type,d=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),m={type:h};a.src&&(m.src=a.src),d&&h!=="video_note"&&h!=="sticker"&&(m.caption=d),h==="location"&&(a.latitude&&(m.latitude=a.latitude),a.longitude&&(m.longitude=a.longitude),d&&(m.caption=d)),h==="contact"&&(a.phone&&(m.phone=a.phone),a.first_name&&(m.first_name=a.first_name),a.last_name&&(m.last_name=a.last_name),a.vcard&&(m.vcard=a.vcard),d&&(m.caption=d)),s[c]=m}return s}static _processMessageBlocks(e){let t=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let h of n.matchAll(a))o[h[1]]=h[2];let r=o.lang||"default",c=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=c}return s}static _processDescriptionBlocks(e){let t=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(a))o[d[1]]=d[2];let r=o.lang||"default",c=o.scope||"default",h=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][c]=h}return s}static _processKeyboardBlocks(e){let t=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(a))o[d[1]]=d[2];let r=o.lang||"default",c=o.type==="bottom"?"bottom":"inline",h=i.trim();s[r]||(s[r]={}),s[r][c]=h}return s}static _compileToFunction(e,t){let s;t?s=e.map(o=>`\`${o}\``).join(","):s=`\`${e}\``;let n=s;if(n=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(n))),t){let i=`return [${n}]`;return new Function("data",i)}else{let i=`return ${n}`;return new Function("data",i)}}static compileBlockMedia(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processMediaBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){let h={};for(let[d,m]of Object.entries(c)){if(d==="type"||typeof m!="string")continue;let l=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(m)))));h[d]=this._compileToFunction(l,!1)}n[i][r]=d=>{let m={...c};for(let[l,p]of Object.entries(h))m[l]=p(d);return m}}}return n}static compileBlockMessage(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processMessageBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){let h=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));n[i][r]=this._compileToFunction(h,!1)}}return n}static compileBlockDescription(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processDescriptionBlocks(o);n[i]={};for(let[r,c]of Object.entries(a))for(let[h,d]of Object.entries(c)){n[i][h]||(n[i][h]={});let m=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));n[i][h][r]=this._compileToFunction(m,!1)}}return n}static compileBlockKeyboards(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processKeyboardBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){n[i][r]={};for(let[h,d]of Object.entries(c)){let l=d.split(/(?<!\\),\s*/).map(p=>p.replace(/\\,/g,",").trim()).map(p=>this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(p))))));n[i][r][h]=this._compileToFunction(l,!0)}}}return n}static _extractBlock(e,t,s="default",n="all",i){let o=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,a=e,r=!1;for(let c of e.matchAll(o))if((c[2]??"default")===s){a=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(e);if(!(s==="default"&&!c))return""}if(t){if(t==="all")return a;let c=Array.isArray(t)?t:[t],h=[];for(let m of c){let l=new RegExp(`([ \\t]*)<${m}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${m}>`,"gi");for(let p of a.matchAll(l)){let _=p[2];if(i){let C=/lang="([^"]*)"/i,I=_?.match(C);if(((I?I[1]:void 0)||"default")!==i)continue}h.push({start:p.index,content:p[0],innerContent:p[3]??""})}}h.sort((m,l)=>m.start-l.start);let d=u(m=>{let l=m.split(`
|
|
2
|
-
`);if(
|
|
3
|
-
`).trim()},"processResult");return n==="all"?
|
|
4
|
-
`):
|
|
5
|
-
`)}return a}static _processImportBlocks(e){let t=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,s=[];return{processed:e.replace(t,(i,o,a)=>{let r={},c=/(\w+)="([^"]*)"/g;if(a)for(let
|
|
6
|
-
`).map((
|
|
7
|
-
`);a=a.replace(`__IMPORT_${r}__`,m)}return a}static validateBlockNames(e){let t=[],s=new Set(g.ALLOWED_BLOCKS.map(o=>o.replace(/^<\/?/,"").replace(/\s.*?>$/,"").replace(/\/?>$/,"").toLowerCase())),n=new Set(["b","i","u","s","code","pre","a","blockquote"]),i=/<\/?\s*([a-z][\w-]*)(?:\s[^<>]*)?\/?\s*>/gi;for(let o of e.matchAll(i)){let a=o[1]?.toLowerCase();if(!a||n.has(a)||s.has(a))continue;let r=(e.slice(0,o.index).match(/\n/g)||[]).length+1;t.push({line:r,message:`Unsupported template block: <${a}>`})}return{valid:t.length===0,errors:t}}static validateScopes(e){let t=[],s=new Set(g.ALLOWED_SCOPE),n=/\{([^\s{}\w])([\s\S]*?)\1\}/g;for(let i of e.matchAll(n)){let o=`{${i[1]}${i[1]}}`;if(i[1]&&s.has(o))continue;let a=(e.slice(0,i.index).match(/\n/g)||[]).length+1,r=i[1]??"?";t.push({line:a,message:`Unsupported template scope: {${r} ${r}}`})}return{valid:t.length===0,errors:t}}static validateBlockPositions(e){let t=[],s=[],n=new Set(["b","i","u","s","code","pre","a","blockquote"]),i={base:new Set(["__root__"]),message:new Set(["base"]),keyboard:new Set(["base"]),media:new Set(["base"]),description:new Set(["base"]),switch:new Set(["base","message","description","keyboard","case","default","map","div"]),case:new Set(["switch"]),default:new Set(["switch"]),map:new Set(["base","message","description","keyboard","case","default","div"]),div:new Set(["base","message","description","keyboard","case","default","map"]),script:new Set(["base","message","description","keyboard","case","default","map","div"]),import:new Set(["base"]),space:new Set(["base","message","description","keyboard","case","default","switch","map","div"])},o=/<(\/?)(\w[\w-]*)([^>]*)>/g,a;for(;(a=o.exec(e))!==null;){let r=a[0],c=a[1],h=a[2].toLowerCase(),d=c==="/",m=!d&&r.endsWith("/>");if(n.has(h)||!i[h])continue;let l=(e.slice(0,a.index).match(/\n/g)||[]).length+1;if(d)if(s.length===0)t.push({line:l,message:`Unexpected closing tag </${h}>: no matching opening tag`});else{let p=s[s.length-1];p.block!==h?t.push({line:l,message:`Mismatched closing tag: expected </${p.block}> but found </${h}>`}):s.pop()}else if(m){let p=s.length>0?s[s.length-1].block:"__root__";i[h].has(p)||t.push({line:l,message:`Block <${h}> is not allowed inside <${p}>`})}else{let p=s.length>0?s[s.length-1].block:"__root__";i[h].has(p)||t.push({line:l,message:`Block <${h}> is not allowed inside <${p}>`}),s.push({block:h,line:l})}}for(let r of s)t.push({line:r.line,message:`Unclosed block <${r.block}>: missing closing tag </${r.block}>`});return{valid:t.length===0,errors:t}}static validateBlockFormat(e){let t=[],s=new Set(["space","import"]),n=new Set(["base","message","keyboard","media","description","script","switch","case","default","map","div"]),i=/<(\/?)(\w[\w-]*)([^>]*)>/g,o;for(;(o=i.exec(e))!==null;){let a=o[0],r=o[1],c=o[2].toLowerCase(),h=r==="/",d=!h&&a.endsWith("/>");if(h)continue;let m=(e.slice(0,o.index).match(/\n/g)||[]).length+1;d?n.has(c)&&t.push({line:m,message:`Block <${c}> must not be self-closing: use <${c}>...</${c}> instead`}):s.has(c)&&t.push({line:m,message:`Block <${c}> must be self-closing: use <${c} /> instead`})}return{valid:t.length===0,errors:t}}static validateTemplate(e){let t=this.validateBlockNames(e),s=this.validateScopes(e),n=this.validateBlockFormat(e),i=this.validateBlockPositions(e),o=[...t.errors,...s.errors,...n.errors,...i.errors];return{valid:o.length===0,errors:o}}};var L=class{static{u(this,"TemplateManager")}_map=new Map;_engine=A;_watcher=[];_pageManager=M;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(e){let{path:t,enableWatch:s=!1}=e;this._path=t,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(e.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let e=0;e<this._path.length;e++){let t=this._path[e];if(!(0,T.existsSync)(t))throw new Error(`Template base path is not exists: ${t}`);if(!(0,T.statSync)(t).isDirectory())throw new Error(`Template base path is not a directory: ${t}`)}return!0}catch(e){throw new Error(`Failed to validate Template base path: ${String(e)}`)}}_initializeWatcher(e){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let t=0;t<this._path.length;t++){let s=this._path[t],n=(0,he.watch)(s,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...e});this._watcher[t]=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(e){let t=(0,w.basename)(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileAdd(e){let t=(0,w.basename)(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileDelete(e){let t=(0,w.basename)(e),s=this._getKey(t);this._map.has(s)&&this._map.delete(s)}_handleWatchError(e){}_loadAllFiles(){let e=new Map,t=[];for(let n=0;n<this._path.length;n++){let i=this._path[n],a=(0,T.readdirSync)(i,"utf8").filter(r=>this._isValidFile(r));for(let r of a){let c=(0,w.join)(i,r),h=this._getExtension(r),d=this._getKey(r);if(h===".html")e.set(d,(0,T.readFileSync)(c,"utf8"));else if(h===".ts"||h===".js"){let m=M.getFileSync(c);m?.template!==void 0&&(e.set(d,m.template),t.push(m))}}}let s=new Map;for(let[n,i]of e.entries())this._compile(n,i,void 0,s,e);e.clear(),s.clear();for(let n of t)n.template=void 0}_loadFile(e){for(let t=0;t<this._path.length;t++){let s=this._path[t],n=(0,w.join)(s,e),i=this._getExtension(e),o=this._getKey(e);if(i==".html"){let a=(0,T.readFileSync)(n,"utf8");this._compile(o,a)}else if(i==".ts"||i==".js"){let a=M.getFileSync(n);a?.template!==void 0&&(this._compile(o,a.template),a.template=void 0)}else throw new Error(`File ${e} is not support`)}}_getExtension(e){return(0,w.extname)(e).toLowerCase()}_readTemplateFile(e){for(let t of this._path){let s=(0,w.extname)(e).toLowerCase();if(s){let a=(0,w.join)(t,e);if((0,T.existsSync)(a)&&(0,T.statSync)(a).isFile()){if(s===".html")return(0,T.readFileSync)(a,"utf8");if(s===".ts"||s===".js")try{return M.getFileSync(a)?.template??null}catch{return null}}continue}let n=(0,w.join)(t,`${e}.ts`),i=(0,w.join)(t,`${e}.js`);if((0,T.existsSync)(n)&&(0,T.statSync)(n).isFile())try{return M.getFileSync(n)?.template??null}catch{}else if((0,T.existsSync)(i)&&(0,T.statSync)(i).isFile())try{return M.getFileSync(n)?.template??null}catch{}let o=(0,w.join)(t,`${e}.html`);if((0,T.existsSync)(o)&&(0,T.statSync)(o).isFile())return(0,T.readFileSync)(o,"utf8")}return null}_isValidFile(e){return this._supportedExtensions.has(this._getExtension(e))}_validateTemplate(e,t){let s=A.validateTemplate(t);if(!s.valid&&s.errors.length>0){let n=s.errors[0];throw new Error(`Template on base "${e}" (line ${n.line}): ${n.message}`)}}_getKey(e){return e.replace(/\.[^/.]+$/,"")}_compile(e,t,s,n,i){let o=this._map.get(e),a=o||{},r=!1;this._validateTemplate(e,t);let c=A.processImportBlocks(t,d=>i&&i.has(d)?i.get(d):this._readTemplateFile(d),0,n);this._validateTemplate(e,c);let h=A._processBaseBlocks(c);(s===void 0||s?.media===!1||o?.media===void 0)&&(a.media=A.compileBlockMedia(c,h),r=!0),(s===void 0||s?.message===!1||o?.message===void 0)&&(a.message=A.compileBlockMessage(c,h),r=!0),(s===void 0||s?.keyboard===!1||o?.keyboard===void 0)&&(a.keyboard=A.compileBlockKeyboards(c,h),r=!0),(s===void 0||s?.description===!1||o?.description===void 0)&&(a.description=A.compileBlockDescription(c,h),r=!0),r&&this._map.set(e,a)}getMedia(e,t="default",s="default",n){let o=this._map.get(e)?.media?.[t],a=o?.[s]||o?.default;try{if(!a)throw new Error("Media function not found, please check your template");return a(n)}catch{return{}}}getMessage(e,t="default",s="default",n){try{let o=this._map.get(e)?.message?.[t],a=o?.[s]||o?.default;if(!a)throw"";return a(n)}catch{return""}}getDescription(e,t="default",s="default",n="default",i){try{let a=this._map.get(e)?.description?.[t]?.[n],r=a?.[s]||a?.default;if(!r)throw"";return r(i)}catch{return""}}getDescriptionLanguage(e,t="default",s="default"){try{let i=this._map.get(e)?.description?.[t]?.[s];return i?Object.keys(i):[]}catch{return[]}}getDescriptionScopes(e,t="default"){try{let n=this._map.get(e)?.description?.[t];return n?Object.keys(n):[]}catch{return[]}}getKeyboard(e,t="default",s="default",n="inline",i){try{let a=this._map.get(e)?.keyboard?.[t],r=a?.[s]?.[n]||a?.default?.[n];if(!r)throw[];return r(i)}catch{return[]}}async write(e,t){if(this._getExtension(e)!=".html")return null;for(let s=0;s<this._path.length;s++){let n=(0,w.join)(this._path[s],e);if((0,T.existsSync)(n))return(0,T.writeFileSync)(n,t,"utf8"),this._loadFile(e),!0}return null}has(e){return this._map.has(e)}async destroy(){if(this._watcher)for(let e of this._watcher)await e.close();this._map.clear()}};var q=require("grammy");var E=class{constructor(e){this.maxSize=e;if(!Number.isFinite(e)||e<=0)throw new Error("WebhookQueue maxSize must be a positive number")}maxSize;static{u(this,"WebhookQueue")}queue=[];waitEnqueue=[];waitDequeue=[];getStats(){return{length:this.queue.length,maxSize:this.maxSize,waitingEnqueue:this.waitEnqueue.length,waitingDequeue:this.waitDequeue.length}}get length(){return this.queue.length}async enqueue(e){if(this.queue.length>=this.maxSize&&await new Promise(t=>this.waitEnqueue.push(t)),this.waitDequeue.length>0){this.waitDequeue.shift()(e);return}this.queue.push(e)}async dequeue(){if(this.queue.length>0){let e=this.queue.shift();return this.waitEnqueue.shift()?.(),e}return await new Promise(e=>this.waitDequeue.push(e))}};var Ie=(0,v.dirname)((()=>{try{return __filename}catch{return(0,me.fileURLToPath)(f)}})()),xe=JSON.parse((0,le.readFileSync)((0,v.join)(Ie,"../../package.json"),"utf-8")).version,z=class{static{u(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;optionsPage={shortCallbackData:!1};log;bot;botConfig;webhookQueue;webhookQueueInstance;webhookServer;handlerBotUpdate;deployType;constructor(e){if(!e?.token||e?.token?.length==0)throw new Error("Token is not valid or empty");if(typeof e.optionsPage?.shortCallbackData=="boolean"&&(this.optionsPage.shortCallbackData=e.optionsPage.shortCallbackData),this.log=e.log===!0?$:e.log?e.log:void 0,this.log?.info?.(`Gramstax v${xe}`),this.cacheSession=e.cacheSession||new V("memory"),this.cacheKeyboard=e.cacheKeyboard||new Map,this.botConfig=e.botConfig,this.webhookQueue=e.webhookQueue,this.templateManager=e.templateManager||new L({path:[(0,v.join)(process.cwd(),"src","pages")]}),this.bot=this.createBot(e.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.stop()),process.once("SIGTERM",()=>this.stop()),this.hookBeforeStart(),e.deploy.startsWith("polling"))this.deployType="polling",this._runPolling();else if(e.deploy.startsWith("webhook:"))this.deployType="webhook",this._runWebhook(e.deploy.split("webhook:")[1]);else if(e.deploy.startsWith("serverless:"))this.deployType="serverless",this._runServerless(e.deploy.split("serverless:")[1]);else if(e.deploy.startsWith("test"))this.deployType="test";else throw new Error("Params deploy is not valid, expected: polling, webhook:<public-url>, serverless:<your-adapter>")}async stop(){await this.bot.stop(),this.deployType==="webhook"&&(await this.webhookServer?.stop(),this.webhookServer=void 0)}_onCatch(e){if(this.log?.errorMake)this.log?.errorMake(e,"Bot","catch");else{let t=JSON.stringify(e,null,2);this.log?.error?.(`[Bot.catch]: ${t}`)}}hookBeforeStart(){}hookAfterStart(){}async _onStart(e,t,s){await this.executeSyncBlocksDescription(this.pages);let{username:n}=e;this.log?.success?.(`Telegram bot deploy ${t} started: ${n} ${t=="webhook"||t=="serverless"?`(${s})`:""}`),this.hookAfterStart()}createBot(e){return new q.Bot(e,this.botConfig)}createCtx(e){return new K({ct:e,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{isAnswer:!1,session:{},data:{}}})}_runPolling(){this.bot.start({drop_pending_updates:!0,onStart:u(e=>{this._onStart(e,"polling",null)},"onStart")})}async _runWebhook(e){let{serve:t}=await import("bun"),s=(0,q.webhookCallback)(this.bot,"bun"),n=this.webhookQueue,i=n?.enabled===!0;this.handlerBotUpdate=i?this.bot.handleUpdate.bind(this.bot):s;let o=i?new E(n?.maxQueueSize??5e3):void 0,a=n?.workerCount??8,r=n?.perChatConcurrency??1,c=n?.blockWhenFull!==!1,h=new Map,d=new Map;this.webhookQueueInstance=o;let m=u(y=>y?.message?.chat?.id??y?.edited_message?.chat?.id??y?.channel_post?.chat?.id??y?.edited_channel_post?.chat?.id??y?.callback_query?.message?.chat?.id??y?.callback_query?.from?.id??y?.inline_query?.from?.id??y?.chosen_inline_result?.from?.id,"getChatId"),l=u(async y=>{if(!i||r<=0||y===void 0||y===null)return()=>{};let b=String(y),k=h.get(b)||0;if(k<r)return h.set(b,k+1),()=>this._releaseWebhookChat(b,h,d);await new Promise(ye=>{let ne=d.get(b)||[];ne.push(ye),d.set(b,ne)});let ge=(h.get(b)||0)+1;return h.set(b,ge),()=>this._releaseWebhookChat(b,h,d)},"acquireChat");if(i&&o){await this.bot.init();for(let y=0;y<a;y++)this._startWebhookWorker(o,l,m)}let p=new URL(e),_=p.pathname,C=parseInt(p.port)||3e3,I=this.log,S="/stats_queue";this.webhookServer?.stop();let x=t({port:C,async fetch(y){let{pathname:b}=new URL(y.url);if(y.method=="POST"&&b==_){if(!i||!o)return s(y);if(!c&&o.length>=(n?.maxQueueSize??5e3))return new Response("Queue full",{status:429});try{let k=await y.json();return await o.enqueue(k),new Response("OK",{status:200})}catch(k){return I?.error?.(`Webhook queue error: ${String(k)}`),new Response("Bad Request",{status:400})}}if(y.method=="GET"&&b==S){let k=o?.getStats()||{length:0,maxSize:n?.maxQueueSize??5e3,waitingEnqueue:0,waitingDequeue:0};return new Response(JSON.stringify({enabled:i,path:S,timestamp:new Date().toISOString(),maxQueueSize:n?.maxQueueSize??5e3,workerCount:a,perChatConcurrency:r,blockWhenFull:c,queue:k,activeChats:h.size}),{status:200,headers:{"Content-Type":"application/json"}})}if(y.method=="GET"&&b=="/"){let k=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:k}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}});this.webhookServer=x,(await this.bot.api.getWebhookInfo()).url!=e&&await this.bot.api.setWebhook(e);let B=await this.bot.api.getMe();await this._onStart(B,"webhook",e)}_startWebhookWorker(e,t,s){u(async()=>{for(;;){let i=await e.dequeue(),o=await t(s(i));try{await this.bot.handleUpdate(i)}catch(a){this.log?.error?.(`Webhook worker error: ${String(a)}`)}finally{o()}}},"run")()}_releaseWebhookChat(e,t,s){let n=t.get(e)||0,i=Math.max(0,n-1);i===0?t.delete(e):t.set(e,i);let o=s.get(e);o&&o.length>0&&(o.shift()(),o.length===0&&s.delete(e))}getWebhookQueueStats(){if(!this.webhookQueue?.enabled||!this.webhookQueueInstance)return null;let e=this.webhookQueueInstance.getStats(),t=this.webhookQueue.maxQueueSize??5e3,s=this.webhookQueue.workerCount??8,n=this.webhookQueue.perChatConcurrency??1,i=this.webhookQueue.blockWhenFull!==!1;return{enabled:!0,maxQueueSize:t,workerCount:s,perChatConcurrency:n,blockWhenFull:i,...e}}async _runServerless(e){this.handlerBotUpdate=(0,q.webhookCallback)(this.bot,e);let t=await this.bot.api.getMe();await this._onStart(t,"serverless",e)}_pageBuildData(e,t){e?.data===void 0&&(e.data=e.buildData());let{name:s}=(0,v.parse)(t);e.data.name||(e.data.name=s),e.data.intentText||(e.data.intentText=e.data.name),e.data.intentCommandText||(e.data.intentCommandText=e.data.name),e.data.intentCallbackData||(e.data.intentCallbackData=e.data.name)}_pageSorts(e,t,s){let n=e.data.name,i=e.prototype,o="handle",a="Args",r="Command",c="Caption",h="Free",d=t.routeDynamic,m=t.routeDynamicSpesific;t.all[n]=e;for(let l=0;l<t.lenListRouteStaticSession;l++){let p=t.listRouteStaticSession[l];if(typeof i[p]!="function")continue;let _=t.routeStatic[p],C=t.routeStaticIntent[p],I=t.routeStaticSession[p],S={name:n,routeName:p},x=_||C;if(x!==void 0){let F=p.includes(r),B=p.endsWith("CallbackData"),y=p.endsWith("Text"),b;if(F){let k=e.data.intentCommandText;b=k?`/${k}`:void 0}else if(B){let k=e.data.intentCallbackData;this.optionsPage.shortCallbackData===!0&&(k=String(s),e.data.intentCallbackData=k),b=k}else y?b=e.data.intentText:b=e.data.name;b&&(x[b]=S)}if(I!==void 0){let B=`methodSession${p.replace("handle","")}`,y=i[B]?.(n);I[y]=S}if(p.startsWith("handleFree")){let F=p.replace(o,"").replace(a,"").replace(r,"").replace(c,"").replace(h,"").toLowerCase();m[F].push(S)}}i.handleFree&&d.push(n)}async executeSyncBlocksDescription(e){let t=new Map,s=e.routeStatic.handleCommandText;for(let[,n]of Object.entries(s)){let i=n.name,o=this.templateManager.getDescriptionScopes(i);for(let a of o){t.has(a)||t.set(a,new Set);let r=this.templateManager.getDescriptionLanguage(i,"default",a);for(let c of r)t.get(a).add(c)}}for(let[n,i]of t)for(let o of i){let a=[];for(let[,h]of Object.entries(s)){let d=h.name,m=this.templateManager.getDescription(d,"default",o,n);m&&a.push({command:d,description:m})}if(a.length===0)continue;let r={type:n},c=o==="default"?void 0:o;try{let h=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(h.map(l=>({command:l.command,description:l.description})).sort((l,p)=>l.command.localeCompare(p.command))),m=JSON.stringify(a.sort((l,p)=>l.command.localeCompare(p.command)));d!==m&&(await this.bot.api.setMyCommands(a,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${n},${c?` lang: ${c},`:""} total (${a.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 e=["handleCallbackData","handleText","handleCommandText","handleCaptionPhoto","handleCommandCaptionPhoto","handleCaptionVideo","handleCommandCaptionVideo","handleCaptionAudio","handleCommandCaptionAudio","handleCaptionDocument","handleCommandCaptionDocument","handleCaptionAnimation","handleCommandCaptionAnimation","handleCaptionVoice","handleCommandCaptionVoice"],t=["handleArgsCallbackData","handleArgsText","handleCommandArgsText","handleCaptionArgsPhoto","handleCommandCaptionArgsPhoto","handleCaptionArgsVideo","handleCommandCaptionArgsVideo","handleCaptionArgsAudio","handleCommandCaptionArgsAudio","handleCaptionArgsDocument","handleCommandCaptionArgsDocument","handleCaptionArgsAnimation","handleCommandCaptionArgsAnimation","handleCaptionArgsVoice","handleCommandCaptionArgsAnimation"],s=[...e,...t,"handleFreeText","handleFreePhoto","handleFreeVideo","handleFreeAudio","handleFreeDocument","handleFreeAnimation","handleFreeVoice","handleFreeVideoNote","handleFreeSticker","handleFreeLocation","handleFreeContact"],n=u((a,r)=>Object.fromEntries(a.map(c=>[c,r()])),"makeObject"),i=u(()=>[],"initDynamicSpesific"),o={all:{},routeDynamic:[],routeDynamicSpesific:{text:i(),photo:i(),video:i(),audio:i(),document:i(),animation:i(),voice:i(),videonote:i(),sticker:i(),location:i(),contact:i()},routeStatic:n(e,()=>({})),routeStaticIntent:n(t,()=>({})),routeStaticSession:n(s,()=>({})),listRouteStatic:e,listRouteStaticIntent:t,listRouteStaticSession:s,lenListRouteStatic:e.length,lenListRouteStaticIntent:t.length,lenListRouteStaticSession:s.length};return M.getFileManySync(void 0).forEach(({path:a,page:r},c)=>{this._pageBuildData(r,a),this._pageSorts(r,o,c),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(o.all).length})`),o}async _pageRoutes(e,t){let s,n;if(s===void 0){let o=await e.getSession();if(o){let a=o.method,r=this.pages.routeStaticSession,c=e.callbackData,h=e.msgText,d=e.msgCaption,m=c||h||d,l=t==="callbackdata",p=l?"colon":"space",_=m&&e.haveArgs(m,p)?e.getIntent(m,p,1):void 0,C=!l&&m?e.getIntent(m,"space",2):void 0;for(let I=0;I<this.pages.lenListRouteStaticSession;I++){let S=this.pages.listRouteStaticSession[I];if(S.toLowerCase().endsWith(t)){if(m){if(this.pages.routeStatic[S]?.[m])continue;let x=this.pages.routeStaticIntent[S];if(x&&(_&&x[_]||C&&x[C]))continue}n=r[S][a]}if(n)break}n!==void 0&&(s=this.pages.all[n.name])}}if(s===void 0){let o=e.callbackData,a=e.msgText,r=e.msgCaption,c=this.pages.routeStatic;for(let h=0;h<this.pages.lenListRouteStatic;h++){let d=this.pages.listRouteStatic[h];if(d.toLowerCase().endsWith(t)&&(n=c[d][o||a||r]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s===void 0){let o=this.pages.routeStaticIntent,a=t==="callbackdata",r=a?"colon":"space",c=a?e.callbackData:e.msgText||e.msgCaption,h=e.haveArgs(c,r);if(c&&h)for(let d=0;d<this.pages.lenListRouteStaticIntent;d++){let m=this.pages.listRouteStaticIntent[d];if(!m.toLowerCase().endsWith(t))continue;let l=o[m];if(n=l[e.getIntent(c,r,1)],!n&&!a&&(n=l[e.getIntent(c,"space",2)]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s!==void 0&&n!==void 0){if(!s.prototype[n.routeName])return;let a=await new s(e)[n.routeName]?.();return e.temp.isAnswer===!0?a:null}let i=this.pages.routeDynamicSpesific[t]||[];for(let o=0;o<i.length;o++){let a=i[o];if(a===void 0)continue;let r=this.pages.all[a.name];r!==void 0&&typeof r.prototype[a.routeName]=="function"&&await new r(e)[a.routeName]()}for(let o=0;o<this.pages.routeDynamic.length;o++){let a=this.pages.routeDynamic[o];if(a===void 0)continue;let r=this.pages.all[a];r!==void 0&&typeof r.prototype.handleFree=="function"&&await new r(e).handleFree()}if(e.temp.isAnswer===!1)return null}async hookBeforeRoute(e,t){return!!(e||t)}async hookErrorPage(e,t,s,n){}async hookErrorInputNotFoundPage(e){}async _onMessage(e,t){let s=this.createCtx(e);try{if(await this.hookBeforeRoute(s,t)===!1)return;await this._pageRoutes(s,t)===null&&await this.hookErrorInputNotFoundPage(s)}catch(n){await this.hookErrorPage(s,t,n,!1)}}async _onCallbackQueryData(e){let t=this.createCtx(e);try{if(await this.hookBeforeRoute(t,"onCallbackQueryData")===!1)return;await this._pageRoutes(t,"callbackdata")}catch(s){await this.hookErrorPage(t,"onCallbackQueryData",s,!0)}}async _onMessageText(e){await this._onMessage(e,"text")}async _onMessagePhoto(e){await this._onMessage(e,"photo")}async _onMessageVideo(e){await this._onMessage(e,"video")}async _onMessageAudio(e){await this._onMessage(e,"audio")}async _onMessageDocument(e){await this._onMessage(e,"document")}async _onMessageAnimation(e){await this._onMessage(e,"animation")}async _onMessageVoice(e){await this._onMessage(e,"voice")}async _onMessageVideoNote(e){await this._onMessage(e,"videonote")}async _onMessageSticker(e){await this._onMessage(e,"sticker")}async _onMessageLocation(e){await this._onMessage(e,"location")}async _onMessageContact(e){await this._onMessage(e,"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{u(this,"BlockKeyboard")}static label;static _build(e,t,s,n){if(!this.label)throw new Error("Label not found, make sure set this.label from class extends LabelKeyboard");s||(s="inline");let i=this.label[e];if(!i)throw new Error(`Object value ${e} not found`);let o=u((a,r)=>`<keyboard type="${s}" lang="${r}">${n?this.label._reverse(a):a}</keyboard>`,"pro");return t?o(i[t],t):Object.keys(i).map(a=>o(i[a],a)).join(" ")}};var Y=class{static{u(this,"LabelKeyboard")}static _reverse(e){return e.split(/(?<!\\), */).reverse().join(", ")}static _reverseObj(e){return Object.keys(e).reduce((t,s)=>(t[s]=this._reverse(e[s]),t),{})}};var H=require("worker_threads");var R=class{constructor(e,t){this.send=e;this.register=t}send;register;static{u(this,"WorkerThreadRpc")}map=new Map;async make(e){let t=this.map,s=this.send,{id:n,method:i,params:o,result:a,error:r}=e;if(i!==void 0)try{let c=this.register[i];if(typeof c!="function")throw new Error(`Method ${i} not found or not function`);let h=await c.apply(this.register,o);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(a!==void 0){let c=t.get(n);c&&(c.resolve(a),t.delete(n))}else if(r!==void 0){let c=t.get(n);c&&(c.reject(r),t.delete(n))}}makeId(){return Math.random()}makeRequest(e,t,s=!0,n){let i=this.makeId(),o={id:i,method:e,params:t,...n};return s?new Promise((a,r)=>{this.map.set(i,{resolve:a,reject:r}),this.send(o)}):this.send(o)}};var U=class{constructor(e,t,s){this.path=e;this.argv=t;this.register=s;this.init(),s||(s=this),this.rpc=new R(this.send.bind(this),s)}path;argv;register;static{u(this,"WorkerThreadLaunch")}static isMainThread=H.isMainThread;_readyResolve;_readyPromise=new Promise(e=>this._readyResolve=e);pid=process.pid;thread={};threadId={};rpc={};ready(){return this._readyPromise}readyResolve(){this._readyResolve?.()}init(){this.thread=new H.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",e=>this.handleOnMessage(e)),this.thread.on("exit",()=>this.kill()),process.once("SIGINT",()=>this.kill()),process.once("SIGTERM",()=>this.kill())}async handleOnMessage(e){this.rpc.make(e)}kill(){this.thread.terminate()}send(e){this.thread.postMessage(e)}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};var Z=class g{static{u(this,"WorkerThreadExport")}static launchGatewayClient(e){let t=new Proxy({},{get(n,i){if(!(typeof i!="string"||i==="then"))return async(o,...a)=>{let r=o.gatewayClients.get(e);return r||(r=await o.createGatewayClient(e)),r.request(i,a)}}}),s=u(function(n){return new Proxy({},{get(i,o){if(!(typeof o!="string"||o==="then"))return async(...a)=>{let r=n.gatewayClients.get(e);return r||(r=await n.createGatewayClient(e)),r.request(o,a)}}})},"ctor");return Object.setPrototypeOf(s,t),s}static init(e){let{WTInit:t,WTLaunch:s=U,path:n,wrap:i}=e,o=`for-${n}`;if(process.argv[2]===o)return new t,{launchGatewayClient:u(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};let a,r=new Proxy({},{get(d,m){if(m!=="then")return m==="sendRequest"||m==="request"||m==="kill"||m==="send"?(...l)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a[m](...l)}:(...l)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a.request(m,l)}}}),h={...i?i(r):{},launchWorker:u(async(d=[])=>(a=new s(n,[o,...d]),await a.ready(),a),"launchWorker"),launchGatewayClient:u(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};return new Proxy(h,{get(d,m){if(m!=="then")return m==="launchGatewayClient"?d.launchGatewayClient:m==="launchWorker"?d.launchWorker:m in d?d[m]:typeof m=="string"?(...l)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a.request(m,l)}:d[m]}})}};var pe=require("net-ipc");var N=class{static{u(this,"WorkerThreadGatewayClient")}client=new pe.Client;rpc;constructor(){this.rpc=new R(e=>this.client.send(e),{}),this.client.on("message",e=>{this.rpc.make(e)})}async connect(e){this.client.options.path=e;let t=new Promise(s=>{this.client.once("ready",()=>s(this))});return await this.client.connect(),t}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};var ue=require("net-ipc");var j=class{static{u(this,"WorkerThreadGatewayServer")}server=new ue.Server;rpc=new Map;register={};constructor(){this.server.on("connect",e=>{let t=new R(s=>e.send(s),this.register);this.rpc.set(e.id,t)}),this.server.on("disconnect",e=>{this.rpc.delete(e.id)}),this.server.on("message",(e,t)=>{let s=this.rpc.get(t.id);s&&s.make(e)}),this.server.on("error",e=>{console.error(e)})}async start(e,t={}){this.register=t,this.server.options.path=e;let s=new Promise(n=>{this.server.once("ready",()=>n(this))});return await this.server.start(),s}};var O=require("worker_threads");var ee=class{static{u(this,"WorkerThreadInit")}argv=process.argv;id=O.threadId;pid=process.pid;rpc={};parentPort=O.parentPort;gatewayServer;gatewayClients=new Map;gatewayClientLatest;static gatewayServerPath;gatewayServerPath=this.constructor.gatewayServerPath;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=O.isMainThread;constructor(){this.init(),this.rpc=new R(this.send.bind(this),this),this.send({method:"readyResolve"})}init(){this.parentPort?.on("message",e=>this.handleOnMessage(e))}handleOnMessage(e){this.rpc.make(e)}send(e){this.parentPort?.postMessage(e)}request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}async createGatewayServer(e,t){return e||(e=this),t||(t=this.constructor.gatewayServerPath),this.gatewayServer=new j,await this.gatewayServer.start(t,e),this.constructor.gatewayServerPath=t,!0}async createGatewayClient(e){let t=new N;return await t.connect(e),this.gatewayClients.set(e,t),this.gatewayClientLatest=t,t}};var te=class{static{u(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(e){this.addMany(e)}add(e){this.thread.set(e.threadId,e),this.threadCount+=1}addMany(e){e.forEach(t=>this.add(t))}getInstance(e){return this.thread.get(e)}kill(e){let t=this.thread.get(e);return t?.kill(),this.thread.delete(e),this.threadCount-=1,t?.threadId}killAll(){this.thread.values().forEach(({threadId:e})=>this.kill(e))}async broadcastRequest(e,t){return await Promise.all(Object.values(this.thread).map(s=>s.request(e,t,!0)))}async request(e,t,s,n=!0,i){return await this.thread.get(e)?.request(t,s,n,i)}};var se=class{static{u(this,"MockTelegramServer")}botToken="";hostname;port;log;handlers;defaultHandler;apiRoot="";webhookUrl="";requests=[];updates=[];server;_nextUpdateId=1;_nextMessageId=1;constructor(e={}){this.hostname=e.hostname??"127.0.0.1",this.port=e.port??0,this.log=e.log===!0?$:e.log?e.log:void 0,this.handlers=e.handlers??{},this.defaultHandler=e.defaultHandler}async start(){if(this.server)return this.apiRoot;let e=Bun.serve({port:this.port,hostname:this.hostname,fetch:u(async t=>this._handleRequest(t),"fetch")});return this.server=e,this.apiRoot=`http://${this.hostname}:${e.port??this.port}`,process.once("SIGINT",()=>this.stop()),process.once("SIGTERM",()=>this.stop()),this.log?.info?.(`Mock Telegram server started: ${this.apiRoot}`),this.apiRoot}async stop(){this.server?.stop(),this.server=void 0,this.log?.info?.("Mock Telegram server stopped")}_json(e){return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":"application/json"}})}lastRequest(e){if(!e)return this.requests[this.requests.length-1];for(let t=this.requests.length-1;t>=0;t--){let s=this.requests[t];if(s?.method===e)return s}}clearRequests(){this.requests.length=0}_defaultResponse(e,t){if(e==="getMe")return{ok:!0,result:{id:123456789,is_bot:!0,first_name:"Mock",username:"mock_gramstax_bot"}};if(e==="getUpdates")return{ok:!0,result:[]};if(e==="getMyCommands")return{ok:!0,result:[]};if(e==="setMyCommands")return{ok:!0,result:!0};if(e==="setWebhook"){let s=this._bodyRecord(t),n=typeof s?.url=="string"?s.url:"";return this.webhookUrl=n,this.log?.info?.(`Mock Telegram webhook set: ${n}`),{ok:!0,result:!0}}return e==="getWebhookInfo"?{ok:!0,result:{url:this.webhookUrl}}:{ok:!0,result:!0}}async _handleRequest(e){let{pathname:t}=new URL(e.url),s=t.match(/^\/bot([^/]+)\/(.+)$/);if(!s)return new Response("Not found",{status:404});let n=s[1],i=s[2];if(!n||!i)return new Response("Not found",{status:404});this.botToken=n;let o=await this._readBody(e.clone());this.log?.debug?.(`Mock Telegram API request: ${i}`),this.requests.push({method:i,body:o,url:e.url,requestMethod:e.method,headers:Object.fromEntries(e.headers.entries())});let a=this.handlers[i]??this.defaultHandler,r=a?await a({method:i,request:e}):this._defaultResponse(i,o);return this._json(r)}_bodyRecord(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}async _readBody(e){if(e.method==="GET"||e.method==="HEAD")return;let t=e.headers.get("content-type")||"";try{if(t.includes("application/json"))return await e.json();if(t.includes("multipart/form-data")||t.includes("application/x-www-form-urlencoded")){let n=await e.formData();return Object.fromEntries(n.entries())}let s=await e.text();if(!s)return;try{return JSON.parse(s)}catch{return s}}catch{return}}_defaultUser(e){return{id:e?.id??1001,is_bot:e?.is_bot??!1,first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.username?{username:e.username}:{},language_code:e?.language_code??"en"}}_defaultChat(e){return{id:e?.id??1001,type:e?.type??"private",first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.username?{username:e.username}:{},...e?.title?{title:e.title}:{}}}_nextIds(e){return{updateId:this._nextUpdateId++,messageId:e?.message_id??this._nextMessageId++,date:e?.date??Math.floor(Date.now()/1e3)}}_buildMessageUpdate(e,t){let{updateId:s,messageId:n,date:i}=this._nextIds(t);return{update_id:s,message:{message_id:n,date:i,chat:this._defaultChat(t?.chat),from:this._defaultUser(t?.user),...e}}}async _postUpdate(e,t){if(await this._waitForWebhookUrl(t?.responseTimeoutMs??1e3),!this.webhookUrl)throw new Error("Webhook URL is not set. Call setWebhook first or assign mockServer.webhookUrl.");let s=this.requests.length;this.updates.push(e),this.log?.info?.(`Mock Telegram update sent: ${this.webhookUrl}`);let n=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`Webhook request failed with status ${n.status}`);let i=await this._waitForResponses(s,t?.responseTimeoutMs??1e3);return this.log?.info?.(`Mock Telegram bot responses captured: ${i.length}`),i}async _waitForWebhookUrl(e){if(this.webhookUrl||e<=0)return this.webhookUrl;let t=Date.now();for(;Date.now()-t<e&&(await new Promise(s=>setTimeout(s,5)),!this.webhookUrl););return this.webhookUrl}async _waitForResponses(e,t){if(t<=0)return this._userResponseRequests(e);if(this._userResponseRequests(e).length>0)return this._userResponseRequests(e);let s=Date.now();for(;Date.now()-s<t&&(await new Promise(n=>setTimeout(n,5)),!(this._userResponseRequests(e).length>0)););return this._userResponseRequests(e)}_userResponseRequests(e){return this.requests.slice(e).filter(t=>this._isUserResponseMethod(t.method))}_isUserResponseMethod(e){return e.startsWith("send")||e.startsWith("edit")||e.startsWith("answer")||e.startsWith("delete")||e.startsWith("copy")||e.startsWith("forward")||e==="pinChatMessage"||e==="unpinChatMessage"||e==="setMessageReaction"}async sendText(e,t){let s=e.startsWith("/")?[{offset:0,length:e.split(" ")[0]?.length??e.length,type:"bot_command"}]:void 0;return await this._postUpdate(this._buildMessageUpdate({text:e,...s?{entities:s}:{}},t),t)}async sendPhoto(e){return await this._postUpdate(this._buildMessageUpdate({photo:[{file_id:"mock-photo-file-id",file_unique_id:"mock-photo-unique-id",width:1,height:1}],...e?.caption?{caption:e.caption}:{}},e),e)}async sendVideo(e){return await this._postUpdate(this._buildMessageUpdate({video:{file_id:"mock-video-file-id",file_unique_id:"mock-video-unique-id",width:1,height:1,duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendAudio(e){return await this._postUpdate(this._buildMessageUpdate({audio:{file_id:"mock-audio-file-id",file_unique_id:"mock-audio-unique-id",duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendDocument(e){return await this._postUpdate(this._buildMessageUpdate({document:{file_id:"mock-document-file-id",file_unique_id:"mock-document-unique-id",file_name:"mock.txt"},...e?.caption?{caption:e.caption}:{}},e),e)}async sendAnimation(e){return await this._postUpdate(this._buildMessageUpdate({animation:{file_id:"mock-animation-file-id",file_unique_id:"mock-animation-unique-id",width:1,height:1,duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendVoice(e){return await this._postUpdate(this._buildMessageUpdate({voice:{file_id:"mock-voice-file-id",file_unique_id:"mock-voice-unique-id",duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendVideoNote(e){return await this._postUpdate(this._buildMessageUpdate({video_note:{file_id:"mock-video-note-file-id",file_unique_id:"mock-video-note-unique-id",length:1,duration:1}},e),e)}async sendSticker(e){return await this._postUpdate(this._buildMessageUpdate({sticker:{file_id:"mock-sticker-file-id",file_unique_id:"mock-sticker-unique-id",type:"regular",width:1,height:1,is_animated:!1,is_video:!1}},e),e)}async sendLocation(e){return await this._postUpdate(this._buildMessageUpdate({location:{latitude:e?.latitude??0,longitude:e?.longitude??0}},e),e)}async sendContact(e){return await this._postUpdate(this._buildMessageUpdate({contact:{phone_number:e?.phone_number??"+10000000000",first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.user_id?{user_id:e.user_id}:{}}},e),e)}async sendCallbackQuery(e,t){let{updateId:s,messageId:n,date:i}=this._nextIds(t);return await this._postUpdate({update_id:s,callback_query:{id:t?.id??`mock-callback-${s}`,from:this._defaultUser(t?.user),message:{message_id:n,date:i,chat:this._defaultChat(t?.chat),text:t?.messageText??"Mock message"},chat_instance:"mock-chat-instance",data:e}},t)}};0&&(module.exports={BlockKeyboard,CacheExternal,Ctx,Gramstax,LabelKeyboard,LoggingHelper,MockTelegramServer,PageManager,TemplateEngine,TemplateManager,WebhookQueue,WorkerThreadExport,WorkerThreadGatewayClient,WorkerThreadGatewayServer,WorkerThreadInit,WorkerThreadLaunch,WorkerThreadPool,WorkerThreadRpc,log});
|
|
1
|
+
"use strict";var fe=Object.create;var W=Object.defineProperty;var be=Object.getOwnPropertyDescriptor;var Te=Object.getOwnPropertyNames;var Ce=Object.getPrototypeOf,ke=Object.prototype.hasOwnProperty;var u=(g,e)=>W(g,"name",{value:e,configurable:!0});var Se=(g,e)=>{for(var t in e)W(g,t,{get:e[t],enumerable:!0})},ie=(g,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Te(e))!ke.call(g,n)&&n!==t&&W(g,n,{get:()=>e[n],enumerable:!(s=be(e,n))||s.enumerable});return g};var oe=(g,e,t)=>(t=g!=null?fe(Ce(g)):{},ie(e||!g||!g.__esModule?W(t,"default",{value:g,enumerable:!0}):t,g)),we=g=>ie(W({},"__esModule",{value:!0}),g);var Me={};Se(Me,{BlockKeyboard:()=>X,CacheExternal:()=>V,Ctx:()=>E,Gramstax:()=>z,LabelKeyboard:()=>Y,LoggingHelper:()=>Q,MockTelegramServer:()=>se,PageManager:()=>M,TemplateEngine:()=>A,TemplateManager:()=>L,WebhookQueue:()=>K,WorkerThreadExport:()=>Z,WorkerThreadGatewayClient:()=>N,WorkerThreadGatewayServer:()=>j,WorkerThreadInit:()=>ee,WorkerThreadLaunch:()=>U,WorkerThreadPool:()=>te,WorkerThreadRpc:()=>R,log:()=>$});module.exports=we(Me);var _e=u(()=>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=_e();var ae=require("logging-pretty");var Q=class extends ae.LoggingPretty{static{u(this,"LoggingHelper")}timers=new Map;constructor(e){super(e)}errorMake(e,t,s){this.error(`[${t?`${t}:${s}`:s}] ${this._formatErrorObj(e)}`)}_formatErrorObj(e){return JSON.stringify(e instanceof Error?{message:e.message,stack:e.stack,name:e.name}:e,null,2)}time(e){this.timers.set(e,process.hrtime.bigint())}timeEnd(e,t){let s=this.timers.get(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}let n=(Number(process.hrtime.bigint()-s)/1e6).toFixed(3);this.timers.delete(e),t?this.debug(`${t} (took ${n}ms)`):this.debug(`${e} (took ${n}ms)`)}timeCheck(e){let t=this.timers.get(e);if(t!==void 0)return(Number(process.hrtime.bigint()-t)/1e6).toFixed(3)}timeLog(e,t){let s=this.timeCheck(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}t?this.debug(`${t} (${s}ms)`):this.debug(`${e} (${s}ms)`)}timeClear(){this.timers.clear()}timeActive(){return Array.from(this.timers.keys())}},$=new Q;var re=require("keyv"),ce=oe(require("@keyv/redis"),1);var V=class extends re.Keyv{constructor(t="memory",s,n,i){let o;t.startsWith("redis")&&(o=new ce.default(t)),t==="memory"&&(o=new Map),i?.forceStore&&(o=i.forceStore);super({store:o,namespace:n,ttl:s});this.url=t}url;static{u(this,"CacheExternal")}refreshLruCache(t){let s=this.store,n=this.opts.namespace?this.opts.namespace?.length+1:null,i=s.keys().toArray();for(let o=0;o<i.length;o++){let a=i[o];if(o==t)return;this.get(n?a.slice(n):a)}}};var J=require("timers/promises"),P=require("grammy");var E=class{static{u(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(e){this.ct.from.language_code=e}get msgText(){return this.ct.message?.text}get msgTextArgs(){return this.getArgs(this.msgText,"space",this.data?._positionArgText||this.temp?.data?._positionArgText)}get msgTextArg(){return this.msgTextArgs[0]}get msgTextCommandArgs(){return this.getArgs(this.msgText,"space")}get msgTextCommandArg(){return this.msgTextCommandArgs[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionArg(){return this.msgCaptionArgs[0]}get msgCaptionCommandArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionCommandArg(){return this.msgCaptionCommandArgs[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get msgDocument(){return this.ct.message?.document}get msgAnimation(){return this.ct.message?.animation}get msgVoice(){return this.ct.message?.voice}get msgVideoNote(){return this.ct.message?.video_note}get msgSticker(){return this.ct.message?.sticker}get msgLocation(){return this.ct.message?.location}get msgContact(){return this.ct.message?.contact}get msgWebAppData(){return this.ct.message?.web_app_data}get msgGift(){return this.ct.message?.gift}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataArgs(){return this.getArgs(this.callbackData,"colon")}get callbackDataArg(){return this.callbackDataArgs?.[0]}ct;cacheSession;cacheKeyboard;templateManager;temp;constructor(e){this.ct=e.ct,this.cacheSession=e.cacheSession,this.cacheKeyboard=e.cacheKeyboard,this.templateManager=e.templateManager,this.temp=e.temp}async broadcast(e,t,s,n,i,o,a=!1){let r={successCount:0,failedCount:0,totalCount:0};r.totalCount=e.length;try{this.temp.isAnswer=!0;let c=30,l=t.map(d=>this.templateManager.getMessage(this.data.name,i,d,n));for(let d=0;d<e.length;d++){let h=e[d],m=l[d];await this.ct.api.sendMessage(h,m,{parse_mode:"HTML",reply_markup:s,...o}),r.successCount+=1,d+1==c&&await(0,J.setTimeout)(1200)}}catch(c){if(r.failedCount+=1,a)throw{...r,err:c}}return r}async broadcastMedia(e,t,s,n,i,o,a=!1){let r={successCount:0,failedCount:0,totalCount:0};r.totalCount=e.length;try{this.temp.isAnswer=!0;let c=30,l=t.map(d=>this.templateManager.getMedia(this.data.name,i,d,n));for(let d=0;d<e.length;d++){let h=e[d],m=l[d];if(!m)continue;let p={parse_mode:"HTML",reply_markup:s,...o};m.type=="photo"&&await this.ct.api.sendPhoto(h,m.src,{caption:m.caption,...p}),m.type=="video"&&await this.ct.api.sendVideo(h,m.src,{caption:m.caption,...p}),m.type=="audio"&&await this.ct.api.sendAudio(h,m.src,{caption:m.caption,...p}),m.type=="document"&&await this.ct.api.sendDocument(h,m.src,{caption:m.caption,...p}),m.type=="animation"&&await this.ct.api.sendAnimation(h,m.src,{caption:m.caption,...p}),m.type=="voice"&&await this.ct.api.sendVoice(h,m.src,p),m.type=="video_note"&&await this.ct.api.sendVideoNote(h,m.src,p),m.type=="sticker"&&await this.ct.api.sendSticker(h,m.src,p),m.type=="location"&&await this.ct.api.sendLocation(h,parseInt(m.latitude),parseInt(m.longitude),p),m.type=="contact"&&await this.ct.api.sendContact(h,m.phone,m.first_name,{vcard:m.vcard,...p}),r.successCount+=1,d+1==c&&await(0,J.setTimeout)(1200)}}catch(c){if(r.failedCount+=1,a)throw{...r,err:c}}return r}async reply(e,t,s,n){this.temp.isAnswer=!0;let i=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.reply(i,{parse_mode:"HTML",reply_markup:e,...n})}async replyMedia(e,t,s,n,i){this.temp.isAnswer=!0;let o=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s),a={parse_mode:"HTML",reply_markup:t,...i};if(e=="photo")return await this.ct.replyWithPhoto(o.src,{caption:o.caption,...a});if(e=="video")return await this.ct.replyWithVideo(o.src,{caption:o.caption,...a});if(e=="audio")return await this.ct.replyWithAudio(o.src,{caption:o.caption,...a});if(e=="document")return await this.ct.replyWithDocument(o.src,{caption:o.caption,...a});if(e=="animation")return await this.ct.replyWithAnimation(o.src,{caption:o.caption,...a});if(e=="voice")return await this.ct.replyWithVoice(o.src,a);if(e=="video_note")return await this.ct.replyWithVideoNote(o.src,a);if(e=="sticker")return await this.ct.replyWithSticker(o.src,a);if(e=="location")return await this.ct.replyWithLocation(parseInt(o.latitude),parseInt(o.longitude),a);if(e=="contact")return await this.ct.replyWithContact(o.phone,o.first_name,{vcard:o.vcard,...a})}async replyPhoto(e,t,s,n){return this.replyMedia("photo",e,t,s,n)}async replyVideo(e,t,s,n){return this.replyMedia("video",e,t,s,n)}async replyAudio(e,t,s,n){return this.replyMedia("audio",e,t,s,n)}async replyDocument(e,t,s,n){return this.replyMedia("document",e,t,s,n)}async replyAnimation(e,t,s,n){return this.replyMedia("animation",e,t,s,n)}async replyVoice(e,t,s,n){return this.replyMedia("voice",e,t,s,n)}async replyVideoNote(e,t,s,n){return this.replyMedia("video_note",e,t,s,n)}async replySticker(e,t,s,n){return this.replyMedia("sticker",e,t,s,n)}async replyLocation(e,t,s,n){return this.replyMedia("location",e,t,s,n)}async replyContact(e,t,s,n){return this.replyMedia("contact",e,t,s,n)}async replyAction(e){return await this.ct.replyWithChatAction(e)}async edit(e,t,s,n,i=!0){try{this.temp.isAnswer=!0;let o=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.editMessageText(o,{parse_mode:"HTML",reply_markup:e,...n})}catch(o){if(i)await this.reply(e,t,s,n);else throw o}}async editMedia(e,t,s,n,i,o,a=!0){try{this.temp.isAnswer=!0;let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s);return e=="voice"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="video_note"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="sticker"?(await this.delete(),await this.replySticker(t,s,n,i)):e=="location"?(await this.delete(),await this.replyLocation(t,s,n,i)):e=="contact"?(await this.delete(),await this.replyContact(t,s,n,i)):await this.ct.editMessageMedia({media:r,caption:c,type:e,parse_mode:"HTML",...i},{reply_markup:t,...o})}catch(r){if(a===!0)await this.reply(t,s,n,o);else throw r}}async editPhoto(e,t,s,n,i){return await this.editMedia("photo",e,t,s,n,i)}async editVideo(e,t,s,n,i){return await this.editMedia("video",e,t,s,n,i)}async editAudio(e,t,s,n,i){return await this.editMedia("audio",e,t,s,n,i)}async editDocument(e,t,s,n,i){return await this.editMedia("document",e,t,s,n,i)}async editAnimation(e,t,s,n,i){return await this.editMedia("animation",e,t,s,n,i)}async editVoice(e,t,s,n){return await this.editMedia("voice",e,t,s,n)}async editVideoNote(e,t,s,n){return await this.editMedia("video_note",e,t,s,n)}async editSticker(e,t,s,n){return await this.editMedia("sticker",e,t,s,n)}async editLocation(e,t,s,n){return await this.editMedia("location",e,t,s,n)}async editContact(e,t,s,n){return await this.editMedia("contact",e,t,s,n)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(e){try{return this.temp.isAnswer=!0,await this.ct.answerCallbackQuery(e)}catch{return null}}async setSession(e,t,s){try{let n={method:e,params:t,...s},i=await this.cacheSession.set(`${this.userId}`,n);return i&&(this.temp.session=n),i}catch{return null}}async getSession(){try{let e=await this.cacheSession.get(`${this.userId}`);return e&&(this.temp.session=e),e||null}catch{return null}}async clearSession(){try{let e=await this.cacheSession.delete(`${this.userId}`);return e&&(this.temp.session={}),e}catch{return null}}static buildData(e){let s=typeof e=="function"?{callbackData:e}:e||{},n=s.callbackData,i=this.prototype.addArgs.bind(this.prototype),o=s.name||"";return{name:o,intentText:s.intentText||o,intentCommandText:s.intentCommandText||o,intentCallbackData:o,callbackData:n?function(...r){return i(this.intentCallbackData,"colon",n(...r))}:function(){return this?.intentCallbackData},_positionArgText:s.intentText?s.intentText.split(this.prototype.getSeperatorTag("space")).length:void 0}}keyboardCols(e,t,s,n){let[i,o]=s.split("-"),a=parseInt(i),r=o?parseInt(o):null,c=t.length,l=e;for(let d=0;d<c;d++){let h=t[d];if(n(h,d),r===null)(d+1)%a===0&&d<c-1&&l.row();else{let m=c-(d+1);(m===r||m>r&&(d+1)%a===0)&&l.row()}}return e}bottomKeyboardT(e="1",t,s){return this.bottomKeyboard((n,i)=>this.keyboardCols(n,i,e,o=>n.text(o)),{baseId:t??void 0,data:s})}inlineKeyboardT(e,t="1",s,n){return this.inlineKeyboard((i,o)=>this.keyboardCols(i,o,t,(a,r)=>{let c=e[r],l=typeof c=="string"?c:c.data.callbackData();i.text(a,l)}),{baseId:s??void 0,data:n})}inlineKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let a=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(a);if(!r){let c=new P.InlineKeyboard,l=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data),d=e(c,l);return this.cacheKeyboard.set(a,d),d}return r}let n=new P.InlineKeyboard,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data);return e(n,i)}bottomKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let a=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(a);if(!r){let c=new P.Keyboard,l=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),d=e(c,l);return d.resized(!0),this.cacheKeyboard.set(a,d),d}return r}let n=new P.Keyboard,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),o=e(n,i);return o.resized(),o}getSeperatorTag(e="space"){return e=="space"?" ":":"}haveArgs(e="",t){return e.includes(this.getSeperatorTag(t))}addArgs(e="",t,s){let n=this.getSeperatorTag(t),i="";for(let o=0;o<s.length;o++){let a=s[o];a!=null&&a!==""&&(i+=n+a)}return e+i}getArgs(e="",t,s=1){if(!e)return[];let n=this.getSeperatorTag(t);return e.split(n).slice(s)}getIntent(e="",t,s=1){if(!e)return"";let n=this.getSeperatorTag(t),i=e.split(n);return s==1?i[0]:i.slice(0,s).join(n)}isSessionCallbackData(){return this.temp.session.method===this.methodSessionCallbackData()}isSessionArgsCallbackData(){return this.temp.session.method===this.methodSessionArgsCallbackData()}isSessionText(){return this.temp.session.method===this.methodSessionText()}isSessionArgsText(){return this.temp.session.method===this.methodSessionArgsText()}isSessionCommandText(){return this.temp.session.method===this.methodSessionCommandText()}isSessionCommandArgsText(){return this.temp.session.method===this.methodSessionCommandArgsText()}isSessionFreeText(){return this.temp.session.method===this.methodSessionFreeText()}isSessionCaptionPhoto(){return this.temp.session.method===this.methodSessionCaptionPhoto()}isSessionCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCaptionArgsPhoto()}isSessionCommandCaptionPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionPhoto()}isSessionCommandCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionArgsPhoto()}isSessionFreePhoto(){return this.temp.session.method===this.methodSessionFreePhoto()}isSessionCaptionVideo(){return this.temp.session.method===this.methodSessionCaptionVideo()}isSessionCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCaptionArgsVideo()}isSessionCommandCaptionVideo(){return this.temp.session.method===this.methodSessionCommandCaptionVideo()}isSessionCommandCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVideo()}isSessionFreeVideo(){return this.temp.session.method===this.methodSessionFreeVideo()}isSessionCaptionAudio(){return this.temp.session.method===this.methodSessionCaptionAudio()}isSessionCaptionArgsAudio(){return this.temp.session.method===this.methodSessionCaptionArgsAudio()}isSessionCaptionCommandAudio(){return this.temp.session.method===this.methodSessionCaptionCommandAudio()}isSessionCaptionCommandArgsAudio(){return this.temp.session.method===this.methodSessionCaptionCommandArgsAudio()}isSessionFreeAudio(){return this.temp.session.method===this.methodSessionFreeAudio()}isSessionCaptionDocument(){return this.temp.session.method===this.methodSessionCaptionDocument()}isSessionCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCaptionArgsDocument()}isSessionCommandCaptionDocument(){return this.temp.session.method===this.methodSessionCommandCaptionDocument()}isSessionCommandCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCommandCaptionArgsDocument()}isSessionFreeDocument(){return this.temp.session.method===this.methodSessionFreeDocument()}isSessionCaptionAnimation(){return this.temp.session.method===this.methodSessionCaptionAnimation()}isSessionCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCaptionArgsAnimation()}isSessionCommandCaptionAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionAnimation()}isSessionCommandCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionArgsAnimation()}isSessionFreeAnimation(){return this.temp.session.method===this.methodSessionFreeAnimation()}isSessionCaptionVoice(){return this.temp.session.method===this.methodSessionCaptionVoice()}isSessionCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCaptionArgsVoice()}isSessionCommandCaptionVoice(){return this.temp.session.method===this.methodSessionCommandCaptionVoice()}isSessionCommandCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVoice()}isSessionFreeVoice(){return this.temp.session.method===this.methodSessionFreeVoice()}isSessionFreeVideoNote(){return this.temp.session.method===this.methodSessionFreeVideoNote()}isSessionFreeSticker(){return this.temp.session.method===this.methodSessionFreeSticker()}isSessionFreeLocation(){return this.temp.session.method===this.methodSessionFreeLocation()}isSessionFreeContact(){return this.temp.session.method===this.methodSessionFreeContact()}sessionCallbackData(e){return this.setSession(this.methodSessionCallbackData(),e)}sessionArgsCallbackData(e){return this.setSession(this.methodSessionArgsCallbackData(),e)}sessionText(e){return this.setSession(this.methodSessionText(),e)}sessionArgsText(e){return this.setSession(this.methodSessionArgsText(),e)}sessionCommandText(e){return this.setSession(this.methodSessionCommandText(),e)}sessionCommandArgsText(e){return this.setSession(this.methodSessionCommandArgsText(),e)}sessionFreeText(e){return this.setSession(this.methodSessionFreeText(),e)}sessionCaptionPhoto(e){return this.setSession(this.methodSessionCaptionPhoto(),e)}sessionCaptionArgsPhoto(e){return this.setSession(this.methodSessionCaptionArgsPhoto(),e)}sessionCommandCaptionPhoto(e){return this.setSession(this.methodSessionCommandCaptionPhoto(),e)}sessionCommandCaptionArgsPhoto(e){return this.setSession(this.methodSessionCommandCaptionArgsPhoto(),e)}sessionFreePhoto(e){return this.setSession(this.methodSessionFreePhoto(),e)}sessionCaptionVideo(e){return this.setSession(this.methodSessionCaptionVideo(),e)}sessionCaptionArgsVideo(e){return this.setSession(this.methodSessionCaptionArgsVideo(),e)}sessionCommandCaptionVideo(e){return this.setSession(this.methodSessionCommandCaptionVideo(),e)}sessionCommandCaptionArgsVideo(e){return this.setSession(this.methodSessionCommandCaptionArgsVideo(),e)}sessionFreeVideo(e){return this.setSession(this.methodSessionFreeVideo(),e)}sessionCaptionAudio(e){return this.setSession(this.methodSessionCaptionAudio(),e)}sessionCaptionArgsAudio(e){return this.setSession(this.methodSessionCaptionArgsAudio(),e)}sessionCaptionCommandAudio(e){return this.setSession(this.methodSessionCaptionCommandAudio(),e)}sessionCaptionCommandArgsAudio(e){return this.setSession(this.methodSessionCaptionCommandArgsAudio(),e)}sessionFreeAudio(e){return this.setSession(this.methodSessionFreeAudio(),e)}sessionCaptionDocument(e){return this.setSession(this.methodSessionCaptionDocument(),e)}sessionCaptionArgsDocument(e){return this.setSession(this.methodSessionCaptionArgsDocument(),e)}sessionCommandCaptionDocument(e){return this.setSession(this.methodSessionCommandCaptionDocument(),e)}sessionCommandCaptionArgsDocument(e){return this.setSession(this.methodSessionCommandCaptionArgsDocument(),e)}sessionFreeDocument(e){return this.setSession(this.methodSessionFreeDocument(),e)}sessionCaptionAnimation(e){return this.setSession(this.methodSessionCaptionAnimation(),e)}sessionCaptionArgsAnimation(e){return this.setSession(this.methodSessionCaptionArgsAnimation(),e)}sessionCommandCaptionAnimation(e){return this.setSession(this.methodSessionCommandCaptionAnimation(),e)}sessionCommandCaptionArgsAnimation(e){return this.setSession(this.methodSessionCommandCaptionArgsAnimation(),e)}sessionFreeAnimation(e){return this.setSession(this.methodSessionFreeAnimation(),e)}sessionCaptionVoice(e){return this.setSession(this.methodSessionCaptionVoice(),e)}sessionCaptionArgsVoice(e){return this.setSession(this.methodSessionCaptionArgsVoice(),e)}sessionCommandCaptionVoice(e){return this.setSession(this.methodSessionCommandCaptionVoice(),e)}sessionCommandCaptionArgsVoice(e){return this.setSession(this.methodSessionCommandCaptionArgsVoice(),e)}sessionFreeVoice(e){return this.setSession(this.methodSessionFreeVoice(),e)}sessionFreeVideoNote(e){return this.setSession(this.methodSessionFreeVideoNote(),e)}sessionFreeSticker(e){return this.setSession(this.methodSessionFreeSticker(),e)}sessionFreeLocation(e){return this.setSession(this.methodSessionFreeLocation(),e)}sessionFreeContact(e){return this.setSession(this.methodSessionFreeContact(),e)}methodSession(e,t){return`${e}-${t||this.data.name}`}methodSessionCallbackData(e){return this.methodSession("1",e)}methodSessionArgsCallbackData(e){return this.methodSession("2",e)}methodSessionText(e){return this.methodSession("3",e)}methodSessionArgsText(e){return this.methodSession("4",e)}methodSessionCommandText(e){return this.methodSession("5",e)}methodSessionCommandArgsText(e){return this.methodSession("6",e)}methodSessionFreeText(e){return this.methodSession("7",e)}methodSessionCaptionPhoto(e){return this.methodSession("8",e)}methodSessionCaptionArgsPhoto(e){return this.methodSession("9",e)}methodSessionCommandCaptionPhoto(e){return this.methodSession("10",e)}methodSessionCommandCaptionArgsPhoto(e){return this.methodSession("11",e)}methodSessionFreePhoto(e){return this.methodSession("12",e)}methodSessionCaptionVideo(e){return this.methodSession("13",e)}methodSessionCaptionArgsVideo(e){return this.methodSession("14",e)}methodSessionCommandCaptionVideo(e){return this.methodSession("15",e)}methodSessionCommandCaptionArgsVideo(e){return this.methodSession("16",e)}methodSessionFreeVideo(e){return this.methodSession("17",e)}methodSessionCaptionAudio(e){return this.methodSession("18",e)}methodSessionCaptionArgsAudio(e){return this.methodSession("19",e)}methodSessionCaptionCommandAudio(e){return this.methodSession("20",e)}methodSessionCaptionCommandArgsAudio(e){return this.methodSession("21",e)}methodSessionFreeAudio(e){return this.methodSession("22",e)}methodSessionCaptionDocument(e){return this.methodSession("23",e)}methodSessionCaptionArgsDocument(e){return this.methodSession("24",e)}methodSessionCommandCaptionDocument(e){return this.methodSession("25",e)}methodSessionCommandCaptionArgsDocument(e){return this.methodSession("26",e)}methodSessionFreeDocument(e){return this.methodSession("27",e)}methodSessionCaptionAnimation(e){return this.methodSession("28",e)}methodSessionCaptionArgsAnimation(e){return this.methodSession("29",e)}methodSessionCommandCaptionAnimation(e){return this.methodSession("30",e)}methodSessionCommandCaptionArgsAnimation(e){return this.methodSession("31",e)}methodSessionFreeAnimation(e){return this.methodSession("32",e)}methodSessionCaptionVoice(e){return this.methodSession("33",e)}methodSessionCaptionArgsVoice(e){return this.methodSession("34",e)}methodSessionCommandCaptionVoice(e){return this.methodSession("35",e)}methodSessionCommandCaptionArgsVoice(e){return this.methodSession("36",e)}methodSessionFreeVoice(e){return this.methodSession("37",e)}methodSessionFreeVideoNote(e){return this.methodSession("38",e)}methodSessionFreeSticker(e){return this.methodSession("39",e)}methodSessionFreeLocation(e){return this.methodSession("40",e)}methodSessionFreeContact(e){return this.methodSession("41",e)}};var G=require("path"),D=require("fs"),de=require("module");var M=class{static{u(this,"PageManager")}static _getFile(e,t,s=0){let i=Object.values(e)[s];if(i===void 0)throw new Error(`File ${t} must have export (not default) class page`);return i}static getFilePath(){return(0,G.join)(process.cwd(),"src","pages")}static getFileSync(e,t=0){e||(e=this.getFilePath());let n=(0,de.createRequire)(e)(e);return this._getFile(n,e,t)}static async getFile(e,t=0){e||(e=this.getFilePath());let s=await import(`${e}?t=${Date.now()}`);return this._getFile(s,e,t)}static getFileManySync(e,t=0){if(e||(e=this.getFilePath()),!(0,D.existsSync)(e))throw new Error(`Directory ${e} is not found, please make it manually`);return(0,D.readdirSync)(e).map(n=>{let i=(0,G.join)(e,n);return{path:i,page:this.getFileSync(i,t)}})}static clearCacheRequire(e){if(e||(e=this.getFilePath()),!(0,D.existsSync)(e))throw new Error(`Directory ${e} is not found, please make it manually`);return(0,D.readdirSync)(e).forEach(s=>{let n=(0,G.join)(e,s);delete require.cache[require.resolve(n)]}),!0}};var he=require("fs"),me=require("url"),v=require("path");var w=require("path"),b=require("fs"),le=require("chokidar");var A=class g{static{u(this,"TemplateEngine")}static ALLOWED_BLOCKS=["<base>","<message>","<keyboard>","<media>","<description>","<script>","<switch>","<case>","<default>","<map>","<div>","<import/>","<space/>","<b>","<i>","<u>","<s>","<code>","<pre>","<a>","<blockquote>","<blockquote expandable>"];static ALLOWED_SCOPE=["{{}}","{~~}"];static _escape(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processScopeVariables(e){return e.replace(/\{\{(\w+)\}\}/g,(t,s)=>`\${(data && data["${s}"]) ?? ""}`)}static _processScopeExec(e){return e.replace(/{~\s*([\s\S]*?)\s*~}/g,(t,s)=>`\${(() => { try { return ${s} } catch(e) { try { with(data || {}) { return ${s} } } catch(ee) { return '' } } })()}`)}static _processBaseBlocks(e){let t=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,s={};for(let n of e.matchAll(t)){let i=n[2]??"default",a=(n[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[i]=a}return s}static _processScriptBlocks(e){return e.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(t,s)=>{let n=s.trim();return n?`\${(() => { if (!data) return ''; try { with(data) { ${n} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(e){return e.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(e){return e.replace(/<div>([\s\S]*?)<\/div>/gi,(t,s)=>s.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(e){let t=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return e.replace(t,(s,n,i)=>{if(!n)return"";let o="",a=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=a.exec(i))!==null;){let d=(c[1]||"").split(",").map(m=>m.trim()),h=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(m=>{o+=`case "${m}": `}),o+=`return \`${h}\`; `}let l=r.exec(i);if(l){let d=(l[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();o+=`default: return \`${d}\`; `}else o+="default: return ''; ";return`\${(() => { switch((data && data["${n}"])) { ${o} } })()}`})}static _processMapBlocks(e){let t=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return e.replace(t,(s,n,i)=>{let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let h of n.matchAll(a))o[h[1]]=h[2];let r=o.src;if(!r)return"";let c=o.join??"\\n",l=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");l=l.replace(/\{\{([\w.]+)\}\}/g,(h,m)=>m==="e"||m.startsWith("e.")?`\${${m}}`:m==="i"?"${i}":h);let d=c.replace(/"/g,'\\"');return`\${(() => { const __arr = (data && data["${r}"]) || []; let __out = ""; for (let i = 0; i < __arr.length; i++) { const e = __arr[i]; if (i > 0) { __out += "${d}" } __out += \`${l}\`; } return __out; })()}`})}static _processMediaBlocks(e){let t=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let n of e.matchAll(t)){let i=n[1],o=n[2],a={},r=/(\w+)="([^"]*)"/g;if(i)for(let m of i.matchAll(r))a[m[1]]=m[2];let c=a.lang||"default",l=a.type,d=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),h={type:l};a.src&&(h.src=a.src),d&&l!=="video_note"&&l!=="sticker"&&(h.caption=d),l==="location"&&(a.latitude&&(h.latitude=a.latitude),a.longitude&&(h.longitude=a.longitude),d&&(h.caption=d)),l==="contact"&&(a.phone&&(h.phone=a.phone),a.first_name&&(h.first_name=a.first_name),a.last_name&&(h.last_name=a.last_name),a.vcard&&(h.vcard=a.vcard),d&&(h.caption=d)),s[c]=h}return s}static _processMessageBlocks(e){let t=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let l of n.matchAll(a))o[l[1]]=l[2];let r=o.lang||"default",c=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=c}return s}static _processDescriptionBlocks(e){let t=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(a))o[d[1]]=d[2];let r=o.lang||"default",c=o.scope||"default",l=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][c]=l}return s}static _processKeyboardBlocks(e){let t=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(a))o[d[1]]=d[2];let r=o.lang||"default",c=o.type==="bottom"?"bottom":"inline",l=i.trim();s[r]||(s[r]={}),s[r][c]=l}return s}static _compileToFunction(e,t){let s;t?s=e.map(o=>`\`${o}\``).join(","):s=`\`${e}\``;let n=s;if(n=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(n))),t){let i=`return [${n}]`;return new Function("data",i)}else{let i=`return ${n}`;return new Function("data",i)}}static compileBlockMedia(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processMediaBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){let l={};for(let[d,h]of Object.entries(c)){if(d==="type"||typeof h!="string")continue;let m=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(h)))));l[d]=this._compileToFunction(m,!1)}n[i][r]=d=>{let h={...c};for(let[m,p]of Object.entries(l))h[m]=p(d);return h}}}return n}static compileBlockMessage(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processMessageBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){let l=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));n[i][r]=this._compileToFunction(l,!1)}}return n}static compileBlockDescription(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processDescriptionBlocks(o);n[i]={};for(let[r,c]of Object.entries(a))for(let[l,d]of Object.entries(c)){n[i][l]||(n[i][l]={});let h=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));n[i][l][r]=this._compileToFunction(h,!1)}}return n}static compileBlockKeyboards(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processKeyboardBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){n[i][r]={};for(let[l,d]of Object.entries(c)){let m=d.split(/(?<!\\),\s*/).map(p=>p.replace(/\\,/g,",").trim()).map(p=>this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(p))))));n[i][r][l]=this._compileToFunction(m,!0)}}}return n}static _extractBlock(e,t,s="default",n="all",i){let o=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,a=e,r=!1;for(let c of e.matchAll(o))if((c[2]??"default")===s){a=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(e);if(!(s==="default"&&!c))return""}if(t){if(t==="all")return a;let c=Array.isArray(t)?t:[t],l=[];for(let h of c){let m=new RegExp(`([ \\t]*)<${h}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${h}>`,"gi");for(let p of a.matchAll(m)){let _=p[2];if(i){let C=/lang="([^"]*)"/i,I=_?.match(C);if(((I?I[1]:void 0)||"default")!==i)continue}l.push({start:p.index,content:p[0],innerContent:p[3]??""})}}l.sort((h,m)=>h.start-m.start);let d=u(h=>{let m=h.split(`
|
|
2
|
+
`);if(m.length<=1)return h.trim();let p=m.filter(C=>C.trim().length>0);if(p.length===0)return"";let _=p.reduce((C,I)=>{let S=I.match(/^([ \t]*)/),x=S?S[1].length:0;return x<C?x:C},1/0);return m.map(C=>C.length>=_?C.slice(_):C.trimStart()).join(`
|
|
3
|
+
`).trim()},"processResult");return n==="all"?l.map(m=>d(m.content)).join(`
|
|
4
|
+
`):l.map(m=>d(m.innerContent)).join(`
|
|
5
|
+
`)}return a}static _processImportBlocks(e){let t=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,s=[];return{processed:e.replace(t,(i,o,a)=>{let r={},c=/(\w+)="([^"]*)"/g;if(a)for(let m of a.matchAll(c))r[m[1]]=m[2];let l=r.src;if(!l)return"";let d;r.block&&(r.block==="all"?d="all":r.block.includes(",")?d=r.block.split(",").map(m=>m.trim()).filter(m=>m):d=r.block);let h={src:l,blocks:d,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:o||""};return s.push(h),`${o}__IMPORT_${s.length-1}__`}),imports:s}}static processImportBlocks(e,t,s=0,n){if(s>10)return"";let{processed:i,imports:o}=this._processImportBlocks(e),a=i;for(let r=0;r<o.length;r++){let c=o[r],l=`${c.src}|${c.base}|${c.lang||""}|${c.section}|${Array.isArray(c.blocks)?c.blocks.join(","):c.blocks||""}`,d;if(n&&n.has(l))d=n.get(l);else{let m=t(c.src);d=m?this._extractBlock(m,c.blocks,c.base,c.section,c.lang):"",d&&d.includes("<import")&&(d=this.processImportBlocks(d,t,s+1,n)),n&&n.set(l,d)}let h=d.split(`
|
|
6
|
+
`).map((m,p)=>p===0?m:c.indent+m).join(`
|
|
7
|
+
`);a=a.replace(`__IMPORT_${r}__`,h)}return a}static validateBlockNames(e){let t=[],s=new Set(g.ALLOWED_BLOCKS.map(o=>o.replace(/^<\/?/,"").replace(/\s.*?>$/,"").replace(/\/?>$/,"").toLowerCase())),n=new Set(["b","i","u","s","code","pre","a","blockquote"]),i=/<\/?\s*([a-z][\w-]*)(?:\s[^<>]*)?\/?\s*>/gi;for(let o of e.matchAll(i)){let a=o[1]?.toLowerCase();if(!a||n.has(a)||s.has(a))continue;let r=(e.slice(0,o.index).match(/\n/g)||[]).length+1;t.push({line:r,message:`Unsupported template block: <${a}>`})}return{valid:t.length===0,errors:t}}static validateScopes(e){let t=[],s=new Set(g.ALLOWED_SCOPE),n=/\{([^\s{}\w])([\s\S]*?)\1\}/g;for(let i of e.matchAll(n)){let o=`{${i[1]}${i[1]}}`;if(i[1]&&s.has(o))continue;let a=(e.slice(0,i.index).match(/\n/g)||[]).length+1,r=i[1]??"?";t.push({line:a,message:`Unsupported template scope: {${r} ${r}}`})}return{valid:t.length===0,errors:t}}static validateBlockPositions(e){let t=[],s=[],n=new Set(["b","i","u","s","code","pre","a","blockquote"]),i={base:new Set(["__root__"]),message:new Set(["base"]),keyboard:new Set(["base"]),media:new Set(["base"]),description:new Set(["base"]),switch:new Set(["message","keyboard","media","description"]),case:new Set(["switch"]),default:new Set(["switch"]),map:new Set(["message","keyboard","media","description"]),div:new Set(["base","message","description","keyboard","case","default","map"]),script:new Set(["base","message","description","keyboard","case","default","map","div"]),import:new Set(["base"]),space:new Set(["base","message","description","keyboard","case","default","switch","map","div"])},o=/<(\/?)(\w[\w-]*)([^>]*)>/g,a;for(;(a=o.exec(e))!==null;){let r=a[0],c=a[1],l=a[2].toLowerCase(),d=c==="/",h=!d&&r.endsWith("/>");if(n.has(l)||!i[l])continue;let m=(e.slice(0,a.index).match(/\n/g)||[]).length+1;if(d)if(s.length===0)t.push({line:m,message:`Unexpected closing tag </${l}>: no matching opening tag`});else{let p=s[s.length-1];p.block!==l?t.push({line:m,message:`Mismatched closing tag: expected </${p.block}> but found </${l}>`}):s.pop()}else if(h){let p=s.length>0?s[s.length-1].block:"__root__";i[l].has(p)||t.push({line:m,message:`Block <${l}> is not allowed inside <${p}>`})}else{let p=s.length>0?s[s.length-1].block:"__root__";i[l].has(p)||t.push({line:m,message:`Block <${l}> is not allowed inside <${p}>`}),s.push({block:l,line:m})}}for(let r of s)t.push({line:r.line,message:`Unclosed block <${r.block}>: missing closing tag </${r.block}>`});if(t.length===0){let r=[],c=/<base\b[^>]*>[\s\S]*?<\/base>/g,l;for(;(l=c.exec(e))!==null;)r.push({start:l.index,end:l.index+l[0].length});if(r.length===0&&e.trim())t.push({line:1,message:"Missing <base> block: template content must be wrapped in <base>...</base>"});else{let d=0;for(let h of r){if(h.start>d&&e.slice(d,h.start).trim()){let p=(e.slice(0,d).match(/\n/g)||[]).length+1;t.push({line:p,message:"Content found outside <base> block: move content inside a <base>...</base>"});break}d=h.end}if(t.length===0&&d<e.length&&e.slice(d).trim()){let h=(e.slice(0,d).match(/\n/g)||[]).length+1;t.push({line:h,message:"Content found outside <base> block: move content inside a <base>...</base>"})}}}return{valid:t.length===0,errors:t}}static validateBlockFormat(e){let t=[],s=new Set(["space","import"]),n=new Set(["base","message","keyboard","media","description","script","switch","case","default","map","div"]),i=/<(\/?)(\w[\w-]*)([^>]*)>/g,o;for(;(o=i.exec(e))!==null;){let a=o[0],r=o[1],c=o[2].toLowerCase(),l=r==="/",d=!l&&a.endsWith("/>");if(l)continue;let h=(e.slice(0,o.index).match(/\n/g)||[]).length+1;d?n.has(c)&&t.push({line:h,message:`Block <${c}> must not be self-closing: use <${c}>...</${c}> instead`}):s.has(c)&&t.push({line:h,message:`Block <${c}> must be self-closing: use <${c} /> instead`})}return{valid:t.length===0,errors:t}}static validateTemplate(e){let t=this.validateBlockNames(e),s=this.validateScopes(e),n=this.validateBlockFormat(e),i=this.validateBlockPositions(e),o=[...t.errors,...s.errors,...n.errors,...i.errors];return{valid:o.length===0,errors:o}}};var L=class{static{u(this,"TemplateManager")}_map=new Map;_engine=A;_watcher=[];_pageManager=M;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(e){let{path:t,enableWatch:s=!1}=e;this._path=t,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(e.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let e=0;e<this._path.length;e++){let t=this._path[e];if(!(0,b.existsSync)(t))throw new Error(`Template base path is not exists: ${t}`);if(!(0,b.statSync)(t).isDirectory())throw new Error(`Template base path is not a directory: ${t}`)}return!0}catch(e){throw new Error(`Failed to validate Template base path: ${String(e)}`)}}_initializeWatcher(e){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let t=0;t<this._path.length;t++){let s=this._path[t],n=(0,le.watch)(s,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...e});this._watcher[t]=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(e){let t=(0,w.basename)(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileAdd(e){let t=(0,w.basename)(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileDelete(e){let t=(0,w.basename)(e),s=this._getKey(t);this._map.has(s)&&this._map.delete(s)}_handleWatchError(e){}_loadAllFiles(){let e=new Map,t=new Map,s=[];for(let i=0;i<this._path.length;i++){let o=this._path[i],r=(0,b.readdirSync)(o,"utf8").filter(c=>this._isValidFile(c));for(let c of r){let l=(0,w.join)(o,c),d=this._getExtension(c),h=this._getKey(c);if(d===".html")e.set(h,(0,b.readFileSync)(l,"utf8")),t.set(h,c);else if(d===".ts"||d===".js"){let m=M.getFileSync(l);m?.template!==void 0&&(e.set(h,m.template),t.set(h,c),s.push(m))}}}let n=new Map;for(let[i,o]of e.entries())this._compile(i,o,void 0,n,e,t.get(i));e.clear(),n.clear();for(let i of s)i.template=void 0}_loadFile(e){for(let t=0;t<this._path.length;t++){let s=this._path[t],n=(0,w.join)(s,e),i=this._getExtension(e),o=this._getKey(e);if(i==".html"){let a=(0,b.readFileSync)(n,"utf8");this._compile(o,a,void 0,void 0,void 0,e)}else if(i==".ts"||i==".js"){let a=M.getFileSync(n);a?.template!==void 0&&(this._compile(o,a.template,void 0,void 0,void 0,e),a.template=void 0)}else throw new Error(`File ${e} is not support`)}}_getExtension(e){return(0,w.extname)(e).toLowerCase()}_readTemplateFile(e){for(let t of this._path){let s=(0,w.extname)(e).toLowerCase();if(s){let a=(0,w.join)(t,e);if((0,b.existsSync)(a)&&(0,b.statSync)(a).isFile()){if(s===".html")return(0,b.readFileSync)(a,"utf8");if(s===".ts"||s===".js")try{return M.getFileSync(a)?.template??null}catch{return null}}continue}let n=(0,w.join)(t,`${e}.ts`),i=(0,w.join)(t,`${e}.js`);if((0,b.existsSync)(n)&&(0,b.statSync)(n).isFile())try{return M.getFileSync(n)?.template??null}catch{}else if((0,b.existsSync)(i)&&(0,b.statSync)(i).isFile())try{return M.getFileSync(n)?.template??null}catch{}let o=(0,w.join)(t,`${e}.html`);if((0,b.existsSync)(o)&&(0,b.statSync)(o).isFile())return(0,b.readFileSync)(o,"utf8")}return null}_isValidFile(e){return this._supportedExtensions.has(this._getExtension(e))}_getBaseAtLine(e,t){let s=/<base\b([^>]*?)>/gi,n=/<\/base>/gi,i=t,o,a;for(;(o=s.exec(e))!==null&&!((e.slice(0,o.index).match(/\n/g)||[]).length+1>i);){let l=o[1].match(/\sid\s*=\s*(["']?)([^"'\s>]+)\1/i),d=l?.[2]??null,h=!!l;for(n.lastIndex||(n.lastIndex=s.lastIndex);(a=n.exec(e))!==null;){if((e.slice(0,a.index).match(/\n/g)||[]).length+1>i)return{baseId:d,hasId:h};s.lastIndex=n.lastIndex;break}}return null}_validateTemplate(e,t,s=e){let n=A.validateTemplate(t);if(!n.valid&&n.errors.length>0){let i=n.errors[0],o=this._getBaseAtLine(t,i.line),a=o?.hasId?` on base "${o.baseId}"`:"",r=`${s}, line ${i.line}`;throw new Error(`Template${a} (${r}): ${i.message}`)}}_getKey(e){return e.replace(/\.[^/.]+$/,"")}_compile(e,t,s,n,i,o=e){let a=this._map.get(e),r=a||{},c=!1;this._validateTemplate(e,t,o);let l=A.processImportBlocks(t,h=>i&&i.has(h)?i.get(h):this._readTemplateFile(h),0,n);this._validateTemplate(e,l,o);let d=A._processBaseBlocks(l);(s===void 0||s?.media===!1||a?.media===void 0)&&(r.media=A.compileBlockMedia(l,d),c=!0),(s===void 0||s?.message===!1||a?.message===void 0)&&(r.message=A.compileBlockMessage(l,d),c=!0),(s===void 0||s?.keyboard===!1||a?.keyboard===void 0)&&(r.keyboard=A.compileBlockKeyboards(l,d),c=!0),(s===void 0||s?.description===!1||a?.description===void 0)&&(r.description=A.compileBlockDescription(l,d),c=!0),c&&this._map.set(e,r)}getMedia(e,t="default",s="default",n){let o=this._map.get(e)?.media?.[t],a=o?.[s]||o?.default;try{if(!a)throw new Error("Media function not found, please check your template");return a(n)}catch{return{}}}getMessage(e,t="default",s="default",n){try{let o=this._map.get(e)?.message?.[t],a=o?.[s]||o?.default;if(!a)throw"";return a(n)}catch{return""}}getDescription(e,t="default",s="default",n="default",i){try{let a=this._map.get(e)?.description?.[t]?.[n],r=a?.[s]||a?.default;if(!r)throw"";return r(i)}catch{return""}}getDescriptionLanguage(e,t="default",s="default"){try{let i=this._map.get(e)?.description?.[t]?.[s];return i?Object.keys(i):[]}catch{return[]}}getDescriptionScopes(e,t="default"){try{let n=this._map.get(e)?.description?.[t];return n?Object.keys(n):[]}catch{return[]}}getKeyboard(e,t="default",s="default",n="inline",i){try{let a=this._map.get(e)?.keyboard?.[t],r=a?.[s]?.[n]||a?.default?.[n];if(!r)throw[];return r(i)}catch{return[]}}async write(e,t){if(this._getExtension(e)!=".html")return null;for(let s=0;s<this._path.length;s++){let n=(0,w.join)(this._path[s],e);if((0,b.existsSync)(n))return(0,b.writeFileSync)(n,t,"utf8"),this._loadFile(e),!0}return null}has(e){return this._map.has(e)}async destroy(){if(this._watcher)for(let e of this._watcher)await e.close();this._map.clear()}};var q=require("grammy");var K=class{constructor(e){this.maxSize=e;if(!Number.isFinite(e)||e<=0)throw new Error("WebhookQueue maxSize must be a positive number")}maxSize;static{u(this,"WebhookQueue")}queue=[];waitEnqueue=[];waitDequeue=[];getStats(){return{length:this.queue.length,maxSize:this.maxSize,waitingEnqueue:this.waitEnqueue.length,waitingDequeue:this.waitDequeue.length}}get length(){return this.queue.length}async enqueue(e){if(this.queue.length>=this.maxSize&&await new Promise(t=>this.waitEnqueue.push(t)),this.waitDequeue.length>0){this.waitDequeue.shift()(e);return}this.queue.push(e)}async dequeue(){if(this.queue.length>0){let e=this.queue.shift();return this.waitEnqueue.shift()?.(),e}return await new Promise(e=>this.waitDequeue.push(e))}};var Ie=(0,v.dirname)((()=>{try{return __filename}catch{return(0,me.fileURLToPath)(f)}})()),xe=JSON.parse((0,he.readFileSync)((0,v.join)(Ie,"../../package.json"),"utf-8")).version,z=class{static{u(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;optionsPage={shortCallbackData:!1};log;bot;botConfig;webhookQueue;webhookQueueInstance;webhookServer;handlerBotUpdate;deployType;constructor(e){if(!e?.token||e?.token?.length==0)throw new Error("Token is not valid or empty");if(typeof e.optionsPage?.shortCallbackData=="boolean"&&(this.optionsPage.shortCallbackData=e.optionsPage.shortCallbackData),this.log=e.log===!0?$:e.log?e.log:void 0,this.log?.info?.(`Gramstax v${xe}`),this.cacheSession=e.cacheSession||new V("memory"),this.cacheKeyboard=e.cacheKeyboard||new Map,this.botConfig=e.botConfig,this.webhookQueue=e.webhookQueue,this.templateManager=e.templateManager||new L({path:[(0,v.join)(process.cwd(),"src","pages")]}),this.bot=this.createBot(e.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.stop()),process.once("SIGTERM",()=>this.stop()),this.hookBeforeStart(),e.deploy.startsWith("polling"))this.deployType="polling",this._runPolling();else if(e.deploy.startsWith("webhook:"))this.deployType="webhook",this._runWebhook(e.deploy.split("webhook:")[1]);else if(e.deploy.startsWith("serverless:"))this.deployType="serverless",this._runServerless(e.deploy.split("serverless:")[1]);else if(e.deploy.startsWith("test"))this.deployType="test";else throw new Error("Params deploy is not valid, expected: polling, webhook:<public-url>, serverless:<your-adapter>")}async stop(){await this.bot.stop(),this.deployType==="webhook"&&(await this.webhookServer?.stop(),this.webhookServer=void 0)}_onCatch(e){if(this.log?.errorMake)this.log?.errorMake(e,"Bot","catch");else{let t=JSON.stringify(e,null,2);this.log?.error?.(`[Bot.catch]: ${t}`)}}hookBeforeStart(){}hookAfterStart(){}async _onStart(e,t,s){await this.executeSyncBlocksDescription(this.pages);let{username:n}=e;this.log?.success?.(`Telegram bot deploy ${t} started: ${n} ${t=="webhook"||t=="serverless"?`(${s})`:""}`),this.hookAfterStart()}createBot(e){return new q.Bot(e,this.botConfig)}createCtx(e){return new E({ct:e,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{isAnswer:!1,session:{},data:{}}})}_runPolling(){this.bot.start({drop_pending_updates:!0,onStart:u(e=>{this._onStart(e,"polling",null)},"onStart")})}async _runWebhook(e){let{serve:t}=await import("bun"),s=(0,q.webhookCallback)(this.bot,"bun"),n=this.webhookQueue,i=n?.enabled===!0;this.handlerBotUpdate=i?this.bot.handleUpdate.bind(this.bot):s;let o=i?new K(n?.maxQueueSize??5e3):void 0,a=n?.workerCount??8,r=n?.perChatConcurrency??1,c=n?.blockWhenFull!==!1,l=new Map,d=new Map;this.webhookQueueInstance=o;let h=u(y=>y?.message?.chat?.id??y?.edited_message?.chat?.id??y?.channel_post?.chat?.id??y?.edited_channel_post?.chat?.id??y?.callback_query?.message?.chat?.id??y?.callback_query?.from?.id??y?.inline_query?.from?.id??y?.chosen_inline_result?.from?.id,"getChatId"),m=u(async y=>{if(!i||r<=0||y===void 0||y===null)return()=>{};let T=String(y),k=l.get(T)||0;if(k<r)return l.set(T,k+1),()=>this._releaseWebhookChat(T,l,d);await new Promise(ye=>{let ne=d.get(T)||[];ne.push(ye),d.set(T,ne)});let ge=(l.get(T)||0)+1;return l.set(T,ge),()=>this._releaseWebhookChat(T,l,d)},"acquireChat");if(i&&o){await this.bot.init();for(let y=0;y<a;y++)this._startWebhookWorker(o,m,h)}let p=new URL(e),_=p.pathname,C=parseInt(p.port)||3e3,I=this.log,S="/stats_queue";this.webhookServer?.stop();let x=t({port:C,async fetch(y){let{pathname:T}=new URL(y.url);if(y.method=="POST"&&T==_){if(!i||!o)return s(y);if(!c&&o.length>=(n?.maxQueueSize??5e3))return new Response("Queue full",{status:429});try{let k=await y.json();return await o.enqueue(k),new Response("OK",{status:200})}catch(k){return I?.error?.(`Webhook queue error: ${String(k)}`),new Response("Bad Request",{status:400})}}if(y.method=="GET"&&T==S){let k=o?.getStats()||{length:0,maxSize:n?.maxQueueSize??5e3,waitingEnqueue:0,waitingDequeue:0};return new Response(JSON.stringify({enabled:i,path:S,timestamp:new Date().toISOString(),maxQueueSize:n?.maxQueueSize??5e3,workerCount:a,perChatConcurrency:r,blockWhenFull:c,queue:k,activeChats:l.size}),{status:200,headers:{"Content-Type":"application/json"}})}if(y.method=="GET"&&T=="/"){let k=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:k}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}});this.webhookServer=x,(await this.bot.api.getWebhookInfo()).url!=e&&await this.bot.api.setWebhook(e);let B=await this.bot.api.getMe();await this._onStart(B,"webhook",e)}_startWebhookWorker(e,t,s){u(async()=>{for(;;){let i=await e.dequeue(),o=await t(s(i));try{await this.bot.handleUpdate(i)}catch(a){this.log?.error?.(`Webhook worker error: ${String(a)}`)}finally{o()}}},"run")()}_releaseWebhookChat(e,t,s){let n=t.get(e)||0,i=Math.max(0,n-1);i===0?t.delete(e):t.set(e,i);let o=s.get(e);o&&o.length>0&&(o.shift()(),o.length===0&&s.delete(e))}getWebhookQueueStats(){if(!this.webhookQueue?.enabled||!this.webhookQueueInstance)return null;let e=this.webhookQueueInstance.getStats(),t=this.webhookQueue.maxQueueSize??5e3,s=this.webhookQueue.workerCount??8,n=this.webhookQueue.perChatConcurrency??1,i=this.webhookQueue.blockWhenFull!==!1;return{enabled:!0,maxQueueSize:t,workerCount:s,perChatConcurrency:n,blockWhenFull:i,...e}}async _runServerless(e){this.handlerBotUpdate=(0,q.webhookCallback)(this.bot,e);let t=await this.bot.api.getMe();await this._onStart(t,"serverless",e)}_pageBuildData(e,t){e?.data===void 0&&(e.data=e.buildData());let{name:s}=(0,v.parse)(t);e.data.name||(e.data.name=s),e.data.intentText||(e.data.intentText=e.data.name),e.data.intentCommandText||(e.data.intentCommandText=e.data.name),e.data.intentCallbackData||(e.data.intentCallbackData=e.data.name)}_pageSorts(e,t,s){let n=e.data.name,i=e.prototype,o="handle",a="Args",r="Command",c="Caption",l="Free",d=t.routeDynamic,h=t.routeDynamicSpesific;t.all[n]=e;for(let m=0;m<t.lenListRouteStaticSession;m++){let p=t.listRouteStaticSession[m];if(typeof i[p]!="function")continue;let _=t.routeStatic[p],C=t.routeStaticIntent[p],I=t.routeStaticSession[p],S={name:n,routeName:p},x=_||C;if(x!==void 0){let F=p.includes(r),B=p.endsWith("CallbackData"),y=p.endsWith("Text"),T;if(F){let k=e.data.intentCommandText;T=k?`/${k}`:void 0}else if(B){let k=e.data.intentCallbackData;this.optionsPage.shortCallbackData===!0&&(k=String(s),e.data.intentCallbackData=k),T=k}else y?T=e.data.intentText:T=e.data.name;T&&(x[T]=S)}if(I!==void 0){let B=`methodSession${p.replace("handle","")}`,y=i[B]?.(n);I[y]=S}if(p.startsWith("handleFree")){let F=p.replace(o,"").replace(a,"").replace(r,"").replace(c,"").replace(l,"").toLowerCase();h[F].push(S)}}i.handleFree&&d.push(n)}async executeSyncBlocksDescription(e){let t=new Map,s=e.routeStatic.handleCommandText;for(let[,n]of Object.entries(s)){let i=n.name,o=this.templateManager.getDescriptionScopes(i);for(let a of o){t.has(a)||t.set(a,new Set);let r=this.templateManager.getDescriptionLanguage(i,"default",a);for(let c of r)t.get(a).add(c)}}for(let[n,i]of t)for(let o of i){let a=[];for(let[,l]of Object.entries(s)){let d=l.name,h=this.templateManager.getDescription(d,"default",o,n);h&&a.push({command:d,description:h})}if(a.length===0)continue;let r={type:n},c=o==="default"?void 0:o;try{let l=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(l.map(m=>({command:m.command,description:m.description})).sort((m,p)=>m.command.localeCompare(p.command))),h=JSON.stringify(a.sort((m,p)=>m.command.localeCompare(p.command)));d!==h&&(await this.bot.api.setMyCommands(a,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${n},${c?` lang: ${c},`:""} total (${a.length})`))}catch(l){this.log?.error?.(`Failed to sync descriptions for scope: ${n},${c?` lang: ${c},`:""} error: ${String(l)}`)}}}_pageLoads(){this.log?.info?.("Load pages..");let e=["handleCallbackData","handleText","handleCommandText","handleCaptionPhoto","handleCommandCaptionPhoto","handleCaptionVideo","handleCommandCaptionVideo","handleCaptionAudio","handleCommandCaptionAudio","handleCaptionDocument","handleCommandCaptionDocument","handleCaptionAnimation","handleCommandCaptionAnimation","handleCaptionVoice","handleCommandCaptionVoice"],t=["handleArgsCallbackData","handleArgsText","handleCommandArgsText","handleCaptionArgsPhoto","handleCommandCaptionArgsPhoto","handleCaptionArgsVideo","handleCommandCaptionArgsVideo","handleCaptionArgsAudio","handleCommandCaptionArgsAudio","handleCaptionArgsDocument","handleCommandCaptionArgsDocument","handleCaptionArgsAnimation","handleCommandCaptionArgsAnimation","handleCaptionArgsVoice","handleCommandCaptionArgsAnimation"],s=[...e,...t,"handleFreeText","handleFreePhoto","handleFreeVideo","handleFreeAudio","handleFreeDocument","handleFreeAnimation","handleFreeVoice","handleFreeVideoNote","handleFreeSticker","handleFreeLocation","handleFreeContact"],n=u((a,r)=>Object.fromEntries(a.map(c=>[c,r()])),"makeObject"),i=u(()=>[],"initDynamicSpesific"),o={all:{},routeDynamic:[],routeDynamicSpesific:{text:i(),photo:i(),video:i(),audio:i(),document:i(),animation:i(),voice:i(),videonote:i(),sticker:i(),location:i(),contact:i()},routeStatic:n(e,()=>({})),routeStaticIntent:n(t,()=>({})),routeStaticSession:n(s,()=>({})),listRouteStatic:e,listRouteStaticIntent:t,listRouteStaticSession:s,lenListRouteStatic:e.length,lenListRouteStaticIntent:t.length,lenListRouteStaticSession:s.length};return M.getFileManySync(void 0).forEach(({path:a,page:r},c)=>{this._pageBuildData(r,a),this._pageSorts(r,o,c),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(o.all).length})`),o}async _pageRoutes(e,t){let s,n;if(s===void 0){let o=await e.getSession();if(o){let a=o.method,r=this.pages.routeStaticSession,c=e.callbackData,l=e.msgText,d=e.msgCaption,h=c||l||d,m=t==="callbackdata",p=m?"colon":"space",_=h&&e.haveArgs(h,p)?e.getIntent(h,p,1):void 0,C=!m&&h?e.getIntent(h,"space",2):void 0;for(let I=0;I<this.pages.lenListRouteStaticSession;I++){let S=this.pages.listRouteStaticSession[I];if(S.toLowerCase().endsWith(t)){if(h){if(this.pages.routeStatic[S]?.[h])continue;let x=this.pages.routeStaticIntent[S];if(x&&(_&&x[_]||C&&x[C]))continue}n=r[S][a]}if(n)break}n!==void 0&&(s=this.pages.all[n.name])}}if(s===void 0){let o=e.callbackData,a=e.msgText,r=e.msgCaption,c=this.pages.routeStatic;for(let l=0;l<this.pages.lenListRouteStatic;l++){let d=this.pages.listRouteStatic[l];if(d.toLowerCase().endsWith(t)&&(n=c[d][o||a||r]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s===void 0){let o=this.pages.routeStaticIntent,a=t==="callbackdata",r=a?"colon":"space",c=a?e.callbackData:e.msgText||e.msgCaption,l=e.haveArgs(c,r);if(c&&l)for(let d=0;d<this.pages.lenListRouteStaticIntent;d++){let h=this.pages.listRouteStaticIntent[d];if(!h.toLowerCase().endsWith(t))continue;let m=o[h];if(n=m[e.getIntent(c,r,1)],!n&&!a&&(n=m[e.getIntent(c,"space",2)]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s!==void 0&&n!==void 0){if(!s.prototype[n.routeName])return;let a=await new s(e)[n.routeName]?.();return e.temp.isAnswer===!0?a:null}let i=this.pages.routeDynamicSpesific[t]||[];for(let o=0;o<i.length;o++){let a=i[o];if(a===void 0)continue;let r=this.pages.all[a.name];r!==void 0&&typeof r.prototype[a.routeName]=="function"&&await new r(e)[a.routeName]()}for(let o=0;o<this.pages.routeDynamic.length;o++){let a=this.pages.routeDynamic[o];if(a===void 0)continue;let r=this.pages.all[a];r!==void 0&&typeof r.prototype.handleFree=="function"&&await new r(e).handleFree()}if(e.temp.isAnswer===!1)return null}async hookBeforeRoute(e,t){return!!(e||t)}async hookErrorPage(e,t,s,n){}async hookErrorInputNotFoundPage(e){}async _onMessage(e,t){let s=this.createCtx(e);try{if(await this.hookBeforeRoute(s,t)===!1)return;await this._pageRoutes(s,t)===null&&await this.hookErrorInputNotFoundPage(s)}catch(n){await this.hookErrorPage(s,t,n,!1)}}async _onCallbackQueryData(e){let t=this.createCtx(e);try{if(await this.hookBeforeRoute(t,"onCallbackQueryData")===!1)return;await this._pageRoutes(t,"callbackdata")}catch(s){await this.hookErrorPage(t,"onCallbackQueryData",s,!0)}}async _onMessageText(e){await this._onMessage(e,"text")}async _onMessagePhoto(e){await this._onMessage(e,"photo")}async _onMessageVideo(e){await this._onMessage(e,"video")}async _onMessageAudio(e){await this._onMessage(e,"audio")}async _onMessageDocument(e){await this._onMessage(e,"document")}async _onMessageAnimation(e){await this._onMessage(e,"animation")}async _onMessageVoice(e){await this._onMessage(e,"voice")}async _onMessageVideoNote(e){await this._onMessage(e,"videonote")}async _onMessageSticker(e){await this._onMessage(e,"sticker")}async _onMessageLocation(e){await this._onMessage(e,"location")}async _onMessageContact(e){await this._onMessage(e,"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{u(this,"BlockKeyboard")}static label;static _build(e,t,s,n){if(!this.label)throw new Error("Label not found, make sure set this.label from class extends LabelKeyboard");s||(s="inline");let i=this.label[e];if(!i)throw new Error(`Object value ${e} not found`);let o=u((a,r)=>`<keyboard type="${s}" lang="${r}">${n?this.label._reverse(a):a}</keyboard>`,"pro");return t?o(i[t],t):Object.keys(i).map(a=>o(i[a],a)).join(" ")}};var Y=class{static{u(this,"LabelKeyboard")}static _reverse(e){return e.split(/(?<!\\), */).reverse().join(", ")}static _reverseObj(e){return Object.keys(e).reduce((t,s)=>(t[s]=this._reverse(e[s]),t),{})}};var H=require("worker_threads");var R=class{constructor(e,t){this.send=e;this.register=t}send;register;static{u(this,"WorkerThreadRpc")}map=new Map;async make(e){let t=this.map,s=this.send,{id:n,method:i,params:o,result:a,error:r}=e;if(i!==void 0)try{let c=this.register[i];if(typeof c!="function")throw new Error(`Method ${i} not found or not function`);let l=await c.apply(this.register,o);s({id:n,result:l})}catch(c){s({id:n,error:c instanceof Error?{message:c.message,stack:c.stack,name:c.name}:c})}else if(a!==void 0){let c=t.get(n);c&&(c.resolve(a),t.delete(n))}else if(r!==void 0){let c=t.get(n);c&&(c.reject(r),t.delete(n))}}makeId(){return Math.random()}makeRequest(e,t,s=!0,n){let i=this.makeId(),o={id:i,method:e,params:t,...n};return s?new Promise((a,r)=>{this.map.set(i,{resolve:a,reject:r}),this.send(o)}):this.send(o)}};var U=class{constructor(e,t,s){this.path=e;this.argv=t;this.register=s;this.init(),s||(s=this),this.rpc=new R(this.send.bind(this),s)}path;argv;register;static{u(this,"WorkerThreadLaunch")}static isMainThread=H.isMainThread;_readyResolve;_readyPromise=new Promise(e=>this._readyResolve=e);pid=process.pid;thread={};threadId={};rpc={};ready(){return this._readyPromise}readyResolve(){this._readyResolve?.()}init(){this.thread=new H.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",e=>this.handleOnMessage(e)),this.thread.on("exit",()=>this.kill()),process.once("SIGINT",()=>this.kill()),process.once("SIGTERM",()=>this.kill())}async handleOnMessage(e){this.rpc.make(e)}kill(){this.thread.terminate()}send(e){this.thread.postMessage(e)}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};var Z=class g{static{u(this,"WorkerThreadExport")}static launchGatewayClient(e){let t=new Proxy({},{get(n,i){if(!(typeof i!="string"||i==="then"))return async(o,...a)=>{let r=o.gatewayClients.get(e);return r||(r=await o.createGatewayClient(e)),r.request(i,a)}}}),s=u(function(n){return new Proxy({},{get(i,o){if(!(typeof o!="string"||o==="then"))return async(...a)=>{let r=n.gatewayClients.get(e);return r||(r=await n.createGatewayClient(e)),r.request(o,a)}}})},"ctor");return Object.setPrototypeOf(s,t),s}static init(e){let{WTInit:t,WTLaunch:s=U,path:n,wrap:i}=e,o=`for-${n}`;if(process.argv[2]===o)return new t,{launchGatewayClient:u(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};let a,r=new Proxy({},{get(d,h){if(h!=="then")return h==="sendRequest"||h==="request"||h==="kill"||h==="send"?(...m)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a[h](...m)}:(...m)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a.request(h,m)}}}),l={...i?i(r):{},launchWorker:u(async(d=[])=>(a=new s(n,[o,...d]),await a.ready(),a),"launchWorker"),launchGatewayClient:u(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};return new Proxy(l,{get(d,h){if(h!=="then")return h==="launchGatewayClient"?d.launchGatewayClient:h==="launchWorker"?d.launchWorker:h in d?d[h]:typeof h=="string"?(...m)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a.request(h,m)}:d[h]}})}};var pe=require("net-ipc");var N=class{static{u(this,"WorkerThreadGatewayClient")}client=new pe.Client;rpc;constructor(){this.rpc=new R(e=>this.client.send(e),{}),this.client.on("message",e=>{this.rpc.make(e)})}async connect(e){this.client.options.path=e;let t=new Promise(s=>{this.client.once("ready",()=>s(this))});return await this.client.connect(),t}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};var ue=require("net-ipc");var j=class{static{u(this,"WorkerThreadGatewayServer")}server=new ue.Server;rpc=new Map;register={};constructor(){this.server.on("connect",e=>{let t=new R(s=>e.send(s),this.register);this.rpc.set(e.id,t)}),this.server.on("disconnect",e=>{this.rpc.delete(e.id)}),this.server.on("message",(e,t)=>{let s=this.rpc.get(t.id);s&&s.make(e)}),this.server.on("error",e=>{console.error(e)})}async start(e,t={}){this.register=t,this.server.options.path=e;let s=new Promise(n=>{this.server.once("ready",()=>n(this))});return await this.server.start(),s}};var O=require("worker_threads");var ee=class{static{u(this,"WorkerThreadInit")}argv=process.argv;id=O.threadId;pid=process.pid;rpc={};parentPort=O.parentPort;gatewayServer;gatewayClients=new Map;gatewayClientLatest;static gatewayServerPath;gatewayServerPath=this.constructor.gatewayServerPath;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=O.isMainThread;constructor(){this.init(),this.rpc=new R(this.send.bind(this),this),this.send({method:"readyResolve"})}init(){this.parentPort?.on("message",e=>this.handleOnMessage(e))}handleOnMessage(e){this.rpc.make(e)}send(e){this.parentPort?.postMessage(e)}request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}async createGatewayServer(e,t){return e||(e=this),t||(t=this.constructor.gatewayServerPath),this.gatewayServer=new j,await this.gatewayServer.start(t,e),this.constructor.gatewayServerPath=t,!0}async createGatewayClient(e){let t=new N;return await t.connect(e),this.gatewayClients.set(e,t),this.gatewayClientLatest=t,t}};var te=class{static{u(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(e){this.addMany(e)}add(e){this.thread.set(e.threadId,e),this.threadCount+=1}addMany(e){e.forEach(t=>this.add(t))}getInstance(e){return this.thread.get(e)}kill(e){let t=this.thread.get(e);return t?.kill(),this.thread.delete(e),this.threadCount-=1,t?.threadId}killAll(){this.thread.values().forEach(({threadId:e})=>this.kill(e))}async broadcastRequest(e,t){return await Promise.all(Object.values(this.thread).map(s=>s.request(e,t,!0)))}async request(e,t,s,n=!0,i){return await this.thread.get(e)?.request(t,s,n,i)}};var se=class{static{u(this,"MockTelegramServer")}botToken="";hostname;port;log;handlers;defaultHandler;apiRoot="";webhookUrl="";requests=[];updates=[];server;_nextUpdateId=1;_nextMessageId=1;constructor(e={}){this.hostname=e.hostname??"127.0.0.1",this.port=e.port??0,this.log=e.log===!0?$:e.log?e.log:void 0,this.handlers=e.handlers??{},this.defaultHandler=e.defaultHandler}async start(){if(this.server)return this.apiRoot;let e=Bun.serve({port:this.port,hostname:this.hostname,fetch:u(async t=>this._handleRequest(t),"fetch")});return this.server=e,this.apiRoot=`http://${this.hostname}:${e.port??this.port}`,process.once("SIGINT",()=>this.stop()),process.once("SIGTERM",()=>this.stop()),this.log?.info?.(`Mock Telegram server started: ${this.apiRoot}`),this.apiRoot}async stop(){this.server?.stop(),this.server=void 0,this.log?.info?.("Mock Telegram server stopped")}_json(e){return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":"application/json"}})}lastRequest(e){if(!e)return this.requests[this.requests.length-1];for(let t=this.requests.length-1;t>=0;t--){let s=this.requests[t];if(s?.method===e)return s}}clearRequests(){this.requests.length=0}_defaultResponse(e,t){if(e==="getMe")return{ok:!0,result:{id:123456789,is_bot:!0,first_name:"Mock",username:"mock_gramstax_bot"}};if(e==="getUpdates")return{ok:!0,result:[]};if(e==="getMyCommands")return{ok:!0,result:[]};if(e==="setMyCommands")return{ok:!0,result:!0};if(e==="setWebhook"){let s=this._bodyRecord(t),n=typeof s?.url=="string"?s.url:"";return this.webhookUrl=n,this.log?.info?.(`Mock Telegram webhook set: ${n}`),{ok:!0,result:!0}}return e==="getWebhookInfo"?{ok:!0,result:{url:this.webhookUrl}}:{ok:!0,result:!0}}async _handleRequest(e){let{pathname:t}=new URL(e.url),s=t.match(/^\/bot([^/]+)\/(.+)$/);if(!s)return new Response("Not found",{status:404});let n=s[1],i=s[2];if(!n||!i)return new Response("Not found",{status:404});this.botToken=n;let o=await this._readBody(e.clone());this.log?.debug?.(`Mock Telegram API request: ${i}`),this.requests.push({method:i,body:o,url:e.url,requestMethod:e.method,headers:Object.fromEntries(e.headers.entries())});let a=this.handlers[i]??this.defaultHandler,r=a?await a({method:i,request:e}):this._defaultResponse(i,o);return this._json(r)}_bodyRecord(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}async _readBody(e){if(e.method==="GET"||e.method==="HEAD")return;let t=e.headers.get("content-type")||"";try{if(t.includes("application/json"))return await e.json();if(t.includes("multipart/form-data")||t.includes("application/x-www-form-urlencoded")){let n=await e.formData();return Object.fromEntries(n.entries())}let s=await e.text();if(!s)return;try{return JSON.parse(s)}catch{return s}}catch{return}}_defaultUser(e){return{id:e?.id??1001,is_bot:e?.is_bot??!1,first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.username?{username:e.username}:{},language_code:e?.language_code??"en"}}_defaultChat(e){return{id:e?.id??1001,type:e?.type??"private",first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.username?{username:e.username}:{},...e?.title?{title:e.title}:{}}}_nextIds(e){return{updateId:this._nextUpdateId++,messageId:e?.message_id??this._nextMessageId++,date:e?.date??Math.floor(Date.now()/1e3)}}_buildMessageUpdate(e,t){let{updateId:s,messageId:n,date:i}=this._nextIds(t);return{update_id:s,message:{message_id:n,date:i,chat:this._defaultChat(t?.chat),from:this._defaultUser(t?.user),...e}}}async _postUpdate(e,t){if(await this._waitForWebhookUrl(t?.responseTimeoutMs??1e3),!this.webhookUrl)throw new Error("Webhook URL is not set. Call setWebhook first or assign mockServer.webhookUrl.");let s=this.requests.length;this.updates.push(e),this.log?.info?.(`Mock Telegram update sent: ${this.webhookUrl}`);let n=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`Webhook request failed with status ${n.status}`);let i=await this._waitForResponses(s,t?.responseTimeoutMs??1e3);return this.log?.info?.(`Mock Telegram bot responses captured: ${i.length}`),i}async _waitForWebhookUrl(e){if(this.webhookUrl||e<=0)return this.webhookUrl;let t=Date.now();for(;Date.now()-t<e&&(await new Promise(s=>setTimeout(s,5)),!this.webhookUrl););return this.webhookUrl}async _waitForResponses(e,t){if(t<=0)return this._userResponseRequests(e);if(this._userResponseRequests(e).length>0)return this._userResponseRequests(e);let s=Date.now();for(;Date.now()-s<t&&(await new Promise(n=>setTimeout(n,5)),!(this._userResponseRequests(e).length>0)););return this._userResponseRequests(e)}_userResponseRequests(e){return this.requests.slice(e).filter(t=>this._isUserResponseMethod(t.method))}_isUserResponseMethod(e){return e.startsWith("send")||e.startsWith("edit")||e.startsWith("answer")||e.startsWith("delete")||e.startsWith("copy")||e.startsWith("forward")||e==="pinChatMessage"||e==="unpinChatMessage"||e==="setMessageReaction"}async sendText(e,t){let s=e.startsWith("/")?[{offset:0,length:e.split(" ")[0]?.length??e.length,type:"bot_command"}]:void 0;return await this._postUpdate(this._buildMessageUpdate({text:e,...s?{entities:s}:{}},t),t)}async sendPhoto(e){return await this._postUpdate(this._buildMessageUpdate({photo:[{file_id:"mock-photo-file-id",file_unique_id:"mock-photo-unique-id",width:1,height:1}],...e?.caption?{caption:e.caption}:{}},e),e)}async sendVideo(e){return await this._postUpdate(this._buildMessageUpdate({video:{file_id:"mock-video-file-id",file_unique_id:"mock-video-unique-id",width:1,height:1,duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendAudio(e){return await this._postUpdate(this._buildMessageUpdate({audio:{file_id:"mock-audio-file-id",file_unique_id:"mock-audio-unique-id",duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendDocument(e){return await this._postUpdate(this._buildMessageUpdate({document:{file_id:"mock-document-file-id",file_unique_id:"mock-document-unique-id",file_name:"mock.txt"},...e?.caption?{caption:e.caption}:{}},e),e)}async sendAnimation(e){return await this._postUpdate(this._buildMessageUpdate({animation:{file_id:"mock-animation-file-id",file_unique_id:"mock-animation-unique-id",width:1,height:1,duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendVoice(e){return await this._postUpdate(this._buildMessageUpdate({voice:{file_id:"mock-voice-file-id",file_unique_id:"mock-voice-unique-id",duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendVideoNote(e){return await this._postUpdate(this._buildMessageUpdate({video_note:{file_id:"mock-video-note-file-id",file_unique_id:"mock-video-note-unique-id",length:1,duration:1}},e),e)}async sendSticker(e){return await this._postUpdate(this._buildMessageUpdate({sticker:{file_id:"mock-sticker-file-id",file_unique_id:"mock-sticker-unique-id",type:"regular",width:1,height:1,is_animated:!1,is_video:!1}},e),e)}async sendLocation(e){return await this._postUpdate(this._buildMessageUpdate({location:{latitude:e?.latitude??0,longitude:e?.longitude??0}},e),e)}async sendContact(e){return await this._postUpdate(this._buildMessageUpdate({contact:{phone_number:e?.phone_number??"+10000000000",first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.user_id?{user_id:e.user_id}:{}}},e),e)}async sendCallbackQuery(e,t){let{updateId:s,messageId:n,date:i}=this._nextIds(t);return await this._postUpdate({update_id:s,callback_query:{id:t?.id??`mock-callback-${s}`,from:this._defaultUser(t?.user),message:{message_id:n,date:i,chat:this._defaultChat(t?.chat),text:t?.messageText??"Mock message"},chat_instance:"mock-chat-instance",data:e}},t)}};0&&(module.exports={BlockKeyboard,CacheExternal,Ctx,Gramstax,LabelKeyboard,LoggingHelper,MockTelegramServer,PageManager,TemplateEngine,TemplateManager,WebhookQueue,WorkerThreadExport,WorkerThreadGatewayClient,WorkerThreadGatewayServer,WorkerThreadInit,WorkerThreadLaunch,WorkerThreadPool,WorkerThreadRpc,log});
|
package/dist/src/index.d.cts
CHANGED
|
@@ -199,11 +199,15 @@ declare class TemplateManager {
|
|
|
199
199
|
_getExtension(filename: string): string;
|
|
200
200
|
_readTemplateFile(filename: string): string | null;
|
|
201
201
|
_isValidFile(filename: string): boolean;
|
|
202
|
-
|
|
202
|
+
_getBaseAtLine(template: string, line: number): {
|
|
203
|
+
baseId: string | null;
|
|
204
|
+
hasId: boolean;
|
|
205
|
+
} | null;
|
|
206
|
+
_validateTemplate(baseId: string, template: string, filename?: string): void;
|
|
203
207
|
_getKey(filename: string): string;
|
|
204
208
|
_compile(key: string, template: string, keepIfExist?: Partial<{
|
|
205
209
|
[K in keyof ITCompiledTemplate]: boolean;
|
|
206
|
-
}>, importCache?: Map<string, string>, rawCache?: Map<string, string
|
|
210
|
+
}>, importCache?: Map<string, string>, rawCache?: Map<string, string>, filename?: string): void;
|
|
207
211
|
getMedia(key: string, baseId?: string, language?: string, data?: Record<string, any>): ReturnType<ITCompiledTemplate[`media`][`default`][`default`]>;
|
|
208
212
|
getMessage(key: string, baseId?: string, language?: string, data?: Record<string, any>): string;
|
|
209
213
|
getDescription(key: string, baseId?: string, language?: string, scope?: string, data?: Record<string, any>): string;
|
package/dist/src/index.d.ts
CHANGED
|
@@ -199,11 +199,15 @@ declare class TemplateManager {
|
|
|
199
199
|
_getExtension(filename: string): string;
|
|
200
200
|
_readTemplateFile(filename: string): string | null;
|
|
201
201
|
_isValidFile(filename: string): boolean;
|
|
202
|
-
|
|
202
|
+
_getBaseAtLine(template: string, line: number): {
|
|
203
|
+
baseId: string | null;
|
|
204
|
+
hasId: boolean;
|
|
205
|
+
} | null;
|
|
206
|
+
_validateTemplate(baseId: string, template: string, filename?: string): void;
|
|
203
207
|
_getKey(filename: string): string;
|
|
204
208
|
_compile(key: string, template: string, keepIfExist?: Partial<{
|
|
205
209
|
[K in keyof ITCompiledTemplate]: boolean;
|
|
206
|
-
}>, importCache?: Map<string, string>, rawCache?: Map<string, string
|
|
210
|
+
}>, importCache?: Map<string, string>, rawCache?: Map<string, string>, filename?: string): void;
|
|
207
211
|
getMedia(key: string, baseId?: string, language?: string, data?: Record<string, any>): ReturnType<ITCompiledTemplate[`media`][`default`][`default`]>;
|
|
208
212
|
getMessage(key: string, baseId?: string, language?: string, data?: Record<string, any>): string;
|
|
209
213
|
getDescription(key: string, baseId?: string, language?: string, scope?: string, data?: Record<string, any>): string;
|
package/dist/src/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
var le=Object.defineProperty;var u=(g,e)=>le(g,"name",{value:e,configurable:!0}),U=(g=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(g,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):g)(function(g){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+g+'" is not supported')});import $e from"path";import{fileURLToPath as me}from"url";var pe=u(()=>me(import.meta.url),"getFilename");var f=pe();import{LoggingPretty as ue}from"logging-pretty";var N=class extends ue{static{u(this,"LoggingHelper")}timers=new Map;constructor(e){super(e)}errorMake(e,t,s){this.error(`[${t?`${t}:${s}`:s}] ${this._formatErrorObj(e)}`)}_formatErrorObj(e){return JSON.stringify(e instanceof Error?{message:e.message,stack:e.stack,name:e.name}:e,null,2)}time(e){this.timers.set(e,process.hrtime.bigint())}timeEnd(e,t){let s=this.timers.get(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}let n=(Number(process.hrtime.bigint()-s)/1e6).toFixed(3);this.timers.delete(e),t?this.debug(`${t} (took ${n}ms)`):this.debug(`${e} (took ${n}ms)`)}timeCheck(e){let t=this.timers.get(e);if(t!==void 0)return(Number(process.hrtime.bigint()-t)/1e6).toFixed(3)}timeLog(e,t){let s=this.timeCheck(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}t?this.debug(`${t} (${s}ms)`):this.debug(`${e} (${s}ms)`)}timeClear(){this.timers.clear()}timeActive(){return Array.from(this.timers.keys())}},F=new N;import{Keyv as ge}from"keyv";import ye from"@keyv/redis";var B=class extends ge{constructor(t="memory",s,n,i){let o;t.startsWith("redis")&&(o=new ye(t)),t==="memory"&&(o=new Map),i?.forceStore&&(o=i.forceStore);super({store:o,namespace:n,ttl:s});this.url=t}url;static{u(this,"CacheExternal")}refreshLruCache(t){let s=this.store,n=this.opts.namespace?this.opts.namespace?.length+1:null,i=s.keys().toArray();for(let o=0;o<i.length;o++){let a=i[o];if(o==t)return;this.get(n?a.slice(n):a)}}};import{setTimeout as H}from"timers/promises";import{InlineKeyboard as J,Keyboard as z}from"grammy";var W=class{static{u(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(e){this.ct.from.language_code=e}get msgText(){return this.ct.message?.text}get msgTextArgs(){return this.getArgs(this.msgText,"space",this.data?._positionArgText||this.temp?.data?._positionArgText)}get msgTextArg(){return this.msgTextArgs[0]}get msgTextCommandArgs(){return this.getArgs(this.msgText,"space")}get msgTextCommandArg(){return this.msgTextCommandArgs[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionArg(){return this.msgCaptionArgs[0]}get msgCaptionCommandArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionCommandArg(){return this.msgCaptionCommandArgs[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get msgDocument(){return this.ct.message?.document}get msgAnimation(){return this.ct.message?.animation}get msgVoice(){return this.ct.message?.voice}get msgVideoNote(){return this.ct.message?.video_note}get msgSticker(){return this.ct.message?.sticker}get msgLocation(){return this.ct.message?.location}get msgContact(){return this.ct.message?.contact}get msgWebAppData(){return this.ct.message?.web_app_data}get msgGift(){return this.ct.message?.gift}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataArgs(){return this.getArgs(this.callbackData,"colon")}get callbackDataArg(){return this.callbackDataArgs?.[0]}ct;cacheSession;cacheKeyboard;templateManager;temp;constructor(e){this.ct=e.ct,this.cacheSession=e.cacheSession,this.cacheKeyboard=e.cacheKeyboard,this.templateManager=e.templateManager,this.temp=e.temp}async broadcast(e,t,s,n,i,o,a=!1){let r={successCount:0,failedCount:0,totalCount:0};r.totalCount=e.length;try{this.temp.isAnswer=!0;let c=30,h=t.map(d=>this.templateManager.getMessage(this.data.name,i,d,n));for(let d=0;d<e.length;d++){let m=e[d],l=h[d];await this.ct.api.sendMessage(m,l,{parse_mode:"HTML",reply_markup:s,...o}),r.successCount+=1,d+1==c&&await H(1200)}}catch(c){if(r.failedCount+=1,a)throw{...r,err:c}}return r}async broadcastMedia(e,t,s,n,i,o,a=!1){let r={successCount:0,failedCount:0,totalCount:0};r.totalCount=e.length;try{this.temp.isAnswer=!0;let c=30,h=t.map(d=>this.templateManager.getMedia(this.data.name,i,d,n));for(let d=0;d<e.length;d++){let m=e[d],l=h[d];if(!l)continue;let p={parse_mode:"HTML",reply_markup:s,...o};l.type=="photo"&&await this.ct.api.sendPhoto(m,l.src,{caption:l.caption,...p}),l.type=="video"&&await this.ct.api.sendVideo(m,l.src,{caption:l.caption,...p}),l.type=="audio"&&await this.ct.api.sendAudio(m,l.src,{caption:l.caption,...p}),l.type=="document"&&await this.ct.api.sendDocument(m,l.src,{caption:l.caption,...p}),l.type=="animation"&&await this.ct.api.sendAnimation(m,l.src,{caption:l.caption,...p}),l.type=="voice"&&await this.ct.api.sendVoice(m,l.src,p),l.type=="video_note"&&await this.ct.api.sendVideoNote(m,l.src,p),l.type=="sticker"&&await this.ct.api.sendSticker(m,l.src,p),l.type=="location"&&await this.ct.api.sendLocation(m,parseInt(l.latitude),parseInt(l.longitude),p),l.type=="contact"&&await this.ct.api.sendContact(m,l.phone,l.first_name,{vcard:l.vcard,...p}),r.successCount+=1,d+1==c&&await H(1200)}}catch(c){if(r.failedCount+=1,a)throw{...r,err:c}}return r}async reply(e,t,s,n){this.temp.isAnswer=!0;let i=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.reply(i,{parse_mode:"HTML",reply_markup:e,...n})}async replyMedia(e,t,s,n,i){this.temp.isAnswer=!0;let o=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s),a={parse_mode:"HTML",reply_markup:t,...i};if(e=="photo")return await this.ct.replyWithPhoto(o.src,{caption:o.caption,...a});if(e=="video")return await this.ct.replyWithVideo(o.src,{caption:o.caption,...a});if(e=="audio")return await this.ct.replyWithAudio(o.src,{caption:o.caption,...a});if(e=="document")return await this.ct.replyWithDocument(o.src,{caption:o.caption,...a});if(e=="animation")return await this.ct.replyWithAnimation(o.src,{caption:o.caption,...a});if(e=="voice")return await this.ct.replyWithVoice(o.src,a);if(e=="video_note")return await this.ct.replyWithVideoNote(o.src,a);if(e=="sticker")return await this.ct.replyWithSticker(o.src,a);if(e=="location")return await this.ct.replyWithLocation(parseInt(o.latitude),parseInt(o.longitude),a);if(e=="contact")return await this.ct.replyWithContact(o.phone,o.first_name,{vcard:o.vcard,...a})}async replyPhoto(e,t,s,n){return this.replyMedia("photo",e,t,s,n)}async replyVideo(e,t,s,n){return this.replyMedia("video",e,t,s,n)}async replyAudio(e,t,s,n){return this.replyMedia("audio",e,t,s,n)}async replyDocument(e,t,s,n){return this.replyMedia("document",e,t,s,n)}async replyAnimation(e,t,s,n){return this.replyMedia("animation",e,t,s,n)}async replyVoice(e,t,s,n){return this.replyMedia("voice",e,t,s,n)}async replyVideoNote(e,t,s,n){return this.replyMedia("video_note",e,t,s,n)}async replySticker(e,t,s,n){return this.replyMedia("sticker",e,t,s,n)}async replyLocation(e,t,s,n){return this.replyMedia("location",e,t,s,n)}async replyContact(e,t,s,n){return this.replyMedia("contact",e,t,s,n)}async replyAction(e){return await this.ct.replyWithChatAction(e)}async edit(e,t,s,n,i=!0){try{this.temp.isAnswer=!0;let o=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.editMessageText(o,{parse_mode:"HTML",reply_markup:e,...n})}catch(o){if(i)await this.reply(e,t,s,n);else throw o}}async editMedia(e,t,s,n,i,o,a=!0){try{this.temp.isAnswer=!0;let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s);return e=="voice"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="video_note"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="sticker"?(await this.delete(),await this.replySticker(t,s,n,i)):e=="location"?(await this.delete(),await this.replyLocation(t,s,n,i)):e=="contact"?(await this.delete(),await this.replyContact(t,s,n,i)):await this.ct.editMessageMedia({media:r,caption:c,type:e,parse_mode:"HTML",...i},{reply_markup:t,...o})}catch(r){if(a===!0)await this.reply(t,s,n,o);else throw r}}async editPhoto(e,t,s,n,i){return await this.editMedia("photo",e,t,s,n,i)}async editVideo(e,t,s,n,i){return await this.editMedia("video",e,t,s,n,i)}async editAudio(e,t,s,n,i){return await this.editMedia("audio",e,t,s,n,i)}async editDocument(e,t,s,n,i){return await this.editMedia("document",e,t,s,n,i)}async editAnimation(e,t,s,n,i){return await this.editMedia("animation",e,t,s,n,i)}async editVoice(e,t,s,n){return await this.editMedia("voice",e,t,s,n)}async editVideoNote(e,t,s,n){return await this.editMedia("video_note",e,t,s,n)}async editSticker(e,t,s,n){return await this.editMedia("sticker",e,t,s,n)}async editLocation(e,t,s,n){return await this.editMedia("location",e,t,s,n)}async editContact(e,t,s,n){return await this.editMedia("contact",e,t,s,n)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(e){try{return this.temp.isAnswer=!0,await this.ct.answerCallbackQuery(e)}catch{return null}}async setSession(e,t,s){try{let n={method:e,params:t,...s},i=await this.cacheSession.set(`${this.userId}`,n);return i&&(this.temp.session=n),i}catch{return null}}async getSession(){try{let e=await this.cacheSession.get(`${this.userId}`);return e&&(this.temp.session=e),e||null}catch{return null}}async clearSession(){try{let e=await this.cacheSession.delete(`${this.userId}`);return e&&(this.temp.session={}),e}catch{return null}}static buildData(e){let s=typeof e=="function"?{callbackData:e}:e||{},n=s.callbackData,i=this.prototype.addArgs.bind(this.prototype),o=s.name||"";return{name:o,intentText:s.intentText||o,intentCommandText:s.intentCommandText||o,intentCallbackData:o,callbackData:n?function(...r){return i(this.intentCallbackData,"colon",n(...r))}:function(){return this?.intentCallbackData},_positionArgText:s.intentText?s.intentText.split(this.prototype.getSeperatorTag("space")).length:void 0}}keyboardCols(e,t,s,n){let[i,o]=s.split("-"),a=parseInt(i),r=o?parseInt(o):null,c=t.length,h=e;for(let d=0;d<c;d++){let m=t[d];if(n(m,d),r===null)(d+1)%a===0&&d<c-1&&h.row();else{let l=c-(d+1);(l===r||l>r&&(d+1)%a===0)&&h.row()}}return e}bottomKeyboardT(e="1",t,s){return this.bottomKeyboard((n,i)=>this.keyboardCols(n,i,e,o=>n.text(o)),{baseId:t??void 0,data:s})}inlineKeyboardT(e,t="1",s,n){return this.inlineKeyboard((i,o)=>this.keyboardCols(i,o,t,(a,r)=>{let c=e[r],h=typeof c=="string"?c:c.data.callbackData();i.text(a,h)}),{baseId:s??void 0,data:n})}inlineKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let a=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(a);if(!r){let c=new J,h=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data),d=e(c,h);return this.cacheKeyboard.set(a,d),d}return r}let n=new J,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data);return e(n,i)}bottomKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let a=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(a);if(!r){let c=new z,h=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),d=e(c,h);return d.resized(!0),this.cacheKeyboard.set(a,d),d}return r}let n=new z,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),o=e(n,i);return o.resized(),o}getSeperatorTag(e="space"){return e=="space"?" ":":"}haveArgs(e="",t){return e.includes(this.getSeperatorTag(t))}addArgs(e="",t,s){let n=this.getSeperatorTag(t),i="";for(let o=0;o<s.length;o++){let a=s[o];a!=null&&a!==""&&(i+=n+a)}return e+i}getArgs(e="",t,s=1){if(!e)return[];let n=this.getSeperatorTag(t);return e.split(n).slice(s)}getIntent(e="",t,s=1){if(!e)return"";let n=this.getSeperatorTag(t),i=e.split(n);return s==1?i[0]:i.slice(0,s).join(n)}isSessionCallbackData(){return this.temp.session.method===this.methodSessionCallbackData()}isSessionArgsCallbackData(){return this.temp.session.method===this.methodSessionArgsCallbackData()}isSessionText(){return this.temp.session.method===this.methodSessionText()}isSessionArgsText(){return this.temp.session.method===this.methodSessionArgsText()}isSessionCommandText(){return this.temp.session.method===this.methodSessionCommandText()}isSessionCommandArgsText(){return this.temp.session.method===this.methodSessionCommandArgsText()}isSessionFreeText(){return this.temp.session.method===this.methodSessionFreeText()}isSessionCaptionPhoto(){return this.temp.session.method===this.methodSessionCaptionPhoto()}isSessionCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCaptionArgsPhoto()}isSessionCommandCaptionPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionPhoto()}isSessionCommandCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionArgsPhoto()}isSessionFreePhoto(){return this.temp.session.method===this.methodSessionFreePhoto()}isSessionCaptionVideo(){return this.temp.session.method===this.methodSessionCaptionVideo()}isSessionCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCaptionArgsVideo()}isSessionCommandCaptionVideo(){return this.temp.session.method===this.methodSessionCommandCaptionVideo()}isSessionCommandCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVideo()}isSessionFreeVideo(){return this.temp.session.method===this.methodSessionFreeVideo()}isSessionCaptionAudio(){return this.temp.session.method===this.methodSessionCaptionAudio()}isSessionCaptionArgsAudio(){return this.temp.session.method===this.methodSessionCaptionArgsAudio()}isSessionCaptionCommandAudio(){return this.temp.session.method===this.methodSessionCaptionCommandAudio()}isSessionCaptionCommandArgsAudio(){return this.temp.session.method===this.methodSessionCaptionCommandArgsAudio()}isSessionFreeAudio(){return this.temp.session.method===this.methodSessionFreeAudio()}isSessionCaptionDocument(){return this.temp.session.method===this.methodSessionCaptionDocument()}isSessionCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCaptionArgsDocument()}isSessionCommandCaptionDocument(){return this.temp.session.method===this.methodSessionCommandCaptionDocument()}isSessionCommandCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCommandCaptionArgsDocument()}isSessionFreeDocument(){return this.temp.session.method===this.methodSessionFreeDocument()}isSessionCaptionAnimation(){return this.temp.session.method===this.methodSessionCaptionAnimation()}isSessionCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCaptionArgsAnimation()}isSessionCommandCaptionAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionAnimation()}isSessionCommandCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionArgsAnimation()}isSessionFreeAnimation(){return this.temp.session.method===this.methodSessionFreeAnimation()}isSessionCaptionVoice(){return this.temp.session.method===this.methodSessionCaptionVoice()}isSessionCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCaptionArgsVoice()}isSessionCommandCaptionVoice(){return this.temp.session.method===this.methodSessionCommandCaptionVoice()}isSessionCommandCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVoice()}isSessionFreeVoice(){return this.temp.session.method===this.methodSessionFreeVoice()}isSessionFreeVideoNote(){return this.temp.session.method===this.methodSessionFreeVideoNote()}isSessionFreeSticker(){return this.temp.session.method===this.methodSessionFreeSticker()}isSessionFreeLocation(){return this.temp.session.method===this.methodSessionFreeLocation()}isSessionFreeContact(){return this.temp.session.method===this.methodSessionFreeContact()}sessionCallbackData(e){return this.setSession(this.methodSessionCallbackData(),e)}sessionArgsCallbackData(e){return this.setSession(this.methodSessionArgsCallbackData(),e)}sessionText(e){return this.setSession(this.methodSessionText(),e)}sessionArgsText(e){return this.setSession(this.methodSessionArgsText(),e)}sessionCommandText(e){return this.setSession(this.methodSessionCommandText(),e)}sessionCommandArgsText(e){return this.setSession(this.methodSessionCommandArgsText(),e)}sessionFreeText(e){return this.setSession(this.methodSessionFreeText(),e)}sessionCaptionPhoto(e){return this.setSession(this.methodSessionCaptionPhoto(),e)}sessionCaptionArgsPhoto(e){return this.setSession(this.methodSessionCaptionArgsPhoto(),e)}sessionCommandCaptionPhoto(e){return this.setSession(this.methodSessionCommandCaptionPhoto(),e)}sessionCommandCaptionArgsPhoto(e){return this.setSession(this.methodSessionCommandCaptionArgsPhoto(),e)}sessionFreePhoto(e){return this.setSession(this.methodSessionFreePhoto(),e)}sessionCaptionVideo(e){return this.setSession(this.methodSessionCaptionVideo(),e)}sessionCaptionArgsVideo(e){return this.setSession(this.methodSessionCaptionArgsVideo(),e)}sessionCommandCaptionVideo(e){return this.setSession(this.methodSessionCommandCaptionVideo(),e)}sessionCommandCaptionArgsVideo(e){return this.setSession(this.methodSessionCommandCaptionArgsVideo(),e)}sessionFreeVideo(e){return this.setSession(this.methodSessionFreeVideo(),e)}sessionCaptionAudio(e){return this.setSession(this.methodSessionCaptionAudio(),e)}sessionCaptionArgsAudio(e){return this.setSession(this.methodSessionCaptionArgsAudio(),e)}sessionCaptionCommandAudio(e){return this.setSession(this.methodSessionCaptionCommandAudio(),e)}sessionCaptionCommandArgsAudio(e){return this.setSession(this.methodSessionCaptionCommandArgsAudio(),e)}sessionFreeAudio(e){return this.setSession(this.methodSessionFreeAudio(),e)}sessionCaptionDocument(e){return this.setSession(this.methodSessionCaptionDocument(),e)}sessionCaptionArgsDocument(e){return this.setSession(this.methodSessionCaptionArgsDocument(),e)}sessionCommandCaptionDocument(e){return this.setSession(this.methodSessionCommandCaptionDocument(),e)}sessionCommandCaptionArgsDocument(e){return this.setSession(this.methodSessionCommandCaptionArgsDocument(),e)}sessionFreeDocument(e){return this.setSession(this.methodSessionFreeDocument(),e)}sessionCaptionAnimation(e){return this.setSession(this.methodSessionCaptionAnimation(),e)}sessionCaptionArgsAnimation(e){return this.setSession(this.methodSessionCaptionArgsAnimation(),e)}sessionCommandCaptionAnimation(e){return this.setSession(this.methodSessionCommandCaptionAnimation(),e)}sessionCommandCaptionArgsAnimation(e){return this.setSession(this.methodSessionCommandCaptionArgsAnimation(),e)}sessionFreeAnimation(e){return this.setSession(this.methodSessionFreeAnimation(),e)}sessionCaptionVoice(e){return this.setSession(this.methodSessionCaptionVoice(),e)}sessionCaptionArgsVoice(e){return this.setSession(this.methodSessionCaptionArgsVoice(),e)}sessionCommandCaptionVoice(e){return this.setSession(this.methodSessionCommandCaptionVoice(),e)}sessionCommandCaptionArgsVoice(e){return this.setSession(this.methodSessionCommandCaptionArgsVoice(),e)}sessionFreeVoice(e){return this.setSession(this.methodSessionFreeVoice(),e)}sessionFreeVideoNote(e){return this.setSession(this.methodSessionFreeVideoNote(),e)}sessionFreeSticker(e){return this.setSession(this.methodSessionFreeSticker(),e)}sessionFreeLocation(e){return this.setSession(this.methodSessionFreeLocation(),e)}sessionFreeContact(e){return this.setSession(this.methodSessionFreeContact(),e)}methodSession(e,t){return`${e}-${t||this.data.name}`}methodSessionCallbackData(e){return this.methodSession("1",e)}methodSessionArgsCallbackData(e){return this.methodSession("2",e)}methodSessionText(e){return this.methodSession("3",e)}methodSessionArgsText(e){return this.methodSession("4",e)}methodSessionCommandText(e){return this.methodSession("5",e)}methodSessionCommandArgsText(e){return this.methodSession("6",e)}methodSessionFreeText(e){return this.methodSession("7",e)}methodSessionCaptionPhoto(e){return this.methodSession("8",e)}methodSessionCaptionArgsPhoto(e){return this.methodSession("9",e)}methodSessionCommandCaptionPhoto(e){return this.methodSession("10",e)}methodSessionCommandCaptionArgsPhoto(e){return this.methodSession("11",e)}methodSessionFreePhoto(e){return this.methodSession("12",e)}methodSessionCaptionVideo(e){return this.methodSession("13",e)}methodSessionCaptionArgsVideo(e){return this.methodSession("14",e)}methodSessionCommandCaptionVideo(e){return this.methodSession("15",e)}methodSessionCommandCaptionArgsVideo(e){return this.methodSession("16",e)}methodSessionFreeVideo(e){return this.methodSession("17",e)}methodSessionCaptionAudio(e){return this.methodSession("18",e)}methodSessionCaptionArgsAudio(e){return this.methodSession("19",e)}methodSessionCaptionCommandAudio(e){return this.methodSession("20",e)}methodSessionCaptionCommandArgsAudio(e){return this.methodSession("21",e)}methodSessionFreeAudio(e){return this.methodSession("22",e)}methodSessionCaptionDocument(e){return this.methodSession("23",e)}methodSessionCaptionArgsDocument(e){return this.methodSession("24",e)}methodSessionCommandCaptionDocument(e){return this.methodSession("25",e)}methodSessionCommandCaptionArgsDocument(e){return this.methodSession("26",e)}methodSessionFreeDocument(e){return this.methodSession("27",e)}methodSessionCaptionAnimation(e){return this.methodSession("28",e)}methodSessionCaptionArgsAnimation(e){return this.methodSession("29",e)}methodSessionCommandCaptionAnimation(e){return this.methodSession("30",e)}methodSessionCommandCaptionArgsAnimation(e){return this.methodSession("31",e)}methodSessionFreeAnimation(e){return this.methodSession("32",e)}methodSessionCaptionVoice(e){return this.methodSession("33",e)}methodSessionCaptionArgsVoice(e){return this.methodSession("34",e)}methodSessionCommandCaptionVoice(e){return this.methodSession("35",e)}methodSessionCommandCaptionArgsVoice(e){return this.methodSession("36",e)}methodSessionFreeVoice(e){return this.methodSession("37",e)}methodSessionFreeVideoNote(e){return this.methodSession("38",e)}methodSessionFreeSticker(e){return this.methodSession("39",e)}methodSessionFreeLocation(e){return this.methodSession("40",e)}methodSessionFreeContact(e){return this.methodSession("41",e)}};import{join as j}from"path";import{existsSync as X,readdirSync as Y}from"fs";import{createRequire as fe}from"module";var x=class{static{u(this,"PageManager")}static _getFile(e,t,s=0){let i=Object.values(e)[s];if(i===void 0)throw new Error(`File ${t} must have export (not default) class page`);return i}static getFilePath(){return j(process.cwd(),"src","pages")}static getFileSync(e,t=0){e||(e=this.getFilePath());let n=fe(e)(e);return this._getFile(n,e,t)}static async getFile(e,t=0){e||(e=this.getFilePath());let s=await import(`${e}?t=${Date.now()}`);return this._getFile(s,e,t)}static getFileManySync(e,t=0){if(e||(e=this.getFilePath()),!X(e))throw new Error(`Directory ${e} is not found, please make it manually`);return Y(e).map(n=>{let i=j(e,n);return{path:i,page:this.getFileSync(i,t)}})}static clearCacheRequire(e){if(e||(e=this.getFilePath()),!X(e))throw new Error(`Directory ${e} is not found, please make it manually`);return Y(e).forEach(s=>{let n=j(e,s);delete U.cache[U.resolve(n)]}),!0}};import{readFileSync as ke}from"fs";import{fileURLToPath as Se}from"url";import{dirname as we,join as se,parse as _e}from"path";import{basename as Q,join as v,extname as Z}from"path";import{readdirSync as Te,readFileSync as $,existsSync as R,statSync as O,writeFileSync as be}from"fs";import{watch as Ce}from"chokidar";var M=class g{static{u(this,"TemplateEngine")}static ALLOWED_BLOCKS=["<base>","<message>","<keyboard>","<media>","<description>","<script>","<switch>","<case>","<default>","<map>","<div>","<import/>","<space/>","<b>","<i>","<u>","<s>","<code>","<pre>","<a>","<blockquote>","<blockquote expandable>"];static ALLOWED_SCOPE=["{{}}","{~~}"];static _escape(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processScopeVariables(e){return e.replace(/\{\{(\w+)\}\}/g,(t,s)=>`\${(data && data["${s}"]) ?? ""}`)}static _processScopeExec(e){return e.replace(/{~\s*([\s\S]*?)\s*~}/g,(t,s)=>`\${(() => { try { return ${s} } catch(e) { try { with(data || {}) { return ${s} } } catch(ee) { return '' } } })()}`)}static _processBaseBlocks(e){let t=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,s={};for(let n of e.matchAll(t)){let i=n[2]??"default",a=(n[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[i]=a}return s}static _processScriptBlocks(e){return e.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(t,s)=>{let n=s.trim();return n?`\${(() => { if (!data) return ''; try { with(data) { ${n} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(e){return e.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(e){return e.replace(/<div>([\s\S]*?)<\/div>/gi,(t,s)=>s.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(e){let t=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return e.replace(t,(s,n,i)=>{if(!n)return"";let o="",a=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=a.exec(i))!==null;){let d=(c[1]||"").split(",").map(l=>l.trim()),m=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(l=>{o+=`case "${l}": `}),o+=`return \`${m}\`; `}let h=r.exec(i);if(h){let d=(h[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();o+=`default: return \`${d}\`; `}else o+="default: return ''; ";return`\${(() => { switch((data && data["${n}"])) { ${o} } })()}`})}static _processMapBlocks(e){let t=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return e.replace(t,(s,n,i)=>{let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let m of n.matchAll(a))o[m[1]]=m[2];let r=o.src;if(!r)return"";let c=o.join??"\\n",h=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");h=h.replace(/\{\{([\w.]+)\}\}/g,(m,l)=>l==="e"||l.startsWith("e.")?`\${${l}}`:l==="i"?"${i}":m);let d=c.replace(/"/g,'\\"');return`\${(() => { const __arr = (data && data["${r}"]) || []; let __out = ""; for (let i = 0; i < __arr.length; i++) { const e = __arr[i]; if (i > 0) { __out += "${d}" } __out += \`${h}\`; } return __out; })()}`})}static _processMediaBlocks(e){let t=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let n of e.matchAll(t)){let i=n[1],o=n[2],a={},r=/(\w+)="([^"]*)"/g;if(i)for(let l of i.matchAll(r))a[l[1]]=l[2];let c=a.lang||"default",h=a.type,d=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),m={type:h};a.src&&(m.src=a.src),d&&h!=="video_note"&&h!=="sticker"&&(m.caption=d),h==="location"&&(a.latitude&&(m.latitude=a.latitude),a.longitude&&(m.longitude=a.longitude),d&&(m.caption=d)),h==="contact"&&(a.phone&&(m.phone=a.phone),a.first_name&&(m.first_name=a.first_name),a.last_name&&(m.last_name=a.last_name),a.vcard&&(m.vcard=a.vcard),d&&(m.caption=d)),s[c]=m}return s}static _processMessageBlocks(e){let t=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let h of n.matchAll(a))o[h[1]]=h[2];let r=o.lang||"default",c=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=c}return s}static _processDescriptionBlocks(e){let t=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(a))o[d[1]]=d[2];let r=o.lang||"default",c=o.scope||"default",h=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][c]=h}return s}static _processKeyboardBlocks(e){let t=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(a))o[d[1]]=d[2];let r=o.lang||"default",c=o.type==="bottom"?"bottom":"inline",h=i.trim();s[r]||(s[r]={}),s[r][c]=h}return s}static _compileToFunction(e,t){let s;t?s=e.map(o=>`\`${o}\``).join(","):s=`\`${e}\``;let n=s;if(n=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(n))),t){let i=`return [${n}]`;return new Function("data",i)}else{let i=`return ${n}`;return new Function("data",i)}}static compileBlockMedia(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processMediaBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){let h={};for(let[d,m]of Object.entries(c)){if(d==="type"||typeof m!="string")continue;let l=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(m)))));h[d]=this._compileToFunction(l,!1)}n[i][r]=d=>{let m={...c};for(let[l,p]of Object.entries(h))m[l]=p(d);return m}}}return n}static compileBlockMessage(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processMessageBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){let h=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));n[i][r]=this._compileToFunction(h,!1)}}return n}static compileBlockDescription(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processDescriptionBlocks(o);n[i]={};for(let[r,c]of Object.entries(a))for(let[h,d]of Object.entries(c)){n[i][h]||(n[i][h]={});let m=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));n[i][h][r]=this._compileToFunction(m,!1)}}return n}static compileBlockKeyboards(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processKeyboardBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){n[i][r]={};for(let[h,d]of Object.entries(c)){let l=d.split(/(?<!\\),\s*/).map(p=>p.replace(/\\,/g,",").trim()).map(p=>this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(p))))));n[i][r][h]=this._compileToFunction(l,!0)}}}return n}static _extractBlock(e,t,s="default",n="all",i){let o=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,a=e,r=!1;for(let c of e.matchAll(o))if((c[2]??"default")===s){a=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(e);if(!(s==="default"&&!c))return""}if(t){if(t==="all")return a;let c=Array.isArray(t)?t:[t],h=[];for(let m of c){let l=new RegExp(`([ \\t]*)<${m}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${m}>`,"gi");for(let p of a.matchAll(l)){let w=p[2];if(i){let C=/lang="([^"]*)"/i,_=w?.match(C);if(((_?_[1]:void 0)||"default")!==i)continue}h.push({start:p.index,content:p[0],innerContent:p[3]??""})}}h.sort((m,l)=>m.start-l.start);let d=u(m=>{let l=m.split(`
|
|
2
|
-
`);if(
|
|
3
|
-
`).trim()},"processResult");return n==="all"?
|
|
4
|
-
`):
|
|
5
|
-
`)}return a}static _processImportBlocks(e){let t=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,s=[];return{processed:e.replace(t,(i,o,a)=>{let r={},c=/(\w+)="([^"]*)"/g;if(a)for(let
|
|
6
|
-
`).map((
|
|
7
|
-
`);a=a.replace(`__IMPORT_${r}__`,m)}return a}static validateBlockNames(e){let t=[],s=new Set(g.ALLOWED_BLOCKS.map(o=>o.replace(/^<\/?/,"").replace(/\s.*?>$/,"").replace(/\/?>$/,"").toLowerCase())),n=new Set(["b","i","u","s","code","pre","a","blockquote"]),i=/<\/?\s*([a-z][\w-]*)(?:\s[^<>]*)?\/?\s*>/gi;for(let o of e.matchAll(i)){let a=o[1]?.toLowerCase();if(!a||n.has(a)||s.has(a))continue;let r=(e.slice(0,o.index).match(/\n/g)||[]).length+1;t.push({line:r,message:`Unsupported template block: <${a}>`})}return{valid:t.length===0,errors:t}}static validateScopes(e){let t=[],s=new Set(g.ALLOWED_SCOPE),n=/\{([^\s{}\w])([\s\S]*?)\1\}/g;for(let i of e.matchAll(n)){let o=`{${i[1]}${i[1]}}`;if(i[1]&&s.has(o))continue;let a=(e.slice(0,i.index).match(/\n/g)||[]).length+1,r=i[1]??"?";t.push({line:a,message:`Unsupported template scope: {${r} ${r}}`})}return{valid:t.length===0,errors:t}}static validateBlockPositions(e){let t=[],s=[],n=new Set(["b","i","u","s","code","pre","a","blockquote"]),i={base:new Set(["__root__"]),message:new Set(["base"]),keyboard:new Set(["base"]),media:new Set(["base"]),description:new Set(["base"]),switch:new Set(["base","message","description","keyboard","case","default","map","div"]),case:new Set(["switch"]),default:new Set(["switch"]),map:new Set(["base","message","description","keyboard","case","default","div"]),div:new Set(["base","message","description","keyboard","case","default","map"]),script:new Set(["base","message","description","keyboard","case","default","map","div"]),import:new Set(["base"]),space:new Set(["base","message","description","keyboard","case","default","switch","map","div"])},o=/<(\/?)(\w[\w-]*)([^>]*)>/g,a;for(;(a=o.exec(e))!==null;){let r=a[0],c=a[1],h=a[2].toLowerCase(),d=c==="/",m=!d&&r.endsWith("/>");if(n.has(h)||!i[h])continue;let l=(e.slice(0,a.index).match(/\n/g)||[]).length+1;if(d)if(s.length===0)t.push({line:l,message:`Unexpected closing tag </${h}>: no matching opening tag`});else{let p=s[s.length-1];p.block!==h?t.push({line:l,message:`Mismatched closing tag: expected </${p.block}> but found </${h}>`}):s.pop()}else if(m){let p=s.length>0?s[s.length-1].block:"__root__";i[h].has(p)||t.push({line:l,message:`Block <${h}> is not allowed inside <${p}>`})}else{let p=s.length>0?s[s.length-1].block:"__root__";i[h].has(p)||t.push({line:l,message:`Block <${h}> is not allowed inside <${p}>`}),s.push({block:h,line:l})}}for(let r of s)t.push({line:r.line,message:`Unclosed block <${r.block}>: missing closing tag </${r.block}>`});return{valid:t.length===0,errors:t}}static validateBlockFormat(e){let t=[],s=new Set(["space","import"]),n=new Set(["base","message","keyboard","media","description","script","switch","case","default","map","div"]),i=/<(\/?)(\w[\w-]*)([^>]*)>/g,o;for(;(o=i.exec(e))!==null;){let a=o[0],r=o[1],c=o[2].toLowerCase(),h=r==="/",d=!h&&a.endsWith("/>");if(h)continue;let m=(e.slice(0,o.index).match(/\n/g)||[]).length+1;d?n.has(c)&&t.push({line:m,message:`Block <${c}> must not be self-closing: use <${c}>...</${c}> instead`}):s.has(c)&&t.push({line:m,message:`Block <${c}> must be self-closing: use <${c} /> instead`})}return{valid:t.length===0,errors:t}}static validateTemplate(e){let t=this.validateBlockNames(e),s=this.validateScopes(e),n=this.validateBlockFormat(e),i=this.validateBlockPositions(e),o=[...t.errors,...s.errors,...n.errors,...i.errors];return{valid:o.length===0,errors:o}}};var V=class{static{u(this,"TemplateManager")}_map=new Map;_engine=M;_watcher=[];_pageManager=x;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(e){let{path:t,enableWatch:s=!1}=e;this._path=t,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(e.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let e=0;e<this._path.length;e++){let t=this._path[e];if(!R(t))throw new Error(`Template base path is not exists: ${t}`);if(!O(t).isDirectory())throw new Error(`Template base path is not a directory: ${t}`)}return!0}catch(e){throw new Error(`Failed to validate Template base path: ${String(e)}`)}}_initializeWatcher(e){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let t=0;t<this._path.length;t++){let s=this._path[t],n=Ce(s,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...e});this._watcher[t]=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(e){let t=Q(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileAdd(e){let t=Q(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileDelete(e){let t=Q(e),s=this._getKey(t);this._map.has(s)&&this._map.delete(s)}_handleWatchError(e){}_loadAllFiles(){let e=new Map,t=[];for(let n=0;n<this._path.length;n++){let i=this._path[n],a=Te(i,"utf8").filter(r=>this._isValidFile(r));for(let r of a){let c=v(i,r),h=this._getExtension(r),d=this._getKey(r);if(h===".html")e.set(d,$(c,"utf8"));else if(h===".ts"||h===".js"){let m=x.getFileSync(c);m?.template!==void 0&&(e.set(d,m.template),t.push(m))}}}let s=new Map;for(let[n,i]of e.entries())this._compile(n,i,void 0,s,e);e.clear(),s.clear();for(let n of t)n.template=void 0}_loadFile(e){for(let t=0;t<this._path.length;t++){let s=this._path[t],n=v(s,e),i=this._getExtension(e),o=this._getKey(e);if(i==".html"){let a=$(n,"utf8");this._compile(o,a)}else if(i==".ts"||i==".js"){let a=x.getFileSync(n);a?.template!==void 0&&(this._compile(o,a.template),a.template=void 0)}else throw new Error(`File ${e} is not support`)}}_getExtension(e){return Z(e).toLowerCase()}_readTemplateFile(e){for(let t of this._path){let s=Z(e).toLowerCase();if(s){let a=v(t,e);if(R(a)&&O(a).isFile()){if(s===".html")return $(a,"utf8");if(s===".ts"||s===".js")try{return x.getFileSync(a)?.template??null}catch{return null}}continue}let n=v(t,`${e}.ts`),i=v(t,`${e}.js`);if(R(n)&&O(n).isFile())try{return x.getFileSync(n)?.template??null}catch{}else if(R(i)&&O(i).isFile())try{return x.getFileSync(n)?.template??null}catch{}let o=v(t,`${e}.html`);if(R(o)&&O(o).isFile())return $(o,"utf8")}return null}_isValidFile(e){return this._supportedExtensions.has(this._getExtension(e))}_validateTemplate(e,t){let s=M.validateTemplate(t);if(!s.valid&&s.errors.length>0){let n=s.errors[0];throw new Error(`Template on base "${e}" (line ${n.line}): ${n.message}`)}}_getKey(e){return e.replace(/\.[^/.]+$/,"")}_compile(e,t,s,n,i){let o=this._map.get(e),a=o||{},r=!1;this._validateTemplate(e,t);let c=M.processImportBlocks(t,d=>i&&i.has(d)?i.get(d):this._readTemplateFile(d),0,n);this._validateTemplate(e,c);let h=M._processBaseBlocks(c);(s===void 0||s?.media===!1||o?.media===void 0)&&(a.media=M.compileBlockMedia(c,h),r=!0),(s===void 0||s?.message===!1||o?.message===void 0)&&(a.message=M.compileBlockMessage(c,h),r=!0),(s===void 0||s?.keyboard===!1||o?.keyboard===void 0)&&(a.keyboard=M.compileBlockKeyboards(c,h),r=!0),(s===void 0||s?.description===!1||o?.description===void 0)&&(a.description=M.compileBlockDescription(c,h),r=!0),r&&this._map.set(e,a)}getMedia(e,t="default",s="default",n){let o=this._map.get(e)?.media?.[t],a=o?.[s]||o?.default;try{if(!a)throw new Error("Media function not found, please check your template");return a(n)}catch{return{}}}getMessage(e,t="default",s="default",n){try{let o=this._map.get(e)?.message?.[t],a=o?.[s]||o?.default;if(!a)throw"";return a(n)}catch{return""}}getDescription(e,t="default",s="default",n="default",i){try{let a=this._map.get(e)?.description?.[t]?.[n],r=a?.[s]||a?.default;if(!r)throw"";return r(i)}catch{return""}}getDescriptionLanguage(e,t="default",s="default"){try{let i=this._map.get(e)?.description?.[t]?.[s];return i?Object.keys(i):[]}catch{return[]}}getDescriptionScopes(e,t="default"){try{let n=this._map.get(e)?.description?.[t];return n?Object.keys(n):[]}catch{return[]}}getKeyboard(e,t="default",s="default",n="inline",i){try{let a=this._map.get(e)?.keyboard?.[t],r=a?.[s]?.[n]||a?.default?.[n];if(!r)throw[];return r(i)}catch{return[]}}async write(e,t){if(this._getExtension(e)!=".html")return null;for(let s=0;s<this._path.length;s++){let n=v(this._path[s],e);if(R(n))return be(n,t,"utf8"),this._loadFile(e),!0}return null}has(e){return this._map.has(e)}async destroy(){if(this._watcher)for(let e of this._watcher)await e.close();this._map.clear()}};import{Bot as Ie,webhookCallback as ee}from"grammy";var K=class{constructor(e){this.maxSize=e;if(!Number.isFinite(e)||e<=0)throw new Error("WebhookQueue maxSize must be a positive number")}maxSize;static{u(this,"WebhookQueue")}queue=[];waitEnqueue=[];waitDequeue=[];getStats(){return{length:this.queue.length,maxSize:this.maxSize,waitingEnqueue:this.waitEnqueue.length,waitingDequeue:this.waitDequeue.length}}get length(){return this.queue.length}async enqueue(e){if(this.queue.length>=this.maxSize&&await new Promise(t=>this.waitEnqueue.push(t)),this.waitDequeue.length>0){this.waitDequeue.shift()(e);return}this.queue.push(e)}async dequeue(){if(this.queue.length>0){let e=this.queue.shift();return this.waitEnqueue.shift()?.(),e}return await new Promise(e=>this.waitDequeue.push(e))}};var xe=we((()=>{try{return f}catch{return Se(import.meta.url)}})()),Me=JSON.parse(ke(se(xe,"../../package.json"),"utf-8")).version,te=class{static{u(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;optionsPage={shortCallbackData:!1};log;bot;botConfig;webhookQueue;webhookQueueInstance;webhookServer;handlerBotUpdate;deployType;constructor(e){if(!e?.token||e?.token?.length==0)throw new Error("Token is not valid or empty");if(typeof e.optionsPage?.shortCallbackData=="boolean"&&(this.optionsPage.shortCallbackData=e.optionsPage.shortCallbackData),this.log=e.log===!0?F:e.log?e.log:void 0,this.log?.info?.(`Gramstax v${Me}`),this.cacheSession=e.cacheSession||new B("memory"),this.cacheKeyboard=e.cacheKeyboard||new Map,this.botConfig=e.botConfig,this.webhookQueue=e.webhookQueue,this.templateManager=e.templateManager||new V({path:[se(process.cwd(),"src","pages")]}),this.bot=this.createBot(e.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.stop()),process.once("SIGTERM",()=>this.stop()),this.hookBeforeStart(),e.deploy.startsWith("polling"))this.deployType="polling",this._runPolling();else if(e.deploy.startsWith("webhook:"))this.deployType="webhook",this._runWebhook(e.deploy.split("webhook:")[1]);else if(e.deploy.startsWith("serverless:"))this.deployType="serverless",this._runServerless(e.deploy.split("serverless:")[1]);else if(e.deploy.startsWith("test"))this.deployType="test";else throw new Error("Params deploy is not valid, expected: polling, webhook:<public-url>, serverless:<your-adapter>")}async stop(){await this.bot.stop(),this.deployType==="webhook"&&(await this.webhookServer?.stop(),this.webhookServer=void 0)}_onCatch(e){if(this.log?.errorMake)this.log?.errorMake(e,"Bot","catch");else{let t=JSON.stringify(e,null,2);this.log?.error?.(`[Bot.catch]: ${t}`)}}hookBeforeStart(){}hookAfterStart(){}async _onStart(e,t,s){await this.executeSyncBlocksDescription(this.pages);let{username:n}=e;this.log?.success?.(`Telegram bot deploy ${t} started: ${n} ${t=="webhook"||t=="serverless"?`(${s})`:""}`),this.hookAfterStart()}createBot(e){return new Ie(e,this.botConfig)}createCtx(e){return new W({ct:e,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{isAnswer:!1,session:{},data:{}}})}_runPolling(){this.bot.start({drop_pending_updates:!0,onStart:u(e=>{this._onStart(e,"polling",null)},"onStart")})}async _runWebhook(e){let{serve:t}=await import("bun"),s=ee(this.bot,"bun"),n=this.webhookQueue,i=n?.enabled===!0;this.handlerBotUpdate=i?this.bot.handleUpdate.bind(this.bot):s;let o=i?new K(n?.maxQueueSize??5e3):void 0,a=n?.workerCount??8,r=n?.perChatConcurrency??1,c=n?.blockWhenFull!==!1,h=new Map,d=new Map;this.webhookQueueInstance=o;let m=u(y=>y?.message?.chat?.id??y?.edited_message?.chat?.id??y?.channel_post?.chat?.id??y?.edited_channel_post?.chat?.id??y?.callback_query?.message?.chat?.id??y?.callback_query?.from?.id??y?.inline_query?.from?.id??y?.chosen_inline_result?.from?.id,"getChatId"),l=u(async y=>{if(!i||r<=0||y===void 0||y===null)return()=>{};let b=String(y),k=h.get(b)||0;if(k<r)return h.set(b,k+1),()=>this._releaseWebhookChat(b,h,d);await new Promise(he=>{let G=d.get(b)||[];G.push(he),d.set(b,G)});let de=(h.get(b)||0)+1;return h.set(b,de),()=>this._releaseWebhookChat(b,h,d)},"acquireChat");if(i&&o){await this.bot.init();for(let y=0;y<a;y++)this._startWebhookWorker(o,l,m)}let p=new URL(e),w=p.pathname,C=parseInt(p.port)||3e3,_=this.log,S="/stats_queue";this.webhookServer?.stop();let I=t({port:C,async fetch(y){let{pathname:b}=new URL(y.url);if(y.method=="POST"&&b==w){if(!i||!o)return s(y);if(!c&&o.length>=(n?.maxQueueSize??5e3))return new Response("Queue full",{status:429});try{let k=await y.json();return await o.enqueue(k),new Response("OK",{status:200})}catch(k){return _?.error?.(`Webhook queue error: ${String(k)}`),new Response("Bad Request",{status:400})}}if(y.method=="GET"&&b==S){let k=o?.getStats()||{length:0,maxSize:n?.maxQueueSize??5e3,waitingEnqueue:0,waitingDequeue:0};return new Response(JSON.stringify({enabled:i,path:S,timestamp:new Date().toISOString(),maxQueueSize:n?.maxQueueSize??5e3,workerCount:a,perChatConcurrency:r,blockWhenFull:c,queue:k,activeChats:h.size}),{status:200,headers:{"Content-Type":"application/json"}})}if(y.method=="GET"&&b=="/"){let k=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:k}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}});this.webhookServer=I,(await this.bot.api.getWebhookInfo()).url!=e&&await this.bot.api.setWebhook(e);let D=await this.bot.api.getMe();await this._onStart(D,"webhook",e)}_startWebhookWorker(e,t,s){u(async()=>{for(;;){let i=await e.dequeue(),o=await t(s(i));try{await this.bot.handleUpdate(i)}catch(a){this.log?.error?.(`Webhook worker error: ${String(a)}`)}finally{o()}}},"run")()}_releaseWebhookChat(e,t,s){let n=t.get(e)||0,i=Math.max(0,n-1);i===0?t.delete(e):t.set(e,i);let o=s.get(e);o&&o.length>0&&(o.shift()(),o.length===0&&s.delete(e))}getWebhookQueueStats(){if(!this.webhookQueue?.enabled||!this.webhookQueueInstance)return null;let e=this.webhookQueueInstance.getStats(),t=this.webhookQueue.maxQueueSize??5e3,s=this.webhookQueue.workerCount??8,n=this.webhookQueue.perChatConcurrency??1,i=this.webhookQueue.blockWhenFull!==!1;return{enabled:!0,maxQueueSize:t,workerCount:s,perChatConcurrency:n,blockWhenFull:i,...e}}async _runServerless(e){this.handlerBotUpdate=ee(this.bot,e);let t=await this.bot.api.getMe();await this._onStart(t,"serverless",e)}_pageBuildData(e,t){e?.data===void 0&&(e.data=e.buildData());let{name:s}=_e(t);e.data.name||(e.data.name=s),e.data.intentText||(e.data.intentText=e.data.name),e.data.intentCommandText||(e.data.intentCommandText=e.data.name),e.data.intentCallbackData||(e.data.intentCallbackData=e.data.name)}_pageSorts(e,t,s){let n=e.data.name,i=e.prototype,o="handle",a="Args",r="Command",c="Caption",h="Free",d=t.routeDynamic,m=t.routeDynamicSpesific;t.all[n]=e;for(let l=0;l<t.lenListRouteStaticSession;l++){let p=t.listRouteStaticSession[l];if(typeof i[p]!="function")continue;let w=t.routeStatic[p],C=t.routeStaticIntent[p],_=t.routeStaticSession[p],S={name:n,routeName:p},I=w||C;if(I!==void 0){let P=p.includes(r),D=p.endsWith("CallbackData"),y=p.endsWith("Text"),b;if(P){let k=e.data.intentCommandText;b=k?`/${k}`:void 0}else if(D){let k=e.data.intentCallbackData;this.optionsPage.shortCallbackData===!0&&(k=String(s),e.data.intentCallbackData=k),b=k}else y?b=e.data.intentText:b=e.data.name;b&&(I[b]=S)}if(_!==void 0){let D=`methodSession${p.replace("handle","")}`,y=i[D]?.(n);_[y]=S}if(p.startsWith("handleFree")){let P=p.replace(o,"").replace(a,"").replace(r,"").replace(c,"").replace(h,"").toLowerCase();m[P].push(S)}}i.handleFree&&d.push(n)}async executeSyncBlocksDescription(e){let t=new Map,s=e.routeStatic.handleCommandText;for(let[,n]of Object.entries(s)){let i=n.name,o=this.templateManager.getDescriptionScopes(i);for(let a of o){t.has(a)||t.set(a,new Set);let r=this.templateManager.getDescriptionLanguage(i,"default",a);for(let c of r)t.get(a).add(c)}}for(let[n,i]of t)for(let o of i){let a=[];for(let[,h]of Object.entries(s)){let d=h.name,m=this.templateManager.getDescription(d,"default",o,n);m&&a.push({command:d,description:m})}if(a.length===0)continue;let r={type:n},c=o==="default"?void 0:o;try{let h=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(h.map(l=>({command:l.command,description:l.description})).sort((l,p)=>l.command.localeCompare(p.command))),m=JSON.stringify(a.sort((l,p)=>l.command.localeCompare(p.command)));d!==m&&(await this.bot.api.setMyCommands(a,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${n},${c?` lang: ${c},`:""} total (${a.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 e=["handleCallbackData","handleText","handleCommandText","handleCaptionPhoto","handleCommandCaptionPhoto","handleCaptionVideo","handleCommandCaptionVideo","handleCaptionAudio","handleCommandCaptionAudio","handleCaptionDocument","handleCommandCaptionDocument","handleCaptionAnimation","handleCommandCaptionAnimation","handleCaptionVoice","handleCommandCaptionVoice"],t=["handleArgsCallbackData","handleArgsText","handleCommandArgsText","handleCaptionArgsPhoto","handleCommandCaptionArgsPhoto","handleCaptionArgsVideo","handleCommandCaptionArgsVideo","handleCaptionArgsAudio","handleCommandCaptionArgsAudio","handleCaptionArgsDocument","handleCommandCaptionArgsDocument","handleCaptionArgsAnimation","handleCommandCaptionArgsAnimation","handleCaptionArgsVoice","handleCommandCaptionArgsAnimation"],s=[...e,...t,"handleFreeText","handleFreePhoto","handleFreeVideo","handleFreeAudio","handleFreeDocument","handleFreeAnimation","handleFreeVoice","handleFreeVideoNote","handleFreeSticker","handleFreeLocation","handleFreeContact"],n=u((a,r)=>Object.fromEntries(a.map(c=>[c,r()])),"makeObject"),i=u(()=>[],"initDynamicSpesific"),o={all:{},routeDynamic:[],routeDynamicSpesific:{text:i(),photo:i(),video:i(),audio:i(),document:i(),animation:i(),voice:i(),videonote:i(),sticker:i(),location:i(),contact:i()},routeStatic:n(e,()=>({})),routeStaticIntent:n(t,()=>({})),routeStaticSession:n(s,()=>({})),listRouteStatic:e,listRouteStaticIntent:t,listRouteStaticSession:s,lenListRouteStatic:e.length,lenListRouteStaticIntent:t.length,lenListRouteStaticSession:s.length};return x.getFileManySync(void 0).forEach(({path:a,page:r},c)=>{this._pageBuildData(r,a),this._pageSorts(r,o,c),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(o.all).length})`),o}async _pageRoutes(e,t){let s,n;if(s===void 0){let o=await e.getSession();if(o){let a=o.method,r=this.pages.routeStaticSession,c=e.callbackData,h=e.msgText,d=e.msgCaption,m=c||h||d,l=t==="callbackdata",p=l?"colon":"space",w=m&&e.haveArgs(m,p)?e.getIntent(m,p,1):void 0,C=!l&&m?e.getIntent(m,"space",2):void 0;for(let _=0;_<this.pages.lenListRouteStaticSession;_++){let S=this.pages.listRouteStaticSession[_];if(S.toLowerCase().endsWith(t)){if(m){if(this.pages.routeStatic[S]?.[m])continue;let I=this.pages.routeStaticIntent[S];if(I&&(w&&I[w]||C&&I[C]))continue}n=r[S][a]}if(n)break}n!==void 0&&(s=this.pages.all[n.name])}}if(s===void 0){let o=e.callbackData,a=e.msgText,r=e.msgCaption,c=this.pages.routeStatic;for(let h=0;h<this.pages.lenListRouteStatic;h++){let d=this.pages.listRouteStatic[h];if(d.toLowerCase().endsWith(t)&&(n=c[d][o||a||r]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s===void 0){let o=this.pages.routeStaticIntent,a=t==="callbackdata",r=a?"colon":"space",c=a?e.callbackData:e.msgText||e.msgCaption,h=e.haveArgs(c,r);if(c&&h)for(let d=0;d<this.pages.lenListRouteStaticIntent;d++){let m=this.pages.listRouteStaticIntent[d];if(!m.toLowerCase().endsWith(t))continue;let l=o[m];if(n=l[e.getIntent(c,r,1)],!n&&!a&&(n=l[e.getIntent(c,"space",2)]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s!==void 0&&n!==void 0){if(!s.prototype[n.routeName])return;let a=await new s(e)[n.routeName]?.();return e.temp.isAnswer===!0?a:null}let i=this.pages.routeDynamicSpesific[t]||[];for(let o=0;o<i.length;o++){let a=i[o];if(a===void 0)continue;let r=this.pages.all[a.name];r!==void 0&&typeof r.prototype[a.routeName]=="function"&&await new r(e)[a.routeName]()}for(let o=0;o<this.pages.routeDynamic.length;o++){let a=this.pages.routeDynamic[o];if(a===void 0)continue;let r=this.pages.all[a];r!==void 0&&typeof r.prototype.handleFree=="function"&&await new r(e).handleFree()}if(e.temp.isAnswer===!1)return null}async hookBeforeRoute(e,t){return!!(e||t)}async hookErrorPage(e,t,s,n){}async hookErrorInputNotFoundPage(e){}async _onMessage(e,t){let s=this.createCtx(e);try{if(await this.hookBeforeRoute(s,t)===!1)return;await this._pageRoutes(s,t)===null&&await this.hookErrorInputNotFoundPage(s)}catch(n){await this.hookErrorPage(s,t,n,!1)}}async _onCallbackQueryData(e){let t=this.createCtx(e);try{if(await this.hookBeforeRoute(t,"onCallbackQueryData")===!1)return;await this._pageRoutes(t,"callbackdata")}catch(s){await this.hookErrorPage(t,"onCallbackQueryData",s,!0)}}async _onMessageText(e){await this._onMessage(e,"text")}async _onMessagePhoto(e){await this._onMessage(e,"photo")}async _onMessageVideo(e){await this._onMessage(e,"video")}async _onMessageAudio(e){await this._onMessage(e,"audio")}async _onMessageDocument(e){await this._onMessage(e,"document")}async _onMessageAnimation(e){await this._onMessage(e,"animation")}async _onMessageVoice(e){await this._onMessage(e,"voice")}async _onMessageVideoNote(e){await this._onMessage(e,"videonote")}async _onMessageSticker(e){await this._onMessage(e,"sticker")}async _onMessageLocation(e){await this._onMessage(e,"location")}async _onMessageContact(e){await this._onMessage(e,"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 ne=class{static{u(this,"BlockKeyboard")}static label;static _build(e,t,s,n){if(!this.label)throw new Error("Label not found, make sure set this.label from class extends LabelKeyboard");s||(s="inline");let i=this.label[e];if(!i)throw new Error(`Object value ${e} not found`);let o=u((a,r)=>`<keyboard type="${s}" lang="${r}">${n?this.label._reverse(a):a}</keyboard>`,"pro");return t?o(i[t],t):Object.keys(i).map(a=>o(i[a],a)).join(" ")}};var ie=class{static{u(this,"LabelKeyboard")}static _reverse(e){return e.split(/(?<!\\), */).reverse().join(", ")}static _reverseObj(e){return Object.keys(e).reduce((t,s)=>(t[s]=this._reverse(e[s]),t),{})}};import{isMainThread as Ae,Worker as ve}from"worker_threads";var A=class{constructor(e,t){this.send=e;this.register=t}send;register;static{u(this,"WorkerThreadRpc")}map=new Map;async make(e){let t=this.map,s=this.send,{id:n,method:i,params:o,result:a,error:r}=e;if(i!==void 0)try{let c=this.register[i];if(typeof c!="function")throw new Error(`Method ${i} not found or not function`);let h=await c.apply(this.register,o);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(a!==void 0){let c=t.get(n);c&&(c.resolve(a),t.delete(n))}else if(r!==void 0){let c=t.get(n);c&&(c.reject(r),t.delete(n))}}makeId(){return Math.random()}makeRequest(e,t,s=!0,n){let i=this.makeId(),o={id:i,method:e,params:t,...n};return s?new Promise((a,r)=>{this.map.set(i,{resolve:a,reject:r}),this.send(o)}):this.send(o)}};var E=class{constructor(e,t,s){this.path=e;this.argv=t;this.register=s;this.init(),s||(s=this),this.rpc=new A(this.send.bind(this),s)}path;argv;register;static{u(this,"WorkerThreadLaunch")}static isMainThread=Ae;_readyResolve;_readyPromise=new Promise(e=>this._readyResolve=e);pid=process.pid;thread={};threadId={};rpc={};ready(){return this._readyPromise}readyResolve(){this._readyResolve?.()}init(){this.thread=new ve(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",e=>this.handleOnMessage(e)),this.thread.on("exit",()=>this.kill()),process.once("SIGINT",()=>this.kill()),process.once("SIGTERM",()=>this.kill())}async handleOnMessage(e){this.rpc.make(e)}kill(){this.thread.terminate()}send(e){this.thread.postMessage(e)}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};var oe=class g{static{u(this,"WorkerThreadExport")}static launchGatewayClient(e){let t=new Proxy({},{get(n,i){if(!(typeof i!="string"||i==="then"))return async(o,...a)=>{let r=o.gatewayClients.get(e);return r||(r=await o.createGatewayClient(e)),r.request(i,a)}}}),s=u(function(n){return new Proxy({},{get(i,o){if(!(typeof o!="string"||o==="then"))return async(...a)=>{let r=n.gatewayClients.get(e);return r||(r=await n.createGatewayClient(e)),r.request(o,a)}}})},"ctor");return Object.setPrototypeOf(s,t),s}static init(e){let{WTInit:t,WTLaunch:s=E,path:n,wrap:i}=e,o=`for-${n}`;if(process.argv[2]===o)return new t,{launchGatewayClient:u(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};let a,r=new Proxy({},{get(d,m){if(m!=="then")return m==="sendRequest"||m==="request"||m==="kill"||m==="send"?(...l)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a[m](...l)}:(...l)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a.request(m,l)}}}),h={...i?i(r):{},launchWorker:u(async(d=[])=>(a=new s(n,[o,...d]),await a.ready(),a),"launchWorker"),launchGatewayClient:u(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};return new Proxy(h,{get(d,m){if(m!=="then")return m==="launchGatewayClient"?d.launchGatewayClient:m==="launchWorker"?d.launchWorker:m in d?d[m]:typeof m=="string"?(...l)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a.request(m,l)}:d[m]}})}};import{Client as Re}from"net-ipc";var L=class{static{u(this,"WorkerThreadGatewayClient")}client=new Re;rpc;constructor(){this.rpc=new A(e=>this.client.send(e),{}),this.client.on("message",e=>{this.rpc.make(e)})}async connect(e){this.client.options.path=e;let t=new Promise(s=>{this.client.once("ready",()=>s(this))});return await this.client.connect(),t}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};import{Server as Pe}from"net-ipc";var q=class{static{u(this,"WorkerThreadGatewayServer")}server=new Pe;rpc=new Map;register={};constructor(){this.server.on("connect",e=>{let t=new A(s=>e.send(s),this.register);this.rpc.set(e.id,t)}),this.server.on("disconnect",e=>{this.rpc.delete(e.id)}),this.server.on("message",(e,t)=>{let s=this.rpc.get(t.id);s&&s.make(e)}),this.server.on("error",e=>{console.error(e)})}async start(e,t={}){this.register=t,this.server.options.path=e;let s=new Promise(n=>{this.server.once("ready",()=>n(this))});return await this.server.start(),s}};import{parentPort as De,threadId as Oe,isMainThread as Fe}from"worker_threads";var ae=class{static{u(this,"WorkerThreadInit")}argv=process.argv;id=Oe;pid=process.pid;rpc={};parentPort=De;gatewayServer;gatewayClients=new Map;gatewayClientLatest;static gatewayServerPath;gatewayServerPath=this.constructor.gatewayServerPath;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=Fe;constructor(){this.init(),this.rpc=new A(this.send.bind(this),this),this.send({method:"readyResolve"})}init(){this.parentPort?.on("message",e=>this.handleOnMessage(e))}handleOnMessage(e){this.rpc.make(e)}send(e){this.parentPort?.postMessage(e)}request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}async createGatewayServer(e,t){return e||(e=this),t||(t=this.constructor.gatewayServerPath),this.gatewayServer=new q,await this.gatewayServer.start(t,e),this.constructor.gatewayServerPath=t,!0}async createGatewayClient(e){let t=new L;return await t.connect(e),this.gatewayClients.set(e,t),this.gatewayClientLatest=t,t}};var re=class{static{u(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(e){this.addMany(e)}add(e){this.thread.set(e.threadId,e),this.threadCount+=1}addMany(e){e.forEach(t=>this.add(t))}getInstance(e){return this.thread.get(e)}kill(e){let t=this.thread.get(e);return t?.kill(),this.thread.delete(e),this.threadCount-=1,t?.threadId}killAll(){this.thread.values().forEach(({threadId:e})=>this.kill(e))}async broadcastRequest(e,t){return await Promise.all(Object.values(this.thread).map(s=>s.request(e,t,!0)))}async request(e,t,s,n=!0,i){return await this.thread.get(e)?.request(t,s,n,i)}};var ce=class{static{u(this,"MockTelegramServer")}botToken="";hostname;port;log;handlers;defaultHandler;apiRoot="";webhookUrl="";requests=[];updates=[];server;_nextUpdateId=1;_nextMessageId=1;constructor(e={}){this.hostname=e.hostname??"127.0.0.1",this.port=e.port??0,this.log=e.log===!0?F:e.log?e.log:void 0,this.handlers=e.handlers??{},this.defaultHandler=e.defaultHandler}async start(){if(this.server)return this.apiRoot;let e=Bun.serve({port:this.port,hostname:this.hostname,fetch:u(async t=>this._handleRequest(t),"fetch")});return this.server=e,this.apiRoot=`http://${this.hostname}:${e.port??this.port}`,process.once("SIGINT",()=>this.stop()),process.once("SIGTERM",()=>this.stop()),this.log?.info?.(`Mock Telegram server started: ${this.apiRoot}`),this.apiRoot}async stop(){this.server?.stop(),this.server=void 0,this.log?.info?.("Mock Telegram server stopped")}_json(e){return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":"application/json"}})}lastRequest(e){if(!e)return this.requests[this.requests.length-1];for(let t=this.requests.length-1;t>=0;t--){let s=this.requests[t];if(s?.method===e)return s}}clearRequests(){this.requests.length=0}_defaultResponse(e,t){if(e==="getMe")return{ok:!0,result:{id:123456789,is_bot:!0,first_name:"Mock",username:"mock_gramstax_bot"}};if(e==="getUpdates")return{ok:!0,result:[]};if(e==="getMyCommands")return{ok:!0,result:[]};if(e==="setMyCommands")return{ok:!0,result:!0};if(e==="setWebhook"){let s=this._bodyRecord(t),n=typeof s?.url=="string"?s.url:"";return this.webhookUrl=n,this.log?.info?.(`Mock Telegram webhook set: ${n}`),{ok:!0,result:!0}}return e==="getWebhookInfo"?{ok:!0,result:{url:this.webhookUrl}}:{ok:!0,result:!0}}async _handleRequest(e){let{pathname:t}=new URL(e.url),s=t.match(/^\/bot([^/]+)\/(.+)$/);if(!s)return new Response("Not found",{status:404});let n=s[1],i=s[2];if(!n||!i)return new Response("Not found",{status:404});this.botToken=n;let o=await this._readBody(e.clone());this.log?.debug?.(`Mock Telegram API request: ${i}`),this.requests.push({method:i,body:o,url:e.url,requestMethod:e.method,headers:Object.fromEntries(e.headers.entries())});let a=this.handlers[i]??this.defaultHandler,r=a?await a({method:i,request:e}):this._defaultResponse(i,o);return this._json(r)}_bodyRecord(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}async _readBody(e){if(e.method==="GET"||e.method==="HEAD")return;let t=e.headers.get("content-type")||"";try{if(t.includes("application/json"))return await e.json();if(t.includes("multipart/form-data")||t.includes("application/x-www-form-urlencoded")){let n=await e.formData();return Object.fromEntries(n.entries())}let s=await e.text();if(!s)return;try{return JSON.parse(s)}catch{return s}}catch{return}}_defaultUser(e){return{id:e?.id??1001,is_bot:e?.is_bot??!1,first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.username?{username:e.username}:{},language_code:e?.language_code??"en"}}_defaultChat(e){return{id:e?.id??1001,type:e?.type??"private",first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.username?{username:e.username}:{},...e?.title?{title:e.title}:{}}}_nextIds(e){return{updateId:this._nextUpdateId++,messageId:e?.message_id??this._nextMessageId++,date:e?.date??Math.floor(Date.now()/1e3)}}_buildMessageUpdate(e,t){let{updateId:s,messageId:n,date:i}=this._nextIds(t);return{update_id:s,message:{message_id:n,date:i,chat:this._defaultChat(t?.chat),from:this._defaultUser(t?.user),...e}}}async _postUpdate(e,t){if(await this._waitForWebhookUrl(t?.responseTimeoutMs??1e3),!this.webhookUrl)throw new Error("Webhook URL is not set. Call setWebhook first or assign mockServer.webhookUrl.");let s=this.requests.length;this.updates.push(e),this.log?.info?.(`Mock Telegram update sent: ${this.webhookUrl}`);let n=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`Webhook request failed with status ${n.status}`);let i=await this._waitForResponses(s,t?.responseTimeoutMs??1e3);return this.log?.info?.(`Mock Telegram bot responses captured: ${i.length}`),i}async _waitForWebhookUrl(e){if(this.webhookUrl||e<=0)return this.webhookUrl;let t=Date.now();for(;Date.now()-t<e&&(await new Promise(s=>setTimeout(s,5)),!this.webhookUrl););return this.webhookUrl}async _waitForResponses(e,t){if(t<=0)return this._userResponseRequests(e);if(this._userResponseRequests(e).length>0)return this._userResponseRequests(e);let s=Date.now();for(;Date.now()-s<t&&(await new Promise(n=>setTimeout(n,5)),!(this._userResponseRequests(e).length>0)););return this._userResponseRequests(e)}_userResponseRequests(e){return this.requests.slice(e).filter(t=>this._isUserResponseMethod(t.method))}_isUserResponseMethod(e){return e.startsWith("send")||e.startsWith("edit")||e.startsWith("answer")||e.startsWith("delete")||e.startsWith("copy")||e.startsWith("forward")||e==="pinChatMessage"||e==="unpinChatMessage"||e==="setMessageReaction"}async sendText(e,t){let s=e.startsWith("/")?[{offset:0,length:e.split(" ")[0]?.length??e.length,type:"bot_command"}]:void 0;return await this._postUpdate(this._buildMessageUpdate({text:e,...s?{entities:s}:{}},t),t)}async sendPhoto(e){return await this._postUpdate(this._buildMessageUpdate({photo:[{file_id:"mock-photo-file-id",file_unique_id:"mock-photo-unique-id",width:1,height:1}],...e?.caption?{caption:e.caption}:{}},e),e)}async sendVideo(e){return await this._postUpdate(this._buildMessageUpdate({video:{file_id:"mock-video-file-id",file_unique_id:"mock-video-unique-id",width:1,height:1,duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendAudio(e){return await this._postUpdate(this._buildMessageUpdate({audio:{file_id:"mock-audio-file-id",file_unique_id:"mock-audio-unique-id",duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendDocument(e){return await this._postUpdate(this._buildMessageUpdate({document:{file_id:"mock-document-file-id",file_unique_id:"mock-document-unique-id",file_name:"mock.txt"},...e?.caption?{caption:e.caption}:{}},e),e)}async sendAnimation(e){return await this._postUpdate(this._buildMessageUpdate({animation:{file_id:"mock-animation-file-id",file_unique_id:"mock-animation-unique-id",width:1,height:1,duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendVoice(e){return await this._postUpdate(this._buildMessageUpdate({voice:{file_id:"mock-voice-file-id",file_unique_id:"mock-voice-unique-id",duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendVideoNote(e){return await this._postUpdate(this._buildMessageUpdate({video_note:{file_id:"mock-video-note-file-id",file_unique_id:"mock-video-note-unique-id",length:1,duration:1}},e),e)}async sendSticker(e){return await this._postUpdate(this._buildMessageUpdate({sticker:{file_id:"mock-sticker-file-id",file_unique_id:"mock-sticker-unique-id",type:"regular",width:1,height:1,is_animated:!1,is_video:!1}},e),e)}async sendLocation(e){return await this._postUpdate(this._buildMessageUpdate({location:{latitude:e?.latitude??0,longitude:e?.longitude??0}},e),e)}async sendContact(e){return await this._postUpdate(this._buildMessageUpdate({contact:{phone_number:e?.phone_number??"+10000000000",first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.user_id?{user_id:e.user_id}:{}}},e),e)}async sendCallbackQuery(e,t){let{updateId:s,messageId:n,date:i}=this._nextIds(t);return await this._postUpdate({update_id:s,callback_query:{id:t?.id??`mock-callback-${s}`,from:this._defaultUser(t?.user),message:{message_id:n,date:i,chat:this._defaultChat(t?.chat),text:t?.messageText??"Mock message"},chat_instance:"mock-chat-instance",data:e}},t)}};export{ne as BlockKeyboard,B as CacheExternal,W as Ctx,te as Gramstax,ie as LabelKeyboard,N as LoggingHelper,ce as MockTelegramServer,x as PageManager,M as TemplateEngine,V as TemplateManager,K as WebhookQueue,oe as WorkerThreadExport,L as WorkerThreadGatewayClient,q as WorkerThreadGatewayServer,ae as WorkerThreadInit,E as WorkerThreadLaunch,re as WorkerThreadPool,A as WorkerThreadRpc,F as log};
|
|
1
|
+
var he=Object.defineProperty;var u=(g,e)=>he(g,"name",{value:e,configurable:!0}),U=(g=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(g,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):g)(function(g){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+g+'" is not supported')});import $e from"path";import{fileURLToPath as me}from"url";var pe=u(()=>me(import.meta.url),"getFilename");var f=pe();import{LoggingPretty as ue}from"logging-pretty";var N=class extends ue{static{u(this,"LoggingHelper")}timers=new Map;constructor(e){super(e)}errorMake(e,t,s){this.error(`[${t?`${t}:${s}`:s}] ${this._formatErrorObj(e)}`)}_formatErrorObj(e){return JSON.stringify(e instanceof Error?{message:e.message,stack:e.stack,name:e.name}:e,null,2)}time(e){this.timers.set(e,process.hrtime.bigint())}timeEnd(e,t){let s=this.timers.get(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}let n=(Number(process.hrtime.bigint()-s)/1e6).toFixed(3);this.timers.delete(e),t?this.debug(`${t} (took ${n}ms)`):this.debug(`${e} (took ${n}ms)`)}timeCheck(e){let t=this.timers.get(e);if(t!==void 0)return(Number(process.hrtime.bigint()-t)/1e6).toFixed(3)}timeLog(e,t){let s=this.timeCheck(e);if(s===void 0){this.debug(`${e}: Timer was never started`);return}t?this.debug(`${t} (${s}ms)`):this.debug(`${e} (${s}ms)`)}timeClear(){this.timers.clear()}timeActive(){return Array.from(this.timers.keys())}},F=new N;import{Keyv as ge}from"keyv";import ye from"@keyv/redis";var B=class extends ge{constructor(t="memory",s,n,i){let o;t.startsWith("redis")&&(o=new ye(t)),t==="memory"&&(o=new Map),i?.forceStore&&(o=i.forceStore);super({store:o,namespace:n,ttl:s});this.url=t}url;static{u(this,"CacheExternal")}refreshLruCache(t){let s=this.store,n=this.opts.namespace?this.opts.namespace?.length+1:null,i=s.keys().toArray();for(let o=0;o<i.length;o++){let a=i[o];if(o==t)return;this.get(n?a.slice(n):a)}}};import{setTimeout as H}from"timers/promises";import{InlineKeyboard as J,Keyboard as z}from"grammy";var W=class{static{u(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(e){this.ct.from.language_code=e}get msgText(){return this.ct.message?.text}get msgTextArgs(){return this.getArgs(this.msgText,"space",this.data?._positionArgText||this.temp?.data?._positionArgText)}get msgTextArg(){return this.msgTextArgs[0]}get msgTextCommandArgs(){return this.getArgs(this.msgText,"space")}get msgTextCommandArg(){return this.msgTextCommandArgs[0]}get msgCaption(){return this.ct.message?.caption}get msgCaptionArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionArg(){return this.msgCaptionArgs[0]}get msgCaptionCommandArgs(){return this.getArgs(this.msgCaption,"space")}get msgCaptionCommandArg(){return this.msgCaptionCommandArgs[0]}get msgPhoto(){return this.ct.message?.photo}get msgVideo(){return this.ct.message?.video}get msgAudio(){return this.ct.message?.audio}get msgDocument(){return this.ct.message?.document}get msgAnimation(){return this.ct.message?.animation}get msgVoice(){return this.ct.message?.voice}get msgVideoNote(){return this.ct.message?.video_note}get msgSticker(){return this.ct.message?.sticker}get msgLocation(){return this.ct.message?.location}get msgContact(){return this.ct.message?.contact}get msgWebAppData(){return this.ct.message?.web_app_data}get msgGift(){return this.ct.message?.gift}get callbackData(){return this.ct.callbackQuery?.data}get callbackDataArgs(){return this.getArgs(this.callbackData,"colon")}get callbackDataArg(){return this.callbackDataArgs?.[0]}ct;cacheSession;cacheKeyboard;templateManager;temp;constructor(e){this.ct=e.ct,this.cacheSession=e.cacheSession,this.cacheKeyboard=e.cacheKeyboard,this.templateManager=e.templateManager,this.temp=e.temp}async broadcast(e,t,s,n,i,o,a=!1){let r={successCount:0,failedCount:0,totalCount:0};r.totalCount=e.length;try{this.temp.isAnswer=!0;let c=30,l=t.map(d=>this.templateManager.getMessage(this.data.name,i,d,n));for(let d=0;d<e.length;d++){let h=e[d],m=l[d];await this.ct.api.sendMessage(h,m,{parse_mode:"HTML",reply_markup:s,...o}),r.successCount+=1,d+1==c&&await H(1200)}}catch(c){if(r.failedCount+=1,a)throw{...r,err:c}}return r}async broadcastMedia(e,t,s,n,i,o,a=!1){let r={successCount:0,failedCount:0,totalCount:0};r.totalCount=e.length;try{this.temp.isAnswer=!0;let c=30,l=t.map(d=>this.templateManager.getMedia(this.data.name,i,d,n));for(let d=0;d<e.length;d++){let h=e[d],m=l[d];if(!m)continue;let p={parse_mode:"HTML",reply_markup:s,...o};m.type=="photo"&&await this.ct.api.sendPhoto(h,m.src,{caption:m.caption,...p}),m.type=="video"&&await this.ct.api.sendVideo(h,m.src,{caption:m.caption,...p}),m.type=="audio"&&await this.ct.api.sendAudio(h,m.src,{caption:m.caption,...p}),m.type=="document"&&await this.ct.api.sendDocument(h,m.src,{caption:m.caption,...p}),m.type=="animation"&&await this.ct.api.sendAnimation(h,m.src,{caption:m.caption,...p}),m.type=="voice"&&await this.ct.api.sendVoice(h,m.src,p),m.type=="video_note"&&await this.ct.api.sendVideoNote(h,m.src,p),m.type=="sticker"&&await this.ct.api.sendSticker(h,m.src,p),m.type=="location"&&await this.ct.api.sendLocation(h,parseInt(m.latitude),parseInt(m.longitude),p),m.type=="contact"&&await this.ct.api.sendContact(h,m.phone,m.first_name,{vcard:m.vcard,...p}),r.successCount+=1,d+1==c&&await H(1200)}}catch(c){if(r.failedCount+=1,a)throw{...r,err:c}}return r}async reply(e,t,s,n){this.temp.isAnswer=!0;let i=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.reply(i,{parse_mode:"HTML",reply_markup:e,...n})}async replyMedia(e,t,s,n,i){this.temp.isAnswer=!0;let o=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s),a={parse_mode:"HTML",reply_markup:t,...i};if(e=="photo")return await this.ct.replyWithPhoto(o.src,{caption:o.caption,...a});if(e=="video")return await this.ct.replyWithVideo(o.src,{caption:o.caption,...a});if(e=="audio")return await this.ct.replyWithAudio(o.src,{caption:o.caption,...a});if(e=="document")return await this.ct.replyWithDocument(o.src,{caption:o.caption,...a});if(e=="animation")return await this.ct.replyWithAnimation(o.src,{caption:o.caption,...a});if(e=="voice")return await this.ct.replyWithVoice(o.src,a);if(e=="video_note")return await this.ct.replyWithVideoNote(o.src,a);if(e=="sticker")return await this.ct.replyWithSticker(o.src,a);if(e=="location")return await this.ct.replyWithLocation(parseInt(o.latitude),parseInt(o.longitude),a);if(e=="contact")return await this.ct.replyWithContact(o.phone,o.first_name,{vcard:o.vcard,...a})}async replyPhoto(e,t,s,n){return this.replyMedia("photo",e,t,s,n)}async replyVideo(e,t,s,n){return this.replyMedia("video",e,t,s,n)}async replyAudio(e,t,s,n){return this.replyMedia("audio",e,t,s,n)}async replyDocument(e,t,s,n){return this.replyMedia("document",e,t,s,n)}async replyAnimation(e,t,s,n){return this.replyMedia("animation",e,t,s,n)}async replyVoice(e,t,s,n){return this.replyMedia("voice",e,t,s,n)}async replyVideoNote(e,t,s,n){return this.replyMedia("video_note",e,t,s,n)}async replySticker(e,t,s,n){return this.replyMedia("sticker",e,t,s,n)}async replyLocation(e,t,s,n){return this.replyMedia("location",e,t,s,n)}async replyContact(e,t,s,n){return this.replyMedia("contact",e,t,s,n)}async replyAction(e){return await this.ct.replyWithChatAction(e)}async edit(e,t,s,n,i=!0){try{this.temp.isAnswer=!0;let o=this.templateManager.getMessage(this.data.name,s,this.userLanguage,t);return await this.ct.editMessageText(o,{parse_mode:"HTML",reply_markup:e,...n})}catch(o){if(i)await this.reply(e,t,s,n);else throw o}}async editMedia(e,t,s,n,i,o,a=!0){try{this.temp.isAnswer=!0;let{src:r,caption:c}=this.templateManager.getMedia(this.data.name,n,this.userLanguage,s);return e=="voice"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="video_note"?(await this.delete(),await this.replyVoice(t,s,n,i)):e=="sticker"?(await this.delete(),await this.replySticker(t,s,n,i)):e=="location"?(await this.delete(),await this.replyLocation(t,s,n,i)):e=="contact"?(await this.delete(),await this.replyContact(t,s,n,i)):await this.ct.editMessageMedia({media:r,caption:c,type:e,parse_mode:"HTML",...i},{reply_markup:t,...o})}catch(r){if(a===!0)await this.reply(t,s,n,o);else throw r}}async editPhoto(e,t,s,n,i){return await this.editMedia("photo",e,t,s,n,i)}async editVideo(e,t,s,n,i){return await this.editMedia("video",e,t,s,n,i)}async editAudio(e,t,s,n,i){return await this.editMedia("audio",e,t,s,n,i)}async editDocument(e,t,s,n,i){return await this.editMedia("document",e,t,s,n,i)}async editAnimation(e,t,s,n,i){return await this.editMedia("animation",e,t,s,n,i)}async editVoice(e,t,s,n){return await this.editMedia("voice",e,t,s,n)}async editVideoNote(e,t,s,n){return await this.editMedia("video_note",e,t,s,n)}async editSticker(e,t,s,n){return await this.editMedia("sticker",e,t,s,n)}async editLocation(e,t,s,n){return await this.editMedia("location",e,t,s,n)}async editContact(e,t,s,n){return await this.editMedia("contact",e,t,s,n)}async delete(){return await this.ct.deleteMessage()}async callbackQueryAnswer(e){try{return this.temp.isAnswer=!0,await this.ct.answerCallbackQuery(e)}catch{return null}}async setSession(e,t,s){try{let n={method:e,params:t,...s},i=await this.cacheSession.set(`${this.userId}`,n);return i&&(this.temp.session=n),i}catch{return null}}async getSession(){try{let e=await this.cacheSession.get(`${this.userId}`);return e&&(this.temp.session=e),e||null}catch{return null}}async clearSession(){try{let e=await this.cacheSession.delete(`${this.userId}`);return e&&(this.temp.session={}),e}catch{return null}}static buildData(e){let s=typeof e=="function"?{callbackData:e}:e||{},n=s.callbackData,i=this.prototype.addArgs.bind(this.prototype),o=s.name||"";return{name:o,intentText:s.intentText||o,intentCommandText:s.intentCommandText||o,intentCallbackData:o,callbackData:n?function(...r){return i(this.intentCallbackData,"colon",n(...r))}:function(){return this?.intentCallbackData},_positionArgText:s.intentText?s.intentText.split(this.prototype.getSeperatorTag("space")).length:void 0}}keyboardCols(e,t,s,n){let[i,o]=s.split("-"),a=parseInt(i),r=o?parseInt(o):null,c=t.length,l=e;for(let d=0;d<c;d++){let h=t[d];if(n(h,d),r===null)(d+1)%a===0&&d<c-1&&l.row();else{let m=c-(d+1);(m===r||m>r&&(d+1)%a===0)&&l.row()}}return e}bottomKeyboardT(e="1",t,s){return this.bottomKeyboard((n,i)=>this.keyboardCols(n,i,e,o=>n.text(o)),{baseId:t??void 0,data:s})}inlineKeyboardT(e,t="1",s,n){return this.inlineKeyboard((i,o)=>this.keyboardCols(i,o,t,(a,r)=>{let c=e[r],l=typeof c=="string"?c:c.data.callbackData();i.text(a,l)}),{baseId:s??void 0,data:n})}inlineKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let a=`${s}:${this.userLanguage}:i`,r=this.cacheKeyboard.get(a);if(!r){let c=new J,l=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data),d=e(c,l);return this.cacheKeyboard.set(a,d),d}return r}let n=new J,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"inline",t?.data);return e(n,i)}bottomKeyboard(e,t){let s=this.data.name;if(t?.cache===!0){let a=`${s}:${this.userLanguage}:b`,r=this.cacheKeyboard.get(a);if(!r){let c=new z,l=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),d=e(c,l);return d.resized(!0),this.cacheKeyboard.set(a,d),d}return r}let n=new z,i=this.templateManager.getKeyboard(s,t?.baseId,this.userLanguage,"bottom",t?.data),o=e(n,i);return o.resized(),o}getSeperatorTag(e="space"){return e=="space"?" ":":"}haveArgs(e="",t){return e.includes(this.getSeperatorTag(t))}addArgs(e="",t,s){let n=this.getSeperatorTag(t),i="";for(let o=0;o<s.length;o++){let a=s[o];a!=null&&a!==""&&(i+=n+a)}return e+i}getArgs(e="",t,s=1){if(!e)return[];let n=this.getSeperatorTag(t);return e.split(n).slice(s)}getIntent(e="",t,s=1){if(!e)return"";let n=this.getSeperatorTag(t),i=e.split(n);return s==1?i[0]:i.slice(0,s).join(n)}isSessionCallbackData(){return this.temp.session.method===this.methodSessionCallbackData()}isSessionArgsCallbackData(){return this.temp.session.method===this.methodSessionArgsCallbackData()}isSessionText(){return this.temp.session.method===this.methodSessionText()}isSessionArgsText(){return this.temp.session.method===this.methodSessionArgsText()}isSessionCommandText(){return this.temp.session.method===this.methodSessionCommandText()}isSessionCommandArgsText(){return this.temp.session.method===this.methodSessionCommandArgsText()}isSessionFreeText(){return this.temp.session.method===this.methodSessionFreeText()}isSessionCaptionPhoto(){return this.temp.session.method===this.methodSessionCaptionPhoto()}isSessionCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCaptionArgsPhoto()}isSessionCommandCaptionPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionPhoto()}isSessionCommandCaptionArgsPhoto(){return this.temp.session.method===this.methodSessionCommandCaptionArgsPhoto()}isSessionFreePhoto(){return this.temp.session.method===this.methodSessionFreePhoto()}isSessionCaptionVideo(){return this.temp.session.method===this.methodSessionCaptionVideo()}isSessionCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCaptionArgsVideo()}isSessionCommandCaptionVideo(){return this.temp.session.method===this.methodSessionCommandCaptionVideo()}isSessionCommandCaptionArgsVideo(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVideo()}isSessionFreeVideo(){return this.temp.session.method===this.methodSessionFreeVideo()}isSessionCaptionAudio(){return this.temp.session.method===this.methodSessionCaptionAudio()}isSessionCaptionArgsAudio(){return this.temp.session.method===this.methodSessionCaptionArgsAudio()}isSessionCaptionCommandAudio(){return this.temp.session.method===this.methodSessionCaptionCommandAudio()}isSessionCaptionCommandArgsAudio(){return this.temp.session.method===this.methodSessionCaptionCommandArgsAudio()}isSessionFreeAudio(){return this.temp.session.method===this.methodSessionFreeAudio()}isSessionCaptionDocument(){return this.temp.session.method===this.methodSessionCaptionDocument()}isSessionCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCaptionArgsDocument()}isSessionCommandCaptionDocument(){return this.temp.session.method===this.methodSessionCommandCaptionDocument()}isSessionCommandCaptionArgsDocument(){return this.temp.session.method===this.methodSessionCommandCaptionArgsDocument()}isSessionFreeDocument(){return this.temp.session.method===this.methodSessionFreeDocument()}isSessionCaptionAnimation(){return this.temp.session.method===this.methodSessionCaptionAnimation()}isSessionCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCaptionArgsAnimation()}isSessionCommandCaptionAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionAnimation()}isSessionCommandCaptionArgsAnimation(){return this.temp.session.method===this.methodSessionCommandCaptionArgsAnimation()}isSessionFreeAnimation(){return this.temp.session.method===this.methodSessionFreeAnimation()}isSessionCaptionVoice(){return this.temp.session.method===this.methodSessionCaptionVoice()}isSessionCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCaptionArgsVoice()}isSessionCommandCaptionVoice(){return this.temp.session.method===this.methodSessionCommandCaptionVoice()}isSessionCommandCaptionArgsVoice(){return this.temp.session.method===this.methodSessionCommandCaptionArgsVoice()}isSessionFreeVoice(){return this.temp.session.method===this.methodSessionFreeVoice()}isSessionFreeVideoNote(){return this.temp.session.method===this.methodSessionFreeVideoNote()}isSessionFreeSticker(){return this.temp.session.method===this.methodSessionFreeSticker()}isSessionFreeLocation(){return this.temp.session.method===this.methodSessionFreeLocation()}isSessionFreeContact(){return this.temp.session.method===this.methodSessionFreeContact()}sessionCallbackData(e){return this.setSession(this.methodSessionCallbackData(),e)}sessionArgsCallbackData(e){return this.setSession(this.methodSessionArgsCallbackData(),e)}sessionText(e){return this.setSession(this.methodSessionText(),e)}sessionArgsText(e){return this.setSession(this.methodSessionArgsText(),e)}sessionCommandText(e){return this.setSession(this.methodSessionCommandText(),e)}sessionCommandArgsText(e){return this.setSession(this.methodSessionCommandArgsText(),e)}sessionFreeText(e){return this.setSession(this.methodSessionFreeText(),e)}sessionCaptionPhoto(e){return this.setSession(this.methodSessionCaptionPhoto(),e)}sessionCaptionArgsPhoto(e){return this.setSession(this.methodSessionCaptionArgsPhoto(),e)}sessionCommandCaptionPhoto(e){return this.setSession(this.methodSessionCommandCaptionPhoto(),e)}sessionCommandCaptionArgsPhoto(e){return this.setSession(this.methodSessionCommandCaptionArgsPhoto(),e)}sessionFreePhoto(e){return this.setSession(this.methodSessionFreePhoto(),e)}sessionCaptionVideo(e){return this.setSession(this.methodSessionCaptionVideo(),e)}sessionCaptionArgsVideo(e){return this.setSession(this.methodSessionCaptionArgsVideo(),e)}sessionCommandCaptionVideo(e){return this.setSession(this.methodSessionCommandCaptionVideo(),e)}sessionCommandCaptionArgsVideo(e){return this.setSession(this.methodSessionCommandCaptionArgsVideo(),e)}sessionFreeVideo(e){return this.setSession(this.methodSessionFreeVideo(),e)}sessionCaptionAudio(e){return this.setSession(this.methodSessionCaptionAudio(),e)}sessionCaptionArgsAudio(e){return this.setSession(this.methodSessionCaptionArgsAudio(),e)}sessionCaptionCommandAudio(e){return this.setSession(this.methodSessionCaptionCommandAudio(),e)}sessionCaptionCommandArgsAudio(e){return this.setSession(this.methodSessionCaptionCommandArgsAudio(),e)}sessionFreeAudio(e){return this.setSession(this.methodSessionFreeAudio(),e)}sessionCaptionDocument(e){return this.setSession(this.methodSessionCaptionDocument(),e)}sessionCaptionArgsDocument(e){return this.setSession(this.methodSessionCaptionArgsDocument(),e)}sessionCommandCaptionDocument(e){return this.setSession(this.methodSessionCommandCaptionDocument(),e)}sessionCommandCaptionArgsDocument(e){return this.setSession(this.methodSessionCommandCaptionArgsDocument(),e)}sessionFreeDocument(e){return this.setSession(this.methodSessionFreeDocument(),e)}sessionCaptionAnimation(e){return this.setSession(this.methodSessionCaptionAnimation(),e)}sessionCaptionArgsAnimation(e){return this.setSession(this.methodSessionCaptionArgsAnimation(),e)}sessionCommandCaptionAnimation(e){return this.setSession(this.methodSessionCommandCaptionAnimation(),e)}sessionCommandCaptionArgsAnimation(e){return this.setSession(this.methodSessionCommandCaptionArgsAnimation(),e)}sessionFreeAnimation(e){return this.setSession(this.methodSessionFreeAnimation(),e)}sessionCaptionVoice(e){return this.setSession(this.methodSessionCaptionVoice(),e)}sessionCaptionArgsVoice(e){return this.setSession(this.methodSessionCaptionArgsVoice(),e)}sessionCommandCaptionVoice(e){return this.setSession(this.methodSessionCommandCaptionVoice(),e)}sessionCommandCaptionArgsVoice(e){return this.setSession(this.methodSessionCommandCaptionArgsVoice(),e)}sessionFreeVoice(e){return this.setSession(this.methodSessionFreeVoice(),e)}sessionFreeVideoNote(e){return this.setSession(this.methodSessionFreeVideoNote(),e)}sessionFreeSticker(e){return this.setSession(this.methodSessionFreeSticker(),e)}sessionFreeLocation(e){return this.setSession(this.methodSessionFreeLocation(),e)}sessionFreeContact(e){return this.setSession(this.methodSessionFreeContact(),e)}methodSession(e,t){return`${e}-${t||this.data.name}`}methodSessionCallbackData(e){return this.methodSession("1",e)}methodSessionArgsCallbackData(e){return this.methodSession("2",e)}methodSessionText(e){return this.methodSession("3",e)}methodSessionArgsText(e){return this.methodSession("4",e)}methodSessionCommandText(e){return this.methodSession("5",e)}methodSessionCommandArgsText(e){return this.methodSession("6",e)}methodSessionFreeText(e){return this.methodSession("7",e)}methodSessionCaptionPhoto(e){return this.methodSession("8",e)}methodSessionCaptionArgsPhoto(e){return this.methodSession("9",e)}methodSessionCommandCaptionPhoto(e){return this.methodSession("10",e)}methodSessionCommandCaptionArgsPhoto(e){return this.methodSession("11",e)}methodSessionFreePhoto(e){return this.methodSession("12",e)}methodSessionCaptionVideo(e){return this.methodSession("13",e)}methodSessionCaptionArgsVideo(e){return this.methodSession("14",e)}methodSessionCommandCaptionVideo(e){return this.methodSession("15",e)}methodSessionCommandCaptionArgsVideo(e){return this.methodSession("16",e)}methodSessionFreeVideo(e){return this.methodSession("17",e)}methodSessionCaptionAudio(e){return this.methodSession("18",e)}methodSessionCaptionArgsAudio(e){return this.methodSession("19",e)}methodSessionCaptionCommandAudio(e){return this.methodSession("20",e)}methodSessionCaptionCommandArgsAudio(e){return this.methodSession("21",e)}methodSessionFreeAudio(e){return this.methodSession("22",e)}methodSessionCaptionDocument(e){return this.methodSession("23",e)}methodSessionCaptionArgsDocument(e){return this.methodSession("24",e)}methodSessionCommandCaptionDocument(e){return this.methodSession("25",e)}methodSessionCommandCaptionArgsDocument(e){return this.methodSession("26",e)}methodSessionFreeDocument(e){return this.methodSession("27",e)}methodSessionCaptionAnimation(e){return this.methodSession("28",e)}methodSessionCaptionArgsAnimation(e){return this.methodSession("29",e)}methodSessionCommandCaptionAnimation(e){return this.methodSession("30",e)}methodSessionCommandCaptionArgsAnimation(e){return this.methodSession("31",e)}methodSessionFreeAnimation(e){return this.methodSession("32",e)}methodSessionCaptionVoice(e){return this.methodSession("33",e)}methodSessionCaptionArgsVoice(e){return this.methodSession("34",e)}methodSessionCommandCaptionVoice(e){return this.methodSession("35",e)}methodSessionCommandCaptionArgsVoice(e){return this.methodSession("36",e)}methodSessionFreeVoice(e){return this.methodSession("37",e)}methodSessionFreeVideoNote(e){return this.methodSession("38",e)}methodSessionFreeSticker(e){return this.methodSession("39",e)}methodSessionFreeLocation(e){return this.methodSession("40",e)}methodSessionFreeContact(e){return this.methodSession("41",e)}};import{join as j}from"path";import{existsSync as X,readdirSync as Y}from"fs";import{createRequire as fe}from"module";var x=class{static{u(this,"PageManager")}static _getFile(e,t,s=0){let i=Object.values(e)[s];if(i===void 0)throw new Error(`File ${t} must have export (not default) class page`);return i}static getFilePath(){return j(process.cwd(),"src","pages")}static getFileSync(e,t=0){e||(e=this.getFilePath());let n=fe(e)(e);return this._getFile(n,e,t)}static async getFile(e,t=0){e||(e=this.getFilePath());let s=await import(`${e}?t=${Date.now()}`);return this._getFile(s,e,t)}static getFileManySync(e,t=0){if(e||(e=this.getFilePath()),!X(e))throw new Error(`Directory ${e} is not found, please make it manually`);return Y(e).map(n=>{let i=j(e,n);return{path:i,page:this.getFileSync(i,t)}})}static clearCacheRequire(e){if(e||(e=this.getFilePath()),!X(e))throw new Error(`Directory ${e} is not found, please make it manually`);return Y(e).forEach(s=>{let n=j(e,s);delete U.cache[U.resolve(n)]}),!0}};import{readFileSync as ke}from"fs";import{fileURLToPath as Se}from"url";import{dirname as we,join as se,parse as _e}from"path";import{basename as Q,join as R,extname as Z}from"path";import{readdirSync as be,readFileSync as $,existsSync as v,statSync as O,writeFileSync as Te}from"fs";import{watch as Ce}from"chokidar";var M=class g{static{u(this,"TemplateEngine")}static ALLOWED_BLOCKS=["<base>","<message>","<keyboard>","<media>","<description>","<script>","<switch>","<case>","<default>","<map>","<div>","<import/>","<space/>","<b>","<i>","<u>","<s>","<code>","<pre>","<a>","<blockquote>","<blockquote expandable>"];static ALLOWED_SCOPE=["{{}}","{~~}"];static _escape(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`")}static _processScopeVariables(e){return e.replace(/\{\{(\w+)\}\}/g,(t,s)=>`\${(data && data["${s}"]) ?? ""}`)}static _processScopeExec(e){return e.replace(/{~\s*([\s\S]*?)\s*~}/g,(t,s)=>`\${(() => { try { return ${s} } catch(e) { try { with(data || {}) { return ${s} } } catch(ee) { return '' } } })()}`)}static _processBaseBlocks(e){let t=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,s={};for(let n of e.matchAll(t)){let i=n[2]??"default",a=(n[3]??"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[i]=a}return s}static _processScriptBlocks(e){return e.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi,(t,s)=>{let n=s.trim();return n?`\${(() => { if (!data) return ''; try { with(data) { ${n} } } catch(e) { return '' } })()}`:""})}static _processSpaceBlocks(e){return e.replace(/^[ \t]*<space\s*\/>[ \t]*$/gim,"")}static _processDivBlocks(e){return e.replace(/<div>([\s\S]*?)<\/div>/gi,(t,s)=>s.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,""))}static _processSwitchBlocks(e){let t=/<switch\b(?:\s+value="([^"]+)")?>([\s\S]*?)<\/switch>/gi;return e.replace(t,(s,n,i)=>{if(!n)return"";let o="",a=/<case\b(?:\s+is="([^"]+)")?>([\s\S]*?)<\/case>/gi,r=/<default>([\s\S]*?)<\/default>/gi,c;for(;(c=a.exec(i))!==null;){let d=(c[1]||"").split(",").map(m=>m.trim()),h=(c[2]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim().replace(/`/g,"\\`");d.forEach(m=>{o+=`case "${m}": `}),o+=`return \`${h}\`; `}let l=r.exec(i);if(l){let d=(l[1]||"").replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();o+=`default: return \`${d}\`; `}else o+="default: return ''; ";return`\${(() => { switch((data && data["${n}"])) { ${o} } })()}`})}static _processMapBlocks(e){let t=/<map(?:\s+([^>]*))?>([\s\S]*?)<\/map>/gi;return e.replace(t,(s,n,i)=>{let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let h of n.matchAll(a))o[h[1]]=h[2];let r=o.src;if(!r)return"";let c=o.join??"\\n",l=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").replace(/`/g,"\\`");l=l.replace(/\{\{([\w.]+)\}\}/g,(h,m)=>m==="e"||m.startsWith("e.")?`\${${m}}`:m==="i"?"${i}":h);let d=c.replace(/"/g,'\\"');return`\${(() => { const __arr = (data && data["${r}"]) || []; let __out = ""; for (let i = 0; i < __arr.length; i++) { const e = __arr[i]; if (i > 0) { __out += "${d}" } __out += \`${l}\`; } return __out; })()}`})}static _processMediaBlocks(e){let t=/<media(?:\s+([^>]*))?>([\s\S]*?)<\/media>/gi,s={};for(let n of e.matchAll(t)){let i=n[1],o=n[2],a={},r=/(\w+)="([^"]*)"/g;if(i)for(let m of i.matchAll(r))a[m[1]]=m[2];let c=a.lang||"default",l=a.type,d=o.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim(),h={type:l};a.src&&(h.src=a.src),d&&l!=="video_note"&&l!=="sticker"&&(h.caption=d),l==="location"&&(a.latitude&&(h.latitude=a.latitude),a.longitude&&(h.longitude=a.longitude),d&&(h.caption=d)),l==="contact"&&(a.phone&&(h.phone=a.phone),a.first_name&&(h.first_name=a.first_name),a.last_name&&(h.last_name=a.last_name),a.vcard&&(h.vcard=a.vcard),d&&(h.caption=d)),s[c]=h}return s}static _processMessageBlocks(e){let t=/<message(?:\s+([^>]*))?>([\s\S]*?)<\/message>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let l of n.matchAll(a))o[l[1]]=l[2];let r=o.lang||"default",c=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]=c}return s}static _processDescriptionBlocks(e){let t=/<description(?:\s+([^>]*))?>([\s\S]*?)<\/description>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(a))o[d[1]]=d[2];let r=o.lang||"default",c=o.scope||"default",l=i.replace(/^[\t ]+/gm,"").replace(/^\n+/,"").replace(/\n+$/,"").trim();s[r]||(s[r]={}),s[r][c]=l}return s}static _processKeyboardBlocks(e){let t=/<keyboard(?:\s+([^>]*))?>([\s\S]*?)<\/keyboard>/gi,s={};for(let[,n,i]of e.matchAll(t)){let o={},a=/(\w+)="([^"]*)"/g;if(n)for(let d of n.matchAll(a))o[d[1]]=d[2];let r=o.lang||"default",c=o.type==="bottom"?"bottom":"inline",l=i.trim();s[r]||(s[r]={}),s[r][c]=l}return s}static _compileToFunction(e,t){let s;t?s=e.map(o=>`\`${o}\``).join(","):s=`\`${e}\``;let n=s;if(n=this._processScriptBlocks(this._processDivBlocks(this._processSpaceBlocks(n))),t){let i=`return [${n}]`;return new Function("data",i)}else{let i=`return ${n}`;return new Function("data",i)}}static compileBlockMedia(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processMediaBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){let l={};for(let[d,h]of Object.entries(c)){if(d==="type"||typeof h!="string")continue;let m=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(h)))));l[d]=this._compileToFunction(m,!1)}n[i][r]=d=>{let h={...c};for(let[m,p]of Object.entries(l))h[m]=p(d);return h}}}return n}static compileBlockMessage(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processMessageBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){let l=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(c)))));n[i][r]=this._compileToFunction(l,!1)}}return n}static compileBlockDescription(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processDescriptionBlocks(o);n[i]={};for(let[r,c]of Object.entries(a))for(let[l,d]of Object.entries(c)){n[i][l]||(n[i][l]={});let h=this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(d)))));n[i][l][r]=this._compileToFunction(h,!1)}}return n}static compileBlockKeyboards(e,t){let s=t||this._processBaseBlocks(e),n={};for(let[i,o]of Object.entries(s)){let a=this._processKeyboardBlocks(o);n[i]={};for(let[r,c]of Object.entries(a)){n[i][r]={};for(let[l,d]of Object.entries(c)){let m=d.split(/(?<!\\),\s*/).map(p=>p.replace(/\\,/g,",").trim()).map(p=>this._processScopeVariables(this._processScopeExec(this._processSwitchBlocks(this._processMapBlocks(this._processScriptBlocks(p))))));n[i][r][l]=this._compileToFunction(m,!0)}}}return n}static _extractBlock(e,t,s="default",n="all",i){let o=/<base\b[^>]*?(?:\sid=(["']?)([^"'\s>]+)\1)?[^>]*?>([\s\S]*?)<\/base>/g,a=e,r=!1;for(let c of e.matchAll(o))if((c[2]??"default")===s){a=c[3]??"",r=!0;break}if(!r){let c=/<base\b/.test(e);if(!(s==="default"&&!c))return""}if(t){if(t==="all")return a;let c=Array.isArray(t)?t:[t],l=[];for(let h of c){let m=new RegExp(`([ \\t]*)<${h}(?:\\s+([^>]*))?>([\\s\\S]*?)<\\/${h}>`,"gi");for(let p of a.matchAll(m)){let w=p[2];if(i){let C=/lang="([^"]*)"/i,_=w?.match(C);if(((_?_[1]:void 0)||"default")!==i)continue}l.push({start:p.index,content:p[0],innerContent:p[3]??""})}}l.sort((h,m)=>h.start-m.start);let d=u(h=>{let m=h.split(`
|
|
2
|
+
`);if(m.length<=1)return h.trim();let p=m.filter(C=>C.trim().length>0);if(p.length===0)return"";let w=p.reduce((C,_)=>{let S=_.match(/^([ \t]*)/),I=S?S[1].length:0;return I<C?I:C},1/0);return m.map(C=>C.length>=w?C.slice(w):C.trimStart()).join(`
|
|
3
|
+
`).trim()},"processResult");return n==="all"?l.map(m=>d(m.content)).join(`
|
|
4
|
+
`):l.map(m=>d(m.innerContent)).join(`
|
|
5
|
+
`)}return a}static _processImportBlocks(e){let t=/([ \t]*)<import(?:\s+([^>]*))?\/?>/gi,s=[];return{processed:e.replace(t,(i,o,a)=>{let r={},c=/(\w+)="([^"]*)"/g;if(a)for(let m of a.matchAll(c))r[m[1]]=m[2];let l=r.src;if(!l)return"";let d;r.block&&(r.block==="all"?d="all":r.block.includes(",")?d=r.block.split(",").map(m=>m.trim()).filter(m=>m):d=r.block);let h={src:l,blocks:d,base:r.base||"default",lang:r.lang,section:r.section||"all",indent:o||""};return s.push(h),`${o}__IMPORT_${s.length-1}__`}),imports:s}}static processImportBlocks(e,t,s=0,n){if(s>10)return"";let{processed:i,imports:o}=this._processImportBlocks(e),a=i;for(let r=0;r<o.length;r++){let c=o[r],l=`${c.src}|${c.base}|${c.lang||""}|${c.section}|${Array.isArray(c.blocks)?c.blocks.join(","):c.blocks||""}`,d;if(n&&n.has(l))d=n.get(l);else{let m=t(c.src);d=m?this._extractBlock(m,c.blocks,c.base,c.section,c.lang):"",d&&d.includes("<import")&&(d=this.processImportBlocks(d,t,s+1,n)),n&&n.set(l,d)}let h=d.split(`
|
|
6
|
+
`).map((m,p)=>p===0?m:c.indent+m).join(`
|
|
7
|
+
`);a=a.replace(`__IMPORT_${r}__`,h)}return a}static validateBlockNames(e){let t=[],s=new Set(g.ALLOWED_BLOCKS.map(o=>o.replace(/^<\/?/,"").replace(/\s.*?>$/,"").replace(/\/?>$/,"").toLowerCase())),n=new Set(["b","i","u","s","code","pre","a","blockquote"]),i=/<\/?\s*([a-z][\w-]*)(?:\s[^<>]*)?\/?\s*>/gi;for(let o of e.matchAll(i)){let a=o[1]?.toLowerCase();if(!a||n.has(a)||s.has(a))continue;let r=(e.slice(0,o.index).match(/\n/g)||[]).length+1;t.push({line:r,message:`Unsupported template block: <${a}>`})}return{valid:t.length===0,errors:t}}static validateScopes(e){let t=[],s=new Set(g.ALLOWED_SCOPE),n=/\{([^\s{}\w])([\s\S]*?)\1\}/g;for(let i of e.matchAll(n)){let o=`{${i[1]}${i[1]}}`;if(i[1]&&s.has(o))continue;let a=(e.slice(0,i.index).match(/\n/g)||[]).length+1,r=i[1]??"?";t.push({line:a,message:`Unsupported template scope: {${r} ${r}}`})}return{valid:t.length===0,errors:t}}static validateBlockPositions(e){let t=[],s=[],n=new Set(["b","i","u","s","code","pre","a","blockquote"]),i={base:new Set(["__root__"]),message:new Set(["base"]),keyboard:new Set(["base"]),media:new Set(["base"]),description:new Set(["base"]),switch:new Set(["message","keyboard","media","description"]),case:new Set(["switch"]),default:new Set(["switch"]),map:new Set(["message","keyboard","media","description"]),div:new Set(["base","message","description","keyboard","case","default","map"]),script:new Set(["base","message","description","keyboard","case","default","map","div"]),import:new Set(["base"]),space:new Set(["base","message","description","keyboard","case","default","switch","map","div"])},o=/<(\/?)(\w[\w-]*)([^>]*)>/g,a;for(;(a=o.exec(e))!==null;){let r=a[0],c=a[1],l=a[2].toLowerCase(),d=c==="/",h=!d&&r.endsWith("/>");if(n.has(l)||!i[l])continue;let m=(e.slice(0,a.index).match(/\n/g)||[]).length+1;if(d)if(s.length===0)t.push({line:m,message:`Unexpected closing tag </${l}>: no matching opening tag`});else{let p=s[s.length-1];p.block!==l?t.push({line:m,message:`Mismatched closing tag: expected </${p.block}> but found </${l}>`}):s.pop()}else if(h){let p=s.length>0?s[s.length-1].block:"__root__";i[l].has(p)||t.push({line:m,message:`Block <${l}> is not allowed inside <${p}>`})}else{let p=s.length>0?s[s.length-1].block:"__root__";i[l].has(p)||t.push({line:m,message:`Block <${l}> is not allowed inside <${p}>`}),s.push({block:l,line:m})}}for(let r of s)t.push({line:r.line,message:`Unclosed block <${r.block}>: missing closing tag </${r.block}>`});if(t.length===0){let r=[],c=/<base\b[^>]*>[\s\S]*?<\/base>/g,l;for(;(l=c.exec(e))!==null;)r.push({start:l.index,end:l.index+l[0].length});if(r.length===0&&e.trim())t.push({line:1,message:"Missing <base> block: template content must be wrapped in <base>...</base>"});else{let d=0;for(let h of r){if(h.start>d&&e.slice(d,h.start).trim()){let p=(e.slice(0,d).match(/\n/g)||[]).length+1;t.push({line:p,message:"Content found outside <base> block: move content inside a <base>...</base>"});break}d=h.end}if(t.length===0&&d<e.length&&e.slice(d).trim()){let h=(e.slice(0,d).match(/\n/g)||[]).length+1;t.push({line:h,message:"Content found outside <base> block: move content inside a <base>...</base>"})}}}return{valid:t.length===0,errors:t}}static validateBlockFormat(e){let t=[],s=new Set(["space","import"]),n=new Set(["base","message","keyboard","media","description","script","switch","case","default","map","div"]),i=/<(\/?)(\w[\w-]*)([^>]*)>/g,o;for(;(o=i.exec(e))!==null;){let a=o[0],r=o[1],c=o[2].toLowerCase(),l=r==="/",d=!l&&a.endsWith("/>");if(l)continue;let h=(e.slice(0,o.index).match(/\n/g)||[]).length+1;d?n.has(c)&&t.push({line:h,message:`Block <${c}> must not be self-closing: use <${c}>...</${c}> instead`}):s.has(c)&&t.push({line:h,message:`Block <${c}> must be self-closing: use <${c} /> instead`})}return{valid:t.length===0,errors:t}}static validateTemplate(e){let t=this.validateBlockNames(e),s=this.validateScopes(e),n=this.validateBlockFormat(e),i=this.validateBlockPositions(e),o=[...t.errors,...s.errors,...n.errors,...i.errors];return{valid:o.length===0,errors:o}}};var V=class{static{u(this,"TemplateManager")}_map=new Map;_engine=M;_watcher=[];_pageManager=x;_supportedExtensions=new Set([".html",".ts",".js"]);_path;_isWatchEnabled;constructor(e){let{path:t,enableWatch:s=!1}=e;this._path=t,this._isWatchEnabled=s,this._validatePath(),this._initializeWatcher(e.watchOptions),this._loadAllFiles()}_validatePath(){try{if(!this._path||!Array.isArray(this._path))throw new Error("Path must be set as string array");for(let e=0;e<this._path.length;e++){let t=this._path[e];if(!v(t))throw new Error(`Template base path is not exists: ${t}`);if(!O(t).isDirectory())throw new Error(`Template base path is not a directory: ${t}`)}return!0}catch(e){throw new Error(`Failed to validate Template base path: ${String(e)}`)}}_initializeWatcher(e){if(this._isWatchEnabled){if(this._watcher.length>0)throw new Error("Watcher already enabled");for(let t=0;t<this._path.length;t++){let s=this._path[t],n=Ce(s,{persistent:!0,ignoreInitial:!0,awaitWriteFinish:{stabilityThreshold:100,pollInterval:50},...e});this._watcher[t]=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(e){let t=Q(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileAdd(e){let t=Q(e);this._isValidFile(t)&&this._loadFile(t)}_handleFileDelete(e){let t=Q(e),s=this._getKey(t);this._map.has(s)&&this._map.delete(s)}_handleWatchError(e){}_loadAllFiles(){let e=new Map,t=new Map,s=[];for(let i=0;i<this._path.length;i++){let o=this._path[i],r=be(o,"utf8").filter(c=>this._isValidFile(c));for(let c of r){let l=R(o,c),d=this._getExtension(c),h=this._getKey(c);if(d===".html")e.set(h,$(l,"utf8")),t.set(h,c);else if(d===".ts"||d===".js"){let m=x.getFileSync(l);m?.template!==void 0&&(e.set(h,m.template),t.set(h,c),s.push(m))}}}let n=new Map;for(let[i,o]of e.entries())this._compile(i,o,void 0,n,e,t.get(i));e.clear(),n.clear();for(let i of s)i.template=void 0}_loadFile(e){for(let t=0;t<this._path.length;t++){let s=this._path[t],n=R(s,e),i=this._getExtension(e),o=this._getKey(e);if(i==".html"){let a=$(n,"utf8");this._compile(o,a,void 0,void 0,void 0,e)}else if(i==".ts"||i==".js"){let a=x.getFileSync(n);a?.template!==void 0&&(this._compile(o,a.template,void 0,void 0,void 0,e),a.template=void 0)}else throw new Error(`File ${e} is not support`)}}_getExtension(e){return Z(e).toLowerCase()}_readTemplateFile(e){for(let t of this._path){let s=Z(e).toLowerCase();if(s){let a=R(t,e);if(v(a)&&O(a).isFile()){if(s===".html")return $(a,"utf8");if(s===".ts"||s===".js")try{return x.getFileSync(a)?.template??null}catch{return null}}continue}let n=R(t,`${e}.ts`),i=R(t,`${e}.js`);if(v(n)&&O(n).isFile())try{return x.getFileSync(n)?.template??null}catch{}else if(v(i)&&O(i).isFile())try{return x.getFileSync(n)?.template??null}catch{}let o=R(t,`${e}.html`);if(v(o)&&O(o).isFile())return $(o,"utf8")}return null}_isValidFile(e){return this._supportedExtensions.has(this._getExtension(e))}_getBaseAtLine(e,t){let s=/<base\b([^>]*?)>/gi,n=/<\/base>/gi,i=t,o,a;for(;(o=s.exec(e))!==null&&!((e.slice(0,o.index).match(/\n/g)||[]).length+1>i);){let l=o[1].match(/\sid\s*=\s*(["']?)([^"'\s>]+)\1/i),d=l?.[2]??null,h=!!l;for(n.lastIndex||(n.lastIndex=s.lastIndex);(a=n.exec(e))!==null;){if((e.slice(0,a.index).match(/\n/g)||[]).length+1>i)return{baseId:d,hasId:h};s.lastIndex=n.lastIndex;break}}return null}_validateTemplate(e,t,s=e){let n=M.validateTemplate(t);if(!n.valid&&n.errors.length>0){let i=n.errors[0],o=this._getBaseAtLine(t,i.line),a=o?.hasId?` on base "${o.baseId}"`:"",r=`${s}, line ${i.line}`;throw new Error(`Template${a} (${r}): ${i.message}`)}}_getKey(e){return e.replace(/\.[^/.]+$/,"")}_compile(e,t,s,n,i,o=e){let a=this._map.get(e),r=a||{},c=!1;this._validateTemplate(e,t,o);let l=M.processImportBlocks(t,h=>i&&i.has(h)?i.get(h):this._readTemplateFile(h),0,n);this._validateTemplate(e,l,o);let d=M._processBaseBlocks(l);(s===void 0||s?.media===!1||a?.media===void 0)&&(r.media=M.compileBlockMedia(l,d),c=!0),(s===void 0||s?.message===!1||a?.message===void 0)&&(r.message=M.compileBlockMessage(l,d),c=!0),(s===void 0||s?.keyboard===!1||a?.keyboard===void 0)&&(r.keyboard=M.compileBlockKeyboards(l,d),c=!0),(s===void 0||s?.description===!1||a?.description===void 0)&&(r.description=M.compileBlockDescription(l,d),c=!0),c&&this._map.set(e,r)}getMedia(e,t="default",s="default",n){let o=this._map.get(e)?.media?.[t],a=o?.[s]||o?.default;try{if(!a)throw new Error("Media function not found, please check your template");return a(n)}catch{return{}}}getMessage(e,t="default",s="default",n){try{let o=this._map.get(e)?.message?.[t],a=o?.[s]||o?.default;if(!a)throw"";return a(n)}catch{return""}}getDescription(e,t="default",s="default",n="default",i){try{let a=this._map.get(e)?.description?.[t]?.[n],r=a?.[s]||a?.default;if(!r)throw"";return r(i)}catch{return""}}getDescriptionLanguage(e,t="default",s="default"){try{let i=this._map.get(e)?.description?.[t]?.[s];return i?Object.keys(i):[]}catch{return[]}}getDescriptionScopes(e,t="default"){try{let n=this._map.get(e)?.description?.[t];return n?Object.keys(n):[]}catch{return[]}}getKeyboard(e,t="default",s="default",n="inline",i){try{let a=this._map.get(e)?.keyboard?.[t],r=a?.[s]?.[n]||a?.default?.[n];if(!r)throw[];return r(i)}catch{return[]}}async write(e,t){if(this._getExtension(e)!=".html")return null;for(let s=0;s<this._path.length;s++){let n=R(this._path[s],e);if(v(n))return Te(n,t,"utf8"),this._loadFile(e),!0}return null}has(e){return this._map.has(e)}async destroy(){if(this._watcher)for(let e of this._watcher)await e.close();this._map.clear()}};import{Bot as Ie,webhookCallback as ee}from"grammy";var E=class{constructor(e){this.maxSize=e;if(!Number.isFinite(e)||e<=0)throw new Error("WebhookQueue maxSize must be a positive number")}maxSize;static{u(this,"WebhookQueue")}queue=[];waitEnqueue=[];waitDequeue=[];getStats(){return{length:this.queue.length,maxSize:this.maxSize,waitingEnqueue:this.waitEnqueue.length,waitingDequeue:this.waitDequeue.length}}get length(){return this.queue.length}async enqueue(e){if(this.queue.length>=this.maxSize&&await new Promise(t=>this.waitEnqueue.push(t)),this.waitDequeue.length>0){this.waitDequeue.shift()(e);return}this.queue.push(e)}async dequeue(){if(this.queue.length>0){let e=this.queue.shift();return this.waitEnqueue.shift()?.(),e}return await new Promise(e=>this.waitDequeue.push(e))}};var xe=we((()=>{try{return f}catch{return Se(import.meta.url)}})()),Me=JSON.parse(ke(se(xe,"../../package.json"),"utf-8")).version,te=class{static{u(this,"Gramstax")}templateManager;cacheKeyboard;cacheSession;pages;optionsPage={shortCallbackData:!1};log;bot;botConfig;webhookQueue;webhookQueueInstance;webhookServer;handlerBotUpdate;deployType;constructor(e){if(!e?.token||e?.token?.length==0)throw new Error("Token is not valid or empty");if(typeof e.optionsPage?.shortCallbackData=="boolean"&&(this.optionsPage.shortCallbackData=e.optionsPage.shortCallbackData),this.log=e.log===!0?F:e.log?e.log:void 0,this.log?.info?.(`Gramstax v${Me}`),this.cacheSession=e.cacheSession||new B("memory"),this.cacheKeyboard=e.cacheKeyboard||new Map,this.botConfig=e.botConfig,this.webhookQueue=e.webhookQueue,this.templateManager=e.templateManager||new V({path:[se(process.cwd(),"src","pages")]}),this.bot=this.createBot(e.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.stop()),process.once("SIGTERM",()=>this.stop()),this.hookBeforeStart(),e.deploy.startsWith("polling"))this.deployType="polling",this._runPolling();else if(e.deploy.startsWith("webhook:"))this.deployType="webhook",this._runWebhook(e.deploy.split("webhook:")[1]);else if(e.deploy.startsWith("serverless:"))this.deployType="serverless",this._runServerless(e.deploy.split("serverless:")[1]);else if(e.deploy.startsWith("test"))this.deployType="test";else throw new Error("Params deploy is not valid, expected: polling, webhook:<public-url>, serverless:<your-adapter>")}async stop(){await this.bot.stop(),this.deployType==="webhook"&&(await this.webhookServer?.stop(),this.webhookServer=void 0)}_onCatch(e){if(this.log?.errorMake)this.log?.errorMake(e,"Bot","catch");else{let t=JSON.stringify(e,null,2);this.log?.error?.(`[Bot.catch]: ${t}`)}}hookBeforeStart(){}hookAfterStart(){}async _onStart(e,t,s){await this.executeSyncBlocksDescription(this.pages);let{username:n}=e;this.log?.success?.(`Telegram bot deploy ${t} started: ${n} ${t=="webhook"||t=="serverless"?`(${s})`:""}`),this.hookAfterStart()}createBot(e){return new Ie(e,this.botConfig)}createCtx(e){return new W({ct:e,cacheSession:this.cacheSession,cacheKeyboard:this.cacheKeyboard,templateManager:this.templateManager,temp:{isAnswer:!1,session:{},data:{}}})}_runPolling(){this.bot.start({drop_pending_updates:!0,onStart:u(e=>{this._onStart(e,"polling",null)},"onStart")})}async _runWebhook(e){let{serve:t}=await import("bun"),s=ee(this.bot,"bun"),n=this.webhookQueue,i=n?.enabled===!0;this.handlerBotUpdate=i?this.bot.handleUpdate.bind(this.bot):s;let o=i?new E(n?.maxQueueSize??5e3):void 0,a=n?.workerCount??8,r=n?.perChatConcurrency??1,c=n?.blockWhenFull!==!1,l=new Map,d=new Map;this.webhookQueueInstance=o;let h=u(y=>y?.message?.chat?.id??y?.edited_message?.chat?.id??y?.channel_post?.chat?.id??y?.edited_channel_post?.chat?.id??y?.callback_query?.message?.chat?.id??y?.callback_query?.from?.id??y?.inline_query?.from?.id??y?.chosen_inline_result?.from?.id,"getChatId"),m=u(async y=>{if(!i||r<=0||y===void 0||y===null)return()=>{};let T=String(y),k=l.get(T)||0;if(k<r)return l.set(T,k+1),()=>this._releaseWebhookChat(T,l,d);await new Promise(le=>{let G=d.get(T)||[];G.push(le),d.set(T,G)});let de=(l.get(T)||0)+1;return l.set(T,de),()=>this._releaseWebhookChat(T,l,d)},"acquireChat");if(i&&o){await this.bot.init();for(let y=0;y<a;y++)this._startWebhookWorker(o,m,h)}let p=new URL(e),w=p.pathname,C=parseInt(p.port)||3e3,_=this.log,S="/stats_queue";this.webhookServer?.stop();let I=t({port:C,async fetch(y){let{pathname:T}=new URL(y.url);if(y.method=="POST"&&T==w){if(!i||!o)return s(y);if(!c&&o.length>=(n?.maxQueueSize??5e3))return new Response("Queue full",{status:429});try{let k=await y.json();return await o.enqueue(k),new Response("OK",{status:200})}catch(k){return _?.error?.(`Webhook queue error: ${String(k)}`),new Response("Bad Request",{status:400})}}if(y.method=="GET"&&T==S){let k=o?.getStats()||{length:0,maxSize:n?.maxQueueSize??5e3,waitingEnqueue:0,waitingDequeue:0};return new Response(JSON.stringify({enabled:i,path:S,timestamp:new Date().toISOString(),maxQueueSize:n?.maxQueueSize??5e3,workerCount:a,perChatConcurrency:r,blockWhenFull:c,queue:k,activeChats:l.size}),{status:200,headers:{"Content-Type":"application/json"}})}if(y.method=="GET"&&T=="/"){let k=new Date().toISOString();return new Response(JSON.stringify({status:"OK",timestamp:k}),{status:200,headers:{"Content-Type":"application/json"}})}return new Response("Not found",{status:404})}});this.webhookServer=I,(await this.bot.api.getWebhookInfo()).url!=e&&await this.bot.api.setWebhook(e);let D=await this.bot.api.getMe();await this._onStart(D,"webhook",e)}_startWebhookWorker(e,t,s){u(async()=>{for(;;){let i=await e.dequeue(),o=await t(s(i));try{await this.bot.handleUpdate(i)}catch(a){this.log?.error?.(`Webhook worker error: ${String(a)}`)}finally{o()}}},"run")()}_releaseWebhookChat(e,t,s){let n=t.get(e)||0,i=Math.max(0,n-1);i===0?t.delete(e):t.set(e,i);let o=s.get(e);o&&o.length>0&&(o.shift()(),o.length===0&&s.delete(e))}getWebhookQueueStats(){if(!this.webhookQueue?.enabled||!this.webhookQueueInstance)return null;let e=this.webhookQueueInstance.getStats(),t=this.webhookQueue.maxQueueSize??5e3,s=this.webhookQueue.workerCount??8,n=this.webhookQueue.perChatConcurrency??1,i=this.webhookQueue.blockWhenFull!==!1;return{enabled:!0,maxQueueSize:t,workerCount:s,perChatConcurrency:n,blockWhenFull:i,...e}}async _runServerless(e){this.handlerBotUpdate=ee(this.bot,e);let t=await this.bot.api.getMe();await this._onStart(t,"serverless",e)}_pageBuildData(e,t){e?.data===void 0&&(e.data=e.buildData());let{name:s}=_e(t);e.data.name||(e.data.name=s),e.data.intentText||(e.data.intentText=e.data.name),e.data.intentCommandText||(e.data.intentCommandText=e.data.name),e.data.intentCallbackData||(e.data.intentCallbackData=e.data.name)}_pageSorts(e,t,s){let n=e.data.name,i=e.prototype,o="handle",a="Args",r="Command",c="Caption",l="Free",d=t.routeDynamic,h=t.routeDynamicSpesific;t.all[n]=e;for(let m=0;m<t.lenListRouteStaticSession;m++){let p=t.listRouteStaticSession[m];if(typeof i[p]!="function")continue;let w=t.routeStatic[p],C=t.routeStaticIntent[p],_=t.routeStaticSession[p],S={name:n,routeName:p},I=w||C;if(I!==void 0){let P=p.includes(r),D=p.endsWith("CallbackData"),y=p.endsWith("Text"),T;if(P){let k=e.data.intentCommandText;T=k?`/${k}`:void 0}else if(D){let k=e.data.intentCallbackData;this.optionsPage.shortCallbackData===!0&&(k=String(s),e.data.intentCallbackData=k),T=k}else y?T=e.data.intentText:T=e.data.name;T&&(I[T]=S)}if(_!==void 0){let D=`methodSession${p.replace("handle","")}`,y=i[D]?.(n);_[y]=S}if(p.startsWith("handleFree")){let P=p.replace(o,"").replace(a,"").replace(r,"").replace(c,"").replace(l,"").toLowerCase();h[P].push(S)}}i.handleFree&&d.push(n)}async executeSyncBlocksDescription(e){let t=new Map,s=e.routeStatic.handleCommandText;for(let[,n]of Object.entries(s)){let i=n.name,o=this.templateManager.getDescriptionScopes(i);for(let a of o){t.has(a)||t.set(a,new Set);let r=this.templateManager.getDescriptionLanguage(i,"default",a);for(let c of r)t.get(a).add(c)}}for(let[n,i]of t)for(let o of i){let a=[];for(let[,l]of Object.entries(s)){let d=l.name,h=this.templateManager.getDescription(d,"default",o,n);h&&a.push({command:d,description:h})}if(a.length===0)continue;let r={type:n},c=o==="default"?void 0:o;try{let l=await this.bot.api.getMyCommands({scope:r,language_code:c}),d=JSON.stringify(l.map(m=>({command:m.command,description:m.description})).sort((m,p)=>m.command.localeCompare(p.command))),h=JSON.stringify(a.sort((m,p)=>m.command.localeCompare(p.command)));d!==h&&(await this.bot.api.setMyCommands(a,{scope:r,language_code:c}),this.log?.info?.(`Synced descriptions for scope: ${n},${c?` lang: ${c},`:""} total (${a.length})`))}catch(l){this.log?.error?.(`Failed to sync descriptions for scope: ${n},${c?` lang: ${c},`:""} error: ${String(l)}`)}}}_pageLoads(){this.log?.info?.("Load pages..");let e=["handleCallbackData","handleText","handleCommandText","handleCaptionPhoto","handleCommandCaptionPhoto","handleCaptionVideo","handleCommandCaptionVideo","handleCaptionAudio","handleCommandCaptionAudio","handleCaptionDocument","handleCommandCaptionDocument","handleCaptionAnimation","handleCommandCaptionAnimation","handleCaptionVoice","handleCommandCaptionVoice"],t=["handleArgsCallbackData","handleArgsText","handleCommandArgsText","handleCaptionArgsPhoto","handleCommandCaptionArgsPhoto","handleCaptionArgsVideo","handleCommandCaptionArgsVideo","handleCaptionArgsAudio","handleCommandCaptionArgsAudio","handleCaptionArgsDocument","handleCommandCaptionArgsDocument","handleCaptionArgsAnimation","handleCommandCaptionArgsAnimation","handleCaptionArgsVoice","handleCommandCaptionArgsAnimation"],s=[...e,...t,"handleFreeText","handleFreePhoto","handleFreeVideo","handleFreeAudio","handleFreeDocument","handleFreeAnimation","handleFreeVoice","handleFreeVideoNote","handleFreeSticker","handleFreeLocation","handleFreeContact"],n=u((a,r)=>Object.fromEntries(a.map(c=>[c,r()])),"makeObject"),i=u(()=>[],"initDynamicSpesific"),o={all:{},routeDynamic:[],routeDynamicSpesific:{text:i(),photo:i(),video:i(),audio:i(),document:i(),animation:i(),voice:i(),videonote:i(),sticker:i(),location:i(),contact:i()},routeStatic:n(e,()=>({})),routeStaticIntent:n(t,()=>({})),routeStaticSession:n(s,()=>({})),listRouteStatic:e,listRouteStaticIntent:t,listRouteStaticSession:s,lenListRouteStatic:e.length,lenListRouteStaticIntent:t.length,lenListRouteStaticSession:s.length};return x.getFileManySync(void 0).forEach(({path:a,page:r},c)=>{this._pageBuildData(r,a),this._pageSorts(r,o,c),r.template=void 0}),this.log?.info?.(`Finish load pages with total (${Object.keys(o.all).length})`),o}async _pageRoutes(e,t){let s,n;if(s===void 0){let o=await e.getSession();if(o){let a=o.method,r=this.pages.routeStaticSession,c=e.callbackData,l=e.msgText,d=e.msgCaption,h=c||l||d,m=t==="callbackdata",p=m?"colon":"space",w=h&&e.haveArgs(h,p)?e.getIntent(h,p,1):void 0,C=!m&&h?e.getIntent(h,"space",2):void 0;for(let _=0;_<this.pages.lenListRouteStaticSession;_++){let S=this.pages.listRouteStaticSession[_];if(S.toLowerCase().endsWith(t)){if(h){if(this.pages.routeStatic[S]?.[h])continue;let I=this.pages.routeStaticIntent[S];if(I&&(w&&I[w]||C&&I[C]))continue}n=r[S][a]}if(n)break}n!==void 0&&(s=this.pages.all[n.name])}}if(s===void 0){let o=e.callbackData,a=e.msgText,r=e.msgCaption,c=this.pages.routeStatic;for(let l=0;l<this.pages.lenListRouteStatic;l++){let d=this.pages.listRouteStatic[l];if(d.toLowerCase().endsWith(t)&&(n=c[d][o||a||r]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s===void 0){let o=this.pages.routeStaticIntent,a=t==="callbackdata",r=a?"colon":"space",c=a?e.callbackData:e.msgText||e.msgCaption,l=e.haveArgs(c,r);if(c&&l)for(let d=0;d<this.pages.lenListRouteStaticIntent;d++){let h=this.pages.listRouteStaticIntent[d];if(!h.toLowerCase().endsWith(t))continue;let m=o[h];if(n=m[e.getIntent(c,r,1)],!n&&!a&&(n=m[e.getIntent(c,"space",2)]),n)break}n!==void 0&&(s=this.pages.all[n.name])}if(s!==void 0&&n!==void 0){if(!s.prototype[n.routeName])return;let a=await new s(e)[n.routeName]?.();return e.temp.isAnswer===!0?a:null}let i=this.pages.routeDynamicSpesific[t]||[];for(let o=0;o<i.length;o++){let a=i[o];if(a===void 0)continue;let r=this.pages.all[a.name];r!==void 0&&typeof r.prototype[a.routeName]=="function"&&await new r(e)[a.routeName]()}for(let o=0;o<this.pages.routeDynamic.length;o++){let a=this.pages.routeDynamic[o];if(a===void 0)continue;let r=this.pages.all[a];r!==void 0&&typeof r.prototype.handleFree=="function"&&await new r(e).handleFree()}if(e.temp.isAnswer===!1)return null}async hookBeforeRoute(e,t){return!!(e||t)}async hookErrorPage(e,t,s,n){}async hookErrorInputNotFoundPage(e){}async _onMessage(e,t){let s=this.createCtx(e);try{if(await this.hookBeforeRoute(s,t)===!1)return;await this._pageRoutes(s,t)===null&&await this.hookErrorInputNotFoundPage(s)}catch(n){await this.hookErrorPage(s,t,n,!1)}}async _onCallbackQueryData(e){let t=this.createCtx(e);try{if(await this.hookBeforeRoute(t,"onCallbackQueryData")===!1)return;await this._pageRoutes(t,"callbackdata")}catch(s){await this.hookErrorPage(t,"onCallbackQueryData",s,!0)}}async _onMessageText(e){await this._onMessage(e,"text")}async _onMessagePhoto(e){await this._onMessage(e,"photo")}async _onMessageVideo(e){await this._onMessage(e,"video")}async _onMessageAudio(e){await this._onMessage(e,"audio")}async _onMessageDocument(e){await this._onMessage(e,"document")}async _onMessageAnimation(e){await this._onMessage(e,"animation")}async _onMessageVoice(e){await this._onMessage(e,"voice")}async _onMessageVideoNote(e){await this._onMessage(e,"videonote")}async _onMessageSticker(e){await this._onMessage(e,"sticker")}async _onMessageLocation(e){await this._onMessage(e,"location")}async _onMessageContact(e){await this._onMessage(e,"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 ne=class{static{u(this,"BlockKeyboard")}static label;static _build(e,t,s,n){if(!this.label)throw new Error("Label not found, make sure set this.label from class extends LabelKeyboard");s||(s="inline");let i=this.label[e];if(!i)throw new Error(`Object value ${e} not found`);let o=u((a,r)=>`<keyboard type="${s}" lang="${r}">${n?this.label._reverse(a):a}</keyboard>`,"pro");return t?o(i[t],t):Object.keys(i).map(a=>o(i[a],a)).join(" ")}};var ie=class{static{u(this,"LabelKeyboard")}static _reverse(e){return e.split(/(?<!\\), */).reverse().join(", ")}static _reverseObj(e){return Object.keys(e).reduce((t,s)=>(t[s]=this._reverse(e[s]),t),{})}};import{isMainThread as Ae,Worker as Re}from"worker_threads";var A=class{constructor(e,t){this.send=e;this.register=t}send;register;static{u(this,"WorkerThreadRpc")}map=new Map;async make(e){let t=this.map,s=this.send,{id:n,method:i,params:o,result:a,error:r}=e;if(i!==void 0)try{let c=this.register[i];if(typeof c!="function")throw new Error(`Method ${i} not found or not function`);let l=await c.apply(this.register,o);s({id:n,result:l})}catch(c){s({id:n,error:c instanceof Error?{message:c.message,stack:c.stack,name:c.name}:c})}else if(a!==void 0){let c=t.get(n);c&&(c.resolve(a),t.delete(n))}else if(r!==void 0){let c=t.get(n);c&&(c.reject(r),t.delete(n))}}makeId(){return Math.random()}makeRequest(e,t,s=!0,n){let i=this.makeId(),o={id:i,method:e,params:t,...n};return s?new Promise((a,r)=>{this.map.set(i,{resolve:a,reject:r}),this.send(o)}):this.send(o)}};var L=class{constructor(e,t,s){this.path=e;this.argv=t;this.register=s;this.init(),s||(s=this),this.rpc=new A(this.send.bind(this),s)}path;argv;register;static{u(this,"WorkerThreadLaunch")}static isMainThread=Ae;_readyResolve;_readyPromise=new Promise(e=>this._readyResolve=e);pid=process.pid;thread={};threadId={};rpc={};ready(){return this._readyPromise}readyResolve(){this._readyResolve?.()}init(){this.thread=new Re(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",e=>this.handleOnMessage(e)),this.thread.on("exit",()=>this.kill()),process.once("SIGINT",()=>this.kill()),process.once("SIGTERM",()=>this.kill())}async handleOnMessage(e){this.rpc.make(e)}kill(){this.thread.terminate()}send(e){this.thread.postMessage(e)}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};var oe=class g{static{u(this,"WorkerThreadExport")}static launchGatewayClient(e){let t=new Proxy({},{get(n,i){if(!(typeof i!="string"||i==="then"))return async(o,...a)=>{let r=o.gatewayClients.get(e);return r||(r=await o.createGatewayClient(e)),r.request(i,a)}}}),s=u(function(n){return new Proxy({},{get(i,o){if(!(typeof o!="string"||o==="then"))return async(...a)=>{let r=n.gatewayClients.get(e);return r||(r=await n.createGatewayClient(e)),r.request(o,a)}}})},"ctor");return Object.setPrototypeOf(s,t),s}static init(e){let{WTInit:t,WTLaunch:s=L,path:n,wrap:i}=e,o=`for-${n}`;if(process.argv[2]===o)return new t,{launchGatewayClient:u(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};let a,r=new Proxy({},{get(d,h){if(h!=="then")return h==="sendRequest"||h==="request"||h==="kill"||h==="send"?(...m)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a[h](...m)}:(...m)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a.request(h,m)}}}),l={...i?i(r):{},launchWorker:u(async(d=[])=>(a=new s(n,[o,...d]),await a.ready(),a),"launchWorker"),launchGatewayClient:u(d=>g.launchGatewayClient(d||t.gatewayServerPath),"launchGatewayClient")};return new Proxy(l,{get(d,h){if(h!=="then")return h==="launchGatewayClient"?d.launchGatewayClient:h==="launchWorker"?d.launchWorker:h in d?d[h]:typeof h=="string"?(...m)=>{if(!a)throw new Error(`Thread at ${n} not launched yet.`);return a.request(h,m)}:d[h]}})}};import{Client as ve}from"net-ipc";var K=class{static{u(this,"WorkerThreadGatewayClient")}client=new ve;rpc;constructor(){this.rpc=new A(e=>this.client.send(e),{}),this.client.on("message",e=>{this.rpc.make(e)})}async connect(e){this.client.options.path=e;let t=new Promise(s=>{this.client.once("ready",()=>s(this))});return await this.client.connect(),t}async request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}};import{Server as Pe}from"net-ipc";var q=class{static{u(this,"WorkerThreadGatewayServer")}server=new Pe;rpc=new Map;register={};constructor(){this.server.on("connect",e=>{let t=new A(s=>e.send(s),this.register);this.rpc.set(e.id,t)}),this.server.on("disconnect",e=>{this.rpc.delete(e.id)}),this.server.on("message",(e,t)=>{let s=this.rpc.get(t.id);s&&s.make(e)}),this.server.on("error",e=>{console.error(e)})}async start(e,t={}){this.register=t,this.server.options.path=e;let s=new Promise(n=>{this.server.once("ready",()=>n(this))});return await this.server.start(),s}};import{parentPort as De,threadId as Oe,isMainThread as Fe}from"worker_threads";var ae=class{static{u(this,"WorkerThreadInit")}argv=process.argv;id=Oe;pid=process.pid;rpc={};parentPort=De;gatewayServer;gatewayClients=new Map;gatewayClientLatest;static gatewayServerPath;gatewayServerPath=this.constructor.gatewayServerPath;get gatewayClient(){return this.gatewayClientLatest}static isMainThread=Fe;constructor(){this.init(),this.rpc=new A(this.send.bind(this),this),this.send({method:"readyResolve"})}init(){this.parentPort?.on("message",e=>this.handleOnMessage(e))}handleOnMessage(e){this.rpc.make(e)}send(e){this.parentPort?.postMessage(e)}request(e,t,s=!0,n){return this.rpc.makeRequest(e,t,s,n)}async createGatewayServer(e,t){return e||(e=this),t||(t=this.constructor.gatewayServerPath),this.gatewayServer=new q,await this.gatewayServer.start(t,e),this.constructor.gatewayServerPath=t,!0}async createGatewayClient(e){let t=new K;return await t.connect(e),this.gatewayClients.set(e,t),this.gatewayClientLatest=t,t}};var re=class{static{u(this,"WorkerThreadPool")}thread=new Map;threadCount=0;constructor(e){this.addMany(e)}add(e){this.thread.set(e.threadId,e),this.threadCount+=1}addMany(e){e.forEach(t=>this.add(t))}getInstance(e){return this.thread.get(e)}kill(e){let t=this.thread.get(e);return t?.kill(),this.thread.delete(e),this.threadCount-=1,t?.threadId}killAll(){this.thread.values().forEach(({threadId:e})=>this.kill(e))}async broadcastRequest(e,t){return await Promise.all(Object.values(this.thread).map(s=>s.request(e,t,!0)))}async request(e,t,s,n=!0,i){return await this.thread.get(e)?.request(t,s,n,i)}};var ce=class{static{u(this,"MockTelegramServer")}botToken="";hostname;port;log;handlers;defaultHandler;apiRoot="";webhookUrl="";requests=[];updates=[];server;_nextUpdateId=1;_nextMessageId=1;constructor(e={}){this.hostname=e.hostname??"127.0.0.1",this.port=e.port??0,this.log=e.log===!0?F:e.log?e.log:void 0,this.handlers=e.handlers??{},this.defaultHandler=e.defaultHandler}async start(){if(this.server)return this.apiRoot;let e=Bun.serve({port:this.port,hostname:this.hostname,fetch:u(async t=>this._handleRequest(t),"fetch")});return this.server=e,this.apiRoot=`http://${this.hostname}:${e.port??this.port}`,process.once("SIGINT",()=>this.stop()),process.once("SIGTERM",()=>this.stop()),this.log?.info?.(`Mock Telegram server started: ${this.apiRoot}`),this.apiRoot}async stop(){this.server?.stop(),this.server=void 0,this.log?.info?.("Mock Telegram server stopped")}_json(e){return new Response(JSON.stringify(e),{status:200,headers:{"Content-Type":"application/json"}})}lastRequest(e){if(!e)return this.requests[this.requests.length-1];for(let t=this.requests.length-1;t>=0;t--){let s=this.requests[t];if(s?.method===e)return s}}clearRequests(){this.requests.length=0}_defaultResponse(e,t){if(e==="getMe")return{ok:!0,result:{id:123456789,is_bot:!0,first_name:"Mock",username:"mock_gramstax_bot"}};if(e==="getUpdates")return{ok:!0,result:[]};if(e==="getMyCommands")return{ok:!0,result:[]};if(e==="setMyCommands")return{ok:!0,result:!0};if(e==="setWebhook"){let s=this._bodyRecord(t),n=typeof s?.url=="string"?s.url:"";return this.webhookUrl=n,this.log?.info?.(`Mock Telegram webhook set: ${n}`),{ok:!0,result:!0}}return e==="getWebhookInfo"?{ok:!0,result:{url:this.webhookUrl}}:{ok:!0,result:!0}}async _handleRequest(e){let{pathname:t}=new URL(e.url),s=t.match(/^\/bot([^/]+)\/(.+)$/);if(!s)return new Response("Not found",{status:404});let n=s[1],i=s[2];if(!n||!i)return new Response("Not found",{status:404});this.botToken=n;let o=await this._readBody(e.clone());this.log?.debug?.(`Mock Telegram API request: ${i}`),this.requests.push({method:i,body:o,url:e.url,requestMethod:e.method,headers:Object.fromEntries(e.headers.entries())});let a=this.handlers[i]??this.defaultHandler,r=a?await a({method:i,request:e}):this._defaultResponse(i,o);return this._json(r)}_bodyRecord(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:void 0}async _readBody(e){if(e.method==="GET"||e.method==="HEAD")return;let t=e.headers.get("content-type")||"";try{if(t.includes("application/json"))return await e.json();if(t.includes("multipart/form-data")||t.includes("application/x-www-form-urlencoded")){let n=await e.formData();return Object.fromEntries(n.entries())}let s=await e.text();if(!s)return;try{return JSON.parse(s)}catch{return s}}catch{return}}_defaultUser(e){return{id:e?.id??1001,is_bot:e?.is_bot??!1,first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.username?{username:e.username}:{},language_code:e?.language_code??"en"}}_defaultChat(e){return{id:e?.id??1001,type:e?.type??"private",first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.username?{username:e.username}:{},...e?.title?{title:e.title}:{}}}_nextIds(e){return{updateId:this._nextUpdateId++,messageId:e?.message_id??this._nextMessageId++,date:e?.date??Math.floor(Date.now()/1e3)}}_buildMessageUpdate(e,t){let{updateId:s,messageId:n,date:i}=this._nextIds(t);return{update_id:s,message:{message_id:n,date:i,chat:this._defaultChat(t?.chat),from:this._defaultUser(t?.user),...e}}}async _postUpdate(e,t){if(await this._waitForWebhookUrl(t?.responseTimeoutMs??1e3),!this.webhookUrl)throw new Error("Webhook URL is not set. Call setWebhook first or assign mockServer.webhookUrl.");let s=this.requests.length;this.updates.push(e),this.log?.info?.(`Mock Telegram update sent: ${this.webhookUrl}`);let n=await fetch(this.webhookUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});if(!n.ok)throw new Error(`Webhook request failed with status ${n.status}`);let i=await this._waitForResponses(s,t?.responseTimeoutMs??1e3);return this.log?.info?.(`Mock Telegram bot responses captured: ${i.length}`),i}async _waitForWebhookUrl(e){if(this.webhookUrl||e<=0)return this.webhookUrl;let t=Date.now();for(;Date.now()-t<e&&(await new Promise(s=>setTimeout(s,5)),!this.webhookUrl););return this.webhookUrl}async _waitForResponses(e,t){if(t<=0)return this._userResponseRequests(e);if(this._userResponseRequests(e).length>0)return this._userResponseRequests(e);let s=Date.now();for(;Date.now()-s<t&&(await new Promise(n=>setTimeout(n,5)),!(this._userResponseRequests(e).length>0)););return this._userResponseRequests(e)}_userResponseRequests(e){return this.requests.slice(e).filter(t=>this._isUserResponseMethod(t.method))}_isUserResponseMethod(e){return e.startsWith("send")||e.startsWith("edit")||e.startsWith("answer")||e.startsWith("delete")||e.startsWith("copy")||e.startsWith("forward")||e==="pinChatMessage"||e==="unpinChatMessage"||e==="setMessageReaction"}async sendText(e,t){let s=e.startsWith("/")?[{offset:0,length:e.split(" ")[0]?.length??e.length,type:"bot_command"}]:void 0;return await this._postUpdate(this._buildMessageUpdate({text:e,...s?{entities:s}:{}},t),t)}async sendPhoto(e){return await this._postUpdate(this._buildMessageUpdate({photo:[{file_id:"mock-photo-file-id",file_unique_id:"mock-photo-unique-id",width:1,height:1}],...e?.caption?{caption:e.caption}:{}},e),e)}async sendVideo(e){return await this._postUpdate(this._buildMessageUpdate({video:{file_id:"mock-video-file-id",file_unique_id:"mock-video-unique-id",width:1,height:1,duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendAudio(e){return await this._postUpdate(this._buildMessageUpdate({audio:{file_id:"mock-audio-file-id",file_unique_id:"mock-audio-unique-id",duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendDocument(e){return await this._postUpdate(this._buildMessageUpdate({document:{file_id:"mock-document-file-id",file_unique_id:"mock-document-unique-id",file_name:"mock.txt"},...e?.caption?{caption:e.caption}:{}},e),e)}async sendAnimation(e){return await this._postUpdate(this._buildMessageUpdate({animation:{file_id:"mock-animation-file-id",file_unique_id:"mock-animation-unique-id",width:1,height:1,duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendVoice(e){return await this._postUpdate(this._buildMessageUpdate({voice:{file_id:"mock-voice-file-id",file_unique_id:"mock-voice-unique-id",duration:1},...e?.caption?{caption:e.caption}:{}},e),e)}async sendVideoNote(e){return await this._postUpdate(this._buildMessageUpdate({video_note:{file_id:"mock-video-note-file-id",file_unique_id:"mock-video-note-unique-id",length:1,duration:1}},e),e)}async sendSticker(e){return await this._postUpdate(this._buildMessageUpdate({sticker:{file_id:"mock-sticker-file-id",file_unique_id:"mock-sticker-unique-id",type:"regular",width:1,height:1,is_animated:!1,is_video:!1}},e),e)}async sendLocation(e){return await this._postUpdate(this._buildMessageUpdate({location:{latitude:e?.latitude??0,longitude:e?.longitude??0}},e),e)}async sendContact(e){return await this._postUpdate(this._buildMessageUpdate({contact:{phone_number:e?.phone_number??"+10000000000",first_name:e?.first_name??"Test",...e?.last_name?{last_name:e.last_name}:{},...e?.user_id?{user_id:e.user_id}:{}}},e),e)}async sendCallbackQuery(e,t){let{updateId:s,messageId:n,date:i}=this._nextIds(t);return await this._postUpdate({update_id:s,callback_query:{id:t?.id??`mock-callback-${s}`,from:this._defaultUser(t?.user),message:{message_id:n,date:i,chat:this._defaultChat(t?.chat),text:t?.messageText??"Mock message"},chat_instance:"mock-chat-instance",data:e}},t)}};export{ne as BlockKeyboard,B as CacheExternal,W as Ctx,te as Gramstax,ie as LabelKeyboard,N as LoggingHelper,ce as MockTelegramServer,x as PageManager,M as TemplateEngine,V as TemplateManager,E as WebhookQueue,oe as WorkerThreadExport,K as WorkerThreadGatewayClient,q as WorkerThreadGatewayServer,ae as WorkerThreadInit,L as WorkerThreadLaunch,re as WorkerThreadPool,A as WorkerThreadRpc,F as log};
|