sublime_pkg_tools 0.0.27

Package and version management toolkit for Node.js projects with changeset support
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
//! Version consistency audit section for analyzing internal dependency version alignment.
//!
//! **What**: Provides functionality to audit version consistency of internal (workspace)
//! dependencies, detecting cases where the same internal package is depended upon with
//! different version specifications across the workspace.
//!
//! **How**: Analyzes all packages in the workspace and their internal dependencies,
//! tracking which version specifications are used for each internal package. Identifies
//! inconsistencies where multiple different version specs are declared for the same
//! internal package, and recommends the most appropriate consistent version.
//!
//! **Why**: To ensure internal dependency versions are consistent across the workspace,
//! which helps prevent version conflicts, simplifies dependency management, and ensures
//! all packages work with compatible versions of internal dependencies.

use crate::audit::issue::{AuditIssue, IssueCategory, IssueSeverity};
use crate::audit::sections::dependencies::VersionUsage;
use crate::config::PackageToolsConfig;
use crate::error::{AuditError, AuditResult};
use crate::types::PackageInfo;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Audit section containing version consistency analysis results.
///
/// Contains detailed information about version inconsistencies found across
/// internal dependencies in the workspace, with recommendations for resolution.
///
/// # Examples
///
/// ## Accessing consistency statistics
///
/// ```rust,ignore
/// use sublime_pkg_tools::audit::VersionConsistencyAuditSection;
///
/// # fn example(section: VersionConsistencyAuditSection) {
/// println!("Inconsistencies found: {}", section.inconsistencies.len());
/// println!("Issues found: {}", section.issues.len());
///
/// for inconsistency in &section.inconsistencies {
///     println!("Package {} has {} different versions used",
///         inconsistency.package_name,
///         inconsistency.versions_used.len());
/// }
/// # }
/// ```
///
/// ## Checking for critical issues
///
/// ```rust,ignore
/// use sublime_pkg_tools::audit::VersionConsistencyAuditSection;
///
/// # fn example(section: VersionConsistencyAuditSection) {
/// let critical_issues: Vec<_> = section.issues.iter()
///     .filter(|issue| issue.is_critical())
///     .collect();
///
/// if !critical_issues.is_empty() {
///     println!("Found {} critical version consistency issues", critical_issues.len());
/// }
/// # }
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VersionConsistencyAuditSection {
    /// List of version inconsistencies detected across internal dependencies.
    ///
    /// Each inconsistency represents an internal package that is depended upon
    /// with different version specifications across the workspace.
    pub inconsistencies: Vec<VersionInconsistency>,

    /// List of audit issues generated from the consistency analysis.
    ///
    /// Issues are created based on configuration:
    /// - Critical issues if `fail_on_inconsistency` is enabled
    /// - Warning issues if `warn_on_inconsistency` is enabled
    pub issues: Vec<AuditIssue>,
}

impl VersionConsistencyAuditSection {
    /// Creates an empty version consistency audit section.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::audit::VersionConsistencyAuditSection;
    ///
    /// let section = VersionConsistencyAuditSection::empty();
    /// assert_eq!(section.inconsistencies.len(), 0);
    /// assert_eq!(section.issues.len(), 0);
    /// ```
    #[must_use]
    pub fn empty() -> Self {
        Self { inconsistencies: Vec::new(), issues: Vec::new() }
    }

    /// Returns whether any inconsistencies were found.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::audit::VersionConsistencyAuditSection;
    ///
    /// let section = VersionConsistencyAuditSection::empty();
    /// assert!(!section.has_inconsistencies());
    /// ```
    #[must_use]
    pub fn has_inconsistencies(&self) -> bool {
        !self.inconsistencies.is_empty()
    }

    /// Returns the number of critical issues found.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::audit::VersionConsistencyAuditSection;
    ///
    /// let section = VersionConsistencyAuditSection::empty();
    /// assert_eq!(section.critical_issue_count(), 0);
    /// ```
    #[must_use]
    pub fn critical_issue_count(&self) -> usize {
        self.issues.iter().filter(|issue| issue.is_critical()).count()
    }

    /// Returns the number of warning issues found.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::audit::VersionConsistencyAuditSection;
    ///
    /// let section = VersionConsistencyAuditSection::empty();
    /// assert_eq!(section.warning_issue_count(), 0);
    /// ```
    #[must_use]
    pub fn warning_issue_count(&self) -> usize {
        self.issues.iter().filter(|issue| issue.is_warning()).count()
    }

    /// Returns the number of informational issues found.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::audit::VersionConsistencyAuditSection;
    ///
    /// let section = VersionConsistencyAuditSection::empty();
    /// assert_eq!(section.info_issue_count(), 0);
    /// ```
    #[must_use]
    pub fn info_issue_count(&self) -> usize {
        self.issues.iter().filter(|issue| issue.is_info()).count()
    }

    /// Returns inconsistencies for a specific internal package.
    ///
    /// # Arguments
    ///
    /// * `package_name` - Name of the internal package to find inconsistencies for
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::audit::VersionConsistencyAuditSection;
    ///
    /// # fn example(section: VersionConsistencyAuditSection) {
    /// if let Some(inconsistency) = section.inconsistency_for_package("@myorg/core") {
    ///     println!("Found inconsistency for @myorg/core");
    ///     println!("Recommended version: {}", inconsistency.recommended_version);
    /// }
    /// # }
    /// ```
    #[must_use]
    pub fn inconsistency_for_package(&self, package_name: &str) -> Option<&VersionInconsistency> {
        self.inconsistencies.iter().find(|i| i.package_name == package_name)
    }
}

/// Represents a version inconsistency for an internal package.
///
/// Contains information about different version specifications used across
/// the workspace for a single internal package, along with a recommended
/// version for consistency.
///
/// # Examples
///
/// ## Creating an inconsistency manually
///
/// ```rust
/// use sublime_pkg_tools::audit::{VersionInconsistency, VersionUsage};
///
/// let inconsistency = VersionInconsistency {
///     package_name: "@myorg/core".to_string(),
///     versions_used: vec![
///         VersionUsage {
///             package_name: "app-a".to_string(),
///             version_spec: "^1.0.0".to_string(),
///         },
///         VersionUsage {
///             package_name: "app-b".to_string(),
///             version_spec: "^1.1.0".to_string(),
///         },
///     ],
///     recommended_version: "^1.1.0".to_string(),
/// };
///
/// assert_eq!(inconsistency.version_count(), 2);
/// ```
///
/// ## Describing the inconsistency
///
/// ```rust
/// use sublime_pkg_tools::audit::{VersionInconsistency, VersionUsage};
///
/// let inconsistency = VersionInconsistency {
///     package_name: "@myorg/utils".to_string(),
///     versions_used: vec![
///         VersionUsage {
///             package_name: "pkg-a".to_string(),
///             version_spec: "workspace:*".to_string(),
///         },
///         VersionUsage {
///             package_name: "pkg-b".to_string(),
///             version_spec: "^2.0.0".to_string(),
///         },
///     ],
///     recommended_version: "workspace:*".to_string(),
/// };
///
/// let description = inconsistency.describe();
/// assert!(description.contains("@myorg/utils"));
/// assert!(description.contains("pkg-a"));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct VersionInconsistency {
    /// Name of the internal package with inconsistent versions.
    ///
    /// This is the package that is being depended upon with different
    /// version specifications across the workspace.
    pub package_name: String,

    /// List of version specifications used across different packages.
    ///
    /// Each entry represents a package and the version spec it uses
    /// for this internal dependency.
    pub versions_used: Vec<VersionUsage>,

    /// Recommended version specification for consistency.
    ///
    /// This is typically:
    /// - "workspace:*" if any package uses it (preferred for monorepos)
    /// - The most recent semver version if specified versions are used
    /// - The most commonly used version if no clear preference
    pub recommended_version: String,
}

impl VersionInconsistency {
    /// Returns the number of different version specifications.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::audit::{VersionInconsistency, VersionUsage};
    ///
    /// let inconsistency = VersionInconsistency {
    ///     package_name: "@myorg/core".to_string(),
    ///     versions_used: vec![
    ///         VersionUsage {
    ///             package_name: "app-a".to_string(),
    ///             version_spec: "^1.0.0".to_string(),
    ///         },
    ///         VersionUsage {
    ///             package_name: "app-b".to_string(),
    ///             version_spec: "^1.1.0".to_string(),
    ///         },
    ///     ],
    ///     recommended_version: "^1.1.0".to_string(),
    /// };
    ///
    /// assert_eq!(inconsistency.version_count(), 2);
    /// ```
    #[must_use]
    pub fn version_count(&self) -> usize {
        self.versions_used.len()
    }

    /// Returns a human-readable description of the inconsistency.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::audit::{VersionInconsistency, VersionUsage};
    ///
    /// let inconsistency = VersionInconsistency {
    ///     package_name: "@myorg/utils".to_string(),
    ///     versions_used: vec![
    ///         VersionUsage {
    ///             package_name: "pkg-a".to_string(),
    ///             version_spec: "^1.0.0".to_string(),
    ///         },
    ///     ],
    ///     recommended_version: "^1.0.0".to_string(),
    /// };
    ///
    /// let description = inconsistency.describe();
    /// assert!(description.contains("@myorg/utils"));
    /// ```
    #[must_use]
    pub fn describe(&self) -> String {
        let version_details: Vec<String> = self
            .versions_used
            .iter()
            .map(|v| format!("{} ({})", v.package_name, v.version_spec))
            .collect();

        format!(
            "Package '{}' is used with {} different versions: {}",
            self.package_name,
            self.version_count(),
            version_details.join(", ")
        )
    }

    /// Returns the unique version specifications used.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use sublime_pkg_tools::audit::{VersionInconsistency, VersionUsage};
    ///
    /// let inconsistency = VersionInconsistency {
    ///     package_name: "@myorg/core".to_string(),
    ///     versions_used: vec![
    ///         VersionUsage {
    ///             package_name: "app-a".to_string(),
    ///             version_spec: "^1.0.0".to_string(),
    ///         },
    ///         VersionUsage {
    ///             package_name: "app-b".to_string(),
    ///             version_spec: "^1.0.0".to_string(),
    ///         },
    ///         VersionUsage {
    ///             package_name: "app-c".to_string(),
    ///             version_spec: "^1.1.0".to_string(),
    ///         },
    ///     ],
    ///     recommended_version: "^1.1.0".to_string(),
    /// };
    ///
    /// let unique_versions = inconsistency.unique_versions();
    /// assert_eq!(unique_versions.len(), 2);
    /// assert!(unique_versions.contains(&"^1.0.0".to_string()));
    /// assert!(unique_versions.contains(&"^1.1.0".to_string()));
    /// ```
    #[must_use]
    pub fn unique_versions(&self) -> Vec<String> {
        let mut versions: Vec<String> =
            self.versions_used.iter().map(|v| v.version_spec.clone()).collect();
        versions.sort();
        versions.dedup();
        versions
    }
}

/// Audits version consistency of internal dependencies across the workspace.
///
/// This function analyzes all internal dependencies across packages in the workspace
/// and identifies cases where the same internal package is depended upon with different
/// version specifications. It generates issues based on configuration settings.
///
/// # Arguments
///
/// * `packages` - List of all packages in the workspace
/// * `internal_package_names` - Set of internal package names to check for consistency
/// * `config` - Configuration controlling issue severity
///
/// # Returns
///
/// Returns a `VersionConsistencyAuditSection` containing detected inconsistencies and
/// generated audit issues.
///
/// # Errors
///
/// This function is currently infallible and returns `Ok` in all cases. The error
/// return type is maintained for API consistency with other audit functions.
///
/// # Examples
///
/// ```rust,ignore
/// use sublime_pkg_tools::audit::audit_version_consistency;
/// use sublime_pkg_tools::config::PackageToolsConfig;
/// use std::collections::HashSet;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let packages = vec![/* discovered packages */];
/// let internal_names: HashSet<String> = packages.iter()
///     .map(|p| p.name().to_string())
///     .collect();
/// let config = PackageToolsConfig::default();
///
/// let section = audit_version_consistency(&packages, &internal_names, &config).await?;
///
/// println!("Found {} inconsistencies", section.inconsistencies.len());
/// for inconsistency in &section.inconsistencies {
///     println!("  - {}", inconsistency.describe());
/// }
/// # Ok(())
/// # }
/// ```
///
/// ## With custom configuration
///
/// ```rust,ignore
/// use sublime_pkg_tools::audit::audit_version_consistency;
/// use sublime_pkg_tools::config::PackageToolsConfig;
/// use std::collections::HashSet;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let packages = vec![/* discovered packages */];
/// let internal_names: HashSet<String> = packages.iter()
///     .map(|p| p.name().to_string())
///     .collect();
///
/// let mut config = PackageToolsConfig::default();
/// config.audit.version_consistency.fail_on_inconsistency = true;
///
/// let section = audit_version_consistency(&packages, &internal_names, &config).await?;
///
/// // Critical issues will be generated with fail_on_inconsistency = true
/// if section.critical_issue_count() > 0 {
///     eprintln!("Critical version consistency issues found!");
/// }
/// # Ok(())
/// # }
/// ```
pub async fn audit_version_consistency(
    packages: &[PackageInfo],
    internal_package_names: &std::collections::HashSet<String>,
    config: &PackageToolsConfig,
) -> AuditResult<VersionConsistencyAuditSection> {
    // If the section is disabled, return empty
    if !config.audit.sections.version_consistency {
        return Err(AuditError::SectionDisabled { section: "version_consistency".to_string() });
    }

    // Track internal dependency usage across all packages
    let internal_usage = collect_internal_dependency_usage(packages, internal_package_names);

    // Detect inconsistencies
    let inconsistencies = detect_inconsistencies(internal_usage);

    // Generate issues based on configuration
    let issues = generate_issues(&inconsistencies, config);

    Ok(VersionConsistencyAuditSection { inconsistencies, issues })
}

/// Collects all internal dependency usage across packages.
///
/// Returns a map from internal package name to all version usages across the workspace.
fn collect_internal_dependency_usage(
    packages: &[PackageInfo],
    internal_package_names: &std::collections::HashSet<String>,
) -> HashMap<String, Vec<VersionUsage>> {
    let mut usage_map: HashMap<String, Vec<VersionUsage>> = HashMap::new();

    for package in packages {
        let package_name = package.name();

        // Get all dependencies from package.json - we need to access raw dependencies
        // to include workspace protocol dependencies which are filtered out by all_dependencies()
        let mut all_deps: Vec<(String, String)> = Vec::new();

        // Collect from all dependency types
        if let Some(deps) = &package.package_json().dependencies {
            all_deps.extend(deps.iter().map(|(k, v)| (k.clone(), v.clone())));
        }
        if let Some(deps) = &package.package_json().dev_dependencies {
            all_deps.extend(deps.iter().map(|(k, v)| (k.clone(), v.clone())));
        }
        if let Some(deps) = &package.package_json().peer_dependencies {
            all_deps.extend(deps.iter().map(|(k, v)| (k.clone(), v.clone())));
        }
        if let Some(deps) = &package.package_json().optional_dependencies {
            all_deps.extend(deps.iter().map(|(k, v)| (k.clone(), v.clone())));
        }

        for (dep_name, version_spec) in all_deps {
            // Only track internal dependencies
            if internal_package_names.contains(&dep_name) {
                // Skip self-references
                if dep_name == package_name {
                    continue;
                }

                usage_map.entry(dep_name.clone()).or_default().push(VersionUsage {
                    package_name: package_name.to_string(),
                    version_spec: version_spec.clone(),
                });
            }
        }
    }

    usage_map
}

/// Detects inconsistencies in internal dependency versions.
///
/// An inconsistency exists when an internal package is referenced with more than
/// one unique version specification across the workspace.
fn detect_inconsistencies(
    usage_map: HashMap<String, Vec<VersionUsage>>,
) -> Vec<VersionInconsistency> {
    let mut inconsistencies = Vec::new();

    for (package_name, usages) in usage_map {
        // Get unique version specifications
        let unique_versions: std::collections::HashSet<String> =
            usages.iter().map(|u| u.version_spec.clone()).collect();

        // If more than one unique version, it's an inconsistency
        if unique_versions.len() > 1 {
            // Determine recommended version
            let recommended_version = determine_recommended_version(&usages, &unique_versions);

            inconsistencies.push(VersionInconsistency {
                package_name,
                versions_used: usages,
                recommended_version,
            });
        }
    }

    // Sort by package name for consistent output
    inconsistencies.sort_by(|a, b| a.package_name.cmp(&b.package_name));

    inconsistencies
}

/// Determines the recommended version for consistency.
///
/// The logic prioritizes:
/// 1. "workspace:*" if any package uses it (best practice for monorepos)
/// 2. Most commonly used version
/// 3. Alphabetically first version as fallback
fn determine_recommended_version(
    usages: &[VersionUsage],
    unique_versions: &std::collections::HashSet<String>,
) -> String {
    // Prefer workspace protocol if any package uses it
    if unique_versions.contains("workspace:*") {
        return "workspace:*".to_string();
    }

    // Check for any workspace protocol variant
    for version in unique_versions {
        if version.starts_with("workspace:") {
            return version.clone();
        }
    }

    // Count occurrences of each version
    let mut version_counts: HashMap<String, usize> = HashMap::new();
    for usage in usages {
        *version_counts.entry(usage.version_spec.clone()).or_insert(0) += 1;
    }

    // Find the most commonly used version
    let most_common =
        version_counts.iter().max_by_key(|(_, count)| *count).map(|(version, _)| version.clone());

    // Return most common, or fallback to first alphabetically
    most_common.unwrap_or_else(|| {
        let mut versions: Vec<String> = unique_versions.iter().cloned().collect();
        versions.sort();
        versions.first().cloned().unwrap_or_default()
    })
}

/// Generates audit issues from detected inconsistencies.
///
/// Issue severity is determined by configuration:
/// - Critical if `fail_on_inconsistency` is true
/// - Warning if `warn_on_inconsistency` is true
/// - No issues if both are false
fn generate_issues(
    inconsistencies: &[VersionInconsistency],
    config: &PackageToolsConfig,
) -> Vec<AuditIssue> {
    let mut issues = Vec::new();

    let severity = if config.audit.version_consistency.fail_on_inconsistency {
        IssueSeverity::Critical
    } else if config.audit.version_consistency.warn_on_inconsistency {
        IssueSeverity::Warning
    } else {
        // If both are false, don't generate issues
        return issues;
    };

    for inconsistency in inconsistencies {
        let mut issue = AuditIssue::new(
            severity,
            IssueCategory::VersionConsistency,
            format!("Inconsistent versions for internal package '{}'", inconsistency.package_name),
            format!(
                "The internal package '{}' is referenced with {} different version specifications across the workspace. \
                 This can lead to confusion and potential runtime issues.",
                inconsistency.package_name,
                inconsistency.version_count()
            ),
        );

        // Add all affected packages
        for usage in &inconsistency.versions_used {
            issue.add_affected_package(usage.package_name.clone());
        }

        // Add suggestion
        issue.set_suggestion(format!(
            "Update all references to '{}' to use '{}' for consistency. \
             The workspace protocol (workspace:*) is recommended for internal dependencies in monorepos.",
            inconsistency.package_name, inconsistency.recommended_version
        ));

        // Add metadata
        issue.add_metadata("internal_package".to_string(), inconsistency.package_name.clone());
        issue.add_metadata(
            "recommended_version".to_string(),
            inconsistency.recommended_version.clone(),
        );
        issue.add_metadata(
            "unique_version_count".to_string(),
            inconsistency.unique_versions().len().to_string(),
        );

        // Add version details
        for (idx, usage) in inconsistency.versions_used.iter().enumerate() {
            issue.add_metadata(format!("version_{}_package", idx), usage.package_name.clone());
            issue.add_metadata(format!("version_{}_spec", idx), usage.version_spec.clone());
        }

        issues.push(issue);
    }

    issues
}