Skip to main content

aster/foundation/
config.rs

1//! Typed views of the project manifest consumed by Aster.
2
3use std::path::Path;
4
5use anyhow::{Context, Result};
6use serde::Deserialize;
7use typst::ecow::{EcoString, EcoVec, eco_vec};
8
9/// Highlight theme configuration from `aster.toml`.
10#[derive(Clone, Deserialize)]
11#[serde(default)]
12pub struct HighlightConfig {
13    /// Whether syntax highlighting is enabled.
14    pub enabled: bool,
15    /// Light and dark syntax-highlighting themes.
16    pub themes: Themes,
17}
18
19impl Default for HighlightConfig {
20    fn default() -> Self {
21        Self {
22            enabled: true,
23            themes: Themes::default(),
24        }
25    }
26}
27
28/// Syntax-highlighting themes selected for light and dark color schemes.
29#[derive(Clone, Deserialize)]
30#[serde(default)]
31pub struct Themes {
32    /// Lumis theme used for light color schemes.
33    pub light: EcoString,
34    /// Lumis theme used for dark color schemes.
35    pub dark: EcoString,
36}
37
38impl Default for Themes {
39    fn default() -> Self {
40        Self {
41            light: "github_light".into(),
42            dark: "github_dark".into(),
43        }
44    }
45}
46
47/// Configured project directories.
48#[derive(Clone, Deserialize)]
49#[serde(default, deny_unknown_fields)]
50pub struct PathsConfig {
51    /// Directory containing HTML page templates.
52    pub pages: EcoString,
53    /// Directory containing exact-path Typst generators.
54    pub generate: EcoString,
55    /// Directory containing content collections.
56    pub content: EcoString,
57    /// Directory copied verbatim into the output.
58    pub public: EcoString,
59    /// Directory receiving the generated site.
60    pub output: EcoString,
61}
62
63impl Default for PathsConfig {
64    fn default() -> Self {
65        Self {
66            pages: "pages".into(),
67            generate: "generate".into(),
68            content: "content".into(),
69            public: "public".into(),
70            output: "dist".into(),
71        }
72    }
73}
74
75/// Generated-output settings.
76#[derive(Clone, Deserialize)]
77#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
78pub struct OutputConfig {
79    /// Directory for generated resources, relative to the output directory.
80    pub assets: EcoString,
81    /// Whether generated HTML is formatted with indentation.
82    pub pretty: bool,
83}
84
85impl Default for OutputConfig {
86    fn default() -> Self {
87        Self {
88            assets: "_assets".into(),
89            pretty: false,
90        }
91    }
92}
93
94/// Resource processing settings.
95#[derive(Clone, Deserialize)]
96#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
97pub struct AssetsConfig {
98    /// Maximum decoded image size retained as a data URL.
99    pub image_inline_threshold: usize,
100    /// Raster-image transformation settings.
101    pub images: ImageConfig,
102}
103
104impl Default for AssetsConfig {
105    fn default() -> Self {
106        Self {
107            image_inline_threshold: 1024,
108            images: ImageConfig::default(),
109        }
110    }
111}
112
113/// Raster-image transformation settings.
114#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq)]
115#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
116pub struct ImageConfig {
117    /// Whether PNG/JPEG optimization and explicit-size downsampling are enabled.
118    pub enabled: bool,
119    /// JPEG quality used when optimizing JPEG resources.
120    pub jpeg_quality: u8,
121    /// Optional density multiplier for raster images embedded by `html.frame`.
122    pub frame_density: Option<u8>,
123}
124
125impl Default for ImageConfig {
126    fn default() -> Self {
127        Self {
128            enabled: true,
129            jpeg_quality: 85,
130            frame_density: None,
131        }
132    }
133}
134
135/// CSS bundling and transformation settings.
136#[derive(Clone, Deserialize, Eq, Hash, PartialEq)]
137#[serde(default, rename_all = "kebab-case", deny_unknown_fields)]
138pub struct CssConfig {
139    /// Serialize generated CSS without unnecessary whitespace.
140    pub minify: bool,
141    /// Browserslist queries used for syntax lowering and vendor prefixes.
142    pub targets: EcoVec<EcoString>,
143    /// Enable parsing and transforming `@custom-media` rules.
144    pub custom_media: bool,
145}
146
147impl Default for CssConfig {
148    fn default() -> Self {
149        Self {
150            minify: true,
151            targets: eco_vec!["defaults".into()],
152            custom_media: false,
153        }
154    }
155}
156
157/// Additional project paths observed by development commands.
158#[derive(Clone, Default, Deserialize)]
159#[serde(default, deny_unknown_fields)]
160pub struct WatchConfig {
161    /// Additional project-relative files or trees observed by watch commands.
162    pub paths: EcoVec<EcoString>,
163}
164
165/// One external command run against the completed staged site.
166#[derive(Clone, Deserialize)]
167#[serde(deny_unknown_fields)]
168pub struct PostprocessConfig {
169    /// Human-readable name used in diagnostics.
170    pub name: EcoString,
171    /// Executable and arguments. `{site}` and `{output}` are replaced by paths.
172    pub command: EcoVec<EcoString>,
173    /// Output-tree directory receiving a private `{output}` tree, when used.
174    #[serde(default)]
175    pub mount: Option<EcoString>,
176    /// Additional project paths observed by development commands.
177    #[serde(default)]
178    pub watch: EcoVec<EcoString>,
179}
180
181/// Typst compiler settings.
182#[derive(Clone, Default, Deserialize)]
183#[serde(default)]
184pub struct TypstConfig {
185    /// Font discovery settings.
186    pub fonts: FontConfig,
187}
188
189/// Font discovery settings for Typst compilation.
190#[derive(Clone, Deserialize, Eq, PartialEq)]
191#[serde(default)]
192pub struct FontConfig {
193    /// Additional project-relative font directories.
194    pub paths: EcoVec<EcoString>,
195    /// Whether fonts installed on the system are discovered.
196    pub system: bool,
197}
198
199impl Default for FontConfig {
200    fn default() -> Self {
201        Self {
202            paths: EcoVec::new(),
203            system: true,
204        }
205    }
206}
207
208/// Aster-owned configuration extracted from the project manifest.
209#[derive(Default, Deserialize)]
210#[serde(default)]
211pub struct AsterConfig {
212    /// Project directory layout.
213    pub paths: PathsConfig,
214    /// Generated-output settings.
215    pub output: OutputConfig,
216    /// Resource processing settings.
217    pub assets: AssetsConfig,
218    /// CSS transformation settings.
219    pub css: CssConfig,
220    /// Additional development watcher inputs.
221    pub watch: WatchConfig,
222    /// External postprocessors run after Typst pages and generators.
223    pub postprocess: EcoVec<PostprocessConfig>,
224    /// Typst compiler settings.
225    pub typst: TypstConfig,
226    /// Syntax-highlighting settings.
227    pub highlight: HighlightConfig,
228}
229
230impl AsterConfig {
231    /// Parse Aster-owned settings from `aster.toml`.
232    pub fn parse(content: &[u8], path: &Path) -> Result<Self> {
233        let content = std::str::from_utf8(content)
234            .with_context(|| format!("{} is not valid UTF-8", path.display()))?;
235        let table: toml::Table = content
236            .parse()
237            .with_context(|| format!("failed to parse {}", path.display()))?;
238        Self::deserialize(toml::Value::Table(table))
239            .with_context(|| format!("failed to extract Aster config from {}", path.display()))
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246
247    fn load(path: &Path) -> Result<AsterConfig> {
248        let content = std::fs::read(path)?;
249        AsterConfig::parse(&content, path)
250    }
251
252    #[test]
253    fn loads_aster_config_and_ignores_project_fields() {
254        let temp = tempfile::tempdir().unwrap();
255        let config_file = temp.path().join("aster.toml");
256        std::fs::write(
257            &config_file,
258            concat!(
259                "title = \"Aster\"\n",
260                "published = 1979-05-27T07:32:00Z\n",
261                "[site]\n",
262                "enabled = true\n",
263                "[highlight.themes]\n",
264                "light = \"catppuccin_latte\"\n",
265                "dark = \"catppuccin_mocha\"\n",
266            ),
267        )
268        .unwrap();
269
270        let config = load(&config_file).unwrap();
271
272        assert_eq!(config.highlight.themes.light, "catppuccin_latte");
273        assert_eq!(config.highlight.themes.dark, "catppuccin_mocha");
274        assert_eq!(
275            config
276                .css
277                .targets
278                .iter()
279                .map(EcoString::as_str)
280                .collect::<Vec<_>>(),
281            ["defaults"]
282        );
283        assert!(config.watch.paths.is_empty());
284    }
285
286    #[test]
287    fn fills_missing_highlight_settings_with_defaults() {
288        let temp = tempfile::tempdir().unwrap();
289        let config_file = temp.path().join("aster.toml");
290        std::fs::write(
291            &config_file,
292            "[highlight.themes]\nlight = \"catppuccin_latte\"\n",
293        )
294        .unwrap();
295
296        let config = load(&config_file).unwrap();
297
298        assert_eq!(config.highlight.themes.light, "catppuccin_latte");
299        assert_eq!(config.highlight.themes.dark, "github_dark");
300    }
301
302    #[test]
303    fn loads_build_options_and_fills_their_defaults() {
304        let temp = tempfile::tempdir().unwrap();
305        let config_file = temp.path().join("aster.toml");
306        std::fs::write(
307            &config_file,
308            concat!(
309                "[paths]\n",
310                "pages = \"routes\"\n",
311                "public = \"files\"\n",
312                "output = \"public\"\n",
313                "[output]\n",
314                "assets = \"static/generated\"\n",
315                "pretty = true\n",
316                "[assets]\n",
317                "image-inline-threshold = 2048\n",
318                "[assets.images]\n",
319                "jpeg-quality = 90\n",
320                "frame-density = 2\n",
321                "[css]\n",
322                "minify = false\n",
323                "targets = [\"last 2 Chrome versions\", \"Firefox ESR\"]\n",
324                "custom-media = true\n",
325                "[watch]\n",
326                "paths = [\"components\", \"plugins/theme.ts\"]\n",
327                "[typst.fonts]\n",
328                "paths = [\"fonts\"]\n",
329                "system = false\n",
330                "[highlight]\n",
331                "enabled = false\n",
332            ),
333        )
334        .unwrap();
335
336        let config = load(&config_file).unwrap();
337
338        assert_eq!(config.paths.pages, "routes");
339        assert_eq!(config.paths.generate, "generate");
340        assert_eq!(config.paths.content, "content");
341        assert_eq!(config.paths.public, "files");
342        assert_eq!(config.paths.output, "public");
343        assert_eq!(config.output.assets, "static/generated");
344        assert!(config.output.pretty);
345        assert_eq!(config.assets.image_inline_threshold, 2048);
346        assert!(config.assets.images.enabled);
347        assert_eq!(config.assets.images.jpeg_quality, 90);
348        assert_eq!(config.assets.images.frame_density, Some(2));
349        assert!(!config.css.minify);
350        assert_eq!(
351            config
352                .css
353                .targets
354                .iter()
355                .map(EcoString::as_str)
356                .collect::<Vec<_>>(),
357            ["last 2 Chrome versions", "Firefox ESR"]
358        );
359        assert!(config.css.custom_media);
360        assert_eq!(
361            config
362                .watch
363                .paths
364                .iter()
365                .map(EcoString::as_str)
366                .collect::<Vec<_>>(),
367            ["components", "plugins/theme.ts"]
368        );
369        assert_eq!(config.typst.fonts.paths, eco_vec!["fonts".into()]);
370        assert!(!config.typst.fonts.system);
371        assert!(!config.highlight.enabled);
372        assert_eq!(config.highlight.themes.light, "github_light");
373    }
374
375    #[test]
376    fn rejects_invalid_highlight_settings() {
377        let temp = tempfile::tempdir().unwrap();
378        let config_file = temp.path().join("aster.toml");
379        std::fs::write(&config_file, "[highlight]\nthemes = \"github_light\"\n").unwrap();
380
381        let error = match load(&config_file) {
382            Ok(_) => panic!("invalid highlight settings must be rejected"),
383            Err(error) => error,
384        };
385
386        assert!(
387            format!("{error:#}").contains("invalid type"),
388            "unexpected error: {error:#}"
389        );
390    }
391}