quantalang 1.0.0

The QuantaLang compiler — an effects-oriented systems language with multi-backend codegen (C, HLSL, GLSL, SPIR-V, LLVM IR, WebAssembly, x86-64, ARM64)
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
// ===============================================================================
// QUANTALANG PACKAGE REGISTRY CLIENT
// ===============================================================================
// Copyright (c) 2022-2026 Zain Dana Harper. MIT License.
// ===============================================================================

//! Registry client for downloading and publishing packages.
//!
//! Supports:
//! - Default Quanta registry (registry.quantalang.org)
//! - Custom registries
//! - Git repositories
//! - Local paths

use std::collections::HashMap;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

use super::{Manifest, Version, VersionReq};

/// Registry configuration
#[derive(Debug, Clone)]
pub struct RegistryConfig {
    /// Registry URL
    pub url: String,
    /// Authentication token
    pub token: Option<String>,
    /// Cache directory
    pub cache_dir: PathBuf,
    /// Request timeout
    pub timeout: Duration,
    /// Maximum concurrent downloads
    pub max_concurrent: usize,
}

impl Default for RegistryConfig {
    fn default() -> Self {
        Self {
            url: "https://registry.quantalang.org".to_string(),
            token: None,
            cache_dir: dirs_cache().join("quanta").join("registry"),
            timeout: Duration::from_secs(30),
            max_concurrent: 4,
        }
    }
}

/// Get cache directory
fn dirs_cache() -> PathBuf {
    #[cfg(target_os = "windows")]
    {
        std::env::var("LOCALAPPDATA")
            .map(PathBuf::from)
            .unwrap_or_else(|_| PathBuf::from("C:\\Users\\Default\\AppData\\Local"))
    }
    #[cfg(not(target_os = "windows"))]
    {
        std::env::var("XDG_CACHE_HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|_| {
                std::env::var("HOME")
                    .map(|h| PathBuf::from(h).join(".cache"))
                    .unwrap_or_else(|_| PathBuf::from("/tmp"))
            })
    }
}

/// Registry error types
#[derive(Debug)]
pub enum RegistryError {
    /// Network error
    Network(String),
    /// Package not found
    NotFound(String),
    /// Version not found
    VersionNotFound(String, String),
    /// Authentication required
    AuthRequired,
    /// Authentication failed
    AuthFailed,
    /// Rate limited
    RateLimited(Duration),
    /// Invalid response
    InvalidResponse(String),
    /// Cache error
    CacheError(String),
    /// IO error
    Io(io::Error),
    /// Checksum mismatch
    ChecksumMismatch { expected: String, actual: String },
    /// Package yanked
    Yanked(String, Version),
}

impl std::fmt::Display for RegistryError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Network(msg) => write!(f, "network error: {}", msg),
            Self::NotFound(name) => write!(f, "package '{}' not found", name),
            Self::VersionNotFound(name, ver) => {
                write!(f, "version {} of package '{}' not found", ver, name)
            }
            Self::AuthRequired => write!(f, "authentication required"),
            Self::AuthFailed => write!(f, "authentication failed"),
            Self::RateLimited(dur) => write!(f, "rate limited, retry after {:?}", dur),
            Self::InvalidResponse(msg) => write!(f, "invalid response: {}", msg),
            Self::CacheError(msg) => write!(f, "cache error: {}", msg),
            Self::Io(e) => write!(f, "IO error: {}", e),
            Self::ChecksumMismatch { expected, actual } => {
                write!(
                    f,
                    "checksum mismatch: expected {}, got {}",
                    expected, actual
                )
            }
            Self::Yanked(name, ver) => write!(f, "package {}@{} has been yanked", name, ver),
        }
    }
}

impl std::error::Error for RegistryError {}

impl From<io::Error> for RegistryError {
    fn from(e: io::Error) -> Self {
        Self::Io(e)
    }
}

/// Package metadata from registry
#[derive(Debug, Clone)]
pub struct PackageMetadata {
    /// Package name
    pub name: String,
    /// Description
    pub description: Option<String>,
    /// Repository URL
    pub repository: Option<String>,
    /// Documentation URL
    pub documentation: Option<String>,
    /// Homepage
    pub homepage: Option<String>,
    /// Keywords
    pub keywords: Vec<String>,
    /// Categories
    pub categories: Vec<String>,
    /// License
    pub license: Option<String>,
    /// All published versions
    pub versions: Vec<VersionInfo>,
    /// Download count
    pub downloads: u64,
    /// Created timestamp
    pub created_at: Option<SystemTime>,
    /// Updated timestamp
    pub updated_at: Option<SystemTime>,
}

/// Information about a specific version
#[derive(Debug, Clone)]
pub struct VersionInfo {
    /// Version number
    pub version: Version,
    /// Dependencies
    pub dependencies: HashMap<String, VersionReq>,
    /// Dev dependencies
    pub dev_dependencies: HashMap<String, VersionReq>,
    /// Features
    pub features: HashMap<String, Vec<String>>,
    /// Checksum (SHA256)
    pub checksum: String,
    /// Tarball size
    pub size: u64,
    /// Whether version is yanked
    pub yanked: bool,
    /// Published timestamp
    pub published_at: Option<SystemTime>,
    /// Minimum Quanta version required
    pub quanta_version: Option<VersionReq>,
}

/// Downloaded package
#[derive(Debug)]
pub struct DownloadedPackage {
    /// Package name
    pub name: String,
    /// Version
    pub version: Version,
    /// Path to extracted package
    pub path: PathBuf,
    /// Manifest
    pub manifest: Manifest,
}

/// Registry client
pub struct Registry {
    config: RegistryConfig,
    cache: PackageCache,
}

impl Registry {
    /// Create new registry client
    pub fn new(config: RegistryConfig) -> Self {
        let cache = PackageCache::new(config.cache_dir.clone());
        Self { config, cache }
    }

    /// Create with default configuration
    pub fn default_registry() -> Self {
        Self::new(RegistryConfig::default())
    }

    /// Search for packages
    pub fn search(&self, query: &str, limit: usize) -> Result<Vec<PackageMetadata>, RegistryError> {
        let url = format!(
            "{}/api/v1/search?q={}&limit={}",
            self.config.url,
            urlencoding::encode(query),
            limit
        );

        let response = self.http_get(&url)?;
        self.parse_search_response(&response)
    }

    /// Get package metadata
    pub fn get_package(&self, name: &str) -> Result<PackageMetadata, RegistryError> {
        // Check cache first
        if let Some(meta) = self.cache.get_metadata(name) {
            return Ok(meta);
        }

        let url = format!("{}/api/v1/packages/{}", self.config.url, name);
        let response = self.http_get(&url)?;
        let meta = self.parse_package_response(&response)?;

        // Cache the metadata
        self.cache.store_metadata(name, &meta)?;

        Ok(meta)
    }

    /// Get specific version info
    pub fn get_version(&self, name: &str, version: &Version) -> Result<VersionInfo, RegistryError> {
        let meta = self.get_package(name)?;

        meta.versions
            .into_iter()
            .find(|v| &v.version == version)
            .ok_or_else(|| RegistryError::VersionNotFound(name.to_string(), version.to_string()))
    }

    /// Find best matching version
    pub fn find_version(&self, name: &str, req: &VersionReq) -> Result<VersionInfo, RegistryError> {
        let meta = self.get_package(name)?;

        // Find all matching non-yanked versions
        let mut matching: Vec<_> = meta
            .versions
            .into_iter()
            .filter(|v| !v.yanked && req.matches(&v.version))
            .collect();

        // Sort by version descending
        matching.sort_by(|a, b| b.version.cmp(&a.version));

        matching
            .into_iter()
            .next()
            .ok_or_else(|| RegistryError::VersionNotFound(name.to_string(), req.to_string()))
    }

    /// Download a package
    pub fn download(
        &self,
        name: &str,
        version: &Version,
    ) -> Result<DownloadedPackage, RegistryError> {
        // Check cache first
        if let Some(path) = self.cache.get_package(name, version) {
            let manifest = self.load_manifest(&path)?;
            return Ok(DownloadedPackage {
                name: name.to_string(),
                version: version.clone(),
                path,
                manifest,
            });
        }

        // Get version info for checksum
        let info = self.get_version(name, version)?;

        if info.yanked {
            return Err(RegistryError::Yanked(name.to_string(), version.clone()));
        }

        // Download tarball
        let url = format!(
            "{}/api/v1/packages/{}/{}/download",
            self.config.url, name, version
        );
        let data = self.http_get_binary(&url)?;

        // Verify checksum
        let checksum = sha256_hex(&data);
        if checksum != info.checksum {
            return Err(RegistryError::ChecksumMismatch {
                expected: info.checksum,
                actual: checksum,
            });
        }

        // Extract to cache
        let path = self.cache.store_package(name, version, &data)?;
        let manifest = self.load_manifest(&path)?;

        Ok(DownloadedPackage {
            name: name.to_string(),
            version: version.clone(),
            path,
            manifest,
        })
    }

    /// Publish a package
    pub fn publish(&self, tarball: &[u8], manifest: &Manifest) -> Result<(), RegistryError> {
        let token = self
            .config
            .token
            .as_ref()
            .ok_or(RegistryError::AuthRequired)?;

        let url = format!("{}/api/v1/packages/new", self.config.url);

        // Create multipart body
        let boundary = "----QuantaPublishBoundary";
        let mut body = Vec::new();

        // Add manifest part
        write!(body, "--{}\r\n", boundary)?;
        write!(
            body,
            "Content-Disposition: form-data; name=\"manifest\"\r\n"
        )?;
        write!(body, "Content-Type: application/toml\r\n\r\n")?;
        body.extend_from_slice(manifest.to_toml().as_bytes());
        write!(body, "\r\n")?;

        // Add tarball part
        write!(body, "--{}\r\n", boundary)?;
        write!(
            body,
            "Content-Disposition: form-data; name=\"tarball\"; filename=\"package.tar.gz\"\r\n"
        )?;
        write!(body, "Content-Type: application/gzip\r\n\r\n")?;
        body.extend_from_slice(tarball);
        write!(body, "\r\n--{}--\r\n", boundary)?;

        let _response = self.http_post(&url, &body, token, boundary)?;

        Ok(())
    }

    /// Yank a version
    pub fn yank(&self, name: &str, version: &Version) -> Result<(), RegistryError> {
        let token = self
            .config
            .token
            .as_ref()
            .ok_or(RegistryError::AuthRequired)?;

        let url = format!(
            "{}/api/v1/packages/{}/{}/yank",
            self.config.url, name, version
        );

        self.http_delete(&url, token)?;

        // Invalidate cache
        self.cache.invalidate(name);

        Ok(())
    }

    /// Unyank a version
    pub fn unyank(&self, name: &str, version: &Version) -> Result<(), RegistryError> {
        let token = self
            .config
            .token
            .as_ref()
            .ok_or(RegistryError::AuthRequired)?;

        let url = format!(
            "{}/api/v1/packages/{}/{}/unyank",
            self.config.url, name, version
        );

        self.http_put(&url, &[], token)?;

        // Invalidate cache
        self.cache.invalidate(name);

        Ok(())
    }

    /// Get owners of a package
    pub fn get_owners(&self, name: &str) -> Result<Vec<Owner>, RegistryError> {
        let url = format!("{}/api/v1/packages/{}/owners", self.config.url, name);
        let response = self.http_get(&url)?;
        self.parse_owners_response(&response)
    }

    /// Add owner to a package
    pub fn add_owner(&self, name: &str, user: &str) -> Result<(), RegistryError> {
        let token = self
            .config
            .token
            .as_ref()
            .ok_or(RegistryError::AuthRequired)?;

        let url = format!("{}/api/v1/packages/{}/owners", self.config.url, name);
        let body = format!(r#"{{"login":"{}"}}"#, user);

        self.http_put(&url, body.as_bytes(), token)?;

        Ok(())
    }

    /// Remove owner from a package
    pub fn remove_owner(&self, name: &str, user: &str) -> Result<(), RegistryError> {
        let token = self
            .config
            .token
            .as_ref()
            .ok_or(RegistryError::AuthRequired)?;

        let url = format!(
            "{}/api/v1/packages/{}/owners/{}",
            self.config.url, name, user
        );

        self.http_delete(&url, token)?;

        Ok(())
    }

    // HTTP helpers - placeholder implementations
    // In a real implementation, these would use an HTTP client

    fn http_get(&self, url: &str) -> Result<String, RegistryError> {
        // Placeholder - would use HTTP client
        let _ = url;
        let _ = self.config.timeout;
        Err(RegistryError::Network(
            "HTTP client not implemented".to_string(),
        ))
    }

    fn http_get_binary(&self, url: &str) -> Result<Vec<u8>, RegistryError> {
        let _ = url;
        Err(RegistryError::Network(
            "HTTP client not implemented".to_string(),
        ))
    }

    fn http_post(
        &self,
        url: &str,
        body: &[u8],
        token: &str,
        boundary: &str,
    ) -> Result<String, RegistryError> {
        let _ = (url, body, token, boundary);
        Err(RegistryError::Network(
            "HTTP client not implemented".to_string(),
        ))
    }

    fn http_put(&self, url: &str, body: &[u8], token: &str) -> Result<String, RegistryError> {
        let _ = (url, body, token);
        Err(RegistryError::Network(
            "HTTP client not implemented".to_string(),
        ))
    }

    fn http_delete(&self, url: &str, token: &str) -> Result<(), RegistryError> {
        let _ = (url, token);
        Err(RegistryError::Network(
            "HTTP client not implemented".to_string(),
        ))
    }

    fn parse_search_response(
        &self,
        _response: &str,
    ) -> Result<Vec<PackageMetadata>, RegistryError> {
        // Placeholder JSON parsing
        Ok(Vec::new())
    }

    fn parse_package_response(&self, _response: &str) -> Result<PackageMetadata, RegistryError> {
        Err(RegistryError::InvalidResponse(
            "JSON parsing not implemented".to_string(),
        ))
    }

    fn parse_owners_response(&self, _response: &str) -> Result<Vec<Owner>, RegistryError> {
        Ok(Vec::new())
    }

    fn load_manifest(&self, path: &Path) -> Result<Manifest, RegistryError> {
        let manifest_path = path.join("Quanta.toml");
        let content = std::fs::read_to_string(&manifest_path)?;
        Manifest::from_str(&content)
            .map_err(|e| RegistryError::InvalidResponse(format!("invalid manifest: {}", e)))
    }
}

/// Package owner information
#[derive(Debug, Clone)]
pub struct Owner {
    /// Login/username
    pub login: String,
    /// Display name
    pub name: Option<String>,
    /// Email
    pub email: Option<String>,
}

/// Package cache
pub struct PackageCache {
    root: PathBuf,
}

impl PackageCache {
    /// Create new cache
    pub fn new(root: PathBuf) -> Self {
        Self { root }
    }

    /// Get cached metadata
    pub fn get_metadata(&self, name: &str) -> Option<PackageMetadata> {
        let path = self.metadata_path(name);
        if !path.exists() {
            return None;
        }

        // Check freshness (1 hour)
        if let Ok(meta) = std::fs::metadata(&path) {
            if let Ok(modified) = meta.modified() {
                if let Ok(elapsed) = SystemTime::now().duration_since(modified) {
                    if elapsed > Duration::from_secs(3600) {
                        return None;
                    }
                }
            }
        }

        // Parse cached metadata
        let content = std::fs::read_to_string(&path).ok()?;
        self.parse_cached_metadata(&content)
    }

    /// Store metadata in cache
    pub fn store_metadata(&self, name: &str, _meta: &PackageMetadata) -> Result<(), RegistryError> {
        let path = self.metadata_path(name);
        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        // Serialize metadata (placeholder)
        let content = "{}"; // Would serialize to JSON
        std::fs::write(&path, content)?;

        Ok(())
    }

    /// Get cached package
    pub fn get_package(&self, name: &str, version: &Version) -> Option<PathBuf> {
        let path = self.package_path(name, version);
        if path.exists() && path.join("Quanta.toml").exists() {
            Some(path)
        } else {
            None
        }
    }

    /// Store package in cache
    pub fn store_package(
        &self,
        name: &str,
        version: &Version,
        data: &[u8],
    ) -> Result<PathBuf, RegistryError> {
        let path = self.package_path(name, version);

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)?;
        }

        // Extract tarball
        self.extract_tarball(data, &path)?;

        Ok(path)
    }

    /// Invalidate cache for a package
    pub fn invalidate(&self, name: &str) {
        let path = self.metadata_path(name);
        let _ = std::fs::remove_file(path);
    }

    /// Clear all cached data
    pub fn clear(&self) -> Result<(), RegistryError> {
        if self.root.exists() {
            std::fs::remove_dir_all(&self.root)?;
        }
        Ok(())
    }

    fn metadata_path(&self, name: &str) -> PathBuf {
        self.root.join("metadata").join(format!("{}.json", name))
    }

    fn package_path(&self, name: &str, version: &Version) -> PathBuf {
        self.root
            .join("packages")
            .join(name)
            .join(version.to_string())
    }

    fn parse_cached_metadata(&self, _content: &str) -> Option<PackageMetadata> {
        // Placeholder JSON parsing
        None
    }

    fn extract_tarball(&self, _data: &[u8], _dest: &Path) -> Result<(), RegistryError> {
        // Placeholder - would use tar/gzip libraries
        Ok(())
    }
}

/// URL encoding helper
mod urlencoding {
    pub fn encode(s: &str) -> String {
        let mut result = String::with_capacity(s.len() * 3);
        for c in s.chars() {
            match c {
                'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_' | '.' | '~' => {
                    result.push(c);
                }
                _ => {
                    for b in c.to_string().as_bytes() {
                        result.push_str(&format!("%{:02X}", b));
                    }
                }
            }
        }
        result
    }
}

/// SHA256 hash helper (placeholder)
fn sha256_hex(data: &[u8]) -> String {
    // Placeholder - would use sha2 crate
    use std::collections::hash_map::DefaultHasher;
    use std::hash::{Hash, Hasher};

    let mut hasher = DefaultHasher::new();
    data.hash(&mut hasher);
    format!(
        "{:016x}{:016x}{:016x}{:016x}",
        hasher.finish(),
        hasher.finish(),
        hasher.finish(),
        hasher.finish()
    )
}

/// Git source for packages
#[derive(Debug, Clone)]
pub struct GitSource {
    /// Repository URL
    pub url: String,
    /// Branch
    pub branch: Option<String>,
    /// Tag
    pub tag: Option<String>,
    /// Commit
    pub rev: Option<String>,
}

impl GitSource {
    /// Create from URL
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            branch: None,
            tag: None,
            rev: None,
        }
    }

    /// Set branch
    pub fn with_branch(mut self, branch: impl Into<String>) -> Self {
        self.branch = Some(branch.into());
        self
    }

    /// Set tag
    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
        self.tag = Some(tag.into());
        self
    }

    /// Set revision
    pub fn with_rev(mut self, rev: impl Into<String>) -> Self {
        self.rev = Some(rev.into());
        self
    }

    /// Clone/fetch the repository
    pub fn fetch(&self, dest: &Path) -> Result<(), RegistryError> {
        // Placeholder - would use git2 crate
        let _ = dest;
        Err(RegistryError::Network(
            "Git support not implemented".to_string(),
        ))
    }
}

/// Path source for local packages
#[derive(Debug, Clone)]
pub struct PathSource {
    /// Local path
    pub path: PathBuf,
}

impl PathSource {
    /// Create from path
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self { path: path.into() }
    }

    /// Resolve the path relative to a base
    pub fn resolve(&self, base: &Path) -> PathBuf {
        if self.path.is_absolute() {
            self.path.clone()
        } else {
            base.join(&self.path)
        }
    }

    /// Load manifest from path
    pub fn load_manifest(&self) -> Result<Manifest, RegistryError> {
        let manifest_path = self.path.join("Quanta.toml");
        let content = std::fs::read_to_string(&manifest_path)?;
        Manifest::from_str(&content)
            .map_err(|e| RegistryError::InvalidResponse(format!("invalid manifest: {}", e)))
    }
}

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

    #[test]
    fn test_url_encoding() {
        assert_eq!(urlencoding::encode("hello"), "hello");
        assert_eq!(urlencoding::encode("hello world"), "hello%20world");
        assert_eq!(urlencoding::encode("a+b=c"), "a%2Bb%3Dc");
    }

    #[test]
    fn test_cache_paths() {
        let cache = PackageCache::new(PathBuf::from("/cache"));

        let meta_path = cache.metadata_path("my-package");
        assert!(meta_path.to_str().unwrap().contains("my-package.json"));

        let pkg_path = cache.package_path("my-package", &Version::new(1, 2, 3));
        assert!(pkg_path.to_str().unwrap().contains("1.2.3"));
    }

    #[test]
    fn test_git_source() {
        let source = GitSource::new("https://github.com/user/repo")
            .with_branch("main")
            .with_tag("v1.0.0");

        assert_eq!(source.url, "https://github.com/user/repo");
        assert_eq!(source.branch, Some("main".to_string()));
        assert_eq!(source.tag, Some("v1.0.0".to_string()));
    }

    #[test]
    fn test_path_source() {
        let source = PathSource::new("../other-package");
        let resolved = source.resolve(Path::new("/home/user/project"));

        assert!(resolved.to_str().unwrap().contains("other-package"));
    }
}