deps-core 6.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
//! Newtypes distinguishing package names, version requirement strings, and
//! concrete resolved versions.
//!
//! [`PackageName`], [`VersionReq`], and [`ConcreteVersion`] wrap `String` to
//! give these kinds of manifest and registry data their own types, so a
//! function that expects one cannot accidentally be called with another.
//! None of these types validate, trim, or normalize their contents:
//! ecosystem-specific normalization (case folding, separator rewriting,
//! etc.) belongs to `EcosystemFormatter`, not to these types. See each
//! type's documentation for details.

use std::borrow::Borrow;
use std::fmt;

use crate::lsp_helpers::{NormalizeName, PackageNaming};

/// A package/crate name as it appears in a manifest file.
///
/// This is deliberately permissive: it stores whatever bytes the manifest
/// contained, including the empty string, leading/trailing whitespace, or
/// non-ASCII characters. No validation, trimming, or normalization is
/// performed by this type.
///
/// For several ecosystems this is not a "package name" in the narrow sense
/// but a registry lookup key: Maven and Gradle store `"group:artifact"`, Swift
/// stores `"owner/repo"`, and Go stores a URL-like module path. All of these
/// are valid `PackageName` values. Ecosystem-specific normalization (case
/// folding, separator rewriting, etc.) is the responsibility of
/// `EcosystemFormatter`, not this type — do not add validation rules here,
/// as it would silently break those ecosystems.
///
/// This type has no [`Display`](fmt::Display) impl, and its [`Debug`](fmt::Debug) impl
/// redacts via [`crate::redact::redact_declaration_key`] rather than deriving (#1217) —
/// see [`Self::for_tracing`] for why, and use [`Self::as_str`]/[`Self::as_ref`]/
/// [`Self::into_string`] for the raw value.
///
/// # Examples
///
/// ```
/// use deps_core::PackageName;
///
/// let name = PackageName::new("serde");
/// assert_eq!(name.as_str(), "serde");
/// assert_eq!(name, "serde");
/// ```
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct PackageName(String);

impl PackageName {
    /// Wraps `value` as a `PackageName`, unchanged.
    ///
    /// This never fails and never modifies its input: an empty string is a
    /// valid `PackageName`, as is a string with surrounding whitespace.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::PackageName;
    ///
    /// let name = PackageName::new(String::from("tokio"));
    /// assert_eq!(name.as_str(), "tokio");
    /// ```
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// Returns the package name as a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::PackageName;
    ///
    /// let name = PackageName::new("axum");
    /// assert_eq!(name.as_str(), "axum");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the `PackageName`, returning the wrapped `String`.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::PackageName;
    ///
    /// let name = PackageName::new("axum");
    /// let owned: String = name.into_string();
    /// assert_eq!(owned, "axum");
    /// ```
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }

    /// Renders this name for `tracing`/log output, redacting it via
    /// [`crate::redact::redact_declaration_key`] first (#1209).
    ///
    /// A manifest can hold a credential in a name-shaped field (e.g. a Maven
    /// `group:artifact:secret@host` coordinate produced by property
    /// interpolation), and this type's raw accessors ([`Self::as_str`], [`Self::as_ref`],
    /// [`Self::into_string`]) return the string verbatim — so any `tracing` field or span
    /// built from a `PackageName` must go through this method instead. (`?name` and
    /// `Debug`-derived output are already safe — see [`Self`]'s `Debug` impl — but `%name`,
    /// which requires `Display`, does not compile at all, since `PackageName` has none.) An
    /// ordinary package name (including scoped ones like `@types/node` or
    /// `com.google.guava:guava`) passes through unchanged.
    ///
    /// The result is also swept for control/format characters (`\n`, `\r`, a raw ESC byte, and
    /// the wider Unicode `Cc`/`Cf`/`Zl`/`Zp` set), via
    /// [`redact_declaration_key`](crate::redact::redact_declaration_key)'s own final pass — a
    /// manifest-controlled name has no credential shape to trigger the redaction above, but could
    /// otherwise forge a whole `tracing` log line or terminal escape sequence verbatim (#1469).
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::PackageName;
    ///
    /// let name = PackageName::new("com.google.guava:guava");
    /// assert_eq!(name.for_tracing(), "com.google.guava:guava");
    ///
    /// let name = PackageName::new("com.google.guava:deploy:TOKEN@git.internal.corp");
    /// assert_eq!(name.for_tracing(), "***@git.internal.corp");
    ///
    /// let name = PackageName::new("lodash\nERROR deps_lsp: FORGED\x1b[31mRED");
    /// assert_eq!(name.for_tracing(), "lodash ERROR deps_lsp: FORGED [31mRED");
    /// ```
    #[must_use]
    pub fn for_tracing(&self) -> String {
        crate::redact::redact_declaration_key(&self.0).into_owned()
    }
}

impl fmt::Debug for PackageName {
    /// Forwards to the redacted text's own `Debug` (a quoted string), not a struct-wrapper
    /// rendering — mirrors [`crate::redact::RedactedName`]'s `Debug` impl. This makes
    /// `?name`, and any `#[derive(Debug)]` struct/enum that embeds a `PackageName`, safe by
    /// construction against the credential-in-a-name-shaped-field case [`Self::for_tracing`]
    /// documents (#1217).
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&crate::redact::redact_declaration_key(&self.0), f)
    }
}

impl From<String> for PackageName {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for PackageName {
    fn from(value: &str) -> Self {
        Self(value.to_string())
    }
}

impl AsRef<str> for PackageName {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

/// Enables `&str` lookups into `HashMap<PackageName, _>`/`HashSet<PackageName>`.
///
/// Sound because derived `Hash`/`Eq` on `PackageName(String)` delegate to
/// `String`'s implementations, which in turn are defined to match `str`'s
/// exactly (`String: Borrow<str>` in `std` rests on the same guarantee) — so
/// `PackageName` and the `str` it borrows always hash and compare equal.
impl Borrow<str> for PackageName {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl PartialEq<str> for PackageName {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<&str> for PackageName {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

/// A formatter-normalized package lookup key.
///
/// A dependency has two spellings: the declared [`PackageName`] and the ecosystem's normalized
/// form (PyPI folds `My_Pkg` to `my-pkg`, NuGet and Composer fold case). A value of this type
/// is the second one: it is produced only by
/// [`NormalizeName::normalize_package_name`]
/// (or [`PackageKey::new`]), so a map keyed by it cannot be probed with the declared spelling
/// by accident, and a function taking one cannot be handed `dep.name().as_str()`. Deliberately
/// no `Borrow<str>` and no public constructor.
///
/// This guards against passing the wrong spelling, not against a wrong formatter:
/// [`PackageNaming`] is public and unsealed, so any
/// implementation can mint a key from an arbitrary string, and nothing binds a key to the
/// ecosystem whose formatter produced it.
///
/// `Debug` redacts like [`PackageName`]'s, since the text derives from a manifest name.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::{NormalizeName, PackageNaming};
/// use deps_core::PackageName;
///
/// struct Lowercase;
/// impl PackageNaming for Lowercase {
///     fn normalized_spelling(&self, name: &PackageName) -> String {
///         name.as_str().to_lowercase()
///     }
/// }
///
/// let key = Lowercase.normalize_package_name(&PackageName::new("Serde"));
/// assert_eq!(key.as_str(), "serde");
/// ```
///
/// Neither a raw string nor a hand-built value is accepted where a key is expected:
///
/// ```compile_fail
/// use deps_core::NormalizedName;
///
/// let _: NormalizedName = NormalizedName::new("serde".to_string());
/// ```
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct NormalizedName(String);

impl NormalizedName {
    /// Wraps a spelling a formatter produced; reachable only through
    /// [`NormalizeName`].
    pub(crate) const fn new(spelling: String) -> Self {
        Self(spelling)
    }

    /// A key spelled as given, for fixtures that stand in for a formatter's output.
    #[cfg(any(test, feature = "test-util"))]
    #[must_use]
    pub fn for_test(spelling: impl Into<String>) -> Self {
        Self(spelling.into())
    }

    /// The normalized spelling.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the key, returning the normalized spelling.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl fmt::Debug for NormalizedName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&crate::redact::redact_declaration_key(&self.0), f)
    }
}

/// A dependency's two lookup spellings, bound together at construction.
///
/// Every per-package cache the LSP and CLI layers consult is keyed by the ecosystem-normalized
/// spelling, while registry requests and edits use the declared one. A `PackageKey` carries both
/// halves, derived from one [`PackageName`] through one formatter in a single call, so a
/// consumer can no longer pair one dependency's declared name with another's normalized key.
/// Functions that need the normalized spelling take a `&PackageKey` (or a
/// [`NormalizedName`]) instead of a `&str`, so `dep.name().as_str()` stops compiling there.
///
/// This is misuse-resistant, not unforgeable: the fields are private and there is no `From`,
/// `Default` or `Deserialize`, but [`Self::new`] trusts the caller that `naming` is the
/// document's own formatter, and any [`PackageNaming`]
/// implementation can mint any normalized spelling.
///
/// # Examples
///
/// ```
/// use deps_core::lsp_helpers::PackageNaming;
/// use deps_core::{NormalizedName, PackageKey, PackageName};
/// use std::collections::HashMap;
///
/// struct Lowercase;
/// impl PackageNaming for Lowercase {
///     fn normalized_spelling(&self, name: &PackageName) -> String {
///         name.as_str().to_lowercase()
///     }
/// }
///
/// let key = PackageKey::new(&PackageName::new("Flask"), &Lowercase);
/// assert_eq!(key.declared().as_str(), "Flask");
/// assert_eq!(key.normalized().as_str(), "flask");
///
/// let mut cache: HashMap<NormalizedName, u32> = HashMap::new();
/// cache.insert(key.normalized().clone(), 3);
/// assert_eq!(cache.get(key.normalized()), Some(&3));
/// ```
///
/// A struct literal does not compile, so a key cannot be assembled from unrelated halves:
///
/// ```compile_fail
/// use deps_core::lsp_helpers::{NormalizeName, PackageNaming};
/// use deps_core::{PackageKey, PackageName};
///
/// struct Identity;
/// impl PackageNaming for Identity {}
///
/// let declared = PackageName::new("serde");
/// let normalized = Identity.normalize_package_name(&declared);
/// let _ = PackageKey { declared, normalized };
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct PackageKey {
    declared: PackageName,
    normalized: NormalizedName,
}

impl PackageKey {
    /// Derives both spellings of `declared` through `naming`.
    ///
    /// The caller asserts that `naming` is the formatter of the document `declared` came from.
    #[must_use]
    pub fn new(declared: &PackageName, naming: &(impl PackageNaming + ?Sized)) -> Self {
        Self {
            declared: declared.clone(),
            normalized: naming.normalize_package_name(declared),
        }
    }

    /// The name as the manifest spells it.
    #[must_use]
    pub const fn declared(&self) -> &PackageName {
        &self.declared
    }

    /// The ecosystem-normalized spelling.
    #[must_use]
    pub const fn normalized(&self) -> &NormalizedName {
        &self.normalized
    }
}

/// A package name that failed a [`PackageNaming::validate_package_name`] lint.
///
/// This is not a construction-time gate — [`PackageName::new`] stays infallible — it
/// only carries *why* a name looks wrong so an LSP diagnostic can say something more
/// specific than "invalid name".
///
/// Also the payload of [`DepsError::InvalidPackageName`] (#1514): `deps-go`'s
/// `validate_module_path` returns this type directly, propagated into `DepsError` via
/// `#[from]`, so a malformed Go module path shares this same "why was the name rejected"
/// carrier instead of a second, ecosystem-local error type.
///
/// [`PackageNaming::validate_package_name`]: crate::lsp_helpers::PackageNaming::validate_package_name
/// [`DepsError::InvalidPackageName`]: crate::DepsError::InvalidPackageName
///
/// # Examples
///
/// ```
/// use deps_core::InvalidPackageName;
///
/// let err = InvalidPackageName::new("name is longer than 214 characters");
/// assert_eq!(err.reason(), "name is longer than 214 characters");
/// assert_eq!(err.to_string(), "name is longer than 214 characters");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("{0}")]
pub struct InvalidPackageName(std::borrow::Cow<'static, str>);

impl InvalidPackageName {
    /// Creates an `InvalidPackageName` carrying `reason` as the explanation.
    pub fn new(reason: impl Into<std::borrow::Cow<'static, str>>) -> Self {
        Self(reason.into())
    }

    /// Returns why the name was rejected.
    #[must_use]
    pub fn reason(&self) -> &str {
        &self.0
    }
}

/// A version requirement string as it appears in a manifest file.
///
/// This is deliberately permissive: it stores whatever bytes the manifest
/// contained (e.g. `"^1.0"`, `">=2.0,<3.0"`, `"*"`), including the empty
/// string. No parsing, validation, trimming, or normalization is performed
/// by this type — ecosystems that need to parse a requirement (via `semver`,
/// `node-semver`, `pep440_rs`, etc.) do so from [`VersionReq::as_str`], not
/// from this type. Note that `deps-go`'s `GoDependency.version` also uses this
/// type even though it holds an exact pinned version (e.g. `"v1.9.1"`), not a
/// range or constraint — Go modules don't have a separate "requirement"
/// concept, so the exact version doubles as the requirement.
///
/// # Examples
///
/// ```
/// use deps_core::VersionReq;
///
/// let req = VersionReq::new("^1.0");
/// assert_eq!(req.as_str(), "^1.0");
/// assert_eq!(req, "^1.0");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct VersionReq(String);

impl VersionReq {
    /// Wraps `value` as a `VersionReq`, unchanged.
    ///
    /// This never fails and never modifies its input: an empty string is a
    /// valid `VersionReq`, as is a string with surrounding whitespace.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::VersionReq;
    ///
    /// let req = VersionReq::new(String::from(">=1.0"));
    /// assert_eq!(req.as_str(), ">=1.0");
    /// ```
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// Returns the version requirement as a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::VersionReq;
    ///
    /// let req = VersionReq::new("~1.2");
    /// assert_eq!(req.as_str(), "~1.2");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the `VersionReq`, returning the wrapped `String`.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::VersionReq;
    ///
    /// let req = VersionReq::new("~1.2");
    /// let owned: String = req.into_string();
    /// assert_eq!(owned, "~1.2");
    /// ```
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl fmt::Display for VersionReq {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<String> for VersionReq {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for VersionReq {
    fn from(value: &str) -> Self {
        Self(value.to_string())
    }
}

impl AsRef<str> for VersionReq {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl PartialEq<str> for VersionReq {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<&str> for VersionReq {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

/// A concrete, resolved version string as returned by a registry.
///
/// This is deliberately permissive: it stores whatever bytes the registry
/// returned (e.g. `"1.2.3"`, `"2.0.0-beta.1"`), including the empty string.
/// No parsing, validation, trimming, or normalization is performed by this
/// type — ecosystems that need to parse a version (via `semver`,
/// `node-semver`, `pep440_rs`, etc.) do so from [`ConcreteVersion::as_str`],
/// not from this type. It is distinct from [`VersionReq`]: a `VersionReq` is
/// a constraint written in a manifest (`"^1.0"`), while a `ConcreteVersion`
/// is a single resolved version (`"1.0.4"`).
///
/// # Examples
///
/// ```
/// use deps_core::ConcreteVersion;
///
/// let version = ConcreteVersion::new("1.2.3");
/// assert_eq!(version.as_str(), "1.2.3");
/// assert_eq!(version, "1.2.3");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ConcreteVersion(String);

impl ConcreteVersion {
    /// Wraps `value` as a `ConcreteVersion`, unchanged.
    ///
    /// This never fails and never modifies its input: an empty string is a
    /// valid `ConcreteVersion`, as is a string with surrounding whitespace.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::ConcreteVersion;
    ///
    /// let version = ConcreteVersion::new(String::from("1.0.0"));
    /// assert_eq!(version.as_str(), "1.0.0");
    /// ```
    pub fn new(value: impl Into<String>) -> Self {
        Self(value.into())
    }

    /// Returns the concrete version as a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::ConcreteVersion;
    ///
    /// let version = ConcreteVersion::new("4.5.6");
    /// assert_eq!(version.as_str(), "4.5.6");
    /// ```
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the `ConcreteVersion`, returning the wrapped `String`.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::ConcreteVersion;
    ///
    /// let version = ConcreteVersion::new("4.5.6");
    /// let owned: String = version.into_string();
    /// assert_eq!(owned, "4.5.6");
    /// ```
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }

    /// Whether `self` and `other` are the same version once semver build metadata
    /// (`+...`, which carries no precedence) is ignored.
    ///
    /// Follows SemVer 2.0.0 precedence only; ecosystems where a `+N` suffix denotes a
    /// distinct release (e.g. pub.dev build numbers) are out of scope.
    ///
    /// # Examples
    ///
    /// ```
    /// use deps_core::ConcreteVersion;
    ///
    /// let resolved = ConcreteVersion::new("1.2.3");
    /// assert!(resolved.eq_ignoring_build_metadata(&ConcreteVersion::new("1.2.3+build.7")));
    /// assert!(!resolved.eq_ignoring_build_metadata(&ConcreteVersion::new("1.2.4+build.7")));
    /// ```
    #[must_use]
    pub fn eq_ignoring_build_metadata(&self, other: &Self) -> bool {
        strip_build_metadata(&self.0) == strip_build_metadata(&other.0)
    }
}

impl fmt::Display for ConcreteVersion {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl From<String> for ConcreteVersion {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl From<&str> for ConcreteVersion {
    fn from(value: &str) -> Self {
        Self(value.to_string())
    }
}

impl AsRef<str> for ConcreteVersion {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl PartialEq<str> for ConcreteVersion {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<&str> for ConcreteVersion {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

/// `version` without its semver build metadata (`+...`), which carries no precedence.
pub(crate) fn strip_build_metadata(version: &str) -> &str {
    version
        .split_once('+')
        .map_or(version, |(precedence, _)| precedence)
}

/// Length, in bytes, of an `@scope/pkg` or unscoped `pkg` name at the start of `rest`.
///
/// Follows the scoped-package grammar shared by npm-style ecosystems: the name runs up to
/// (but excludes) the first `@` or `/` after it, without mistaking a scoped name's own
/// leading `@` or inner `/` for that boundary.
///
/// Shared by `deps-npm`'s `npm:` alias parsing (issue #654) and `deps-deno`'s
/// `jsr:`/`npm:` specifier grammar (`deps_deno::specifier::parse_specifier`) — both need
/// the identical scope-aware boundary, and a per-crate reimplementation had drifted looser
/// than this one (accepting `"@/pkg"`, `"@scope/"`, and a lone `"@"` as valid names).
///
/// Returns `None` for a malformed scoped name (empty scope `"@/pkg"`, missing `/` `"@std"`,
/// or an empty package segment `"@std/"`) or an empty unscoped name (`rest` is empty, or
/// starts with `@`/`/`).
///
/// # Examples
///
/// ```
/// use deps_core::package::npm_style_name_boundary;
///
/// assert_eq!(npm_style_name_boundary("react@^18.0.0"), Some(5));
/// assert_eq!(npm_style_name_boundary("@scope/pkg@^1.0.0"), Some(10));
/// assert_eq!(npm_style_name_boundary("@scope/pkg"), Some(10));
/// assert_eq!(npm_style_name_boundary("@/pkg"), None);
/// assert_eq!(npm_style_name_boundary("@scope/"), None);
/// assert_eq!(npm_style_name_boundary("@"), None);
/// assert_eq!(npm_style_name_boundary(""), None);
/// ```
#[expect(
    clippy::string_slice,
    reason = "slash_rel comes from str::find('/'), an ASCII byte, so slash_rel + 1 is always \
              a char boundary"
)]
#[must_use]
pub fn npm_style_name_boundary(rest: &str) -> Option<usize> {
    if let Some(after_at) = rest.strip_prefix('@') {
        let slash_rel = after_at.find('/')?;
        if slash_rel == 0 {
            return None; // empty scope, e.g. "@/pkg"
        }
        let after_slash = &after_at[slash_rel + 1..];
        let pkg_end_rel = after_slash.find(['@', '/']).unwrap_or(after_slash.len());
        if pkg_end_rel == 0 {
            return None; // empty pkg name, e.g. "@scope/"
        }
        Some(1 + slash_rel + 1 + pkg_end_rel)
    } else {
        let end = rest.find(['@', '/']).unwrap_or(rest.len());
        (end > 0).then_some(end)
    }
}

#[cfg(test)]
mod tests {
    use super::{ConcreteVersion, PackageKey, PackageName, VersionReq};
    use crate::lsp_helpers::PackageNaming;
    use std::collections::HashMap;

    struct Lowercase;
    impl PackageNaming for Lowercase {
        fn normalized_spelling(&self, name: &PackageName) -> String {
            name.as_str().to_lowercase()
        }
    }

    #[test]
    fn case_variant_declared_names_share_one_normalized_key() {
        let upper = PackageKey::new(&PackageName::new("Flask"), &Lowercase);
        let lower = PackageKey::new(&PackageName::new("flask"), &Lowercase);
        assert_ne!(
            upper, lower,
            "PackageKey equality includes the declared spelling"
        );
        assert_eq!(upper.normalized(), lower.normalized());

        let mut map = HashMap::new();
        map.insert(upper.normalized().clone(), "value");
        assert_eq!(map.get(lower.normalized()), Some(&"value"));
    }

    #[test]
    fn eq_ignoring_build_metadata_cases() {
        for (a, b, expected) in [
            ("1.2.3", "1.2.3", true),
            ("1.2.3+a", "1.2.3+b", true),
            ("1.2.3", "1.2.3+b", true),
            ("1.2.3+a", "1.2.3", true),
            ("1.2.3", "1.2.4+b", false),
            ("1.2.3-beta.1", "1.2.3+b", false),
            ("1.2.3-beta.1+a", "1.2.3-beta.1+b", true),
            ("1.2.3+", "1.2.3", true),
            ("1.2.3+a+b", "1.2.3+c", true),
            ("1.2.3+a+b", "1.2.4+a+b", false),
        ] {
            assert_eq!(
                ConcreteVersion::new(a).eq_ignoring_build_metadata(&ConcreteVersion::new(b)),
                expected,
                "{a} vs {b}"
            );
        }
    }

    #[test]
    fn package_name_round_trips_empty_string() {
        let name = PackageName::new("");
        assert_eq!(name.as_str(), "");
        assert_eq!(name, "");
    }

    #[test]
    fn package_name_round_trips_surrounding_whitespace() {
        let name = PackageName::new("  serde  ");
        assert_eq!(name.as_str(), "  serde  ");
        assert_eq!(name, "  serde  ");
    }

    #[test]
    fn package_name_round_trips_non_ascii() {
        let name = PackageName::new("パッケージ");
        assert_eq!(name.as_str(), "パッケージ");
        assert_eq!(name, "パッケージ");
    }

    #[test]
    fn package_name_compares_byte_wise_like_string() {
        assert_ne!(PackageName::new("Foo"), PackageName::new("foo"));
        assert_eq!(
            PackageName::new("Foo") == PackageName::new("foo"),
            "Foo" == "foo"
        );
    }

    #[test]
    fn package_name_into_string_roundtrip() {
        let original = String::from("tokio");
        let name = PackageName::new(original.clone());
        assert_eq!(name.into_string(), original);
    }

    #[test]
    fn package_name_debug_redacts_credential_shape() {
        let name = PackageName::new("com.google.guava:deploy:TOKEN@git.internal.corp");
        assert_eq!(format!("{name:?}"), "\"***@git.internal.corp\"");
    }

    #[test]
    fn package_name_debug_leaves_ordinary_name_untouched() {
        let name = PackageName::new("com.google.guava:guava");
        assert_eq!(format!("{name:?}"), "\"com.google.guava:guava\"");
    }

    /// #1469 (CWE-117/CWE-150): a manifest-controlled name with no credential shape at all still
    /// carries `\n`/`\r`/ESC through untouched, letting it forge a fake `tracing` log line or
    /// terminal escape sequence in `deps-lsp`'s stderr output. Adapted from the issue's PoC.
    #[test]
    fn for_tracing_neutralizes_control_characters() {
        for forged in [
            "lodash\nERROR deps_lsp: FORGED\x1b[31mRED",
            "ok\r\nWARN forged2",
        ] {
            let rendered = PackageName::new(forged).for_tracing();
            assert!(
                !rendered.contains('\n'),
                "{rendered:?} must not contain \\n"
            );
            assert!(
                !rendered.contains('\r'),
                "{rendered:?} must not contain \\r"
            );
            assert!(
                !rendered.contains('\x1b'),
                "{rendered:?} must not contain ESC"
            );
        }
    }

    /// #1469: the same sweep must also apply once the credential-shape gate fires, so a
    /// control character hiding past a redacted credential can't survive either.
    #[test]
    fn for_tracing_neutralizes_control_characters_alongside_credential_redaction() {
        let rendered =
            PackageName::new("com.google.guava:deploy:TOKEN@git.internal\ncorp").for_tracing();
        assert!(!rendered.contains('\n'));
        assert!(!rendered.contains("TOKEN"));
    }

    #[test]
    fn package_name_hashmap_reachable_by_str_and_by_package_name() {
        use std::collections::HashMap;

        let mut map: HashMap<PackageName, u32> = HashMap::new();
        map.insert(PackageName::new("serde"), 1);

        assert_eq!(map.get("serde"), Some(&1));
        assert_eq!(map.get(&PackageName::new("serde")), Some(&1));
    }

    #[test]
    fn version_req_round_trips_empty_string() {
        let req = VersionReq::new("");
        assert_eq!(req.as_str(), "");
        assert_eq!(req, "");
    }

    #[test]
    fn version_req_round_trips_surrounding_whitespace() {
        let req = VersionReq::new("  ^1.0  ");
        assert_eq!(req.as_str(), "  ^1.0  ");
        assert_eq!(req, "  ^1.0  ");
    }

    #[test]
    fn version_req_round_trips_non_ascii() {
        let req = VersionReq::new("非対応");
        assert_eq!(req.as_str(), "非対応");
        assert_eq!(req, "非対応");
    }

    #[test]
    fn version_req_compares_byte_wise_like_string() {
        assert_ne!(VersionReq::new("^1.0"), VersionReq::new("^1.0 "));
    }

    #[test]
    fn version_req_into_string_roundtrip() {
        let original = String::from("~2.3.4");
        let req = VersionReq::new(original.clone());
        assert_eq!(req.into_string(), original);
    }

    #[test]
    fn concrete_version_round_trips_empty_string() {
        let version = ConcreteVersion::new("");
        assert_eq!(version.as_str(), "");
        assert_eq!(version, "");
    }

    #[test]
    fn concrete_version_round_trips_surrounding_whitespace() {
        let version = ConcreteVersion::new("  1.0.0  ");
        assert_eq!(version.as_str(), "  1.0.0  ");
        assert_eq!(version, "  1.0.0  ");
    }

    #[test]
    fn concrete_version_round_trips_non_ascii() {
        let version = ConcreteVersion::new("バージョン");
        assert_eq!(version.as_str(), "バージョン");
        assert_eq!(version, "バージョン");
    }

    #[test]
    fn concrete_version_compares_byte_wise_like_string() {
        assert_ne!(
            ConcreteVersion::new("1.0.0"),
            ConcreteVersion::new("1.0.0 ")
        );
    }

    #[test]
    fn concrete_version_into_string_roundtrip() {
        let original = String::from("2.3.4");
        let version = ConcreteVersion::new(original.clone());
        assert_eq!(version.into_string(), original);
    }
}