node-app-build 6.2.0

Mini app developer CLI: scaffold, validate, package node-app-* Debian packages
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
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! `node-app package` — build a `.deb` for a node mini-app.
//!
//! Supports three app types (controlled by `manifest.json#app_type`):
//!
//!   * **bun** (`--arch all`): stages `dist/index.js`, `manifest.json`,
//!     `package.json`, and any `manifest.nodeApp.privateRuntime` packages
//!     into `usr/lib/node/apps/<name>/`. Depends on `node-app-bun-runtime`.
//!
//!   * **native** (`--arch arm64|amd64`): stages the cross-compiled `.so`
//!     (from `target/node-app/<arch>/`) into `usr/lib/node/apps/<name>/`
//!     as the entrypoint filename. Depends on `node-runtime-abi-1`.
//!
//!   * **standalone** (`--arch arm64|amd64`): stages the cross-compiled
//!     binary into `usr/bin/node-app-<name>` (0755), a systemd unit into
//!     `lib/systemd/system/`, and maintainer scripts into `DEBIAN/`. No
//!     runtime `Depends:`; `node` is listed as `Recommends:`.
//!
//! **`has_ui` bundle staging** applies to bun and native fullstack apps:
//! their built `ui/dist` is staged into `usr/lib/node/apps/<name>/` and
//! served by the platform. Standalone apps serve their own UI and are not
//! staged here. Run `node-app build` (which also builds the UI) before
//! packaging.
//!
//! Two infrastructure features apply to all types:
//!
//!   1. **Docker fallback** for hosts without `dpkg-deb` (macOS, Windows).
//!      Selectable via `--docker {auto,force,never}`; `auto` picks
//!      container mode on non-Linux hosts.
//!   2. **GPG sidecar signing** of `manifest.json` → `manifest.json.sig`,
//!      written next to the `.deb` so apt.economy1.cloud's release flow
//!      can validate app provenance independently of the deb's own
//!      `dpkg-sig`. Opt-in via `--sign --gpg-key <ID>` (or `GPG_KEY` env).
//!
//! `--arch` accepts: `all` (bun only), `arm64`, or `amd64`.

use anyhow::{bail, Context, Result};
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::commands::{crossbuild, package_docker, package_sign};

/// Where to run `dpkg-deb`. Auto-detects from the host OS: Linux gets the
/// native path, everything else falls back to a container.
#[derive(clap::ValueEnum, Clone, Copy, Debug)]
pub enum DockerMode {
    /// Linux → native `dpkg-deb`; everything else → container.
    Auto,
    /// Always run `dpkg-deb` inside `debian:stable-slim`.
    Force,
    /// Never use Docker; require host `dpkg-deb` on PATH (Linux only).
    Never,
}

/// Render a `DEBIAN/control` file. `depends`/`recommends` are emitted only when
/// non-empty. `arch` is the Debian arch string (`all`, `arm64`, `amd64`).
fn control_file(
    name: &str,
    version: &str,
    arch: &str,
    maintainer: &str,
    depends: &[&str],
    recommends: &[&str],
    short_desc: &str,
) -> String {
    let mut s = format!(
        "Package: node-app-{name}\nVersion: {version}\nArchitecture: {arch}\nMaintainer: {maintainer}\n"
    );
    if !depends.is_empty() {
        s.push_str(&format!("Depends: {}\n", depends.join(", ")));
    }
    if !recommends.is_empty() {
        s.push_str(&format!("Recommends: {}\n", recommends.join(", ")));
    }
    s.push_str(&format!("Description: {short_desc}\n"));
    s
}

/// Pure size-cap predicate. Extracted so the boundary can be unit-tested
/// without producing a real `.deb` artifact.
#[inline]
fn deb_within_cap(size: u64) -> bool {
    const MAX_DEB_SIZE: u64 = 100 * 1024 * 1024;
    size <= MAX_DEB_SIZE
}

/// Finalize a staged tree into a `.deb`: build it, enforce the 100 MB size cap,
/// then optionally write the sidecar signature. Shared by all app types so every
/// arm gets identical size-guard + signing behavior.
#[allow(clippy::too_many_arguments)]
fn finalize_deb(
    staging: &Path,
    deb_path: &Path,
    docker: DockerMode,
    manifest_path: &Path,
    out: &Path,
    name: &str,
    version: &str,
    sign: bool,
    gpg_key: &Option<String>,
) -> Result<()> {
    build_deb(staging, deb_path, docker)?;
    let size = std::fs::metadata(deb_path)?.len();
    if !deb_within_cap(size) {
        bail!(
            "built .deb exceeds the 100 MB cap: {} bytes ({})",
            size,
            deb_path.display()
        );
    }
    println!("✓ packaged {} ({})", deb_path.display(), format_size(size));
    if sign {
        let key = gpg_key.clone().ok_or_else(|| {
            anyhow::anyhow!(
                "--sign requires --gpg-key <ID> (or set GPG_KEY env var). \
                 Run `gpg --list-secret-keys` to find a key ID."
            )
        })?;
        let sig_path = package_sign::sign_sidecar(manifest_path, out, name, version, &key)?;
        let sig_size = std::fs::metadata(&sig_path)?.len();
        println!(
            "✓ signed sidecar {} ({})",
            sig_path.display(),
            format_size(sig_size)
        );
    }
    Ok(())
}

/// Invoke `dpkg-deb --build` — natively on Linux, or via a `debian:stable-slim`
/// container otherwise. Behavior is identical to the inline branch it replaces.
fn build_deb(staging: &Path, deb_path: &Path, docker: DockerMode) -> Result<()> {
    let use_docker = match docker {
        DockerMode::Force => true,
        DockerMode::Never => false,
        DockerMode::Auto => !cfg!(target_os = "linux"),
    };

    if use_docker {
        package_docker::run_in_container(staging, deb_path)?;
    } else if cfg!(target_os = "linux") {
        let status = Command::new("dpkg-deb")
            .arg("--build")
            .arg(staging)
            .arg(deb_path)
            .status()
            .with_context(|| "failed to run `dpkg-deb` — is `dpkg-deb` on PATH?")?;
        if !status.success() {
            bail!("`dpkg-deb --build` failed");
        }
    } else {
        bail!(
            "node-app package on non-Linux requires Docker (auto-detected by default). \
             Pass --docker auto or --docker force; --docker never requires a Linux host \
             with `dpkg-deb` on PATH."
        );
    }
    Ok(())
}

/// Enforce the arch rule: bun → `all` only; native/standalone → arm64|amd64.
fn validate_arch_for_type(app_type: &str, arch: &str) -> Result<()> {
    match app_type {
        "bun" if arch == "all" => Ok(()),
        "bun" => bail!("bun apps are arch-agnostic; use --arch all"),
        "native" | "standalone" if arch == "all" => {
            bail!("{app_type} apps need --arch arm64 or amd64, not 'all'")
        }
        "native" | "standalone" => crossbuild::Arch::from_deb_arch(arch).map(|_| ()),
        other => bail!("unrecognized app_type: {other}"),
    }
}

/// Copy the built `.so` from `target/node-app/<arch>/<entrypoint>` into the
/// staging app dir as the entrypoint filename, chmod 644.
fn stage_native(
    project: &Path,
    app_root: &Path,
    manifest: &serde_json::Value,
    arch: crossbuild::Arch,
) -> Result<()> {
    let entrypoint = manifest
        .get("entrypoint")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("manifest.entrypoint missing"))?;
    let built = crossbuild::staged_artifact_dir(project, arch).join(entrypoint);
    if !built.exists() {
        bail!(
            "native artifact not found at {}. Run `node-app build --arch {}` first.",
            built.display(),
            arch.deb_arch()
        );
    }
    std::fs::create_dir_all(app_root)
        .with_context(|| format!("mkdir -p {}", app_root.display()))?;
    let dest = app_root.join(entrypoint);
    std::fs::copy(&built, &dest)
        .with_context(|| format!("stage {} -> {}", built.display(), dest.display()))?;
    let mut perms = std::fs::metadata(&dest)?.permissions();
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        perms.set_mode(0o644);
    }
    std::fs::set_permissions(&dest, perms).ok();
    Ok(())
}

/// Stage the built UI bundle (`ui_path`, default `ui/dist`) into the app dir.
///
/// No-op when `manifest.has_ui` is absent or `false`. Bails with a build
/// hint if `has_ui=true` but the bundle directory does not exist yet.
fn stage_ui(project: &Path, app_root: &Path, manifest: &serde_json::Value) -> Result<()> {
    if !manifest.get("has_ui").and_then(|v| v.as_bool()).unwrap_or(false) {
        return Ok(());
    }
    let ui_path = manifest.get("ui_path").and_then(|v| v.as_str()).unwrap_or("ui/dist");
    let src = project.join(ui_path);
    if !src.is_dir() {
        bail!("has_ui=true but UI bundle not found at {}. Run `node-app build` first.", src.display());
    }
    let dest = app_root.join(ui_path);
    copy_dir_recursive(&src, &dest)?;
    Ok(())
}

pub fn run(
    path: PathBuf,
    arch: String,
    out: PathBuf,
    docker: DockerMode,
    sign: bool,
    gpg_key: Option<String>,
) -> Result<()> {
    // 1. Read manifest (needed to determine app_type before arch validation).
    let manifest_path = path.join("manifest.json");
    let manifest_raw = std::fs::read_to_string(&manifest_path)
        .with_context(|| format!("manifest.json not found at {}", manifest_path.display()))?;
    let manifest: serde_json::Value = serde_json::from_str(&manifest_raw)
        .with_context(|| format!("manifest.json is not valid JSON: {}", manifest_path.display()))?;

    let app_type = manifest
        .get("app_type")
        .and_then(|v| v.as_str())
        .unwrap_or("bun")
        .to_string();

    let name = manifest
        .get("name")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("manifest.name missing"))?
        .to_string();
    let version = manifest
        .get("version")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("manifest.version missing"))?
        .to_string();
    let description = manifest
        .get("description")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string();
    let maintainer = manifest
        .get("maintainer")
        .and_then(|v| v.as_str())
        .unwrap_or("Unknown <unknown@example.com>")
        .to_string();

    // 2. Validate arch against app_type (replaces the old `if arch != "all"` guard).
    validate_arch_for_type(&app_type, &arch)?;

    // 3. Branch on app_type.
    match app_type.as_str() {
        "bun" => {
            run_bun(
                &path, &arch, &out, docker, sign, gpg_key,
                &manifest, &manifest_path, &name, &version, &description, &maintainer,
            )?;
        }
        "native" => {
            let a = crossbuild::Arch::from_deb_arch(&arch)?;
            run_native(
                &path, &out, docker, sign, gpg_key,
                &manifest, &manifest_path, &name, &version, &description, &maintainer, a,
            )?;
        }
        "standalone" => {
            let a = crossbuild::Arch::from_deb_arch(&arch)?;
            std::fs::create_dir_all(&out)
                .with_context(|| format!("mkdir -p {}", out.display()))?;
            let staging = out.join("staging");
            let _ = std::fs::remove_dir_all(&staging);
            stage_standalone(&path, &staging, &manifest, &name, a)?;
            let deps = crate::blueprint::apt_deps("standalone");
            let recs = crate::blueprint::recommends("standalone");
            let control = control_file(
                &name,
                &version,
                a.deb_arch(),
                &maintainer,
                deps,
                recs,
                description.lines().next().unwrap_or("").trim(),
            );
            std::fs::write(staging.join("DEBIAN/control"), control)
                .with_context(|| "write DEBIAN/control")?;
            let deb_path =
                out.join(format!("node-app-{}_{}_{}.deb", name, version, a.deb_arch()));
            finalize_deb(&staging, &deb_path, docker, &manifest_path, &out, &name, &version, sign, &gpg_key)?;
        }
        other => bail!("unsupported app_type: {other}"),
    }

    Ok(())
}

/// `daemon-reload` + `enable --now`, best-effort, exit 0, idempotent.
fn standalone_postinst(name: &str) -> String {
    format!(
        "#!/bin/sh\nset -e\ncase \"$1\" in\n  configure)\n    systemctl daemon-reload || true\n    systemctl enable --now node-app-{name}.service || true\n    ;;\nesac\nexit 0\n"
    )
}

fn standalone_prerm(name: &str) -> String {
    format!(
        "#!/bin/sh\nset -e\ncase \"$1\" in\n  remove|deconfigure)\n    systemctl stop node-app-{name}.service || true\n    ;;\nesac\nexit 0\n"
    )
}

fn standalone_postrm(name: &str) -> String {
    format!(
        "#!/bin/sh\nset -e\ncase \"$1\" in\n  remove|purge)\n    systemctl disable node-app-{name}.service || true\n    systemctl daemon-reload || true\n    ;;\nesac\nexit 0\n"
    )
}

fn stage_standalone(
    project: &Path,
    staging: &Path,
    _manifest: &serde_json::Value,
    name: &str,
    arch: crossbuild::Arch,
) -> Result<()> {
    // Binary → usr/bin/node-app-<name> (0755).
    let bin_name = format!("node-app-{name}");
    let built = crossbuild::staged_artifact_dir(project, arch).join(&bin_name);
    if !built.exists() {
        bail!(
            "standalone binary not found at {}. Run `node-app build --arch {}` first.",
            built.display(),
            arch.deb_arch()
        );
    }
    let bin_dir = staging.join("usr/bin");
    std::fs::create_dir_all(&bin_dir)?;
    let bin_dest = bin_dir.join(&bin_name);
    std::fs::copy(&built, &bin_dest)?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&bin_dest, std::fs::Permissions::from_mode(0o755))?;
    }

    // systemd unit (already placeholder-substituted by the scaffolder).
    let unit_src = project.join(format!("systemd/node-app-{name}.service"));
    if !unit_src.exists() {
        bail!("systemd unit not found at {}", unit_src.display());
    }
    let unit_dir = staging.join("lib/systemd/system");
    std::fs::create_dir_all(&unit_dir)?;
    std::fs::copy(&unit_src, unit_dir.join(format!("node-app-{name}.service")))?;

    // manifest.json under the app dir (for discovery/metadata).
    let app_root = staging.join(format!("usr/lib/node/apps/{name}"));
    std::fs::create_dir_all(&app_root)?;
    std::fs::copy(project.join("manifest.json"), app_root.join("manifest.json"))?;

    // Maintainer scripts (0755).
    let debian = staging.join("DEBIAN");
    std::fs::create_dir_all(&debian)?;
    for (file, body) in [
        ("postinst", standalone_postinst(name)),
        ("prerm", standalone_prerm(name)),
        ("postrm", standalone_postrm(name)),
    ] {
        let p = debian.join(file);
        std::fs::write(&p, body)?;
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755))?;
        }
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn run_bun(
    path: &Path,
    _arch: &str,
    out: &Path,
    docker: DockerMode,
    sign: bool,
    gpg_key: Option<String>,
    manifest: &serde_json::Value,
    manifest_path: &Path,
    name: &str,
    version: &str,
    description: &str,
    maintainer: &str,
) -> Result<()> {
    // Verify dist/index.js.
    let dist_index = path.join("dist/index.js");
    if !dist_index.exists() {
        bail!(
            "dist/index.js not found at {}. Run `node-app build` first.",
            dist_index.display()
        );
    }

    // Stage.
    std::fs::create_dir_all(out)
        .with_context(|| format!("mkdir -p {}", out.display()))?;
    let staging = out.join("staging");
    let _ = std::fs::remove_dir_all(&staging);
    let app_root = staging.join(format!("usr/lib/node/apps/{}", name));
    std::fs::create_dir_all(app_root.join("dist"))
        .with_context(|| format!("mkdir -p {}", app_root.join("dist").display()))?;
    std::fs::create_dir_all(staging.join("DEBIAN"))
        .with_context(|| format!("mkdir -p {}", staging.join("DEBIAN").display()))?;

    std::fs::copy(manifest_path, app_root.join("manifest.json"))
        .with_context(|| "copy manifest.json into staging")?;
    let pkg_json = path.join("package.json");
    if pkg_json.exists() {
        std::fs::copy(&pkg_json, app_root.join("package.json"))
            .with_context(|| "copy package.json into staging")?;
    }
    std::fs::copy(&dist_index, app_root.join("dist/index.js"))
        .with_context(|| "copy dist/index.js into staging")?;

    // Blueprint v2: stage private_modules/ from manifest.nodeApp.privateRuntime.
    // NO wholesale node_modules/ is copied — only the explicitly-declared
    // native runtime deps. Apps without a privateRuntime list get NO
    // private_modules/ directory in the .deb.
    let private_runtime: Vec<String> = manifest
        .get("nodeApp")
        .and_then(|n| n.get("privateRuntime"))
        .and_then(|v| v.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|v| v.as_str().map(String::from))
                .collect()
        })
        .unwrap_or_default();

    if !private_runtime.is_empty() {
        let pm_dir = app_root.join("private_modules");
        std::fs::create_dir_all(&pm_dir)
            .with_context(|| format!("mkdir -p {}", pm_dir.display()))?;
        for pkg in &private_runtime {
            let src = path.join("node_modules").join(pkg);
            if !src.exists() {
                bail!(
                    "manifest.nodeApp.privateRuntime declares `{}` but {} not found. \
                     Run `bun install` first.",
                    pkg,
                    src.display()
                );
            }
            let dst = pm_dir.join(pkg);
            copy_dir_recursive(&src, &dst).with_context(|| {
                format!("stage private_modules/{} from {}", pkg, src.display())
            })?;
        }
        println!(
            "✓ staged private_modules/ ({} packages: {})",
            private_runtime.len(),
            private_runtime.join(", ")
        );
    } else {
        println!("✓ no private_modules/ (manifest.nodeApp.privateRuntime is empty)");
    }

    // Stage UI bundle if has_ui=true.
    stage_ui(path, &app_root, manifest)?;

    // Generate DEBIAN/control.
    let deps = crate::blueprint::apt_deps("bun");
    let control = control_file(
        name,
        version,
        "all",
        maintainer,
        deps,
        &[],
        description.lines().next().unwrap_or("").trim(),
    );
    std::fs::write(staging.join("DEBIAN/control"), control)
        .with_context(|| "write DEBIAN/control")?;

    // Finalize: build .deb, enforce size cap, optionally sign.
    let deb_path = out.join(format!("node-app-{}_{}_all.deb", name, version));
    finalize_deb(&staging, &deb_path, docker, manifest_path, out, name, version, sign, &gpg_key)?;

    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn run_native(
    path: &Path,
    out: &Path,
    docker: DockerMode,
    sign: bool,
    gpg_key: Option<String>,
    manifest: &serde_json::Value,
    manifest_path: &Path,
    name: &str,
    version: &str,
    description: &str,
    maintainer: &str,
    a: crossbuild::Arch,
) -> Result<()> {
    // Stage.
    std::fs::create_dir_all(out)
        .with_context(|| format!("mkdir -p {}", out.display()))?;
    let staging = out.join("staging");
    let _ = std::fs::remove_dir_all(&staging);
    let app_root = staging.join(format!("usr/lib/node/apps/{}", name));
    std::fs::create_dir_all(staging.join("DEBIAN"))
        .with_context(|| format!("mkdir -p {}", staging.join("DEBIAN").display()))?;

    // Stage the built .so (reads from target/node-app/<arch>/<entrypoint>).
    stage_native(path, &app_root, manifest, a)?;

    // Copy manifest.json.
    std::fs::copy(manifest_path, app_root.join("manifest.json"))
        .with_context(|| "copy manifest.json into staging")?;

    // Stage UI bundle if has_ui=true.
    stage_ui(path, &app_root, manifest)?;

    // Generate DEBIAN/control.
    let deps = crate::blueprint::apt_deps("native");
    let control = control_file(
        name,
        version,
        a.deb_arch(),
        maintainer,
        deps,
        &[],
        description.lines().next().unwrap_or("").trim(),
    );
    std::fs::write(staging.join("DEBIAN/control"), control)
        .with_context(|| "write DEBIAN/control")?;

    // Finalize: build .deb, enforce size cap, optionally sign.
    let deb_path = out.join(format!("node-app-{}_{}_{}.deb", name, version, a.deb_arch()));
    finalize_deb(&staging, &deb_path, docker, manifest_path, out, name, version, sign, &gpg_key)?;

    Ok(())
}

fn format_size(bytes: u64) -> String {
    if bytes < 1024 {
        format!("{} B", bytes)
    } else if bytes < 1024 * 1024 {
        format!("{:.1} KB", bytes as f64 / 1024.0)
    } else {
        format!("{:.2} MB", bytes as f64 / 1024.0 / 1024.0)
    }
}

/// Recursive directory copy that preserves the source tree shape under `dst`.
/// Used to stage each `node_modules/<pkg>/` declared in
/// `manifest.nodeApp.privateRuntime` into `private_modules/<pkg>/`. Follows
/// no symlinks (a `bun install` tree should be self-contained), and creates
/// parent dirs lazily.
fn copy_dir_recursive(src: &Path, dst: &Path) -> Result<()> {
    let src_meta = std::fs::symlink_metadata(src)
        .with_context(|| format!("stat {}", src.display()))?;
    if src_meta.file_type().is_symlink() {
        // Cheap fallback: read the link target and copy what it points at.
        // node_modules/<pkg> can be a symlink in monorepos.
        let resolved = std::fs::canonicalize(src)
            .with_context(|| format!("resolve symlink {}", src.display()))?;
        return copy_dir_recursive(&resolved, dst);
    }
    if src_meta.is_file() {
        if let Some(parent) = dst.parent() {
            std::fs::create_dir_all(parent)
                .with_context(|| format!("mkdir -p {}", parent.display()))?;
        }
        std::fs::copy(src, dst)
            .with_context(|| format!("copy {} -> {}", src.display(), dst.display()))?;
        return Ok(());
    }
    if !src_meta.is_dir() {
        // Skip sockets / fifos — these don't belong in a .deb.
        return Ok(());
    }
    std::fs::create_dir_all(dst)
        .with_context(|| format!("mkdir -p {}", dst.display()))?;
    for entry in std::fs::read_dir(src)
        .with_context(|| format!("read_dir {}", src.display()))?
    {
        let entry = entry?;
        let name = entry.file_name();
        let from = src.join(&name);
        let to = dst.join(&name);
        copy_dir_recursive(&from, &to)?;
    }
    Ok(())
}

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

    #[test]
    fn size_cap_boundary() {
        const CAP: u64 = 100 * 1024 * 1024;
        assert!(deb_within_cap(0));
        assert!(deb_within_cap(CAP));
        assert!(!deb_within_cap(CAP + 1));
        assert!(!deb_within_cap(u64::MAX));
    }

    #[test]
    fn control_omits_empty_dep_lines_and_uses_node() {
        let c = control_file("foo", "0.1.0", "arm64", "Jane <j@x>", &[], &["node"], "desc");
        assert!(c.contains("Architecture: arm64"));
        assert!(!c.contains("Depends:"));
        assert!(c.contains("Recommends: node"));
        assert!(!c.contains("econ-v1"));

        let c2 = control_file("foo", "0.1.0", "all", "Jane <j@x>", &["node-app-bun-runtime"], &[], "desc");
        assert!(c2.contains("Depends: node-app-bun-runtime"));
        assert!(!c2.contains("Recommends:"));
    }

    #[test]
    fn arch_rules_per_app_type() {
        assert!(validate_arch_for_type("bun", "all").is_ok());
        assert!(validate_arch_for_type("bun", "arm64").is_err());
        assert!(validate_arch_for_type("native", "all").is_err());
        assert!(validate_arch_for_type("native", "arm64").is_ok());
        assert!(validate_arch_for_type("standalone", "amd64").is_ok());
    }

    #[test]
    fn maintainer_scripts_target_the_named_service() {
        let pi = standalone_postinst("foo");
        assert!(pi.starts_with("#!/bin/sh"));
        assert!(pi.contains("enable --now node-app-foo.service"));
        assert!(standalone_prerm("foo").contains("stop node-app-foo.service"));
        assert!(standalone_postrm("foo").contains("disable node-app-foo.service"));
        for s in [standalone_postinst("foo"), standalone_prerm("foo"), standalone_postrm("foo")] {
            assert!(!s.contains("econ-v1"));
        }
    }

    #[test]
    fn stage_standalone_lays_out_bin_unit_and_scripts() {
        let proj = tempfile::tempdir().unwrap();
        let arch = crossbuild::Arch::Amd64;
        std::fs::create_dir_all(crossbuild::staged_artifact_dir(proj.path(), arch)).unwrap();
        std::fs::write(
            crossbuild::staged_artifact_dir(proj.path(), arch).join("node-app-foo"),
            b"bin",
        )
        .unwrap();
        std::fs::create_dir_all(proj.path().join("systemd")).unwrap();
        std::fs::write(proj.path().join("systemd/node-app-foo.service"), "[Unit]\n").unwrap();
        std::fs::write(proj.path().join("manifest.json"), "{\"name\":\"foo\"}").unwrap();
        let staging = proj.path().join("staging");
        let manifest = serde_json::json!({"name":"foo"});
        stage_standalone(proj.path(), &staging, &manifest, "foo", arch).unwrap();
        assert!(staging.join("usr/bin/node-app-foo").exists());
        assert!(staging.join("lib/systemd/system/node-app-foo.service").exists());
        assert!(staging.join("DEBIAN/postinst").exists());
    }

    #[test]
    fn stage_native_copies_so_as_entrypoint() {
        let proj = tempfile::tempdir().unwrap();
        let arch = crossbuild::Arch::Arm64;
        let art = crossbuild::staged_artifact_dir(proj.path(), arch);
        std::fs::create_dir_all(&art).unwrap();
        std::fs::write(art.join("libfoo.so"), b"\x7fELF-fake").unwrap();
        let manifest: serde_json::Value = serde_json::json!({"entrypoint": "libfoo.so"});
        let app_root = proj.path().join("staging/usr/lib/node/apps/foo");
        stage_native(proj.path(), &app_root, &manifest, arch).unwrap();
        assert!(app_root.join("libfoo.so").exists());
    }

    #[test]
    fn stage_ui_noop_without_has_ui_and_copies_when_set() {
        let proj = tempfile::tempdir().unwrap();
        let app_root = proj.path().join("app");
        stage_ui(proj.path(), &app_root, &serde_json::json!({})).unwrap(); // no-op
        std::fs::create_dir_all(proj.path().join("ui/dist")).unwrap();
        std::fs::write(proj.path().join("ui/dist/index.html"), "<html>").unwrap();
        stage_ui(proj.path(), &app_root, &serde_json::json!({"has_ui": true})).unwrap();
        assert!(app_root.join("ui/dist/index.html").exists());
    }
}