usage-lib 3.5.0

Library for working with usage specs
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
use heck::AsPascalCase;

use crate::spec::cmd::SpecCommand;
use crate::spec::config::SpecConfigProp;
use crate::spec::data_types::SpecDataTypes;
use crate::{Spec, SpecArg, SpecFlag};

use crate::sdk::{
    collect_choice_types, command_type_name, escape_jsdoc, escape_ts_string, generated_header,
    ChoiceTypeMap, CodeWriter,
};

pub fn render(spec: &Spec, package_name: &str, source_file: &Option<String>) -> String {
    let mut w = CodeWriter::new();

    w.line(&generated_header("//", source_file));

    // spec metadata constants
    if let Some(version) = &spec.version {
        w.line(&format!(
            "export const VERSION = \"{}\";",
            escape_ts_string(version)
        ));
    }
    if let Some(about) = &spec.about {
        w.line(&format!("/** {} */", escape_jsdoc(about)));
        w.line(&format!(
            "export const ABOUT = \"{}\";",
            escape_ts_string(about)
        ));
    }
    if let Some(author) = &spec.author {
        w.line(&format!(
            "export const AUTHOR = \"{}\";",
            escape_ts_string(author)
        ));
    }

    let choice_types = collect_choice_types(&spec.cmd);

    // collect root-level global flags
    let root_global_flags: Vec<&SpecFlag> = spec
        .cmd
        .flags
        .iter()
        .filter(|f| f.global && !f.hide)
        .collect();
    let has_global_flags = !root_global_flags.is_empty();

    if !choice_types.is_empty() {
        w.line("");
        for (name, choices) in choice_types.iter() {
            let union = choices
                .iter()
                .map(|c| format!("\"{}\"", escape_ts_string(c)))
                .collect::<Vec<_>>()
                .join(" | ");
            w.line(&format!("export type {name} = {union};"));
        }
    }

    // render GlobalFlags interface if root has global flags
    if has_global_flags {
        w.line("");
        w.line("/** Global flags available on all subcommands. */");
        w.line("export interface GlobalFlags {");
        w.indent();
        for flag in &root_global_flags {
            let prop = flag_property_name(flag);
            let ts_type = flag_ts_type(flag, &spec.cmd.name, &choice_types);
            let optional = if flag.required { "" } else { "?" };
            let mut doc_parts = Vec::new();
            if let Some(help) = &flag.help {
                doc_parts.push(help.clone());
            }
            if let Some(env) = &flag.env {
                doc_parts.push(format!("Environment variable: {env}"));
            }
            if !doc_parts.is_empty() {
                w.line(&format!("/** {} */", escape_jsdoc(&doc_parts.join(". "))));
            }
            w.line(&format!("{prop}{optional}: {ts_type};"));
        }
        w.dedent();
        w.line("}");
    }

    render_command_types(
        &spec.cmd,
        package_name,
        &choice_types,
        has_global_flags,
        &mut w,
    );

    if !spec.config.props.is_empty() {
        w.line("");
        let config_name = format!("{}Config", AsPascalCase(package_name));
        w.line(&format!("export interface {config_name} {{"));
        w.indent();
        for (name, prop) in &spec.config.props {
            let ts_type = config_prop_type(prop);
            let optional = if prop.default.is_some() { "?" } else { "" };
            if let Some(help) = &prop.help {
                w.line(&format!("/** {} */", escape_jsdoc(help)));
            }
            w.line(&format!("{name}{optional}: {ts_type};"));
        }
        w.dedent();
        w.line("}");
    }

    w.finish()
}

fn render_command_types(
    cmd: &SpecCommand,
    package_name: &str,
    choice_types: &ChoiceTypeMap,
    has_global_flags: bool,
    w: &mut CodeWriter,
) {
    if cmd.hide {
        return;
    }

    let name = command_type_name(cmd, package_name);
    let cmd_name = &cmd.name;

    let visible_args: Vec<&SpecArg> = cmd.args.iter().filter(|a| !a.hide).collect();
    let visible_flags: Vec<&SpecFlag> = cmd.flags.iter().filter(|f| !f.hide).collect();

    if !visible_args.is_empty() {
        w.line("");
        w.line(&format!("export interface {name}Args {{"));
        w.indent();
        for arg in &visible_args {
            render_arg_field(arg, cmd_name, choice_types, w);
        }
        w.dedent();
        w.line("}");
    }

    if !visible_flags.is_empty() {
        w.line("");
        if has_global_flags {
            w.line(&format!(
                "export interface {name}Flags extends GlobalFlags {{"
            ));
        } else {
            w.line(&format!("export interface {name}Flags {{"));
        }
        w.indent();
        for flag in &visible_flags {
            if has_global_flags && flag.global {
                continue;
            }
            render_flag_field(flag, cmd_name, choice_types, w);
        }
        w.dedent();
        w.line("}");
    }

    for subcmd in cmd.subcommands.values() {
        render_command_types(subcmd, package_name, choice_types, has_global_flags, w);
    }
}

fn render_arg_field(
    arg: &SpecArg,
    cmd_name: &str,
    choice_types: &ChoiceTypeMap,
    w: &mut CodeWriter,
) {
    let ts_type = arg_ts_type(arg, cmd_name, choice_types);
    let optional = if arg.required && arg.default.is_empty() {
        ""
    } else {
        "?"
    };
    let mut doc_parts = Vec::new();
    if let Some(help) = &arg.help {
        doc_parts.push(help.clone());
    }
    if let Some(env) = &arg.env {
        doc_parts.push(format!("Environment variable: {env}"));
    }
    if arg.var {
        if let Some(min) = arg.var_min {
            doc_parts.push(format!("Min count: {min}"));
        }
        if let Some(max) = arg.var_max {
            doc_parts.push(format!("Max count: {max}"));
        }
    }
    if !doc_parts.is_empty() {
        w.line(&format!("/** {} */", escape_jsdoc(&doc_parts.join(". "))));
    }
    w.line(&format!(
        "{}{optional}: {ts_type};",
        sanitize_ident(&arg.name)
    ));
}

fn render_flag_field(
    flag: &SpecFlag,
    cmd_name: &str,
    choice_types: &ChoiceTypeMap,
    w: &mut CodeWriter,
) {
    let ts_type = flag_ts_type(flag, cmd_name, choice_types);
    let optional = if flag.required && flag.default.is_empty() {
        ""
    } else {
        "?"
    };
    let mut doc_parts = Vec::new();
    if let Some(help) = &flag.help {
        doc_parts.push(help.clone());
    }
    if let Some(env) = &flag.env {
        doc_parts.push(format!("Environment variable: {env}"));
    }
    if let Some(deprecated) = &flag.deprecated {
        doc_parts.push(format!("@deprecated {deprecated}"));
    }
    if !flag.default.is_empty() {
        doc_parts.push(format!("@default {}", flag.default.join(", ")));
    }
    // document flag aliases
    let alias_strs: Vec<String> = flag
        .short
        .iter()
        .skip(1)
        .map(|c| format!("-{c}"))
        .chain(flag.long.iter().skip(1).map(|l| format!("--{l}")))
        .collect();
    if !alias_strs.is_empty() {
        doc_parts.push(format!("Aliases: {}", alias_strs.join(", ")));
    }
    if !doc_parts.is_empty() {
        w.line(&format!("/** {} */", escape_jsdoc(&doc_parts.join(". "))));
    }
    let prop_name = flag_property_name(flag);
    w.line(&format!("{prop_name}{optional}: {ts_type};"));
}

fn arg_ts_type(arg: &SpecArg, cmd_name: &str, choice_types: &ChoiceTypeMap) -> String {
    let base = if let Some(choices) = &arg.choices {
        if let Some(resolved) = choice_types.lookup(cmd_name, &arg.name) {
            resolved.to_string()
        } else {
            choices
                .choices
                .iter()
                .map(|c| format!("\"{}\"", escape_ts_string(c)))
                .collect::<Vec<_>>()
                .join(" | ")
        }
    } else {
        "string".to_string()
    };

    if arg.var {
        format!("{base}[]")
    } else {
        base
    }
}

fn flag_ts_type(flag: &SpecFlag, cmd_name: &str, choice_types: &ChoiceTypeMap) -> String {
    if flag.count {
        return "number".to_string();
    }

    match &flag.arg {
        Some(arg) => {
            let base = if let Some(choices) = &arg.choices {
                if let Some(resolved) = choice_types.lookup(cmd_name, &flag.name) {
                    resolved.to_string()
                } else {
                    choices
                        .choices
                        .iter()
                        .map(|c| format!("\"{}\"", escape_ts_string(c)))
                        .collect::<Vec<_>>()
                        .join(" | ")
                }
            } else {
                "string".to_string()
            };

            if flag.var {
                format!("{base}[]")
            } else {
                base
            }
        }
        None => {
            if flag.var {
                "boolean[]".to_string()
            } else {
                "boolean".to_string()
            }
        }
    }
}

fn config_prop_type(prop: &SpecConfigProp) -> String {
    match prop.data_type {
        SpecDataTypes::String => "string".to_string(),
        SpecDataTypes::Integer => "number".to_string(),
        SpecDataTypes::Float => "number".to_string(),
        SpecDataTypes::Boolean => "boolean".to_string(),
        SpecDataTypes::Null => "unknown".to_string(),
    }
}

pub(crate) fn flag_property_name(flag: &SpecFlag) -> String {
    if let Some(long) = flag.long.first() {
        return sanitize_ident(&heck::AsLowerCamelCase(long).to_string());
    }
    if let Some(short) = flag.short.first() {
        return short.to_string();
    }
    sanitize_ident(&flag.name)
}

pub(crate) fn sanitize_ident(name: &str) -> String {
    let camel = heck::AsLowerCamelCase(name).to_string();
    match camel.as_str() {
        "function" | "class" | "const" | "let" | "var" | "type" | "interface" | "new"
        | "delete" | "return" | "export" | "import" | "default" | "in" | "instanceof" | "exec"
        | "runner" | "buildFlagArgs" | "constructor" => {
            format!("_{camel}")
        }
        _ => camel,
    }
}

#[cfg(test)]
mod tests {
    use crate::sdk::{SdkLanguage, SdkOptions};
    use crate::test::SPEC_KITCHEN_SINK;
    use crate::Spec;

    fn make_opts() -> SdkOptions {
        SdkOptions {
            language: SdkLanguage::TypeScript,
            package_name: None,
            source_file: Some("test.usage.kdl".to_string()),
        }
    }

    fn get_file<'a>(output: &'a crate::sdk::SdkOutput, name: &str) -> &'a str {
        output
            .files
            .iter()
            .find(|f| f.path.to_str() == Some(name))
            .unwrap_or_else(|| panic!("{name} should exist"))
            .content
            .as_str()
    }

    #[test]
    fn test_typescript_types() {
        let output = super::super::super::generate(&SPEC_KITCHEN_SINK, &make_opts());
        insta::assert_snapshot!(get_file(&output, "types.ts"));
    }

    #[test]
    fn test_typescript_client() {
        let output = super::super::super::generate(&SPEC_KITCHEN_SINK, &make_opts());
        insta::assert_snapshot!(get_file(&output, "client.ts"));
    }

    #[test]
    fn test_typescript_runtime() {
        let output = super::super::super::generate(&SPEC_KITCHEN_SINK, &make_opts());
        insta::assert_snapshot!(get_file(&output, "runtime.ts"));
    }

    #[test]
    fn test_typescript_index() {
        let output = super::super::super::generate(&SPEC_KITCHEN_SINK, &make_opts());
        insta::assert_snapshot!(get_file(&output, "index.ts"));
    }

    /// Spec with version, about, author, global flags, double_dash,
    /// deprecated, aliases, examples, repeatable value flags.
    fn full_feature_spec() -> Spec {
        let spec: Spec = r##"
            bin "mytool"
            name "mytool"
            version "1.2.3"
            about "A powerful CLI tool"
            author "Jane Doe"

            flag "-v --verbose" help="Verbosity level" count=#true global=#true
            flag "-C --config <path>" help="Config file path" global=#true env="MYTOOL_CONFIG"
            flag "--dry-run" help="Show what would be done" negate="--no-dry-run"

            arg "input" help="Input file" required=#true
            arg "extra" var=#true help="Extra files"

            cmd "build" help="Build the project" deprecated="Use 'compile' instead" {
                alias "b"
                arg "target" help="Build target" {
                    choices "debug" "release"
                }
                arg "output" help="Output directory" double_dash="required"
                flag "-j --jobs <n>" help="Parallel jobs" var=#true
                flag "--release" help="Build in release mode"
                example "mytool build --release target" header="Build in release mode" lang="bash"
            }

            cmd "deploy" help="Deploy the project" {
                arg "env" help="Target environment" {
                    choices "staging" "production"
                }
                arg "tags" var=#true help="Deployment tags" var_min=1 var_max=5
                flag "-f --force" help="Force deploy" deprecated="Use --confirm instead"
                flag "--confirm" help="Confirm deployment"
            }
        "##
        .parse()
        .unwrap();
        spec
    }

    #[test]
    fn test_full_feature_types() {
        let spec = full_feature_spec();
        let output = super::super::super::generate(&spec, &make_opts());
        insta::assert_snapshot!(get_file(&output, "types.ts"));
    }

    #[test]
    fn test_full_feature_client() {
        let spec = full_feature_spec();
        let output = super::super::super::generate(&spec, &make_opts());
        insta::assert_snapshot!(get_file(&output, "client.ts"));
    }

    /// Spec with config props.
    #[test]
    fn test_config_props() {
        let spec: Spec = r##"
            bin "myapp"
            config {
                prop "debug" default=#true data_type=boolean help="Enable debug mode"
                prop "port" default=8080 data_type=integer env="MYAPP_PORT"
                prop "host" data_type=string
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        // just verify it doesn't crash and has the config interface
        let types = get_file(&output, "types.ts");
        assert!(types.contains("MyappConfig"));
        assert!(types.contains("debug?: boolean"));
        assert!(types.contains("port?: number"));
        assert!(types.contains("host: string"));
    }

    /// Spec with hyphenated subcommand names.
    #[test]
    fn test_hyphenated_subcommands() {
        let spec: Spec = r##"
            bin "cli"
            cmd "add-remote" help="Add a remote" {
                arg "name"
                arg "url"
            }
            cmd "remove-remote" help="Remove a remote" {
                arg "name"
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        insta::assert_snapshot!(get_file(&output, "client.ts"));
    }

    /// Spec with deeply nested subcommands.
    #[test]
    fn test_deep_nesting() {
        let spec: Spec = r##"
            bin "app"
            cmd "db" help="Database operations" {
                cmd "migration" help="Migration management" {
                    cmd "create" help="Create a new migration" {
                        arg "name"
                        flag "--template <t>" help="Migration template"
                    }
                    cmd "run" help="Run pending migrations" {
                        flag "--step <n>" help="Number of migrations to run"
                    }
                }
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        insta::assert_snapshot!(get_file(&output, "client.ts"));
    }

    /// Minimal spec with no args, no flags, no subcommands.
    #[test]
    fn test_minimal_spec() {
        let spec: Spec = r##"
            bin "hello"
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        insta::assert_snapshot!(get_file(&output, "client.ts"));
    }

    /// Test package_name override.
    #[test]
    fn test_package_name_override() {
        let spec: Spec = r##"
            bin "original-cli"
        "##
        .parse()
        .unwrap();
        let opts = SdkOptions {
            language: SdkLanguage::TypeScript,
            package_name: Some("MyCustomSdk".to_string()),
            source_file: None,
        };
        let output = super::super::super::generate(&spec, &opts);
        insta::assert_snapshot!(get_file(&output, "index.ts"));
    }

    /// Choice type collision: same arg name with different choices in different subcommands.
    #[test]
    fn test_choice_collision() {
        let spec: Spec = r##"
            bin "tool"
            cmd "build" help="Build" {
                arg "env" help="Build environment" {
                    choices "debug" "release"
                }
            }
            cmd "deploy" help="Deploy" {
                arg "env" help="Deploy environment" {
                    choices "staging" "production"
                }
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("BuildEnvChoice"));
        assert!(types.contains("DeployEnvChoice"));
        assert!(types.contains(r#""debug""#));
        assert!(types.contains(r#""staging""#));
        insta::assert_snapshot!(types);
    }

    /// Flags-only subcommand (no positional args).
    #[test]
    fn test_flags_only_subcommand() {
        let spec: Spec = r##"
            bin "app"
            cmd "status" help="Show status" {
                flag "--verbose" help="Show detailed status"
                flag "--json" help="Output as JSON"
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let client = get_file(&output, "client.ts");
        assert!(client.contains("async exec(flags?: StatusFlags): Promise<CliResult>"));
        insta::assert_snapshot!(client);
    }

    /// Config with all data_type variants, arg with env, flag with deprecated + aliases,
    /// reserved keyword identifiers.
    #[test]
    fn test_typescript_config_and_flag_edge_cases() {
        let spec: Spec = r##"
            bin "myapp"
            config {
                prop "debug" default=#true data_type=boolean help="Enable debug mode"
                prop "port" default=8080 data_type=integer
                prop "rate" default="1.5" data_type=float
                prop "host" data_type=string
                prop "extra" data_type="null"
            }
            arg "input" help="Input file" env="MYAPP_INPUT"
            flag "--type" help="Reserved keyword" deprecated="Use --kind"
            flag "-f --format --fmt <fmt>" help="Flag with short and long alias"
            flag "-v" help="Short-only flag"
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("MyappConfig"));
        insta::assert_snapshot!(types);
    }

    /// Hidden command — covers cmd.hide early-return in render_command_types.
    #[test]
    fn test_typescript_hidden_command() {
        let spec: Spec = r##"
            bin "app"
            cmd "visible" help="A visible command" {
                arg "name"
            }
            cmd "secret" hide=#true help="Hidden command" {
                arg "name"
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("VisibleArgs"));
        assert!(!types.contains("SecretArgs"));
    }

    /// double_dash=automatic, examples with lang, global flags with flags-only subcommand,
    /// repeatable boolean flag, short-only flag build.
    #[test]
    fn test_typescript_client_edge_cases() {
        let spec: Spec = r##"
            bin "runner"
            flag "-v --verbose" global=#true help="Verbosity"
            flag "--debug" var=#true help="Repeatable boolean flag"
            arg "input" help="Input file"
            arg "extra" double_dash="automatic" var=#true help="Extra files"
            cmd "run" help="Run a task" {
                example "runner run hello" header="Basic run" lang="bash"
                arg "task" help="Task to run" double_dash="automatic"
            }
            cmd "info" help="Show info" {}
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let client = get_file(&output, "client.ts");
        assert!(client.contains("double_dash=automatic"));
        assert!(client.contains("@example Basic run"));
        assert!(client.contains("```bash"));
        // GlobalFlags type for info subcommand
        assert!(client.contains("flags?: GlobalFlags"));
        // repeatable boolean flag
        assert!(client.contains("for (const v of flags.debug)"));
        insta::assert_snapshot!(client);
    }

    /// Args with default values — tests that defaults are preserved, not dropped to undefined.
    #[test]
    fn test_typescript_arg_defaults() {
        let spec: Spec = r##"
            bin "runner"
            arg "mode" default="fast" help="Run mode"
            arg "output" help="Output path" required=#true
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("mode?: string"));
        assert!(types.contains("output: string"));
        insta::assert_snapshot!(types);
    }

    /// Optional arg without default and empty flags interface.
    #[test]
    fn test_typescript_optional_arg_empty_flags() {
        let spec: Spec = r##"
            bin "app"
            arg "[name]" help="Optional arg without default"
            cmd "check" help="Check something" {
                arg "target" required=#true help="Required arg"
                arg "mode" default="quick" help="Optional arg with default"
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("name?: string"));
        insta::assert_snapshot!(types);
    }

    /// Flag with choices — flag arg with choices renders correct type.
    #[test]
    fn test_typescript_flag_with_choices() {
        let spec: Spec = r##"
            bin "tool"
            flag "--shell <shell>" help="Shell type" {
                choices "bash" "zsh" "fish"
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains(r#""bash" | "zsh" | "fish""#));
        insta::assert_snapshot!(types);
    }

    /// Flag with env annotation — env variable appears in JSDoc.
    #[test]
    fn test_typescript_flag_with_env() {
        let spec: Spec = r##"
            bin "app"
            flag "--config <path>" help="Config file" env="APP_CONFIG"
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("APP_CONFIG"));
        insta::assert_snapshot!(types);
    }

    /// Hidden flag excluded from types and client.
    #[test]
    fn test_typescript_flag_hide() {
        let spec: Spec = r##"
            bin "app"
            flag "--verbose" help="Verbosity"
            flag "--debug" hide=#true help="Hidden debug flag"
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("verbose"));
        assert!(!types.contains("debug"));
    }

    /// Negate flag rendered in client build method.
    #[test]
    fn test_typescript_negate_flag_build() {
        let spec: Spec = r##"
            bin "app"
            flag "--dry-run" help="Dry run" negate="--no-dry-run"
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let client = get_file(&output, "client.ts");
        assert!(client.contains("--dry-run"));
        assert!(client.contains("--no-dry-run"));
        insta::assert_snapshot!(client);
    }

    /// Count flag rendered in client build method.
    #[test]
    fn test_typescript_count_flag_build() {
        let spec: Spec = r##"
            bin "app"
            flag "-v --verbose" count=#true help="Verbosity level"
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let client = get_file(&output, "client.ts");
        assert!(client.contains("-v"));
        insta::assert_snapshot!(client);
    }

    /// Repeatable value flag with default — covers var + arg + default in client build.
    #[test]
    fn test_typescript_var_value_flag_with_default() {
        let spec: Spec = r##"
            bin "tool"
            flag "--tag <t>" var=#true default="latest" help="Tags"
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("string[]"));
        let client = get_file(&output, "client.ts");
        assert!(client.contains("for (const v of flags.tag)"));
        insta::assert_snapshot!(types);
    }

    /// Flag with multiple long aliases — `-f --format --fmt <fmt>`.
    #[test]
    fn test_typescript_multiple_aliases() {
        let spec: Spec = r##"
            bin "tool"
            flag "-f --format --fmt <fmt>" help="Output format"
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("fmt"));
        let client = get_file(&output, "client.ts");
        // should use first long for the flag argument name
        assert!(client.contains("--format"));
        insta::assert_snapshot!(client);
    }

    /// Required flag without default — tests non-optional flag type in Flags interface.
    #[test]
    fn test_typescript_required_flag_type() {
        let spec: Spec = r##"
            bin "tool"
            flag "--token <t>" required=#true help="Auth token"
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        // required flag without default should NOT have "?"
        assert!(types.contains("token: string;"));
        assert!(!types.contains("token?:"));
        insta::assert_snapshot!(types);
    }

    /// Global repeatable flags — covers flag_ts_simple var branches in GlobalFlags.
    #[test]
    fn test_typescript_global_repeatable_flags() {
        let spec: Spec = r##"
            bin "app"
            flag "-v --verbose" global=#true var=#true help="Repeatable verbose"
            flag "--tag <t>" global=#true var=#true help="Repeatable tag"
            cmd "run" help="Run" {
                arg "target"
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        // GlobalFlags should have boolean[] and string[] types
        assert!(types.contains("boolean[]"));
        assert!(types.contains("string[]"));
        insta::assert_snapshot!(types);
    }

    /// Boolean flag with default=#false — covers False default in types.
    #[test]
    fn test_typescript_boolean_flag_default_false() {
        let spec: Spec = r##"
            bin "app"
            flag "--no-cache" default=#false help="Disable cache"
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("@default false"));
        insta::assert_snapshot!(types);
    }

    /// Config with all props having defaults — tests Default-friendly rendering.
    #[test]
    fn test_typescript_config_all_optional() {
        let spec: Spec = r##"
            bin "app"
            config {
                prop "debug" default=#true data_type=boolean
                prop "port" default=8080 data_type=integer
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("AppConfig"));
        insta::assert_snapshot!(types);
    }

    /// Optional variadic arg — covers the optional + var branch.
    #[test]
    fn test_typescript_optional_variadic_arg() {
        let spec: Spec = r##"
            bin "tool"
            arg "[files]" var=#true help="Input files"
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("string[]"));
        let client = get_file(&output, "client.ts");
        // optional variadic arg should use spread with undefined guard
        assert!(client.contains("args.files !== undefined"));
        insta::assert_snapshot!(client);
    }

    /// Boolean config prop with default=#false — covers the false default branch.
    #[test]
    fn test_typescript_config_boolean_default_false() {
        let spec: Spec = r##"
            bin "app"
            config {
                prop "verbose" default=#false data_type=boolean help="Verbose output"
                prop "dry_run" default=#true data_type=boolean help="Dry run mode"
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("verbose?: boolean"));
        assert!(types.contains("dry_run?: boolean"));
        insta::assert_snapshot!(types);
    }

    /// String config prop with default — covers string default branch.
    #[test]
    fn test_typescript_config_string_with_default() {
        let spec: Spec = r##"
            bin "app"
            config {
                prop "host" default="localhost" data_type=string help="Server host"
                prop "name" default="myapp" data_type=string
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        assert!(types.contains("host?: string"));
        assert!(types.contains("name?: string"));
        insta::assert_snapshot!(types);
    }

    /// Example without lang — covers example rendering without language tag.
    #[test]
    fn test_typescript_example_without_lang() {
        let spec: Spec = r##"
            bin "app"
            cmd "greet" help="Greet someone" {
                example "app greet hello"
                arg "name" help="Name to greet"
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let client = get_file(&output, "client.ts");
        assert!(client.contains("app greet hello"));
        insta::assert_snapshot!(client);
    }

    /// Flag edge cases — short-only, deprecated, count with default, value flag with default,
    /// required flag, repeatable boolean flag.
    #[test]
    fn test_typescript_flag_edge_cases() {
        let spec: Spec = r##"
            bin "tool"
            flag "-v" help="Short-only flag"
            flag "--type" help="Reserved keyword" deprecated="Use --kind"
            flag "--level" count=#true default="2" help="Count flag with default"
            flag "--format <fmt>" default="json" help="Value flag with default"
            flag "--confirm" required=#true help="Required flag"
            flag "--verbose" var=#true help="Repeatable boolean flag"
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let types = get_file(&output, "types.ts");
        insta::assert_snapshot!(types);
        let client = get_file(&output, "client.ts");
        // short-only flag build
        assert!(client.contains(r#""-v""#));
        // repeatable boolean flag build
        assert!(client.contains("for (const v of flags.verbose)"));
        insta::assert_snapshot!(client);
    }

    /// Global flags with flags-only subcommand — covers GlobalFlags type branch.
    #[test]
    fn test_typescript_global_flags_flags_only() {
        let spec: Spec = r##"
            bin "app"
            flag "-v --verbose" global=#true help="Verbosity"
            cmd "status" help="Show status" {
                flag "--json" help="JSON output"
            }
            cmd "info" help="Show info" {}
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let client = get_file(&output, "client.ts");
        // "info" subcommand has no own flags, only global flags => GlobalFlags type
        assert!(client.contains("GlobalFlags"));
        insta::assert_snapshot!(client);
    }

    /// double_dash=automatic — covers arg ordering and separator insertion.
    #[test]
    fn test_typescript_double_dash_automatic() {
        let spec: Spec = r##"
            bin "runner"
            arg "input" help="Input file"
            arg "extra" double_dash="automatic" var=#true help="Extra files"
            flag "--verbose" var=#true help="Repeatable boolean flag"
            cmd "run" help="Run a task" {
                example "runner run hello" header="Basic run"
                arg "task" help="Task to run" double_dash="automatic"
            }
        "##
        .parse()
        .unwrap();
        let output = super::super::super::generate(&spec, &make_opts());
        let client = get_file(&output, "client.ts");
        assert!(client.contains("double_dash=automatic"));
        insta::assert_snapshot!(client);
    }
}