nativeview-cli 0.1.0-rc.1

Developer CLI (`nv`) for Native View Engine: dev hot-reload, builds, pairing, SDK management, app scaffolding, and docs.
Documentation
//! `nv new app <name>` & `nv init` — external consumer app scaffolder using crates.io `nativeview`.

use std::fs;
use std::path::{Path, PathBuf};

use clap::Subcommand;

use crate::cargo_env::sdk::CLI_VERSION;

#[derive(Subcommand, Debug, Clone)]
pub(crate) enum NewAction {
    /// Scaffold a standalone cross-platform NativeView app (`Cargo.toml`, `nativeview.toml`, `src/lib.rs`, `web/index.html`).
    App {
        /// Kebab-case application name (e.g. `hello-nv`).
        name: String,
        /// Destination directory (defaults to `./<name>`).
        #[arg(long)]
        dir: Option<PathBuf>,
        /// `nativeview` crate version constraint (defaults to this CLI's version).
        #[arg(long, default_value = CLI_VERSION)]
        sdk_version: String,
    },
}

pub(crate) fn cmd_new(action: NewAction) {
    let res = match action {
        NewAction::App {
            name,
            dir,
            sdk_version,
        } => {
            let dest = dir.unwrap_or_else(|| PathBuf::from(&name));
            scaffold_external_app(&dest, &name, &sdk_version)
        }
    };
    if let Err(err) = res {
        eprintln!("error: {err}");
        std::process::exit(1);
    }
}

pub(crate) fn cmd_init(name: Option<String>, sdk_version: &str) {
    let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
    let app_name = name.unwrap_or_else(|| {
        cwd.file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("nativeview-app")
            .to_owned()
    });
    if let Err(err) = scaffold_external_app(&cwd, &app_name, sdk_version) {
        eprintln!("error: {err}");
        std::process::exit(1);
    }
}

fn validate_app_name(name: &str) -> Result<(), String> {
    if name.is_empty()
        || !name
            .bytes()
            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-' || b == b'_')
        || !name.as_bytes()[0].is_ascii_lowercase()
    {
        return Err(format!(
            "invalid app name '{name}': must start with a lowercase letter and use only a-z, 0-9, '-', or '_'"
        ));
    }
    Ok(())
}

pub(crate) fn scaffold_external_app(
    dest_dir: &Path,
    name: &str,
    sdk_version: &str,
) -> Result<(), String> {
    validate_app_name(name)?;
    let lib_name = name.replace('-', "_");
    let id_slug: String = name
        .replace('_', "-")
        .trim_matches('-')
        .to_owned();
    let app_id = format!("com.example.{id_slug}");

    let cargo_toml_path = dest_dir.join("Cargo.toml");
    if cargo_toml_path.exists() {
        return Err(format!(
            "refusing to overwrite existing '{}'",
            cargo_toml_path.display()
        ));
    }

    fs::create_dir_all(dest_dir.join("src"))
        .map_err(|e| format!("failed to create '{}/src': {e}", dest_dir.display()))?;
    fs::create_dir_all(dest_dir.join("web"))
        .map_err(|e| format!("failed to create '{}/web': {e}", dest_dir.display()))?;

    let cargo_toml = format!(
        r#"[package]
name = "{name}"
version = "0.1.0"
edition = "2024"

[lib]
name = "{lib_name}"
crate-type = ["cdylib", "rlib"]

[features]
web = ["nativeview/web", "dep:wasm-bindgen"]

[dependencies]
nativeview = {{ version = "{sdk_version}", default-features = false, features = ["core", "ui"] }}
wasm-bindgen = {{ version = "0.2", optional = true }}
"#
    );

    let nv_toml = format!(
        r#"[app]
name = "{name}"
id = "{app_id}"
width = 1024
height = 720

[web]
root = "web"
index = "index.html"
"#
    );

    let lib_rs = r#"use nativeview::prelude::*;

#[component]
pub fn App() -> impl View {
    let count = Signal::new(0i32);
    view! {
        Node(
            style: TypedStyle::new()
                .width_pct(100.0)
                .height_pct(100.0)
                .padding(24.0)
                .gap(16.0),
        ) {
            Text(
                "Hello from NativeView ({count})",
                style: TypedStyle::new().font_size(24.0),
            )
            Button(on_press: move |()| count.update(|n| *n += 1)) {
                Text("Increment")
            }
        }
    }
}

// The app's `nv_get_interface` export. Only a leaf package (no dependents, no `[[bin]]`) may
// export it; split the export into a cdylib-only crate before another crate depends on this one.
#[cfg(not(target_arch = "wasm32"))]
mod native_export {
    struct AppSpec;

    impl nativeview::app::ReactiveAppSpec for AppSpec {
        fn create_surface(surface_id: nativeview::abi::SurfaceId) -> super::ReactiveSurface {
            super::ReactiveSurface::new(surface_id, super::App::new)
        }
    }

    type NativeApp = nativeview::app::ReactiveSurfaceApp<AppSpec>;
    nativeview::engine::export_nv_app!(NativeApp);
}

#[cfg(all(feature = "web", target_arch = "wasm32"))]
#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn web_main() {
    nativeview::backends::web_runtime::mount_reactive_app(App::new);
}
"#;

    let index_html = format!(
        r#"<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>{name}</title>
</head>
<body>
  <div id="nv-root"></div>
  <script type="module">
    import init from "./pkg/{lib_name}.js";
    init();
  </script>
</body>
</html>
"#
    );

    let readme = format!(
        r#"# {name}

Standalone NativeView application scaffolded via `nv new app {name}`.

## Run

```bash
nv dev --web
nv build --target web
```
"#
    );

    fs::write(&cargo_toml_path, cargo_toml)
        .map_err(|e| format!("failed to write '{}': {e}", cargo_toml_path.display()))?;
    fs::write(dest_dir.join("nativeview.toml"), nv_toml)
        .map_err(|e| format!("failed to write nativeview.toml: {e}"))?;
    fs::write(dest_dir.join("src/lib.rs"), lib_rs)
        .map_err(|e| format!("failed to write src/lib.rs: {e}"))?;
    fs::write(dest_dir.join("web/index.html"), index_html)
        .map_err(|e| format!("failed to write web/index.html: {e}"))?;
    fs::write(dest_dir.join("README.md"), readme)
        .map_err(|e| format!("failed to write README.md: {e}"))?;

    println!("Created NativeView app '{name}' in {}", dest_dir.display());
    println!("Next steps:\n  cd {}\n  nv dev --web", dest_dir.display());
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn scaffolds_valid_standalone_external_app() {
        let tmp = std::env::temp_dir().join(format!("nv-new-app-test-{}", std::process::id()));
        let _ = fs::remove_dir_all(&tmp);
        scaffold_external_app(&tmp, "demo-app", "0.1.0").expect("scaffold app");
        let cargo = fs::read_to_string(tmp.join("Cargo.toml")).unwrap();
        assert!(cargo.contains("name = \"demo-app\""));
        assert!(cargo.contains("nativeview = { version = \"0.1.0\""));
        assert!(cargo.contains("web = [\"nativeview/web\""));
        assert!(tmp.join("nativeview.toml").is_file());
        let manifest = nativeview_cli::manifest::NvManifest::load_for_dir(&tmp)
            .expect("scaffolded nativeview.toml must parse cleanly");
        assert_eq!(manifest.app.id.as_deref(), Some("com.example.demo-app"));
        let lib_rs = fs::read_to_string(tmp.join("src/lib.rs")).unwrap();
        assert!(lib_rs.contains("ReactiveAppSpec"));
        assert!(lib_rs.contains("ReactiveSurfaceApp"));
        assert!(lib_rs.contains("mount_reactive_app"));
        assert!(lib_rs.contains("view!"));
        assert!(tmp.join("web/index.html").is_file());
        let _ = fs::remove_dir_all(&tmp);
    }
}