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