bonsai-ninja-lang-typescript 0.2.2

TypeScript language adapter.
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
//! TypeScript language adapter.
use bonsai_common::FileId;
use bonsai_lang_api::{
    collect_modifier_visibility, collect_param_type_aliases, decl_index_with_handler, extract_imports_via,
    kit::{collect_kinds, first_named_child_of_kind, language_from_pack, node_text, parse_with, span_of},
    AdapterContext, AdapterError, CallArg, CallKind, CallTargetExtraction, DeclIndex, DeclKind, FieldWrite,
    FlowEvent, GrammarHandler, ImportIndex, ImportScope, ImportSpec, LanguageAdapter, LanguageCapabilities,
    LanguageId, ModifierVocabulary, TypeAliasBinding, TypeAliasVocabulary, Visibility, EMPTY_HANDLER,
};
use tree_sitter::Node;

fn typescript_call_target<'tree>(node: Node<'tree>, src: &[u8]) -> Option<CallTargetExtraction<'tree>> {
    let target = match node.kind() {
        "call_expression" => node.child_by_field_name("function")?,
        "new_expression" => node.child_by_field_name("constructor")?,
        _ => return None,
    };
    let full_text = node_text(&target, src).trim();
    (!full_text.is_empty()).then_some(CallTargetExtraction {
        node: target,
        full_text: full_text.to_string(),
    })
}

fn typescript_foreach_binding(node: Node<'_>) -> Option<(Node<'_>, Node<'_>)> {
    (node.kind() == "for_in_statement")
        .then(|| {
            Some((
                node.child_by_field_name("left")?,
                node.child_by_field_name("right")?,
            ))
        })
        .flatten()
}

const TYPESCRIPT_TYPE_ALIASES: TypeAliasVocabulary = TypeAliasVocabulary {
    fn_kinds: &["function_declaration", "method_definition", "method_signature"],
    param_kinds: &["required_parameter", "optional_parameter"],
    name_field: "pattern",
    type_field: "type",
};

const TYPESCRIPT_VOCAB: ModifierVocabulary = ModifierVocabulary {
    decl_kinds: &[
        "method_definition",
        "method_signature",
        "public_field_definition",
        "abstract_method_signature",
    ],
    modifier_container_kinds: &["accessibility_modifier"],
    keyword_to_visibility: &[
        ("private", Visibility::Private),
        ("protected", Visibility::Protected),
        ("public", Visibility::Public),
    ],
    // TypeScript's default class-member visibility is `public`.
    default_visibility: Visibility::Public,
};
use bonsai_lang_javascript::{
    apply_ecmascript_assigned_member_callable_owners, apply_javascript_getter_property_sources,
    apply_js_ts_commonjs_named_export_aliases, apply_js_ts_default_export_aliases,
    extract_ecmascript_pseudo_call, js_ts_imports, js_ts_module_segments, js_ts_require_calls,
    populate_ecmascript_compiler_facts, JS_TS_MODULE_RESOLUTION_EXTENSIONS,
};
use tree_sitter::{Language, Tree};

pub const LANG_ID: LanguageId = LanguageId::new("typescript");
const PACK_NAME: &str = "typescript";
const TSX_PACK_NAME: &str = "tsx";

fn grammar_pack_for_file(file: FileId, ctx: &AdapterContext<'_>) -> &'static str {
    ctx.vfs
        .path(file)
        .ok()
        .as_deref()
        .and_then(|path| path.extension())
        .and_then(std::ffi::OsStr::to_str)
        .filter(|extension| extension.eq_ignore_ascii_case("tsx"))
        .map_or(PACK_NAME, |_| TSX_PACK_NAME)
}
const HANDLER: GrammarHandler = GrammarHandler {
    expression_value_kind_extractor: None,
    literal_value_kinds: &["null", "number", "true", "false"],
    string_literal_kinds: &["string", "template_string"],
    comment_kinds: &["comment", "hash_bang_line"],
    doc_comment_prefixes: &["/**"],
    decorator_kinds: &["decorator"],
    parameter_container_kinds: &["formal_parameters"],
    parameter_kinds: &["identifier", "required_parameter", "optional_parameter"],
    parameter_modifier_kinds: &["decorator"],
    parameter_annotation_kinds: &["decorator"],
    variadic_parameter_kinds: &["rest_pattern", "rest_parameter"],
    destructured_parameter_kinds: &["object_pattern", "array_pattern", "object_type"],
    binding_identifier_kinds: &["identifier", "shorthand_property_identifier_pattern"],
    binding_lhs_pattern_kinds: &["assignment_pattern"],
    binding_pattern_field_names: &["left"],
    non_binding_pattern_field_names: &["type", "key", "property"],
    identifier_kinds: &["identifier", "shorthand_property_identifier", "this", "super"],
    aggregate_pattern_kinds: &["array_pattern", "object_pattern"],
    named_aggregate_kinds: &["object"],
    positional_aggregate_kinds: &["array"],
    aggregate_pair_kinds: &["pair", "pair_pattern"],
    aggregate_key_field_names: &["key"],
    aggregate_value_field_names: &["value"],
    static_field_name_kinds: &["identifier", "property_identifier"],
    shorthand_field_kinds: &["shorthand_property_identifier"],
    spread_kinds: &["spread_element"],
    spread_value_field_names: &["argument"],
    lambda_value_container_kinds: &["object", "pair", "array", "object_type"],
    transparent_call_wrapper_kinds: &[
        "member_expression",
        "property_access_expression",
        "parenthesized_expression",
        "await_expression",
        "as_expression",
        "satisfies_expression",
        "non_null_expression",
        "type_assertion",
    ],
    single_expression_group_kinds: &["expressions"],
    assignment_target_wrapper_kinds: &["variable_declarator"],
    binding_declaration_keyword_spellings: &["var", "let", "const"],
    fn_kinds: &[
        "function_declaration",
        "method_definition",
        "method_signature",
        "generator_function_declaration",
        "generator_function",
    ],
    call_kinds: &["call_expression", "new_expression"],
    constructor_call_kinds: &["new_expression"],
    call_callee_field_names: &["function", "constructor"],
    constructor_type_field_names: &["constructor"],
    call_target_extractor: Some(typescript_call_target),
    call_argument_field_names: &["arguments"],
    call_argument_container_kinds: &["arguments"],
    argument_wrapper_kinds: &["pair"],
    argument_name_field_names: &["key"],
    argument_value_field_names: &["value"],
    transparent_expression_wrapper_kinds: &["parenthesized_expression"],
    lambda_body_field_names: &["body"],
    pseudo_call_extractor: Some(extract_ecmascript_pseudo_call),
    syntax_event_extractor: None,
    argument_passing_mode_extractor: None,
    call_ref_kinds: &["call_expression", "new_expression"],
    member_expression_kinds: &["member_expression", "property_access_expression"],
    subscript_expression_kinds: &["subscript_expression"],
    member_base_field_names: &["object", "expression"],
    member_name_field_names: &["property", "name"],
    subscript_base_field_names: &["object", "expression"],
    subscript_index_field_names: &["index", "argument"],
    static_subscript_key_extractor: Some(bonsai_lang_javascript::ecmascript_static_subscript_key),
    constructor_names: &["constructor"],
    runtime_type_guard_operators: &["instanceof"],
    runtime_typeof_operators: &["typeof"],
    runtime_type_equality_operators: &["==", "==="],
    runtime_type_wrapper_kinds: &["parenthesized_expression"],
    value_free_unary_operators: &["typeof"],
    // TypeScript exposes `abstract class Foo` under
    // `abstract_class_declaration`; without the exact adapter entry,
    // abstract base classes are missed at decl-emission time, and
    // every subclass ends up with `decl.parent = None`. That
    // breaks Phase 3c/3d field-flow stitching: the inheritance
    // walk has no class to attach `BaseRepository` to.
    class_kinds: &[
        "class_declaration",
        "abstract_class_declaration",
        "interface_declaration",
        "enum_declaration",
    ],
    class_decl_kinds: &[
        ("class_declaration", DeclKind::Class),
        ("abstract_class_declaration", DeclKind::Class),
        ("interface_declaration", DeclKind::Interface),
        ("enum_declaration", DeclKind::Enum),
    ],
    method_kinds: &["method_definition", "method_signature"],
    method_context_kinds: &[
        "class_declaration",
        "abstract_class_declaration",
        "interface_declaration",
    ],
    if_kinds: &["if_statement", "switch_statement"],
    branch_then_field_names: &["consequence", "body"],
    branch_else_field_names: &["alternative"],
    branch_condition_field_names: &["condition", "value"],
    loop_body_field_names: &["body"],
    loop_body_kinds: &["statement_block", "expression_statement"],
    branch_arm_kinds: &[
        "statement_block",
        "expression_statement",
        "switch_case",
        "switch_default",
    ],
    for_kinds: &["for_statement"],
    foreach_kinds: &["for_in_statement"],
    foreach_binding_extractor: Some(typescript_foreach_binding),
    while_kinds: &["while_statement"],
    do_kinds: &["do_statement"],
    assignment_kinds: &[
        "assignment_expression",
        "augmented_assignment_expression",
        "variable_declarator",
        "variable_declaration",
    ],
    compound_assignment_kinds: &["augmented_assignment_expression"],
    compound_assignment_operators: &[
        "+=", "-=", "*=", "/=", "%=", "**=", "<<=", ">>=", ">>>=", "&=", "^=", "|=", "&&=", "||=", "??=",
    ],
    return_kinds: &["return_statement"],
    throw_kinds: &["throw_statement"],
    lambda_kinds: &["arrow_function", "function_expression"],
    try_kinds: &["try_statement"],
    catch_kinds: &["catch_clause"],
    finally_kinds: &["finally_clause"],
    break_kinds: &["break_statement"],
    continue_kinds: &["continue_statement"],
    control_label_field_names: &["label"],
    yield_kinds: &["yield_expression"],
    yield_value_field_names: &["argument"],
    await_kinds: &["await_expression"],
    using_kinds: &["with_statement"],
    using_body_field_names: &["body"],
    try_body_field_names: &["body"],
    implicit_receiver_names: &["this"],
    ..EMPTY_HANDLER
};

#[derive(Debug, Default, Copy, Clone)]
pub struct TypeScriptAdapter;

impl TypeScriptAdapter {
    /// Construct a fresh adapter. Stateless; cheap to copy.
    #[must_use]
    pub fn new() -> Self {
        Self
    }
}

impl LanguageAdapter for TypeScriptAdapter {
    fn language_id(&self) -> LanguageId {
        LANG_ID
    }
    fn display_name(&self) -> &'static str {
        "TypeScript"
    }
    fn file_extensions(&self) -> &'static [&'static str] {
        &["ts", "tsx", "mts", "cts"]
    }
    fn tree_sitter_language(&self) -> Result<Language, AdapterError> {
        language_from_pack(PACK_NAME)
    }
    fn grammar_name_for_path(&self, path: &std::path::Path) -> &'static str {
        path.extension()
            .and_then(std::ffi::OsStr::to_str)
            .filter(|extension| extension.eq_ignore_ascii_case("tsx"))
            .map_or(PACK_NAME, |_| TSX_PACK_NAME)
    }
    fn capabilities(&self) -> LanguageCapabilities {
        LanguageCapabilities {
            universal_type_names: &["any", "unknown", "object", "Object"],
            module_export_aliases: &["exports", "module.exports"],
            module_default_export_names: &["default"],
            module_path_syntax: bonsai_lang_api::ModulePathSyntax::none(),
            receiver_types: bonsai_lang_api::CapabilityLevel::Partial,
            constructor_method_names: &["constructor"],
            super_receiver_tokens: &["super"],
            implicit_receiver_tokens: &["this"],
            receiver_type_syntax: bonsai_lang_api::ReceiverTypeSyntax {
                wrapper_calls: &[],
                class_object_suffixes: &[".constructor"],
            },
            module_resolution_extensions: JS_TS_MODULE_RESOLUTION_EXTENSIONS,
            ..LanguageCapabilities::partial_baseline()
        }
    }
    fn extract_declarations(&self, file: FileId, ctx: &AdapterContext<'_>) -> DeclIndex {
        let grammar = grammar_pack_for_file(file, ctx);
        let mut decl_index = decl_index_with_handler(grammar, file, ctx, &HANDLER);
        if let Some((snapshot, tree)) = parse_with(grammar, file, ctx) {
            let src = snapshot.text.as_bytes();
            populate_ecmascript_compiler_facts(&mut decl_index, &tree, file, src);
            populate_typescript_readonly_instance_literals(&mut decl_index, &tree, file, src);
            apply_ecmascript_assigned_member_callable_owners(&mut decl_index, &tree, file, src);
            apply_js_ts_commonjs_named_export_aliases(&mut decl_index, &tree, src, file);
        }
        // TS/JS module = workspace-relative file path with `.ts`/`.tsx` (etc.) stripped.
        let module_segments = ctx
            .workspace_relative_path(file)
            .map(|p| js_ts_module_segments(&p))
            .unwrap_or_default();
        if !module_segments.is_empty() {
            bonsai_lang_api::apply_module_path_semantic_identity(&mut decl_index, module_segments);
        } else {
            // Fall back to the file stem when the workspace root is unknown.
            bonsai_lang_api::apply_file_stem_semantic_identity(&mut decl_index, ctx);
        }
        if let Some((snapshot, tree)) = parse_with(grammar, file, ctx) {
            let src = snapshot.text.as_bytes();
            apply_js_ts_default_export_aliases(&mut decl_index, &tree, src, file);
            // Phase-6 return-type extraction: `function f(): T {}` / `(): T => ...`
            // populates `Decl.return_type` for `apply_assign_call_result_types`.
            bonsai_lang_api::populate_decl_return_types(&mut decl_index, &tree, src, &HANDLER);
            // Visibility from `public/protected/private` keywords, and parameter type aliases.
            let visibility_by_span =
                collect_modifier_visibility(tree.root_node(), file, src, &TYPESCRIPT_VOCAB);
            let type_aliases_by_span = collect_param_type_aliases(&tree, file, src, &TYPESCRIPT_TYPE_ALIASES);
            // WS2 cast typing: `const c = make() as Foo` / `const c = <Foo>make()`.
            // The cast type lives only on the initializer (the declared-type /
            // return-type paths don't see it), so capture it as a local type
            // alias so `c.method(...)` resolves `receiver_type_in` / `[Foo, m]`.
            let cast_aliases_by_span = collect_typescript_cast_aliases(&tree, file, src);
            // TypeScript constructor parameter properties are both parameters
            // and instance fields: `constructor(private svc: Service)`.
            // The generic assignment walker sees no `this.svc = svc` write,
            // so emit the equivalent precise field/type facts from the syntax.
            let parameter_properties_by_span = collect_typescript_parameter_properties(&tree, file, src);
            for decl in &mut decl_index.defs {
                if let Some(vis) = visibility_by_span.get(&decl.span).copied() {
                    decl.visibility = vis;
                }
                if let Some(aliases) = type_aliases_by_span.get(&decl.span) {
                    decl.type_aliases = aliases.clone();
                }
                if let Some(cast_aliases) = cast_aliases_by_span.get(&decl.span) {
                    decl.type_aliases.extend(cast_aliases.iter().cloned());
                }
                if let Some(parameter_properties) = parameter_properties_by_span.get(&decl.span) {
                    for (alias, field_write) in parameter_properties {
                        if !decl.type_aliases.contains(alias) {
                            decl.type_aliases.push(alias.clone());
                        }
                        if !decl.receiver_field_writes.contains(field_write) {
                            decl.receiver_field_writes.push(field_write.clone());
                        }
                    }
                }
            }
            // ECMAScript `#name` private fields/methods are syntactically marked.
            for decl in &mut decl_index.defs {
                if decl.name.starts_with('#') {
                    decl.visibility = Visibility::Private;
                }
            }
            // Per-class `bases`: `class Echo extends WebSocketHandler implements Mixin { ... }`
            // becomes `["WebSocketHandler", "Mixin"]`. The TS grammar groups extends +
            // implements under a `class_heritage` child of the class.
            let bases_by_span = collect_typescript_class_bases(&tree, file, src);
            for decl in &mut decl_index.defs {
                // Bases only make sense on type-defining declarations.
                if !is_class_like(decl.kind) {
                    continue;
                }
                if let Some(bases) = bases_by_span
                    .iter()
                    .find_map(|(span, bases)| (*span == decl.span).then_some(bases))
                {
                    decl.bases = bases.clone();
                }
            }
            apply_javascript_getter_property_sources(&mut decl_index, &tree, src, file);
            inject_typescript_graphql_root_resolver_calls(&mut decl_index, &tree, src, file);
        }
        for decl in &mut decl_index.defs {
            bonsai_lang_api::normalize_call_result_assignment_sources(&mut decl.flow_events);
        }
        // Precompute `self.<field> → Type` bindings from each
        // class's constructor `receiver_field_writes` so receiver-
        // typed dispatch through stable instance state is an O(1)
        // lookup against the method's `type_aliases` instead of a
        // per-call walk over sibling decls.
        // Local constructor-result receiver typing
        // (`const c = new Foo()` → `c: Foo`); see the JS adapter for the
        // exact CST/declaration-evidence contract.
        bonsai_lang_api::apply_constructor_result_type_aliases(&mut decl_index);
        bonsai_lang_api::apply_class_field_type_aliases(&mut decl_index);
        bonsai_lang_api::apply_call_receiver_types(&mut decl_index);
        decl_index
    }
    fn extract_imports(&self, file: FileId, ctx: &AdapterContext<'_>) -> ImportIndex {
        extract_imports_via(grammar_pack_for_file(file, ctx), file, ctx, parse_imports)
    }
}

/// Lower immutable instance-field literals into the same exact assignment IR
/// used for local bindings. TypeScript spells a field read as `this.name`,
/// while the declaration node contains only `name`; recording the canonical
/// receiver projection here keeps shared analyses language-agnostic.
fn populate_typescript_readonly_instance_literals(
    index: &mut DeclIndex,
    tree: &Tree,
    file: FileId,
    src: &[u8],
) {
    for field in collect_kinds(tree, &["public_field_definition"]) {
        let has_modifier = |wanted: &str| {
            let mut cursor = field.walk();
            let found = field.children(&mut cursor).any(|child| child.kind() == wanted);
            found
        };
        if !has_modifier("readonly") || has_modifier("static") {
            continue;
        }
        let (Some(name_node), Some(value)) = (
            field.child_by_field_name("name"),
            field.child_by_field_name("value"),
        ) else {
            continue;
        };
        if name_node.kind() != "property_identifier"
            || !matches!(value.kind(), "string" | "number" | "true" | "false" | "null")
        {
            continue;
        }
        let name = node_text(&name_node, src).trim();
        let canonical = format!("this.{name}");
        let field_span = span_of(file, &field);
        if index.assignment_values.iter().any(|fact| {
            fact.assignment_span.start > field_span.start
                && fact.target.as_deref() == Some(canonical.as_str())
        }) {
            continue;
        }
        index
            .assignment_values
            .push(bonsai_lang_api::AssignmentValueFact {
                assignment_span: field_span,
                target: Some(canonical),
                target_is_immutable: true,
                target_owner: None,
                target_span: Some(span_of(file, &name_node)),
                value_span: span_of(file, &value),
                call_sites: Vec::new(),
                value_flow: bonsai_lang_api::ExpressionFlow::default(),
                exact_callable_return: None,
                exact_static_call_args: None,
                direct_call_name: None,
                direct_call_receiver: None,
            });
    }
    index.assignment_values.sort_by_key(|fact| {
        (
            fact.assignment_span.start,
            fact.assignment_span.end,
            fact.target_span.map_or(0, |span| span.start),
            fact.target_span.map_or(0, |span| span.end),
            fact.value_span.start,
            fact.value_span.end,
        )
    });
    index.assignment_values.dedup();
}

#[derive(Clone, Debug)]
struct TsGraphqlRootResolver {
    name: String,
    arg_fields: Vec<String>,
}

#[derive(Clone, Debug)]
struct TsGraphqlResolverDispatch {
    call_span: bonsai_common::Span,
    arg_span: bonsai_common::Span,
    variable_values: String,
    resolvers: Vec<TsGraphqlRootResolver>,
}

fn inject_typescript_graphql_root_resolver_calls(
    decl_index: &mut DeclIndex,
    tree: &Tree,
    src: &[u8],
    file: FileId,
) {
    let dispatches = collect_typescript_graphql_resolver_dispatches(tree, src, file);
    if dispatches.is_empty() {
        return;
    }
    for decl in &mut decl_index.defs {
        let owner_span = decl.body_span.unwrap_or(decl.span);
        let relevant = dispatches
            .iter()
            .filter(|dispatch| span_contains_or_equal(owner_span, dispatch.call_span))
            .cloned()
            .collect::<Vec<_>>();
        if !relevant.is_empty() {
            insert_graphql_resolver_dispatches(&mut decl.flow_events, &relevant);
        }
    }
}

fn collect_typescript_graphql_resolver_dispatches(
    tree: &Tree,
    src: &[u8],
    file: FileId,
) -> Vec<TsGraphqlResolverDispatch> {
    let root_resolvers = collect_typescript_graphql_root_resolvers(tree, src);
    if root_resolvers.is_empty() {
        return Vec::new();
    }
    let mut out = Vec::new();
    for call in collect_kinds(tree, &["call_expression"]) {
        if !typescript_graphql_execute_call(&call, src) {
            continue;
        }
        let Some(args) = call.child_by_field_name("arguments") else {
            continue;
        };
        let Some(config) = first_named_child_of_kind(&args, "object") else {
            continue;
        };
        let Some(root_value) = typescript_object_pair_value(config, src, "rootValue") else {
            continue;
        };
        let root_name = node_text(&root_value, src).trim();
        if root_name.is_empty()
            || !root_name
                .chars()
                .all(|ch| ch == '_' || ch == '$' || ch.is_ascii_alphanumeric())
        {
            continue;
        }
        let Some(variable_values) = typescript_object_pair_value(config, src, "variableValues") else {
            continue;
        };
        let variable_values_text = node_text(&variable_values, src).trim().to_string();
        if variable_values_text.is_empty() {
            continue;
        }
        let Some(resolvers) = root_resolvers.get(root_name) else {
            continue;
        };
        if resolvers.is_empty() {
            continue;
        }
        out.push(TsGraphqlResolverDispatch {
            call_span: span_of(file, &call),
            arg_span: span_of(file, &variable_values),
            variable_values: variable_values_text,
            resolvers: resolvers.clone(),
        });
    }
    out
}

fn collect_typescript_graphql_root_resolvers(
    tree: &Tree,
    src: &[u8],
) -> std::collections::HashMap<String, Vec<TsGraphqlRootResolver>> {
    let mut out = std::collections::HashMap::new();
    for declarator in collect_kinds(tree, &["variable_declarator"]) {
        let Some(name_node) = declarator.child_by_field_name("name") else {
            continue;
        };
        if name_node.kind() != "identifier" {
            continue;
        }
        let Some(value_node) = declarator.child_by_field_name("value") else {
            continue;
        };
        if value_node.kind() != "object" {
            continue;
        }
        let name = node_text(&name_node, src).trim().to_string();
        if name.is_empty() {
            continue;
        }
        let resolvers = typescript_object_resolvers(value_node, src);
        if !resolvers.is_empty() {
            out.insert(name, resolvers);
        }
    }
    out
}

fn typescript_object_resolvers(object: Node<'_>, src: &[u8]) -> Vec<TsGraphqlRootResolver> {
    let mut out = Vec::new();
    let mut cursor = object.walk();
    for child in object.named_children(&mut cursor) {
        match child.kind() {
            "pair" => {
                let Some(key_node) = child.child_by_field_name("key") else {
                    continue;
                };
                let Some(value_node) = child.child_by_field_name("value") else {
                    continue;
                };
                if !matches!(
                    value_node.kind(),
                    "arrow_function" | "function" | "function_expression" | "generator_function"
                ) {
                    continue;
                }
                let Some(name) = typescript_object_field_key(key_node, src) else {
                    continue;
                };
                out.push(TsGraphqlRootResolver {
                    name,
                    arg_fields: typescript_first_param_object_fields(value_node, src),
                });
            }
            "method_definition" => {
                let Some(name_node) = child.child_by_field_name("name") else {
                    continue;
                };
                let Some(name) = typescript_object_field_key(name_node, src) else {
                    continue;
                };
                out.push(TsGraphqlRootResolver {
                    name,
                    arg_fields: typescript_first_param_object_fields(child, src),
                });
            }
            _ => {}
        }
    }
    out
}

fn typescript_graphql_execute_call(call: &Node<'_>, src: &[u8]) -> bool {
    let Some(callee) = call.child_by_field_name("function") else {
        return false;
    };
    let callee_text = node_text(&callee, src).trim();
    let tail = callee_text
        .rsplit(['.', ':'])
        .find(|part| !part.trim().is_empty())
        .unwrap_or(callee_text)
        .trim();
    matches!(tail, "graphql" | "execute")
}

fn typescript_object_pair_value<'tree>(object: Node<'tree>, src: &[u8], key: &str) -> Option<Node<'tree>> {
    let mut cursor = object.walk();
    for child in object.named_children(&mut cursor) {
        if child.kind() != "pair" {
            continue;
        }
        let Some(key_node) = child.child_by_field_name("key") else {
            continue;
        };
        if typescript_object_field_key(key_node, src).as_deref() != Some(key) {
            continue;
        }
        return child.child_by_field_name("value");
    }
    None
}

fn typescript_object_field_key(node: Node<'_>, src: &[u8]) -> Option<String> {
    let raw = node_text(&node, src).trim();
    let key = raw
        .strip_prefix('"')
        .and_then(|part| part.strip_suffix('"'))
        .or_else(|| raw.strip_prefix('\'').and_then(|part| part.strip_suffix('\'')))
        .or_else(|| raw.strip_prefix('`').and_then(|part| part.strip_suffix('`')))
        .unwrap_or(raw)
        .trim();
    if key.is_empty()
        || !key
            .chars()
            .all(|ch| ch == '_' || ch == '$' || ch.is_ascii_alphanumeric())
    {
        return None;
    }
    Some(key.to_string())
}

fn typescript_first_param_object_fields(callable: Node<'_>, src: &[u8]) -> Vec<String> {
    let Some(params) = callable
        .child_by_field_name("parameters")
        .or_else(|| first_named_child_of_kind(&callable, "formal_parameters"))
    else {
        return Vec::new();
    };
    let mut cursor = params.walk();
    let Some(first_param) = params.named_children(&mut cursor).find(|child| {
        matches!(
            child.kind(),
            "required_parameter" | "optional_parameter" | "identifier" | "object_pattern"
        )
    }) else {
        return Vec::new();
    };
    let pattern = first_param.child_by_field_name("pattern").unwrap_or(first_param);
    let object_pattern = if pattern.kind() == "object_pattern" {
        Some(pattern)
    } else {
        first_named_child_of_kind(&pattern, "object_pattern")
    };
    let Some(object_pattern) = object_pattern else {
        return Vec::new();
    };
    let mut out = Vec::new();
    collect_typescript_object_pattern_fields(object_pattern, src, &mut out);
    out.sort();
    out.dedup();
    out
}

fn collect_typescript_object_pattern_fields(pattern: Node<'_>, src: &[u8], out: &mut Vec<String>) {
    let mut cursor = pattern.walk();
    for child in pattern.named_children(&mut cursor) {
        match child.kind() {
            "shorthand_property_identifier_pattern" => {
                let field = node_text(&child, src).trim();
                if !field.is_empty() {
                    out.push(field.to_string());
                }
            }
            "pair_pattern" => {
                if let Some(key_node) = child.child_by_field_name("key") {
                    if let Some(field) = typescript_object_field_key(key_node, src) {
                        out.push(field);
                    }
                }
            }
            _ => collect_typescript_object_pattern_fields(child, src, out),
        }
    }
}

fn insert_graphql_resolver_dispatches(events: &mut Vec<FlowEvent>, dispatches: &[TsGraphqlResolverDispatch]) {
    let mut index = 0usize;
    while index < events.len() {
        match &mut events[index] {
            FlowEvent::Branch {
                then_events,
                else_events,
                ..
            } => {
                insert_graphql_resolver_dispatches(then_events, dispatches);
                insert_graphql_resolver_dispatches(else_events, dispatches);
            }
            FlowEvent::Loop { body, .. } | FlowEvent::Defer { body, .. } | FlowEvent::Using { body, .. } => {
                insert_graphql_resolver_dispatches(body, dispatches);
            }
            FlowEvent::Try {
                body,
                catch_events,
                finally_events,
                ..
            } => {
                insert_graphql_resolver_dispatches(body, dispatches);
                insert_graphql_resolver_dispatches(catch_events, dispatches);
                insert_graphql_resolver_dispatches(finally_events, dispatches);
            }
            _ => {}
        }

        let inserts = match &events[index] {
            FlowEvent::Call { span, name, .. } if matches!(name.as_str(), "graphql" | "execute") => {
                dispatches
                    .iter()
                    .filter(|dispatch| spans_overlap_or_contain(*span, dispatch.call_span))
                    .flat_map(graphql_dispatch_call_events)
                    .filter(|event| !graphql_dispatch_event_exists(events, event))
                    .collect::<Vec<_>>()
            }
            _ => Vec::new(),
        };
        if inserts.is_empty() {
            index += 1;
            continue;
        }
        let inserted = inserts.len();
        let insert_at = index + 1;
        events.splice(insert_at..insert_at, inserts);
        index += inserted + 1;
    }
}

fn graphql_dispatch_call_events(dispatch: &TsGraphqlResolverDispatch) -> Vec<FlowEvent> {
    let mut out = Vec::new();
    for resolver in &dispatch.resolvers {
        let arg_text = if resolver.arg_fields.len() == 1 {
            format!("{}.{}", dispatch.variable_values, resolver.arg_fields[0])
        } else {
            dispatch.variable_values.clone()
        };
        out.push(FlowEvent::Call {
            span: dispatch.call_span,
            receiver: None,
            receiver_types: Vec::new(),
            name: resolver.name.clone(),
            call_kind: CallKind::Function,
            args: vec![CallArg {
                passing_mode: Default::default(),
                span: dispatch.arg_span,
                name: None,
                place: Some(arg_text.clone()),
                source_names: vec![dispatch.variable_values.clone(), arg_text.clone()],
                value_text: arg_text,
            }],
        });
    }
    out
}

fn graphql_dispatch_event_exists(events: &[FlowEvent], candidate: &FlowEvent) -> bool {
    let FlowEvent::Call {
        span: wanted_span,
        name: wanted_name,
        ..
    } = candidate
    else {
        return false;
    };
    events.iter().any(|event| match event {
        FlowEvent::Call { span, name, .. } => span == wanted_span && name == wanted_name,
        FlowEvent::Branch {
            then_events,
            else_events,
            ..
        } => {
            graphql_dispatch_event_exists(then_events, candidate)
                || graphql_dispatch_event_exists(else_events, candidate)
        }
        FlowEvent::Loop { body, .. } | FlowEvent::Defer { body, .. } | FlowEvent::Using { body, .. } => {
            graphql_dispatch_event_exists(body, candidate)
        }
        FlowEvent::Try {
            body,
            catch_events,
            finally_events,
            ..
        } => {
            graphql_dispatch_event_exists(body, candidate)
                || graphql_dispatch_event_exists(catch_events, candidate)
                || graphql_dispatch_event_exists(finally_events, candidate)
        }
        _ => false,
    })
}

fn span_contains_or_equal(outer: bonsai_common::Span, inner: bonsai_common::Span) -> bool {
    outer.file == inner.file && outer.start <= inner.start && outer.end >= inner.end
}

fn spans_overlap_or_contain(left: bonsai_common::Span, right: bonsai_common::Span) -> bool {
    left.file == right.file
        && (span_contains_or_equal(left, right)
            || span_contains_or_equal(right, left)
            || (left.start < right.end && right.start < left.end))
}

/// Combine ES-module imports, CommonJS `require(...)` calls, and the
/// TypeScript-only `import x = require("y")` legacy form. Delegates to
/// the JS helpers so the two adapters cannot drift on import semantics.
fn parse_imports(tree: &Tree, src: &[u8], file: FileId) -> Vec<ImportSpec> {
    let mut imports = js_ts_imports(file, tree, src);
    // Dedup against `import_alias`: the JS helper sees an anonymous `require("y")`
    // and would emit `alias=None` for the same module the TS-specific pass below
    // emits with `alias=Some("x")`.
    let mut require_calls = js_ts_require_calls(file, tree, src);
    let alias_call_spans = ts_import_alias_call_spans(tree);
    require_calls.retain(|spec| !span_inside_any(spec.span, &alias_call_spans));
    imports.extend(require_calls);
    // `import x = require("y")` — TS legacy form. tree-sitter-typescript wraps it
    // in `import_alias` (not `import_statement`), so the JS helper never sees it.
    imports.extend(parse_ts_import_alias(file, tree, src));
    imports
}

/// Return the byte spans of every `call_expression` that lives
/// inside an `import_alias` node. Used to dedup the JS helper's
/// anonymous emission against the TS-specific aliased emission.
fn ts_import_alias_call_spans(tree: &Tree) -> Vec<(u32, u32)> {
    let mut alias_call_spans = Vec::new();
    for alias_node in collect_kinds(tree, &["import_alias"]) {
        let mut stack = vec![alias_node];
        while let Some(current) = stack.pop() {
            if current.kind() == "call_expression" {
                let start = current.start_byte() as u32;
                let end = current.end_byte() as u32;
                alias_call_spans.push((start, end));
            }
            // Descend even past `call_expression` — nested forms are rare but possible.
            let mut cursor = current.walk();
            for child in current.named_children(&mut cursor) {
                stack.push(child);
            }
        }
    }
    alias_call_spans
}

/// True when `span` is byte-contained within any of the given ranges.
/// Used to suppress duplicate require-call imports that already have an
/// `import_alias` entry above them.
fn span_inside_any(span: bonsai_common::Span, ranges: &[(u32, u32)]) -> bool {
    ranges
        .iter()
        .any(|&(start, end)| span.start >= u64::from(start) && span.end <= u64::from(end))
}

/// Parse TypeScript-only `import x = require("y")` statements. The
/// grammar wraps these in `import_alias` nodes whose `name` field
/// holds `x` and whose `value` field is a call to `require` with a
/// single string argument. Emits a single Module-scope ImportSpec
/// with `alias = Some("x")` so resolve sees `x` as an alias for
/// the `y` module.
fn parse_ts_import_alias(file: FileId, tree: &Tree, src: &[u8]) -> Vec<ImportSpec> {
    let mut imports = Vec::new();
    for alias_node in collect_kinds(tree, &["import_alias"]) {
        let local_alias = alias_node
            .child_by_field_name("name")
            .map(|name_node| node_text(&name_node, src).to_string());
        // Prefer the documented `value` field; fall back to the first `call_expression`
        // named child to tolerate grammar revisions that expose the require call differently.
        let value_node = alias_node.child_by_field_name("value").or_else(|| {
            let mut cursor = alias_node.walk();
            // Bind explicitly so the cursor outlives the iterator return.
            let found = alias_node
                .named_children(&mut cursor)
                .find(|child| child.kind() == "call_expression");
            found
        });
        let Some(value_node) = value_node else { continue };
        // The value is typically `require("...")`; pull the module path from the first string.
        let module = first_named_child_of_kind(&value_node, "string")
            .and_then(|string_node| first_named_child_of_kind(&string_node, "string_fragment"))
            .map(|fragment| node_text(&fragment, src).to_string())
            .unwrap_or_else(|| {
                // Fallback: walk for any `string_fragment` descendant. Rare, but covers
                // grammars that nest the literal under different node kinds.
                let mut stack = vec![value_node];
                while let Some(current) = stack.pop() {
                    if current.kind() == "string_fragment" {
                        return node_text(&current, src).to_string();
                    }
                    let mut cursor = current.walk();
                    for child in current.named_children(&mut cursor) {
                        stack.push(child);
                    }
                }
                String::new()
            });
        if module.is_empty() {
            continue;
        }
        imports.push(ImportSpec {
            span: span_of(file, &alias_node),
            module,
            alias: local_alias,
            is_wildcard: false,
            original_name: None,
            scope: ImportScope::Module,
        });
    }
    imports
}

/// Whether a declaration kind can carry a base list (`extends` / `implements`).
fn is_class_like(kind: DeclKind) -> bool {
    matches!(
        kind,
        DeclKind::Class | DeclKind::Interface | DeclKind::Trait | DeclKind::Struct | DeclKind::Enum
    )
}

/// WS2 cast-expression typing. A `const c = make() as Foo` / `const c =
/// <Foo>make()` carries its type ONLY on the cast — the declared-type
/// extractor (`collect_param_type_aliases` handles params, not locals)
/// and the return-type path (`make(): Foo`) both miss it. Capture the
/// cast type as a per-enclosing-function `c -> Foo` alias so
/// `c.method(tainted)` resolves `receiver_type_in: [Foo]` / `[Foo, m]`.
///
/// Keyed by the enclosing function declaration's span (matching how
/// `collect_param_type_aliases` keys). The cast's type node is authoritative;
/// capitalization is only a style convention and must not filter facts.
fn collect_typescript_cast_aliases(
    tree: &Tree,
    file: FileId,
    src: &[u8],
) -> std::collections::HashMap<bonsai_common::Span, Vec<TypeAliasBinding>> {
    const FN_KINDS: &[&str] = &[
        "function_declaration",
        "function_expression",
        "method_definition",
        "arrow_function",
        "generator_function_declaration",
    ];
    let mut out = std::collections::HashMap::new();
    for fn_node in collect_kinds(tree, FN_KINDS) {
        let mut aliases: Vec<TypeAliasBinding> = Vec::new();
        let mut work = vec![fn_node];
        while let Some(node) = work.pop() {
            // A nested function owns its own locals — let its own
            // iteration scope them rather than leaking into the parent.
            if node != fn_node && FN_KINDS.contains(&node.kind()) {
                continue;
            }
            if node.kind() == "variable_declarator" {
                extend_ts_aliases_from_cast(node, src, &mut aliases);
            }
            let mut cursor = node.walk();
            for child in node.named_children(&mut cursor) {
                work.push(child);
            }
        }
        if !aliases.is_empty() {
            out.insert(span_of(file, &fn_node), aliases);
        }
    }
    out
}

/// Emit a `name -> Type` alias when a `variable_declarator`'s initializer
/// IS a cast (`x as Foo` / `<Foo>x`). Reads only the declarator's `value`
/// field, so a cast nested in a call argument (`const c = wrap(x as Foo)`)
/// does NOT mistype the local — only a cast that is the whole initializer.
fn extend_ts_aliases_from_cast(declarator: Node<'_>, src: &[u8], aliases: &mut Vec<TypeAliasBinding>) {
    let Some(name_node) = declarator.child_by_field_name("name") else {
        return;
    };
    // Only simple identifier bindings (`const c = ...`); destructuring
    // patterns don't bind a single receiver.
    if name_node.kind() != "identifier" {
        return;
    }
    let name = node_text(&name_node, src).trim().to_string();
    if name.is_empty() {
        return;
    }
    let Some(value) = declarator.child_by_field_name("value") else {
        return;
    };
    // `x as Foo` is `as_expression`; `<Foo>x` is `type_assertion`.
    if !matches!(value.kind(), "as_expression" | "type_assertion") {
        return;
    }
    let Some(type_name) = ts_cast_type_name(value, src) else {
        return;
    };
    if type_name.is_empty() {
        return;
    }
    aliases.push(TypeAliasBinding { name, type_name });
}

/// The cast's target type. For `x as Foo` the `type_identifier` is the
/// trailing child; for `<Foo>x` it is the leading child. Generic casts
/// (`as Foo<T>`) surface a `generic_type` whose `name` is the base type.
fn ts_cast_type_name(cast: Node<'_>, src: &[u8]) -> Option<String> {
    let mut cursor = cast.walk();
    for child in cast.named_children(&mut cursor) {
        match child.kind() {
            "type_identifier" => return Some(node_text(&child, src).trim().to_string()),
            "generic_type" => {
                if let Some(name) = child.child_by_field_name("name") {
                    return Some(node_text(&name, src).trim().to_string());
                }
            }
            // `<Foo>x` (type_assertion) nests the type under `type_arguments`.
            "type_arguments" => {
                let mut inner = child.walk();
                for ty in child.named_children(&mut inner) {
                    match ty.kind() {
                        "type_identifier" => return Some(node_text(&ty, src).trim().to_string()),
                        "generic_type" => {
                            if let Some(name) = ty.child_by_field_name("name") {
                                return Some(node_text(&name, src).trim().to_string());
                            }
                        }
                        _ => {}
                    }
                }
            }
            _ => {}
        }
    }
    None
}

/// TypeScript parameter properties are the syntax-level equivalent of:
///
///   constructor(private readonly diag: DiagService) { this.diag = diag; }
///
/// Tree-sitter exposes this as a normal constructor parameter carrying
/// an `accessibility_modifier` token rather than an assignment event. Emit
/// the same `this.diag -> DiagService` type and `this.diag` field-write facts
/// that a handwritten assignment would have produced, but only for the
/// syntactic parameter-property forms (`public` / `private` / `protected` /
/// `readonly`). The ordinary parameter type (`diag -> DiagService`) is already
/// lowered by `collect_param_type_aliases`.
fn collect_typescript_parameter_properties(
    tree: &Tree,
    file: FileId,
    src: &[u8],
) -> std::collections::HashMap<bonsai_common::Span, Vec<(TypeAliasBinding, FieldWrite)>> {
    let mut out = std::collections::HashMap::new();
    for ctor in collect_kinds(tree, &["method_definition"]) {
        if !typescript_method_name_is(&ctor, src, "constructor") {
            continue;
        }
        let Some(params_node) = ctor
            .child_by_field_name("parameters")
            .or_else(|| first_named_child_of_kind(&ctor, "formal_parameters"))
        else {
            continue;
        };

        let mut bindings: Vec<(TypeAliasBinding, FieldWrite)> = Vec::new();
        let mut param_index = 0usize;
        let mut cursor = params_node.walk();
        for param in params_node.named_children(&mut cursor) {
            if !matches!(param.kind(), "required_parameter" | "optional_parameter") {
                continue;
            }
            let current_index = param_index;
            param_index += 1;

            if !typescript_parameter_property_declares_field(&param, src) {
                continue;
            }
            let Some(name) = typescript_parameter_property_name(&param, src) else {
                continue;
            };
            let Some(type_name) = typescript_parameter_property_type(&param, src) else {
                continue;
            };
            if name.is_empty() || name == type_name {
                continue;
            }
            // A parameter property is a TypeScript syntax-level declaration
            // of the receiver field. Record that exact receiver projection so
            // shared class-field propagation does not need to invent a
            // synthetic assignment event to prove the type.
            let receiver_field = format!("this.{name}");
            let alias = TypeAliasBinding {
                name: receiver_field.clone(),
                type_name,
            };
            let field_write = FieldWrite {
                span: span_of(file, &param),
                target: receiver_field,
                source_param_indices: vec![current_index],
            };
            let entry = (alias, field_write);
            if !bindings.contains(&entry) {
                bindings.push(entry);
            }
        }
        if !bindings.is_empty() {
            out.insert(span_of(file, &ctor), bindings);
        }
    }
    out
}

fn typescript_method_name_is(node: &Node<'_>, src: &[u8], expected: &str) -> bool {
    node.child_by_field_name("name")
        .map(|name| node_text(&name, src).trim() == expected)
        .unwrap_or(false)
}

fn typescript_parameter_property_declares_field(param: &Node<'_>, src: &[u8]) -> bool {
    let mut cursor = param.walk();
    for child in param.named_children(&mut cursor) {
        let kind = child.kind();
        if matches!(kind, "accessibility_modifier" | "readonly_modifier") || kind.contains("readonly") {
            return true;
        }
    }
    let Some(pattern) = param.child_by_field_name("pattern") else {
        return false;
    };
    if pattern.start_byte() <= param.start_byte() || pattern.start_byte() > src.len() {
        return false;
    }
    let prefix = std::str::from_utf8(&src[param.start_byte()..pattern.start_byte()]).unwrap_or_default();
    prefix
        .split(|ch: char| !(ch.is_ascii_alphanumeric() || ch == '_'))
        .any(|token| matches!(token, "public" | "private" | "protected" | "readonly"))
}

fn typescript_parameter_property_name(param: &Node<'_>, src: &[u8]) -> Option<String> {
    let pattern = param.child_by_field_name("pattern")?;
    typescript_identifier_leaf(pattern, src)
}

fn typescript_parameter_property_type(param: &Node<'_>, src: &[u8]) -> Option<String> {
    let type_node = param.child_by_field_name("type")?;
    typescript_type_name_leaf(type_node, src)
}

fn typescript_identifier_leaf(node: Node<'_>, src: &[u8]) -> Option<String> {
    if matches!(
        node.kind(),
        "identifier" | "shorthand_property_identifier_pattern" | "private_property_identifier"
    ) {
        let name = node_text(&node, src).trim().trim_start_matches('#').to_string();
        return (!name.is_empty()).then_some(name);
    }
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        if let Some(name) = typescript_identifier_leaf(child, src) {
            return Some(name);
        }
    }
    None
}

fn typescript_type_name_leaf(node: Node<'_>, src: &[u8]) -> Option<String> {
    match node.kind() {
        "type_identifier" | "identifier" | "predefined_type" | "nested_type_identifier" => {
            return canonical_ts_type_name(node_text(&node, src));
        }
        "generic_type" => {
            if let Some(name) = node.child_by_field_name("name") {
                return canonical_ts_type_name(node_text(&name, src));
            }
        }
        _ => {}
    }
    let mut cursor = node.walk();
    for child in node.named_children(&mut cursor) {
        if let Some(type_name) = typescript_type_name_leaf(child, src) {
            return Some(type_name);
        }
    }
    None
}

fn canonical_ts_type_name(raw: &str) -> Option<String> {
    let raw = raw.trim().trim_start_matches(':').trim();
    let name = canonical_ts_base_name(raw)?;
    name.chars()
        .next()
        .is_some_and(|ch| ch.is_ascii_alphabetic() || ch == '_')
        .then_some(name)
}

/// Walk TS class / interface / abstract-class declarations and
/// collect bare base type names. Grammar shape:
///
///   `class Echo extends WebSocketHandler implements Mixin { ... }` →
///     (class_declaration name: (type_identifier)
///        (class_heritage
///           (extends_clause value: (identifier))
///           (implements_clause (type_identifier))))
///
/// `interface_declaration` uses `extends_type_clause` (multiple
/// type identifiers under one wrapper) instead of `class_heritage`.
fn collect_typescript_class_bases(
    tree: &Tree,
    file: FileId,
    src: &[u8],
) -> Vec<(bonsai_common::Span, Vec<String>)> {
    let mut bases_by_class = Vec::new();
    let class_kinds = &[
        "class_declaration",
        "abstract_class_declaration",
        "class",
        "interface_declaration",
    ];
    for class_node in collect_kinds(tree, class_kinds) {
        let mut bases: Vec<String> = Vec::new();
        let mut class_cursor = class_node.walk();
        for class_child in class_node.named_children(&mut class_cursor) {
            match class_child.kind() {
                // Class wrapper containing both `extends_clause` and `implements_clause`.
                "class_heritage" => {
                    collect_ts_heritage_names(class_child, src, &mut bases);
                }
                // `interface_declaration` and direct `extends_clause` children.
                "extends_type_clause" | "extends_clause" => {
                    collect_ts_heritage_names(class_child, src, &mut bases);
                }
                _ => {}
            }
        }
        if !bases.is_empty() {
            bases_by_class.push((span_of(file, &class_node), bases));
        }
    }
    bases_by_class
}

/// Walk a TS heritage wrapper (class_heritage / extends_clause /
/// implements_clause / extends_type_clause) and pick out every
/// identifier-like base name. Generics → leftmost name.
fn collect_ts_heritage_names(node: Node<'_>, src: &[u8], collected_bases: &mut Vec<String>) {
    let mut stack = vec![node];
    while let Some(current) = stack.pop() {
        match current.kind() {
            // Wrapper kinds — descend; the actual identifier is one or more levels down.
            "extends_clause" | "implements_clause" | "extends_type_clause" | "class_heritage" => {
                let mut cursor = current.walk();
                for child in current.named_children(&mut cursor) {
                    stack.push(child);
                }
            }
            "identifier" | "type_identifier" => {
                if let Some(name) = canonical_ts_base_name(node_text(&current, src)) {
                    if !collected_bases.iter().any(|b| b == &name) {
                        collected_bases.push(name);
                    }
                }
            }
            "generic_type" => {
                // `Foo<T>` — keep `Foo` and skip `type_arguments` entirely so we
                // don't accidentally collect `T` as a base.
                if let Some(name_child) = current.child_by_field_name("name") {
                    if let Some(name) = canonical_ts_base_name(node_text(&name_child, src)) {
                        if !collected_bases.iter().any(|b| b == &name) {
                            collected_bases.push(name);
                        }
                    }
                } else {
                    // Fallback for grammars without the `name` field: take the
                    // first identifier-like child and stop.
                    let mut cursor = current.walk();
                    for child in current.named_children(&mut cursor) {
                        if matches!(child.kind(), "identifier" | "type_identifier") {
                            if let Some(name) = canonical_ts_base_name(node_text(&child, src)) {
                                if !collected_bases.iter().any(|b| b == &name) {
                                    collected_bases.push(name);
                                }
                            }
                            break;
                        }
                    }
                }
            }
            "nested_type_identifier" | "nested_identifier" => {
                // `Foo.Bar` — `canonical_ts_base_name` keeps only the right-most segment.
                if let Some(name) = canonical_ts_base_name(node_text(&current, src)) {
                    if !collected_bases.iter().any(|b| b == &name) {
                        collected_bases.push(name);
                    }
                }
            }
            _ => {
                // Unknown wrapper — keep descending; we'd rather over-walk than miss a base.
                let mut cursor = current.walk();
                for child in current.named_children(&mut cursor) {
                    stack.push(child);
                }
            }
        }
    }
}

/// Reduce a heritage type expression to a bare class/interface name:
/// strips generics (`Foo<T>` -> `Foo`) and nested-type prefixes
/// (`mod.Foo` -> `Foo`). Returns `None` if nothing usable remains.
fn canonical_ts_base_name(raw: &str) -> Option<String> {
    let trimmed = raw.trim();
    // Drop generic argument list before any path split — `mod.Foo<T>` should yield `Foo`.
    let without_generics = trimmed.split('<').next().unwrap_or(trimmed).trim();
    let bare = without_generics
        .rsplit('.')
        .next()
        .unwrap_or(without_generics)
        .trim();
    if bare.is_empty() {
        return None;
    }
    Some(bare.to_string())
}