nsh-cli 0.7.1

The nsh command line tool: build, package and run apps.
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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
//! `nsh test`: runs an app's test files (`*.test.tsx`, `*.test.ts`, which
//! import `nsh/test`) headless, each on an engine of its own, and says how
//! each test ended (`nsh-testing` runs them). Given an app's entry instead,
//! it opens the app as a test would and takes the steps standard input
//! gives (`await app.press("Add")`); `--trace` prints the mount batches of
//! the apps under their steps.
//!
//! An app this command line serves runs in its process. An app with Rust
//! crates of its own runs in the headless runner built with them
//! (`rust_app.rs`, `nsh_testing::runner`), which asks this process to build
//! each entry ([`RunnerMessage::Build`]): the runner links no bundler. On a
//! real platform (`--target`) the apps run in its hosts, built with the
//! app's crates (`test_host.rs`), and the test files in this process.
//!
//! Given a directory of an app with Rust crates of its own (`nsh.json`
//! `"rust"`), the crates in it are tested first with `cargo test`, each in
//! its own directory ([`cargo_test`]): their results are shown and counted
//! with the TypeScript tests', so a Rust app without test files is tested
//! too. Their tests run on this machine: with `--target` only the test
//! files run.

use std::{
    collections::HashMap,
    io::{BufRead as _, BufReader, IsTerminal as _, Read as _, Write as _},
    path::{Path, PathBuf},
    process::{Command, Stdio},
    sync::{Arc, Mutex},
    time::Instant,
};

use anyhow::{Context as _, bail};
use nsh_bundler::BundleOptions;
use nsh_core::element::description::SetDescription;
use nsh_engine::Bundle;
use nsh_testing::{
    Built, Entry, Reply, RunnerMessage, SCREEN_TEXT_LIMIT, TestRequest, TestResult, TestRun,
    TestStatus, screen_texts,
};

use crate::{
    build::BuildError,
    logger,
    rust_app::{AppCrate, RustApp},
    ui,
};

/// How long the app runs after it opened before the steps of standard
/// input: long enough for the engine's idle collection (every second at
/// most), so what the app keeps alive shows in a trace.
const IDLE_MS: u32 = 1200;

/// Runs the tests `path` names, of the app whose entry is `entry`: a test
/// file, the test files in a directory (an app's), or an app's entry with
/// the steps standard input gives.
#[allow(
    clippy::too_many_arguments,
    reason = "the flags of `nsh test`, one each"
)]
pub(crate) fn test(
    path: &Path,
    entry: &Path,
    filter: Option<String>,
    release: bool,
    trace: bool,
    fps: bool,
    junit: Option<&Path>,
    jobs: Option<std::num::NonZeroUsize>,
    target: Option<crate::run::Target>,
    browser: Option<&Path>,
    web_host: Option<PathBuf>,
    device: Option<&str>,
    display: Option<usize>,
    foreground: bool,
) -> anyhow::Result<()> {
    let app_dir = nsh_bundler::app_dir::app_dir_of(entry);
    let work_dir = app_dir.join(".nsh/test");
    // The app's crates in the directory, which `cargo test` tests.
    let crates: Vec<AppCrate> = match crate::rust_app::current() {
        Some(app) if path.is_dir() => app
            .crates()
            .iter()
            .filter(|c| c.dir().starts_with(path))
            .cloned()
            .collect(),
        _ => Vec::new(),
    };
    let files = if is_test_file(path) {
        vec![path.to_owned()]
    } else if path.is_dir() {
        let mut files = Vec::new();
        find_tests(&test_root(path), &mut files);
        files.sort();
        if files.is_empty() && (crates.is_empty() || target.is_some()) {
            bail!(
                "no test files in {}: tests are `*.test.tsx` / `*.test.ts` files importing nsh/test{}",
                ui::path(path),
                if crates.is_empty() {
                    ""
                } else {
                    ", and the crates' Rust tests run without --target"
                }
            );
        }
        files
    } else {
        vec![steps_file(&work_dir, path)?]
    };
    // How the files are shown: an entry's steps by the entry.
    let shown = |file: &Path| {
        if file.starts_with(&work_dir) {
            ui::path(path)
        } else {
            ui::path(file)
        }
    };
    let start = Instant::now();
    let mut tally = Tally::default();
    if browser.is_some() && target.is_none() {
        bail!("--browser goes with --target web");
    }
    if device.is_some()
        && !matches!(
            target,
            Some(crate::run::Target::Ios | crate::run::Target::Android)
        )
    {
        bail!("--device goes with --target ios or android");
    }
    if display.is_some() && !target.is_some_and(crate::test_host::opens_on_a_display) {
        bail!("{}", crate::test_host::DISPLAY_TARGETS);
    }
    if foreground && !target.is_some_and(crate::test_host::runs_in_background) {
        bail!("{}", crate::test_host::FOREGROUND_TARGETS);
    }
    if web_host.is_some() && target.is_some() {
        bail!(
            "--web-host goes with headless runs: --target web takes nsh.json's web.host, the other targets have no page host"
        );
    }
    if release {
        // The app's crates and NSH's in the headless runner and development
        // hosts, optimized as in a package.
        crate::rust_app::set_release_hosts();
    }
    // The page's host of headless runs: `--web-host`, else nsh.json's.
    // Absolute: an app's headless runner opens it too.
    let page_host = match web_host {
        Some(module) => Some(
            dunce::canonicalize(&module)
                .with_context(|| format!("the web host module {}", ui::path(&module)))?,
        ),
        None if target.is_none() => crate::package::read_config(entry)?
            .web
            .host
            .map(|host| crate::package::web_host_module(entry, &host))
            .transpose()?,
        None => None,
    };
    if !crates.is_empty() {
        if target.is_some() {
            ui::note("the crates' Rust tests (`cargo test`) run without --target");
        } else {
            for krate in &crates {
                cargo_test(krate, filter.as_deref(), release, &mut tally);
            }
        }
    }
    let host = target
        .filter(|_| !files.is_empty())
        .map(|target| {
            crate::test_host::starter(
                target, browser, &work_dir, fps, device, display, foreground, release,
            )
        })
        .transpose()?;
    // What `open` checks its options against on that host.
    let host_target = target
        .filter(|_| host.is_some())
        .map(crate::test_host::host_target);
    // On a real platform the apps run in hosts built with the app's crates:
    // the test files run here, whatever the app is.
    match crate::rust_app::current().filter(|_| host.is_none()) {
        _ if files.is_empty() => {}
        Some(app) => {
            let request = TestRequest {
                protocol: nsh_testing::PROTOCOL,
                bytecode_version: nsh_js::BYTECODE_VERSION.to_owned(),
                files,
                work_dir: work_dir.clone(),
                filter,
                trace,
                verbose: ui::verbose(),
                page_host,
            };
            in_runner(&app, &request, release, &shown, &mut tally)?;
        }
        None => {
            let run = TestRun {
                ui_sets: crate::own_sets().to_vec(),
                compile: compiler(release),
                work_dir: work_dir.clone(),
                filter,
                trace: trace.then(|| Arc::new(Mutex::new(Box::new(std::io::stdout()) as _))),
                host,
                target: host_target,
                page_host,
            };
            // A host, or a trace, takes one file at a time.
            let jobs = if run.host.is_some() || trace {
                1
            } else {
                jobs.or_else(|| std::thread::available_parallelism().ok())
                    .map_or(1, std::num::NonZeroUsize::get)
            };
            run_files(&run, &files, jobs, &shown, &mut tally);
        }
    }
    crate::test_web::close();
    if let Some(report) = junit {
        std::fs::write(report, tally.junit(start.elapsed()))
            .with_context(|| format!("write {}", ui::path(report)))?;
    }
    let total = tally.passed + tally.failed + tally.skipped + tally.todo;
    let mut counts = format!("{} passed, {} failed", tally.passed, tally.failed);
    if tally.skipped > 0 {
        counts.push_str(&format!(", {} skipped", tally.skipped));
    }
    if tally.todo > 0 {
        counts.push_str(&format!(", {} todo", tally.todo));
    }
    let summary = format!(
        "{total} {}: {counts} {}",
        if total == 1 { "test" } else { "tests" },
        ui::dim(format!("({})", ui::duration(start.elapsed())))
    );
    if tally.failed > 0 {
        bail!(summary);
    }
    ui::done(summary);
    Ok(())
}

/// Runs the test files `files` as `run` says, `jobs` at a time, showing
/// each one's results as it ends: in order, a file's once those before it
/// were shown.
fn run_files(
    run: &nsh_testing::TestRun,
    files: &[PathBuf],
    jobs: usize,
    shown: &dyn Fn(&Path) -> String,
    tally: &mut Tally,
) {
    if jobs <= 1 || files.len() <= 1 {
        for file in files {
            let shown = shown(file);
            let ran = nsh_testing::run_file(run, file, &mut |result| {
                tally.show(&shown, result);
            });
            if let Err(e) = ran {
                tally.failed(&shown, &e);
            }
        }
        return;
    }
    let next = std::sync::atomic::AtomicUsize::new(0);
    let (done, ended) = std::sync::mpsc::channel();
    std::thread::scope(|scope| {
        for _ in 0..jobs.min(files.len()) {
            let done = done.clone();
            let next = &next;
            scope.spawn(move || {
                loop {
                    let n = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                    let Some(file) = files.get(n) else { break };
                    let ran = nsh_testing::run_file(run, file, &mut |_| {});
                    if done.send((n, ran)).is_err() {
                        break;
                    }
                }
            });
        }
        drop(done);
        let mut waiting = HashMap::new();
        let mut shown_up_to = 0;
        for (n, ran) in ended {
            waiting.insert(n, ran);
            while let Some(ran) = waiting.remove(&shown_up_to) {
                let shown = shown(&files[shown_up_to]);
                match ran {
                    Ok(results) => results.iter().for_each(|r| tally.show(&shown, r)),
                    Err(e) => tally.failed(&shown, &e),
                }
                shown_up_to += 1;
            }
        }
    });
}

/// How the tests ended so far, by file.
#[derive(Default)]
struct Tally {
    passed: usize,
    failed: usize,
    skipped: usize,
    todo: usize,
    /// The files shown, in order, with their results, or why one could not
    /// run.
    files: Vec<(String, Vec<TestResult>, Option<String>)>,
}

impl Tally {
    /// Shows how a test of the file shown as `file` ended, and counts it.
    fn show(&mut self, file: &str, result: &TestResult) {
        show(file, result);
        self.count(file, result);
    }

    /// Counts how a test of the file shown as `file` ended, without showing
    /// it.
    fn count(&mut self, file: &str, result: &TestResult) {
        match result.status {
            TestStatus::Passed => self.passed += 1,
            TestStatus::Skipped => self.skipped += 1,
            TestStatus::Todo => self.todo += 1,
            TestStatus::Failed => self.failed += 1,
        }
        self.file(file).1.push(result.clone());
    }

    /// The test file shown as `file` could not run: it counts as a failure.
    fn failed(&mut self, file: &str, message: &str) {
        self.failed += 1;
        ui::error(format!("{file}: {message}"));
        self.file(file).2 = Some(message.to_owned());
    }

    fn file(&mut self, file: &str) -> &mut (String, Vec<TestResult>, Option<String>) {
        let at = match self.files.iter().position(|(f, ..)| f == file) {
            Some(at) => at,
            None => {
                self.files.push((file.to_owned(), Vec::new(), None));
                self.files.len() - 1
            }
        };
        &mut self.files[at]
    }

    /// The results as a JUnit XML report: a `testsuite` per file, a
    /// `testcase` per test, a file that could not run as an `error`.
    fn junit(&self, elapsed: std::time::Duration) -> String {
        use std::fmt::Write as _;
        let seconds = |d: std::time::Duration| format!("{:.3}", d.as_secs_f64());
        let mut suites = String::new();
        let (mut tests, mut failures, mut errors, mut skipped) = (0, 0, 0, 0);
        for (file, results, error) in &self.files {
            let failed = results
                .iter()
                .filter(|r| r.status == TestStatus::Failed)
                .count();
            let skips = results
                .iter()
                .filter(|r| matches!(r.status, TestStatus::Skipped | TestStatus::Todo))
                .count();
            let errs = usize::from(error.is_some());
            let time: std::time::Duration = results.iter().map(|r| r.elapsed).sum();
            tests += results.len() + errs;
            failures += failed;
            errors += errs;
            skipped += skips;
            let file = xml(file);
            let _ = writeln!(
                suites,
                "  <testsuite name=\"{file}\" tests=\"{}\" failures=\"{failed}\" errors=\"{errs}\" \
                 skipped=\"{skips}\" time=\"{}\">",
                results.len() + errs,
                seconds(time)
            );
            for result in results {
                let _ = write!(
                    suites,
                    "    <testcase classname=\"{file}\" name=\"{}\" time=\"{}\"",
                    xml(&result.name),
                    seconds(result.elapsed)
                );
                match (&result.status, &result.failure) {
                    (TestStatus::Skipped, _) => {
                        suites.push_str(">\n      <skipped/>\n    </testcase>\n")
                    }
                    (TestStatus::Todo, _) => {
                        suites.push_str(">\n      <skipped message=\"todo\"/>\n    </testcase>\n");
                    }
                    (_, Some(failure)) => {
                        let mut text = failure.message.clone();
                        if let Some(stack) = &failure.stack {
                            text.push('\n');
                            text.push_str(stack);
                        }
                        if let Some(screen) = &failure.screen {
                            // The report is read by tools: it is cut even
                            // with `-v`, which is for the terminal.
                            let texts = screen_texts(screen, Some(SCREEN_TEXT_LIMIT));
                            text.push_str(&format!("\non screen: {texts}"));
                        }
                        let message = failure.message.lines().next().unwrap_or_default();
                        let _ = write!(
                            suites,
                            ">\n      <failure message=\"{}\">{}</failure>\n    </testcase>\n",
                            xml(message),
                            xml(&text)
                        );
                    }
                    _ => suites.push_str("/>\n"),
                }
            }
            if let Some(error) = error {
                let _ = write!(
                    suites,
                    "    <testcase classname=\"{file}\" name=\"{file}\" time=\"0.000\">\n      \
                     <error message=\"{}\">{}</error>\n    </testcase>\n",
                    xml(error.lines().next().unwrap_or_default()),
                    xml(error)
                );
            }
            suites.push_str("  </testsuite>\n");
        }
        format!(
            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\
             <testsuites name=\"nsh test\" tests=\"{tests}\" failures=\"{failures}\" errors=\"{errors}\" \
             skipped=\"{skipped}\" time=\"{}\">\n{suites}</testsuites>\n",
            seconds(elapsed)
        )
    }
}

/// `text` as XML text or an attribute's value: escaped, without the
/// control characters XML 1.0 refuses.
fn xml(text: &str) -> String {
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            '"' => out.push_str("&quot;"),
            '\'' => out.push_str("&apos;"),
            '\n' => out.push_str("&#10;"),
            '\t' | '\r' => out.push(c),
            c if (c as u32) < 0x20 => {}
            c => out.push(c),
        }
    }
    out
}

/// Runs `request` in the headless runner of the app with Rust crates
/// `app`: builds the entries it asks for, shows its results and its log.
fn in_runner(
    app: &RustApp,
    request: &TestRequest,
    release: bool,
    shown: &dyn Fn(&Path) -> String,
    tally: &mut Tally,
) -> anyhow::Result<()> {
    let runner = app.test_runner()?;
    let mut child = Command::new(&runner)
        .arg(serde_json::to_string(request)?)
        .stdin(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .with_context(|| format!("run {}", runner.display()))?;
    let mut input = child.stdin.take().context("the runner's standard input")?;
    let stderr = child.stderr.take().context("the runner's standard error")?;
    let mut builds = 0;
    for line in BufReader::new(stderr).lines() {
        let line = line?;
        match RunnerMessage::parse(&line) {
            Some(RunnerMessage::Log {
                level,
                target,
                message,
            }) => {
                let level = level.parse().unwrap_or(log::Level::Info);
                logger::forward(level, &target, &message);
            }
            Some(RunnerMessage::Build { entry, kind }) => {
                builds += 1;
                let reply = build_for_runner(&entry, kind, &request.work_dir, builds, release);
                writeln!(input, "{}", serde_json::to_string(&reply)?)
                    .context("answer the runner")?;
            }
            Some(RunnerMessage::Result { file, result }) => tally.show(&shown(&file), &result),
            Some(RunnerMessage::Failed { file, message }) => {
                tally.failed(&shown(&file), &message);
            }
            None => ui::plain(line),
        }
    }
    let status = child.wait()?;
    if !status.success() {
        bail!(
            "the headless runner {} exited with {status}",
            ui::path(&runner)
        );
    }
    Ok(())
}

/// Builds `entry` for the app's runner, the `n`th build of the run: its
/// files in `work_dir`, or the app's root.
fn build_for_runner(entry: &Path, kind: Entry, work_dir: &Path, n: usize, release: bool) -> Reply {
    let built = (|| -> anyhow::Result<Reply> {
        let (bytecode, map, capabilities, links, main_window, application, asset_root) = match kind
        {
            Entry::TestFile => test_file_bytecode(entry)?,
            Entry::App => {
                let entry = crate::entry::resolve(entry)?;
                if crate::rust_app::is_root(&entry) {
                    return Ok(Reply::Root);
                }
                bytecode_of(&entry, &crate::ui_sets(), true, release)?
            }
        };
        let dir = work_dir.join("build");
        std::fs::create_dir_all(&dir).with_context(|| format!("{}", dir.display()))?;
        let file = dir.join(format!("{n}.nshc"));
        std::fs::write(&file, bytecode).with_context(|| format!("write {}", file.display()))?;
        let source_map = match map {
            Some(map) => {
                let path = dir.join(format!("{n}.js.map"));
                std::fs::write(&path, map).with_context(|| format!("write {}", path.display()))?;
                Some(path)
            }
            None => None,
        };
        Ok(Reply::Js {
            bytecode: file,
            source_map,
            capabilities,
            links,
            main_window,
            application,
            asset_root: Some(asset_root),
        })
    })();
    built.unwrap_or_else(|e| Reply::Failed {
        message: crate::ui::with_details(&e),
    })
}

/// The entry made for a test file, bundled against the app's sets and
/// `nsh/test`, and compiled. Test files always keep debug info so failure
/// stacks report exact source locations.
fn test_file_bytecode(entry: &Path) -> anyhow::Result<Compiled> {
    let mut sets = crate::ui_sets().to_vec();
    sets.extend(
        nsh_testing::test_sets()
            .iter()
            .flat_map(nsh_core::element::Registry::sets)
            .map(SetDescription::from),
    );
    bytecode_of(entry, &sets, false, false)
}

/// A compiled entry: its bytecode, its source map, the capabilities
/// (JSON), links and main window's launch options (JSON) its
/// `nsh.json` declares, which the app runs under, as on a device, and the
/// directory its assets are named from (`nsh_bundler::Bundle::asset_root`).
type Compiled = (
    Vec<u8>,
    Option<String>,
    Option<String>,
    nsh_core::url_scheme::AppLinks,
    Option<String>,
    Option<String>,
    PathBuf,
);

/// `entry` bundled against `sets` and compiled to bytecode, with its
/// source map, declared capabilities, links and main window's launch
/// options; `announce`: saying so; `release`: minify and strip debug info.
fn bytecode_of(
    entry: &Path,
    sets: &[SetDescription],
    announce: bool,
    release: bool,
) -> anyhow::Result<Compiled> {
    let bundle = nsh_bundler::bundle(&BundleOptions {
        entry: entry.to_path_buf(),
        minify: release,
        split: false,
        ui_sets: sets.to_vec(),
        development: !release,
        ..Default::default()
    })
    .map_err(|e| BuildError::from(e).into_error(entry))?;
    if announce {
        ui::done(format!(
            "bundled {} {}",
            ui::path(entry),
            ui::dim(format!(
                "({} B in {:.1} ms)",
                bundle.code.len(),
                bundle.elapsed_ms
            ))
        ));
    }
    let bytecode = nsh_js::compile_bytecode_with(&bundle.code, release, sets)?;
    let capabilities = bundle.capabilities.map(|c| c.to_json().to_string());
    Ok((
        bytecode,
        bundle.source_map,
        capabilities,
        bundle.links,
        bundle.main_window,
        bundle.application,
        bundle.asset_root,
    ))
}

/// Prints how a test of the file shown as `file` ended: a line, and for a
/// failure what was thrown, where, and what was on screen.
fn show(file: &str, result: &TestResult) {
    // `cargo test` does not time its tests: theirs show no time.
    let line = if result.elapsed.is_zero() {
        format!("{file} › {}", result.name)
    } else {
        format!(
            "{file} › {} {}",
            result.name,
            ui::dim(format!("({})", ui::duration(result.elapsed)))
        )
    };
    let failure = match (result.status, &result.failure) {
        (TestStatus::Skipped, _) => {
            ui::plain(format!("{} {line} {}", ui::dim("â—‹"), ui::dim("skipped")));
            return;
        }
        (TestStatus::Todo, _) => {
            ui::plain(format!(
                "{} {file} › {} {}",
                ui::yellow("✎"),
                result.name,
                ui::yellow("todo")
            ));
            return;
        }
        (_, Some(failure)) => failure,
        (_, None) => {
            ui::done(line);
            return;
        }
    };
    ui::plain(format!("{} {line}", ui::red("✗")));
    for text in failure.message.lines() {
        ui::detail(format!("  {text}"));
    }
    if let Some(stack) = &failure.stack {
        // The frames in the test file: the runtime's own say nothing.
        for frame in stack.lines().filter(|l| !l.contains("(native)")) {
            ui::detail(ui::dim(format!("  {}", frame.trim_start())));
        }
    }
    // A step's error says what is on screen already, cut to a few KB; `-v`
    // shows all of it.
    if let Some(screen) = failure
        .screen
        .as_ref()
        .filter(|_| ui::verbose() || !failure.message.contains("on screen: "))
    {
        let texts = screen_texts(screen, screen_limit());
        ui::detail(format!("  on screen: {texts}"));
    }
}

/// How much of a failure's texts on screen to show: a few KB, all of them
/// with `-v` (a failure is read, not a document's whole text).
fn screen_limit() -> Option<usize> {
    (!ui::verbose()).then_some(SCREEN_TEXT_LIMIT)
}

/// Tests the app's crate `krate` with `cargo test --no-fail-fast` (with
/// `--release` when `release` is set, and only the tests whose name contains
/// `filter`, if given) in its directory, and shows and counts each test it
/// ran, under the file of its test target.
/// A run that fails with no test failing (the tests do not build, a test
/// binary crashed) counts as a failure of the crate, with cargo's output.
fn cargo_test(krate: &AppCrate, filter: Option<&str>, release: bool, tally: &mut Tally) {
    let step = ui::Step::start(format!(
        "testing {}{}",
        krate.package(),
        if release { " (release build)" } else { "" }
    ));
    let mut cmd = cargo_test_command(krate, filter, release);
    let ran = ui::capture_all(&mut cmd, |line| {
        let line = line.trim_start();
        if let Some(rest) = line.strip_prefix("Compiling ") {
            step.status(rest.split(' ').next().unwrap_or(rest));
        } else if let Some(rest) = line.strip_prefix("Running ") {
            step.status(rest.split(" (").next().unwrap_or(rest));
        }
    });
    step.finish();
    let shown = ui::path(krate.dir());
    let (status, output) = match ran {
        Ok(ran) => ran,
        Err(e) => {
            tally.failed(&shown, &format!("run cargo test: {e}"));
            return;
        }
    };
    let targets = cargo_test_results(&output, &|source| match source {
        Some(source) => ui::path(&krate.dir().join(source)),
        None => format!("{shown} (doc tests)"),
    });
    let mut any_failed = false;
    for (file, results) in &targets {
        for result in results {
            any_failed |= result.status == TestStatus::Failed;
            tally.show(file, result);
        }
    }
    if !status.success() && !any_failed {
        tally.failed(
            &shown,
            &format!("cargo test failed ({status})\n{}", output.trim_end()),
        );
    }
}

/// The `cargo test` command for `krate`, with `--release` and `filter` when
/// given.
fn cargo_test_command(krate: &AppCrate, filter: Option<&str>, release: bool) -> Command {
    let mut cmd = krate.cargo("test");
    cmd.arg("--no-fail-fast").env("CARGO_TERM_COLOR", "never");
    if release {
        cmd.arg("--release");
    }
    if let Some(filter) = filter {
        cmd.arg(filter);
    }
    cmd
}

/// The tests `cargo test`'s `output` reports, by test target in order:
/// each target's name (`file` of its source, `src/lib.rs` or
/// `tests/app/main.rs`; of `None` for the doc tests) and its tests, a
/// failed one with what it printed (its panic).
fn cargo_test_results(
    output: &str,
    file: &dyn Fn(Option<&str>) -> String,
) -> Vec<(String, Vec<TestResult>)> {
    let mut targets: Vec<(String, Vec<TestResult>)> = Vec::new();
    // The failed test whose output is being read, and the output.
    let mut failure: Option<(String, Vec<&str>)> = None;
    let attach = |targets: &mut Vec<(String, Vec<TestResult>)>,
                  failure: &mut Option<(String, Vec<&str>)>| {
        let Some((name, lines)) = failure.take() else {
            return;
        };
        let Some(result) = targets
            .last_mut()
            .and_then(|(_, results)| results.iter_mut().find(|r| r.name == name))
        else {
            return;
        };
        let message = lines.join("\n").trim().to_owned();
        if let Some(failure) = &mut result.failure
            && !message.is_empty()
        {
            failure.message = message;
        }
    };
    for line in output.lines() {
        let trimmed = line.trim_start();
        if let Some(rest) = trimmed.strip_prefix("Running ") {
            attach(&mut targets, &mut failure);
            let source = rest.strip_prefix("unittests ").unwrap_or(rest);
            let source = source.split(" (").next().unwrap_or(source);
            targets.push((file(Some(source)), Vec::new()));
        } else if trimmed.starts_with("Doc-tests ") {
            attach(&mut targets, &mut failure);
            targets.push((file(None), Vec::new()));
        } else if let Some(name) = line
            .strip_prefix("---- ")
            .and_then(|l| l.strip_suffix(" stdout ----"))
        {
            attach(&mut targets, &mut failure);
            failure = Some((name.to_owned(), Vec::new()));
        } else if line == "failures:" || line.starts_with("test result: ") {
            attach(&mut targets, &mut failure);
        } else if let Some((_, lines)) = &mut failure {
            lines.push(line);
        } else if let Some((name, outcome)) = line
            .strip_prefix("test ")
            .and_then(|l| l.rsplit_once(" ... "))
            && let Some((_, results)) = targets.last_mut()
        {
            let status = match outcome {
                "ok" => TestStatus::Passed,
                "FAILED" => TestStatus::Failed,
                o if o.starts_with("ignored") => TestStatus::Skipped,
                _ => continue,
            };
            let failure = (status == TestStatus::Failed).then(|| nsh_testing::Failure {
                message: "failed".to_owned(),
                stack: None,
                screen: None,
            });
            results.push(TestResult::new(
                name,
                std::time::Duration::ZERO,
                status,
                failure,
            ));
        }
    }
    attach(&mut targets, &mut failure);
    targets.retain(|(_, results)| !results.is_empty());
    targets
}

/// The entry of the app `path` is part of: a directory's, a test file's
/// (the nearest directory up with an app), or `path` itself.
pub(crate) fn app_entry(path: &Path) -> anyhow::Result<PathBuf> {
    if path.is_dir() {
        return crate::entry::resolve(path);
    }
    if !is_test_file(path) {
        return Ok(path.to_owned());
    }
    let mut dir = path.parent();
    while let Some(d) = dir {
        if d.join("nsh.json").is_file() || crate::entry::resolve(d).is_ok() {
            return crate::entry::resolve(d);
        }
        dir = d.parent();
    }
    bail!(
        "{}: no app around it (an App.tsx or nsh.json)",
        ui::path(path)
    )
}

/// Where the test files of the directory `path` are: the directory of the
/// entry its `nsh.json` names (`"entry": "app/App.tsx"`: `app/`), the rest
/// of such a project being other code (a server's, with tests of its own);
/// else `path` itself.
fn test_root(path: &Path) -> PathBuf {
    match nsh_bundler::app_dir::config_entry(path) {
        Ok(Some(entry)) => entry
            .parent()
            .map_or_else(|| path.to_owned(), Path::to_path_buf),
        _ => path.to_owned(),
    }
}

fn is_test_file(path: &Path) -> bool {
    path.is_file()
        && path
            .file_name()
            .and_then(|n| n.to_str())
            .is_some_and(|n| n.ends_with(".test.tsx") || n.ends_with(".test.ts"))
}

/// Adds the test files under `dir` to `out`, outside hidden directories
/// (`.nsh`), `node_modules` and `target`.
fn find_tests(dir: &Path, out: &mut Vec<PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if path.is_dir() {
            if !name.starts_with('.') && name != "node_modules" && name != "target" {
                find_tests(&path, out);
            }
        } else if is_test_file(&path) {
            out.push(path);
        }
    }
}

/// A test file that opens the app at `entry` on the network, lets it run
/// for a while, then takes the steps standard input gives (none from a
/// terminal), with `app` the app.
fn steps_file(work_dir: &Path, entry: &Path) -> anyhow::Result<PathBuf> {
    let mut steps = String::new();
    let stdin = std::io::stdin();
    if !stdin.is_terminal() {
        stdin
            .lock()
            .read_to_string(&mut steps)
            .context("read the steps from standard input")?;
    }
    let name = entry
        .file_name()
        .map_or("app".into(), |n| n.to_string_lossy().into_owned());
    let entry_js = serde_json::to_string(&entry.to_string_lossy().replace('\\', "/"))?;
    let code = format!(
        "// Made by `nsh test {name}`: the steps of standard input.\n\
         import {{ expect, open, test }} from \"nsh/test\";\n\n\
         test(\"steps\", async () => {{\n\
         const app = await open({entry_js}, {{ network: \"live\" }});\n\
         await app.wait({IDLE_MS});\n\
         {steps}\n\
         }});\n"
    );
    std::fs::create_dir_all(work_dir).with_context(|| format!("{}", work_dir.display()))?;
    let file = work_dir.join(format!("{name}.steps.test.ts"));
    std::fs::write(&file, code).with_context(|| format!("write {}", file.display()))?;
    Ok(file)
}

/// Builds the apps tests open against the UI sets this command line
/// serves (each entry once), and the entries made for test files against
/// them and `nsh/test`, in this process.
fn compiler(release: bool) -> nsh_testing::Compile {
    let built: Mutex<HashMap<PathBuf, Compiled>> = Mutex::new(HashMap::new());
    Arc::new(move |entry: &Path, kind: Entry| {
        let (bytecode, map, capabilities, links, main_window, application, asset_root) = match kind
        {
            Entry::App => {
                let entry =
                    crate::entry::resolve(entry).map_err(|e| crate::ui::with_details(&e))?;
                let cached = built
                    .lock()
                    .unwrap_or_else(|e| e.into_inner())
                    .get(&entry)
                    .cloned();
                match cached {
                    Some(built) => built,
                    None => {
                        let out = bytecode_of(&entry, &crate::ui_sets(), true, release)
                            .map_err(|e| crate::ui::with_details(&e))?;
                        built
                            .lock()
                            .unwrap_or_else(|e| e.into_inner())
                            .insert(entry, out.clone());
                        out
                    }
                }
            }
            Entry::TestFile => {
                test_file_bytecode(entry).map_err(|e| crate::ui::with_details(&e))?
            }
        };
        // SAFETY: compiled just now by this runtime.
        let bundle = unsafe { Bundle::bytecode(bytecode) }
            .with_capabilities_json(capabilities.as_deref())?
            // The links it claims and its main window's launch options, as
            // a packaged app's runner reads them.
            .with_links(links)
            .with_main_window(main_window.as_deref())
            .with_application(application.as_deref());
        Ok(Built::Js {
            bundle: Box::new(bundle),
            source_map: map,
            asset_root,
        })
    })
}

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

    #[test]
    fn cargo_tests_are_read_by_target_with_their_failures() {
        let output = "   Compiling app v0.1.0 (/app)
    Finished `test` profile [unoptimized + debuginfo] target(s) in 1.00s
     Running unittests src/lib.rs (target/debug/deps/app-0123)

running 3 tests
test tests::later ... ignored, slow
test tests::adds ... ok
test tests::fails ... FAILED

failures:

---- tests::fails stdout ----
thread 'tests::fails' panicked at src/lib.rs:9:9:
math is broken

failures:
    tests::fails

test result: FAILED. 1 passed; 1 failed; 1 ignored; 0 measured; 0 filtered out

     Running unittests src/main.rs (target/debug/deps/app-4567)

running 0 tests

test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

     Running tests/app/main.rs (target/debug/deps/app-89ab)

running 1 test
test opens ... ok

   Doc-tests app

running 1 test
test src/lib.rs - App (line 3) ... ok
";
        let targets = cargo_test_results(output, &|source| {
            source.map_or("app (doc tests)".to_owned(), |s| format!("app/{s}"))
        });
        let names: Vec<(&str, Vec<(&str, TestStatus)>)> = targets
            .iter()
            .map(|(file, results)| {
                (
                    file.as_str(),
                    results
                        .iter()
                        .map(|r| (r.name.as_str(), r.status))
                        .collect(),
                )
            })
            .collect();
        assert_eq!(
            names,
            [
                (
                    "app/src/lib.rs",
                    vec![
                        ("tests::later", TestStatus::Skipped),
                        ("tests::adds", TestStatus::Passed),
                        ("tests::fails", TestStatus::Failed),
                    ]
                ),
                ("app/tests/app/main.rs", vec![("opens", TestStatus::Passed)]),
                (
                    "app (doc tests)",
                    vec![("src/lib.rs - App (line 3)", TestStatus::Passed)]
                ),
            ]
        );
        let failed = &targets[0].1[2];
        assert_eq!(
            failed.failure.as_ref().unwrap().message,
            "thread 'tests::fails' panicked at src/lib.rs:9:9:\nmath is broken"
        );
        assert!(targets[0].1[1].failure.is_none());
    }

    /// A headless run refuses `--device` before it builds or runs anything:
    /// the simulator it names would go unused.
    #[test]
    fn a_headless_run_refuses_a_simulator() {
        let dir = std::env::temp_dir().join(format!("nsh-test-device-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        let file = dir.join("App.test.tsx");
        std::fs::write(&file, "").unwrap();
        let err = test(
            &file,
            &dir.join("App.tsx"),
            None,
            false,
            false,
            false,
            None,
            None,
            None,
            None,
            None,
            Some("iPhone 16"),
            None,
            false,
        )
        .err();
        std::fs::remove_dir_all(&dir).unwrap();
        assert_eq!(
            err.map(|e| e.to_string()).as_deref(),
            Some("--device goes with --target ios or android")
        );
    }

    #[test]
    fn test_files_are_found_where_the_app_keeps_them_and_know_their_app() {
        let dir = std::env::temp_dir().join(format!("nsh-test-files-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        for file in [
            "App.tsx",
            "App.test.tsx",
            "src/cart/Cart.test.ts",
            "src/cart/Cart.tsx",
            ".nsh/test/App.test.tsx.run.js",
            ".nsh/test/Old.test.ts",
            "node_modules/x/x.test.ts",
        ] {
            let path = dir.join(file);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(&path, "").unwrap();
        }
        let dir = dunce::canonicalize(&dir).unwrap();
        let mut found = Vec::new();
        find_tests(&dir, &mut found);
        found.sort();
        assert_eq!(
            found,
            [dir.join("App.test.tsx"), dir.join("src/cart/Cart.test.ts")]
        );
        // A test file's app is the nearest one up; a directory's is its own;
        // any other file is an entry.
        let entry = dir.join("App.tsx");
        assert_eq!(
            app_entry(&dir.join("src/cart/Cart.test.ts")).unwrap(),
            entry
        );
        assert_eq!(app_entry(&dir).unwrap(), entry);
        assert_eq!(
            app_entry(&dir.join("src/cart/Cart.tsx")).unwrap(),
            dir.join("src/cart/Cart.tsx")
        );
        std::fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn apps_open_with_the_url_schemes_their_nsh_json_claims() {
        let dir = std::env::temp_dir().join(format!("nsh-test-schemes-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(
            dir.join("nsh.json"),
            r#"{ "schemes": ["MyApp"], "links": [{ "host": "Example.com", "paths": ["/orders/*"] }] }"#,
        )
        .unwrap();
        std::fs::write(dir.join("App.tsx"), "export {};\n").unwrap();
        let built = compiler(false)(&dir.join("App.tsx"), Entry::App);
        std::fs::remove_dir_all(&dir).unwrap();
        match built {
            Ok(Built::Js { bundle, .. }) => {
                assert_eq!(bundle.links.schemes(), ["myapp"]);
                assert_eq!(bundle.links.web().len(), 1);
                assert_eq!(bundle.links.check("https://example.com/orders/7"), Ok(()));
                assert!(bundle.links.check("https://example.com/").is_err());
            }
            Ok(_) => panic!("a TSX entry builds to JS"),
            Err(e) => panic!("{e}"),
        }
    }

    #[test]
    fn a_junit_report_has_a_suite_per_file_and_says_how_each_test_ended() {
        let result =
            |json: serde_json::Value| -> TestResult { serde_json::from_value(json).unwrap() };
        let elapsed = serde_json::json!({ "secs": 0, "nanos": 250_000_000 });
        let mut tally = Tally::default();
        tally.show(
            "App.test.tsx",
            &result(serde_json::json!({ "name": "cart › adds", "elapsed": elapsed, "status": "Passed", "failure": null })),
        );
        tally.show(
            "App.test.tsx",
            &result(serde_json::json!({
                "name": "shows <b>",
                "elapsed": elapsed,
                "status": "Failed",
                "failure": { "message": "expected \"a\" to be \"b\"\nmore", "stack": "at (App.test.tsx:3:5)", "screen": ["a"] },
            })),
        );
        tally.show(
            "App.test.tsx",
            &result(serde_json::json!({ "name": "later", "elapsed": elapsed, "status": "Skipped", "failure": null })),
        );
        tally.show(
            "App.test.tsx",
            &result(serde_json::json!({ "name": "someday", "elapsed": elapsed, "status": "Todo", "failure": null })),
        );
        tally.failed("Broken.test.ts", "the file is broken");
        assert_eq!(
            (tally.passed, tally.failed, tally.skipped, tally.todo),
            (1, 2, 1, 1)
        );
        let report = tally.junit(std::time::Duration::from_secs(2));
        assert_eq!(
            report,
            r#"<?xml version="1.0" encoding="UTF-8"?>
<testsuites name="nsh test" tests="5" failures="1" errors="1" skipped="2" time="2.000">
  <testsuite name="App.test.tsx" tests="4" failures="1" errors="0" skipped="2" time="1.000">
    <testcase classname="App.test.tsx" name="cart › adds" time="0.250"/>
    <testcase classname="App.test.tsx" name="shows &lt;b&gt;" time="0.250">
      <failure message="expected &quot;a&quot; to be &quot;b&quot;">expected &quot;a&quot; to be &quot;b&quot;&#10;more&#10;at (App.test.tsx:3:5)&#10;on screen: &quot;a&quot;</failure>
    </testcase>
    <testcase classname="App.test.tsx" name="later" time="0.250">
      <skipped/>
    </testcase>
    <testcase classname="App.test.tsx" name="someday" time="0.250">
      <skipped message="todo"/>
    </testcase>
  </testsuite>
  <testsuite name="Broken.test.ts" tests="1" failures="0" errors="1" skipped="0" time="0.000">
    <testcase classname="Broken.test.ts" name="Broken.test.ts" time="0.000">
      <error message="the file is broken">the file is broken</error>
    </testcase>
  </testsuite>
</testsuites>
"#
        );
    }

    #[test]
    fn a_junit_report_cuts_a_long_screen() {
        let result =
            |json: serde_json::Value| -> TestResult { serde_json::from_value(json).unwrap() };
        let mut tally = Tally::default();
        let big = "x".repeat(200_000);
        tally.show(
            "App.test.tsx",
            &result(serde_json::json!({
                "name": "a long document",
                "elapsed": { "secs": 0, "nanos": 0 },
                "status": "Failed",
                "failure": { "message": "failed", "screen": [big] },
            })),
        );
        let report = tally.junit(std::time::Duration::from_secs(1));
        assert!(report.len() < 10_000, "{} characters", report.len());
        assert!(report.contains("more characters"), "{report}");
    }

    #[test]
    fn cargo_test_command_passes_release_flag_when_requested() {
        let krate = AppCrate::new("app-native".into(), PathBuf::from("/app/native"));
        let args = |filter: Option<&str>, release: bool| -> Vec<String> {
            cargo_test_command(&krate, filter, release)
                .get_args()
                .map(|a| a.to_string_lossy().into_owned())
                .collect()
        };
        assert!(!args(None, false).iter().any(|a| a == "--release"));
        assert!(args(None, true).iter().any(|a| a == "--release"));
        let filtered = args(Some("adds"), true);
        let release_at = filtered.iter().position(|a| a == "--release").unwrap();
        let filter_at = filtered.iter().position(|a| a == "adds").unwrap();
        assert!(release_at < filter_at, "{filtered:?}");
    }

    #[test]
    fn release_mode_builds_app_bundle_without_development_debug_info() {
        let dir = std::env::temp_dir().join(format!("nsh-test-release-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("nsh.json"), "{}").unwrap();
        std::fs::write(
            dir.join("App.tsx"),
            "import { appInfo, mount, Text } from \"nsh\";\n\
             mount(() => <Text>{appInfo().development ? \"dev\" : \"prod\"}</Text>);\n",
        )
        .unwrap();
        let entry = dir.join("App.tsx");
        let debug = bytecode_of(&entry, &crate::ui_sets(), false, false).unwrap();
        let release = bytecode_of(&entry, &crate::ui_sets(), false, true).unwrap();
        std::fs::remove_dir_all(&dir).unwrap();
        assert!(
            release.0.len() < debug.0.len(),
            "release bytecode ({} B) should be smaller than debug ({} B)",
            release.0.len(),
            debug.0.len()
        );
    }
}