UNPKG

@idoctor-devs/event-logger

Version:

NPM библиотека для отправки событий и сообщений в мессенджеры из веб-приложений

3 lines (2 loc) 4.1 kB
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class t{}class e extends t{constructor(t){super(),this.config=t}async send(t,e,r){try{const o=this.formatMessage(t,e,r),i=await async function(t,e,r,o={}){const{timeout:i=5e3,retryAttempts:n=3}=o,s=`https://api.telegram.org/bot${t}/sendMessage`,a={chat_id:e,text:(d=r,d.replace(/[().-]/g,"\\$&")),parse_mode:"MarkdownV2"};var d;for(let g=1;g<=n;g++)try{const t=new AbortController,e=setTimeout((()=>t.abort()),i),r=await fetch(s,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(a),signal:t.signal});if(clearTimeout(e),r.ok)return!0;const o=await r.json().catch((()=>({})));if(console.warn(`Telegram API error (attempt ${g}):`,{status:r.status,statusText:r.statusText,error:o}),g===n)return!1;await new Promise((t=>setTimeout(t,1e3*Math.pow(2,g))))}catch(c){if(console.warn(`Network error (attempt ${g}):`,c),g===n)return!1;await new Promise((t=>setTimeout(t,1e3*Math.pow(2,g))))}return!1}(this.config.botToken,this.config.chatId,o,{timeout:this.config.timeout||5e3,retryAttempts:this.config.retryAttempts||3});return i}catch(o){return console.error("TelegramProvider send error:",o),!1}}getBotToken(){return this.config.botToken}getChatId(){return this.config.chatId}formatDate(t=new Date){const e="string"==typeof t?new Date(t):t;return`${String(e.getDate()).padStart(2,"0")}.${String(e.getMonth()+1).padStart(2,"0")}.${e.getFullYear()} ${String(e.getHours()).padStart(2,"0")}.${String(e.getMinutes()).padStart(2,"0")}.${String(e.getSeconds()).padStart(2,"0")}`}formatMessage(t,e,r){const o=this.formatDate();let i=`${this.getLevelEmoji(e)} [${e.toUpperCase()}] ${o}`;if(r&&Object.keys(r).length>0){i+="\n\n*METADATA*\n";for(const[t,e]of Object.entries(r))i+=`\n*${t}*: ${e}`;i+="\n"}return i+=`\n${t}`,i}getLevelEmoji(t){return{log:"📝",info:"ℹ️",warn:"⚠️",error:"❌"}[t]}}class r extends Error{constructor(t){super(t),this.name="ValidationError"}}function o(t){if(!t)throw new r("Configuration is required");if(!t.environment)throw new r("Environment is required");if("browser"!==t.environment)throw new r('Only "browser" environment is supported');if(!t.providers||!Array.isArray(t.providers))throw new r("Providers array is required");if(0===t.providers.length)throw new r("At least one provider is required");t.providers.forEach(((t,e)=>{!function(t,e){const o=void 0!==e?`Provider[${e}]: `:"";if(!t)throw new r(`${o}Provider configuration is required`);if("telegram"!==t.type)throw new r(`${o}Only "telegram" provider type is supported`);if(!t.botToken||"string"!=typeof t.botToken)throw new r(`${o}Bot token is required and must be a string`);if(!t.botToken.trim())throw new r(`${o}Bot token cannot be empty`);if(!t.chatId||"string"!=typeof t.chatId)throw new r(`${o}Chat ID is required and must be a string`);if(!t.chatId.trim())throw new r(`${o}Chat ID cannot be empty`);if(void 0!==t.timeout&&("number"!=typeof t.timeout||t.timeout<=0))throw new r(`${o}Timeout must be a positive number`);if(void 0!==t.retryAttempts&&("number"!=typeof t.retryAttempts||t.retryAttempts<0))throw new r(`${o}Retry attempts must be a non-negative number`)}(t,e)}))}exports.BaseProvider=t,exports.EventLogger=class{constructor(t){this.providers=[],o(t),this.config=t,this.initializeProviders()}initializeProviders(){for(const t of this.config.providers)if("telegram"===t.type){const r=new e(t);this.providers.push(r)}}async log(t,e){await this.sendToAllProviders(t,"log",e)}async info(t,e){await this.sendToAllProviders(t,"info",e)}async warn(t,e){await this.sendToAllProviders(t,"warn",e)}async error(t,e){await this.sendToAllProviders(t,"error",e)}async sendToAllProviders(t,e,r){if(!(t&&"string"==typeof t||r))return void console.warn("EventLogger: Message must be a non-empty string or metadata must be provided");const o=this.providers.map((async o=>{try{await o.send(t,e,r)}catch(i){console.error("EventLogger: Failed to send message via provider:",i)}}));await Promise.allSettled(o)}},exports.TelegramProvider=e,exports.ValidationError=r; //# sourceMappingURL=event-logger.cjs.js.map