zorto-core 0.23.1

Core library for zorto — the AI-native static site generator (SSG) with executable code blocks
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
use pulldown_cmark::{BlockQuoteKind, CodeBlockKind, CowStr, Event, Options, Parser, Tag, TagEnd};
use regex::Regex;
use std::sync::LazyLock;
use syntect::highlighting::ThemeSet;
use syntect::html::highlighted_html_for_string;
use syntect::parsing::{SyntaxDefinition, SyntaxSet};

use crate::config::{AnchorLinks, MarkdownConfig};
use crate::content::escape_xml;
use crate::execute::{ExecutableBlock, VizOutput};
use crate::shortcodes::{
    CALLOUT_ICON_CAUTION, CALLOUT_ICON_IMPORTANT, CALLOUT_ICON_NOTE, CALLOUT_ICON_TIP,
    CALLOUT_ICON_WARNING,
};

static SYNTAX_SET: LazyLock<SyntaxSet> = LazyLock::new(|| {
    let mut builder = SyntaxSet::load_defaults_newlines().into_builder();
    // Add TOML syntax (not in syntect's defaults)
    if let Ok(toml_syn) = SyntaxDefinition::load_from_str(
        include_str!("../syntaxes/TOML.sublime-syntax"),
        true,
        Some("TOML"),
    ) {
        builder.add(toml_syn);
    }
    builder.build()
});
static THEME_SET: LazyLock<ThemeSet> = LazyLock::new(ThemeSet::load_defaults);
static FILE_ATTR_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r#"file="([^"]+)""#).unwrap());

const DEFAULT_HIGHLIGHT_THEME: &str = "base16-ocean.dark";

/// Render markdown to HTML with all processing steps.
pub fn render_markdown(
    content: &str,
    config: &MarkdownConfig,
    executable_blocks: &mut Vec<ExecutableBlock>,
    base_url: &str,
) -> String {
    let mut options = Options::empty();
    options.insert(Options::ENABLE_TABLES);
    options.insert(Options::ENABLE_FOOTNOTES);
    options.insert(Options::ENABLE_STRIKETHROUGH);
    options.insert(Options::ENABLE_TASKLISTS);
    options.insert(Options::ENABLE_GFM);
    if config.smart_punctuation {
        options.insert(Options::ENABLE_SMART_PUNCTUATION);
    }

    let parser = Parser::new_ext(content, options);
    let mut events: Vec<Event> = Vec::new();

    let mut in_code_block = false;
    let mut code_lang = String::new();
    let mut code_content = String::new();
    let mut heading_text = String::new();
    let mut in_heading = false;

    for event in parser {
        match event {
            // --- GitHub-style callout / alert blockquotes ---
            Event::Start(Tag::BlockQuote(Some(kind))) => {
                let (css_class, icon, title) = callout_info(&kind);
                let html = format!(
                    "<div class=\"callout callout--{css_class}\">\
                     <p class=\"callout__title\">{icon} {title}</p>"
                );
                events.push(Event::Html(CowStr::from(html)));
            }
            Event::End(TagEnd::BlockQuote(Some(_))) => {
                events.push(Event::Html(CowStr::from("</div>")));
            }

            Event::Start(Tag::CodeBlock(kind)) => {
                in_code_block = true;
                code_content.clear();
                code_lang = match &kind {
                    CodeBlockKind::Fenced(lang) => lang.to_string(),
                    CodeBlockKind::Indented => String::new(),
                };
            }
            Event::End(TagEnd::CodeBlock) => {
                in_code_block = false;

                // Check if this is an executable code block
                if code_lang.starts_with('{') && code_lang.ends_with('}') {
                    let lang = &code_lang[1..code_lang.len() - 1];
                    // Parse potential attributes like file="..."
                    let (actual_lang, file_ref) = parse_code_attrs(lang);

                    let block_idx = executable_blocks.len();
                    executable_blocks.push(ExecutableBlock {
                        language: actual_lang.to_string(),
                        source: code_content.clone(),
                        file_ref,
                        output: None,
                        error: None,
                        viz: Vec::new(),
                    });

                    // Insert placeholder that will be replaced after execution
                    let placeholder = format!("<!-- EXEC_BLOCK_{block_idx} -->");
                    events.push(Event::Html(CowStr::from(placeholder)));
                } else {
                    // Regular code block with syntax highlighting
                    let html = highlight_code(&code_content, &code_lang, config);
                    events.push(Event::Html(CowStr::from(html)));
                }
            }
            Event::Text(text) if in_code_block => {
                code_content.push_str(&text);
            }
            Event::Start(Tag::Heading { level, .. }) => {
                in_heading = true;
                heading_text.clear();
                // Remember where we'll patch in the id later
                events.push(Event::Start(Tag::Heading {
                    level,
                    id: None,
                    classes: vec![],
                    attrs: vec![],
                }));
            }
            Event::End(TagEnd::Heading(_level)) => {
                in_heading = false;
                let id = slug::slugify(&heading_text);

                // Patch the heading start event with the computed id
                for ev in events.iter_mut().rev() {
                    if let Event::Start(Tag::Heading { id: h_id, .. }) = ev {
                        *h_id = Some(CowStr::from(id.clone()));
                        break;
                    }
                }

                // Insert anchor link if configured
                if config.insert_anchor_links == AnchorLinks::Right {
                    let anchor_html = format!(
                        " <a class=\"zorto-anchor\" href=\"#{}\" aria-label=\"Anchor link for: {}\">#</a>",
                        id, heading_text
                    );
                    events.push(Event::Html(CowStr::from(anchor_html)));
                }

                events.push(event);
            }
            Event::Text(ref text) if in_heading => {
                heading_text.push_str(text);
                events.push(event);
            }
            Event::Start(Tag::Link {
                dest_url, title, ..
            }) => {
                // Rewrite external links
                if is_external_url(&dest_url, base_url) && config.external_links_target_blank {
                    let mut attrs = vec![r#"target="_blank""#.to_string()];
                    let mut rel_parts = Vec::new();
                    if config.external_links_no_follow {
                        rel_parts.push("nofollow");
                    }
                    if config.external_links_no_referrer {
                        rel_parts.push("noreferrer");
                    }
                    if !rel_parts.is_empty() {
                        attrs.push(format!(r#"rel="{}""#, rel_parts.join(" ")));
                    }
                    let attrs_str = attrs.join(" ");
                    let html = format!(
                        r#"<a href="{}" title="{}" {attrs_str}>"#,
                        escape_xml(&dest_url),
                        escape_xml(&title),
                    );
                    events.push(Event::Html(CowStr::from(html)));
                } else {
                    events.push(Event::Start(Tag::Link {
                        link_type: pulldown_cmark::LinkType::Inline,
                        dest_url,
                        title,
                        id: CowStr::from(""),
                    }));
                }
            }
            _ => {
                events.push(event);
            }
        }
    }

    // Render to HTML
    let mut html = String::new();
    pulldown_cmark::html::push_html(&mut html, events.into_iter());

    html
}

/// Get CSS class, SVG icon, and display title for a GitHub-style callout.
fn callout_info(kind: &BlockQuoteKind) -> (&'static str, &'static str, &'static str) {
    match kind {
        BlockQuoteKind::Note => ("note", CALLOUT_ICON_NOTE, "Note"),
        BlockQuoteKind::Tip => ("tip", CALLOUT_ICON_TIP, "Tip"),
        BlockQuoteKind::Warning => ("warning", CALLOUT_ICON_WARNING, "Warning"),
        BlockQuoteKind::Caution => ("caution", CALLOUT_ICON_CAUTION, "Caution"),
        BlockQuoteKind::Important => ("important", CALLOUT_ICON_IMPORTANT, "Important"),
    }
}

/// Extract summary from content at <!-- more --> marker
pub fn extract_summary(content: &str) -> Option<String> {
    let marker = "<!-- more -->";
    content.find(marker).map(|pos| content[..pos].to_string())
}

/// Replace executable block placeholders with rendered output
pub fn replace_exec_placeholders(
    html: &str,
    blocks: &[ExecutableBlock],
    config: &MarkdownConfig,
) -> String {
    let mut result = html.to_string();

    for (i, block) in blocks.iter().enumerate() {
        let placeholder = format!("<!-- EXEC_BLOCK_{i} -->");
        if result.contains(&placeholder) {
            let source_html = highlight_code(&block.source, &block.language, config);
            let mut block_html = format!(r#"<div class="code-block-executed">{source_html}"#,);

            if let Some(ref output) = block.output
                && !output.is_empty()
            {
                block_html.push_str(&format!(
                    r#"<div class="code-output"><pre><code>{}</code></pre></div>"#,
                    escape_xml(output)
                ));
            }
            if let Some(ref error) = block.error
                && !error.is_empty()
            {
                block_html.push_str(&format!(
                    r#"<div class="code-error"><pre><code>{}</code></pre></div>"#,
                    escape_xml(error)
                ));
            }
            // Render visualization output (after text output, before closing div)
            for v in &block.viz {
                block_html.push_str(&render_viz_output(v));
            }
            block_html.push_str("</div>");
            // replacen with limit 1 so that an executed block whose output text
            // happens to contain another block's placeholder string does not
            // cause that later substitution to land in the wrong place.
            result = result.replacen(&placeholder, &block_html, 1);
        }
    }

    result
}

/// Render a single visualization output into HTML.
fn render_viz_output(viz: &VizOutput) -> String {
    match viz.kind.as_str() {
        "img" => {
            format!(
                r#"<div class="code-viz"><img src="{}" alt="Plot output"></div>"#,
                escape_xml(&viz.data)
            )
        }
        "html" => {
            // SAFETY: This raw HTML injection is intentional. Plotly/altair HTML contains
            // <script> tags required for interactive visualizations. Since executable code
            // blocks already run arbitrary Python, XSS via visualization output is not a
            // meaningful additional risk — the user already has full code execution.
            format!(r#"<div class="code-viz">{}</div>"#, viz.data)
        }
        _ => String::new(),
    }
}

/// Highlight a code block with syntect
fn highlight_code(code: &str, lang: &str, config: &MarkdownConfig) -> String {
    let ss = &*SYNTAX_SET;
    let ts = &*THEME_SET;
    let fallback = || {
        format!(
            "<pre><code class=\"language-{lang}\">{}</code></pre>",
            escape_xml(code)
        )
    };

    if !config.highlight_code || lang.is_empty() {
        return fallback();
    }

    let theme_name = config
        .highlight_theme
        .as_deref()
        .unwrap_or(DEFAULT_HIGHLIGHT_THEME);
    let syntax = ss
        .find_syntax_by_token(lang)
        .unwrap_or_else(|| ss.find_syntax_plain_text());
    let theme = ts
        .themes
        .get(theme_name)
        .unwrap_or(&ts.themes[DEFAULT_HIGHLIGHT_THEME]);

    highlighted_html_for_string(code, ss, syntax, theme).unwrap_or_else(|_| fallback())
}

/// Parse code block attributes like {python file="script.py"}
fn parse_code_attrs(lang: &str) -> (&str, Option<String>) {
    let parts: Vec<&str> = lang.splitn(2, ' ').collect();
    let actual_lang = parts[0];

    let file_ref = if parts.len() > 1 {
        FILE_ATTR_RE.captures(parts[1]).map(|c| c[1].to_string())
    } else {
        None
    };

    (actual_lang, file_ref)
}

fn is_external_url(url: &str, base_url: &str) -> bool {
    if !(url.starts_with("http://") || url.starts_with("https://")) {
        return false;
    }
    match (url_host(url), url_host(base_url)) {
        (Some(uh), Some(bh)) => !uh.eq_ignore_ascii_case(bh),
        // If we can't extract a host from base_url (misconfigured), treat any
        // absolute http(s) URL as external — matches the prior behaviour but
        // without the prefix-substring trap.
        _ => true,
    }
}

/// Extract the host component from an http(s) URL.
///
/// Returns the substring between `://` and the next `/`, `?`, or `#`. The
/// userinfo prefix (`user:pass@`) and `:port` suffix are stripped so two URLs
/// pointing at the same origin compare equal regardless of incidental syntax.
/// Returns `None` for inputs that aren't `http://` or `https://`.
fn url_host(url: &str) -> Option<&str> {
    let after_scheme = url
        .strip_prefix("https://")
        .or_else(|| url.strip_prefix("http://"))?;
    let end = after_scheme
        .find(['/', '?', '#'])
        .unwrap_or(after_scheme.len());
    let authority = &after_scheme[..end];
    // Strip userinfo (`user:pass@host`)
    let host_with_port = authority.rsplit_once('@').map_or(authority, |(_, h)| h);
    // Strip port (`host:8080`). For IPv6 the host is bracketed (`[::1]:8080`),
    // so only treat the LAST `:` as a port separator if there's no `]` after it.
    let host = if host_with_port.starts_with('[') {
        // IPv6 literal: keep through the closing bracket, drop any `:port` after.
        match host_with_port.rfind(']') {
            Some(idx) => &host_with_port[..=idx],
            None => host_with_port,
        }
    } else {
        host_with_port
            .rsplit_once(':')
            .map_or(host_with_port, |(h, _)| h)
    };
    if host.is_empty() { None } else { Some(host) }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::MarkdownConfig;
    use crate::execute::{ExecutableBlock, VizOutput};

    fn default_config() -> MarkdownConfig {
        MarkdownConfig::default()
    }

    #[test]
    fn test_render_basic_paragraph() {
        let mut blocks = Vec::new();
        let html = render_markdown(
            "Hello world",
            &default_config(),
            &mut blocks,
            "https://example.com",
        );
        assert!(html.contains("<p>Hello world</p>"));
    }

    #[test]
    fn test_render_code_block_highlighted() {
        let config = default_config();
        let mut blocks = Vec::new();
        let input = "```rust\nfn main() {}\n```";
        let html = render_markdown(input, &config, &mut blocks, "https://example.com");
        // Syntax highlighting produces <pre style="..."> tags from syntect
        assert!(html.contains("<pre"));
        assert!(blocks.is_empty());
    }

    #[test]
    fn test_toml_syntax_available() {
        let ss = &*SYNTAX_SET;
        assert!(
            ss.find_syntax_by_token("toml").is_some(),
            "TOML syntax should be available for highlighting"
        );
    }

    #[test]
    fn test_render_executable_block_detected() {
        let mut blocks = Vec::new();
        let input = "```{python}\nprint('hello')\n```";
        let html = render_markdown(input, &default_config(), &mut blocks, "https://example.com");
        assert_eq!(blocks.len(), 1);
        assert_eq!(blocks[0].language, "python");
        assert!(blocks[0].source.contains("print('hello')"));
        assert!(html.contains("<!-- EXEC_BLOCK_0 -->"));
    }

    #[test]
    fn test_render_table() {
        let mut blocks = Vec::new();
        let input = "| A | B |\n|---|---|\n| 1 | 2 |";
        let html = render_markdown(input, &default_config(), &mut blocks, "https://example.com");
        assert!(html.contains("<table>"));
        assert!(html.contains("<td>1</td>"));
    }

    #[test]
    fn test_render_heading_anchor_right() {
        let mut config = default_config();
        config.insert_anchor_links = AnchorLinks::Right;
        let mut blocks = Vec::new();
        let html = render_markdown(
            "## Hello World",
            &config,
            &mut blocks,
            "https://example.com",
        );
        assert!(html.contains("zorto-anchor"));
        assert!(html.contains("href=\"#hello-world\""));
        assert!(html.contains("id=\"hello-world\""));
    }

    #[test]
    fn test_render_heading_id_always_present() {
        let config = default_config(); // insert_anchor_links = "none"
        let mut blocks = Vec::new();
        let html = render_markdown(
            "## Hello World",
            &config,
            &mut blocks,
            "https://example.com",
        );
        assert!(!html.contains("zorto-anchor"));
        // Heading id should always be present even without anchor links
        assert!(html.contains("id=\"hello-world\""));
    }

    #[test]
    fn test_render_external_link_target_blank() {
        let mut config = default_config();
        config.external_links_target_blank = true;
        let mut blocks = Vec::new();
        let input = "[link](https://other.com)";
        let html = render_markdown(input, &config, &mut blocks, "https://example.com");
        assert!(html.contains(r#"target="_blank""#));
    }

    #[test]
    fn test_render_internal_link_no_target_blank() {
        let mut config = default_config();
        config.external_links_target_blank = true;
        let mut blocks = Vec::new();
        let input = "[link](https://example.com/page)";
        let html = render_markdown(input, &config, &mut blocks, "https://example.com");
        assert!(!html.contains("target="));
    }

    #[test]
    fn test_extract_summary_present() {
        let content = "First part\n<!-- more -->\nRest of content";
        let result = extract_summary(content);
        assert!(result.is_some());
        assert_eq!(result.unwrap(), "First part\n");
    }

    #[test]
    fn test_extract_summary_absent() {
        let content = "No summary marker here";
        assert!(extract_summary(content).is_none());
    }

    #[test]
    fn test_replace_exec_with_output() {
        let html = "before <!-- EXEC_BLOCK_0 --> after";
        let blocks = vec![ExecutableBlock {
            language: "python".into(),
            source: "print('hi')".into(),
            file_ref: None,
            output: Some("hi\n".into()),
            error: None,
            viz: Vec::new(),
        }];
        let result = replace_exec_placeholders(html, &blocks, &default_config());
        assert!(result.contains("code-block-executed"));
        assert!(result.contains("code-output"));
        assert!(result.contains("hi\n"));
        assert!(!result.contains("EXEC_BLOCK_0"));
    }

    #[test]
    fn test_replace_exec_with_error() {
        let html = "<!-- EXEC_BLOCK_0 -->";
        let blocks = vec![ExecutableBlock {
            language: "python".into(),
            source: "bad".into(),
            file_ref: None,
            output: None,
            error: Some("NameError".into()),
            viz: Vec::new(),
        }];
        let result = replace_exec_placeholders(html, &blocks, &default_config());
        assert!(result.contains("code-error"));
        assert!(result.contains("NameError"));
    }

    #[test]
    fn test_render_external_link_escapes_attributes() {
        let mut config = default_config();
        config.external_links_target_blank = true;
        let mut blocks = Vec::new();
        let input = r#"[xss](https://evil.com/"><script>alert(1)</script>)"#;
        let html = render_markdown(input, &config, &mut blocks, "https://example.com");
        assert!(!html.contains("<script>"));
        assert!(html.contains("&lt;script&gt;"));
    }

    #[test]
    fn test_render_callout_note() {
        let mut blocks = Vec::new();
        let input = "> [!NOTE]\n> This is a note.";
        let html = render_markdown(input, &default_config(), &mut blocks, "https://example.com");
        assert!(html.contains("callout callout--note"));
        assert!(html.contains("callout__title"));
        assert!(html.contains("Note"));
        assert!(html.contains("This is a note."));
    }

    #[test]
    fn test_render_callout_tip() {
        let mut blocks = Vec::new();
        let input = "> [!TIP]\n> Helpful advice here.";
        let html = render_markdown(input, &default_config(), &mut blocks, "https://example.com");
        assert!(html.contains("callout--tip"));
        assert!(html.contains("Tip"));
        assert!(html.contains("Helpful advice here."));
    }

    #[test]
    fn test_render_callout_warning() {
        let mut blocks = Vec::new();
        let input = "> [!WARNING]\n> Be careful.";
        let html = render_markdown(input, &default_config(), &mut blocks, "https://example.com");
        assert!(html.contains("callout--warning"));
        assert!(html.contains("Warning"));
    }

    #[test]
    fn test_render_callout_caution() {
        let mut blocks = Vec::new();
        let input = "> [!CAUTION]\n> Danger zone.";
        let html = render_markdown(input, &default_config(), &mut blocks, "https://example.com");
        assert!(html.contains("callout--caution"));
        assert!(html.contains("Caution"));
    }

    #[test]
    fn test_render_callout_important() {
        let mut blocks = Vec::new();
        let input = "> [!IMPORTANT]\n> Key info.";
        let html = render_markdown(input, &default_config(), &mut blocks, "https://example.com");
        assert!(html.contains("callout--important"));
        assert!(html.contains("Important"));
    }

    #[test]
    fn test_render_regular_blockquote_unchanged() {
        let mut blocks = Vec::new();
        let input = "> This is a regular blockquote.";
        let html = render_markdown(input, &default_config(), &mut blocks, "https://example.com");
        assert!(html.contains("<blockquote>"));
        assert!(!html.contains("callout"));
    }

    #[test]
    fn test_render_callout_with_multiple_paragraphs() {
        let mut blocks = Vec::new();
        let input = "> [!NOTE]\n> First paragraph.\n>\n> Second paragraph.";
        let html = render_markdown(input, &default_config(), &mut blocks, "https://example.com");
        assert!(html.contains("callout--note"));
        assert!(html.contains("First paragraph."));
        assert!(html.contains("Second paragraph."));
    }

    #[test]
    fn test_replace_exec_with_viz_img() {
        let html = "<!-- EXEC_BLOCK_0 -->";
        let blocks = vec![ExecutableBlock {
            language: "python".into(),
            source: "import matplotlib".into(),
            file_ref: None,
            output: Some(String::new()),
            error: None,
            viz: vec![VizOutput {
                kind: "img".into(),
                data: "data:image/png;base64,abc123".into(),
            }],
        }];
        let result = replace_exec_placeholders(html, &blocks, &default_config());
        assert!(result.contains("code-viz"));
        assert!(result.contains(r#"<img src="data:image/png;base64,abc123""#));
        assert!(result.contains(r#"alt="Plot output""#));
    }

    #[test]
    fn test_replace_exec_with_viz_html() {
        let html = "<!-- EXEC_BLOCK_0 -->";
        let blocks = vec![ExecutableBlock {
            language: "python".into(),
            source: "import plotly".into(),
            file_ref: None,
            output: Some(String::new()),
            error: None,
            viz: vec![VizOutput {
                kind: "html".into(),
                data: "<div id=\"plotly\">chart</div>".into(),
            }],
        }];
        let result = replace_exec_placeholders(html, &blocks, &default_config());
        assert!(result.contains("code-viz"));
        assert!(result.contains("<div id=\"plotly\">chart</div>"));
    }

    #[test]
    fn test_replace_exec_with_output_and_viz() {
        let html = "<!-- EXEC_BLOCK_0 -->";
        let blocks = vec![ExecutableBlock {
            language: "python".into(),
            source: "print('hello')".into(),
            file_ref: None,
            output: Some("hello\n".into()),
            error: None,
            viz: vec![VizOutput {
                kind: "img".into(),
                data: "data:image/png;base64,xyz".into(),
            }],
        }];
        let result = replace_exec_placeholders(html, &blocks, &default_config());
        // Both text output and viz should appear
        assert!(result.contains("code-output"));
        assert!(result.contains("code-viz"));
        // Viz should come after text output
        let output_pos = result.find("code-output").unwrap();
        let viz_pos = result.find("code-viz").unwrap();
        assert!(viz_pos > output_pos, "viz should appear after text output");
    }

    #[test]
    fn test_replace_exec_no_viz_no_overhead() {
        let html = "<!-- EXEC_BLOCK_0 -->";
        let blocks = vec![ExecutableBlock {
            language: "python".into(),
            source: "print('hi')".into(),
            file_ref: None,
            output: Some("hi\n".into()),
            error: None,
            viz: Vec::new(),
        }];
        let result = replace_exec_placeholders(html, &blocks, &default_config());
        assert!(!result.contains("code-viz"));
    }

    #[test]
    fn test_is_external_url() {
        assert!(is_external_url("https://other.com", "https://example.com"));
        assert!(is_external_url("http://other.com", "https://example.com"));
        assert!(!is_external_url(
            "https://example.com/page",
            "https://example.com"
        ));
        assert!(!is_external_url("/relative/path", "https://example.com"));
        assert!(!is_external_url("#anchor", "https://example.com"));
    }

    #[test]
    fn test_is_external_url_lookalike_domain() {
        // Regression: prefix-only check used to treat `example.com.evil.com`
        // as same-origin to `example.com`, suppressing the noreferrer/nofollow
        // hardening on exactly the URLs that need it most.
        assert!(is_external_url(
            "https://example.com.evil.com/path",
            "https://example.com"
        ));
        assert!(is_external_url(
            "https://example.com.evil.com/",
            "https://example.com"
        ));
        // Subdomain is also a different host.
        assert!(is_external_url(
            "https://sub.example.com/x",
            "https://example.com"
        ));
        // Same host on different scheme is still same-origin for our purposes.
        assert!(!is_external_url(
            "http://example.com/page",
            "https://example.com"
        ));
        // Host comparison is case-insensitive (DNS is).
        assert!(!is_external_url(
            "https://EXAMPLE.com/page",
            "https://example.com"
        ));
        // Userinfo and ports must not confuse the comparison.
        assert!(!is_external_url(
            "https://user:pass@example.com:8080/page",
            "https://example.com"
        ));
        // IPv6 host literal.
        assert!(is_external_url(
            "https://[2001:db8::1]/x",
            "https://example.com"
        ));
        assert!(!is_external_url(
            "https://[2001:db8::1]:8080/x",
            "https://[2001:db8::1]"
        ));
    }

    #[test]
    fn test_url_host_extraction() {
        assert_eq!(url_host("https://example.com"), Some("example.com"));
        assert_eq!(url_host("https://example.com/path"), Some("example.com"));
        assert_eq!(url_host("http://example.com:8080/x"), Some("example.com"));
        assert_eq!(
            url_host("https://user:pass@example.com/x"),
            Some("example.com")
        );
        assert_eq!(url_host("https://[2001:db8::1]"), Some("[2001:db8::1]"));
        assert_eq!(
            url_host("https://[2001:db8::1]:8080/x"),
            Some("[2001:db8::1]")
        );
        assert_eq!(url_host("/relative"), None);
        assert_eq!(url_host("ftp://x.com"), None);
    }

    #[test]
    fn test_replace_exec_placeholder_collision() {
        // Regression: block 0's output happens to contain block 1's placeholder
        // string. Without the replacen-with-limit-1 fix, the second pass would
        // substitute that copy and corrupt block 0's output.
        let html = "<!-- EXEC_BLOCK_0 -->\n<!-- EXEC_BLOCK_1 -->";
        let blocks = vec![
            ExecutableBlock {
                language: "python".into(),
                source: "print('a')".into(),
                file_ref: None,
                output: Some("<!-- EXEC_BLOCK_1 -->".into()),
                error: None,
                viz: Vec::new(),
            },
            ExecutableBlock {
                language: "python".into(),
                source: "print('b')".into(),
                file_ref: None,
                output: Some("BLOCK_ONE_OUTPUT".into()),
                error: None,
                viz: Vec::new(),
            },
        ];
        let result = replace_exec_placeholders(html, &blocks, &default_config());
        assert!(
            result.contains("BLOCK_ONE_OUTPUT"),
            "block 1 must still be replaced at its original position"
        );
        // Block 0's literal placeholder text in its output is HTML-escaped, so
        // the comment form is gone — but the escaped form must survive,
        // proving block 1's substitution did not consume it.
        assert!(
            result.contains("&lt;!-- EXEC_BLOCK_1 --&gt;"),
            "block 0's output (containing the escaped placeholder text) must survive"
        );
    }
}