fix: persist resolved telegram delivery targets at runtime

This commit is contained in:
Ayaan Zaidi
2026-02-23 09:13:35 +05:30
committed by Ayaan Zaidi
parent 35fbf26d24
commit dcc52850c3
8 changed files with 632 additions and 77 deletions

View File

@@ -4,6 +4,9 @@ export type TelegramTarget = {
chatType: "direct" | "group" | "unknown";
};
const TELEGRAM_NUMERIC_CHAT_ID_REGEX = /^-?\d+$/;
const TELEGRAM_USERNAME_REGEX = /^[A-Za-z0-9_]{5,}$/i;
export function stripTelegramInternalPrefixes(to: string): string {
let trimmed = to.trim();
let strippedTelegramPrefix = false;
@@ -26,6 +29,46 @@ export function stripTelegramInternalPrefixes(to: string): string {
}
}
export function normalizeTelegramChatId(raw: string): string | undefined {
const stripped = stripTelegramInternalPrefixes(raw);
if (!stripped) {
return undefined;
}
if (TELEGRAM_NUMERIC_CHAT_ID_REGEX.test(stripped)) {
return stripped;
}
return undefined;
}
export function isNumericTelegramChatId(raw: string): boolean {
return TELEGRAM_NUMERIC_CHAT_ID_REGEX.test(raw.trim());
}
export function normalizeTelegramLookupTarget(raw: string): string | undefined {
const stripped = stripTelegramInternalPrefixes(raw);
if (!stripped) {
return undefined;
}
if (isNumericTelegramChatId(stripped)) {
return stripped;
}
const tmeMatch = /^(?:https?:\/\/)?t\.me\/([A-Za-z0-9_]+)$/i.exec(stripped);
if (tmeMatch?.[1]) {
return `@${tmeMatch[1]}`;
}
if (stripped.startsWith("@")) {
const handle = stripped.slice(1);
if (!handle || !TELEGRAM_USERNAME_REGEX.test(handle)) {
return undefined;
}
return `@${handle}`;
}
if (TELEGRAM_USERNAME_REGEX.test(stripped)) {
return `@${stripped}`;
}
return undefined;
}
/**
* Parse a Telegram delivery target into chatId and optional topic/thread ID.
*
@@ -39,7 +82,7 @@ function resolveTelegramChatType(chatId: string): "direct" | "group" | "unknown"
if (!trimmed) {
return "unknown";
}
if (/^-?\d+$/.test(trimmed)) {
if (isNumericTelegramChatId(trimmed)) {
return trimmed.startsWith("-") ? "group" : "direct";
}
return "unknown";