1use 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 #[serde(skip)]
55 pub root: PathBuf,
56 #[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 pub plugins: BTreeMap<String, serde_json::Value>,
75 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(default, deny_unknown_fields)]
124pub struct TailwindConfig {
125 pub enabled: bool,
127 pub preflight: bool,
129 pub dark_mode: TailwindDarkMode,
131 pub theme: BTreeMap<String, String>,
134 pub utilities: BTreeMap<String, TailwindUtility>,
137 pub variants: BTreeMap<String, String>,
139 pub plugins: Vec<String>,
142 pub safelist: Vec<String>,
144 pub sources: Vec<PathBuf>,
146 pub css: String,
149 pub minify_classes: bool,
153 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
180#[serde(rename_all = "lowercase")]
181pub enum TailwindDarkMode {
182 #[default]
184 Media,
185 Class,
187 Attribute,
189}
190
191#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
193#[serde(untagged)]
194pub enum TailwindUtility {
195 Apply(String),
197 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 pub directory: PathBuf,
218 pub public: PathBuf,
220 pub base_path: String,
222 pub trailing_slash: bool,
224 pub lang: String,
226 pub html_precedence: HtmlPrecedence,
228 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 #[default]
251 Error,
252 Rs,
254 Html,
256}
257
258#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(default, deny_unknown_fields)]
260pub struct ApiConfig {
261 pub directory: Option<PathBuf>,
263 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 pub body_limit: usize,
280 pub header_timeout: u64,
282 pub request_timeout: u64,
284 pub shutdown_timeout: u64,
286 pub compression: bool,
287 pub http2: bool,
288 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 pub concurrency: usize,
314 pub optimize: Optimize,
316 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
333#[serde(rename_all = "lowercase")]
334pub enum Optimize {
335 #[default]
337 Size,
338 Speed,
340}
341
342#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
344#[serde(rename_all = "lowercase")]
345pub enum PanicStrategy {
346 #[default]
348 Unwind,
349 Abort,
352}
353
354#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
355#[serde(default, deny_unknown_fields)]
356pub struct AssetsConfig {
357 pub optimize: bool,
359 pub public_max_age: u64,
361 pub prune_css: bool,
364 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 pub streaming: bool,
381 pub revalidate: Option<u64>,
383 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 pub sizes: Vec<u32>,
398 pub quality: u8,
399 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 pub headers: bool,
414 pub csp: Option<String>,
416 pub csrf: CsrfMode,
418 pub hsts_max_age: u64,
420 pub allowed_origins: Vec<String>,
422 pub action_token_ttl: u64,
424}
425
426impl Default for SecurityConfig {
427 fn default() -> Self {
428 Self {
429 headers: true,
430 csp: None,
431 csrf: CsrfMode::Origin,
432 hsts_max_age: 0,
433 allowed_origins: Vec::new(),
434 action_token_ttl: 60 * 60 * 12,
435 }
436 }
437}
438
439#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
440#[serde(rename_all = "lowercase")]
441pub enum CsrfMode {
442 #[default]
444 Origin,
445 Token,
448 Off,
451}
452
453#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
454#[serde(default, deny_unknown_fields)]
455pub struct EnvConfig {
456 pub public_prefix: String,
458}
459
460impl Default for EnvConfig {
461 fn default() -> Self {
462 Self { public_prefix: "NEXT_RUST_PUBLIC_".into() }
463 }
464}
465
466#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
467#[serde(default, deny_unknown_fields)]
468pub struct DevConfig {
469 pub poll_interval: u64,
471 pub overlay: bool,
473 pub watch: Vec<PathBuf>,
475 pub scaffold: bool,
478}
479
480impl Default for DevConfig {
481 fn default() -> Self {
482 Self { poll_interval: 250, overlay: true, watch: Vec::new(), scaffold: true }
483 }
484}
485
486#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
487#[serde(default, deny_unknown_fields)]
488pub struct LoggingConfig {
489 pub format: LogFormat,
490 pub level: Option<String>,
493 pub requests: Option<bool>,
495}
496
497impl Default for LoggingConfig {
498 fn default() -> Self {
499 Self { format: LogFormat::Auto, level: None, requests: None }
500 }
501}
502
503impl LoggingConfig {
504 pub fn level(&self, env: crate::Environment) -> &str {
506 match &self.level {
507 Some(level) => level,
508 None if env.is_dev() => "info",
509 None => "error",
510 }
511 }
512
513 pub fn requests(&self, env: crate::Environment) -> bool {
515 self.requests.unwrap_or(env.is_dev())
516 }
517}
518
519#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
520#[serde(rename_all = "lowercase")]
521pub enum LogFormat {
522 #[default]
524 Auto,
525 Pretty,
526 Json,
527}
528
529#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
530#[serde(deny_unknown_fields)]
531pub struct RedirectRule {
532 pub source: String,
534 pub destination: String,
536 #[serde(default)]
537 pub permanent: bool,
538}
539
540#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
541#[serde(deny_unknown_fields)]
542pub struct HeaderRule {
543 pub source: String,
544 pub headers: BTreeMap<String, String>,
545}
546
547#[derive(Debug)]
548pub enum ConfigError {
549 Io { path: PathBuf, error: std::io::Error },
550 Parse { path: PathBuf, message: String },
551 Ambiguous { dir: PathBuf },
552}
553
554impl fmt::Display for ConfigError {
555 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
556 match self {
557 ConfigError::Io { path, error } => write!(f, "could not read {}: {error}", path.display()),
558 ConfigError::Parse { path, message } => {
559 write!(f, "invalid configuration in {}:\n{message}", path.display())
560 }
561 ConfigError::Ambiguous { dir } => write!(
562 f,
563 "both {TOML_FILE} and {JSON_FILE} exist in {}; keep only one (TOML is preferred)",
564 dir.display()
565 ),
566 }
567 }
568}
569
570impl std::error::Error for ConfigError {}
571
572pub type TomlParser = fn(&str) -> Result<Config, String>;
576
577impl Config {
578 pub fn discover(start: impl AsRef<Path>) -> Result<Self, ConfigError> {
580 Self::discover_with(start, Some(Self::from_toml_str))
581 }
582
583 pub fn discover_with(start: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
587 if let Ok(explicit) = std::env::var("NEXT_RUST_CONFIG") {
588 return Self::load_with(explicit, toml);
589 }
590 let start = absolutize(start.as_ref());
591 for dir in start.ancestors() {
592 let toml_file = dir.join(TOML_FILE);
593 let json = dir.join(JSON_FILE);
594 match (toml_file.is_file(), json.is_file()) {
595 (true, true) => return Err(ConfigError::Ambiguous { dir: dir.to_path_buf() }),
596 (true, false) => return Self::load_with(toml_file, toml),
597 (false, true) => return Self::load_with(json, toml),
598 _ => {}
599 }
600 if dir.join("Cargo.toml").is_file() && dir.join("app").is_dir() {
603 break;
604 }
605 }
606 let mut config = Config { root: start, ..Config::default() };
607 config.apply_env_overrides();
608 Ok(config)
609 }
610
611 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
613 Self::load_with(path, Some(Self::from_toml_str))
614 }
615
616 pub fn load_with(path: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
618 let path = absolutize(path.as_ref());
619 let text = std::fs::read_to_string(&path).map_err(|error| ConfigError::Io { path: path.clone(), error })?;
620 let mut config = if path.extension().is_some_and(|e| e == "json") {
621 Self::from_json_str(&text)
622 } else {
623 match toml {
624 Some(parse) => parse(&text),
625 None => Err("this binary reads JSON configuration only (its configuration was embedded at build \
626 time); point NEXT_RUST_CONFIG at a .json file"
627 .to_owned()),
628 }
629 }
630 .map_err(|message| ConfigError::Parse { path: path.clone(), message })?;
631 config.root = path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
632 config.source = Some(path);
633 config.apply_env_overrides();
634 Ok(config)
635 }
636
637 pub fn from_toml_str(text: &str) -> Result<Self, String> {
638 toml::from_str(text).map_err(|e| e.to_string())
639 }
640
641 pub fn from_json_str(text: &str) -> Result<Self, String> {
642 serde_json::from_str(text).map_err(|e| e.to_string())
643 }
644
645 pub fn apply_env_overrides(&mut self) {
647 if let Some(port) = std::env::var("PORT").ok().and_then(|p| p.parse().ok()) {
648 self.server.port = port;
649 }
650 if let Ok(host) = std::env::var("HOST")
651 && !host.is_empty()
652 {
653 self.server.host = host;
654 }
655 }
656
657 pub fn resolve(&self, path: impl AsRef<Path>) -> PathBuf {
659 let path = path.as_ref();
660 if path.is_absolute() { normalize(path) } else { normalize(&self.root.join(path)) }
661 }
662
663 pub fn app_dir(&self) -> PathBuf {
664 self.resolve(&self.app.directory)
665 }
666
667 pub fn public_dir(&self) -> PathBuf {
668 self.resolve(&self.app.public)
669 }
670
671 pub fn api_dir(&self) -> Option<PathBuf> {
672 self.api.directory.as_ref().map(|d| self.resolve(d))
673 }
674
675 pub fn output_dir(&self) -> PathBuf {
676 self.resolve(&self.build.output)
677 }
678
679 pub fn validate(&self) -> Vec<Diagnostic> {
681 let mut out = Vec::new();
682 let app = self.app_dir();
683 if !app.exists() {
684 out.push(
685 Diagnostic::error("NR0001", "App directory not found")
686 .location(&app)
687 .message(format!(
688 "The routing directory configured as `app.directory = {:?}`\nresolves to {}, which does not exist.",
689 self.app.directory,
690 app.display()
691 ))
692 .help("create the directory or change `[app] directory` in next-rust.toml"),
693 );
694 } else if !app.is_dir() {
695 out.push(
696 Diagnostic::error("NR0002", "App directory is not a directory")
697 .location(&app)
698 .help("`[app] directory` must point to a directory"),
699 );
700 }
701 if let Some(api) = self.api_dir() {
702 if !api.is_dir() {
703 out.push(Diagnostic::error("NR0003", "API directory not found").location(api));
704 }
705 if !self.api.prefix.starts_with('/') {
706 out.push(
707 Diagnostic::error("NR0004", "API prefix must start with `/`")
708 .message(format!("found `api.prefix = {:?}`", self.api.prefix)),
709 );
710 }
711 }
712 if !self.app.base_path.is_empty() && (!self.app.base_path.starts_with('/') || self.app.base_path.ends_with('/'))
713 {
714 out.push(
715 Diagnostic::error("NR0005", "Invalid base path")
716 .message(format!("`app.base_path = {:?}`", self.app.base_path))
717 .help("use a leading slash and no trailing slash, e.g. `/docs`"),
718 );
719 }
720 for rule in &self.redirects {
721 if !rule.source.starts_with('/') {
722 out.push(
723 Diagnostic::error("NR0006", "Redirect source must start with `/`")
724 .message(format!("source = {:?}", rule.source)),
725 );
726 }
727 }
728 if let Some(level) = &self.logging.level
729 && !matches!(level.as_str(), "error" | "warn" | "info" | "debug" | "trace")
730 {
731 out.push(
732 Diagnostic::warning("NR0007", "Unknown log level")
733 .message(format!("`logging.level = {level:?}`; falling back to `info`")),
734 );
735 }
736 out
737 }
738
739 pub fn socket_addr_string(&self) -> String {
740 if self.server.host.contains(':') {
741 format!("[{}]:{}", self.server.host, self.server.port)
742 } else {
743 format!("{}:{}", self.server.host, self.server.port)
744 }
745 }
746}
747
748fn absolutize(p: &Path) -> PathBuf {
749 if p.is_absolute() {
750 normalize(p)
751 } else {
752 normalize(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")).join(p))
753 }
754}
755
756pub fn normalize(path: &Path) -> PathBuf {
759 let mut out = PathBuf::new();
760 for comp in path.components() {
761 match comp {
762 Component::CurDir => {}
763 Component::ParentDir => {
764 if !out.pop() {
765 out.push("..");
766 }
767 }
768 other => out.push(other.as_os_str()),
769 }
770 }
771 if out.as_os_str().is_empty() { PathBuf::from(".") } else { out }
772}
773
774#[cfg(test)]
775mod tests {
776 use super::*;
777
778 #[test]
779 fn defaults_are_zero_config() {
780 let c = Config::from_toml_str("").unwrap();
781 assert_eq!(c.app.directory, PathBuf::from("app"));
782 assert_eq!(c.server.port, 3000);
783 assert_eq!(c.build.output, PathBuf::from(".next-rust"));
784 assert_eq!(c.rendering.default, RenderingMode::Auto);
785 }
786
787 #[test]
788 fn parses_sections() {
789 let c = Config::from_toml_str(
790 r#"
791 [app]
792 directory = "src/web"
793 [server]
794 port = 8080
795 [rendering]
796 default = "server"
797 [[redirects]]
798 source = "/old"
799 destination = "/new"
800 permanent = true
801 [plugins.analytics]
802 id = "x"
803 "#,
804 )
805 .unwrap();
806 assert_eq!(c.app.directory, PathBuf::from("src/web"));
807 assert_eq!(c.server.port, 8080);
808 assert_eq!(c.rendering.default, RenderingMode::Dynamic);
809 assert!(c.redirects[0].permanent);
810 assert_eq!(c.plugins["analytics"]["id"], "x");
811 }
812
813 #[test]
814 fn rejects_unknown_keys() {
815 let err = Config::from_toml_str("[app]\ndirectroy = \"x\"").unwrap_err();
816 assert!(err.contains("directroy"), "{err}");
817 }
818
819 #[test]
820 fn json_is_supported() {
821 let c = Config::from_json_str(r#"{"app":{"directory":"frontend"}}"#).unwrap();
822 assert_eq!(c.app.directory, PathBuf::from("frontend"));
823 }
824
825 #[test]
826 fn resolves_relative_to_root() {
827 let c = Config {
828 root: PathBuf::from("/work/repo/apps/site"),
829 app: AppConfig { directory: PathBuf::from("../shared/my-pages"), ..Default::default() },
830 ..Default::default()
831 };
832 assert_eq!(c.app_dir(), PathBuf::from("/work/repo/apps/shared/my-pages"));
833 let c = Config {
834 root: PathBuf::from("/work"),
835 app: AppConfig { directory: PathBuf::from("/abs/pages/./x/.."), ..Default::default() },
836 ..Default::default()
837 };
838 assert_eq!(c.app_dir(), PathBuf::from("/abs/pages"));
839 }
840
841 #[test]
842 fn discovery_walks_up() {
843 let base = std::env::temp_dir().join(format!("nr-config-{}", std::process::id()));
844 let nested = base.join("a/b");
845 std::fs::create_dir_all(&nested).unwrap();
846 std::fs::write(base.join(TOML_FILE), "[app]\ndirectory = \"website/routes\"\n").unwrap();
847 let c = Config::discover(&nested).unwrap();
848 assert_eq!(c.root, base);
849 assert_eq!(c.app_dir(), base.join("website/routes"));
850 let diags = c.validate();
851 assert_eq!(diags[0].code, "NR0001");
852 std::fs::write(base.join(JSON_FILE), "{}").unwrap();
853 assert!(matches!(Config::discover(&nested), Err(ConfigError::Ambiguous { .. })));
854 std::fs::remove_dir_all(&base).unwrap();
855 }
856}