tsz-cli 0.1.9

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

use tsz::checker::diagnostics::DiagnosticCategory;
use tsz_cli::args::CliArgs;
use tsz_cli::{driver, locale, reporter::Reporter, watch};

/// tsc exit status codes (matching TypeScript's `ExitStatus` enum)
const EXIT_SUCCESS: i32 = 0;
const EXIT_DIAGNOSTICS_OUTPUTS_SKIPPED: i32 = 1;
const EXIT_DIAGNOSTICS_OUTPUTS_GENERATED: i32 = 2;

fn main() -> Result<()> {
    // Initialize tracing if TSZ_LOG or RUST_LOG is set (zero cost otherwise).
    // Supports TSZ_LOG_FORMAT=tree|json|text (see src/tracing_config.rs).
    tsz_cli::tracing_config::init_tracing();

    let preprocessed = preprocess_args(std::env::args_os().collect());
    let args = CliArgs::parse_from(preprocessed);
    let cwd = std::env::current_dir().context("failed to resolve current directory")?;

    // Run on a larger stack for project-sized and multi-file workflows.
    // Single-file CLI probes avoid this extra thread hop for lower startup overhead.
    if should_use_large_stack_thread(&args) {
        const MAIN_STACK_SIZE: usize = 64 * 1024 * 1024;
        std::thread::Builder::new()
            .stack_size(MAIN_STACK_SIZE)
            .spawn(move || actual_main(args, cwd))
            .expect("failed to spawn main thread")
            .join()
            .expect("main thread panicked")
    } else {
        actual_main(args, cwd)
    }
}

fn actual_main(args: CliArgs, cwd: std::path::PathBuf) -> Result<()> {
    // Initialize locale for i18n message translation
    locale::init_locale(args.locale.as_deref());

    // Handle --batch: enter batch compilation mode
    if args.batch {
        return run_batch_mode();
    }

    // Handle --init: create tsconfig.json
    if args.init {
        return handle_init(&args, &cwd);
    }

    // Handle --showConfig: print resolved configuration
    if args.show_config {
        return handle_show_config(&args, &cwd);
    }

    // Handle --listFilesOnly: print file list and exit
    if args.list_files_only {
        return handle_list_files_only(&args, &cwd);
    }

    // Handle --all: show all compiler options
    if args.all {
        return handle_all();
    }

    // Handle --build mode
    if args.build {
        return handle_build(&args, &cwd);
    }

    if args.watch {
        return watch::run(&args, &cwd);
    }

    // Initialize tracer if --generateTrace is specified
    let tracer = args.generate_trace.is_some().then(|| {
        let mut t = tsz_cli::trace::Tracer::new();
        // Add process metadata
        let mut meta_args = FxHashMap::default();
        meta_args.insert("name".to_string(), serde_json::json!("tsz"));
        t.metadata("process_name", meta_args);
        t
    });

    // Handle --generateCpuProfile: this is a V8-specific feature not applicable to a native
    // Rust compiler. The flag is accepted for CLI compatibility with tsc but has no effect.
    if let Some(ref _profile_path) = args.generate_cpu_profile {
        println!(
            "The --generateCpuProfile flag is a V8/Node.js feature and is not applicable to tsz (a native Rust compiler). The flag is accepted for compatibility but has no effect."
        );
    }

    let start_time = std::time::Instant::now();
    let result = driver::compile(&args, &cwd)?;
    let elapsed = start_time.elapsed();

    // Write trace file if requested
    if let (Some(trace_path), Some(mut tracer)) = (args.generate_trace.as_ref(), tracer) {
        use tsz_cli::trace::categories;

        // Record compilation summary events
        tracer.complete_with_args("Compile", categories::PROGRAM, start_time, elapsed, {
            let mut args = FxHashMap::default();
            args.insert(
                "fileCount".to_string(),
                serde_json::json!(result.files_read.len()),
            );
            args.insert(
                "errorCount".to_string(),
                serde_json::json!(result.diagnostics.len()),
            );
            args.insert(
                "emittedCount".to_string(),
                serde_json::json!(result.emitted_files.len()),
            );
            args
        });

        // Add per-file events for files read
        for file in &result.files_read {
            let mut args = FxHashMap::default();
            args.insert(
                "path".to_string(),
                serde_json::json!(file.display().to_string()),
            );
            tracer.instant_with_args("FileProcessed", categories::IO, args);
        }

        // Write the trace file
        let trace_file = if trace_path.is_dir() {
            trace_path.join("trace.json")
        } else {
            trace_path.to_path_buf()
        };

        if let Err(e) = tracer.write_to_file(&trace_file) {
            println!("Warning: Failed to write trace file: {e}");
        } else {
            println!("Trace written to: {}", trace_file.display());
        }
    }

    // Handle --listFiles: print all files read during compilation
    if args.list_files {
        for file in &result.files_read {
            println!("{}", file.display());
        }
    }

    // Handle --listEmittedFiles: print emitted file list
    if args.list_emitted_files && !result.emitted_files.is_empty() {
        for file in &result.emitted_files {
            println!("TSFILE: {}", file.display());
        }
    }

    // Handle --explainFiles: print files with inclusion reasons
    if args.explain_files {
        for info in &result.file_infos {
            println!("{}", info.path.display());
            for reason in &info.reasons {
                println!("  {reason}");
            }
        }
    }

    // Handle --traceDependencies: print dependency graph
    if args.trace_dependencies {
        // Note: Full dependency tracing would require access to the dependency map
        // For now, just list all files that were read (which includes dependencies)
        for file in &result.files_read {
            println!("{}", file.display());
        }
    }

    // Handle --diagnostics: print compilation performance info
    if args.diagnostics || args.extended_diagnostics {
        print_diagnostics(&result, elapsed, args.extended_diagnostics);
    }

    if !result.diagnostics.is_empty() {
        let pretty = args
            .pretty
            .unwrap_or_else(|| std::io::stderr().is_terminal());
        let mut reporter = Reporter::new(pretty);
        let output = reporter.render(&result.diagnostics);
        if !output.is_empty() {
            // Use eprint (not eprintln) because render() already includes all newlines
            print!("{output}");
        }
    }

    let has_errors = result
        .diagnostics
        .iter()
        .any(|diag| diag.category == DiagnosticCategory::Error);

    if has_errors {
        // Match tsc exit codes:
        // tsc uses exit code 2 when there are errors (DiagnosticsPresent_OutputsGenerated)
        // regardless of whether --noEmit is set. Exit code 1 is only for when emit
        // is explicitly skipped due to errors (noEmitOnError).
        if args.no_emit || !result.emitted_files.is_empty() {
            std::process::exit(EXIT_DIAGNOSTICS_OUTPUTS_GENERATED);
        } else {
            std::process::exit(EXIT_DIAGNOSTICS_OUTPUTS_SKIPPED);
        }
    }

    std::process::exit(EXIT_SUCCESS);
}

const fn should_use_large_stack_thread(args: &CliArgs) -> bool {
    args.project.is_some() || args.build || args.watch || args.batch || args.files.len() != 1
}

/// Batch compilation mode: read project directory paths from stdin (one per line),
/// compile each with `--project <path> --noEmit --pretty false`, print diagnostics,
/// then print a sentinel line so the caller can demarcate output boundaries.
///
/// Each iteration creates fresh `CliArgs` — no state is shared between compilations.
/// If tsz panics during any compilation, the process exits naturally (no `catch_unwind`).
/// The pool manager detects EOF on stdout and respawns a fresh worker.
fn run_batch_mode() -> Result<()> {
    use std::io::{BufRead, Write};

    let stdin = std::io::stdin();
    let reader = stdin.lock();
    let mut stdout = std::io::stdout().lock();

    for line in reader.lines() {
        let line = line.context("failed to read from stdin")?;
        let project_dir = line.trim();
        if project_dir.is_empty() {
            // Skip empty lines, print sentinel to keep protocol in sync
            writeln!(stdout, "---TSZ-BATCH-DONE---")?;
            stdout.flush()?;
            continue;
        }

        let project_path = std::path::Path::new(project_dir);

        // Build args matching what the conformance runner passes per test
        let batch_args = CliArgs::parse_from([
            "tsz",
            "--project",
            project_dir,
            "--noEmit",
            "--pretty",
            "false",
        ]);

        match driver::compile(&batch_args, project_path) {
            Ok(result) => {
                if !result.diagnostics.is_empty() {
                    let mut reporter = Reporter::new(false);
                    let output = reporter.render(&result.diagnostics);
                    if !output.is_empty() {
                        write!(stdout, "{output}")?;
                    }
                }
            }
            Err(e) => {
                // Print the error so the runner can see it, but don't exit
                writeln!(stdout, "error: {e}")?;
            }
        }

        writeln!(stdout, "---TSZ-BATCH-DONE---")?;
        stdout.flush()?;
    }

    Ok(())
}

/// Preprocess command-line arguments for tsc compatibility.
///
/// Handles:
/// - `-v` → `-V` conversion (tsc uses lowercase `-v` for version; clap uses `-V`)
/// - `@file` response file expansion (tsc reads args from response files)
fn preprocess_args(args: Vec<OsString>) -> Vec<OsString> {
    let mut result = Vec::with_capacity(args.len());

    for (i, arg) in args.iter().enumerate() {
        let arg_str = arg.to_string_lossy();

        if i == 0 {
            // Always keep the program name as-is
            result.push(arg.clone());
            continue;
        }

        if arg_str == "-v" {
            // tsc uses -v for version; clap uses -V
            result.push(OsString::from("-V"));
        } else if arg_str.starts_with('@') && arg_str.len() > 1 {
            // Response file: @path reads arguments from file
            let path = &arg_str[1..];
            match std::fs::read_to_string(path) {
                Ok(content) => {
                    for line in content.lines() {
                        let trimmed = line.trim();
                        // Skip empty lines and comments
                        if !trimmed.is_empty() && !trimmed.starts_with('#') {
                            // Split on whitespace, respecting quoted strings
                            // (matching tsc behavior for response files)
                            for part in split_response_line(trimmed) {
                                result.push(OsString::from(part));
                            }
                        }
                    }
                }
                Err(_) => {
                    // If the file can't be read, pass the argument through
                    // (clap will report an unknown argument error)
                    result.push(arg.clone());
                }
            }
        } else {
            result.push(arg.clone());
        }
    }

    result
}

/// Split a response file line into arguments, respecting quoted strings.
///
/// Handles both double (`"`) and single (`'`) quotes. Quotes are stripped
/// from the resulting tokens. Unquoted regions are split on whitespace.
fn split_response_line(line: &str) -> Vec<String> {
    let mut args = Vec::new();
    let mut current = String::new();
    let mut in_quote: Option<char> = None;

    for ch in line.chars() {
        match in_quote {
            Some(q) if ch == q => {
                // Closing quote — end quoted region but don't push yet,
                // there may be more content adjacent (e.g. foo"bar"baz)
                in_quote = None;
            }
            Some(_) => {
                // Inside quotes — take character literally
                current.push(ch);
            }
            None if ch == '"' || ch == '\'' => {
                // Opening quote
                in_quote = Some(ch);
            }
            None if ch.is_ascii_whitespace() => {
                // Unquoted whitespace — flush current token
                if !current.is_empty() {
                    args.push(std::mem::take(&mut current));
                }
            }
            None => {
                current.push(ch);
            }
        }
    }

    if !current.is_empty() {
        args.push(current);
    }

    args
}

fn print_diagnostics(result: &driver::CompilationResult, elapsed: Duration, extended: bool) {
    let files_count = result.files_read.len();

    // Count lines by file category, matching tsc's --diagnostics output
    let mut lines_of_library: u64 = 0;
    let mut lines_of_definitions: u64 = 0;
    let mut lines_of_typescript: u64 = 0;
    let mut lines_of_javascript: u64 = 0;
    let mut lines_of_json: u64 = 0;
    let mut lines_of_other: u64 = 0;

    for path in &result.files_read {
        let count = std::fs::read_to_string(path)
            .ok()
            .map_or(0, |text| text.lines().count() as u64);
        let name = path.to_string_lossy();
        if name.contains("lib.") && name.ends_with(".d.ts") {
            lines_of_library += count;
        } else if name.ends_with(".d.ts") || name.ends_with(".d.mts") || name.ends_with(".d.cts") {
            lines_of_definitions += count;
        } else if name.ends_with(".ts")
            || name.ends_with(".tsx")
            || name.ends_with(".mts")
            || name.ends_with(".cts")
        {
            lines_of_typescript += count;
        } else if name.ends_with(".js")
            || name.ends_with(".jsx")
            || name.ends_with(".mjs")
            || name.ends_with(".cjs")
        {
            lines_of_javascript += count;
        } else if name.ends_with(".json") {
            lines_of_json += count;
        } else {
            lines_of_other += count;
        }
    }

    let errors = result
        .diagnostics
        .iter()
        .filter(|d| d.category == DiagnosticCategory::Error)
        .count();

    println!();
    println!("Files:                         {files_count}");
    println!("Lines of Library:              {lines_of_library}");
    println!("Lines of Definitions:          {lines_of_definitions}");
    println!("Lines of TypeScript:           {lines_of_typescript}");
    println!("Lines of JavaScript:           {lines_of_javascript}");
    println!("Lines of JSON:                 {lines_of_json}");
    println!("Lines of Other:                {lines_of_other}");
    println!("Errors:                        {errors}");
    println!(
        "Total time:                    {:.2}s",
        elapsed.as_secs_f64()
    );

    if extended {
        // Use process memory info if available
        let memory_used = get_memory_usage_kb();
        println!(
            "Emitted files:                 {}",
            result.emitted_files.len()
        );
        println!(
            "Total diagnostics:             {}",
            result.diagnostics.len()
        );
        if memory_used > 0 {
            println!("Memory used:                   {memory_used}K");
        }
    }
}

/// Get current process memory usage in KB (Linux only, returns 0 on other platforms).
fn get_memory_usage_kb() -> u64 {
    // Read from /proc/self/status for RSS on Linux
    std::fs::read_to_string("/proc/self/status")
        .ok()
        .and_then(|status| {
            for line in status.lines() {
                if line.starts_with("VmRSS:") {
                    let parts: Vec<&str> = line.split_whitespace().collect();
                    if parts.len() >= 2 {
                        return parts[1].parse::<u64>().ok();
                    }
                }
            }
            None
        })
        .unwrap_or(0)
}

fn handle_init(_args: &CliArgs, cwd: &std::path::Path) -> Result<()> {
    let tsconfig_path = cwd.join("tsconfig.json");
    if tsconfig_path.exists() {
        println!(
            "A tsconfig.json file is already defined at: {}",
            tsconfig_path.display()
        );
        std::process::exit(1);
    }

    // Build the tsconfig.json content matching tsc 5.x --init output format
    // Uses JSONC (JSON with comments) which TypeScript supports
    let config = r#"{
  // Visit https://aka.ms/tsconfig to read more about this file
  "compilerOptions": {
    // File Layout
    // "rootDir": "./src",
    // "outDir": "./dist",

    // Environment Settings
    // See also https://aka.ms/tsconfig/module
    "module": "nodenext",
    "target": "esnext",
    "types": [],
    // For nodejs:
    // "lib": ["esnext"],
    // "types": ["node"],
    // and npm install -D @types/node

    // Other Outputs
    "sourceMap": true,
    "declaration": true,
    "declarationMap": true,

    // Stricter Typechecking Options
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,

    // Style Options
    // "noImplicitReturns": true,
    // "noImplicitOverride": true,
    // "noUnusedLocals": true,
    // "noUnusedParameters": true,
    // "noFallthroughCasesInSwitch": true,
    // "noPropertyAccessFromIndexSignature": true,

    // Recommended Options
    "strict": true,
    "jsx": "react-jsx",
    "verbatimModuleSyntax": true,
    "isolatedModules": true,
    "noUncheckedSideEffectImports": true,
    "moduleDetection": "force",
    "skipLibCheck": true,
  }
}
"#;

    std::fs::write(&tsconfig_path, config).with_context(|| {
        format!(
            "failed to write tsconfig.json to {}",
            tsconfig_path.display()
        )
    })?;

    println!(
        "\nCreated a new tsconfig.json\n\n\
You can learn more at https://aka.ms/tsconfig"
    );

    Ok(())
}

fn handle_show_config(args: &CliArgs, cwd: &std::path::Path) -> Result<()> {
    use tsz_cli::config::{load_tsconfig, resolve_compiler_options};
    use tsz_cli::driver::apply_cli_overrides;

    let tsconfig_path = args
        .project
        .as_ref()
        .map(|p| {
            if p.is_dir() {
                p.join("tsconfig.json")
            } else {
                p.clone()
            }
        })
        .or_else(|| {
            let default_path = cwd.join("tsconfig.json");
            default_path.exists().then_some(default_path)
        });

    let config = if let Some(path) = tsconfig_path.as_ref() {
        Some(load_tsconfig(path)?)
    } else {
        None
    };

    let mut resolved = resolve_compiler_options(
        config
            .as_ref()
            .and_then(|cfg| cfg.compiler_options.as_ref()),
    )?;
    apply_cli_overrides(&mut resolved, args)?;

    // Build compilerOptions as a serde_json::Map for proper JSON output (matching tsc)
    let mut opts = serde_json::Map::new();

    // Language and Environment
    opts.insert(
        "target".into(),
        serde_json::Value::String(format!("{:?}", resolved.printer.target).to_lowercase()),
    );
    opts.insert(
        "module".into(),
        serde_json::Value::String(format!("{:?}", resolved.printer.module).to_lowercase()),
    );

    // Modules
    if let Some(ref module_resolution) = resolved.module_resolution {
        opts.insert(
            "moduleResolution".into(),
            serde_json::Value::String(format!("{module_resolution:?}").to_lowercase()),
        );
    }
    if let Some(ref out_dir) = resolved.out_dir {
        opts.insert(
            "outDir".into(),
            serde_json::Value::String(out_dir.display().to_string()),
        );
    }
    if let Some(ref root_dir) = resolved.root_dir {
        opts.insert(
            "rootDir".into(),
            serde_json::Value::String(root_dir.display().to_string()),
        );
    }
    if let Some(ref out_file) = resolved.out_file {
        opts.insert(
            "outFile".into(),
            serde_json::Value::String(out_file.display().to_string()),
        );
    }
    if let Some(ref base_url) = resolved.base_url {
        opts.insert(
            "baseUrl".into(),
            serde_json::Value::String(base_url.display().to_string()),
        );
    }
    if let Some(ref declaration_dir) = resolved.declaration_dir {
        opts.insert(
            "declarationDir".into(),
            serde_json::Value::String(declaration_dir.display().to_string()),
        );
    }

    // Strict checks
    opts.insert("strict".into(), resolved.checker.strict.into());
    opts.insert(
        "noImplicitAny".into(),
        resolved.checker.no_implicit_any.into(),
    );
    opts.insert(
        "strictNullChecks".into(),
        resolved.checker.strict_null_checks.into(),
    );
    opts.insert(
        "strictFunctionTypes".into(),
        resolved.checker.strict_function_types.into(),
    );
    opts.insert(
        "strictPropertyInitialization".into(),
        resolved.checker.strict_property_initialization.into(),
    );
    opts.insert(
        "strictBindCallApply".into(),
        resolved.checker.strict_bind_call_apply.into(),
    );
    opts.insert(
        "noImplicitThis".into(),
        resolved.checker.no_implicit_this.into(),
    );
    opts.insert(
        "noImplicitReturns".into(),
        resolved.checker.no_implicit_returns.into(),
    );
    opts.insert(
        "useUnknownInCatchVariables".into(),
        resolved.checker.use_unknown_in_catch_variables.into(),
    );
    opts.insert(
        "noUncheckedIndexedAccess".into(),
        resolved.checker.no_unchecked_indexed_access.into(),
    );
    opts.insert(
        "exactOptionalPropertyTypes".into(),
        resolved.checker.exact_optional_property_types.into(),
    );
    opts.insert(
        "isolatedModules".into(),
        resolved.checker.isolated_modules.into(),
    );
    opts.insert(
        "esModuleInterop".into(),
        resolved.checker.es_module_interop.into(),
    );
    opts.insert(
        "allowSyntheticDefaultImports".into(),
        resolved.checker.allow_synthetic_default_imports.into(),
    );

    // Emit
    opts.insert("declaration".into(), resolved.emit_declarations.into());
    opts.insert("declarationMap".into(), resolved.declaration_map.into());
    opts.insert("sourceMap".into(), resolved.source_map.into());
    opts.insert("noEmit".into(), resolved.no_emit.into());
    opts.insert("noEmitOnError".into(), resolved.no_emit_on_error.into());
    opts.insert(
        "removeComments".into(),
        resolved.printer.remove_comments.into(),
    );
    opts.insert(
        "noEmitHelpers".into(),
        resolved.printer.no_emit_helpers.into(),
    );

    // Other
    opts.insert("incremental".into(), resolved.incremental.into());
    opts.insert("noCheck".into(), resolved.no_check.into());

    // Build top-level JSON object
    let mut top = serde_json::Map::new();
    top.insert("compilerOptions".into(), serde_json::Value::Object(opts));

    // Include files/include/exclude from tsconfig
    if let Some(ref cfg) = config {
        if let Some(ref files) = cfg.files {
            top.insert(
                "files".into(),
                serde_json::Value::Array(
                    files
                        .iter()
                        .map(|f| serde_json::Value::String(f.clone()))
                        .collect(),
                ),
            );
        }
        if let Some(ref include) = cfg.include {
            top.insert(
                "include".into(),
                serde_json::Value::Array(
                    include
                        .iter()
                        .map(|f| serde_json::Value::String(f.clone()))
                        .collect(),
                ),
            );
        }
        if let Some(ref exclude) = cfg.exclude {
            top.insert(
                "exclude".into(),
                serde_json::Value::Array(
                    exclude
                        .iter()
                        .map(|f| serde_json::Value::String(f.clone()))
                        .collect(),
                ),
            );
        }
    }

    let json = serde_json::Value::Object(top);
    println!("{}", serde_json::to_string_pretty(&json).unwrap());

    Ok(())
}

fn handle_list_files_only(args: &CliArgs, cwd: &std::path::Path) -> Result<()> {
    use tsz_cli::config::{load_tsconfig, resolve_compiler_options};
    use tsz_cli::driver::apply_cli_overrides;
    use tsz_cli::fs::{FileDiscoveryOptions, discover_ts_files};

    let tsconfig_path = args
        .project
        .as_ref()
        .map(|p| {
            if p.is_dir() {
                p.join("tsconfig.json")
            } else {
                p.clone()
            }
        })
        .or_else(|| {
            let default_path = cwd.join("tsconfig.json");
            default_path.exists().then_some(default_path)
        });

    let config = if let Some(path) = tsconfig_path.as_ref() {
        Some(load_tsconfig(path)?)
    } else {
        None
    };

    let mut resolved = resolve_compiler_options(
        config
            .as_ref()
            .and_then(|cfg| cfg.compiler_options.as_ref()),
    )?;
    apply_cli_overrides(&mut resolved, args)?;

    let base_dir = tsconfig_path
        .as_ref()
        .and_then(|p| p.parent())
        .unwrap_or(cwd);

    // Build file list from CLI args or config
    let files: Vec<std::path::PathBuf> = if !args.files.is_empty() {
        args.files.clone()
    } else if let Some(ref cfg) = config {
        cfg.files
            .as_ref()
            .map(|f| f.iter().map(std::path::PathBuf::from).collect())
            .unwrap_or_default()
    } else {
        Vec::new()
    };

    let discovery = FileDiscoveryOptions {
        base_dir: base_dir.to_path_buf(),
        files,
        include: config.as_ref().and_then(|c| c.include.clone()),
        exclude: config.as_ref().and_then(|c| c.exclude.clone()),
        out_dir: resolved.out_dir.clone(),
        follow_links: false,
        allow_js: resolved.allow_js,
    };

    let files = discover_ts_files(&discovery)?;
    for file in files {
        println!("{}", file.display());
    }

    Ok(())
}

fn handle_all() -> Result<()> {
    use clap::CommandFactory;

    println!("tsz: The TypeScript Compiler - Codename Zang\n");
    println!("ALL COMPILER OPTIONS\n");

    // Use clap to generate the full help text
    let mut cmd = tsz_cli::args::CliArgs::command();
    let help = cmd.render_long_help();
    println!("{help}");

    println!(
        "\nYou can learn about all of the compiler options at https://www.typescriptlang.org/tsconfig"
    );
    Ok(())
}

fn handle_build(args: &CliArgs, cwd: &std::path::Path) -> Result<()> {
    use tsz::checker::diagnostics::DiagnosticCategory;
    use tsz_cli::build;
    use tsz_cli::project_refs::ProjectReferenceGraph;

    let tsconfig_path = args
        .project
        .as_ref()
        .map(|p| {
            if p.is_dir() {
                p.join("tsconfig.json")
            } else {
                p.clone()
            }
        })
        .or_else(|| {
            let default_path = cwd.join("tsconfig.json");
            default_path.exists().then_some(default_path)
        });

    let Some(ref root_config_path) = tsconfig_path else {
        anyhow::bail!("No tsconfig.json found. Use --project to specify one.");
    };

    // Load project reference graph
    let graph = match ProjectReferenceGraph::load(root_config_path) {
        Ok(g) => g,
        Err(e) => {
            println!("Warning: Could not load project references: {e}");
            // Fall back to single project build
            return handle_build_single_project(args, cwd, root_config_path);
        }
    };

    // Handle --clean: delete build artifacts for all projects
    if args.clean {
        return handle_build_clean(&graph, args.build_verbose);
    }

    // Get build order (topologically sorted)
    let build_order: Vec<tsz_cli::project_refs::ProjectId> = match graph.build_order() {
        Ok(order) => order,
        Err(e) => {
            println!("Error: {e}");
            std::process::exit(EXIT_DIAGNOSTICS_OUTPUTS_SKIPPED);
        }
    };

    // Handle --dry: show what would be built without building
    if args.dry {
        println!(
            "Dry run - would build {} project(s) in order:",
            build_order.len()
        );
        for (i, project_id) in build_order.iter().enumerate() {
            if let Some(project) = graph.get_project(*project_id) {
                println!("  {}. {}", i + 1, project.config_path.display());
            }
        }
        return Ok(());
    }

    // Build each project in dependency order
    let mut total_errors = 0;
    let mut built_count = 0;
    let mut skipped_count = 0;
    let pretty = args
        .pretty
        .unwrap_or_else(|| std::io::stderr().is_terminal());
    let mut reporter = Reporter::new(pretty);

    if args.build_verbose {
        println!("Checking {} project(s)...", build_order.len());
    }

    for project_id in &build_order {
        let Some(project) = graph.get_project(*project_id) else {
            continue;
        };

        // Check if project is up-to-date (unless --force is set)
        if !args.force && build::is_project_up_to_date(project, args) {
            if args.build_verbose {
                println!("✓ Up to date: {}", project.config_path.display());
            }
            skipped_count += 1;
            continue;
        }

        if args.build_verbose {
            println!("\nBuilding: {}", project.config_path.display());
        }

        // Compile the project using the project-specific tsconfig
        let project_cwd = project.root_dir.clone();

        // Use driver::compile_project which accepts the tsconfig path directly
        let result = driver::compile_project(args, &project_cwd, &project.config_path)?;

        // Count errors
        let error_count = result
            .diagnostics
            .iter()
            .filter(|d| d.category == DiagnosticCategory::Error)
            .count();

        if error_count > 0 {
            total_errors += error_count;
            if !result.diagnostics.is_empty() {
                let output = reporter.render(&result.diagnostics);
                if !output.is_empty() {
                    print!("{output}");
                }
            }

            // Stop on first error if --stopBuildOnErrors is set
            if args.stop_build_on_errors {
                println!(
                    "\nBuild stopped due to errors in {}",
                    project.config_path.display()
                );
                std::process::exit(EXIT_DIAGNOSTICS_OUTPUTS_SKIPPED);
            }
        }

        built_count += 1;
    }

    if args.build_verbose {
        println!(
            "\nBuilt {built_count} project(s), skipped {skipped_count} up-to-date project(s), {total_errors} error(s)"
        );
    }

    if total_errors > 0 {
        std::process::exit(if built_count > 0 {
            EXIT_DIAGNOSTICS_OUTPUTS_GENERATED
        } else {
            EXIT_DIAGNOSTICS_OUTPUTS_SKIPPED
        });
    }

    Ok(())
}

/// Handle --build --clean for all projects in the graph
fn handle_build_clean(
    graph: &tsz_cli::project_refs::ProjectReferenceGraph,
    verbose: bool,
) -> Result<()> {
    use std::fs;
    use tsz_cli::config::resolve_compiler_options;

    let mut deleted_count = 0;

    for project in graph.projects() {
        let base_dir = &project.root_dir;

        // Delete .tsbuildinfo file
        let buildinfo_path = project.config_path.with_extension("tsbuildinfo");
        if buildinfo_path.exists() {
            fs::remove_file(&buildinfo_path)?;
            if verbose {
                println!("Deleted: {}", buildinfo_path.display());
            }
            deleted_count += 1;
        }

        // Get resolved options to find output directories
        let resolved = resolve_compiler_options(project.config.base.compiler_options.as_ref())?;

        // Delete outDir
        if let Some(ref out_dir) = resolved.out_dir {
            let full_out_dir = base_dir.join(out_dir);
            if full_out_dir.exists() {
                fs::remove_dir_all(&full_out_dir)?;
                if verbose {
                    println!("Deleted: {}", full_out_dir.display());
                }
                deleted_count += 1;
            }
        }

        // Delete declarationDir
        if let Some(ref declaration_dir) = resolved.declaration_dir {
            let full_decl_dir = base_dir.join(declaration_dir);
            if full_decl_dir.exists() {
                fs::remove_dir_all(&full_decl_dir)?;
                if verbose {
                    println!("Deleted: {}", full_decl_dir.display());
                }
                deleted_count += 1;
            }
        }
    }

    println!(
        "Build cleaned successfully ({} project(s), {} item(s) deleted).",
        graph.project_count(),
        deleted_count
    );
    Ok(())
}

/// Fallback to single project build when no references are found
fn handle_build_single_project(
    args: &CliArgs,
    cwd: &std::path::Path,
    config_path: &std::path::Path,
) -> Result<()> {
    use tsz::checker::diagnostics::DiagnosticCategory;

    let result = driver::compile(args, cwd)?;

    if args.build_verbose {
        println!("Projects in this build: ");
        println!("  * {}", config_path.display());
    }

    if !result.diagnostics.is_empty() {
        let pretty = args
            .pretty
            .unwrap_or_else(|| std::io::stderr().is_terminal());
        let mut reporter = Reporter::new(pretty);
        let output = reporter.render(&result.diagnostics);
        if !output.is_empty() {
            print!("{output}");
        }
    }

    let has_errors = result
        .diagnostics
        .iter()
        .any(|d| d.category == DiagnosticCategory::Error);

    if has_errors {
        std::process::exit(if result.emitted_files.is_empty() {
            EXIT_DIAGNOSTICS_OUTPUTS_SKIPPED
        } else {
            EXIT_DIAGNOSTICS_OUTPUTS_GENERATED
        });
    }

    Ok(())
}

#[cfg(test)]
#[path = "tsz/tests.rs"]
mod tests;