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: true,
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}
202
203impl Default for BuildConfig {
204 fn default() -> Self {
205 Self { output: PathBuf::from(".next-rust"), concurrency: 8 }
206 }
207}
208
209#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
210#[serde(default, deny_unknown_fields)]
211pub struct AssetsConfig {
212 pub optimize: bool,
214 pub public_max_age: u64,
216}
217
218impl Default for AssetsConfig {
219 fn default() -> Self {
220 Self { optimize: true, public_max_age: 0 }
221 }
222}
223
224#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
225#[serde(default, deny_unknown_fields)]
226pub struct RenderingConfig {
227 pub default: RenderingMode,
228 pub streaming: bool,
230 pub revalidate: Option<u64>,
232 pub client_navigation: bool,
234}
235
236impl Default for RenderingConfig {
237 fn default() -> Self {
238 Self { default: RenderingMode::Auto, streaming: true, revalidate: None, client_navigation: true }
239 }
240}
241
242#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
243#[serde(default, deny_unknown_fields)]
244pub struct ImagesConfig {
245 pub sizes: Vec<u32>,
247 pub quality: u8,
248 pub max_age: u64,
250}
251
252impl Default for ImagesConfig {
253 fn default() -> Self {
254 Self { sizes: vec![640, 750, 828, 1080, 1200, 1920, 2048, 3840], quality: 75, max_age: 60 * 60 * 24 * 30 }
255 }
256}
257
258#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
259#[serde(default, deny_unknown_fields)]
260pub struct SecurityConfig {
261 pub headers: bool,
263 pub csp: Option<String>,
265 pub csrf: CsrfMode,
267 pub hsts_max_age: u64,
269 pub allowed_origins: Vec<String>,
271}
272
273impl Default for SecurityConfig {
274 fn default() -> Self {
275 Self { headers: true, csp: None, csrf: CsrfMode::Origin, hsts_max_age: 0, allowed_origins: Vec::new() }
276 }
277}
278
279#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
280#[serde(rename_all = "lowercase")]
281pub enum CsrfMode {
282 #[default]
284 Origin,
285 Token,
287 Off,
289}
290
291#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
292#[serde(default, deny_unknown_fields)]
293pub struct EnvConfig {
294 pub public_prefix: String,
296}
297
298impl Default for EnvConfig {
299 fn default() -> Self {
300 Self { public_prefix: "NEXT_RUST_PUBLIC_".into() }
301 }
302}
303
304#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
305#[serde(default, deny_unknown_fields)]
306pub struct DevConfig {
307 pub poll_interval: u64,
309 pub overlay: bool,
311 pub watch: Vec<PathBuf>,
313 pub scaffold: bool,
316}
317
318impl Default for DevConfig {
319 fn default() -> Self {
320 Self { poll_interval: 250, overlay: true, watch: Vec::new(), scaffold: true }
321 }
322}
323
324#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
325#[serde(default, deny_unknown_fields)]
326pub struct LoggingConfig {
327 pub format: LogFormat,
328 pub level: Option<String>,
331 pub requests: Option<bool>,
333}
334
335impl Default for LoggingConfig {
336 fn default() -> Self {
337 Self { format: LogFormat::Auto, level: None, requests: None }
338 }
339}
340
341impl LoggingConfig {
342 pub fn level(&self, env: crate::Environment) -> &str {
344 match &self.level {
345 Some(level) => level,
346 None if env.is_dev() => "info",
347 None => "error",
348 }
349 }
350
351 pub fn requests(&self, env: crate::Environment) -> bool {
353 self.requests.unwrap_or(env.is_dev())
354 }
355}
356
357#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
358#[serde(rename_all = "lowercase")]
359pub enum LogFormat {
360 #[default]
362 Auto,
363 Pretty,
364 Json,
365}
366
367#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
368#[serde(deny_unknown_fields)]
369pub struct RedirectRule {
370 pub source: String,
372 pub destination: String,
374 #[serde(default)]
375 pub permanent: bool,
376}
377
378#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
379#[serde(deny_unknown_fields)]
380pub struct HeaderRule {
381 pub source: String,
382 pub headers: BTreeMap<String, String>,
383}
384
385#[derive(Debug)]
386pub enum ConfigError {
387 Io { path: PathBuf, error: std::io::Error },
388 Parse { path: PathBuf, message: String },
389 Ambiguous { dir: PathBuf },
390}
391
392impl fmt::Display for ConfigError {
393 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
394 match self {
395 ConfigError::Io { path, error } => write!(f, "could not read {}: {error}", path.display()),
396 ConfigError::Parse { path, message } => {
397 write!(f, "invalid configuration in {}:\n{message}", path.display())
398 }
399 ConfigError::Ambiguous { dir } => write!(
400 f,
401 "both {TOML_FILE} and {JSON_FILE} exist in {}; keep only one (TOML is preferred)",
402 dir.display()
403 ),
404 }
405 }
406}
407
408impl std::error::Error for ConfigError {}
409
410impl Config {
411 pub fn discover(start: impl AsRef<Path>) -> Result<Self, ConfigError> {
413 if let Ok(explicit) = std::env::var("NEXT_RUST_CONFIG") {
414 return Self::load(explicit);
415 }
416 let start = absolutize(start.as_ref());
417 for dir in start.ancestors() {
418 let toml = dir.join(TOML_FILE);
419 let json = dir.join(JSON_FILE);
420 match (toml.is_file(), json.is_file()) {
421 (true, true) => return Err(ConfigError::Ambiguous { dir: dir.to_path_buf() }),
422 (true, false) => return Self::load(toml),
423 (false, true) => return Self::load(json),
424 _ => {}
425 }
426 if dir.join("Cargo.toml").is_file() && dir.join("app").is_dir() {
429 break;
430 }
431 }
432 let mut config = Config { root: start, ..Config::default() };
433 config.apply_env_overrides();
434 Ok(config)
435 }
436
437 pub fn load(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
439 let path = absolutize(path.as_ref());
440 let text = std::fs::read_to_string(&path).map_err(|error| ConfigError::Io { path: path.clone(), error })?;
441 let mut config = if path.extension().is_some_and(|e| e == "json") {
442 Self::from_json_str(&text)
443 } else {
444 Self::from_toml_str(&text)
445 }
446 .map_err(|message| ConfigError::Parse { path: path.clone(), message })?;
447 config.root = path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
448 config.source = Some(path);
449 config.apply_env_overrides();
450 Ok(config)
451 }
452
453 pub fn from_toml_str(text: &str) -> Result<Self, String> {
454 toml::from_str(text).map_err(|e| e.to_string())
455 }
456
457 pub fn from_json_str(text: &str) -> Result<Self, String> {
458 serde_json::from_str(text).map_err(|e| e.to_string())
459 }
460
461 pub fn apply_env_overrides(&mut self) {
463 if let Some(port) = std::env::var("PORT").ok().and_then(|p| p.parse().ok()) {
464 self.server.port = port;
465 }
466 if let Ok(host) = std::env::var("HOST")
467 && !host.is_empty()
468 {
469 self.server.host = host;
470 }
471 }
472
473 pub fn resolve(&self, path: impl AsRef<Path>) -> PathBuf {
475 let path = path.as_ref();
476 if path.is_absolute() { normalize(path) } else { normalize(&self.root.join(path)) }
477 }
478
479 pub fn app_dir(&self) -> PathBuf {
480 self.resolve(&self.app.directory)
481 }
482
483 pub fn public_dir(&self) -> PathBuf {
484 self.resolve(&self.app.public)
485 }
486
487 pub fn api_dir(&self) -> Option<PathBuf> {
488 self.api.directory.as_ref().map(|d| self.resolve(d))
489 }
490
491 pub fn output_dir(&self) -> PathBuf {
492 self.resolve(&self.build.output)
493 }
494
495 pub fn validate(&self) -> Vec<Diagnostic> {
497 let mut out = Vec::new();
498 let app = self.app_dir();
499 if !app.exists() {
500 out.push(
501 Diagnostic::error("NR0001", "App directory not found")
502 .location(&app)
503 .message(format!(
504 "The routing directory configured as `app.directory = {:?}`\nresolves to {}, which does not exist.",
505 self.app.directory,
506 app.display()
507 ))
508 .help("create the directory or change `[app] directory` in next-rust.toml"),
509 );
510 } else if !app.is_dir() {
511 out.push(
512 Diagnostic::error("NR0002", "App directory is not a directory")
513 .location(&app)
514 .help("`[app] directory` must point to a directory"),
515 );
516 }
517 if let Some(api) = self.api_dir() {
518 if !api.is_dir() {
519 out.push(Diagnostic::error("NR0003", "API directory not found").location(api));
520 }
521 if !self.api.prefix.starts_with('/') {
522 out.push(
523 Diagnostic::error("NR0004", "API prefix must start with `/`")
524 .message(format!("found `api.prefix = {:?}`", self.api.prefix)),
525 );
526 }
527 }
528 if !self.app.base_path.is_empty() && (!self.app.base_path.starts_with('/') || self.app.base_path.ends_with('/'))
529 {
530 out.push(
531 Diagnostic::error("NR0005", "Invalid base path")
532 .message(format!("`app.base_path = {:?}`", self.app.base_path))
533 .help("use a leading slash and no trailing slash, e.g. `/docs`"),
534 );
535 }
536 for rule in &self.redirects {
537 if !rule.source.starts_with('/') {
538 out.push(
539 Diagnostic::error("NR0006", "Redirect source must start with `/`")
540 .message(format!("source = {:?}", rule.source)),
541 );
542 }
543 }
544 if let Some(level) = &self.logging.level
545 && !matches!(level.as_str(), "error" | "warn" | "info" | "debug" | "trace")
546 {
547 out.push(
548 Diagnostic::warning("NR0007", "Unknown log level")
549 .message(format!("`logging.level = {level:?}`; falling back to `info`")),
550 );
551 }
552 out
553 }
554
555 pub fn socket_addr_string(&self) -> String {
556 if self.server.host.contains(':') {
557 format!("[{}]:{}", self.server.host, self.server.port)
558 } else {
559 format!("{}:{}", self.server.host, self.server.port)
560 }
561 }
562}
563
564fn absolutize(p: &Path) -> PathBuf {
565 if p.is_absolute() {
566 normalize(p)
567 } else {
568 normalize(&std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")).join(p))
569 }
570}
571
572pub fn normalize(path: &Path) -> PathBuf {
575 let mut out = PathBuf::new();
576 for comp in path.components() {
577 match comp {
578 Component::CurDir => {}
579 Component::ParentDir => {
580 if !out.pop() {
581 out.push("..");
582 }
583 }
584 other => out.push(other.as_os_str()),
585 }
586 }
587 if out.as_os_str().is_empty() { PathBuf::from(".") } else { out }
588}
589
590#[cfg(test)]
591mod tests {
592 use super::*;
593
594 #[test]
595 fn defaults_are_zero_config() {
596 let c = Config::from_toml_str("").unwrap();
597 assert_eq!(c.app.directory, PathBuf::from("app"));
598 assert_eq!(c.server.port, 3000);
599 assert_eq!(c.build.output, PathBuf::from(".next-rust"));
600 assert_eq!(c.rendering.default, RenderingMode::Auto);
601 }
602
603 #[test]
604 fn parses_sections() {
605 let c = Config::from_toml_str(
606 r#"
607 [app]
608 directory = "src/web"
609 [server]
610 port = 8080
611 [rendering]
612 default = "server"
613 [[redirects]]
614 source = "/old"
615 destination = "/new"
616 permanent = true
617 [plugins.analytics]
618 id = "x"
619 "#,
620 )
621 .unwrap();
622 assert_eq!(c.app.directory, PathBuf::from("src/web"));
623 assert_eq!(c.server.port, 8080);
624 assert_eq!(c.rendering.default, RenderingMode::Dynamic);
625 assert!(c.redirects[0].permanent);
626 assert_eq!(c.plugins["analytics"]["id"], "x");
627 }
628
629 #[test]
630 fn rejects_unknown_keys() {
631 let err = Config::from_toml_str("[app]\ndirectroy = \"x\"").unwrap_err();
632 assert!(err.contains("directroy"), "{err}");
633 }
634
635 #[test]
636 fn json_is_supported() {
637 let c = Config::from_json_str(r#"{"app":{"directory":"frontend"}}"#).unwrap();
638 assert_eq!(c.app.directory, PathBuf::from("frontend"));
639 }
640
641 #[test]
642 fn resolves_relative_to_root() {
643 let c = Config {
644 root: PathBuf::from("/work/repo/apps/site"),
645 app: AppConfig { directory: PathBuf::from("../shared/my-pages"), ..Default::default() },
646 ..Default::default()
647 };
648 assert_eq!(c.app_dir(), PathBuf::from("/work/repo/apps/shared/my-pages"));
649 let c = Config {
650 root: PathBuf::from("/work"),
651 app: AppConfig { directory: PathBuf::from("/abs/pages/./x/.."), ..Default::default() },
652 ..Default::default()
653 };
654 assert_eq!(c.app_dir(), PathBuf::from("/abs/pages"));
655 }
656
657 #[test]
658 fn discovery_walks_up() {
659 let base = std::env::temp_dir().join(format!("nr-config-{}", std::process::id()));
660 let nested = base.join("a/b");
661 std::fs::create_dir_all(&nested).unwrap();
662 std::fs::write(base.join(TOML_FILE), "[app]\ndirectory = \"website/routes\"\n").unwrap();
663 let c = Config::discover(&nested).unwrap();
664 assert_eq!(c.root, base);
665 assert_eq!(c.app_dir(), base.join("website/routes"));
666 let diags = c.validate();
667 assert_eq!(diags[0].code, "NR0001");
668 std::fs::write(base.join(JSON_FILE), "{}").unwrap();
669 assert!(matches!(Config::discover(&nested), Err(ConfigError::Ambiguous { .. })));
670 std::fs::remove_dir_all(&base).unwrap();
671 }
672}