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}
150
151impl Default for TailwindConfig {
152 fn default() -> Self {
153 Self {
154 enabled: false,
155 preflight: true,
156 dark_mode: TailwindDarkMode::Media,
157 theme: BTreeMap::new(),
158 utilities: BTreeMap::new(),
159 variants: BTreeMap::new(),
160 plugins: Vec::new(),
161 safelist: Vec::new(),
162 sources: Vec::new(),
163 css: String::new(),
164 }
165 }
166}
167
168#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
170#[serde(rename_all = "lowercase")]
171pub enum TailwindDarkMode {
172 #[default]
174 Media,
175 Class,
177 Attribute,
179}
180
181#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
183#[serde(untagged)]
184pub enum TailwindUtility {
185 Apply(String),
187 Declarations(BTreeMap<String, String>),
189}
190
191impl From<&str> for TailwindUtility {
192 fn from(classes: &str) -> Self {
193 Self::Apply(classes.to_owned())
194 }
195}
196
197impl From<String> for TailwindUtility {
198 fn from(classes: String) -> Self {
199 Self::Apply(classes)
200 }
201}
202
203#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
204#[serde(default, deny_unknown_fields)]
205pub struct AppConfig {
206 pub directory: PathBuf,
208 pub public: PathBuf,
210 pub base_path: String,
212 pub trailing_slash: bool,
214 pub lang: String,
216 pub html_precedence: HtmlPrecedence,
218 pub follow_symlinks: bool,
220}
221
222impl Default for AppConfig {
223 fn default() -> Self {
224 Self {
225 directory: PathBuf::from("app"),
226 public: PathBuf::from("public"),
227 base_path: String::new(),
228 trailing_slash: false,
229 lang: "en".into(),
230 html_precedence: HtmlPrecedence::Error,
231 follow_symlinks: true,
232 }
233 }
234}
235
236#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
237#[serde(rename_all = "lowercase")]
238pub enum HtmlPrecedence {
239 #[default]
241 Error,
242 Rs,
244 Html,
246}
247
248#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
249#[serde(default, deny_unknown_fields)]
250pub struct ApiConfig {
251 pub directory: Option<PathBuf>,
253 pub prefix: String,
255}
256
257impl Default for ApiConfig {
258 fn default() -> Self {
259 Self { directory: None, prefix: "/api".into() }
260 }
261}
262
263#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
264#[serde(default, deny_unknown_fields)]
265pub struct ServerConfig {
266 pub host: String,
267 pub port: u16,
268 pub body_limit: usize,
270 pub header_timeout: u64,
272 pub request_timeout: u64,
274 pub shutdown_timeout: u64,
276 pub compression: bool,
277 pub http2: bool,
278 pub trust_proxy: bool,
280}
281
282impl Default for ServerConfig {
283 fn default() -> Self {
284 Self {
285 host: "0.0.0.0".into(),
286 port: 3000,
287 body_limit: 2 * 1024 * 1024,
288 header_timeout: 10,
289 request_timeout: 60,
290 shutdown_timeout: 10,
291 compression: true,
292 http2: false,
293 trust_proxy: false,
294 }
295 }
296}
297
298#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
299#[serde(default, deny_unknown_fields)]
300pub struct BuildConfig {
301 pub output: PathBuf,
302 pub concurrency: usize,
304 pub optimize: Optimize,
306 pub panic: PanicStrategy,
308}
309
310impl Default for BuildConfig {
311 fn default() -> Self {
312 Self {
313 output: PathBuf::from(".next-rust"),
314 concurrency: 8,
315 optimize: Optimize::Size,
316 panic: PanicStrategy::Unwind,
317 }
318 }
319}
320
321#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
323#[serde(rename_all = "lowercase")]
324pub enum Optimize {
325 #[default]
327 Size,
328 Speed,
330}
331
332#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
334#[serde(rename_all = "lowercase")]
335pub enum PanicStrategy {
336 #[default]
338 Unwind,
339 Abort,
342}
343
344#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
345#[serde(default, deny_unknown_fields)]
346pub struct AssetsConfig {
347 pub optimize: bool,
349 pub public_max_age: u64,
351 pub prune_css: bool,
354 pub css_safelist: Vec<String>,
357}
358
359impl Default for AssetsConfig {
360 fn default() -> Self {
361 Self { optimize: true, public_max_age: 0, prune_css: true, css_safelist: Vec::new() }
362 }
363}
364
365#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
366#[serde(default, deny_unknown_fields)]
367pub struct RenderingConfig {
368 pub default: RenderingMode,
369 pub streaming: bool,
371 pub revalidate: Option<u64>,
373 pub client_navigation: bool,
375}
376
377impl Default for RenderingConfig {
378 fn default() -> Self {
379 Self { default: RenderingMode::Auto, streaming: true, revalidate: None, client_navigation: true }
380 }
381}
382
383#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
384#[serde(default, deny_unknown_fields)]
385pub struct ImagesConfig {
386 pub sizes: Vec<u32>,
388 pub quality: u8,
389 pub max_age: u64,
391}
392
393impl Default for ImagesConfig {
394 fn default() -> Self {
395 Self { sizes: vec![640, 750, 828, 1080, 1200, 1920, 2048, 3840], quality: 75, max_age: 60 * 60 * 24 * 30 }
396 }
397}
398
399#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
400#[serde(default, deny_unknown_fields)]
401pub struct SecurityConfig {
402 pub headers: bool,
404 pub csp: Option<String>,
406 pub csrf: CsrfMode,
408 pub hsts_max_age: u64,
410 pub allowed_origins: Vec<String>,
412}
413
414impl Default for SecurityConfig {
415 fn default() -> Self {
416 Self { headers: true, csp: None, csrf: CsrfMode::Origin, hsts_max_age: 0, allowed_origins: Vec::new() }
417 }
418}
419
420#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
421#[serde(rename_all = "lowercase")]
422pub enum CsrfMode {
423 #[default]
425 Origin,
426 Token,
428 Off,
430}
431
432#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
433#[serde(default, deny_unknown_fields)]
434pub struct EnvConfig {
435 pub public_prefix: String,
437}
438
439impl Default for EnvConfig {
440 fn default() -> Self {
441 Self { public_prefix: "NEXT_RUST_PUBLIC_".into() }
442 }
443}
444
445#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
446#[serde(default, deny_unknown_fields)]
447pub struct DevConfig {
448 pub poll_interval: u64,
450 pub overlay: bool,
452 pub watch: Vec<PathBuf>,
454 pub scaffold: bool,
457}
458
459impl Default for DevConfig {
460 fn default() -> Self {
461 Self { poll_interval: 250, overlay: true, watch: Vec::new(), scaffold: true }
462 }
463}
464
465#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
466#[serde(default, deny_unknown_fields)]
467pub struct LoggingConfig {
468 pub format: LogFormat,
469 pub level: Option<String>,
472 pub requests: Option<bool>,
474}
475
476impl Default for LoggingConfig {
477 fn default() -> Self {
478 Self { format: LogFormat::Auto, level: None, requests: None }
479 }
480}
481
482impl LoggingConfig {
483 pub fn level(&self, env: crate::Environment) -> &str {
485 match &self.level {
486 Some(level) => level,
487 None if env.is_dev() => "info",
488 None => "error",
489 }
490 }
491
492 pub fn requests(&self, env: crate::Environment) -> bool {
494 self.requests.unwrap_or(env.is_dev())
495 }
496}
497
498#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
499#[serde(rename_all = "lowercase")]
500pub enum LogFormat {
501 #[default]
503 Auto,
504 Pretty,
505 Json,
506}
507
508#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
509#[serde(deny_unknown_fields)]
510pub struct RedirectRule {
511 pub source: String,
513 pub destination: String,
515 #[serde(default)]
516 pub permanent: bool,
517}
518
519#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
520#[serde(deny_unknown_fields)]
521pub struct HeaderRule {
522 pub source: String,
523 pub headers: BTreeMap<String, String>,
524}
525
526#[derive(Debug)]
527pub enum ConfigError {
528 Io { path: PathBuf, error: std::io::Error },
529 Parse { path: PathBuf, message: String },
530 Ambiguous { dir: PathBuf },
531}
532
533impl fmt::Display for ConfigError {
534 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
535 match self {
536 ConfigError::Io { path, error } => write!(f, "could not read {}: {error}", path.display()),
537 ConfigError::Parse { path, message } => {
538 write!(f, "invalid configuration in {}:\n{message}", path.display())
539 }
540 ConfigError::Ambiguous { dir } => write!(
541 f,
542 "both {TOML_FILE} and {JSON_FILE} exist in {}; keep only one (TOML is preferred)",
543 dir.display()
544 ),
545 }
546 }
547}
548
549impl std::error::Error for ConfigError {}
550
551pub type TomlParser = fn(&str) -> Result<Config, String>;
555
556impl Config {
557 pub fn discover(start: impl AsRef<Path>) -> Result<Self, ConfigError> {
559 Self::discover_with(start, Some(Self::from_toml_str))
560 }
561
562 pub fn discover_with(start: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
566 if let Ok(explicit) = std::env::var("NEXT_RUST_CONFIG") {
567 return Self::load_with(explicit, toml);
568 }
569 let start = absolutize(start.as_ref());
570 for dir in start.ancestors() {
571 let toml_file = dir.join(TOML_FILE);
572 let json = dir.join(JSON_FILE);
573 match (toml_file.is_file(), json.is_file()) {
574 (true, true) => return Err(ConfigError::Ambiguous { dir: dir.to_path_buf() }),
575 (true, false) => return Self::load_with(toml_file, toml),
576 (false, true) => return Self::load_with(json, toml),
577 _ => {}
578 }
579 if dir.join("Cargo.toml").is_file() && dir.join("app").is_dir() {
582 break;
583 }
584 }
585 let mut config = Config { root: start, ..Config::default() };
586 config.apply_env_overrides();
587 Ok(config)
588 }
589
590 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
592 Self::load_with(path, Some(Self::from_toml_str))
593 }
594
595 pub fn load_with(path: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
597 let path = absolutize(path.as_ref());
598 let text = std::fs::read_to_string(&path).map_err(|error| ConfigError::Io { path: path.clone(), error })?;
599 let mut config = if path.extension().is_some_and(|e| e == "json") {
600 Self::from_json_str(&text)
601 } else {
602 match toml {
603 Some(parse) => parse(&text),
604 None => Err("this binary reads JSON configuration only (its configuration was embedded at build \
605 time); point NEXT_RUST_CONFIG at a .json file"
606 .to_owned()),
607 }
608 }
609 .map_err(|message| ConfigError::Parse { path: path.clone(), message })?;
610 config.root = path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
611 config.source = Some(path);
612 config.apply_env_overrides();
613 Ok(config)
614 }
615
616 pub fn from_toml_str(text: &str) -> Result<Self, String> {
617 toml::from_str(text).map_err(|e| e.to_string())
618 }
619
620 pub fn from_json_str(text: &str) -> Result<Self, String> {
621 serde_json::from_str(text).map_err(|e| e.to_string())
622 }
623
624 pub fn apply_env_overrides(&mut self) {
626 if let Some(port) = std::env::var("PORT").ok().and_then(|p| p.parse().ok()) {
627 self.server.port = port;
628 }
629 if let Ok(host) = std::env::var("HOST")
630 && !host.is_empty()
631 {
632 self.server.host = host;
633 }
634 }
635
636 pub fn resolve(&self, path: impl AsRef<Path>) -> PathBuf {
638 let path = path.as_ref();
639 if path.is_absolute() { normalize(path) } else { normalize(&self.root.join(path)) }
640 }
641
642 pub fn app_dir(&self) -> PathBuf {
643 self.resolve(&self.app.directory)
644 }
645
646 pub fn public_dir(&self) -> PathBuf {
647 self.resolve(&self.app.public)
648 }
649
650 pub fn api_dir(&self) -> Option<PathBuf> {
651 self.api.directory.as_ref().map(|d| self.resolve(d))
652 }
653
654 pub fn output_dir(&self) -> PathBuf {
655 self.resolve(&self.build.output)
656 }
657
658 pub fn validate(&self) -> Vec<Diagnostic> {
660 let mut out = Vec::new();
661 let app = self.app_dir();
662 if !app.exists() {
663 out.push(
664 Diagnostic::error("NR0001", "App directory not found")
665 .location(&app)
666 .message(format!(
667 "The routing directory configured as `app.directory = {:?}`\nresolves to {}, which does not exist.",
668 self.app.directory,
669 app.display()
670 ))
671 .help("create the directory or change `[app] directory` in next-rust.toml"),
672 );
673 } else if !app.is_dir() {
674 out.push(
675 Diagnostic::error("NR0002", "App directory is not a directory")
676 .location(&app)
677 .help("`[app] directory` must point to a directory"),
678 );
679 }
680 if let Some(api) = self.api_dir() {
681 if !api.is_dir() {
682 out.push(Diagnostic::error("NR0003", "API directory not found").location(api));
683 }
684 if !self.api.prefix.starts_with('/') {
685 out.push(
686 Diagnostic::error("NR0004", "API prefix must start with `/`")
687 .message(format!("found `api.prefix = {:?}`", self.api.prefix)),
688 );
689 }
690 }
691 if !self.app.base_path.is_empty() && (!self.app.base_path.starts_with('/') || self.app.base_path.ends_with('/'))
692 {
693 out.push(
694 Diagnostic::error("NR0005", "Invalid base path")
695 .message(format!("`app.base_path = {:?}`", self.app.base_path))
696 .help("use a leading slash and no trailing slash, e.g. `/docs`"),
697 );
698 }
699 for rule in &self.redirects {
700 if !rule.source.starts_with('/') {
701 out.push(
702 Diagnostic::error("NR0006", "Redirect source must start with `/`")
703 .message(format!("source = {:?}", rule.source)),
704 );
705 }
706 }
707 if let Some(level) = &self.logging.level
708 && !matches!(level.as_str(), "error" | "warn" | "info" | "debug" | "trace")
709 {
710 out.push(
711 Diagnostic::warning("NR0007", "Unknown log level")
712 .message(format!("`logging.level = {level:?}`; falling back to `info`")),
713 );
714 }
715 out
716 }
717
718 pub fn socket_addr_string(&self) -> String {
719 if self.server.host.contains(':') {
720 format!("[{}]:{}", self.server.host, self.server.port)
721 } else {
722 format!("{}:{}", self.server.host, self.server.port)
723 }
724 }
725}
726
727fn absolutize(p: &Path) -> PathBuf {
728 if p.is_absolute() {
729 normalize(p)
730 } else {
731 normalize(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")).join(p))
732 }
733}
734
735pub fn normalize(path: &Path) -> PathBuf {
738 let mut out = PathBuf::new();
739 for comp in path.components() {
740 match comp {
741 Component::CurDir => {}
742 Component::ParentDir => {
743 if !out.pop() {
744 out.push("..");
745 }
746 }
747 other => out.push(other.as_os_str()),
748 }
749 }
750 if out.as_os_str().is_empty() { PathBuf::from(".") } else { out }
751}
752
753#[cfg(test)]
754mod tests {
755 use super::*;
756
757 #[test]
758 fn defaults_are_zero_config() {
759 let c = Config::from_toml_str("").unwrap();
760 assert_eq!(c.app.directory, PathBuf::from("app"));
761 assert_eq!(c.server.port, 3000);
762 assert_eq!(c.build.output, PathBuf::from(".next-rust"));
763 assert_eq!(c.rendering.default, RenderingMode::Auto);
764 }
765
766 #[test]
767 fn parses_sections() {
768 let c = Config::from_toml_str(
769 r#"
770 [app]
771 directory = "src/web"
772 [server]
773 port = 8080
774 [rendering]
775 default = "server"
776 [[redirects]]
777 source = "/old"
778 destination = "/new"
779 permanent = true
780 [plugins.analytics]
781 id = "x"
782 "#,
783 )
784 .unwrap();
785 assert_eq!(c.app.directory, PathBuf::from("src/web"));
786 assert_eq!(c.server.port, 8080);
787 assert_eq!(c.rendering.default, RenderingMode::Dynamic);
788 assert!(c.redirects[0].permanent);
789 assert_eq!(c.plugins["analytics"]["id"], "x");
790 }
791
792 #[test]
793 fn rejects_unknown_keys() {
794 let err = Config::from_toml_str("[app]\ndirectroy = \"x\"").unwrap_err();
795 assert!(err.contains("directroy"), "{err}");
796 }
797
798 #[test]
799 fn json_is_supported() {
800 let c = Config::from_json_str(r#"{"app":{"directory":"frontend"}}"#).unwrap();
801 assert_eq!(c.app.directory, PathBuf::from("frontend"));
802 }
803
804 #[test]
805 fn resolves_relative_to_root() {
806 let c = Config {
807 root: PathBuf::from("/work/repo/apps/site"),
808 app: AppConfig { directory: PathBuf::from("../shared/my-pages"), ..Default::default() },
809 ..Default::default()
810 };
811 assert_eq!(c.app_dir(), PathBuf::from("/work/repo/apps/shared/my-pages"));
812 let c = Config {
813 root: PathBuf::from("/work"),
814 app: AppConfig { directory: PathBuf::from("/abs/pages/./x/.."), ..Default::default() },
815 ..Default::default()
816 };
817 assert_eq!(c.app_dir(), PathBuf::from("/abs/pages"));
818 }
819
820 #[test]
821 fn discovery_walks_up() {
822 let base = std::env::temp_dir().join(format!("nr-config-{}", std::process::id()));
823 let nested = base.join("a/b");
824 std::fs::create_dir_all(&nested).unwrap();
825 std::fs::write(base.join(TOML_FILE), "[app]\ndirectory = \"website/routes\"\n").unwrap();
826 let c = Config::discover(&nested).unwrap();
827 assert_eq!(c.root, base);
828 assert_eq!(c.app_dir(), base.join("website/routes"));
829 let diags = c.validate();
830 assert_eq!(diags[0].code, "NR0001");
831 std::fs::write(base.join(JSON_FILE), "{}").unwrap();
832 assert!(matches!(Config::discover(&nested), Err(ConfigError::Ambiguous { .. })));
833 std::fs::remove_dir_all(&base).unwrap();
834 }
835}