node-app-build 6.4.3

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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
//! `node-app new [name] --profile <profile>` — embedded-fixture scaffolding.
//!
//! This is the new (phase 2 of econ-v1/node#868) codepath that scaffolds a
//! fresh node-app from a profile fixture set embedded into the binary at
//! compile time via `include_dir!`. It is intentionally separate from the
//! legacy GitHub-template-cloning code in `commands::new`:
//!
//! - **Legacy `commands::new`** (`--type <kind>`): clones a template repo
//!   from GitHub (or a local dir), strips variants the caller didn't ask
//!   for, optionally `gh repo create`s a new GitHub repo. Powers the
//!   interactive wizard.
//! - **This module** (`--profile <profile>`): writes fixture files embedded
//!   into the CLI binary, with `{{...}}` placeholder substitution. No
//!   network, no `gh`, no `git`. Deterministic and fast.
//!
//! Key design choices baked into the default `bun` profile (phase 2) and
//! carried into the rest of phase 4ab (`bun-fullstack`, `native`,
//! `native-fullstack`, plus the `standalone-*` escape hatches):
//!
//! 1. `bun` and `bun-fullstack` set `manifest.app_type = "bun"`, NOT
//!    `"standalone"`. Every Bun app scaffolded this way is therefore
//!    eligible for the shared Bun runtime at install time
//!    (econ-v1/node#810). The legacy `node-app-template-bun` defaults to
//!    `"standalone"`, which is explicitly outside `BunLoader`'s control —
//!    flipping that default is what makes shared-runtime adoption scale
//!    beyond the 4 in-monorepo apps.
//! 2. `manifest.nodeApp.blueprint` is pinned to `">=1"`. When blueprint v2
//!    ships (phase 5 of #868), `node-app audit` will tell the maintainer
//!    what they need to bump.
//! 3. `standalone-*` profiles emit a **friction prompt** before scaffolding
//!    — they are an explicit escape hatch (own systemd unit, NOT
//!    shared-runtime eligible), not a default-suitable choice. Bypass with
//!    `--yes` for CI / scripted use.
//!
//! Placeholder substitution is naive string replace — no template engine
//! dependency. Supported placeholders: `{{name}}`, `{{description}}`,
//! `{{author}}`, `{{author_email}}`. Substitution applies to BOTH file
//! contents AND file/directory names (so `systemd/node-app-{{name}}.service`
//! renames at scaffold time).

use anyhow::{bail, Context, Result};
use include_dir::{include_dir, Dir, DirEntry};
use std::io::Write;
use std::path::{Path, PathBuf};

// ── Embedded profile trees ────────────────────────────────────────────────────
//
// Each profile is a sibling directory under `profiles/` checked into the repo.
// `include_dir!` recursively walks the tree at compile time and bakes every
// file's contents into the binary as a `&'static [u8]`. Adding a new profile
// is: drop a directory under `profiles/`, add a const here, add a `Profile`
// variant, and wire it up in `Profile::embedded()`.

static PROFILE_BUN: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/profiles/bun");
static PROFILE_BUN_STAGE: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/profiles/bun-stage");
static PROFILE_STAGE: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/profiles/stage");
static PROFILE_BUN_FULLSTACK: Dir<'_> =
    include_dir!("$CARGO_MANIFEST_DIR/profiles/bun-fullstack");
static PROFILE_NATIVE: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/profiles/native");
static PROFILE_NATIVE_FULLSTACK: Dir<'_> =
    include_dir!("$CARGO_MANIFEST_DIR/profiles/native-fullstack");
static PROFILE_STANDALONE_BUN: Dir<'_> =
    include_dir!("$CARGO_MANIFEST_DIR/profiles/standalone-bun");
static PROFILE_STANDALONE_NATIVE: Dir<'_> =
    include_dir!("$CARGO_MANIFEST_DIR/profiles/standalone-native");

// ── Profile enum ──────────────────────────────────────────────────────────────

/// Which profile to scaffold from. `bun` is the default; the other variants
/// land in phase 4ab/4b of econ-v1/node#868.
#[derive(Debug, Copy, Clone, PartialEq, Eq, clap::ValueEnum)]
pub enum Profile {
    /// Platform-loaded Bun TypeScript app. Default. Eligible for the shared
    /// Bun runtime out of the box.
    Bun,
    /// Platform-loaded Bun app with a framework-free stage UI compiled to a
    /// browser ES module.
    BunStage,
    /// Platform-loaded Bun app whose UI is a stage: a framework-free ES
    /// module that mounts directly into the client-node PWA shell, with a
    /// heavily-commented, self-stamping teaching template (one live
    /// `ctx.invokeCapability` example, one commented `ctx.liveQuery`
    /// example, and a `ui/scripts/stamp-integrity.mjs` build step that
    /// fills in `manifest.json`'s `ui.integrity`).
    Stage,
    /// Platform-loaded Bun TS app **plus** a React + Vite UI bundle served
    /// by the platform's reverse-proxy. Shared-runtime eligible.
    BunFullstack,
    /// Native Rust cdylib loaded in-process by the platform via `dlopen`.
    /// Shared runtime does not apply (Bun-only feature).
    Native,
    /// Native cdylib **plus** a React + Vite UI bundle. Shared runtime
    /// does not apply (Bun-only feature).
    NativeFullstack,
    /// Standalone systemd-managed Bun daemon. ESCAPE HATCH — NOT eligible
    /// for the shared Bun runtime because the platform's `BunLoader` does
    /// not own its lifecycle. Use only when you genuinely need your own
    /// systemd unit. Friction-prompted at scaffold time.
    StandaloneBun,
    /// Standalone systemd-managed Rust daemon. ESCAPE HATCH —
    /// friction-prompted at scaffold time.
    StandaloneNative,
}

impl Profile {
    fn embedded(self) -> &'static Dir<'static> {
        match self {
            Profile::Bun => &PROFILE_BUN,
            Profile::BunStage => &PROFILE_BUN_STAGE,
            Profile::Stage => &PROFILE_STAGE,
            Profile::BunFullstack => &PROFILE_BUN_FULLSTACK,
            Profile::Native => &PROFILE_NATIVE,
            Profile::NativeFullstack => &PROFILE_NATIVE_FULLSTACK,
            Profile::StandaloneBun => &PROFILE_STANDALONE_BUN,
            Profile::StandaloneNative => &PROFILE_STANDALONE_NATIVE,
        }
    }

    fn label(self) -> &'static str {
        match self {
            Profile::Bun => "bun",
            Profile::BunStage => "bun-stage",
            Profile::Stage => "stage",
            Profile::BunFullstack => "bun-fullstack",
            Profile::Native => "native",
            Profile::NativeFullstack => "native-fullstack",
            Profile::StandaloneBun => "standalone-bun",
            Profile::StandaloneNative => "standalone-native",
        }
    }

    /// `standalone-*` profiles prompt the operator before scaffolding —
    /// they're an explicit escape hatch, not a default-suitable choice.
    fn requires_friction_confirm(self) -> bool {
        matches!(self, Profile::StandaloneBun | Profile::StandaloneNative)
    }

    /// Whether the profile's `manifest.app_type` is `"bun"` (and therefore
    /// eligible for the shared Bun runtime). Used by the friction prompt
    /// copy to recommend the right alternative.
    fn alternative_for_friction(self) -> &'static str {
        match self {
            Profile::StandaloneBun => "--profile bun",
            Profile::StandaloneNative => "--profile native",
            _ => "--profile bun",
        }
    }
}

// ── Substitutions ─────────────────────────────────────────────────────────────

/// Values to substitute into the fixture's `{{...}}` placeholders. Applied
/// to both file contents and file/directory names.
#[derive(Debug)]
struct Substitutions {
    name: String,
    description: String,
    author: String,
    author_email: String,
}

impl Substitutions {
    fn apply(&self, content: &str) -> String {
        content
            .replace("{{name}}", &self.name)
            .replace("{{description}}", &self.description)
            .replace("{{author}}", &self.author)
            .replace("{{author_email}}", &self.author_email)
    }
}

// ── Entry point ───────────────────────────────────────────────────────────────

/// Scaffold args used by `commands::new_profile::run`. Kept as a struct so
/// future profile-specific knobs (e.g. `--with-ui`) don't make the function
/// signature explode.
#[derive(Debug)]
pub struct ProfileScaffoldArgs {
    pub name: String,
    pub profile: Profile,
    pub output_dir: Option<PathBuf>,
    pub description: Option<String>,
    pub author: Option<String>,
    pub author_email: Option<String>,
    pub force: bool,
    /// Bypass the standalone-profile friction prompt (CI / scripted use).
    pub yes: bool,
}

/// Entry point dispatched from `main.rs` when `--profile` is supplied.
pub fn run(args: ProfileScaffoldArgs) -> Result<()> {
    validate_name(&args.name)?;

    // Standalone profiles ask for confirmation before scaffolding so a
    // maintainer who reaches for `--profile standalone-bun` by reflex sees
    // exactly why it's an escape hatch and what the better default is.
    if args.profile.requires_friction_confirm() && !args.yes
        && !confirm_standalone(args.profile)? {
        println!("Aborted.");
        return Ok(());
    }

    let target = args
        .output_dir
        .clone()
        .unwrap_or_else(|| PathBuf::from(&args.name));

    // Refuse to overwrite an existing dir unless --force was passed.
    // (`--force` only allows scaffolding *into* an existing dir; it does
    // not remove its contents. We just write our files over the top.)
    if target.exists() && !args.force {
        bail!(
            "target directory already exists: {} (use --force to overwrite)",
            target.display()
        );
    }

    let subs = Substitutions {
        name: args.name.clone(),
        description: args
            .description
            .unwrap_or_else(|| format!("A node-app: {}", args.name)),
        author: args.author.unwrap_or_default(),
        author_email: args.author_email.unwrap_or_default(),
    };

    std::fs::create_dir_all(&target)
        .with_context(|| format!("create target dir {}", target.display()))?;
    write_dir(&target, args.profile.embedded(), &subs)?;

    println!(
        "✓ scaffolded {} ({} profile) at {}",
        args.name,
        args.profile.label(),
        target.display()
    );
    println!();
    println!("Next steps:");
    println!("  cd {}", target.display());
    match args.profile {
        Profile::Bun
        | Profile::BunStage
        | Profile::Stage
        | Profile::BunFullstack
        | Profile::StandaloneBun => {
            println!("  bun install");
        }
        Profile::Native | Profile::NativeFullstack | Profile::StandaloneNative => {
            println!("  cargo check");
        }
    }
    if args.profile == Profile::Stage {
        // A fresh stage ships `ui.integrity: {}` and an unbuilt `ui/dist` —
        // `bun run build` (root script) chains the backend bundle and the
        // UI build, stamping `ui.integrity` in the process. Without it,
        // the first `node-app audit`/`node-app dev` sideload fails. See
        // docs/development/BUILD_A_STAGE.md.
        println!("  bun run build        # stamps manifest.json's ui.integrity");
    }
    println!("  node-app audit       # check this app against the blueprint");
    println!("  node-app dev         # hot-reload dev loop");
    Ok(())
}

// ── Friction prompt for standalone profiles ───────────────────────────────────

fn confirm_standalone(profile: Profile) -> Result<bool> {
    println!();
    println!("⚠ You're scaffolding a STANDALONE app.");
    println!();
    println!("  Standalone apps run as their own systemd unit. They are explicitly");
    println!(
        "  EXCLUDED from the shared Bun runtime memory-saving feature (econ-v1/node#810)"
    );
    println!("  because the platform's BunLoader does not own their lifecycle.");
    println!();
    println!("  Use standalone only when you genuinely need:");
    println!("    - Own systemd unit (LCD daemons, OTA controllers, hardware bridges)");
    println!("    - Independent process lifecycle the platform shouldn't own");
    println!();
    println!(
        "  For most apps, prefer {} instead.",
        profile.alternative_for_friction()
    );
    println!();
    print!("  Continue with standalone? [y/N] ");
    std::io::stdout().flush().context("flush stdout")?;

    let mut answer = String::new();
    std::io::stdin()
        .read_line(&mut answer)
        .context("read confirmation")?;
    Ok(matches!(answer.trim().to_lowercase().as_str(), "y" | "yes"))
}

// ── Name validation ───────────────────────────────────────────────────────────

/// Strict: lowercase letters, digits, hyphens. Must start with a letter, must
/// not end with a hyphen, and must contain no double-hyphens. Matches the
/// manifest schema's `name` regex (without the optional publisher prefix —
/// we don't support that here).
fn validate_name(name: &str) -> Result<()> {
    if name.is_empty() {
        bail!("name must not be empty");
    }
    let bytes = name.as_bytes();
    if !bytes[0].is_ascii_lowercase() {
        bail!(
            "name must start with a lowercase letter (got {:?}); use lowercase letters, digits, and hyphens only",
            name
        );
    }
    for &b in bytes {
        let ok = b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-';
        if !ok {
            bail!(
                "name must contain only lowercase letters, digits, and hyphens (got {:?})",
                name
            );
        }
    }
    if name.ends_with('-') {
        bail!("name must not end with a hyphen (got {:?})", name);
    }
    if name.contains("--") {
        bail!("name must not contain consecutive hyphens (got {:?})", name);
    }
    Ok(())
}

// ── Tree walker ───────────────────────────────────────────────────────────────

const CARGO_MANIFEST_TEMPLATE: &str = "Cargo.toml.template";

fn rendered_fixture_basename(basename: &str, subs: &Substitutions) -> String {
    if basename == CARGO_MANIFEST_TEMPLATE {
        "Cargo.toml".to_string()
    } else {
        subs.apply(basename)
    }
}

/// Recursively write `dir` to `dest`, substituting placeholders in BOTH file
/// contents AND file/directory names. `dir.path()` returns paths relative to
/// the embed root, so we strip to the basename before joining onto `dest` at
/// each level.
///
/// Filename substitution is required by the `standalone-*` profiles, whose
/// systemd unit ships as `systemd/node-app-{{name}}.service` in the fixture
/// tree and lands as `systemd/node-app-<name>.service` on disk.
fn write_dir(dest: &Path, dir: &Dir<'_>, subs: &Substitutions) -> Result<()> {
    for entry in dir.entries() {
        match entry {
            DirEntry::Dir(subdir) => {
                let basename = subdir
                    .path()
                    .file_name()
                    .with_context(|| format!("embedded subdir has no basename: {:?}", subdir.path()))?
                    .to_str()
                    .with_context(|| format!("embedded subdir basename is not UTF-8: {:?}", subdir.path()))?;
                let rendered_basename = subs.apply(basename);
                let subdest = dest.join(&rendered_basename);
                std::fs::create_dir_all(&subdest)
                    .with_context(|| format!("create {}", subdest.display()))?;
                write_dir(&subdest, subdir, subs)?;
            }
            DirEntry::File(file) => {
                let basename = file
                    .path()
                    .file_name()
                    .with_context(|| format!("embedded file has no basename: {:?}", file.path()))?
                    .to_str()
                    .with_context(|| format!("embedded file basename is not UTF-8: {:?}", file.path()))?;
                let rendered_basename = rendered_fixture_basename(basename, subs);
                let path = dest.join(&rendered_basename);
                let raw = file.contents();
                // All current fixture files are UTF-8 text. If a future profile
                // ever adds a binary asset (icon, etc.), branch here and write
                // bytes verbatim with no substitution.
                let content = std::str::from_utf8(raw).with_context(|| {
                    format!("embedded file {:?} is not UTF-8", file.path())
                })?;
                let rendered = subs.apply(content);
                std::fs::write(&path, rendered)
                    .with_context(|| format!("write {}", path.display()))?;
            }
        }
    }
    Ok(())
}

// ── Tests ─────────────────────────────────────────────────────────────────────

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

    #[test]
    fn name_validation_accepts_simple() {
        assert!(validate_name("foo").is_ok());
        assert!(validate_name("foo-bar").is_ok());
        assert!(validate_name("foo123").is_ok());
        assert!(validate_name("a").is_ok());
    }

    #[test]
    fn name_validation_rejects_bad() {
        assert!(validate_name("").is_err());
        assert!(validate_name("Foo").is_err());
        assert!(validate_name("foo_bar").is_err());
        assert!(validate_name("123foo").is_err());
        assert!(validate_name("foo-").is_err());
        assert!(validate_name("-foo").is_err());
        assert!(validate_name("foo--bar").is_err());
        assert!(validate_name("foo bar").is_err());
        assert!(validate_name("foo.bar").is_err());
    }

    #[test]
    fn substitution_replaces_all_placeholders() {
        let subs = Substitutions {
            name: "my-app".to_string(),
            description: "A test app".to_string(),
            author: "Daisy".to_string(),
            author_email: "daisy@example.com".to_string(),
        };
        let input = "name={{name}} desc={{description}} who={{author}}<{{author_email}}>";
        let got = subs.apply(input);
        assert_eq!(
            got,
            "name=my-app desc=A test app who=Daisy<daisy@example.com>"
        );
    }

    #[test]
    fn bun_profile_fixture_has_required_files() {
        // Sanity check that include_dir! actually picked everything up at
        // compile time. If the fixture tree drifts (file renamed/removed),
        // we want a loud test failure before the scaffold ever runs.
        let dir = PROFILE_BUN.entries();
        let names: Vec<_> = dir
            .iter()
            .filter_map(|e| e.path().file_name().and_then(|s| s.to_str()))
            .collect();
        for required in [
            "manifest.json",
            "package.json",
            "node-app.toml",
            "AGENTS.md",
            "README.md",
            ".gitignore",
            "src",
        ] {
            assert!(
                names.contains(&required),
                "embedded bun profile missing {:?}; got {:?}",
                required,
                names
            );
        }
    }

    #[test]
    fn bun_profile_manifest_has_no_unsubstituted_placeholders_after_render() {
        // End-to-end: render the manifest with realistic substitutions, then
        // confirm no `{{` brace pair remains. Catches a missing placeholder
        // in the substitution table.
        let subs = Substitutions {
            name: "demo-app".to_string(),
            description: "demo".to_string(),
            author: "T".to_string(),
            author_email: "t@example.com".to_string(),
        };
        let manifest = PROFILE_BUN
            .get_file("manifest.json")
            .expect("manifest.json must exist in embedded bun profile");
        let content = std::str::from_utf8(manifest.contents()).unwrap();
        let rendered = subs.apply(content);
        assert!(
            !rendered.contains("{{"),
            "rendered manifest still contains an unsubstituted placeholder:\n{}",
            rendered
        );
        // And the literal app_type=bun must survive — the entire point.
        assert!(
            rendered.contains("\"app_type\": \"bun\""),
            "rendered manifest must keep app_type=bun:\n{}",
            rendered
        );
    }

    #[test]
    fn bun_fullstack_profile_has_ui_directory_and_has_ui_flag() {
        // The whole point of the -fullstack profiles is the embedded UI.
        let ui_pkg = PROFILE_BUN_FULLSTACK
            .get_file("ui/package.json")
            .expect("bun-fullstack profile must ship ui/package.json");
        let content = std::str::from_utf8(ui_pkg.contents()).unwrap();
        assert!(
            content.contains("\"react\""),
            "bun-fullstack ui/package.json must depend on React"
        );

        let manifest = PROFILE_BUN_FULLSTACK
            .get_file("manifest.json")
            .expect("bun-fullstack profile must ship manifest.json");
        let manifest_str = std::str::from_utf8(manifest.contents()).unwrap();
        assert!(
            manifest_str.contains("\"has_ui\": true"),
            "bun-fullstack manifest must set has_ui=true"
        );
        assert!(
            manifest_str.contains("\"app_type\": \"bun\""),
            "bun-fullstack manifest must keep app_type=bun (shared-runtime eligible)"
        );
    }

    #[test]
    fn bun_stage_profile_is_framework_free_and_stage_shaped() {
        let ui_pkg = PROFILE_BUN_STAGE
            .get_file("ui/package.json")
            .expect("bun-stage profile must ship ui/package.json");
        let content = std::str::from_utf8(ui_pkg.contents()).unwrap();
        assert!(
            !content.contains("\"react\"") && !content.contains("\"vue\""),
            "bun-stage ui/package.json must not depend on React or Vue"
        );

        let manifest = PROFILE_BUN_STAGE
            .get_file("manifest.json")
            .expect("bun-stage profile must ship manifest.json");
        let manifest_str = std::str::from_utf8(manifest.contents()).unwrap();
        assert!(manifest_str.contains("\"kind\": \"stage\""));
        assert!(manifest_str.contains("\"entry\": \"ui/dist/main.js\""));
        assert!(manifest_str.contains("\"has_ui\": true"));
        assert!(
            !manifest_str.contains("\"integrity\""),
            "bun-stage manifest must leave ui.integrity for staged generation only"
        );
    }

    #[test]
    fn stage_profile_is_framework_free_and_ships_placeholder_integrity() {
        let ui_pkg = PROFILE_STAGE
            .get_file("ui/package.json")
            .expect("stage profile must ship ui/package.json");
        let content = std::str::from_utf8(ui_pkg.contents()).unwrap();
        assert!(
            !content.contains("\"react\"") && !content.contains("\"vue\""),
            "stage ui/package.json must not depend on React or Vue"
        );
        assert!(
            content.contains("stamp-integrity.mjs"),
            "stage ui/package.json build script must wire in the integrity stamping step"
        );

        let manifest = PROFILE_STAGE
            .get_file("manifest.json")
            .expect("stage profile must ship manifest.json");
        let manifest_str = std::str::from_utf8(manifest.contents()).unwrap();
        assert!(manifest_str.contains("\"kind\": \"stage\""));
        assert!(manifest_str.contains("\"entry\": \"ui/dist/main.js\""));
        assert!(manifest_str.contains("\"has_ui\": true"));
        assert!(
            manifest_str.contains("\"integrity\": {}"),
            "stage manifest must ship an explicit (empty) ui.integrity placeholder that \
             `ui/scripts/stamp-integrity.mjs` fills in on build:\n{}",
            manifest_str
        );

        assert!(
            PROFILE_STAGE
                .get_file("ui/scripts/stamp-integrity.mjs")
                .is_some(),
            "stage profile must ship ui/scripts/stamp-integrity.mjs"
        );
    }

    #[test]
    fn stage_profile_manifest_has_no_unsubstituted_placeholders_after_render() {
        let subs = Substitutions {
            name: "demo-stage".to_string(),
            description: "demo".to_string(),
            author: "T".to_string(),
            author_email: "t@example.com".to_string(),
        };
        for path in [
            "manifest.json",
            "package.json",
            "src/index.ts",
            "ui/package.json",
            "ui/src/main.ts",
        ] {
            let file = PROFILE_STAGE
                .get_file(path)
                .unwrap_or_else(|| panic!("stage profile must ship {}", path));
            let content = std::str::from_utf8(file.contents()).unwrap();
            let rendered = subs.apply(content);
            assert!(
                !rendered.contains("{{"),
                "rendered {} still contains an unsubstituted placeholder:\n{}",
                path,
                rendered
            );
        }
    }

    #[test]
    fn native_profile_manifest_uses_native_app_type() {
        let manifest = PROFILE_NATIVE
            .get_file("manifest.json")
            .expect("native profile must ship manifest.json");
        let content = std::str::from_utf8(manifest.contents()).unwrap();
        assert!(
            content.contains("\"app_type\": \"native\""),
            "native manifest must set app_type=native"
        );
    }

    #[test]
    fn native_profile_has_cargo_and_lib_rs() {
        assert!(
            PROFILE_NATIVE.get_file(CARGO_MANIFEST_TEMPLATE).is_some(),
            "native profile must ship a Cargo manifest template"
        );
        assert!(
            PROFILE_NATIVE.get_file("src/lib.rs").is_some(),
            "native profile must ship src/lib.rs"
        );
    }

    #[test]
    fn native_profile_ships_release_workflow_and_deb_metadata() {
        // The native profile is what extracted-repo cdylib node-apps
        // (notifications, memory, ldk-node, …) get scaffolded from. Without
        // these two pieces every maintainer has to hand-author the .deb
        // build pipeline, which is exactly what the embedded scaffold is
        // supposed to remove.
        let workflow = PROFILE_NATIVE
            .get_file(".github/workflows/release.yml")
            .expect("native profile must ship .github/workflows/release.yml");
        let workflow_str = std::str::from_utf8(workflow.contents()).unwrap();
        assert!(
            workflow_str.contains("cargo deb"),
            "release workflow must invoke cargo deb"
        );
        assert!(
            workflow_str.contains("aarch64-unknown-linux-gnu"),
            "release workflow must cross-build for arm64"
        );
        assert!(
            workflow_str.contains("econ-v1/node-releases"),
            "release workflow must dispatch the apt-repo aggregator"
        );

        let cargo = PROFILE_NATIVE
            .get_file(CARGO_MANIFEST_TEMPLATE)
            .expect("native profile must ship a Cargo manifest template");
        let cargo_str = std::str::from_utf8(cargo.contents()).unwrap();
        assert!(
            cargo_str.contains("[package.metadata.deb]"),
            "native Cargo.toml must declare [package.metadata.deb] for cargo-deb"
        );
        assert!(
            cargo_str.contains("node-runtime-abi-1"),
            "native cargo-deb metadata must depend on node-runtime-abi-1"
        );
        assert!(
            cargo_str.contains("libnode_app_{{name}}.so"),
            "native cargo-deb assets must stage libnode_app_<name>.so"
        );
        assert!(
            cargo_str.contains("usr/lib/node/apps/{{name}}/"),
            "native cargo-deb assets must install under /usr/lib/node/apps/<name>/"
        );
    }

    #[test]
    fn native_profile_cargo_renders_placeholders_in_deb_metadata() {
        // End-to-end: scaffold-time substitution must reach the cargo-deb
        // assets path and maintainer field — otherwise `cargo deb` will look
        // for a literal `libnode_app_{{name}}.so` and fail.
        let subs = Substitutions {
            name: "myapp".to_string(),
            description: "A test app".to_string(),
            author: "Test Author".to_string(),
            author_email: "test@example.com".to_string(),
        };
        let cargo = PROFILE_NATIVE.get_file(CARGO_MANIFEST_TEMPLATE).unwrap();
        let rendered = subs.apply(std::str::from_utf8(cargo.contents()).unwrap());
        assert!(
            !rendered.contains("{{"),
            "rendered Cargo.toml still contains an unsubstituted placeholder:\n{}",
            rendered
        );
        assert!(
            rendered.contains("libnode_app_myapp.so"),
            "rendered Cargo.toml must reference libnode_app_myapp.so:\n{}",
            rendered
        );
        assert!(
            rendered.contains("usr/lib/node/apps/myapp/"),
            "rendered Cargo.toml must reference usr/lib/node/apps/myapp/:\n{}",
            rendered
        );
        assert!(
            rendered.contains("Test Author <test@example.com>"),
            "rendered Cargo.toml must carry the maintainer:\n{}",
            rendered
        );
    }

    #[test]
    fn native_fullstack_profile_has_ui_and_lib_rs() {
        assert!(
            PROFILE_NATIVE_FULLSTACK.get_file("src/lib.rs").is_some(),
            "native-fullstack profile must ship src/lib.rs"
        );
        assert!(
            PROFILE_NATIVE_FULLSTACK
                .get_file("ui/package.json")
                .is_some(),
            "native-fullstack profile must ship ui/package.json"
        );
        let manifest = PROFILE_NATIVE_FULLSTACK
            .get_file("manifest.json")
            .expect("native-fullstack must ship manifest.json");
        let content = std::str::from_utf8(manifest.contents()).unwrap();
        assert!(
            content.contains("\"has_ui\": true"),
            "native-fullstack manifest must set has_ui=true"
        );
        assert!(
            content.contains("\"app_type\": \"native\""),
            "native-fullstack manifest must keep app_type=native"
        );
    }

    #[test]
    fn standalone_profiles_have_systemd_unit() {
        // Standalone profiles ship a systemd unit with `{{name}}` in the
        // filename — this is the load-bearing case for filename substitution
        // in write_dir().
        let unit_bun = PROFILE_STANDALONE_BUN
            .get_file("systemd/node-app-{{name}}.service");
        assert!(
            unit_bun.is_some(),
            "standalone-bun profile must ship systemd/node-app-{{{{name}}}}.service"
        );
        let unit_native = PROFILE_STANDALONE_NATIVE
            .get_file("systemd/node-app-{{name}}.service");
        assert!(
            unit_native.is_some(),
            "standalone-native profile must ship systemd/node-app-{{{{name}}}}.service"
        );
    }

    #[test]
    fn standalone_profiles_use_standalone_app_type() {
        for (label, profile_dir) in [
            ("standalone-bun", &PROFILE_STANDALONE_BUN),
            ("standalone-native", &PROFILE_STANDALONE_NATIVE),
        ] {
            let manifest = profile_dir
                .get_file("manifest.json")
                .unwrap_or_else(|| panic!("{} must ship manifest.json", label));
            let content = std::str::from_utf8(manifest.contents()).unwrap();
            assert!(
                content.contains("\"app_type\": \"standalone\""),
                "{} manifest must set app_type=standalone, got:\n{}",
                label,
                content
            );
        }
    }

    #[test]
    fn standalone_profiles_require_friction_confirm() {
        assert!(Profile::StandaloneBun.requires_friction_confirm());
        assert!(Profile::StandaloneNative.requires_friction_confirm());
        assert!(!Profile::Bun.requires_friction_confirm());
        assert!(!Profile::BunFullstack.requires_friction_confirm());
        assert!(!Profile::Native.requires_friction_confirm());
        assert!(!Profile::NativeFullstack.requires_friction_confirm());
    }

    #[test]
    fn filename_placeholder_substitution() {
        // The substitution logic must rewrite `{{name}}` in filenames at
        // scaffold time — exercised by the standalone profiles' systemd unit.
        let subs = Substitutions {
            name: "my-app".to_string(),
            description: "demo".to_string(),
            author: "T".to_string(),
            author_email: "t@example.com".to_string(),
        };
        let rendered = subs.apply("node-app-{{name}}.service");
        assert_eq!(rendered, "node-app-my-app.service");
    }

    #[test]
    fn cargo_manifest_template_is_materialized_as_cargo_toml() {
        let subs = Substitutions {
            name: "my-app".to_string(),
            description: "demo".to_string(),
            author: "T".to_string(),
            author_email: "t@example.com".to_string(),
        };

        assert_eq!(
            rendered_fixture_basename("Cargo.toml.template", &subs),
            "Cargo.toml"
        );
    }

    #[test]
    fn native_profile_writes_a_real_cargo_manifest() {
        let temp = tempfile::tempdir().unwrap();
        let subs = Substitutions {
            name: "my-app".to_string(),
            description: "demo".to_string(),
            author: "T".to_string(),
            author_email: "t@example.com".to_string(),
        };

        write_dir(temp.path(), &PROFILE_NATIVE, &subs).unwrap();

        assert!(temp.path().join("Cargo.toml").is_file());
        assert!(!temp.path().join(CARGO_MANIFEST_TEMPLATE).exists());
    }
}