fallow-extract 3.22.0

AST extraction engine for fallow codebase intelligence (parser, complexity, SFC / Astro / MDX / CSS)
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
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
//! Astro component frontmatter extraction.
//!
//! Extracts the TypeScript code between `---` delimiters in `.astro` files,
//! plus `<script src="...">` references and inline `<script>` import
//! statements from the template body. Astro bundles per-component client
//! scripts at build time when the script tag opts into Astro processing, so
//! both processed reference shapes must keep their targets reachable.

use std::path::Path;
use std::sync::LazyLock;

use oxc_allocator::Allocator;
use oxc_ast_visit::Visit;
use oxc_parser::Parser;
use oxc_span::{SourceType, Span};
use rustc_hash::FxHashSet;

use crate::asset_url::normalize_asset_url;
use crate::html::is_remote_url;
use crate::sfc::{SfcScript, SourceRegion};
use crate::source_map::ExtractionResult;
use crate::template_expression_scan::{
    TemplateScanMode, guarded_import_locals, import_declaration_ranges, merge_ranges,
    narrowable_import_locals, pos_in_ranges, record_unexplained_mentions,
    record_unexplained_script_mentions, recorded_member_pairs, scan_template_usage,
};
use crate::visitor::{
    ModuleInfoExtractor, extend_member_accesses, extend_whole_object_uses, push_member_tag_accesses,
};
use crate::{ImportInfo, ImportedName, MemberAccess, ModuleInfo};
use fallow_types::discover::FileId;

/// Regex to extract Astro frontmatter (content between `---` delimiters at file start).
static ASTRO_FRONTMATTER_RE: LazyLock<regex::Regex> =
    LazyLock::new(|| crate::static_regex(r"(?s)\A\s*---[ \t]*\r?\n(?P<body>.*?\r?\n)---"));

/// Regex matching `<script>` blocks in the Astro template body. Captures the
/// attribute list and the body so callers can decide whether to follow `src=`
/// or parse the inline body as TypeScript.
static SCRIPT_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
    crate::static_regex(
        r#"(?is)<script\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>(?P<body>[\s\S]*?)</script>"#,
    )
});

/// Regex matching opening `<script>` tags in the Astro template body.
static SCRIPT_OPEN_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
    crate::static_regex(r#"(?is)<script\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>"#)
});

/// Regex matching `<style>` blocks in the Astro template body.
static STYLE_BLOCK_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
    crate::static_regex(
        r#"(?is)<style\b(?P<attrs>(?:[^>"']|"[^"]*"|'[^']*')*)>(?P<body>[\s\S]*?)</style>"#,
    )
});

/// Regex detecting and capturing a `src` attribute on a script tag.
static SRC_ATTR_RE: LazyLock<regex::Regex> =
    LazyLock::new(|| crate::static_regex(r#"(?i)(?:^|\s)src\s*=\s*["'](?P<src>[^"']+)["']"#));

/// Regex matching HTML comments for stripping before template scanning.
static HTML_COMMENT_RE: LazyLock<regex::Regex> =
    LazyLock::new(|| crate::static_regex(r"(?s)<!--.*?-->"));

/// Regex matching JavaScript identifier tokens for template-usage scanning.
static TEMPLATE_IDENT_RE: LazyLock<regex::Regex> =
    LazyLock::new(|| crate::static_regex(r"[A-Za-z_$][A-Za-z0-9_$]*"));

/// Regex matching the root identifier of an opening/closing markup tag
/// (`<Header`, `</Header`, `<ui.Card` -> `ui`). The capture stops at the first
/// non-identifier byte, so a dotted namespace tag yields its root binding.
static TEMPLATE_TAG_RE: LazyLock<regex::Regex> =
    LazyLock::new(|| crate::static_regex(r"</?\s*([A-Za-z_$][A-Za-z0-9_$]*)"));

/// Regex matching an opening member-expression component tag (`<SC.Card`,
/// `<A.B.C`) and capturing its full dotted name. Opening tags only, so a paired
/// closing tag does not double-record. The whitespace allowance after `<`
/// mirrors `TEMPLATE_TAG_RE`, so every dotted tag whose root the used-name scan
/// credits also feeds the member-access stream (issue #2355).
static TEMPLATE_MEMBER_TAG_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
    crate::static_regex(r"<\s*([A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)+)")
});

/// Regex matching the `define:vars=` directive prefix. The expression object
/// that follows (`define:vars={{ a, b: c }}`) passes frontmatter values into a
/// scoped `<style>` / `<script>` / element, so the identifiers it references are
/// real prop / import uses.
static DEFINE_VARS_RE: LazyLock<regex::Regex> =
    LazyLock::new(|| crate::static_regex(r"define:vars\s*="));

/// Build the disjoint, ascending list of byte ranges to mask when scanning the
/// Astro template: whole `<script>` / `<style>` blocks (opening tag included)
/// and HTML comments. The three `find_iter` passes are concatenated (not
/// globally sorted, and their ranges overlap when e.g. an HTML comment wraps a
/// `<script>`), then merged into a non-overlapping ascending list so membership
/// can be tested by binary search (`pos_in_ranges`) instead of a linear scan
/// over every range per position. The merged union covers exactly the same byte
/// positions as the raw ranges, so masking decisions are byte-identical.
fn build_masked_ranges(template: &str) -> Vec<(usize, usize)> {
    let mut masked: Vec<(usize, usize)> = Vec::new();
    masked.extend(
        SCRIPT_BLOCK_RE
            .find_iter(template)
            .map(|m| (m.start(), m.end())),
    );
    masked.extend(
        STYLE_BLOCK_RE
            .find_iter(template)
            .map(|m| (m.start(), m.end())),
    );
    masked.extend(
        HTML_COMMENT_RE
            .find_iter(template)
            .map(|m| (m.start(), m.end())),
    );
    merge_ranges(masked)
}

/// Collect the set of identifier names that appear USED in the Astro template
/// markup, so the frontmatter semantic pass does not mark a template-only-used
/// import (a rendered `<Header/>` component, or a `{fmt(x)}` expression binding)
/// as unused. Only two genuine usage positions are credited: component tag roots
/// (`<Header>`, `<ui.Card>`) and identifiers inside `{ ... }` expression regions
/// (attribute values and text expressions). Raw text content is deliberately NOT
/// scanned, so prose that happens to spell a component name (`references Header`)
/// does not credit the import. `<script>` / `<style>` blocks and HTML comments
/// are masked first so their identifiers (client-script locals, CSS) never
/// credit a frontmatter import. The complement (a frontmatter import referenced
/// in NEITHER the frontmatter script NOR a tag/expression position) is the
/// genuinely-dead case the `unused-import` / `unrendered-component` arms surface.
/// `masked` is the template's `build_masked_ranges` result: positions inside it
/// are skipped rather than mutating the source (mutation would corrupt
/// multibyte UTF-8 inside a masked range).
fn collect_astro_template_used_names(
    template: &str,
    masked: &[(usize, usize)],
) -> FxHashSet<String> {
    let mut used = FxHashSet::default();
    if template.is_empty() {
        return used;
    }
    let is_masked = |pos: usize| pos_in_ranges(masked, pos);

    // Component tag roots.
    for cap in TEMPLATE_TAG_RE.captures_iter(template) {
        if let Some(root) = cap.get(1)
            && !is_masked(root.start())
        {
            used.insert(root.as_str().to_string());
        }
    }

    // Identifiers inside `{ ... }` expression regions.
    collect_brace_expression_idents(template, &is_masked, &mut used);

    // Identifiers inside `define:vars={ ... }` directive values. These sit in the
    // opening tag of a `<style>` / `<script>` block (masked above), so they are
    // scanned separately over the unmasked template.
    collect_define_vars_idents(template, &mut used);

    used
}

/// Given `open` = the index of a `{` byte in `bytes`, return the index of the
/// matching `}` (exclusive region end), or `bytes.len()` if unterminated. The
/// scan is string-aware so braces inside quoted strings do not shift the depth.
/// All boundary bytes (`{`, `}`, quotes, backslash) are ASCII, so the returned
/// index always lands on a char boundary.
fn brace_body_end(bytes: &[u8], open: usize) -> usize {
    let len = bytes.len();
    let mut depth = 1usize;
    let mut j = open + 1;
    let mut quote: Option<u8> = None;
    while j < len && depth > 0 {
        let c = bytes[j];
        if let Some(q) = quote {
            if c == b'\\' {
                j += 1; // skip the escaped byte
            } else if c == q {
                quote = None;
            }
        } else {
            match c {
                b'"' | b'\'' | b'`' => quote = Some(c),
                b'{' => depth += 1,
                b'}' => depth -= 1,
                _ => {}
            }
        }
        j += 1;
    }
    // `j` is one past the matching `}` (or `len` if unterminated); the region body
    // excludes the closing brace.
    if depth == 0 { j - 1 } else { len }
}

/// Credit every identifier inside each `define:vars={ ... }` directive value.
/// Astro's `define:vars` injects frontmatter values into a scoped `<style>` /
/// `<script>` (or element) as the expression object, so a prop or import used
/// only there is a genuine use. Because the directive sits inside the opening tag
/// of a `<style>` / `<script>` block that the main scanner masks, this runs over
/// the unmasked template and matches the directive directly. Over-crediting (e.g.
/// an identifier-shaped fragment of a quoted CSS-variable key) only suppresses a
/// finding, never creates one.
fn collect_define_vars_idents(template: &str, used: &mut FxHashSet<String>) {
    let bytes = template.as_bytes();
    for m in DEFINE_VARS_RE.find_iter(template) {
        // Skip whitespace after `define:vars=` to the JSX expression `{`.
        let mut k = m.end();
        while k < bytes.len() && bytes[k].is_ascii_whitespace() {
            k += 1;
        }
        if k >= bytes.len() || bytes[k] != b'{' {
            continue;
        }
        let end = brace_body_end(bytes, k);
        if let Some(region) = template.get(k + 1..end) {
            for token in TEMPLATE_IDENT_RE.find_iter(region) {
                used.insert(token.as_str().to_string());
            }
        }
    }
}

/// Collect every identifier inside each top-level `{ ... }` expression region of
/// the Astro markup. The scan is depth-counted and string-aware so object
/// literals (`{ class: x }`) and strings containing braces do not break region
/// boundaries. Region boundaries (`{`, `}`, and quote bytes) are ASCII, so the
/// `template.get(..)` slice always lands on char boundaries even when the region
/// body contains multibyte text.
fn collect_brace_expression_idents(
    template: &str,
    is_masked: &impl Fn(usize) -> bool,
    used: &mut FxHashSet<String>,
) {
    let bytes = template.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    while i < len {
        if bytes[i] != b'{' || is_masked(i) {
            i += 1;
            continue;
        }
        let start = i + 1;
        let region_end = brace_body_end(bytes, i);
        if let Some(region) = template.get(start..region_end) {
            for token in TEMPLATE_IDENT_RE.find_iter(region) {
                used.insert(token.as_str().to_string());
            }
        }
        i = region_end.max(start);
    }
}

/// Collect the body byte range (`{` exclusive, `}` exclusive) of every
/// top-level `{ ... }` expression region in the Astro markup, skipping
/// `<script>` / `<style>` / HTML-comment ranges. Mirrors
/// `collect_brace_expression_idents`'s scan but returns each region's position
/// (for re-parsing and for the completeness guard) instead of tokenizing
/// identifiers. See issues #1713 and #2355.
fn collect_template_expression_regions(
    template: &str,
    masked: &[(usize, usize)],
) -> Vec<(usize, usize)> {
    let mut regions = Vec::new();
    if template.is_empty() {
        return regions;
    }
    let bytes = template.as_bytes();
    let len = bytes.len();
    let mut i = 0;
    while i < len {
        if bytes[i] != b'{' || pos_in_ranges(masked, i) {
            i += 1;
            continue;
        }
        let start = i + 1;
        let region_end = brace_body_end(bytes, i);
        if region_end > start {
            regions.push((start, region_end));
        }
        i = region_end.max(start);
    }
    regions
}

/// Collect the member accesses implied by member-expression component tags in
/// the Astro markup (`<SC.Card />` records `SC.Card`, `<A.B.C />` one access
/// per nesting level), skipping the same `<script>` / `<style>` / HTML-comment
/// ranges the used-name scan masks. The root credit from
/// `collect_astro_template_used_names` keeps the import binding alive; this
/// adds the member-level stream the JSX visitor records for `.tsx` (issue
/// #2348), so a namespace import rendered only through dotted tags narrows to
/// the members actually used instead of crediting nothing (entry files) or
/// everything (non-entry files). See issue #2355.
fn collect_template_member_tag_accesses(
    template: &str,
    masked: &[(usize, usize)],
) -> Vec<MemberAccess> {
    let mut accesses = Vec::new();
    if template.is_empty() {
        return accesses;
    }
    for cap in TEMPLATE_MEMBER_TAG_RE.captures_iter(template) {
        if let Some(name) = cap.get(1)
            && !pos_in_ranges(masked, name.start())
        {
            push_member_tag_accesses(&mut accesses, name.as_str());
        }
    }
    accesses
}

/// Run the member-recording visitor over every Astro template `{ ... }`
/// expression region and append what it records to `info`: the member accesses
/// (`icon={SC.Moon}`, `{SC.helper()}`) and whole-object uses (`{...SC}`,
/// `Object.keys(SC)`) the visitor records for `.tsx`, plus the class-qualified
/// iteration credits (`{utils.map((util) => util.getter)}` resolves to
/// `Util.getter` through the seeded frontmatter element types, issue #1713).
/// Each region is parsed as a standalone TSX expression (Astro template
/// expressions contain JSX) and visited by one extractor shared across the
/// file's regions. A bare mention of a frontmatter import binding inside a
/// parsed region (`all={SC}`) is the one shape the visitor does not record as
/// a whole-object use, so the text scan adds it.
///
/// Returns the byte ranges of the regions the parser accepted. Inside those,
/// every mention of an import binding is either a member access the visitor
/// recorded or a whole-object use the text scan recorded, so they count as
/// structurally understood for the completeness guard
/// (`extend_unexplained_template_mentions`). A region the parser rejects is
/// left out: its mentions stay unexplained and keep their bindings on the
/// mark-all path. See issue #2355.
fn extend_template_expression_usage(
    info: &mut ModuleInfo,
    template: &str,
    regions: &[(usize, usize)],
    frontmatter_array_element_types: &rustc_hash::FxHashMap<String, String>,
) -> Vec<(usize, usize)> {
    let mut parsed_regions = Vec::with_capacity(regions.len());
    if regions.is_empty() {
        return parsed_regions;
    }
    let import_locals: FxHashSet<&str> = info
        .imports
        .iter()
        .map(|import| import.local_name.as_str())
        .collect();
    let mut accesses = Vec::new();
    let mut whole_object_uses = Vec::new();
    let mut extractor = ModuleInfoExtractor::new();
    extractor.seed_array_binding_element_types(frontmatter_array_element_types);
    for &(start, end) in regions {
        let Some(region) = template.get(start..end) else {
            continue;
        };
        let region = region.trim();
        if region.is_empty() {
            continue;
        }
        // Wrap as a parenthesized expression statement so the region parses as a
        // valid TSX program. Spans are irrelevant: only span-less name pairs are
        // drained.
        let wrapped = format!("({region});");
        let allocator = Allocator::default();
        let parser_return = Parser::new(&allocator, &wrapped, SourceType::tsx()).parse();
        if parser_return.panicked || !parser_return.errors.is_empty() {
            continue;
        }
        extractor.visit_program(&parser_return.program);
        scan_template_usage(
            region,
            &import_locals,
            TemplateScanMode::AstroParsedRegion,
            &mut accesses,
            &mut whole_object_uses,
        );
        parsed_regions.push((start, end));
    }
    let (visited_accesses, visited_whole_object_uses) = extractor.take_template_expression_usage();
    accesses.extend(visited_accesses);
    whole_object_uses.extend(visited_whole_object_uses);
    extend_member_accesses(info, accesses);
    extend_whole_object_uses(info, whole_object_uses);
    parsed_regions
}

/// Completeness guard for the template-sourced access stream (issue #2355).
///
/// Namespace-import (and CSS-module, enum, class member) narrowing trusts the
/// member-access stream: one recorded access from a non-entry consumer narrows
/// the target to the accessed members, so every mention of a binding the
/// structured passes did not see would turn a used sibling into a finding. The
/// structured passes cover exactly two kinds of span: component tag roots
/// outside the masked ranges (the tag scans) and `{ ... }` regions the parser
/// accepted (the region visitor plus the bare-mention scan). Every other
/// mention of a frontmatter import binding in the raw template text, including
/// the masked `<script>` / `<style>` blocks and their opening-tag directives
/// (`define:vars={{ accent: NS.accent }}`, `set:html={NS.code}`), HTML
/// comments, attribute strings, text content, and regions the parser rejected,
/// records a whole-object use so the graph keeps mark-all crediting for that
/// binding. Together with `extend_unexplained_frontmatter_mentions` this
/// covers the whole file, so narrowing applies only when every mention was
/// structurally understood; any unmodelled shape degrades to over-credit.
fn extend_unexplained_template_mentions(
    info: &mut ModuleInfo,
    template: &str,
    masked: &[(usize, usize)],
    parsed_regions: Vec<(usize, usize)>,
) {
    let guarded = guarded_import_locals(&info.imports);
    if guarded.is_empty() || template.is_empty() {
        return;
    }
    let mut explained = parsed_regions;
    explained.extend(
        TEMPLATE_TAG_RE
            .captures_iter(template)
            .filter_map(|cap| cap.get(1))
            .filter(|root| !pos_in_ranges(masked, root.start()))
            .map(|root| (root.start(), root.end())),
    );
    let explained = merge_ranges(explained);
    let mut whole_object_uses = Vec::new();
    record_unexplained_mentions(template, &guarded, &explained, &mut whole_object_uses);
    extend_whole_object_uses(info, whole_object_uses);
}

/// Script-side completeness guard (issue #2355), the frontmatter half of
/// `extend_unexplained_template_mentions`. The visitor parsed the frontmatter,
/// but it records a bare import binding as a whole-object use only for an
/// allow-list of positions, so an alias (`const N = NS`), a cast (`NS as T`),
/// a call argument (`pick(NS)`), `Object.assign({}, NS)`, an array literal
/// (`[NS]`), or a props object (`{ all: NS }`) would leave the binding free to
/// narrow to its dotted accesses and report the members reached through the
/// copy. Every mention of a namespace or CSS-module binding (the bindings the
/// graph narrows exports for) in the frontmatter outside its own import
/// declaration that is not a dotted access the visitor recorded therefore
/// records a whole-object use; class and enum bindings keep the visitor's
/// member crediting, since a type annotation or `new` expression names them
/// bare in ordinary code. Runs after the template passes so the recorded pairs
/// cover the whole file.
fn extend_unexplained_frontmatter_mentions(info: &mut ModuleInfo, frontmatter: Option<&SfcScript>) {
    let Some(script) = frontmatter else {
        return;
    };
    let mut whole_object_uses = Vec::new();
    {
        let guarded = narrowable_import_locals(&info.imports);
        if guarded.is_empty() || script.body.is_empty() {
            return;
        }
        let recorded = recorded_member_pairs(&info.member_accesses, &guarded);
        let excluded = import_declaration_ranges(&info.imports);
        record_unexplained_script_mentions(
            &script.body,
            script.byte_offset,
            &guarded,
            &excluded,
            &recorded,
            &mut whole_object_uses,
        );
    }
    extend_whole_object_uses(info, whole_object_uses);
}

/// Extract frontmatter from an Astro component.
pub fn extract_astro_frontmatter(source: &str) -> Option<SfcScript> {
    ASTRO_FRONTMATTER_RE.captures(source).map(|cap| {
        let body_match = cap.name("body");
        SfcScript {
            body: body_match.map_or("", |m| m.as_str()).to_string(),
            is_typescript: true, // Astro frontmatter is always TS-compatible
            is_jsx: false,
            byte_offset: body_match.map_or(0, |m| m.start()),
            src: None,
            src_span: None,
            is_setup: false,
            is_context_module: false,
            generic_attr: None,
        }
    })
}

/// Extract Astro template markup regions while preserving original byte offsets.
///
/// Frontmatter, `<script>` blocks, `<style>` blocks, and HTML comments are
/// excluded. Inline scripts are deliberately not tokenized as markup; script
/// handling stays with the Astro extraction path that understands processed
/// Astro client scripts.
#[must_use]
pub fn extract_astro_template_regions(source: &str) -> Vec<SourceRegion> {
    let mut ranges = Vec::new();
    if let Some(frontmatter) = ASTRO_FRONTMATTER_RE.find(source) {
        ranges.push((frontmatter.start(), frontmatter.end()));
    }
    ranges.extend(
        SCRIPT_BLOCK_RE
            .find_iter(source)
            .map(|m| (m.start(), m.end())),
    );
    ranges.extend(
        STYLE_BLOCK_RE
            .find_iter(source)
            .map(|m| (m.start(), m.end())),
    );
    ranges.extend(
        HTML_COMMENT_RE
            .find_iter(source)
            .map(|m| (m.start(), m.end())),
    );
    ranges.sort_unstable_by_key(|(start, _)| *start);
    ranges_to_gaps(source, &ranges)
}

/// Extract Astro `<style>` block bodies while preserving original byte offsets.
#[must_use]
pub fn extract_astro_style_regions(source: &str) -> Vec<SourceRegion> {
    let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
        .find_iter(source)
        .map(|m| (m.start(), m.end()))
        .collect();

    STYLE_BLOCK_RE
        .captures_iter(source)
        .filter(|cap| {
            let start = cap.get(0).map_or(0, |m| m.start());
            !comment_ranges
                .iter()
                .any(|&(cs, ce)| start >= cs && start < ce)
        })
        .filter_map(|cap| {
            let body = cap.name("body")?;
            let text = body.as_str();
            if text.trim().is_empty() {
                return None;
            }
            Some(SourceRegion {
                body: text.to_string(),
                byte_offset: body.start(),
            })
        })
        .collect()
}

fn ranges_to_gaps(source: &str, ranges: &[(usize, usize)]) -> Vec<SourceRegion> {
    let mut regions = Vec::new();
    let mut cursor = 0;
    for &(start, end) in ranges {
        if start > cursor {
            push_region(source, cursor, start, &mut regions);
        }
        cursor = cursor.max(end);
    }
    if cursor < source.len() {
        push_region(source, cursor, source.len(), &mut regions);
    }
    regions
}

fn push_region(source: &str, start: usize, end: usize, regions: &mut Vec<SourceRegion>) {
    let Some(body) = source.get(start..end) else {
        return;
    };
    if body.trim().is_empty() {
        return;
    }
    regions.push(SourceRegion {
        body: body.to_string(),
        byte_offset: start,
    });
}

pub(crate) fn is_astro_file(path: &Path) -> bool {
    path.extension()
        .and_then(|e| e.to_str())
        .is_some_and(|ext| ext == "astro")
}

struct AstroFrontmatterAnalysis {
    extractor: ModuleInfoExtractor,
    semantic_usage: crate::parse::SemanticUsage,
    props_harvest: crate::sfc_props::DefinePropsHarvest,
    complexity: Vec<fallow_types::extract::FunctionComplexity>,
}

/// Parse an Astro file by extracting the frontmatter section, plus any
/// `<script src="...">` references and inline `<script>` import statements
/// in the template body.
pub(crate) fn parse_astro_to_module(
    file_id: FileId,
    source: &str,
    content_hash: u64,
    need_complexity: bool,
) -> ModuleInfo {
    let parsed_suppressions = crate::suppress::parse_suppressions_from_source(source);
    let line_offsets = fallow_types::extract::compute_line_offsets(source);

    let frontmatter = extract_astro_frontmatter(source);
    let template_offset = frontmatter
        .as_ref()
        .map_or(0, |script| script.byte_offset + script.body.len());
    let template = source.get(template_offset..).unwrap_or("");
    // `<script>` / `<style>` blocks and HTML comments, shared by every template
    // scan below.
    let masked = build_masked_ranges(template);

    // Names used in the template markup (rendered components, expression
    // bindings). Passed to the frontmatter semantic pass so a template-only-used
    // import is not falsely classified as an unused binding.
    let template_used = collect_astro_template_used_names(template, &masked);

    let frontmatter_offset = frontmatter.as_ref().map_or(0, |script| script.byte_offset);

    let AstroFrontmatterAnalysis {
        mut extractor,
        semantic_usage,
        props_harvest,
        complexity: frontmatter_complexity,
    } = analyze_astro_frontmatter(
        frontmatter.as_ref(),
        &template_used,
        need_complexity,
        &line_offsets,
    );

    extend_imports_from_template(&mut extractor.imports, template, template_offset);

    // Capture the frontmatter's array/reactive-array element-type map before
    // `into_module_info` consumes the extractor, so the template-expression pass
    // below can type a `{utils.map((util) => util.getter)}` callback param to the
    // `const utils: Util[]` element class (issue #1713).
    let frontmatter_array_element_types = extractor.array_binding_element_types().clone();

    let mut info = extractor.into_module_info(file_id, content_hash, parsed_suppressions);

    // Member-expression component tags (`<SC.Card />`) feed the same
    // member-access stream namespace narrowing reads for `.tsx` (issue #2355).
    extend_member_accesses(
        &mut info,
        collect_template_member_tag_accesses(template, &masked),
    );
    // The `{ ... }` expression regions add the expression accesses (issue #2355)
    // and carry the iteration credits of issue #1713; the pass is unconditional
    // because narrowing on a partial stream turns used members into findings.
    let parsed_regions = extend_template_expression_usage(
        &mut info,
        template,
        &collect_template_expression_regions(template, &masked),
        &frontmatter_array_element_types,
    );
    // Every mention the two passes above did not classify keeps its binding on
    // the mark-all path (issue #2355), in the markup and in the frontmatter.
    extend_unexplained_template_mentions(&mut info, template, &masked, parsed_regions);
    extend_unexplained_frontmatter_mentions(&mut info, frontmatter.as_ref());
    // Astro-only: thread the frontmatter binding usage onto the module so
    // `referenced_import_bindings` (derived from `imports` minus
    // `unused_import_bindings` in `release_resolution_payload`) reflects ACTUAL
    // use. `auto_import_candidates` is intentionally left empty: Astro has no
    // Nuxt-style convention auto-import, so seeding it would be inert at best.
    info.unused_import_bindings = semantic_usage.import_binding_usage.unused;
    info.type_referenced_import_bindings = semantic_usage.import_binding_usage.type_referenced;
    info.value_referenced_import_bindings = semantic_usage.import_binding_usage.value_referenced;
    crate::parse::append_declaration_merge_facts(
        &mut info.semantic_facts,
        semantic_usage.declaration_merges,
        frontmatter_offset as u32,
    );
    apply_astro_props(
        &mut info,
        props_harvest,
        &template_used,
        template,
        frontmatter_offset,
    );
    // Health complexity (only when requested): the frontmatter functions (scored
    // above) plus a synthetic `<template>` entry for the markup `{ ... }`
    // expression / iteration complexity, mirroring the Vue/Svelte synthetic
    // template entry. Folds into the existing complexity aggregate; no new rule.
    info.complexity.extend(frontmatter_complexity);
    if need_complexity {
        info.complexity
            .extend(crate::template_complexity::compute_astro_template_complexity(source));
    }
    info.line_offsets = line_offsets;
    info
}

fn analyze_astro_frontmatter(
    frontmatter: Option<&SfcScript>,
    template_used: &FxHashSet<String>,
    need_complexity: bool,
    line_offsets: &[u32],
) -> AstroFrontmatterAnalysis {
    let Some(script) = frontmatter else {
        return empty_astro_frontmatter_analysis();
    };
    let source_type = SourceType::ts();
    let allocator = Allocator::default();
    let parser_return = Parser::new(&allocator, &script.body, source_type).parse();
    let mut extractor = ModuleInfoExtractor::new();
    extractor.visit_program(&parser_return.program);
    let semantic_usage = crate::parse::compute_semantic_usage_for_extractor(
        &parser_return.program,
        &mut extractor,
        template_used,
    );
    let extraction = ExtractionResult::contiguous(&script.body, script.byte_offset);
    extractor.remap_spans_with(|span| extraction.remap_span(span));
    let props_harvest = crate::sfc_props::harvest_astro_props(&parser_return.program);
    let complexity = if need_complexity {
        compute_astro_frontmatter_complexity(
            &parser_return.program,
            &script.body,
            script.byte_offset,
            line_offsets,
        )
    } else {
        Vec::new()
    };
    AstroFrontmatterAnalysis {
        extractor,
        semantic_usage,
        props_harvest,
        complexity,
    }
}

fn empty_astro_frontmatter_analysis() -> AstroFrontmatterAnalysis {
    AstroFrontmatterAnalysis {
        extractor: ModuleInfoExtractor::new(),
        semantic_usage: crate::parse::SemanticUsage::default(),
        props_harvest: crate::sfc_props::DefinePropsHarvest::default(),
        complexity: Vec::new(),
    }
}

/// Score the frontmatter's JS functions (cyclomatic/cognitive), remapping each
/// function's line/col from the frontmatter-body coordinate space onto the
/// `.astro` source. Mirrors the Vue/Svelte `sfc::translate_script_complexity`
/// path so a complex `.astro` frontmatter contributes to the health complexity
/// aggregate the same as an SFC `<script>`.
fn compute_astro_frontmatter_complexity(
    program: &oxc_ast::ast::Program<'_>,
    body: &str,
    body_byte_offset: usize,
    source_line_offsets: &[u32],
) -> Vec<fallow_types::extract::FunctionComplexity> {
    let body_line_offsets = fallow_types::extract::compute_line_offsets(body);
    let mut complexity = crate::complexity::compute_complexity(program, body, &body_line_offsets);
    let (body_start_line, body_start_col) = fallow_types::extract::byte_offset_to_line_col(
        source_line_offsets,
        u32::try_from(body_byte_offset).unwrap_or(u32::MAX),
    );
    for function in &mut complexity {
        function.line = body_start_line + function.line.saturating_sub(1);
        if function.line == body_start_line {
            function.col += body_start_col;
        }
    }
    complexity
}

/// Thread the harvested Astro `Props` declaration + `Astro.props` usage onto the
/// module: copy the abstain flags, remap each prop span onto the `.astro` source,
/// and set `used_in_template` from the template-usage scan. A template spread
/// `{...Astro.props}` forwards every prop opaquely, so it sets the whole-file
/// fallthrough abstain (the markup analog of a script-side whole-object use).
fn apply_astro_props(
    info: &mut ModuleInfo,
    harvest: crate::sfc_props::DefinePropsHarvest,
    template_used: &FxHashSet<String>,
    template: &str,
    frontmatter_offset: usize,
) {
    if harvest.has_unharvestable_props {
        info.has_unharvestable_props = true;
    }
    if harvest.has_props_attrs_fallthrough || template.contains("...Astro.props") {
        info.has_props_attrs_fallthrough = true;
    }
    for mut prop in harvest.props {
        prop.span_start = prop
            .span_start
            .saturating_add(u32::try_from(frontmatter_offset).unwrap_or(u32::MAX));
        prop.used_in_template =
            template_used.contains(&prop.local) || template_used.contains(&prop.name);
        info.component_props.push(prop);
    }
}

/// Append imports discovered in the Astro template body: `<script src="...">`
/// references and ESM `import` statements inside inline `<script>` blocks.
fn extend_imports_from_template(
    imports: &mut Vec<ImportInfo>,
    template: &str,
    template_offset: usize,
) {
    if template.is_empty() {
        return;
    }

    let comment_ranges: Vec<(usize, usize)> = HTML_COMMENT_RE
        .find_iter(template)
        .map(|m| (m.start(), m.end()))
        .collect();

    extend_processed_script_src_imports(imports, template, template_offset, &comment_ranges);
    extend_inline_script_imports(imports, template, template_offset, &comment_ranges);
}

/// Whether `pos` falls inside any HTML comment range.
fn pos_in_comment(comment_ranges: &[(usize, usize)], pos: usize) -> bool {
    comment_ranges
        .iter()
        .any(|&(start, end)| pos >= start && pos < end)
}

/// Append `<script src="...">` processed-script references from the template.
fn extend_processed_script_src_imports(
    imports: &mut Vec<ImportInfo>,
    template: &str,
    template_offset: usize,
    comment_ranges: &[(usize, usize)],
) {
    for cap in SCRIPT_OPEN_RE.captures_iter(template) {
        let Some(open) = cap.get(0) else {
            continue;
        };
        if pos_in_comment(comment_ranges, open.start()) {
            continue;
        }
        let attrs = cap.name("attrs").map_or("", |m| m.as_str());
        if let Some((raw, source_span)) = processed_script_src_with_span(attrs, cap.name("attrs")) {
            let tag_span = Span::new(
                (template_offset + open.start()) as u32,
                (template_offset + open.end()) as u32,
            );
            imports.push(ImportInfo {
                source: normalize_asset_url(raw),
                imported_name: ImportedName::SideEffect,
                local_name: String::new(),
                is_type_only: false,
                is_type_only_star: false,
                from_style: false,
                span: tag_span,
                source_span: Span::new(
                    template_offset as u32 + source_span.start,
                    template_offset as u32 + source_span.end,
                ),
            });
        }
    }
}

/// Append ESM `import` statements found in attribute-free inline `<script>`
/// blocks of the template, remapping spans onto the SFC source.
fn extend_inline_script_imports(
    imports: &mut Vec<ImportInfo>,
    template: &str,
    template_offset: usize,
    comment_ranges: &[(usize, usize)],
) {
    for cap in SCRIPT_BLOCK_RE.captures_iter(template) {
        let Some(open) = cap.get(0) else {
            continue;
        };
        if pos_in_comment(comment_ranges, open.start()) {
            continue;
        }
        let attrs = cap.name("attrs").map_or("", |m| m.as_str());
        if !attrs.trim().is_empty() {
            continue;
        }
        let Some(body_match) = cap.name("body") else {
            continue;
        };
        let body = body_match.as_str();
        if body.trim().is_empty() {
            continue;
        }

        let allocator = Allocator::default();
        let parser_return = Parser::new(&allocator, body, SourceType::ts()).parse();
        let mut inline_extractor = ModuleInfoExtractor::new();
        inline_extractor.visit_program(&parser_return.program);
        let extraction = ExtractionResult::contiguous(body, template_offset + body_match.start());
        inline_extractor.remap_spans_with(|span| extraction.remap_span(span));
        imports.append(&mut inline_extractor.imports);
    }
}

fn processed_script_src_with_span<'a>(
    attrs: &'a str,
    attrs_match: Option<regex::Match<'_>>,
) -> Option<(&'a str, Span)> {
    let cap = SRC_ATTR_RE.captures(attrs)?;
    let src_match = cap.name("src")?;
    let src = src_match.as_str().trim();
    if src.is_empty() || is_remote_url(src) {
        return None;
    }

    let without_src = SRC_ATTR_RE.replace(attrs, "");
    let extra_attrs = without_src.trim();
    let extra_attrs = extra_attrs.strip_suffix('/').unwrap_or(extra_attrs).trim();
    if !extra_attrs.is_empty() {
        return None;
    }

    let attrs_start = attrs_match.map_or(0, |m| m.start());
    Some((
        src,
        Span::new(
            (attrs_start + src_match.start()) as u32,
            (attrs_start + src_match.end()) as u32,
        ),
    ))
}

// Astro tests use regex-based frontmatter extraction.
#[cfg(all(test, not(miri)))]
mod tests {
    use super::*;

    #[test]
    fn is_astro_file_positive() {
        assert!(is_astro_file(Path::new("Layout.astro")));
    }

    #[test]
    fn is_astro_file_rejects_vue() {
        assert!(!is_astro_file(Path::new("App.vue")));
    }

    #[test]
    fn is_astro_file_rejects_ts() {
        assert!(!is_astro_file(Path::new("utils.ts")));
    }

    #[test]
    fn is_astro_file_rejects_mdx() {
        assert!(!is_astro_file(Path::new("post.mdx")));
    }

    #[test]
    fn extracts_frontmatter_body() {
        let source = "---\nimport Layout from '../layouts/Layout.astro';\nconst title = 'Hi';\n---\n<Layout />";
        let script = extract_astro_frontmatter(source);
        assert!(script.is_some());
        let script = script.unwrap();
        assert!(script.body.contains("import Layout"));
        assert!(script.body.contains("const title"));
    }

    #[test]
    fn frontmatter_is_always_typescript() {
        let source = "---\nconst x = 1;\n---\n<div />";
        let script = extract_astro_frontmatter(source).unwrap();
        assert!(script.is_typescript);
    }

    #[test]
    fn frontmatter_is_not_jsx() {
        let source = "---\nconst x = 1;\n---\n<div />";
        let script = extract_astro_frontmatter(source).unwrap();
        assert!(!script.is_jsx);
    }

    #[test]
    fn frontmatter_has_no_src() {
        let source = "---\nconst x = 1;\n---\n<div />";
        let script = extract_astro_frontmatter(source).unwrap();
        assert!(script.src.is_none());
    }

    #[test]
    fn no_frontmatter_returns_none() {
        let source = "<div>No frontmatter here</div>";
        assert!(extract_astro_frontmatter(source).is_none());
    }

    #[test]
    fn no_frontmatter_just_html() {
        let source = "<html><body><h1>Hello</h1></body></html>";
        assert!(extract_astro_frontmatter(source).is_none());
    }

    #[test]
    fn empty_frontmatter() {
        let source = "---\n\n---\n<div />";
        let script = extract_astro_frontmatter(source);
        assert!(script.is_some());
        let body = script.unwrap().body;
        assert!(body.trim().is_empty());
    }

    #[test]
    fn only_first_frontmatter_pair() {
        let source = "---\nconst first = true;\n---\n<div />\n---\nconst second = true;\n---\n";
        let script = extract_astro_frontmatter(source);
        assert!(script.is_some());
        let body = script.unwrap().body;
        assert!(body.contains("first"));
        assert!(!body.contains("second"));
    }

    #[test]
    fn byte_offset_points_to_body() {
        let source = "---\nconst x = 1;\n---\n<div />";
        let script = extract_astro_frontmatter(source).unwrap();
        let offset = script.byte_offset;
        assert!(source[offset..].starts_with("const x = 1;"));
    }

    #[test]
    fn leading_whitespace_before_frontmatter() {
        let source = "  \n---\nconst x = 1;\n---\n<div />";
        let script = extract_astro_frontmatter(source);
        assert!(script.is_some());
        assert!(script.unwrap().body.contains("const x = 1;"));
    }

    #[test]
    fn frontmatter_with_type_annotations() {
        let source = "---\ninterface Props { title: string; }\nconst { title } = Astro.props as Props;\n---\n<h1>{title}</h1>";
        let script = extract_astro_frontmatter(source);
        assert!(script.is_some());
        let body = script.unwrap().body;
        assert!(body.contains("interface Props"));
        assert!(body.contains("Astro.props"));
    }

    #[test]
    fn frontmatter_with_multiline_imports() {
        let source = "---\nimport {\n  Component,\n  Fragment\n} from 'react';\n---\n<Component />";
        let script = extract_astro_frontmatter(source).unwrap();
        assert!(script.body.contains("Component"));
        assert!(script.body.contains("Fragment"));
    }

    #[test]
    fn frontmatter_with_crlf_line_endings() {
        let source = "---\r\nexport const x = 1;\r\n---\r\n<div />";
        let script = extract_astro_frontmatter(source);
        assert!(script.is_some());
        assert!(script.unwrap().body.contains("export const x = 1;"));
    }

    #[test]
    fn frontmatter_not_at_start_returns_none() {
        let source = "<div />\n---\nconst x = 1;\n---\n";
        assert!(extract_astro_frontmatter(source).is_none());
    }

    #[test]
    fn frontmatter_dashes_in_body_not_confused() {
        let source = "---\nconst x = '---';\nconst y = 2;\n---\n<div />";
        let script = extract_astro_frontmatter(source);
        assert!(script.is_some());
        let body = script.unwrap().body;
        assert!(body.contains("const x = '---';"));
    }

    #[test]
    fn parse_astro_to_module_no_frontmatter() {
        let info = parse_astro_to_module(FileId(0), "<div>Hello</div>", 42, false);
        assert!(info.imports.is_empty());
        assert!(info.exports.is_empty());
        assert_eq!(info.content_hash, 42);
        assert_eq!(info.file_id, FileId(0));
    }

    #[test]
    fn parse_astro_to_module_with_imports() {
        let source = "---\nimport { ref } from 'vue';\nconst x = ref(0);\n---\n<div />";
        let info = parse_astro_to_module(FileId(1), source, 99, false);
        assert_eq!(info.imports.len(), 1);
        assert_eq!(info.imports[0].source, "vue");
        assert_eq!(info.file_id, FileId(1));
        assert_eq!(info.content_hash, 99);
    }

    #[test]
    fn parse_astro_to_module_has_line_offsets() {
        let source = "---\nconst x = 1;\n---\n<div />";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert!(!info.line_offsets.is_empty());
    }

    #[test]
    fn parse_astro_to_module_has_suppressions() {
        let source = "---\n// fallow-ignore-file\nconst x = 1;\n---\n<div />";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert!(!info.suppressions.is_empty());
        assert_eq!(info.suppressions[0].line, 0);
    }

    #[test]
    fn is_astro_file_rejects_svelte() {
        assert!(!is_astro_file(Path::new("Component.svelte")));
    }

    #[test]
    fn is_astro_file_rejects_no_extension() {
        assert!(!is_astro_file(Path::new("Makefile")));
    }

    #[test]
    fn parse_astro_template_script_src_relative() {
        let source = "---\nconst x = 1;\n---\n<script src=\"./client.ts\"></script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert_eq!(info.imports.len(), 1);
        assert_eq!(info.imports[0].source, "./client.ts");
    }

    #[test]
    fn parse_astro_template_script_src_parent_relative() {
        let source = "---\n---\n<script src=\"../scripts/foo.ts\"></script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert_eq!(info.imports.len(), 1);
        assert_eq!(info.imports[0].source, "../scripts/foo.ts");
    }

    #[test]
    fn parse_astro_template_script_src_bare_normalized() {
        let source = "---\n---\n<script src=\"client.ts\"></script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert_eq!(info.imports.len(), 1);
        assert_eq!(info.imports[0].source, "./client.ts");
    }

    #[test]
    fn parse_astro_template_script_src_skips_remote() {
        let source = "---\n---\n<script src=\"https://cdn.example.com/lib.js\"></script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert!(info.imports.is_empty());
    }

    #[test]
    fn parse_astro_template_script_src_multiline_attrs() {
        let source = "---\n---\n<script\n  src=\"./client.ts\"\n></script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert_eq!(info.imports.len(), 1);
        assert_eq!(info.imports[0].source, "./client.ts");
    }

    #[test]
    fn parse_astro_template_script_src_with_extra_attrs_is_unprocessed() {
        let source = "---\n---\n<script type=\"module\" src=\"./client.ts\"></script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert!(info.imports.is_empty());
    }

    #[test]
    fn parse_astro_template_inline_script_import() {
        let source = "---\n---\n<script>\n  import '../scripts/bar';\n</script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert_eq!(info.imports.len(), 1);
        assert_eq!(info.imports[0].source, "../scripts/bar");
        assert!(matches!(
            info.imports[0].imported_name,
            crate::ImportedName::SideEffect
        ));
    }

    #[test]
    fn parse_astro_template_inline_script_named_import() {
        let source = "---\n---\n<script>\n  import { foo } from '../utils';\n  foo();\n</script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert_eq!(info.imports.len(), 1);
        assert_eq!(info.imports[0].source, "../utils");
    }

    #[test]
    fn parse_astro_template_inline_script_typescript_syntax() {
        let source = "---\n---\n<script>\n  import { foo } from '../utils';\n  const x: number = foo();\n</script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert_eq!(info.imports.len(), 1);
        assert_eq!(info.imports[0].source, "../utils");
    }

    #[test]
    fn parse_astro_template_inline_script_with_attributes_is_unprocessed() {
        let source = "---\n---\n<script is:inline>\n  import '../scripts/bar';\n</script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert!(info.imports.is_empty());
    }

    #[test]
    fn parse_astro_template_type_module_inline_script_is_unprocessed() {
        let source = "---\n---\n<script type=\"module\">\n  import '../scripts/bar';\n</script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert!(info.imports.is_empty());
    }

    #[test]
    fn parse_astro_template_skips_inline_body_when_src_present() {
        let source = "---\n---\n<script src=\"./client.ts\">import 'should-be-ignored';</script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert_eq!(info.imports.len(), 1);
        assert_eq!(info.imports[0].source, "./client.ts");
    }

    #[test]
    fn parse_astro_template_combined_src_and_inline() {
        let source = "---\nconst title = \"Hi\";\n---\n\
                      <html><body>\n\
                      <h1>{title}</h1>\n\
                      <script src=\"../scripts/foo.ts\"></script>\n\
                      <script>\n  import '../scripts/bar';\n</script>\n\
                      </body></html>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        let sources: Vec<&str> = info.imports.iter().map(|i| i.source.as_str()).collect();
        assert!(sources.contains(&"../scripts/foo.ts"));
        assert!(sources.contains(&"../scripts/bar"));
    }

    #[test]
    fn parse_astro_template_multiple_inline_scripts() {
        let source = "---\n---\n\
                      <script>\n  import '../a';\n</script>\n\
                      <script>\n  import '../b';\n</script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        let sources: Vec<&str> = info.imports.iter().map(|i| i.source.as_str()).collect();
        assert!(sources.contains(&"../a"));
        assert!(sources.contains(&"../b"));
    }

    #[test]
    fn parse_astro_template_skips_commented_out_script_src() {
        let source = "---\n---\n<!-- <script src=\"./old.ts\"></script> -->\n<script src=\"./new.ts\"></script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert_eq!(info.imports.len(), 1);
        assert_eq!(info.imports[0].source, "./new.ts");
    }

    #[test]
    fn parse_astro_template_skips_commented_out_inline_script() {
        let source = "---\n---\n<!-- <script>\n  import '../old';\n</script> -->\n<script>\n  import '../new';\n</script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        let sources: Vec<&str> = info.imports.iter().map(|i| i.source.as_str()).collect();
        assert!(sources.contains(&"../new"));
        assert!(!sources.contains(&"../old"));
    }

    #[test]
    fn parse_astro_template_no_frontmatter_with_script() {
        let source = "<html><body><script src=\"./client.ts\"></script></body></html>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert_eq!(info.imports.len(), 1);
        assert_eq!(info.imports[0].source, "./client.ts");
    }

    #[test]
    fn parse_astro_template_empty_inline_script_is_skipped() {
        let source = "---\n---\n<script></script>";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert!(info.imports.is_empty());
    }

    #[test]
    fn parse_astro_template_does_not_double_count_frontmatter_imports() {
        let source = "---\nimport Layout from '../Layout.astro';\n---\n<Layout />";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert_eq!(info.imports.len(), 1);
        assert_eq!(info.imports[0].source, "../Layout.astro");
    }

    #[test]
    fn astro_template_map_callback_element_type() {
        // Issue #1713: a `.map()` callback param in the TEMPLATE body (not the
        // frontmatter) whose receiver is a frontmatter `Util[]` binding is typed
        // to the `Util` element class, so `util.getter()` credits `Util.getter`.
        let source = "---\n\
            import { Util } from './Util'\n\
            const utils: Util[] = [new Util()]\n\
            ---\n\
            <div>\n\
              {utils.map((util) => <p>{util.getter()}</p>)}\n\
            </div>\n";
        let info = parse_astro_to_module(FileId(0), source, 0, false);

        let has_util_getter = info
            .member_accesses
            .iter()
            .any(|access| access.object == "Util" && access.member == "getter");
        assert!(
            has_util_getter,
            "expected Util.getter from the template .map callback, found: {:?}",
            info.member_accesses
        );
    }

    #[test]
    fn astro_template_map_does_not_credit_unrelated_member() {
        // Control: a member NOT accessed anywhere (frontmatter or template) must
        // not be synthesized as a Util access. Proves the pass is over-credit-only
        // and does not blanket-credit the class.
        let source = "---\n\
            import { Util } from './Util'\n\
            const utils: Util[] = [new Util()]\n\
            ---\n\
            <div>\n\
              {utils.map((util) => <p>{util.getter()}</p>)}\n\
            </div>\n";
        let info = parse_astro_to_module(FileId(0), source, 0, false);

        let has_unused = info
            .member_accesses
            .iter()
            .any(|access| access.object == "Util" && access.member == "unusedMethod");
        assert!(
            !has_unused,
            "Util.unusedMethod is never accessed and must not be credited, found: {:?}",
            info.member_accesses
        );
    }

    #[test]
    fn astro_template_map_without_typed_array_credits_nothing() {
        // Neuter check: no frontmatter typed array => no element type => the
        // template pass contributes no class-qualified access.
        let source = "---\n\
            import { Util } from './Util'\n\
            const utils = getUtils()\n\
            ---\n\
            <div>\n\
              {utils.map((util) => <p>{util.getter()}</p>)}\n\
            </div>\n";
        let info = parse_astro_to_module(FileId(0), source, 0, false);

        assert!(
            !info
                .member_accesses
                .iter()
                .any(|access| access.object == "Util"),
            "an untyped receiver must not credit any Util member, found: {:?}",
            info.member_accesses
        );
    }

    /// Template that is roughly half HTML comments (masked) and half `{expr}`
    /// braces / tags (credited), with an overlapping masked range (a comment that
    /// wraps a `<script>`). The merged binary-search masking must decide every
    /// byte position identically to the old linear `.any()` over the raw,
    /// unsorted, overlapping ranges. Regression for the masking-cost change
    /// (issue #1843 follow-up): behavior must stay byte-identical.
    const MASKED_MIX_TEMPLATE: &str = concat!(
        "<!-- <Widget/> and {Sidebar} -->\n",
        "<Header title={fmt(x)} />\n",
        "<!-- <script>{Buried}</script> -->\n",
        "<script><Hidden/>{Ghost}</script>\n",
        "<style>a { color: {red}; }</style>\n",
        "<Footer>{items.map((i) => i.label)}</Footer>\n",
    );

    #[test]
    fn astro_masked_ranges_match_linear_reference() {
        let template = MASKED_MIX_TEMPLATE;

        // Old masking: a linear scan over the three raw (unsorted, overlapping)
        // `find_iter` passes.
        let mut raw: Vec<(usize, usize)> = Vec::new();
        raw.extend(
            SCRIPT_BLOCK_RE
                .find_iter(template)
                .map(|m| (m.start(), m.end())),
        );
        raw.extend(
            STYLE_BLOCK_RE
                .find_iter(template)
                .map(|m| (m.start(), m.end())),
        );
        raw.extend(
            HTML_COMMENT_RE
                .find_iter(template)
                .map(|m| (m.start(), m.end())),
        );
        let linear = |pos: usize| raw.iter().any(|&(s, e)| pos >= s && pos < e);

        let merged = build_masked_ranges(template);
        // The overlapping comment+script pair must collapse during the merge.
        assert!(
            merged.len() < raw.len(),
            "expected overlapping ranges to merge, raw={raw:?} merged={merged:?}"
        );
        for pos in 0..template.len() {
            assert_eq!(
                pos_in_ranges(&merged, pos),
                linear(pos),
                "masking decision differs at byte {pos}"
            );
        }
    }

    #[test]
    fn astro_template_used_names_masks_comments_credits_braces() {
        let masked = build_masked_ranges(MASKED_MIX_TEMPLATE);
        let used = collect_astro_template_used_names(MASKED_MIX_TEMPLATE, &masked);

        // Credited: tag roots + brace-expression identifiers outside masked regions.
        for name in ["Header", "Footer", "fmt", "x", "items", "map", "i", "label"] {
            assert!(
                used.contains(name),
                "expected {name} to be credited, got {used:?}"
            );
        }

        // Masked: identifiers only reachable inside comments / `<script>` / `<style>`
        // (each would be a tag root or brace ident if the range were not masked).
        for name in ["Widget", "Sidebar", "Buried", "Hidden", "Ghost", "red"] {
            assert!(
                !used.contains(name),
                "expected {name} to stay masked, got {used:?}"
            );
        }
    }

    fn template_member_accesses(source: &str) -> Vec<(String, String)> {
        parse_astro_to_module(FileId(0), source, 0, false)
            .member_accesses
            .iter()
            .map(|access| (access.object.clone(), access.member.clone()))
            .collect()
    }

    /// Issue #2355: a member-expression component tag in the markup
    /// (`<SC.Card />`) records the same `SC.Card` access the JSX visitor records
    /// for `.tsx`, while the root credit that keeps `SC` a used import binding
    /// stays in place.
    #[test]
    fn astro_template_member_tag_records_member_access() {
        let source = "---\nimport * as SC from './style';\n---\n<SC.Card />\n";
        let info = parse_astro_to_module(FileId(0), source, 0, false);
        assert!(
            info.member_accesses
                .iter()
                .any(|access| access.object == "SC" && access.member == "Card"),
            "<SC.Card /> should record SC.Card; got {:?}",
            info.member_accesses
        );
        assert!(
            !info.unused_import_bindings.iter().any(|b| b == "SC"),
            "the dotted tag root must still credit the SC import binding; got {:?}",
            info.unused_import_bindings
        );
    }

    /// Issue #2355: `<A.B.C />` records one access per nesting level, matching
    /// the plain-expression walk of `A.B.C` (`{A, B}` and `{A.B, C}`).
    #[test]
    fn astro_template_nested_member_tag_records_each_level() {
        let accesses = template_member_accesses(
            "---\nimport * as A from './widgets';\n---\n<A.B.C label=\"x\" />\n",
        );
        assert!(
            accesses.contains(&("A".to_string(), "B".to_string())),
            "<A.B.C /> should record A.B for namespace crediting; got {accesses:?}"
        );
        assert!(
            accesses.contains(&("A.B".to_string(), "C".to_string())),
            "<A.B.C /> should record the full A.B.C path; got {accesses:?}"
        );
    }

    /// Issue #2355: only the opening tag records, so a paired
    /// `<SC.Layout>..</SC.Layout>` yields exactly one `SC.Layout` access.
    #[test]
    fn astro_template_paired_member_tag_records_single_access() {
        let accesses = template_member_accesses(
            "---\nimport * as SC from './style';\n---\n<SC.Layout>\n  <p>text</p>\n</SC.Layout>\n",
        );
        let count = accesses
            .iter()
            .filter(|(object, member)| object == "SC" && member == "Layout")
            .count();
        assert_eq!(
            count, 1,
            "paired tags should record exactly one SC.Layout access; got {accesses:?}"
        );
    }

    fn template_whole_object_uses(source: &str) -> Vec<String> {
        parse_astro_to_module(FileId(0), source, 0, false)
            .whole_object_uses
            .to_vec()
    }

    /// Issue #2355: member tags inside masked ranges (HTML comments,
    /// `<script>` and `<style>` bodies) never record an access, mirroring the
    /// root-credit masking, but the mention is unexplained, so the binding
    /// keeps its mark-all crediting instead of narrowing to the visible tag.
    #[test]
    fn astro_template_member_tag_in_masked_region_records_no_access_but_keeps_mark_all() {
        let source = "---\nimport * as SC from './style';\n---\n\
             <!-- <SC.Commented /> -->\n\
             <script>const x = '<SC.Scripted />';</script>\n\
             <style>/* <SC.Styled /> */</style>\n\
             <SC.Visible />\n";
        let accesses = template_member_accesses(source);
        assert_eq!(
            accesses,
            vec![("SC".to_string(), "Visible".to_string())],
            "only the unmasked member tag should record; got {accesses:?}"
        );
        assert_eq!(
            template_whole_object_uses(source),
            vec!["SC".to_string()],
            "a masked mention must keep SC on the mark-all path"
        );
    }

    /// Issue #2355: a namespace member read inside a template expression
    /// (attribute value or text expression) records the same access a dotted
    /// tag does, so a component mixing `<NS.Star />` with `icon={NS.Moon}` and
    /// `{NS.Moon()}` narrows to a complete member set.
    #[test]
    fn astro_template_expression_member_access_records() {
        let accesses = template_member_accesses(
            "---\nimport * as NS from './icons';\nimport Callout from './Callout.astro';\n---\n\
             <NS.Star />\n<Callout icon={NS.Moon} />\n<p>{NS.Sun()}</p>\n",
        );
        for member in ["Star", "Moon", "Sun"] {
            assert!(
                accesses.contains(&("NS".to_string(), member.to_string())),
                "NS.{member} should be recorded from the markup; got {accesses:?}"
            );
        }
    }

    /// Issue #2355: passing the namespace object whole through an expression
    /// (`all={NS}`) records a whole-object use so narrowing falls back to
    /// crediting every export, while a bare identifier that is not an import
    /// binding records nothing.
    #[test]
    fn astro_template_whole_namespace_pass_records_whole_object_use() {
        let info = parse_astro_to_module(
            FileId(0),
            "---\nimport * as NS from './icons';\nimport Callout from './Callout.astro';\n\
             const local = 1;\n---\n<NS.Star />\n<Callout all={NS} count={local} />\n",
            0,
            false,
        );
        assert!(
            info.whole_object_uses.iter().any(|name| name == "NS"),
            "all={{NS}} should record a whole-object use; got {:?}",
            info.whole_object_uses
        );
        assert!(
            !info.whole_object_uses.iter().any(|name| name == "local"),
            "a frontmatter local is not an import binding; got {:?}",
            info.whole_object_uses
        );
    }

    /// Issue #2355: a member tag nested inside an expression region
    /// (`{flag && <EX.Cond />}`) is seen by both the masking-aware tag scan and
    /// the region visitor, and still records once.
    #[test]
    fn astro_template_member_tag_inside_expression_records_once() {
        let accesses = template_member_accesses(
            "---\nimport * as EX from './ex';\nconst flag = true;\n---\n{flag && <EX.Cond />}\n",
        );
        let count = accesses
            .iter()
            .filter(|(object, member)| object == "EX" && member == "Cond")
            .count();
        assert_eq!(
            count, 1,
            "a tag inside an expression region should record exactly once; got {accesses:?}"
        );
    }

    /// Issue #2355: a parsed expression region is read with the visitor's
    /// expression semantics, so a dotted name inside a string literal is not an
    /// access, while a reflective whole-object use (`Object.keys(NS)`) records
    /// the same whole-object use it records for `.tsx`.
    #[test]
    fn astro_template_parsed_expression_uses_visitor_semantics() {
        let info = parse_astro_to_module(
            FileId(0),
            "---\nimport * as NS from './icons';\n---\n\
             <NS.Star />\n<p>{\"NS.Ghost\"}</p>\n<p>{Object.keys(NS).length}</p>\n",
            0,
            false,
        );
        assert!(
            !info
                .member_accesses
                .iter()
                .any(|access| access.object == "NS" && access.member == "Ghost"),
            "a string literal is not a member access; got {:?}",
            info.member_accesses
        );
        assert!(
            info.whole_object_uses.iter().any(|name| name == "NS"),
            "Object.keys(NS) should record a whole-object use; got {:?}",
            info.whole_object_uses
        );
    }

    /// Issue #2355: a region the visitor cannot parse cleanly (`{NS.Moon(}`)
    /// is not structurally understood, so its mention keeps the binding on the
    /// mark-all path and narrowing never runs on a partial view.
    #[test]
    fn astro_template_unparsed_expression_region_keeps_binding_on_mark_all() {
        let source = "---\nimport * as NS from './icons';\n---\n<NS.Star />\n<p>{NS.Moon(}</p>\n";
        let accesses = template_member_accesses(source);
        assert!(
            !accesses.contains(&("NS".to_string(), "Moon".to_string())),
            "an unparsed region records no access; got {accesses:?}"
        );
        assert_eq!(
            template_whole_object_uses(source),
            vec!["NS".to_string()],
            "an unparsed region must keep NS on the mark-all path"
        );
    }

    /// Issue #2355 completeness guard: `{ ... }` expressions on the opening tag
    /// of a masked `<style>` / `<script>` block (`define:vars`, `set:html`)
    /// never reach the region visitor, so the binding they mention must keep
    /// its mark-all crediting rather than narrow to the dotted tag. The same
    /// holds for a CSS module default import read through `define:vars`.
    #[test]
    fn astro_template_masked_tag_directive_mention_keeps_binding_on_mark_all() {
        let source = "---\n\
             import * as SV from './sv';\nimport * as SD from './sd';\n\
             import * as SH from './sh';\nimport * as SW from './sw';\n\
             import styles from './card.module.css';\n\
             ---\n\
             <SV.Star /><SD.Star /><SH.Star /><SW.Star />\n\
             <div class={styles.root}></div>\n\
             <style define:vars={{ accent: SV.accent }}>div { color: var(--accent); }</style>\n\
             <script define:vars={{ moon: SD.Moon }}>console.log(moon);</script>\n\
             <script is:inline set:html={SH.code}></script>\n\
             <script define:vars={{ SW }}>console.log(SW);</script>\n\
             <style define:vars={{ spare: styles.spare }}></style>\n";
        let accesses = template_member_accesses(source);
        for root in ["SV", "SD", "SH", "SW"] {
            assert!(
                accesses.contains(&(root.to_string(), "Star".to_string())),
                "{root}.Star should still record from the dotted tag; got {accesses:?}"
            );
        }
        assert!(
            accesses.contains(&("styles".to_string(), "root".to_string())),
            "styles.root should record from the markup expression; got {accesses:?}"
        );
        let mut whole = template_whole_object_uses(source);
        whole.sort();
        assert_eq!(
            whole,
            vec![
                "SD".to_string(),
                "SH".to_string(),
                "SV".to_string(),
                "SW".to_string(),
                "styles".to_string(),
            ],
            "every binding mentioned on a masked opening tag must keep mark-all"
        );
    }

    /// Issue #2355 completeness guard: mentions in an HTML comment, in text
    /// content, in an attribute string, and in a `<script>` body are outside
    /// every structured span, so each keeps its binding on the mark-all path.
    #[test]
    fn astro_template_unstructured_mention_keeps_binding_on_mark_all() {
        let source = "---\n\
             import * as CM from './cm';\nimport * as TX from './tx';\n\
             import * as AT from './at';\nimport * as SB from './sb';\n\
             ---\n\
             <CM.Star /><TX.Star /><AT.Star /><SB.Star />\n\
             <!-- {CM.Moon} -->\n\
             <p>see TX.Moon for details</p>\n\
             <div data-icon=\"AT.Moon\"></div>\n\
             <script>SB.Moon();</script>\n";
        let mut whole = template_whole_object_uses(source);
        whole.sort();
        assert_eq!(
            whole,
            vec![
                "AT".to_string(),
                "CM".to_string(),
                "SB".to_string(),
                "TX".to_string(),
            ],
            "got {whole:?}"
        );
    }

    /// Issue #2355 precision: when every mention of a binding sits in a tag
    /// root or a parsed expression region, no whole-object use is recorded and
    /// narrowing stays precise. Paired tags, a dotted tag nested in an
    /// expression, attribute and text expressions, a template literal inside an
    /// expression, and a rendered default import all count as understood.
    #[test]
    fn astro_template_fully_understood_mentions_record_no_whole_object_use() {
        let source = "---\n\
             import * as NS from './icons';\nimport Card from './Card.astro';\n\
             import styles from './card.module.css';\nconst flag = true;\n\
             ---\n\
             <NS.Star />\n<NS.Moon>\n  <Card icon={NS.Sun} class={styles.root} />\n</NS.Moon>\n\
             {flag && <NS.Cond />}\n<p>{NS.helper()}</p>\n<p class={`x ${styles.spare}`}>{`${NS.Tpl}`}</p>\n";
        let whole = template_whole_object_uses(source);
        assert!(
            whole.is_empty(),
            "fully understood mentions must not record a whole-object use; got {whole:?}"
        );
        let accesses = template_member_accesses(source);
        for member in ["Star", "Moon", "Sun", "Cond", "helper", "Tpl"] {
            assert!(
                accesses.contains(&("NS".to_string(), member.to_string())),
                "NS.{member} should be recorded; got {accesses:?}"
            );
        }
        for class in ["root", "spare"] {
            assert!(
                accesses.contains(&("styles".to_string(), class.to_string())),
                "styles.{class} should be recorded; got {accesses:?}"
            );
        }
    }

    /// Issue #2355 script guard: a frontmatter mention of a namespace (or a
    /// CSS module) the visitor does not record as a whole-object use, such as
    /// an alias, a cast, a call argument, `Object.assign`, an array literal,
    /// or a props object, keeps the binding on the mark-all path, while a
    /// dotted-only frontmatter use (`const moon = FD.Moon`) records no
    /// whole-object use and stays precise. A class named in a type annotation
    /// and a `new` expression is not guarded: its members keep the visitor's
    /// crediting. A binding the visitor already records whole
    /// (`Object.keys(AL)`) is recorded once, not once per guard.
    #[test]
    fn astro_frontmatter_bare_mention_keeps_narrowable_binding_on_mark_all() {
        let source = "---\n\
             import * as AL from './al';\nimport * as AC from './ac';\n\
             import * as CA from './ca';\nimport * as OA from './oa';\n\
             import * as AR from './ar';\nimport * as PP from './pp';\n\
             import * as FD from './fd';\nimport styles from './card.module.css';\n\
             import { Util } from './util';\nimport Callout from './Callout.astro';\n\
             const N = AL;\nconst keys = Object.keys(AL);\n\
             const rec = AC as Record<string, unknown>;\n\
             const pick = (o: object) => o;\nconst picked = pick(CA);\n\
             const merged = Object.assign({}, OA);\n\
             const list = [AR];\n\
             const props = { all: PP, classes: styles };\n\
             const moon = FD.Moon;\n\
             const util: Util = new Util();\nconst value = util.getter;\n\
             ---\n\
             <AL.Star /><AC.Star /><CA.Star /><OA.Star /><AR.Star /><PP.Star /><FD.Star />\n\
             <p class={styles.root}>{N.Moon}{keys.length}{rec.Moon}{picked}{merged.Moon}{list.length}{moon}{value}</p>\n\
             <Callout {...props} />\n";
        let mut whole = template_whole_object_uses(source);
        whole.sort();
        assert_eq!(
            whole,
            vec!["AC", "AL", "AR", "CA", "OA", "PP", "styles"]
                .into_iter()
                .map(str::to_string)
                .collect::<Vec<_>>(),
            "every bare frontmatter mention of a narrowable binding must keep it on mark-all, once"
        );
        let accesses = template_member_accesses(source);
        assert!(
            accesses.contains(&("FD".to_string(), "Moon".to_string())),
            "the dotted-only frontmatter access should be recorded; got {accesses:?}"
        );
    }
}