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
//! Integration tests for `cargo nv docs check` and `cargo nv docs build`.

use std::collections::BTreeSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use nativeview_mdx::{SEARCH_INDEX_FILE_NAME, SEARCH_INDEX_MAGIC, SearchIndex};

fn nv_bin() -> &'static str {
    env!("CARGO_BIN_EXE_nv")
}

fn repo_root() -> PathBuf {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("..")
        .join("..")
        .join("..")
}

fn temp_test_dir(tag: &str) -> PathBuf {
    let dir = std::env::temp_dir().join(format!(
        "nv-docs-cli-test-{tag}-{}",
        std::process::id()
    ));
    let _ = fs::remove_dir_all(&dir);
    fs::create_dir_all(&dir).expect("create temp test dir");
    dir
}

#[test]
fn docs_check_passes_on_official_docs_content() {
    let output = Command::new(nv_bin())
        .current_dir(repo_root())
        .args(["docs", "check", "--content", "docs/content"])
        .output()
        .expect("run nv docs check");

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "docs check failed:\nstdout: {stdout}\nstderr: {stderr}"
    );
    assert!(
        stdout.contains("30 pages") && stdout.contains("5 live demos"),
        "unexpected docs check summary: {stdout}"
    );
}

#[test]
fn docs_check_fails_non_zero_on_broken_link_and_unknown_demo() {
    let dir = temp_test_dir("broken");
    fs::write(
        dir.join("_meta.toml"),
        "index = \"Home\"\n",
    )
    .unwrap();
    fs::write(
        dir.join("index.mdx"),
        "---\ntitle: Broken Test\n---\n\nSee [Missing](/does/not/exist) and <LiveDemo id=\"unknown-demo-xyz\" />\n",
    )
    .unwrap();

    let output = Command::new(nv_bin())
        .args(["docs", "check", "--content"])
        .arg(&dir)
        .output()
        .expect("run nv docs check on broken content");

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        !output.status.success(),
        "expected non-zero exit code for broken link + unknown demo"
    );
    assert!(
        stderr.contains("Broken internal link") && stderr.contains("unknown-demo-xyz"),
        "expected both broken link and unknown LiveDemo diagnostics, got:\n{stderr}"
    );

    let _ = fs::remove_dir_all(&dir);
}

#[test]
fn docs_check_generic_validates_standalone_external_mdx_without_site_package() {
    let dir = temp_test_dir("generic-mdx");
    fs::write(dir.join("_meta.toml"), "index = \"Home\"\n").unwrap();
    fs::write(
        dir.join("index.mdx"),
        "---\ntitle: External Docs\n---\n\n# External Docs\n\nStandalone MDX check.\n",
    )
    .unwrap();

    let output = Command::new(nv_bin())
        .args(["docs", "check", "--generic", "--content"])
        .arg(&dir)
        .output()
        .expect("run nv docs check --generic");
    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);
    assert!(
        output.status.success(),
        "docs check --generic failed:\nstdout: {stdout}\nstderr: {stderr}"
    );
    assert!(stdout.contains("1 pages"), "unexpected stdout: {stdout}");

    let _ = fs::remove_dir_all(&dir);
}

const SITE_URL: &str = "https://nativeview.github.io/nativeview";

/// The official site's non-MDX routes (`nativeview_docs_site::CUSTOM_ROUTES`, without slashes);
/// every other route is one `/docs/**` page per MDX file.
const CUSTOM_ROUTES: [&str; 6] =
    ["", "progress", "benchmarks", "examples", "examples/studio", "examples/kitchen-sink"];

/// `nv docs build --content docs/content --skip-wasm <extra…> --out <out>`.
fn docs_build(extra: &[&std::ffi::OsStr], out: &Path) -> std::process::Output {
    Command::new(nv_bin())
        .current_dir(repo_root())
        .args(["docs", "build", "--content", "docs/content", "--skip-wasm"])
        .args(extra)
        .arg("--out")
        .arg(out)
        .output()
        .expect("run nv docs build")
}

fn assert_success(output: &std::process::Output) {
    assert!(
        output.status.success(),
        "docs build failed:\nstdout: {}\nstderr: {}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
}

/// Route (relative dir, no slashes) of every `index.html` under `dir`.
fn emitted_routes(root: &Path, dir: &Path, out: &mut BTreeSet<String>) {
    for entry in fs::read_dir(dir).expect("read out dir").flatten() {
        let p = entry.path();
        if p.is_dir() {
            emitted_routes(root, &p, out);
        } else if p.file_name().is_some_and(|n| n == "index.html") {
            let rel = p
                .parent()
                .and_then(|d| d.strip_prefix(root).ok())
                .expect("index.html lies under the output root");
            out.insert(rel.to_string_lossy().replace('\\', "/"));
        }
    }
}

fn count_files_with_ext(dir: &Path, ext: &str) -> usize {
    fs::read_dir(dir)
        .expect("read dir")
        .flatten()
        .map(|e| e.path())
        .map(|p| {
            if p.is_dir() {
                count_files_with_ext(&p, ext)
            } else {
                usize::from(p.extension().is_some_and(|e| e == ext))
            }
        })
        .sum()
}

#[test]
fn docs_build_skip_wasm_emits_one_page_per_sitemap_route_plus_search_index() {
    let out_dir = temp_test_dir("build-base");
    let output = docs_build(
        &["--base-path".as_ref(), "/nativeview".as_ref(), "--site-url".as_ref(), SITE_URL.as_ref()],
        &out_dir,
    );
    assert_success(&output);

    // Top-level static artifacts.
    assert!(out_dir.join(".nojekyll").is_file());
    assert!(out_dir.join("404.html").is_file());
    assert!(out_dir.join("sitemap.xml").is_file());
    assert!(out_dir.join(SEARCH_INDEX_FILE_NAME).is_file());

    // The binary search index decodes and answers queries.
    let idx_bytes = fs::read(out_dir.join(SEARCH_INDEX_FILE_NAME)).expect("read search.nv-idx");
    assert_eq!(&idx_bytes[..SEARCH_INDEX_MAGIC.len()], SEARCH_INDEX_MAGIC);
    let index = SearchIndex::decode(&idx_bytes).expect("decode search index");
    assert!(!index.query("VirtualList", 5).is_empty(), "expected search hits for VirtualList");

    // Every sitemap `<loc>` is a canonical, slash-terminated URL under the site URL, listed once.
    let sitemap = fs::read_to_string(out_dir.join("sitemap.xml")).expect("read sitemap.xml");
    let mut sitemap_routes = BTreeSet::new();
    for loc in sitemap.split("<loc>").skip(1) {
        let url = loc.split_once("</loc>").expect("closed <loc>").0;
        let route = url
            .strip_prefix(SITE_URL)
            .and_then(|r| r.strip_prefix('/'))
            .and_then(|r| r.strip_suffix('/').or((r.is_empty()).then_some(r)))
            .unwrap_or_else(|| panic!("non-canonical sitemap loc {url}"));
        assert!(sitemap_routes.insert(route.to_string()), "duplicate sitemap loc {url}");
    }

    // Pages: exactly one `<route>/index.html` per sitemap route, plus `404.html`, and nothing else.
    let mut emitted = BTreeSet::new();
    emitted_routes(&out_dir, &out_dir, &mut emitted);
    assert_eq!(emitted, sitemap_routes, "emitted index.html routes differ from sitemap routes");
    assert_eq!(count_files_with_ext(&out_dir, "html"), sitemap_routes.len() + 1);

    // Routes: every custom route, and one `/docs/**` route per MDX source file.
    for route in CUSTOM_ROUTES {
        assert!(sitemap_routes.contains(route), "missing custom route `/{route}`");
    }
    let docs_routes: Vec<_> =
        sitemap_routes.iter().filter(|r| !CUSTOM_ROUTES.contains(&r.as_str())).collect();
    assert!(docs_routes.iter().all(|r| *r == "docs" || r.starts_with("docs/")), "{docs_routes:?}");
    assert_eq!(docs_routes.len(), count_files_with_ext(&repo_root().join("docs/content"), "mdx"));

    // `--skip-wasm` ships no WASM: no islands, no hydration bundle, no bootstrap script, and the
    // pre-redesign `examples/_runtime/` portal is gone.
    assert!(!out_dir.join("examples/_islands").exists());
    assert!(!out_dir.join("examples/_runtime").exists());
    assert!(!out_dir.join("assets/nativeview_docs_site_bg.wasm").exists());

    // Landing: SSR document with base-path-prefixed CTAs and no example WASM.
    let root_html = fs::read_to_string(out_dir.join("index.html")).expect("read root index.html");
    assert!(root_html.contains("<!doctype html>"));
    assert!(root_html.contains("<style data-nv-base>"));
    assert!(root_html.contains("<style data-nv-ssr data-nv-hashes=\""));
    assert!(root_html.contains("<h1"));
    assert!(root_html.contains("Native-speed UI in Rust"));
    assert!(!root_html.contains("<script type=\"module\""), "--skip-wasm must not bootstrap hydration");
    assert!(!root_html.contains("nativeview_web_shell"));
    assert!(root_html.contains("href=\"/nativeview/docs/getting-started/quickstart\""));
    assert!(root_html.contains("href=\"/nativeview/examples/studio/\""));

    // Example pages server-render their island host and its frame-0 mount root, with a canonical URL.
    for (slug, title) in
        [("studio", "Aether Workspace + NV Studio"), ("kitchen-sink", "NV Kitchen Sink Gallery")]
    {
        let html = fs::read_to_string(out_dir.join(format!("examples/{slug}/index.html")))
            .expect("read example page");
        assert!(html.contains(&format!("<title>{title} — Native View Engine</title>")), "{slug}");
        assert!(html.contains(&format!("{SITE_URL}/examples/{slug}/\"")), "{slug} canonical");
        assert!(html.contains(&format!("data-nv-island-host=\"{slug}\"")), "{slug} island host");
        assert!(html.contains(&format!("data-nv-app=\"{slug}\"")), "{slug} mount root");
    }

    // Docs pages: semantic HTML5 with `/docs`-prefixed internal links.
    let docs_root_html = fs::read_to_string(out_dir.join("docs/index.html")).expect("read docs/index.html");
    assert!(docs_root_html.contains("<nav") && docs_root_html.contains("<main") && docs_root_html.contains("<article"));
    assert!(docs_root_html.contains("href=\"/nativeview/docs/getting-started/quickstart\""));
    let guide_html = fs::read_to_string(out_dir.join("docs/guides/ui-components/index.html"))
        .expect("read docs/guides/ui-components/index.html");
    assert!(guide_html.contains("<h1") && guide_html.contains("data-nv-island=\"ui-playground\""));

    let _ = fs::remove_dir_all(&out_dir);
}

#[test]
fn docs_build_stages_hashed_and_direct_web_shell_bundles_as_islands() {
    let dist_arg = |dir: &Path| -> [std::ffi::OsString; 2] { ["--web-shell-dist".into(), dir.into()] };
    let build = |dist: &Path, out: &Path| {
        let args = dist_arg(dist);
        docs_build(&[args[0].as_os_str(), args[1].as_os_str()], out)
    };

    // 1. Unified `build.sh` layout: `pkg/<bundle>/manifest.json` naming the entry files in a
    //    content-hashed `pkg/<bundle>/<hash>/` directory. Only example apps are staged, never `dev`.
    let unified_src = temp_test_dir("ws-unified-src");
    fs::write(unified_src.join("index.html"), "<html></html>").unwrap();
    for (bundle, hash) in [("studio", "0123456789abcdef"), ("kitchen-sink", "fedcba9876543210"), ("dev", "00112233aabbccdd")] {
        let dir = unified_src.join("pkg").join(bundle).join(hash);
        fs::create_dir_all(dir.join("snippets/nv-web-shell-1/")).unwrap();
        fs::write(dir.join("nativeview_web_shell.js"), "export default function(){}").unwrap();
        fs::write(dir.join("nativeview_web_shell_bg.wasm"), b"\0asm").unwrap();
        fs::write(dir.join("snippets/nv-web-shell-1/inline0.js"), "export const x = 1;").unwrap();
        fs::write(
            unified_src.join("pkg").join(bundle).join("manifest.json"),
            format!("{{\"js\":\"{hash}/nativeview_web_shell.js\",\"wasm\":\"{hash}/nativeview_web_shell_bg.wasm\"}}"),
        )
        .unwrap();
    }
    let out_unified = temp_test_dir("ws-unified-out");
    assert_success(&build(&unified_src, &out_unified));
    let islands = out_unified.join("examples/_islands");
    for file in [
        "studio/0123456789abcdef/nativeview_web_shell.js",
        "studio/0123456789abcdef/nativeview_web_shell_bg.wasm",
        "studio/0123456789abcdef/snippets/nv-web-shell-1/inline0.js",
        "kitchen-sink/fedcba9876543210/nativeview_web_shell.js",
        "kitchen-sink/fedcba9876543210/nativeview_web_shell_bg.wasm",
    ] {
        assert!(islands.join(file).is_file(), "{file} staged");
    }
    assert!(!islands.join("dev").exists(), "dev-only bundle must not ship in static docs output");
    assert!(!out_unified.join("examples/_runtime").exists());
    for slug in ["studio", "kitchen-sink"] {
        let html = fs::read_to_string(out_unified.join(format!("examples/{slug}/index.html"))).unwrap();
        assert!(html.contains(&format!("data-nv-island-host=\"{slug}\"")), "{slug}");
    }

    // 2. An explicit `--web-shell-dist` missing an app's bundle (here: no manifest) fails the build
    //    before any page is written.
    let no_manifest_src = temp_test_dir("ws-no-manifest-src");
    fs::create_dir_all(no_manifest_src.join("pkg/studio/0123456789abcdef")).unwrap();
    fs::write(no_manifest_src.join("pkg/studio/0123456789abcdef/nativeview_web_shell_bg.wasm"), b"\0asm").unwrap();
    let out_no_manifest = temp_test_dir("ws-no-manifest-out");
    let output_nm = build(&no_manifest_src, &out_no_manifest);
    let stderr_nm = String::from_utf8_lossy(&output_nm.stderr);
    assert!(!output_nm.status.success(), "missing bundles must fail the build");
    assert!(stderr_nm.contains("has no WASM bundle for [\"studio\", \"kitchen-sink\"]"), "{stderr_nm}");
    assert!(!out_no_manifest.join("examples/studio/index.html").exists(), "no page may be emitted");
    assert!(!out_no_manifest.join("examples/_islands").exists());

    // 3. Per-app direct layout (`<dist>/<slug>/nativeview_web_shell.js`, unhashed): the whole app
    //    dir is staged as the island, and siblings outside it are not.
    let per_app_src = temp_test_dir("ws-perapp-src");
    fs::write(per_app_src.join("nv_dom.js"), "// shared, not part of any island").unwrap();
    for slug in ["studio", "kitchen-sink"] {
        let dir = per_app_src.join(slug);
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("nativeview_web_shell.js"), "export default function(){}").unwrap();
        fs::write(dir.join(format!("{slug}.wasm")), b"\0asm").unwrap();
    }
    let out_per_app = temp_test_dir("ws-perapp-out");
    assert_success(&build(&per_app_src, &out_per_app));
    let islands = out_per_app.join("examples/_islands");
    for slug in ["studio", "kitchen-sink"] {
        assert!(islands.join(slug).join("nativeview_web_shell.js").is_file(), "{slug} entry");
        assert!(islands.join(slug).join(format!("{slug}.wasm")).is_file(), "{slug} wasm");
    }
    assert!(!islands.join("nv_dom.js").exists() && !out_per_app.join("examples/nv_dom.js").exists());

    for dir in [unified_src, out_unified, no_manifest_src, out_no_manifest, per_app_src, out_per_app] {
        let _ = fs::remove_dir_all(dir);
    }
}