UNPKG

@bxshefby/b24jssdk

Version:

Bitrix24 REST API JavaScript SDK

143 lines (138 loc) • 4.92 kB
/** * @package @bxshefby/b24jssdk * @version 3.3.0 * @copyright (c) 2026 Bitrix24 * @license MIT * @see https://github.com/bx-shef/b24-js-sdk * @see https://b24-js-sdk.bx-shef.by/ */ 'use strict'; const abstractFormatter = require('./abstract-formatter.cjs'); var __defProp = Object.defineProperty; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); const LEGACY_MARKDOWN_RESERVED = /* @__PURE__ */ new Set(["_", "*", "`", "["]); class TelegramFormatter extends abstractFormatter.AbstractFormatter { static { __name(this, "TelegramFormatter"); } parseMode; maxMessageLength; constructor(useHtml = true, dateFormat = "YYYY-MM-DD HH:mm:ss", maxMessageLength = 4096) { super(dateFormat); this.parseMode = useHtml ? "HTML" : "Markdown"; this.maxMessageLength = maxMessageLength; } format(record) { let message = this._formatBaseMessage(record); const additionalInfo = this._formatAdditionalInfo(record); if (additionalInfo) { message += ` ${additionalInfo}`; } if (message.length > this.maxMessageLength) { message = this._truncate(message); } return message; } // Обрезка не должна оставлять разметку, которую Telegram отвергнет целиком (#121, #127): разрезанную // HTML-сущность (`&am`), одиночную «\» в конце, незакрытый блок кода _truncate(message) { const ellipsis = this.parseMode === "MarkdownV2" ? "\\.\\.\\." : "..."; const reserve = this.parseMode === "HTML" ? 0 : 4; let cut = message.substring(0, this.maxMessageLength - ellipsis.length - reserve); if (this.parseMode === "HTML") { cut = cut.replace(/&[#a-z0-9]{0,7}$/i, ""); return cut + ellipsis; } const slashes = /\\+$/.exec(cut)?.[0].length ?? 0; if (slashes % 2 === 1) { cut = cut.slice(0, -1); } cut = cut.replace(/(?<!`)`{1,2}$/, ""); const fences = cut.match(/```/g)?.length ?? 0; if (fences % 2 === 1) { return `${cut} \`\`\`${ellipsis}`; } return cut + ellipsis; } _formatBaseMessage(record) { const date = String(this._formatDate(record.timestamp)); const level = String(record.levelName); const channel = String(record.channel); const message = String(record.message); if (this.parseMode === "HTML") { return `<b>${this._escapeHtml(level)}</b> | <code>${this._escapeHtml(channel)}</code> <i>Time:</i> ${this._escapeHtml(date)} <i>Message:</i> ${this._escapeHtml(message)}`; } return `*${this._escapeText(level)}* \`${this._escapeCode(channel)}\` _Time:_ \`${this._escapeCode(date)}\` _Message:_ ${this._escapeText(message)}`; } _formatAdditionalInfo(record) { const parts = []; if (record.context && Object.keys(record.context).length > 0) { parts.push(this._formatJsonBlock("Context", JSON.stringify(record.context, null, 2))); } if (record.extra && Object.keys(record.extra).length > 0) { parts.push(this._formatJsonBlock("Extra", JSON.stringify(record.extra, null, 2))); } return parts.join("\n\n"); } _formatJsonBlock(title, json) { if (this.parseMode === "HTML") { return `<i>${title}:</i> <pre><code class="language-json">${this._escapeHtml(json)}</code></pre>`; } return `_${title}:_ \`\`\`json ${this._escapeCode(json)} \`\`\``; } // Текст вне сущностей в Markdown-режимах _escapeText(text) { if (this.parseMode === "MarkdownV2") { return this._escapeMarkdownV2(text); } return Array.from(text, (char) => LEGACY_MARKDOWN_RESERVED.has(char) ? `\\${char}` : char).join(""); } // Текст внутри `code` и ```pre```: в MarkdownV2 экранируются только «`» и «\», в старом Markdown экранирования // внутри сущности нет — обратная кавычка закрыла бы её, поэтому заменяется на «'» _escapeCode(text) { if (this.parseMode === "MarkdownV2") { return text.replace(/[\\`]/g, "\\$&"); } return text.replace(/`/g, "'"); } _escapeHtml(text) { return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;"); } _escapeMarkdownV2(text) { return text.replace(/[\\_*[\]()~`>#+\-=|{}.!]/g, "\\$&"); } /** * Set the use of HTML markup */ setUseHtml(useHtml) { this.parseMode = useHtml ? "HTML" : "Markdown"; return this; } /** * Set the Telegram `parse_mode` to escape for */ setParseMode(parseMode) { this.parseMode = parseMode; return this; } /** * // Set the maximum message length */ setMaxMessageLength(maxLength) { this.maxMessageLength = maxLength; return this; } } exports.TelegramFormatter = TelegramFormatter;