sublime_standard_tools 0.0.15

A collection of utilities for working with Node.js projects from Rust applications
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
//! # Project Detection Implementation - Async Only
//!
//! ## What
//! This file implements async project detection, providing a unified interface
//! for detecting and analyzing Node.js projects using async I/O operations.
//! All sync operations have been removed for architectural clarity.
//!
//! ## How
//! The detector uses async filesystem operations to analyze project structures,
//! eliminating code duplication by centralizing common operations like package.json
//! parsing and package manager detection.
//!
//! ## Why
//! Async project detection is essential for performance when dealing with large
//! monorepos where multiple projects need to be detected concurrently. This unified
//! async-only approach eliminates confusion and provides consistent API.

use super::Project;
use super::types::{ProjectDescriptor, ProjectKind, ProjectValidationStatus};
use crate::config::StandardConfig;
use crate::error::{Error, Result};
use crate::filesystem::{AsyncFileSystem, FileSystemManager};
use crate::monorepo::{MonorepoDetector, MonorepoDetectorTrait};
use crate::node::{PackageManager, RepoKind};
use async_trait::async_trait;
use package_json::PackageJson;
use std::path::{Path, PathBuf};

/// Internal structure to hold unified project metadata.
///
/// This structure centralizes common project information that is used
/// across both simple and monorepo project types.
#[derive(Debug)]
struct ProjectMetadata {
    /// The root path of the project
    root: PathBuf,
    /// Parsed package.json content, if available
    package_json: Option<PackageJson>,
    /// Detected package manager, if any
    package_manager: Option<PackageManager>,
    /// Validation status for the project structure
    validation_status: ProjectValidationStatus,
}

impl ProjectMetadata {
    /// Creates new project metadata with the given root path.
    ///
    /// # Arguments
    ///
    /// * `root` - The root directory of the project
    ///
    /// # Returns
    ///
    /// A new `ProjectMetadata` instance with unvalidated status.
    fn new(root: PathBuf) -> Self {
        Self {
            root,
            package_json: None,
            package_manager: None,
            validation_status: ProjectValidationStatus::NotValidated,
        }
    }
}

/// Async trait for project detection.
///
/// This trait provides async methods for detecting and analyzing Node.js projects
/// in a non-blocking manner, allowing for concurrent detection operations.
///
/// # Examples
///
/// ```no_run
/// use sublime_standard_tools::project::{ProjectDetector, ProjectDetectorTrait};
/// use std::path::Path;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let detector = ProjectDetector::new();
/// let project = detector.detect(Path::new("."), None).await?;
/// println!("Found project: {:?}", project.as_project_info().kind());
/// # Ok(())
/// # }
/// ```
#[async_trait]
pub trait ProjectDetectorTrait: Send + Sync {
    /// Asynchronously detects and analyzes a project at the given path.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to analyze for project detection
    /// * `config` - Configuration options for project detection
    ///
    /// # Returns
    ///
    /// * `Ok(ProjectDescriptor)` - The detected project descriptor
    /// * `Err(Error)` - If detection fails or no project is found
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use sublime_standard_tools::project::{ProjectDetector, ProjectDetectorTrait};
    /// use std::path::Path;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let detector = ProjectDetector::new();
    /// let project = detector.detect(Path::new("."), None).await?;
    /// println!("Detected project kind: {:?}", project.as_project_info().kind());
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The path does not exist
    /// - No valid project is found at the path
    /// - Filesystem operations fail
    /// - Project structure is invalid
    async fn detect(
        &self,
        path: &Path,
        config: Option<&StandardConfig>,
    ) -> Result<ProjectDescriptor>;

    /// Asynchronously detects only the project kind without full analysis.
    ///
    /// This method is faster than full detection as it only determines the project
    /// type without analyzing the complete project structure.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to analyze for project kind detection
    ///
    /// # Returns
    ///
    /// * `Ok(ProjectKind)` - The detected project kind
    /// * `Err(Error)` - If detection fails or no project is found
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use sublime_standard_tools::project::{ProjectDetector, ProjectDetectorTrait};
    /// use std::path::Path;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let detector = ProjectDetector::new();
    /// let kind = detector.detect_kind(Path::new(".")).await?;
    /// println!("Project kind: {:?}", kind);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The path does not exist
    /// - No valid project is found at the path
    /// - Filesystem operations fail
    async fn detect_kind(&self, path: &Path) -> Result<ProjectKind>;

    /// Asynchronously checks if the path contains a valid Node.js project.
    ///
    /// This method performs a quick check to determine if a path contains a
    /// valid Node.js project without full analysis.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to check for project validity
    ///
    /// # Returns
    ///
    /// * `true` - If the path contains a valid Node.js project
    /// * `false` - If the path does not contain a valid Node.js project
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use sublime_standard_tools::project::{ProjectDetector, ProjectDetectorTrait};
    /// use std::path::Path;
    ///
    /// # async fn example() {
    /// let detector = ProjectDetector::new();
    /// if detector.is_valid_project(Path::new(".")).await {
    ///     println!("This is a valid Node.js project");
    /// } else {
    ///     println!("This is not a valid Node.js project");
    /// }
    /// # }
    /// ```
    async fn is_valid_project(&self, path: &Path) -> bool;
}

/// Async trait for project detection with custom filesystem.
///
/// This trait extends `ProjectDetectorTrait` to allow custom filesystem implementations
/// for testing or specialized use cases.
///
/// # Type Parameters
///
/// * `F` - The filesystem implementation type
///
/// # Examples
///
/// ```no_run
/// use sublime_standard_tools::project::{ProjectDetector, ProjectDetectorWithFs, ProjectDetectorTrait};
/// use sublime_standard_tools::filesystem::FileSystemManager;
/// use std::path::Path;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let fs = FileSystemManager::new();
/// let detector = ProjectDetector::with_filesystem(fs);
/// let project = detector.detect(Path::new("."), None).await?;
/// println!("Found project: {:?}", project.as_project_info().kind());
/// # Ok(())
/// # }
/// ```
#[async_trait]
pub trait ProjectDetectorWithFs<F: AsyncFileSystem>: ProjectDetectorTrait {
    /// Gets a reference to the filesystem implementation.
    ///
    /// # Returns
    ///
    /// A reference to the filesystem implementation.
    fn filesystem(&self) -> &F;

    /// Asynchronously detects projects in multiple paths concurrently.
    ///
    /// This method processes multiple paths in parallel for improved performance
    /// when analyzing multiple project directories.
    ///
    /// # Arguments
    ///
    /// * `paths` - A slice of paths to analyze for projects
    /// * `config` - Configuration options for project detection
    ///
    /// # Returns
    ///
    /// * `Ok(Vec<Result<ProjectDescriptor>>)` - Results for each path
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use sublime_standard_tools::project::{ProjectDetector, ProjectDetectorWithFs};
    /// use sublime_standard_tools::filesystem::FileSystemManager;
    /// use std::path::Path;
    ///
    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let fs = FileSystemManager::new();
    /// let detector = ProjectDetector::with_filesystem(fs);
    /// let paths = vec![Path::new("."), Path::new("../other-project")];
    /// let results = detector.detect_multiple(&paths, None).await;
    /// for (i, result) in results.iter().enumerate() {
    ///     match result {
    ///         Ok(project) => println!("Path {}: {:?}", i, project.as_project_info().kind()),
    ///         Err(e) => println!("Path {}: Error - {}", i, e),
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// Each result in the vector may contain an error if detection fails for that path.
    async fn detect_multiple(
        &self,
        paths: &[&Path],
        config: Option<&StandardConfig>,
    ) -> Vec<Result<ProjectDescriptor>>;
}

/// Provides unified detection and analysis of Node.js projects.
///
/// This detector implements a truly unified approach to project detection,
/// eliminating code duplication by centralizing common operations and using
/// async I/O operations for maximum performance.
///
/// # Type Parameters
///
/// * `F` - An async filesystem implementation that satisfies the `AsyncFileSystem` trait.
///   Defaults to `FileSystemManager` for standard operations.
///
/// # Examples
///
/// ```no_run
/// use sublime_standard_tools::project::{ProjectDetector, ProjectDetectorTrait};
/// use std::path::Path;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let detector = ProjectDetector::new();
///
/// match detector.detect(Path::new("."), None).await {
///     Ok(project) => {
///         println!("Detected {} project", project.as_project_info().kind().name());
///     }
///     Err(e) => eprintln!("Detection failed: {}", e),
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug)]
pub struct ProjectDetector<F: AsyncFileSystem = FileSystemManager> {
    /// Async filesystem implementation for file operations
    fs: F,
}

impl ProjectDetector<FileSystemManager> {
    /// Creates a new `ProjectDetector` with the default async filesystem implementation.
    ///
    /// # Returns
    ///
    /// A new `ProjectDetector` instance using the `FileSystemManager`.
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::project::ProjectDetector;
    ///
    /// let detector = ProjectDetector::new();
    /// ```
    #[must_use]
    pub fn new() -> Self {
        let fs = FileSystemManager::new();
        Self { fs }
    }
}

impl<F: AsyncFileSystem + Clone + 'static> ProjectDetector<F> {
    /// Creates a new `ProjectDetector` with a custom async filesystem implementation.
    ///
    /// # Arguments
    ///
    /// * `fs` - The async filesystem implementation to use
    ///
    /// # Returns
    ///
    /// A new `ProjectDetector` instance using the provided filesystem.
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::filesystem::FileSystemManager;
    /// use sublime_standard_tools::project::ProjectDetector;
    ///
    /// let fs = FileSystemManager::new();
    /// let detector = ProjectDetector::with_filesystem(fs);
    /// ```
    #[must_use]
    pub fn with_filesystem(fs: F) -> Self {
        Self { fs }
    }

    /// Loads project metadata using configuration settings.
    ///
    /// This method loads project metadata taking into account configuration
    /// settings for package manager detection, validation, and other options.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to analyze
    /// * `config` - Configuration settings to control behavior
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - The package.json file cannot be read or parsed
    /// - An I/O error occurs while reading files
    /// - Configuration validation fails
    ///
    /// # Returns
    ///
    /// * `Ok(ProjectMetadata)` - Loaded project metadata
    /// * `Err(Error)` - If metadata loading failed
    async fn load_project_metadata(
        &self,
        path: &Path,
        config: &StandardConfig,
    ) -> Result<ProjectMetadata> {
        let mut metadata = ProjectMetadata::new(path.to_path_buf());

        // Load package.json if it exists
        let package_json_path = path.join("package.json");
        if self.fs.exists(&package_json_path).await {
            let content = self.fs.read_file_string(&package_json_path).await?;
            metadata.package_json = Some(
                serde_json::from_str::<PackageJson>(&content)
                    .map_err(|e| Error::operation(format!("Invalid package.json: {e}")))?,
            );
        }

        // Detect package manager using configuration
        log::debug!(
            "Package manager detection with config: detection_order={:?}, detect_from_env={}",
            config.package_managers.detection_order,
            config.package_managers.detect_from_env
        );

        if let Ok(pm) = PackageManager::detect_with_config(path, &config.package_managers) {
            metadata.package_manager = Some(pm);
        }
        // Package manager detection failure is not fatal for simple projects

        // Set validation status based on configuration requirements
        if config.validation.require_package_json && metadata.package_json.is_none() {
            metadata.validation_status = ProjectValidationStatus::Error(vec![
                "package.json is required by configuration".to_string(),
            ]);
        } else {
            // Simple projects start as not validated - will be validated later if needed
            metadata.validation_status = ProjectValidationStatus::NotValidated;
        }

        Ok(metadata)
    }

    /// Determines if monorepo detection should be performed based on configuration.
    ///
    /// This method checks the StandardConfig to determine if monorepo detection
    /// is enabled and should be performed for the current project.
    ///
    /// # Arguments
    ///
    /// * `config` - The effective configuration to check
    ///
    /// # Returns
    ///
    /// `true` if monorepo detection should be performed, `false` otherwise.
    fn should_detect_monorepo(config: &StandardConfig) -> bool {
        // Check if monorepo detection is enabled via configuration
        // For now, we always enable it unless explicitly disabled in future config versions
        // This can be extended to check specific config flags when added
        !config.monorepo.workspace_patterns.is_empty() && config.monorepo.max_search_depth > 0
    }

    /// Detects monorepo structure using configuration settings.
    ///
    /// This method performs monorepo detection while respecting the configuration
    /// settings for workspace patterns, search depth, and other monorepo-specific options.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to analyze for monorepo structure
    /// * `config` - Configuration settings to control detection behavior
    ///
    /// # Returns
    ///
    /// * `Ok(MonorepoDescriptor)` - If a monorepo is detected
    /// * `Err(Error)` - If no monorepo is found or detection fails
    async fn detect_monorepo_with_config(
        &self,
        path: &Path,
        config: &StandardConfig,
    ) -> Result<crate::monorepo::MonorepoDescriptor> {
        // Log configuration being used for transparency
        log::debug!(
            "Detecting monorepo with config: max_depth={}, patterns={:?}, exclude={:?}",
            config.monorepo.max_search_depth,
            config.monorepo.workspace_patterns,
            config.monorepo.exclude_patterns
        );

        // Create a config-aware monorepo detector for this specific operation
        let config_aware_detector =
            MonorepoDetector::with_filesystem_and_config(self.fs.clone(), config.monorepo.clone());

        // Use the config-aware detector
        config_aware_detector.detect_monorepo(path).await
    }

    /// Detects and analyzes a Node.js project using unified detection logic.
    ///
    /// This method uses a truly unified approach that eliminates code duplication
    /// by centralizing common operations and determining project type through
    /// async analysis.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to analyze for a Node.js project
    /// * `config` - Optional configuration (if None, uses default configuration)
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - The path does not exist or cannot be accessed
    /// - The path does not contain a valid Node.js project
    /// - An I/O error occurs while reading project files
    ///
    /// # Returns
    ///
    /// * `Ok(ProjectDescriptor)` - A descriptor containing all project information
    /// * `Err(Error)` - If the path is not a valid project or an error occurred
    pub async fn detect(
        &self,
        path: impl AsRef<Path>,
        config: Option<&StandardConfig>,
    ) -> Result<ProjectDescriptor> {
        let path = path.as_ref();

        // First validate basic path requirements
        self.validate_project_path(path).await?;

        // Use provided configuration or default
        let effective_config = match config {
            Some(cfg) => cfg.clone(),
            None => StandardConfig::default(),
        };

        // Create a unified project structure using configuration
        let metadata = self.load_project_metadata(path, &effective_config).await?;

        // Determine project kind based on configuration-controlled monorepo detection
        let project_kind = if Self::should_detect_monorepo(&effective_config) {
            if let Ok(monorepo) = self.detect_monorepo_with_config(path, &effective_config).await {
                // It's a monorepo, use the detected monorepo kind
                ProjectKind::Repository(RepoKind::Monorepo(monorepo.kind().clone()))
            } else {
                // Not a monorepo, it's a simple project
                ProjectKind::Repository(RepoKind::Simple)
            }
        } else {
            // Monorepo detection disabled by configuration
            ProjectKind::Repository(RepoKind::Simple)
        };

        // Create unified Project with detected metadata
        let mut project = Project::new(metadata.root, project_kind);

        // Set detected metadata
        project.package_manager = metadata.package_manager;
        project.package_json = metadata.package_json;
        project.validation_status = metadata.validation_status;

        // If it's a monorepo, populate internal dependencies using config-aware detection
        if project.is_monorepo()
            && let Ok(monorepo) = self.detect_monorepo_with_config(path, &effective_config).await
        {
            project.internal_dependencies = monorepo.packages().to_vec();
        }

        Ok(ProjectDescriptor::NodeJs(project))
    }

    /// Detects the type of Node.js project without full analysis using default configuration.
    ///
    /// This method provides a quick way to determine project type without
    /// loading all project data, useful for lightweight operations.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to analyze
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - The path does not exist or cannot be accessed
    /// - The path does not contain a package.json file
    /// - An I/O error occurs while reading files
    ///
    /// # Returns
    ///
    /// * `Ok(ProjectKind)` - The type of project detected
    /// * `Err(Error)` - If detection failed
    pub async fn detect_kind(&self, path: impl AsRef<Path>) -> Result<ProjectKind> {
        let default_config = StandardConfig::default();
        self.detect_kind_with_config(path, &default_config).await
    }

    /// Detects the type of Node.js project without full analysis using custom configuration.
    ///
    /// This method provides a quick way to determine project type without
    /// loading all project data, using the provided configuration for monorepo detection.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to analyze
    /// * `config` - Configuration to control detection behavior
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - The path does not exist or cannot be accessed
    /// - The path does not contain a package.json file
    /// - An I/O error occurs while reading files
    ///
    /// # Returns
    ///
    /// * `Ok(ProjectKind)` - The type of project detected
    /// * `Err(Error)` - If detection failed
    pub async fn detect_kind_with_config(
        &self,
        path: impl AsRef<Path>,
        config: &StandardConfig,
    ) -> Result<ProjectKind> {
        let path = path.as_ref();

        // Validate path and package.json existence
        self.validate_project_path(path).await?;

        // Check for monorepo using configuration
        if Self::should_detect_monorepo(config) {
            let config_aware_detector = MonorepoDetector::with_filesystem_and_config(
                self.fs.clone(),
                config.monorepo.clone(),
            );

            if let Some(monorepo_kind) = config_aware_detector.is_monorepo_root(path).await? {
                return Ok(ProjectKind::Repository(RepoKind::Monorepo(monorepo_kind)));
            }
        }

        Ok(ProjectKind::Repository(RepoKind::Simple))
    }

    /// Validates that a path contains the basic requirements for a Node.js project.
    ///
    /// This method centralizes path validation logic used across detection methods.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to validate
    ///
    /// # Errors
    ///
    /// Returns an [`Error`] if:
    /// - The path does not exist
    /// - The path does not contain a package.json file
    ///
    /// # Returns
    ///
    /// * `Ok(())` - If the path is valid
    /// * `Err(Error)` - If validation failed
    async fn validate_project_path(&self, path: &Path) -> Result<()> {
        if !self.fs.exists(path).await {
            return Err(Error::operation(format!("Path does not exist: {}", path.display())));
        }

        let package_json_path = path.join("package.json");
        if !self.fs.exists(&package_json_path).await {
            return Err(Error::operation(format!(
                "No package.json found at: {}",
                package_json_path.display()
            )));
        }

        Ok(())
    }

    /// Determines if a path contains a valid Node.js project.
    ///
    /// This method performs a comprehensive validation to check if the path
    /// contains all requirements for a valid Node.js project.
    ///
    /// # Arguments
    ///
    /// * `path` - The path to validate
    ///
    /// # Returns
    ///
    /// `true` if the path contains a valid Node.js project, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```
    /// use sublime_standard_tools::project::ProjectDetector;
    /// use std::path::Path;
    ///
    /// # async fn example() {
    /// let detector = ProjectDetector::new();
    /// if detector.is_valid_project(Path::new(".")).await {
    ///     println!("Current directory is a valid Node.js project");
    /// }
    /// # }
    /// ```
    #[must_use]
    pub async fn is_valid_project(&self, path: impl AsRef<Path>) -> bool {
        let path = path.as_ref();

        // Use unified validation logic
        if self.validate_project_path(path).await.is_err() {
            return false;
        }

        // Additional validation: ensure package.json can be parsed
        let package_json_path = path.join("package.json");
        match self.fs.read_file_string(&package_json_path).await {
            Ok(content) => match serde_json::from_str::<PackageJson>(&content) {
                Ok(_) => true,
                Err(e) => {
                    log::warn!(
                        "Failed to parse package.json at {}: {}",
                        package_json_path.display(),
                        e
                    );
                    false
                }
            },
            Err(e) => {
                log::debug!(
                    "Could not read package.json at {} for validation: {}",
                    package_json_path.display(),
                    e
                );
                false
            }
        }
    }
}

#[async_trait]
impl<F: AsyncFileSystem + Clone + 'static> ProjectDetectorTrait for ProjectDetector<F> {
    async fn detect(
        &self,
        path: &Path,
        config: Option<&StandardConfig>,
    ) -> Result<ProjectDescriptor> {
        self.detect(path, config).await
    }

    async fn detect_kind(&self, path: &Path) -> Result<ProjectKind> {
        self.detect_kind(path).await
    }

    async fn is_valid_project(&self, path: &Path) -> bool {
        self.is_valid_project(path).await
    }
}

#[async_trait]
impl<F: AsyncFileSystem + Clone + 'static> ProjectDetectorWithFs<F> for ProjectDetector<F> {
    fn filesystem(&self) -> &F {
        &self.fs
    }

    async fn detect_multiple(
        &self,
        paths: &[&Path],
        config: Option<&StandardConfig>,
    ) -> Vec<Result<ProjectDescriptor>> {
        let mut results = Vec::with_capacity(paths.len());

        // Process all paths concurrently
        let futures = paths.iter().map(|path| self.detect(path, config));

        // Collect all results
        for future in futures {
            results.push(future.await);
        }

        results
    }
}

impl<F: AsyncFileSystem + Clone> Default for ProjectDetector<F>
where
    F: Default,
{
    fn default() -> Self {
        let fs = F::default();
        Self { fs }
    }
}