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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
//! Unified `nv build` and `nv run` pipeline for desktop (macOS, Linux, Windows), iOS Simulator, Android, and Web apps.

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";

/// First-class `nv build` / `nv run` target platforms.
#[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",
        }
    }
}

/// CLI options for `nv build`.
#[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,
}

/// CLI options for `nv run`.
#[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,
    }
}

/// Resolved target + shell + output directory for a build or run invocation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct ResolvedBuildPlan {
    pub target: BuildTarget,
    pub shell: Option<HostShell>,
    pub out_dir: PathBuf,
    pub release: bool,
}

/// Concrete artifacts emitted by a live `nv build`.
#[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 },
}

/// Resolves the target shell (explicit CLI `--shell` > `nativeview.toml [app.shell]` > OS default) and
/// validates target/shell compatibility.
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))
}

/// Computes the per-app output directory (`--out` or `<target_dir>/nv-{apps,packages}/<lib_name>/<seg>/`).
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);
        }
    }
}