coatcheck 0.2.1

Contracts and a Playwright accessibility runner for Topcoat component workbenches.
Documentation
//! Project configuration loaded from `Coatcheck.toml`.

use std::error::Error;
use std::fmt;
use std::fs;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use url::Url;

use crate::contract::DEFAULT_MANIFEST_PATH;

/// Current `Coatcheck.toml` schema version.
pub const CONFIG_VERSION: u16 = 1;

/// Default project configuration file name.
pub const CONFIG_FILE: &str = "Coatcheck.toml";

/// Parsed version-1 project configuration.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// Must equal [`CONFIG_VERSION`].
    pub version: u16,
    /// Human-readable project name.
    pub name: String,
    /// Host process and endpoint settings.
    pub host: HostConfig,
    /// Playwright generation and gate settings.
    #[serde(default)]
    pub test: TestConfig,
}

impl Config {
    /// Loads and validates a configuration file.
    ///
    /// # Errors
    ///
    /// Returns a [`ConfigError`] when the file cannot be read, parsed, or
    /// validated.
    pub fn load(path: &Path) -> Result<Self, ConfigError> {
        let source = fs::read_to_string(path).map_err(|source| ConfigError::Read {
            path: path.to_path_buf(),
            source,
        })?;
        let config: Self = toml::from_str(&source).map_err(ConfigError::Parse)?;
        config.validate()?;
        Ok(config)
    }

    /// Validates command, URL, endpoint, and runner settings.
    ///
    /// # Errors
    ///
    /// Returns a [`ConfigError`] when a required value is missing or invalid.
    pub fn validate(&self) -> Result<(), ConfigError> {
        if self.version != CONFIG_VERSION {
            return Err(ConfigError::UnsupportedVersion(self.version));
        }
        if self.name.trim().is_empty() {
            return Err(ConfigError::Invalid("name cannot be empty"));
        }
        if self.host.command.is_empty()
            || self.host.command.iter().any(|part| part.trim().is_empty())
        {
            return Err(ConfigError::Invalid(
                "host.command must contain non-empty program arguments",
            ));
        }

        let base_url = Url::parse(&self.host.url)
            .map_err(|_| ConfigError::Invalid("host.url must be an absolute HTTP(S) URL"))?;
        if !matches!(base_url.scheme(), "http" | "https") || base_url.cannot_be_a_base() {
            return Err(ConfigError::Invalid(
                "host.url must be an absolute HTTP(S) URL",
            ));
        }

        for (name, value) in [
            ("host.health", self.host.health.as_str()),
            ("host.manifest", self.host.manifest.as_str()),
        ] {
            if value.trim().is_empty() || !value.starts_with('/') {
                return Err(ConfigError::Invalid(match name {
                    "host.health" => "host.health must start with /",
                    _ => "host.manifest must start with /",
                }));
            }
        }

        if self.host.startup_timeout_seconds == 0 {
            return Err(ConfigError::Invalid(
                "host.startup_timeout_seconds must be greater than zero",
            ));
        }
        if self.test.timeout_ms == 0 {
            return Err(ConfigError::Invalid(
                "test.timeout_ms must be greater than zero",
            ));
        }
        if self
            .test
            .story_globs
            .iter()
            .any(|glob| glob.trim().is_empty())
        {
            return Err(ConfigError::Invalid(
                "test.story_globs cannot contain empty patterns",
            ));
        }
        if self.test.artifacts.as_os_str().is_empty() {
            return Err(ConfigError::Invalid("test.artifacts cannot be empty"));
        }
        if self.test.axe_impacts.is_empty()
            || self.test.axe_impacts.iter().any(|impact| {
                !matches!(
                    impact.as_str(),
                    "minor" | "moderate" | "serious" | "critical"
                )
            })
        {
            return Err(ConfigError::Invalid(
                "test.axe_impacts must use minor, moderate, serious, or critical",
            ));
        }

        Ok(())
    }

    /// Resolves a host endpoint against the configured base URL.
    ///
    /// # Errors
    ///
    /// Returns a [`ConfigError`] when URL joining fails.
    pub fn endpoint(&self, path: &str) -> Result<Url, ConfigError> {
        let base = Url::parse(&self.host.url)
            .map_err(|_| ConfigError::Invalid("host.url must be an absolute HTTP(S) URL"))?;
        base.join(path)
            .map_err(|_| ConfigError::Invalid("host endpoint path is invalid"))
    }

    /// Resolves the artifact directory under a project root.
    #[must_use]
    pub fn artifacts_dir(&self, project_root: &Path) -> PathBuf {
        project_root.join(&self.test.artifacts)
    }
}

/// Host process and endpoint configuration.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct HostConfig {
    /// Program followed by arguments, executed without a shell.
    pub command: Vec<String>,
    /// Base URL served by the host.
    pub url: String,
    /// Health endpoint used before manifest fetching.
    #[serde(default = "default_health")]
    pub health: String,
    /// Version-1 manifest endpoint.
    #[serde(default = "default_manifest")]
    pub manifest: String,
    /// Maximum wait for the health endpoint.
    #[serde(default = "default_startup_timeout")]
    pub startup_timeout_seconds: u64,
}

/// Playwright generation and semantic gate configuration.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct TestConfig {
    /// Additional project-local Playwright spec globs.
    pub story_globs: Vec<String>,
    /// Review artifact directory relative to the project.
    pub artifacts: PathBuf,
    /// Per-test timeout.
    pub timeout_ms: u64,
    /// Axe impacts that fail the semantic gate.
    pub axe_impacts: Vec<String>,
}

impl Default for TestConfig {
    fn default() -> Self {
        Self {
            story_globs: vec!["coatcheck/**/*.spec.ts".to_owned()],
            artifacts: PathBuf::from(".coatcheck/artifacts"),
            timeout_ms: 30_000,
            axe_impacts: vec!["serious".to_owned(), "critical".to_owned()],
        }
    }
}

fn default_health() -> String {
    "/health".to_owned()
}

fn default_manifest() -> String {
    DEFAULT_MANIFEST_PATH.to_owned()
}

const fn default_startup_timeout() -> u64 {
    30
}

/// Errors loading or validating `Coatcheck.toml`.
#[derive(Debug)]
pub enum ConfigError {
    /// The configuration file could not be read.
    Read {
        /// Attempted path.
        path: PathBuf,
        /// Underlying I/O error.
        source: std::io::Error,
    },
    /// TOML parsing failed.
    Parse(toml::de::Error),
    /// The configuration schema version is unsupported.
    UnsupportedVersion(u16),
    /// A field failed semantic validation.
    Invalid(&'static str),
}

impl fmt::Display for ConfigError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Read { path, source } => {
                write!(formatter, "could not read {}: {source}", path.display())
            }
            Self::Parse(error) => write!(formatter, "invalid Coatcheck.toml: {error}"),
            Self::UnsupportedVersion(version) => {
                write!(formatter, "unsupported Coatcheck.toml version: {version}")
            }
            Self::Invalid(message) => formatter.write_str(message),
        }
    }
}

impl Error for ConfigError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Read { source, .. } => Some(source),
            Self::Parse(source) => Some(source),
            Self::UnsupportedVersion(_) | Self::Invalid(_) => None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{Config, TestConfig};

    #[test]
    fn parses_a_cold_front_style_config() {
        let config: Config = toml::from_str(
            r#"
version = 1
name = "Cold Front"

[host]
command = ["cargo", "run", "-p", "coldfront-coatcheck"]
url = "http://127.0.0.1:3001"
health = "/health"
manifest = "/__coatcheck/manifest.json"

[test]
story_globs = ["coatcheck/**/*.spec.ts"]
artifacts = ".coatcheck/artifacts"
timeout_ms = 30000
axe_impacts = ["serious", "critical"]
"#,
        )
        .unwrap();

        assert_eq!(config.test, TestConfig::default());
        assert!(config.validate().is_ok());
        assert_eq!(
            config.endpoint(&config.host.manifest).unwrap().as_str(),
            "http://127.0.0.1:3001/__coatcheck/manifest.json"
        );
    }

    #[test]
    fn rejects_shell_strings_as_commands() {
        let config: Config = toml::from_str(
            r#"
version = 1
name = "Example"
[host]
command = []
url = "http://127.0.0.1:3000"
"#,
        )
        .unwrap();

        assert!(config.validate().is_err());
    }
}