use std::collections::BTreeMap;
use std::env;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use nativeview_cli::manifest::{AndroidShell, NvManifest};
use super::android::bundle::build_android_apk;
use super::android::run::run_android_apk;
use super::apple::ios_bundle::{build_ios_sim_app, launch_ios_sim_app};
use super::apple::macos_bundle::{
launch_macos_app, package_macos_app_bundle, should_direct_exec_macos,
};
use super::export_pkg::{build_export_package, format_export_plan};
use super::host_cache::{ensure_host_shell, HostShell};
pub(crate) use super::plan_format::append_manifest_shell_args;
use super::plan_format::{
desktop_shell_launch_args, format_app_plan, format_built_app_summary, PlanRunOptions,
};
use super::web_bundle::{build_web_app, copy_file_ensuring_parent, serve_web_bundle};
use crate::cargo_env::{
absolutize_path_from, build_artifact, host_target_triple, resolve_app_and_optional_sdk,
resolve_app_and_sdk, AppContext, AppSelector, ArtifactKind, BuildArtifactSpec, NvSdkRoot,
};
pub(crate) const WASM_TARGET: &str = "wasm32-unknown-unknown";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum BuildTarget {
Macos,
Linux,
Windows,
Web,
IosSim,
Android,
WebPkg,
RnPkg,
NitroUiPkg,
}
impl BuildTarget {
pub(crate) fn parse(raw: &str) -> Result<Self, String> {
const TARGETS: &[(&str, BuildTarget)] = &[
("macos", BuildTarget::Macos), ("linux", BuildTarget::Linux), ("windows", BuildTarget::Windows),
("web", BuildTarget::Web), ("ios-sim", BuildTarget::IosSim), ("android", BuildTarget::Android),
("web-pkg", BuildTarget::WebPkg), ("rn-pkg", BuildTarget::RnPkg), ("nitro-ui-pkg", BuildTarget::NitroUiPkg),
];
let trimmed = raw.trim();
TARGETS
.iter()
.find_map(|(name, target)| trimmed.eq_ignore_ascii_case(name).then_some(*target))
.ok_or_else(|| format!("unknown --target '{trimmed}' (expected one of: macos, linux, windows, web, ios-sim, android, web-pkg, rn-pkg, nitro-ui-pkg)"))
}
pub(crate) const fn is_export_package(self) -> bool {
matches!(self, Self::WebPkg | Self::RnPkg | Self::NitroUiPkg)
}
pub(crate) fn host_default() -> Result<Self, String> {
match env::consts::OS {
"macos" => Ok(Self::Macos),
"linux" => Ok(Self::Linux),
"windows" => Ok(Self::Windows),
other => Err(format!(
"unsupported host OS '{other}' for default target; pass --target <macos|linux|windows|web>"
)),
}
}
pub(crate) const fn as_str(self) -> &'static str {
match self {
Self::Macos => "macos",
Self::Linux => "linux",
Self::Windows => "windows",
Self::Web => "web",
Self::IosSim => "ios-sim",
Self::Android => "android",
Self::WebPkg => "web-pkg",
Self::RnPkg => "rn-pkg",
Self::NitroUiPkg => "nitro-ui-pkg",
}
}
}
#[derive(Debug, Clone)]
pub(crate) struct AppBuildOptions {
pub app_path: Option<PathBuf>,
pub package: Option<String>,
pub target: Option<String>,
pub shell: Option<String>,
pub kit: Option<String>,
pub platforms: Option<String>,
pub release: bool,
pub out: Option<PathBuf>,
pub sdk_root: Option<PathBuf>,
pub dry_run: bool,
}
#[derive(Debug, Clone)]
pub(crate) struct AppRunOptions {
pub app_path: Option<PathBuf>,
pub package: Option<String>,
pub target: Option<String>,
pub shell: Option<String>,
pub release: bool,
pub sdk_root: Option<PathBuf>,
pub http_port: u16,
pub direct: bool,
pub device: Option<String>,
pub headless: bool,
pub pair_only: bool,
pub pair_uri: Option<String>,
pub pair_dev: bool,
pub dry_run: bool,
pub shell_args: Vec<String>,
}
fn filter_platform_for_target(target: BuildTarget) -> Option<&'static str> {
match target {
BuildTarget::Web | BuildTarget::WebPkg => Some(WASM_TARGET),
BuildTarget::Macos => {
if env::consts::OS == "macos" { host_target_triple() } else { Some("aarch64-apple-darwin") }
}
BuildTarget::Linux => {
if env::consts::OS == "linux" { host_target_triple() } else { Some("x86_64-unknown-linux-gnu") }
}
BuildTarget::Windows => {
if env::consts::OS == "windows" { host_target_triple() } else { Some("x86_64-pc-windows-msvc") }
}
BuildTarget::IosSim => Some("aarch64-apple-ios-sim"),
BuildTarget::Android => Some("aarch64-linux-android"),
BuildTarget::RnPkg | BuildTarget::NitroUiPkg => None,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ResolvedBuildPlan {
pub target: BuildTarget,
pub shell: Option<HostShell>,
pub out_dir: PathBuf,
pub release: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum BuiltAppArtifact {
MacosApp { app_bundle: PathBuf, executable: PathBuf, dylib: PathBuf, bundle_id: String },
IosSimApp {
app_bundle: PathBuf,
executable: PathBuf,
dylib: Option<PathBuf>,
bundle_id: String,
},
DesktopStaged { shell_binary: PathBuf, app_dylib: PathBuf, shell: HostShell },
WebBundle { pwa_dir: PathBuf, extension_dir: Option<PathBuf> },
AndroidApk { apk_path: PathBuf, app_id: String, shell: AndroidShell },
}
pub(crate) fn resolve_target_and_shell(
target_opt: Option<&str>,
shell_opt: Option<&str>,
manifest: &NvManifest,
) -> Result<(BuildTarget, Option<HostShell>), String> {
let target = match target_opt {
Some(raw) => BuildTarget::parse(raw)?,
None => BuildTarget::host_default()?,
};
let explicit_shell = shell_opt.map(HostShell::parse).transpose()?;
let select = |manifest_default: Option<HostShell>,
fallback: HostShell,
allowed: &[HostShell],
expected: &str|
-> Result<HostShell, String> {
let chosen = explicit_shell.or(manifest_default).unwrap_or(fallback);
if !allowed.contains(&chosen) {
return Err(format!(
"--shell '{}' is not valid for --target {} (expected: {expected})",
chosen.as_str(),
target.as_str()
));
}
Ok(chosen)
};
let shell = match target {
BuildTarget::Macos => Some(select(
manifest.app.shell.macos.as_deref().map(HostShell::parse).transpose()?,
HostShell::Macos,
&[HostShell::Macos, HostShell::Skia],
"macos, skia",
)?),
BuildTarget::Linux => Some(select(
manifest.app.shell.linux.as_deref().map(HostShell::parse).transpose()?,
HostShell::Gtk,
&[HostShell::Gtk, HostShell::Qt, HostShell::Skia],
"gtk, qt, skia",
)?),
BuildTarget::Windows => Some(select(
manifest.app.shell.windows.as_deref().map(HostShell::parse).transpose()?,
HostShell::Windows,
&[HostShell::Windows, HostShell::Skia],
"windows, skia",
)?),
BuildTarget::Android => Some(select(
manifest.app.shell.android.map(|s| match s {
AndroidShell::View => HostShell::View,
AndroidShell::Compose => HostShell::Compose,
}),
HostShell::View,
&[HostShell::View, HostShell::Compose],
"view, compose",
)?),
BuildTarget::Web
| BuildTarget::IosSim
| BuildTarget::WebPkg
| BuildTarget::RnPkg
| BuildTarget::NitroUiPkg => {
if let Some(s) = explicit_shell {
return Err(format!(
"--shell '{}' is not applicable for --target {}",
s.as_str(),
target.as_str()
));
}
None
}
};
Ok((target, shell))
}
pub(crate) fn resolved_out_dir(
target_dir: &Path,
lib_name: &str,
target: BuildTarget,
shell: Option<HostShell>,
out_override: Option<&Path>,
cwd: &Path,
) -> PathBuf {
if let Some(custom) = out_override {
return absolutize_path_from(custom, cwd);
}
let root = if target.is_export_package() { "nv-packages" } else { "nv-apps" };
let seg = match shell {
Some(s) => format!("{}-{}", target.as_str(), s.as_str()),
None => target.as_str().to_owned(),
};
target_dir.join(root).join(lib_name).join(seg)
}
pub(crate) fn app_cdylib_spec(app: &AppContext, release: bool, suffix: &str) -> BuildArtifactSpec {
BuildArtifactSpec {
manifest_path: Some(app.manifest_path.clone()),
working_dir: app.manifest_dir.clone(),
package: app.package_name.clone(),
package_id: app.package_id.clone(),
artifact_name: app.lib_name.clone(),
kind: ArtifactKind::Cdylib,
crate_type_override: None,
target_triple: None,
no_default_features: false,
features: Vec::new(),
release,
locked: app.has_lockfile,
target_dir: Some(app.target_directory.clone()),
env: BTreeMap::new(),
expected_suffix: suffix.to_owned(),
}
}
pub(crate) fn app_wasm_spec(app: &AppContext, release: bool) -> BuildArtifactSpec {
BuildArtifactSpec {
manifest_path: Some(app.manifest_path.clone()),
working_dir: app.manifest_dir.clone(),
package: app.package_name.clone(),
package_id: app.package_id.clone(),
artifact_name: app.lib_name.clone(),
kind: ArtifactKind::Cdylib,
crate_type_override: None,
target_triple: Some(WASM_TARGET.to_owned()),
no_default_features: true,
features: vec!["web".to_owned()],
release,
locked: app.has_lockfile,
target_dir: Some(app.target_directory.clone()),
env: BTreeMap::new(),
expected_suffix: ".wasm".to_owned(),
}
}
fn ensure_matching_host_os(target: BuildTarget) -> Result<(), String> {
let required = match target {
BuildTarget::Macos | BuildTarget::IosSim => "macos",
BuildTarget::Linux => "linux",
BuildTarget::Windows => "windows",
_ => return Ok(()),
};
if env::consts::OS != required {
return Err(format!(
"cannot build native --target {} on host OS '{}' (use --dry-run to inspect the plan)",
target.as_str(),
env::consts::OS
));
}
Ok(())
}
fn require_sdk(sdk_root: Option<&NvSdkRoot>, target: BuildTarget) -> Result<&NvSdkRoot, String> {
sdk_root.ok_or_else(|| {
format!(
"NV SDK root is required for --target {} (run `nv sdk install`, pass --sdk-root <DIR>, or set NV_SDK_ROOT)",
target.as_str()
)
})
}
fn execute_build(
app: &AppContext,
sdk_root: Option<&NvSdkRoot>,
manifest: &NvManifest,
plan: &ResolvedBuildPlan,
pair_only: bool,
) -> Result<BuiltAppArtifact, String> {
match plan.target {
BuildTarget::IosSim => {
ensure_matching_host_os(BuildTarget::IosSim)?;
let sdk = require_sdk(sdk_root, plan.target)?;
let bundle = build_ios_sim_app(app, sdk, manifest, &plan.out_dir, plan.release, pair_only)?;
Ok(BuiltAppArtifact::IosSimApp {
app_bundle: bundle.app_bundle,
executable: bundle.executable_path,
dylib: bundle.dylib_path,
bundle_id: bundle.bundle_id,
})
}
BuildTarget::Android => {
let sdk = require_sdk(sdk_root, plan.target)?;
let shell = match plan.shell {
Some(HostShell::Compose) => AndroidShell::Compose,
_ => AndroidShell::View,
};
let built = build_android_apk(app, sdk, manifest, shell, &plan.out_dir, plan.release)?;
Ok(BuiltAppArtifact::AndroidApk {
apk_path: built.apk_path,
app_id: built.app_id,
shell: built.shell,
})
}
BuildTarget::WebPkg | BuildTarget::RnPkg | BuildTarget::NitroUiPkg => {
Err("export package targets are dispatched directly by run_build_command".to_owned())
}
BuildTarget::Web => {
let web = build_web_app(app, sdk_root, manifest, &plan.out_dir, plan.release)?;
Ok(BuiltAppArtifact::WebBundle {
pwa_dir: web.pwa_dir,
extension_dir: web.extension_dir,
})
}
BuildTarget::Macos => {
ensure_matching_host_os(BuildTarget::Macos)?;
let sdk = require_sdk(sdk_root, plan.target)?;
let shell = plan.shell.ok_or_else(|| "missing macOS host shell".to_owned())?;
println!("==> Building app cdylib '{}'...", app.package_name);
let dylib = build_artifact(&app_cdylib_spec(app, plan.release, env::consts::DLL_SUFFIX))?;
let host = ensure_host_shell(
sdk,
&app.target_directory,
shell,
plan.release,
&app.host_modules,
)?;
let info = app.manifest_app_info();
println!("==> Packaging macOS .app bundle...");
let bundle = package_macos_app_bundle(
&plan.out_dir,
manifest,
&info,
shell,
&host.binary_path,
&dylib,
)?;
Ok(BuiltAppArtifact::MacosApp {
app_bundle: bundle.app_bundle,
executable: bundle.executable_path,
dylib: bundle.dylib_path,
bundle_id: bundle.bundle_id,
})
}
BuildTarget::Linux | BuildTarget::Windows => {
ensure_matching_host_os(plan.target)?;
let sdk = require_sdk(sdk_root, plan.target)?;
let shell = plan.shell.ok_or_else(|| "missing desktop host shell".to_owned())?;
println!("==> Building app cdylib '{}'...", app.package_name);
let dylib = build_artifact(&app_cdylib_spec(app, plan.release, env::consts::DLL_SUFFIX))?;
let host = ensure_host_shell(
sdk,
&app.target_directory,
shell,
plan.release,
&app.host_modules,
)?;
fs::create_dir_all(&plan.out_dir)
.map_err(|e| format!("failed to create '{}': {e}", plan.out_dir.display()))?;
let shell_name = host
.binary_path
.file_name()
.ok_or_else(|| format!("invalid shell path '{}'", host.binary_path.display()))?;
let dylib_name = dylib
.file_name()
.ok_or_else(|| format!("invalid dylib path '{}'", dylib.display()))?;
let staged_shell = plan.out_dir.join(shell_name);
let staged_dylib = plan.out_dir.join(dylib_name);
copy_file_ensuring_parent(&host.binary_path, &staged_shell)?;
copy_file_ensuring_parent(&dylib, &staged_dylib)?;
if let Some(a11y_dll) = &host.a11y_dll_path
&& let Some(name) = a11y_dll.file_name()
{
copy_file_ensuring_parent(a11y_dll, &plan.out_dir.join(name))?;
}
Ok(BuiltAppArtifact::DesktopStaged {
shell_binary: staged_shell,
app_dylib: staged_dylib,
shell,
})
}
}
}
fn prepare_build_plan(
selector: &AppSelector,
target_opt: Option<&str>,
shell_opt: Option<&str>,
sdk_root_opt: Option<&Path>,
out_opt: Option<&Path>,
release: bool,
cwd: &Path,
) -> Result<(AppContext, Option<NvSdkRoot>, NvManifest, ResolvedBuildPlan), String> {
let target_pre = match target_opt {
Some(raw) => BuildTarget::parse(raw)?,
None => BuildTarget::host_default()?,
};
let (app, sdk_root) = if target_pre == BuildTarget::Web {
resolve_app_and_optional_sdk(
selector,
sdk_root_opt,
cwd,
filter_platform_for_target(target_pre),
)?
} else {
let (app, sdk) = resolve_app_and_sdk(
selector,
sdk_root_opt,
cwd,
filter_platform_for_target(target_pre),
)?;
(app, Some(sdk))
};
let manifest = NvManifest::load_for_dir(&app.manifest_dir).map_err(|e| e.to_string())?;
let (target, shell) = resolve_target_and_shell(target_opt, shell_opt, &manifest)?;
let out_dir =
resolved_out_dir(&app.target_directory, &app.lib_name, target, shell, out_opt, cwd);
let plan = ResolvedBuildPlan { target, shell, out_dir, release };
if target == BuildTarget::Android {
manifest.resolved_android_id(&app.manifest_app_info()).map_err(|e| e.to_string())?;
}
Ok((app, sdk_root, manifest, plan))
}
pub(crate) fn run_build_command(opts: AppBuildOptions, cwd: &Path) -> Result<String, String> {
if let Some(kit) = opts.kit.as_deref() {
if opts.app_path.is_some()
|| opts.package.is_some()
|| opts.target.is_some()
|| opts.shell.is_some()
{
return Err(
"--kit cannot be combined with APP_PATH, --package, --target, or --shell"
.to_owned(),
);
}
return super::export_pkg::kit_runtime::run_kit_runtime_build(
kit,
opts.platforms.as_deref(),
opts.release,
opts.out.as_deref(),
opts.sdk_root.as_deref(),
opts.dry_run,
cwd,
);
}
let selector = AppSelector { app_path: opts.app_path, package: opts.package };
let (app, sdk_root, manifest, plan) = prepare_build_plan(
&selector,
opts.target.as_deref(),
opts.shell.as_deref(),
opts.sdk_root.as_deref(),
opts.out.as_deref(),
opts.release,
cwd,
)?;
if plan.target.is_export_package() {
if plan.target == BuildTarget::WebPkg && opts.platforms.is_some() {
return Err("--platforms is only supported with --target rn-pkg or --target nitro-ui-pkg".to_owned());
}
let sdk = require_sdk(sdk_root.as_ref(), plan.target)?;
if opts.dry_run {
return format_export_plan(&app, sdk, &manifest, &plan, opts.platforms.as_deref());
}
let built =
build_export_package(&app, sdk, &manifest, &plan, opts.platforms.as_deref())?;
return Ok(built.format_summary());
}
if opts.platforms.is_some() {
return Err(format!(
"--platforms is only supported with --target rn-pkg or --target nitro-ui-pkg (got --target {})",
plan.target.as_str()
));
}
if opts.dry_run {
return Ok(format_app_plan(&app, sdk_root.as_ref(), &manifest, &plan, None));
}
let built = execute_build(&app, sdk_root.as_ref(), &manifest, &plan, false)?;
Ok(format_built_app_summary(&built))
}
pub(crate) fn run_run_command(mut opts: AppRunOptions, cwd: &Path) -> Result<String, String> {
let target_pre = match opts.target.as_deref() {
Some(raw) => BuildTarget::parse(raw)?,
None => BuildTarget::host_default()?,
};
if target_pre.is_export_package() {
return Err(format!(
"--target {} builds an embeddable package and cannot be launched with `nv run`; use `nv build --target {}`",
target_pre.as_str(),
target_pre.as_str()
));
}
if opts.device.is_some() && !matches!(target_pre, BuildTarget::IosSim | BuildTarget::Android) {
return Err(format!(
"--device is only supported with --target ios-sim or --target android (got --target {})",
target_pre.as_str()
));
}
if target_pre != BuildTarget::IosSim {
let ios_only_used =
opts.headless || opts.pair_only || opts.pair_uri.is_some() || opts.pair_dev;
if ios_only_used {
return Err(format!(
"--headless, --pair-only, --pair-uri, and --pair-dev are only supported with --target ios-sim (got --target {})",
target_pre.as_str()
));
}
}
let mut resolved_pair_uri = opts.pair_uri.clone();
if opts.pair_dev && !opts.dry_run {
let start_dir = match opts.app_path.as_deref() {
Some(p) => {
let abs = absolutize_path_from(p, cwd);
if abs.is_file() { abs.parent().unwrap_or(cwd).to_path_buf() } else { abs }
}
None => cwd.to_path_buf(),
};
let (ws_root, target_dir) =
crate::dev::session::fast_workspace_and_target_dir_from(&start_dir)
.ok_or_else(|| "could not locate workspace root for --pair-dev".to_owned())?;
let session = crate::dev::session::discover_live_session(
&target_dir,
&ws_root,
opts.package.as_deref(),
)?;
let uri = session.pair_uri.ok_or_else(|| {
"live `nv dev` session has no pair_uri; start it with `--pair`".to_owned()
})?;
resolved_pair_uri = Some(uri);
if opts.app_path.is_none() && opts.package.is_none() {
opts.package = Some(session.package);
}
}
let pair_only = opts.pair_only || opts.pair_dev || resolved_pair_uri.is_some();
let selector = AppSelector { app_path: opts.app_path, package: opts.package };
let (app, sdk_root, manifest, plan) = prepare_build_plan(
&selector,
opts.target.as_deref(),
opts.shell.as_deref(),
opts.sdk_root.as_deref(),
None,
opts.release,
cwd,
)?;
if opts.dry_run {
return Ok(format_app_plan(
&app,
sdk_root.as_ref(),
&manifest,
&plan,
Some(PlanRunOptions {
http_port: opts.http_port,
direct: opts.direct,
device: opts.device.as_deref(),
headless: opts.headless,
pair_only,
pair_uri: resolved_pair_uri.as_deref(),
shell_args: &opts.shell_args,
}),
));
}
let built = execute_build(&app, sdk_root.as_ref(), &manifest, &plan, pair_only)?;
match built {
BuiltAppArtifact::MacosApp { app_bundle, executable, .. } => {
launch_macos_app(
&app_bundle,
&executable,
should_direct_exec_macos(opts.direct, &opts.shell_args),
&opts.shell_args,
)?;
Ok(String::new())
}
BuiltAppArtifact::IosSimApp { app_bundle, bundle_id, .. } => {
launch_ios_sim_app(
&app_bundle,
&bundle_id,
opts.device.as_deref(),
opts.headless,
resolved_pair_uri.as_deref(),
&opts.shell_args,
)?;
Ok(String::new())
}
BuiltAppArtifact::DesktopStaged { shell_binary, app_dylib, shell } => {
let args = desktop_shell_launch_args(shell, &app_dylib, &manifest, &opts.shell_args);
println!("==> Launching {}...", shell_binary.display());
let status = Command::new(&shell_binary)
.args(&args)
.status()
.map_err(|e| format!("failed to spawn '{}': {e}", shell_binary.display()))?;
if !status.success() {
return Err(format!("app exited with {status}"));
}
Ok(String::new())
}
BuiltAppArtifact::WebBundle { pwa_dir, extension_dir } => {
serve_web_bundle(pwa_dir, extension_dir, &manifest.web.index, opts.http_port)?;
Ok(String::new())
}
BuiltAppArtifact::AndroidApk { apk_path, app_id, shell } => {
run_android_apk(&apk_path, &app_id, shell, opts.device.as_deref())?;
Ok(String::new())
}
}
}
pub(crate) fn cmd_build(opts: AppBuildOptions) {
let cwd = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
match run_build_command(opts, &cwd) {
Ok(report) => print!("{report}"),
Err(err) => {
eprintln!("error: {err}");
std::process::exit(1);
}
}
}
pub(crate) fn cmd_run(opts: AppRunOptions) {
let cwd = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
match run_run_command(opts, &cwd) {
Ok(report) => print!("{report}"),
Err(err) => {
eprintln!("error: {err}");
std::process::exit(1);
}
}
}