use anyhow::{Context, Result, bail};
use camino::Utf8PathBuf;
use clap::{Parser, Subcommand};
use odk_schema::CompiledSchema;
use std::fs;
use std::path::PathBuf;
use std::process::Command;
mod builder;
use odk_cli::config;
mod error_mapper;
mod extism_host;
mod source_map;
mod templates;
mod ts_executor;
mod typespec_bridge;
use odk_cli::loaders;
#[derive(Parser, Debug)]
#[command(name = "odk", version, about = "ODK - Omni Development Kit CLI")]
struct Cli {
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand, Debug)]
enum Commands {
Compile {
input: Option<Utf8PathBuf>,
#[arg(short, long)]
config: Option<Utf8PathBuf>,
#[arg(short, long)]
out: Option<Utf8PathBuf>,
#[arg(short, long, value_delimiter = ',')]
emit: Option<Vec<String>>,
#[arg(short, long)]
namespace: Option<String>,
#[arg(long)]
keep_temp: bool,
#[arg(long)]
operations: Option<String>,
#[arg(long)]
introspect: Option<String>,
},
Init {
#[arg(short, long)]
lang: Option<String>,
#[arg(short, long)]
name: Option<String>,
},
Build {
#[arg(default_value = ".")]
input: Utf8PathBuf,
#[arg(short, long)]
out: Option<Utf8PathBuf>,
#[arg(long, default_value = "true")]
release: bool,
},
Check {
input: Utf8PathBuf,
#[arg(long)]
operations: Option<String>,
},
Generate {
input: Option<Utf8PathBuf>,
#[arg(short, long)]
config: Option<Utf8PathBuf>,
#[arg(short, long, default_value = "./generated")]
out: Utf8PathBuf,
#[arg(short, long, default_value = "sdk,react-query,msw")]
targets: String,
#[arg(long)]
operations: Option<String>,
#[arg(long)]
introspect: Option<String>,
#[arg(long)]
out_file: Option<String>,
},
Typespec {
input: Utf8PathBuf,
#[arg(short, long)]
out: Option<Utf8PathBuf>,
#[arg(short, long)]
namespace: Option<String>,
},
Publish {
input: Utf8PathBuf,
#[arg(short, long)]
registry: String,
#[arg(long)]
repository: String,
#[arg(short, long, default_value = "latest")]
tag: String,
#[arg(long)]
token: Option<String>,
},
}
fn main() -> Result<()> {
let cli = Cli::parse();
match cli.command {
Commands::Compile {
input,
config,
out,
emit,
namespace,
keep_temp,
operations,
introspect,
} => cmd_compile(
input, config, out, emit, namespace, keep_temp, operations, introspect,
),
Commands::Init { lang, name } => cmd_init(lang, name),
Commands::Build {
input,
out,
release,
} => builder::cmd_build(input, out, release),
Commands::Check { input, operations } => cmd_check(input, operations),
Commands::Generate {
input,
config,
out,
targets,
operations,
introspect,
out_file,
} => cmd_generate(
input, config, out, targets, operations, introspect, out_file,
),
Commands::Typespec {
input,
out,
namespace,
} => cmd_typespec(input, out, namespace),
Commands::Publish {
input,
registry,
repository,
tag,
token,
} => cmd_publish(input, registry, repository, tag, token),
}
}
fn load_schema(input: &Utf8PathBuf) -> Result<CompiledSchema> {
let ext = input.extension().unwrap_or("");
match ext {
"ts" => {
eprintln!(" Compiling TypeScript schema via bun...");
ts_executor::compile_ts_schema(input)
}
"wasm" => {
extism_host::load_schema_from_plugin(input)
}
"json" => {
let path = std::path::Path::new(input.as_str());
let content =
fs::read_to_string(input).with_context(|| format!("Failed to read {}", input))?;
if loaders::is_json_schema(&content) {
return loaders::load_json_schema(path)
.map_err(|e| anyhow::anyhow!("Failed to load JSON Schema: {}", e));
}
match loaders::load_yaml_schema(path) {
Ok(schema) => Ok(schema),
Err(_) => {
let content = fs::read_to_string(input)
.with_context(|| format!("Failed to read {}", input))?;
CompiledSchema::from_json(&content)
.with_context(|| format!("Failed to parse JSON schema from {}", input))
}
}
}
"yaml" | "yml" => {
let path = std::path::Path::new(input.as_str());
loaders::load_yaml_schema(path)
.map_err(|e| anyhow::anyhow!("Failed to load YAML schema: {}", e))
}
"graphql" | "gql" => {
let path = std::path::Path::new(input.as_str());
loaders::load_graphql_schema(path)
.map_err(|e| anyhow::anyhow!("Failed to load GraphQL schema: {}", e))
}
_ => bail!(
"Unsupported input format: .{}. Use .ts, .wasm, .json, .yaml, or .graphql",
ext
),
}
}
fn cmd_compile(
input: Option<Utf8PathBuf>,
config_path: Option<Utf8PathBuf>,
out: Option<Utf8PathBuf>,
emit: Option<Vec<String>>,
namespace: Option<String>,
keep_temp: bool,
operations: Option<String>,
introspect_url: Option<String>,
) -> Result<()> {
let cfg = if let Some(ref path) = config_path {
eprintln!("Loading config from {}...", path);
Some(config::load_config(path)?)
} else if let Some(found) = config::find_config_file() {
eprintln!("Using config file: {}", found);
Some(config::load_config(&found)?)
} else {
None
};
let (schema_path, output_dir, emitters, ns) = if let Some(cfg) = cfg {
let merged = config::merge_with_cli(cfg, input.as_ref(), out.as_ref(), &emit, &namespace);
(merged.schema, merged.output, merged.emit, merged.namespace)
} else {
(
input,
out.unwrap_or_else(|| Utf8PathBuf::from("./generated")),
emit.unwrap_or_default(),
namespace,
)
};
let schema_path = schema_path.ok_or_else(|| {
anyhow::anyhow!(
"No schema file specified. Use: odk compile <schema> or set 'schema' in config file."
)
})?;
let mut schema = if let Some(url) = &introspect_url {
eprintln!("Introspecting {}...", url);
loaders::introspect_schema(url)
.map_err(|e| anyhow::anyhow!("Introspection failed: {}", e))?
} else {
eprintln!("Loading schema from {}...", schema_path);
load_schema(&schema_path)?
};
if let Some(pattern) = &operations {
eprintln!("Loading operations from {}...", pattern);
let (ops, frags) = loaders::load_graphql_operations(pattern)
.map_err(|e| anyhow::anyhow!("Failed to load operations: {}", e))?;
for op in ops {
schema.add_operation(op);
}
for frag in frags {
schema.add_fragment(frag);
}
eprintln!(
" Loaded {} operations, {} fragments",
schema.operations.len(),
schema.fragments.len()
);
}
eprintln!(
" Loaded: {} ({} models, {} unions, {} operations)",
schema.name,
schema.models.len(),
schema.unions.len(),
schema.operations.len()
);
compile_with_typespec(&schema, &emitters, &output_dir, ns, keep_temp)
}
fn compile_with_typespec(
schema: &CompiledSchema,
emit: &[String],
out: &Utf8PathBuf,
namespace: Option<String>,
keep_temp: bool,
) -> Result<()> {
if let Some(message) = typespec_bridge::unsupported_feature(schema) {
bail!(message);
}
if which::which("tsp").is_err() {
bail!(
"TypeSpec compiler (tsp) not found. Install it with:\n\
npm install -g @typespec/compiler"
);
}
let emitters: Vec<String> = if emit.is_empty() {
vec![
"@typespec/json-schema".to_string(),
"@typespec/openapi3".to_string(),
]
} else {
emit.to_vec()
};
eprintln!("Using TypeSpec emitters: {}", emitters.join(", "));
let ns = namespace.as_deref().unwrap_or(&schema.name);
let emit_options = typespec_bridge::emit_options_for(&emitters, ns);
let tsp_source = typespec_bridge::compiled_to_typespec_with_options(schema, ns, &emit_options);
let temp_dir = tempfile::tempdir()?;
let temp_path = Utf8PathBuf::try_from(temp_dir.path().to_path_buf())?;
let tsp_file = temp_path.join("main.tsp");
fs::write(&tsp_file, &tsp_source)?;
let mut deps = serde_json::Map::new();
deps.insert("@typespec/compiler".into(), serde_json::json!("*"));
for emitter in &emitters {
deps.insert(emitter.clone(), serde_json::json!("*"));
}
for import in &schema.imports {
if import.starts_with('.') || import.starts_with('/') {
continue;
}
deps.insert(import.clone(), serde_json::json!("*"));
}
let package_json = serde_json::json!({
"name": "odk-temp-project",
"type": "module",
"dependencies": deps
});
fs::write(temp_path.join("package.json"), package_json.to_string())?;
let required: Vec<String> = deps.keys().cloned().collect();
let search_start = Utf8PathBuf::try_from(std::env::current_dir()?)?;
let reusable =
find_node_modules(&search_start).filter(|nm| node_modules_has_packages(nm, &required));
if let Some(node_modules) = reusable {
let temp_node_modules = temp_path.join("node_modules");
#[cfg(unix)]
std::os::unix::fs::symlink(&node_modules, &temp_node_modules)
.with_context(|| "Failed to symlink node_modules".to_string())?;
#[cfg(windows)]
std::os::windows::fs::symlink_dir(&node_modules, &temp_node_modules)
.with_context(|| "Failed to symlink node_modules".to_string())?;
eprintln!(" Using node_modules from {}", node_modules.display());
} else {
eprintln!(" Installing TypeSpec dependencies...");
let npm_output = Command::new("npm")
.args(["install", "--silent"])
.current_dir(&temp_path)
.output()
.context("Failed to run npm install")?;
if !npm_output.status.success() {
bail!(
"npm install failed: {}",
String::from_utf8_lossy(&npm_output.stderr)
);
}
}
let absolute_out = if out.is_absolute() {
out.clone()
} else {
Utf8PathBuf::try_from(std::env::current_dir()?)?.join(out)
};
let tsp_config = format!(
"output-dir: \"{}\"\nemit:\n{}\noptions:\n{}",
absolute_out,
emitters
.iter()
.map(|e| format!(" - \"{}\"", e))
.collect::<Vec<_>>()
.join("\n"),
emitters
.iter()
.map(|e| emitter_options(e))
.collect::<Vec<_>>()
.join("\n")
);
fs::write(temp_path.join("tspconfig.yaml"), &tsp_config)?;
fs::create_dir_all(&absolute_out)?;
eprintln!("Running TypeSpec compiler...");
let output = Command::new("tsp")
.args(["compile", tsp_file.as_str()])
.current_dir(&temp_path)
.output()
.context("Failed to run tsp compiler")?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
eprintln!("TypeSpec stdout:\n{}", stdout);
eprintln!("TypeSpec stderr:\n{}", stderr);
bail!("TypeSpec compilation failed");
}
eprintln!("Generated output to {}", absolute_out);
if keep_temp {
let kept_path = temp_dir.keep();
eprintln!("Kept temp files at: {}", kept_path.display());
}
Ok(())
}
fn emitter_options(emitter: &str) -> String {
match emitter {
"@typespec/json-schema" => format!(
" \"{}\":\n emitter-output-dir: \"{{output-dir}}\"\n emitAllModels: false\n emitAllRefs: true",
emitter
),
"@typespec/openapi3" => format!(
" \"{}\":\n emitter-output-dir: \"{{output-dir}}\"",
emitter
),
_ => format!(
" \"{}\":\n emitter-output-dir: \"{{output-dir}}\"",
emitter
),
}
}
fn find_node_modules(start: &Utf8PathBuf) -> Option<PathBuf> {
let mut current = start.as_std_path().to_path_buf();
loop {
let node_modules = current.join("node_modules");
if node_modules.is_dir() && node_modules.join("@typespec").is_dir() {
return Some(node_modules);
}
if !current.pop() {
return None;
}
}
}
fn node_modules_has_packages(node_modules: &std::path::Path, packages: &[String]) -> bool {
packages.iter().all(|pkg| node_modules.join(pkg).is_dir())
}
fn cmd_init(lang: Option<String>, name: Option<String>) -> Result<()> {
use templates::ProjectLang;
let project_name = match name {
Some(n) => n,
None => {
std::env::current_dir()?
.file_name()
.and_then(|n| n.to_str())
.map(|s| s.to_string())
.unwrap_or_else(|| "my-schema".to_string())
}
};
let project_lang = match lang {
Some(l) => ProjectLang::from_str(&l).ok_or_else(|| {
anyhow::anyhow!("Unknown language: '{}'. Use: rust, python, or yaml", l)
})?,
None => prompt_for_language()?,
};
eprintln!(
"Initializing {} project '{}'...",
project_lang.display_name(),
project_name
);
let is_directory = match project_lang {
ProjectLang::Rust => {
let dir = std::path::Path::new(&project_name);
fs::create_dir_all(dir.join("src"))?;
let cargo_toml = templates::render(templates::RUST_CARGO_TOML, &project_name);
fs::write(dir.join("Cargo.toml"), cargo_toml)?;
let lib_rs = templates::render(templates::RUST_LIB_RS, &project_name);
fs::write(dir.join("src/lib.rs"), lib_rs)?;
true
}
ProjectLang::Python => {
let schema_py = templates::render(templates::PYTHON_SCHEMA, &project_name);
fs::write("schema.py", schema_py)?;
false
}
ProjectLang::Yaml => {
let schema_yaml = templates::render(templates::YAML_SCHEMA, &project_name);
fs::write("schema.yaml", schema_yaml)?;
false
}
};
eprintln!(
"{}",
templates::post_init_message(project_lang, &project_name, is_directory)
);
Ok(())
}
fn prompt_for_language() -> Result<templates::ProjectLang> {
use std::io::{self, Write};
eprintln!("Select a project type:");
for (i, lang) in templates::ProjectLang::all().iter().enumerate() {
eprintln!(" {}. {}", i + 1, lang.display_name());
}
eprint!("Enter choice [1-3]: ");
io::stderr().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
let choice: usize = input
.trim()
.parse()
.map_err(|_| anyhow::anyhow!("Invalid choice. Please enter 1, 2, or 3."))?;
templates::ProjectLang::all()
.get(choice.saturating_sub(1))
.copied()
.ok_or_else(|| anyhow::anyhow!("Invalid choice. Please enter 1, 2, or 3."))
}
fn cmd_check(input: Utf8PathBuf, operations: Option<String>) -> Result<()> {
eprintln!("Checking {}...", input);
let mut schema = load_schema(&input)?;
if let Some(pattern) = &operations {
let (ops, frags) = loaders::load_graphql_operations(pattern)
.map_err(|e| anyhow::anyhow!("Failed to load operations: {}", e))?;
for op in ops {
schema.add_operation(op);
}
for frag in frags {
schema.add_fragment(frag);
}
}
println!("Schema: {}", schema.name);
println!("Models: {}", schema.models.len());
for model in &schema.models {
println!(" - {} ({} fields)", model.name, model.fields.len());
}
println!("Unions: {}", schema.unions.len());
for union in &schema.unions {
println!(" - {} ({} variants)", union.name, union.variants.len());
}
println!("Operations: {}", schema.operations.len());
for op in &schema.operations {
println!(" - {} ({:?})", op.name, op.kind);
}
println!("Fragments: {}", schema.fragments.len());
for frag in &schema.fragments {
println!(" - {} on {}", frag.name, frag.type_condition);
}
if let Some(warnings) = &schema.warnings {
if !warnings.is_empty() {
println!("\nWarnings:");
for w in warnings {
println!(" - {}", w);
}
}
}
println!("\nSchema is valid!");
Ok(())
}
fn cmd_generate(
input: Option<Utf8PathBuf>,
config_path: Option<Utf8PathBuf>,
out: Utf8PathBuf,
targets_str: String,
operations: Option<String>,
introspect_url: Option<String>,
out_file: Option<String>,
) -> Result<()> {
use odk_cli::generate::{self, Target};
let cfg = if let Some(ref path) = config_path {
Some(config::load_config(path)?)
} else if let Some(found) = config::find_config_file() {
eprintln!("Using config file: {}", found);
Some(config::load_config(&found)?)
} else {
None
};
let gen_cfg = cfg.as_ref().and_then(|c| c.generate.as_ref());
let schema_input = input.or_else(|| cfg.as_ref().and_then(|c| c.schema.clone()));
let final_targets_str = if targets_str == "sdk,react-query,msw" {
gen_cfg
.filter(|g| !g.targets.is_empty())
.map(|g| g.targets.join(","))
.unwrap_or(targets_str)
} else {
targets_str
};
let final_operations = operations.or_else(|| gen_cfg.and_then(|g| g.operations.clone()));
let final_out = if out == Utf8PathBuf::from("./generated") {
gen_cfg.and_then(|g| g.output.clone()).unwrap_or(out)
} else {
out
};
let targets = Target::parse_list(&final_targets_str).map_err(|e| anyhow::anyhow!(e))?;
if targets.is_empty() {
bail!(
"No targets specified. Available: sdk, react-query, msw, mcp, python, typescript, rust"
);
}
let mut schema = if let Some(url) = &introspect_url {
eprintln!("Introspecting {}...", url);
loaders::introspect_schema(url)
.map_err(|e| anyhow::anyhow!("Introspection failed: {}", e))?
} else if let Some(ref input_path) = schema_input {
eprintln!("Loading schema from {}...", input_path);
load_schema(input_path)?
} else {
bail!("No schema source. Provide an input file or --introspect URL.");
};
if let Some(pattern) = &final_operations {
eprintln!("Loading operations from {}...", pattern);
let (ops, frags) = loaders::load_graphql_operations(pattern)
.map_err(|e| anyhow::anyhow!("Failed to load operations: {}", e))?;
for op in ops {
schema.add_operation(op);
}
for frag in frags {
schema.add_fragment(frag);
}
}
let needs_operations = targets
.iter()
.any(|t| *t != Target::Python && *t != Target::Typescript && *t != Target::Rust);
if needs_operations && schema.operations.is_empty() {
bail!(
"No operations found. Provide operation documents via --operations \
or include them in the schema file."
);
}
if schema.operations.is_empty() {
eprintln!(
" {} models, {} unions",
schema.models.len(),
schema.unions.len()
);
} else {
eprintln!(
" {} operations, {} fragments",
schema.operations.len(),
schema.fragments.len()
);
}
let target_names: Vec<String> = targets.iter().map(|t| t.to_string()).collect();
eprintln!("Generating targets: {}", target_names.join(", "));
let mcp_config = cfg
.as_ref()
.and_then(|c| c.generate.as_ref())
.and_then(|g| g.mcp.as_ref());
if let Err(message) = generate::check_support(&schema, &targets) {
bail!(message);
}
let mut output = generate::generate(&schema, &targets, mcp_config);
if let Some(stem) = &out_file {
output = rename_model_stem(output, stem);
}
fs::create_dir_all(&final_out)
.with_context(|| format!("Failed to create output directory: {}", final_out))?;
for (filename, content) in &output {
let path = final_out.join(filename);
fs::write(&path, content).with_context(|| format!("Failed to write {}", path))?;
eprintln!(" Wrote {}", path);
}
eprintln!("Done! {} files generated.", output.len());
Ok(())
}
fn rename_model_stem(
output: std::collections::BTreeMap<String, String>,
stem: &str,
) -> std::collections::BTreeMap<String, String> {
output
.into_iter()
.map(|(name, content)| match name.strip_prefix("models.") {
Some(ext) => (format!("{stem}.{ext}"), content),
None => (name, content),
})
.collect()
}
fn cmd_publish(
input: Utf8PathBuf,
registry: String,
repository: String,
tag: String,
token: Option<String>,
) -> Result<()> {
use odk_cli::publish::{self, PublishTarget};
eprintln!("Loading schema from {input}...");
let schema = load_schema(&input)?;
let token = token.or_else(|| std::env::var("ODK_REGISTRY_TOKEN").ok());
let target = PublishTarget {
registry,
repository,
tag,
token,
};
eprintln!(
"Publishing to {}/v2/{}:{}...",
target.registry.trim_end_matches('/'),
target.repository,
target.tag
);
let reference = publish::publish(&schema, &target)?;
println!("Published {reference}");
Ok(())
}
fn cmd_typespec(
input: Utf8PathBuf,
out: Option<Utf8PathBuf>,
namespace: Option<String>,
) -> Result<()> {
let schema = load_schema(&input)?;
let ns = namespace.as_deref().unwrap_or(&schema.name);
let tsp_source = typespec_bridge::compiled_to_typespec(&schema, ns);
match out {
Some(path) => {
fs::write(&path, &tsp_source)?;
eprintln!("Wrote TypeSpec to {}", path);
}
None => {
println!("{}", tsp_source);
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::{node_modules_has_packages, rename_model_stem};
use std::collections::BTreeMap;
#[test]
fn node_modules_reused_only_when_all_required_packages_present() {
let dir = tempfile::tempdir().unwrap();
let nm = dir.path().join("node_modules");
std::fs::create_dir_all(nm.join("@typespec/compiler")).unwrap();
std::fs::create_dir_all(nm.join("@typespec/openapi3")).unwrap();
let present = [
"@typespec/compiler".to_string(),
"@typespec/openapi3".to_string(),
];
assert!(node_modules_has_packages(&nm, &present));
let missing = [
"@typespec/compiler".to_string(),
"@omnidotdev/typespec-drizzle".to_string(),
];
assert!(!node_modules_has_packages(&nm, &missing));
}
#[test]
fn out_file_renames_only_the_models_stem() {
let mut out = BTreeMap::new();
out.insert("models.rs".to_string(), "r".to_string());
out.insert("models.ts".to_string(), "t".to_string());
out.insert("client.ts".to_string(), "c".to_string());
let renamed = rename_model_stem(out, "opgraph");
assert_eq!(renamed.get("opgraph.rs").map(String::as_str), Some("r"));
assert_eq!(renamed.get("opgraph.ts").map(String::as_str), Some("t"));
assert_eq!(renamed.get("client.ts").map(String::as_str), Some("c"));
assert!(!renamed.contains_key("models.rs"));
}
}