microsoft-webui-press 0.0.25

High-performance Static Site Generator powered by WebUI Framework
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
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Content pipeline: reads markdown files, parses frontmatter, builds page state.

use std::collections::HashMap;
use std::fs;
use std::path::Path;

use serde_json::{Map, Value};

use crate::error::{Error, Result};
use crate::markdown::{render_markdown, Highlighter};
use crate::state::{load_render_states, merge_page_state, LoadedStates};
use crate::types::{DocsConfig, NavLink, PageDescriptor, SidebarItem, SidebarSection};

/// Normalize a config link (e.g. `/guide/intro/` or `/guide/intro`) to a
/// canonical URL path that includes the site's `base_path` prefix and
/// **never** has a trailing slash (except for root, which is just the base).
/// GitHub Pages and most static hosts auto-redirect `/foo` → `/foo/index.html`,
/// so trailing slashes are unnecessary and pollute internal hrefs.
fn normalize_link(base: &str, link: &str) -> String {
    if link.is_empty() {
        return String::new();
    }
    // Tolerate config links written without a leading slash; also avoids a
    // panic when `link` starts with a multi-byte UTF-8 char (a bare `&link[1..]`
    // would slice mid-char and abort the build).
    let stripped = link.strip_prefix('/').unwrap_or(link);
    if link.contains('#') {
        // Fragment link — preserve original shape, don't touch the slash.
        return format!("{base}{stripped}");
    }
    let cleaned = stripped.trim_end_matches('/');
    if cleaned.is_empty() {
        // Root: `base` already ends with '/'.
        base.to_string()
    } else {
        format!("{base}{cleaned}")
    }
}

/// Build a JSON object from key-value pairs without using `json!` (which calls `unwrap`).
fn json_obj<const N: usize>(entries: [(&str, Value); N]) -> Value {
    let mut map = Map::with_capacity(N);
    for (k, v) in entries {
        map.insert(k.to_string(), v);
    }
    Value::Object(map)
}

/// Parsed frontmatter from a markdown file.
#[derive(Debug)]
struct Frontmatter {
    title: Option<String>,
    description: Option<String>,
    layout: Option<String>,
}

fn parse_frontmatter(content: &str) -> Result<(Frontmatter, &str)> {
    if !content.starts_with("---\n") && !content.starts_with("---\r\n") {
        return Ok((
            Frontmatter {
                title: None,
                description: None,
                layout: None,
            },
            content,
        ));
    }

    // Skip leading "---" + line ending.
    let body_start_marker = if content.starts_with("---\r\n") { 5 } else { 4 };
    let after_open = &content[body_start_marker..];

    // Find the closing "---" on its own line (preceded by `\n` or `\r\n`).
    let (yaml_end_offset, close_skip) = if let Some(i) = after_open.find("\r\n---") {
        (i, "\r\n---".len())
    } else if let Some(i) = after_open.find("\n---") {
        (i, "\n---".len())
    } else {
        (after_open.len(), 0)
    };

    let yaml_str = &after_open[..yaml_end_offset];
    let body_offset = body_start_marker + yaml_end_offset + close_skip;
    let body = if body_offset < content.len() {
        // Strip the line-ending immediately following the closing "---".
        let rest = &content[body_offset..];
        rest.strip_prefix("\r\n")
            .or_else(|| rest.strip_prefix('\n'))
            .unwrap_or(rest)
    } else {
        ""
    };

    let yaml: HashMap<String, serde_yaml::Value> = serde_yaml::from_str(yaml_str)
        .map_err(|e| crate::error::Error::Markdown(format!("Invalid frontmatter YAML: {e}")))?;

    Ok((
        Frontmatter {
            title: yaml.get("title").and_then(|v| v.as_str()).map(String::from),
            description: yaml
                .get("description")
                .and_then(|v| v.as_str())
                .map(String::from),
            layout: yaml
                .get("layout")
                .and_then(|v| v.as_str())
                .map(String::from),
        },
        body,
    ))
}

fn extract_h1(content: &str) -> Option<String> {
    for line in content.lines() {
        if let Some(heading) = line.strip_prefix("# ") {
            return Some(heading.trim().to_string());
        }
    }
    None
}

/// Collect all links from a sidebar item and its children (iterative).
fn collect_sidebar_links(items: &[SidebarItem]) -> Vec<&str> {
    let mut links = Vec::new();
    let mut stack: Vec<&SidebarItem> = items.iter().rev().collect();
    while let Some(item) = stack.pop() {
        if !item.link.is_empty() {
            links.push(item.link.as_str());
        }
        for child in item.items.iter().rev() {
            stack.push(child);
        }
    }
    links
}

/// Strip a redundant filename when it should resolve to its parent folder.
///
/// E.g., "my-button/my-button" → "my-button"
///       "my-button/usage" → "my-button/usage" (unchanged)
fn normalize_path_as_index(path: &str) -> &str {
    // Find the last slash to split parent/filename
    let Some(slash_pos) = path.rfind('/') else {
        return path;
    };

    let parent = &path[..slash_pos];
    let filename = &path[slash_pos + 1..];

    // Get the parent folder name (last segment before filename)
    let folder_name = parent.rsplit('/').next().unwrap_or("");

    // If folder name matches filename, treat as index and strip filename
    if folder_name == filename {
        parent
    } else {
        path
    }
}

/// Resolve the public URL path for a markdown file.
///
/// `rel_path` is the file's path relative to the content directory, using
/// forward slashes (e.g. `guide/install.md`). A nav entry that claims this
/// file via its `source` field wins outright, which lets a page keep a stable
/// URL when its filename is dictated by an outside convention. Any fragment
/// (`#`) or query string (`?`) in the override link is stripped before the
/// route is formed — they are navigation-only markers that cannot appear in a
/// filesystem path and would break prev/next matching against normalized
/// sidebar links. Otherwise the URL is derived from the filesystem: `.md` is
/// dropped, then a trailing `index` — or a filename that repeats its parent
/// folder — collapses to the folder.
fn page_url_path(rel_path: &str, base_path: &str, sources: &HashMap<&str, &str>) -> String {
    let prefix = base_path.trim_end_matches('/');

    if let Some(&link) = sources.get(rel_path) {
        // Strip any fragment (#) or query (?) — they are navigation-only and
        // cannot appear in a filesystem-derived route or match sidebar links.
        let end = link.find(['#', '?']).unwrap_or(link.len());
        let link = &link[..end];
        let cleaned = link.trim_matches('/');
        return if cleaned.is_empty() {
            format!("{prefix}/")
        } else {
            format!("{prefix}/{cleaned}")
        };
    }

    let trimmed = rel_path.trim_end_matches(".md");
    let trimmed = trimmed.strip_suffix("/index").unwrap_or(trimmed);
    let trimmed = normalize_path_as_index(trimmed);

    if trimmed.is_empty() || trimmed == "index" {
        format!("{prefix}/")
    } else {
        format!("{prefix}/{trimmed}")
    }
}

fn markdown_link_base_url(source_path: &Path, content_dir: &Path, base_path: &str) -> String {
    let parent = source_path
        .strip_prefix(content_dir)
        .ok()
        .and_then(Path::parent);
    let parent = parent
        .filter(|path| !path.as_os_str().is_empty())
        .map(|path| path.to_string_lossy().replace('\\', "/"))
        .unwrap_or_default();

    let prefix = base_path.trim_end_matches('/');
    let parent = parent.trim_matches('/');
    let mut url = String::with_capacity(prefix.len() + parent.len() + 2);
    url.push_str(prefix);
    url.push('/');
    if !parent.is_empty() {
        url.push_str(parent);
        url.push('/');
    }
    url
}

/// Map each nav entry that declares a `source` file to its configured link.
///
/// Keys are content-relative markdown paths; values are raw config links.
/// Entries whose `link` starts with `http` are excluded because `source` is
/// only meaningful for internal routes; pairing it with an external URL would
/// produce an invalid route in `page_url_path`.
fn nav_source_overrides(nav: &[NavLink]) -> HashMap<&str, &str> {
    nav.iter()
        .filter_map(|item| {
            let source = item.source.as_deref()?;
            if item.link.starts_with("http") {
                return None;
            }
            Some((source, item.link.as_str()))
        })
        .collect()
}

/// Build the page registry by walking content_dir for every `.md` file.
///
/// Discovery is filesystem-driven: any markdown file under content_dir becomes
/// a page. The sidebar/nav config controls navigation, not discovery.
fn build_page_registry(
    content_dir: &Path,
    base_path: &str,
    sources: &HashMap<&str, &str>,
) -> Vec<(String, std::path::PathBuf)> {
    let mut pages = Vec::new();
    let mut stack: Vec<std::path::PathBuf> = vec![content_dir.to_path_buf()];

    while let Some(dir) = stack.pop() {
        let Ok(entries) = fs::read_dir(&dir) else {
            continue;
        };
        for entry in entries.flatten() {
            let path = entry.path();
            // Skip dotfiles/dotdirs and the build output.
            let name = entry.file_name();
            let name_str = name.to_string_lossy();
            if name_str.starts_with('.') || name_str == "dist" || name_str == "node_modules" {
                continue;
            }
            if path.is_dir() {
                stack.push(path);
                continue;
            }
            if path.extension().and_then(|s| s.to_str()) != Some("md") {
                continue;
            }

            let rel = match path.strip_prefix(content_dir) {
                Ok(r) => r,
                Err(_) => continue,
            };
            let rel_str = rel.to_string_lossy().replace('\\', "/");
            pages.push((page_url_path(&rel_str, base_path, sources), path));
        }
    }

    pages.sort_by(|a, b| a.0.cmp(&b.0));
    pages
}

fn build_sidebar_state(url_path: &str, config: &DocsConfig) -> serde_json::Value {
    let base = &config.base_path;

    // Determine active sidebar
    let active_sidebar = config
        .sidebar_groups
        .iter()
        .find(|(prefix, _)| {
            let full_prefix = format!("{}{}", base, prefix.strip_prefix('/').unwrap_or(prefix));
            let trimmed = full_prefix.trim_end_matches('/');
            url_path == trimmed || url_path.starts_with(&format!("{trimmed}/"))
        })
        .map(|(_, s)| s.as_slice())
        .unwrap_or(&config.sidebar);

    // Convert a SidebarItem to a JSON value (iterative via stack for children)
    let item_to_value = |item: &SidebarItem| -> Value {
        let item_path = normalize_link(base, &item.link);
        let active = !item_path.is_empty() && item_path == url_path;
        let children: Vec<Value> = item
            .items
            .iter()
            .map(|child| {
                let child_path = normalize_link(base, &child.link);
                let child_active = !child_path.is_empty() && child_path == url_path;
                json_obj([
                    ("text", Value::String(child.text.clone())),
                    ("link", Value::String(child_path)),
                    ("active", Value::Bool(child_active)),
                    ("hasChildren", Value::Bool(false)),
                    ("children", Value::Array(vec![])),
                ])
            })
            .collect();
        json_obj([
            ("text", Value::String(item.text.clone())),
            ("link", Value::String(item_path)),
            ("active", Value::Bool(active)),
            ("hasChildren", Value::Bool(!children.is_empty())),
            ("children", Value::Array(children)),
        ])
    };

    let sections: Vec<Value> = active_sidebar
        .iter()
        .map(|section| {
            let items: Vec<Value> = section.items.iter().map(item_to_value).collect();
            json_obj([
                ("title", Value::String(section.title.clone())),
                ("items", Value::Array(items)),
            ])
        })
        .collect();

    json_obj([("sections", Value::Array(sections))])
}

fn find_sidebar_text(url_path: &str, config: &DocsConfig) -> Option<String> {
    let base = &config.base_path;
    let all: Vec<&[SidebarSection]> = std::iter::once(config.sidebar.as_slice())
        .chain(config.sidebar_groups.values().map(|v| v.as_slice()))
        .collect();

    for sidebar in all {
        for section in sidebar {
            // Use iterative stack to search nested items
            let mut stack: Vec<&SidebarItem> = section.items.iter().collect();
            while let Some(item) = stack.pop() {
                if !item.link.is_empty() {
                    let item_path = normalize_link(base, &item.link);
                    if item_path == url_path {
                        return Some(item.text.clone());
                    }
                }
                for child in &item.items {
                    stack.push(child);
                }
            }
        }
    }
    None
}

/// Process all content files and return page descriptors.
///
/// `config_dir` is the directory containing `config.json`; relative paths
/// declared in the config (such as a custom page's `stateFile`) are resolved
/// against it.
///
/// `head_injection` is the fully-resolved `<head>` snippet (CSS link
/// tags + `config.head` entries). It MUST be computed before this call
/// so the descriptor is render-ready.
#[allow(dead_code)] // Public library API; the binary uses preloaded state for 404 parity.
pub fn process_content(
    config: &DocsConfig,
    config_dir: &Path,
    highlighter: &Highlighter,
    head_injection: &str,
) -> Result<Vec<PageDescriptor>> {
    let states = load_render_states(config, config_dir)?;
    process_content_with_states(config, highlighter, head_injection, &states)
}

pub(crate) fn process_content_with_states(
    config: &DocsConfig,
    highlighter: &Highlighter,
    head_injection: &str,
    states: &LoadedStates,
) -> Result<Vec<PageDescriptor>> {
    let content_dir = Path::new(&config.content_dir);
    let base_path = &config.base_path;

    let nav_links: Vec<Value> = config
        .nav
        .iter()
        .map(|item| {
            let (link, section) = if item.link.starts_with("http") {
                // External links can never match a docs section. Use the URL
                // itself as a unique sentinel so the equality check below
                // never matches any page's section slug.
                (item.link.clone(), item.link.clone())
            } else {
                let full = format!("{}{}", base_path, &item.link[1..]);
                // Derive a section slug from the raw config link, e.g. "/guide/" -> "guide".
                let slug = item
                    .link
                    .trim_start_matches('/')
                    .split('/')
                    .next()
                    .unwrap_or("")
                    .to_string();
                (full, slug)
            };
            json_obj([
                ("text", Value::String(item.text.clone())),
                ("link", Value::String(link)),
                ("section", Value::String(section)),
            ])
        })
        .collect();

    let mut registry =
        build_page_registry(content_dir, base_path, &nav_source_overrides(&config.nav));

    // Register custom pages
    for page_link in config.custom_pages.keys() {
        let normalized = if page_link.ends_with('/') {
            page_link.clone()
        } else {
            format!("{}/", page_link)
        };
        let url_path = format!("{}{}", base_path, &normalized[1..]);
        let src_file = format!("{}index.md", &normalized[1..]);
        let full_path = content_dir.join(&src_file);
        if !registry.iter().any(|(p, _)| p == &url_path) {
            registry.push((url_path, full_path));
        }
    }

    use rayon::prelude::*;

    // Per-page processing: parse markdown / load custom HTML, expand
    // syntax highlighting, build the state JSON. Always runs for every
    // page on every call — there is no descriptor cache. The dev
    // server keeps a `BuildCache` only to amortize the syntect
    // highlighter load.
    let results: Vec<(usize, PageDescriptor)> = registry
        .par_iter()
        .enumerate()
        .map(
            |(idx, (url_path, full_path))| -> Result<(usize, PageDescriptor)> {
                let mut is_home = false;
                let mut html = String::new();
                let mut title = config.site.title.clone();
                let mut description = config.site.description.clone();
                let mut layout = "doc".to_string();

                // Check custom page override
                let logical_path = format!("/{}", &url_path[base_path.len()..]);
                let custom_entry = config
                    .custom_pages
                    .get(&logical_path)
                    .or_else(|| config.custom_pages.get(logical_path.trim_end_matches('/')));
                let custom_state = states.custom_page_state(&logical_path);

                if let Some(entry) = custom_entry {
                    html = entry.html().to_string();
                    layout = entry.layout().to_string();
                } else if full_path.exists() {
                    let raw = fs::read_to_string(full_path)
                        .map_err(|e| crate::error::Error::Io(e.to_string()))?;
                    let (fm, body) = parse_frontmatter(&raw).map_err(|e| {
                        crate::error::Error::Markdown(format!("{}: {e}", full_path.display()))
                    })?;

                    is_home = fm.layout.as_deref() == Some("home");
                    layout = if is_home {
                        "home".to_string()
                    } else {
                        fm.layout.unwrap_or_else(|| "doc".to_string())
                    };

                    if !is_home {
                        // Canonical page URL: every page is written as
                        // `<dir>/index.html`, so it is served with a trailing
                        // slash. In-page anchors need this exact path so they
                        // aren't resolved against `<base href>`.
                        let page_url = if url_path.ends_with('/') {
                            url_path.to_string()
                        } else {
                            format!("{url_path}/")
                        };
                        let link_base_url =
                            markdown_link_base_url(full_path, content_dir, base_path);
                        html = render_markdown(
                            body,
                            highlighter,
                            base_path,
                            &page_url,
                            &link_base_url,
                        )?;
                    }

                    if let Some(d) = fm.description {
                        description = d;
                    }

                    let h1 = extract_h1(body);
                    let sidebar_text = find_sidebar_text(url_path, config);
                    title = fm
                        .title
                        .or(h1)
                        .or(sidebar_text)
                        .unwrap_or_else(|| config.site.title.clone());
                }

                let hero_val = if is_home {
                    config
                        .hero
                        .as_ref()
                        .map(|h| {
                            json_obj([
                                (
                                    "text",
                                    h.text
                                        .as_ref()
                                        .map_or(Value::Null, |t| Value::String(t.clone())),
                                ),
                                ("tagline", Value::String(h.tagline.clone())),
                                (
                                    "manifesto",
                                    h.manifesto
                                        .as_ref()
                                        .map_or(Value::Null, |m| Value::String(m.clone())),
                                ),
                                (
                                    "actions",
                                    Value::Array(
                                        h.actions
                                            .iter()
                                            .map(|a| {
                                                json_obj([
                                                    ("text", Value::String(a.text.clone())),
                                                    ("link", Value::String(a.link.clone())),
                                                    ("brand", Value::Bool(a.brand)),
                                                ])
                                            })
                                            .collect(),
                                    ),
                                ),
                                (
                                    "features",
                                    Value::Array(
                                        h.features
                                            .iter()
                                            .map(|f| {
                                                json_obj([
                                                    ("icon", Value::String(f.icon.clone())),
                                                    ("title", Value::String(f.title.clone())),
                                                    (
                                                        "description",
                                                        Value::String(f.description.clone()),
                                                    ),
                                                ])
                                            })
                                            .collect(),
                                    ),
                                ),
                            ])
                        })
                        .unwrap_or(Value::Null)
                } else {
                    Value::Null
                };

                let footer_val = config
                    .footer
                    .as_ref()
                    .map(|f| json_obj([("html", Value::String(f.html.clone()))]))
                    .unwrap_or(Value::Null);

                // Top-level section slug for the current page, derived from the
                // first path segment after the base. Used by the nav template to
                // mark the active link via `?active="{{link.section == page.section}}"`.
                let page_section = logical_path
                    .trim_start_matches('/')
                    .split('/')
                    .next()
                    .unwrap_or("")
                    .to_string();

                let state = json_obj([
                    (
                        "site",
                        json_obj([
                            ("title", Value::String(config.site.title.clone())),
                            ("base", Value::String(base_path.to_string())),
                        ]),
                    ),
                    ("navigation", Value::Array(nav_links.clone())),
                    ("sidebar", build_sidebar_state(url_path, config)),
                    (
                        "page",
                        json_obj([
                            ("title", Value::String(title.clone())),
                            ("description", Value::String(description.clone())),
                            ("content", Value::String(html.clone())),
                            ("isHome", Value::Bool(is_home)),
                            ("layout", Value::String(layout)),
                            ("section", Value::String(page_section)),
                        ]),
                    ),
                    ("hero", hero_val),
                    ("footer", footer_val),
                    ("prev", Value::Null),
                    ("next", Value::Null),
                    ("pageData", custom_state.cloned().unwrap_or(Value::Null)),
                    ("headTags", Value::String(head_injection.to_string())),
                    ("label", Value::String("Copy".to_string())),
                    ("icon", Value::String("🌙".to_string())),
                ]);

                // Flatten shared state first, then custom-page state. Component
                // templates can bind directly to these fields (e.g.
                // `<for each="item in files">`) while reserved docs keys keep
                // their canonical values.
                let state = merge_page_state(state, states.global(), custom_state);

                Ok((
                    idx,
                    PageDescriptor {
                        path: url_path.clone(),
                        is_home,
                        state,
                    },
                ))
            },
        )
        .collect::<Result<Vec<_>>>()?;

    // Build prev/next links from the sidebar that matches each page's URL.
    // We resolve the active sidebar per-page by checking sidebar_groups
    // prefixes, then falling back to the default config.sidebar.
    let resolve_sidebar = |page_path: &str| -> Vec<SidebarItem> {
        let active = config
            .sidebar_groups
            .iter()
            .find(|(prefix, _)| {
                let full_prefix = format!(
                    "{}{}",
                    base_path,
                    prefix.strip_prefix('/').unwrap_or(prefix)
                );
                let trimmed = full_prefix.trim_end_matches('/');
                page_path == trimmed || page_path.starts_with(&format!("{trimmed}/"))
            })
            .map(|(_, s)| s.as_slice())
            .unwrap_or(&config.sidebar);
        active.iter().flat_map(|s| s.items.clone()).collect()
    };

    // Restore canonical (registry) order and apply prev/next to each
    // descriptor. Carrying the registry index explicitly through the
    // parallel pass avoids depending on `par_iter().collect()`'s
    // implicit order-preservation contract.
    let mut pages: Vec<Option<PageDescriptor>> = (0..results.len()).map(|_| None).collect();
    for (idx, mut desc) in results {
        let sidebar_items = resolve_sidebar(&desc.path);
        let flat_links = collect_sidebar_links(&sidebar_items);
        let all_links: Vec<(String, String)> = flat_links
            .iter()
            .map(|link| {
                let path = normalize_link(base_path, link);
                let text = find_sidebar_text(&path, config).unwrap_or_default();
                (path, text)
            })
            .collect();
        if let Some(pos) = all_links.iter().position(|(p, _)| p == &desc.path) {
            if pos > 0 {
                let (link, text) = &all_links[pos - 1];
                desc.state["prev"] = json_obj([
                    ("link", Value::String(link.clone())),
                    ("text", Value::String(text.clone())),
                ]);
            }
            if pos + 1 < all_links.len() {
                let (link, text) = &all_links[pos + 1];
                desc.state["next"] = json_obj([
                    ("link", Value::String(link.clone())),
                    ("text", Value::String(text.clone())),
                ]);
            }
        }
        pages[idx] = Some(desc);
    }
    let pages: Vec<PageDescriptor> = pages
        .into_iter()
        .enumerate()
        .map(|(i, slot)| {
            slot.ok_or_else(|| Error::Build(format!("missing page at registry index {i}")))
        })
        .collect::<Result<Vec<_>>>()?;

    Ok(pages)
}

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

    // --- normalize_link --------------------------------------------------

    #[test]
    fn normalize_link_empty_returns_empty() {
        assert_eq!(normalize_link("/webui/", ""), "");
    }

    #[test]
    fn normalize_link_root_slash_returns_base() {
        assert_eq!(normalize_link("/webui/", "/"), "/webui/");
    }

    #[test]
    fn normalize_link_trims_trailing_slash() {
        assert_eq!(
            normalize_link("/webui/", "/guide/intro/"),
            "/webui/guide/intro"
        );
        assert_eq!(
            normalize_link("/webui/", "/guide/intro"),
            "/webui/guide/intro"
        );
    }

    #[test]
    fn normalize_link_preserves_fragment() {
        assert_eq!(
            normalize_link("/webui/", "/guide/intro#section"),
            "/webui/guide/intro#section"
        );
    }

    #[test]
    fn normalize_link_tolerates_missing_leading_slash() {
        // Was previously a slice-from-1 panic risk on multi-byte chars.
        assert_eq!(
            normalize_link("/webui/", "guide/intro"),
            "/webui/guide/intro"
        );
    }

    #[test]
    fn normalize_link_tolerates_non_ascii_first_char() {
        // `&link[1..]` would have panicked here on UTF-8 boundary.
        let out = normalize_link("/webui/", "é-page");
        assert!(out.ends_with("é-page"), "got {out}");
    }

    // --- normalize_path_as_index -----------------------------------------

    #[test]
    fn normalize_path_as_index_strips_duplicate_folder_name() {
        assert_eq!(
            normalize_path_as_index("webui-button/webui-button"),
            "webui-button"
        );
    }

    #[test]
    fn normalize_path_as_index_keeps_different_filename() {
        assert_eq!(
            normalize_path_as_index("webui-button/usage"),
            "webui-button/usage"
        );
    }

    #[test]
    fn normalize_path_as_index_nested_folders() {
        assert_eq!(
            normalize_path_as_index("components/webui-button/webui-button"),
            "components/webui-button"
        );
    }

    #[test]
    fn normalize_path_as_index_no_slash_returns_unchanged() {
        assert_eq!(normalize_path_as_index("webui-button"), "webui-button");
    }

    // --- page_url_path ----------------------------------------------------

    fn sources(pairs: &[(&'static str, &'static str)]) -> HashMap<&'static str, &'static str> {
        pairs.iter().copied().collect()
    }

    #[test]
    fn page_url_path_derives_url_from_filesystem() {
        let none = sources(&[]);
        assert_eq!(
            page_url_path("guide/install.md", "/webui/", &none),
            "/webui/guide/install"
        );
    }

    #[test]
    fn page_url_path_collapses_index_and_root() {
        let none = sources(&[]);
        assert_eq!(
            page_url_path("guide/index.md", "/webui/", &none),
            "/webui/guide"
        );
        assert_eq!(page_url_path("index.md", "/webui/", &none), "/webui/");
        assert_eq!(page_url_path("index.md", "", &none), "/");
    }

    #[test]
    fn page_url_path_collapses_filename_repeating_its_folder() {
        let none = sources(&[]);
        assert_eq!(
            page_url_path("components/webui-button/webui-button.md", "/webui/", &none),
            "/webui/components/webui-button"
        );
    }

    #[test]
    fn page_url_path_nav_source_overrides_derived_url() {
        // `SKILL.md` is a filename fixed by the agent-skill spec; the nav entry
        // keeps the page on `/ai` instead of leaking it as `/ai/SKILL`.
        let map = sources(&[("ai/SKILL.md", "/ai")]);
        assert_eq!(page_url_path("ai/SKILL.md", "/webui/", &map), "/webui/ai");
    }

    #[test]
    fn page_url_path_nav_source_tolerates_surrounding_slashes() {
        let map = sources(&[("ai/SKILL.md", "ai/"), ("b/SKILL.md", "/b")]);
        assert_eq!(page_url_path("ai/SKILL.md", "/webui/", &map), "/webui/ai");
        assert_eq!(page_url_path("b/SKILL.md", "", &map), "/b");
    }

    #[test]
    fn page_url_path_nav_source_can_target_site_root() {
        let map = sources(&[("home/landing.md", "/")]);
        assert_eq!(page_url_path("home/landing.md", "/webui/", &map), "/webui/");
    }

    #[test]
    fn page_url_path_ignores_nav_source_for_other_files() {
        let map = sources(&[("ai/SKILL.md", "/ai")]);
        assert_eq!(
            page_url_path("guide/SKILL.md", "/webui/", &map),
            "/webui/guide/SKILL"
        );
    }

    #[test]
    fn page_url_path_nav_source_strips_fragment_from_override() {
        // A nav link like "/ai#rules" must route to "/ai", not "/ai#rules".
        let map = sources(&[("ai/SKILL.md", "/ai#rules")]);
        assert_eq!(page_url_path("ai/SKILL.md", "/webui/", &map), "/webui/ai");
    }

    #[test]
    fn page_url_path_nav_source_strips_query_from_override() {
        // A nav link like "/ai?v=2" must route to "/ai", not "/ai?v=2".
        let map = sources(&[("ai/SKILL.md", "/ai?v=2")]);
        assert_eq!(page_url_path("ai/SKILL.md", "/webui/", &map), "/webui/ai");
    }

    #[test]
    fn markdown_link_base_uses_source_directory_for_index_and_leaf_pages() {
        let content_dir = Path::new("docs");
        assert_eq!(
            markdown_link_base_url(Path::new("docs/guide/index.md"), content_dir, "/webui/"),
            "/webui/guide/"
        );
        assert_eq!(
            markdown_link_base_url(
                Path::new("docs/guide/installation.md"),
                content_dir,
                "/webui/"
            ),
            "/webui/guide/"
        );
        assert_eq!(
            markdown_link_base_url(
                Path::new("docs/guide/topic/index.md"),
                content_dir,
                "/webui/"
            ),
            "/webui/guide/topic/"
        );
    }

    // --- nav_source_overrides ---------------------------------------------

    fn nav_link(text: &str, link: &str, source: Option<&str>) -> NavLink {
        NavLink {
            text: text.to_string(),
            link: link.to_string(),
            source: source.map(String::from),
        }
    }

    #[test]
    fn nav_source_overrides_collects_only_entries_declaring_a_source() {
        let nav = vec![
            nav_link("Guide", "/guide/", None),
            nav_link("AI", "/ai", Some("ai/SKILL.md")),
            nav_link("GitHub", "https://github.com/microsoft/webui", None),
        ];
        let map = nav_source_overrides(&nav);
        assert_eq!(map.len(), 1);
        assert_eq!(map.get("ai/SKILL.md"), Some(&"/ai"));
    }

    #[test]
    fn nav_source_overrides_empty_nav_yields_no_overrides() {
        assert!(nav_source_overrides(&[]).is_empty());
    }

    #[test]
    fn nav_source_overrides_excludes_external_link_with_source() {
        // Accidentally pairing `source` with an external URL must be silently
        // dropped so it never reaches `page_url_path` as a broken route.
        let nav = vec![
            nav_link("AI", "/ai", Some("ai/SKILL.md")),
            nav_link(
                "GitHub",
                "https://github.com/microsoft/webui",
                Some("github.md"),
            ),
        ];
        let map = nav_source_overrides(&nav);
        assert_eq!(map.len(), 1);
        assert_eq!(map.get("ai/SKILL.md"), Some(&"/ai"));
        assert!(!map.contains_key("github.md"));
    }

    #[test]
    fn normalize_path_as_index_deep_nesting_with_match() {
        assert_eq!(
            normalize_path_as_index("a/b/c/webui-card/webui-card"),
            "a/b/c/webui-card"
        );
    }

    #[test]
    fn normalize_path_as_index_deep_nesting_without_match() {
        assert_eq!(
            normalize_path_as_index("a/b/c/webui-card/examples"),
            "a/b/c/webui-card/examples"
        );
    }

    // --- parse_frontmatter -----------------------------------------------

    #[test]
    fn parse_frontmatter_no_frontmatter_returns_full_body() {
        let (fm, body) = parse_frontmatter("# Hello\nworld\n").expect("ok");
        assert!(fm.title.is_none());
        assert!(fm.layout.is_none());
        assert_eq!(body, "# Hello\nworld\n");
    }

    #[test]
    fn parse_frontmatter_valid_yaml_extracts_fields() {
        let raw = "---\ntitle: Hello\ndescription: World\nlayout: home\n---\n# Body\n";
        let (fm, body) = parse_frontmatter(raw).expect("ok");
        assert_eq!(fm.title.as_deref(), Some("Hello"));
        assert_eq!(fm.description.as_deref(), Some("World"));
        assert_eq!(fm.layout.as_deref(), Some("home"));
        assert_eq!(body, "# Body\n");
    }

    #[test]
    fn parse_frontmatter_handles_crlf_line_endings() {
        let raw = "---\r\ntitle: CRLF\r\nlayout: doc\r\n---\r\n# Body\r\n";
        let (fm, body) = parse_frontmatter(raw).expect("ok");
        assert_eq!(fm.title.as_deref(), Some("CRLF"));
        assert_eq!(fm.layout.as_deref(), Some("doc"));
        assert_eq!(body, "# Body\r\n");
    }

    #[test]
    fn parse_frontmatter_malformed_yaml_returns_error() {
        // `: : :` is not valid YAML.
        let raw = "---\ntitle: : : :\n---\nBody\n";
        let result = parse_frontmatter(raw);
        assert!(result.is_err(), "expected error, got {result:?}");
    }
}