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}
76
77impl Default for Config {
78 fn default() -> Self {
79 Self {
80 root: PathBuf::from("."),
81 source: None,
82 app: AppConfig::default(),
83 api: ApiConfig::default(),
84 server: ServerConfig::default(),
85 build: BuildConfig::default(),
86 assets: AssetsConfig::default(),
87 rendering: RenderingConfig::default(),
88 images: ImagesConfig::default(),
89 security: SecurityConfig::default(),
90 env: EnvConfig::default(),
91 dev: DevConfig::default(),
92 logging: LoggingConfig::default(),
93 redirects: Vec::new(),
94 headers: Vec::new(),
95 plugins: BTreeMap::new(),
96 }
97 }
98}
99
100#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
101#[serde(default, deny_unknown_fields)]
102pub struct AppConfig {
103 pub directory: PathBuf,
105 pub public: PathBuf,
107 pub base_path: String,
109 pub trailing_slash: bool,
111 pub lang: String,
113 pub html_precedence: HtmlPrecedence,
115 pub follow_symlinks: bool,
117}
118
119impl Default for AppConfig {
120 fn default() -> Self {
121 Self {
122 directory: PathBuf::from("app"),
123 public: PathBuf::from("public"),
124 base_path: String::new(),
125 trailing_slash: false,
126 lang: "en".into(),
127 html_precedence: HtmlPrecedence::Error,
128 follow_symlinks: true,
129 }
130 }
131}
132
133#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
134#[serde(rename_all = "lowercase")]
135pub enum HtmlPrecedence {
136 #[default]
138 Error,
139 Rs,
141 Html,
143}
144
145#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
146#[serde(default, deny_unknown_fields)]
147pub struct ApiConfig {
148 pub directory: Option<PathBuf>,
150 pub prefix: String,
152}
153
154impl Default for ApiConfig {
155 fn default() -> Self {
156 Self { directory: None, prefix: "/api".into() }
157 }
158}
159
160#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
161#[serde(default, deny_unknown_fields)]
162pub struct ServerConfig {
163 pub host: String,
164 pub port: u16,
165 pub body_limit: usize,
167 pub header_timeout: u64,
169 pub request_timeout: u64,
171 pub shutdown_timeout: u64,
173 pub compression: bool,
174 pub http2: bool,
175 pub trust_proxy: bool,
177}
178
179impl Default for ServerConfig {
180 fn default() -> Self {
181 Self {
182 host: "0.0.0.0".into(),
183 port: 3000,
184 body_limit: 2 * 1024 * 1024,
185 header_timeout: 10,
186 request_timeout: 60,
187 shutdown_timeout: 10,
188 compression: true,
189 http2: false,
190 trust_proxy: false,
191 }
192 }
193}
194
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
196#[serde(default, deny_unknown_fields)]
197pub struct BuildConfig {
198 pub output: PathBuf,
199 pub concurrency: usize,
201 pub optimize: Optimize,
203 pub panic: PanicStrategy,
205}
206
207impl Default for BuildConfig {
208 fn default() -> Self {
209 Self {
210 output: PathBuf::from(".next-rust"),
211 concurrency: 8,
212 optimize: Optimize::Size,
213 panic: PanicStrategy::Unwind,
214 }
215 }
216}
217
218#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
220#[serde(rename_all = "lowercase")]
221pub enum Optimize {
222 #[default]
224 Size,
225 Speed,
227}
228
229#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
231#[serde(rename_all = "lowercase")]
232pub enum PanicStrategy {
233 #[default]
235 Unwind,
236 Abort,
239}
240
241#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
242#[serde(default, deny_unknown_fields)]
243pub struct AssetsConfig {
244 pub optimize: bool,
246 pub public_max_age: u64,
248}
249
250impl Default for AssetsConfig {
251 fn default() -> Self {
252 Self { optimize: true, public_max_age: 0 }
253 }
254}
255
256#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
257#[serde(default, deny_unknown_fields)]
258pub struct RenderingConfig {
259 pub default: RenderingMode,
260 pub streaming: bool,
262 pub revalidate: Option<u64>,
264 pub client_navigation: bool,
266}
267
268impl Default for RenderingConfig {
269 fn default() -> Self {
270 Self { default: RenderingMode::Auto, streaming: true, revalidate: None, client_navigation: true }
271 }
272}
273
274#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
275#[serde(default, deny_unknown_fields)]
276pub struct ImagesConfig {
277 pub sizes: Vec<u32>,
279 pub quality: u8,
280 pub max_age: u64,
282}
283
284impl Default for ImagesConfig {
285 fn default() -> Self {
286 Self { sizes: vec![640, 750, 828, 1080, 1200, 1920, 2048, 3840], quality: 75, max_age: 60 * 60 * 24 * 30 }
287 }
288}
289
290#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
291#[serde(default, deny_unknown_fields)]
292pub struct SecurityConfig {
293 pub headers: bool,
295 pub csp: Option<String>,
297 pub csrf: CsrfMode,
299 pub hsts_max_age: u64,
301 pub allowed_origins: Vec<String>,
303}
304
305impl Default for SecurityConfig {
306 fn default() -> Self {
307 Self { headers: true, csp: None, csrf: CsrfMode::Origin, hsts_max_age: 0, allowed_origins: Vec::new() }
308 }
309}
310
311#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
312#[serde(rename_all = "lowercase")]
313pub enum CsrfMode {
314 #[default]
316 Origin,
317 Token,
319 Off,
321}
322
323#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
324#[serde(default, deny_unknown_fields)]
325pub struct EnvConfig {
326 pub public_prefix: String,
328}
329
330impl Default for EnvConfig {
331 fn default() -> Self {
332 Self { public_prefix: "NEXT_RUST_PUBLIC_".into() }
333 }
334}
335
336#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
337#[serde(default, deny_unknown_fields)]
338pub struct DevConfig {
339 pub poll_interval: u64,
341 pub overlay: bool,
343 pub watch: Vec<PathBuf>,
345 pub scaffold: bool,
348}
349
350impl Default for DevConfig {
351 fn default() -> Self {
352 Self { poll_interval: 250, overlay: true, watch: Vec::new(), scaffold: true }
353 }
354}
355
356#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
357#[serde(default, deny_unknown_fields)]
358pub struct LoggingConfig {
359 pub format: LogFormat,
360 pub level: Option<String>,
363 pub requests: Option<bool>,
365}
366
367impl Default for LoggingConfig {
368 fn default() -> Self {
369 Self { format: LogFormat::Auto, level: None, requests: None }
370 }
371}
372
373impl LoggingConfig {
374 pub fn level(&self, env: crate::Environment) -> &str {
376 match &self.level {
377 Some(level) => level,
378 None if env.is_dev() => "info",
379 None => "error",
380 }
381 }
382
383 pub fn requests(&self, env: crate::Environment) -> bool {
385 self.requests.unwrap_or(env.is_dev())
386 }
387}
388
389#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
390#[serde(rename_all = "lowercase")]
391pub enum LogFormat {
392 #[default]
394 Auto,
395 Pretty,
396 Json,
397}
398
399#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
400#[serde(deny_unknown_fields)]
401pub struct RedirectRule {
402 pub source: String,
404 pub destination: String,
406 #[serde(default)]
407 pub permanent: bool,
408}
409
410#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
411#[serde(deny_unknown_fields)]
412pub struct HeaderRule {
413 pub source: String,
414 pub headers: BTreeMap<String, String>,
415}
416
417#[derive(Debug)]
418pub enum ConfigError {
419 Io { path: PathBuf, error: std::io::Error },
420 Parse { path: PathBuf, message: String },
421 Ambiguous { dir: PathBuf },
422}
423
424impl fmt::Display for ConfigError {
425 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
426 match self {
427 ConfigError::Io { path, error } => write!(f, "could not read {}: {error}", path.display()),
428 ConfigError::Parse { path, message } => {
429 write!(f, "invalid configuration in {}:\n{message}", path.display())
430 }
431 ConfigError::Ambiguous { dir } => write!(
432 f,
433 "both {TOML_FILE} and {JSON_FILE} exist in {}; keep only one (TOML is preferred)",
434 dir.display()
435 ),
436 }
437 }
438}
439
440impl std::error::Error for ConfigError {}
441
442pub type TomlParser = fn(&str) -> Result<Config, String>;
446
447impl Config {
448 pub fn discover(start: impl AsRef<Path>) -> Result<Self, ConfigError> {
450 Self::discover_with(start, Some(Self::from_toml_str))
451 }
452
453 pub fn discover_with(start: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
457 if let Ok(explicit) = std::env::var("NEXT_RUST_CONFIG") {
458 return Self::load_with(explicit, toml);
459 }
460 let start = absolutize(start.as_ref());
461 for dir in start.ancestors() {
462 let toml_file = dir.join(TOML_FILE);
463 let json = dir.join(JSON_FILE);
464 match (toml_file.is_file(), json.is_file()) {
465 (true, true) => return Err(ConfigError::Ambiguous { dir: dir.to_path_buf() }),
466 (true, false) => return Self::load_with(toml_file, toml),
467 (false, true) => return Self::load_with(json, toml),
468 _ => {}
469 }
470 if dir.join("Cargo.toml").is_file() && dir.join("app").is_dir() {
473 break;
474 }
475 }
476 let mut config = Config { root: start, ..Config::default() };
477 config.apply_env_overrides();
478 Ok(config)
479 }
480
481 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
483 Self::load_with(path, Some(Self::from_toml_str))
484 }
485
486 pub fn load_with(path: impl AsRef<Path>, toml: Option<TomlParser>) -> Result<Self, ConfigError> {
488 let path = absolutize(path.as_ref());
489 let text = std::fs::read_to_string(&path).map_err(|error| ConfigError::Io { path: path.clone(), error })?;
490 let mut config = if path.extension().is_some_and(|e| e == "json") {
491 Self::from_json_str(&text)
492 } else {
493 match toml {
494 Some(parse) => parse(&text),
495 None => Err("this binary reads JSON configuration only (its configuration was embedded at build \
496 time); point NEXT_RUST_CONFIG at a .json file"
497 .to_owned()),
498 }
499 }
500 .map_err(|message| ConfigError::Parse { path: path.clone(), message })?;
501 config.root = path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
502 config.source = Some(path);
503 config.apply_env_overrides();
504 Ok(config)
505 }
506
507 pub fn from_toml_str(text: &str) -> Result<Self, String> {
508 toml::from_str(text).map_err(|e| e.to_string())
509 }
510
511 pub fn from_json_str(text: &str) -> Result<Self, String> {
512 serde_json::from_str(text).map_err(|e| e.to_string())
513 }
514
515 pub fn apply_env_overrides(&mut self) {
517 if let Some(port) = std::env::var("PORT").ok().and_then(|p| p.parse().ok()) {
518 self.server.port = port;
519 }
520 if let Ok(host) = std::env::var("HOST")
521 && !host.is_empty()
522 {
523 self.server.host = host;
524 }
525 }
526
527 pub fn resolve(&self, path: impl AsRef<Path>) -> PathBuf {
529 let path = path.as_ref();
530 if path.is_absolute() { normalize(path) } else { normalize(&self.root.join(path)) }
531 }
532
533 pub fn app_dir(&self) -> PathBuf {
534 self.resolve(&self.app.directory)
535 }
536
537 pub fn public_dir(&self) -> PathBuf {
538 self.resolve(&self.app.public)
539 }
540
541 pub fn api_dir(&self) -> Option<PathBuf> {
542 self.api.directory.as_ref().map(|d| self.resolve(d))
543 }
544
545 pub fn output_dir(&self) -> PathBuf {
546 self.resolve(&self.build.output)
547 }
548
549 pub fn validate(&self) -> Vec<Diagnostic> {
551 let mut out = Vec::new();
552 let app = self.app_dir();
553 if !app.exists() {
554 out.push(
555 Diagnostic::error("NR0001", "App directory not found")
556 .location(&app)
557 .message(format!(
558 "The routing directory configured as `app.directory = {:?}`\nresolves to {}, which does not exist.",
559 self.app.directory,
560 app.display()
561 ))
562 .help("create the directory or change `[app] directory` in next-rust.toml"),
563 );
564 } else if !app.is_dir() {
565 out.push(
566 Diagnostic::error("NR0002", "App directory is not a directory")
567 .location(&app)
568 .help("`[app] directory` must point to a directory"),
569 );
570 }
571 if let Some(api) = self.api_dir() {
572 if !api.is_dir() {
573 out.push(Diagnostic::error("NR0003", "API directory not found").location(api));
574 }
575 if !self.api.prefix.starts_with('/') {
576 out.push(
577 Diagnostic::error("NR0004", "API prefix must start with `/`")
578 .message(format!("found `api.prefix = {:?}`", self.api.prefix)),
579 );
580 }
581 }
582 if !self.app.base_path.is_empty() && (!self.app.base_path.starts_with('/') || self.app.base_path.ends_with('/'))
583 {
584 out.push(
585 Diagnostic::error("NR0005", "Invalid base path")
586 .message(format!("`app.base_path = {:?}`", self.app.base_path))
587 .help("use a leading slash and no trailing slash, e.g. `/docs`"),
588 );
589 }
590 for rule in &self.redirects {
591 if !rule.source.starts_with('/') {
592 out.push(
593 Diagnostic::error("NR0006", "Redirect source must start with `/`")
594 .message(format!("source = {:?}", rule.source)),
595 );
596 }
597 }
598 if let Some(level) = &self.logging.level
599 && !matches!(level.as_str(), "error" | "warn" | "info" | "debug" | "trace")
600 {
601 out.push(
602 Diagnostic::warning("NR0007", "Unknown log level")
603 .message(format!("`logging.level = {level:?}`; falling back to `info`")),
604 );
605 }
606 out
607 }
608
609 pub fn socket_addr_string(&self) -> String {
610 if self.server.host.contains(':') {
611 format!("[{}]:{}", self.server.host, self.server.port)
612 } else {
613 format!("{}:{}", self.server.host, self.server.port)
614 }
615 }
616}
617
618fn absolutize(p: &Path) -> PathBuf {
619 if p.is_absolute() {
620 normalize(p)
621 } else {
622 normalize(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")).join(p))
623 }
624}
625
626pub fn normalize(path: &Path) -> PathBuf {
629 let mut out = PathBuf::new();
630 for comp in path.components() {
631 match comp {
632 Component::CurDir => {}
633 Component::ParentDir => {
634 if !out.pop() {
635 out.push("..");
636 }
637 }
638 other => out.push(other.as_os_str()),
639 }
640 }
641 if out.as_os_str().is_empty() { PathBuf::from(".") } else { out }
642}
643
644#[cfg(test)]
645mod tests {
646 use super::*;
647
648 #[test]
649 fn defaults_are_zero_config() {
650 let c = Config::from_toml_str("").unwrap();
651 assert_eq!(c.app.directory, PathBuf::from("app"));
652 assert_eq!(c.server.port, 3000);
653 assert_eq!(c.build.output, PathBuf::from(".next-rust"));
654 assert_eq!(c.rendering.default, RenderingMode::Auto);
655 }
656
657 #[test]
658 fn parses_sections() {
659 let c = Config::from_toml_str(
660 r#"
661 [app]
662 directory = "src/web"
663 [server]
664 port = 8080
665 [rendering]
666 default = "server"
667 [[redirects]]
668 source = "/old"
669 destination = "/new"
670 permanent = true
671 [plugins.analytics]
672 id = "x"
673 "#,
674 )
675 .unwrap();
676 assert_eq!(c.app.directory, PathBuf::from("src/web"));
677 assert_eq!(c.server.port, 8080);
678 assert_eq!(c.rendering.default, RenderingMode::Dynamic);
679 assert!(c.redirects[0].permanent);
680 assert_eq!(c.plugins["analytics"]["id"], "x");
681 }
682
683 #[test]
684 fn rejects_unknown_keys() {
685 let err = Config::from_toml_str("[app]\ndirectroy = \"x\"").unwrap_err();
686 assert!(err.contains("directroy"), "{err}");
687 }
688
689 #[test]
690 fn json_is_supported() {
691 let c = Config::from_json_str(r#"{"app":{"directory":"frontend"}}"#).unwrap();
692 assert_eq!(c.app.directory, PathBuf::from("frontend"));
693 }
694
695 #[test]
696 fn resolves_relative_to_root() {
697 let c = Config {
698 root: PathBuf::from("/work/repo/apps/site"),
699 app: AppConfig { directory: PathBuf::from("../shared/my-pages"), ..Default::default() },
700 ..Default::default()
701 };
702 assert_eq!(c.app_dir(), PathBuf::from("/work/repo/apps/shared/my-pages"));
703 let c = Config {
704 root: PathBuf::from("/work"),
705 app: AppConfig { directory: PathBuf::from("/abs/pages/./x/.."), ..Default::default() },
706 ..Default::default()
707 };
708 assert_eq!(c.app_dir(), PathBuf::from("/abs/pages"));
709 }
710
711 #[test]
712 fn discovery_walks_up() {
713 let base = std::env::temp_dir().join(format!("nr-config-{}", std::process::id()));
714 let nested = base.join("a/b");
715 std::fs::create_dir_all(&nested).unwrap();
716 std::fs::write(base.join(TOML_FILE), "[app]\ndirectory = \"website/routes\"\n").unwrap();
717 let c = Config::discover(&nested).unwrap();
718 assert_eq!(c.root, base);
719 assert_eq!(c.app_dir(), base.join("website/routes"));
720 let diags = c.validate();
721 assert_eq!(diags[0].code, "NR0001");
722 std::fs::write(base.join(JSON_FILE), "{}").unwrap();
723 assert!(matches!(Config::discover(&nested), Err(ConfigError::Ambiguous { .. })));
724 std::fs::remove_dir_all(&base).unwrap();
725 }
726}