Skip to main content

odk_cli/
config.rs

1//! ODK configuration file support
2//!
3//! Supports loading configuration from:
4//! - odk.config.ts (TypeScript, executed via bun)
5//! - odk.config.yaml / odk.config.yml
6//! - odk.config.json / odk.config.jsonc
7
8use anyhow::{Context, Result, bail};
9use camino::Utf8PathBuf;
10use serde::{Deserialize, Serialize};
11use std::collections::HashMap;
12use std::fs;
13use std::process::Command;
14
15/// ODK project configuration
16#[derive(Debug, Clone, Default, Serialize, Deserialize)]
17pub struct OdkConfig {
18    /// Input schema file
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub schema: Option<Utf8PathBuf>,
21
22    /// Output directory for generated files
23    #[serde(default = "default_output")]
24    pub output: Utf8PathBuf,
25
26    /// TypeSpec emitters to use
27    #[serde(default)]
28    pub emit: Vec<String>,
29
30    /// Emitter-specific options
31    #[serde(default)]
32    pub options: HashMap<String, serde_json::Value>,
33
34    /// Namespace for generated TypeSpec
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub namespace: Option<String>,
37
38    /// Generate configuration (for `odk generate`)
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub generate: Option<GenerateConfig>,
41}
42
43/// Configuration for the `generate` command.
44#[derive(Debug, Clone, Default, Serialize, Deserialize)]
45pub struct GenerateConfig {
46    /// Generation targets (e.g. ["sdk", "react-query", "msw"])
47    #[serde(default)]
48    pub targets: Vec<String>,
49
50    /// Output directory for generated files
51    #[serde(skip_serializing_if = "Option::is_none")]
52    pub output: Option<Utf8PathBuf>,
53
54    /// GraphQL operation documents glob pattern
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub operations: Option<String>,
57
58    /// MCP target-specific configuration
59    #[serde(skip_serializing_if = "Option::is_none")]
60    pub mcp: Option<McpGenerateConfig>,
61}
62
63/// MCP target configuration.
64#[derive(Debug, Clone, Default, Serialize, Deserialize)]
65pub struct McpGenerateConfig {
66    /// MCP server name (used in package.json and server metadata)
67    pub name: String,
68
69    /// Human-readable description of the MCP server
70    #[serde(default)]
71    pub description: String,
72
73    /// Tools to expose (curated subset of GraphQL operations)
74    #[serde(default)]
75    pub tools: Vec<McpToolConfig>,
76}
77
78/// Configuration for a single MCP tool.
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct McpToolConfig {
81    /// GraphQL operation name to wrap (must match an operation in the schema)
82    pub operation: String,
83
84    /// Tool name override (defaults to snake_case of operation name)
85    #[serde(skip_serializing_if = "Option::is_none")]
86    pub name: Option<String>,
87
88    /// Tool description override (defaults to operation description from schema)
89    #[serde(skip_serializing_if = "Option::is_none")]
90    pub description: Option<String>,
91}
92
93fn default_output() -> Utf8PathBuf {
94    Utf8PathBuf::from("./generated")
95}
96
97/// Config file names to search for, in priority order
98const CONFIG_FILES: &[&str] = &[
99    "odk.config.ts",
100    "odk.config.yaml",
101    "odk.config.yml",
102    "odk.config.json",
103    "odk.config.jsonc",
104];
105
106/// Find a config file in the current directory
107pub fn find_config_file() -> Option<Utf8PathBuf> {
108    for name in CONFIG_FILES {
109        let path = Utf8PathBuf::from(*name);
110        if path.exists() {
111            return Some(path);
112        }
113    }
114    None
115}
116
117/// Load configuration from a file
118pub fn load_config(path: &Utf8PathBuf) -> Result<OdkConfig> {
119    let ext = path.extension().unwrap_or("");
120
121    match ext {
122        "ts" => load_ts_config(path),
123        "yaml" | "yml" => load_yaml_config(path),
124        "json" => load_json_config(path),
125        "jsonc" => load_jsonc_config(path),
126        _ => bail!("Unsupported config file format: .{}", ext),
127    }
128}
129
130/// Load TypeScript config by executing via bun
131fn load_ts_config(path: &Utf8PathBuf) -> Result<OdkConfig> {
132    // Check bun is available
133    if which::which("bun").is_err() {
134        bail!(
135            "bun not found. TypeScript config requires bun.\n\
136             Install with: curl -fsSL https://bun.sh/install | bash"
137        );
138    }
139
140    // Execute the config file and capture JSON output
141    let script = format!(
142        r#"
143        import config from './{path}';
144        const resolved = typeof config === 'function' ? config() : config;
145        const final = resolved.default ?? resolved;
146        console.log(JSON.stringify(final));
147        "#,
148        path = path
149    );
150
151    let output = Command::new("bun")
152        .args(["-e", &script])
153        .output()
154        .context("Failed to execute TypeScript config")?;
155
156    if !output.status.success() {
157        let stderr = String::from_utf8_lossy(&output.stderr);
158        bail!("Failed to load TypeScript config:\n{}", stderr);
159    }
160
161    let json = String::from_utf8_lossy(&output.stdout);
162    serde_json::from_str(&json).with_context(|| format!("Failed to parse config from {}", path))
163}
164
165/// Load YAML config
166fn load_yaml_config(path: &Utf8PathBuf) -> Result<OdkConfig> {
167    let content = fs::read_to_string(path).with_context(|| format!("Failed to read {}", path))?;
168
169    serde_yaml::from_str(&content)
170        .with_context(|| format!("Failed to parse YAML config from {}", path))
171}
172
173/// Load JSON config
174fn load_json_config(path: &Utf8PathBuf) -> Result<OdkConfig> {
175    let content = fs::read_to_string(path).with_context(|| format!("Failed to read {}", path))?;
176
177    serde_json::from_str(&content)
178        .with_context(|| format!("Failed to parse JSON config from {}", path))
179}
180
181/// Load JSONC config (JSON with comments)
182fn load_jsonc_config(path: &Utf8PathBuf) -> Result<OdkConfig> {
183    let content = fs::read_to_string(path).with_context(|| format!("Failed to read {}", path))?;
184
185    // Strip comments (simple approach: remove // and /* */ comments)
186    let stripped = strip_json_comments(&content);
187
188    serde_json::from_str(&stripped)
189        .with_context(|| format!("Failed to parse JSONC config from {}", path))
190}
191
192/// Strip JavaScript-style comments from JSON
193fn strip_json_comments(input: &str) -> String {
194    let mut result = String::with_capacity(input.len());
195    let mut chars = input.chars().peekable();
196    let mut in_string = false;
197    let mut escape_next = false;
198
199    while let Some(c) = chars.next() {
200        if escape_next {
201            result.push(c);
202            escape_next = false;
203            continue;
204        }
205
206        if c == '\\' && in_string {
207            result.push(c);
208            escape_next = true;
209            continue;
210        }
211
212        if c == '"' {
213            in_string = !in_string;
214            result.push(c);
215            continue;
216        }
217
218        if in_string {
219            result.push(c);
220            continue;
221        }
222
223        if c == '/' {
224            match chars.peek() {
225                Some('/') => {
226                    // Line comment - skip until newline
227                    chars.next();
228                    while let Some(&next) = chars.peek() {
229                        if next == '\n' {
230                            break;
231                        }
232                        chars.next();
233                    }
234                }
235                Some('*') => {
236                    // Block comment - skip until */
237                    chars.next();
238                    while let Some(next) = chars.next() {
239                        if next == '*' && chars.peek() == Some(&'/') {
240                            chars.next();
241                            break;
242                        }
243                    }
244                }
245                _ => result.push(c),
246            }
247        } else {
248            result.push(c);
249        }
250    }
251
252    result
253}
254
255/// Merge CLI arguments with config file settings (CLI takes precedence)
256pub fn merge_with_cli(
257    config: OdkConfig,
258    cli_input: Option<&Utf8PathBuf>,
259    cli_out: Option<&Utf8PathBuf>,
260    cli_emit: &Option<Vec<String>>,
261    cli_namespace: &Option<String>,
262) -> OdkConfig {
263    OdkConfig {
264        schema: cli_input.cloned().or(config.schema),
265        output: cli_out.cloned().unwrap_or(config.output),
266        emit: if let Some(e) = cli_emit {
267            if e.is_empty() { config.emit } else { e.clone() }
268        } else {
269            config.emit
270        },
271        options: config.options,
272        namespace: cli_namespace.clone().or(config.namespace),
273        generate: config.generate,
274    }
275}
276
277#[cfg(test)]
278mod tests {
279    use super::*;
280
281    #[test]
282    fn test_strip_json_comments() {
283        let input = r#"{
284  // This is a comment
285  "key": "value", // inline comment
286  /* block
287     comment */
288  "other": "data"
289}"#;
290
291        let stripped = strip_json_comments(input);
292        let parsed: serde_json::Value = serde_json::from_str(&stripped).unwrap();
293        assert_eq!(parsed["key"], "value");
294        assert_eq!(parsed["other"], "data");
295    }
296
297    #[test]
298    fn test_strip_json_comments_in_string() {
299        let input = r#"{"url": "https://example.com/path"}"#;
300        let stripped = strip_json_comments(input);
301        let parsed: serde_json::Value = serde_json::from_str(&stripped).unwrap();
302        assert_eq!(parsed["url"], "https://example.com/path");
303    }
304
305    #[test]
306    fn test_mcp_config_deserialization() {
307        let json = r#"{
308            "schema": "schema.graphql",
309            "generate": {
310                "targets": ["mcp"],
311                "mcp": {
312                    "name": "backfeed-mcp",
313                    "description": "Backfeed feedback tools",
314                    "tools": [
315                        {
316                            "operation": "createPost",
317                            "name": "submit_feedback",
318                            "description": "Submit feedback to a board"
319                        },
320                        {
321                            "operation": "posts"
322                        }
323                    ]
324                }
325            }
326        }"#;
327
328        let config: OdkConfig = serde_json::from_str(json).unwrap();
329        let generate = config.generate.unwrap();
330        let mcp = generate.mcp.unwrap();
331        assert_eq!(mcp.name, "backfeed-mcp");
332        assert_eq!(mcp.tools.len(), 2);
333        assert_eq!(mcp.tools[0].operation, "createPost");
334        assert_eq!(mcp.tools[0].name.as_deref(), Some("submit_feedback"));
335        assert_eq!(mcp.tools[1].name, None);
336    }
337}