self_update 1.3.0

Self updates for standalone executables
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
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
/*!
gitee releases
*/
use crate::backends::common::{CommonBuilderConfig, CommonConfig, RequestConfig};
use crate::backends::{Page, PageRequest, first_page_url, next_link, run_paginated};
use crate::http_client::{HeaderMap, header};
use crate::version::bump_is_greater;
use crate::{
    errors::*,
    update::{Release, ReleaseAsset, ReleaseUpdate, Releases},
};
use serde::Deserialize;

/// The default gitee host. Unlike gitea (which has no canonical public host and requires one),
/// gitee.com is the canonical public instance, so `host(..)` is optional and defaults here. The
/// setter is kept for self-hosted Gitee Enterprise deployments.
const DEFAULT_HOST: &str = "https://gitee.com";

/// Gitee's canonical host. A token resolved from the environment is bound to whatever host the
/// application configured, so `build()` warns when that host is neither this one nor an
/// acknowledged `allow_auth_host` entry (see
/// [`env_token_host_decision`](crate::backends::common::env_token_host_decision)).
const CANONICAL_AUTH_HOST: &str = "gitee.com";

/// Gitee release-asset JSON shape (download URL is `browser_download_url`). Private DTO converted
/// into the public [`ReleaseAsset`]; keeping it private keeps `Deserialize` out of `ReleaseAsset`'s
/// public API.
#[derive(Deserialize)]
struct AssetDto {
    name: Option<String>,
    browser_download_url: Option<String>,
}

impl AssetDto {
    /// Convert to a public asset, or `None` (skipped) when it lacks a usable `name` or
    /// `browser_download_url`.
    ///
    /// This is deliberately LENIENT, unlike gitea's strict `into_asset` (which errors on a missing
    /// field). Every gitee release carries an auto-generated source-code archive that appears in the
    /// `assets` array WITHOUT a `name` (and often without a `browser_download_url`). Treating that
    /// as a hard `MissingAssetField` error would make every gitee release fail to parse and thus be
    /// unusable, so a nameless / URL-less asset is quietly dropped (debug-logged) instead. Named,
    /// downloadable assets on the same release still parse normally.
    fn into_asset(self) -> Option<ReleaseAsset> {
        let name = match self.name {
            Some(name) => name,
            None => {
                log::debug!(
                    "self_update: skipping gitee asset with no name (likely the auto-generated \
                     source archive)"
                );
                return None;
            }
        };
        let download_url = match self.browser_download_url {
            Some(url) => url,
            None => {
                log::debug!(
                    "self_update: skipping gitee asset `{name}` with no browser_download_url"
                );
                return None;
            }
        };
        Some(ReleaseAsset::new(name, download_url))
    }
}

/// Gitee release JSON shape. Private DTO deserialized directly from the response bytes, then
/// converted into the public [`Release`].
#[derive(Deserialize)]
struct ReleaseDto {
    tag_name: Option<String>,
    created_at: Option<String>,
    name: Option<String>,
    body: Option<String>,
    html_url: Option<String>,
    assets: Option<Vec<AssetDto>>,
}

impl ReleaseDto {
    fn into_release(self, tag_prefix: Option<&str>) -> Result<Release> {
        let tag = self
            .tag_name
            .ok_or_else(|| Error::missing_asset_field("tag_name"))?;
        let date = self
            .created_at
            .ok_or_else(|| Error::missing_asset_field("created_at"))?;
        let assets = self
            .assets
            .ok_or_else(|| Error::missing_asset_field("assets"))?;
        let name = self.name.unwrap_or_else(|| tag.clone());
        // Lenient asset mapping: nameless / URL-less assets (gitee's auto-generated source archive)
        // are skipped rather than failing the whole release. See `AssetDto::into_asset`.
        let assets = assets
            .into_iter()
            .filter_map(AssetDto::into_asset)
            .collect::<Vec<ReleaseAsset>>();
        let version =
            crate::backends::common::strip_tag_prefix(&tag, tag_prefix).ok_or_else(|| {
                crate::backends::common::tag_prefix_mismatch_error(
                    &tag,
                    tag_prefix.unwrap_or_default(),
                )
            })?;
        let mut builder = Release::builder();
        builder
            .name(name)
            .version(version)
            .date(date)
            .assets(assets);
        if let Some(body) = self.body {
            builder.body(body);
        }
        if let Some(url) = self.html_url {
            builder.release_notes_url(url);
        }
        builder
            .build()
            .map_err(|e| crate::backends::common::name_tag_in_semver_error(&tag, e))
    }
}

/// `ReleaseList` Builder
///
/// `Debug` is hand-written (not derived) so `auth_token` renders as `"<token>"` instead of printing
/// a live credential from a `log::debug!("{builder:?}")`.
#[derive(Clone)]
#[must_use]
pub struct ReleaseListBuilder {
    host: Option<String>,
    repo_owner: Option<String>,
    repo_name: Option<String>,
    target: Option<String>,
    auth_token: Option<String>,
    /// `true` when `auth_token` came from `auth_token_from_env()`; cleared by `auth_token(..)`.
    auth_token_from_env: bool,
    request: RequestConfig,
}

impl std::fmt::Debug for ReleaseListBuilder {
    /// Every field, with the token redacted exactly as `RequestConfig`'s `Debug` does.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        // Exhaustive, no `..`: a field added to the struct and not listed here is a compile error.
        let Self {
            host,
            repo_owner,
            repo_name,
            target,
            auth_token,
            auth_token_from_env,
            request,
        } = self;
        f.debug_struct("ReleaseListBuilder")
            .field("host", host)
            .field("repo_owner", repo_owner)
            .field("repo_name", repo_name)
            .field("target", target)
            .field("auth_token", &auth_token.as_ref().map(|_| "<token>"))
            .field("auth_token_from_env", auth_token_from_env)
            .field("request", request)
            .finish()
    }
}

impl ReleaseListBuilder {
    /// Optional. Set the base URL of a self-hosted Gitee (Gitee Enterprise) instance, e.g.
    /// `https://gitee.example.com`. Defaults to `https://gitee.com`.
    ///
    /// Unlike `gitea` (which has no canonical public host and so requires this), gitee.com is the
    /// canonical public instance, so leaving this unset targets gitee.com.
    ///
    /// Pass the instance host only (scheme + host, no trailing slash); the crate appends the
    /// `/api/v5/...` path itself. Do not include `/api/v5`.
    pub fn host(&mut self, url: impl Into<String>) -> &mut Self {
        self.host = Some(url.into());
        self
    }

    /// Required. Set the repo owner, used to build a gitee api url
    pub fn repo_owner(&mut self, owner: impl Into<String>) -> &mut Self {
        self.repo_owner = Some(owner.into());
        self
    }

    /// Required. Set the repo name, used to build a gitee api url
    pub fn repo_name(&mut self, name: impl Into<String>) -> &mut Self {
        self.repo_name = Some(name.into());
        self
    }

    /// Set the optional arch `target` name, used to filter the releases this list returns to
    /// those carrying an asset whose name contains `target`.
    ///
    /// This is the **`ReleaseList`** filter and differs from
    /// [`Update::target`](UpdateBuilder::target): `filter_target` drops whole releases from the
    /// listing when no asset matches, whereas the `Update` `target` selects *which asset* of the
    /// chosen release to download.
    pub fn filter_target(&mut self, target: impl Into<String>) -> &mut Self {
        self.target = Some(target.into());
        self
    }

    /// Set the authorization token, used in requests to the gitee api url
    ///
    /// This is to support private repos where you need a gitee auth token.
    /// **Make sure not to bake the token into your app**; it is recommended
    /// you obtain it via another mechanism, such as environment variables
    /// or prompting the user for input
    ///
    /// The token can also be taken from the environment with
    /// [`auth_token_from_env`](Self::auth_token_from_env). This setter always wins over that one,
    /// in either call order.
    pub fn auth_token(&mut self, auth_token: impl Into<String>) -> &mut Self {
        crate::backends::common::set_explicit_auth_token(
            &mut self.auth_token,
            &mut self.auth_token_from_env,
            auth_token,
        );
        self
    }

    impl_auth_token_from_env!(
        token: auth_token,
        env_sourced: auth_token_from_env,
        vars: ["GITEE_TOKEN"],
        rationale: "Authenticating lifts whatever anonymous request budget the host applies -- such \
                    budgets are typically counted **per source IP**, so one can be exhausted by \
                    unrelated traffic behind the same NAT, surfacing as \
                    [`RateLimited`](crate::errors::Error::RateLimited). See the crate-level \
                    rate-limit notes.\n\n`GITEE_TOKEN` is read whatever `host(..)` you configure, \
                    so pointing this builder at a Gitee Enterprise instance while the variable \
                    holds a gitee.com token logs a warning from `build()`.",
    );

    request_config_setters!(request);

    /// Verify builder args, returning a `ReleaseList`
    pub fn build(&self) -> Result<ReleaseList> {
        // Thread the auth token + gitee's `Bearer` scheme into the request so the shared
        // `apply_auth` applies it on the listing path (honoring a user override). Gitee v5 accepts
        // `Authorization: Bearer <token>` (verified against gitee's official client
        // oschina/mcp-gitee gitee_client.go).
        let host = self
            .host
            .clone()
            .unwrap_or_else(|| DEFAULT_HOST.to_string());
        let mut request = self.request.clone();
        request.auth_scheme = crate::backends::common::AuthScheme::Bearer;
        request.auth_token = self.auth_token.clone();
        request.auth_base_host = crate::backends::common::host_of(&host);
        request.build_client();
        request.check()?;
        // An env-sourced token is bound to whatever host was configured, which the request-time host
        // gate cannot flag (the configured host *is* `auth_base_host`); warn when that is not
        // gitee.com (or an acknowledged `allow_auth_host` entry). gitee always has a canonical host,
        // so the token is still sent either way (DECIDED, A1) -- checked after `request.check()?` so
        // a builder that is about to fail validation does not also log.
        crate::backends::common::env_token_host_decision(
            self.auth_token_from_env,
            request.auth_base_host.as_deref(),
            &request.auth_hosts,
            Some(CANONICAL_AUTH_HOST),
        );
        Ok(ReleaseList {
            host,
            repo_owner: if let Some(ref owner) = self.repo_owner {
                owner.to_owned()
            } else {
                return Err(Error::MissingField {
                    field: "repo_owner",
                });
            },
            repo_name: if let Some(ref name) = self.repo_name {
                name.to_owned()
            } else {
                return Err(Error::MissingField { field: "repo_name" });
            },
            target: self.target.clone(),
            request,
        })
    }
}

/// `ReleaseList` provides a builder api for querying a gitee repo,
/// returning a `Vec` of available `Release`s
#[derive(Clone, Debug)]
pub struct ReleaseList {
    host: String,
    repo_owner: String,
    repo_name: String,
    target: Option<String>,
    request: RequestConfig,
}
impl ReleaseList {
    /// Initialize a ReleaseListBuilder
    pub fn configure() -> ReleaseListBuilder {
        ReleaseListBuilder {
            host: None,
            repo_owner: None,
            repo_name: None,
            target: None,
            auth_token: None,
            auth_token_from_env: false,
            request: RequestConfig::default(),
        }
    }
    // Note: `auth_token` lives only in `ReleaseListBuilder` (to wire into `request.auth_token`
    // during `build()`). The built `ReleaseList` does not carry it: auth is applied centrally
    // by `apply_auth` on the request config during transport.

    /// Retrieve the available `Release`s as a [`Releases`].
    ///
    /// If a `filter_target` is set, only releases carrying an asset whose name contains it are
    /// returned. The result carries no current version (it is a bare listing), so
    /// [`Releases::current_version`] is `None`; use [`Releases::into_vec`] to recover the raw
    /// `Vec<Release>`.
    pub fn fetch(&self) -> Result<Releases> {
        let api_url = format!(
            "{}/api/v5/repos/{}/{}/releases",
            self.host,
            urlencoding::encode(&self.repo_owner),
            urlencoding::encode(&self.repo_name)
        );

        // An unfiltered listing must walk ALL pages: `stop_at = None`.
        let releases = run_paginated(releases_plan(&api_url, None, None)?, &self.request)?;
        let releases = match self.target {
            None => releases,
            Some(ref target) => releases
                .into_iter()
                .filter(|r| r.has_target_asset(target))
                .collect::<Vec<_>>(),
        };
        Ok(Releases::from_listing(releases))
    }

    /// Async sibling of [`fetch`](Self::fetch).
    #[cfg(feature = "async")]
    pub async fn fetch_async(&self) -> Result<Releases> {
        let api_url = format!(
            "{}/api/v5/repos/{}/{}/releases",
            self.host,
            urlencoding::encode(&self.repo_owner),
            urlencoding::encode(&self.repo_name)
        );

        // An unfiltered listing must walk ALL pages: `stop_at = None`.
        let releases = crate::backends::run_paginated_async(
            releases_plan(&api_url, None, None)?,
            &self.request,
        )
        .await?;
        let releases = match self.target {
            None => releases,
            Some(ref target) => releases
                .into_iter()
                .filter(|r| r.has_target_asset(target))
                .collect::<Vec<_>>(),
        };
        Ok(Releases::from_listing(releases))
    }
}

/// `gitee::Update` builder
///
/// Configure download and installation from
/// `https://<gitee-host>/api/v5/repos/<repo_owner>/<repo_name>/releases`
#[derive(Clone, Debug, Default)]
#[must_use]
pub struct UpdateBuilder {
    host: Option<String>,
    repo_owner: Option<String>,
    repo_name: Option<String>,
    common: CommonBuilderConfig,
}

impl UpdateBuilder {
    /// Initialize a new builder
    pub fn new() -> Self {
        Default::default()
    }

    /// Optional. Set the base URL of a self-hosted Gitee (Gitee Enterprise) instance, e.g.
    /// `https://gitee.example.com`. Defaults to `https://gitee.com`.
    ///
    /// Unlike `gitea` (which has no canonical public host and so requires this), gitee.com is the
    /// canonical public instance, so leaving this unset targets gitee.com.
    ///
    /// Pass the instance host only (scheme + host, no trailing slash); the crate appends the
    /// `/api/v5/...` path itself. Do not include `/api/v5`.
    pub fn host(&mut self, url: impl Into<String>) -> &mut Self {
        self.host = Some(url.into());
        self
    }

    /// Required. Set the repo owner, used to build a gitee api url
    pub fn repo_owner(&mut self, owner: impl Into<String>) -> &mut Self {
        self.repo_owner = Some(owner.into());
        self
    }

    /// Required. Set the repo name, used to build a gitee api url
    pub fn repo_name(&mut self, name: impl Into<String>) -> &mut Self {
        self.repo_name = Some(name.into());
        self
    }

    /// Set the tag prefix used to derive a release version from its tag. Defaults to unset, which
    /// trims a leading `v` (so `v1.2.3` and `1.2.3` both yield `1.2.3`). Set it to, e.g., `myapp-`
    /// for a monorepo whose tags look like `myapp-1.2.3` (or `myapp-v1.2.3`); tags without the
    /// prefix are then skipped from the listing rather than mis-parsed.
    pub fn tag_prefix(&mut self, prefix: impl Into<String>) -> &mut Self {
        self.common.tag_prefix = Some(prefix.into());
        self
    }

    impl_common_builder_setters!(
        auth_env: ["GITEE_TOKEN"],
        rationale: "Authenticating lifts whatever anonymous request budget the host applies -- such \
                    budgets are typically counted **per source IP**, so one can be exhausted by \
                    unrelated traffic behind the same NAT, surfacing as \
                    [`RateLimited`](crate::errors::Error::RateLimited). See the crate-level \
                    rate-limit notes.\n\n`GITEE_TOKEN` is read whatever `host(..)` you configure, \
                    so pointing this builder at a Gitee Enterprise instance while the variable \
                    holds a gitee.com token logs a warning from `build()`.",
    );

    /// Internal: validate config into a concrete `Update`. Shared by `build` / `build_async`.
    fn build_update(&self) -> Result<Update> {
        let host = self
            .host
            .clone()
            .unwrap_or_else(|| DEFAULT_HOST.to_string());
        Ok(Update {
            repo_owner: if let Some(ref owner) = self.repo_owner {
                owner.to_owned()
            } else {
                return Err(Error::MissingField {
                    field: "repo_owner",
                });
            },
            repo_name: if let Some(ref name) = self.repo_name {
                name.to_owned()
            } else {
                return Err(Error::MissingField { field: "repo_name" });
            },
            common: {
                // Gitee authenticates with `Bearer <token>` (verified against gitee's official
                // client oschina/mcp-gitee gitee_client.go); set the scheme explicitly rather than
                // relying on `AuthScheme::default()` (which is `Token`).
                let mut resolved = self.common.build()?;
                resolved.request.auth_scheme = crate::backends::common::AuthScheme::Bearer;
                // Only the gitee host receives the token; a server-supplied asset download URL on
                // another host does not.
                resolved.request.auth_base_host = crate::backends::common::host_of(&host);
                // An env-sourced token is bound to whatever host was configured, which the
                // request-time host gate cannot flag (the configured host *is* `auth_base_host`);
                // warn when that is not gitee.com (or an acknowledged `allow_auth_host` entry).
                // gitee always has a canonical host, so the token is still sent either way
                // (DECIDED, A1).
                crate::backends::common::env_token_host_decision(
                    self.common.auth_token_from_env,
                    resolved.request.auth_base_host.as_deref(),
                    &resolved.request.auth_hosts,
                    Some(CANONICAL_AUTH_HOST),
                );
                resolved
            },
            host,
        })
    }

    /// Confirm config and create a ready-to-use `Update`.
    ///
    /// Returns the concrete [`Update`], which is `Send` and exposes the update verbs as inherent
    /// methods.
    pub fn build(&self) -> Result<Update> {
        self.build_update()
    }

    /// Confirm config and create a ready-to-use [`AsyncUpdate`] for the async API (`update_async`).
    ///
    /// Unlike [`build`](Self::build) this returns the distinct [`AsyncUpdate`] newtype, which exposes
    /// only the inherent `*_async` verbs, so a stray blocking `.update()` on an async-built updater
    /// is a compile error rather than a silent block of the executor.
    #[cfg(feature = "async")]
    pub fn build_async(&self) -> Result<AsyncUpdate> {
        Ok(AsyncUpdate(self.build_update()?))
    }
}

/// Updates to a specified or latest release distributed via gitee
#[derive(Debug)]
#[non_exhaustive]
pub struct Update {
    host: String,
    repo_owner: String,
    repo_name: String,
    common: CommonConfig,
}
impl Update {
    /// Initialize a new `Update` builder
    pub fn configure() -> UpdateBuilder {
        UpdateBuilder::new()
    }

    /// Base releases URL. Shared by the sync and async fetch paths so they can't drift.
    fn releases_url(&self) -> String {
        format!(
            "{}/api/v5/repos/{}/{}/releases",
            self.host,
            urlencoding::encode(&self.repo_owner),
            urlencoding::encode(&self.repo_name)
        )
    }

    /// The dedicated newest-release URL: `.../releases/latest` (a single release *object*).
    fn latest_url(&self) -> String {
        format!("{}/latest", self.releases_url())
    }
}

impl crate::update::sealed::Sealed for Update {}

impl Update {
    /// The single-release-by-tag URL: `.../releases/tags/{ver}`.
    fn tag_url(&self, ver: &str) -> String {
        format!("{}/tags/{}", self.releases_url(), urlencoding::encode(ver))
    }
}

impl ReleaseUpdate for Update {
    fn get_latest_release(&self) -> Result<Releases> {
        let current_version = crate::update::UpdateConfig::current_version(self).to_owned();
        let releases = run_paginated(
            newest_plan(
                self.latest_url(),
                &self.releases_url(),
                self.common.tag_prefix.as_deref(),
            )?,
            &self.common.request,
        )?;
        let release = releases
            .into_iter()
            .next()
            .ok_or_else(|| Error::NoReleaseFound { target: None })?;
        Ok(Releases::new(vec![release], current_version))
    }

    fn get_newer_releases(&self) -> Result<Releases> {
        let current_version = crate::update::UpdateConfig::current_version(self).to_owned();
        let releases = run_paginated(
            releases_plan(
                &self.releases_url(),
                Some(&current_version),
                self.common.tag_prefix.as_deref(),
            )?,
            &self.common.request,
        )?;
        Ok(Releases::new(releases, current_version))
    }

    fn get_release_version(&self, ver: &str) -> Result<Release> {
        let releases = run_paginated(
            single_plan(self.tag_url(ver), self.common.tag_prefix.as_deref())?,
            &self.common.request,
        )?;
        releases
            .into_iter()
            .next()
            .ok_or_else(|| Error::NoReleaseFound { target: None })
    }
}

impl_sync_update_verbs!(Update);

/// Async-only updater returned by [`UpdateBuilder::build_async`].
///
/// A newtype over the blocking [`Update`] that exposes **only** the inherent `*_async` verbs. Using
/// it (instead of returning `Update` from `build_async`) makes a blocking call on an async-built
/// updater -- e.g. `build_async()?.update()` -- a compile error, so the async executor cannot be
/// silently blocked.
#[cfg(feature = "async")]
#[derive(Debug)]
pub struct AsyncUpdate(Update);

#[cfg(feature = "async")]
impl_async_update_verbs!(AsyncUpdate);

impl_update_config_accessors!(Update, {
    fn api_headers(&self, _auth_token: Option<&str>) -> Result<header::HeaderMap> {
        api_headers()
    }
});

/// Transport-free plan to fetch the paginated `releases` array (Gitee format), parsing each page
/// via the private `ReleaseDto` and following `Link: rel="next"`. See github's `releases_plan`
/// for the `stop_at` per-item filter contract.
///
/// `stop_at` filters per-item: when `Some(current_version)` each release that is not strictly
/// newer than it is omitted from the collected list, but pagination continues to subsequent pages
/// regardless (a backport release -- older semver, newer creation date -- must not halt the walk
/// and cause a genuinely newer release on a later page to be missed). When `None` the listing is
/// unfiltered and every page is walked (used by `ReleaseList`).
fn releases_plan(
    base_url: &str,
    stop_at: Option<&str>,
    tag_prefix: Option<&str>,
) -> Result<PageRequest<Release>> {
    let headers = api_headers()?;
    let stop_at = stop_at.map(str::to_owned);
    Ok(release_array_page(
        first_page_url(base_url),
        headers,
        stop_at,
        tag_prefix.map(str::to_owned),
    ))
}

fn release_array_page(
    url: String,
    headers: HeaderMap,
    stop_at: Option<String>,
    tag_prefix: Option<String>,
) -> PageRequest<Release> {
    PageRequest {
        url,
        headers,
        parse: Box::new(move |body, resp_headers| {
            // Deserialize the page directly into the private DTO vec (no intermediate
            // `serde_json::Value` tree), then convert each into a public `Release`.
            let dtos: Vec<ReleaseDto> =
                serde_json::from_slice(body).map_err(|e| Error::InvalidResponse {
                    source: Box::new(e),
                })?;
            let mut items = Vec::new();
            for dto in dtos {
                let release = match dto.into_release(tag_prefix.as_deref()) {
                    Ok(release) => release,
                    // A non-semver tag (`nightly`, `latest`, a date tag) is not a release the
                    // updater can compare; skip it rather than failing the whole listing, so a
                    // repository mixing rolling tags with semver releases stays updatable.
                    Err(e @ Error::SemVer(_)) => {
                        log::debug!("self_update: skipping listed release: {e}");
                        continue;
                    }
                    Err(e) => return Err(e),
                };
                // Skip releases not strictly newer than the current version, but do NOT stop
                // pagination. A backport release (older semver, newer creation date) must not
                // halt the walk; a genuinely newer release on a later page must still be found.
                if let Some(ref current) = stop_at
                    && !bump_is_greater(current, release.version()).unwrap_or(false)
                {
                    continue;
                }
                items.push(release);
            }
            let next = next_link(resp_headers)
                .map(|next_url| -> Result<PageRequest<Release>> {
                    Ok(release_array_page(
                        next_url,
                        api_headers()?,
                        stop_at.clone(),
                        tag_prefix.clone(),
                    ))
                })
                .transpose()?;
            Ok(Page {
                items,
                next,
                stop: false,
            })
        }),
    }
}

/// Transport-free plan for the newest release. Unlike gitea/gitlab (which have no `/releases/latest`
/// and take the listing's first entry), gitee has a dedicated `/api/v5/.../releases/latest`
/// endpoint returning a single release *object*. Fetch that first.
///
/// If that "latest" release carries a non-semver rolling tag (`nightly`, `latest`, ...) the updater
/// cannot compare it, so fall back to scanning the listing's first page for the newest release the
/// updater CAN compare -- mirroring gitea's `newest_plan` skip semantics. That fallback is wired as
/// the `next` page of the initial (empty-items) `/latest` page, so the shared paginated driver
/// performs the second fetch.
fn newest_plan(
    latest_url: String,
    listing_url: &str,
    tag_prefix: Option<&str>,
) -> Result<PageRequest<Release>> {
    let headers = api_headers()?;
    let tag_prefix = tag_prefix.map(str::to_owned);
    let listing_first = first_page_url(listing_url);
    Ok(PageRequest {
        url: latest_url,
        headers,
        parse: Box::new(move |body, _resp_headers| {
            // `/releases/latest` returns a single release *object* (parsed like the tag route).
            let dto: ReleaseDto =
                serde_json::from_slice(body).map_err(crate::errors::Error::invalid_response)?;
            match dto.into_release(tag_prefix.as_deref()) {
                Ok(release) => Ok(Page::last(vec![release])),
                // The pinned "latest" is a non-semver rolling tag; fall back to scanning the
                // listing for the newest release the updater can actually compare.
                Err(Error::SemVer(e)) => {
                    log::debug!(
                        "self_update: gitee latest release is non-semver ({e}); \
                         scanning the listing for the newest comparable release"
                    );
                    Ok(Page {
                        items: vec![],
                        next: Some(newest_from_listing_page(
                            listing_first.clone(),
                            api_headers()?,
                            tag_prefix.clone(),
                        )),
                        stop: false,
                    })
                }
                Err(e) => Err(e),
            }
        }),
    })
}

/// The listing-scan fallback used by [`newest_plan`] when `/releases/latest` is a non-semver tag.
/// Parses the listing array (newest-first) and returns the first release the updater can compare,
/// skipping non-semver rolling tags. An all-non-semver (or empty) page yields `NoReleaseFound`.
fn newest_from_listing_page(
    url: String,
    headers: HeaderMap,
    tag_prefix: Option<String>,
) -> PageRequest<Release> {
    PageRequest {
        url,
        headers,
        parse: Box::new(move |body, _resp_headers| {
            let dtos: Vec<ReleaseDto> =
                serde_json::from_slice(body).map_err(|e| Error::InvalidResponse {
                    source: Box::new(e),
                })?;
            for dto in dtos {
                match dto.into_release(tag_prefix.as_deref()) {
                    Ok(release) => return Ok(Page::last(vec![release])),
                    Err(e @ Error::SemVer(_)) => {
                        log::debug!("self_update: skipping listed release: {e}");
                    }
                    Err(e) => return Err(e),
                }
            }
            Err(Error::NoReleaseFound { target: None })
        }),
    }
}

/// Transport-free plan to fetch a single release *object* (the `.../releases/tags/{ver}` endpoint).
fn single_plan(url: String, tag_prefix: Option<&str>) -> Result<PageRequest<Release>> {
    let headers = api_headers()?;
    let tag_prefix = tag_prefix.map(str::to_owned);
    Ok(PageRequest {
        url,
        headers,
        parse: Box::new(move |body, _resp_headers| {
            // An unparseable body is `InvalidResponse`, matching the paginated listing parser.
            let dto: ReleaseDto =
                serde_json::from_slice(body).map_err(crate::errors::Error::invalid_response)?;
            Ok(Page::last(vec![dto.into_release(tag_prefix.as_deref())?]))
        }),
    })
}

#[cfg(feature = "async")]
impl crate::update::AsyncReleaseUpdate for Update {
    async fn get_latest_release_async(&self) -> Result<Releases> {
        use crate::backends::run_paginated_async;
        let current_version = crate::update::UpdateConfig::current_version(self).to_owned();
        let releases = run_paginated_async(
            newest_plan(
                self.latest_url(),
                &self.releases_url(),
                self.common.tag_prefix.as_deref(),
            )?,
            &self.common.request,
        )
        .await?;
        let release = releases
            .into_iter()
            .next()
            .ok_or_else(|| Error::NoReleaseFound { target: None })?;
        Ok(Releases::new(vec![release], current_version))
    }

    async fn get_newer_releases_async(&self) -> Result<Releases> {
        use crate::backends::run_paginated_async;
        let current_version = crate::update::UpdateConfig::current_version(self).to_owned();
        let releases = run_paginated_async(
            releases_plan(
                &self.releases_url(),
                Some(&current_version),
                self.common.tag_prefix.as_deref(),
            )?,
            &self.common.request,
        )
        .await?;
        Ok(Releases::new(releases, current_version))
    }

    async fn get_release_version_async(&self, ver: &str) -> Result<Release> {
        use crate::backends::run_paginated_async;
        let releases = run_paginated_async(
            single_plan(self.tag_url(ver), self.common.tag_prefix.as_deref())?,
            &self.common.request,
        )
        .await?;
        releases
            .into_iter()
            .next()
            .ok_or_else(|| Error::NoReleaseFound { target: None })
    }
}

/// Build gitee's base request headers (its User-Agent). The Authorization header is applied
/// centrally by the shared [`apply_auth`](crate::backends::common::RequestConfig::apply_auth) using
/// gitee's `Bearer` scheme on both the listing and download paths, honoring a user override.
fn api_headers() -> Result<header::HeaderMap> {
    let mut headers = header::HeaderMap::new();
    headers.insert(
        header::USER_AGENT,
        crate::DEFAULT_USER_AGENT
            .parse()
            .expect("gitee invalid user-agent"),
    );

    Ok(headers)
}

#[cfg(test)]
mod tests {
    use super::Update;
    use crate::update::UpdateConfig;

    // --- AUTH-1: the environment-sourced auth token -------------------------------------------

    // AUTH-1: `auth_token_from_env()` is present on both gitee builders and is chainable. This is
    // effectively a "the method exists and does not panic" check, not a behavioral one: it reads the
    // REAL process environment, so it means something different on a clean machine (nothing set)
    // than on a dev box exporting `GITEE_TOKEN` -- either way it only asserts `build()` stays `Ok`,
    // which passes in both cases. The env-var precedence itself is unit-tested in `backends::common`
    // without touching process env; the actual pickup-from-environment behavior is pinned on the
    // wire by the per-backend integration binary `tests/auth_token_env_gitee.rs`, which controls the
    // environment directly.
    #[test]
    fn auth_token_from_env_is_available_on_both_builders() {
        super::Update::configure()
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .auth_token_from_env()
            .build()
            .expect("an env-sourced token must leave the update builder buildable");
        super::ReleaseList::configure()
            .repo_owner("o")
            .repo_name("r")
            .auth_token_from_env()
            .build()
            .expect("an env-sourced token must leave the release-list builder buildable");
    }

    // The exact variable list, on both builders: gitee reads only `GITEE_TOKEN`. Nothing else
    // catches a typo, or another backend's list arriving here by copy-paste -- which would send a
    // credential meant for a different forge to gitee.
    #[test]
    fn auth_token_env_vars_are_gitee_token_only() {
        assert_eq!(super::UpdateBuilder::AUTH_TOKEN_ENV_VARS, ["GITEE_TOKEN"]);
        assert_eq!(
            super::ReleaseListBuilder::AUTH_TOKEN_ENV_VARS,
            ["GITEE_TOKEN"]
        );
    }

    // ...and that declared list is the one actually consulted: candidate `(name, value)` pairs
    // built FROM the const, run through the very resolver the setter uses, resolve to the first
    // name in it. Proves the const is not a stale copy of the real list, without mutating env.
    //
    // Both builders' consts are driven, not just the `UpdateBuilder`'s: they are declared by two
    // separate macro invocations, so a typo in the `ReleaseListBuilder`'s list is a real (and
    // previously untested) way for the two builders of one backend to disagree about which
    // credential to use.
    #[test]
    fn the_declared_env_vars_drive_the_resolver() {
        for (builder, vars) in [
            ("UpdateBuilder", super::UpdateBuilder::AUTH_TOKEN_ENV_VARS),
            (
                "ReleaseListBuilder",
                super::ReleaseListBuilder::AUTH_TOKEN_ENV_VARS,
            ),
        ] {
            let candidates: Vec<(&str, Option<String>)> = vars
                .iter()
                .map(|name| (*name, Some(format!("token-for-{name}"))))
                .collect();
            assert_eq!(
                crate::backends::common::first_env_token(&candidates).as_deref(),
                Some("token-for-GITEE_TOKEN"),
                "the first declared variable must win on {builder}"
            );
        }
    }

    // C: an explicit `auth_token(..)` always wins over the environment, in EITHER call order, on
    // both builders -- the pair is order-independent like every other setter pair.
    #[test]
    fn an_explicit_auth_token_wins_over_the_env_lookup_in_either_order() {
        let env_then_explicit = super::Update::configure()
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .auth_token_from_env()
            .auth_token("explicit")
            .build()
            .unwrap();
        let explicit_then_env = super::Update::configure()
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .auth_token("explicit")
            .auth_token_from_env()
            .build()
            .unwrap();
        for upd in [env_then_explicit, explicit_then_env] {
            assert_eq!(upd.auth_token(), Some("explicit"));
        }

        let env_then_explicit = super::ReleaseList::configure()
            .repo_owner("o")
            .repo_name("r")
            .auth_token_from_env()
            .auth_token("explicit")
            .build()
            .unwrap();
        let explicit_then_env = super::ReleaseList::configure()
            .repo_owner("o")
            .repo_name("r")
            .auth_token("explicit")
            .auth_token_from_env()
            .build()
            .unwrap();
        for list in [env_then_explicit, explicit_then_env] {
            assert_eq!(list.request.auth_token.as_deref(), Some("explicit"));
        }
    }

    // K: `has_auth_token()` answers "is a token configured?" on both builders without the
    // application reimplementing the variable list. (The env-pickup half is covered by the
    // single-test integration binary `tests/auth_token_env_gitee.rs`, which may set process env.)
    #[test]
    fn has_auth_token_reports_an_explicitly_set_token() {
        let mut upd = super::Update::configure();
        assert!(
            !upd.has_auth_token(),
            "a fresh builder has no token: the update runs anonymously"
        );
        upd.auth_token("explicit");
        assert!(upd.has_auth_token());

        let mut list = super::ReleaseList::configure();
        assert!(!list.has_auth_token());
        list.auth_token("explicit");
        assert!(list.has_auth_token());
    }

    // A5: a blank explicit token (empty or all-whitespace) is not "configured" -- otherwise
    // `apply_auth` would go on to send a literal `Authorization: Bearer ` header.
    #[test]
    fn has_auth_token_treats_a_blank_explicit_token_as_unset() {
        let mut upd = super::Update::configure();
        upd.auth_token("");
        assert!(
            !upd.has_auth_token(),
            "an empty token must not count as configured"
        );
        upd.auth_token("   ");
        assert!(
            !upd.has_auth_token(),
            "an all-whitespace token must not count as configured"
        );

        let mut list = super::ReleaseList::configure();
        list.auth_token("");
        assert!(!list.has_auth_token());
        list.auth_token("   ");
        assert!(!list.has_auth_token());
    }

    // A1 (DECIDED): gitee has a canonical host, so an env-sourced token bound to an unacknowledged
    // custom host is still SENT (only the warning differs from the canonical-host case; gitea is the
    // backend that withholds instead -- see `backends::gitea`'s equivalent test).
    #[test]
    fn release_list_still_sends_an_env_sourced_token_off_the_canonical_host() {
        let mut list = super::ReleaseList::configure();
        list.host("https://gitee.mycorp.com")
            .repo_owner("o")
            .repo_name("r");
        list.auth_token = Some("ambient".to_string());
        list.auth_token_from_env = true;
        let built = list
            .build()
            .expect("an unacknowledged host must not fail build()");
        assert_eq!(
            built.request.auth_token.as_deref(),
            Some("ambient"),
            "gitee must still send an env-sourced token off its canonical host"
        );
    }

    // A: `Debug` on either builder must never print the token. Both hold a plaintext
    // `Option<String>`, so a plain `log::debug!("{builder:?}")` used to dump a live credential --
    // and `auth_token_from_env()` is exactly what puts an ambient CI credential there.
    #[test]
    fn builder_debug_redacts_the_auth_token() {
        let mut upd = super::Update::configure();
        upd.repo_owner("owner-o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .auth_token("gitee_supersecret");
        let rendered = format!("{upd:?}");
        assert!(
            !rendered.contains("gitee_supersecret"),
            "the UpdateBuilder must not print the token, got: {rendered}"
        );
        assert!(rendered.contains("<token>"), "got: {rendered}");
        assert!(
            rendered.contains("owner-o"),
            "other fields must survive the hand-written Debug, got: {rendered}"
        );

        let mut list = super::ReleaseList::configure();
        list.repo_owner("owner-o")
            .repo_name("r")
            .auth_token("gitee_supersecret");
        let rendered = format!("{list:?}");
        assert!(
            !rendered.contains("gitee_supersecret"),
            "the ReleaseListBuilder must not print the token, got: {rendered}"
        );
        assert!(rendered.contains("<token>"), "got: {rendered}");
        assert!(rendered.contains("owner-o"), "got: {rendered}");
    }

    // A hand-written `Debug` can leak a secret, and it can also silently *lose* a field -- a
    // regression the "does not contain the secret" assertion above would happily pass. Pin the
    // full field list of `ReleaseListBuilder`'s (this is the debug dump an application prints when
    // an update misbehaves; a dropped `host` or `auth_token_from_env` makes it useless).
    #[test]
    fn release_list_builder_debug_renders_every_field() {
        let rendered = format!("{:?}", super::ReleaseList::configure());
        for field in [
            "host",
            "repo_owner",
            "repo_name",
            "target",
            "auth_token",
            "auth_token_from_env",
            "request",
        ] {
            assert!(
                rendered.contains(&format!("{field}:")),
                "the hand-written Debug dropped `{field}`, got: {rendered}"
            );
        }
    }

    // A: the redaction must hold on every public type reachable from a configured builder, not just
    // on the builders themselves. The built `Update`'s Debug is covered by
    // `auth_token_never_appears_in_debug_or_error_display`; this adds the redaction *marker* (so a
    // Debug that dropped the field entirely is not mistaken for a redacted one), the `ReleaseList`,
    // and the async newtype, each of which is a distinct public type an application holds and dumps
    // into a bug report.
    #[test]
    fn built_types_debug_redacts_the_auth_token() {
        let list = super::ReleaseList::configure()
            .repo_owner("owner-o")
            .repo_name("r")
            .auth_token("gitee_supersecret")
            .build()
            .unwrap();
        let rendered = format!("{list:?}");
        assert!(
            !rendered.contains("gitee_supersecret"),
            "the built ReleaseList must not print the token, got: {rendered}"
        );
        assert!(
            rendered.contains("<token>"),
            "the token must still render as the redaction marker, got: {rendered}"
        );
        assert!(
            rendered.contains("owner-o"),
            "non-secret fields must survive, got: {rendered}"
        );

        let upd = super::Update::configure()
            .repo_owner("owner-o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .auth_token("gitee_supersecret")
            .build()
            .unwrap();
        let rendered = format!("{upd:?}");
        assert!(!rendered.contains("gitee_supersecret"), "got: {rendered}");
        assert!(rendered.contains("<token>"), "got: {rendered}");
        assert!(rendered.contains("owner-o"), "got: {rendered}");

        // The async newtype wraps the same `Update`, but it is a separate public type with its own
        // derived `Debug`.
        #[cfg(feature = "async")]
        {
            let upd = super::Update::configure()
                .repo_owner("owner-o")
                .repo_name("r")
                .bin_name("app")
                .current_version("0.1.0")
                .auth_token("gitee_supersecret")
                .build_async()
                .unwrap();
            let rendered = format!("{upd:?}");
            assert!(
                !rendered.contains("gitee_supersecret"),
                "the built AsyncUpdate must not print the token, got: {rendered}"
            );
            assert!(rendered.contains("<token>"), "got: {rendered}");
        }
    }

    /// Async test wrapper over `releases_plan` + the async driver (unfiltered, all pages).
    #[cfg(feature = "async")]
    async fn fetch_all_releases_async(
        base_url: &str,
        req: &crate::backends::common::RequestConfig,
    ) -> crate::errors::Result<Vec<super::Release>> {
        crate::backends::run_paginated_async(super::releases_plan(base_url, None, None)?, req).await
    }

    // The single-release endpoint (`.../releases/tags/{ver}`) surfaces an unparseable body as
    // `InvalidResponse`, matching the paginated listing parser.
    #[test]
    fn single_plan_parse_failure_is_invalid_response() {
        let req = super::single_plan("https://example.test/releases/tags/1.0.0".to_string(), None)
            .unwrap();
        let res = (req.parse)(b"not-json", &crate::http_client::HeaderMap::new());
        assert!(
            matches!(res, Err(crate::errors::Error::InvalidResponse { .. })),
            "a malformed single-release body must map to InvalidResponse"
        );
    }

    // A rolling non-semver tag (`nightly`) in the listing must be skipped, not fail the whole
    // fetch: repositories commonly mix rolling tags with semver releases.
    #[test]
    fn listing_skips_non_semver_tags() {
        let req = super::release_array_page(
            "https://example.test/releases".to_string(),
            crate::http_client::HeaderMap::new(),
            None,
            None,
        );
        let body = releases_json(&["nightly", "v1.2.3", "v1.0.0"]);
        let page = (req.parse)(body.as_bytes(), &crate::http_client::HeaderMap::new()).unwrap();
        let versions: Vec<&str> = page.items.iter().map(|r| r.version()).collect();
        assert_eq!(
            versions,
            vec!["1.2.3", "1.0.0"],
            "non-semver tags are skipped; the semver releases survive"
        );
    }

    // A configured `tag_prefix` derives the version from monorepo-style tags (`myapp-1.2.3`,
    // `myapp-v1.3.0`); tags without the prefix are skipped rather than mis-parsed.
    #[test]
    fn listing_with_tag_prefix_parses_prefixed_tags_and_skips_others() {
        let req = super::release_array_page(
            "https://example.test/releases".to_string(),
            crate::http_client::HeaderMap::new(),
            None,
            Some("myapp-".to_string()),
        );
        let body = releases_json(&["myapp-1.2.3", "otherapp-2.0.0", "myapp-v1.3.0", "1.0.0"]);
        let page = (req.parse)(body.as_bytes(), &crate::http_client::HeaderMap::new()).unwrap();
        let versions: Vec<&str> = page.items.iter().map(|r| r.version()).collect();
        assert_eq!(
            versions,
            vec!["1.2.3", "1.3.0"],
            "only `myapp-`-prefixed tags are parsed (with an optional inner `v`); the rest are skipped"
        );
    }

    // The listing-scan fallback skips a rolling tag so the first COMPARABLE release wins.
    #[test]
    fn newest_from_listing_skips_non_semver_tags() {
        let req = super::newest_from_listing_page(
            "https://example.test/releases".to_string(),
            crate::http_client::HeaderMap::new(),
            None,
        );
        let body = releases_json(&["nightly", "v1.2.3", "v1.0.0"]);
        let page = (req.parse)(body.as_bytes(), &crate::http_client::HeaderMap::new()).unwrap();
        let versions: Vec<&str> = page.items.iter().map(|r| r.version()).collect();
        assert_eq!(versions, vec!["1.2.3"]);
    }

    // With only non-semver tags in the fallback listing there is nothing the updater can compare:
    // NoReleaseFound.
    #[test]
    fn newest_from_listing_with_only_non_semver_tags_is_no_release_found() {
        let req = super::newest_from_listing_page(
            "https://example.test/releases".to_string(),
            crate::http_client::HeaderMap::new(),
            None,
        );
        let body = releases_json(&["nightly", "latest"]);
        let res = (req.parse)(body.as_bytes(), &crate::http_client::HeaderMap::new());
        assert!(
            matches!(
                res,
                Err(crate::errors::Error::NoReleaseFound { target: None })
            ),
            "an all-rolling-tag listing must yield NoReleaseFound"
        );
    }

    // The single-release endpoint cannot skip: a pinned non-semver tag errors, naming the tag.
    #[test]
    fn single_plan_non_semver_tag_errors_naming_the_tag() {
        let req = super::single_plan(
            "https://example.test/releases/tags/nightly".to_string(),
            None,
        )
        .unwrap();
        let res = (req.parse)(
            release_obj_json("nightly").as_bytes(),
            &crate::http_client::HeaderMap::new(),
        );
        match res {
            Err(crate::errors::Error::SemVer(e)) => {
                assert!(
                    e.to_string().contains("nightly"),
                    "the error must name the offending tag, got: {e}"
                );
            }
            Err(other) => panic!("expected Error::SemVer, got {other:?}"),
            Ok(_) => panic!("a non-semver pinned tag must error"),
        }
    }

    use std::io::{Read, Write};
    use std::net::TcpListener;

    struct Resp {
        status: &'static str,
        link: Option<String>,
        body: String,
    }

    /// Bind a loopback listener and serve `make(base_url)`'s responses in order, one per
    /// incoming connection, on a background thread. Returns the server's base URL
    /// (`http://127.0.0.1:<port>`). No external network is used.
    fn stub(make: impl FnOnce(&str) -> Vec<Resp>) -> String {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let responses = make(&base);
        std::thread::spawn(move || {
            for r in responses {
                let (mut stream, _) = match listener.accept() {
                    Ok(c) => c,
                    Err(_) => return,
                };
                let mut buf = [0u8; 4096];
                let _ = stream.read(&mut buf); // drain the request line/headers
                let mut out = format!(
                    "HTTP/1.1 {}\r\nContent-Type: application/json\r\n",
                    r.status
                );
                if let Some(link) = r.link {
                    out.push_str(&format!("Link: <{link}>; rel=\"next\"\r\n"));
                }
                out.push_str(&format!(
                    "Content-Length: {}\r\nConnection: close\r\n\r\n{}",
                    r.body.len(),
                    r.body
                ));
                let _ = stream.write_all(out.as_bytes());
                let _ = stream.flush();
            }
        });
        base
    }

    /// A JSON array of one release (used by the async pagination tests).
    #[cfg(feature = "async")]
    fn release_json(tag: &str) -> String {
        format!(
            r#"[{{"tag_name":"{tag}","created_at":"2020-01-01T00:00:00Z","name":"{tag}","assets":[],"body":null}}]"#
        )
    }

    /// A JSON array of several releases (one object per `tag`), used by the listing-based tests.
    fn releases_json(tags: &[&str]) -> String {
        let objs = tags
            .iter()
            .map(|tag| {
                format!(
                    r#"{{"tag_name":"{tag}","created_at":"2020-01-01T00:00:00Z","name":"{tag}","assets":[],"body":null}}"#
                )
            })
            .collect::<Vec<_>>()
            .join(",");
        format!("[{objs}]")
    }

    /// A bare JSON release object (not wrapped in an array). Gitee's `get_release_version[_async]`
    /// hits `/tags/{ver}` and `get_latest_release[_async]` hits `/releases/latest`, both of which
    /// return a single release object, so this is parsed directly.
    fn release_obj_json(tag: &str) -> String {
        format!(
            r#"{{"tag_name":"{tag}","created_at":"2020-01-01T00:00:00Z","name":"{tag}","assets":[],"body":null}}"#
        )
    }

    #[cfg(feature = "async")]
    fn gitee_update(base: &str, current_version: &str) -> super::AsyncUpdate {
        Update::configure()
            .host(base)
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version(current_version)
            .build_async()
            .unwrap()
    }

    /// Build a `ReleaseUpdate` (sync) gitee `Update` pointed at the loopback stub.
    fn gitee_update_sync(base: &str, current_version: &str) -> Update {
        Update::configure()
            .host(base)
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version(current_version)
            .build()
            .unwrap()
    }

    // --- Default host ------------------------------------------------------------------------

    #[test]
    fn update_defaults_host_to_gitee_com() {
        // Unlike gitea, gitee's host is optional and defaults to gitee.com; the releases URL and
        // the latest URL must be built against it.
        let upd = Update::configure()
            .repo_owner("owner")
            .repo_name("repo")
            .bin_name("app")
            .current_version("0.1.0")
            .build()
            .unwrap();
        assert_eq!(
            upd.releases_url(),
            "https://gitee.com/api/v5/repos/owner/repo/releases"
        );
        assert_eq!(
            upd.latest_url(),
            "https://gitee.com/api/v5/repos/owner/repo/releases/latest"
        );
    }

    #[test]
    fn release_list_defaults_host_to_gitee_com() {
        // The ReleaseList builder also defaults the host: build() must succeed without a host.
        let _list = super::ReleaseList::configure()
            .repo_owner("o")
            .repo_name("r")
            .build()
            .unwrap();
    }

    #[test]
    fn host_setter_overrides_default_for_enterprise() {
        let upd = Update::configure()
            .host("https://gitee.example.com")
            .repo_owner("owner")
            .repo_name("repo")
            .bin_name("app")
            .current_version("0.1.0")
            .build()
            .unwrap();
        assert_eq!(
            upd.releases_url(),
            "https://gitee.example.com/api/v5/repos/owner/repo/releases"
        );
    }

    // --- Sync `Releases`-returning fetch coverage -------------------------------------------

    #[test]
    fn get_latest_release_sync_wraps_newest_into_one_element_releases() {
        // `get_latest_release` fetches the dedicated `/releases/latest` object and wraps it in a
        // one-element `Releases` carrying the configured current version.
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: release_obj_json("v2.5.0"),
            }]
        });
        let upd = gitee_update_sync(&base, "1.0.0");
        let releases = upd.get_latest_release().unwrap();
        assert_eq!(
            releases.all().len(),
            1,
            "get_latest_release yields a one-element Releases"
        );
        assert_eq!(releases.latest().unwrap().version(), "2.5.0");
        assert!(
            releases.is_update_available().unwrap(),
            "2.5.0 > 1.0.0 via the one-element Releases pre-check"
        );
    }

    #[test]
    fn get_latest_release_routes_to_latest_endpoint() {
        // The first (and only) request for the semver-latest path must hit `/releases/latest`.
        let (base, captured) = stub_capturing(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: release_obj_json("v2.5.0"),
            }]
        });
        let upd = gitee_update_sync(&base, "1.0.0");
        upd.get_latest_release().unwrap();
        let reqs = captured.lock().unwrap();
        assert_eq!(reqs.len(), 1, "a semver latest needs exactly one request");
        let line = reqs[0].lines().next().unwrap_or("");
        assert!(
            line.contains("/api/v5/repos/o/r/releases/latest"),
            "the latest path must hit /releases/latest, got: {line}"
        );
    }

    #[test]
    fn get_latest_release_falls_back_to_listing_when_latest_is_non_semver() {
        // `/releases/latest` returns a non-semver rolling tag; the updater must then scan the
        // listing and pick the newest comparable release. Two requests are made: /releases/latest
        // then the listing (with the ?per_page=100 first page).
        let (base, captured) = stub_capturing(|_| {
            vec![
                Resp {
                    status: "200 OK",
                    link: None,
                    body: release_obj_json("nightly"),
                },
                Resp {
                    status: "200 OK",
                    link: None,
                    body: releases_json(&["v1.2.3", "v1.0.0"]),
                },
            ]
        });
        let upd = gitee_update_sync(&base, "0.1.0");
        let releases = upd.get_latest_release().unwrap();
        assert_eq!(
            releases.latest().unwrap().version(),
            "1.2.3",
            "the non-semver latest falls back to the newest comparable listing release"
        );
        let reqs = captured.lock().unwrap();
        assert_eq!(reqs.len(), 2, "fallback fetches /latest then the listing");
        assert!(
            reqs[0]
                .lines()
                .next()
                .unwrap_or("")
                .contains("/releases/latest"),
            "first request must be /releases/latest"
        );
        let second = reqs[1].lines().next().unwrap_or("");
        assert!(
            second.contains("/api/v5/repos/o/r/releases?per_page=100"),
            "second request must be the listing first page, got: {second}"
        );
    }

    #[test]
    fn get_latest_release_empty_listing_fallback_is_no_release_found() {
        // Non-semver latest, then an empty listing array: NoReleaseFound { target: None }.
        let base = stub(|_| {
            vec![
                Resp {
                    status: "200 OK",
                    link: None,
                    body: release_obj_json("nightly"),
                },
                Resp {
                    status: "200 OK",
                    link: None,
                    body: "[]".to_string(),
                },
            ]
        });
        let upd = gitee_update_sync(&base, "0.1.0");
        match upd.get_latest_release() {
            Err(crate::errors::Error::NoReleaseFound { target }) => {
                assert_eq!(target, None, "empty listing carries no asset target");
            }
            other => panic!(
                "empty fallback listing must be NoReleaseFound {{ target: None }}, got {:?}",
                other
            ),
        }
    }

    #[test]
    fn get_latest_release_non_array_listing_fallback_is_invalid_response() {
        // Non-semver latest, then a non-array `{}` listing body: InvalidResponse.
        let base = stub(|_| {
            vec![
                Resp {
                    status: "200 OK",
                    link: None,
                    body: release_obj_json("nightly"),
                },
                Resp {
                    status: "200 OK",
                    link: None,
                    body: "{}".to_string(),
                },
            ]
        });
        let upd = gitee_update_sync(&base, "0.1.0");
        match upd.get_latest_release() {
            Err(crate::errors::Error::InvalidResponse { .. }) => {}
            other => panic!(
                "a non-array fallback listing must be InvalidResponse, got {:?}",
                other
            ),
        }
    }

    #[test]
    fn get_latest_release_missing_tag_name_is_missing_asset_field() {
        // `/releases/latest` object missing `tag_name` must surface as EXACTLY
        // `MissingAssetField { field: "tag_name" }`.
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: r#"{"created_at":"2020-01-01T00:00:00Z","name":"x","assets":[]}"#.to_string(),
            }]
        });
        let upd = gitee_update_sync(&base, "0.1.0");
        match upd.get_latest_release() {
            Err(crate::errors::Error::MissingAssetField { field }) => {
                assert_eq!(field, "tag_name", "must name the absent field exactly");
            }
            other => panic!(
                "missing tag_name must be MissingAssetField {{ field: \"tag_name\" }}, got {:?}",
                other
            ),
        }
    }

    #[test]
    fn get_newer_releases_sync_returns_releases_and_filters_to_newer() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: releases_json(&["v2.0.0", "v1.5.0", "v1.0.0", "v0.9.0"]),
            }]
        });
        let upd = gitee_update_sync(&base, "1.0.0");
        let releases = upd.get_newer_releases().unwrap();
        let versions: Vec<&str> = releases.all().iter().map(|r| r.version()).collect();
        assert_eq!(
            versions,
            vec!["2.0.0", "1.5.0"],
            "only releases strictly newer than the current version are kept, in order"
        );
        assert_eq!(releases.latest().unwrap().version(), "2.0.0");
        assert!(releases.is_update_available().unwrap());
    }

    #[test]
    fn get_newer_releases_sync_reports_no_update_when_up_to_date() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: releases_json(&["v1.0.0", "v0.9.0"]),
            }]
        });
        let upd = gitee_update_sync(&base, "1.0.0");
        let releases = upd.get_newer_releases().unwrap();
        assert!(releases.all().is_empty(), "no newer release => empty list");
        assert!(
            !releases.is_update_available().unwrap(),
            "empty list => no update available"
        );
    }

    #[test]
    fn get_newer_releases_sync_empty_array_returns_empty() {
        // An empty listing array on the paginated path is not an error: the filtered result is
        // simply empty (distinct from `get_latest_release`, which errors on nothing to return).
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: "[]".to_string(),
            }]
        });
        let upd = gitee_update_sync(&base, "0.1.0");
        let releases = upd.get_newer_releases().unwrap();
        assert!(releases.all().is_empty());
    }

    #[test]
    fn get_newer_releases_sync_non_array_is_invalid_response() {
        // A top-level `{}` object cannot be deserialized as `Vec<ReleaseDto>` on the listing path.
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: "{}".to_string(),
            }]
        });
        let upd = gitee_update_sync(&base, "0.1.0");
        match upd.get_newer_releases() {
            Err(crate::errors::Error::InvalidResponse { .. }) => {}
            other => panic!(
                "a non-array listing must be Error::InvalidResponse, got {:?}",
                other
            ),
        }
    }

    /// Like [`stub`], but also captures each incoming raw request so tests can assert on what the
    /// client actually sent (e.g. which path was requested, and which headers).
    fn stub_capturing(
        make: impl FnOnce(&str) -> Vec<Resp>,
    ) -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let base = format!("http://{}", listener.local_addr().unwrap());
        let responses = make(&base);
        let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
        let sink = captured.clone();
        std::thread::spawn(move || {
            for r in responses {
                let (mut stream, _) = match listener.accept() {
                    Ok(c) => c,
                    Err(_) => return,
                };
                let mut buf = [0u8; 4096];
                let n = stream.read(&mut buf).unwrap_or(0);
                sink.lock()
                    .unwrap()
                    .push(String::from_utf8_lossy(&buf[..n]).into_owned());
                let mut out = format!(
                    "HTTP/1.1 {}\r\nContent-Type: application/json\r\n",
                    r.status
                );
                if let Some(link) = r.link {
                    out.push_str(&format!("Link: <{link}>; rel=\"next\"\r\n"));
                }
                out.push_str(&format!(
                    "Content-Length: {}\r\nConnection: close\r\n\r\n{}",
                    r.body.len(),
                    r.body
                ));
                let _ = stream.write_all(out.as_bytes());
                let _ = stream.flush();
            }
        });
        (base, captured)
    }

    #[test]
    fn get_newer_releases_continues_past_non_newer_releases_and_fetches_page_two() {
        // Non-newer releases must NOT halt pagination -- page 2 must be fetched and its newer
        // release returned alongside the newer items from page 1.
        let (base, captured) = stub_capturing(|base| {
            vec![
                Resp {
                    status: "200 OK",
                    link: Some(format!("{base}/api/v5/repos/o/r/releases?page=2")),
                    body: releases_json(&["v2.0.0", "v1.5.0", "v1.0.0", "v0.9.0"]),
                },
                Resp {
                    status: "200 OK",
                    link: None,
                    body: releases_json(&["v3.0.0"]),
                },
            ]
        });
        let upd = gitee_update_sync(&base, "1.0.0");
        let releases = upd.get_newer_releases().unwrap();
        let versions: Vec<&str> = releases.all().iter().map(|r| r.version()).collect();
        assert_eq!(versions, vec!["2.0.0", "1.5.0", "3.0.0"]);
        assert_eq!(
            captured.lock().unwrap().len(),
            2,
            "non-newer releases must not halt pagination; both pages must be requested"
        );
    }

    #[test]
    fn release_list_fetch_walks_all_pages_unfiltered() {
        // `ReleaseList::fetch` is an UNFILTERED listing (stop_at = None) and must walk ALL pages,
        // accumulating even releases older than any current version.
        let (base, captured) = stub_capturing(|base| {
            vec![
                Resp {
                    status: "200 OK",
                    link: Some(format!("{base}/api/v5/repos/o/r/releases?page=2")),
                    body: releases_json(&["v2.0.0", "v0.5.0"]),
                },
                Resp {
                    status: "200 OK",
                    link: None,
                    body: releases_json(&["v0.1.0"]),
                },
            ]
        });
        let releases = super::ReleaseList::configure()
            .host(&base)
            .repo_owner("o")
            .repo_name("r")
            .build()
            .unwrap()
            .fetch()
            .unwrap()
            .into_vec();
        let versions: Vec<&str> = releases.iter().map(|r| r.version()).collect();
        assert_eq!(
            versions,
            vec!["2.0.0", "0.5.0", "0.1.0"],
            "the unfiltered ReleaseList must accumulate ALL pages, older releases included"
        );
        assert_eq!(
            captured.lock().unwrap().len(),
            2,
            "both pages must be requested for the unfiltered listing"
        );
    }

    // A realistic populated payload parses through the DTO into a `Release` whose getters surface
    // every field (via the `/releases/latest` single object).
    #[test]
    fn dto_parse_maps_populated_payload_through_getters() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: r#"{"tag_name":"v3.4.5","created_at":"2021-07-08T09:10:11Z","name":"My App 3.4.5","html_url":"https://gitee.com/o/r/releases/v3.4.5","body":"the notes","assets":[{"name":"app-x86_64-linux.tar.gz","browser_download_url":"https://gitee.example/app-x86_64-linux.tar.gz"},{"name":"app-aarch64-linux.tar.gz","browser_download_url":"https://gitee.example/app-aarch64-linux.tar.gz"}]}"#
                    .to_string(),
            }]
        });
        let upd = gitee_update_sync(&base, "0.1.0");
        let releases = upd.get_latest_release().unwrap();
        let rel = releases.latest().unwrap();
        assert_eq!(rel.version(), "3.4.5", "leading `v` stripped from tag_name");
        assert_eq!(rel.name(), "My App 3.4.5", "name surfaces from `name`");
        assert_eq!(rel.date(), "2021-07-08T09:10:11Z", "date from `created_at`");
        assert_eq!(
            rel.body(),
            Some("the notes"),
            "body surfaces from gitee's `body` field"
        );
        assert_eq!(
            rel.release_notes_url(),
            Some("https://gitee.com/o/r/releases/v3.4.5"),
            "release notes URL surfaces from `html_url`"
        );
        assert_eq!(rel.assets().len(), 2, "both `assets` entries parsed");
        assert_eq!(rel.assets()[0].name(), "app-x86_64-linux.tar.gz");
        assert_eq!(
            rel.assets()[0].download_url(),
            "https://gitee.example/app-x86_64-linux.tar.gz",
            "asset download_url comes from `browser_download_url`"
        );
        assert_eq!(rel.assets()[1].name(), "app-aarch64-linux.tar.gz");
    }

    // THE core gitee divergence: gitee's auto-generated source archive appears in `assets` WITHOUT
    // a `name` (and often without a `browser_download_url`). Those nameless / URL-less assets must
    // be SKIPPED (debug-logged), not error the whole release; named downloadable assets survive.
    #[test]
    fn nameless_source_zip_skipped_named_assets_survive() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: concat!(
                    r#"{"tag_name":"v1.2.3","created_at":"2020-01-01T00:00:00Z","name":"v1.2.3","assets":["#,
                    // gitee's auto-generated source zip: no `name` (has a url) -> skipped.
                    r#"{"browser_download_url":"https://gitee.com/o/r/repository/archive/v1.2.3.zip"},"#,
                    // a source archive with a name but NO download url -> also skipped.
                    r#"{"name":"v1.2.3.tar.gz"},"#,
                    // a real, named, downloadable binary -> survives.
                    r#"{"name":"app-x86_64-linux.tar.gz","browser_download_url":"https://gitee.com/o/r/attach_files/app-x86_64-linux.tar.gz"}"#,
                    r#"]}"#
                )
                .to_string(),
            }]
        });
        let upd = gitee_update_sync(&base, "0.1.0");
        let releases = upd.get_latest_release().unwrap();
        let rel = releases.latest().unwrap();
        assert_eq!(
            rel.assets().len(),
            1,
            "the nameless and the URL-less assets are skipped; only the named binary survives"
        );
        assert_eq!(rel.assets()[0].name(), "app-x86_64-linux.tar.gz");
        assert_eq!(
            rel.assets()[0].download_url(),
            "https://gitee.com/o/r/attach_files/app-x86_64-linux.tar.gz"
        );
    }

    // The listing `Releases` from `ReleaseList::fetch` carries NO current version, so
    // `current_version()` is `None` and `is_update_available()` errors with EXACTLY
    // `NoCurrentVersion`. `into_vec()` recovers the release vec.
    #[test]
    fn release_list_fetch_returns_listing_releases_without_current_version() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: releases_json(&["v2.0.0", "v1.0.0"]),
            }]
        });
        let releases = super::ReleaseList::configure()
            .host(&base)
            .repo_owner("o")
            .repo_name("r")
            .build()
            .unwrap()
            .fetch()
            .unwrap();
        assert_eq!(
            releases.current_version(),
            None,
            "a bare listing carries no current version"
        );
        assert!(
            matches!(
                releases.is_update_available(),
                Err(crate::errors::Error::NoCurrentVersion)
            ),
            "is_update_available() on a listing must error with NoCurrentVersion, got {:?}",
            releases.is_update_available()
        );
        let versions: Vec<String> = releases
            .into_vec()
            .into_iter()
            .map(|r| r.version().to_string())
            .collect();
        assert_eq!(versions, vec!["2.0.0", "1.0.0"]);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn release_list_fetch_async_returns_listing_releases_without_current_version() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: releases_json(&["v2.0.0", "v1.0.0"]),
            }]
        });
        let releases = super::ReleaseList::configure()
            .host(&base)
            .repo_owner("o")
            .repo_name("r")
            .build()
            .unwrap()
            .fetch_async()
            .await
            .unwrap();
        assert_eq!(releases.current_version(), None);
        assert!(matches!(
            releases.is_update_available(),
            Err(crate::errors::Error::NoCurrentVersion)
        ));
        let versions: Vec<String> = releases
            .into_vec()
            .into_iter()
            .map(|r| r.version().to_string())
            .collect();
        assert_eq!(versions, vec!["2.0.0", "1.0.0"]);
    }

    #[test]
    fn filter_target_drops_releases_without_matching_asset() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: concat!(
                    r#"[{"tag_name":"v2.0.0","created_at":"2020-01-01T00:00:00Z","name":"v2.0.0","assets":[{"name":"app-x86_64-linux.tar.gz","browser_download_url":"https://example.com/2.0.0"}]},"#,
                    r#"{"tag_name":"v1.0.0","created_at":"2019-01-01T00:00:00Z","name":"v1.0.0","assets":[{"name":"app-windows.zip","browser_download_url":"https://example.com/1.0.0"}]}]"#
                )
                .to_string(),
            }]
        });
        let releases = super::ReleaseList::configure()
            .host(&base)
            .repo_owner("o")
            .repo_name("r")
            .filter_target("x86_64-linux")
            .build()
            .unwrap()
            .fetch()
            .unwrap()
            .into_vec();
        assert_eq!(releases.len(), 1);
        assert_eq!(releases[0].version(), "2.0.0");
    }

    #[test]
    fn build_requires_repo_owner_and_name() {
        let missing_owner = Update::configure()
            .repo_name("repo")
            .current_version("0.1.0")
            .build();
        assert!(missing_owner.is_err(), "build must fail without repo_owner");

        let missing_name = Update::configure()
            .repo_owner("owner")
            .current_version("0.1.0")
            .build();
        assert!(missing_name.is_err(), "build must fail without repo_name");
    }

    #[test]
    fn release_list_build_requires_repo_owner_and_repo_name() {
        let res = super::ReleaseList::configure().repo_name("r").build();
        assert!(
            matches!(
                res,
                Err(crate::errors::Error::MissingField {
                    field: "repo_owner"
                })
            ),
            "missing repo_owner must surface as MissingField, got {:?}",
            res
        );
        let res = super::ReleaseList::configure().repo_owner("o").build();
        assert!(
            matches!(
                res,
                Err(crate::errors::Error::MissingField { field: "repo_name" })
            ),
            "missing repo_name must surface as MissingField, got {:?}",
            res
        );
    }

    #[test]
    fn releases_url_encodes_owner_and_name() {
        let upd = Update::configure()
            .host("https://gitee.example.com")
            .repo_owner("my owner")
            .repo_name("my repo")
            .bin_name("app")
            .current_version("0.1.0")
            .build_update()
            .unwrap();
        assert_eq!(
            upd.releases_url(),
            "https://gitee.example.com/api/v5/repos/my%20owner/my%20repo/releases",
            "repo_owner and repo_name must be percent-encoded in the releases URL"
        );
    }

    #[test]
    fn release_list_fetch_encodes_owner_and_name_in_request_path() {
        let (base, captured) = stub_capturing(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: releases_json(&["v1.0.0"]),
            }]
        });
        super::ReleaseList::configure()
            .host(&base)
            .repo_owner("my owner")
            .repo_name("my repo")
            .build()
            .unwrap()
            .fetch()
            .unwrap();
        let reqs = captured.lock().unwrap();
        assert_eq!(reqs.len(), 1);
        let request_line = reqs[0].lines().next().unwrap_or("");
        assert!(
            request_line.contains("/api/v5/repos/my%20owner/my%20repo/releases"),
            "owner and name must be percent-encoded in the request path; got: {request_line}"
        );
    }

    #[test]
    fn release_list_build_surfaces_invalid_header() {
        let res = super::ReleaseList::configure()
            .repo_owner("o")
            .repo_name("r")
            .request_header("inva lid", "ok")
            .build();
        assert!(matches!(
            res,
            Err(crate::errors::Error::InvalidHeader { .. })
        ));
    }

    #[test]
    fn update_build_surfaces_invalid_header() {
        let res = Update::configure()
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .request_header("inva lid", "ok")
            .build();
        assert!(matches!(
            res,
            Err(crate::errors::Error::InvalidHeader { .. })
        ));
    }

    #[test]
    fn identifier_is_wired() {
        let upd = Update::configure()
            .repo_owner("owner")
            .repo_name("repo")
            .bin_name("app")
            .current_version("0.1.0")
            .asset_identifier("musl")
            .build()
            .unwrap();
        assert_eq!(upd.asset_identifier(), Some("musl"));
    }

    #[test]
    fn api_headers_override_uses_gitee_user_agent() {
        // The `{api_headers}` override arm must wire gitee's custom `api_headers` (User-Agent), not
        // the trait default. The auth scheme/token is applied centrally by `apply_auth`.
        let upd = Update::configure()
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .build()
            .unwrap();
        let headers = upd.api_headers(Some("secret")).unwrap();
        assert_eq!(
            headers
                .get(crate::http_client::header::USER_AGENT)
                .unwrap()
                .to_str()
                .unwrap(),
            crate::DEFAULT_USER_AGENT
        );
        assert!(
            headers
                .get(crate::http_client::header::AUTHORIZATION)
                .is_none(),
            "api_headers no longer bakes auth; apply_auth applies the Bearer scheme"
        );
    }

    // --- AUTH: Bearer scheme, both paths, override, no-leak -----------------------------------

    // gitee resolves to the `Bearer` scheme, applied by the shared `apply_auth` on the request
    // config consumed by BOTH the listing and download paths. A user override wins. The applied
    // Authorization header value is marked sensitive so it never renders in Debug output or logs.
    #[test]
    fn gitee_bearer_scheme_applied_to_both_paths() {
        use crate::http_client::header::{AUTHORIZATION, HeaderMap};
        #[allow(unused_imports)]
        use crate::update::UpdateInternals;
        let upd = Update::configure()
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .auth_token("secret")
            .build()
            .unwrap();

        // Listing path host (gitee.com api).
        let mut headers = HeaderMap::new();
        upd.request_config()
            .apply_auth("https://gitee.com/api/v5/repos/o/r/releases", &mut headers)
            .unwrap();
        let value = headers.get(AUTHORIZATION).unwrap();
        assert_eq!(
            value.to_str().unwrap(),
            "Bearer secret",
            "gitee authenticates with the Bearer scheme"
        );
        assert!(
            value.is_sensitive(),
            "the applied Authorization value must be marked sensitive so it is kept out of logs"
        );

        // Download path (an attachment URL on the same gitee host) also receives the token.
        let mut dl_headers = HeaderMap::new();
        upd.request_config()
            .apply_auth(
                "https://gitee.com/o/r/attach_files/app.tar.gz",
                &mut dl_headers,
            )
            .unwrap();
        assert_eq!(
            dl_headers.get(AUTHORIZATION).unwrap().to_str().unwrap(),
            "Bearer secret",
            "the download path on the gitee host also receives the Bearer token"
        );

        // A user AUTHORIZATION override wins.
        let upd = Update::configure()
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .auth_token("secret")
            .request_header(AUTHORIZATION, "Bearer user-override")
            .build()
            .unwrap();
        let mut headers = upd.request_config().headers.clone();
        upd.request_config()
            .apply_auth("https://gitee.com/api/v5/repos/o/r/releases", &mut headers)
            .unwrap();
        assert_eq!(
            headers.get(AUTHORIZATION).unwrap().to_str().unwrap(),
            "Bearer user-override",
            "a user AUTHORIZATION override must win over the Bearer scheme"
        );
    }

    #[test]
    fn release_list_auth_token_transmitted_as_bearer() {
        // End-to-end: `ReleaseListBuilder::auth_token` must cause `Authorization: Bearer <secret>`
        // to appear in the actual HTTP request, and the token must NOT leak into the request line
        // (URL).
        let (base, captured) = stub_capturing(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: releases_json(&["v1.0.0"]),
            }]
        });
        super::ReleaseList::configure()
            .host(&base)
            .repo_owner("o")
            .repo_name("r")
            .auth_token("secret")
            .build()
            .unwrap()
            .fetch()
            .unwrap();
        let reqs = captured.lock().unwrap();
        assert_eq!(reqs.len(), 1, "exactly one request must be made");
        let auth_header = reqs[0]
            .lines()
            .find(|l| l.to_lowercase().starts_with("authorization:"));
        assert!(
            auth_header.is_some_and(|l| l.contains("Bearer secret")),
            "ReleaseList::fetch must transmit `Authorization: Bearer secret`, got header: {:?}",
            auth_header
        );
        let request_line = reqs[0].lines().next().unwrap_or("");
        assert!(
            !request_line.contains("secret"),
            "the token must never appear in the request URL/line, got: {request_line}"
        );
    }

    #[test]
    fn get_latest_release_sync_transmits_bearer_token_and_never_in_url() {
        let (base, captured) = stub_capturing(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: release_obj_json("v2.0.0"),
            }]
        });
        let upd = Update::configure()
            .host(&base)
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("1.0.0")
            .auth_token("mytoken")
            .build()
            .unwrap();
        upd.get_latest_release().unwrap();
        let reqs = captured.lock().unwrap();
        assert_eq!(reqs.len(), 1, "exactly one request for get_latest_release");
        let auth_header = reqs[0]
            .lines()
            .find(|l| l.to_lowercase().starts_with("authorization:"));
        assert!(
            auth_header.is_some_and(|l| l.contains("Bearer mytoken")),
            "get_latest_release must transmit `Authorization: Bearer mytoken`, got: {:?}",
            auth_header
        );
        let request_line = reqs[0].lines().next().unwrap_or("");
        assert!(
            !request_line.contains("mytoken"),
            "the token must never appear in the request URL/line, got: {request_line}"
        );
    }

    #[test]
    fn auth_token_never_appears_in_debug_or_error_display() {
        // The token must not leak into the built updater's Debug output (RequestConfig renders it
        // as `<token>`), nor into any error Display produced while a token is configured.
        let upd = Update::configure()
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .auth_token("supersecret")
            .build()
            .unwrap();
        let debug = format!("{:?}", upd);
        assert!(
            !debug.contains("supersecret"),
            "the auth token must not appear in the Update Debug output: {debug}"
        );

        // An error surfaced from a request path (e.g. a non-semver pinned tag) must not carry the
        // token in its Display.
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: release_obj_json("nightly"),
            }]
        });
        let upd = Update::configure()
            .host(&base)
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .auth_token("supersecret")
            .build()
            .unwrap();
        let err = upd
            .get_release_version("nightly")
            .expect_err("a non-semver pinned tag must error");
        assert!(
            !format!("{err}").contains("supersecret"),
            "the auth token must not appear in an error Display: {err}"
        );
    }

    // --- latest-vs-current comparison (outside-in) -------------------------------------------

    // The `/releases/latest` object can carry a semver tag OLDER than the configured current
    // version (e.g. the maintainer re-pinned an old release, or current is a pre-release ahead of
    // the last published tag). `get_latest_release` must still succeed (it reports what the server
    // says is latest) and the one-element `Releases` pre-check must report NO update available.
    #[test]
    fn get_latest_release_older_semver_reports_no_update() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: release_obj_json("v0.5.0"),
            }]
        });
        let upd = gitee_update_sync(&base, "1.0.0");
        let releases = upd.get_latest_release().unwrap();
        assert_eq!(
            releases.latest().unwrap().version(),
            "0.5.0",
            "get_latest_release surfaces whatever /releases/latest reports, even if older"
        );
        assert!(
            !releases.is_update_available().unwrap(),
            "0.5.0 < 1.0.0 => no update available (no panic, no confusing error)"
        );
    }

    // A `/releases/latest` semver tag EQUAL to the current version is not an update.
    #[test]
    fn get_latest_release_equal_semver_reports_no_update() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: release_obj_json("v1.0.0"),
            }]
        });
        let upd = gitee_update_sync(&base, "1.0.0");
        let releases = upd.get_latest_release().unwrap();
        assert_eq!(releases.latest().unwrap().version(), "1.0.0");
        assert!(
            !releases.is_update_available().unwrap(),
            "latest == current => no update available"
        );
    }

    // --- all-assets-skipped leniency (outside-in) --------------------------------------------

    // The lenient asset strategy can drop EVERY asset when a release carries only the nameless
    // source archive and a URL-less entry. The release must still parse (that is the deliberate
    // divergence), yielding an EMPTY asset list rather than an error -- and downstream target
    // selection over that release must report "no match" sanely (never panic).
    #[test]
    fn get_latest_release_all_assets_skipped_yields_empty_asset_list() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: concat!(
                    r#"{"tag_name":"v1.2.3","created_at":"2020-01-01T00:00:00Z","name":"v1.2.3","assets":["#,
                    // nameless source zip (has a url) -> skipped
                    r#"{"browser_download_url":"https://gitee.com/o/r/repository/archive/v1.2.3.zip"},"#,
                    // named but no url -> skipped
                    r#"{"name":"v1.2.3.tar.gz"}"#,
                    r#"]}"#
                )
                .to_string(),
            }]
        });
        let upd = gitee_update_sync(&base, "0.1.0");
        let releases = upd.get_latest_release().unwrap();
        let rel = releases.latest().unwrap();
        assert!(
            rel.assets().is_empty(),
            "every asset was lenient-skipped; the release parses with an empty asset list"
        );
        assert!(
            !rel.has_target_asset("x86_64-linux"),
            "target selection over an asset-less release reports no match, not a panic"
        );
    }

    // Downstream: an asset-less (all-skipped) release is dropped by a `filter_target` listing,
    // so the user gets an empty listing rather than a release that cannot be downloaded.
    #[test]
    fn filter_target_drops_release_whose_assets_all_skipped() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: concat!(
                    r#"[{"tag_name":"v2.0.0","created_at":"2020-01-01T00:00:00Z","name":"v2.0.0","assets":["#,
                    r#"{"browser_download_url":"https://gitee.com/o/r/repository/archive/v2.0.0.zip"}"#,
                    r#"]}]"#
                )
                .to_string(),
            }]
        });
        let releases = super::ReleaseList::configure()
            .host(&base)
            .repo_owner("o")
            .repo_name("r")
            .filter_target("x86_64-linux")
            .build()
            .unwrap()
            .fetch()
            .unwrap()
            .into_vec();
        assert!(
            releases.is_empty(),
            "a release whose only assets are lenient-skipped matches no target and is dropped"
        );
    }

    // --- tag_prefix x /releases/latest interaction (outside-in) -------------------------------

    // `/releases/latest` returns a prefixed tag (`myapp-2.0.0`); with `tag_prefix("myapp-")` the
    // backend must strip the prefix on the dedicated latest endpoint too (not only in the listing),
    // yielding version `2.0.0`.
    #[test]
    fn get_latest_release_strips_tag_prefix_on_latest_endpoint() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: release_obj_json("myapp-2.0.0"),
            }]
        });
        let upd = Update::configure()
            .host(&base)
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .tag_prefix("myapp-")
            .build()
            .unwrap();
        let releases = upd.get_latest_release().unwrap();
        assert_eq!(
            releases.latest().unwrap().version(),
            "2.0.0",
            "the configured tag_prefix is stripped from the /releases/latest tag"
        );
    }

    // A `/releases/latest` tag that does NOT carry the configured prefix is a prefix mismatch,
    // which the backend maps to `Error::SemVer` -- the same skippable class as a rolling tag -- so
    // it must trigger the LISTING FALLBACK (not surface as a hard error). The fallback then picks
    // the newest prefixed release it can compare.
    #[test]
    fn get_latest_release_prefix_mismatch_falls_back_to_listing() {
        let (base, captured) = stub_capturing(|_| {
            vec![
                Resp {
                    status: "200 OK",
                    link: None,
                    // no `myapp-` prefix -> mismatch -> SemVer -> fallback
                    body: release_obj_json("2.0.0"),
                },
                Resp {
                    status: "200 OK",
                    link: None,
                    body: releases_json(&["otherapp-9.9.9", "myapp-1.5.0", "myapp-1.0.0"]),
                },
            ]
        });
        let upd = Update::configure()
            .host(&base)
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .tag_prefix("myapp-")
            .build()
            .unwrap();
        let releases = upd.get_latest_release().unwrap();
        assert_eq!(
            releases.latest().unwrap().version(),
            "1.5.0",
            "prefix-mismatched latest falls back to the newest prefixed listing release"
        );
        assert_eq!(
            captured.lock().unwrap().len(),
            2,
            "prefix mismatch must fetch /releases/latest then the listing"
        );
    }

    // --- host formatting (characterization, parity with gitea) -------------------------------

    // The host setter is documented as "scheme + host, no trailing slash"; the crate does NOT
    // normalize a stray trailing slash (parity with gitea, which pins nothing here). Pin the
    // current behavior so an accidental change to host handling is caught.
    #[test]
    fn host_trailing_slash_is_not_normalized() {
        let upd = Update::configure()
            .host("https://gitee.example.com/")
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .build()
            .unwrap();
        assert_eq!(
            upd.releases_url(),
            "https://gitee.example.com//api/v5/repos/o/r/releases",
            "a trailing slash is not stripped (documented: pass host without one)"
        );
    }

    // An enterprise host mounted under a path prefix is preserved verbatim in the built URL, and
    // auth host-gating still resolves the bare host so the Bearer token is attached to that host.
    #[test]
    fn enterprise_host_with_path_prefix_is_preserved_and_auth_gated() {
        use crate::http_client::header::{AUTHORIZATION, HeaderMap};
        #[allow(unused_imports)]
        use crate::update::UpdateInternals;
        let upd = Update::configure()
            .host("https://gitee.example.com/prefix")
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .auth_token("secret")
            .build()
            .unwrap();
        assert_eq!(
            upd.releases_url(),
            "https://gitee.example.com/prefix/api/v5/repos/o/r/releases",
            "a path-prefixed enterprise host is preserved in the URL"
        );
        let mut headers = HeaderMap::new();
        upd.request_config()
            .apply_auth(&upd.releases_url(), &mut headers)
            .unwrap();
        assert_eq!(
            headers.get(AUTHORIZATION).unwrap().to_str().unwrap(),
            "Bearer secret",
            "auth host-gating resolves the bare host and still attaches the token"
        );
    }

    // --- async coverage ----------------------------------------------------------------------

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn get_latest_release_async_parses_release() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: release_obj_json("v2.5.0"),
            }]
        });
        let upd = gitee_update(&base, "0.1.0");
        let releases = upd.get_latest_release_async().await.unwrap();
        assert_eq!(releases.latest().unwrap().version(), "2.5.0");
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn get_latest_release_async_falls_back_to_listing_when_non_semver() {
        let base = stub(|_| {
            vec![
                Resp {
                    status: "200 OK",
                    link: None,
                    body: release_obj_json("nightly"),
                },
                Resp {
                    status: "200 OK",
                    link: None,
                    body: releases_json(&["v1.2.3", "v1.0.0"]),
                },
            ]
        });
        let upd = gitee_update(&base, "0.1.0");
        let releases = upd.get_latest_release_async().await.unwrap();
        assert_eq!(releases.latest().unwrap().version(), "1.2.3");
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn fetch_all_releases_async_follows_link_pagination() {
        let base = stub(|base| {
            vec![
                Resp {
                    status: "200 OK",
                    link: Some(format!("{base}/api/v5/repos/o/r/releases?page=2")),
                    body: release_json("v1.0.0"),
                },
                Resp {
                    status: "200 OK",
                    link: None,
                    body: release_json("v0.9.0"),
                },
            ]
        });
        let releases = fetch_all_releases_async(
            &format!("{base}/api/v5/repos/o/r/releases"),
            &crate::backends::common::RequestConfig::default(),
        )
        .await
        .unwrap();
        assert_eq!(
            releases.len(),
            2,
            "both pages accumulated over async transport"
        );
        assert_eq!(releases[0].version(), "1.0.0");
        assert_eq!(releases[1].version(), "0.9.0");
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn get_release_version_async_parses_single_tag_object() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: release_obj_json("v4.2.1"),
            }]
        });
        let upd = gitee_update(&base, "0.1.0");
        let rel = upd.get_release_version_async("v4.2.1").await.unwrap();
        assert_eq!(rel.version(), "4.2.1");
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn get_release_version_async_missing_tag_name_is_missing_asset_field() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: r#"{"created_at":"2020-01-01T00:00:00Z","assets":[]}"#.to_string(),
            }]
        });
        let upd = gitee_update(&base, "0.1.0");
        match upd.get_release_version_async("v1.0.0").await {
            Err(crate::errors::Error::MissingAssetField { field }) => {
                assert_eq!(field, "tag_name", "must name the absent field exactly");
            }
            other => panic!(
                "missing tag_name must be MissingAssetField {{ field: \"tag_name\" }}, got {:?}",
                other
            ),
        }
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn get_newer_releases_async_filters_to_newer_only() {
        let base = stub(|_| {
            vec![Resp {
                status: "200 OK",
                link: None,
                body: releases_json(&["v2.0.0", "v1.5.0", "v1.0.0", "v0.9.0"]),
            }]
        });
        let upd = gitee_update(&base, "1.0.0");
        let releases = upd.get_newer_releases_async().await.unwrap();
        let versions: Vec<&str> = releases.all().iter().map(|r| r.version()).collect();
        assert_eq!(versions, vec!["2.0.0", "1.5.0"]);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn get_newer_releases_async_accumulates_across_pages_then_filters() {
        let base = stub(|base| {
            vec![
                Resp {
                    status: "200 OK",
                    link: Some(format!("{base}/api/v5/repos/o/r/releases?page=2")),
                    body: releases_json(&["v3.0.0"]),
                },
                Resp {
                    status: "200 OK",
                    link: None,
                    body: releases_json(&["v2.0.0"]),
                },
            ]
        });
        let upd = gitee_update(&base, "1.0.0");
        let releases = upd.get_newer_releases_async().await.unwrap();
        let versions: Vec<&str> = releases.all().iter().map(|r| r.version()).collect();
        assert_eq!(versions, vec!["3.0.0", "2.0.0"]);
    }

    #[cfg(feature = "async")]
    #[tokio::test]
    async fn get_latest_release_async_errors_on_non_array_fallback_payload() {
        // Non-semver latest, then a non-array listing body: InvalidResponse (async path).
        let base = stub(|_| {
            vec![
                Resp {
                    status: "200 OK",
                    link: None,
                    body: release_obj_json("nightly"),
                },
                Resp {
                    status: "200 OK",
                    link: None,
                    body: "{}".to_string(),
                },
            ]
        });
        let upd = gitee_update(&base, "0.1.0");
        let res = upd.get_latest_release_async().await;
        assert!(
            matches!(res, Err(crate::errors::Error::InvalidResponse { .. })),
            "non-array fallback payload must surface as InvalidResponse, got {:?}",
            res
        );
    }

    // Belt-and-suspenders: the async newtype's Debug output must not leak the auth token either
    // (its inner blocking `Update` renders the token as `<token>`).
    #[cfg(feature = "async")]
    #[test]
    fn async_update_debug_never_leaks_token() {
        let upd = Update::configure()
            .repo_owner("o")
            .repo_name("r")
            .bin_name("app")
            .current_version("0.1.0")
            .auth_token("supersecret")
            .build_async()
            .unwrap();
        let debug = format!("{upd:?}");
        assert!(
            !debug.contains("supersecret"),
            "the auth token must not appear in the AsyncUpdate Debug output: {debug}"
        );
    }
}