alef 0.61.1

Opinionated polyglot binding generator for Rust libraries
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
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
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
//! TypeScript declaration file (`.d.ts`) generation for NAPI-RS bindings.

use super::enums;
use super::types::{opaque_instance_method_is_dropped, opaque_static_method_is_dropped};
use crate::codegen::naming::{to_node_name, wire_variant_value};
use crate::codegen::shared::{binding_fields, substitute_excluded_types};
use crate::core::config::NodeCapsuleTypeConfig;
use crate::core::hash::{self, CommentStyle};
use crate::core::ir::{ApiSurface, EnumDef, EnumVariant, FunctionDef, ParamDef, TypeDef, TypeRef};
use std::collections::HashMap;

/// Generate the TypeScript declaration file for NAPI-RS bindings.
///
/// `streaming_item_types` maps `"OwnerType.method_name"` (snake_case) to the item type name
/// (unprefixed, e.g. `"ChatCompletionChunk"`). When a class method is identified as a streaming
/// method, its return type is overridden to `Promise<AsyncGenerator<ItemType, void, undefined>>`
/// and a matching iterator class declaration is appended.
// Each parameter is an independent slice of the generation input with no shared owner to group
// them under; bundling them into a struct would add a type whose only purpose is to satisfy the
// arity lint, and every call site would construct it inline anyway. ~keep
#[allow(
    clippy::too_many_arguments,
    reason = "independent codegen inputs with no natural grouping"
)]
pub(super) fn gen_dts(
    api: &ApiSurface,
    prefix: &str,
    exclude_functions: &ahash::AHashSet<String>,
    trait_bridges: &[crate::core::config::TraitBridgeConfig],
    capsule_types: &HashMap<String, NodeCapsuleTypeConfig>,
    streaming_item_types: &ahash::AHashMap<String, String>,
    default_types: &ahash::AHashSet<String>,
    adapter_bodies: &crate::adapters::AdapterBodies,
) -> String {
    let header = hash::header(CommentStyle::DoubleSlash);
    let mut lines: Vec<String> = header.lines().map(|l| l.to_string()).collect();
    lines.push("/* eslint-disable */".to_string());

    if !capsule_types.is_empty() {
        let mut by_module: std::collections::BTreeMap<&str, Vec<&str>> = std::collections::BTreeMap::new();
        for cfg in capsule_types.values() {
            by_module
                .entry(cfg.from_module.as_str())
                .or_default()
                .push(cfg.type_name.as_str());
        }
        for (module, mut names) in by_module {
            names.sort_unstable();
            lines.push(format!("import type {{ {} }} from \"{module}\";", names.join(", ")));
        }
    }

    lines.push(String::new());
    lines.push(
        "export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };"
            .to_string(),
    );

    let mut opaque_types: Vec<&TypeDef> = api
        .types
        .iter()
        .filter(|t| t.is_opaque && !t.is_trait && !capsule_types.contains_key(&t.name))
        .collect();
    opaque_types.sort_by(|a, b| a.name.cmp(&b.name));

    // Same name sets `gen_opaque_struct_methods` (`types.rs`) builds at its call site — passed to
    // the two `opaque_*_method_is_dropped` predicates below so a `Decl::Class` method is declared
    // here only when the binding actually generates a wrapper for it.
    let opaque_type_names: ahash::AHashSet<String> = opaque_types.iter().map(|t| t.name.clone()).collect();
    let capsule_type_names: ahash::AHashSet<String> = capsule_types.keys().cloned().collect();

    let mut plain_types: Vec<&TypeDef> = api.types.iter().filter(|t| !t.is_opaque && !t.is_trait).collect();
    plain_types.sort_by(|a, b| a.name.cmp(&b.name));

    let mut visitor_traits: Vec<&TypeDef> = api.types.iter().filter(|t| t.is_trait).collect();
    visitor_traits.sort_by(|a, b| a.name.cmp(&b.name));

    let mut sorted_enums: Vec<&EnumDef> = api.enums.iter().collect();
    sorted_enums.sort_by(|a, b| a.name.cmp(&b.name));

    let mut sorted_fns: Vec<&FunctionDef> = api
        .functions
        .iter()
        .filter(|f| {
            if exclude_functions.contains(&f.name) {
                return false;
            }
            if f.sanitized && crate::backends::napi::trait_bridge::find_bridge_param(f, trait_bridges).is_none() {
                return false;
            }
            true
        })
        .collect();
    sorted_fns.sort_by(|a, b| a.name.cmp(&b.name));

    let mut trait_bridge_fns: Vec<(String, String, String)> = Vec::new();
    for bridge in trait_bridges {
        if let Some(register) = &bridge.register_fn {
            let js_name = crate::codegen::naming::to_node_name(register);
            trait_bridge_fns.push((js_name, format!("impl: {}", bridge.trait_name), "void".to_string()));
        }
        if let Some(unregister) = &bridge.unregister_fn {
            let js_name = crate::codegen::naming::to_node_name(unregister);
            trait_bridge_fns.push((js_name, "name: string".to_string(), "void".to_string()));
        }
        if let Some(clear) = &bridge.clear_fn {
            let js_name = crate::codegen::naming::to_node_name(clear);
            trait_bridge_fns.push((js_name, String::new(), "void".to_string()));
        }
    }
    trait_bridge_fns.sort_by(|a, b| a.0.cmp(&b.0));

    let mut service_entrypoint_fns: Vec<(String, String, String)> = Vec::new();
    for service in &api.services {
        for entrypoint in &service.entrypoints {
            let bridge_name = to_node_name(&format!("{}_{}", service.name.to_lowercase(), entrypoint.method));
            let registrations_param = "registrations: Array<[string, any[], (...args: any[]) => any]>".to_string();
            let return_type = if entrypoint.is_async {
                "Promise<void>".to_string()
            } else {
                "void".to_string()
            };
            service_entrypoint_fns.push((bridge_name, registrations_param, return_type));
        }
    }
    service_entrypoint_fns.sort_by(|a, b| a.0.cmp(&b.0));

    enum Decl<'a> {
        Class(&'a TypeDef),
        Interface(&'a TypeDef),
        VisitorInterface(&'a TypeDef),
        Enum(&'a EnumDef),
        Function(&'a FunctionDef),
        TraitBridgeFunction {
            name: String,
            params: String,
            return_type: String,
        },
        ServiceEntrypoint {
            name: String,
            params: String,
            return_type: String,
        },
    }

    let mut all_decls: Vec<(String, Decl<'_>)> = Vec::new();
    for t in &opaque_types {
        all_decls.push((format!("{prefix}{}", t.name), Decl::Class(t)));
    }
    for t in &plain_types {
        all_decls.push((format!("{prefix}{}", t.name), Decl::Interface(t)));
    }
    for t in &visitor_traits {
        all_decls.push((format!("{prefix}{}", t.name), Decl::VisitorInterface(t)));
    }
    for e in &sorted_enums {
        all_decls.push((format!("{prefix}{}", e.name), Decl::Enum(e)));
    }
    for f in &sorted_fns {
        all_decls.push((to_node_name(&f.name), Decl::Function(f)));
    }
    for (name, params, ret) in trait_bridge_fns {
        all_decls.push((
            name.clone(),
            Decl::TraitBridgeFunction {
                name,
                params,
                return_type: ret,
            },
        ));
    }
    for (name, params, ret) in service_entrypoint_fns {
        all_decls.push((
            name.clone(),
            Decl::ServiceEntrypoint {
                name,
                params,
                return_type: ret,
            },
        ));
    }
    all_decls.sort_by_key(|a| a.0.to_lowercase());

    all_decls.dedup_by(|a, b| a.0 == b.0);

    // `#[napi(js_name = "Foo")]` so NAPI-RS maps JsFoo → Foo at runtime.
    let no_prefix: &str = "";
    let _ = prefix;
    for (_, decl) in &all_decls {
        lines.push(String::new());
        match decl {
            Decl::Class(typ) => {
                lines.extend(format_jsdoc(&typ.doc, ""));
                lines.push(format!("export declare class {} {{", typ.name));
                // `gen_opaque_struct_methods` (`types.rs`) silently drops a method that can't
                // cross into a `#[napi]` wrapper — never registering it in the `#[napi]` impl
                // block — for the exact reasons these two predicates check. Calling them here
                // (rather than re-deriving the condition) is what keeps `index.d.ts` from
                // promising a method the compiled extension does not export. ~keep
                let declared_methods = typ.methods.iter().filter(|method| {
                    if method.receiver.is_some() {
                        !opaque_instance_method_is_dropped(
                            method,
                            &typ.name,
                            adapter_bodies,
                            &capsule_type_names,
                            &opaque_type_names,
                        )
                    } else {
                        !opaque_static_method_is_dropped(method, &typ.name, adapter_bodies)
                    }
                });
                for method in declared_methods {
                    let js_name = to_node_name(&method.name);
                    let params = dts_params(&method.params, no_prefix, default_types);
                    let streaming_key = format!("{}.{}", typ.name, method.name);
                    let ret = if let Some(item_type) = streaming_item_types.get(&streaming_key) {
                        format!("Promise<AsyncGenerator<{item_type}, void, undefined>>")
                    } else {
                        dts_return_type_capsule(
                            &method.return_type,
                            method.error_type.is_some(),
                            method.is_async,
                            no_prefix,
                            capsule_types,
                        )
                    };
                    lines.extend(format_jsdoc(&method.doc, "  "));
                    if method.is_static {
                        lines.push(format!("  static {js_name}({params}): {ret}"));
                    } else {
                        lines.push(format!("  {js_name}({params}): {ret}"));
                    }
                }
                lines.push("}".to_string());
            }
            Decl::Interface(typ) => {
                lines.extend(format_jsdoc(&typ.doc, ""));
                lines.push(format!("export interface {} {{", typ.name));
                for field in binding_fields(&typ.fields) {
                    let js_name = to_node_name(&field.name);
                    let ts_ty = dts_type(&field.ty, no_prefix);
                    lines.extend(format_jsdoc(&field.doc, "  "));
                    let is_optional = matches!(field.ty, TypeRef::Optional(_)) || field.optional || typ.has_default;
                    if is_optional {
                        lines.push(format!("  readonly {js_name}?: {ts_ty}"));
                    } else {
                        lines.push(format!("  readonly {js_name}: {ts_ty}"));
                    }
                }
                lines.push("}".to_string());
            }
            Decl::VisitorInterface(typ) => {
                let excluded: std::collections::HashSet<&str> = api
                    .excluded_type_paths
                    .keys()
                    .map(String::as_str)
                    .chain(api.types.iter().filter(|t| t.binding_excluded).map(|t| t.name.as_str()))
                    .collect();
                lines.extend(format_jsdoc(&typ.doc, ""));
                lines.push(format!("export interface {} {{", typ.name));
                if trait_bridge_requires_plugin_name(typ, trait_bridges) {
                    lines.push("  name(): string".to_string());
                    lines.push("  version?(): string".to_string());
                    lines.push("  initialize?(): void".to_string());
                    lines.push("  shutdown?(): void".to_string());
                }
                for method in &typ.methods {
                    let js_name = to_node_name(&method.name);
                    if trait_bridge_requires_plugin_name(typ, trait_bridges) && method.name == "name" {
                        continue;
                    }
                    let sub_params: Vec<ParamDef> = method
                        .params
                        .iter()
                        .map(|p| ParamDef {
                            ty: substitute_excluded_types(&p.ty, &excluded),
                            ..p.clone()
                        })
                        .collect();
                    let params = dts_params(&sub_params, no_prefix, default_types);
                    let ret = trait_bridge_dts_return_type(
                        &substitute_excluded_types(&method.return_type, &excluded),
                        method.is_async,
                        no_prefix,
                    );
                    lines.extend(format_jsdoc(&method.doc, "  "));
                    let optional_marker = if method.has_default_impl { "?" } else { "" };
                    lines.push(format!("  {js_name}{optional_marker}({params}): {ret}"));
                }
                lines.push("}".to_string());
            }
            Decl::Enum(e) => {
                // Internal tagging always produces an object at the wire level, even when every
                // variant is a unit variant (`{"kind":"A"}`), so the gate must not require a
                // data-bearing variant. (~keep)
                let is_data_enum = e.serde_tag.is_some();
                lines.extend(format_jsdoc(&e.doc, ""));
                if is_data_enum && e.serde_content.is_some() {
                    // Adjacent tagging (`#[serde(tag, content)]`): each variant serializes as its
                    // own `{ tag: 'value'; content: T }`, so a discriminated union of per-variant
                    // shapes matches the wire format exactly. (~keep)
                    let tag_field = e.serde_tag.as_deref().unwrap_or("type");
                    let mut member_lines: Vec<String> = Vec::new();
                    for variant in &e.variants {
                        let tag_value = wire_variant_value(
                            &variant.name,
                            variant.serde_rename.as_deref(),
                            e.serde_rename_all.as_deref(),
                        );
                        let mut obj_fields: Vec<String> = vec![format!("{tag_field}: '{tag_value}'")];
                        for field in &variant.fields {
                            let js_name = if crate::codegen::conversions::is_tuple_variant(&variant.fields) {
                                e.serde_content
                                    .as_deref()
                                    .expect("adjacent content is present")
                                    .to_string()
                            } else {
                                to_node_name(&field.name)
                            };
                            let ts_ty = dts_type(&field.ty, no_prefix);
                            if matches!(field.ty, TypeRef::Optional(_)) {
                                obj_fields.push(format!("{js_name}?: {ts_ty}"));
                            } else {
                                obj_fields.push(format!("{js_name}: {ts_ty}"));
                            }
                        }
                        member_lines.push(format!("  | {{ {} }}", obj_fields.join("; ")));
                    }
                    lines.push(format!("export type {} =", e.name));
                    lines.extend(member_lines);
                    lines.push(format!("export declare const {}: {{", e.name));
                    for variant in &e.variants {
                        if let Some(field) = variant.fields.first() {
                            lines.push(format!(
                                "  {}({}: {}): {};",
                                variant.name,
                                e.serde_content.as_deref().expect("adjacent content is present"),
                                dts_type(&field.ty, no_prefix),
                                e.name
                            ));
                        } else {
                            lines.push(format!("  readonly {}: {};", variant.name, e.name));
                        }
                    }
                    lines.push("};".to_string());
                } else if is_data_enum && e.variants.iter().any(|v| !v.fields.is_empty()) {
                    // Internal tagging (`#[serde(tag = "...")]`) with at least one data-bearing
                    // variant: each variant serializes to its own flat object on the wire —
                    // `{"type":"basic","username":"...","password":"..."}` — with no other keys
                    // present, so a discriminated union of per-variant shapes matches the wire
                    // format exactly and gives callers real narrowing plus required fields. The
                    // compiled napi struct behind this still stores every variant's fields as one
                    // flattened `Option<T>` bag (`gen_tagged_enum_as_object`), but a constructed
                    // instance only ever populates its own variant's fields, so the union type is
                    // a faithful (if narrower) view of what a caller actually receives — the same
                    // relationship the adjacent-tagging branch above already relies on. Field
                    // naming reuses `tagged_enum_field_js_name` so a newtype variant's synthetic
                    // `_0` field still gets its variant-derived name, not a bare `0`. (~keep)
                    let tag_field = e.serde_tag.as_deref().unwrap_or("type");
                    let mut member_lines: Vec<String> = Vec::new();
                    for variant in &e.variants {
                        let tag_value = wire_variant_value(
                            &variant.name,
                            variant.serde_rename.as_deref(),
                            e.serde_rename_all.as_deref(),
                        );
                        let mut obj_fields: Vec<String> = vec![format!("{tag_field}: '{tag_value}'")];
                        for field in &variant.fields {
                            let js_name = enums::tagged_enum_field_js_name(variant, field);
                            let ts_ty = dts_type(&field.ty, no_prefix);
                            if matches!(field.ty, TypeRef::Optional(_)) {
                                obj_fields.push(format!("{js_name}?: {ts_ty}"));
                            } else {
                                obj_fields.push(format!("{js_name}: {ts_ty}"));
                            }
                        }
                        member_lines.push(format!("  | {{ {} }}", obj_fields.join("; ")));
                    }
                    lines.push(format!("export type {} =", e.name));
                    lines.extend(member_lines);
                } else if is_data_enum {
                    // Internal tagging, every variant a unit variant: `{"kind":"A"}` carries no
                    // payload fields to differentiate, so a single object with a union-valued tag
                    // says the same thing as a per-variant union without the redundant repetition.
                    // (~keep)
                    let tag_field = e.serde_tag.as_deref().unwrap_or("type");
                    let tag_values: Vec<String> = e
                        .variants
                        .iter()
                        .map(|v| {
                            format!(
                                "'{}'",
                                wire_variant_value(&v.name, v.serde_rename.as_deref(), e.serde_rename_all.as_deref())
                            )
                        })
                        .collect();
                    lines.push(format!(
                        "export type {} = {{ {tag_field}: {} }};",
                        e.name,
                        tag_values.join(" | ")
                    ));
                } else if e.serde_untagged && e.variants.iter().any(|v| !v.fields.is_empty()) {
                    // `#[serde(untagged)]`: each variant serializes as its own bare shape, with no
                    // discriminant and no wrapper object — the napi glue already reflects this by
                    // passing the value through as opaque `serde_json::Value`
                    // (`gen_untagged_data_enum_as_value_wrapper`), so the `.d.ts` union is the only
                    // place the real per-variant shapes can be expressed. (~keep)
                    lines.push(format!("export type {} =", e.name));
                    for variant in &e.variants {
                        lines.push(format!("  | {}", untagged_variant_dts_type(variant, no_prefix)));
                    }
                } else {
                    lines.push(format!("export declare enum {} {{", e.name));
                    for variant in &e.variants {
                        let value = wire_variant_value(
                            &variant.name,
                            variant.serde_rename.as_deref(),
                            e.serde_rename_all.as_deref(),
                        );
                        lines.extend(format_jsdoc(&variant.doc, "  "));
                        lines.push(format!("  {} = \"{}\",", variant.name, value));
                    }
                    lines.push("}".to_string());
                }
            }
            Decl::Function(func) => {
                let js_name = to_node_name(&func.name);
                let params = dts_params(&func.params, no_prefix, default_types);
                let ret = dts_return_type_capsule(
                    &func.return_type,
                    func.error_type.is_some(),
                    func.is_async,
                    no_prefix,
                    capsule_types,
                );
                lines.extend(format_jsdoc(&func.doc, ""));
                lines.push(format!("export declare function {js_name}({params}): {ret};"));
            }
            Decl::TraitBridgeFunction {
                name,
                params,
                return_type,
            } => {
                lines.push(format!("export declare function {name}({params}): {return_type};"));
            }
            Decl::ServiceEntrypoint {
                name,
                params,
                return_type,
            } => {
                lines.push(format!("export declare function {name}({params}): {return_type};"));
            }
        }
    }

    // automatically added by #[napi(async_iterator)] at build time.
    let mut sorted_streaming: Vec<(&String, &String)> = streaming_item_types.iter().collect();
    sorted_streaming.sort_by_key(|(k, _)| k.as_str());
    for (owner_method_key, item_type) in sorted_streaming {
        let method_name = owner_method_key
            .split('.')
            .next_back()
            .unwrap_or(owner_method_key.as_str());
        let iter_class_name = method_name
            .split('_')
            .map(|part| {
                let mut chars = part.chars();
                match chars.next() {
                    None => String::new(),
                    Some(first) => first.to_uppercase().to_string() + chars.as_str(),
                }
            })
            .collect::<String>()
            + "Iterator";
        lines.push(String::new());
        lines.push(format!("export declare class {iter_class_name} {{"));
        lines.push(format!(
            "  next(value?: undefined): Promise<IteratorResult<{item_type}, void>>"
        ));
        lines.push(format!(
            "  [Symbol.asyncIterator](): AsyncGenerator<{item_type}, void, undefined>"
        ));
        lines.push("}".to_string());
    }

    // The Rust-side #[napi] struct is named `Js{ErrorName}Info`; the TypeScript
    let mut sorted_errors: Vec<_> = api.errors.iter().filter(|e| !e.methods.is_empty()).collect();
    sorted_errors.sort_by_key(|e| e.name.as_str());
    for error in sorted_errors {
        let class_name = format!("{}Info", error.name);
        lines.push(String::new());
        lines.push(format!("export declare class {class_name} {{"));
        // `code` is always present — it doesn't depend on which introspection methods the
        // error type implements (see `gen_napi_error_class`). (~keep)
        lines.push("  code(): number".to_string());
        for method in &error.methods {
            let (js_name, ret_type): (&str, &str) = match method.name.as_str() {
                "status_code" => ("statusCode", "number"),
                "is_transient" => ("isTransient", "boolean"),
                "error_type" => ("errorType", "string"),
                _ => continue,
            };
            lines.push(format!("  {js_name}(): {ret_type}"));
        }
        lines.push("}".to_string());
    }

    lines.push(String::new());
    lines.join("\n")
}

fn trait_bridge_requires_plugin_name(typ: &TypeDef, trait_bridges: &[crate::core::config::TraitBridgeConfig]) -> bool {
    trait_bridges
        .iter()
        .any(|bridge| bridge.trait_name == typ.name && bridge.super_trait.as_deref().is_some())
}

/// TypeScript return type for a trait-bridge host interface method.
///
/// The host interface is the type a JS object must satisfy to be registered as a plugin (or used
/// as a visitor). Its method returns are typed natively against the binding's emitted type
/// (`dts_type`) — e.g. a `Doc` return becomes `Doc`, an `Option<Doc>` becomes `Doc | null` — so
/// callers get a precise contract instead of the prior opaque `string`. `()` returns map to
/// `void`. Async methods are wrapped in `Promise<...>`.
fn trait_bridge_dts_return_type(return_type: &TypeRef, is_async: bool, prefix: &str) -> String {
    let base = match return_type {
        TypeRef::Unit => "void".to_string(),
        other => dts_type(other, prefix),
    };
    if is_async { format!("Promise<{base}>") } else { base }
}

/// Format a rustdoc string as JSDoc comment lines with the given `indent` prefix.
///
/// Translates rustdoc Markdown sections (`# Arguments`, `# Returns`,
/// `# Errors`, `# Example`) into JSDoc tags (`@param`, `@returns`,
/// `@throws`, `@example`) via [`crate::codegen::doc_emission::render_jsdoc_sections`].
/// Replaces ` ```rust ` fences with ` ```typescript `.
///
/// Returns an empty `Vec` when `doc` is empty. For a single-line doc, emits
/// `["/** Description */"]`. For multi-line docs, emits the block form:
/// `["/**", " * line1", " * line2", " */"]`, each prefixed by `indent`.
pub(super) fn format_jsdoc(doc: &str, indent: &str) -> Vec<String> {
    let sanitized =
        crate::codegen::doc_emission::sanitize_rust_idioms(doc, crate::codegen::doc_emission::DocTarget::TsDoc);
    let doc = sanitized.trim();
    if doc.is_empty() {
        return vec![];
    }
    let sections = crate::codegen::doc_emission::parse_rustdoc_sections(doc);
    let rendered = crate::codegen::doc_emission::render_jsdoc_sections(&sections);
    let body = if rendered.trim().is_empty() {
        doc.to_string()
    } else {
        rendered
    };
    let lines: Vec<&str> = body.lines().collect();
    if lines.len() == 1 {
        vec![format!("{indent}/** {} */", lines[0].trim())]
    } else {
        let mut out = Vec::with_capacity(lines.len() + 2);
        out.push(format!("{indent}/**"));
        for line in &lines {
            let trimmed = line.trim_end();
            if trimmed.is_empty() {
                out.push(format!("{indent} *"));
            } else {
                out.push(format!("{indent} * {trimmed}"));
            }
        }
        out.push(format!("{indent} */"));
        out
    }
}

/// Map an IR `TypeRef` to its TypeScript equivalent for `.d.ts` generation.
pub(super) fn dts_type(ty: &TypeRef, prefix: &str) -> String {
    match ty {
        TypeRef::Primitive(p) => match p {
            crate::core::ir::PrimitiveType::Bool => "boolean".to_string(),
            crate::core::ir::PrimitiveType::U8
            | crate::core::ir::PrimitiveType::U16
            | crate::core::ir::PrimitiveType::U32
            | crate::core::ir::PrimitiveType::I8
            | crate::core::ir::PrimitiveType::I16
            | crate::core::ir::PrimitiveType::I32
            | crate::core::ir::PrimitiveType::F32
            | crate::core::ir::PrimitiveType::F64 => "number".to_string(),
            crate::core::ir::PrimitiveType::U64
            | crate::core::ir::PrimitiveType::I64
            | crate::core::ir::PrimitiveType::Usize
            | crate::core::ir::PrimitiveType::Isize => "number".to_string(),
        },
        TypeRef::String | TypeRef::Char | TypeRef::Path => "string".to_string(),
        TypeRef::Bytes => "Uint8Array".to_string(),
        TypeRef::Json => "JsonValue".to_string(),
        TypeRef::Duration => "number".to_string(),
        TypeRef::Unit => "void".to_string(),
        TypeRef::Optional(inner) => format!("{} | null", dts_type(inner, prefix)),
        TypeRef::Vec(inner) => format!("Array<{}>", dts_type(inner, prefix)),
        TypeRef::Map(k, v) => format!("Record<{}, {}>", dts_type(k, prefix), dts_type(v, prefix)),
        TypeRef::Named(name) => format!("{prefix}{name}"),
    }
}

/// TypeScript shape of one variant of an `untagged` enum, as it actually appears on the wire:
/// a newtype variant serializes as its inner value, a multi-field tuple variant as a TS tuple,
/// a struct variant as its own object, and a unit variant as `null`. There is no discriminant —
/// serde distinguishes untagged variants structurally at deserialize time. (~keep)
fn untagged_variant_dts_type(variant: &EnumVariant, prefix: &str) -> String {
    if variant.fields.is_empty() {
        return "null".to_string();
    }
    if variant.is_tuple {
        if variant.fields.len() == 1 {
            return dts_type(&variant.fields[0].ty, prefix);
        }
        let elems: Vec<String> = variant.fields.iter().map(|f| dts_type(&f.ty, prefix)).collect();
        return format!("[{}]", elems.join(", "));
    }
    let fields: Vec<String> = variant
        .fields
        .iter()
        .map(|field| {
            let js_name = to_node_name(&field.name);
            let ts_ty = dts_type(&field.ty, prefix);
            if matches!(field.ty, TypeRef::Optional(_)) {
                format!("{js_name}?: {ts_ty}")
            } else {
                format!("{js_name}: {ts_ty}")
            }
        })
        .collect();
    format!("{{ {} }}", fields.join("; "))
}

/// Render a list of parameters as a TypeScript parameter string for `.d.ts`.
pub(super) fn dts_params(params: &[ParamDef], prefix: &str, default_types: &ahash::AHashSet<String>) -> String {
    dts_params_with_order(params, prefix, true, default_types)
}

fn dts_params_with_order(
    params: &[ParamDef],
    prefix: &str,
    reorder_for_typescript: bool,
    default_types: &ahash::AHashSet<String>,
) -> String {
    if !reorder_for_typescript {
        let has_required_after = required_after_optional(params, default_types);
        return params
            .iter()
            .enumerate()
            .map(|(idx, p)| dts_param(p, prefix, param_is_optional(p, default_types), !has_required_after[idx]))
            .collect::<Vec<_>>()
            .join(", ");
    }

    let mut required: Vec<&ParamDef> = Vec::new();
    let mut optional: Vec<&ParamDef> = Vec::new();
    for p in params {
        if param_is_optional(p, default_types) {
            optional.push(p);
        } else {
            required.push(p);
        }
    }
    let ordered: Vec<&ParamDef> = if params
        .iter()
        .zip(required.iter().chain(optional.iter()))
        .all(|(a, b)| std::ptr::eq(a as *const ParamDef, *b as *const ParamDef))
    {
        params.iter().collect()
    } else {
        required.into_iter().chain(optional).collect()
    };
    ordered
        .iter()
        .map(|p| dts_param(p, prefix, param_is_optional(p, default_types), true))
        .collect::<Vec<_>>()
        .join(", ")
}

fn dts_param(p: &ParamDef, prefix: &str, is_optional: bool, allow_question_optional: bool) -> String {
    let js_name = to_node_name(&p.name);
    let ts_ty = dts_type(&p.ty, prefix);
    if is_optional && allow_question_optional {
        format!("{js_name}?: {ts_ty} | undefined | null")
    } else if is_optional {
        format!("{js_name}: {ts_ty} | undefined | null")
    } else {
        format!("{js_name}: {ts_ty}")
    }
}

fn param_is_optional(p: &ParamDef, default_types: &ahash::AHashSet<String>) -> bool {
    p.optional
        || p.default.is_some()
        || p.typed_default.is_some()
        || matches!(&p.ty, TypeRef::Named(name) if default_types.contains(name.as_str()))
}

fn required_after_optional(params: &[ParamDef], default_types: &ahash::AHashSet<String>) -> Vec<bool> {
    let mut seen_optional = false;
    let mut result = vec![false; params.len()];
    for (idx, param) in params.iter().enumerate() {
        let is_optional = param_is_optional(param, default_types);
        result[idx] = seen_optional && !is_optional;
        seen_optional |= is_optional;
    }
    result
}

/// Render the TypeScript return type for a function/method in `.d.ts`, substituting
/// the ecosystem type name for capsule-configured types.
///
/// When the return type is a capsule type (e.g. `Language` → `tree-sitter`), emits
/// the type_name from the capsule config (e.g. `Language`) instead of the Js-prefixed
/// wrapper name (e.g. `JsLanguage`). The `import type` line at the top of the file
/// makes that name resolvable.
pub(super) fn dts_return_type_capsule(
    ret: &TypeRef,
    _has_error: bool,
    is_async: bool,
    prefix: &str,
    capsule_types: &HashMap<String, NodeCapsuleTypeConfig>,
) -> String {
    let base = match ret {
        TypeRef::Unit => "void".to_string(),
        TypeRef::Named(name) => {
            if let Some(cfg) = capsule_types.get(name.as_str()) {
                cfg.type_name.clone()
            } else {
                dts_type(ret, prefix)
            }
        }
        other => dts_type(other, prefix),
    };
    if is_async { format!("Promise<{base}>") } else { base }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::ir::{EnumVariant, FieldDef, ParamDef, TypeDef, TypeRef};

    #[test]
    fn format_jsdoc_escapes_embedded_block_comment_closers() {
        let lines = format_jsdoc("Supports literal `/** example */` syntax.", "  ");

        assert_eq!(lines, vec!["  /** Supports literal `/** example * /` syntax. */"]);
    }

    fn make_param(name: &str, optional: bool) -> ParamDef {
        ParamDef {
            name: name.to_string(),
            ty: TypeRef::String,
            optional,
            default: None,
            sanitized: false,
            typed_default: None,
            is_ref: false,
            is_mut: false,
            newtype_wrapper: None,
            original_type: None,
            map_is_ahash: false,
            map_key_is_cow: false,
            vec_inner_is_ref: false,
            map_is_btree: false,
            core_wrapper: crate::core::ir::CoreWrapper::None,
        }
    }

    /// TypeScript TS1016: required parameter must not follow optional parameter.
    /// A visitor method like `visit_code_block(ctx, lang?: Option<str>, code: str)`
    /// must be reordered to `visit_code_block(ctx, code, lang?)` in the `.d.ts`.
    #[test]
    fn dts_params_reorders_required_after_optional() {
        let params = vec![
            make_param("ctx", false),
            make_param("lang", true),
            make_param("code", false),
        ];
        let result = dts_params(&params, "Js", &ahash::AHashSet::new());
        let ctx_pos = result.find("ctx:").expect("ctx not found");
        let code_pos = result.find("code:").expect("code not found");
        let lang_pos = result.find("lang?:").expect("lang? not found");
        assert!(ctx_pos < lang_pos, "ctx should come before lang?: {result}");
        assert!(code_pos < lang_pos, "code should come before lang?: {result}");
    }

    /// When params are already in valid order (all required before all optional),
    /// the output must be unchanged — no unnecessary reordering.
    #[test]
    fn dts_params_preserves_already_valid_order() {
        let params = vec![
            make_param("ctx", false),
            make_param("code", false),
            make_param("lang", true),
        ];
        let result = dts_params(&params, "Js", &ahash::AHashSet::new());
        assert_eq!(result, "ctx: string, code: string, lang?: string | undefined | null");
    }

    /// All-required params: order must be preserved exactly.
    #[test]
    fn dts_params_all_required_preserves_order() {
        let params = vec![make_param("a", false), make_param("b", false), make_param("c", false)];
        let result = dts_params(&params, "Js", &ahash::AHashSet::new());
        assert_eq!(result, "a: string, b: string, c: string");
    }

    #[test]
    fn dts_params_treats_defaulted_params_as_optional() {
        let mut params = vec![make_param("path", false), make_param("config", false)];
        params[1].default = Some("Default::default()".to_string());
        let result = dts_params(&params, "Js", &ahash::AHashSet::new());
        assert_eq!(
            result, "path: string, config?: string | undefined | null",
            "defaulted params must be optional in generated declarations"
        );
    }

    #[test]
    fn trait_bridge_dts_return_type_wraps_async_methods_in_promise() {
        assert_eq!(
            trait_bridge_dts_return_type(&TypeRef::Named("ExtractionResult".to_string()), true, ""),
            "Promise<ExtractionResult>"
        );
        assert_eq!(trait_bridge_dts_return_type(&TypeRef::Unit, true, ""), "Promise<void>");
        assert_eq!(
            trait_bridge_dts_return_type(&TypeRef::Named("ExtractionResult".to_string()), false, ""),
            "ExtractionResult"
        );
    }

    #[test]
    fn plugin_trait_bridge_requires_name_in_typescript_interface() {
        let typ = TypeDef {
            name: "DocumentExtractor".to_string(),
            rust_path: String::new(),
            original_rust_path: String::new(),
            fields: Vec::new(),
            methods: Vec::new(),
            is_opaque: false,
            is_clone: false,
            is_copy: false,
            doc: String::new(),
            cfg: None,
            is_trait: true,
            has_default: false,
            has_stripped_cfg_fields: false,
            is_return_type: false,
            serde_rename_all: None,
            has_serde: false,
            serde_container_default: false,
            super_traits: Vec::new(),
            binding_excluded: false,
            binding_exclusion_reason: None,
            is_variant_wrapper: false,

            has_lifetime_params: false,
            has_private_fields: false,
            version: Default::default(),
        };
        let bridges = vec![crate::core::config::TraitBridgeConfig {
            trait_name: "DocumentExtractor".to_string(),
            super_trait: Some("Plugin".to_string()),
            ..Default::default()
        }];
        assert!(trait_bridge_requires_plugin_name(&typ, &bridges));
    }

    #[test]
    fn adjacent_enum_dts_declares_runtime_namespace() {
        let api = ApiSurface {
            enums: vec![EnumDef {
                name: "Action".to_string(),
                serde_tag: Some("type".to_string()),
                serde_content: Some("output".to_string()),
                serde_rename_all: Some("snake_case".to_string()),
                variants: vec![
                    EnumVariant {
                        name: "Skip".to_string(),
                        ..Default::default()
                    },
                    EnumVariant {
                        name: "Custom".to_string(),
                        fields: vec![FieldDef {
                            name: "_0".to_string(),
                            ty: TypeRef::String,
                            ..Default::default()
                        }],
                        ..Default::default()
                    },
                ],
                ..Default::default()
            }],
            ..Default::default()
        };

        let dts = gen_dts(
            &api,
            "",
            &Default::default(),
            &[],
            &Default::default(),
            &Default::default(),
            &Default::default(),
            &Default::default(),
        );
        assert!(dts.contains("| { type: 'custom'; output: string }"));
        assert!(dts.contains("export declare const Action: {"));
        assert!(dts.contains("readonly Skip: Action;"));
        assert!(dts.contains("Custom(output: string): Action;"));
    }

    /// Internally-tagged enums whose variants are newtype wrappers around struct types must
    /// declare a discriminated union keyed by the variant-derived field name (e.g. `system`,
    /// `user`) — not the tuple field's synthetic `_0` name, and not the napi glue's internal
    /// flattened `#[napi(object)]` representation. Regression test for the `0:` key bug and for
    /// the flattening regression introduced alongside its original fix (see
    /// `internally_tagged_struct_variants_declare_discriminated_union` for the more common
    /// struct-variant case).
    #[test]
    fn internally_tagged_newtype_variants_declare_discriminated_union() {
        let api = ApiSurface {
            enums: vec![EnumDef {
                name: "InternalNewtype".to_string(),
                serde_tag: Some("role".to_string()),
                serde_rename_all: Some("snake_case".to_string()),
                variants: vec![
                    EnumVariant {
                        name: "System".to_string(),
                        fields: vec![FieldDef {
                            name: "_0".to_string(),
                            ty: TypeRef::Named("SystemMessage".to_string()),
                            ..Default::default()
                        }],
                        ..Default::default()
                    },
                    EnumVariant {
                        name: "User".to_string(),
                        fields: vec![FieldDef {
                            name: "_0".to_string(),
                            ty: TypeRef::Named("UserMessage".to_string()),
                            ..Default::default()
                        }],
                        ..Default::default()
                    },
                ],
                ..Default::default()
            }],
            ..Default::default()
        };

        let dts = gen_dts(
            &api,
            "",
            &Default::default(),
            &[],
            &Default::default(),
            &Default::default(),
            &Default::default(),
            &Default::default(),
        );

        assert_eq!(
            dts.lines()
                .skip_while(|l| *l != "export type InternalNewtype =")
                .take(3)
                .collect::<Vec<_>>(),
            vec![
                "export type InternalNewtype =",
                "  | { role: 'system'; system: SystemMessage }",
                "  | { role: 'user'; user: UserMessage }",
            ],
            "expected a discriminated union keyed by the variant-derived field name, got:\n{dts}"
        );
        assert!(
            !dts.contains("0:"),
            "must not emit the tuple field's synthetic `_0` name as a `0:` key:\n{dts}"
        );
        assert!(
            !dts.contains("system?:") && !dts.contains("user?:"),
            "a field belonging to only one variant must not be optional:\n{dts}"
        );
    }

    /// The reported regression: an internally-tagged enum whose variants are struct variants
    /// (e.g. `AuthConfig::Basic { username, password }`) must declare a real discriminated union
    /// — one member per variant, each variant's own fields required — not a single flattened
    /// object with every field made optional. Each variant serializes to its own flat object on
    /// the wire (`{"type":"basic","username":"...","password":"..."}`), so the union is a
    /// one-to-one match for what a caller actually receives.
    #[test]
    fn internally_tagged_struct_variants_declare_discriminated_union() {
        let api = ApiSurface {
            enums: vec![EnumDef {
                name: "AuthConfig".to_string(),
                serde_tag: Some("type".to_string()),
                serde_rename_all: Some("snake_case".to_string()),
                variants: vec![
                    EnumVariant {
                        name: "Basic".to_string(),
                        fields: vec![
                            FieldDef {
                                name: "username".to_string(),
                                ty: TypeRef::String,
                                ..Default::default()
                            },
                            FieldDef {
                                name: "password".to_string(),
                                ty: TypeRef::String,
                                ..Default::default()
                            },
                        ],
                        ..Default::default()
                    },
                    EnumVariant {
                        name: "Bearer".to_string(),
                        fields: vec![FieldDef {
                            name: "token".to_string(),
                            ty: TypeRef::String,
                            ..Default::default()
                        }],
                        ..Default::default()
                    },
                ],
                ..Default::default()
            }],
            ..Default::default()
        };

        let dts = gen_dts(
            &api,
            "",
            &Default::default(),
            &[],
            &Default::default(),
            &Default::default(),
            &Default::default(),
            &Default::default(),
        );

        assert_eq!(
            dts.lines()
                .skip_while(|l| *l != "export type AuthConfig =")
                .take(3)
                .collect::<Vec<_>>(),
            vec![
                "export type AuthConfig =",
                "  | { type: 'basic'; username: string; password: string }",
                "  | { type: 'bearer'; token: string }",
            ],
            "expected one discriminated-union member per variant with required fields, got:\n{dts}"
        );
        assert!(
            !dts.contains("username?:") && !dts.contains("password?:") && !dts.contains("token?:"),
            "a field belonging to only one variant must not be optional:\n{dts}"
        );
        assert!(
            !dts.contains("export type AuthConfig = {"),
            "must not emit a single flattened object type:\n{dts}"
        );
    }

    /// `#[serde(tag = "kind")] enum E { A, B }` serializes as `{"kind":"A"}` — internal tagging is
    /// always an object, even when every variant is a unit variant. `is_data_enum` must not
    /// require a data-bearing variant, or an all-unit internally-tagged enum wrongly falls back
    /// to a plain string enum declaration.
    #[test]
    fn internally_tagged_all_unit_variants_declare_object_not_string_enum() {
        let api = ApiSurface {
            enums: vec![EnumDef {
                name: "InternalAllUnit".to_string(),
                serde_tag: Some("kind".to_string()),
                variants: vec![
                    EnumVariant {
                        name: "A".to_string(),
                        ..Default::default()
                    },
                    EnumVariant {
                        name: "B".to_string(),
                        ..Default::default()
                    },
                ],
                ..Default::default()
            }],
            ..Default::default()
        };

        let dts = gen_dts(
            &api,
            "",
            &Default::default(),
            &[],
            &Default::default(),
            &Default::default(),
            &Default::default(),
            &Default::default(),
        );

        assert!(
            dts.contains("export type InternalAllUnit = { kind: 'A' | 'B' };"),
            "expected an object type matching the napi glue struct, got:\n{dts}"
        );
        assert!(
            !dts.contains("export declare enum InternalAllUnit"),
            "must not emit a plain string enum for an internally-tagged enum:\n{dts}"
        );
    }

    /// `#[serde(untagged)]` enums serialize each variant as its own bare shape (no wrapper, no
    /// discriminant) — a newtype variant as its inner value, a struct variant as its own object.
    /// The napi glue already treats the whole enum as opaque `serde_json::Value`, so this is a
    /// `.d.ts`-only fix: the union of real per-variant shapes.
    #[test]
    fn untagged_enum_declares_bare_union_of_variant_shapes() {
        let api = ApiSurface {
            enums: vec![EnumDef {
                name: "Untagged".to_string(),
                serde_untagged: true,
                variants: vec![
                    EnumVariant {
                        name: "Single".to_string(),
                        is_tuple: true,
                        fields: vec![FieldDef {
                            name: "_0".to_string(),
                            ty: TypeRef::String,
                            ..Default::default()
                        }],
                        ..Default::default()
                    },
                    EnumVariant {
                        name: "Pair".to_string(),
                        fields: vec![
                            FieldDef {
                                name: "x".to_string(),
                                ty: TypeRef::Primitive(crate::core::ir::PrimitiveType::I32),
                                ..Default::default()
                            },
                            FieldDef {
                                name: "y".to_string(),
                                ty: TypeRef::Primitive(crate::core::ir::PrimitiveType::I32),
                                ..Default::default()
                            },
                        ],
                        ..Default::default()
                    },
                ],
                ..Default::default()
            }],
            ..Default::default()
        };

        let dts = gen_dts(
            &api,
            "",
            &Default::default(),
            &[],
            &Default::default(),
            &Default::default(),
            &Default::default(),
            &Default::default(),
        );

        assert!(
            dts.contains("export type Untagged =\n  | string\n  | { x: number; y: number }"),
            "expected a bare union of each variant's own shape, got:\n{dts}"
        );
        assert!(
            !dts.contains("export declare enum Untagged"),
            "must not emit a plain string enum for an untagged data enum:\n{dts}"
        );
    }

    #[test]
    fn gen_dts_includes_service_entrypoint_bridge_functions() {
        use crate::core::ir::{EntrypointDef, EntrypointKind, MethodDef, ReceiverKind, ServiceDef};
        let api = ApiSurface {
            crate_name: "test".to_string(),
            version: "0.1.0".to_string(),
            types: vec![],
            functions: vec![],
            enums: vec![],
            errors: vec![],
            excluded_type_paths: Default::default(),
            excluded_trait_names: Default::default(),
            services: vec![ServiceDef {
                name: "App".to_string(),
                rust_path: "test::App".to_string(),
                constructor: MethodDef {
                    name: "new".to_string(),
                    params: vec![],
                    return_type: TypeRef::Named("App".to_string()),
                    is_async: false,
                    is_static: false,
                    error_type: None,
                    receiver: Some(ReceiverKind::Owned),
                    cfg: None,
                    doc: String::new(),
                    sanitized: false,
                    trait_source: None,
                    returns_ref: false,
                    returns_cow: false,
                    return_newtype_wrapper: None,
                    has_default_impl: false,
                    binding_excluded: false,
                    binding_exclusion_reason: None,
                    version: Default::default(),
                },
                configurators: vec![],
                registrations: vec![],
                entrypoints: vec![EntrypointDef {
                    method: "into_router".to_string(),
                    kind: EntrypointKind::Finalize,
                    is_async: true,
                    params: vec![],
                    return_type: TypeRef::Unit,
                    error_type: None,
                    doc: String::new(),
                }],
                doc: String::new(),
                cfg: None,
            }],
            handler_contracts: vec![],
            unsupported_public_items: vec![],
        };
        let dts = gen_dts(
            &api,
            "",
            &ahash::AHashSet::new(),
            &[],
            &Default::default(),
            &Default::default(),
            &Default::default(),
            &Default::default(),
        );
        assert!(
            dts.contains("export declare function appIntoRouter"),
            "dts should declare appIntoRouter bridge function for App.into_router"
        );
        assert!(
            dts.contains("registrations: Array<[string, any[], (...args: any[]) => any]>"),
            "service entrypoint should have registrations parameter"
        );
        assert!(
            dts.contains("Promise<void>"),
            "async into_router entrypoint should return Promise<void>"
        );
    }

    /// Regression: `gen_opaque_struct_methods` (`types.rs`) never generates a `#[napi]` wrapper
    /// for an opaque instance method that takes another opaque type by value — opaque types only
    /// implement `FromNapiValue` by reference — unless an adapter overrides it. `gen_dts` used to
    /// iterate every method with no such check, so `index.d.ts` promised a method the compiled
    /// extension does not export.
    #[test]
    fn opaque_by_value_param_without_adapter_is_not_declared_in_dts() {
        use crate::core::ir::{MethodDef, ReceiverKind};

        let api = ApiSurface {
            types: vec![
                TypeDef {
                    name: "Worker".to_string(),
                    is_opaque: true,
                    methods: vec![MethodDef {
                        name: "process".to_string(),
                        receiver: Some(ReceiverKind::Ref),
                        cfg: None,
                        params: vec![ParamDef {
                            name: "handle".to_string(),
                            ty: TypeRef::Named("Handle".to_string()),
                            is_ref: false,
                            ..Default::default()
                        }],
                        return_type: TypeRef::Unit,
                        ..Default::default()
                    }],
                    ..Default::default()
                },
                TypeDef {
                    name: "Handle".to_string(),
                    is_opaque: true,
                    ..Default::default()
                },
            ],
            ..Default::default()
        };

        let dts = gen_dts(
            &api,
            "",
            &Default::default(),
            &[],
            &Default::default(),
            &Default::default(),
            &Default::default(),
            &Default::default(),
        );

        assert!(
            !dts.contains("process("),
            "no #[napi] wrapper exists for an opaque-by-value param with no adapter override: {dts}"
        );
    }

    /// Regression, static side: `gen_static_method` never registers a sanitized static method
    /// with no adapter override either (see `opaque_static_method_is_dropped`).
    #[test]
    fn sanitized_static_method_without_adapter_is_not_declared_in_dts() {
        use crate::core::ir::MethodDef;

        let api = ApiSurface {
            types: vec![TypeDef {
                name: "Config".to_string(),
                is_opaque: true,
                methods: vec![MethodDef {
                    name: "fromRaw".to_string(),
                    receiver: None,
                    cfg: None,
                    is_static: true,
                    sanitized: true,
                    return_type: TypeRef::Named("Config".to_string()),
                    ..Default::default()
                }],
                ..Default::default()
            }],
            ..Default::default()
        };

        let dts = gen_dts(
            &api,
            "",
            &Default::default(),
            &[],
            &Default::default(),
            &Default::default(),
            &Default::default(),
            &Default::default(),
        );

        assert!(
            !dts.contains("static fromRaw"),
            "gen_static_method also drops a sanitized static method with no adapter override: {dts}"
        );
    }

    /// Control for the two regressions above: a delegatable instance method and a non-sanitized
    /// static method must still be declared, proving the new filter doesn't over-drop.
    #[test]
    fn delegatable_methods_are_still_declared_in_dts() {
        use crate::core::ir::{MethodDef, ReceiverKind};

        let api = ApiSurface {
            types: vec![TypeDef {
                name: "Worker".to_string(),
                is_opaque: true,
                methods: vec![
                    MethodDef {
                        name: "run".to_string(),
                        receiver: Some(ReceiverKind::Ref),
                        cfg: None,
                        return_type: TypeRef::Unit,
                        ..Default::default()
                    },
                    MethodDef {
                        name: "create".to_string(),
                        receiver: None,
                        cfg: None,
                        is_static: true,
                        return_type: TypeRef::Named("Worker".to_string()),
                        ..Default::default()
                    },
                ],
                ..Default::default()
            }],
            ..Default::default()
        };

        let dts = gen_dts(
            &api,
            "",
            &Default::default(),
            &[],
            &Default::default(),
            &Default::default(),
            &Default::default(),
            &Default::default(),
        );

        assert!(
            dts.contains("run("),
            "delegatable instance method must still be declared: {dts}"
        );
        assert!(
            dts.contains("static create("),
            "non-sanitized static method must still be declared: {dts}"
        );
    }
}