thru-abi-loader 0.2.28

ABI loading utilities for the Thru blockchain
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
//! Enhanced Import Resolver
//!
//! This module provides the full import resolution system that supports all import
//! types (path, git, http, onchain) with cycle detection, version conflict detection,
//! and the local import restriction rule.

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;

use crate::fetcher::{CompositeFetcher, FetchContext, FetchError, FetcherConfig};
use crate::file::{AbiFile, ImportSource};
use crate::package::{PackageId, ResolutionResult, ResolveError, ResolvedPackage};

/* ============================================================================
Enhanced Import Resolver
============================================================================ */

/* Full-featured import resolver supporting all import types */
pub struct EnhancedImportResolver {
    /* Composite fetcher for handling all import types */
    fetcher: CompositeFetcher,

    /* Include directories for path resolution */
    include_dirs: Vec<PathBuf>,

    /* Enable verbose logging */
    verbose: bool,
}

impl EnhancedImportResolver {
    /* Create a new enhanced import resolver with the given configuration */
    pub fn new(config: FetcherConfig, include_dirs: Vec<PathBuf>) -> Result<Self, ResolveError> {
        let fetcher = CompositeFetcher::new(config).map_err(|e| ResolveError::InitError {
            message: e.to_string(),
        })?;
        Ok(Self {
            fetcher,
            include_dirs,
            verbose: false,
        })
    }

    /* Create with default configuration (all import types enabled) */
    pub fn with_defaults(include_dirs: Vec<PathBuf>) -> Result<Self, ResolveError> {
        Self::new(FetcherConfig::cli_default(), include_dirs)
    }

    /* Enable verbose logging */
    pub fn with_verbose(mut self, verbose: bool) -> Self {
        self.verbose = verbose;
        self
    }

    /* Get the fetcher configuration */
    pub fn config(&self) -> &FetcherConfig {
        self.fetcher.config()
    }

    /* Resolve a root ABI file and all its transitive imports */
    pub fn resolve_file(&self, file_path: &PathBuf) -> Result<ResolutionResult, ResolveError> {
        /* Create root import source */
        let root_source = ImportSource::Path {
            path: file_path.to_string_lossy().to_string(),
        };

        /* Create root context */
        let root_ctx = FetchContext::for_root(Some(file_path.clone()), self.include_dirs.clone());

        /* Initialize resolution state */
        let mut state = ResolutionState::new();

        /* Resolve recursively */
        let root_id = self.resolve_import(&root_source, &root_ctx, &mut state)?;

        /* Build result */
        let root_package = state
            .resolved_packages
            .get(&root_id)
            .cloned()
            .ok_or_else(|| ResolveError::FetchError {
                source: root_source,
                message: "Root package not found in resolution state".to_string(),
            })?;

        Ok(ResolutionResult {
            root: root_package,
            all_packages: state.resolved_packages.into_values().collect(),
        })
    }

    /* Resolve an ABI from raw YAML content (for WASM/embedded use) */
    pub fn resolve_content(
        &self,
        content: &str,
        canonical_location: &str,
    ) -> Result<ResolutionResult, ResolveError> {
        /* Parse the ABI file */
        let abi_file: AbiFile =
            serde_yml::from_str(content).map_err(|e| ResolveError::ParseError {
                location: canonical_location.to_string(),
                message: e.to_string(),
            })?;

        /* Create a synthetic import source */
        let root_source = ImportSource::Path {
            path: canonical_location.to_string(),
        };

        /* Initialize resolution state */
        let mut state = ResolutionState::new();

        /* Create root context - not remote since content is provided directly */
        let root_ctx = FetchContext::for_root(None, self.include_dirs.clone());

        /* Process this package directly */
        let pkg_id = PackageId::from_abi_file(&abi_file);

        /* Check for version conflict */
        self.check_version_conflict(&pkg_id, &state)?;

        /* Mark as being resolved (for cycle detection) */
        state.in_progress.insert(canonical_location.to_string());
        state.resolution_chain.push(pkg_id.clone());

        /* Resolve all imports */
        let mut dependencies = Vec::new();
        for import in abi_file.imports() {
            let child_ctx = root_ctx.child_context(import, None);
            let dep_id = self.resolve_import(import, &child_ctx, &mut state)?;
            dependencies.push(dep_id);
        }

        /* Create resolved package */
        let resolved = ResolvedPackage::new(root_source.clone(), abi_file, dependencies);

        /* Mark as fully resolved */
        state.in_progress.remove(canonical_location);
        state.resolution_chain.pop();
        state
            .resolved_packages
            .insert(pkg_id.clone(), resolved.clone());
        state
            .versions
            .insert(pkg_id.package_name.clone(), pkg_id.version.clone());

        Ok(ResolutionResult {
            root: resolved,
            all_packages: state.resolved_packages.into_values().collect(),
        })
    }

    /* Internal: Resolve a single import and its transitive dependencies */
    fn resolve_import(
        &self,
        source: &ImportSource,
        ctx: &FetchContext,
        state: &mut ResolutionState,
    ) -> Result<PackageId, ResolveError> {
        /* Fetch the content */
        let fetch_result = self.fetcher.fetch(source, ctx).map_err(|e| match e {
            FetchError::NotAllowed(s) => ResolveError::ImportTypeNotAllowed {
                source: s,
                reason: "Import type not allowed by configuration".to_string(),
            },
            FetchError::LocalFromRemote(path) => ResolveError::LocalImportFromRemote {
                remote_package: state
                    .resolution_chain
                    .last()
                    .cloned()
                    .unwrap_or_else(|| PackageId::new("<root>", "0.0.0")),
                local_import: ImportSource::Path { path },
            },
            FetchError::RevisionMismatch { required, actual } => ResolveError::RevisionMismatch {
                source: source.clone(),
                required,
                actual,
            },
            _ => ResolveError::FetchError {
                source: source.clone(),
                message: e.to_string(),
            },
        })?;

        if self.verbose {
            println!("[~] Fetched: {}", fetch_result.canonical_location);
        }

        /* Check for cycle using canonical location */
        if state.in_progress.contains(&fetch_result.canonical_location) {
            return Err(ResolveError::CyclicDependency {
                package_id: state
                    .resolution_chain
                    .last()
                    .cloned()
                    .unwrap_or_else(|| PackageId::new("<unknown>", "0.0.0")),
                cycle_chain: state.resolution_chain.clone(),
            });
        }

        /* Check if already fully resolved (by canonical location) */
        if let Some(pkg_id) = state
            .location_to_package
            .get(&fetch_result.canonical_location)
        {
            if self.verbose {
                println!("    [~] Already resolved: {}", pkg_id);
            }
            return Ok(pkg_id.clone());
        }

        /* Parse the ABI file */
        let abi_file: AbiFile =
            serde_yml::from_str(&fetch_result.content).map_err(|e| ResolveError::ParseError {
                location: fetch_result.canonical_location.clone(),
                message: e.to_string(),
            })?;

        let pkg_id = PackageId::from_abi_file(&abi_file);

        if self.verbose {
            println!("    Package: {}", pkg_id);
        }

        /* Check for version conflict */
        self.check_version_conflict(&pkg_id, state)?;

        /* Mark as being resolved */
        state
            .in_progress
            .insert(fetch_result.canonical_location.clone());
        state.resolution_chain.push(pkg_id.clone());

        /* Create context for resolving this file's imports:
        - base_path: current file's resolved path (for relative path resolution)
        - parent_is_remote: whether this file came from a remote source
        - include_dirs: inherited from root context */
        let import_ctx = FetchContext {
            base_path: fetch_result.resolved_path.clone(),
            parent_is_remote: fetch_result.is_remote,
            include_dirs: ctx.include_dirs.clone(),
        };

        /* Resolve all imports recursively */
        let mut dependencies = Vec::new();
        for import in abi_file.imports() {
            if self.verbose {
                println!("    [~] Resolving import: {:?}", import);
            }

            let dep_id = self.resolve_import(import, &import_ctx, state)?;
            dependencies.push(dep_id);
        }

        /* Create resolved package */
        let resolved = ResolvedPackage {
            id: pkg_id.clone(),
            source: source.clone(),
            abi_file,
            dependencies,
            is_remote: fetch_result.is_remote,
        };

        /* Mark as fully resolved */
        state.in_progress.remove(&fetch_result.canonical_location);
        state.resolution_chain.pop();
        state.resolved_packages.insert(pkg_id.clone(), resolved);
        state
            .location_to_package
            .insert(fetch_result.canonical_location, pkg_id.clone());
        state
            .versions
            .insert(pkg_id.package_name.clone(), pkg_id.version.clone());

        Ok(pkg_id)
    }

    /* Check for version conflicts */
    fn check_version_conflict(
        &self,
        pkg_id: &PackageId,
        state: &ResolutionState,
    ) -> Result<(), ResolveError> {
        if let Some(existing_version) = state.versions.get(&pkg_id.package_name) {
            if existing_version != &pkg_id.version {
                return Err(ResolveError::VersionConflict {
                    package_name: pkg_id.package_name.clone(),
                    version_a: existing_version.clone(),
                    version_b: pkg_id.version.clone(),
                });
            }
        }
        Ok(())
    }
}

/* ============================================================================
Resolution State (internal)
============================================================================ */

/* Internal state tracked during resolution */
struct ResolutionState {
    /* Packages currently being resolved (for cycle detection) */
    in_progress: HashSet<String>,

    /* Chain of packages being resolved (for error reporting) */
    resolution_chain: Vec<PackageId>,

    /* Fully resolved packages by PackageId */
    resolved_packages: HashMap<PackageId, ResolvedPackage>,

    /* Map from canonical location to PackageId */
    location_to_package: HashMap<String, PackageId>,

    /* Map from package name to resolved version (for conflict detection) */
    versions: HashMap<String, String>,
}

impl ResolutionState {
    fn new() -> Self {
        Self {
            in_progress: HashSet::new(),
            resolution_chain: Vec::new(),
            resolved_packages: HashMap::new(),
            location_to_package: HashMap::new(),
            versions: HashMap::new(),
        }
    }
}

/* ============================================================================
Tests
============================================================================ */

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::TempDir;

    fn create_test_abi(dir: &std::path::Path, name: &str, content: &str) -> PathBuf {
        let path = dir.join(name);
        let mut file = std::fs::File::create(&path).unwrap();
        file.write_all(content.as_bytes()).unwrap();
        path
    }

    #[test]
    fn test_resolve_single_file() {
        let temp_dir = TempDir::new().unwrap();
        let abi_content = r#"
abi:
  package: "test.single"
  abi-version: 1
  package-version: "1.0.0"
  description: "Single file test"
types: []
"#;
        let abi_path = create_test_abi(temp_dir.path(), "single.abi.yaml", abi_content);

        let resolver = EnhancedImportResolver::with_defaults(vec![]).unwrap();
        let result = resolver.resolve_file(&abi_path).unwrap();

        assert_eq!(result.root.package_name(), "test.single");
        assert_eq!(result.package_count(), 1);
    }

    #[test]
    fn test_resolve_with_imports() {
        let temp_dir = TempDir::new().unwrap();

        /* Create child ABI */
        let child_content = r#"
abi:
  package: "test.child"
  abi-version: 1
  package-version: "1.0.0"
  description: "Child package"
types:
  - name: "ChildType"
    kind:
      struct:
        fields:
          - name: "value"
            field-type:
              primitive: u32
"#;
        create_test_abi(temp_dir.path(), "child.abi.yaml", child_content);

        /* Create parent ABI that imports child */
        let parent_content = r#"
abi:
  package: "test.parent"
  abi-version: 1
  package-version: "1.0.0"
  description: "Parent package"
  imports:
    - type: path
      path: "child.abi.yaml"
types:
  - name: "ParentType"
    kind:
      struct:
        fields:
          - name: "child"
            field-type:
              type-ref:
                name: ChildType
"#;
        let parent_path = create_test_abi(temp_dir.path(), "parent.abi.yaml", parent_content);

        let resolver = EnhancedImportResolver::with_defaults(vec![]).unwrap();
        let result = resolver.resolve_file(&parent_path).unwrap();

        assert_eq!(result.root.package_name(), "test.parent");
        assert_eq!(result.package_count(), 2);

        /* Verify child was resolved */
        let child_id = PackageId::new("test.child", "1.0.0");
        assert!(result.get_package(&child_id).is_some());
    }

    #[test]
    fn test_cycle_detection() {
        let temp_dir = TempDir::new().unwrap();

        /* Create ABI A that imports B */
        let a_content = r#"
abi:
  package: "test.a"
  abi-version: 1
  package-version: "1.0.0"
  description: "Package A"
  imports:
    - type: path
      path: "b.abi.yaml"
types: []
"#;
        create_test_abi(temp_dir.path(), "a.abi.yaml", a_content);

        /* Create ABI B that imports A (cycle) */
        let b_content = r#"
abi:
  package: "test.b"
  abi-version: 1
  package-version: "1.0.0"
  description: "Package B"
  imports:
    - type: path
      path: "a.abi.yaml"
types: []
"#;
        create_test_abi(temp_dir.path(), "b.abi.yaml", b_content);

        let a_path = temp_dir.path().join("a.abi.yaml");
        let resolver = EnhancedImportResolver::with_defaults(vec![]).unwrap();
        let result = resolver.resolve_file(&a_path);

        assert!(matches!(result, Err(ResolveError::CyclicDependency { .. })));
    }

    #[test]
    fn test_version_conflict_detection() {
        let temp_dir = TempDir::new().unwrap();

        /* Create two versions of the same package */
        let common_v1 = r#"
abi:
  package: "test.common"
  abi-version: 1
  package-version: "1.0.0"
  description: "Common v1"
types: []
"#;
        create_test_abi(temp_dir.path(), "common_v1.abi.yaml", common_v1);

        let common_v2 = r#"
abi:
  package: "test.common"
  abi-version: 1
  package-version: "2.0.0"
  description: "Common v2"
types: []
"#;
        create_test_abi(temp_dir.path(), "common_v2.abi.yaml", common_v2);

        /* Create package A importing common v1 */
        let a_content = r#"
abi:
  package: "test.a"
  abi-version: 1
  package-version: "1.0.0"
  description: "Package A"
  imports:
    - type: path
      path: "common_v1.abi.yaml"
types: []
"#;
        create_test_abi(temp_dir.path(), "a.abi.yaml", a_content);

        /* Create package B importing common v2 */
        let b_content = r#"
abi:
  package: "test.b"
  abi-version: 1
  package-version: "1.0.0"
  description: "Package B"
  imports:
    - type: path
      path: "common_v2.abi.yaml"
types: []
"#;
        create_test_abi(temp_dir.path(), "b.abi.yaml", b_content);

        /* Create root importing both A and B */
        let root_content = r#"
abi:
  package: "test.root"
  abi-version: 1
  package-version: "1.0.0"
  description: "Root package"
  imports:
    - type: path
      path: "a.abi.yaml"
    - type: path
      path: "b.abi.yaml"
types: []
"#;
        let root_path = create_test_abi(temp_dir.path(), "root.abi.yaml", root_content);

        let resolver = EnhancedImportResolver::with_defaults(vec![]).unwrap();
        let result = resolver.resolve_file(&root_path);

        assert!(matches!(
            result,
            Err(ResolveError::VersionConflict {
                package_name,
                ..
            }) if package_name == "test.common"
        ));
    }

    #[test]
    fn test_duplicate_import_deduplication() {
        let temp_dir = TempDir::new().unwrap();

        /* Create common package */
        let common_content = r#"
abi:
  package: "test.common"
  abi-version: 1
  package-version: "1.0.0"
  description: "Common package"
types: []
"#;
        create_test_abi(temp_dir.path(), "common.abi.yaml", common_content);

        /* Create A importing common */
        let a_content = r#"
abi:
  package: "test.a"
  abi-version: 1
  package-version: "1.0.0"
  description: "Package A"
  imports:
    - type: path
      path: "common.abi.yaml"
types: []
"#;
        create_test_abi(temp_dir.path(), "a.abi.yaml", a_content);

        /* Create B importing common */
        let b_content = r#"
abi:
  package: "test.b"
  abi-version: 1
  package-version: "1.0.0"
  description: "Package B"
  imports:
    - type: path
      path: "common.abi.yaml"
types: []
"#;
        create_test_abi(temp_dir.path(), "b.abi.yaml", b_content);

        /* Create root importing both A and B (common imported twice, same version) */
        let root_content = r#"
abi:
  package: "test.root"
  abi-version: 1
  package-version: "1.0.0"
  description: "Root package"
  imports:
    - type: path
      path: "a.abi.yaml"
    - type: path
      path: "b.abi.yaml"
types: []
"#;
        let root_path = create_test_abi(temp_dir.path(), "root.abi.yaml", root_content);

        let resolver = EnhancedImportResolver::with_defaults(vec![]).unwrap();
        let result = resolver.resolve_file(&root_path).unwrap();

        /* Should have 4 packages: root, a, b, common (common only once) */
        assert_eq!(result.package_count(), 4);

        /* Verify common appears only once */
        let common_count = result
            .all_packages
            .iter()
            .filter(|p| p.package_name() == "test.common")
            .count();
        assert_eq!(common_count, 1);
    }

    #[test]
    fn test_to_manifest() {
        let temp_dir = TempDir::new().unwrap();
        let abi_content = r#"
abi:
  package: "test.manifest"
  abi-version: 1
  package-version: "1.0.0"
  description: "Manifest test"
types:
  - name: "TestType"
    kind:
      struct:
        fields:
          - name: "value"
            field-type:
              primitive: u32
"#;
        let abi_path = create_test_abi(temp_dir.path(), "manifest.abi.yaml", abi_content);

        let resolver = EnhancedImportResolver::with_defaults(vec![]).unwrap();
        let result = resolver.resolve_file(&abi_path).unwrap();

        let manifest = result.to_manifest();
        assert_eq!(manifest.len(), 1);
        assert!(manifest.contains_key("test.manifest"));
        assert!(manifest.get("test.manifest").unwrap().contains("TestType"));
    }

    #[test]
    fn test_local_only_config() {
        let temp_dir = TempDir::new().unwrap();
        let abi_content = r#"
abi:
  package: "test.local"
  abi-version: 1
  package-version: "1.0.0"
  description: "Local only test"
types: []
"#;
        let abi_path = create_test_abi(temp_dir.path(), "local.abi.yaml", abi_content);

        /* Use local_only config */
        let resolver = EnhancedImportResolver::new(FetcherConfig::local_only(), vec![]).unwrap();
        let result = resolver.resolve_file(&abi_path).unwrap();

        assert_eq!(result.root.package_name(), "test.local");
    }
}