Skip to main content

adk_site/generator/
mod.rs

1//! Site generators and the built-in renderer (spec 3.5 §7.8 "Generator", §7.4 "Machine view
2//! of every page", §7.8.2 step 5).
3//!
4//! [`BuiltinGenerator`] renders Markdown and templates with no plugins. For every page it
5//! writes `index.html`, the Markdown twin `index.md` and the structured twin
6//! `index.awp.json` (an awp-types [`MachineView`](awp_types::MachineView)), linked from the
7//! HTML with `<link rel="alternate">`; and for the site `llms.txt`, `robots.txt` with
8//! `Content-Usage` from the charter's public terms, `/.well-known/security.txt`, sitemaps
9//! with `lastmod`, Atom feeds, `/.well-known/awp/charter.json`, schema.org JSON-LD per content
10//! kind, and redirects in the host's format.
11//!
12//! Output is deterministic: identical projects give byte-identical files. Incremental builds
13//! render the changed items and their dependents only, from the [`DependencyGraph`] of the
14//! previous build, and give the same files a full build gives.
15
16#[cfg(any(
17    feature = "gen-zola",
18    feature = "gen-hugo",
19    feature = "gen-astro",
20    feature = "gen-build-awesome"
21))]
22pub mod external;
23mod files;
24mod plan;
25mod render;
26
27use std::collections::{BTreeMap, BTreeSet};
28use std::path::Path;
29use std::sync::Arc;
30
31use async_trait::async_trait;
32use awp_types::{ContentId, GeneratorRef, LanguageTag, Redirect};
33use serde::{Deserialize, Serialize};
34
35use crate::content::SiteProject;
36use crate::error::{Result, SiteError};
37
38pub use files::CHARTER_PATH;
39pub use plan::DepKey;
40pub use render::markdown_to_html;
41
42/// Builds a site's files from a project (spec 3.5 §7.8).
43///
44/// External generators (`gen-zola`, `gen-hugo`, …) implement it as sandboxed processes;
45/// [`BuiltinGenerator`] is the default.
46#[async_trait]
47pub trait SiteGenerator: Send + Sync {
48    /// Builds every file of `project` into `out`, leaving nothing else there.
49    ///
50    /// # Errors
51    ///
52    /// Returns an error when the project is invalid, a template fails or `out` cannot be
53    /// written.
54    async fn build(&self, project: &SiteProject, out: &Path) -> Result<BuildReport>;
55
56    /// Rebuilds in `out`, which holds the build `changes.previous` describes, only what the
57    /// changed items affect. Generators without dependency tracking build everything.
58    ///
59    /// # Errors
60    ///
61    /// As [`build`](Self::build).
62    async fn build_incremental(
63        &self,
64        project: &SiteProject,
65        out: &Path,
66        changes: &ChangeSet,
67    ) -> Result<BuildReport> {
68        let _ = changes;
69        self.build(project, out).await
70    }
71}
72
73/// What changed since the previous build.
74#[derive(Debug, Clone, Default)]
75pub struct ChangeSet {
76    /// The items added, edited, removed, scheduled or withdrawn.
77    pub items: BTreeSet<ContentId>,
78    /// The previous build's dependency graph.
79    pub previous: DependencyGraph,
80}
81
82/// Which outputs depend on what, and what each item touches (spec 3.5 §7.8.2 step 5).
83#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
84#[serde(rename_all = "camelCase")]
85pub struct DependencyGraph {
86    /// Output path → the keys it depends on.
87    pub outputs: BTreeMap<String, BTreeSet<DepKey>>,
88    /// Item → the keys it touches.
89    pub footprints: BTreeMap<ContentId, BTreeSet<DepKey>>,
90    /// Language → navigation signature.
91    pub nav: BTreeMap<String, String>,
92    /// Translation group (`<kind>/<slug>`) → alternates signature.
93    pub groups: BTreeMap<String, String>,
94}
95
96impl DependencyGraph {
97    /// The keys a change to `items` touches between this (previous) graph and `next`.
98    pub fn affected_keys(
99        &self,
100        next: &DependencyGraph,
101        items: &BTreeSet<ContentId>,
102    ) -> BTreeSet<DepKey> {
103        let mut keys = BTreeSet::new();
104        for id in items {
105            keys.insert(DepKey::Item { id: id.clone() });
106            for graph in [self, next] {
107                if let Some(footprint) = graph.footprints.get(id) {
108                    keys.extend(footprint.iter().cloned());
109                }
110            }
111        }
112        let languages: BTreeSet<&String> = self.nav.keys().chain(next.nav.keys()).collect();
113        for language in languages {
114            if self.nav.get(language) != next.nav.get(language) {
115                keys.insert(DepKey::Nav { language: language.clone() });
116            }
117        }
118        let groups: BTreeSet<&String> = self.groups.keys().chain(next.groups.keys()).collect();
119        for group in groups {
120            if self.groups.get(group) != next.groups.get(group)
121                && let Some((kind, slug)) = group.split_once('/')
122                && let Ok(kind) = serde_json::from_value(serde_json::Value::String(kind.into()))
123            {
124                keys.insert(DepKey::Group { kind, slug: slug.to_string() });
125            }
126        }
127        keys
128    }
129
130    /// The outputs whose dependencies meet `keys`.
131    pub fn outputs_for(&self, keys: &BTreeSet<DepKey>) -> BTreeSet<String> {
132        self.outputs
133            .iter()
134            .filter(|(_, deps)| !deps.is_disjoint(keys))
135            .map(|(path, _)| path.clone())
136            .collect()
137    }
138}
139
140/// One page of a build.
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142#[serde(rename_all = "camelCase")]
143pub struct PageRecord {
144    /// The page's URL path.
145    pub path: String,
146    /// The page's language.
147    pub language: LanguageTag,
148    /// The item the page shows, if one.
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub item: Option<ContentId>,
151    /// The HTML file.
152    pub html: String,
153    /// The Markdown twin.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub markdown: Option<String>,
156    /// The machine view.
157    #[serde(default, skip_serializing_if = "Option::is_none")]
158    pub machine_view: Option<String>,
159}
160
161/// What a build produced.
162#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
163#[serde(rename_all = "camelCase")]
164pub struct BuildReport {
165    /// The generator, for the release manifest.
166    pub generator: GeneratorRef,
167    /// Every page, sorted by path.
168    pub pages: Vec<PageRecord>,
169    /// Every file the build owns in `out`.
170    pub outputs: BTreeSet<String>,
171    /// Files this build wrote.
172    pub written: BTreeSet<String>,
173    /// Files this build removed.
174    pub removed: BTreeSet<String>,
175    /// The full redirect set, 410 rules for withdrawn pages included.
176    pub redirects: Vec<Redirect>,
177    /// The dependency graph for the next incremental build.
178    pub graph: DependencyGraph,
179    /// The theme, for the accessibility check of its tokens.
180    pub theme: String,
181    /// Whether the build was incremental.
182    pub incremental: bool,
183}
184
185/// The built-in renderer: Markdown plus templates, no plugins (spec 3.5 §7.8).
186///
187/// # Example
188///
189/// ```rust
190/// use adk_site::content::{SiteConfig, SiteProject};
191/// use adk_site::generator::{BuiltinGenerator, SiteGenerator};
192/// use chrono::{TimeZone, Utc};
193///
194/// # async fn demo() -> adk_site::Result<()> {
195/// let config = SiteConfig::new("Example", "example.com", vec!["en".parse().unwrap()]);
196/// let project = SiteProject::new(config, Vec::new(), Utc.with_ymd_and_hms(2026, 10, 25, 0, 0, 0).unwrap());
197/// let out = tempfile::tempdir().unwrap();
198/// let report = BuiltinGenerator.build(&project, out.path()).await?;
199/// assert!(report.outputs.contains("index.html"));
200/// assert!(report.outputs.contains("llms.txt"));
201/// # Ok(())
202/// # }
203/// ```
204#[derive(Debug, Clone, Copy, Default)]
205pub struct BuiltinGenerator;
206
207impl BuiltinGenerator {
208    /// The generator's reference in release manifests.
209    pub fn reference() -> GeneratorRef {
210        GeneratorRef { name: "adk-site".into(), version: env!("CARGO_PKG_VERSION").into() }
211    }
212}
213
214#[async_trait]
215impl SiteGenerator for BuiltinGenerator {
216    async fn build(&self, project: &SiteProject, out: &Path) -> Result<BuildReport> {
217        let project = Arc::new(project.clone());
218        let out = out.to_path_buf();
219        tokio::task::spawn_blocking(move || build_sync(&project, &out, None))
220            .await
221            .map_err(|e| SiteError::Pipeline(format!("build task failed: {e}")))?
222    }
223
224    async fn build_incremental(
225        &self,
226        project: &SiteProject,
227        out: &Path,
228        changes: &ChangeSet,
229    ) -> Result<BuildReport> {
230        let project = Arc::new(project.clone());
231        let out = out.to_path_buf();
232        let changes = changes.clone();
233        tokio::task::spawn_blocking(move || build_sync(&project, &out, Some(&changes)))
234            .await
235            .map_err(|e| SiteError::Pipeline(format!("build task failed: {e}")))?
236    }
237}
238
239enum Output {
240    Page(usize),
241    Media(String),
242    Site,
243}
244
245fn write(out: &Path, path: &str, bytes: &[u8]) -> Result<()> {
246    let full = out.join(path);
247    if let Some(parent) = full.parent() {
248        std::fs::create_dir_all(parent).map_err(|e| SiteError::io(parent, e))?;
249    }
250    std::fs::write(&full, bytes).map_err(|e| SiteError::io(&full, e))
251}
252
253/// Every file under `dir`, as `/`-separated relative paths.
254pub(crate) fn list_files(dir: &Path) -> Result<BTreeSet<String>> {
255    let mut files = BTreeSet::new();
256    if !dir.exists() {
257        return Ok(files);
258    }
259    let mut stack = vec![dir.to_path_buf()];
260    while let Some(current) = stack.pop() {
261        for entry in std::fs::read_dir(&current).map_err(|e| SiteError::io(&current, e))? {
262            let entry = entry.map_err(|e| SiteError::io(&current, e))?;
263            let path = entry.path();
264            let file_type = entry.file_type().map_err(|e| SiteError::io(&path, e))?;
265            if file_type.is_dir() {
266                stack.push(path);
267            } else {
268                let relative =
269                    path.strip_prefix(dir).unwrap_or(&path).to_string_lossy().replace('\\', "/");
270                files.insert(relative);
271            }
272        }
273    }
274    Ok(files)
275}
276
277fn remove(out: &Path, path: &str) -> Result<()> {
278    let full = out.join(path);
279    match std::fs::remove_file(&full) {
280        Ok(()) => {}
281        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
282        Err(e) => return Err(SiteError::io(&full, e)),
283    }
284    let mut dir = full.parent();
285    while let Some(current) = dir {
286        if current == out || std::fs::remove_dir(current).is_err() {
287            break;
288        }
289        dir = current.parent();
290    }
291    Ok(())
292}
293
294fn build_sync(
295    project: &SiteProject,
296    out: &Path,
297    changes: Option<&ChangeSet>,
298) -> Result<BuildReport> {
299    if let Some(issue) = project.issues().into_iter().next() {
300        return Err(SiteError::InvalidContent {
301            path: issue.item.map_or_else(|| "site.toml".into(), |id| id.0),
302            message: issue.message,
303        });
304    }
305    let plan = plan::plan(project)?;
306    let mut outputs: BTreeMap<String, (Output, BTreeSet<DepKey>)> = BTreeMap::new();
307    let mut claim = |path: String, output: Output, deps: BTreeSet<DepKey>| -> Result<()> {
308        if outputs.insert(path.clone(), (output, deps)).is_some() {
309            return Err(SiteError::InvalidContent {
310                path,
311                message: "two outputs share this file; rename a media file or change a redirect"
312                    .into(),
313            });
314        }
315        Ok(())
316    };
317    for (index, page) in plan.pages.iter().enumerate() {
318        let (html, md, view) = plan::page_files(&page.path);
319        for path in std::iter::once(html).chain(md).chain(view) {
320            claim(path, Output::Page(index), page.deps.clone())?;
321        }
322    }
323    for (path, repo_path, index) in &plan.media {
324        let deps = BTreeSet::from([DepKey::Item { id: project.items[*index].id.clone() }]);
325        claim(path.clone(), Output::Media(repo_path.clone()), deps)?;
326    }
327    for (path, deps) in files::site_file_paths(project, &plan) {
328        claim(path, Output::Site, deps)?;
329    }
330    let graph = DependencyGraph {
331        outputs: outputs.iter().map(|(path, (_, deps))| (path.clone(), deps.clone())).collect(),
332        footprints: plan.footprints.clone(),
333        nav: project
334            .config
335            .languages
336            .iter()
337            .map(|l| (plan::lang_key(l), plan.nav_signature(&plan::lang_key(l))))
338            .collect(),
339        groups: plan.group_signatures(&project.items),
340    };
341    let on_disk = list_files(out)?;
342    let (render, removed): (BTreeSet<String>, BTreeSet<String>) = match changes {
343        None => {
344            let stale: BTreeSet<String> =
345                on_disk.difference(&graph.outputs.keys().cloned().collect()).cloned().collect();
346            (graph.outputs.keys().cloned().collect(), stale)
347        }
348        Some(changes) => {
349            let keys = changes.previous.affected_keys(&graph, &changes.items);
350            let mut render = graph.outputs_for(&keys);
351            for path in graph.outputs.keys() {
352                if !changes.previous.outputs.contains_key(path) || !on_disk.contains(path) {
353                    render.insert(path.clone());
354                }
355            }
356            let removed = changes
357                .previous
358                .outputs
359                .keys()
360                .filter(|path| !graph.outputs.contains_key(*path))
361                .cloned()
362                .collect();
363            (render, removed)
364        }
365    };
366    for path in &removed {
367        remove(out, path)?;
368    }
369    let renderer = render::Renderer::new(project, &plan)?;
370    let mut written = BTreeSet::new();
371    let mut rendered_pages = BTreeSet::new();
372    for path in &render {
373        let Some((output, _)) = outputs.get(path) else { continue };
374        match output {
375            Output::Page(index) => {
376                if !rendered_pages.insert(*index) {
377                    continue;
378                }
379                for (file, bytes) in renderer.page(&plan.pages[*index])? {
380                    write(out, &file, &bytes)?;
381                    written.insert(file);
382                }
383            }
384            Output::Media(repo_path) => {
385                write(out, path, &project.media_bytes(repo_path)?)?;
386                written.insert(path.clone());
387            }
388            Output::Site => {
389                write(out, path, &files::render(project, &plan, path)?)?;
390                written.insert(path.clone());
391            }
392        }
393    }
394    let pages = plan
395        .pages
396        .iter()
397        .map(|page| {
398            let (html, markdown, machine_view) = plan::page_files(&page.path);
399            let item = match &page.kind {
400                plan::PageKind::Item(i) | plan::PageKind::Notice(i, _) => {
401                    Some(project.items[*i].id.clone())
402                }
403                plan::PageKind::Home { item, .. } => item.map(|i| project.items[i].id.clone()),
404                plan::PageKind::Listing { collection, .. } => {
405                    collection.map(|i| project.items[i].id.clone())
406                }
407                plan::PageKind::NotFound | plan::PageKind::Gone => None,
408            };
409            PageRecord {
410                path: page.path.clone(),
411                language: page.language.clone(),
412                item,
413                html,
414                markdown,
415                machine_view,
416            }
417        })
418        .collect();
419    Ok(BuildReport {
420        generator: BuiltinGenerator::reference(),
421        pages,
422        outputs: graph.outputs.keys().cloned().collect(),
423        written,
424        removed,
425        redirects: files::redirects(project, &plan),
426        graph,
427        theme: project.theme.name.clone(),
428        incremental: changes.is_some(),
429    })
430}