Skip to main content

next_rust_core/
config.rs

1//! `next-rust.toml` configuration.
2//!
3//! Every section and key is optional; an empty file (or no file at all) is a
4//! valid, fully working configuration.
5//!
6//! ```toml
7//! [app]
8//! directory = "app"          # any relative or absolute path
9//! public = "public"
10//!
11//! [server]
12//! host = "0.0.0.0"
13//! port = 3000
14//!
15//! [build]
16//! output = ".next-rust"
17//!
18//! [rendering]
19//! default = "auto"
20//! ```
21//!
22//! ## Discovery
23//!
24//! 1. If `NEXT_RUST_CONFIG` is set, that file is used.
25//! 2. Otherwise, starting from the working directory and walking up through
26//!    its ancestors, the first directory containing `next-rust.toml` or
27//!    `next-rust.json` wins. Having both in one directory is an error.
28//! 3. If nothing is found, defaults are used with the working directory as
29//!    the project root.
30//!
31//! ## Path resolution
32//!
33//! Relative paths are resolved against the directory containing the
34//! configuration file (the *project root*), never against the process working
35//! directory. `..` components are allowed, which makes monorepo layouts like
36//! `directory = "../shared/pages"` possible. Paths are normalized lexically.
37
38use std::collections::BTreeMap;
39use std::fmt;
40use std::path::{Component, Path, PathBuf};
41
42use serde::{Deserialize, Serialize};
43
44use crate::diagnostic::Diagnostic;
45use crate::mode::RenderingMode;
46
47pub const TOML_FILE: &str = "next-rust.toml";
48pub const JSON_FILE: &str = "next-rust.json";
49
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51#[serde(default, deny_unknown_fields)]
52pub struct Config {
53    /// Project root (directory containing the config file). Not read from the file.
54    #[serde(skip)]
55    pub root: PathBuf,
56    /// The config file that was loaded, if any.
57    #[serde(skip)]
58    pub source: Option<PathBuf>,
59
60    pub app: AppConfig,
61    pub api: ApiConfig,
62    pub server: ServerConfig,
63    pub build: BuildConfig,
64    pub assets: AssetsConfig,
65    pub rendering: RenderingConfig,
66    pub images: ImagesConfig,
67    pub security: SecurityConfig,
68    pub env: EnvConfig,
69    pub dev: DevConfig,
70    pub logging: LoggingConfig,
71    pub redirects: Vec<RedirectRule>,
72    pub headers: Vec<HeaderRule>,
73    /// Free-form plugin configuration: `[plugins.my-plugin]`.
74    pub plugins: BTreeMap<String, serde_json::Value>,
75    /// Tailwind CSS: `[tailwind]`.
76    pub tailwind: TailwindConfig,
77}
78
79impl Default for Config {
80    fn default() -> Self {
81        Self {
82            root: PathBuf::from("."),
83            source: None,
84            app: AppConfig::default(),
85            api: ApiConfig::default(),
86            server: ServerConfig::default(),
87            build: BuildConfig::default(),
88            assets: AssetsConfig::default(),
89            rendering: RenderingConfig::default(),
90            images: ImagesConfig::default(),
91            security: SecurityConfig::default(),
92            env: EnvConfig::default(),
93            dev: DevConfig::default(),
94            logging: LoggingConfig::default(),
95            redirects: Vec::new(),
96            headers: Vec::new(),
97            plugins: BTreeMap::new(),
98            tailwind: TailwindConfig::default(),
99        }
100    }
101}
102
103/// `[tailwind]`: Tailwind CSS generated from the classes used in the app.
104///
105/// ```toml
106/// [tailwind]
107/// enabled = true
108/// dark_mode = "class"
109/// plugins = ["@tailwindcss/typography"]
110///
111/// [tailwind.theme]                 # becomes @theme { --color-brand: …; }
112/// color-brand = "#f26b2a"
113/// font-display = "Inter, sans-serif"
114///
115/// [tailwind.utilities]             # becomes @utility …
116/// btn = "rounded-lg bg-brand px-4 py-2 font-semibold text-white"
117/// content-auto = { content-visibility = "auto" }
118///
119/// [tailwind.variants]              # becomes @custom-variant …
120/// theme-midnight = "&:where([data-theme=midnight] *)"
121/// ```
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(default, deny_unknown_fields)]
124pub struct TailwindConfig {
125    /// Generate Tailwind CSS for the app. Off unless set.
126    pub enabled: bool,
127    /// Include Tailwind's base styles (Preflight).
128    pub preflight: bool,
129    /// When `dark:` applies.
130    pub dark_mode: TailwindDarkMode,
131    /// Theme variables, with or without the leading `--`:
132    /// `color-brand = "#f26b2a"`, `breakpoint-3xl = "120rem"`.
133    pub theme: BTreeMap<String, String>,
134    /// Custom utility classes: a list of Tailwind classes to combine, or CSS
135    /// declarations.
136    pub utilities: BTreeMap<String, TailwindUtility>,
137    /// Custom variants: name → selector (`&:where(…)`) or at-rule.
138    pub variants: BTreeMap<String, String>,
139    /// First-party plugins bundled with Tailwind, e.g. `@tailwindcss/typography`
140    /// and `@tailwindcss/forms`.
141    pub plugins: Vec<String>,
142    /// Classes to generate even if they don't appear in the source.
143    pub safelist: Vec<String>,
144    /// Extra directories to scan for classes, besides the app directory and `src/`.
145    pub sources: Vec<PathBuf>,
146    /// Raw CSS appended after everything else (`@keyframes`, `@layer`, …), for
147    /// what the options above can't express.
148    pub css: String,
149    /// Release builds rename every Tailwind class to a short random name
150    /// (`rounded-lg` → `k7`) in the CSS and the HTML. Development builds
151    /// always keep the names you wrote.
152    pub minify_classes: bool,
153    /// Classes that keep their names in release builds, for code outside the
154    /// view tree that refers to them (a script in a Rust string, HTML from an
155    /// external service).
156    pub keep_classes: Vec<String>,
157}
158
159impl Default for TailwindConfig {
160    fn default() -> Self {
161        Self {
162            enabled: false,
163            preflight: true,
164            dark_mode: TailwindDarkMode::Media,
165            theme: BTreeMap::new(),
166            utilities: BTreeMap::new(),
167            variants: BTreeMap::new(),
168            plugins: Vec::new(),
169            safelist: Vec::new(),
170            sources: Vec::new(),
171            css: String::new(),
172            minify_classes: true,
173            keep_classes: Vec::new(),
174        }
175    }
176}
177
178/// `[tailwind] dark_mode`
179#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
180#[serde(rename_all = "lowercase")]
181pub enum TailwindDarkMode {
182    /// Follow the operating system (`prefers-color-scheme`).
183    #[default]
184    Media,
185    /// When an ancestor has the `dark` class.
186    Class,
187    /// When an ancestor has `data-theme="dark"`.
188    Attribute,
189}
190
191/// A custom utility in `[tailwind.utilities]`.
192#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(untagged)]
194pub enum TailwindUtility {
195    /// Tailwind classes combined with `@apply`: `"rounded-lg px-4 py-2"`.
196    Apply(String),
197    /// CSS declarations: `{ content-visibility = "auto" }`.
198    Declarations(BTreeMap<String, String>),
199}
200
201impl From<&str> for TailwindUtility {
202    fn from(classes: &str) -> Self {
203        Self::Apply(classes.to_owned())
204    }
205}
206
207impl From<String> for TailwindUtility {
208    fn from(classes: String) -> Self {
209        Self::Apply(classes)
210    }
211}
212
213#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
214#[serde(default, deny_unknown_fields)]
215pub struct AppConfig {
216    /// Routing directory, scanned recursively.
217    pub directory: PathBuf,
218    /// Static files served from the site root.
219    pub public: PathBuf,
220    /// Mount the whole application under a sub-path, e.g. `/docs`.
221    pub base_path: String,
222    /// `false`: `/about/` redirects to `/about`. `true`: the reverse.
223    pub trailing_slash: bool,
224    /// `lang` attribute of the `<html>` element.
225    pub lang: String,
226    /// What to do when a directory contains both `page.rs` and `page.html`.
227    pub html_precedence: HtmlPrecedence,
228    /// Follow symbolic links while scanning (loops are detected).
229    pub follow_symlinks: bool,
230}
231
232impl Default for AppConfig {
233    fn default() -> Self {
234        Self {
235            directory: PathBuf::from("app"),
236            public: PathBuf::from("public"),
237            base_path: String::new(),
238            trailing_slash: false,
239            lang: "en".into(),
240            html_precedence: HtmlPrecedence::Error,
241            follow_symlinks: true,
242        }
243    }
244}
245
246#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
247#[serde(rename_all = "lowercase")]
248pub enum HtmlPrecedence {
249    /// Report a build error (default).
250    #[default]
251    Error,
252    /// `page.rs` wins; `page.html` is ignored with a warning.
253    Rs,
254    /// `page.html` wins; `page.rs` is ignored with a warning.
255    Html,
256}
257
258#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(default, deny_unknown_fields)]
260pub struct ApiConfig {
261    /// Optional second routing root that only contains `route.rs` handlers.
262    pub directory: Option<PathBuf>,
263    /// URL prefix under which `api.directory` is mounted.
264    pub prefix: String,
265}
266
267impl Default for ApiConfig {
268    fn default() -> Self {
269        Self { directory: None, prefix: "/api".into() }
270    }
271}
272
273#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
274#[serde(default, deny_unknown_fields)]
275pub struct ServerConfig {
276    pub host: String,
277    pub port: u16,
278    /// Maximum buffered request body size in bytes.
279    pub body_limit: usize,
280    /// Seconds allowed for reading request headers (slowloris protection).
281    pub header_timeout: u64,
282    /// Seconds after which an in-flight request is aborted (0 = never).
283    pub request_timeout: u64,
284    /// Seconds to wait for in-flight requests on shutdown.
285    pub shutdown_timeout: u64,
286    pub compression: bool,
287    pub http2: bool,
288    /// Trust `X-Forwarded-For` / `X-Forwarded-Proto` from a reverse proxy.
289    pub trust_proxy: bool,
290}
291
292impl Default for ServerConfig {
293    fn default() -> Self {
294        Self {
295            host: "0.0.0.0".into(),
296            port: 3000,
297            body_limit: 2 * 1024 * 1024,
298            header_timeout: 10,
299            request_timeout: 60,
300            shutdown_timeout: 10,
301            compression: true,
302            http2: false,
303            trust_proxy: false,
304        }
305    }
306}
307
308#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
309#[serde(default, deny_unknown_fields)]
310pub struct BuildConfig {
311    pub output: PathBuf,
312    /// Reserved: static generation currently renders pages sequentially.
313    pub concurrency: usize,
314    /// What `next-rust build` optimizes the binary for.
315    pub optimize: Optimize,
316    /// What happens when code panics in a release binary.
317    pub panic: PanicStrategy,
318}
319
320impl Default for BuildConfig {
321    fn default() -> Self {
322        Self {
323            output: PathBuf::from(".next-rust"),
324            concurrency: 8,
325            optimize: Optimize::Size,
326            panic: PanicStrategy::Unwind,
327        }
328    }
329}
330
331/// `[build] optimize`
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
333#[serde(rename_all = "lowercase")]
334pub enum Optimize {
335    /// Smallest binary (`opt-level = "z"`).
336    #[default]
337    Size,
338    /// Fastest code (`opt-level = 3`), larger binary.
339    Speed,
340}
341
342/// `[build] panic`
343#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
344#[serde(rename_all = "lowercase")]
345pub enum PanicStrategy {
346    /// A panic fails only the request that caused it; the server keeps running.
347    #[default]
348    Unwind,
349    /// A panic stops the whole process. About 20% smaller; run it under a
350    /// supervisor that restarts it.
351    Abort,
352}
353
354#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
355#[serde(default, deny_unknown_fields)]
356pub struct AssetsConfig {
357    /// Reserved: CSS is always minified at compile time by the CSS macros.
358    pub optimize: bool,
359    /// `Cache-Control` max-age (seconds) for files from `public/`.
360    pub public_max_age: u64,
361    /// Release builds leave out CSS rules (from `global_css!` and
362    /// `css_module!`) whose classes or ids appear nowhere in the project.
363    pub prune_css: bool,
364    /// Class and id names to keep even though they don't appear in the
365    /// source, e.g. names assembled at runtime.
366    pub css_safelist: Vec<String>,
367}
368
369impl Default for AssetsConfig {
370    fn default() -> Self {
371        Self { optimize: true, public_max_age: 0, prune_css: true, css_safelist: Vec::new() }
372    }
373}
374
375#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
376#[serde(default, deny_unknown_fields)]
377pub struct RenderingConfig {
378    pub default: RenderingMode,
379    /// Stream HTML progressively when a route has `loading.rs` / suspense.
380    pub streaming: bool,
381    /// Default revalidation interval (seconds) for static pages. `None` = never.
382    pub revalidate: Option<u64>,
383    /// Client-side navigation for `Link!` (loads a ~4 KB gzipped script).
384    pub client_navigation: bool,
385}
386
387impl Default for RenderingConfig {
388    fn default() -> Self {
389        Self { default: RenderingMode::Auto, streaming: true, revalidate: None, client_navigation: true }
390    }
391}
392
393#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
394#[serde(default, deny_unknown_fields)]
395pub struct ImagesConfig {
396    /// Reserved for the image optimizer (`Image!` currently uses the same default widths).
397    pub sizes: Vec<u32>,
398    pub quality: u8,
399    /// Seconds optimized images are cached by clients.
400    pub max_age: u64,
401}
402
403impl Default for ImagesConfig {
404    fn default() -> Self {
405        Self { sizes: vec![640, 750, 828, 1080, 1200, 1920, 2048, 3840], quality: 75, max_age: 60 * 60 * 24 * 30 }
406    }
407}
408
409#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
410#[serde(default, deny_unknown_fields)]
411pub struct SecurityConfig {
412    /// Send a conservative set of security headers on every response.
413    pub headers: bool,
414    /// `Content-Security-Policy` value. `{nonce}` is replaced by the per-request nonce.
415    pub csp: Option<String>,
416    /// CSRF protection for server actions.
417    pub csrf: CsrfMode,
418    /// `Strict-Transport-Security` max-age in seconds (0 disables the header).
419    pub hsts_max_age: u64,
420    /// Additional origins allowed to invoke server actions.
421    pub allowed_origins: Vec<String>,
422}
423
424impl Default for SecurityConfig {
425    fn default() -> Self {
426        Self { headers: true, csp: None, csrf: CsrfMode::Origin, hsts_max_age: 0, allowed_origins: Vec::new() }
427    }
428}
429
430#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
431#[serde(rename_all = "lowercase")]
432pub enum CsrfMode {
433    /// Verify `Origin`/`Sec-Fetch-Site` against the request host (default).
434    #[default]
435    Origin,
436    /// Additionally require a double-submit token.
437    Token,
438    /// Disable (not recommended).
439    Off,
440}
441
442#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
443#[serde(default, deny_unknown_fields)]
444pub struct EnvConfig {
445    /// Only variables with this prefix may reach client-visible output.
446    pub public_prefix: String,
447}
448
449impl Default for EnvConfig {
450    fn default() -> Self {
451        Self { public_prefix: "NEXT_RUST_PUBLIC_".into() }
452    }
453}
454
455#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
456#[serde(default, deny_unknown_fields)]
457pub struct DevConfig {
458    /// File watcher polling interval in milliseconds.
459    pub poll_interval: u64,
460    /// Show the error overlay in the browser.
461    pub overlay: bool,
462    /// Extra paths (relative to the project root) that trigger rebuilds.
463    pub watch: Vec<PathBuf>,
464    /// Fill newly created, empty special files (`page.rs`, `layout.rs`,
465    /// `route.rs`, ...) with starter code while `next-rust dev` runs.
466    pub scaffold: bool,
467}
468
469impl Default for DevConfig {
470    fn default() -> Self {
471        Self { poll_interval: 250, overlay: true, watch: Vec::new(), scaffold: true }
472    }
473}
474
475#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
476#[serde(default, deny_unknown_fields)]
477pub struct LoggingConfig {
478    pub format: LogFormat,
479    /// `error`, `warn`, `info`, `debug` or `trace`.
480    /// Default: `info` in development, `error` in production and tests.
481    pub level: Option<String>,
482    /// Log one line per request. Default: on in development, off otherwise.
483    pub requests: Option<bool>,
484}
485
486impl Default for LoggingConfig {
487    fn default() -> Self {
488        Self { format: LogFormat::Auto, level: None, requests: None }
489    }
490}
491
492impl LoggingConfig {
493    /// Effective log level. Production prints only errors unless configured.
494    pub fn level(&self, env: crate::Environment) -> &str {
495        match &self.level {
496            Some(level) => level,
497            None if env.is_dev() => "info",
498            None => "error",
499        }
500    }
501
502    /// Whether request lines are logged. Off outside development unless configured.
503    pub fn requests(&self, env: crate::Environment) -> bool {
504        self.requests.unwrap_or(env.is_dev())
505    }
506}
507
508#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
509#[serde(rename_all = "lowercase")]
510pub enum LogFormat {
511    /// `pretty` in development, `json` in production.
512    #[default]
513    Auto,
514    Pretty,
515    Json,
516}
517
518#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
519#[serde(deny_unknown_fields)]
520pub struct RedirectRule {
521    /// Path pattern: `/old/:slug`, `/blog/:path*`.
522    pub source: String,
523    /// Destination; may reference captured parameters (`/new/:slug`).
524    pub destination: String,
525    #[serde(default)]
526    pub permanent: bool,
527}
528
529#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
530#[serde(deny_unknown_fields)]
531pub struct HeaderRule {
532    pub source: String,
533    pub headers: BTreeMap<String, String>,
534}
535
536#[derive(Debug)]
537pub enum ConfigError {
538    Io { path: PathBuf, error: std::io::Error },
539    Parse { path: PathBuf, message: String },
540    Ambiguous { dir: PathBuf },
541}
542
543impl fmt::Display for ConfigError {
544    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
545        match self {
546            ConfigError::Io { path, error } => write!(f, "could not read {}: {error}", path.display()),
547            ConfigError::Parse { path, message } => {
548                write!(f, "invalid configuration in {}:\n{message}", path.display())
549            }
550            ConfigError::Ambiguous { dir } => write!(
551                f,
552                "both {TOML_FILE} and {JSON_FILE} exist in {}; keep only one (TOML is preferred)",
553                dir.display()
554            ),
555        }
556    }
557}
558
559impl std::error::Error for ConfigError {}
560
561/// Parses TOML configuration. Passed explicitly so programs that never read
562/// TOML at runtime (release binaries, whose configuration is embedded as
563/// JSON) don't link a TOML parser.
564pub type TomlParser = fn(&str) -> Result<Config, String>;
565
566impl Config {
567    /// Discover and load the configuration starting at `start`.
568    pub fn discover(start: impl AsRef<Path>) -> Result<Self, ConfigError> {
569        Self::discover_with(start, Some(Self::from_toml_str))
570    }
571
572    /// [`Config::discover`] with an optional TOML parser. Without one,
573    /// `next-rust.toml` files are reported as an error and only JSON
574    /// configuration can be read.
575    pub fn discover_with(start: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
576        if let Ok(explicit) = std::env::var("NEXT_RUST_CONFIG") {
577            return Self::load_with(explicit, toml);
578        }
579        let start = absolutize(start.as_ref());
580        for dir in start.ancestors() {
581            let toml_file = dir.join(TOML_FILE);
582            let json = dir.join(JSON_FILE);
583            match (toml_file.is_file(), json.is_file()) {
584                (true, true) => return Err(ConfigError::Ambiguous { dir: dir.to_path_buf() }),
585                (true, false) => return Self::load_with(toml_file, toml),
586                (false, true) => return Self::load_with(json, toml),
587                _ => {}
588            }
589            // Stop at the Cargo package boundary if there is no config:
590            // zero-config projects are rooted at their manifest.
591            if dir.join("Cargo.toml").is_file() && dir.join("app").is_dir() {
592                break;
593            }
594        }
595        let mut config = Config { root: start, ..Config::default() };
596        config.apply_env_overrides();
597        Ok(config)
598    }
599
600    /// Load a specific file (`.toml` or `.json`).
601    pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
602        Self::load_with(path, Some(Self::from_toml_str))
603    }
604
605    /// [`Config::load`] with an optional TOML parser (see [`TomlParser`]).
606    pub fn load_with(path: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
607        let path = absolutize(path.as_ref());
608        let text = std::fs::read_to_string(&path).map_err(|error| ConfigError::Io { path: path.clone(), error })?;
609        let mut config = if path.extension().is_some_and(|e| e == "json") {
610            Self::from_json_str(&text)
611        } else {
612            match toml {
613                Some(parse) => parse(&text),
614                None => Err("this binary reads JSON configuration only (its configuration was embedded at build \
615                     time); point NEXT_RUST_CONFIG at a .json file"
616                    .to_owned()),
617            }
618        }
619        .map_err(|message| ConfigError::Parse { path: path.clone(), message })?;
620        config.root = path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
621        config.source = Some(path);
622        config.apply_env_overrides();
623        Ok(config)
624    }
625
626    pub fn from_toml_str(text: &str) -> Result<Self, String> {
627        toml::from_str(text).map_err(|e| e.to_string())
628    }
629
630    pub fn from_json_str(text: &str) -> Result<Self, String> {
631        serde_json::from_str(text).map_err(|e| e.to_string())
632    }
633
634    /// `PORT` and `HOST` (conventional on container platforms) override the file.
635    pub fn apply_env_overrides(&mut self) {
636        if let Some(port) = std::env::var("PORT").ok().and_then(|p| p.parse().ok()) {
637            self.server.port = port;
638        }
639        if let Ok(host) = std::env::var("HOST")
640            && !host.is_empty()
641        {
642            self.server.host = host;
643        }
644    }
645
646    /// Resolve a path from the configuration against the project root.
647    pub fn resolve(&self, path: impl AsRef<Path>) -> PathBuf {
648        let path = path.as_ref();
649        if path.is_absolute() { normalize(path) } else { normalize(&self.root.join(path)) }
650    }
651
652    pub fn app_dir(&self) -> PathBuf {
653        self.resolve(&self.app.directory)
654    }
655
656    pub fn public_dir(&self) -> PathBuf {
657        self.resolve(&self.app.public)
658    }
659
660    pub fn api_dir(&self) -> Option<PathBuf> {
661        self.api.directory.as_ref().map(|d| self.resolve(d))
662    }
663
664    pub fn output_dir(&self) -> PathBuf {
665        self.resolve(&self.build.output)
666    }
667
668    /// Validate paths and values; returns human friendly diagnostics.
669    pub fn validate(&self) -> Vec<Diagnostic> {
670        let mut out = Vec::new();
671        let app = self.app_dir();
672        if !app.exists() {
673            out.push(
674                Diagnostic::error("NR0001", "App directory not found")
675                    .location(&app)
676                    .message(format!(
677                        "The routing directory configured as `app.directory = {:?}`\nresolves to {}, which does not exist.",
678                        self.app.directory,
679                        app.display()
680                    ))
681                    .help("create the directory or change `[app] directory` in next-rust.toml"),
682            );
683        } else if !app.is_dir() {
684            out.push(
685                Diagnostic::error("NR0002", "App directory is not a directory")
686                    .location(&app)
687                    .help("`[app] directory` must point to a directory"),
688            );
689        }
690        if let Some(api) = self.api_dir() {
691            if !api.is_dir() {
692                out.push(Diagnostic::error("NR0003", "API directory not found").location(api));
693            }
694            if !self.api.prefix.starts_with('/') {
695                out.push(
696                    Diagnostic::error("NR0004", "API prefix must start with `/`")
697                        .message(format!("found `api.prefix = {:?}`", self.api.prefix)),
698                );
699            }
700        }
701        if !self.app.base_path.is_empty() && (!self.app.base_path.starts_with('/') || self.app.base_path.ends_with('/'))
702        {
703            out.push(
704                Diagnostic::error("NR0005", "Invalid base path")
705                    .message(format!("`app.base_path = {:?}`", self.app.base_path))
706                    .help("use a leading slash and no trailing slash, e.g. `/docs`"),
707            );
708        }
709        for rule in &self.redirects {
710            if !rule.source.starts_with('/') {
711                out.push(
712                    Diagnostic::error("NR0006", "Redirect source must start with `/`")
713                        .message(format!("source = {:?}", rule.source)),
714                );
715            }
716        }
717        if let Some(level) = &self.logging.level
718            && !matches!(level.as_str(), "error" | "warn" | "info" | "debug" | "trace")
719        {
720            out.push(
721                Diagnostic::warning("NR0007", "Unknown log level")
722                    .message(format!("`logging.level = {level:?}`; falling back to `info`")),
723            );
724        }
725        out
726    }
727
728    pub fn socket_addr_string(&self) -> String {
729        if self.server.host.contains(':') {
730            format!("[{}]:{}", self.server.host, self.server.port)
731        } else {
732            format!("{}:{}", self.server.host, self.server.port)
733        }
734    }
735}
736
737fn absolutize(p: &Path) -> PathBuf {
738    if p.is_absolute() {
739        normalize(p)
740    } else {
741        normalize(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")).join(p))
742    }
743}
744
745/// Lexically normalize a path: removes `.` and resolves `..` without
746/// touching the filesystem (so it works for paths that do not exist yet).
747pub fn normalize(path: &Path) -> PathBuf {
748    let mut out = PathBuf::new();
749    for comp in path.components() {
750        match comp {
751            Component::CurDir => {}
752            Component::ParentDir => {
753                if !out.pop() {
754                    out.push("..");
755                }
756            }
757            other => out.push(other.as_os_str()),
758        }
759    }
760    if out.as_os_str().is_empty() { PathBuf::from(".") } else { out }
761}
762
763#[cfg(test)]
764mod tests {
765    use super::*;
766
767    #[test]
768    fn defaults_are_zero_config() {
769        let c = Config::from_toml_str("").unwrap();
770        assert_eq!(c.app.directory, PathBuf::from("app"));
771        assert_eq!(c.server.port, 3000);
772        assert_eq!(c.build.output, PathBuf::from(".next-rust"));
773        assert_eq!(c.rendering.default, RenderingMode::Auto);
774    }
775
776    #[test]
777    fn parses_sections() {
778        let c = Config::from_toml_str(
779            r#"
780            [app]
781            directory = "src/web"
782            [server]
783            port = 8080
784            [rendering]
785            default = "server"
786            [[redirects]]
787            source = "/old"
788            destination = "/new"
789            permanent = true
790            [plugins.analytics]
791            id = "x"
792            "#,
793        )
794        .unwrap();
795        assert_eq!(c.app.directory, PathBuf::from("src/web"));
796        assert_eq!(c.server.port, 8080);
797        assert_eq!(c.rendering.default, RenderingMode::Dynamic);
798        assert!(c.redirects[0].permanent);
799        assert_eq!(c.plugins["analytics"]["id"], "x");
800    }
801
802    #[test]
803    fn rejects_unknown_keys() {
804        let err = Config::from_toml_str("[app]\ndirectroy = \"x\"").unwrap_err();
805        assert!(err.contains("directroy"), "{err}");
806    }
807
808    #[test]
809    fn json_is_supported() {
810        let c = Config::from_json_str(r#"{"app":{"directory":"frontend"}}"#).unwrap();
811        assert_eq!(c.app.directory, PathBuf::from("frontend"));
812    }
813
814    #[test]
815    fn resolves_relative_to_root() {
816        let c = Config {
817            root: PathBuf::from("/work/repo/apps/site"),
818            app: AppConfig { directory: PathBuf::from("../shared/my-pages"), ..Default::default() },
819            ..Default::default()
820        };
821        assert_eq!(c.app_dir(), PathBuf::from("/work/repo/apps/shared/my-pages"));
822        let c = Config {
823            root: PathBuf::from("/work"),
824            app: AppConfig { directory: PathBuf::from("/abs/pages/./x/.."), ..Default::default() },
825            ..Default::default()
826        };
827        assert_eq!(c.app_dir(), PathBuf::from("/abs/pages"));
828    }
829
830    #[test]
831    fn discovery_walks_up() {
832        let base = std::env::temp_dir().join(format!("nr-config-{}", std::process::id()));
833        let nested = base.join("a/b");
834        std::fs::create_dir_all(&nested).unwrap();
835        std::fs::write(base.join(TOML_FILE), "[app]\ndirectory = \"website/routes\"\n").unwrap();
836        let c = Config::discover(&nested).unwrap();
837        assert_eq!(c.root, base);
838        assert_eq!(c.app_dir(), base.join("website/routes"));
839        let diags = c.validate();
840        assert_eq!(diags[0].code, "NR0001");
841        std::fs::write(base.join(JSON_FILE), "{}").unwrap();
842        assert!(matches!(Config::discover(&nested), Err(ConfigError::Ambiguous { .. })));
843        std::fs::remove_dir_all(&base).unwrap();
844    }
845}