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
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
//! Version resolver implementation for package version management.
//!
//! **What**: Provides the main `VersionResolver` struct that orchestrates version resolution,
//! dependency propagation, and version application for Node.js packages in both monorepo and
//! single-package configurations.
//!
//! **How**: The resolver detects the project structure (monorepo or single package) using
//! `MonorepoDetector` from `sublime_standard_tools`, loads all packages in the workspace,
//! and provides methods for version resolution and application. It uses the configured
//! versioning strategy (independent or unified) to determine version updates.
//!
//! **Why**: To provide a unified interface for version management that automatically adapts
//! to the project structure and handles the complexity of version resolution, dependency
//! propagation, and file updates in a safe and predictable manner.

use crate::config::PackageToolsConfig;
use crate::error::{VersionError, VersionResult};
use crate::types::{Changeset, DependencyType, PackageInfo, VersioningStrategy};
use crate::version::application::ApplyResult;
use crate::version::graph::DependencyGraph;
use crate::version::propagation::DependencyPropagator;
use crate::version::resolution::{PackageUpdate, VersionResolution, resolve_versions};
use package_json::PackageJson;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use sublime_standard_tools::config::MonorepoConfig;
use sublime_standard_tools::filesystem::{AsyncFileSystem, FileSystemManager};
use sublime_standard_tools::monorepo::{MonorepoDetector, MonorepoDetectorTrait, WorkspacePackage};

/// Main version resolver for managing package versions.
///
/// The `VersionResolver` is the central component for version management in Node.js projects.
/// It automatically detects whether the project is a monorepo or single package, loads all
/// packages, and provides methods for version resolution and application.
///
/// # Type Parameters
///
/// * `F` - The filesystem implementation type, defaults to `FileSystemManager`
///
/// # Fields
///
/// * `workspace_root` - Root directory of the workspace/project
/// * `strategy` - Versioning strategy (independent or unified)
/// * `fs` - Filesystem implementation for I/O operations
/// * `config` - Complete package tools configuration
/// * `is_monorepo` - Whether the project is detected as a monorepo
///
/// # Examples
///
/// ```rust,ignore
/// use sublime_pkg_tools::version::VersionResolver;
/// use sublime_pkg_tools::config::PackageToolsConfig;
/// use sublime_standard_tools::filesystem::FileSystemManager;
/// use std::path::PathBuf;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let workspace_root = PathBuf::from("/path/to/workspace");
/// let fs = FileSystemManager::new();
/// let config = PackageToolsConfig::default();
///
/// let resolver = VersionResolver::new(
///     workspace_root,
///     fs,
///     config,
/// ).await?;
///
/// // Check if monorepo
/// if resolver.is_monorepo() {
///     println!("Detected monorepo structure");
/// } else {
///     println!("Detected single package");
/// }
///
/// // Resolve versions from changeset
/// let mut changeset = Changeset::new("main", VersionBump::Minor, vec!["production".to_string()]);
/// changeset.add_package("@myorg/package");
///
/// let resolution = resolver.resolve_versions(&changeset).await?;
/// for update in &resolution.updates {
///     println!("{}: {} -> {}", update.name, update.current_version, update.next_version);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct VersionResolver<F: AsyncFileSystem = FileSystemManager> {
    /// Root directory of the workspace/project.
    workspace_root: PathBuf,
    /// Versioning strategy (independent or unified).
    strategy: VersioningStrategy,
    /// Filesystem implementation for I/O operations.
    fs: F,
    /// Complete package tools configuration.
    config: PackageToolsConfig,
    /// Whether the project is detected as a monorepo.
    is_monorepo: bool,
}

impl VersionResolver<FileSystemManager> {
    /// Creates a new `VersionResolver` with the default filesystem.
    ///
    /// This constructor uses `FileSystemManager` from `sublime_standard_tools` for
    /// filesystem operations. It automatically detects the project structure and
    /// validates the workspace root.
    ///
    /// # Arguments
    ///
    /// * `workspace_root` - Root directory of the workspace/project (by value)
    /// * `config` - Complete package tools configuration
    ///
    /// # Returns
    ///
    /// Returns a new `VersionResolver` instance or an error if:
    /// - The workspace root does not exist
    /// - The workspace root is not a directory
    /// - Package detection fails
    ///
    /// # Errors
    ///
    /// Returns `VersionError::InvalidWorkspaceRoot` if the workspace root is invalid.
    /// Returns `VersionError::PackageJsonError` if package.json cannot be read.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::version::VersionResolver;
    /// use sublime_pkg_tools::config::PackageToolsConfig;
    /// use std::path::PathBuf;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let workspace_root = PathBuf::from(".");
    /// let config = PackageToolsConfig::default();
    ///
    /// let resolver = VersionResolver::new(workspace_root, config).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn new(workspace_root: PathBuf, config: PackageToolsConfig) -> VersionResult<Self> {
        let fs = FileSystemManager::new();
        Self::with_filesystem(workspace_root, fs, config).await
    }
}

impl<F: AsyncFileSystem + Clone + Send + Sync + 'static> VersionResolver<F> {
    /// Creates a new `VersionResolver` with a custom filesystem implementation.
    ///
    /// This constructor allows injecting a custom filesystem implementation, which is
    /// useful for testing with mock filesystems or using alternative I/O implementations.
    ///
    /// # Arguments
    ///
    /// * `workspace_root` - Root directory of the workspace/project
    /// * `fs` - Filesystem implementation for I/O operations
    /// * `config` - Complete package tools configuration
    ///
    /// # Returns
    ///
    /// Returns a new `VersionResolver` instance or an error if workspace validation fails.
    ///
    /// # Errors
    ///
    /// Returns `VersionError::InvalidWorkspaceRoot` if the workspace root is invalid.
    /// Returns `VersionError::PackageJsonError` if package.json cannot be read in single-package mode.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::version::VersionResolver;
    /// use sublime_pkg_tools::config::PackageToolsConfig;
    /// use sublime_standard_tools::filesystem::FileSystemManager;
    /// use std::path::PathBuf;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let workspace_root = PathBuf::from(".");
    /// let fs = FileSystemManager::new();
    /// let config = PackageToolsConfig::default();
    ///
    /// let resolver = VersionResolver::with_filesystem(
    ///     workspace_root,
    ///     fs,
    ///     config,
    /// ).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn with_filesystem(
        workspace_root: PathBuf,
        fs: F,
        config: PackageToolsConfig,
    ) -> VersionResult<Self> {
        // Validate workspace root exists
        if !fs.exists(&workspace_root).await {
            return Err(VersionError::InvalidWorkspaceRoot {
                path: workspace_root,
                reason: "Path does not exist".to_string(),
            });
        }

        // Build monorepo config with workspace patterns from repo.config.toml
        let monorepo_config = Self::build_monorepo_config(&config);

        // Detect if monorepo or single package
        // This will also validate that the workspace root is a valid directory
        let is_monorepo = Self::detect_monorepo(&workspace_root, &fs, &monorepo_config).await?;

        // Extract strategy from config
        let strategy = match config.version.strategy {
            crate::config::VersioningStrategy::Independent => VersioningStrategy::Independent,
            crate::config::VersioningStrategy::Unified => VersioningStrategy::Unified,
        };

        Ok(Self { workspace_root, strategy, fs, config, is_monorepo })
    }

    /// Returns whether the project is detected as a monorepo.
    ///
    /// This method provides access to the monorepo detection result, which is computed
    /// during initialization.
    ///
    /// # Returns
    ///
    /// Returns `true` if the project is a monorepo, `false` for single packages.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::version::VersionResolver;
    /// # async fn example(resolver: &VersionResolver) {
    /// if resolver.is_monorepo() {
    ///     println!("Working with a monorepo");
    /// } else {
    ///     println!("Working with a single package");
    /// }
    /// # }
    /// ```
    #[must_use]
    pub fn is_monorepo(&self) -> bool {
        self.is_monorepo
    }

    /// Returns the workspace root path.
    ///
    /// This method provides access to the workspace root directory path.
    ///
    /// # Returns
    ///
    /// Returns a reference to the workspace root path.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::version::VersionResolver;
    /// # async fn example(resolver: &VersionResolver) {
    /// let root = resolver.workspace_root();
    /// println!("Workspace root: {}", root.display());
    /// # }
    /// ```
    #[must_use]
    pub fn workspace_root(&self) -> &Path {
        &self.workspace_root
    }

    /// Returns the configured versioning strategy.
    ///
    /// This method provides access to the versioning strategy (independent or unified)
    /// that was configured for this resolver.
    ///
    /// # Returns
    ///
    /// Returns the versioning strategy.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::version::VersionResolver;
    /// # use sublime_pkg_tools::types::VersioningStrategy;
    /// # async fn example(resolver: &VersionResolver) {
    /// match resolver.strategy() {
    ///     VersioningStrategy::Independent => println!("Using independent versioning"),
    ///     VersioningStrategy::Unified => println!("Using unified versioning"),
    /// }
    /// # }
    /// ```
    #[must_use]
    pub fn strategy(&self) -> VersioningStrategy {
        self.strategy
    }

    /// Returns a reference to the filesystem implementation.
    ///
    /// This method provides access to the underlying filesystem implementation,
    /// which is useful for advanced operations or testing.
    ///
    /// # Returns
    ///
    /// Returns a reference to the filesystem.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::version::VersionResolver;
    /// # use sublime_standard_tools::filesystem::AsyncFileSystem;
    /// # async fn example(resolver: &VersionResolver) -> Result<(), Box<dyn std::error::Error>> {
    /// let fs = resolver.filesystem();
    /// let exists = fs.exists(resolver.workspace_root()).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn filesystem(&self) -> &F {
        &self.fs
    }

    /// Returns a reference to the package tools configuration.
    ///
    /// This method provides access to the complete configuration including
    /// version, dependency, changeset, and other settings.
    ///
    /// # Returns
    ///
    /// Returns a reference to the configuration.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::version::VersionResolver;
    /// # async fn example(resolver: &VersionResolver) {
    /// let config = resolver.config();
    /// println!("Default bump: {}", config.version.default_bump);
    /// # }
    /// ```
    #[must_use]
    pub fn config(&self) -> &PackageToolsConfig {
        &self.config
    }

    /// Discovers all packages in the workspace.
    ///
    /// This method loads package information for all packages in the workspace:
    /// - For monorepos: Uses `MonorepoDetector` to find all workspace packages
    /// - For single packages: Loads the single package.json at the root
    ///
    /// # Returns
    ///
    /// Returns a vector of `PackageInfo` instances, one for each package found.
    ///
    /// # Errors
    ///
    /// Returns `VersionError::PackageNotFound` if no packages are found.
    /// Returns `VersionError::PackageJsonError` if package.json files cannot be read or parsed.
    /// Returns `VersionError::FileSystemError` if filesystem operations fail.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// # use sublime_pkg_tools::version::VersionResolver;
    /// # async fn example(resolver: &VersionResolver) -> Result<(), Box<dyn std::error::Error>> {
    /// let packages = resolver.discover_packages().await?;
    /// for package in &packages {
    ///     println!("Found package: {}", package.name());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn discover_packages(&self) -> VersionResult<Vec<PackageInfo>> {
        if self.is_monorepo {
            self.discover_monorepo_packages().await
        } else {
            self.discover_single_package().await
        }
    }

    /// Builds a `MonorepoConfig` from the `PackageToolsConfig`.
    ///
    /// This method creates a `MonorepoConfig` that includes workspace patterns from
    /// the `repo.config.toml` file. It merges the project-specific patterns with
    /// the standard configuration patterns to ensure all workspace directories
    /// are discovered correctly.
    ///
    /// # Arguments
    ///
    /// * `config` - The package tools configuration containing workspace patterns
    ///
    /// # Returns
    ///
    /// Returns a `MonorepoConfig` with merged workspace patterns.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::config::PackageToolsConfig;
    /// use sublime_pkg_tools::version::VersionResolver;
    ///
    /// let config = PackageToolsConfig::default();
    /// let monorepo_config = VersionResolver::<FileSystemManager>::build_monorepo_config(&config);
    /// ```
    #[must_use]
    pub fn build_monorepo_config(config: &PackageToolsConfig) -> MonorepoConfig {
        let mut monorepo_config = config.standard_config.monorepo.clone();

        // Merge workspace patterns from repo.config.toml if available
        // These patterns are project-specific and take precedence
        if let Some(ref workspace) = config.workspace
            && !workspace.patterns.is_empty()
        {
            // Add project-specific patterns to the config
            // We add them to ensure they're included in package discovery
            for pattern in &workspace.patterns {
                if !monorepo_config.workspace_patterns.contains(pattern) {
                    monorepo_config.workspace_patterns.push(pattern.clone());
                }
            }
        }

        monorepo_config
    }

    /// Detects whether the workspace is a monorepo.
    ///
    /// This method uses `MonorepoDetector` from `sublime_standard_tools` to determine
    /// if the workspace contains multiple packages (monorepo) or a single package.
    ///
    /// # Arguments
    ///
    /// * `workspace_root` - Root directory to check
    /// * `fs` - Filesystem implementation
    /// * `monorepo_config` - Configuration containing workspace patterns
    ///
    /// # Returns
    ///
    /// Returns `true` if monorepo is detected, `false` otherwise.
    ///
    /// # Errors
    ///
    /// Returns `VersionError::FileSystemError` if detection fails.
    async fn detect_monorepo(
        workspace_root: &Path,
        fs: &F,
        monorepo_config: &MonorepoConfig,
    ) -> VersionResult<bool> {
        let detector =
            MonorepoDetector::with_filesystem_and_config(fs.clone(), monorepo_config.clone());

        // Check if this is a monorepo root
        let monorepo_kind = detector.is_monorepo_root(workspace_root).await.map_err(|e| {
            VersionError::FileSystemError {
                path: workspace_root.to_path_buf(),
                reason: format!("Failed to detect monorepo: {}", e),
            }
        })?;

        Ok(monorepo_kind.is_some())
    }

    /// Discovers packages in a monorepo workspace.
    ///
    /// This method uses `MonorepoDetector` to find all workspace packages and
    /// converts them to `PackageInfo` instances.
    ///
    /// # Returns
    ///
    /// Returns a vector of `PackageInfo` instances for all packages in the monorepo.
    ///
    /// # Errors
    ///
    /// Returns `VersionError::PackageNotFound` if no packages are found.
    /// Returns `VersionError::PackageJsonError` if package.json files cannot be read or parsed.
    async fn discover_monorepo_packages(&self) -> VersionResult<Vec<PackageInfo>> {
        // Build monorepo config with workspace patterns from repo.config.toml
        let monorepo_config = Self::build_monorepo_config(&self.config);
        let detector =
            MonorepoDetector::with_filesystem_and_config(self.fs.clone(), monorepo_config);

        // Detect the monorepo structure
        let monorepo = detector.detect_monorepo(&self.workspace_root).await.map_err(|e| {
            VersionError::FileSystemError {
                path: self.workspace_root.clone(),
                reason: format!("Failed to detect monorepo: {}", e),
            }
        })?;

        // Get all workspace packages
        let workspace_packages = monorepo.packages();

        if workspace_packages.is_empty() {
            return Err(VersionError::PackageNotFound {
                name: "any package".to_string(),
                workspace_root: self.workspace_root.clone(),
            });
        }

        // Convert workspace packages to PackageInfo
        let mut packages = Vec::with_capacity(workspace_packages.len());
        for workspace_package in workspace_packages {
            let package_info = self
                .load_package_info(
                    &workspace_package.absolute_path,
                    Some(workspace_package.clone()),
                )
                .await?;
            packages.push(package_info);
        }

        Ok(packages)
    }

    /// Discovers the single package at the workspace root.
    ///
    /// This method loads the package.json file from the workspace root and
    /// creates a `PackageInfo` instance for it.
    ///
    /// # Returns
    ///
    /// Returns a vector containing a single `PackageInfo` instance.
    ///
    /// # Errors
    ///
    /// Returns `VersionError::PackageJsonError` if package.json cannot be read or parsed.
    async fn discover_single_package(&self) -> VersionResult<Vec<PackageInfo>> {
        let package_info = self.load_package_info(&self.workspace_root, None).await?;
        Ok(vec![package_info])
    }

    /// Loads package information from a package directory.
    ///
    /// This method reads and parses the package.json file at the given path and
    /// creates a `PackageInfo` instance.
    ///
    /// # Arguments
    ///
    /// * `package_path` - Directory containing the package.json file
    /// * `workspace_package` - Optional workspace package information (for monorepos)
    ///
    /// # Returns
    ///
    /// Returns a `PackageInfo` instance for the package.
    ///
    /// # Errors
    ///
    /// Returns `VersionError::PackageJsonError` if the package.json file cannot be
    /// read, parsed, or is missing required fields.
    async fn load_package_info(
        &self,
        package_path: &Path,
        workspace_package: Option<WorkspacePackage>,
    ) -> VersionResult<PackageInfo> {
        let package_json_path = package_path.join("package.json");

        // Read package.json file
        let content = self.fs.read_file_string(&package_json_path).await.map_err(|e| {
            VersionError::PackageJsonError {
                path: package_json_path.clone(),
                reason: format!("Failed to read file: {}", e),
            }
        })?;

        // Parse package.json
        let package_json: package_json::PackageJson =
            serde_json::from_str(&content).map_err(|e| VersionError::PackageJsonError {
                path: package_json_path.clone(),
                reason: format!("Failed to parse JSON: {}", e),
            })?;

        // Create PackageInfo with workspace package info if available
        Ok(PackageInfo::new(package_json, workspace_package, package_path.to_path_buf()))
    }

    /// Resolves versions for packages in a changeset.
    ///
    /// This method calculates the next versions for all packages in the changeset based on
    /// their current versions and the bump type specified in the changeset. It uses the
    /// configured versioning strategy (independent or unified) to determine how versions
    /// are calculated.
    ///
    /// # Arguments
    ///
    /// * `changeset` - The changeset containing packages and bump type
    ///
    /// # Returns
    ///
    /// Returns a `VersionResolution` containing all package updates with their current
    /// and next versions, along with the reason for each update.
    ///
    /// # Errors
    ///
    /// This method will return an error if:
    /// - A package in the changeset is not found in the workspace
    /// - A package has an invalid version in package.json
    /// - Version bump calculation fails
    /// - Filesystem operations fail
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::version::VersionResolver;
    /// use sublime_pkg_tools::types::{Changeset, VersionBump};
    /// use sublime_pkg_tools::config::PackageToolsConfig;
    /// use std::path::PathBuf;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let workspace_root = PathBuf::from(".");
    /// let config = PackageToolsConfig::default();
    /// let resolver = VersionResolver::new(workspace_root, config).await?;
    ///
    /// let mut changeset = Changeset::new(
    ///     "main",
    ///     VersionBump::Minor,
    ///     vec!["production".to_string()],
    /// );
    /// changeset.add_package("@myorg/core");
    /// changeset.add_package("@myorg/utils");
    ///
    /// let resolution = resolver.resolve_versions(&changeset).await?;
    ///
    /// for update in &resolution.updates {
    ///     println!("{}: {} -> {}",
    ///         update.name,
    ///         update.current_version,
    ///         update.next_version
    ///     );
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn resolve_versions(
        &self,
        changeset: &Changeset,
    ) -> VersionResult<VersionResolution> {
        // Discover all packages in the workspace
        let package_list = self.discover_packages().await?;

        // Build dependency graph for propagation (before consuming package_list)
        let (graph, circular_deps) = if self.config.dependency.propagation_bump != "none" {
            let g = DependencyGraph::from_packages(&package_list)?;
            let cycles = g.detect_cycles();
            (Some(g), cycles)
        } else {
            (None, Vec::new())
        };

        // Build a map of package name to package info (consuming package_list)
        let mut packages = HashMap::new();
        for package_info in package_list {
            let name = package_info.name().to_string();
            packages.insert(name, package_info);
        }

        // Step 1: Resolve direct version changes from changeset
        let mut resolution = resolve_versions(changeset, &packages, self.strategy).await?;

        // Step 2: Add circular dependencies to resolution
        resolution.circular_dependencies = circular_deps;

        // Step 3: Apply dependency propagation if configured
        if let Some(graph) = graph {
            // Create propagator and apply propagation
            let propagator = DependencyPropagator::new(&graph, &packages, &self.config.dependency);
            propagator.propagate(&mut resolution)?;
        }

        Ok(resolution)
    }

    /// Resolves versions with optional prerelease support.
    ///
    /// # What
    ///
    /// Extends the standard version resolution to support prerelease versions,
    /// allowing controlled creation and increment of prerelease versions.
    ///
    /// # How
    ///
    /// Follows the same flow as `resolve_versions()` but passes prerelease
    /// configuration down to the resolution logic, which then uses
    /// `Version::bump_with_prerelease()` instead of standard bump.
    ///
    /// # Why
    ///
    /// Enables prerelease workflows while maintaining the existing resolution
    /// logic for dependency propagation and strategy handling.
    ///
    /// # Arguments
    ///
    /// * `changeset` - Changeset containing packages and bump type
    /// * `prerelease_config` - Optional prerelease configuration
    ///
    /// # Errors
    ///
    /// Returns error if version resolution or propagation fails.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::version::VersionResolver;
    /// use sublime_pkg_tools::types::prerelease::{PrereleaseConfig, PrereleaseMode};
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let resolver = VersionResolver::new(workspace_root, config).await?;
    ///
    /// // Without prerelease (standard behavior)
    /// let resolution = resolver.resolve_versions_with_prerelease(&changeset, None).await?;
    ///
    /// // With prerelease
    /// let config = PrereleaseConfig {
    ///     tag: "beta".to_string(),
    ///     mode: PrereleaseMode::Create,
    /// };
    /// let resolution = resolver.resolve_versions_with_prerelease(&changeset, Some(&config)).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn resolve_versions_with_prerelease(
        &self,
        changeset: &Changeset,
        prerelease_config: Option<&crate::types::prerelease::PrereleaseConfig>,
    ) -> VersionResult<VersionResolution> {
        // Discover all packages in the workspace
        let package_list = self.discover_packages().await?;

        // Build dependency graph for propagation (before consuming package_list)
        let (graph, circular_deps) = if self.config.dependency.propagation_bump != "none" {
            let g = DependencyGraph::from_packages(&package_list)?;
            let cycles = g.detect_cycles();
            (Some(g), cycles)
        } else {
            (None, Vec::new())
        };

        // Build a map of package name to package info (consuming package_list)
        let mut packages = HashMap::new();
        for package_info in package_list {
            let name = package_info.name().to_string();
            packages.insert(name, package_info);
        }

        // Step 1: Resolve direct version changes from changeset with prerelease support
        let mut resolution = crate::version::resolution::resolve_versions_with_prerelease(
            changeset,
            &packages,
            self.strategy,
            prerelease_config,
        )
        .await?;

        // Step 2: Add circular dependencies to resolution
        resolution.circular_dependencies = circular_deps;

        // Step 3: Apply dependency propagation if configured
        if let Some(graph) = graph {
            // Create propagator and apply propagation
            let propagator = DependencyPropagator::new(&graph, &packages, &self.config.dependency);
            propagator.propagate(&mut resolution)?;
        }

        Ok(resolution)
    }

    /// Resolves versions with automatic prerelease mode inference.
    ///
    /// Similar to `resolve_versions_with_prerelease`, but automatically determines
    /// the appropriate prerelease mode (create, increment) based on each package's
    /// current version state:
    ///
    /// - If current version is stable → **Create** new prerelease
    /// - If current version has same prerelease tag → **Increment**
    /// - If current version has different prerelease tag → **Create** new
    ///
    /// This provides a simpler API where only the tag is needed.
    ///
    /// # Arguments
    ///
    /// * `changeset` - The changeset containing packages and version bump
    /// * `prerelease_tag` - Optional prerelease tag (e.g., "alpha", "beta", "rc")
    ///
    /// # Returns
    ///
    /// Returns a `VersionResolution` with all calculated updates.
    ///
    /// # Errors
    ///
    /// Returns error if version parsing or bumping fails.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::version::VersionResolver;
    /// use sublime_pkg_tools::types::{Changeset, VersionBump};
    /// use sublime_pkg_tools::config::PackageToolsConfig;
    /// use std::path::PathBuf;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let workspace_root = PathBuf::from(".");
    /// let config = PackageToolsConfig::default();
    /// let resolver = VersionResolver::new(workspace_root, config).await?;
    ///
    /// let mut changeset = Changeset::new("feature/new-api", VersionBump::Minor, vec![]);
    /// changeset.add_package("my-package");
    ///
    /// // Just pass the tag - mode is automatically inferred
    /// let resolution = resolver.resolve_versions_with_prerelease_auto(&changeset, Some("beta")).await?;
    /// // If current version is 1.0.0 → next is 1.1.0-beta.0
    /// // If current version is 1.1.0-beta.0 → next is 1.1.0-beta.1
    /// # Ok(())
    /// # }
    /// ```
    pub async fn resolve_versions_with_prerelease_auto(
        &self,
        changeset: &Changeset,
        prerelease_tag: Option<&str>,
    ) -> VersionResult<VersionResolution> {
        // Discover all packages in the workspace
        let package_list = self.discover_packages().await?;

        // Build dependency graph for propagation (before consuming package_list)
        let (graph, circular_deps) = if self.config.dependency.propagation_bump != "none" {
            let g = DependencyGraph::from_packages(&package_list)?;
            let cycles = g.detect_cycles();
            (Some(g), cycles)
        } else {
            (None, Vec::new())
        };

        // Build a map of package name to package info (consuming package_list)
        let mut packages = HashMap::new();
        for package_info in package_list {
            let name = package_info.name().to_string();
            packages.insert(name, package_info);
        }

        // Step 1: Resolve direct version changes with automatic prerelease mode
        let mut resolution = crate::version::resolution::resolve_versions_with_prerelease_auto(
            changeset,
            &packages,
            self.strategy,
            prerelease_tag,
        )
        .await?;

        // Step 2: Add circular dependencies to resolution
        resolution.circular_dependencies = circular_deps;

        // Step 3: Apply dependency propagation if configured
        if let Some(graph) = graph {
            // Create propagator and apply propagation
            let propagator = DependencyPropagator::new(&graph, &packages, &self.config.dependency);
            propagator.propagate(&mut resolution)?;
        }

        Ok(resolution)
    }

    /// Applies version changes from a changeset to package.json files.
    ///
    /// This method resolves versions for all packages in the changeset and optionally
    /// writes the updated versions and dependency references to package.json files.
    /// When `dry_run` is true, no files are modified and the method only returns
    /// what would be changed.
    ///
    /// # Arguments
    ///
    /// * `changeset` - The changeset containing packages and version bump information
    /// * `dry_run` - If true, only preview changes without modifying files (default: true)
    ///
    /// # Returns
    ///
    /// Returns an `ApplyResult` containing the resolution details, list of modified
    /// files (empty for dry-run), and summary statistics.
    ///
    /// # Errors
    ///
    /// This method will return an error if:
    /// - Version resolution fails (package not found, invalid version, etc.)
    /// - File reading or writing fails (dry_run = false)
    /// - JSON serialization fails
    /// - Backup or rollback operations fail
    ///
    /// # Examples
    ///
    /// ## Preview changes (dry-run)
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::version::VersionResolver;
    /// use sublime_pkg_tools::types::{Changeset, VersionBump};
    /// use sublime_pkg_tools::config::PackageToolsConfig;
    /// use std::path::PathBuf;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let workspace_root = PathBuf::from(".");
    /// let config = PackageToolsConfig::default();
    /// let resolver = VersionResolver::new(workspace_root, config).await?;
    ///
    /// let mut changeset = Changeset::new(
    ///     "main",
    ///     VersionBump::Minor,
    ///     vec!["production".to_string()],
    /// );
    /// changeset.add_package("@myorg/core");
    ///
    /// // Preview changes without modifying files
    /// let result = resolver.apply_versions(&changeset, true).await?;
    ///
    /// assert!(result.dry_run);
    /// assert!(result.modified_files.is_empty());
    ///
    /// println!("Would update {} packages:", result.summary.packages_updated);
    /// for update in &result.resolution.updates {
    ///     println!("  {}: {} -> {}",
    ///         update.name,
    ///         update.current_version,
    ///         update.next_version
    ///     );
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Apply changes to files
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::version::VersionResolver;
    /// use sublime_pkg_tools::types::{Changeset, VersionBump};
    /// use sublime_pkg_tools::config::PackageToolsConfig;
    /// use std::path::PathBuf;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let workspace_root = PathBuf::from(".");
    /// let config = PackageToolsConfig::default();
    /// let resolver = VersionResolver::new(workspace_root, config).await?;
    ///
    /// let mut changeset = Changeset::new(
    ///     "main",
    ///     VersionBump::Minor,
    ///     vec!["production".to_string()],
    /// );
    /// changeset.add_package("@myorg/core");
    ///
    /// // Apply changes to package.json files
    /// let result = resolver.apply_versions(&changeset, false).await?;
    ///
    /// assert!(!result.dry_run);
    /// println!("Modified {} files:", result.modified_files.len());
    /// for file in &result.modified_files {
    ///     println!("  - {}", file.display());
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub async fn apply_versions(
        &self,
        changeset: &Changeset,
        dry_run: bool,
    ) -> VersionResult<ApplyResult> {
        // First, resolve versions to get all the updates
        let resolution = self.resolve_versions(changeset).await?;

        // If dry-run, return early without modifying files
        if dry_run {
            return Ok(ApplyResult::new(true, resolution, vec![]));
        }

        // Discover all packages again to have full package info with paths
        let package_list = self.discover_packages().await?;
        let mut packages = HashMap::new();
        for package_info in package_list {
            let name = package_info.name().to_string();
            packages.insert(name, package_info);
        }

        // Track modified files and backups for rollback
        let mut modified_files = Vec::new();
        let mut backups: Vec<(PathBuf, Vec<u8>)> = Vec::new();

        // Apply updates to each package
        let apply_result = self
            .apply_updates_to_packages(&resolution, &packages, &mut modified_files, &mut backups)
            .await;

        // If there was an error, restore backups
        if let Err(e) = apply_result {
            self.restore_backups(&backups).await?;
            return Err(e);
        }

        Ok(ApplyResult::new(false, resolution, modified_files))
    }

    /// Applies a pre-calculated version resolution to packages.
    ///
    /// Unlike `apply_versions` which resolves versions internally, this method
    /// takes an already-calculated `VersionResolution` and applies it directly.
    /// This is useful when you need to apply resolutions that were computed
    /// with special options like prerelease support.
    ///
    /// # Arguments
    ///
    /// * `resolution` - The pre-calculated version resolution to apply
    /// * `dry_run` - If true, returns the resolution without modifying files
    ///
    /// # Returns
    ///
    /// Returns an `ApplyResult` containing the resolution and list of modified files.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Package discovery fails
    /// - File operations fail (reading, writing package.json)
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use sublime_pkg_tools::version::VersionResolver;
    /// use sublime_pkg_tools::types::{Changeset, VersionBump};
    /// use sublime_pkg_tools::types::prerelease::{PrereleaseConfig, PrereleaseMode};
    /// use sublime_pkg_tools::config::PackageToolsConfig;
    /// use std::path::PathBuf;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let workspace_root = PathBuf::from(".");
    /// let config = PackageToolsConfig::default();
    /// let resolver = VersionResolver::new(workspace_root, config).await?;
    ///
    /// let mut changeset = Changeset::new("feature/new-api", VersionBump::Minor, vec![]);
    /// changeset.add_package("my-package");
    ///
    /// // Resolve with prerelease support
    /// let prerelease_config = PrereleaseConfig {
    ///     tag: "beta".to_string(),
    ///     mode: PrereleaseMode::Create,
    /// };
    /// let resolution = resolver
    ///     .resolve_versions_with_prerelease(&changeset, Some(&prerelease_config))
    ///     .await?;
    ///
    /// // Apply the pre-calculated resolution
    /// let result = resolver.apply_from_resolution(resolution, false).await?;
    /// println!("Updated {} packages", result.summary.packages_updated);
    /// # Ok(())
    /// # }
    /// ```
    pub async fn apply_from_resolution(
        &self,
        resolution: VersionResolution,
        dry_run: bool,
    ) -> VersionResult<ApplyResult> {
        // If dry-run, return early without modifying files
        if dry_run {
            return Ok(ApplyResult::new(true, resolution, vec![]));
        }

        // Discover all packages to have full package info with paths
        let package_list = self.discover_packages().await?;
        let mut packages = HashMap::new();
        for package_info in package_list {
            let name = package_info.name().to_string();
            packages.insert(name, package_info);
        }

        // Track modified files and backups for rollback
        let mut modified_files = Vec::new();
        let mut backups: Vec<(PathBuf, Vec<u8>)> = Vec::new();

        // Apply updates to each package
        let apply_result = self
            .apply_updates_to_packages(&resolution, &packages, &mut modified_files, &mut backups)
            .await;

        // If there was an error, restore backups
        if let Err(e) = apply_result {
            self.restore_backups(&backups).await?;
            return Err(e);
        }

        Ok(ApplyResult::new(false, resolution, modified_files))
    }

    /// Applies version updates to all packages in the resolution.
    ///
    /// This internal method iterates through all package updates and writes
    /// the new versions and dependency references to package.json files.
    ///
    /// # Arguments
    ///
    /// * `resolution` - The version resolution containing all updates
    /// * `packages` - Map of package names to package information
    /// * `modified_files` - Vector to track modified file paths
    /// * `backups` - Vector to store backup data for rollback
    ///
    /// # Errors
    ///
    /// Returns an error if file operations fail.
    async fn apply_updates_to_packages(
        &self,
        resolution: &VersionResolution,
        packages: &HashMap<String, PackageInfo>,
        modified_files: &mut Vec<PathBuf>,
        backups: &mut Vec<(PathBuf, Vec<u8>)>,
    ) -> VersionResult<()> {
        for update in &resolution.updates {
            let package_info =
                packages.get(&update.name).ok_or_else(|| VersionError::PackageNotFound {
                    name: update.name.clone(),
                    workspace_root: self.workspace_root.clone(),
                })?;

            let package_json_path = self.write_package_json(package_info, update, backups).await?;

            modified_files.push(package_json_path);
        }

        Ok(())
    }

    /// Writes updated version and dependencies to a package.json file.
    ///
    /// This method reads the current package.json, creates a backup, updates
    /// the version field and dependency references, then writes the file back
    /// with preserved formatting.
    ///
    /// # Arguments
    ///
    /// * `package` - Information about the package to update
    /// * `update` - The version update to apply
    /// * `backups` - Vector storing backup data
    ///
    /// # Returns
    ///
    /// Returns the path to the modified package.json file.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - File reading fails
    /// - JSON parsing fails
    /// - Backup creation fails
    /// - File writing fails
    async fn write_package_json(
        &self,
        package: &PackageInfo,
        update: &PackageUpdate,
        backups: &mut Vec<(PathBuf, Vec<u8>)>,
    ) -> VersionResult<PathBuf> {
        let package_json_path = package.path().join("package.json");

        // Read current package.json content
        let current_content = self.fs.read_file(&package_json_path).await.map_err(|e| {
            VersionError::FileSystemError {
                path: package_json_path.clone(),
                reason: format!("Failed to read package.json: {}", e),
            }
        })?;

        // Create backup before modifying
        backups.push((package_json_path.clone(), current_content.clone()));

        // Parse package.json
        let mut pkg_json: PackageJson = serde_json::from_slice(&current_content).map_err(|e| {
            VersionError::PackageJsonError {
                path: package_json_path.clone(),
                reason: format!("Failed to parse JSON: {}", e),
            }
        })?;

        // Update version
        pkg_json.version = update.next_version.to_string();

        // Update dependency references
        for dep_update in &update.dependency_updates {
            // Skip workspace protocols and local references
            if Self::is_skipped_version_spec(&dep_update.old_version_spec) {
                continue;
            }

            match dep_update.dependency_type {
                DependencyType::Regular => {
                    if let Some(deps) = &mut pkg_json.dependencies {
                        deps.insert(
                            dep_update.dependency_name.clone(),
                            dep_update.new_version_spec.clone(),
                        );
                    }
                }
                DependencyType::Dev => {
                    if let Some(dev_deps) = &mut pkg_json.dev_dependencies {
                        dev_deps.insert(
                            dep_update.dependency_name.clone(),
                            dep_update.new_version_spec.clone(),
                        );
                    }
                }
                DependencyType::Peer => {
                    if let Some(peer_deps) = &mut pkg_json.peer_dependencies {
                        peer_deps.insert(
                            dep_update.dependency_name.clone(),
                            dep_update.new_version_spec.clone(),
                        );
                    }
                }
                DependencyType::Optional => {
                    if let Some(optional_deps) = &mut pkg_json.optional_dependencies {
                        optional_deps.insert(
                            dep_update.dependency_name.clone(),
                            dep_update.new_version_spec.clone(),
                        );
                    }
                }
            }
        }

        // Serialize with pretty formatting
        let json_string =
            serde_json::to_string_pretty(&pkg_json).map_err(|e| VersionError::ApplyFailed {
                path: package_json_path.clone(),
                reason: format!("Failed to serialize JSON: {}", e),
            })?;

        // Write to file using filesystem manager
        self.fs.write_file_string(&package_json_path, &json_string).await.map_err(|e| {
            VersionError::ApplyFailed {
                path: package_json_path.clone(),
                reason: format!("Failed to write package.json: {}", e),
            }
        })?;

        Ok(package_json_path)
    }

    /// Checks if a version spec should be skipped (workspace protocols and local references).
    ///
    /// This method identifies version specifications that should not be updated:
    /// - `workspace:*` - workspace protocol
    /// - `file:` - file protocol
    /// - `link:` - link protocol
    /// - `portal:` - portal protocol
    ///
    /// # Arguments
    ///
    /// * `version_spec` - The version specification string to check
    ///
    /// # Returns
    ///
    /// Returns true if the version spec should be skipped.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// assert!(VersionResolver::is_skipped_version_spec("workspace:*"));
    /// assert!(VersionResolver::is_skipped_version_spec("file:../local-pkg"));
    /// assert!(VersionResolver::is_skipped_version_spec("link:../linked"));
    /// assert!(VersionResolver::is_skipped_version_spec("portal:../portal"));
    /// assert!(!VersionResolver::is_skipped_version_spec("^1.2.3"));
    /// assert!(!VersionResolver::is_skipped_version_spec("~2.0.0"));
    /// ```
    pub(crate) fn is_skipped_version_spec(version_spec: &str) -> bool {
        version_spec.starts_with("workspace:")
            || version_spec.starts_with("file:")
            || version_spec.starts_with("link:")
            || version_spec.starts_with("portal:")
    }

    /// Restores backed-up files after a failed operation.
    ///
    /// This method is called when an error occurs during version application
    /// to roll back any files that were modified before the error occurred.
    ///
    /// # Arguments
    ///
    /// * `backups` - Vector of (path, content) tuples to restore
    ///
    /// # Errors
    ///
    /// Returns an error if any restore operation fails.
    async fn restore_backups(&self, backups: &[(PathBuf, Vec<u8>)]) -> VersionResult<()> {
        for (path, content) in backups {
            self.fs.write_file(path, content).await.map_err(|e| VersionError::ApplyFailed {
                path: path.clone(),
                reason: format!("Failed to restore backup: {}", e),
            })?;
        }
        Ok(())
    }
}