Skip to main content

reflex/pulse/model/
mod.rs

1//! The Pulse Docs Model: a renderer-independent description of the whole site.
2//!
3//! ```text
4//! Site ─┬─ meta (title, repo permalinks)
5//!       ├─ tabs: Docs | Internals ── nav tree of PageIds
6//!       ├─ pages: PageId → Page { route, kind, blocks }
7//!       ├─ facts: FactId → Fact (every number, with provenance)
8//!       └─ report (broken links, excluded files)
9//! ```
10//!
11//! Builders in [`crate::pulse::build`] produce it from the index; the writing pass fills
12//! its narrative slots; a renderer turns it into files. The JSON form
13//! (`rfx pulse model --json`) is deterministic: no timestamps, sorted maps.
14
15pub mod content;
16pub mod evidence;
17pub mod facts;
18pub mod ids;
19pub mod text;
20pub mod xref;
21
22pub use content::{Block, Card, Inline, MarkdownOrigin, MarkdownText, ParamRow, Stat, SymbolBlock};
23pub use facts::{Fact, FactStore, FactValue, Provenance, Subject};
24pub use ids::{AnchorId, FactId, ModuleId, PageId, SlugAllocator, SymbolId};
25pub use xref::{Linker, RepoInfo, SourceLoc, Target};
26
27use serde::{Deserialize, Serialize};
28use std::collections::BTreeMap;
29
30/// Bump when the JSON shape changes incompatibly.
31pub const SCHEMA_VERSION: u32 = 1;
32
33#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
34pub struct Site {
35    pub schema_version: u32,
36    pub meta: SiteMeta,
37    pub tabs: Vec<Tab>,
38    pub pages: BTreeMap<PageId, Page>,
39    /// Every documented symbol and where it is documented.
40    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
41    pub symbols: BTreeMap<SymbolId, SymbolEntry>,
42    pub facts: FactStore,
43    pub report: BuildReport,
44    /// Evidence for each narrative slot (not part of the JSON model).
45    #[serde(skip)]
46    pub evidence: BTreeMap<String, evidence::EvidencePack>,
47    /// Every name the index knows, for the grounding gate (not part of the JSON model).
48    #[serde(skip)]
49    pub known_names: Vec<String>,
50}
51
52/// Where a symbol is documented.
53#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
54pub struct SymbolEntry {
55    pub name: String,
56    /// Language path (`reflex::query::QueryEngine`).
57    pub path: String,
58    pub kind: String,
59    pub page: PageId,
60    pub anchor: Option<AnchorId>,
61}
62
63#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
64pub struct SiteMeta {
65    pub title: String,
66    #[serde(skip_serializing_if = "Option::is_none")]
67    pub description: Option<String>,
68    #[serde(skip_serializing_if = "Option::is_none")]
69    pub repo: Option<RepoInfo>,
70    /// Version of rfx that built the model.
71    pub generator: String,
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
75#[serde(rename_all = "kebab-case")]
76pub enum TabId {
77    /// For people who use the code.
78    Docs,
79    /// For people who work on the code.
80    Internals,
81}
82
83impl TabId {
84    /// Route prefix of the tab's pages.
85    pub fn prefix(&self) -> &'static str {
86        match self {
87            TabId::Docs => "/docs/",
88            TabId::Internals => "/internals/",
89        }
90    }
91}
92
93#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
94pub struct Tab {
95    pub id: TabId,
96    pub label: String,
97    pub landing: PageId,
98    pub nav: Vec<NavNode>,
99}
100
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
102#[serde(tag = "type", rename_all = "kebab-case")]
103pub enum NavNode {
104    Page {
105        page: PageId,
106    },
107    Group {
108        label: String,
109        #[serde(default)]
110        collapsed: bool,
111        children: Vec<NavNode>,
112    },
113}
114
115impl NavNode {
116    pub fn page(id: &PageId) -> Self {
117        NavNode::Page { page: id.clone() }
118    }
119}
120
121pub(crate) fn collect_nav_pages(nav: &[NavNode], out: &mut Vec<PageId>) {
122    for n in nav {
123        match n {
124            NavNode::Page { page } => out.push(page.clone()),
125            NavNode::Group { children, .. } => collect_nav_pages(children, out),
126        }
127    }
128}
129
130#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
131pub struct Page {
132    pub id: PageId,
133    pub tab: TabId,
134    pub kind: PageKind,
135    pub title: String,
136    #[serde(skip_serializing_if = "Option::is_none")]
137    pub description: Option<String>,
138    /// Base-less route, e.g. `/internals/modules/src-pulse/`. Always ends with `/`.
139    pub route: String,
140    #[serde(default, skip_serializing_if = "Vec::is_empty")]
141    pub badges: Vec<String>,
142    pub blocks: Vec<Block>,
143}
144
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146#[serde(tag = "type", rename_all = "kebab-case")]
147pub enum PageKind {
148    /// Site home (Docs tab landing).
149    Landing,
150    /// Internals tab landing: how the system is put together.
151    Architecture,
152    /// One module (a directory of source files).
153    Module {
154        module: ModuleId,
155    },
156    /// All modules and their dependency graph.
157    DependencyMap,
158    Changelog,
159    Glossary,
160    /// A page built from a repository document.
161    Guide {
162        source: String,
163    },
164    /// A library module in the API reference.
165    ReferenceModule {
166        path: String,
167    },
168    /// A type (struct, enum, trait) in the API reference.
169    ReferenceType {
170        path: String,
171    },
172    /// A command in the CLI reference.
173    CliCommand {
174        command: String,
175    },
176}
177
178/// What the builder noticed while building.
179#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
180pub struct BuildReport {
181    /// Indexed files per role that produced no reference content (tests, fixtures, …).
182    pub files_by_role: BTreeMap<String, usize>,
183    pub broken_links: Vec<(PageId, Target)>,
184    pub warnings: Vec<String>,
185}
186
187impl Site {
188    /// Page ids in nav order for one tab, landing first.
189    pub fn nav_order(&self, tab: TabId) -> Vec<PageId> {
190        let Some(t) = self.tabs.iter().find(|t| t.id == tab) else {
191            return Vec::new();
192        };
193        let mut ids = vec![t.landing.clone()];
194        collect_nav_pages(&t.nav, &mut ids);
195        ids
196    }
197
198    /// Fill narrative slots from the writing pass. `text(slot)` returns the markdown for
199    /// a slot or `None` to keep the structural fallback.
200    pub fn fill_narratives(&mut self, mut text: impl FnMut(&str) -> Option<String>) -> usize {
201        fn fill(blocks: &mut [Block], text: &mut dyn FnMut(&str) -> Option<String>) -> usize {
202            let mut n = 0;
203            for b in blocks {
204                match b {
205                    Block::Narrative { slot, text: t, .. } => {
206                        if let Some(md) = text(slot) {
207                            *t = Some(MarkdownText {
208                                source: md,
209                                origin: MarkdownOrigin::Llm,
210                                from: None,
211                            });
212                            n += 1;
213                        }
214                    }
215                    Block::Callout { body, .. } => n += fill(body, text),
216                    _ => {}
217                }
218            }
219            n
220        }
221        self.pages
222            .values_mut()
223            .map(|p| fill(&mut p.blocks, &mut text))
224            .sum()
225    }
226
227    /// Every narrative slot id on the site, sorted.
228    pub fn narrative_slots(&self) -> Vec<String> {
229        let mut out = Vec::new();
230        for p in self.pages.values() {
231            for b in &p.blocks {
232                if let Block::Narrative { slot, .. } = b {
233                    out.push(slot.clone());
234                }
235            }
236        }
237        out.sort();
238        out.dedup();
239        out
240    }
241
242    /// Record every link that does not resolve in `report.broken_links`.
243    pub fn check_links(&mut self) {
244        let broken = Linker::new(self).broken();
245        self.report.broken_links = broken;
246    }
247
248    pub fn to_json(&self) -> serde_json::Result<String> {
249        serde_json::to_string_pretty(self)
250    }
251}