zeph-channels 0.18.3

Multi-channel I/O adapters (CLI, Telegram, Discord, Slack) for Zeph
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
// SPDX-FileCopyrightText: 2026 Andrei G <bug-ops>
// SPDX-License-Identifier: MIT OR Apache-2.0

use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};

const SPECIAL_CHARS: &[char] = &[
    '_', '*', '[', ']', '(', ')', '~', '`', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!', '\\',
];

/// Converts standard Markdown to Telegram `MarkdownV2` format.
///
/// Uses `pulldown-cmark` to parse the input into AST events, then walks
/// those events to produce properly escaped Telegram `MarkdownV2` output.
///
/// Formatting conversions:
/// - `**bold**` → `*bold*` (Telegram uses single asterisk)
/// - `*italic*` → `_italic_` (Telegram uses underscore)
/// - `# Header` → `*Header*` (headers become bold text)
/// - Code blocks and inline code preserve content with minimal escaping
///
/// Escaping rules:
/// - Regular text: escape all 19 special characters
/// - Code blocks and inline code: escape only `\` and `` ` ``
#[must_use]
pub fn markdown_to_telegram(input: &str) -> String {
    let options = Options::ENABLE_STRIKETHROUGH;
    let parser = Parser::new_ext(input, options);
    let mut renderer = TelegramRenderer::new(input.len());
    for event in parser {
        renderer.push_event(event);
    }
    renderer.finish()
}

/// Splits text into chunks respecting UTF-8 character boundaries.
///
/// Prefers splitting at newline boundaries when possible for better readability.
/// Each chunk is guaranteed to be valid UTF-8 and at most `max_bytes` in length.
#[must_use]
pub fn utf8_chunks(text: &str, max_bytes: usize) -> Vec<&str> {
    if text.len() <= max_bytes {
        return vec![text];
    }

    let mut chunks = Vec::new();
    let mut offset = 0;

    while offset < text.len() {
        let remaining = text.len() - offset;
        if remaining <= max_bytes {
            chunks.push(&text[offset..]);
            break;
        }

        let mut split_at = offset + max_bytes;

        if split_at >= text.len() {
            chunks.push(&text[offset..]);
            break;
        }

        if !text.is_char_boundary(split_at) {
            while split_at > offset && !text.is_char_boundary(split_at) {
                split_at -= 1;
            }
        }

        let search_start = split_at.saturating_sub(256).max(offset);
        if let Some(newline_pos) = text[search_start..split_at].rfind('\n') {
            let potential_split = search_start + newline_pos + 1;
            if potential_split > offset {
                split_at = potential_split;
            }
        }

        chunks.push(&text[offset..split_at]);
        offset = split_at;
    }

    chunks
}

struct TelegramRenderer {
    output: String,
    in_code_block: bool,
    link_url: Option<String>,
}

impl TelegramRenderer {
    fn new(capacity: usize) -> Self {
        Self {
            output: String::with_capacity(capacity),
            in_code_block: false,
            link_url: None,
        }
    }

    fn push_event(&mut self, event: Event<'_>) {
        match event {
            Event::End(TagEnd::Heading { .. }) => {
                self.output.push_str("*\n");
            }
            Event::Start(Tag::Heading { .. } | Tag::Strong) | Event::End(TagEnd::Strong) => {
                self.output.push('*');
            }
            Event::Start(Tag::Emphasis) | Event::End(TagEnd::Emphasis) => {
                self.output.push('_');
            }
            Event::Start(Tag::Strikethrough) | Event::End(TagEnd::Strikethrough) => {
                self.output.push('~');
            }
            Event::Start(Tag::CodeBlock(_)) => {
                self.output.push_str("```\n");
                self.in_code_block = true;
            }
            Event::End(TagEnd::CodeBlock) => {
                self.output.push_str("```");
                self.in_code_block = false;
            }
            Event::Code(text) => {
                self.output.push('`');
                self.output.push_str(&Self::escape_code_text(&text));
                self.output.push('`');
            }
            Event::Text(text) => {
                let escaped = if self.in_code_block {
                    Self::escape_code_text(&text)
                } else {
                    Self::escape_text(&text)
                };
                self.output.push_str(&escaped);
            }
            Event::Start(Tag::Link { dest_url, .. }) => {
                self.output.push('[');
                self.link_url = Some(dest_url.to_string());
            }
            Event::End(TagEnd::Link) => {
                if let Some(url) = self.link_url.take() {
                    self.output.push_str("](");
                    self.output.push_str(&Self::escape_url(&url));
                    self.output.push(')');
                }
            }
            Event::Start(Tag::Item) => {
                self.output.push_str("");
            }
            Event::Start(Tag::BlockQuote(_)) => {
                self.output.push('>');
            }
            Event::End(TagEnd::Paragraph | TagEnd::Item | TagEnd::BlockQuote(_))
            | Event::SoftBreak
            | Event::HardBreak => {
                self.output.push('\n');
            }
            _ => {}
        }
    }

    fn escape_text(text: &str) -> String {
        let mut result = String::with_capacity(text.len() * 2);
        for c in text.chars() {
            if SPECIAL_CHARS.contains(&c) {
                result.push('\\');
            }
            result.push(c);
        }
        result
    }

    fn escape_code_text(text: &str) -> String {
        let mut result = String::with_capacity(text.len() * 2);
        for c in text.chars() {
            match c {
                '`' | '\\' => {
                    result.push('\\');
                    result.push(c);
                }
                _ => result.push(c),
            }
        }
        result
    }

    fn escape_url(text: &str) -> String {
        let mut result = String::with_capacity(text.len());
        for c in text.chars() {
            if c == ')' || c == '\\' {
                result.push('\\');
            }
            result.push(c);
        }
        result
    }

    fn finish(mut self) -> String {
        if self.output.ends_with('\n') {
            self.output.pop();
        }
        self.output
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bold_conversion() {
        let input = "**bold**";
        let output = markdown_to_telegram(input);
        assert_eq!(output, "*bold*");
    }

    #[test]
    fn test_italic_conversion() {
        let input = "*italic*";
        let output = markdown_to_telegram(input);
        assert_eq!(output, "_italic_");
    }

    #[test]
    fn test_strikethrough_conversion() {
        let input = "~~strikethrough~~";
        let output = markdown_to_telegram(input);
        assert_eq!(output, "~strikethrough~");
    }

    #[test]
    fn test_header_to_bold() {
        let input = "# Header 1\n## Header 2";
        let output = markdown_to_telegram(input);
        assert!(output.contains("*Header 1*"));
        assert!(output.contains("*Header 2*"));
    }

    #[test]
    fn test_nested_formatting() {
        let input = "**bold _italic_**";
        let output = markdown_to_telegram(input);
        assert_eq!(output, "*bold _italic_*");
    }

    #[test]
    fn test_inline_code() {
        let input = "text `code` text";
        let output = markdown_to_telegram(input);
        assert!(output.contains("`code`"));
    }

    #[test]
    fn test_code_block() {
        let input = "```\ncode block\n```";
        let output = markdown_to_telegram(input);
        assert!(output.starts_with("```\n"));
        assert!(output.contains("code block"));
        assert!(output.ends_with("```"));
    }

    #[test]
    fn test_links() {
        let input = "[text](https://example.com)";
        let output = markdown_to_telegram(input);
        assert_eq!(output, "[text](https://example.com)");
    }

    #[test]
    fn test_blockquote() {
        let input = "> quote";
        let output = markdown_to_telegram(input);
        assert!(output.starts_with('>'));
    }

    #[test]
    fn test_lists() {
        let input = "- item 1\n- item 2";
        let output = markdown_to_telegram(input);
        assert!(output.contains("• item 1"));
        assert!(output.contains("• item 2"));
    }

    #[test]
    fn test_escape_special_chars() {
        let input = "Special: . ! - + = | { }";
        let output = markdown_to_telegram(input);
        assert_eq!(output, "Special: \\. \\! \\- \\+ \\= \\| \\{ \\}");
    }

    #[test]
    fn test_code_block_minimal_escape() {
        let input = "```\nbackslash \\ and backtick `\n```";
        let output = markdown_to_telegram(input);
        assert!(output.contains("backslash \\\\"));
        assert!(output.contains("backtick \\`"));
    }

    #[test]
    fn test_no_double_escape() {
        let input = "already escaped: \\*";
        let output = markdown_to_telegram(input);
        assert_eq!(output, "already escaped: \\*");
    }

    #[test]
    fn test_mixed_code_and_text() {
        let input = "text with `code` and **bold**";
        let output = markdown_to_telegram(input);
        assert!(output.contains("`code`"));
        assert!(output.contains("*bold*"));
    }

    #[test]
    fn test_empty_input() {
        let input = "";
        let output = markdown_to_telegram(input);
        assert_eq!(output, "");
    }

    #[test]
    fn test_plain_text() {
        let input = "Plain text with special chars: -";
        let output = markdown_to_telegram(input);
        assert!(output.contains("\\-"));
    }

    #[test]
    fn test_unclosed_bold() {
        let input = "**unclosed bold";
        let output = markdown_to_telegram(input);
        assert!(!output.is_empty());
    }

    #[test]
    fn test_unclosed_code_block() {
        let input = "```\nunclosed";
        let output = markdown_to_telegram(input);
        assert!(!output.is_empty());
    }

    #[test]
    fn test_horizontal_rule() {
        let input = "Text\n---\nMore";
        let output = markdown_to_telegram(input);
        assert!(output.contains("Text"));
        assert!(output.contains("More"));
    }

    #[test]
    fn test_unicode_text() {
        let input = "emoji 🎉 and CJK 中文";
        let output = markdown_to_telegram(input);
        assert!(output.contains("🎉"));
        assert!(output.contains("中文"));
    }

    #[test]
    fn test_multiline() {
        let input = "# Title\n\nParagraph 1.\n\nParagraph 2 with **bold**.";
        let output = markdown_to_telegram(input);
        assert!(output.contains("*Title*"));
        assert!(output.contains("Paragraph 1"));
        assert!(output.contains("*bold*"));
    }

    #[test]
    fn test_no_split_needed() {
        let text = "short text";
        let chunks = utf8_chunks(text, 100);
        assert_eq!(chunks.len(), 1);
        assert_eq!(chunks[0], text);
    }

    #[test]
    fn test_split_at_newline() {
        let text = "line 1\nline 2\nline 3";
        let chunks = utf8_chunks(text, 10);
        assert!(chunks.len() > 1);
        for chunk in &chunks {
            assert!(chunk.len() <= 10);
        }
    }

    #[test]
    fn test_split_respects_utf8() {
        let text = "日本語";
        let chunks = utf8_chunks(text, 5);
        for chunk in &chunks {
            assert!(std::str::from_utf8(chunk.as_bytes()).is_ok());
        }
    }

    #[test]
    fn test_split_emoji() {
        let text = "🎉🎊🎈🎁";
        let chunks = utf8_chunks(text, 8);
        for chunk in &chunks {
            assert!(std::str::from_utf8(chunk.as_bytes()).is_ok());
            assert!(chunk.len() <= 8);
        }
    }

    #[test]
    fn test_chunks_concatenate() {
        let text = "The quick brown fox jumps over the lazy dog";
        let chunks = utf8_chunks(text, 10);
        let rejoined = chunks.join("");
        assert_eq!(rejoined, text);
    }

    #[test]
    fn test_each_chunk_within_limit() {
        let text = "a".repeat(1000);
        let max_bytes = 100;
        let chunks = utf8_chunks(&text, max_bytes);
        for chunk in &chunks {
            assert!(chunk.len() <= max_bytes);
        }
    }

    #[test]
    fn test_code_block_with_special_chars() {
        let input = "```bash\nfind . -name \"*.txt\"\n```";
        let output = markdown_to_telegram(input);
        assert!(output.contains("find . -name"));
    }

    #[test]
    fn test_escaping_backslash() {
        let input = "backslash \\";
        let output = markdown_to_telegram(input);
        assert!(output.contains("\\\\"));
    }

    #[test]
    fn test_link_with_special_chars() {
        let input = "[link](https://example.com/path?param=value)";
        let output = markdown_to_telegram(input);
        assert!(output.contains("[link]"));
        assert!(output.contains("example.com"));
    }

    #[test]
    fn test_utf8_chunks_no_infinite_loop() {
        let text = format!("{}\n{}{}", "A".repeat(7), "X".repeat(90), "Y".repeat(50));
        let chunks = utf8_chunks(&text, 50);
        let rejoined: String = chunks.concat();
        assert_eq!(rejoined, text);
        assert!(chunks.len() >= 2, "Should produce at least 2 chunks");
        for chunk in &chunks {
            assert!(
                chunk.len() <= 50,
                "Chunk exceeds max_bytes: {}",
                chunk.len()
            );
            assert!(
                !chunk.is_empty(),
                "Empty chunk detected - infinite loop bug"
            );
        }
    }
}