Skip to main content

proa_cli/
config.rs

1// Copyright Proa Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{
5    collections::BTreeMap,
6    fs,
7    path::{Component, Path, PathBuf},
8};
9
10use anyhow::{Context, Result};
11use reqwest::Url;
12use serde::{Deserialize, Serialize};
13
14mod model;
15mod rust;
16pub(crate) use rust::DevConfigRunner;
17
18pub use model::{Config, DatabaseDriver, CONFIG_FILE};
19pub(crate) use model::{DEFAULT_BUILD_COMMAND, DEFAULT_DEV_COMMAND, DEFAULT_PUBLIC_DIRECTORY};
20pub type ProjectConfig = Config<String, PathBuf>;
21
22macro_rules! owned_config_sections {
23    ($($name:ident <$($storage:ty),+ $(,)?>),+ $(,)?) => {
24        $(pub type $name = model::$name<$($storage),+>;)*
25    };
26}
27
28owned_config_sections! {
29    ApplicationConfig<String>,
30    AssetConfig<String, PathBuf>,
31    BuildConfig<String, PathBuf>,
32    CdnConfig<String>,
33    DatabaseConfig<String, PathBuf>,
34    DeployConfig<String>,
35    ProjectPaths<PathBuf>,
36    RegistriesConfig<String>,
37    ScriptConfig<String, PathBuf>,
38    ScriptHooks<String>,
39    ScriptsConfig<String, PathBuf>,
40}
41
42pub const LOCK_FILE: &str = "proa.lock.json";
43pub const LOCK_SCHEMA_URL: &str = "https://proa.so/schema/proa.lock.json";
44
45#[derive(Debug, Clone, Deserialize, Serialize)]
46#[serde(default)]
47pub struct ComponentLockFile {
48    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
49    pub schema: Option<String>,
50    pub components: BTreeMap<String, InstalledComponent>,
51    // Component installs rewrite this lock. Preserve scaffold metadata and
52    // version keys written by the site generator and capability commands.
53    #[serde(flatten)]
54    pub metadata: BTreeMap<String, serde_json::Value>,
55}
56
57impl ComponentLockFile {
58    pub(crate) fn scaffold_capabilities(&self) -> impl Iterator<Item = &str> {
59        self.metadata
60            .get("scaffold")
61            .and_then(|scaffold| scaffold.get("capabilities"))
62            .and_then(serde_json::Value::as_array)
63            .into_iter()
64            .flatten()
65            .filter_map(|capability| capability.get("id")?.as_str())
66    }
67
68    pub(crate) fn scaffold_markdown(&self) -> Option<bool> {
69        if self
70            .scaffold_capabilities()
71            .any(|id| id == "representation:markdown")
72        {
73            Some(true)
74        } else if self.scaffold_capabilities().any(|id| id == "base:site") {
75            Some(false)
76        } else {
77            None
78        }
79    }
80}
81
82#[derive(Debug, Clone, Deserialize, Serialize)]
83#[serde(default, rename_all = "camelCase")]
84pub struct InstalledComponent {
85    pub version: String,
86    pub registry: String,
87    pub mode: String,
88    pub source_hash: String,
89    pub local_hash_at_install: String,
90    pub installed_files: Vec<PathBuf>,
91    pub dependencies: Vec<String>,
92    pub rust_modules: Vec<InstalledRustModules>,
93    pub cargo_dependencies: Vec<InstalledCargoDependency>,
94}
95
96#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
97#[serde(rename_all = "camelCase")]
98pub struct InstalledRustModules {
99    pub target: PathBuf,
100    pub modules: Vec<String>,
101}
102
103#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
104#[serde(rename_all = "camelCase")]
105pub struct InstalledCargoDependency {
106    pub name: String,
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub path: Option<PathBuf>,
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub version: Option<String>,
111    #[serde(default, skip_serializing_if = "Option::is_none")]
112    pub git: Option<String>,
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub registry: Option<String>,
115    pub features: Vec<String>,
116    #[serde(skip_serializing_if = "Option::is_none")]
117    pub default_features: Option<bool>,
118}
119
120#[derive(Debug, Clone, Deserialize, Serialize)]
121pub struct ConfigInitReport {
122    pub root: PathBuf,
123    pub config_path: PathBuf,
124    pub lock_path: PathBuf,
125    pub wrote_config: bool,
126    pub wrote_lock: bool,
127}
128
129impl Default for ComponentLockFile {
130    fn default() -> Self {
131        Self {
132            schema: Some(LOCK_SCHEMA_URL.into()),
133            components: BTreeMap::new(),
134            metadata: BTreeMap::new(),
135        }
136    }
137}
138
139impl Default for InstalledComponent {
140    fn default() -> Self {
141        Self {
142            version: String::new(),
143            registry: String::new(),
144            mode: "source".into(),
145            source_hash: String::new(),
146            local_hash_at_install: String::new(),
147            installed_files: Vec::new(),
148            dependencies: Vec::new(),
149            rust_modules: Vec::new(),
150            cargo_dependencies: Vec::new(),
151        }
152    }
153}
154
155pub fn load_project_config(root: &Path) -> Result<ProjectConfig> {
156    load_project_config_with_runner(root, None)
157}
158
159pub(crate) fn load_project_config_with_runner(
160    root: &Path,
161    runner: Option<&mut DevConfigRunner>,
162) -> Result<ProjectConfig> {
163    let mut config = match project_config_path(root) {
164        Some(path) => rust::load(root, &path, runner)
165            .with_context(|| format!("evaluate {}", path.display()))?,
166        None if root.join("proa.config.json").exists() => {
167            anyhow::bail!(
168                "`proa.config.json` is no longer supported; migrate settings to `{CONFIG_FILE}` (run `proa init` for a starter file)"
169            );
170        }
171        None => ProjectConfig::default(),
172    };
173    fill_inferred_defaults(root, &mut config);
174    Ok(config)
175}
176
177pub(crate) fn project_config_path(root: &Path) -> Option<PathBuf> {
178    let path = root.join(CONFIG_FILE);
179    path.exists().then_some(path)
180}
181
182pub(crate) fn generated_rust_config(config: &ProjectConfig) -> Result<String> {
183    rust::source(config)
184}
185
186pub(crate) fn add_rust_capability(
187    source: &str,
188    before: &ProjectConfig,
189    after: &ProjectConfig,
190) -> Result<String> {
191    rust::with_capability_changes(source, before, after)
192}
193
194#[derive(Debug, Serialize)]
195pub struct ConfigValidation {
196    pub config_path: Option<PathBuf>,
197    pub warnings: Vec<String>,
198    pub errors: Vec<String>,
199}
200
201pub fn validate_project_config(root: &Path) -> Result<ConfigValidation> {
202    let config = load_project_config(root)?;
203    let mut validation = validate_build_config(root, &config);
204    for (name, command) in [
205        ("dev", &config.scripts.dev),
206        ("build", &config.scripts.build),
207    ] {
208        if let Err(error) = crate::commands::script::validate(name, command) {
209            validation.errors.push(error.to_string());
210        }
211    }
212    Ok(validation)
213}
214
215pub(crate) fn validate_build_config(root: &Path, config: &ProjectConfig) -> ConfigValidation {
216    let mut validation = ConfigValidation {
217        config_path: project_config_path(root),
218        warnings: Vec::new(),
219        errors: Vec::new(),
220    };
221
222    if validation.config_path.is_none() {
223        validation
224            .warnings
225            .push(format!("{CONFIG_FILE} not found; using inferred defaults"));
226    }
227
228    if !config.scripts.css.trim().is_empty() {
229        if let Err(error) = crate::commands::script::validate("css", &config.scripts.css) {
230            validation.errors.push(error.to_string());
231        }
232    }
233    for (phase, hooks) in [
234        ("dev", &config.scripts.before.dev),
235        ("build", &config.scripts.before.build),
236        ("test", &config.scripts.before.test),
237    ] {
238        if let Err(error) = crate::commands::task::validate_lifecycle_tasks(config, hooks) {
239            validation
240                .errors
241                .push(format!("scripts.before.{phase}: {error}"));
242        }
243    }
244    for name in config.scripts.named.keys() {
245        if crate::commands::script::shell_entries(&config.scripts).any(|(script, _)| script == name)
246        {
247            validation.warnings.push(format!(
248                "scripts.named.{name} is shadowed by scripts.{name}"
249            ));
250        }
251    }
252    for (name, path) in [
253        ("paths.components", &config.paths.components),
254        ("paths.assets", &config.paths.assets),
255    ] {
256        if let Err(error) = validate_project_relative_path(path) {
257            validation.errors.push(format!("{name}: {error}"));
258        }
259    }
260    if let Some(path) = &config.paths.public {
261        if let Err(error) = validate_project_relative_path(path) {
262            validation.errors.push(format!("paths.public: {error}"));
263        }
264    }
265    if config.paths.components == config.paths.assets {
266        validation
267            .errors
268            .push("paths.components and paths.assets must be different".to_string());
269    }
270
271    if config.registries.proa.is_none() {
272        validation
273            .errors
274            .push("registries.@proa is required".to_string());
275    }
276    for (registry, template) in config.registries.iter() {
277        if let Err(error) = validate_registry_template(template) {
278            validation
279                .errors
280                .push(format!("registries.{registry}: {error}"));
281        }
282    }
283
284    for (index, asset) in config.build.assets().iter().enumerate() {
285        match asset.kind.as_str() {
286            "tailwind" => {
287                if !root.join(&asset.input).exists() {
288                    validation.warnings.push(format!(
289                        "build.assets[{index}]: tailwind input `{}` does not exist; the asset build will be skipped",
290                        asset.input.display()
291                    ));
292                }
293                if asset.output.as_os_str().is_empty() {
294                    validation.errors.push(format!(
295                        "build.assets[{index}]: tailwind asset has no output path"
296                    ));
297                }
298            }
299            "command" => {
300                if asset.command.is_empty() {
301                    validation.warnings.push(format!(
302                        "build.assets[{index}]: command asset with an empty command does nothing"
303                    ));
304                }
305            }
306            other => validation.errors.push(format!(
307                "build.assets[{index}]: unknown kind `{other}` (expected `tailwind` or `command`)"
308            )),
309        }
310    }
311
312    validation
313}
314
315pub(crate) fn validate_project_relative_path(path: &Path) -> std::result::Result<(), String> {
316    if path.as_os_str().is_empty() || path.is_absolute() {
317        return Err(format!(
318            "`{}` must be a non-empty project-relative path",
319            path.display()
320        ));
321    }
322    if path
323        .components()
324        .any(|component| !matches!(component, Component::Normal(_)))
325    {
326        return Err(format!(
327            "`{}` contains an unsafe path component",
328            path.display()
329        ));
330    }
331    Ok(())
332}
333
334fn validate_registry_template(template: &str) -> std::result::Result<(), String> {
335    if template.matches("{name}").count() != 1 {
336        return Err(format!(
337            "`{template}` must contain exactly one `{{name}}` placeholder"
338        ));
339    }
340    let rendered = template.replace("{name}", "button");
341    if rendered.starts_with("https://") || rendered.starts_with("http://") {
342        let url = Url::parse(&rendered)
343            .map_err(|error| format!("`{template}` is not a valid registry URL: {error}"))?;
344        if url.scheme() == "http"
345            && !matches!(url.host_str(), Some("localhost" | "127.0.0.1" | "::1"))
346        {
347            return Err("HTTP is only allowed for localhost registries; use HTTPS".to_string());
348        }
349        return Ok(());
350    }
351    if rendered.starts_with("file://") {
352        let url = Url::parse(&rendered)
353            .map_err(|error| format!("`{template}` is not a valid file URL: {error}"))?;
354        url.to_file_path()
355            .map_err(|_| format!("`{template}` is not a valid file URL"))?;
356        return Ok(());
357    }
358    if rendered.contains("://") {
359        return Err(format!("`{template}` uses an unsupported URL scheme"));
360    }
361    if rendered.trim().is_empty() {
362        return Err("registry path cannot be empty".to_string());
363    }
364    Ok(())
365}
366
367pub fn load_component_lock(root: &Path) -> Result<ComponentLockFile> {
368    let path = root.join(LOCK_FILE);
369    if path.exists() {
370        let source =
371            fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
372        let mut lock: ComponentLockFile =
373            serde_json::from_str(&source).with_context(|| format!("parse {}", path.display()))?;
374        if lock.schema.is_none() {
375            lock.schema = Some(LOCK_SCHEMA_URL.into());
376        }
377        Ok(lock)
378    } else {
379        Ok(ComponentLockFile::default())
380    }
381}
382
383pub fn generated_project_config(tailwind: bool) -> Result<String> {
384    generated_rust_config(&ProjectConfig {
385        build: BuildConfig {
386            assets: (!tailwind).then(Vec::new),
387            ..Default::default()
388        },
389        ..Default::default()
390    })
391}
392
393pub fn generated_component_lock() -> Result<String> {
394    Ok(serde_json::to_string_pretty(&ComponentLockFile::default())? + "\n")
395}
396
397pub fn init_project_files(root: &Path, force: bool) -> Result<ConfigInitReport> {
398    fs::create_dir_all(root).with_context(|| format!("create {}", root.display()))?;
399
400    let config_path = root.join(CONFIG_FILE);
401    let lock_path = root.join(LOCK_FILE);
402    let mut wrote_config = false;
403    let mut wrote_lock = false;
404
405    if force || !config_path.exists() {
406        fs::write(&config_path, generated_project_config(true)?)
407            .with_context(|| format!("write {}", config_path.display()))?;
408        wrote_config = true;
409    }
410
411    if force || !lock_path.exists() {
412        fs::write(&lock_path, generated_component_lock()?)
413            .with_context(|| format!("write {}", lock_path.display()))?;
414        wrote_lock = true;
415    }
416
417    Ok(ConfigInitReport {
418        root: root.to_path_buf(),
419        config_path,
420        lock_path,
421        wrote_config,
422        wrote_lock,
423    })
424}
425
426fn fill_inferred_defaults(root: &Path, config: &mut ProjectConfig) {
427    if config.paths.components.as_os_str().is_empty() {
428        config.paths.components = ProjectPaths::default().components;
429    }
430    if config.paths.assets.as_os_str().is_empty() {
431        config.paths.assets = ProjectPaths::default().assets;
432    }
433    if config.registries.proa.is_none() && config.registries.proa_pro.is_none() {
434        config.registries = RegistriesConfig::default();
435    }
436    if config.scripts.css.trim().is_empty()
437        && config.build.assets.is_none()
438        && root.join("styles/input.css").exists()
439    {
440        config.build.assets = Some(vec![tailwind_asset(stylesheet_output(config))]);
441    }
442}
443
444pub(crate) fn css_script_output(config: &ProjectConfig) -> Option<PathBuf> {
445    (!config.scripts.css.trim().is_empty()).then(|| stylesheet_output(config))
446}
447
448fn stylesheet_output(config: &ProjectConfig) -> PathBuf {
449    config
450        .paths
451        .public
452        .as_deref()
453        .unwrap_or(Path::new(DEFAULT_PUBLIC_DIRECTORY))
454        .join("styles.css")
455}
456
457fn tailwind_asset(output: PathBuf) -> AssetConfig {
458    AssetConfig {
459        kind: "tailwind".into(),
460        command: Vec::new(),
461        input: PathBuf::from("styles/input.css"),
462        output,
463        // Tailwind v4 discovers sources from the CSS entrypoint's `@source`
464        // directives. The optional config field remains supported for older
465        // and custom projects, but generated v4 sites do not need `-c`.
466        config: None,
467    }
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473
474    #[test]
475    fn adding_a_capability_preserves_an_async_config_and_its_error_type() {
476        let temp = tempfile::tempdir().unwrap();
477        let source = r#"
478use proa::config::{CdnConfig, Config, DeployConfig, ProjectPaths, ScriptsConfig, tokio};
479
480pub async fn config() -> std::io::Result<Config<&'static str, String>> {
481    let public = tokio::fs::read_to_string("public-dir.txt").await?;
482    return Ok(Config {
483        scripts: ScriptsConfig {
484            dev: "cargo run",
485            build: "cargo build --release",
486            ..Default::default()
487        },
488        paths: ProjectPaths { public: Some(public), ..Default::default() },
489        deploy: Some(DeployConfig {
490            cdn: Some(CdnConfig::Command { command: vec!["purge-cache"] }),
491            ..Default::default()
492        }),
493        ..Config::default()
494    });
495}
496"#;
497        let before = ProjectConfig::default();
498        let mut after = before.clone();
499        after.database = Some(DatabaseConfig {
500            driver: DatabaseDriver::Sqlite,
501            ..Default::default()
502        });
503        after.deploy = Some(DeployConfig {
504            provider: "docker".into(),
505            ..Default::default()
506        });
507        let patched = add_rust_capability(source, &before, &after).unwrap();
508        fs::write(temp.path().join(CONFIG_FILE), patched).unwrap();
509        fs::write(temp.path().join("public-dir.txt"), "public").unwrap();
510        let actual = load_project_config(temp.path()).unwrap();
511        assert_eq!(actual.paths.public, Some("public".into()));
512        assert_eq!(actual.database, after.database);
513        let deploy = actual.deploy.unwrap();
514        assert_eq!(deploy.provider, "docker");
515        assert_eq!(
516            deploy.cdn,
517            Some(CdnConfig::Command {
518                command: vec!["purge-cache".into()]
519            })
520        );
521    }
522
523    #[test]
524    fn validate_passes_defaults_and_flags_missing_config() {
525        let temp = tempfile::tempdir().unwrap();
526        let validation = validate_project_config(temp.path()).unwrap();
527        assert!(validation.errors.is_empty(), "{validation:?}");
528        assert!(
529            validation
530                .warnings
531                .iter()
532                .any(|warning| warning.contains("not found")),
533            "{validation:?}"
534        );
535    }
536
537    #[test]
538    fn validate_rejects_unsafe_paths_and_broken_registry_templates() {
539        let temp = tempfile::tempdir().unwrap();
540        fs::write(
541            temp.path().join(CONFIG_FILE),
542            generated_rust_config(&ProjectConfig {
543                paths: ProjectPaths {
544                    components: "../outside".into(),
545                    assets: "/tmp/assets".into(),
546                    public: Some("../public".into()),
547                },
548                registries: RegistriesConfig {
549                    proa: Some("https://ui.proa.so/r/component.json".into()),
550                    proa_pro: Some("http://console.proa.so/r/{name}.json".into()),
551                },
552                ..ProjectConfig::default()
553            })
554            .unwrap(),
555        )
556        .unwrap();
557
558        let validation = validate_project_config(temp.path()).unwrap();
559        assert!(
560            validation
561                .errors
562                .iter()
563                .any(|error| error.contains("paths.components")),
564            "{validation:?}"
565        );
566        assert!(
567            validation
568                .errors
569                .iter()
570                .any(|error| error.contains("paths.assets")),
571            "{validation:?}"
572        );
573        assert!(
574            validation
575                .errors
576                .iter()
577                .any(|error| error.contains("paths.public")),
578            "{validation:?}"
579        );
580        assert!(
581            validation
582                .errors
583                .iter()
584                .any(|error| error.contains("exactly one `{name}`")),
585            "{validation:?}"
586        );
587        assert!(
588            validation
589                .errors
590                .iter()
591                .any(|error| error.contains("use HTTPS")),
592            "{validation:?}"
593        );
594    }
595
596    #[test]
597    fn generated_config_has_a_typed_entry_and_explicit_asset_choice() {
598        for tailwind in [false, true] {
599            let source = generated_project_config(tailwind).unwrap();
600            assert!(syn::parse_file(&source).is_ok());
601            assert!(source.contains("dev: \"proa dev\""));
602            assert!(source.contains("build: \"proa build\""));
603            assert_eq!(source.contains("assets: Some(vec![])"), !tailwind);
604        }
605    }
606
607    #[test]
608    fn generated_lock_starts_empty() {
609        let json = generated_component_lock().unwrap();
610
611        assert!(json.contains("\"$schema\": \"https://proa.so/schema/proa.lock.json\""));
612        assert!(json.contains("\"components\": {}"));
613    }
614
615    #[test]
616    fn init_project_files_writes_config_and_lock() {
617        let temp = tempfile::tempdir().unwrap();
618        let report = init_project_files(temp.path(), false).unwrap();
619
620        assert!(report.wrote_config);
621        assert!(report.wrote_lock);
622        assert!(temp.path().join(CONFIG_FILE).exists());
623        assert!(temp.path().join(LOCK_FILE).exists());
624
625        let second = init_project_files(temp.path(), false).unwrap();
626        assert!(!second.wrote_config);
627        assert!(!second.wrote_lock);
628    }
629
630    #[test]
631    fn load_rejects_stale_json_config_without_rust_config() {
632        let temp = tempfile::tempdir().unwrap();
633        fs::write(temp.path().join("proa.config.json"), "{}").unwrap();
634
635        let error = load_project_config(temp.path()).unwrap_err().to_string();
636        assert!(error.contains("proa.config.json"), "{error}");
637        assert!(error.contains(CONFIG_FILE), "{error}");
638    }
639
640    #[test]
641    fn validate_flags_missing_before_hooks_and_shadowed_named_scripts() {
642        let temp = tempfile::tempdir().unwrap();
643        let config = ProjectConfig {
644            scripts: ScriptsConfig {
645                before: ScriptHooks {
646                    dev: vec!["missing-task".into()],
647                    ..Default::default()
648                },
649                named: BTreeMap::from([(
650                    "dev".into(),
651                    ScriptConfig {
652                        command: vec!["echo".into(), "shadowed".into()],
653                        ..Default::default()
654                    },
655                )]),
656                ..Default::default()
657            },
658            ..Default::default()
659        };
660        let validation = validate_build_config(temp.path(), &config);
661        assert!(
662            validation
663                .errors
664                .iter()
665                .any(|error| error.contains("scripts.before.dev")
666                    && error.contains("missing-task")),
667            "{validation:?}"
668        );
669        assert!(
670            validation
671                .warnings
672                .iter()
673                .any(|warning| warning.contains("scripts.named.dev")),
674            "{validation:?}"
675        );
676    }
677}