deps-core 1.0.0

Core abstractions for deps-lsp: caching, errors, and traits
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
use crate::error::{DepsError, Result};
use crate::parser::DependencySource;
use crate::{ConcreteVersion, PackageName, VersionReq};
use dashmap::DashMap;
use dashmap::mapref::entry::Entry;
use std::any::Any;
use std::hash::Hash;
use std::pin::Pin;

type BoxFuture<'a, T> = Pin<Box<dyn std::future::Future<Output = T> + Send + 'a>>;

/// Generic package registry interface.
///
/// Implementors provide access to a package registry (crates.io, npm, PyPI, etc.)
/// with version lookup, search, and metadata retrieval capabilities.
///
/// All methods return `Result<T>` to allow graceful error handling.
/// LSP handlers must never panic on registry errors.
///
/// # Type Erasure
///
/// This trait uses `Box<dyn Trait>` return types instead of associated types
/// to allow runtime polymorphism and dynamic ecosystem registration.
///
/// # Registry client API contract (#834)
///
/// Each ecosystem crate's own registry struct (`CratesIoRegistry`, `NpmRegistry`,
/// `MavenCentralRegistry`, ...) additionally exposes a set of **inherent** async methods
/// with concrete (non-boxed) parameter/return types — this trait's own methods box and
/// type-erase, which every hover/completion/diagnostic call site needs, but a caller that
/// already knows the concrete ecosystem (most ecosystem-crate-internal code, and every
/// conformance test) wants the unboxed value directly. The trait method of the same name is
/// expected to delegate to its inherent counterpart (see `deps-cargo::registry::CratesIoRegistry`
/// for the canonical shape). Naming previously drifted per crate (issue #760, #834); the
/// canonical vocabulary going forward is:
///
/// - `get_versions` — fetch all versions.
/// - `get_versions_with` — fetch all versions plus extra data (e.g. publish dates).
/// - `get_latest_matching` — fetch the single version matching a requirement.
/// - `search` — fetch search results for a query.
/// - `register_alternate` — register an alternate/private registry source.
/// - `package_url` — build the registry's web-display URL for a package (re-exported from
///   the crate root wherever it exists).
/// - `with_base` — construct a registry client pointed at a non-default base URL (tests,
///   alternate-registry hops); a plain, ungated `with_base` for production use, distinct
///   from any additional `#[cfg(test)]`/`test-util`-gated constructor a crate also needs
///   (see `deps-npm::registry::NpmRegistry::with_public_base_for_test` for that shape).
/// - Pure in-memory getters (no I/O) drop the `get_` prefix entirely, per the Rust API
///   Guidelines' C-GETTER (e.g. `ResolvedPackages::version`/`all`,
///   `EcosystemRegistry::for_filename`/`for_uri`/`for_lockfile`/`for_watched_config`).
///
/// Two sanctioned, named exceptions to this vocabulary (a deliberate #834 scope decision,
/// not drift left to fix): ecosystem-specific display-URL builder names (`gem_url` in
/// `deps-bundler`, `crate_url` in `deps-cargo`, `jsr_package_url` in `deps-deno`) stay as-is
/// — only re-export consistency was in scope, not the name itself; and the metadata-fetch
/// **return type** stays per-ecosystem (`GemInfo`/`PackageInfo`/`ArtifactInfo`/`CrateInfo`/
/// `DenoMetadata`/`GoMetadata`, ...) — only the *method* name converges on
/// `get_package_metadata`.
///
/// [`crate::registry_conformance!`]'s `ty:` form asserts the first four names exist on a
/// given registry type at compile time (and, since #834 critic S5, actually asserts they
/// are *inherent* — see [`crate::conformance::NotInherent`]'s own doc), so a future
/// ecosystem crate cannot silently reintroduce this drift. Wired directly into 9 of the 14
/// ecosystem crates as of #834; `deps-gradle` reuses `deps-maven`'s `MavenCentralRegistry`
/// unchanged and so is covered transitively through `deps-maven`'s own check. Four crates
/// are exempt, each for a distinct, documented reason rather than a silent gap:
/// - `deps-gitlab-ci` — route-based, no name+version registry concept at all; every one of
///   the four trait methods is an inline stub in the `Registry` impl itself, with no real
///   per-package logic anywhere to extract.
/// - `deps-deno` — `DenoRegistry`, the type that implements `Registry`, is a
///   scheme-dispatching facade with no single struct holding all four methods (it dispatches
///   by `jsr:`/`npm:` prefix to either its `JsrRegistry` field or an `NpmRegistry`, with
///   different call shapes on each side). Note this is a statement about `DenoRegistry`
///   specifically, not about the crate as a whole: `JsrRegistry` itself already has genuine
///   inherent `get_versions`/`search`, just not `get_versions_with`/`get_latest_matching`,
///   and its `get_versions(&self, scope: &str, name: &str)` is a fifth, two-part-key
///   argument shape for the canonical `get_versions` name (JSR packages are scoped,
///   `@scope/name`) that this contract's table does not otherwise cover.
/// - `deps-go`, `deps-github-actions` — both have genuine inherent `get_versions`/
///   `get_versions_with`/`get_latest_matching`; only `search` is missing, because neither
///   registry (the Go module proxy, the GitHub tags API) exposes a search endpoint this
///   crate can call at all. An inherent `search` here would be a fabricated always-empty
///   stub whose only purpose is satisfying this check, not a real, callable operation — the
///   `Registry` trait impl's own `search` (also always empty, for the same reason) is the
///   honest place for that.
///
/// # Examples
///
/// ```no_run
/// use deps_core::{Registry, Version, Metadata, PackageName, ConcreteVersion};
/// use std::any::Any;
/// use std::pin::Pin;
///
/// struct MyRegistry;
///
/// #[derive(Clone)]
/// struct MyVersion { version: ConcreteVersion }
///
/// impl Version for MyVersion {
///     fn version_string(&self) -> &ConcreteVersion { &self.version }
///     fn as_any(&self) -> &dyn Any { self }
/// }
///
/// #[derive(Clone)]
/// struct MyMetadata { name: PackageName, latest: ConcreteVersion }
///
/// impl Metadata for MyMetadata {
///     fn name(&self) -> &PackageName { &self.name }
///     fn description(&self) -> Option<&str> { None }
///     fn repository(&self) -> Option<&str> { None }
///     fn documentation(&self) -> Option<&str> { None }
///     fn latest_version(&self) -> &ConcreteVersion { &self.latest }
///     fn as_any(&self) -> &dyn Any { self }
/// }
///
/// impl Registry for MyRegistry {
///     fn get_versions<'a>(&'a self, _name: &'a PackageName)
///         -> Pin<Box<dyn std::future::Future<Output = deps_core::error::Result<Vec<Box<dyn Version>>>> + Send + 'a>>
///     {
///         Box::pin(async move { Ok(vec![Box::new(MyVersion { version: "1.0.0".into() }) as Box<dyn Version>]) })
///     }
///
///     fn get_latest_matching<'a>(&'a self, _name: &'a PackageName, _req: &'a deps_core::VersionReq)
///         -> Pin<Box<dyn std::future::Future<Output = deps_core::error::Result<Option<Box<dyn Version>>>> + Send + 'a>>
///     {
///         Box::pin(async move { Ok(None) })
///     }
///
///     fn search<'a>(&'a self, _query: &'a str, _limit: usize)
///         -> Pin<Box<dyn std::future::Future<Output = deps_core::error::Result<Vec<Box<dyn Metadata>>>> + Send + 'a>>
///     {
///         Box::pin(async move { Ok(vec![]) })
///     }
///
///     fn as_any(&self) -> &dyn Any { self }
/// }
/// ```
pub trait Registry: Send + Sync {
    /// Fetches all available versions for a package.
    ///
    /// Returns versions sorted newest-first. May include yanked/deprecated versions.
    ///
    /// # Errors
    ///
    /// Returns error if:
    /// - Package does not exist
    /// - Network request fails
    /// - Response parsing fails
    fn get_versions<'a>(
        &'a self,
        name: &'a PackageName,
    ) -> BoxFuture<'a, Result<Vec<Box<dyn Version>>>>;

    /// Like [`get_versions`](Self::get_versions), but lets a registry that can obtain
    /// [`Version::published_at`] only through an *extra* request gate that request behind
    /// `freshness.enabled` instead of always paying for it.
    ///
    /// Implementors overriding this method MUST keep every other aspect of
    /// [`get_versions`](Self::get_versions)'s behavior — set, order, and content of the
    /// returned versions — identical; the only difference the override may introduce is
    /// populating [`Version::published_at`]. Callers that render publish ages MUST call this
    /// method rather than [`get_versions`](Self::get_versions): the default implementation
    /// below simply forwards to `get_versions` and ignores `freshness`, so a caller that
    /// keeps calling `get_versions` silently gets no freshness signal even from a registry
    /// that implements this override.
    ///
    /// Default: forwards to [`get_versions`](Self::get_versions), ignoring `freshness`. This
    /// keeps the ten registries with no extra publish-time source unchanged, and keeps
    /// [`FreshnessSettings`](crate::freshness::FreshnessSettings) — a `Copy + 'static` DTO —
    /// out of every `Registry::new` signature and the `register!` ecosystem-registration
    /// macro.
    fn get_versions_with<'a>(
        &'a self,
        name: &'a PackageName,
        freshness: crate::freshness::FreshnessSettings,
    ) -> BoxFuture<'a, Result<Vec<Box<dyn Version>>>> {
        let _ = freshness;
        self.get_versions(name)
    }

    /// Like [`get_versions_with`](Self::get_versions_with), but additionally carries the
    /// dependency's resolved [`DependencySource`], for a registry that routes a single
    /// fetch across more than one underlying index (e.g. `deps-cargo`'s `CargoRegistry`,
    /// which dispatches a `DependencySource::AlternateRegistry` to a private sparse index
    /// instead of crates.io).
    ///
    /// Default: forwards to [`get_versions_with`](Self::get_versions_with), ignoring
    /// `source` entirely. This keeps every registry with no per-dependency routing concept
    /// — every ecosystem except Cargo today — bit-identical: `source` is accepted and
    /// dropped, so a caller migrating to this method from `get_versions_with` changes no
    /// observable behavior for them.
    ///
    /// Callers that know which source a dependency resolved to should call this rather
    /// than [`get_versions_with`](Self::get_versions_with), even against a registry with no
    /// override — the whole point is that call sites don't need to know which registries
    /// route on source and which don't.
    fn get_versions_from<'a>(
        &'a self,
        name: &'a PackageName,
        source: &'a DependencySource,
        freshness: crate::freshness::FreshnessSettings,
    ) -> BoxFuture<'a, Result<Vec<Box<dyn Version>>>> {
        let _ = source;
        self.get_versions_with(name, freshness)
    }

    /// Finds the latest version matching a version requirement.
    ///
    /// Filter with [`RemovalStatus::blocks_resolution`], never with
    /// [`RemovalStatus::is_flagged`]. An `AdvisoryDeprecated` version is fully
    /// installable — excluding it turns an existing package into a false
    /// "Unknown package" (#347). Under a wildcard/empty requirement
    /// (`"*"`/`""`, see [`is_existence_wildcard`]) this is an *existence* check ("does this
    /// package exist / what is its newest version for display purposes"), not an upgrade
    /// recommendation: an implementation may prefer a non-yanked version but fall back to a
    /// yanked one rather than returning `None` when no non-yanked version exists — a yanked
    /// package still exists. `deps-npm` implements this fallback (mirrored by
    /// [`select_latest_matching`](Self::select_latest_matching)'s wildcard branch on the
    /// same registry, which every caller reaching this trait method through the shared
    /// fetch loop actually goes through first); the exception never applies to a concrete
    /// requirement.
    ///
    /// # Arguments
    ///
    /// * `name` - Package name
    /// * `req` - Version requirement string (e.g., "^1.0", ">=2.0")
    ///
    /// # Returns
    ///
    /// - `Ok(Some(version))` - Latest matching version found
    /// - `Ok(None)` - No matching version found
    /// - `Err(_)` - Network or parsing error
    fn get_latest_matching<'a>(
        &'a self,
        name: &'a PackageName,
        req: &'a VersionReq,
    ) -> BoxFuture<'a, Result<Option<Box<dyn Version>>>>;

    /// Like [`get_latest_matching`](Self::get_latest_matching), but lets a registry whose
    /// "latest matching" selection can be refined by ecosystem-specific manifest state (e.g.
    /// Composer's `minimum-stability` field, #424) read it, alongside `req`.
    ///
    /// `minimum_stability` is an opaque, ecosystem-defined string (Composer's own stability
    /// keyword: `"dev"`, `"alpha"`, `"beta"`, `"RC"`, or `"stable"`) rather than a shared type,
    /// mirroring [`get_versions_with`](Self::get_versions_with)'s
    /// [`FreshnessSettings`](crate::freshness::FreshnessSettings) precedent for "an optional
    /// extra parameter most registries ignore" — except here even the *shape* of the extra
    /// context is ecosystem-specific, so no shared DTO is introduced for it; only the one
    /// registry that understands the string overrides this method.
    ///
    /// Default: forwards to [`get_latest_matching`](Self::get_latest_matching), ignoring
    /// `minimum_stability`. This keeps every registry with no manifest-level stability
    /// concept unchanged.
    fn get_latest_matching_with_context<'a>(
        &'a self,
        name: &'a PackageName,
        req: &'a VersionReq,
        minimum_stability: Option<&'a str>,
    ) -> BoxFuture<'a, Result<Option<Box<dyn Version>>>> {
        let _ = minimum_stability;
        self.get_latest_matching(name, req)
    }

    /// Like [`get_latest_matching_with_context`](Self::get_latest_matching_with_context),
    /// but additionally carries the dependency's resolved [`DependencySource`] — the
    /// `get_latest_matching`-shaped counterpart to
    /// [`get_versions_from`](Self::get_versions_from), covering the fallback path a caller
    /// takes when the list-based pick fails on a non-empty [`get_versions_from`](Self::get_versions_from)
    /// result (see `deps_core::lsp_helpers::hover`'s `list_fallback_latest` and
    /// `deps-lsp`'s background-fetch fallback for the two call sites this exists for).
    ///
    /// Default: forwards to
    /// [`get_latest_matching_with_context`](Self::get_latest_matching_with_context),
    /// ignoring `source` — every registry with no per-dependency routing concept stays
    /// bit-identical, exactly as [`get_versions_from`](Self::get_versions_from) does for the
    /// list-fetching side.
    fn get_latest_matching_from<'a>(
        &'a self,
        name: &'a PackageName,
        source: &'a DependencySource,
        req: &'a VersionReq,
        minimum_stability: Option<&'a str>,
    ) -> BoxFuture<'a, Result<Option<Box<dyn Version>>>> {
        let _ = source;
        self.get_latest_matching_with_context(name, req, minimum_stability)
    }

    /// Searches for packages by name or keywords.
    ///
    /// Returns up to `limit` results sorted by relevance/popularity.
    ///
    /// # Errors
    ///
    /// Returns error if network request or parsing fails.
    fn search<'a>(
        &'a self,
        query: &'a str,
        limit: usize,
    ) -> BoxFuture<'a, Result<Vec<Box<dyn Metadata>>>>;

    /// Index of the latest version in `versions` satisfying `req`, with no I/O.
    ///
    /// Filter with [`RemovalStatus::blocks_resolution`], never with
    /// [`RemovalStatus::is_flagged`]. An `AdvisoryDeprecated` version is fully
    /// installable — excluding it turns an existing package into a false
    /// "Unknown package" (#347). Under a wildcard/empty requirement (see
    /// [`is_existence_wildcard`]) this is an *existence* check, not an upgrade
    /// recommendation: Cargo, PyPI, Dart, npm, and Deno implement it by gating on
    /// [`is_existence_wildcard`] and delegating to [`select_latest_for_existence`].
    ///
    /// `versions` must be a newest-first list as returned by this registry's
    /// [`get_versions`](Self::get_versions). Returns an index rather than a reference so
    /// callers holding an owned `Vec` can move the chosen element out
    /// (`versions.into_iter().nth(i)`) — a borrow into the list would keep it frozen while
    /// [`get_latest_matching`](Self::get_latest_matching) needs to return an owned
    /// `Box<dyn Version>`, and `Version` has no `clone_box`.
    ///
    /// Default: `None`. Every registry reachable from the LSP fetch path overrides this so
    /// the fetch loop can obtain both "latest" and the full version list from one round
    /// trip; the default exists so test doubles that never resolve a "latest" compile
    /// unchanged.
    fn select_latest_matching(
        &self,
        _versions: &[Box<dyn Version>],
        _req: &VersionReq,
    ) -> Option<usize> {
        None
    }

    /// Like [`select_latest_matching`](Self::select_latest_matching), but lets a registry
    /// whose selection can be refined by ecosystem-specific manifest state (e.g. Composer's
    /// `minimum-stability` field, #424) read it, alongside `versions` and `req`. See
    /// [`get_latest_matching_with_context`](Self::get_latest_matching_with_context) for why
    /// `minimum_stability` is an opaque per-ecosystem string rather than a shared type.
    ///
    /// Default: forwards to [`select_latest_matching`](Self::select_latest_matching), ignoring
    /// `minimum_stability`. This keeps every registry with no manifest-level stability concept
    /// unchanged.
    fn select_latest_matching_with_context(
        &self,
        versions: &[Box<dyn Version>],
        req: &VersionReq,
        minimum_stability: Option<&str>,
    ) -> Option<usize> {
        let _ = minimum_stability;
        self.select_latest_matching(versions, req)
    }

    /// Whether [`get_versions`](Self::get_versions) results carry meaningful
    /// per-version yank/deprecation data via [`Version::removal_status`].
    ///
    /// Default `true`: a registry is opted into the yanked-version diagnostic
    /// unless it explicitly says it cannot answer. This fails toward
    /// correctness — a registry whose `removal_status` later becomes real
    /// data starts participating automatically, by deleting its opt-out
    /// rather than by someone remembering to add an opt-in. Return `false`
    /// only when `removal_status()` is hardcoded (e.g. always
    /// `RemovalStatus::Available`) or otherwise cannot reflect real registry
    /// data; a `true` return authorizes callers to trust `removal_status()`
    /// on versions from this registry's normal
    /// [`get_versions`](Self::get_versions)/
    /// [`get_latest_matching`](Self::get_latest_matching) results — it does
    /// not trigger any additional network request.
    fn reports_yanked(&self) -> bool {
        true
    }

    /// Downcast to concrete registry type for ecosystem-specific operations
    fn as_any(&self) -> &dyn Any;
}

/// Whether `version` contains one of the common pre-release substrings
/// (`-alpha`, `-beta`, `-rc`, `-dev`, `-pre`, `-snapshot`, `-canary`,
/// `-nightly`), case-insensitively.
///
/// This is [`Version::is_prerelease`]'s default heuristic, extracted so an
/// ecosystem that overrides `is_prerelease` to cover format-specific gaps
/// (e.g. Composer's `dev-` branch-alias prefix) can extend this baseline
/// instead of copy-pasting the substring list out of sync with it.
///
/// # Examples
///
/// ```
/// use deps_core::has_default_prerelease_marker;
///
/// assert!(has_default_prerelease_marker("1.0.0-beta"));
/// assert!(has_default_prerelease_marker("1.0.0-RC1"));
/// assert!(!has_default_prerelease_marker("1.0.0"));
/// ```
#[must_use]
pub fn has_default_prerelease_marker(version: &str) -> bool {
    let v = version.to_lowercase();
    v.contains("-alpha")
        || v.contains("-beta")
        || v.contains("-rc")
        || v.contains("-dev")
        || v.contains("-pre")
        || v.contains("-snapshot")
        || v.contains("-canary")
        || v.contains("-nightly")
}

/// Maps a `404` (plus any status in `also_not_found`) [`DepsError::HttpStatus`] to
/// [`DepsError::PackageNotFound`], passing through any other error unchanged.
///
/// Extracted from four byte-identical copies of this mapper in `deps-pypi`, `deps-deno`,
/// `deps-npm`, and `deps-go` (deps-lsp#929 item 1). `also_not_found` keeps ecosystem-specific
/// extra statuses explicit at the call site instead of hardcoded here — `deps-go` passes
/// `&[410]` for the Go module proxy's "retracted" status, which the other three ecosystems
/// must not silently inherit.
///
/// # Examples
///
/// ```
/// use deps_core::DepsError;
/// use deps_core::net_policy::RedactedUrl;
/// use deps_core::not_found_or;
///
/// let url = RedactedUrl::new("https://example.test/pkg");
/// let not_found = DepsError::HttpStatus {
///     url: url.clone(),
///     status: 404,
/// };
/// assert!(matches!(
///     not_found_or(not_found, "pkg", "example", &[]),
///     DepsError::PackageNotFound { .. }
/// ));
///
/// let server_error = DepsError::HttpStatus { url, status: 500 };
/// assert!(matches!(
///     not_found_or(server_error, "pkg", "example", &[]),
///     DepsError::HttpStatus { status: 500, .. }
/// ));
/// ```
#[must_use]
pub fn not_found_or(
    err: DepsError,
    package: &str,
    registry: &'static str,
    also_not_found: &[u16],
) -> DepsError {
    match err {
        DepsError::HttpStatus { status, .. }
            if status == 404 || also_not_found.contains(&status) =>
        {
            DepsError::PackageNotFound {
                package: package.to_string(),
                registry,
            }
        }
        other => other,
    }
}

/// Classifies a manifest-declared registry URL against an ecosystem's own default-registry
/// aliases.
///
/// A URL matching one of `default_urls` (ignoring a trailing slash) resolves to
/// [`DependencySource::Registry`]; anything else has no client this LSP can query, so it
/// becomes [`DependencySource::CustomRegistry`].
///
/// Extracted from byte-identical logic independently added to `deps-bundler` (rubygems.org)
/// and `deps-dart` (pub.dev, plus its legacy `pub.dartlang.org` alias) in the same change
/// (deps-lsp#980) — this project's cross-ecosystem-consistency rule treats that pattern as a
/// bug class rather than an acceptable duplication (see `.claude/CLAUDE.md`, and the #976/#969
/// precedent of centralizing similarly-shaped per-crate logic into `deps-core`).
///
/// # Examples
///
/// ```
/// use deps_core::DependencySource;
/// use deps_core::classify_default_registry_url;
///
/// assert_eq!(
///     classify_default_registry_url("https://rubygems.org".to_string(), &["https://rubygems.org"]),
///     DependencySource::Registry
/// );
///
/// // A trailing slash is ignored when comparing against the default list.
/// assert_eq!(
///     classify_default_registry_url("https://pub.dev/".to_string(), &["https://pub.dev", "https://pub.dartlang.org"]),
///     DependencySource::Registry
/// );
///
/// assert_eq!(
///     classify_default_registry_url("https://gems.mycorp.com".to_string(), &["https://rubygems.org"]),
///     DependencySource::CustomRegistry { url: "https://gems.mycorp.com".to_string() }
/// );
/// ```
#[must_use]
pub fn classify_default_registry_url(url: String, default_urls: &[&str]) -> DependencySource {
    let normalized = url.trim_end_matches('/');
    if default_urls.contains(&normalized) {
        DependencySource::Registry
    } else {
        DependencySource::CustomRegistry { url }
    }
}

/// Hashes an ordered sequence of `&str` routing-hop parts into an opaque
/// `"{prefix}:{digest:016x}"` chain-identity key, using
/// [`std::collections::hash_map::DefaultHasher`].
///
/// Extracted from three independently hand-rolled copies of this exact pattern
/// (`deps_pypi::config::ResolvedChain::chain`, `deps_nuget::config::NuGetSourceChain::chain`,
/// `deps_go::config::GoProxyChain::keyed`, #579) so "never hash a credential" is a property of
/// one function signature instead of a convention repeated in three doc comments.
///
/// Deliberately takes `&str`, not `impl Hash`: a caller with a typed credential wrapper (e.g.
/// `NuGetAuth`, which deliberately does not derive `Hash` — see its doc) must explicitly
/// convert it to a string before it can even be considered here, rather than being able to
/// `.hash()` the whole struct in place. Prefer a small, explicit, non-`Debug` `as_key_str()`-
/// style accessor on the hashed field's own type over `format!("{value:?}")` at the call
/// site — chain identity would otherwise silently change if that type's `Debug` output is
/// ever reworded (e.g. an enum variant rename), even though nothing routing-relevant changed.
///
/// **Security invariant**: `parts` must contain only routing-identity data (URLs, slot/hop
/// kind markers, boolean flags) — **never** credential material. Hashing a credential would
/// make the chain's identity key change whenever that credential value rotates, defeating
/// rotation-stability guarantees callers rely on (e.g. NuGet issue #561's FR-016). This
/// function has no way to enforce that; it is a caller obligation.
///
/// # Examples
///
/// ```
/// use deps_core::hash_routing_key;
///
/// let key = hash_routing_key("pypi-chain", ["https://example.test/simple/", "true"].into_iter());
/// assert!(key.starts_with("pypi-chain:"));
/// assert_eq!(key.len(), "pypi-chain:".len() + 16);
///
/// // Same parts, same key — deterministic within a process.
/// let key2 = hash_routing_key("pypi-chain", ["https://example.test/simple/", "true"].into_iter());
/// assert_eq!(key, key2);
///
/// // Hop order is part of the identity.
/// let forward = hash_routing_key("go-proxy", ["a", "b"].into_iter());
/// let reversed = hash_routing_key("go-proxy", ["b", "a"].into_iter());
/// assert_ne!(forward, reversed);
/// ```
#[must_use]
pub fn hash_routing_key<'a>(prefix: &str, parts: impl Iterator<Item = &'a str>) -> String {
    use std::hash::{Hash, Hasher};

    let mut hasher = std::collections::hash_map::DefaultHasher::new();
    for part in parts {
        part.hash(&mut hasher);
    }
    format!("{prefix}:{:016x}", hasher.finish())
}

/// Outcome of a registry's per-version removal/deprecation signal.
///
/// Replaces a bare `is_yanked(): bool`, which could not distinguish a version
/// a registry has *hard-removed from resolution* (`Yanked`) from one that is
/// merely flagged as deprecated/abandoned but still fully installable
/// (`AdvisoryDeprecated`). Conflating the two caused #347: Composer's
/// package-level `abandoned` flag was read through `is_yanked()`, so every
/// version of an abandoned-but-installable package was filtered out of
/// resolution, turning an existing package into a false "Unknown package"
/// diagnostic.
///
/// Call [`blocks_resolution`](Self::blocks_resolution) to decide whether a
/// version may be selected as an upgrade/latest candidate. Call
/// [`is_flagged`](Self::is_flagged) only to surface the registry's flag to
/// the user (e.g. a yanked/deprecated diagnostic) — never to filter
/// resolution.
///
/// # Examples
///
/// ```
/// use deps_core::RemovalStatus;
///
/// assert!(!RemovalStatus::Available.blocks_resolution());
/// assert!(!RemovalStatus::AdvisoryDeprecated.blocks_resolution());
/// assert!(RemovalStatus::Yanked.blocks_resolution());
///
/// assert!(RemovalStatus::AdvisoryDeprecated.is_flagged());
/// assert!(RemovalStatus::Yanked.is_flagged());
/// assert!(!RemovalStatus::Available.is_flagged());
/// ```
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RemovalStatus {
    /// The registry reports no removal/deprecation signal for this version.
    Available,
    /// The registry flags this version (or its package) as
    /// deprecated/abandoned, but the version remains fully resolvable and
    /// installable.
    AdvisoryDeprecated,
    /// The registry has hard-removed this version from fresh resolution (a
    /// real yank/retraction). Existing installs may keep using it, but it
    /// must not be selected as an upgrade/latest candidate.
    Yanked,
}

impl RemovalStatus {
    /// Whether fresh resolution must skip this version.
    ///
    /// `true` only for [`Yanked`](Self::Yanked). An
    /// [`AdvisoryDeprecated`](Self::AdvisoryDeprecated) version is fully
    /// installable — excluding it from resolution is what caused #347.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::RemovalStatus;
    ///
    /// assert!(!RemovalStatus::AdvisoryDeprecated.blocks_resolution());
    /// assert!(RemovalStatus::Yanked.blocks_resolution());
    /// ```
    #[must_use]
    pub const fn blocks_resolution(self) -> bool {
        matches!(self, Self::Yanked)
    }

    /// Whether the registry flags this version at all, hard or advisory.
    ///
    /// Use this only to decide whether to surface a warning to the user —
    /// never to filter resolution; use
    /// [`blocks_resolution`](Self::blocks_resolution) for that.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::RemovalStatus;
    ///
    /// assert!(!RemovalStatus::Available.is_flagged());
    /// assert!(RemovalStatus::AdvisoryDeprecated.is_flagged());
    /// assert!(RemovalStatus::Yanked.is_flagged());
    /// ```
    #[must_use]
    pub const fn is_flagged(self) -> bool {
        !matches!(self, Self::Available)
    }

    /// Builds a status from a registry's hard yanked/retracted boolean flag.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::RemovalStatus;
    ///
    /// assert_eq!(RemovalStatus::from_yanked(true), RemovalStatus::Yanked);
    /// assert_eq!(RemovalStatus::from_yanked(false), RemovalStatus::Available);
    /// ```
    #[must_use]
    pub const fn from_yanked(flag: bool) -> Self {
        if flag { Self::Yanked } else { Self::Available }
    }

    /// Builds a status from a registry's advisory deprecated/abandoned boolean flag.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::RemovalStatus;
    ///
    /// assert_eq!(RemovalStatus::from_advisory(true), RemovalStatus::AdvisoryDeprecated);
    /// assert_eq!(RemovalStatus::from_advisory(false), RemovalStatus::Available);
    /// ```
    #[must_use]
    pub const fn from_advisory(flag: bool) -> Self {
        if flag {
            Self::AdvisoryDeprecated
        } else {
            Self::Available
        }
    }
}

/// Package-level deprecation/abandonment payload: why a package is deprecated, and what
/// to use instead.
///
/// Distinct from [`RemovalStatus`], which answers *"may resolution select this
/// version"*. `Deprecation` answers *"what should the user be told"* — the reason text
/// and/or a registry-supplied replacement package name. Kept as a separate type rather
/// than a payload-carrying `RemovalStatus` variant: `RemovalStatus` is `Copy`, returned
/// from `const fn`s, and matched in every ecosystem crate, so widening it would ripple
/// everywhere for a concept that only a couple of registries expose.
///
/// Both fields are `None` when the registry has nothing to say beyond "deprecated" —
/// e.g. Packagist's bare `"abandoned": true`, with no replacement named.
///
/// # Examples
///
/// ```
/// use deps_core::Deprecation;
///
/// let deprecation = Deprecation {
///     reason: Some("no longer maintained".into()),
///     replacement: Some("some-other/package".into()),
/// };
///
/// assert_eq!(deprecation.reason.as_deref(), Some("no longer maintained"));
/// assert_eq!(deprecation.replacement.as_deref(), Some("some-other/package"));
/// ```
// Exhaustive: 25+ existing struct-literal construction sites across `deps-npm`,
// `deps-composer`, and `deps-lsp` (production code and tests) already build this directly
// by field; adding `#[non_exhaustive]` here would force a wide, low-value migration to a
// constructor for a two-field type that isn't expected to grow often, not because it's
// somehow less likely to grow than other types in this pass (issue #755).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Deprecation {
    /// Free-text reason the registry gives for the deprecation, if any.
    pub reason: Option<String>,
    /// Registry-supplied replacement package name, if any. Only ever populated from a
    /// structured registry field (never regex-extracted from free text — see #205's
    /// typosquatting rationale), so it is safe to offer as a rename target.
    pub replacement: Option<String>,
}

/// Version information trait.
///
/// All version types must implement this to work with generic handlers.
pub trait Version: Send + Sync {
    /// Version string (e.g., "1.0.214", "14.21.3").
    fn version_string(&self) -> &ConcreteVersion;

    /// This version's removal/deprecation status as reported by the registry.
    ///
    /// Default: [`RemovalStatus::Available`] — ecosystems with no
    /// yank/deprecation signal need no override.
    fn removal_status(&self) -> RemovalStatus {
        RemovalStatus::Available
    }

    /// Package-level deprecation payload, when this version's registry data carries one.
    ///
    /// Default `None` — the `Option` is the capability gate: an ecosystem that never
    /// overrides this produces no deprecation diagnostic/hover/quickfix at all, rather
    /// than depending on a separate "does this ecosystem report deprecation" predicate.
    fn deprecation(&self) -> Option<&Deprecation> {
        None
    }

    /// Whether this version is a pre-release (alpha, beta, rc, etc.).
    ///
    /// Default implementation checks for common pre-release patterns via
    /// [`has_default_prerelease_marker`].
    fn is_prerelease(&self) -> bool {
        has_default_prerelease_marker(self.version_string().as_str())
    }

    /// Available feature flags (empty if not supported by ecosystem).
    fn features(&self) -> Vec<String> {
        vec![]
    }

    /// Downcast to concrete version type
    fn as_any(&self) -> &dyn Any;

    /// Whether this version is stable: not hard-yanked and not a pre-release.
    ///
    /// An [`AdvisoryDeprecated`](RemovalStatus::AdvisoryDeprecated) version counts as
    /// stable here — it remains fully resolvable, just flagged. Only
    /// [`Yanked`](RemovalStatus::Yanked) disqualifies a version; see
    /// [`RemovalStatus::blocks_resolution`].
    fn is_stable(&self) -> bool {
        !self.removal_status().blocks_resolution() && !self.is_prerelease()
    }

    /// When this version was published, if the registry exposes it.
    ///
    /// Default `None` — ecosystems without publish metadata (or where
    /// fetching it would add a network round trip) degrade to pre-feature
    /// behavior: no freshness signal shown, no error, no change in ranking.
    fn published_at(&self) -> Option<crate::freshness::PublishTime> {
        None
    }

    /// SPDX license identifier(s) declared for this version, when the registry's
    /// already-fetched version-list response carries them.
    ///
    /// Default: empty slice — the capability gate for ecosystems whose hot-path
    /// version fetch doesn't carry license data (issue #204). `Vec<String>`, never
    /// `Option<String>`, everywhere this is implemented: a package can declare more
    /// than one license (an SPDX `OR`/dual-license split reported as discrete
    /// identifiers by the registry), and a single shape avoids an `Option` vs `Vec`
    /// split across ecosystems (spec 010 plan.md's "License shape" decision). An
    /// empty slice means "unknown/not reported", never "explicitly no license".
    fn license(&self) -> &[String] {
        &[]
    }
}

/// Finds the latest stable version from a list of versions.
///
/// Returns the first version that is:
/// - Not hard-yanked ([`RemovalStatus::Yanked`]) — an
///   [`AdvisoryDeprecated`](RemovalStatus::AdvisoryDeprecated) version still counts as
///   stable, since it remains fully resolvable
/// - Not a pre-release (alpha, beta, rc, etc.)
///
/// Assumes versions are sorted newest-first (as returned by registries).
///
/// # Examples
///
/// ```
/// use deps_core::registry::{RemovalStatus, Version, find_latest_stable};
/// use deps_core::ConcreteVersion;
/// use std::any::Any;
///
/// struct MyVersion { version: ConcreteVersion, yanked: bool }
///
/// impl Version for MyVersion {
///     fn version_string(&self) -> &ConcreteVersion { &self.version }
///     fn removal_status(&self) -> RemovalStatus { RemovalStatus::from_yanked(self.yanked) }
///     fn as_any(&self) -> &dyn Any { self }
/// }
///
/// let versions: Vec<Box<dyn Version>> = vec![
///     Box::new(MyVersion { version: "2.0.0-alpha.1".into(), yanked: false }),
///     Box::new(MyVersion { version: "1.5.0".into(), yanked: true }),
///     Box::new(MyVersion { version: "1.4.0".into(), yanked: false }),
/// ];
///
/// let latest = find_latest_stable(&versions);
/// assert_eq!(latest.map(|v| v.version_string().as_str()), Some("1.4.0"));
/// ```
pub fn find_latest_stable(versions: &[Box<dyn Version>]) -> Option<&dyn Version> {
    versions.iter().find(|v| v.is_stable()).map(|v| v.as_ref())
}

/// Whether `req` is a wildcard/empty requirement (`""` or `"*"`, ignoring surrounding
/// whitespace) rather than a concrete version constraint.
///
/// A wildcard requirement turns [`get_latest_matching`](Registry::get_latest_matching) and
/// [`select_latest_matching`](Registry::select_latest_matching) into an *existence* check
/// ("does this package exist / what is its newest version for display purposes") instead of
/// an upgrade recommendation — see [`select_latest_for_existence`], which callers must gate
/// on this function before use.
///
/// # Examples
///
/// ```
/// use deps_core::{VersionReq, is_existence_wildcard};
///
/// assert!(is_existence_wildcard(&VersionReq::new("*")));
/// assert!(is_existence_wildcard(&VersionReq::new("")));
/// assert!(!is_existence_wildcard(&VersionReq::new("^1.2")));
/// ```
#[must_use]
pub fn is_existence_wildcard(req: &crate::VersionReq) -> bool {
    is_existence_wildcard_str(req.as_str())
}

/// [`is_existence_wildcard`] for a raw `&str`, without allocating a [`VersionReq`] wrapper.
///
/// Exists for callers that hold a version requirement as `&str` rather than a `VersionReq`
/// (e.g. an inherent method taking `req_str: &str` for its own parsing needs) — going through
/// [`is_existence_wildcard`] there would allocate a `String` via `VersionReq::new` on every
/// call just to check it.
///
/// # Examples
///
/// ```
/// use deps_core::registry::is_existence_wildcard_str;
///
/// assert!(is_existence_wildcard_str("*"));
/// assert!(is_existence_wildcard_str(""));
/// assert!(!is_existence_wildcard_str("^1.2"));
/// ```
#[must_use]
pub fn is_existence_wildcard_str(req: &str) -> bool {
    matches!(req.trim(), "" | "*")
}

/// Builds the canonical existence-check requirement (`"*"`) [`is_existence_wildcard`] recognizes.
///
/// [`Registry::select_latest_matching`] callers pass this when they want "the newest version
/// for display purposes" rather than an upgrade recommendation against a real constraint.
/// Centralizes what was three independent `VersionReq::new("*")` call sites (hover, version
/// completion, code-action quick-fixes) all constructing the identical value for the
/// identical purpose.
///
/// # Examples
///
/// ```
/// use deps_core::{existence_wildcard_req, is_existence_wildcard};
///
/// assert!(is_existence_wildcard(&existence_wildcard_req()));
/// ```
#[must_use]
pub fn existence_wildcard_req() -> crate::VersionReq {
    crate::VersionReq::new("*")
}

/// Index of the version an *existence* check should report as "latest", ignoring `req`
/// entirely.
///
/// This is the shared 3-rung fallback ladder used under a wildcard/empty requirement, where
/// every version satisfies by definition and the question is only which one to prefer for
/// display:
///
/// 1. The newest version that is neither flagged
///    ([`RemovalStatus::is_flagged`]) nor a pre-release ([`Version::is_prerelease`]).
/// 2. Else, the newest version that does not block resolution
///    ([`RemovalStatus::blocks_resolution`]) — an `AdvisoryDeprecated` version counts here.
/// 3. Else, index `0` unconditionally — the newest version overall, however it is flagged.
///    A yanked-or-prerelease-only package still exists; this rung is what turns that case
///    into "here is its newest version" instead of a false "Unknown package" (#347, #364).
///
/// `versions` must be sorted newest-first, as returned by [`Registry::get_versions`]. Returns
/// `None` only when `versions` is empty.
///
/// # Requirement-blindness is deliberate and dangerous
///
/// This function takes no `req` parameter and does not check whether the caller is under a
/// wildcard requirement — it always returns rung 3 as a last resort, regardless of what a
/// concrete requirement might demand. It is **only correct once the caller has already
/// confirmed the requirement is a wildcard** via [`is_existence_wildcard`]. Calling it
/// ungated — e.g. under a concrete `^1.2` requirement — can return a version that does not
/// satisfy that requirement at all, silently corrupting upgrade resolution.
///
/// # Examples
///
/// ```
/// use deps_core::registry::{RemovalStatus, Version, select_latest_for_existence};
/// use deps_core::ConcreteVersion;
/// use std::any::Any;
///
/// struct MyVersion { version: ConcreteVersion, status: RemovalStatus, prerelease: bool }
///
/// impl Version for MyVersion {
///     fn version_string(&self) -> &ConcreteVersion { &self.version }
///     fn removal_status(&self) -> RemovalStatus { self.status }
///     fn is_prerelease(&self) -> bool { self.prerelease }
///     fn as_any(&self) -> &dyn Any { self }
/// }
///
/// // Newest version is yanked; rung 3 still returns it rather than `None`.
/// let versions = vec![
///     MyVersion { version: "2.0.0".into(), status: RemovalStatus::Yanked, prerelease: false },
///     MyVersion { version: "1.5.0".into(), status: RemovalStatus::Yanked, prerelease: false },
/// ];
///
/// let idx = select_latest_for_existence(&versions, |v| v as &dyn Version);
/// assert_eq!(idx, Some(0));
///
/// assert_eq!(select_latest_for_existence::<MyVersion>(&[], |v| v as &dyn Version), None);
/// ```
#[must_use]
pub fn select_latest_for_existence<T>(
    versions: &[T],
    as_version: impl Fn(&T) -> &dyn Version,
) -> Option<usize> {
    if versions.is_empty() {
        return None;
    }
    Some(
        versions
            .iter()
            .position(|v| {
                let v = as_version(v);
                !v.removal_status().is_flagged() && !v.is_prerelease()
            })
            .or_else(|| {
                versions
                    .iter()
                    .position(|v| !as_version(v).removal_status().blocks_resolution())
            })
            .unwrap_or(0),
    )
}

/// Package metadata trait.
///
/// Used for completion items and hover documentation.
pub trait Metadata: Send + Sync {
    /// The package name as the *registry* reports it.
    ///
    /// This is the identifier the registry displays and that completion
    /// pastes into a manifest. It is not guaranteed byte-identical to the
    /// manifest-declared [`Dependency::name`](crate::ecosystem::Dependency::name)
    /// for the same package: casing may differ (NuGet, Composer, Swift), and
    /// for Maven/Gradle it is a `"group:artifact"` value synthesized from two
    /// separate response fields. Do not compare it to a manifest name
    /// without going through
    /// [`PackageNaming::normalize_package_name`](crate::lsp_helpers::PackageNaming::normalize_package_name).
    fn name(&self) -> &crate::PackageName;

    /// Short description (optional).
    fn description(&self) -> Option<&str>;

    /// Repository URL (optional).
    fn repository(&self) -> Option<&str>;

    /// Documentation URL (optional).
    fn documentation(&self) -> Option<&str>;

    /// Latest stable version.
    fn latest_version(&self) -> &ConcreteVersion;

    /// Downcast to concrete metadata type
    fn as_any(&self) -> &dyn Any;
}

/// Shared capacity ceiling for a per-ecosystem alternate-registry client map.
///
/// Reached via each ecosystem's own `register_alternate` (`Cargo`, `npm`, `PyPI`, `NuGet`,
/// `Go`, #976). Once reached, a not-yet-registered key is refused rather than evicting an
/// existing, possibly still-in-use, client.
pub const MAX_ALTERNATE_REGISTRIES: usize = 256;

/// How a [`register_capped`]/[`register_capped_with_occupied`] key must be rendered in the
/// cap-reached log line (#969 S3).
///
/// A URL-shaped key is redacted via [`crate::net_policy::RedactedUrl`]; an already-opaque
/// token (e.g. a [`hash_routing_key`] digest) is logged verbatim, since `RedactedUrl`'s
/// Maven-coordinate/REST-path false-positive scan would otherwise collapse every such key —
/// which is exactly one colon plus a hex digest, the shape that scan is designed to catch —
/// to an identical, information-free `"<prefix>:***"`, destroying the very correlation handle
/// the log line exists to provide. A closed, two-variant choice rather than an open `Display`
/// bypass: a call site declares which shape its key is, but cannot smuggle an unredacted URL
/// through under the `Opaque` label by accident in the type system's own vocabulary — though
/// nothing stops a caller from mislabeling one at the value level, so get this right: labeling
/// a URL-shaped key `Opaque` leaks any query-string credential it carries (the dangerous
/// direction); labeling an opaque token `Url` only over-redacts a value that had no secret to
/// begin with (the safe direction).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyShape {
    /// Redact via [`crate::net_policy::RedactedUrl`] before logging.
    Url,
    /// Log verbatim — this value is known to never carry a credential (e.g. a
    /// [`hash_routing_key`] digest, or another fixed, non-URL literal).
    Opaque,
}

/// Registers `key` in a capacity-bounded alternate-client map, refusing (never evicting)
/// once full.
///
/// A no-op when `key` is already registered — the first successful registration for a given
/// key sticks. A no-op, with a `tracing::warn!`, once [`MAX_ALTERNATE_REGISTRIES`] is reached
/// and `key` is not already present.
///
/// Reads `map.len()` **before** calling `entry()`: `DashMap::len` read-locks every shard,
/// while `entry()` holds a write guard on one — checking capacity from inside the `Vacant`
/// arm would self-deadlock on that shard.
///
/// `ecosystem` names the caller in the cap-reached log line (e.g. `"npm"`, `"PyPI"`).
/// `key_shape` picks how `key` is rendered in that same line — see [`KeyShape`].
///
/// Returns `true` when `make()` was inserted, `false` when `key` was already occupied or the
/// map was at capacity.
///
/// # Examples
///
/// ```
/// use dashmap::DashMap;
/// use deps_core::registry::{KeyShape, register_capped};
///
/// let map: DashMap<String, u32> = DashMap::new();
/// assert!(register_capped(&map, "a".to_string(), "test", KeyShape::Opaque, || 1));
/// assert!(!register_capped(&map, "a".to_string(), "test", KeyShape::Opaque, || 2));
/// assert_eq!(*map.get("a").unwrap(), 1);
/// ```
pub fn register_capped<K, V>(
    map: &DashMap<K, V>,
    key: K,
    ecosystem: &'static str,
    key_shape: KeyShape,
    make: impl FnOnce() -> V,
) -> bool
where
    K: Eq + Hash + AsRef<str>,
{
    register_capped_with_occupied(map, key, ecosystem, key_shape, make, |_| {})
}

/// [`register_capped`], plus an `on_occupied` callback for an already-registered key.
///
/// Lets an ecosystem still act on that key — folding a re-registration's trust tier
/// (`deps-cargo`) or rebuilding a client whose credential digest changed (`deps-nuget`).
///
/// `on_occupied` runs instead of `make`/the capacity check, never gated by
/// [`MAX_ALTERNATE_REGISTRIES`] — replacing an already-occupied slot does not grow the map,
/// so gating it would strand a legitimate in-place update (e.g. a rotated credential) once
/// the cap is hit for unrelated keys.
///
/// Returns `true` when `make()` was inserted (the `Vacant` arm), `false` otherwise —
/// `on_occupied` signals its own outcome (e.g. via `tracing::warn!`) rather than through this
/// return value.
///
/// # Examples
///
/// ```
/// use dashmap::DashMap;
/// use deps_core::registry::{KeyShape, register_capped_with_occupied};
///
/// let map: DashMap<String, u32> = DashMap::new();
/// register_capped_with_occupied(&map, "a".to_string(), "test", KeyShape::Opaque, || 1, |_| {});
/// register_capped_with_occupied(
///     &map,
///     "a".to_string(),
///     "test",
///     KeyShape::Opaque,
///     || 1,
///     |v| *v += 10,
/// );
/// assert_eq!(*map.get("a").unwrap(), 11);
/// ```
pub fn register_capped_with_occupied<K, V>(
    map: &DashMap<K, V>,
    key: K,
    ecosystem: &'static str,
    key_shape: KeyShape,
    make: impl FnOnce() -> V,
    on_occupied: impl FnOnce(&mut V),
) -> bool
where
    K: Eq + Hash + AsRef<str>,
{
    let at_capacity = map.len() >= MAX_ALTERNATE_REGISTRIES;

    match map.entry(key) {
        Entry::Occupied(mut slot) => {
            on_occupied(slot.get_mut());
            false
        }
        Entry::Vacant(slot) => {
            if at_capacity {
                // `slot.key()` reads the key back out of the entry rather than requiring a
                // borrow held across the `entry()` call above, so the (possibly allocating)
                // redaction work below stays entirely off the far more common
                // successful-registration path.
                let key_ref = slot.key().as_ref();
                let rendered_key = match key_shape {
                    KeyShape::Url => crate::net_policy::RedactedUrl::new(key_ref).to_string(),
                    KeyShape::Opaque => key_ref.to_string(),
                };
                tracing::warn!(
                    key = %rendered_key,
                    cap = MAX_ALTERNATE_REGISTRIES,
                    "{ecosystem} alternate registry cap reached; not registering a new entry"
                );
                return false;
            }
            slot.insert(make());
            true
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    struct MockVersion {
        version: ConcreteVersion,
        yanked: bool,
    }

    impl Version for MockVersion {
        fn version_string(&self) -> &ConcreteVersion {
            &self.version
        }

        fn removal_status(&self) -> RemovalStatus {
            RemovalStatus::from_yanked(self.yanked)
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    #[test]
    fn test_version_default_features() {
        let version = MockVersion {
            version: "1.0.0".into(),
            yanked: false,
        };

        assert_eq!(version.features(), Vec::<String>::new());
    }

    #[test]
    fn test_version_trait_object() {
        let version = MockVersion {
            version: "1.2.3".into(),
            yanked: false,
        };

        let boxed: Box<dyn Version> = Box::new(version);
        assert_eq!(boxed.version_string().as_str(), "1.2.3");
        assert!(!boxed.removal_status().blocks_resolution());
    }

    #[test]
    fn test_version_downcast() {
        let version = MockVersion {
            version: "1.0.0".into(),
            yanked: true,
        };

        let boxed: Box<dyn Version> = Box::new(version);
        let any = boxed.as_any();

        assert!(any.is::<MockVersion>());
    }

    struct MockMetadata {
        name: crate::PackageName,
        latest: ConcreteVersion,
    }

    impl Metadata for MockMetadata {
        fn name(&self) -> &crate::PackageName {
            &self.name
        }

        fn description(&self) -> Option<&str> {
            None
        }

        fn repository(&self) -> Option<&str> {
            None
        }

        fn documentation(&self) -> Option<&str> {
            None
        }

        fn latest_version(&self) -> &ConcreteVersion {
            &self.latest
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    #[test]
    fn test_metadata_trait_object() {
        let metadata = MockMetadata {
            name: crate::PackageName::new("test-package"),
            latest: "2.0.0".into(),
        };

        let boxed: Box<dyn Metadata> = Box::new(metadata);
        assert_eq!(boxed.name(), "test-package");
        assert_eq!(boxed.latest_version().as_str(), "2.0.0");
        assert!(boxed.description().is_none());
        assert!(boxed.repository().is_none());
        assert!(boxed.documentation().is_none());
    }

    #[test]
    fn test_metadata_with_full_info() {
        struct FullMetadata {
            name: crate::PackageName,
            desc: String,
            repo: String,
            docs: String,
            latest: ConcreteVersion,
        }

        impl Metadata for FullMetadata {
            fn name(&self) -> &crate::PackageName {
                &self.name
            }
            fn description(&self) -> Option<&str> {
                Some(&self.desc)
            }
            fn repository(&self) -> Option<&str> {
                Some(&self.repo)
            }
            fn documentation(&self) -> Option<&str> {
                Some(&self.docs)
            }
            fn latest_version(&self) -> &ConcreteVersion {
                &self.latest
            }
            fn as_any(&self) -> &dyn Any {
                self
            }
        }

        let meta = FullMetadata {
            name: crate::PackageName::new("serde"),
            desc: "Serialization framework".into(),
            repo: "https://github.com/serde-rs/serde".into(),
            docs: "https://docs.rs/serde".into(),
            latest: "1.0.214".into(),
        };

        assert_eq!(meta.description(), Some("Serialization framework"));
        assert_eq!(meta.repository(), Some("https://github.com/serde-rs/serde"));
        assert_eq!(meta.documentation(), Some("https://docs.rs/serde"));
    }

    #[test]
    fn test_is_prerelease_alpha() {
        let version = MockVersion {
            version: "4.0.0-alpha.13".into(),
            yanked: false,
        };
        assert!(version.is_prerelease());
    }

    #[test]
    fn test_is_prerelease_beta() {
        let version = MockVersion {
            version: "2.0.0-beta.1".into(),
            yanked: false,
        };
        assert!(version.is_prerelease());
    }

    #[test]
    fn test_is_prerelease_rc() {
        let version = MockVersion {
            version: "1.5.0-rc.2".into(),
            yanked: false,
        };
        assert!(version.is_prerelease());
    }

    #[test]
    fn test_is_prerelease_dev() {
        let version = MockVersion {
            version: "3.0.0-dev".into(),
            yanked: false,
        };
        assert!(version.is_prerelease());
    }

    #[test]
    fn test_is_prerelease_canary() {
        let version = MockVersion {
            version: "5.0.0-canary".into(),
            yanked: false,
        };
        assert!(version.is_prerelease());
    }

    #[test]
    fn test_is_prerelease_nightly() {
        let version = MockVersion {
            version: "6.0.0-nightly".into(),
            yanked: false,
        };
        assert!(version.is_prerelease());
    }

    #[test]
    fn test_is_not_prerelease_stable() {
        let version = MockVersion {
            version: "1.2.3".into(),
            yanked: false,
        };
        assert!(!version.is_prerelease());
    }

    #[test]
    fn test_is_not_prerelease_patch() {
        let version = MockVersion {
            version: "1.0.214".into(),
            yanked: false,
        };
        assert!(!version.is_prerelease());
    }

    #[test]
    fn test_is_stable_true() {
        let version = MockVersion {
            version: "1.0.0".into(),
            yanked: false,
        };
        assert!(version.is_stable());
    }

    #[test]
    fn test_is_stable_false_yanked() {
        let version = MockVersion {
            version: "1.0.0".into(),
            yanked: true,
        };
        assert!(!version.is_stable());
    }

    #[test]
    fn test_is_stable_false_prerelease() {
        let version = MockVersion {
            version: "1.0.0-alpha.1".into(),
            yanked: false,
        };
        assert!(!version.is_stable());
    }

    #[test]
    fn test_find_latest_stable_skips_prerelease() {
        let versions: Vec<Box<dyn Version>> = vec![
            Box::new(MockVersion {
                version: "2.0.0-alpha.1".into(),
                yanked: false,
            }),
            Box::new(MockVersion {
                version: "1.5.0".into(),
                yanked: false,
            }),
        ];
        let latest = super::find_latest_stable(&versions);
        assert_eq!(latest.map(|v| v.version_string().as_str()), Some("1.5.0"));
    }

    #[test]
    fn test_find_latest_stable_skips_yanked() {
        let versions: Vec<Box<dyn Version>> = vec![
            Box::new(MockVersion {
                version: "2.0.0".into(),
                yanked: true,
            }),
            Box::new(MockVersion {
                version: "1.5.0".into(),
                yanked: false,
            }),
        ];
        let latest = super::find_latest_stable(&versions);
        assert_eq!(latest.map(|v| v.version_string().as_str()), Some("1.5.0"));
    }

    #[test]
    fn test_find_latest_stable_returns_first_stable() {
        let versions: Vec<Box<dyn Version>> = vec![
            Box::new(MockVersion {
                version: "3.0.0-beta.1".into(),
                yanked: false,
            }),
            Box::new(MockVersion {
                version: "2.0.0".into(),
                yanked: true,
            }),
            Box::new(MockVersion {
                version: "1.5.0".into(),
                yanked: false,
            }),
            Box::new(MockVersion {
                version: "1.4.0".into(),
                yanked: false,
            }),
        ];
        let latest = super::find_latest_stable(&versions);
        assert_eq!(latest.map(|v| v.version_string().as_str()), Some("1.5.0"));
    }

    #[test]
    fn test_find_latest_stable_empty_list() {
        let versions: Vec<Box<dyn Version>> = vec![];
        let latest = super::find_latest_stable(&versions);
        assert!(latest.is_none());
    }

    #[test]
    fn test_find_latest_stable_no_stable_versions() {
        let versions: Vec<Box<dyn Version>> = vec![
            Box::new(MockVersion {
                version: "2.0.0-alpha.1".into(),
                yanked: false,
            }),
            Box::new(MockVersion {
                version: "1.0.0".into(),
                yanked: true,
            }),
        ];
        let latest = super::find_latest_stable(&versions);
        assert!(latest.is_none());
    }

    struct StatusVersion {
        version: ConcreteVersion,
        status: RemovalStatus,
    }

    impl Version for StatusVersion {
        fn version_string(&self) -> &ConcreteVersion {
            &self.version
        }

        fn removal_status(&self) -> RemovalStatus {
            self.status
        }

        fn as_any(&self) -> &dyn Any {
            self
        }
    }

    #[test]
    fn test_is_stable_true_for_advisory_deprecated() {
        let version = StatusVersion {
            version: "1.0.0".into(),
            status: RemovalStatus::AdvisoryDeprecated,
        };
        assert!(version.is_stable());
    }

    #[test]
    fn test_is_stable_false_for_yanked() {
        let version = StatusVersion {
            version: "1.0.0".into(),
            status: RemovalStatus::Yanked,
        };
        assert!(!version.is_stable());
    }

    #[test]
    fn test_removal_status_blocks_resolution() {
        assert!(!RemovalStatus::Available.blocks_resolution());
        assert!(!RemovalStatus::AdvisoryDeprecated.blocks_resolution());
        assert!(RemovalStatus::Yanked.blocks_resolution());
    }

    #[test]
    fn test_removal_status_is_flagged() {
        assert!(!RemovalStatus::Available.is_flagged());
        assert!(RemovalStatus::AdvisoryDeprecated.is_flagged());
        assert!(RemovalStatus::Yanked.is_flagged());
    }

    #[test]
    fn test_removal_status_from_yanked() {
        assert_eq!(RemovalStatus::from_yanked(true), RemovalStatus::Yanked);
        assert_eq!(RemovalStatus::from_yanked(false), RemovalStatus::Available);
    }

    #[test]
    fn test_removal_status_from_advisory() {
        assert_eq!(
            RemovalStatus::from_advisory(true),
            RemovalStatus::AdvisoryDeprecated
        );
        assert_eq!(
            RemovalStatus::from_advisory(false),
            RemovalStatus::Available
        );
    }

    #[test]
    fn test_hash_routing_key_format() {
        let key = hash_routing_key("pypi-chain", ["https://example.test/simple/"].into_iter());
        assert!(key.starts_with("pypi-chain:"));
        assert_eq!(key.len(), "pypi-chain:".len() + 16);
    }

    #[test]
    fn test_hash_routing_key_deterministic() {
        let parts = || ["https://a.test/", "https://b.test/", "true"].into_iter();
        assert_eq!(
            hash_routing_key("go-proxy", parts()),
            hash_routing_key("go-proxy", parts())
        );
    }

    #[test]
    fn test_hash_routing_key_distinguishes_prefix() {
        let parts = || ["same"].into_iter();
        assert_ne!(
            hash_routing_key("pypi-chain", parts()),
            hash_routing_key("nuget-chain", parts())
        );
    }

    #[test]
    fn test_hash_routing_key_distinguishes_parts() {
        assert_ne!(
            hash_routing_key("chain", ["a", "b"].into_iter()),
            hash_routing_key("chain", ["a", "c"].into_iter())
        );
    }

    /// Hop order is part of chain identity (spec 034's fallback order, PyPI's FR-005
    /// primary-before-extras order, NuGet's declaration order all rely on this) — the same
    /// set of parts in a different order must not collide.
    #[test]
    fn test_hash_routing_key_order_sensitive() {
        assert_ne!(
            hash_routing_key("chain", ["a", "b", "c"].into_iter()),
            hash_routing_key("chain", ["c", "b", "a"].into_iter())
        );
    }

    /// Documents that credential exclusion is a caller obligation, not something
    /// `hash_routing_key` enforces: two calls that differ only in a credential-shaped extra
    /// part produce different keys, so a caller who mistakenly includes one breaks the
    /// rotation-stability invariant this function's doc warns about.
    #[test]
    fn test_hash_routing_key_only_hashes_what_callers_pass() {
        let identity_only =
            hash_routing_key("nuget-chain", ["https://feed.test/", "corp"].into_iter());
        let with_credential_included = hash_routing_key(
            "nuget-chain",
            ["https://feed.test/", "corp", "hunter2"].into_iter(),
        );
        assert_ne!(identity_only, with_credential_included);
    }

    /// #969 S1: a `KeyShape::Url` key must be redacted before it reaches the cap-reached log
    /// line — the query-string credential must never appear, but the non-secret host must.
    #[cfg(feature = "test-util")]
    #[test]
    fn test_register_capped_url_shape_redacts_credential_on_cap_reached() {
        let map: DashMap<String, usize> = DashMap::new();
        for i in 0..MAX_ALTERNATE_REGISTRIES {
            assert!(register_capped(
                &map,
                format!("https://index{i}.example"),
                "test",
                KeyShape::Url,
                || i,
            ));
        }

        let log = crate::test_util::capture_tracing_output(|| {
            register_capped(
                &map,
                "https://overflow.example/?api_key=SUPERSECRET_TOKEN".to_string(),
                "test",
                KeyShape::Url,
                || 0,
            );
        });

        assert!(
            log.contains("test alternate registry cap reached"),
            "log: {log}"
        );
        assert!(!log.contains("SUPERSECRET_TOKEN"), "log: {log}");
        assert!(log.contains("overflow.example"), "log: {log}");
    }

    /// #969 S3: a `KeyShape::Opaque` key (e.g. a [`hash_routing_key`] digest) must survive
    /// the cap-reached log line intact — `RedactedUrl`'s Maven-coordinate false-positive scan
    /// would otherwise collapse a `"<prefix>:<hex>"` shape to an information-free
    /// `"<prefix>:***"`, destroying the correlation handle to other diagnostics about the
    /// same chain.
    #[cfg(feature = "test-util")]
    #[test]
    fn test_register_capped_opaque_shape_is_not_redacted_on_cap_reached() {
        let map: DashMap<String, usize> = DashMap::new();
        for i in 0..MAX_ALTERNATE_REGISTRIES {
            let key = hash_routing_key("test-chain", std::iter::once(i.to_string().as_str()));
            assert!(register_capped(&map, key, "test", KeyShape::Opaque, || i));
        }

        let overflow_key = hash_routing_key("test-chain", std::iter::once("overflow"));
        let log = crate::test_util::capture_tracing_output(|| {
            register_capped(&map, overflow_key.clone(), "test", KeyShape::Opaque, || 0);
        });

        assert!(
            log.contains("test alternate registry cap reached"),
            "log: {log}"
        );
        assert!(
            log.contains(&overflow_key),
            "opaque key must not be redacted: {log}"
        );
        assert!(
            !log.contains("***"),
            "opaque key must not collapse to '***': {log}"
        );
    }
}