use anyhow::{Context, Result, bail};
use camino::Utf8PathBuf;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fs;
use std::process::Command;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct OdkConfig {
#[serde(skip_serializing_if = "Option::is_none")]
pub schema: Option<Utf8PathBuf>,
#[serde(default = "default_output")]
pub output: Utf8PathBuf,
#[serde(default)]
pub emit: Vec<String>,
#[serde(default)]
pub options: HashMap<String, serde_json::Value>,
#[serde(skip_serializing_if = "Option::is_none")]
pub namespace: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub generate: Option<GenerateConfig>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct GenerateConfig {
#[serde(default)]
pub targets: Vec<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub output: Option<Utf8PathBuf>,
#[serde(skip_serializing_if = "Option::is_none")]
pub operations: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mcp: Option<McpGenerateConfig>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct McpGenerateConfig {
pub name: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub tools: Vec<McpToolConfig>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct McpToolConfig {
pub operation: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
}
fn default_output() -> Utf8PathBuf {
Utf8PathBuf::from("./generated")
}
const CONFIG_FILES: &[&str] = &[
"odk.config.ts",
"odk.config.yaml",
"odk.config.yml",
"odk.config.json",
"odk.config.jsonc",
];
pub fn find_config_file() -> Option<Utf8PathBuf> {
for name in CONFIG_FILES {
let path = Utf8PathBuf::from(*name);
if path.exists() {
return Some(path);
}
}
None
}
pub fn load_config(path: &Utf8PathBuf) -> Result<OdkConfig> {
let ext = path.extension().unwrap_or("");
match ext {
"ts" => load_ts_config(path),
"yaml" | "yml" => load_yaml_config(path),
"json" => load_json_config(path),
"jsonc" => load_jsonc_config(path),
_ => bail!("Unsupported config file format: .{}", ext),
}
}
fn load_ts_config(path: &Utf8PathBuf) -> Result<OdkConfig> {
if which::which("bun").is_err() {
bail!(
"bun not found. TypeScript config requires bun.\n\
Install with: curl -fsSL https://bun.sh/install | bash"
);
}
let script = format!(
r#"
import config from './{path}';
const resolved = typeof config === 'function' ? config() : config;
const final = resolved.default ?? resolved;
console.log(JSON.stringify(final));
"#,
path = path
);
let output = Command::new("bun")
.args(["-e", &script])
.output()
.context("Failed to execute TypeScript config")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
bail!("Failed to load TypeScript config:\n{}", stderr);
}
let json = String::from_utf8_lossy(&output.stdout);
serde_json::from_str(&json).with_context(|| format!("Failed to parse config from {}", path))
}
fn load_yaml_config(path: &Utf8PathBuf) -> Result<OdkConfig> {
let content = fs::read_to_string(path).with_context(|| format!("Failed to read {}", path))?;
serde_norway::from_str(&content)
.with_context(|| format!("Failed to parse YAML config from {}", path))
}
fn load_json_config(path: &Utf8PathBuf) -> Result<OdkConfig> {
let content = fs::read_to_string(path).with_context(|| format!("Failed to read {}", path))?;
serde_json::from_str(&content)
.with_context(|| format!("Failed to parse JSON config from {}", path))
}
fn load_jsonc_config(path: &Utf8PathBuf) -> Result<OdkConfig> {
let content = fs::read_to_string(path).with_context(|| format!("Failed to read {}", path))?;
let stripped = strip_json_comments(&content);
serde_json::from_str(&stripped)
.with_context(|| format!("Failed to parse JSONC config from {}", path))
}
fn strip_json_comments(input: &str) -> String {
let mut result = String::with_capacity(input.len());
let mut chars = input.chars().peekable();
let mut in_string = false;
let mut escape_next = false;
while let Some(c) = chars.next() {
if escape_next {
result.push(c);
escape_next = false;
continue;
}
if c == '\\' && in_string {
result.push(c);
escape_next = true;
continue;
}
if c == '"' {
in_string = !in_string;
result.push(c);
continue;
}
if in_string {
result.push(c);
continue;
}
if c == '/' {
match chars.peek() {
Some('/') => {
chars.next();
while let Some(&next) = chars.peek() {
if next == '\n' {
break;
}
chars.next();
}
}
Some('*') => {
chars.next();
while let Some(next) = chars.next() {
if next == '*' && chars.peek() == Some(&'/') {
chars.next();
break;
}
}
}
_ => result.push(c),
}
} else {
result.push(c);
}
}
result
}
pub fn merge_with_cli(
config: OdkConfig,
cli_input: Option<&Utf8PathBuf>,
cli_out: Option<&Utf8PathBuf>,
cli_emit: &Option<Vec<String>>,
cli_namespace: &Option<String>,
) -> OdkConfig {
OdkConfig {
schema: cli_input.cloned().or(config.schema),
output: cli_out.cloned().unwrap_or(config.output),
emit: if let Some(e) = cli_emit {
if e.is_empty() { config.emit } else { e.clone() }
} else {
config.emit
},
options: config.options,
namespace: cli_namespace.clone().or(config.namespace),
generate: config.generate,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_strip_json_comments() {
let input = r#"{
// This is a comment
"key": "value", // inline comment
/* block
comment */
"other": "data"
}"#;
let stripped = strip_json_comments(input);
let parsed: serde_json::Value = serde_json::from_str(&stripped).unwrap();
assert_eq!(parsed["key"], "value");
assert_eq!(parsed["other"], "data");
}
#[test]
fn test_strip_json_comments_in_string() {
let input = r#"{"url": "https://example.com/path"}"#;
let stripped = strip_json_comments(input);
let parsed: serde_json::Value = serde_json::from_str(&stripped).unwrap();
assert_eq!(parsed["url"], "https://example.com/path");
}
#[test]
fn test_mcp_config_deserialization() {
let json = r#"{
"schema": "schema.graphql",
"generate": {
"targets": ["mcp"],
"mcp": {
"name": "backfeed-mcp",
"description": "Backfeed feedback tools",
"tools": [
{
"operation": "createPost",
"name": "submit_feedback",
"description": "Submit feedback to a board"
},
{
"operation": "posts"
}
]
}
}
}"#;
let config: OdkConfig = serde_json::from_str(json).unwrap();
let generate = config.generate.unwrap();
let mcp = generate.mcp.unwrap();
assert_eq!(mcp.name, "backfeed-mcp");
assert_eq!(mcp.tools.len(), 2);
assert_eq!(mcp.tools[0].operation, "createPost");
assert_eq!(mcp.tools[0].name.as_deref(), Some("submit_feedback"));
assert_eq!(mcp.tools[1].name, None);
}
}